Skip to main content

syncular_command/
lib.rs

1//! # syncular-command — one JSON command surface over the Rust client core
2//!
3//! The command router the conformance shim proved (JSON in, JSON out, bytes
4//! as `{"$bytes": hex}`) factored into a transport-agnostic module so BOTH
5//! the stdio conformance shim AND the FFI native core dispatch through the
6//! same code. That keeps a single command surface, conformance-locked via
7//! the shim: whatever the shim exercises, the FFI core inherits.
8//!
9//! The router is generic over the `Transport` seam. The shim binds it to a
10//! stdio host (transport inverted to the harness); the FFI crate binds it to
11//! a real native HTTP+WS transport. Everything host-specific — realtime
12//! notification draining, deferred requests, event queues — stays in each
13//! host; only the pure `method → result` dispatch (and its JSON parsing) is
14//! shared here.
15
16use serde_json::{json, Value};
17use ssp2::segment::{decode_rows_segment, encode_rows_segment};
18use ssp2::{
19    decode_message, encode_message, parse_control, render_message, render_rows_segment,
20    ControlMessage,
21};
22use syncular_client::previous_version::{PreviousVersionContextConfig, PreviousVersionReadSpec};
23use syncular_client::values::{bytes_to_hex, hex_to_bytes};
24use syncular_client::{
25    ClientDiagnosticsSnapshot, ClientError, ClientLimits, CommandEffects, CommitOutcomeQuery,
26    LocalDataPurgeInput, LocalDataRebootstrapInput, Mutation, QueryOwner, QueryReadFailure,
27    RealtimePolicy, ResolveCommitOutcomeInput, SyncClient, Transport, TransportError,
28    TransportGate, UnitScopes, WindowBase, WindowCoverage, LOCAL_AUTHORITY_UNCONFIGURED_CODE,
29};
30
31// -- bytes <-> {"$bytes": hex} (the driver-protocol byte envelope) ----------
32
33pub fn bytes_value(bytes: &[u8]) -> Value {
34    Value::Object(serde_json::Map::from_iter([(
35        "$bytes".to_owned(),
36        Value::from(bytes_to_hex(bytes)),
37    )]))
38}
39
40pub fn value_bytes(value: Option<&Value>) -> Result<Vec<u8>, String> {
41    let hex = value
42        .and_then(|v| v.get("$bytes"))
43        .and_then(Value::as_str)
44        .ok_or_else(|| "expected a {\"$bytes\": hex} value".to_owned())?;
45    hex_to_bytes(hex)
46}
47
48/// The structured failure the driver protocol carries in an `error`. `details`
49/// and `retryable` carry the typed mutation fields to the host; non-mutation
50/// failures leave both at their defaults.
51#[derive(Debug, Clone)]
52pub struct CommandError {
53    pub code: String,
54    pub message: String,
55    pub details: Option<Value>,
56    pub retryable: bool,
57}
58
59impl CommandError {
60    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
61        Self {
62            code: code.into(),
63            message: message.into(),
64            details: None,
65            retryable: false,
66        }
67    }
68
69    /// Consume a structured client authoring failure without re-parsing text.
70    pub fn from_client(error: ClientError) -> Self {
71        Self {
72            code: error.code,
73            message: error.message,
74            details: error.details,
75            retryable: error.retryable,
76        }
77    }
78}
79
80impl From<(String, String)> for CommandError {
81    fn from((code, message): (String, String)) -> Self {
82        Self {
83            code,
84            message,
85            details: None,
86            retryable: false,
87        }
88    }
89}
90
91/// The `{"code","message","retryable"[,"details"]}` object every host sends
92/// as the `error` of a failed command.
93pub fn error_envelope(error: CommandError) -> Value {
94    let mut envelope = json!({
95        "code": error.code,
96        "message": error.message,
97        "retryable": error.retryable
98    });
99    if let Some(details) = error.details {
100        envelope["details"] = details;
101    }
102    envelope
103}
104
105/// The application-facing `{"result"}` / `{"error"}` reply of a native host.
106/// The router's `effects` are consumed by the host and never leave it.
107pub fn reply(result: Result<Value, CommandError>) -> Value {
108    match result {
109        Ok(mut value) => {
110            if let Some(object) = value.as_object_mut() {
111                object.remove("effects");
112            }
113            // Moved, never serialized through `json!`: payloads can be megabytes.
114            Value::Object(serde_json::Map::from_iter([("result".to_owned(), value)]))
115        }
116        Err(error) => json!({ "error": error_envelope(error) }),
117    }
118}
119
120pub fn projection_pending_event(name: String) -> Value {
121    json!({ "type": "projectionPending", "name": name })
122}
123
124/// A well-formed presence control frame (§8.6.2), the one inbound realtime
125/// event a native host surfaces as an event: a fanout, or the server's refusal
126/// of this client's own publish, which carries the server's `error` code.
127pub fn presence_event(text: &str) -> Option<Value> {
128    let Ok(ControlMessage::Presence {
129        scope_key, error, ..
130    }) = parse_control(text)
131    else {
132        return None;
133    };
134    let mut event = json!({ "type": "presence", "scopeKey": scope_key });
135    if let Some(error) = error {
136        event["error"] = Value::from(error);
137    }
138    Some(event)
139}
140
141/// The privacy-safe diagnostics event for `client`, or `None` while a security
142/// preflight is pending, the snapshot fails, or its state (excluding capture
143/// time) equals `last`. Stores the emitted snapshot in `last`.
144pub fn diagnostics_event(
145    client: &SyncClient,
146    last: &mut Option<ClientDiagnosticsSnapshot>,
147) -> Option<Value> {
148    if client.security_preflight() {
149        return None;
150    }
151    let snapshot = client.diagnostics_snapshot().ok()?;
152    if let Some(previous) = last {
153        // Capture time is observation metadata, excluded from evidence equality.
154        previous.captured_at_ms = snapshot.captured_at_ms;
155        if previous == &snapshot {
156            return None;
157        }
158    }
159    let event = json!({ "type": "diagnostics", "snapshot": snapshot });
160    *last = Some(snapshot);
161    Some(event)
162}
163
164/// Parsed side effects of a `create` command that the host must apply to its
165/// own transport/clock (the router stays transport-agnostic). The client is
166/// already installed into the `Option<SyncClient>` slot by `dispatch`.
167#[derive(Debug, Default, Clone)]
168pub struct CreateEffects {
169    /// §5.4 capability the harness/host announced for its endpoints — the
170    /// host sets its transport's `supports_url_fetch` accordingly.
171    pub signed_urls: bool,
172    /// True while a security preflight is pending: a preflighted client was
173    /// installed (or entered preflight, or was shut down mid-preflight) and
174    /// `activateSecurity` has yet to complete. `dispatch` maintains this so a
175    /// replacement `create` without the `securityPreflight` flag is refused
176    /// across `shutdown`, where the client slot is empty, on a host that reuses
177    /// one `CreateEffects` across creates (the Tauri plugin, the conformance
178    /// shim, the bench harness).
179    ///
180    /// A host that allocates a fresh `CreateEffects` per create — the React
181    /// Native native module rebuilds its FFI handle on every `create` — starts
182    /// each create with this flag clear. For those hosts the persisted marker
183    /// in the client core carries the gate: a file-backed replica reopens in
184    /// preflight, and the `create` path refuses a plain re-create against it.
185    /// This in-memory flag covers the same-handle case where no file persists
186    /// the marker.
187    pub security_preflight_pending: bool,
188    /// §5.11: the native host's authority ceiling, table to permitted
189    /// columns. The host sets it from its own configuration, never from the
190    /// command. While it is set, `create` refuses a declared authority query
191    /// whose authored statement reads outside it
192    /// (`SyncClient::check_authority_ceiling`).
193    pub authority_ceiling: Option<std::collections::BTreeMap<String, Vec<String>>>,
194}
195
196/// §7.5: a read failure keeps its structured code, static message, SQLite
197/// details, and retryability across the command boundary.
198fn read_command_error(failure: QueryReadFailure) -> CommandError {
199    let details = failure.details();
200    let retryable = failure.retryable();
201    CommandError {
202        code: failure.code.unwrap_or("client.failed").to_owned(),
203        message: failure.message,
204        details,
205        retryable,
206    }
207}
208
209/// The code identity follows the client core's own rule
210/// (`ClientError::from`), so a colon-less `sync.unknown_table` keeps its code.
211/// The command boundary keeps the full rendered message.
212fn client_err(message: String) -> CommandError {
213    let code = ClientError::from(message.clone()).code;
214    let retryable = code == "client.storage_busy";
215    CommandError {
216        code,
217        message,
218        details: None,
219        retryable,
220    }
221}
222
223/// An optional command field. Absent or `null` keeps the caller's default; a
224/// present value `read` does not accept is `sync.invalid_request`, never a
225/// silent default.
226fn optional<'a, T>(
227    value: Option<&'a Value>,
228    field: &str,
229    read: impl FnOnce(&'a Value) -> Option<T>,
230) -> Result<Option<T>, String> {
231    match value {
232        None | Some(Value::Null) => Ok(None),
233        Some(value) => read(value)
234            .map(Some)
235            .ok_or_else(|| format!("sync.invalid_request: {field} has the wrong type")),
236    }
237}
238
239/// A transport failure keeps its code and structured details across the
240/// command boundary (`sync.attach_rejected` and its `details.reason`).
241fn transport_command_error(error: TransportError) -> CommandError {
242    CommandError {
243        code: error.code,
244        message: error.message,
245        details: error.details,
246        retryable: false,
247    }
248}
249
250fn need_client(client: &mut Option<SyncClient>) -> Result<&mut SyncClient, CommandError> {
251    client
252        .as_mut()
253        .ok_or_else(|| client_err("no client instance created".to_owned()))
254}
255
256/// RFC 0005 D8: parse the host's `previousVersionContext` config with the
257/// TS keys and defaults: `enabled` (default false), `maxBytes` 8 MiB,
258/// `maxRows` 20000, `maxTables` 32, `maxRowBytes` 1 MiB, `maxAgeMs` 24h.
259/// Invalid values fail the request loudly rather than silently defaulting.
260fn parse_previous_version_context(
261    value: Option<&Value>,
262) -> Result<Option<PreviousVersionContextConfig>, CommandError> {
263    let Some(value) = value else {
264        return Ok(None);
265    };
266    let object = value.as_object().ok_or_else(|| {
267        client_err("sync.invalid_request: previousVersionContext must be an object".to_owned())
268    })?;
269    let enabled = match object.get("enabled") {
270        None => false,
271        Some(Value::Bool(enabled)) => *enabled,
272        Some(_) => {
273            return Err(client_err(
274                "sync.invalid_request: previousVersionContext.enabled must be a boolean".to_owned(),
275            ))
276        }
277    };
278    let mut config = PreviousVersionContextConfig {
279        enabled,
280        ..PreviousVersionContextConfig::default()
281    };
282    for (key, slot) in [
283        ("maxBytes", &mut config.max_bytes),
284        ("maxRows", &mut config.max_rows),
285        ("maxTables", &mut config.max_tables),
286        ("maxRowBytes", &mut config.max_row_bytes),
287        ("maxAgeMs", &mut config.max_age_ms),
288    ] {
289        if let Some(raw) = object.get(key) {
290            *slot = raw.as_i64().ok_or_else(|| {
291                client_err(format!(
292                    "sync.invalid_request: previousVersionContext.{key} must be a positive safe integer"
293                ))
294            })?;
295        }
296    }
297    config.validate().map_err(client_err)?;
298    Ok(Some(config))
299}
300
301/// RFC 0005 D7: `previousVersionSnapshot` params — `{table, rowIds?, limit?}`.
302fn parse_previous_version_snapshot_spec(
303    params: &Value,
304) -> Result<PreviousVersionReadSpec, CommandError> {
305    let table = params.get("table").and_then(Value::as_str).ok_or_else(|| {
306        client_err("sync.invalid_request: previousVersionSnapshot missing table".to_owned())
307    })?;
308    let row_ids = match params.get("rowIds") {
309        None | Some(Value::Null) => Vec::new(),
310        Some(Value::Array(ids)) => ids
311            .iter()
312            .map(|id| match id {
313                Value::String(id) => Ok(id.clone()),
314                Value::Number(number) => Ok(number.to_string()),
315                Value::Bool(boolean) => Ok(boolean.to_string()),
316                _ => Err(client_err(
317                    "sync.invalid_request: previousVersionSnapshot rowIds must be strings"
318                        .to_owned(),
319                )),
320            })
321            .collect::<Result<Vec<_>, _>>()?,
322        Some(_) => {
323            return Err(client_err(
324                "sync.invalid_request: previousVersionSnapshot rowIds must be an array".to_owned(),
325            ))
326        }
327    };
328    let limit = match params.get("limit") {
329        None | Some(Value::Null) => None,
330        Some(value) => Some(value.as_i64().ok_or_else(|| {
331            client_err(
332                "sync.invalid_request: previousVersionSnapshot limit must be a positive number"
333                    .to_owned(),
334            )
335        })?),
336    };
337    Ok(PreviousVersionReadSpec {
338        table: table.to_owned(),
339        row_ids,
340        limit,
341    })
342}
343
344fn parse_limits(value: Option<&Value>) -> Result<ClientLimits, CommandError> {
345    let mut limits = ClientLimits::default();
346    let Some(object) = optional(value, "limits", Value::as_object).map_err(client_err)? else {
347        return Ok(limits);
348    };
349    let i32_field = |key: &str| {
350        optional(object.get(key), key, |v| {
351            v.as_i64().and_then(|n| i32::try_from(n).ok())
352        })
353        .map_err(client_err)
354    };
355    limits.limit_commits = i32_field("limitCommits")?;
356    limits.limit_snapshot_rows = i32_field("limitSnapshotRows")?;
357    limits.max_snapshot_pages = i32_field("maxSnapshotPages")?;
358    limits.accept = optional(object.get("accept"), "limits.accept", |v| {
359        v.as_u64().and_then(|n| u8::try_from(n).ok())
360    })
361    .map_err(client_err)?;
362    limits.blob_cache_max_bytes = optional(
363        object.get("blobCacheMaxBytes"),
364        "limits.blobCacheMaxBytes",
365        Value::as_i64,
366    )
367    .map_err(client_err)?;
368    limits.outcome_retention_max_entries = optional(
369        object.get("outcomeRetentionMaxEntries"),
370        "limits.outcomeRetentionMaxEntries",
371        |v| v.as_u64().and_then(|n| usize::try_from(n).ok()),
372    )
373    .map_err(client_err)?;
374    limits.max_push_commits_per_request = parse_push_limit(object, "maxPushCommitsPerRequest")?;
375    limits.max_push_operations_per_request =
376        parse_push_limit(object, "maxPushOperationsPerRequest")?;
377    limits.max_push_request_bytes = parse_push_limit(object, "maxPushRequestBytes")?;
378    Ok(limits)
379}
380
381/// §7.1: a configured push limit is a positive integer. Null or absent uses
382/// the default for that limit; invalid values fail with a structured error.
383fn parse_push_limit(
384    object: &serde_json::Map<String, Value>,
385    key: &str,
386) -> Result<Option<usize>, CommandError> {
387    match object.get(key) {
388        None | Some(Value::Null) => Ok(None),
389        Some(value) => value
390            .as_u64()
391            .and_then(|n| usize::try_from(n).ok())
392            .filter(|n| *n >= 1 && *n <= u32::MAX as usize)
393            .map(Some)
394            .ok_or_else(|| CommandError {
395                code: "sync.invalid_request".to_owned(),
396                message: "push limit must be an integer in 1..=4294967295".to_owned(),
397                details: Some(serde_json::json!({ "limit": key })),
398                retryable: false,
399            }),
400    }
401}
402
403/// §8.8: parse a transport gate state (`transportGate`, `setTransportGate`).
404fn parse_transport_gate(value: &Value) -> Result<TransportGate, CommandError> {
405    match value.as_str() {
406        Some("closed") => Ok(TransportGate::Closed),
407        Some("pull") => Ok(TransportGate::Pull),
408        Some("open") => Ok(TransportGate::Open),
409        _ => Err(client_err(
410            "sync.invalid_request: transportGate must be 'closed', 'pull' or 'open'".to_owned(),
411        )),
412    }
413}
414
415/// §8.8: parse the `realtimePolicy` create param. Absent ⇒ `optional`.
416fn parse_realtime_policy(value: Option<&Value>) -> Result<RealtimePolicy, CommandError> {
417    match value {
418        None => Ok(RealtimePolicy::Optional),
419        Some(Value::String(text)) => match text.as_str() {
420            "required" => Ok(RealtimePolicy::Required),
421            "optional" => Ok(RealtimePolicy::Optional),
422            "off" => Ok(RealtimePolicy::Off),
423            other => Err(client_err(format!(
424                "sync.invalid_request: realtimePolicy must be 'required', 'optional', or 'off', got {other:?}"
425            ))),
426        },
427        Some(_) => Err(client_err(
428            "sync.invalid_request: realtimePolicy must be a string".to_owned(),
429        )),
430    }
431}
432
433/// §5.11: parse the `encryption` config into the client's portable keyring.
434/// Shape: `{ keys: { "<keyId>": {"$bytes": "<hex>"} },
435/// keyIdColumns: { "<table>": "<column>" } }`.
436/// Keys are 32 bytes.
437fn parse_encryption(value: &Value) -> Result<syncular_client::values::EncryptionConfig, String> {
438    let mut config = syncular_client::values::EncryptionConfig::default();
439    let keys = optional(value.get("keys"), "encryption.keys", Value::as_object)?;
440    for (key_id, key_val) in keys.into_iter().flatten() {
441        let bytes =
442            value_bytes(Some(key_val)).map_err(|e| format!("encryption key {key_id:?}: {e}"))?;
443        if bytes.len() != 32 {
444            return Err(format!(
445                "encryption key {key_id:?} must be 32 bytes, got {}",
446                bytes.len()
447            ));
448        }
449        config.keys.insert(key_id.clone(), bytes);
450    }
451    if let Some(columns) = value.get("keyIdColumns") {
452        let columns = columns
453            .as_object()
454            .ok_or_else(|| "encryption keyIdColumns must be an object".to_owned())?;
455        for (table, column) in columns {
456            let column = column.as_str().ok_or_else(|| {
457                format!("encryption keyIdColumns entry for {table:?} must be a string")
458            })?;
459            if column.is_empty() {
460                return Err(format!(
461                    "encryption keyIdColumns entry for {table:?} must not be empty"
462                ));
463            }
464            config
465                .key_id_columns
466                .insert(table.clone(), column.to_owned());
467        }
468    }
469    Ok(config)
470}
471
472pub fn parse_mutations(value: Option<&Value>) -> Result<Vec<Mutation>, String> {
473    let list = value
474        .and_then(Value::as_array)
475        .ok_or_else(|| "mutations must be a list".to_owned())?;
476    let mut out = Vec::with_capacity(list.len());
477    for entry in list {
478        let op = entry
479            .get("op")
480            .and_then(Value::as_str)
481            .ok_or_else(|| "mutation missing op".to_owned())?;
482        let table = entry
483            .get("table")
484            .and_then(Value::as_str)
485            .ok_or_else(|| "mutation missing table".to_owned())?
486            .to_owned();
487        let base_version = optional(entry.get("baseVersion"), "baseVersion", Value::as_i64)?;
488        match op {
489            "upsert" | "patch" => {
490                let mut values = entry
491                    .get("values")
492                    .and_then(Value::as_object)
493                    .cloned()
494                    .ok_or_else(|| "upsert missing values".to_owned())?;
495                decode_bigint_members(&mut values)?;
496                out.push(if op == "patch" {
497                    Mutation::Patch {
498                        table,
499                        values,
500                        base_version,
501                    }
502                } else {
503                    Mutation::Upsert {
504                        table,
505                        values,
506                        base_version,
507                    }
508                });
509            }
510            "delete" => {
511                let row_id = entry
512                    .get("rowId")
513                    .and_then(Value::as_str)
514                    .ok_or_else(|| "delete missing rowId".to_owned())?
515                    .to_owned();
516                out.push(Mutation::Delete {
517                    table,
518                    row_id,
519                    base_version,
520                });
521            }
522            other => return Err(format!("unknown mutation op {other:?}")),
523        }
524    }
525    Ok(out)
526}
527
528fn decode_bigint_members(values: &mut serde_json::Map<String, Value>) -> Result<(), String> {
529    for value in values.values_mut() {
530        let Some(decimal) = value.get("$bigint").and_then(Value::as_str) else {
531            continue;
532        };
533        let integer = decimal
534            .parse::<i64>()
535            .map_err(|_| format!("bigint value {decimal:?} is outside SQLite's i64 range"))?;
536        *value = Value::from(integer);
537    }
538    Ok(())
539}
540
541/// §4.1: parse a unit scope map `{variable: value}`; absent fails.
542fn unit_scopes(value: Option<&Value>) -> Result<UnitScopes, String> {
543    serde_json::from_value(value.cloned().unwrap_or(Value::Null)).map_err(|_| {
544        "sync.invalid_request: a unit scope map is an object of string values".to_owned()
545    })
546}
547
548/// §4.8: parse a window base descriptor `{ variable, fixedScopes? }` from a
549/// command's `base` param.
550fn window_base_from_params(value: Option<&Value>) -> Result<WindowBase, String> {
551    let object = value
552        .and_then(Value::as_object)
553        .ok_or_else(|| "sync.invalid_request: window base must be an object".to_owned())?;
554    let variable = object
555        .get("variable")
556        .and_then(Value::as_str)
557        .ok_or_else(|| "sync.invalid_request: window base missing variable".to_owned())?
558        .to_owned();
559    Ok(WindowBase {
560        variable,
561        fixed_scopes: match object.get("fixedScopes") {
562            None | Some(Value::Null) => UnitScopes::new(),
563            scopes => unit_scopes(scopes)?,
564        },
565    })
566}
567
568/// §7.5: parse a `coverage` array of `{table, base, units}` entries. Absent or null is
569/// empty; a non-array, a malformed base, or non-string units are rejected
570/// explicitly instead of silently defaulting. Shared with the Tauri plugin's
571/// read sidecar.
572pub fn parse_window_coverage(value: Option<&Value>) -> Result<Vec<WindowCoverage>, String> {
573    let entries = match value {
574        None | Some(Value::Null) => return Ok(Vec::new()),
575        Some(Value::Array(entries)) => entries,
576        Some(_) => return Err("sync.invalid_request: coverage must be a list".to_owned()),
577    };
578    let mut coverage = Vec::with_capacity(entries.len());
579    for entry in entries {
580        let units = match entry.get("units") {
581            None | Some(Value::Null) => Vec::new(),
582            Some(Value::Array(values)) => values
583                .iter()
584                .map(|value| value.as_str().map(str::to_owned))
585                .collect::<Option<Vec<_>>>()
586                .ok_or_else(|| {
587                    "sync.invalid_request: coverage units must be a list of strings".to_owned()
588                })?,
589            Some(_) => {
590                return Err(
591                    "sync.invalid_request: coverage units must be a list of strings".to_owned(),
592                )
593            }
594        };
595        coverage.push(WindowCoverage {
596            table: entry
597                .get("table")
598                .and_then(Value::as_str)
599                .ok_or_else(|| "sync.invalid_request: coverage table must be a string".to_owned())?
600                .to_owned(),
601            base: window_base_from_params(entry.get("base"))?,
602            units,
603        });
604    }
605    Ok(coverage)
606}
607
608/// §7.5 owner: `{id, tables}`, both required when present. Shared by
609/// `querySnapshot` and `snapshotRead`.
610pub fn parse_query_owner<'a>(
611    owner: Option<&'a Value>,
612    method: &str,
613) -> Result<Option<(&'a str, Vec<&'a str>)>, CommandError> {
614    match owner {
615        None | Some(Value::Null) => Ok(None),
616        Some(value) => {
617            let id = value
618                .get("id")
619                .and_then(Value::as_str)
620                .filter(|id| !id.is_empty());
621            let tables = value
622                .get("tables")
623                .and_then(Value::as_array)
624                .and_then(|list| {
625                    list.iter()
626                        .map(Value::as_str)
627                        .collect::<Option<Vec<&str>>>()
628                });
629            match (id, tables) {
630                (Some(id), Some(tables)) => Ok(Some((id, tables))),
631                _ => Err(client_err(format!(
632                    "sync.invalid_request: {method} owner must be {{id: non-empty string, tables: string[]}}"
633                ))),
634            }
635        }
636    }
637}
638
639/// §7.5: parse a `units`/`commitIds` list. Absent or null is empty; a
640/// non-array or a non-string entry is rejected explicitly.
641fn snapshot_string_list(value: Option<&Value>) -> Result<Vec<String>, CommandError> {
642    match value {
643        None | Some(Value::Null) => Ok(Vec::new()),
644        Some(Value::Array(items)) => items
645            .iter()
646            .map(|item| item.as_str().map(str::to_owned))
647            .collect::<Option<Vec<String>>>()
648            .ok_or_else(|| {
649                client_err(
650                    "sync.invalid_request: snapshotRead list must contain strings".to_owned(),
651                )
652            }),
653        Some(_) => Err(client_err(
654            "sync.invalid_request: snapshotRead list must be a list of strings".to_owned(),
655        )),
656    }
657}
658
659/// The parsed `snapshotRead` params (§7.5), owned so a host can move them to
660/// its read thread.
661pub struct SnapshotReadParams {
662    pub statements: Vec<(String, Vec<Value>)>,
663    pub coverage: Vec<WindowCoverage>,
664    pub units: Vec<String>,
665    pub commit_ids: Vec<String>,
666    pub owner: Option<(String, Vec<String>)>,
667}
668
669/// Parse and validate the params of `snapshotRead`; shared by the router and
670/// the Tauri read sidecar.
671pub fn parse_snapshot_read(params: &Value) -> Result<SnapshotReadParams, CommandError> {
672    let mut statements = Vec::new();
673    match params.get("statements") {
674        None | Some(Value::Null) => {}
675        Some(Value::Array(items)) => {
676            for item in items {
677                let Some(sql) = item.get("sql").and_then(Value::as_str) else {
678                    return Err(client_err(
679                        "sync.invalid_request: snapshotRead statements need a sql string"
680                            .to_owned(),
681                    ));
682                };
683                let bind =
684                    match item.get("params") {
685                        None | Some(Value::Null) => Vec::new(),
686                        Some(Value::Array(values)) => values.clone(),
687                        Some(_) => return Err(client_err(
688                            "sync.invalid_request: snapshotRead statement params must be a list"
689                                .to_owned(),
690                        )),
691                    };
692                statements.push((sql.to_owned(), bind));
693            }
694        }
695        Some(_) => {
696            return Err(client_err(
697                "sync.invalid_request: snapshotRead statements must be a list".to_owned(),
698            ))
699        }
700    }
701    Ok(SnapshotReadParams {
702        statements,
703        units: snapshot_string_list(params.get("units"))?,
704        commit_ids: snapshot_string_list(params.get("commitIds"))?,
705        coverage: parse_window_coverage(params.get("coverage")).map_err(client_err)?,
706        owner: parse_query_owner(params.get("owner"), "snapshotRead")?.map(|(id, tables)| {
707            (
708                id.to_owned(),
709                tables.into_iter().map(str::to_owned).collect(),
710            )
711        }),
712    })
713}
714
715/// §5.10.5: parse the common `(table, rowId, column, name)` target of a crdt
716/// command. `name` selects the shared type inside the doc (default `"text"`,
717/// matching the TS `YjsColumn.text()` default).
718#[cfg(feature = "crdt-yjs")]
719fn crdt_target(params: &Value) -> Result<(String, String, String, String), CommandError> {
720    let table = params
721        .get("table")
722        .and_then(Value::as_str)
723        .ok_or_else(|| client_err("crdt command missing table".to_owned()))?
724        .to_owned();
725    let row_id = params
726        .get("rowId")
727        .and_then(Value::as_str)
728        .ok_or_else(|| client_err("crdt command missing rowId".to_owned()))?
729        .to_owned();
730    let column = params
731        .get("column")
732        .and_then(Value::as_str)
733        .ok_or_else(|| client_err("crdt command missing column".to_owned()))?
734        .to_owned();
735    let name = optional(params.get("name"), "crdt name", Value::as_str)
736        .map_err(client_err)?
737        .unwrap_or("text")
738        .to_owned();
739    Ok((table, row_id, column, name))
740}
741
742/// Dispatch one command against the client instance over `transport`.
743///
744/// The `create` command installs a fresh `SyncClient` into `client` and
745/// returns its parsed `CreateEffects` in the `Ok` result via `effects`; every
746/// other command mutates the existing instance. Errors come back as the
747/// driver-protocol `(code, message)` pair.
748///
749/// Generic over `T: Transport` so the shim (host-inverted transport) and the
750/// FFI core (native HTTP+WS transport) share this exact router.
751pub fn dispatch<T: Transport>(
752    transport: &mut T,
753    client: &mut Option<SyncClient>,
754    effects: &mut CreateEffects,
755    method: &str,
756    params: &Value,
757) -> Result<Value, CommandError> {
758    if method == "create" {
759        // Fail-closed against a compromised webview re-issuing `create` (or
760        // `shutdown` + `create`) WITHOUT the securityPreflight flag to exit
761        // the gate: while a preflight is pending — on the live client, or
762        // carried in `effects` across a `shutdown` — a replacement create must
763        // itself request securityPreflight; the gate opens only through
764        // activateSecurity.
765        let requests_preflight = optional(
766            params.get("securityPreflight"),
767            "securityPreflight",
768            Value::as_bool,
769        )
770        .map_err(client_err)?
771        .unwrap_or(false);
772        let preflight_engaged = client.as_ref().map_or(
773            effects.security_preflight_pending,
774            SyncClient::security_preflight,
775        );
776        if preflight_engaged && !requests_preflight {
777            return Err(CommandError::new(
778                syncular_client::SECURITY_PREFLIGHT_REQUIRED_CODE,
779                "the local replica is in security preflight; a replacement create must itself request securityPreflight, and protected data opens only after activateSecurity",
780            ));
781        }
782    } else {
783        let allowed_during_preflight = matches!(
784            method,
785            "authorityRead"
786                | "securityLifecycle"
787                | "beginSecurityPreflight"
788                | "activateSecurity"
789                | "setTransportGate"
790                | "disconnectRealtime"
791                | "purgeLocalData"
792                | "previousVersionDiscard"
793                | "localRevision"
794                | "statusSnapshot"
795                | "localAuthorityState"
796                | "drainRealtime"
797                | "shutdown"
798        );
799        if client
800            .as_ref()
801            .is_some_and(|running| running.security_preflight())
802            && !allowed_during_preflight
803        {
804            return Err(CommandError::new(
805                syncular_client::SECURITY_PREFLIGHT_REQUIRED_CODE,
806                "the local replica is in security preflight; complete quarantine checks and call activateSecurity before accessing protected data",
807            ));
808        }
809    }
810    let mut result = match method {
811        "create" => {
812            let client_id = optional(params.get("clientId"), "clientId", Value::as_str)
813                .map_err(client_err)?
814                .map(str::to_owned);
815            let db_path =
816                optional(params.get("dbPath"), "dbPath", Value::as_str).map_err(client_err)?;
817            let schema = params
818                .get("schema")
819                .ok_or_else(|| client_err("create missing schema".to_owned()))?;
820            let limits = parse_limits(params.get("limits"))?;
821            // RFC 0005 D8: the feature config rides the top-level key the TS
822            // client uses; the Rust core carries it on `ClientLimits` so it is
823            // resolved before the opening schema reset runs.
824            let previous_version_context =
825                parse_previous_version_context(params.get("previousVersionContext"))?;
826            let mut limits = limits;
827            limits.previous_version_context = previous_version_context;
828            if let Some(reads) = params.get("authorityReads") {
829                // §5.11: a malformed declaration is a `shape` refusal; the
830                // core check runs here as well so its details reach the host.
831                let shape = |query: Option<&Value>| {
832                    let mut details = json!({ "reason": "shape" });
833                    if let Some(query) = query {
834                        details["query"] = query.clone();
835                    }
836                    CommandError {
837                        details: Some(details),
838                        ..CommandError::new(
839                            "client.authority_read_forbidden",
840                            "authority read denied",
841                        )
842                    }
843                };
844                limits.authority_reads = reads
845                    .as_array()
846                    .ok_or_else(|| shape(None))?
847                    .iter()
848                    .map(|entry| {
849                        serde_json::from_value(entry.clone()).map_err(|_| shape(entry.get("name")))
850                    })
851                    .collect::<Result<Vec<_>, CommandError>>()?;
852                syncular_client::validate_authority_reads(
853                    &syncular_client::parse_schema_json(schema).map_err(client_err)?,
854                    &limits.authority_reads,
855                )
856                .map_err(CommandError::from_client)?;
857            }
858            // §5.11: the native ceiling prepares each authored statement on an
859            // in-memory replica of the schema, so a refused declaration never
860            // opens the host's database.
861            if let Some(ceiling) = &effects.authority_ceiling {
862                if !limits.authority_reads.is_empty() {
863                    SyncClient::new_with_identity(None, schema, limits.clone())
864                        .map_err(client_err)?
865                        .check_authority_ceiling(ceiling)
866                        .map_err(CommandError::from_client)?;
867                }
868            }
869            // §12: a host-configured local authority opens with the client's
870            // schema before the client, as the browser worker opens it.
871            transport
872                .open_local_authority(schema, db_path)
873                .map_err(transport_command_error)?;
874            // §native: a `dbPath` installs a file-backed rusqlite connection so
875            // native hosts (Tauri plugin, FFI file variant) persist across
876            // restarts; absent it, the default in-memory core (the shim's mode).
877            let mut instance = match db_path {
878                Some(path) => SyncClient::open_path_with_identity(client_id, schema, limits, path)
879                    .map_err(CommandError::from_client)?,
880                None => {
881                    SyncClient::new_with_identity(client_id, schema, limits).map_err(client_err)?
882                }
883            };
884            instance
885                .set_retain_failed_commits(
886                    optional(
887                        params.get("retainFailedCommits"),
888                        "retainFailedCommits",
889                        Value::as_bool,
890                    )
891                    .map_err(client_err)?
892                    .unwrap_or(false),
893                )
894                .map_err(client_err)?;
895            // §8.8: the realtime policy rides the create params; absent ⇒
896            // `optional` (today's socket-or-HTTP behavior).
897            let realtime_policy = parse_realtime_policy(params.get("realtimePolicy"))?;
898            instance
899                .set_realtime_policy(realtime_policy)
900                .map_err(client_err)?;
901            // Harness clock pin (§5.4 expiry runs on the virtual clock).
902            if let Some(now_ms) =
903                optional(params.get("nowMs"), "nowMs", Value::as_i64).map_err(client_err)?
904            {
905                instance.set_now_ms(now_ms);
906            }
907            // §5.4 capability of the host endpoint set (accept bit 3) — the
908            // host applies it to its own transport.
909            effects.signed_urls = optional(params.get("signedUrls"), "signedUrls", Value::as_bool)
910                .map_err(client_err)?
911                .unwrap_or(false);
912            // §5.11: install client-side encryption keys. Shape:
913            // { encryption: { keys: { "<keyId>": {"$bytes": "<hex>"} },
914            //                 keyIdColumns: { "<table>": "<column>" } } }.
915            let security_preflight = optional(
916                params.get("securityPreflight"),
917                "securityPreflight",
918                Value::as_bool,
919            )
920            .map_err(client_err)?
921            .unwrap_or(false);
922            // A file-backed replica reopens in preflight when its persisted
923            // quarantine marker is set (client core restores it). Refuse a plain
924            // re-create so a rebuilt host handle — the React Native native module
925            // tears its FFI handle down on every create — cannot downgrade a
926            // quarantined replica to active. A create that itself requests
927            // securityPreflight, or an activated replica whose marker cleared,
928            // proceeds.
929            if instance.security_preflight() && !security_preflight {
930                return Err(CommandError::new(
931                    syncular_client::SECURITY_PREFLIGHT_REQUIRED_CODE,
932                    "the local replica is in security preflight; a replacement create must itself request securityPreflight, and protected data opens only after activateSecurity",
933                ));
934            }
935            if security_preflight && params.get("encryption").is_some() {
936                return Err(client_err(
937                    "sync.invalid_request: securityPreflight and encryption are mutually exclusive; install keys with activateSecurity after preflight"
938                        .to_owned(),
939                ));
940            }
941            if let Some(enc) = params.get("encryption") {
942                let config = parse_encryption(enc).map_err(client_err)?;
943                instance.set_encryption(config);
944            }
945            if security_preflight {
946                instance.begin_security_preflight().map_err(client_err)?;
947            }
948            if let Some(state) = params.get("transportGate") {
949                instance
950                    .set_transport_gate(transport, parse_transport_gate(state)?)
951                    .map_err(CommandError::from_client)?;
952            }
953            effects.security_preflight_pending = security_preflight;
954            transport.set_client_id(instance.client_id());
955            *client = Some(instance);
956            Ok(json!({}))
957        }
958        "securityLifecycle" => Ok(json!({
959            "state": need_client(client)?.security_lifecycle()
960        })),
961        "beginSecurityPreflight" => {
962            let running = need_client(client)?;
963            running.disconnect_realtime(transport);
964            running.begin_security_preflight().map_err(client_err)?;
965            effects.security_preflight_pending = true;
966            Ok(json!({}))
967        }
968        "authorityRead" => {
969            // §5.11: `requests` is the only param, a list of `{ query, params }`.
970            let forbidden =
971                || CommandError::new("client.authority_read_forbidden", "authority read denied");
972            let requests = params
973                .as_object()
974                .filter(|object| object.len() == 1)
975                .and_then(|object| object.get("requests"))
976                .and_then(Value::as_array)
977                .ok_or_else(forbidden)?
978                .iter()
979                .map(|request| {
980                    let request = request.as_object().filter(|object| object.len() == 2)?;
981                    Some((
982                        request.get("query")?.as_str()?.to_owned(),
983                        request.get("params")?.as_object()?.clone(),
984                    ))
985                })
986                .collect::<Option<Vec<_>>>()
987                .ok_or_else(forbidden)?;
988            let read = client
989                .as_ref()
990                .ok_or_else(|| CommandError::new("client.closed", "no authority client is open"))?
991                .authority_read(&requests)
992                .map_err(CommandError::from_client)?;
993            Ok(serde_json::to_value(read).expect("authority read serializes"))
994        }
995        "activateSecurity" => {
996            let encryption = match params.get("encryption") {
997                Some(value) => parse_encryption(value).map_err(client_err)?,
998                None => syncular_client::values::EncryptionConfig::default(),
999            };
1000            // The transport reads headers from the host's header source at
1001            // each request, so an activation carries none; a host still
1002            // passing them is refused and the gate stays closed.
1003            if params.get("headers").is_some() {
1004                return Err(CommandError::new(
1005                    "sync.invalid_request",
1006                    "activateSecurity takes no headers; the transport asks the host's header source",
1007                ));
1008            }
1009            need_client(client)?
1010                .activate_security(encryption)
1011                .map_err(client_err)?;
1012            effects.security_preflight_pending = false;
1013            Ok(json!({}))
1014        }
1015        "addEncryptionKeys" => {
1016            let running = client
1017                .as_mut()
1018                .ok_or_else(|| CommandError::new("client.closed", "no client is open"))?;
1019            let entries = params
1020                .get("keys")
1021                .and_then(Value::as_object)
1022                .ok_or_else(|| {
1023                    CommandError::new(
1024                        "sync.invalid_request",
1025                        "addEncryptionKeys.keys must be an object of {\"$bytes\": hex} values",
1026                    )
1027                })?;
1028            // A malformed key decodes to no bytes, so the core refuses it in
1029            // key-id order with the other bad keys and zeroes every buffer.
1030            let keys = entries
1031                .iter()
1032                .map(|(key_id, value)| {
1033                    (key_id.clone(), value_bytes(Some(value)).unwrap_or_default())
1034                })
1035                .collect();
1036            running
1037                .add_encryption_keys(keys)
1038                .map_err(CommandError::from_client)?;
1039            Ok(json!({}))
1040        }
1041        "setTransportGate" => {
1042            let state = params.get("state").unwrap_or(&Value::Null);
1043            // §8.8: `{ through }` names a pending commit; creation takes only
1044            // the string states.
1045            let state = match state.get("through").and_then(Value::as_str) {
1046                Some(id) => TransportGate::Through(id.to_owned()),
1047                None => parse_transport_gate(state)?,
1048            };
1049            need_client(client)?
1050                .set_transport_gate(transport, state)
1051                .map_err(CommandError::from_client)?;
1052            Ok(json!({}))
1053        }
1054        "shutdown" => {
1055            if let Some(running) = client.as_mut() {
1056                // Capture the gate state BEFORE the shutdown barrier flips the
1057                // client into preflight: an unactivated preflight stays
1058                // pending across the shutdown, while an activated client may
1059                // be recreated plainly afterwards.
1060                effects.security_preflight_pending = running.security_preflight();
1061                running.disconnect_realtime(transport);
1062                // Teardown barrier only: an activated client that shuts down
1063                // cleanly must not leave a durable quarantine mark, or its next
1064                // plain create would be refused forever.
1065                running.seal_security_on_teardown();
1066            }
1067            *client = None;
1068            Ok(json!({}))
1069        }
1070        "subscribe" => {
1071            let scopes = unit_scopes(params.get("scopes")).map_err(client_err)?;
1072            let id = need_client(client)?.subscribe(scopes).map_err(client_err)?;
1073            Ok(json!({ "id": id }))
1074        }
1075        "subscribeMany" => {
1076            let units = params
1077                .get("units")
1078                .and_then(Value::as_array)
1079                .ok_or_else(|| {
1080                    client_err(
1081                        "sync.invalid_request: subscribeMany units must be a list".to_owned(),
1082                    )
1083                })?
1084                .iter()
1085                .map(|scopes| unit_scopes(Some(scopes)))
1086                .collect::<Result<Vec<_>, _>>()
1087                .map_err(client_err)?;
1088            let ids = need_client(client)?
1089                .subscribe_many(units)
1090                .map_err(client_err)?;
1091            Ok(json!({ "ids": ids }))
1092        }
1093        "unsubscribe" => {
1094            let id = params
1095                .get("id")
1096                .and_then(Value::as_str)
1097                .ok_or_else(|| client_err("unsubscribe missing id".to_owned()))?;
1098            need_client(client)?.unsubscribe(id).map_err(client_err)?;
1099            Ok(json!({}))
1100        }
1101        "setWindow" => {
1102            let base = window_base_from_params(params.get("base")).map_err(client_err)?;
1103            let units: Vec<String> = optional(params.get("units"), "setWindow units", |v| {
1104                v.as_array()?
1105                    .iter()
1106                    .map(|unit| unit.as_str().map(str::to_owned))
1107                    .collect()
1108            })
1109            .map_err(client_err)?
1110            .unwrap_or_default();
1111            let command_effects = need_client(client)?
1112                .set_window(&base, &units)
1113                .map_err(client_err)?;
1114            Ok(json!({ "effects": command_effects }))
1115        }
1116        "windowState" => {
1117            let base = window_base_from_params(params.get("base")).map_err(client_err)?;
1118            let state = need_client(client)?
1119                .window_state(&base)
1120                .map_err(client_err)?;
1121            Ok(json!({ "units": state.units, "pending": state.pending, "revoked": state.revoked }))
1122        }
1123        "timeWindowSugar" => {
1124            let created_at_ms = params
1125                .get("createdAtMs")
1126                .and_then(Value::as_i64)
1127                .ok_or_else(|| client_err("timeWindowSugar missing createdAtMs".to_owned()))?;
1128            let count = params
1129                .get("count")
1130                .and_then(Value::as_u64)
1131                .and_then(|value| usize::try_from(value).ok())
1132                .ok_or_else(|| client_err("timeWindowSugar missing count".to_owned()))?;
1133            let now_ms = params
1134                .get("nowMs")
1135                .and_then(Value::as_i64)
1136                .ok_or_else(|| client_err("timeWindowSugar missing nowMs".to_owned()))?;
1137            if params.get("unit").and_then(Value::as_str) != Some("month") {
1138                return Err(client_err(
1139                    "sync.invalid_request: timeWindowSugar requires the month unit".to_owned(),
1140                ));
1141            }
1142            let unit = syncular_client::TimeBucketUnit::Month;
1143            Ok(json!({
1144                "bucket": syncular_client::creation_time_bucket(created_at_ms, unit)
1145                    .map_err(client_err)?,
1146                "units": syncular_client::last(count, unit, now_ms).map_err(client_err)?,
1147            }))
1148        }
1149        "mutate" => {
1150            let mutations = parse_mutations(params.get("mutations")).map_err(client_err)?;
1151            let id = need_client(client)?
1152                .mutate(mutations)
1153                .map_err(CommandError::from_client)?;
1154            Ok(json!({
1155                "clientCommitId": id,
1156                "effects": CommandEffects::interactive()
1157            }))
1158        }
1159        "replaceCommitOutcome" => {
1160            let id = params
1161                .get("clientCommitId")
1162                .and_then(Value::as_str)
1163                .ok_or_else(|| {
1164                    client_err("sync.invalid_request: clientCommitId must be a string".to_owned())
1165                })?;
1166            let sequence = params
1167                .get("sequence")
1168                .and_then(Value::as_i64)
1169                .ok_or_else(|| {
1170                    client_err("sync.invalid_request: sequence must be an integer".to_owned())
1171                })?;
1172            let replacement = match params.get("replacement") {
1173                None | Some(Value::Null) => None,
1174                value => Some(parse_mutations(value).map_err(client_err)?),
1175            };
1176            let id = need_client(client)?
1177                .replace_commit_outcome(id, sequence, replacement)
1178                .map_err(CommandError::from_client)?;
1179            Ok(json!({
1180                "clientCommitId": id,
1181                "effects": CommandEffects::interactive()
1182            }))
1183        }
1184        "replacePendingCommit" => {
1185            let id = params
1186                .get("clientCommitId")
1187                .and_then(Value::as_str)
1188                .ok_or_else(|| {
1189                    client_err("sync.invalid_request: clientCommitId must be a string".to_owned())
1190                })?;
1191            let replacement = params
1192                .get("replacementClientCommitId")
1193                .and_then(Value::as_str)
1194                .ok_or_else(|| {
1195                    client_err(
1196                        "sync.invalid_request: replacementClientCommitId must be a string"
1197                            .to_owned(),
1198                    )
1199                })?;
1200            let mutations = parse_mutations(params.get("operations")).map_err(client_err)?;
1201            let id = need_client(client)?
1202                .replace_pending_commit(transport, id, mutations, replacement)
1203                .map_err(CommandError::from_client)?;
1204            Ok(json!({
1205                "clientCommitId": id,
1206                "effects": CommandEffects::interactive()
1207            }))
1208        }
1209        "patch" => {
1210            let table = params
1211                .get("table")
1212                .and_then(Value::as_str)
1213                .ok_or_else(|| client_err("patch missing table".to_owned()))?;
1214            let row_id = params
1215                .get("rowId")
1216                .and_then(Value::as_str)
1217                .ok_or_else(|| client_err("patch missing rowId".to_owned()))?;
1218            let mut partial = params
1219                .get("partial")
1220                .and_then(Value::as_object)
1221                .cloned()
1222                .ok_or_else(|| client_err("patch missing partial object".to_owned()))?;
1223            decode_bigint_members(&mut partial).map_err(client_err)?;
1224            let base_version = optional(params.get("baseVersion"), "baseVersion", Value::as_i64)
1225                .map_err(client_err)?;
1226            let id = need_client(client)?
1227                .patch(table, row_id, partial, base_version)
1228                .map_err(CommandError::from_client)?;
1229            Ok(json!({
1230                "clientCommitId": id,
1231                "effects": CommandEffects::interactive()
1232            }))
1233        }
1234        "purgeLocalData" => {
1235            let input: LocalDataPurgeInput =
1236                serde_json::from_value(params.get("input").cloned().ok_or_else(|| {
1237                    client_err("sync.invalid_request: purgeLocalData missing input".to_owned())
1238                })?)
1239                .map_err(|error| {
1240                    client_err(format!(
1241                        "sync.invalid_request: invalid purgeLocalData input: {error}"
1242                    ))
1243                })?;
1244            let result = need_client(client)?
1245                .purge_local_data(&input)
1246                .map_err(CommandError::from_client)?;
1247            serde_json::to_value(result).map_err(|error| client_err(error.to_string()))
1248        }
1249        "rebootstrapLocalData" => {
1250            let input: LocalDataRebootstrapInput =
1251                serde_json::from_value(params.get("input").cloned().ok_or_else(|| {
1252                    client_err(
1253                        "sync.invalid_request: rebootstrapLocalData missing input".to_owned(),
1254                    )
1255                })?)
1256                .map_err(|error| {
1257                    client_err(format!(
1258                        "sync.invalid_request: invalid rebootstrapLocalData input: {error}"
1259                    ))
1260                })?;
1261            let result = need_client(client)?
1262                .rebootstrap_local_data(&input)
1263                .map_err(client_err)?;
1264            Ok(json!({
1265                "alreadyApplied": result.already_applied,
1266                "retainedCommits": result.retained_commits,
1267                "resetSubscriptions": result.reset_subscriptions,
1268                "effects": if result.already_applied {
1269                    CommandEffects::none()
1270                } else {
1271                    CommandEffects::interactive()
1272                }
1273            }))
1274        }
1275        "sync" => {
1276            let outcome = need_client(client)?.sync(transport);
1277            Ok(outcome.to_json())
1278        }
1279        "resetClientId" | "reset_client_id" => {
1280            let client_id = need_client(client)?
1281                .reset_client_id(transport)
1282                .map_err(client_err)?;
1283            Ok(json!({ "clientId": client_id }))
1284        }
1285        "syncUntilIdle" => {
1286            let max_rounds = match params.get("maxRounds") {
1287                None | Some(Value::Null) => None,
1288                Some(value) => Some(
1289                    value
1290                        .as_u64()
1291                        .and_then(|n| u32::try_from(n).ok())
1292                        .filter(|n| *n >= 1)
1293                        .ok_or_else(|| {
1294                            client_err(
1295                                "sync.invalid_request: maxRounds must be a positive integer"
1296                                    .to_owned(),
1297                            )
1298                        })?,
1299                ),
1300            };
1301            let timeout_ms = match params.get("timeoutMs") {
1302                None | Some(Value::Null) => None,
1303                Some(value) => Some(value.as_u64().filter(|ms| *ms >= 1).ok_or_else(|| {
1304                    client_err(
1305                        "sync.invalid_request: timeoutMs must be a positive integer".to_owned(),
1306                    )
1307                })?),
1308            };
1309            let client = need_client(client)?;
1310            let outcome = match timeout_ms {
1311                Some(timeout_ms) => {
1312                    client.sync_until_idle_with_deadline(transport, max_rounds, Some(timeout_ms))
1313                }
1314                None => client.sync_until_idle(transport, max_rounds),
1315            };
1316            Ok(outcome.to_json())
1317        }
1318        "proveCurrentBase" => {
1319            let outcome = params
1320                .get("outcome")
1321                .and_then(Value::as_object)
1322                .ok_or_else(|| client_err("proveCurrentBase missing outcome".to_owned()))?;
1323            let id = outcome
1324                .get("clientCommitId")
1325                .and_then(Value::as_str)
1326                .ok_or_else(|| client_err("proveCurrentBase missing clientCommitId".to_owned()))?;
1327            let sequence = outcome
1328                .get("sequence")
1329                .and_then(Value::as_i64)
1330                .ok_or_else(|| client_err("proveCurrentBase missing sequence".to_owned()))?;
1331            let max_rounds = match params.get("maxRounds") {
1332                None | Some(Value::Null) => None,
1333                Some(value) => Some(
1334                    value
1335                        .as_u64()
1336                        .and_then(|n| u32::try_from(n).ok())
1337                        .filter(|n| *n >= 1)
1338                        .ok_or_else(|| {
1339                            client_err(
1340                                "sync.invalid_request: maxRounds must be a positive integer"
1341                                    .to_owned(),
1342                            )
1343                        })?,
1344                ),
1345            };
1346            Ok(json!(
1347                need_client(client)?.prove_current_base(transport, id, sequence, max_rounds)
1348            ))
1349        }
1350        "readRows" => {
1351            let table = params
1352                .get("table")
1353                .and_then(Value::as_str)
1354                .ok_or_else(|| client_err("readRows missing table".to_owned()))?;
1355            let rows = need_client(client)?.read_rows(table).map_err(client_err)?;
1356            Ok(json!({ "rows": rows }))
1357        }
1358        "projectionPending" | "writeProjection" | "invalidateProjection" => {
1359            let name = params.get("name").and_then(Value::as_str).ok_or_else(|| {
1360                CommandError::new("sync.invalid_request", "projection name must be a string")
1361            })?;
1362            let running = need_client(client)?;
1363            let result = match method {
1364                "projectionPending" => {
1365                    let limit = params.get("limit").and_then(Value::as_i64).ok_or_else(|| {
1366                        CommandError::new(
1367                            "sync.invalid_request",
1368                            "projection limit must be a nonnegative safe integer",
1369                        )
1370                    })?;
1371                    running.projection_pending(name, limit)
1372                }
1373                "writeProjection" => {
1374                    let epoch = params.get("epoch").and_then(Value::as_i64).ok_or_else(|| {
1375                        CommandError::new(
1376                            "sync.invalid_request",
1377                            "projection epoch must be an integer",
1378                        )
1379                    })?;
1380                    let rows = serde_json::from_value::<Vec<syncular_client::ProjectionInput>>(
1381                        params["rows"].clone(),
1382                    )
1383                    .map_err(|_| {
1384                        CommandError::new("sync.invalid_request", "invalid projection rows")
1385                    })?;
1386                    running.write_projection(name, epoch, &rows)
1387                }
1388                _ => {
1389                    let source_ids = params
1390                        .get("sourceIds")
1391                        .map(|value| {
1392                            serde_json::from_value::<Vec<String>>(value.clone()).map_err(|_| {
1393                                CommandError::new(
1394                                    "sync.invalid_request",
1395                                    "projection source IDs must be strings",
1396                                )
1397                            })
1398                        })
1399                        .transpose()?;
1400                    running
1401                        .invalidate_projection(name, source_ids.as_deref())
1402                        .map(|()| json!({}))
1403                }
1404            };
1405            result.map_err(CommandError::from_client)
1406        }
1407        "query" => {
1408            // The React `useSyncQuery` live-query fast path: arbitrary read-only
1409            // SQL over the local visible tables/views. Params ride as the driver
1410            // value forms (bytes as `{"$bytes": hex}`); rows come back the same.
1411            let sql = params
1412                .get("sql")
1413                .and_then(Value::as_str)
1414                .ok_or_else(|| client_err("query missing sql".to_owned()))?;
1415            let bind = match params.get("params") {
1416                Some(Value::Array(list)) => list.as_slice(),
1417                None | Some(Value::Null) => &[],
1418                Some(_) => return Err(client_err("query params must be a list".to_owned())),
1419            };
1420            let rows = need_client(client)?.query(sql, bind).map_err(client_err)?;
1421            Ok(Value::Object(serde_json::Map::from_iter([(
1422                "rows".to_owned(),
1423                Value::Array(rows.into_iter().map(Value::Object).collect()),
1424            )])))
1425        }
1426        "querySnapshot" => {
1427            let sql = params
1428                .get("sql")
1429                .and_then(Value::as_str)
1430                .ok_or_else(|| client_err("querySnapshot missing sql".to_owned()))?;
1431            let bind = match params.get("params") {
1432                Some(Value::Array(list)) => list.as_slice(),
1433                None | Some(Value::Null) => &[],
1434                Some(_) => {
1435                    return Err(client_err("querySnapshot params must be a list".to_owned()))
1436                }
1437            };
1438            let coverage = parse_window_coverage(params.get("coverage")).map_err(client_err)?;
1439            let owner = parse_query_owner(params.get("owner"), "querySnapshot")?;
1440            let mut snapshot = need_client(client)?
1441                .query_snapshot(
1442                    sql,
1443                    bind,
1444                    &coverage,
1445                    owner.as_ref().map(|(id, tables)| QueryOwner { id, tables }),
1446                )
1447                .map_err(client_err)?;
1448            let rows = std::mem::take(&mut snapshot.rows);
1449            let mut result = serde_json::to_value(snapshot).expect("snapshot serializes");
1450            result["rows"] = Value::Array(rows.into_iter().map(Value::Object).collect());
1451            Ok(result)
1452        }
1453        "localRevision" => {
1454            // §7.5: the public revision read is fallible. An empty shared
1455            // snapshot read reports a corrupt marker instead of swallowing it
1456            // to zero. The internal infallible counter stays for bookkeeping.
1457            let read = need_client(client)?
1458                .snapshot_read(&syncular_client::SnapshotReadRequest::default(), None)
1459                .map_err(read_command_error)?;
1460            Ok(json!({ "revision": read.revision }))
1461        }
1462        "snapshotRead" => {
1463            let parsed = parse_snapshot_read(params)?;
1464            let tables: Vec<&str> = parsed.owner.as_ref().map_or_else(Vec::new, |(_, tables)| {
1465                tables.iter().map(String::as_str).collect()
1466            });
1467            let read = need_client(client)?
1468                .snapshot_read(
1469                    &syncular_client::SnapshotReadRequest {
1470                        statements: parsed
1471                            .statements
1472                            .iter()
1473                            .map(|(sql, params)| syncular_client::SnapshotStatement { sql, params })
1474                            .collect(),
1475                        coverage: &parsed.coverage,
1476                        units: parsed.units,
1477                        commit_ids: parsed.commit_ids,
1478                    },
1479                    parsed.owner.as_ref().map(|(id, _)| QueryOwner {
1480                        id,
1481                        tables: &tables,
1482                    }),
1483                )
1484                .map_err(read_command_error)?;
1485            serde_json::to_value(read).map_err(|error| client_err(error.to_string()))
1486        }
1487        "previousVersionSnapshot" | "previous_version_snapshot" => {
1488            let spec = parse_previous_version_snapshot_spec(params)?;
1489            let snapshot = need_client(client)?
1490                .previous_version_snapshot(&spec)
1491                .map_err(client_err)?;
1492            serde_json::to_value(snapshot).map_err(|error| client_err(error.to_string()))
1493        }
1494        "previousVersionAudit" | "previous_version_audit" => Ok(
1495            match need_client(client)?
1496                .previous_version_audit()
1497                .map_err(client_err)?
1498            {
1499                Some(audit) => {
1500                    serde_json::to_value(audit).map_err(|error| client_err(error.to_string()))?
1501                }
1502                None => Value::Null,
1503            },
1504        ),
1505        "previousVersionDiscard" | "previous_version_discard" => {
1506            let outcome = need_client(client)?
1507                .previous_version_discard()
1508                .map_err(client_err)?;
1509            Ok(json!({
1510                "present": outcome.present,
1511                "discarded": outcome.discarded,
1512            }))
1513        }
1514        "statusSnapshot" => Ok(serde_json::to_value(need_client(client)?.status_snapshot())
1515            .expect("status serializes")),
1516        "diagnosticsSnapshot" => {
1517            let snapshot = need_client(client)?
1518                .diagnostics_snapshot()
1519                .map_err(client_err)?;
1520            Ok(serde_json::to_value(snapshot).expect("diagnostics serialize"))
1521        }
1522        // Conformance/debug drains. Production hosts normally drain these
1523        // immediately after every command, but exposing the exact core output
1524        // here lets both client implementations consume one observation
1525        // vector catalog without bridge inference.
1526        "progressSnapshot" => Ok(
1527            serde_json::to_value(need_client(client)?.progress().snapshot())
1528                .expect("progress JSON"),
1529        ),
1530        "drainChangeBatches" => Ok(json!({
1531            "batches": need_client(client)?.drain_change_batches()
1532        })),
1533        "drainProjectionPending" => Ok(json!({
1534            "events": need_client(client)?.drain_projection_pending().into_iter().map(projection_pending_event).collect::<Vec<_>>()
1535        })),
1536        "drainSyncIntents" => Ok(json!({
1537            "intents": need_client(client)?.drain_sync_intents()
1538        })),
1539        // -- §5.10.5 native CRDT (the `crdt-yjs` feature) -----------------------
1540        // Thin forwards to the client core's yrs helpers. The command surface
1541        // stays present-but-unavailable in a lean build: without the feature
1542        // these fail loudly (`client.crdt_unavailable`) rather than being an
1543        // unknown method, so a wrapper's typed method gives a clear error.
1544        #[cfg(feature = "crdt-yjs")]
1545        "crdtText" => {
1546            let (table, row_id, column, name) = crdt_target(params)?;
1547            let text = need_client(client)?
1548                .crdt_text(&table, &row_id, &column, &name)
1549                .map_err(client_err)?;
1550            Ok(json!({ "text": text }))
1551        }
1552        #[cfg(feature = "crdt-yjs")]
1553        "crdtInsertText" => {
1554            let (table, row_id, column, name) = crdt_target(params)?;
1555            let index = params
1556                .get("index")
1557                .and_then(Value::as_u64)
1558                .and_then(|n| u32::try_from(n).ok())
1559                .ok_or_else(|| {
1560                    client_err(
1561                        "sync.invalid_request: crdtInsertText index must be a u32".to_owned(),
1562                    )
1563                })?;
1564            let value = params
1565                .get("value")
1566                .and_then(Value::as_str)
1567                .ok_or_else(|| client_err("crdtInsertText missing value".to_owned()))?;
1568            let id = need_client(client)?
1569                .crdt_insert_text(&table, &row_id, &column, &name, index, value)
1570                .map_err(CommandError::from_client)?;
1571            Ok(json!({ "clientCommitId": id }))
1572        }
1573        #[cfg(feature = "crdt-yjs")]
1574        "crdtDeleteText" => {
1575            let (table, row_id, column, name) = crdt_target(params)?;
1576            let index = params
1577                .get("index")
1578                .and_then(Value::as_u64)
1579                .and_then(|n| u32::try_from(n).ok())
1580                .ok_or_else(|| {
1581                    client_err(
1582                        "sync.invalid_request: crdtDeleteText index must be a u32".to_owned(),
1583                    )
1584                })?;
1585            let len = params
1586                .get("len")
1587                .and_then(Value::as_u64)
1588                .and_then(|n| u32::try_from(n).ok())
1589                .ok_or_else(|| {
1590                    client_err("sync.invalid_request: crdtDeleteText len must be a u32".to_owned())
1591                })?;
1592            let id = need_client(client)?
1593                .crdt_delete_text(&table, &row_id, &column, &name, index, len)
1594                .map_err(CommandError::from_client)?;
1595            Ok(json!({ "clientCommitId": id }))
1596        }
1597        #[cfg(feature = "crdt-yjs")]
1598        "crdtApplyUpdate" => {
1599            let (table, row_id, column, _name) = crdt_target(params)?;
1600            let update = value_bytes(params.get("update")).map_err(client_err)?;
1601            let id = need_client(client)?
1602                .crdt_apply_update(&table, &row_id, &column, &update)
1603                .map_err(CommandError::from_client)?;
1604            Ok(json!({ "clientCommitId": id }))
1605        }
1606        #[cfg(not(feature = "crdt-yjs"))]
1607        "crdtText" | "crdtInsertText" | "crdtDeleteText" | "crdtApplyUpdate" => {
1608            Err(CommandError::new(
1609                "client.crdt_unavailable",
1610                "native CRDT support requires the `crdt-yjs` feature (§5.10.5)",
1611            ))
1612        }
1613
1614        "uploadBlob" => {
1615            let bytes = value_bytes(params.get("bytes")).map_err(client_err)?;
1616            let media_type = optional(params.get("mediaType"), "mediaType", Value::as_str)
1617                .map_err(client_err)?
1618                .map(str::to_owned);
1619            let name = optional(params.get("name"), "blob name", Value::as_str)
1620                .map_err(client_err)?
1621                .map(str::to_owned);
1622            let reference = need_client(client)?
1623                .upload_blob(&bytes, media_type, name)
1624                .map_err(client_err)?;
1625            Ok(json!({ "ref": reference }))
1626        }
1627        "fetchBlob" => {
1628            let blob = params
1629                .get("blob")
1630                .and_then(Value::as_str)
1631                .ok_or_else(|| client_err("fetchBlob missing blob".to_owned()))?
1632                .to_owned();
1633            // fetch_blob_bytes returns (code, message) so the server's blob.*
1634            // code reaches the caller (§5.9.5 cross-scope probe). The command
1635            // boundary owns the JSON byte encoding used by native bindings.
1636            let blob = need_client(client)?.fetch_blob_bytes(transport, &blob)?;
1637            let mut value = serde_json::Map::new();
1638            value.insert("blobId".to_owned(), Value::from(blob.blob_id));
1639            value.insert("byteLength".to_owned(), Value::from(blob.byte_length));
1640            value.insert("bytes".to_owned(), bytes_value(&blob.bytes));
1641            if let Some(media_type) = blob.media_type {
1642                value.insert("mediaType".to_owned(), Value::from(media_type));
1643            }
1644            Ok(Value::Object(serde_json::Map::from_iter([(
1645                "blob".to_owned(),
1646                Value::Object(value),
1647            )])))
1648        }
1649        "conflicts" => {
1650            let conflicts = need_client(client)?.conflicts().to_vec();
1651            Ok(json!({ "conflicts": conflicts }))
1652        }
1653        "rejections" => {
1654            let rejections = need_client(client)?.rejections().to_vec();
1655            Ok(json!({ "rejections": rejections }))
1656        }
1657        "commitDelivery" => {
1658            let client_commit_id = params
1659                .get("clientCommitId")
1660                .and_then(Value::as_str)
1661                .ok_or_else(|| {
1662                    client_err(
1663                        "sync.invalid_request: commitDelivery missing clientCommitId".to_owned(),
1664                    )
1665                })?;
1666            let delivery = need_client(client)?
1667                .commit_delivery(client_commit_id)
1668                .map_err(read_command_error)?;
1669            Ok(json!(delivery))
1670        }
1671        "commitOutcomes" => {
1672            let query = serde_json::from_value::<CommitOutcomeQuery>(
1673                params.get("query").cloned().unwrap_or_else(|| json!({})),
1674            )
1675            .map_err(|error| {
1676                client_err(format!(
1677                    "sync.invalid_request: invalid commit outcome query: {error}"
1678                ))
1679            })?;
1680            let outcomes = need_client(client)?
1681                .commit_outcomes(query)
1682                .map_err(client_err)?;
1683            Ok(json!({ "outcomes": outcomes }))
1684        }
1685        "resolveCommitOutcome" => {
1686            let input = serde_json::from_value::<ResolveCommitOutcomeInput>(
1687                params.get("input").cloned().ok_or_else(|| {
1688                    client_err(
1689                        "sync.invalid_request: resolveCommitOutcome missing input".to_owned(),
1690                    )
1691                })?,
1692            )
1693            .map_err(|error| {
1694                client_err(format!(
1695                    "sync.invalid_request: invalid outcome resolution: {error}"
1696                ))
1697            })?;
1698            let outcome = need_client(client)?
1699                .resolve_commit_outcome(input)
1700                .map_err(client_err)?;
1701            Ok(json!({ "outcome": outcome }))
1702        }
1703        "pendingCommitIds" => {
1704            let ids = need_client(client)?.pending_commit_ids();
1705            Ok(json!({ "ids": ids }))
1706        }
1707        "pendingCommits" => Ok(json!({
1708            "commits": need_client(client)?.pending_commits().map_err(client_err)?
1709        })),
1710        "pendingPayloads" => {
1711            let payloads = need_client(client)?
1712                .pending_payloads()
1713                .map_err(client_err)?;
1714            Ok(json!({
1715                "payloads": payloads.iter().map(|p| bytes_value(p)).collect::<Vec<_>>()
1716            }))
1717        }
1718        "units" => Ok(json!({ "units": need_client(client)?.units().map_err(client_err)? })),
1719        "unit" => {
1720            let id = params
1721                .get("id")
1722                .and_then(Value::as_str)
1723                .ok_or_else(|| client_err("unit missing id".to_owned()))?;
1724            Ok(json!({ "unit": need_client(client)?.unit(id).map_err(client_err)? }))
1725        }
1726        "recreateWithSchema" => {
1727            // §7.4.2 "app ships new code": swap to the new schema on the SAME
1728            // in-memory database (the Rust core has no persistent restart, so
1729            // recreation IS the boot). Fires the §7.4.1 marker check.
1730            let schema = params
1731                .get("schema")
1732                .ok_or_else(|| client_err("recreateWithSchema missing schema".to_owned()))?;
1733            need_client(client)?
1734                .recreate_with_schema(schema)
1735                .map_err(CommandError::from_client)?;
1736            Ok(json!({}))
1737        }
1738        "localAuthorityState" => Ok(json!({ "state": transport.local_authority_state() })),
1739        // A native host drains buffered realtime traffic after every command;
1740        // this command does nothing else. The FFI host answers its
1741        // `realtime-wake` event with it.
1742        "drainRealtime" => Ok(json!({})),
1743        "attachLocalAuthority" | "abandonLocalAuthorityAttach" => {
1744            let running = need_client(client)?;
1745            if transport.local_authority_state().is_none() {
1746                return Err(CommandError::new(
1747                    LOCAL_AUTHORITY_UNCONFIGURED_CODE,
1748                    "the host configured no localAuthorityPath",
1749                ));
1750            }
1751            // §12.3: hold the client's rounds while the authority uploads or
1752            // rolls back, then restore the host's transport gate.
1753            let gate = running.transport_gate();
1754            running
1755                .set_transport_gate(transport, TransportGate::Closed)
1756                .map_err(CommandError::from_client)?;
1757            let outcome = if method == "attachLocalAuthority" {
1758                transport.attach_local_authority()
1759            } else {
1760                transport.abandon_local_authority_attach()
1761            };
1762            running
1763                .set_transport_gate(transport, gate)
1764                .map_err(CommandError::from_client)?;
1765            outcome.map_err(transport_command_error)?;
1766            Ok(json!({ "effects": CommandEffects::interactive() }))
1767        }
1768        "connectRealtime" => {
1769            need_client(client)?
1770                .connect_realtime(transport)
1771                .map_err(client_err)?;
1772            Ok(json!({}))
1773        }
1774        "disconnectRealtime" => {
1775            // A shut-down or not yet created client holds no socket.
1776            if let Some(running) = client.as_mut() {
1777                running.disconnect_realtime(transport);
1778            }
1779            Ok(json!({}))
1780        }
1781        "setPresence" => {
1782            let scope_key = params
1783                .get("scopeKey")
1784                .and_then(Value::as_str)
1785                .ok_or_else(|| client_err("setPresence missing scopeKey".to_owned()))?
1786                .to_owned();
1787            // §8.6.2: `doc` may be a JSON object or null (a leave).
1788            let doc = params.get("doc");
1789            let doc_ref = match doc {
1790                None | Some(Value::Null) => None,
1791                Some(v) => Some(v),
1792            };
1793            need_client(client)?
1794                .set_presence(transport, &scope_key, doc_ref)
1795                .map_err(client_err)?;
1796            Ok(json!({}))
1797        }
1798        "presence" => {
1799            let scope_key = params
1800                .get("scopeKey")
1801                .and_then(Value::as_str)
1802                .ok_or_else(|| client_err("presence missing scopeKey".to_owned()))?;
1803            let peers = need_client(client)?.presence(scope_key);
1804            Ok(json!({ "peers": peers }))
1805        }
1806
1807        // -- CodecDriver surface (Appendix A) — no client instance needed --
1808        "messageRoundtrip" => {
1809            let bytes = value_bytes(params.get("bytes")).map_err(client_err)?;
1810            match decode_message(&bytes) {
1811                Ok(message) => Ok(json!({
1812                    "ok": true,
1813                    "bytes": bytes_value(&encode_message(&message)),
1814                    "renderedJson": render_message(&message).to_string(),
1815                })),
1816                Err(error) => Ok(json!({ "ok": false, "errorCode": error.code.as_str() })),
1817            }
1818        }
1819        "segmentRoundtrip" => {
1820            let bytes = value_bytes(params.get("bytes")).map_err(client_err)?;
1821            match decode_rows_segment(&bytes) {
1822                Ok(segment) => Ok(json!({
1823                    "ok": true,
1824                    "bytes": bytes_value(&encode_rows_segment(&segment)),
1825                    "renderedJson": render_rows_segment(&segment).to_string(),
1826                })),
1827                Err(error) => Ok(json!({ "ok": false, "errorCode": error.code.as_str() })),
1828            }
1829        }
1830        "realtimeKnown" => {
1831            let text = params
1832                .get("text")
1833                .and_then(Value::as_str)
1834                .ok_or_else(|| client_err("realtimeKnown missing text".to_owned()))?;
1835            let known = matches!(
1836                parse_control(text),
1837                Ok(ControlMessage::Hello { .. })
1838                    | Ok(ControlMessage::Wake { .. })
1839                    | Ok(ControlMessage::Heartbeat { .. })
1840                    | Ok(ControlMessage::Scopes { .. })
1841                    | Ok(ControlMessage::Presence { .. })
1842            );
1843            Ok(json!({ "value": known }))
1844        }
1845
1846        other => Err(client_err(format!("unknown method {other:?}"))),
1847    };
1848    // §8.8: a closed gate owes no sync, and a `pull` or `through` gate owes
1849    // no push for a local write.
1850    if client.as_ref().is_some_and(|running| {
1851        running.transport_gate() == TransportGate::Closed
1852            || (running.transport_gate() != TransportGate::Open
1853                && matches!(
1854                    method,
1855                    "mutate" | "patch" | "replaceCommitOutcome" | "replacePendingCommit"
1856                ))
1857    }) {
1858        if let Ok(value) = &mut result {
1859            if let Some(effects) = value.get_mut("effects").and_then(Value::as_object_mut) {
1860                effects.remove("sync");
1861            }
1862        }
1863    }
1864    result
1865}
1866
1867#[cfg(test)]
1868mod tests {
1869    use serde_json::{json, Value};
1870    use syncular_client::{
1871        Mutation, SegmentRequest, SyncClient, Transport, TransportError, TransportGate,
1872        SECURITY_PREFLIGHT_REQUIRED_CODE,
1873    };
1874
1875    use super::{
1876        client_err, dispatch, parse_encryption, parse_previous_version_context,
1877        parse_window_coverage, CreateEffects, UnitScopes,
1878    };
1879
1880    #[derive(Default)]
1881    struct NoNetwork {
1882        realtime_connects: usize,
1883        realtime_closes: usize,
1884    }
1885
1886    impl Transport for NoNetwork {
1887        fn sync(&mut self, _request: &[u8]) -> Result<Vec<u8>, TransportError> {
1888            Err(TransportError::new("sync.transport_failed", "offline"))
1889        }
1890
1891        fn realtime_sync(&mut self, _request: &[u8]) -> Result<Vec<u8>, TransportError> {
1892            Err(TransportError::new("sync.transport_failed", "offline"))
1893        }
1894
1895        fn download_segment(
1896            &mut self,
1897            _request: &SegmentRequest,
1898            _on_progress: &mut dyn FnMut(u64),
1899        ) -> Result<Vec<u8>, TransportError> {
1900            Err(TransportError::new("sync.transport_failed", "offline"))
1901        }
1902
1903        fn realtime_connect(&mut self, _client_id: &str) -> Result<(), TransportError> {
1904            self.realtime_connects += 1;
1905            Ok(())
1906        }
1907
1908        fn realtime_send(&mut self, _text: &str) -> Result<(), TransportError> {
1909            Ok(())
1910        }
1911
1912        fn realtime_close(&mut self) -> Result<(), TransportError> {
1913            self.realtime_closes += 1;
1914            Ok(())
1915        }
1916    }
1917
1918    fn schema() -> Value {
1919        json!({
1920            "version": 1,
1921            "tables": [{
1922                "name": "todos",
1923                "columns": [
1924                    { "name": "id", "type": "string", "nullable": false },
1925                    { "name": "list_id", "type": "string", "nullable": false }
1926                ],
1927                "primaryKey": "id",
1928                "scopes": [{ "pattern": "list:{list_id}", "column": "list_id" }]
1929            }]
1930        })
1931    }
1932
1933    #[test]
1934    fn native_command_realtime_connection_is_idempotent() {
1935        let mut transport = NoNetwork::default();
1936        let mut client: Option<SyncClient> = None;
1937        let mut effects = CreateEffects::default();
1938        dispatch(
1939            &mut transport,
1940            &mut client,
1941            &mut effects,
1942            "create",
1943            &json!({ "schema": schema() }),
1944        )
1945        .expect("create client");
1946
1947        for _ in 0..2 {
1948            dispatch(
1949                &mut transport,
1950                &mut client,
1951                &mut effects,
1952                "connectRealtime",
1953                &json!({}),
1954            )
1955            .expect("idempotent connect command");
1956        }
1957        assert_eq!(transport.realtime_connects, 1);
1958
1959        dispatch(
1960            &mut transport,
1961            &mut client,
1962            &mut effects,
1963            "disconnectRealtime",
1964            &json!({}),
1965        )
1966        .expect("disconnect command");
1967        dispatch(
1968            &mut transport,
1969            &mut client,
1970            &mut effects,
1971            "disconnectRealtime",
1972            &json!({}),
1973        )
1974        .expect("idempotent disconnect command");
1975        assert_eq!(transport.realtime_closes, 1);
1976        dispatch(
1977            &mut transport,
1978            &mut client,
1979            &mut effects,
1980            "connectRealtime",
1981            &json!({}),
1982        )
1983        .expect("deliberate reconnect command");
1984        assert_eq!(transport.realtime_connects, 2);
1985    }
1986
1987    #[test]
1988    fn local_authority_commands_without_one_report_the_unconfigured_code() {
1989        let mut transport = NoNetwork::default();
1990        let mut client: Option<SyncClient> = None;
1991        let mut effects = CreateEffects::default();
1992        let state = dispatch(
1993            &mut transport,
1994            &mut client,
1995            &mut effects,
1996            "localAuthorityState",
1997            &json!({}),
1998        )
1999        .expect("state without a client");
2000        assert_eq!(state, json!({ "state": null }));
2001        dispatch(
2002            &mut transport,
2003            &mut client,
2004            &mut effects,
2005            "create",
2006            &json!({ "schema": schema() }),
2007        )
2008        .expect("create client");
2009        for method in ["attachLocalAuthority", "abandonLocalAuthorityAttach"] {
2010            let error = dispatch(
2011                &mut transport,
2012                &mut client,
2013                &mut effects,
2014                method,
2015                &json!({}),
2016            )
2017            .expect_err("no local authority");
2018            assert_eq!(error.code, "client.local_authority_unconfigured");
2019        }
2020        let running = client.as_mut().expect("client");
2021        assert_eq!(running.transport_gate(), TransportGate::Open);
2022        assert!(
2023            running.drain_sync_intents().is_empty(),
2024            "the gate never toggled"
2025        );
2026    }
2027
2028    /// A host transport with a scripted §12 local authority.
2029    struct ScriptedAuthority {
2030        opened: Vec<(Value, Option<String>)>,
2031        open_error: Option<TransportError>,
2032        attach_error: Option<TransportError>,
2033        abandons: usize,
2034    }
2035
2036    impl Transport for ScriptedAuthority {
2037        fn sync(&mut self, _request: &[u8]) -> Result<Vec<u8>, TransportError> {
2038            Err(TransportError::new("sync.transport_failed", "offline"))
2039        }
2040        fn realtime_sync(&mut self, _request: &[u8]) -> Result<Vec<u8>, TransportError> {
2041            Err(TransportError::new("sync.transport_failed", "offline"))
2042        }
2043        fn download_segment(
2044            &mut self,
2045            _request: &SegmentRequest,
2046            _on_progress: &mut dyn FnMut(u64),
2047        ) -> Result<Vec<u8>, TransportError> {
2048            Err(TransportError::new("sync.transport_failed", "offline"))
2049        }
2050        fn realtime_connect(&mut self, _client_id: &str) -> Result<(), TransportError> {
2051            Ok(())
2052        }
2053        fn realtime_send(&mut self, _text: &str) -> Result<(), TransportError> {
2054            Ok(())
2055        }
2056        fn realtime_close(&mut self) -> Result<(), TransportError> {
2057            Ok(())
2058        }
2059        fn open_local_authority(
2060            &mut self,
2061            schema: &Value,
2062            replica_path: Option<&str>,
2063        ) -> Result<(), TransportError> {
2064            self.opened
2065                .push((schema.clone(), replica_path.map(str::to_owned)));
2066            self.open_error.take().map_or(Ok(()), Err)
2067        }
2068        fn local_authority_state(&self) -> Option<&'static str> {
2069            (!self.opened.is_empty()).then_some("local")
2070        }
2071        fn attach_local_authority(&mut self) -> Result<(), TransportError> {
2072            self.attach_error.take().map_or(Ok(()), Err)
2073        }
2074        fn abandon_local_authority_attach(&mut self) -> Result<(), TransportError> {
2075            self.abandons += 1;
2076            Ok(())
2077        }
2078    }
2079
2080    #[test]
2081    fn local_authority_opens_at_create_and_attach_errors_keep_code_and_details() {
2082        let mut transport = ScriptedAuthority {
2083            opened: Vec::new(),
2084            open_error: Some(TransportError::new("sync.internal_error", "open failed")),
2085            attach_error: Some(TransportError {
2086                code: "sync.attach_rejected".to_owned(),
2087                message: "the remote server refused an attach commit".to_owned(),
2088                details: Some(json!({ "reason": "commit_rejected", "opIndex": 0 })),
2089            }),
2090            abandons: 0,
2091        };
2092        let mut client: Option<SyncClient> = None;
2093        let mut effects = CreateEffects::default();
2094        let error = dispatch(
2095            &mut transport,
2096            &mut client,
2097            &mut effects,
2098            "create",
2099            &json!({ "schema": schema() }),
2100        )
2101        .expect_err("an authority that fails to open fails create");
2102        assert_eq!(error.code, "sync.internal_error");
2103        assert!(client.is_none());
2104
2105        dispatch(
2106            &mut transport,
2107            &mut client,
2108            &mut effects,
2109            "create",
2110            &json!({ "schema": schema() }),
2111        )
2112        .expect("create client");
2113        assert_eq!(transport.opened.len(), 2);
2114        assert_eq!(transport.opened[1], (schema(), None));
2115        let state = dispatch(
2116            &mut transport,
2117            &mut client,
2118            &mut effects,
2119            "localAuthorityState",
2120            &json!({}),
2121        )
2122        .expect("state");
2123        assert_eq!(state, json!({ "state": "local" }));
2124
2125        let error = dispatch(
2126            &mut transport,
2127            &mut client,
2128            &mut effects,
2129            "attachLocalAuthority",
2130            &json!({}),
2131        )
2132        .expect_err("scripted rejection");
2133        assert_eq!(error.code, "sync.attach_rejected");
2134        assert_eq!(
2135            error.details,
2136            Some(json!({ "reason": "commit_rejected", "opIndex": 0 }))
2137        );
2138        assert_eq!(
2139            client.as_ref().expect("client").transport_gate(),
2140            TransportGate::Open
2141        );
2142
2143        let abandoned = dispatch(
2144            &mut transport,
2145            &mut client,
2146            &mut effects,
2147            "abandonLocalAuthorityAttach",
2148            &json!({}),
2149        )
2150        .expect("abandon");
2151        assert_eq!(abandoned["effects"]["sync"]["kind"], "interactive");
2152        assert_eq!(transport.abandons, 1);
2153
2154        // An offline host stays offline across attach.
2155        dispatch(
2156            &mut transport,
2157            &mut client,
2158            &mut effects,
2159            "setTransportGate",
2160            &json!({ "state": "closed" }),
2161        )
2162        .expect("go offline");
2163        let attached = dispatch(
2164            &mut transport,
2165            &mut client,
2166            &mut effects,
2167            "attachLocalAuthority",
2168            &json!({}),
2169        )
2170        .expect("attach");
2171        assert!(attached["effects"].get("sync").is_none());
2172        assert_eq!(
2173            client.as_ref().expect("client").transport_gate(),
2174            TransportGate::Closed
2175        );
2176    }
2177
2178    #[test]
2179    fn schema_downgrade_has_structured_code_at_create_and_recreate_boundaries() {
2180        let path = temp_db_path("schema-downgrade");
2181        let mut newer = schema();
2182        newer["version"] = json!(3);
2183        let mut older = schema();
2184        older["version"] = json!(2);
2185        let mut transport = NoNetwork::default();
2186        let mut client = None;
2187        let mut effects = CreateEffects::default();
2188        dispatch(
2189            &mut transport,
2190            &mut client,
2191            &mut effects,
2192            "create",
2193            &json!({ "schema": newer, "dbPath": path }),
2194        )
2195        .expect("v3 create");
2196        let error = dispatch(
2197            &mut transport,
2198            &mut client,
2199            &mut effects,
2200            "recreateWithSchema",
2201            &json!({ "schema": older }),
2202        )
2203        .expect_err("refuse recreation");
2204        assert_eq!(error.code, "client.schema_downgrade");
2205        assert_eq!(
2206            error.message,
2207            "persisted local schema is newer than the requested schema"
2208        );
2209        assert_eq!(
2210            error.details,
2211            Some(json!({ "persistedVersion": 3, "requestedVersion": 2 }))
2212        );
2213        assert!(!error.retryable);
2214        dispatch(
2215            &mut transport,
2216            &mut client,
2217            &mut effects,
2218            "shutdown",
2219            &json!({}),
2220        )
2221        .expect("shutdown");
2222        let error = dispatch(
2223            &mut transport,
2224            &mut client,
2225            &mut effects,
2226            "create",
2227            &json!({ "schema": older, "dbPath": path }),
2228        )
2229        .expect_err("refuse open");
2230        assert_eq!(error.code, "client.schema_downgrade");
2231        assert_eq!(
2232            error.message,
2233            "persisted local schema is newer than the requested schema"
2234        );
2235        assert_eq!(
2236            error.details,
2237            Some(json!({ "persistedVersion": 3, "requestedVersion": 2 }))
2238        );
2239        assert!(client.is_none());
2240        // Every other open error has the shape of any other command error: a
2241        // static message and the rendered cause in details.legacyCause.
2242        let error = dispatch(
2243            &mut transport,
2244            &mut client,
2245            &mut effects,
2246            "create",
2247            &json!({ "schema": newer, "dbPath": path, "clientId": "another-client" }),
2248        )
2249        .expect_err("refuse another identity");
2250        assert_eq!(error.code, "client.identity_mismatch");
2251        assert!(!error.message.contains("another-client"));
2252        assert!(error.details.as_ref().unwrap()["legacyCause"]
2253            .as_str()
2254            .unwrap()
2255            .starts_with("client.identity_mismatch: this database belongs to"));
2256        assert!(!error.retryable);
2257        assert!(client.is_none());
2258        dispatch(
2259            &mut transport,
2260            &mut client,
2261            &mut effects,
2262            "create",
2263            &json!({ "schema": newer, "dbPath": path }),
2264        )
2265        .expect("compatible reopen");
2266        dispatch(
2267            &mut transport,
2268            &mut client,
2269            &mut effects,
2270            "shutdown",
2271            &json!({}),
2272        )
2273        .expect("shutdown");
2274        let _ = std::fs::remove_file(path);
2275    }
2276
2277    #[test]
2278    fn native_command_realtime_policy_rides_create_and_refuses_http() {
2279        let mut transport = NoNetwork::default();
2280        let mut client: Option<SyncClient> = None;
2281        let mut effects = CreateEffects::default();
2282        dispatch(
2283            &mut transport,
2284            &mut client,
2285            &mut effects,
2286            "create",
2287            &json!({ "schema": schema(), "realtimePolicy": "required" }),
2288        )
2289        .expect("create client with a required realtime policy");
2290        let result = dispatch(
2291            &mut transport,
2292            &mut client,
2293            &mut effects,
2294            "sync",
2295            &json!({}),
2296        )
2297        .expect("sync command");
2298        assert_eq!(result["ok"], json!(false));
2299        assert_eq!(result["errorCode"], json!("sync.realtime_unavailable"));
2300        assert_eq!(result["realtimeState"], json!("disconnected"));
2301        assert_eq!(result["retryDelayMs"], json!(250));
2302        let snapshot = dispatch(
2303            &mut transport,
2304            &mut client,
2305            &mut effects,
2306            "diagnosticsSnapshot",
2307            &json!({}),
2308        )
2309        .expect("diagnostics command");
2310        assert_eq!(snapshot["host"]["realtime"], json!("disconnected"));
2311        assert_eq!(snapshot["host"]["realtimePolicy"], json!("required"));
2312        assert_eq!(snapshot["host"]["realtimeRetryDelayMs"], json!(250));
2313
2314        let mut second: Option<SyncClient> = None;
2315        let error = dispatch(
2316            &mut transport,
2317            &mut second,
2318            &mut effects,
2319            "create",
2320            &json!({ "schema": schema(), "realtimePolicy": "always" }),
2321        )
2322        .expect_err("an unknown policy is refused");
2323        assert_eq!(error.code, "sync.invalid_request");
2324    }
2325
2326    #[test]
2327    fn parses_portable_encryption_keyring_and_key_id_columns() {
2328        let key_hex = "2a".repeat(32);
2329        let config = parse_encryption(&json!({
2330            "keys": { "practice-key-v1": { "$bytes": key_hex } },
2331            "keyIdColumns": { "patients": "encryption_key_id" }
2332        }))
2333        .expect("portable keyring parses");
2334        assert_eq!(config.keys["practice-key-v1"], vec![0x2a; 32]);
2335        assert_eq!(config.key_id_columns["patients"], "encryption_key_id");
2336    }
2337
2338    #[test]
2339    fn rejects_non_string_key_id_columns() {
2340        let error = parse_encryption(&json!({
2341            "keys": {},
2342            "keyIdColumns": { "patients": 7 }
2343        }))
2344        .expect_err("invalid selector must fail");
2345        assert!(error.contains("must be a string"), "{error}");
2346    }
2347
2348    #[test]
2349    fn subscribe_many_registers_every_unit() {
2350        let mut transport = NoNetwork::default();
2351        let mut client: Option<SyncClient> = None;
2352        let mut effects = CreateEffects::default();
2353        let mut run = |command: &str, params: Value| {
2354            dispatch(&mut transport, &mut client, &mut effects, command, &params)
2355        };
2356        run("create", json!({ "schema": schema() })).expect("create client");
2357        let ids = run(
2358            "subscribeMany",
2359            json!({ "units": [{ "list_id": "list-1" }, { "list_id": "list-2" }] }),
2360        )
2361        .expect("register units")["ids"]
2362            .clone();
2363        let single = run("subscribe", json!({ "scopes": { "list_id": "list-1" } }))
2364            .expect("re-register a unit");
2365        assert_eq!(single["id"], ids[0], "a unit id derives from its scope map");
2366        let units = run("units", json!({})).expect("units");
2367        assert_eq!(units["units"].as_array().map(Vec::len), Some(2));
2368        for (index, list) in ["list-1", "list-2"].into_iter().enumerate() {
2369            let unit = run("unit", json!({ "id": ids[index] })).expect("unit");
2370            assert_eq!(unit["unit"]["scopes"], json!({ "list_id": list }));
2371            assert_eq!(unit["unit"]["cursor"], -1);
2372        }
2373        assert_eq!(
2374            run("unit", json!({ "id": "absent" })).expect("unit")["unit"],
2375            Value::Null
2376        );
2377        for scopes in [json!({ "list_id": "*" }), json!({ "other": "x" })] {
2378            let error = run("subscribe", json!({ "scopes": scopes }))
2379                .expect_err("a unit names a non-wildcard value per covered variable");
2380            assert_eq!(error.code, "sync.invalid_subscription", "{scopes}");
2381        }
2382    }
2383
2384    #[test]
2385    fn authority_reads_parse_at_create_and_run_through_authority_read() {
2386        let mut transport = NoNetwork::default();
2387        let mut client: Option<SyncClient> = None;
2388        let mut effects = CreateEffects::default();
2389        let query = json!({
2390            "name": "listOf",
2391            "sql": "SELECT id FROM todos WHERE list_id = ?",
2392            "bind": ["listId"],
2393            "params": [{"name": "listId", "type": "string", "nullable": false}],
2394            "coverage": [{"table": "todos", "variable": "list_id", "units": ["listId"]}],
2395            "reads": {"todos": ["id", "list_id"]},
2396            "resultColumns": [{"name": "id", "type": "string", "nullable": false}]
2397        });
2398        let mut create = |client: &mut Option<SyncClient>,
2399                          effects: &mut CreateEffects,
2400                          reads: Value| {
2401            dispatch(
2402                &mut transport,
2403                client,
2404                effects,
2405                "create",
2406                &json!({ "schema": schema(), "securityPreflight": true, "authorityReads": reads }),
2407            )
2408        };
2409        for (reads, details) in [
2410            (json!({}), json!({"reason": "shape"})),
2411            (
2412                json!([{"name": "x"}]),
2413                json!({"query": "x", "reason": "shape"}),
2414            ),
2415            (json!([{ "sql": "SELECT 1" }]), json!({"reason": "shape"})),
2416        ] {
2417            let error = create(&mut client, &mut effects, reads).unwrap_err();
2418            assert_eq!(error.code, "client.authority_read_forbidden");
2419            assert_eq!(error.details, Some(details));
2420        }
2421        // A host ceiling refuses the column the statement reads past it.
2422        effects.authority_ceiling = Some([("todos".to_owned(), vec!["id".to_owned()])].into());
2423        let refused = create(&mut client, &mut effects, json!([query])).unwrap_err();
2424        assert_eq!(
2425            refused.details,
2426            Some(
2427                json!({"query": "listOf", "reason": "ceiling", "table": "todos", "column": "list_id"})
2428            )
2429        );
2430        assert!(client.is_none());
2431        effects.authority_ceiling = Some(
2432            [(
2433                "todos".to_owned(),
2434                vec!["id".to_owned(), "list_id".to_owned()],
2435            )]
2436            .into(),
2437        );
2438        create(&mut client, &mut effects, json!([query])).expect("create within the ceiling");
2439        let read = dispatch(
2440            &mut transport,
2441            &mut client,
2442            &mut effects,
2443            "authorityRead",
2444            &json!({ "requests": [{ "query": "listOf", "params": { "listId": "l1" } }] }),
2445        )
2446        .expect("authority read in preflight");
2447        assert!(read["revision"].is_string());
2448        assert_eq!(
2449            read["results"],
2450            json!([{
2451                "query": "listOf",
2452                "rows": [],
2453                "coverage": [{"table": "todos", "base": {"variable": "list_id"}, "unit": "l1", "state": "missing"}],
2454                "complete": false
2455            }])
2456        );
2457        for params in [
2458            json!({}),
2459            json!({ "requests": [], "extra": true }),
2460            json!({ "requests": [{ "query": "listOf" }] }),
2461        ] {
2462            let error = dispatch(
2463                &mut transport,
2464                &mut client,
2465                &mut effects,
2466                "authorityRead",
2467                &params,
2468            )
2469            .unwrap_err();
2470            assert_eq!(
2471                (error.code.as_str(), error.details),
2472                ("client.authority_read_forbidden", None)
2473            );
2474        }
2475    }
2476
2477    #[test]
2478    fn window_coverage_parser_reads_the_generated_descriptor_and_rejects_malformed_units() {
2479        let parsed = parse_window_coverage(Some(&json!([{
2480            "table": "tasks",
2481            "base": { "variable": "project_id", "fixedScopes": { "tenant_id": "one" } },
2482            "units": ["a", "b"]
2483        }])))
2484        .expect("parse coverage");
2485        assert_eq!(parsed[0].base.variable, "project_id");
2486        assert_eq!(
2487            parsed[0].base.fixed_scopes,
2488            UnitScopes::from([("tenant_id".to_owned(), "one".to_owned())])
2489        );
2490        assert_eq!(parsed[0].table, "tasks");
2491        assert_eq!(parsed[0].units, ["a", "b"]);
2492        for coverage in [
2493            json!({}),
2494            json!([{ "table": "tasks", "base": { "variable": "project_id" }, "units": ["a", 1] }]),
2495            json!([{ "table": "tasks", "base": { "fixedScopes": {} }, "units": [] }]),
2496            json!([{ "base": { "variable": "project_id" }, "units": ["a"] }]),
2497            json!([{ "table": 1, "base": { "variable": "project_id" }, "units": ["a"] }]),
2498        ] {
2499            let error = parse_window_coverage(Some(&coverage)).expect_err("malformed coverage");
2500            assert!(error.starts_with("sync.invalid_request: "), "{error}");
2501        }
2502    }
2503
2504    #[test]
2505    fn subscribe_and_unsubscribe_queue_an_interactive_sync_intent() {
2506        let mut transport = NoNetwork::default();
2507        let mut client: Option<SyncClient> = None;
2508        let mut effects = CreateEffects::default();
2509        let mut run = |command: &str, params: Value| {
2510            dispatch(&mut transport, &mut client, &mut effects, command, &params)
2511                .expect("command succeeds")
2512        };
2513        run("create", json!({ "schema": schema() }));
2514        run("drainSyncIntents", json!({}));
2515        let id = run("subscribe", json!({ "scopes": { "list_id": "list-1" } }))["id"].clone();
2516        let intents = run("drainSyncIntents", json!({}));
2517        assert_eq!(intents["intents"], json!([{ "kind": "interactive" }]));
2518        run("unsubscribe", json!({ "id": id }));
2519        let intents = run("drainSyncIntents", json!({}));
2520        assert_eq!(intents["intents"], json!([{ "kind": "interactive" }]));
2521    }
2522
2523    #[test]
2524    fn security_preflight_is_fail_closed_until_exact_activation() {
2525        let mut transport = NoNetwork::default();
2526        let mut client: Option<SyncClient> = None;
2527        let mut effects = CreateEffects::default();
2528        dispatch(
2529            &mut transport,
2530            &mut client,
2531            &mut effects,
2532            "create",
2533            &json!({ "schema": schema(), "securityPreflight": true }),
2534        )
2535        .expect("preflight create");
2536
2537        let lifecycle = dispatch(
2538            &mut transport,
2539            &mut client,
2540            &mut effects,
2541            "securityLifecycle",
2542            &json!({}),
2543        )
2544        .expect("lifecycle");
2545        assert_eq!(lifecycle, json!({ "state": "preflight" }));
2546
2547        let query_error = dispatch(
2548            &mut transport,
2549            &mut client,
2550            &mut effects,
2551            "query",
2552            &json!({ "sql": "SELECT id FROM todos", "params": [] }),
2553        )
2554        .expect_err("protected query must fail");
2555        assert_eq!(query_error.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
2556        let diagnostics_error = dispatch(
2557            &mut transport,
2558            &mut client,
2559            &mut effects,
2560            "diagnosticsSnapshot",
2561            &json!({}),
2562        )
2563        .expect_err("diagnostics unit evidence remains protected");
2564        assert_eq!(diagnostics_error.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
2565
2566        dispatch(
2567            &mut transport,
2568            &mut client,
2569            &mut effects,
2570            "purgeLocalData",
2571            &json!({
2572                "input": {
2573                    "purgeId": "directive-1",
2574                    "targets": [{
2575                        "table": "todos",
2576                        "selectors": { "list_id": ["list-1"] }
2577                    }]
2578                }
2579            }),
2580        )
2581        .expect("authorized local purge remains available");
2582
2583        let repair_error = dispatch(
2584            &mut transport,
2585            &mut client,
2586            &mut effects,
2587            "rebootstrapLocalData",
2588            &json!({ "input": { "rebootstrapId": "blocked-repair" } }),
2589        )
2590        .expect_err("projection repair must remain protected during preflight");
2591        assert_eq!(repair_error.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
2592
2593        dispatch(
2594            &mut transport,
2595            &mut client,
2596            &mut effects,
2597            "activateSecurity",
2598            &json!({}),
2599        )
2600        .expect("activation");
2601        let rows = dispatch(
2602            &mut transport,
2603            &mut client,
2604            &mut effects,
2605            "query",
2606            &json!({ "sql": "SELECT id FROM todos", "params": [] }),
2607        )
2608        .expect("active query");
2609        assert_eq!(rows, json!({ "rows": [] }));
2610
2611        dispatch(
2612            &mut transport,
2613            &mut client,
2614            &mut effects,
2615            "beginSecurityPreflight",
2616            &json!({}),
2617        )
2618        .expect("re-enter preflight");
2619        let blocked = dispatch(
2620            &mut transport,
2621            &mut client,
2622            &mut effects,
2623            "mutate",
2624            &json!({ "mutations": [] }),
2625        )
2626        .expect_err("mutation must be gated");
2627        assert_eq!(blocked.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
2628        let blocked = dispatch(
2629            &mut transport,
2630            &mut client,
2631            &mut effects,
2632            "replacePendingCommit",
2633            &json!({ "clientCommitId": "a", "operations": [], "replacementClientCommitId": "b" }),
2634        )
2635        .expect_err("a pending-commit replacement must be gated");
2636        assert_eq!(blocked.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
2637    }
2638
2639    #[test]
2640    fn replace_pending_commit_replaces_a_never_sent_commit_without_transport() {
2641        let schema = json!({
2642            "version": 1,
2643            "tables": [{
2644                "name": "todos",
2645                "columns": [
2646                    { "name": "id", "type": "string", "nullable": false },
2647                    { "name": "title", "type": "string", "nullable": false }
2648                ],
2649                "primaryKey": "id",
2650                "scopes": []
2651            }]
2652        });
2653        let mut transport = NoNetwork::default();
2654        let mut client: Option<SyncClient> = None;
2655        let mut effects = CreateEffects::default();
2656        let mut call = |method: &str, params: Value| {
2657            dispatch(&mut transport, &mut client, &mut effects, method, &params)
2658        };
2659        call("create", json!({ "schema": schema })).expect("create");
2660        let operations = json!([{
2661            "op": "upsert", "table": "todos", "values": { "id": "t1", "title": "first" }
2662        }]);
2663        let original = call("mutate", json!({ "mutations": operations })).expect("mutate")
2664            ["clientCommitId"]
2665            .clone();
2666        for (params, code) in [
2667            (
2668                json!({ "operations": [], "replacementClientCommitId": "r" }),
2669                "sync.invalid_request",
2670            ),
2671            (
2672                json!({ "clientCommitId": original, "operations": [] }),
2673                "sync.invalid_request",
2674            ),
2675            (
2676                json!({ "clientCommitId": "none", "operations": [], "replacementClientCommitId": "r" }),
2677                "sync.outcome_not_found",
2678            ),
2679        ] {
2680            let error = call("replacePendingCommit", params.clone()).expect_err("refused");
2681            assert_eq!(error.code, code, "{params}");
2682        }
2683        let replace = json!({
2684            "clientCommitId": original,
2685            "operations": [{
2686                "op": "upsert", "table": "todos", "values": { "id": "t1", "title": "second" }
2687            }],
2688            "replacementClientCommitId": "replacement-1"
2689        });
2690        for _ in 0..2 {
2691            let replaced = call("replacePendingCommit", replace.clone()).expect("replaced");
2692            assert_eq!(replaced["clientCommitId"], "replacement-1");
2693        }
2694        let pending = call("pendingCommitIds", Value::Null).expect("pending");
2695        assert_eq!(pending["ids"], json!(["replacement-1"]));
2696        let rows = call(
2697            "query",
2698            json!({ "sql": "SELECT title FROM todos", "params": [] }),
2699        )
2700        .expect("query");
2701        assert_eq!(rows["rows"][0]["title"], "second");
2702        let delivery =
2703            call("commitDelivery", json!({ "clientCommitId": original })).expect("delivery");
2704        assert_eq!(delivery["outcome"]["status"], "replaced", "{delivery}");
2705        assert_eq!(
2706            delivery["outcome"]["replacementClientCommitId"],
2707            "replacement-1"
2708        );
2709    }
2710
2711    #[test]
2712    fn replace_commit_outcome_forwards_typed_failures() {
2713        let schema = json!({
2714            "version": 1,
2715            "tables": [{
2716                "name": "todos",
2717                "columns": [{ "name": "id", "type": "string", "nullable": false }],
2718                "primaryKey": "id",
2719                "scopes": []
2720            }]
2721        });
2722        let mut transport = NoNetwork::default();
2723        let mut client: Option<SyncClient> = None;
2724        let mut effects = CreateEffects::default();
2725        dispatch(
2726            &mut transport,
2727            &mut client,
2728            &mut effects,
2729            "create",
2730            &json!({ "schema": schema }),
2731        )
2732        .expect("create");
2733        for (params, code) in [
2734            (json!({ "sequence": 1 }), "sync.invalid_request"),
2735            (json!({ "clientCommitId": "none" }), "sync.invalid_request"),
2736            (
2737                json!({ "clientCommitId": "none", "sequence": 1, "replacement": [] }),
2738                "sync.outcome_not_found",
2739            ),
2740        ] {
2741            let error = dispatch(
2742                &mut transport,
2743                &mut client,
2744                &mut effects,
2745                "replaceCommitOutcome",
2746                &params,
2747            )
2748            .expect_err("refused");
2749            assert_eq!(error.code, code, "{params}");
2750        }
2751    }
2752
2753    #[test]
2754    fn mutate_and_patch_forward_typed_storage_failures() {
2755        let path = temp_db_path("busy-authoring");
2756        let schema = json!({
2757            "version": 1,
2758            "tables": [{
2759                "name": "todos",
2760                "columns": [
2761                    { "name": "id", "type": "string", "nullable": false },
2762                    { "name": "list_id", "type": "string", "nullable": false },
2763                    { "name": "title", "type": "string", "nullable": false }
2764                ],
2765                "primaryKey": "id",
2766                "scopes": [{ "pattern": "list:{list_id}", "column": "list_id" }]
2767            }]
2768        });
2769        let mut transport = NoNetwork::default();
2770        let mut client: Option<SyncClient> = None;
2771        let mut effects = CreateEffects::default();
2772        dispatch(
2773            &mut transport,
2774            &mut client,
2775            &mut effects,
2776            "create",
2777            &json!({ "schema": schema, "dbPath": path }),
2778        )
2779        .expect("create file-backed client");
2780        let upsert = |id: &str| {
2781            json!({ "mutations": [{ "op": "upsert", "table": "todos", "values": {
2782                "id": id, "list_id": "l1", "title": "first" } }] })
2783        };
2784        dispatch(
2785            &mut transport,
2786            &mut client,
2787            &mut effects,
2788            "mutate",
2789            &upsert("t1"),
2790        )
2791        .expect("seed row");
2792
2793        let locker = rusqlite::Connection::open(&path).expect("second connection");
2794        locker.execute_batch("BEGIN IMMEDIATE").unwrap();
2795        let busy = dispatch(
2796            &mut transport,
2797            &mut client,
2798            &mut effects,
2799            "mutate",
2800            &upsert("t2"),
2801        )
2802        .expect_err("busy mutate");
2803        assert_eq!(busy.code, "client.storage_busy");
2804        assert!(busy.retryable);
2805        assert_eq!(busy.details.as_ref().unwrap()["sqliteCode"], 5);
2806
2807        let busy_patch = dispatch(
2808            &mut transport,
2809            &mut client,
2810            &mut effects,
2811            "patch",
2812            &json!({ "table": "todos", "rowId": "t1", "partial": { "title": "second" } }),
2813        )
2814        .expect_err("busy patch");
2815        assert_eq!(busy_patch.code, "client.storage_busy");
2816        assert!(busy_patch.retryable);
2817        assert_eq!(busy_patch.details.as_ref().unwrap()["sqliteCode"], 5);
2818
2819        locker.execute_batch("ROLLBACK").unwrap();
2820        let retried = dispatch(
2821            &mut transport,
2822            &mut client,
2823            &mut effects,
2824            "mutate",
2825            &upsert("t2"),
2826        )
2827        .expect("retry after busy");
2828        assert!(retried.get("clientCommitId").is_some());
2829        let _ = std::fs::remove_file(&path);
2830    }
2831
2832    #[test]
2833    fn read_command_error_preserves_code_details_and_retryability() {
2834        let corrupt = super::read_command_error(syncular_client::QueryReadFailure {
2835            code: Some("sync.local_corrupt"),
2836            sqlite_code: None,
2837            sqlite_message: None,
2838            rollback_failure: None,
2839            message: "persisted local revision is invalid".to_owned(),
2840        });
2841        assert_eq!(corrupt.code, "sync.local_corrupt");
2842        assert!(!corrupt.retryable);
2843        assert!(corrupt.details.is_none());
2844
2845        let busy = super::read_command_error(syncular_client::QueryReadFailure {
2846            code: Some("client.storage_busy"),
2847            sqlite_code: Some(5),
2848            sqlite_message: Some("database is locked".to_owned()),
2849            rollback_failure: None,
2850            message: "local SQLite storage is busy".to_owned(),
2851        });
2852        assert_eq!(busy.code, "client.storage_busy");
2853        assert!(busy.retryable);
2854        assert_eq!(
2855            busy.details.expect("busy details")["sqliteCode"],
2856            serde_json::json!(5)
2857        );
2858    }
2859
2860    #[test]
2861    fn mutate_and_patch_report_caller_value_failures_as_invalid_request() {
2862        let path = temp_db_path("caller-values");
2863        let schema = json!({
2864            "version": 1,
2865            "tables": [{
2866                "name": "todos",
2867                "columns": [
2868                    { "name": "id", "type": "string", "nullable": false },
2869                    { "name": "list_id", "type": "string", "nullable": false },
2870                    { "name": "title", "type": "string", "nullable": false },
2871                    { "name": "priority", "type": "integer", "nullable": false }
2872                ],
2873                "primaryKey": "id",
2874                "scopes": [{ "pattern": "list:{list_id}", "column": "list_id" }]
2875            }]
2876        });
2877        let mut transport = NoNetwork::default();
2878        let mut client: Option<SyncClient> = None;
2879        let mut effects = CreateEffects::default();
2880        dispatch(
2881            &mut transport,
2882            &mut client,
2883            &mut effects,
2884            "create",
2885            &json!({ "schema": schema, "dbPath": path }),
2886        )
2887        .expect("create file-backed client");
2888        let seed = dispatch(
2889            &mut transport,
2890            &mut client,
2891            &mut effects,
2892            "mutate",
2893            &json!({ "mutations": [{ "op": "upsert", "table": "todos", "values": {
2894                "id": "t1", "list_id": "l1", "title": "first", "priority": 1 } }] }),
2895        )
2896        .expect("seed row");
2897        let seed_id = seed["clientCommitId"].clone();
2898
2899        // §6.1/§7.1: a caller value the authoring seam rejects is an invalid
2900        // request, not the internal-failure default.
2901        let unknown = dispatch(
2902            &mut transport,
2903            &mut client,
2904            &mut effects,
2905            "mutate",
2906            &json!({ "mutations": [{ "op": "upsert", "table": "todos", "values": {
2907                "id": "t2", "list_id": "l1", "title": "second", "priority": 1,
2908                "missing_column": 1 } }] }),
2909        )
2910        .expect_err("unknown column");
2911        assert_eq!(unknown.code, "sync.invalid_request");
2912        assert_eq!(unknown.message, "the authoring request is invalid");
2913        assert!(!unknown.retryable);
2914        assert!(unknown.details.as_ref().unwrap()["legacyCause"]
2915            .as_str()
2916            .unwrap()
2917            .contains("unknown column"));
2918
2919        let bad_patch = dispatch(
2920            &mut transport,
2921            &mut client,
2922            &mut effects,
2923            "patch",
2924            &json!({ "table": "todos", "rowId": "t1", "partial": { "priority": "high" } }),
2925        )
2926        .expect_err("bad patch value");
2927        assert_eq!(bad_patch.code, "sync.invalid_request");
2928        assert_eq!(bad_patch.message, "the authoring request is invalid");
2929        assert!(bad_patch.details.as_ref().unwrap()["legacyCause"]
2930            .as_str()
2931            .unwrap()
2932            .contains("priority"));
2933
2934        // Neither rejection enqueued a commit or touched the projection.
2935        let pending = dispatch(
2936            &mut transport,
2937            &mut client,
2938            &mut effects,
2939            "pendingCommitIds",
2940            &json!({}),
2941        )
2942        .expect("pending commit ids");
2943        assert_eq!(pending["ids"], json!([seed_id]));
2944        let rows = dispatch(
2945            &mut transport,
2946            &mut client,
2947            &mut effects,
2948            "query",
2949            &json!({ "sql": "SELECT id, priority FROM todos ORDER BY id" }),
2950        )
2951        .expect("visible rows");
2952        assert_eq!(rows["rows"], json!([{ "id": "t1", "priority": 1 }]));
2953
2954        // The next valid call authorizes normally.
2955        let accepted = dispatch(
2956            &mut transport,
2957            &mut client,
2958            &mut effects,
2959            "mutate",
2960            &json!({ "mutations": [{ "op": "upsert", "table": "todos", "values": {
2961                "id": "t2", "list_id": "l1", "title": "second", "priority": 2 } }] }),
2962        )
2963        .expect("retry after rejection");
2964        assert!(accepted.get("clientCommitId").is_some());
2965        let _ = std::fs::remove_file(&path);
2966    }
2967
2968    #[test]
2969    fn client_err_preserves_retryable_for_storage_busy() {
2970        let busy = client_err("client.storage_busy: local SQLite storage is busy".to_owned());
2971        assert_eq!(busy.code, "client.storage_busy");
2972        assert!(busy.retryable);
2973        // The legacy boundary keeps the full rendered message.
2974        assert_eq!(
2975            busy.message,
2976            "client.storage_busy: local SQLite storage is busy"
2977        );
2978        let full = client_err("client.storage_full: local SQLite storage is full".to_owned());
2979        assert_eq!(full.code, "client.storage_full");
2980        assert!(!full.retryable);
2981    }
2982
2983    #[test]
2984    fn client_err_keeps_a_colon_less_code_identity() {
2985        let error = client_err("sync.unknown_table".to_owned());
2986        assert_eq!(error.code, "sync.unknown_table");
2987        let error = client_err("no client instance created".to_owned());
2988        assert_eq!(error.code, "client.failed");
2989    }
2990
2991    #[cfg(feature = "crdt-yjs")]
2992    #[test]
2993    fn crdt_offsets_outside_u32_are_invalid_requests() {
2994        let mut transport = NoNetwork::default();
2995        let mut client: Option<SyncClient> = None;
2996        let mut effects = CreateEffects::default();
2997        dispatch(
2998            &mut transport,
2999            &mut client,
3000            &mut effects,
3001            "create",
3002            &json!({ "schema": schema() }),
3003        )
3004        .expect("create");
3005        let target = json!({ "table": "todos", "rowId": "t1", "column": "body" });
3006        for (method, extra) in [
3007            (
3008                "crdtInsertText",
3009                json!({ "index": 4_294_967_296u64, "value": "x" }),
3010            ),
3011            ("crdtInsertText", json!({ "index": "0", "value": "x" })),
3012            (
3013                "crdtDeleteText",
3014                json!({ "index": 0, "len": 4_294_967_296u64 }),
3015            ),
3016        ] {
3017            let mut params = target.clone();
3018            params
3019                .as_object_mut()
3020                .unwrap()
3021                .extend(extra.as_object().unwrap().clone());
3022            let error = dispatch(&mut transport, &mut client, &mut effects, method, &params)
3023                .expect_err("out-of-range offset");
3024            assert_eq!(error.code, "sync.invalid_request", "{method} {params}");
3025        }
3026    }
3027
3028    #[test]
3029    fn wrong_typed_optional_fields_are_invalid_requests() {
3030        let created = || {
3031            let mut transport = NoNetwork::default();
3032            let mut client: Option<SyncClient> = None;
3033            let mut effects = CreateEffects::default();
3034            dispatch(
3035                &mut transport,
3036                &mut client,
3037                &mut effects,
3038                "create",
3039                &json!({ "schema": schema() }),
3040            )
3041            .expect("create");
3042            (transport, client, effects)
3043        };
3044        for params in [
3045            json!({ "schema": schema(), "limits": "x" }),
3046            json!({ "schema": schema(), "limits": { "accept": 256 } }),
3047            json!({ "schema": schema(), "limits": { "accept": "15" } }),
3048            json!({ "schema": schema(), "limits": { "limitCommits": 4_294_967_296i64 } }),
3049            json!({ "schema": schema(), "limits": { "outcomeRetentionMaxEntries": -1 } }),
3050            json!({ "schema": schema(), "clientId": 7 }),
3051            json!({ "schema": schema(), "nowMs": "1" }),
3052            json!({ "schema": schema(), "signedUrls": "true" }),
3053            json!({ "schema": schema(), "securityPreflight": 1 }),
3054            json!({ "schema": schema(), "encryption": { "keys": "k" } }),
3055        ] {
3056            let mut transport = NoNetwork::default();
3057            let mut client: Option<SyncClient> = None;
3058            let mut effects = CreateEffects::default();
3059            let error = dispatch(&mut transport, &mut client, &mut effects, "create", &params)
3060                .expect_err("wrong-typed create field");
3061            assert_eq!(error.code, "sync.invalid_request", "{params}");
3062        }
3063        let base = json!({ "variable": "list_id" });
3064        for (method, params) in [
3065            ("setWindow", json!({ "base": base, "units": [1] })),
3066            ("setWindow", json!({ "base": base, "units": "l1" })),
3067            (
3068                "setWindow",
3069                json!({ "base": { "variable": "list_id", "fixedScopes": ["x"] }, "units": [] }),
3070            ),
3071            ("windowState", json!({ "base": {} })),
3072            (
3073                "mutate",
3074                json!({ "mutations": [{ "op": "delete", "table": "todos", "rowId": "t1", "baseVersion": "7" }] }),
3075            ),
3076            (
3077                "patch",
3078                json!({ "table": "todos", "rowId": "t1", "partial": { "title": "x" }, "baseVersion": "7" }),
3079            ),
3080            ("subscribe", json!({ "scopes": { "list_id": ["l1"] } })),
3081            (
3082                "subscribeMany",
3083                json!({ "units": [{ "list_id": "l1" }, 7] }),
3084            ),
3085            (
3086                "uploadBlob",
3087                json!({ "bytes": { "$bytes": "00" }, "mediaType": 1 }),
3088            ),
3089        ] {
3090            let (mut transport, mut client, mut effects) = created();
3091            let error = dispatch(&mut transport, &mut client, &mut effects, method, &params)
3092                .expect_err("wrong-typed field");
3093            assert_eq!(error.code, "sync.invalid_request", "{method} {params}");
3094        }
3095        // An absent or null optional field keeps its default.
3096        let (mut transport, mut client, mut effects) = created();
3097        dispatch(
3098            &mut transport,
3099            &mut client,
3100            &mut effects,
3101            "mutate",
3102            &json!({ "mutations": [{ "op": "delete", "table": "todos", "rowId": "t1", "baseVersion": null }] }),
3103        )
3104        .expect("null baseVersion is absent");
3105    }
3106
3107    #[test]
3108    fn sync_until_idle_rejects_an_invalid_max_rounds_budget() {
3109        for value in [json!(0), json!(-1), json!(1.5), json!(4_294_967_296u64)] {
3110            let mut transport = NoNetwork::default();
3111            let mut client: Option<SyncClient> = None;
3112            let mut effects = CreateEffects::default();
3113            dispatch(
3114                &mut transport,
3115                &mut client,
3116                &mut effects,
3117                "create",
3118                &json!({ "schema": schema() }),
3119            )
3120            .expect("create");
3121            let error = dispatch(
3122                &mut transport,
3123                &mut client,
3124                &mut effects,
3125                "syncUntilIdle",
3126                &json!({ "maxRounds": value }),
3127            )
3128            .expect_err("invalid budget");
3129            assert_eq!(error.code, "sync.invalid_request", "{value}");
3130        }
3131    }
3132
3133    #[test]
3134    fn sync_until_idle_rejects_an_invalid_timeout() {
3135        for value in [json!(0), json!(-1), json!(1.5)] {
3136            let mut transport = NoNetwork::default();
3137            let mut client: Option<SyncClient> = None;
3138            let mut effects = CreateEffects::default();
3139            dispatch(
3140                &mut transport,
3141                &mut client,
3142                &mut effects,
3143                "create",
3144                &json!({ "schema": schema() }),
3145            )
3146            .expect("create");
3147            let error = dispatch(
3148                &mut transport,
3149                &mut client,
3150                &mut effects,
3151                "syncUntilIdle",
3152                &json!({ "timeoutMs": value }),
3153            )
3154            .expect_err("invalid timeout");
3155            assert_eq!(error.code, "sync.invalid_request", "{value}");
3156        }
3157    }
3158
3159    #[test]
3160    fn create_rejects_invalid_push_limits() {
3161        for value in [json!(0), json!(-1), json!(1.5), json!(4_294_967_296u64)] {
3162            let mut transport = NoNetwork::default();
3163            let mut client: Option<SyncClient> = None;
3164            let mut effects = CreateEffects::default();
3165            let error = dispatch(
3166                &mut transport,
3167                &mut client,
3168                &mut effects,
3169                "create",
3170                &json!({
3171                    "schema": schema(),
3172                    "limits": { "maxPushRequestBytes": value }
3173                }),
3174            )
3175            .expect_err("invalid push limit");
3176            assert_eq!(error.code, "sync.invalid_request", "{value}");
3177            assert_eq!(
3178                error.details.as_ref().unwrap()["limit"],
3179                json!("maxPushRequestBytes")
3180            );
3181        }
3182    }
3183
3184    #[test]
3185    fn preflight_allows_only_the_authorized_previous_version_discard() {
3186        let mut transport = NoNetwork::default();
3187        let mut client: Option<SyncClient> = None;
3188        let mut effects = CreateEffects::default();
3189        dispatch(
3190            &mut transport,
3191            &mut client,
3192            &mut effects,
3193            "create",
3194            &json!({ "schema": schema(), "securityPreflight": true }),
3195        )
3196        .expect("preflight create");
3197
3198        // Reads and the audit observe protected local data: still gated.
3199        for method in ["previousVersionSnapshot", "previousVersionAudit"] {
3200            let error = dispatch(
3201                &mut transport,
3202                &mut client,
3203                &mut effects,
3204                method,
3205                &json!({}),
3206            )
3207            .expect_err("previous-version reads stay gated during preflight");
3208            assert_eq!(error.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
3209        }
3210        // RFC 0006 runs the discard consumer inside the quiesced window, so the
3211        // command router must permit it (feature off here: a clean no-op).
3212        let discarded = dispatch(
3213            &mut transport,
3214            &mut client,
3215            &mut effects,
3216            "previousVersionDiscard",
3217            &json!({}),
3218        )
3219        .expect("authorized cleanup is allowed during preflight");
3220        assert_eq!(discarded, json!({ "present": false, "discarded": false }));
3221        // Preflight closed the socket; releasing it again is allowed.
3222        dispatch(
3223            &mut transport,
3224            &mut client,
3225            &mut effects,
3226            "disconnectRealtime",
3227            &json!({}),
3228        )
3229        .expect("disconnect is allowed during preflight");
3230        assert!(client.as_ref().is_some_and(SyncClient::security_preflight));
3231    }
3232
3233    #[test]
3234    fn disconnect_without_a_client_succeeds() {
3235        let mut transport = NoNetwork::default();
3236        let mut client: Option<SyncClient> = None;
3237        let mut effects = CreateEffects::default();
3238        dispatch(
3239            &mut transport,
3240            &mut client,
3241            &mut effects,
3242            "disconnectRealtime",
3243            &json!({}),
3244        )
3245        .expect("a missing client holds no socket");
3246        dispatch(
3247            &mut transport,
3248            &mut client,
3249            &mut effects,
3250            "create",
3251            &json!({ "schema": schema() }),
3252        )
3253        .expect("create");
3254        dispatch(
3255            &mut transport,
3256            &mut client,
3257            &mut effects,
3258            "shutdown",
3259            &json!({}),
3260        )
3261        .expect("shutdown");
3262        dispatch(
3263            &mut transport,
3264            &mut client,
3265            &mut effects,
3266            "disconnectRealtime",
3267            &json!({}),
3268        )
3269        .expect("a shut-down client holds no socket");
3270    }
3271
3272    #[test]
3273    fn preflight_refuses_a_replacement_create_without_the_flag() {
3274        let mut transport = NoNetwork::default();
3275        let mut client: Option<SyncClient> = None;
3276        let mut effects = CreateEffects::default();
3277        dispatch(
3278            &mut transport,
3279            &mut client,
3280            &mut effects,
3281            "create",
3282            &json!({ "schema": schema(), "securityPreflight": true }),
3283        )
3284        .expect("preflight create");
3285
3286        // The escape the gate exists to prevent: a plain re-create must fail.
3287        let escape = dispatch(
3288            &mut transport,
3289            &mut client,
3290            &mut effects,
3291            "create",
3292            &json!({ "schema": schema() }),
3293        )
3294        .expect_err("plain create must be refused during preflight");
3295        assert_eq!(escape.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
3296        // The refused create left the preflighted client installed and gated.
3297        let query_error = dispatch(
3298            &mut transport,
3299            &mut client,
3300            &mut effects,
3301            "query",
3302            &json!({ "sql": "SELECT id FROM todos", "params": [] }),
3303        )
3304        .expect_err("protected query stays gated");
3305        assert_eq!(query_error.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
3306
3307        // A preflighted replacement is permitted and stays gated.
3308        dispatch(
3309            &mut transport,
3310            &mut client,
3311            &mut effects,
3312            "create",
3313            &json!({ "schema": schema(), "securityPreflight": true }),
3314        )
3315        .expect("preflighted replacement create");
3316        let still_gated = dispatch(
3317            &mut transport,
3318            &mut client,
3319            &mut effects,
3320            "query",
3321            &json!({ "sql": "SELECT id FROM todos", "params": [] }),
3322        )
3323        .expect_err("replacement stays gated");
3324        assert_eq!(still_gated.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
3325
3326        // A legitimate activation releases the gate; creates behave as today.
3327        dispatch(
3328            &mut transport,
3329            &mut client,
3330            &mut effects,
3331            "activateSecurity",
3332            &json!({}),
3333        )
3334        .expect("activation");
3335        dispatch(
3336            &mut transport,
3337            &mut client,
3338            &mut effects,
3339            "create",
3340            &json!({ "schema": schema() }),
3341        )
3342        .expect("plain create after activation");
3343        let rows = dispatch(
3344            &mut transport,
3345            &mut client,
3346            &mut effects,
3347            "query",
3348            &json!({ "sql": "SELECT id FROM todos", "params": [] }),
3349        )
3350        .expect("active query");
3351        assert_eq!(rows, json!({ "rows": [] }));
3352    }
3353
3354    /// A file-backed replica: the persisted quarantine marker only exists here,
3355    /// which is why the in-memory tests above could not catch this.
3356    fn temp_db_path(tag: &str) -> String {
3357        std::env::temp_dir()
3358            .join(format!(
3359                "syncular-command-{tag}-{}-{:?}.db",
3360                std::process::id(),
3361                std::time::SystemTime::now()
3362                    .duration_since(std::time::UNIX_EPOCH)
3363                    .expect("clock")
3364                    .as_nanos()
3365            ))
3366            .to_string_lossy()
3367            .into_owned()
3368    }
3369
3370    #[test]
3371    fn an_activated_replica_reopens_plainly_after_shutdown() {
3372        // Shutting an ACTIVATED client down is not a quarantine event. The
3373        // teardown barrier used to call `begin_security_preflight`, which now
3374        // persists the gate, so every cleanly closed replica was marked pending
3375        // and its next plain `create` was refused forever — the reopen path
3376        // restores the flag from the marker and the create guard rejects it.
3377        let path = temp_db_path("activated-reopen");
3378        let mut transport = NoNetwork::default();
3379        let mut client: Option<SyncClient> = None;
3380        let mut effects = CreateEffects::default();
3381
3382        dispatch(
3383            &mut transport,
3384            &mut client,
3385            &mut effects,
3386            "create",
3387            &json!({ "schema": schema(), "securityPreflight": true, "dbPath": path }),
3388        )
3389        .expect("preflight create");
3390        dispatch(
3391            &mut transport,
3392            &mut client,
3393            &mut effects,
3394            "activateSecurity",
3395            &json!({}),
3396        )
3397        .expect("activation clears the gate");
3398        dispatch(
3399            &mut transport,
3400            &mut client,
3401            &mut effects,
3402            "shutdown",
3403            &json!({}),
3404        )
3405        .expect("shutdown after activation");
3406
3407        // The replica is active on disk, so a plain re-create must be admitted.
3408        dispatch(
3409            &mut transport,
3410            &mut client,
3411            &mut effects,
3412            "create",
3413            &json!({ "schema": schema(), "dbPath": path }),
3414        )
3415        .expect("an activated replica must reopen plainly after shutdown");
3416        let state = dispatch(
3417            &mut transport,
3418            &mut client,
3419            &mut effects,
3420            "securityLifecycle",
3421            &json!({}),
3422        )
3423        .expect("lifecycle");
3424        assert_eq!(state, json!({ "state": "active" }));
3425
3426        let _ = std::fs::remove_file(&path);
3427    }
3428
3429    #[test]
3430    fn an_unactivated_replica_stays_quarantined_across_shutdown_on_disk() {
3431        // The other half, and the reason the marker exists: a replica that
3432        // entered preflight and never activated must still refuse a plain
3433        // re-create after shutdown, even on a host that rebuilt its handle and
3434        // carries no in-memory flag.
3435        let path = temp_db_path("quarantined-reopen");
3436        let mut transport = NoNetwork::default();
3437        let mut client: Option<SyncClient> = None;
3438        let mut effects = CreateEffects::default();
3439
3440        dispatch(
3441            &mut transport,
3442            &mut client,
3443            &mut effects,
3444            "create",
3445            &json!({ "schema": schema(), "securityPreflight": true, "dbPath": path }),
3446        )
3447        .expect("preflight create");
3448        dispatch(
3449            &mut transport,
3450            &mut client,
3451            &mut effects,
3452            "shutdown",
3453            &json!({}),
3454        )
3455        .expect("shutdown during preflight");
3456
3457        // A fresh host handle: no in-memory pending flag survives here, so only
3458        // the persisted marker can hold the gate.
3459        let mut rebuilt = CreateEffects::default();
3460        let escape = dispatch(
3461            &mut transport,
3462            &mut client,
3463            &mut rebuilt,
3464            "create",
3465            &json!({ "schema": schema(), "dbPath": path }),
3466        )
3467        .expect_err("a quarantined replica must refuse a plain re-create");
3468        assert_eq!(escape.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
3469
3470        let _ = std::fs::remove_file(&path);
3471    }
3472
3473    #[test]
3474    fn preflight_gate_survives_shutdown_before_replacement_creates() {
3475        let mut transport = NoNetwork::default();
3476        let mut client: Option<SyncClient> = None;
3477        let mut effects = CreateEffects::default();
3478        dispatch(
3479            &mut transport,
3480            &mut client,
3481            &mut effects,
3482            "create",
3483            &json!({ "schema": schema(), "securityPreflight": true }),
3484        )
3485        .expect("preflight create");
3486        dispatch(
3487            &mut transport,
3488            &mut client,
3489            &mut effects,
3490            "shutdown",
3491            &json!({}),
3492        )
3493        .expect("shutdown during preflight");
3494        assert!(client.is_none());
3495
3496        // The pending preflight rides `effects` across the empty client slot.
3497        let escape = dispatch(
3498            &mut transport,
3499            &mut client,
3500            &mut effects,
3501            "create",
3502            &json!({ "schema": schema() }),
3503        )
3504        .expect_err("shutdown + plain create must stay refused");
3505        assert_eq!(escape.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
3506
3507        dispatch(
3508            &mut transport,
3509            &mut client,
3510            &mut effects,
3511            "create",
3512            &json!({ "schema": schema(), "securityPreflight": true }),
3513        )
3514        .expect("preflighted re-create");
3515        dispatch(
3516            &mut transport,
3517            &mut client,
3518            &mut effects,
3519            "activateSecurity",
3520            &json!({}),
3521        )
3522        .expect("activation");
3523
3524        // An ACTIVATED client shut down cleanly may be recreated plainly.
3525        dispatch(
3526            &mut transport,
3527            &mut client,
3528            &mut effects,
3529            "shutdown",
3530            &json!({}),
3531        )
3532        .expect("shutdown after activation");
3533        dispatch(
3534            &mut transport,
3535            &mut client,
3536            &mut effects,
3537            "create",
3538            &json!({ "schema": schema() }),
3539        )
3540        .expect("plain create after an activated shutdown");
3541    }
3542
3543    #[test]
3544    fn activate_security_refuses_headers_and_keeps_the_gate_closed() {
3545        let mut transport = NoNetwork::default();
3546        let mut client: Option<SyncClient> = None;
3547        let mut effects = CreateEffects::default();
3548        dispatch(
3549            &mut transport,
3550            &mut client,
3551            &mut effects,
3552            "create",
3553            &json!({ "schema": schema(), "securityPreflight": true }),
3554        )
3555        .expect("preflight create");
3556
3557        // Activation headers fail loudly and keep the gate closed.
3558        let invalid = dispatch(
3559            &mut transport,
3560            &mut client,
3561            &mut effects,
3562            "activateSecurity",
3563            &json!({ "headers": { "authorization": 7 } }),
3564        )
3565        .expect_err("non-string header must fail");
3566        assert_eq!(invalid.code, "sync.invalid_request");
3567        let lifecycle = dispatch(
3568            &mut transport,
3569            &mut client,
3570            &mut effects,
3571            "securityLifecycle",
3572            &json!({}),
3573        )
3574        .expect("lifecycle");
3575        assert_eq!(lifecycle, json!({ "state": "preflight" }));
3576
3577        // Well-formed headers are refused too: the header source replaced
3578        // them. Activation without them opens the gate.
3579        let refused = dispatch(
3580            &mut transport,
3581            &mut client,
3582            &mut effects,
3583            "activateSecurity",
3584            &json!({ "headers": { "authorization": "Bearer fresh" } }),
3585        )
3586        .expect_err("activation headers are refused");
3587        assert_eq!(refused.code, "sync.invalid_request");
3588        dispatch(
3589            &mut transport,
3590            &mut client,
3591            &mut effects,
3592            "activateSecurity",
3593            &json!({}),
3594        )
3595        .expect("activation");
3596        let lifecycle = dispatch(
3597            &mut transport,
3598            &mut client,
3599            &mut effects,
3600            "securityLifecycle",
3601            &json!({}),
3602        )
3603        .expect("lifecycle");
3604        assert_eq!(lifecycle, json!({ "state": "active" }));
3605    }
3606
3607    #[test]
3608    fn add_encryption_keys_extends_an_active_keyring() {
3609        let mut transport = NoNetwork::default();
3610        let mut client: Option<SyncClient> = None;
3611        let mut effects = CreateEffects::default();
3612        let key = |byte: &str| json!({ "$bytes": byte.repeat(32) });
3613        let closed = dispatch(
3614            &mut transport,
3615            &mut client,
3616            &mut effects,
3617            "addEncryptionKeys",
3618            &json!({ "keys": { "k2": key("2b") } }),
3619        )
3620        .expect_err("no client is open");
3621        assert_eq!(closed.code, "client.closed");
3622        assert_eq!(closed.message, "no client is open");
3623
3624        dispatch(
3625            &mut transport,
3626            &mut client,
3627            &mut effects,
3628            "create",
3629            &json!({ "schema": schema(), "encryption": { "keys": { "k1": key("2a") } } }),
3630        )
3631        .expect("create");
3632        let mut add = |client: &mut Option<SyncClient>, params: Value| {
3633            dispatch(
3634                &mut transport,
3635                client,
3636                &mut effects,
3637                "addEncryptionKeys",
3638                &params,
3639            )
3640        };
3641        assert_eq!(
3642            add(&mut client, json!({ "keys": { "k2": key("2b") } })).expect("add while active"),
3643            json!({})
3644        );
3645        // The installed key answers a conflicting re-add with its id.
3646        let conflict = add(&mut client, json!({ "keys": { "k2": key("2c") } }))
3647            .expect_err("conflicting bytes");
3648        assert_eq!(conflict.code, "sync.invalid_request");
3649        assert_eq!(
3650            conflict.message,
3651            "encryption key id is already held with different key bytes"
3652        );
3653        assert_eq!(conflict.details, Some(json!({ "keyId": "k2" })));
3654        add(&mut client, json!({ "keys": { "k2": key("2b") } })).expect("identical re-add");
3655
3656        let malformed = add(&mut client, json!({ "keys": { "k3": { "$bytes": "zz" } } }))
3657            .expect_err("malformed hex");
3658        assert_eq!(malformed.code, "sync.invalid_request");
3659        assert_eq!(malformed.details, Some(json!({ "keyId": "k3" })));
3660        // Two bad keys: the first in key-id order is named, whatever the input order.
3661        let first = add(
3662            &mut client,
3663            json!({ "keys": { "k9": { "$bytes": "2a2a" }, "k4": { "$bytes": "zz" } } }),
3664        )
3665        .expect_err("two bad keys");
3666        assert_eq!(first.details, Some(json!({ "keyId": "k4" })));
3667        let short = add(
3668            &mut client,
3669            json!({ "keys": { "k3": { "$bytes": "2a2a" } } }),
3670        )
3671        .expect_err("wrong length");
3672        assert_eq!(short.message, "encryption key must be 32 bytes (AES-256)");
3673        assert_eq!(short.details, Some(json!({ "keyId": "k3" })));
3674        for params in [json!({}), json!({ "keys": [] })] {
3675            assert_eq!(
3676                add(&mut client, params).expect_err("keys object").code,
3677                "sync.invalid_request"
3678            );
3679        }
3680
3681        dispatch(
3682            &mut transport,
3683            &mut client,
3684            &mut effects,
3685            "beginSecurityPreflight",
3686            &json!({}),
3687        )
3688        .expect("preflight");
3689        let gated = dispatch(
3690            &mut transport,
3691            &mut client,
3692            &mut effects,
3693            "addEncryptionKeys",
3694            &json!({ "keys": { "k3": key("2d") } }),
3695        )
3696        .expect_err("preflight refuses the addition");
3697        assert_eq!(gated.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
3698    }
3699
3700    fn schema_v2() -> Value {
3701        json!({
3702            "version": 2,
3703            "tables": [{
3704                "name": "todos",
3705                "columns": [
3706                    { "name": "id", "type": "string", "nullable": false },
3707                    { "name": "list_id", "type": "string", "nullable": false },
3708                    { "name": "note", "type": "string", "nullable": true }
3709                ],
3710                "primaryKey": "id",
3711                "scopes": [{ "pattern": "list:{list_id}", "column": "list_id" }]
3712            }]
3713        })
3714    }
3715
3716    fn previous_version_enabled() -> Value {
3717        json!({ "enabled": true })
3718    }
3719
3720    fn container_path(db_path: &str) -> String {
3721        format!("{db_path}.prev-context")
3722    }
3723
3724    #[test]
3725    fn previous_version_config_parser_matches_ts_keys_and_defaults() {
3726        assert_eq!(parse_previous_version_context(None).expect("absent"), None);
3727        let defaults = parse_previous_version_context(Some(&json!({})))
3728            .expect("empty")
3729            .expect("present");
3730        assert!(!defaults.enabled);
3731        assert_eq!(defaults.max_bytes, 8 * 1024 * 1024);
3732        assert_eq!(defaults.max_rows, 20_000);
3733        assert_eq!(defaults.max_tables, 32);
3734        assert_eq!(defaults.max_row_bytes, 1024 * 1024);
3735        assert_eq!(defaults.max_age_ms, 24 * 60 * 60 * 1000);
3736
3737        let configured = parse_previous_version_context(Some(&json!({
3738            "enabled": true,
3739            "maxBytes": 1024,
3740            "maxRows": 3,
3741            "maxTables": 2,
3742            "maxRowBytes": 5,
3743            "maxAgeMs": 7
3744        })))
3745        .expect("configured")
3746        .expect("present");
3747        assert!(configured.enabled);
3748        assert_eq!(configured.max_bytes, 1024);
3749        assert_eq!(configured.max_rows, 3);
3750        assert_eq!(configured.max_tables, 2);
3751        assert_eq!(configured.max_row_bytes, 5);
3752        assert_eq!(configured.max_age_ms, 7);
3753
3754        // Invalid values fail loudly instead of silently defaulting.
3755        for (value, expected) in [
3756            (json!([]), "must be an object"),
3757            (json!({ "enabled": "yes" }), "enabled must be a boolean"),
3758            (
3759                json!({ "maxBytes": 0 }),
3760                "maxBytes must be a positive safe integer",
3761            ),
3762            (
3763                json!({ "maxRows": -1 }),
3764                "maxRows must be a positive safe integer",
3765            ),
3766            (
3767                json!({ "maxTables": 1.5 }),
3768                "maxTables must be a positive safe integer",
3769            ),
3770            (
3771                json!({ "maxRowBytes": "1" }),
3772                "maxRowBytes must be a positive safe integer",
3773            ),
3774            (
3775                json!({ "maxAgeMs": 0 }),
3776                "maxAgeMs must be a positive safe integer",
3777            ),
3778        ] {
3779            let error = parse_previous_version_context(Some(&value)).expect_err("must fail");
3780            assert_eq!(error.code, "sync.invalid_request", "{value}");
3781            assert!(
3782                error.message.contains(expected),
3783                "{value}: {}",
3784                error.message
3785            );
3786        }
3787    }
3788
3789    #[test]
3790    fn invalid_previous_version_config_fails_create_loudly() {
3791        let mut transport = NoNetwork::default();
3792        let mut client: Option<SyncClient> = None;
3793        let mut effects = CreateEffects::default();
3794        let error = dispatch(
3795            &mut transport,
3796            &mut client,
3797            &mut effects,
3798            "create",
3799            &json!({ "schema": schema(), "previousVersionContext": { "enabled": true, "maxRows": 0 } }),
3800        )
3801        .expect_err("invalid config must fail the create");
3802        assert_eq!(error.code, "sync.invalid_request");
3803        assert!(error.message.contains("maxRows"), "{}", error.message);
3804        assert!(client.is_none(), "no client may be installed");
3805    }
3806
3807    #[test]
3808    fn previous_version_snapshot_reports_not_configured_by_default() {
3809        let mut transport = NoNetwork::default();
3810        let mut client: Option<SyncClient> = None;
3811        let mut effects = CreateEffects::default();
3812        dispatch(
3813            &mut transport,
3814            &mut client,
3815            &mut effects,
3816            "create",
3817            &json!({ "schema": schema() }),
3818        )
3819        .expect("create");
3820        let snapshot = dispatch(
3821            &mut transport,
3822            &mut client,
3823            &mut effects,
3824            "previousVersionSnapshot",
3825            &json!({ "table": "todos" }),
3826        )
3827        .expect("snapshot");
3828        assert_eq!(snapshot["state"], json!("previousVersion"));
3829        assert_eq!(snapshot["available"], json!(false));
3830        assert_eq!(snapshot["reason"], json!("not-configured"));
3831        assert_eq!(snapshot["rows"], json!([]));
3832        assert_eq!(snapshot["truncated"], json!(false));
3833        assert_eq!(snapshot["currentVersion"], json!(1));
3834        let discarded = dispatch(
3835            &mut transport,
3836            &mut client,
3837            &mut effects,
3838            "previousVersionDiscard",
3839            &json!({}),
3840        )
3841        .expect("discard");
3842        assert_eq!(discarded, json!({ "present": false, "discarded": false }));
3843        assert_eq!(
3844            dispatch(
3845                &mut transport,
3846                &mut client,
3847                &mut effects,
3848                "previousVersionAudit",
3849                &json!({}),
3850            )
3851            .expect("audit"),
3852            Value::Null
3853        );
3854    }
3855
3856    #[test]
3857    fn previous_version_commands_round_trip_through_the_dispatcher() {
3858        let path = temp_db_path("previous-version");
3859        let mut transport = NoNetwork::default();
3860        let mut client: Option<SyncClient> = None;
3861        let mut effects = CreateEffects::default();
3862
3863        // A v1 replica with one pending local row and the feature on.
3864        dispatch(
3865            &mut transport,
3866            &mut client,
3867            &mut effects,
3868            "create",
3869            &json!({
3870                "schema": schema(),
3871                "dbPath": path,
3872                "previousVersionContext": previous_version_enabled()
3873            }),
3874        )
3875        .expect("create v1");
3876        client
3877            .as_mut()
3878            .expect("client")
3879            .mutate(vec![Mutation::Upsert {
3880                table: "todos".to_owned(),
3881                values: serde_json::Map::from_iter([
3882                    ("id".to_owned(), json!("t1")),
3883                    ("list_id".to_owned(), json!("l1")),
3884                ]),
3885                base_version: None,
3886            }])
3887            .expect("seed a local row");
3888        dispatch(
3889            &mut transport,
3890            &mut client,
3891            &mut effects,
3892            "shutdown",
3893            &json!({}),
3894        )
3895        .expect("shutdown");
3896
3897        // The bump captures into the sibling file.
3898        dispatch(
3899            &mut transport,
3900            &mut client,
3901            &mut effects,
3902            "create",
3903            &json!({
3904                "schema": schema_v2(),
3905                "dbPath": path,
3906                "previousVersionContext": previous_version_enabled()
3907            }),
3908        )
3909        .expect("create v2");
3910        assert!(
3911            std::path::Path::new(&container_path(&path)).exists(),
3912            "the bump must leave a container file"
3913        );
3914        let status = dispatch(
3915            &mut transport,
3916            &mut client,
3917            &mut effects,
3918            "statusSnapshot",
3919            &json!({}),
3920        )
3921        .expect("status");
3922        assert_eq!(
3923            status["previousVersionContext"]["present"],
3924            json!(true),
3925            "{status}"
3926        );
3927        assert!(
3928            status["previousVersionContext"]["createdAtMs"].is_i64(),
3929            "{status}"
3930        );
3931
3932        let snapshot = dispatch(
3933            &mut transport,
3934            &mut client,
3935            &mut effects,
3936            "previousVersionSnapshot",
3937            &json!({ "table": "todos" }),
3938        )
3939        .expect("snapshot");
3940        assert_eq!(snapshot["state"], json!("previousVersion"));
3941        assert_eq!(snapshot["available"], json!(true));
3942        assert_eq!(snapshot["previousVersion"], json!(1));
3943        assert_eq!(snapshot["currentVersion"], json!(2));
3944        assert_eq!(snapshot["truncated"], json!(false));
3945        assert_eq!(snapshot["rows"][0]["id"], json!("t1"));
3946        assert_eq!(snapshot["rows"][0]["list_id"], json!("l1"));
3947
3948        // Unknown previous table and a bad limit are loud request errors.
3949        let unknown = dispatch(
3950            &mut transport,
3951            &mut client,
3952            &mut effects,
3953            "previousVersionSnapshot",
3954            &json!({ "table": "absent" }),
3955        )
3956        .expect_err("unknown previous table");
3957        assert_eq!(unknown.code, "sync.invalid_request");
3958        let bad_limit = dispatch(
3959            &mut transport,
3960            &mut client,
3961            &mut effects,
3962            "previousVersionSnapshot",
3963            &json!({ "table": "todos", "limit": 0 }),
3964        )
3965        .expect_err("bad limit");
3966        assert_eq!(bad_limit.code, "sync.invalid_request");
3967
3968        // D6: the audit names the pending commit's classification, with no
3969        // envelope and nothing dropped.
3970        let audit = dispatch(
3971            &mut transport,
3972            &mut client,
3973            &mut effects,
3974            "previousVersionAudit",
3975            &json!({}),
3976        )
3977        .expect("audit");
3978        assert_eq!(audit["v"], json!(1));
3979        assert_eq!(audit["fromVersion"], json!(1));
3980        assert_eq!(audit["toVersion"], json!(2));
3981        assert_eq!(audit["pending"], json!(1));
3982        assert_eq!(audit["encodable"], json!(1));
3983        assert_eq!(audit["incompatible"], json!([]));
3984        assert!(audit.get("operations").is_none());
3985
3986        // The executable downgrade step, idempotent.
3987        let discarded = dispatch(
3988            &mut transport,
3989            &mut client,
3990            &mut effects,
3991            "previousVersionDiscard",
3992            &json!({}),
3993        )
3994        .expect("discard");
3995        assert_eq!(discarded, json!({ "present": true, "discarded": true }));
3996        assert!(!std::path::Path::new(&container_path(&path)).exists());
3997        let again = dispatch(
3998            &mut transport,
3999            &mut client,
4000            &mut effects,
4001            "previousVersionDiscard",
4002            &json!({}),
4003        )
4004        .expect("idempotent discard");
4005        assert_eq!(again, json!({ "present": false, "discarded": false }));
4006
4007        // Storage read directly: both metadata records are gone.
4008        let inspect = rusqlite::Connection::open(&path).expect("inspect replica");
4009        let remaining: i64 = inspect
4010            .query_row(
4011                "SELECT COUNT(*) FROM _syncular_meta WHERE key IN (?1, ?2)",
4012                rusqlite::params!["previousVersionContext", "previousVersionAudit"],
4013                |row| row.get(0),
4014            )
4015            .expect("count meta");
4016        assert_eq!(remaining, 0);
4017
4018        let _ = std::fs::remove_file(&path);
4019    }
4020
4021    #[test]
4022    fn previous_version_ttl_expires_at_read_through_the_dispatcher() {
4023        let path = temp_db_path("previous-version-ttl");
4024        let mut transport = NoNetwork::default();
4025        let mut client: Option<SyncClient> = None;
4026        let mut effects = CreateEffects::default();
4027        dispatch(
4028            &mut transport,
4029            &mut client,
4030            &mut effects,
4031            "create",
4032            &json!({
4033                "schema": schema(),
4034                "dbPath": path,
4035                "previousVersionContext": previous_version_enabled()
4036            }),
4037        )
4038        .expect("create v1");
4039        dispatch(
4040            &mut transport,
4041            &mut client,
4042            &mut effects,
4043            "shutdown",
4044            &json!({}),
4045        )
4046        .expect("shutdown");
4047
4048        // The injected clock is two seconds past the capture, with a TTL far
4049        // larger than the boot gap but far smaller than the skew, so the boot
4050        // reconcile keeps the container and the read expires it.
4051        let now_ms = std::time::SystemTime::now()
4052            .duration_since(std::time::UNIX_EPOCH)
4053            .expect("clock")
4054            .as_millis() as i64
4055            + 2_000;
4056        dispatch(
4057            &mut transport,
4058            &mut client,
4059            &mut effects,
4060            "create",
4061            &json!({
4062                "schema": schema_v2(),
4063                "dbPath": path,
4064                "nowMs": now_ms,
4065                "previousVersionContext": { "enabled": true, "maxAgeMs": 500 }
4066            }),
4067        )
4068        .expect("create v2");
4069        assert!(std::path::Path::new(&container_path(&path)).exists());
4070        let snapshot = dispatch(
4071            &mut transport,
4072            &mut client,
4073            &mut effects,
4074            "previousVersionSnapshot",
4075            &json!({ "table": "todos" }),
4076        )
4077        .expect("snapshot");
4078        assert_eq!(snapshot["available"], json!(false));
4079        assert_eq!(snapshot["reason"], json!("expired"));
4080        assert_eq!(snapshot["rows"], json!([]));
4081        // The TTL discards, and the FILE is what must be gone.
4082        assert!(!std::path::Path::new(&container_path(&path)).exists());
4083
4084        let _ = std::fs::remove_file(&path);
4085    }
4086
4087    #[test]
4088    fn presence_event_carries_the_fanout_scope_and_the_publish_refusal() {
4089        assert_eq!(
4090            super::presence_event(
4091                r#"{"event":"presence","data":{"scopeKey":"room:42","kind":"leave","actorId":"a","clientId":"c","doc":null,"timestamp":1}}"#
4092            ),
4093            Some(json!({ "type": "presence", "scopeKey": "room:42" }))
4094        );
4095        for code in ["presence.too_large", "presence.forbidden"] {
4096            let frame = format!(
4097                r#"{{"event":"presence","data":{{"scopeKey":"room:42","error":"{code}"}}}}"#
4098            );
4099            assert_eq!(
4100                super::presence_event(&frame),
4101                Some(json!({ "type": "presence", "scopeKey": "room:42", "error": code }))
4102            );
4103        }
4104    }
4105
4106    #[test]
4107    fn presence_event_ignores_malformed_frames_and_unknown_codes() {
4108        for frame in [
4109            r#"{"event":"presence","data":{}}"#,
4110            r#"{"event":"presence","data":{"scopeKey":"room:42","error":"presence.nope"}}"#,
4111            r#"{"event":"presence","data":{"scopeKey":"room:42","error":7}}"#,
4112            r#"{"event":"sync","data":{}}"#,
4113            "not json",
4114        ] {
4115            assert_eq!(super::presence_event(frame), None, "{frame}");
4116        }
4117    }
4118}