Skip to main content

mz_persist_client/
schema.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Persist shard schema information.
11
12use std::collections::BTreeMap;
13use std::fmt::Debug;
14use std::sync::{Arc, RwLock};
15use std::time::Instant;
16
17use differential_dataflow::difference::Monoid;
18use differential_dataflow::lattice::Lattice;
19use mz_ore::cast::CastFrom;
20use mz_persist_types::columnar::data_type;
21use mz_persist_types::schema::{Migration, SchemaId, backward_compatible};
22use mz_persist_types::{Codec, Codec64};
23use timely::progress::Timestamp;
24
25use crate::internal::apply::Applier;
26use crate::internal::encoding::Schemas;
27use crate::internal::metrics::{SchemaCacheMetrics, SchemaMetrics};
28use crate::internal::state::{BatchPart, EncodedSchemas};
29
30/// The result returned by [crate::PersistClient::compare_and_evolve_schema].
31#[derive(Debug)]
32#[cfg_attr(test, derive(PartialEq))]
33pub enum CaESchema<K: Codec, V: Codec> {
34    /// The schema was successfully evolved and registered with the included id.
35    Ok(SchemaId),
36    /// The schema was not compatible with previously registered schemas.
37    Incompatible,
38    /// The `expected` SchemaId did not match reality. The current one is
39    /// included for easy of retry.
40    ExpectedMismatch {
41        /// The current schema id.
42        schema_id: SchemaId,
43        /// The key schema at this id.
44        key: K::Schema,
45        /// The val schema at this id.
46        val: V::Schema,
47    },
48}
49
50/// A cache of decoded schemas and schema migrations.
51///
52/// The decoded schemas are a cache of the registry in state, and so are shared
53/// process-wide.
54///
55/// On the other hand, the migrations have an N^2 problem and so are per-handle.
56/// This also seems reasonable because for any given write handle, the write
57/// schema will be the same for all migration entries, and ditto for read handle
58/// and read schema.
59#[derive(Debug)]
60pub(crate) struct SchemaCache<K: Codec, V: Codec, T, D> {
61    maps: Arc<SchemaCacheMaps<K, V>>,
62    applier: Applier<K, V, T, D>,
63    key_migration_by_ids: MigrationCacheMap,
64    val_migration_by_ids: MigrationCacheMap,
65}
66
67impl<K: Codec, V: Codec, T: Clone, D> Clone for SchemaCache<K, V, T, D> {
68    fn clone(&self) -> Self {
69        Self {
70            maps: Arc::clone(&self.maps),
71            applier: self.applier.clone(),
72            key_migration_by_ids: self.key_migration_by_ids.clone(),
73            val_migration_by_ids: self.val_migration_by_ids.clone(),
74        }
75    }
76}
77
78impl<K: Codec, V: Codec, T, D> Drop for SchemaCache<K, V, T, D> {
79    fn drop(&mut self) {
80        let dropped = u64::cast_from(
81            self.key_migration_by_ids.by_ids.len() + self.val_migration_by_ids.by_ids.len(),
82        );
83        self.applier
84            .metrics
85            .schema
86            .cache_migration
87            .dropped_count
88            .inc_by(dropped);
89    }
90}
91
92impl<K, V, T, D> SchemaCache<K, V, T, D>
93where
94    K: Debug + Codec,
95    V: Debug + Codec,
96    T: Timestamp + Lattice + Codec64 + Sync,
97    D: Monoid + Codec64,
98{
99    /// Returns the [Applier] backing this cache.
100    pub(crate) fn applier(&self) -> &Applier<K, V, T, D> {
101        &self.applier
102    }
103
104    pub fn new(maps: Arc<SchemaCacheMaps<K, V>>, applier: Applier<K, V, T, D>) -> Self {
105        let key_migration_by_ids = MigrationCacheMap {
106            metrics: applier.metrics.schema.cache_migration.clone(),
107            by_ids: BTreeMap::new(),
108        };
109        let val_migration_by_ids = MigrationCacheMap {
110            metrics: applier.metrics.schema.cache_migration.clone(),
111            by_ids: BTreeMap::new(),
112        };
113        SchemaCache {
114            maps,
115            applier,
116            key_migration_by_ids,
117            val_migration_by_ids,
118        }
119    }
120
121    async fn schemas(&self, id: &SchemaId) -> Option<Schemas<K, V>> {
122        let key = self
123            .get_or_try_init(&self.maps.key_by_id, id, |schemas| {
124                self.maps.key_by_id.metrics.computed_count.inc();
125                schemas.get(id).map(|x| K::decode_schema(&x.key))
126            })
127            .await?;
128        let val = self
129            .get_or_try_init(&self.maps.val_by_id, id, |schemas| {
130                self.maps.val_by_id.metrics.computed_count.inc();
131                schemas.get(id).map(|x| V::decode_schema(&x.val))
132            })
133            .await?;
134        Some(Schemas {
135            id: Some(*id),
136            key,
137            val,
138        })
139    }
140
141    fn key_migration(
142        &mut self,
143        write: &Schemas<K, V>,
144        read: &Schemas<K, V>,
145    ) -> Option<Arc<Migration>> {
146        let migration_fn = || Self::migration::<K>(&write.key, &read.key);
147        let (Some(write_id), Some(read_id)) = (write.id, read.id) else {
148            // TODO: Annoying to cache this because we're missing an id. This
149            // will probably require some sort of refactor to fix so punting for
150            // now.
151            self.key_migration_by_ids.metrics.computed_count.inc();
152            return migration_fn().map(Arc::new);
153        };
154        self.key_migration_by_ids
155            .get_or_try_insert(write_id, read_id, migration_fn)
156    }
157
158    fn val_migration(
159        &mut self,
160        write: &Schemas<K, V>,
161        read: &Schemas<K, V>,
162    ) -> Option<Arc<Migration>> {
163        let migration_fn = || Self::migration::<V>(&write.val, &read.val);
164        let (Some(write_id), Some(read_id)) = (write.id, read.id) else {
165            // TODO: Annoying to cache this because we're missing an id. This
166            // will probably require some sort of refactor to fix so punting for
167            // now.
168            self.val_migration_by_ids.metrics.computed_count.inc();
169            return migration_fn().map(Arc::new);
170        };
171        self.val_migration_by_ids
172            .get_or_try_insert(write_id, read_id, migration_fn)
173    }
174
175    fn migration<C: Codec>(write: &C::Schema, read: &C::Schema) -> Option<Migration> {
176        let write_dt = data_type::<C>(write).expect("valid schema");
177        let read_dt = data_type::<C>(read).expect("valid schema");
178        backward_compatible(&write_dt, &read_dt)
179    }
180
181    async fn get_or_try_init<MK: Clone + Ord, MV: PartialEq + Debug>(
182        &self,
183        map: &SchemaCacheMap<MK, MV>,
184        key: &MK,
185        f: impl Fn(&BTreeMap<SchemaId, EncodedSchemas>) -> Option<MV>,
186    ) -> Option<Arc<MV>> {
187        let ret = map.get_or_try_init(key, || {
188            self.applier
189                .schemas(|seqno, schemas| f(schemas).ok_or(seqno))
190        });
191        let seqno = match ret {
192            Ok(ret) => return Some(ret),
193            Err(seqno) => seqno,
194        };
195        self.applier.metrics.schema.cache_fetch_state_count.inc();
196        self.applier.fetch_and_update_state(Some(seqno)).await;
197        map.get_or_try_init(key, || {
198            self.applier
199                .schemas(|seqno, schemas| f(schemas).ok_or(seqno))
200        })
201        .ok()
202    }
203}
204
205#[derive(Debug)]
206pub(crate) struct SchemaCacheMaps<K: Codec, V: Codec> {
207    key_by_id: SchemaCacheMap<SchemaId, K::Schema>,
208    val_by_id: SchemaCacheMap<SchemaId, V::Schema>,
209}
210
211impl<K: Codec, V: Codec> SchemaCacheMaps<K, V> {
212    pub(crate) fn new(metrics: &SchemaMetrics) -> Self {
213        Self {
214            key_by_id: SchemaCacheMap {
215                metrics: metrics.cache_schema.clone(),
216                map: RwLock::new(BTreeMap::new()),
217            },
218            val_by_id: SchemaCacheMap {
219                metrics: metrics.cache_schema.clone(),
220                map: RwLock::new(BTreeMap::new()),
221            },
222        }
223    }
224}
225
226#[derive(Debug)]
227struct SchemaCacheMap<I, S> {
228    metrics: SchemaCacheMetrics,
229    map: RwLock<BTreeMap<I, Arc<S>>>,
230}
231
232impl<I: Clone + Ord, S: PartialEq + Debug> SchemaCacheMap<I, S> {
233    fn get_or_try_init<E>(
234        &self,
235        id: &I,
236        state_fn: impl FnOnce() -> Result<S, E>,
237    ) -> Result<Arc<S>, E> {
238        // First see if we have the value cached.
239        {
240            let map = self.map.read().expect("lock");
241            if let Some(ret) = map.get(id).map(Arc::clone) {
242                self.metrics.cached_count.inc();
243                return Ok(ret);
244            }
245        }
246        // If not, see if we can get the value from current state.
247        let ret = state_fn().map(Arc::new);
248        if let Ok(val) = ret.as_ref() {
249            let mut map = self.map.write().expect("lock");
250            // If any answers got written in the meantime, they should be the
251            // same, so just overwrite
252            let prev = map.insert(id.clone(), Arc::clone(val));
253            match prev {
254                Some(prev) => mz_ore::soft_assert_eq_no_log!(*val, prev),
255                None => self.metrics.added_count.inc(),
256            }
257        } else {
258            self.metrics.unavailable_count.inc();
259        }
260        ret
261    }
262}
263
264impl<I, K> Drop for SchemaCacheMap<I, K> {
265    fn drop(&mut self) {
266        let map = self.map.read().expect("lock");
267        self.metrics.dropped_count.inc_by(u64::cast_from(map.len()));
268    }
269}
270
271#[derive(Debug, Clone)]
272struct MigrationCacheMap {
273    metrics: SchemaCacheMetrics,
274    by_ids: BTreeMap<(SchemaId, SchemaId), Arc<Migration>>,
275}
276
277impl MigrationCacheMap {
278    fn get_or_try_insert(
279        &mut self,
280        write_id: SchemaId,
281        read_id: SchemaId,
282        migration_fn: impl FnOnce() -> Option<Migration>,
283    ) -> Option<Arc<Migration>> {
284        if let Some(migration) = self.by_ids.get(&(write_id, read_id)) {
285            self.metrics.cached_count.inc();
286            return Some(Arc::clone(migration));
287        };
288        self.metrics.computed_count.inc();
289        let migration = migration_fn().map(Arc::new);
290        if let Some(migration) = migration.as_ref() {
291            self.metrics.added_count.inc();
292            // We just looked this up above and we've got mutable access, so no
293            // race issues.
294            self.by_ids
295                .insert((write_id, read_id), Arc::clone(migration));
296        } else {
297            self.metrics.unavailable_count.inc();
298        }
299        migration
300    }
301}
302
303#[derive(Debug)]
304pub(crate) enum PartMigration<K: Codec, V: Codec> {
305    /// No-op!
306    SameSchema { both: Schemas<K, V> },
307    /// We don't have a schema id for write schema.
308    Schemaless { read: Schemas<K, V> },
309    /// We have both write and read schemas, and they don't match.
310    Either {
311        write: Schemas<K, V>,
312        read: Schemas<K, V>,
313        key_migration: Arc<Migration>,
314        val_migration: Arc<Migration>,
315    },
316}
317
318impl<K: Codec, V: Codec> Clone for PartMigration<K, V> {
319    fn clone(&self) -> Self {
320        match self {
321            Self::SameSchema { both } => Self::SameSchema { both: both.clone() },
322            Self::Schemaless { read } => Self::Schemaless { read: read.clone() },
323            Self::Either {
324                write,
325                read,
326                key_migration,
327                val_migration,
328            } => Self::Either {
329                write: write.clone(),
330                read: read.clone(),
331                key_migration: Arc::clone(key_migration),
332                val_migration: Arc::clone(val_migration),
333            },
334        }
335    }
336}
337
338impl<K, V> PartMigration<K, V>
339where
340    K: Debug + Codec,
341    V: Debug + Codec,
342{
343    pub(crate) async fn new<T, D>(
344        part: &BatchPart<T>,
345        read: Schemas<K, V>,
346        schema_cache: &mut SchemaCache<K, V, T, D>,
347    ) -> Result<Self, Schemas<K, V>>
348    where
349        T: Timestamp + Lattice + Codec64 + Sync,
350        D: Monoid + Codec64,
351    {
352        // At one point in time during our structured data migration, we deprecated the
353        // already written schema IDs because we made all columns at the Arrow/Parquet
354        // level nullable, thus changing the schema parts were written with.
355        //
356        // _After_ this deprecation, we've observed at least one instance where a
357        // structured only Part was written with the schema ID in the _old_ deprecated
358        // field. While unexpected, given the ordering of our releases it is safe to
359        // use the deprecated schema ID if we have a structured only part.
360        let write = match (part.schema_id(), part.deprecated_schema_id()) {
361            (Some(write_id), _) => Some(write_id),
362            (None, Some(deprecated_id))
363                if part.is_structured_only(&schema_cache.applier.metrics.columnar) =>
364            {
365                tracing::warn!(?deprecated_id, "falling back to deprecated schema ID");
366                Some(deprecated_id)
367            }
368            (None, _) => None,
369        };
370
371        match (write, read.id) {
372            (None, _) => Ok(PartMigration::Schemaless { read }),
373            (Some(w), Some(r)) if w == r => Ok(PartMigration::SameSchema { both: read }),
374            (Some(w), _) => {
375                let write = schema_cache
376                    .schemas(&w)
377                    .await
378                    .expect("appended part should reference registered schema");
379                // Even if we missing a schema id, if the schemas are equal, use
380                // `SameSchema`. This isn't a correctness issue, we'd just
381                // generate NoOp migrations, but it'll make the metrics more
382                // intuitive.
383                if write.key == read.key && write.val == read.val {
384                    return Ok(PartMigration::SameSchema { both: read });
385                }
386
387                let start = Instant::now();
388                let key_migration = schema_cache
389                    .key_migration(&write, &read)
390                    .ok_or_else(|| read.clone())?;
391                let val_migration = schema_cache
392                    .val_migration(&write, &read)
393                    .ok_or_else(|| read.clone())?;
394                schema_cache
395                    .applier
396                    .metrics
397                    .schema
398                    .migration_new_count
399                    .inc();
400                schema_cache
401                    .applier
402                    .metrics
403                    .schema
404                    .migration_new_seconds
405                    .inc_by(start.elapsed().as_secs_f64());
406
407                Ok(PartMigration::Either {
408                    write,
409                    read,
410                    key_migration,
411                    val_migration,
412                })
413            }
414        }
415    }
416}
417
418impl<K: Codec, V: Codec> PartMigration<K, V> {
419    pub(crate) fn codec_read(&self) -> &Schemas<K, V> {
420        match self {
421            PartMigration::SameSchema { both } => both,
422            PartMigration::Schemaless { read } => read,
423            PartMigration::Either { read, .. } => read,
424        }
425    }
426}
427
428#[cfg(test)]
429mod tests {
430    use arrow::array::{
431        Array, ArrayBuilder, StringArray, StringBuilder, StructArray, as_string_array,
432    };
433    use arrow::datatypes::{DataType, Field};
434    use bytes::BufMut;
435    use futures::StreamExt;
436    use mz_dyncfg::ConfigUpdates;
437    use mz_persist_types::ShardId;
438    use mz_persist_types::arrow::ArrayOrd;
439    use mz_persist_types::codec_impls::UnitSchema;
440    use mz_persist_types::columnar::{ColumnDecoder, ColumnEncoder, Schema};
441    use mz_persist_types::stats::{NoneStats, StructStats};
442    use timely::progress::Antichain;
443
444    use mz_ore::metrics::MetricsRegistry;
445    use mz_persist::location::{Blob, Consensus};
446    use mz_persist::mem::{MemBlob, MemBlobConfig, MemConsensus};
447    use std::sync::atomic::{AtomicBool, Ordering};
448
449    use crate::async_runtime::IsolatedRuntime;
450    use crate::cache::StateCache;
451    use crate::cli::admin::info_log_non_zero_metrics;
452    use crate::internal::metrics::Metrics;
453    use crate::read::ReadHandle;
454    use crate::rpc::NoopPubSubSender;
455    use crate::tests::{LoseOneCasResponse, new_test_client};
456    use crate::{Diagnostics, PersistClient, PersistConfig};
457
458    use super::*;
459
460    #[mz_ore::test]
461    fn schema_id() {
462        assert_eq!(SchemaId(1).to_string(), "h1");
463        assert_eq!(SchemaId::try_from("h1".to_owned()), Ok(SchemaId(1)));
464        assert!(SchemaId::try_from("nope".to_owned()).is_err());
465    }
466
467    #[derive(Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
468    struct Strings(Vec<String>);
469
470    impl Codec for Strings {
471        type Schema = StringsSchema;
472        type Storage = ();
473
474        fn codec_name() -> String {
475            "Strings".into()
476        }
477
478        fn encode<B: BufMut>(&self, buf: &mut B) {
479            buf.put_slice(self.0.join(",").as_bytes());
480        }
481        fn decode<'a>(buf: &'a [u8], schema: &Self::Schema) -> Result<Self, String> {
482            let buf = std::str::from_utf8(buf).map_err(|err| err.to_string())?;
483            let mut ret = buf.split(",").map(|x| x.to_owned()).collect::<Vec<_>>();
484            // Fill in nulls or drop columns to match the requested schema.
485            while schema.0.len() > ret.len() {
486                ret.push("".into());
487            }
488            while schema.0.len() < ret.len() {
489                ret.pop();
490            }
491            Ok(Strings(ret))
492        }
493
494        fn encode_schema(schema: &Self::Schema) -> bytes::Bytes {
495            schema
496                .0
497                .iter()
498                .map(|x| x.then_some('n').unwrap_or(' '))
499                .collect::<String>()
500                .into_bytes()
501                .into()
502        }
503        fn decode_schema(buf: &bytes::Bytes) -> Self::Schema {
504            let buf = std::str::from_utf8(buf).expect("valid schema");
505            StringsSchema(
506                buf.chars()
507                    .map(|x| match x {
508                        'n' => true,
509                        ' ' => false,
510                        _ => unreachable!(),
511                    })
512                    .collect(),
513            )
514        }
515    }
516
517    #[derive(Debug, Clone, Default, PartialEq)]
518    struct StringsSchema(Vec<bool>);
519
520    impl Schema<Strings> for StringsSchema {
521        type ArrowColumn = StructArray;
522        type Statistics = NoneStats;
523        type Decoder = StringsDecoder;
524        type Encoder = StringsEncoder;
525
526        fn decoder(&self, col: Self::ArrowColumn) -> Result<Self::Decoder, anyhow::Error> {
527            let mut cols = Vec::new();
528            for (idx, _) in self.0.iter().enumerate() {
529                cols.push(as_string_array(col.column_by_name(&idx.to_string()).unwrap()).clone());
530            }
531            Ok(StringsDecoder(cols))
532        }
533        fn encoder(&self) -> Result<Self::Encoder, anyhow::Error> {
534            let mut fields = Vec::new();
535            let mut arrays = Vec::new();
536            for (idx, nullable) in self.0.iter().enumerate() {
537                fields.push(Field::new(idx.to_string(), DataType::Utf8, *nullable));
538                arrays.push(StringBuilder::new());
539            }
540            Ok(StringsEncoder { fields, arrays })
541        }
542    }
543
544    #[derive(Debug)]
545    struct StringsDecoder(Vec<StringArray>);
546    impl ColumnDecoder<Strings> for StringsDecoder {
547        fn decode(&self, idx: usize, val: &mut Strings) {
548            val.0.clear();
549            for col in self.0.iter() {
550                if col.is_valid(idx) {
551                    val.0.push(col.value(idx).into());
552                } else {
553                    val.0.push("".into());
554                }
555            }
556        }
557        fn is_null(&self, _: usize) -> bool {
558            false
559        }
560        fn goodbytes(&self) -> usize {
561            self.0
562                .iter()
563                .map(|val| ArrayOrd::String(val.clone()).goodbytes())
564                .sum()
565        }
566        fn stats(&self) -> StructStats {
567            StructStats {
568                len: self.0[0].len(),
569                cols: Default::default(),
570            }
571        }
572    }
573
574    #[derive(Debug)]
575    struct StringsEncoder {
576        fields: Vec<Field>,
577        arrays: Vec<StringBuilder>,
578    }
579    impl ColumnEncoder<Strings> for StringsEncoder {
580        type FinishedColumn = StructArray;
581
582        fn goodbytes(&self) -> usize {
583            self.arrays.iter().map(|a| a.values_slice().len()).sum()
584        }
585
586        fn append(&mut self, val: &Strings) {
587            for (idx, val) in val.0.iter().enumerate() {
588                if val.is_empty() {
589                    self.arrays[idx].append_null();
590                } else {
591                    self.arrays[idx].append_value(val);
592                }
593            }
594        }
595        fn append_null(&mut self) {
596            unreachable!()
597        }
598        fn finish(self) -> Self::FinishedColumn {
599            assert_eq!(self.fields.len(), self.arrays.len(), "invalid schema");
600            if self.fields.is_empty() {
601                StructArray::new_empty_fields(0, None)
602            } else {
603                let arrays = self
604                    .arrays
605                    .into_iter()
606                    .map(|mut x| ArrayBuilder::finish(&mut x))
607                    .collect();
608                StructArray::new(self.fields.into(), arrays, None)
609            }
610        }
611    }
612
613    #[mz_persist_proc::test(tokio::test)]
614    #[cfg_attr(miri, ignore)]
615    async fn compare_and_evolve_schema(dyncfgs: ConfigUpdates) {
616        let client = new_test_client(&dyncfgs).await;
617        let d = Diagnostics::for_tests();
618        let shard_id = ShardId::new();
619        let schema0 = StringsSchema(vec![false]);
620        let schema1 = StringsSchema(vec![false, true]);
621
622        let mut write0 = client
623            .open_writer::<Strings, (), u64, i64>(
624                shard_id,
625                Arc::new(schema0.clone()),
626                Arc::new(UnitSchema),
627                d.clone(),
628            )
629            .await
630            .unwrap();
631
632        write0.try_register_schema().await;
633        assert_eq!(write0.write_schemas.id.unwrap(), SchemaId(0));
634
635        // Not backward compatible (yet... we don't support dropping a column at
636        // the moment).
637        let res = client
638            .compare_and_evolve_schema::<Strings, (), u64, i64>(
639                shard_id,
640                SchemaId(0),
641                &StringsSchema(vec![]),
642                &UnitSchema,
643                d.clone(),
644            )
645            .await
646            .unwrap();
647        assert_eq!(res, CaESchema::Incompatible);
648
649        // Incorrect expectation
650        let res = client
651            .compare_and_evolve_schema::<Strings, (), u64, i64>(
652                shard_id,
653                SchemaId(1),
654                &schema1,
655                &UnitSchema,
656                d.clone(),
657            )
658            .await
659            .unwrap();
660        assert_eq!(
661            res,
662            CaESchema::ExpectedMismatch {
663                schema_id: SchemaId(0),
664                key: schema0,
665                val: UnitSchema
666            }
667        );
668
669        // Successful evolution
670        let res = client
671            .compare_and_evolve_schema::<Strings, (), u64, i64>(
672                shard_id,
673                SchemaId(0),
674                &schema1,
675                &UnitSchema,
676                d.clone(),
677            )
678            .await
679            .unwrap();
680        assert_eq!(res, CaESchema::Ok(SchemaId(1)));
681
682        // Create a write handle with the new schema and validate that it picks
683        // up the correct schema id.
684        let write1 = client
685            .open_writer::<Strings, (), u64, i64>(
686                shard_id,
687                Arc::new(schema1),
688                Arc::new(UnitSchema),
689                d.clone(),
690            )
691            .await
692            .unwrap();
693        assert_eq!(write1.write_schemas.id.unwrap(), SchemaId(1));
694    }
695
696    /// Regression test for SQL-616. `compare_and_evolve_schema` runs through
697    /// `apply_unbatched_idempotent_cmd`, which retries indeterminate errors. A
698    /// retry re-runs the command against state that already carries our own
699    /// evolution, so it must report success rather than an expectation
700    /// mismatch.
701    #[mz_ore::test(tokio::test)]
702    #[cfg_attr(miri, ignore)]
703    async fn compare_and_evolve_schema_indeterminate_retry() {
704        let cfg = PersistConfig::new_for_tests();
705        let armed = Arc::new(AtomicBool::new(false));
706        let consensus = Arc::new(LoseOneCasResponse {
707            inner: Arc::new(MemConsensus::default()),
708            armed: Arc::clone(&armed),
709        });
710        let metrics = Arc::new(Metrics::new(&cfg, &MetricsRegistry::new()));
711        let client = PersistClient::new(
712            cfg,
713            Arc::new(MemBlob::open(MemBlobConfig::default())),
714            consensus,
715            Arc::clone(&metrics),
716            Arc::new(IsolatedRuntime::new_for_tests()),
717            Arc::new(StateCache::new_no_metrics()),
718            Arc::new(NoopPubSubSender),
719        )
720        .expect("client construction failed");
721
722        let d = Diagnostics::for_tests();
723        let shard_id = ShardId::new();
724        let schema0 = StringsSchema(vec![false]);
725        let schema1 = StringsSchema(vec![false, true]);
726
727        let mut write0 = client
728            .open_writer::<Strings, (), u64, i64>(
729                shard_id,
730                Arc::new(schema0),
731                Arc::new(UnitSchema),
732                d.clone(),
733            )
734            .await
735            .unwrap();
736        write0.try_register_schema().await;
737        assert_eq!(write0.write_schemas.id.unwrap(), SchemaId(0));
738
739        // Check that the evolve actually retried, not just that some CaS
740        // consumed the arm. Single writer, no compaction, so only the evolve's
741        // CaS can.
742        let retries_before = metrics.retries.idempotent_cmd.retries.get();
743        armed.store(true, Ordering::SeqCst);
744        let res = client
745            .compare_and_evolve_schema::<Strings, (), u64, i64>(
746                shard_id,
747                SchemaId(0),
748                &schema1,
749                &UnitSchema,
750                d.clone(),
751            )
752            .await
753            .unwrap();
754        assert!(
755            !armed.load(Ordering::SeqCst),
756            "indeterminate error was never injected"
757        );
758        assert!(
759            metrics.retries.idempotent_cmd.retries.get() > retries_before,
760            "evolve did not retry an indeterminate error"
761        );
762        // Old check order returns ExpectedMismatch here; the fix returns Ok.
763        assert_eq!(res, CaESchema::Ok(SchemaId(1)));
764    }
765
766    /// A client with its own metrics and state cache and without PubSub, like
767    /// a separate process.
768    fn new_process(blob: &Arc<dyn Blob>, consensus: &Arc<dyn Consensus>) -> PersistClient {
769        let cfg = PersistConfig::new_for_tests();
770        let metrics = Arc::new(Metrics::new(&cfg, &MetricsRegistry::new()));
771        PersistClient::new(
772            cfg,
773            Arc::clone(blob),
774            Arc::clone(consensus),
775            metrics,
776            Arc::new(IsolatedRuntime::new_for_tests()),
777            Arc::new(StateCache::new_no_metrics()),
778            Arc::new(NoopPubSubSender),
779        )
780        .expect("client construction failed")
781    }
782
783    /// Regression test for PER-130.
784    #[mz_ore::test(tokio::test)]
785    #[cfg_attr(miri, ignore)]
786    async fn append_with_schema_evolved_by_other_process() {
787        let blob: Arc<dyn Blob> = Arc::new(MemBlob::open(MemBlobConfig::default()));
788        let consensus: Arc<dyn Consensus> = Arc::new(MemConsensus::default());
789        let evolver = new_process(&blob, &consensus);
790        let appender = new_process(&blob, &consensus);
791        let d = Diagnostics::for_tests();
792        let shard_id = ShardId::new();
793        let schema1 = StringsSchema(vec![false, true]);
794
795        // Keeps the appender's cached state alive, at schema 0.
796        let mut write0 = appender
797            .open_writer::<Strings, (), u64, i64>(
798                shard_id,
799                Arc::new(StringsSchema(vec![false])),
800                Arc::new(UnitSchema),
801                d.clone(),
802            )
803            .await
804            .unwrap();
805        write0.try_register_schema().await;
806
807        let res = evolver
808            .compare_and_evolve_schema::<Strings, (), u64, i64>(
809                shard_id,
810                SchemaId(0),
811                &schema1,
812                &UnitSchema,
813                d.clone(),
814            )
815            .await
816            .unwrap();
817        assert_eq!(res, CaESchema::Ok(SchemaId(1)));
818
819        let mut write1 = appender
820            .open_writer::<Strings, (), u64, i64>(
821                shard_id,
822                Arc::new(schema1),
823                Arc::new(UnitSchema),
824                d.clone(),
825            )
826            .await
827            .unwrap();
828        assert_eq!(write1.schema_id(), None, "appender state should be stale");
829        write1
830            .compare_and_append_batch(
831                &mut [],
832                Antichain::from_elem(0),
833                Antichain::from_elem(1),
834                true,
835            )
836            .await
837            .unwrap()
838            .unwrap();
839        assert_eq!(write1.schema_id(), Some(SchemaId(1)));
840    }
841
842    #[mz_ore::test(tokio::test)]
843    #[cfg_attr(miri, ignore)]
844    async fn register_schema_on_tombstone_skips_refetch() {
845        let blob: Arc<dyn Blob> = Arc::new(MemBlob::open(MemBlobConfig::default()));
846        let consensus: Arc<dyn Consensus> = Arc::new(MemConsensus::default());
847        // The registerer's metrics count only its own state fetches.
848        let finalizer = new_process(&blob, &consensus);
849        let registerer = new_process(&blob, &consensus);
850        let d = Diagnostics::for_tests();
851        let shard_id = ShardId::new();
852
853        let (mut write, mut read) = finalizer
854            .open::<Strings, (), u64, i64>(
855                shard_id,
856                Arc::new(StringsSchema(vec![false])),
857                Arc::new(UnitSchema),
858                d.clone(),
859                true,
860            )
861            .await
862            .unwrap();
863        read.downgrade_since(&Antichain::new()).await;
864        write.advance_upper(&Antichain::new()).await;
865        write.expire().await;
866        read.expire().await;
867
868        let machine = registerer
869            .make_machine::<Strings, (), u64, i64>(shard_id, d)
870            .await
871            .unwrap();
872        assert!(machine.applier.is_tombstone());
873        let state = &registerer.metrics.state;
874        let fetches = || {
875            state.update_state_noop_path.get()
876                + state.update_state_empty_path.get()
877                + state.update_state_fast_path.get()
878                + state.update_state_slow_path.get()
879        };
880        let before = fetches();
881        let (schema_id, _) = machine
882            .register_schema(&StringsSchema(vec![false, true]), &UnitSchema)
883            .await;
884        assert_eq!(schema_id, None);
885        assert_eq!(fetches(), before, "tombstone should skip the refetch");
886    }
887
888    fn strings(xs: &[((Strings, ()), u64, i64)]) -> Vec<Vec<&str>> {
889        xs.iter()
890            .map(|((k, _), _, _)| k.0.iter().map(|x| x.as_str()).collect())
891            .collect()
892    }
893
894    #[mz_persist_proc::test(tokio::test)]
895    #[cfg_attr(miri, ignore)]
896    async fn schema_evolution(dyncfgs: ConfigUpdates) {
897        async fn snap_streaming(
898            as_of: u64,
899            read: &mut ReadHandle<Strings, (), u64, i64>,
900        ) -> Vec<((Strings, ()), u64, i64)> {
901            // NB: We test with both snapshot_and_fetch and snapshot_and_stream
902            // because one uses the consolidating iter and one doesn't.
903            let mut ret = read
904                .snapshot_and_stream(Antichain::from_elem(as_of))
905                .await
906                .unwrap()
907                .collect::<Vec<_>>()
908                .await;
909            ret.sort();
910            ret
911        }
912
913        let client = new_test_client(&dyncfgs).await;
914        let d = Diagnostics::for_tests();
915        let shard_id = ShardId::new();
916        let schema0 = StringsSchema(vec![false]);
917        let schema1 = StringsSchema(vec![false, true]);
918
919        // Write some data at the original schema.
920        let (mut write0, mut read0) = client
921            .open::<Strings, (), u64, i64>(
922                shard_id,
923                Arc::new(schema0.clone()),
924                Arc::new(UnitSchema),
925                d.clone(),
926                true,
927            )
928            .await
929            .unwrap();
930        write0
931            .expect_compare_and_append(&[((Strings(vec!["0 before".into()]), ()), 0, 1)], 0, 1)
932            .await;
933        let expected = vec![vec!["0 before"]];
934        assert_eq!(strings(&snap_streaming(0, &mut read0).await), expected);
935        assert_eq!(strings(&read0.expect_snapshot_and_fetch(0).await), expected);
936
937        // Register and write some data at the new schema.
938        let res = client
939            .compare_and_evolve_schema::<Strings, (), u64, i64>(
940                shard_id,
941                SchemaId(0),
942                &schema1,
943                &UnitSchema,
944                d.clone(),
945            )
946            .await
947            .unwrap();
948        assert_eq!(res, CaESchema::Ok(SchemaId(1)));
949        let (mut write1, mut read1) = client
950            .open::<Strings, (), u64, i64>(
951                shard_id,
952                Arc::new(schema1.clone()),
953                Arc::new(UnitSchema),
954                d.clone(),
955                true,
956            )
957            .await
958            .unwrap();
959        write1
960            .expect_compare_and_append(
961                &[
962                    ((Strings(vec!["1 null".into(), "".into()]), ()), 1, 1),
963                    ((Strings(vec!["1 not".into(), "x".into()]), ()), 1, 1),
964                ],
965                1,
966                2,
967            )
968            .await;
969
970        // Continue to write data with the original schema.
971        write0
972            .expect_compare_and_append(&[((Strings(vec!["0 after".into()]), ()), 2, 1)], 2, 3)
973            .await;
974
975        // Original schema drops the new column in data written by new schema.
976        let expected = vec![
977            vec!["0 after"],
978            vec!["0 before"],
979            vec!["1 not"],
980            vec!["1 null"],
981        ];
982        assert_eq!(strings(&snap_streaming(2, &mut read0).await), expected);
983        assert_eq!(strings(&read0.expect_snapshot_and_fetch(2).await), expected);
984
985        // New schema adds nulls (represented by empty string in Strings) in
986        // data written by old schema.
987        let expected = vec![
988            vec!["0 after", ""],
989            vec!["0 before", ""],
990            vec!["1 not", "x"],
991            vec!["1 null", ""],
992        ];
993        assert_eq!(strings(&snap_streaming(2, &mut read1).await), expected);
994        assert_eq!(strings(&read1.expect_snapshot_and_fetch(2).await), expected);
995
996        // Probably too spammy to leave in the logs, but it was useful to have
997        // hooked up while iterating.
998        if false {
999            info_log_non_zero_metrics(&client.metrics.registry.gather());
1000        }
1001    }
1002}