Skip to main content

mz_catalog_decode/
audit_log.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//! Reshape proto `audit_log_event_v1::Details` JSON back into the shape
11//! `mz_audit_log::EventDetails::as_json` produces.
12//!
13//! The `mz_audit_events` MV reads audit events from `mz_catalog_raw` as
14//! their durable proto twin (`mz_catalog_protos::objects::audit_log_event_v1`)
15//! and projects `details` through the SQL scalar
16//! `parse_catalog_audit_log_details`. Its output must equal what the prior
17//! `pack_audit_log_update` populator wrote, i.e.
18//! `mz_audit_log::EventDetails::as_json`.
19//!
20//! The reshape is driven by five rule tables below plus two structural
21//! rewrites (`StringWrapper` unwrap and the `ResetAllV1` null case). See the
22//! individual table docstrings for their shapes. The reciprocal is
23//! `EventDetails::as_json` combined with the proto `RustType` conversion in
24//! `src/catalog/src/durable/objects/serialization/audit_log.rs`. The
25//! round-trip property test at `src/catalog/tests/audit_log_details.rs`
26//! samples every `Arbitrary` variant and catches drift when either side gains
27//! a new variant, field, or serde attribute.
28
29use mz_repr::adt::jsonb::{Jsonb, JsonbRef};
30use mz_repr::{Datum, Row, RowPacker};
31
32/// Reshapes proto `audit_log_event_v1::Details` JSON from `mz_catalog_raw`
33/// (e.g. `{"IdFullNameV1": {"id": "u1", "name": {...}}}`) into the shape
34/// `mz_audit_log::EventDetails::as_json` produces: the format the prior
35/// `pack_audit_log_update` populator wrote to `mz_audit_events`.
36///
37/// See the module docstring for the mechanism and the reciprocal side. Rule
38/// changes must be paired with tests; the property test at
39/// `src/catalog/tests/audit_log_details.rs` is the safety net.
40pub fn details(a: JsonbRef<'_>) -> Result<Jsonb, String> {
41    /// `(variant, path, field, sub_variant)`: `#[serde(flatten)]` sites.
42    /// `sub_variant` sets the context for rules on the hoisted content
43    /// when the flattened struct itself has a `#[serde(flatten)]`.
44    const FLATTENED_FIELDS: &[(&str, &str, &str, Option<&str>)] = &[
45        ("IdFullNameV1", "", "name", None),
46        ("CreateSourceSinkV1", "", "name", None),
47        ("CreateSourceSinkV2", "", "name", None),
48        ("CreateSourceSinkV3", "", "name", None),
49        ("CreateSourceSinkV4", "", "name", None),
50        ("CreateIndexV1", "", "name", None),
51        ("CreateMaterializedViewV1", "", "name", None),
52        ("AlterSourceSinkV1", "", "name", None),
53        ("AlterSetClusterV1", "", "name", None),
54        ("UpdateItemV1", "", "name", None),
55        // `AlterApplyReplacementV1.target: IdFullNameV1`, which itself
56        // flattens `name: FullNameV1`.
57        (
58            "AlterApplyReplacementV1",
59            "",
60            "target",
61            Some("IdFullNameV1"),
62        ),
63    ];
64
65    /// `(variant, path, proto_key, audit_key)`: covers `#[serde(rename)]`
66    /// on the audit-log side and Rust field-name diffs between the crates.
67    const RENAMES: &[(&str, &str, &str, &str)] = &[
68        ("CreateSourceSinkV2", "", "external_type", "type"),
69        ("CreateSourceSinkV3", "", "external_type", "type"),
70        ("CreateSourceSinkV4", "", "external_type", "type"),
71        (
72            "RefreshDecisionWithReasonV1",
73            "",
74            "rehydration_time_estimate",
75            "hydration_time_estimate",
76        ),
77        (
78            "RefreshDecisionWithReasonV2",
79            "",
80            "rehydration_time_estimate",
81            "hydration_time_estimate",
82        ),
83    ];
84
85    /// `(variant, path, field)`: drop when null. Keyed on the variant
86    /// because the same field skips in V1 but is nullable in V2+
87    /// (e.g. `replica_id`).
88    const DROP_NULL: &[(&str, &str, &str)] = &[
89        ("CreateClusterReplicaV1", "", "replica_id"),
90        ("DropClusterReplicaV1", "", "replica_id"),
91        ("CreateClusterReplicaV2", "", "scheduling_policies"),
92        ("CreateClusterReplicaV3", "", "scheduling_policies"),
93        ("CreateClusterReplicaV4", "", "scheduling_policies"),
94        ("DropClusterReplicaV2", "", "scheduling_policies"),
95        ("DropClusterReplicaV3", "", "scheduling_policies"),
96        ("CreateMaterializedViewV1", "", "replacement_target_id"),
97    ];
98
99    /// Kebab map for `CreateOrDropClusterReplicaReasonV1`, shared across
100    /// cluster-replica create and drop events.
101    const REASON_MAP: &[(&str, &str)] = &[
102        ("Manual", "manual"),
103        ("Schedule", "schedule"),
104        ("System", "system"),
105        ("Reconfiguration", "reconfiguration"),
106        ("HydrationBurst", "hydration-burst"),
107        ("Retired", "retired"),
108    ];
109
110    /// `(variant, path, field, wrap, kebab_map)`: collapse a proto enum-
111    /// with-`Empty`-payload into a kebab string. `Single` is `{"K": {}}`;
112    /// `Double` is `{"<field>": {"K": {}}}`, where the outer key matches
113    /// the field name in the current schemas (`reason`, `transition`).
114    /// Unlisted variants error (fail-fast).
115    #[allow(dead_code)]
116    #[derive(Copy, Clone)]
117    enum WrapKind {
118        Single,
119        Double,
120    }
121    const ENUM_COLLAPSE: &[(&str, &str, &str, WrapKind, &[(&str, &str)])] = &[
122        (
123            "RefreshDecisionWithReasonV1",
124            "",
125            "decision",
126            WrapKind::Single,
127            &[("On", "on"), ("Off", "off")],
128        ),
129        (
130            "RefreshDecisionWithReasonV2",
131            "",
132            "decision",
133            WrapKind::Single,
134            &[("On", "on"), ("Off", "off")],
135        ),
136        (
137            "CreateClusterReplicaV2",
138            "",
139            "reason",
140            WrapKind::Double,
141            REASON_MAP,
142        ),
143        (
144            "CreateClusterReplicaV3",
145            "",
146            "reason",
147            WrapKind::Double,
148            REASON_MAP,
149        ),
150        (
151            "CreateClusterReplicaV4",
152            "",
153            "reason",
154            WrapKind::Double,
155            REASON_MAP,
156        ),
157        (
158            "DropClusterReplicaV2",
159            "",
160            "reason",
161            WrapKind::Double,
162            REASON_MAP,
163        ),
164        (
165            "DropClusterReplicaV3",
166            "",
167            "reason",
168            WrapKind::Double,
169            REASON_MAP,
170        ),
171        (
172            "AlterClusterReconfigurationV1",
173            "",
174            "transition",
175            WrapKind::Double,
176            &[
177                ("Started", "started"),
178                ("Finalized", "finalized"),
179                ("TimedOut", "timed-out"),
180                ("Cancelled", "cancelled"),
181                ("ResourceExhausted", "resource-exhausted"),
182            ],
183        ),
184        (
185            "ClusterHydrationBurstV1",
186            "",
187            "transition",
188            WrapKind::Double,
189            &[("Started", "started"), ("Finished", "finished")],
190        ),
191        (
192            "ClusterHydrationBurstV1",
193            "",
194            "finish_cause",
195            WrapKind::Double,
196            &[
197                ("LingerElapsed", "linger-elapsed"),
198                ("NoLongerWarranted", "no-longer-warranted"),
199            ],
200        ),
201    ];
202
203    /// `(variant, path, field, sub_variant)`: recurse with `sub_variant` as
204    /// the new context so rules declared from its root fire. Used for
205    /// versioned nested wrappers (`SchedulingDecisionsWithReasonsV1/V2`)
206    /// and by-value `IdFullNameV1` fields whose inner `name: FullNameV1`
207    /// needs flattening.
208    const DESCEND: &[(&str, &str, &str, &str)] = &[
209        ("AlterApplyReplacementV1", "", "replacement", "IdFullNameV1"),
210        (
211            "CreateClusterReplicaV2",
212            "",
213            "scheduling_policies",
214            "SchedulingDecisionsWithReasonsV1",
215        ),
216        (
217            "CreateClusterReplicaV3",
218            "",
219            "scheduling_policies",
220            "SchedulingDecisionsWithReasonsV2",
221        ),
222        (
223            "CreateClusterReplicaV4",
224            "",
225            "scheduling_policies",
226            "SchedulingDecisionsWithReasonsV2",
227        ),
228        (
229            "DropClusterReplicaV2",
230            "",
231            "scheduling_policies",
232            "SchedulingDecisionsWithReasonsV1",
233        ),
234        (
235            "DropClusterReplicaV3",
236            "",
237            "scheduling_policies",
238            "SchedulingDecisionsWithReasonsV2",
239        ),
240        (
241            "SchedulingDecisionsWithReasonsV1",
242            "",
243            "on_refresh",
244            "RefreshDecisionWithReasonV1",
245        ),
246        (
247            "SchedulingDecisionsWithReasonsV2",
248            "",
249            "on_refresh",
250            "RefreshDecisionWithReasonV2",
251        ),
252    ];
253
254    fn lookup_flatten(variant: &str, path: &str, field: &str) -> Option<Option<&'static str>> {
255        FLATTENED_FIELDS
256            .iter()
257            .find(|(v, p, f, _)| *v == variant && *p == path && *f == field)
258            .map(|(_, _, _, sv)| *sv)
259    }
260
261    fn lookup_rename(variant: &str, path: &str, field: &str) -> Option<&'static str> {
262        RENAMES
263            .iter()
264            .find(|(v, p, k, _)| *v == variant && *p == path && *k == field)
265            .map(|(_, _, _, out)| *out)
266    }
267
268    fn is_drop_null(variant: &str, path: &str, field: &str) -> bool {
269        DROP_NULL
270            .iter()
271            .any(|(v, p, f)| *v == variant && *p == path && *f == field)
272    }
273
274    fn lookup_enum_collapse(
275        variant: &str,
276        path: &str,
277        field: &str,
278    ) -> Option<(WrapKind, &'static [(&'static str, &'static str)])> {
279        ENUM_COLLAPSE
280            .iter()
281            .find(|(v, p, f, _, _)| *v == variant && *p == path && *f == field)
282            .map(|(_, _, _, wrap, map)| (*wrap, *map))
283    }
284
285    fn lookup_descend(variant: &str, path: &str, field: &str) -> Option<&'static str> {
286        DESCEND
287            .iter()
288            .find(|(v, p, f, _)| *v == variant && *p == path && *f == field)
289            .map(|(_, _, _, sv)| *sv)
290    }
291
292    /// Unwrap a proto externally-tagged enum-with-`Empty`-payload and return
293    /// its kebab form from `map`. Errors on unexpected shapes or unknown
294    /// variants.
295    fn collapse_enum(
296        datum: Datum,
297        wrap: WrapKind,
298        map: &[(&'static str, &'static str)],
299        context: &str,
300    ) -> Result<&'static str, String> {
301        let inner = match wrap {
302            WrapKind::Single => datum,
303            WrapKind::Double => {
304                let Datum::Map(outer) = datum else {
305                    return Err(format!(
306                        "{context}: double-wrap enum expected outer object, got {datum:?}"
307                    ));
308                };
309                let mut iter = outer.iter();
310                let (Some((_, v)), None) = (iter.next(), iter.next()) else {
311                    return Err(format!(
312                        "{context}: double-wrap enum expected single-key outer object"
313                    ));
314                };
315                v
316            }
317        };
318        let Datum::Map(dict) = inner else {
319            return Err(format!(
320                "{context}: enum collapse expected object, got {inner:?}"
321            ));
322        };
323        let mut iter = dict.iter();
324        let (Some((variant_key, payload)), None) = (iter.next(), iter.next()) else {
325            return Err(format!(
326                "{context}: enum collapse expected single-key object"
327            ));
328        };
329        // The payload must be `{}` (proto `Empty`); fail if a variant
330        // grows a real payload in the future.
331        if let Datum::Map(payload_dict) = payload {
332            if payload_dict.iter().next().is_some() {
333                return Err(format!(
334                    "{context}: enum variant {variant_key} carries non-empty payload"
335                ));
336            }
337        } else {
338            return Err(format!(
339                "{context}: enum variant {variant_key} payload is not an object"
340            ));
341        }
342        map.iter()
343            .find(|(k, _)| *k == variant_key)
344            .map(|(_, kebab)| *kebab)
345            .ok_or_else(|| format!("{context}: unknown enum variant {variant_key}"))
346    }
347
348    fn extend_path(path: &str, field: &str) -> String {
349        if path.is_empty() {
350            field.to_string()
351        } else {
352            format!("{path}.{field}")
353        }
354    }
355
356    /// Recursively rewrite `datum` under `(variant, path)` into `out`.
357    fn rewrite(datum: Datum, variant: &str, path: &str, out: &mut RowPacker) -> Result<(), String> {
358        match datum {
359            Datum::Map(dict) => {
360                // Structural: `{"inner": v}` (proto `StringWrapper`) -> `v`.
361                let mut iter = dict.iter();
362                if let (Some((k, v)), None) = (iter.next(), iter.next()) {
363                    if k == "inner" {
364                        return rewrite(v, variant, path, out);
365                    }
366                }
367                rewrite_map(dict, variant, path, out)
368            }
369            Datum::List(list) => {
370                let mut result: Result<(), String> = Ok(());
371                out.push_list_with(|out| {
372                    for v in list.iter() {
373                        if let Err(e) = rewrite(v, variant, path, out) {
374                            result = Err(e);
375                            break;
376                        }
377                    }
378                });
379                result
380            }
381            other => {
382                out.push(other);
383                Ok(())
384            }
385        }
386    }
387
388    fn rewrite_map(
389        dict: mz_repr::DatumMap,
390        variant: &str,
391        path: &str,
392        out: &mut RowPacker,
393    ) -> Result<(), String> {
394        let mut entries = collect_entries(dict, variant, path)?;
395        // Datum::Map` requires keys in ascending order.
396        // Flattening and renaming can map distinct input fields to the same key.
397        entries.sort_by(|a, b| a.0.cmp(&b.0));
398        for [(key, _), (next_key, _)] in entries.array_windows() {
399            if key == next_key {
400                return Err(format!("duplicate key {key:?} in {variant}"));
401            }
402        }
403        out.push_dict_with(|out| {
404            for (k, temp) in &entries {
405                out.push(Datum::String(k));
406                out.push(temp.unpack_first());
407            }
408        });
409        Ok(())
410    }
411
412    /// Produce the transformed `(key, temp_row)` pairs for `dict` under
413    /// `(variant, path)`. Split from `rewrite_map` so the flatten path can
414    /// hoist a fully-processed sub-entry list into the parent.
415    fn collect_entries(
416        dict: mz_repr::DatumMap,
417        variant: &str,
418        path: &str,
419    ) -> Result<Vec<(String, Row)>, String> {
420        let mut entries: Vec<(String, Row)> = Vec::new();
421
422        for (k, v) in dict.iter() {
423            if is_drop_null(variant, path, k) && matches!(v, Datum::JsonNull) {
424                continue;
425            }
426
427            // Flatten: hoist the sub-object's entries into the parent.
428            if let Some(sub_variant_opt) = lookup_flatten(variant, path, k) {
429                let sub_variant = sub_variant_opt.unwrap_or("");
430                let Datum::Map(sub) = v else {
431                    return Err(format!(
432                        "expected flatten target {variant}.{k} to be an object"
433                    ));
434                };
435                entries.extend(collect_entries(sub, sub_variant, "")?);
436                continue;
437            }
438
439            let out_key = lookup_rename(variant, path, k).unwrap_or(k).to_string();
440
441            // Enum collapse produces a computed string. An optional enum
442            // field (e.g. `finish_cause`) serializes as JSON null on both the
443            // proto and the audit-log side, so null passes through unchanged.
444            if let Some((wrap, map)) = lookup_enum_collapse(variant, path, k) {
445                if matches!(v, Datum::JsonNull) {
446                    let mut temp = Row::default();
447                    temp.packer().push(Datum::JsonNull);
448                    entries.push((out_key, temp));
449                    continue;
450                }
451                let kebab = collapse_enum(v, wrap, map, &format!("{variant}.{k}"))?;
452                let mut temp = Row::default();
453                temp.packer().push(Datum::String(kebab));
454                entries.push((out_key, temp));
455                continue;
456            }
457
458            // Descend: recurse with a fresh variant context (path resets;
459            // rules on the sub-variant are declared from its root).
460            if let Some(sub_variant) = lookup_descend(variant, path, k) {
461                let mut temp = Row::default();
462                rewrite(v, sub_variant, "", &mut temp.packer())?;
463                entries.push((out_key, temp));
464                continue;
465            }
466
467            // Default: recurse with the same variant and an extended path.
468            let child_path = extend_path(path, k);
469            let mut temp = Row::default();
470            rewrite(v, variant, &child_path, &mut temp.packer())?;
471            entries.push((out_key, temp));
472        }
473
474        Ok(entries)
475    }
476
477    let Datum::Map(dict) = a.into_datum() else {
478        return Err("expected object".into());
479    };
480    let mut iter = dict.iter();
481    let (variant, inner) = iter
482        .next()
483        .ok_or_else(|| "empty details enum".to_string())?;
484    if iter.next().is_some() {
485        return Err("details enum had multiple keys".into());
486    }
487    let mut row = Row::default();
488    // `ResetAllV1` is the only variant `as_json` maps to null (the
489    // proto `Empty` payload serializes to `{}`).
490    if variant == "ResetAllV1" {
491        row.packer().push(Datum::JsonNull);
492        return Ok(Jsonb::from_row(row));
493    }
494    let Datum::Map(_) = inner else {
495        return Err(format!("expected inner object for variant {variant}"));
496    };
497    rewrite(inner, variant, "", &mut row.packer())?;
498    Ok(Jsonb::from_row(row))
499}
500
501#[cfg(test)]
502mod tests {
503    use super::*;
504
505    /// Round-trip a JSON `input` through `details` and
506    /// assert the resulting JSON parses equal to `expected`.
507    fn check(input: &str, expected: &str) {
508        let input: Jsonb = input.parse().expect("valid input JSONB");
509        let actual = details(input.as_ref())
510            .expect("helper succeeded")
511            .to_string();
512        let actual_value: serde_json::Value =
513            serde_json::from_str(&actual).expect("valid output JSON");
514        let expected_value: serde_json::Value =
515            serde_json::from_str(expected).expect("valid expected JSON");
516        assert_eq!(actual_value, expected_value);
517    }
518
519    /// Run `details` on `input` and assert it returns an error containing
520    /// `expected_substr`.
521    fn check_err(input: &str, expected_substr: &str) {
522        let input: Jsonb = input.parse().expect("valid input JSONB");
523        let err = details(input.as_ref()).expect_err("helper should error");
524        let msg = format!("{err:?}");
525        assert!(
526            msg.contains(expected_substr),
527            "error did not contain {expected_substr:?}: {msg}",
528        );
529    }
530
531    /// Variant with no nested struct and no `#[serde(flatten)]`. The helper
532    /// just strips the wrapper.
533    #[mz_ore::test]
534    fn variant_strip() {
535        check(
536            r#"{"IdNameV1": {"id": "u1", "name": "foo"}}"#,
537            r#"{"id": "u1", "name": "foo"}"#,
538        );
539    }
540
541    /// `IdFullNameV1` has `#[serde(flatten)] name: FullNameV1`. The helper
542    /// must hoist `database`/`schema`/`item` to the top level.
543    #[mz_ore::test]
544    fn flatten_name() {
545        check(
546            r#"{"IdFullNameV1": {
547                "id": "u1",
548                "name": {"database": "materialize", "schema": "public", "item": "t"}
549            }}"#,
550            r#"{"id": "u1", "database": "materialize", "schema": "public", "item": "t"}"#,
551        );
552    }
553
554    /// `AlterApplyReplacementV1` flattens `target: IdFullNameV1`, which itself
555    /// flattens `name: FullNameV1`. Exercises the recursive sub-variant lookup.
556    /// The non-flattened `replacement: IdFullNameV1` field has its inner
557    /// `name` hoisted via a `DESCEND` entry pointing at `IdFullNameV1`.
558    #[mz_ore::test]
559    fn flatten_recursive_and_nested_full_name() {
560        check(
561            r#"{"AlterApplyReplacementV1": {
562                "target": {
563                    "id": "u1",
564                    "name": {"database": "materialize", "schema": "public", "item": "mv"}
565                },
566                "replacement": {
567                    "id": "u2",
568                    "name": {"database": "materialize", "schema": "public", "item": "rp"}
569                }
570            }}"#,
571            r#"{
572                "id": "u1",
573                "database": "materialize",
574                "schema": "public",
575                "item": "mv",
576                "replacement": {
577                    "id": "u2",
578                    "database": "materialize",
579                    "schema": "public",
580                    "item": "rp"
581                }
582            }"#,
583        );
584    }
585
586    /// `Option<StringWrapper>` fields serialize as `{"inner": "..."}` in the
587    /// proto, where the audit-log crate uses a plain `String`. The helper must
588    /// unwrap recursively (including on optional fields nested under flatten).
589    #[mz_ore::test]
590    fn string_wrapper_unwrap() {
591        check(
592            r#"{"AlterDefaultPrivilegeV1": {
593                "role_id": "u1",
594                "database_id": {"inner": "u2"},
595                "schema_id": {"inner": "u3"},
596                "grantee_id": "p",
597                "privileges": "r"
598            }}"#,
599            r#"{
600                "role_id": "u1",
601                "database_id": "u2",
602                "schema_id": "u3",
603                "grantee_id": "p",
604                "privileges": "r"
605            }"#,
606        );
607    }
608
609    /// Null `Option<StringWrapper>` fields are passed through as JSON null.
610    #[mz_ore::test]
611    fn null_option() {
612        check(
613            r#"{"AlterDefaultPrivilegeV1": {
614                "role_id": "u1",
615                "database_id": null,
616                "schema_id": null,
617                "grantee_id": "p",
618                "privileges": "r"
619            }}"#,
620            r#"{
621                "role_id": "u1",
622                "database_id": null,
623                "schema_id": null,
624                "grantee_id": "p",
625                "privileges": "r"
626            }"#,
627        );
628    }
629
630    /// Non-flattened nested objects pass through untouched. Guards against
631    /// re-introducing a structural "hoist any `FullNameV1`-shaped object"
632    /// heuristic: `RenameItemV1.old_name`/`new_name` are `FullNameV1` fields
633    /// the audit-log side keeps nested, and any generic structural hoist
634    /// would collide their `database`/`schema`/`item` keys.
635    #[mz_ore::test]
636    fn nested_full_name_stays_nested() {
637        check(
638            r#"{"RenameItemV1": {
639                "id": "u1",
640                "old_name": {"database": "d", "schema": "s", "item": "a"},
641                "new_name": {"database": "d", "schema": "s", "item": "b"}
642            }}"#,
643            r#"{
644                "id": "u1",
645                "old_name": {"database": "d", "schema": "s", "item": "a"},
646                "new_name": {"database": "d", "schema": "s", "item": "b"}
647            }"#,
648        );
649    }
650
651    /// Sources V2+ rename proto `external_type` to audit `type`. Value
652    /// unchanged.
653    #[mz_ore::test]
654    fn rename_external_type() {
655        check(
656            r#"{"CreateSourceSinkV2": {
657                "id": "u1",
658                "name": {"database": "d", "schema": "s", "item": "src"},
659                "size": {"inner": "small"},
660                "external_type": "kafka"
661            }}"#,
662            r#"{
663                "id": "u1",
664                "database": "d",
665                "schema": "s",
666                "item": "src",
667                "size": "small",
668                "type": "kafka"
669            }"#,
670        );
671    }
672
673    /// The proto field `rehydration_time_estimate` becomes the audit field
674    /// `hydration_time_estimate` — an invisible rename (no `#[serde(rename)]`
675    /// on either side; just a genuine field-name diff between the crates).
676    /// Nested under `scheduling_policies.on_refresh`, so the descent chain
677    /// must land in the `RefreshDecisionWithReasonV1` variant context.
678    #[mz_ore::test]
679    fn rename_hydration_time_estimate_under_scheduling() {
680        check(
681            r#"{"CreateClusterReplicaV3": {
682                "cluster_id": "u1",
683                "cluster_name": "c",
684                "replica_id": {"inner": "r1"},
685                "replica_name": "n",
686                "logical_size": "small",
687                "disk": false,
688                "billed_as": null,
689                "internal": false,
690                "reason": {"reason": {"Manual": {}}},
691                "scheduling_policies": {
692                    "on_refresh": {
693                        "decision": {"On": {}},
694                        "objects_needing_refresh": [],
695                        "objects_needing_compaction": [],
696                        "rehydration_time_estimate": "00:00:07"
697                    }
698                }
699            }}"#,
700            r#"{
701                "cluster_id": "u1",
702                "cluster_name": "c",
703                "replica_id": "r1",
704                "replica_name": "n",
705                "logical_size": "small",
706                "disk": false,
707                "billed_as": null,
708                "internal": false,
709                "reason": "manual",
710                "scheduling_policies": {
711                    "on_refresh": {
712                        "decision": "on",
713                        "objects_needing_refresh": [],
714                        "objects_needing_compaction": [],
715                        "hydration_time_estimate": "00:00:07"
716                    }
717                }
718            }"#,
719        );
720    }
721
722    /// `CreateClusterReplicaV1.replica_id` uses
723    /// `#[serde(skip_serializing_if = "Option::is_none")]` in the audit-log
724    /// struct: a null proto value must be dropped from the output.
725    #[mz_ore::test]
726    fn drop_null_replica_id_v1() {
727        check(
728            r#"{"CreateClusterReplicaV1": {
729                "cluster_id": "u1",
730                "cluster_name": "c",
731                "replica_id": null,
732                "replica_name": "n",
733                "logical_size": "small",
734                "disk": false,
735                "billed_as": null,
736                "internal": false
737            }}"#,
738            r#"{
739                "cluster_id": "u1",
740                "cluster_name": "c",
741                "replica_name": "n",
742                "logical_size": "small",
743                "disk": false,
744                "billed_as": null,
745                "internal": false
746            }"#,
747        );
748    }
749
750    /// V2+ struct keeps `replica_id` as a plain `Option<StringWrapper>` — no
751    /// `skip_serializing_if`. A null value must round-trip as JSON null.
752    /// This is the paired negative: the drop rule keys on (variant, field),
753    /// not name alone.
754    #[mz_ore::test]
755    fn drop_null_replica_id_v2_kept() {
756        check(
757            r#"{"CreateClusterReplicaV2": {
758                "cluster_id": "u1",
759                "cluster_name": "c",
760                "replica_id": null,
761                "replica_name": "n",
762                "logical_size": "small",
763                "disk": false,
764                "billed_as": null,
765                "internal": false,
766                "reason": {"reason": {"System": {}}},
767                "scheduling_policies": null
768            }}"#,
769            r#"{
770                "cluster_id": "u1",
771                "cluster_name": "c",
772                "replica_id": null,
773                "replica_name": "n",
774                "logical_size": "small",
775                "disk": false,
776                "billed_as": null,
777                "internal": false,
778                "reason": "system"
779            }"#,
780        );
781    }
782
783    /// Single-wrap enum collapse: `{"On":{}}` → `"on"`, applied under the
784    /// `RefreshDecisionWithReasonV1` variant context.
785    #[mz_ore::test]
786    fn enum_single_wrap_decision() {
787        check(
788            r#"{"CreateClusterReplicaV2": {
789                "cluster_id": "u1",
790                "cluster_name": "c",
791                "replica_id": {"inner": "r1"},
792                "replica_name": "n",
793                "logical_size": "small",
794                "disk": false,
795                "billed_as": null,
796                "internal": false,
797                "reason": {"reason": {"Schedule": {}}},
798                "scheduling_policies": {
799                    "on_refresh": {
800                        "decision": {"Off": {}},
801                        "objects_needing_refresh": [],
802                        "rehydration_time_estimate": "00:00:00"
803                    }
804                }
805            }}"#,
806            r#"{
807                "cluster_id": "u1",
808                "cluster_name": "c",
809                "replica_id": "r1",
810                "replica_name": "n",
811                "logical_size": "small",
812                "disk": false,
813                "billed_as": null,
814                "internal": false,
815                "reason": "schedule",
816                "scheduling_policies": {
817                    "on_refresh": {
818                        "decision": "off",
819                        "objects_needing_refresh": [],
820                        "hydration_time_estimate": "00:00:00"
821                    }
822                }
823            }"#,
824        );
825    }
826
827    /// Double-wrap enum collapse: `{"reason":{"HydrationBurst":{}}}` →
828    /// `"hydration-burst"`. Confirms the kebab-case mapping is used (the
829    /// enum variant is `PascalCase` on the proto side).
830    #[mz_ore::test]
831    fn enum_double_wrap_reason_kebab() {
832        check(
833            r#"{"DropClusterReplicaV2": {
834                "cluster_id": "u1",
835                "cluster_name": "c",
836                "replica_id": "r1",
837                "replica_name": "n",
838                "reason": {"reason": {"HydrationBurst": {}}},
839                "scheduling_policies": null
840            }}"#,
841            r#"{
842                "cluster_id": "u1",
843                "cluster_name": "c",
844                "replica_id": "r1",
845                "replica_name": "n",
846                "reason": "hydration-burst"
847            }"#,
848        );
849    }
850
851    /// `AlterClusterReconfigurationV1.transition` uses a distinct kebab map
852    /// (`TimedOut` → `"timed-out"`, not shared with the reason map). Guards
853    /// against accidentally reusing `REASON_MAP` for transitions.
854    #[mz_ore::test]
855    #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `decContextDefault` on OS `linux`
856    fn enum_double_wrap_transition_timed_out() {
857        check(
858            r#"{"AlterClusterReconfigurationV1": {
859                "cluster_id": "u1",
860                "cluster_name": "c",
861                "transition": {"transition": {"TimedOut": {}}},
862                "target_size": "small",
863                "target_replication_factor": 1,
864                "target_availability_zones": [],
865                "target_logging": {"log_logging": false, "interval": null},
866                "deadline": null
867            }}"#,
868            r#"{
869                "cluster_id": "u1",
870                "cluster_name": "c",
871                "transition": "timed-out",
872                "target_size": "small",
873                "target_replication_factor": 1,
874                "target_availability_zones": [],
875                "target_logging": {"log_logging": false, "interval": null},
876                "deadline": null
877            }"#,
878        );
879    }
880
881    /// `ClusterHydrationBurstV1.transition` uses a two-value map
882    /// (`Started`/`Finished`), separate from the reconfiguration lifecycle
883    /// map. Same field name (`transition`), different rule, different map —
884    /// dispatched by variant context. `finish_cause` is an *optional* enum:
885    /// its `Some` collapses like any other double-wrap enum, while `None`
886    /// serializes as JSON null on both sides and passes through.
887    #[mz_ore::test]
888    fn enum_double_wrap_hydration_burst_finished() {
889        check(
890            r#"{"ClusterHydrationBurstV1": {
891                "cluster_id": "u1",
892                "cluster_name": "c",
893                "transition": {"transition": {"Finished": {}}},
894                "finish_cause": {"cause": {"LingerElapsed": {}}},
895                "burst_size": "small"
896            }}"#,
897            r#"{
898                "cluster_id": "u1",
899                "cluster_name": "c",
900                "transition": "finished",
901                "finish_cause": "linger-elapsed",
902                "burst_size": "small"
903            }"#,
904        );
905        check(
906            r#"{"ClusterHydrationBurstV1": {
907                "cluster_id": "u1",
908                "cluster_name": "c",
909                "transition": {"transition": {"Started": {}}},
910                "finish_cause": null,
911                "burst_size": "small"
912            }}"#,
913            r#"{
914                "cluster_id": "u1",
915                "cluster_name": "c",
916                "transition": "started",
917                "finish_cause": null,
918                "burst_size": "small"
919            }"#,
920        );
921    }
922
923    /// `ResetAllV1` is the only variant whose `as_json` returns JSON null.
924    /// The proto side carries an `Empty` payload that serializes to `{}`,
925    /// so a naive strip-the-wrapper would emit `{}`. Special-cased.
926    #[mz_ore::test]
927    fn reset_all_v1_is_null() {
928        check(r#"{"ResetAllV1": {}}"#, r#"null"#);
929    }
930
931    /// An unlisted enum variant errors rather than being silently passed
932    /// through — matches the fail-fast contract on this
933    /// compliance-relevant table.
934    #[mz_ore::test]
935    fn enum_unknown_variant_errors() {
936        check_err(
937            r#"{"DropClusterReplicaV2": {
938                "cluster_id": "u1",
939                "cluster_name": "c",
940                "replica_id": "r1",
941                "replica_name": "n",
942                "reason": {"reason": {"NoSuchVariant": {}}},
943                "scheduling_policies": null
944            }}"#,
945            "unknown enum variant NoSuchVariant",
946        );
947    }
948
949    /// The proto enum payload must be `Empty` (i.e. `{}`); a variant that
950    /// grows a payload in the future would silently break the collapse, so
951    /// we fail fast instead.
952    #[mz_ore::test]
953    fn enum_non_empty_payload_errors() {
954        check_err(
955            r#"{"DropClusterReplicaV2": {
956                "cluster_id": "u1",
957                "cluster_name": "c",
958                "replica_id": "r1",
959                "replica_name": "n",
960                "reason": {"reason": {"Manual": {"unexpected": "x"}}},
961                "scheduling_policies": null
962            }}"#,
963            "non-empty payload",
964        );
965    }
966
967    /// Bad inputs: empty enum object, multiple keys, non-object.
968    #[mz_ore::test]
969    #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `decContextDefault` on OS `linux`
970    fn error_cases() {
971        check_err(r#"{}"#, "empty details enum");
972        check_err(
973            r#"{"A": {"x": 1}, "B": {"y": 2}}"#,
974            "details enum had multiple keys",
975        );
976        check_err(r#"["IdNameV1", {"id": "u1"}]"#, "expected object");
977        check_err(r#"{"IdNameV1": "not an object"}"#, "expected inner object");
978    }
979}