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(client_err)?,
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(client_err)?;
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            "client.schema_downgrade: persisted local schema is newer than the requested schema"
2208        );
2209        dispatch(
2210            &mut transport,
2211            &mut client,
2212            &mut effects,
2213            "shutdown",
2214            &json!({}),
2215        )
2216        .expect("shutdown");
2217        let error = dispatch(
2218            &mut transport,
2219            &mut client,
2220            &mut effects,
2221            "create",
2222            &json!({ "schema": older, "dbPath": path }),
2223        )
2224        .expect_err("refuse open");
2225        assert_eq!(error.code, "client.schema_downgrade");
2226        assert!(client.is_none());
2227        dispatch(
2228            &mut transport,
2229            &mut client,
2230            &mut effects,
2231            "create",
2232            &json!({ "schema": newer, "dbPath": path }),
2233        )
2234        .expect("compatible reopen");
2235        dispatch(
2236            &mut transport,
2237            &mut client,
2238            &mut effects,
2239            "shutdown",
2240            &json!({}),
2241        )
2242        .expect("shutdown");
2243        let _ = std::fs::remove_file(path);
2244    }
2245
2246    #[test]
2247    fn native_command_realtime_policy_rides_create_and_refuses_http() {
2248        let mut transport = NoNetwork::default();
2249        let mut client: Option<SyncClient> = None;
2250        let mut effects = CreateEffects::default();
2251        dispatch(
2252            &mut transport,
2253            &mut client,
2254            &mut effects,
2255            "create",
2256            &json!({ "schema": schema(), "realtimePolicy": "required" }),
2257        )
2258        .expect("create client with a required realtime policy");
2259        let result = dispatch(
2260            &mut transport,
2261            &mut client,
2262            &mut effects,
2263            "sync",
2264            &json!({}),
2265        )
2266        .expect("sync command");
2267        assert_eq!(result["ok"], json!(false));
2268        assert_eq!(result["errorCode"], json!("sync.realtime_unavailable"));
2269        assert_eq!(result["realtimeState"], json!("disconnected"));
2270        assert_eq!(result["retryDelayMs"], json!(250));
2271        let snapshot = dispatch(
2272            &mut transport,
2273            &mut client,
2274            &mut effects,
2275            "diagnosticsSnapshot",
2276            &json!({}),
2277        )
2278        .expect("diagnostics command");
2279        assert_eq!(snapshot["host"]["realtime"], json!("disconnected"));
2280        assert_eq!(snapshot["host"]["realtimePolicy"], json!("required"));
2281        assert_eq!(snapshot["host"]["realtimeRetryDelayMs"], json!(250));
2282
2283        let mut second: Option<SyncClient> = None;
2284        let error = dispatch(
2285            &mut transport,
2286            &mut second,
2287            &mut effects,
2288            "create",
2289            &json!({ "schema": schema(), "realtimePolicy": "always" }),
2290        )
2291        .expect_err("an unknown policy is refused");
2292        assert_eq!(error.code, "sync.invalid_request");
2293    }
2294
2295    #[test]
2296    fn parses_portable_encryption_keyring_and_key_id_columns() {
2297        let key_hex = "2a".repeat(32);
2298        let config = parse_encryption(&json!({
2299            "keys": { "practice-key-v1": { "$bytes": key_hex } },
2300            "keyIdColumns": { "patients": "encryption_key_id" }
2301        }))
2302        .expect("portable keyring parses");
2303        assert_eq!(config.keys["practice-key-v1"], vec![0x2a; 32]);
2304        assert_eq!(config.key_id_columns["patients"], "encryption_key_id");
2305    }
2306
2307    #[test]
2308    fn rejects_non_string_key_id_columns() {
2309        let error = parse_encryption(&json!({
2310            "keys": {},
2311            "keyIdColumns": { "patients": 7 }
2312        }))
2313        .expect_err("invalid selector must fail");
2314        assert!(error.contains("must be a string"), "{error}");
2315    }
2316
2317    #[test]
2318    fn subscribe_many_registers_every_unit() {
2319        let mut transport = NoNetwork::default();
2320        let mut client: Option<SyncClient> = None;
2321        let mut effects = CreateEffects::default();
2322        let mut run = |command: &str, params: Value| {
2323            dispatch(&mut transport, &mut client, &mut effects, command, &params)
2324        };
2325        run("create", json!({ "schema": schema() })).expect("create client");
2326        let ids = run(
2327            "subscribeMany",
2328            json!({ "units": [{ "list_id": "list-1" }, { "list_id": "list-2" }] }),
2329        )
2330        .expect("register units")["ids"]
2331            .clone();
2332        let single = run("subscribe", json!({ "scopes": { "list_id": "list-1" } }))
2333            .expect("re-register a unit");
2334        assert_eq!(single["id"], ids[0], "a unit id derives from its scope map");
2335        let units = run("units", json!({})).expect("units");
2336        assert_eq!(units["units"].as_array().map(Vec::len), Some(2));
2337        for (index, list) in ["list-1", "list-2"].into_iter().enumerate() {
2338            let unit = run("unit", json!({ "id": ids[index] })).expect("unit");
2339            assert_eq!(unit["unit"]["scopes"], json!({ "list_id": list }));
2340            assert_eq!(unit["unit"]["cursor"], -1);
2341        }
2342        assert_eq!(
2343            run("unit", json!({ "id": "absent" })).expect("unit")["unit"],
2344            Value::Null
2345        );
2346        for scopes in [json!({ "list_id": "*" }), json!({ "other": "x" })] {
2347            let error = run("subscribe", json!({ "scopes": scopes }))
2348                .expect_err("a unit names a non-wildcard value per covered variable");
2349            assert_eq!(error.code, "sync.invalid_subscription", "{scopes}");
2350        }
2351    }
2352
2353    #[test]
2354    fn authority_reads_parse_at_create_and_run_through_authority_read() {
2355        let mut transport = NoNetwork::default();
2356        let mut client: Option<SyncClient> = None;
2357        let mut effects = CreateEffects::default();
2358        let query = json!({
2359            "name": "listOf",
2360            "sql": "SELECT id FROM todos WHERE list_id = ?",
2361            "bind": ["listId"],
2362            "params": [{"name": "listId", "type": "string", "nullable": false}],
2363            "coverage": [{"table": "todos", "variable": "list_id", "units": ["listId"]}],
2364            "reads": {"todos": ["id", "list_id"]},
2365            "resultColumns": [{"name": "id", "type": "string", "nullable": false}]
2366        });
2367        let mut create = |client: &mut Option<SyncClient>,
2368                          effects: &mut CreateEffects,
2369                          reads: Value| {
2370            dispatch(
2371                &mut transport,
2372                client,
2373                effects,
2374                "create",
2375                &json!({ "schema": schema(), "securityPreflight": true, "authorityReads": reads }),
2376            )
2377        };
2378        for (reads, details) in [
2379            (json!({}), json!({"reason": "shape"})),
2380            (
2381                json!([{"name": "x"}]),
2382                json!({"query": "x", "reason": "shape"}),
2383            ),
2384            (json!([{ "sql": "SELECT 1" }]), json!({"reason": "shape"})),
2385        ] {
2386            let error = create(&mut client, &mut effects, reads).unwrap_err();
2387            assert_eq!(error.code, "client.authority_read_forbidden");
2388            assert_eq!(error.details, Some(details));
2389        }
2390        // A host ceiling refuses the column the statement reads past it.
2391        effects.authority_ceiling = Some([("todos".to_owned(), vec!["id".to_owned()])].into());
2392        let refused = create(&mut client, &mut effects, json!([query])).unwrap_err();
2393        assert_eq!(
2394            refused.details,
2395            Some(
2396                json!({"query": "listOf", "reason": "ceiling", "table": "todos", "column": "list_id"})
2397            )
2398        );
2399        assert!(client.is_none());
2400        effects.authority_ceiling = Some(
2401            [(
2402                "todos".to_owned(),
2403                vec!["id".to_owned(), "list_id".to_owned()],
2404            )]
2405            .into(),
2406        );
2407        create(&mut client, &mut effects, json!([query])).expect("create within the ceiling");
2408        let read = dispatch(
2409            &mut transport,
2410            &mut client,
2411            &mut effects,
2412            "authorityRead",
2413            &json!({ "requests": [{ "query": "listOf", "params": { "listId": "l1" } }] }),
2414        )
2415        .expect("authority read in preflight");
2416        assert!(read["revision"].is_string());
2417        assert_eq!(
2418            read["results"],
2419            json!([{
2420                "query": "listOf",
2421                "rows": [],
2422                "coverage": [{"table": "todos", "base": {"variable": "list_id"}, "unit": "l1", "state": "missing"}],
2423                "complete": false
2424            }])
2425        );
2426        for params in [
2427            json!({}),
2428            json!({ "requests": [], "extra": true }),
2429            json!({ "requests": [{ "query": "listOf" }] }),
2430        ] {
2431            let error = dispatch(
2432                &mut transport,
2433                &mut client,
2434                &mut effects,
2435                "authorityRead",
2436                &params,
2437            )
2438            .unwrap_err();
2439            assert_eq!(
2440                (error.code.as_str(), error.details),
2441                ("client.authority_read_forbidden", None)
2442            );
2443        }
2444    }
2445
2446    #[test]
2447    fn window_coverage_parser_reads_the_generated_descriptor_and_rejects_malformed_units() {
2448        let parsed = parse_window_coverage(Some(&json!([{
2449            "table": "tasks",
2450            "base": { "variable": "project_id", "fixedScopes": { "tenant_id": "one" } },
2451            "units": ["a", "b"]
2452        }])))
2453        .expect("parse coverage");
2454        assert_eq!(parsed[0].base.variable, "project_id");
2455        assert_eq!(
2456            parsed[0].base.fixed_scopes,
2457            UnitScopes::from([("tenant_id".to_owned(), "one".to_owned())])
2458        );
2459        assert_eq!(parsed[0].table, "tasks");
2460        assert_eq!(parsed[0].units, ["a", "b"]);
2461        for coverage in [
2462            json!({}),
2463            json!([{ "table": "tasks", "base": { "variable": "project_id" }, "units": ["a", 1] }]),
2464            json!([{ "table": "tasks", "base": { "fixedScopes": {} }, "units": [] }]),
2465            json!([{ "base": { "variable": "project_id" }, "units": ["a"] }]),
2466            json!([{ "table": 1, "base": { "variable": "project_id" }, "units": ["a"] }]),
2467        ] {
2468            let error = parse_window_coverage(Some(&coverage)).expect_err("malformed coverage");
2469            assert!(error.starts_with("sync.invalid_request: "), "{error}");
2470        }
2471    }
2472
2473    #[test]
2474    fn subscribe_and_unsubscribe_queue_an_interactive_sync_intent() {
2475        let mut transport = NoNetwork::default();
2476        let mut client: Option<SyncClient> = None;
2477        let mut effects = CreateEffects::default();
2478        let mut run = |command: &str, params: Value| {
2479            dispatch(&mut transport, &mut client, &mut effects, command, &params)
2480                .expect("command succeeds")
2481        };
2482        run("create", json!({ "schema": schema() }));
2483        run("drainSyncIntents", json!({}));
2484        let id = run("subscribe", json!({ "scopes": { "list_id": "list-1" } }))["id"].clone();
2485        let intents = run("drainSyncIntents", json!({}));
2486        assert_eq!(intents["intents"], json!([{ "kind": "interactive" }]));
2487        run("unsubscribe", json!({ "id": id }));
2488        let intents = run("drainSyncIntents", json!({}));
2489        assert_eq!(intents["intents"], json!([{ "kind": "interactive" }]));
2490    }
2491
2492    #[test]
2493    fn security_preflight_is_fail_closed_until_exact_activation() {
2494        let mut transport = NoNetwork::default();
2495        let mut client: Option<SyncClient> = None;
2496        let mut effects = CreateEffects::default();
2497        dispatch(
2498            &mut transport,
2499            &mut client,
2500            &mut effects,
2501            "create",
2502            &json!({ "schema": schema(), "securityPreflight": true }),
2503        )
2504        .expect("preflight create");
2505
2506        let lifecycle = dispatch(
2507            &mut transport,
2508            &mut client,
2509            &mut effects,
2510            "securityLifecycle",
2511            &json!({}),
2512        )
2513        .expect("lifecycle");
2514        assert_eq!(lifecycle, json!({ "state": "preflight" }));
2515
2516        let query_error = dispatch(
2517            &mut transport,
2518            &mut client,
2519            &mut effects,
2520            "query",
2521            &json!({ "sql": "SELECT id FROM todos", "params": [] }),
2522        )
2523        .expect_err("protected query must fail");
2524        assert_eq!(query_error.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
2525        let diagnostics_error = dispatch(
2526            &mut transport,
2527            &mut client,
2528            &mut effects,
2529            "diagnosticsSnapshot",
2530            &json!({}),
2531        )
2532        .expect_err("diagnostics unit evidence remains protected");
2533        assert_eq!(diagnostics_error.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
2534
2535        dispatch(
2536            &mut transport,
2537            &mut client,
2538            &mut effects,
2539            "purgeLocalData",
2540            &json!({
2541                "input": {
2542                    "purgeId": "directive-1",
2543                    "targets": [{
2544                        "table": "todos",
2545                        "selectors": { "list_id": ["list-1"] }
2546                    }]
2547                }
2548            }),
2549        )
2550        .expect("authorized local purge remains available");
2551
2552        let repair_error = dispatch(
2553            &mut transport,
2554            &mut client,
2555            &mut effects,
2556            "rebootstrapLocalData",
2557            &json!({ "input": { "rebootstrapId": "blocked-repair" } }),
2558        )
2559        .expect_err("projection repair must remain protected during preflight");
2560        assert_eq!(repair_error.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
2561
2562        dispatch(
2563            &mut transport,
2564            &mut client,
2565            &mut effects,
2566            "activateSecurity",
2567            &json!({}),
2568        )
2569        .expect("activation");
2570        let rows = dispatch(
2571            &mut transport,
2572            &mut client,
2573            &mut effects,
2574            "query",
2575            &json!({ "sql": "SELECT id FROM todos", "params": [] }),
2576        )
2577        .expect("active query");
2578        assert_eq!(rows, json!({ "rows": [] }));
2579
2580        dispatch(
2581            &mut transport,
2582            &mut client,
2583            &mut effects,
2584            "beginSecurityPreflight",
2585            &json!({}),
2586        )
2587        .expect("re-enter preflight");
2588        let blocked = dispatch(
2589            &mut transport,
2590            &mut client,
2591            &mut effects,
2592            "mutate",
2593            &json!({ "mutations": [] }),
2594        )
2595        .expect_err("mutation must be gated");
2596        assert_eq!(blocked.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
2597        let blocked = dispatch(
2598            &mut transport,
2599            &mut client,
2600            &mut effects,
2601            "replacePendingCommit",
2602            &json!({ "clientCommitId": "a", "operations": [], "replacementClientCommitId": "b" }),
2603        )
2604        .expect_err("a pending-commit replacement must be gated");
2605        assert_eq!(blocked.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
2606    }
2607
2608    #[test]
2609    fn replace_pending_commit_replaces_a_never_sent_commit_without_transport() {
2610        let schema = json!({
2611            "version": 1,
2612            "tables": [{
2613                "name": "todos",
2614                "columns": [
2615                    { "name": "id", "type": "string", "nullable": false },
2616                    { "name": "title", "type": "string", "nullable": false }
2617                ],
2618                "primaryKey": "id",
2619                "scopes": []
2620            }]
2621        });
2622        let mut transport = NoNetwork::default();
2623        let mut client: Option<SyncClient> = None;
2624        let mut effects = CreateEffects::default();
2625        let mut call = |method: &str, params: Value| {
2626            dispatch(&mut transport, &mut client, &mut effects, method, &params)
2627        };
2628        call("create", json!({ "schema": schema })).expect("create");
2629        let operations = json!([{
2630            "op": "upsert", "table": "todos", "values": { "id": "t1", "title": "first" }
2631        }]);
2632        let original = call("mutate", json!({ "mutations": operations })).expect("mutate")
2633            ["clientCommitId"]
2634            .clone();
2635        for (params, code) in [
2636            (
2637                json!({ "operations": [], "replacementClientCommitId": "r" }),
2638                "sync.invalid_request",
2639            ),
2640            (
2641                json!({ "clientCommitId": original, "operations": [] }),
2642                "sync.invalid_request",
2643            ),
2644            (
2645                json!({ "clientCommitId": "none", "operations": [], "replacementClientCommitId": "r" }),
2646                "sync.outcome_not_found",
2647            ),
2648        ] {
2649            let error = call("replacePendingCommit", params.clone()).expect_err("refused");
2650            assert_eq!(error.code, code, "{params}");
2651        }
2652        let replace = json!({
2653            "clientCommitId": original,
2654            "operations": [{
2655                "op": "upsert", "table": "todos", "values": { "id": "t1", "title": "second" }
2656            }],
2657            "replacementClientCommitId": "replacement-1"
2658        });
2659        for _ in 0..2 {
2660            let replaced = call("replacePendingCommit", replace.clone()).expect("replaced");
2661            assert_eq!(replaced["clientCommitId"], "replacement-1");
2662        }
2663        let pending = call("pendingCommitIds", Value::Null).expect("pending");
2664        assert_eq!(pending["ids"], json!(["replacement-1"]));
2665        let rows = call(
2666            "query",
2667            json!({ "sql": "SELECT title FROM todos", "params": [] }),
2668        )
2669        .expect("query");
2670        assert_eq!(rows["rows"][0]["title"], "second");
2671        let delivery =
2672            call("commitDelivery", json!({ "clientCommitId": original })).expect("delivery");
2673        assert_eq!(delivery["outcome"]["status"], "replaced", "{delivery}");
2674        assert_eq!(
2675            delivery["outcome"]["replacementClientCommitId"],
2676            "replacement-1"
2677        );
2678    }
2679
2680    #[test]
2681    fn replace_commit_outcome_forwards_typed_failures() {
2682        let schema = json!({
2683            "version": 1,
2684            "tables": [{
2685                "name": "todos",
2686                "columns": [{ "name": "id", "type": "string", "nullable": false }],
2687                "primaryKey": "id",
2688                "scopes": []
2689            }]
2690        });
2691        let mut transport = NoNetwork::default();
2692        let mut client: Option<SyncClient> = None;
2693        let mut effects = CreateEffects::default();
2694        dispatch(
2695            &mut transport,
2696            &mut client,
2697            &mut effects,
2698            "create",
2699            &json!({ "schema": schema }),
2700        )
2701        .expect("create");
2702        for (params, code) in [
2703            (json!({ "sequence": 1 }), "sync.invalid_request"),
2704            (json!({ "clientCommitId": "none" }), "sync.invalid_request"),
2705            (
2706                json!({ "clientCommitId": "none", "sequence": 1, "replacement": [] }),
2707                "sync.outcome_not_found",
2708            ),
2709        ] {
2710            let error = dispatch(
2711                &mut transport,
2712                &mut client,
2713                &mut effects,
2714                "replaceCommitOutcome",
2715                &params,
2716            )
2717            .expect_err("refused");
2718            assert_eq!(error.code, code, "{params}");
2719        }
2720    }
2721
2722    #[test]
2723    fn mutate_and_patch_forward_typed_storage_failures() {
2724        let path = temp_db_path("busy-authoring");
2725        let schema = json!({
2726            "version": 1,
2727            "tables": [{
2728                "name": "todos",
2729                "columns": [
2730                    { "name": "id", "type": "string", "nullable": false },
2731                    { "name": "list_id", "type": "string", "nullable": false },
2732                    { "name": "title", "type": "string", "nullable": false }
2733                ],
2734                "primaryKey": "id",
2735                "scopes": [{ "pattern": "list:{list_id}", "column": "list_id" }]
2736            }]
2737        });
2738        let mut transport = NoNetwork::default();
2739        let mut client: Option<SyncClient> = None;
2740        let mut effects = CreateEffects::default();
2741        dispatch(
2742            &mut transport,
2743            &mut client,
2744            &mut effects,
2745            "create",
2746            &json!({ "schema": schema, "dbPath": path }),
2747        )
2748        .expect("create file-backed client");
2749        let upsert = |id: &str| {
2750            json!({ "mutations": [{ "op": "upsert", "table": "todos", "values": {
2751                "id": id, "list_id": "l1", "title": "first" } }] })
2752        };
2753        dispatch(
2754            &mut transport,
2755            &mut client,
2756            &mut effects,
2757            "mutate",
2758            &upsert("t1"),
2759        )
2760        .expect("seed row");
2761
2762        let locker = rusqlite::Connection::open(&path).expect("second connection");
2763        locker.execute_batch("BEGIN IMMEDIATE").unwrap();
2764        let busy = dispatch(
2765            &mut transport,
2766            &mut client,
2767            &mut effects,
2768            "mutate",
2769            &upsert("t2"),
2770        )
2771        .expect_err("busy mutate");
2772        assert_eq!(busy.code, "client.storage_busy");
2773        assert!(busy.retryable);
2774        assert_eq!(busy.details.as_ref().unwrap()["sqliteCode"], 5);
2775
2776        let busy_patch = dispatch(
2777            &mut transport,
2778            &mut client,
2779            &mut effects,
2780            "patch",
2781            &json!({ "table": "todos", "rowId": "t1", "partial": { "title": "second" } }),
2782        )
2783        .expect_err("busy patch");
2784        assert_eq!(busy_patch.code, "client.storage_busy");
2785        assert!(busy_patch.retryable);
2786        assert_eq!(busy_patch.details.as_ref().unwrap()["sqliteCode"], 5);
2787
2788        locker.execute_batch("ROLLBACK").unwrap();
2789        let retried = dispatch(
2790            &mut transport,
2791            &mut client,
2792            &mut effects,
2793            "mutate",
2794            &upsert("t2"),
2795        )
2796        .expect("retry after busy");
2797        assert!(retried.get("clientCommitId").is_some());
2798        let _ = std::fs::remove_file(&path);
2799    }
2800
2801    #[test]
2802    fn read_command_error_preserves_code_details_and_retryability() {
2803        let corrupt = super::read_command_error(syncular_client::QueryReadFailure {
2804            code: Some("sync.local_corrupt"),
2805            sqlite_code: None,
2806            sqlite_message: None,
2807            rollback_failure: None,
2808            message: "persisted local revision is invalid".to_owned(),
2809        });
2810        assert_eq!(corrupt.code, "sync.local_corrupt");
2811        assert!(!corrupt.retryable);
2812        assert!(corrupt.details.is_none());
2813
2814        let busy = super::read_command_error(syncular_client::QueryReadFailure {
2815            code: Some("client.storage_busy"),
2816            sqlite_code: Some(5),
2817            sqlite_message: Some("database is locked".to_owned()),
2818            rollback_failure: None,
2819            message: "local SQLite storage is busy".to_owned(),
2820        });
2821        assert_eq!(busy.code, "client.storage_busy");
2822        assert!(busy.retryable);
2823        assert_eq!(
2824            busy.details.expect("busy details")["sqliteCode"],
2825            serde_json::json!(5)
2826        );
2827    }
2828
2829    #[test]
2830    fn mutate_and_patch_report_caller_value_failures_as_invalid_request() {
2831        let path = temp_db_path("caller-values");
2832        let schema = json!({
2833            "version": 1,
2834            "tables": [{
2835                "name": "todos",
2836                "columns": [
2837                    { "name": "id", "type": "string", "nullable": false },
2838                    { "name": "list_id", "type": "string", "nullable": false },
2839                    { "name": "title", "type": "string", "nullable": false },
2840                    { "name": "priority", "type": "integer", "nullable": false }
2841                ],
2842                "primaryKey": "id",
2843                "scopes": [{ "pattern": "list:{list_id}", "column": "list_id" }]
2844            }]
2845        });
2846        let mut transport = NoNetwork::default();
2847        let mut client: Option<SyncClient> = None;
2848        let mut effects = CreateEffects::default();
2849        dispatch(
2850            &mut transport,
2851            &mut client,
2852            &mut effects,
2853            "create",
2854            &json!({ "schema": schema, "dbPath": path }),
2855        )
2856        .expect("create file-backed client");
2857        let seed = dispatch(
2858            &mut transport,
2859            &mut client,
2860            &mut effects,
2861            "mutate",
2862            &json!({ "mutations": [{ "op": "upsert", "table": "todos", "values": {
2863                "id": "t1", "list_id": "l1", "title": "first", "priority": 1 } }] }),
2864        )
2865        .expect("seed row");
2866        let seed_id = seed["clientCommitId"].clone();
2867
2868        // §6.1/§7.1: a caller value the authoring seam rejects is an invalid
2869        // request, not the internal-failure default.
2870        let unknown = dispatch(
2871            &mut transport,
2872            &mut client,
2873            &mut effects,
2874            "mutate",
2875            &json!({ "mutations": [{ "op": "upsert", "table": "todos", "values": {
2876                "id": "t2", "list_id": "l1", "title": "second", "priority": 1,
2877                "missing_column": 1 } }] }),
2878        )
2879        .expect_err("unknown column");
2880        assert_eq!(unknown.code, "sync.invalid_request");
2881        assert_eq!(unknown.message, "the authoring request is invalid");
2882        assert!(!unknown.retryable);
2883        assert!(unknown.details.as_ref().unwrap()["legacyCause"]
2884            .as_str()
2885            .unwrap()
2886            .contains("unknown column"));
2887
2888        let bad_patch = dispatch(
2889            &mut transport,
2890            &mut client,
2891            &mut effects,
2892            "patch",
2893            &json!({ "table": "todos", "rowId": "t1", "partial": { "priority": "high" } }),
2894        )
2895        .expect_err("bad patch value");
2896        assert_eq!(bad_patch.code, "sync.invalid_request");
2897        assert_eq!(bad_patch.message, "the authoring request is invalid");
2898        assert!(bad_patch.details.as_ref().unwrap()["legacyCause"]
2899            .as_str()
2900            .unwrap()
2901            .contains("priority"));
2902
2903        // Neither rejection enqueued a commit or touched the projection.
2904        let pending = dispatch(
2905            &mut transport,
2906            &mut client,
2907            &mut effects,
2908            "pendingCommitIds",
2909            &json!({}),
2910        )
2911        .expect("pending commit ids");
2912        assert_eq!(pending["ids"], json!([seed_id]));
2913        let rows = dispatch(
2914            &mut transport,
2915            &mut client,
2916            &mut effects,
2917            "query",
2918            &json!({ "sql": "SELECT id, priority FROM todos ORDER BY id" }),
2919        )
2920        .expect("visible rows");
2921        assert_eq!(rows["rows"], json!([{ "id": "t1", "priority": 1 }]));
2922
2923        // The next valid call authorizes normally.
2924        let accepted = dispatch(
2925            &mut transport,
2926            &mut client,
2927            &mut effects,
2928            "mutate",
2929            &json!({ "mutations": [{ "op": "upsert", "table": "todos", "values": {
2930                "id": "t2", "list_id": "l1", "title": "second", "priority": 2 } }] }),
2931        )
2932        .expect("retry after rejection");
2933        assert!(accepted.get("clientCommitId").is_some());
2934        let _ = std::fs::remove_file(&path);
2935    }
2936
2937    #[test]
2938    fn client_err_preserves_retryable_for_storage_busy() {
2939        let busy = client_err("client.storage_busy: local SQLite storage is busy".to_owned());
2940        assert_eq!(busy.code, "client.storage_busy");
2941        assert!(busy.retryable);
2942        // The legacy boundary keeps the full rendered message.
2943        assert_eq!(
2944            busy.message,
2945            "client.storage_busy: local SQLite storage is busy"
2946        );
2947        let full = client_err("client.storage_full: local SQLite storage is full".to_owned());
2948        assert_eq!(full.code, "client.storage_full");
2949        assert!(!full.retryable);
2950    }
2951
2952    #[test]
2953    fn client_err_keeps_a_colon_less_code_identity() {
2954        let error = client_err("sync.unknown_table".to_owned());
2955        assert_eq!(error.code, "sync.unknown_table");
2956        let error = client_err("no client instance created".to_owned());
2957        assert_eq!(error.code, "client.failed");
2958    }
2959
2960    #[cfg(feature = "crdt-yjs")]
2961    #[test]
2962    fn crdt_offsets_outside_u32_are_invalid_requests() {
2963        let mut transport = NoNetwork::default();
2964        let mut client: Option<SyncClient> = None;
2965        let mut effects = CreateEffects::default();
2966        dispatch(
2967            &mut transport,
2968            &mut client,
2969            &mut effects,
2970            "create",
2971            &json!({ "schema": schema() }),
2972        )
2973        .expect("create");
2974        let target = json!({ "table": "todos", "rowId": "t1", "column": "body" });
2975        for (method, extra) in [
2976            (
2977                "crdtInsertText",
2978                json!({ "index": 4_294_967_296u64, "value": "x" }),
2979            ),
2980            ("crdtInsertText", json!({ "index": "0", "value": "x" })),
2981            (
2982                "crdtDeleteText",
2983                json!({ "index": 0, "len": 4_294_967_296u64 }),
2984            ),
2985        ] {
2986            let mut params = target.clone();
2987            params
2988                .as_object_mut()
2989                .unwrap()
2990                .extend(extra.as_object().unwrap().clone());
2991            let error = dispatch(&mut transport, &mut client, &mut effects, method, &params)
2992                .expect_err("out-of-range offset");
2993            assert_eq!(error.code, "sync.invalid_request", "{method} {params}");
2994        }
2995    }
2996
2997    #[test]
2998    fn wrong_typed_optional_fields_are_invalid_requests() {
2999        let created = || {
3000            let mut transport = NoNetwork::default();
3001            let mut client: Option<SyncClient> = None;
3002            let mut effects = CreateEffects::default();
3003            dispatch(
3004                &mut transport,
3005                &mut client,
3006                &mut effects,
3007                "create",
3008                &json!({ "schema": schema() }),
3009            )
3010            .expect("create");
3011            (transport, client, effects)
3012        };
3013        for params in [
3014            json!({ "schema": schema(), "limits": "x" }),
3015            json!({ "schema": schema(), "limits": { "accept": 256 } }),
3016            json!({ "schema": schema(), "limits": { "accept": "15" } }),
3017            json!({ "schema": schema(), "limits": { "limitCommits": 4_294_967_296i64 } }),
3018            json!({ "schema": schema(), "limits": { "outcomeRetentionMaxEntries": -1 } }),
3019            json!({ "schema": schema(), "clientId": 7 }),
3020            json!({ "schema": schema(), "nowMs": "1" }),
3021            json!({ "schema": schema(), "signedUrls": "true" }),
3022            json!({ "schema": schema(), "securityPreflight": 1 }),
3023            json!({ "schema": schema(), "encryption": { "keys": "k" } }),
3024        ] {
3025            let mut transport = NoNetwork::default();
3026            let mut client: Option<SyncClient> = None;
3027            let mut effects = CreateEffects::default();
3028            let error = dispatch(&mut transport, &mut client, &mut effects, "create", &params)
3029                .expect_err("wrong-typed create field");
3030            assert_eq!(error.code, "sync.invalid_request", "{params}");
3031        }
3032        let base = json!({ "variable": "list_id" });
3033        for (method, params) in [
3034            ("setWindow", json!({ "base": base, "units": [1] })),
3035            ("setWindow", json!({ "base": base, "units": "l1" })),
3036            (
3037                "setWindow",
3038                json!({ "base": { "variable": "list_id", "fixedScopes": ["x"] }, "units": [] }),
3039            ),
3040            ("windowState", json!({ "base": {} })),
3041            (
3042                "mutate",
3043                json!({ "mutations": [{ "op": "delete", "table": "todos", "rowId": "t1", "baseVersion": "7" }] }),
3044            ),
3045            (
3046                "patch",
3047                json!({ "table": "todos", "rowId": "t1", "partial": { "title": "x" }, "baseVersion": "7" }),
3048            ),
3049            ("subscribe", json!({ "scopes": { "list_id": ["l1"] } })),
3050            (
3051                "subscribeMany",
3052                json!({ "units": [{ "list_id": "l1" }, 7] }),
3053            ),
3054            (
3055                "uploadBlob",
3056                json!({ "bytes": { "$bytes": "00" }, "mediaType": 1 }),
3057            ),
3058        ] {
3059            let (mut transport, mut client, mut effects) = created();
3060            let error = dispatch(&mut transport, &mut client, &mut effects, method, &params)
3061                .expect_err("wrong-typed field");
3062            assert_eq!(error.code, "sync.invalid_request", "{method} {params}");
3063        }
3064        // An absent or null optional field keeps its default.
3065        let (mut transport, mut client, mut effects) = created();
3066        dispatch(
3067            &mut transport,
3068            &mut client,
3069            &mut effects,
3070            "mutate",
3071            &json!({ "mutations": [{ "op": "delete", "table": "todos", "rowId": "t1", "baseVersion": null }] }),
3072        )
3073        .expect("null baseVersion is absent");
3074    }
3075
3076    #[test]
3077    fn sync_until_idle_rejects_an_invalid_max_rounds_budget() {
3078        for value in [json!(0), json!(-1), json!(1.5), json!(4_294_967_296u64)] {
3079            let mut transport = NoNetwork::default();
3080            let mut client: Option<SyncClient> = None;
3081            let mut effects = CreateEffects::default();
3082            dispatch(
3083                &mut transport,
3084                &mut client,
3085                &mut effects,
3086                "create",
3087                &json!({ "schema": schema() }),
3088            )
3089            .expect("create");
3090            let error = dispatch(
3091                &mut transport,
3092                &mut client,
3093                &mut effects,
3094                "syncUntilIdle",
3095                &json!({ "maxRounds": value }),
3096            )
3097            .expect_err("invalid budget");
3098            assert_eq!(error.code, "sync.invalid_request", "{value}");
3099        }
3100    }
3101
3102    #[test]
3103    fn sync_until_idle_rejects_an_invalid_timeout() {
3104        for value in [json!(0), json!(-1), json!(1.5)] {
3105            let mut transport = NoNetwork::default();
3106            let mut client: Option<SyncClient> = None;
3107            let mut effects = CreateEffects::default();
3108            dispatch(
3109                &mut transport,
3110                &mut client,
3111                &mut effects,
3112                "create",
3113                &json!({ "schema": schema() }),
3114            )
3115            .expect("create");
3116            let error = dispatch(
3117                &mut transport,
3118                &mut client,
3119                &mut effects,
3120                "syncUntilIdle",
3121                &json!({ "timeoutMs": value }),
3122            )
3123            .expect_err("invalid timeout");
3124            assert_eq!(error.code, "sync.invalid_request", "{value}");
3125        }
3126    }
3127
3128    #[test]
3129    fn create_rejects_invalid_push_limits() {
3130        for value in [json!(0), json!(-1), json!(1.5), json!(4_294_967_296u64)] {
3131            let mut transport = NoNetwork::default();
3132            let mut client: Option<SyncClient> = None;
3133            let mut effects = CreateEffects::default();
3134            let error = dispatch(
3135                &mut transport,
3136                &mut client,
3137                &mut effects,
3138                "create",
3139                &json!({
3140                    "schema": schema(),
3141                    "limits": { "maxPushRequestBytes": value }
3142                }),
3143            )
3144            .expect_err("invalid push limit");
3145            assert_eq!(error.code, "sync.invalid_request", "{value}");
3146            assert_eq!(
3147                error.details.as_ref().unwrap()["limit"],
3148                json!("maxPushRequestBytes")
3149            );
3150        }
3151    }
3152
3153    #[test]
3154    fn preflight_allows_only_the_authorized_previous_version_discard() {
3155        let mut transport = NoNetwork::default();
3156        let mut client: Option<SyncClient> = None;
3157        let mut effects = CreateEffects::default();
3158        dispatch(
3159            &mut transport,
3160            &mut client,
3161            &mut effects,
3162            "create",
3163            &json!({ "schema": schema(), "securityPreflight": true }),
3164        )
3165        .expect("preflight create");
3166
3167        // Reads and the audit observe protected local data: still gated.
3168        for method in ["previousVersionSnapshot", "previousVersionAudit"] {
3169            let error = dispatch(
3170                &mut transport,
3171                &mut client,
3172                &mut effects,
3173                method,
3174                &json!({}),
3175            )
3176            .expect_err("previous-version reads stay gated during preflight");
3177            assert_eq!(error.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
3178        }
3179        // RFC 0006 runs the discard consumer inside the quiesced window, so the
3180        // command router must permit it (feature off here: a clean no-op).
3181        let discarded = dispatch(
3182            &mut transport,
3183            &mut client,
3184            &mut effects,
3185            "previousVersionDiscard",
3186            &json!({}),
3187        )
3188        .expect("authorized cleanup is allowed during preflight");
3189        assert_eq!(discarded, json!({ "present": false, "discarded": false }));
3190        // Preflight closed the socket; releasing it again is allowed.
3191        dispatch(
3192            &mut transport,
3193            &mut client,
3194            &mut effects,
3195            "disconnectRealtime",
3196            &json!({}),
3197        )
3198        .expect("disconnect is allowed during preflight");
3199        assert!(client.as_ref().is_some_and(SyncClient::security_preflight));
3200    }
3201
3202    #[test]
3203    fn disconnect_without_a_client_succeeds() {
3204        let mut transport = NoNetwork::default();
3205        let mut client: Option<SyncClient> = None;
3206        let mut effects = CreateEffects::default();
3207        dispatch(
3208            &mut transport,
3209            &mut client,
3210            &mut effects,
3211            "disconnectRealtime",
3212            &json!({}),
3213        )
3214        .expect("a missing client holds no socket");
3215        dispatch(
3216            &mut transport,
3217            &mut client,
3218            &mut effects,
3219            "create",
3220            &json!({ "schema": schema() }),
3221        )
3222        .expect("create");
3223        dispatch(
3224            &mut transport,
3225            &mut client,
3226            &mut effects,
3227            "shutdown",
3228            &json!({}),
3229        )
3230        .expect("shutdown");
3231        dispatch(
3232            &mut transport,
3233            &mut client,
3234            &mut effects,
3235            "disconnectRealtime",
3236            &json!({}),
3237        )
3238        .expect("a shut-down client holds no socket");
3239    }
3240
3241    #[test]
3242    fn preflight_refuses_a_replacement_create_without_the_flag() {
3243        let mut transport = NoNetwork::default();
3244        let mut client: Option<SyncClient> = None;
3245        let mut effects = CreateEffects::default();
3246        dispatch(
3247            &mut transport,
3248            &mut client,
3249            &mut effects,
3250            "create",
3251            &json!({ "schema": schema(), "securityPreflight": true }),
3252        )
3253        .expect("preflight create");
3254
3255        // The escape the gate exists to prevent: a plain re-create must fail.
3256        let escape = dispatch(
3257            &mut transport,
3258            &mut client,
3259            &mut effects,
3260            "create",
3261            &json!({ "schema": schema() }),
3262        )
3263        .expect_err("plain create must be refused during preflight");
3264        assert_eq!(escape.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
3265        // The refused create left the preflighted client installed and gated.
3266        let query_error = dispatch(
3267            &mut transport,
3268            &mut client,
3269            &mut effects,
3270            "query",
3271            &json!({ "sql": "SELECT id FROM todos", "params": [] }),
3272        )
3273        .expect_err("protected query stays gated");
3274        assert_eq!(query_error.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
3275
3276        // A preflighted replacement is permitted and stays gated.
3277        dispatch(
3278            &mut transport,
3279            &mut client,
3280            &mut effects,
3281            "create",
3282            &json!({ "schema": schema(), "securityPreflight": true }),
3283        )
3284        .expect("preflighted replacement create");
3285        let still_gated = dispatch(
3286            &mut transport,
3287            &mut client,
3288            &mut effects,
3289            "query",
3290            &json!({ "sql": "SELECT id FROM todos", "params": [] }),
3291        )
3292        .expect_err("replacement stays gated");
3293        assert_eq!(still_gated.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
3294
3295        // A legitimate activation releases the gate; creates behave as today.
3296        dispatch(
3297            &mut transport,
3298            &mut client,
3299            &mut effects,
3300            "activateSecurity",
3301            &json!({}),
3302        )
3303        .expect("activation");
3304        dispatch(
3305            &mut transport,
3306            &mut client,
3307            &mut effects,
3308            "create",
3309            &json!({ "schema": schema() }),
3310        )
3311        .expect("plain create after activation");
3312        let rows = dispatch(
3313            &mut transport,
3314            &mut client,
3315            &mut effects,
3316            "query",
3317            &json!({ "sql": "SELECT id FROM todos", "params": [] }),
3318        )
3319        .expect("active query");
3320        assert_eq!(rows, json!({ "rows": [] }));
3321    }
3322
3323    /// A file-backed replica: the persisted quarantine marker only exists here,
3324    /// which is why the in-memory tests above could not catch this.
3325    fn temp_db_path(tag: &str) -> String {
3326        std::env::temp_dir()
3327            .join(format!(
3328                "syncular-command-{tag}-{}-{:?}.db",
3329                std::process::id(),
3330                std::time::SystemTime::now()
3331                    .duration_since(std::time::UNIX_EPOCH)
3332                    .expect("clock")
3333                    .as_nanos()
3334            ))
3335            .to_string_lossy()
3336            .into_owned()
3337    }
3338
3339    #[test]
3340    fn an_activated_replica_reopens_plainly_after_shutdown() {
3341        // Shutting an ACTIVATED client down is not a quarantine event. The
3342        // teardown barrier used to call `begin_security_preflight`, which now
3343        // persists the gate, so every cleanly closed replica was marked pending
3344        // and its next plain `create` was refused forever — the reopen path
3345        // restores the flag from the marker and the create guard rejects it.
3346        let path = temp_db_path("activated-reopen");
3347        let mut transport = NoNetwork::default();
3348        let mut client: Option<SyncClient> = None;
3349        let mut effects = CreateEffects::default();
3350
3351        dispatch(
3352            &mut transport,
3353            &mut client,
3354            &mut effects,
3355            "create",
3356            &json!({ "schema": schema(), "securityPreflight": true, "dbPath": path }),
3357        )
3358        .expect("preflight create");
3359        dispatch(
3360            &mut transport,
3361            &mut client,
3362            &mut effects,
3363            "activateSecurity",
3364            &json!({}),
3365        )
3366        .expect("activation clears the gate");
3367        dispatch(
3368            &mut transport,
3369            &mut client,
3370            &mut effects,
3371            "shutdown",
3372            &json!({}),
3373        )
3374        .expect("shutdown after activation");
3375
3376        // The replica is active on disk, so a plain re-create must be admitted.
3377        dispatch(
3378            &mut transport,
3379            &mut client,
3380            &mut effects,
3381            "create",
3382            &json!({ "schema": schema(), "dbPath": path }),
3383        )
3384        .expect("an activated replica must reopen plainly after shutdown");
3385        let state = dispatch(
3386            &mut transport,
3387            &mut client,
3388            &mut effects,
3389            "securityLifecycle",
3390            &json!({}),
3391        )
3392        .expect("lifecycle");
3393        assert_eq!(state, json!({ "state": "active" }));
3394
3395        let _ = std::fs::remove_file(&path);
3396    }
3397
3398    #[test]
3399    fn an_unactivated_replica_stays_quarantined_across_shutdown_on_disk() {
3400        // The other half, and the reason the marker exists: a replica that
3401        // entered preflight and never activated must still refuse a plain
3402        // re-create after shutdown, even on a host that rebuilt its handle and
3403        // carries no in-memory flag.
3404        let path = temp_db_path("quarantined-reopen");
3405        let mut transport = NoNetwork::default();
3406        let mut client: Option<SyncClient> = None;
3407        let mut effects = CreateEffects::default();
3408
3409        dispatch(
3410            &mut transport,
3411            &mut client,
3412            &mut effects,
3413            "create",
3414            &json!({ "schema": schema(), "securityPreflight": true, "dbPath": path }),
3415        )
3416        .expect("preflight create");
3417        dispatch(
3418            &mut transport,
3419            &mut client,
3420            &mut effects,
3421            "shutdown",
3422            &json!({}),
3423        )
3424        .expect("shutdown during preflight");
3425
3426        // A fresh host handle: no in-memory pending flag survives here, so only
3427        // the persisted marker can hold the gate.
3428        let mut rebuilt = CreateEffects::default();
3429        let escape = dispatch(
3430            &mut transport,
3431            &mut client,
3432            &mut rebuilt,
3433            "create",
3434            &json!({ "schema": schema(), "dbPath": path }),
3435        )
3436        .expect_err("a quarantined replica must refuse a plain re-create");
3437        assert_eq!(escape.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
3438
3439        let _ = std::fs::remove_file(&path);
3440    }
3441
3442    #[test]
3443    fn preflight_gate_survives_shutdown_before_replacement_creates() {
3444        let mut transport = NoNetwork::default();
3445        let mut client: Option<SyncClient> = None;
3446        let mut effects = CreateEffects::default();
3447        dispatch(
3448            &mut transport,
3449            &mut client,
3450            &mut effects,
3451            "create",
3452            &json!({ "schema": schema(), "securityPreflight": true }),
3453        )
3454        .expect("preflight create");
3455        dispatch(
3456            &mut transport,
3457            &mut client,
3458            &mut effects,
3459            "shutdown",
3460            &json!({}),
3461        )
3462        .expect("shutdown during preflight");
3463        assert!(client.is_none());
3464
3465        // The pending preflight rides `effects` across the empty client slot.
3466        let escape = dispatch(
3467            &mut transport,
3468            &mut client,
3469            &mut effects,
3470            "create",
3471            &json!({ "schema": schema() }),
3472        )
3473        .expect_err("shutdown + plain create must stay refused");
3474        assert_eq!(escape.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
3475
3476        dispatch(
3477            &mut transport,
3478            &mut client,
3479            &mut effects,
3480            "create",
3481            &json!({ "schema": schema(), "securityPreflight": true }),
3482        )
3483        .expect("preflighted re-create");
3484        dispatch(
3485            &mut transport,
3486            &mut client,
3487            &mut effects,
3488            "activateSecurity",
3489            &json!({}),
3490        )
3491        .expect("activation");
3492
3493        // An ACTIVATED client shut down cleanly may be recreated plainly.
3494        dispatch(
3495            &mut transport,
3496            &mut client,
3497            &mut effects,
3498            "shutdown",
3499            &json!({}),
3500        )
3501        .expect("shutdown after activation");
3502        dispatch(
3503            &mut transport,
3504            &mut client,
3505            &mut effects,
3506            "create",
3507            &json!({ "schema": schema() }),
3508        )
3509        .expect("plain create after an activated shutdown");
3510    }
3511
3512    #[test]
3513    fn activate_security_refuses_headers_and_keeps_the_gate_closed() {
3514        let mut transport = NoNetwork::default();
3515        let mut client: Option<SyncClient> = None;
3516        let mut effects = CreateEffects::default();
3517        dispatch(
3518            &mut transport,
3519            &mut client,
3520            &mut effects,
3521            "create",
3522            &json!({ "schema": schema(), "securityPreflight": true }),
3523        )
3524        .expect("preflight create");
3525
3526        // Activation headers fail loudly and keep the gate closed.
3527        let invalid = dispatch(
3528            &mut transport,
3529            &mut client,
3530            &mut effects,
3531            "activateSecurity",
3532            &json!({ "headers": { "authorization": 7 } }),
3533        )
3534        .expect_err("non-string header must fail");
3535        assert_eq!(invalid.code, "sync.invalid_request");
3536        let lifecycle = dispatch(
3537            &mut transport,
3538            &mut client,
3539            &mut effects,
3540            "securityLifecycle",
3541            &json!({}),
3542        )
3543        .expect("lifecycle");
3544        assert_eq!(lifecycle, json!({ "state": "preflight" }));
3545
3546        // Well-formed headers are refused too: the header source replaced
3547        // them. Activation without them opens the gate.
3548        let refused = dispatch(
3549            &mut transport,
3550            &mut client,
3551            &mut effects,
3552            "activateSecurity",
3553            &json!({ "headers": { "authorization": "Bearer fresh" } }),
3554        )
3555        .expect_err("activation headers are refused");
3556        assert_eq!(refused.code, "sync.invalid_request");
3557        dispatch(
3558            &mut transport,
3559            &mut client,
3560            &mut effects,
3561            "activateSecurity",
3562            &json!({}),
3563        )
3564        .expect("activation");
3565        let lifecycle = dispatch(
3566            &mut transport,
3567            &mut client,
3568            &mut effects,
3569            "securityLifecycle",
3570            &json!({}),
3571        )
3572        .expect("lifecycle");
3573        assert_eq!(lifecycle, json!({ "state": "active" }));
3574    }
3575
3576    #[test]
3577    fn add_encryption_keys_extends_an_active_keyring() {
3578        let mut transport = NoNetwork::default();
3579        let mut client: Option<SyncClient> = None;
3580        let mut effects = CreateEffects::default();
3581        let key = |byte: &str| json!({ "$bytes": byte.repeat(32) });
3582        let closed = dispatch(
3583            &mut transport,
3584            &mut client,
3585            &mut effects,
3586            "addEncryptionKeys",
3587            &json!({ "keys": { "k2": key("2b") } }),
3588        )
3589        .expect_err("no client is open");
3590        assert_eq!(closed.code, "client.closed");
3591        assert_eq!(closed.message, "no client is open");
3592
3593        dispatch(
3594            &mut transport,
3595            &mut client,
3596            &mut effects,
3597            "create",
3598            &json!({ "schema": schema(), "encryption": { "keys": { "k1": key("2a") } } }),
3599        )
3600        .expect("create");
3601        let mut add = |client: &mut Option<SyncClient>, params: Value| {
3602            dispatch(
3603                &mut transport,
3604                client,
3605                &mut effects,
3606                "addEncryptionKeys",
3607                &params,
3608            )
3609        };
3610        assert_eq!(
3611            add(&mut client, json!({ "keys": { "k2": key("2b") } })).expect("add while active"),
3612            json!({})
3613        );
3614        // The installed key answers a conflicting re-add with its id.
3615        let conflict = add(&mut client, json!({ "keys": { "k2": key("2c") } }))
3616            .expect_err("conflicting bytes");
3617        assert_eq!(conflict.code, "sync.invalid_request");
3618        assert_eq!(
3619            conflict.message,
3620            "encryption key id is already held with different key bytes"
3621        );
3622        assert_eq!(conflict.details, Some(json!({ "keyId": "k2" })));
3623        add(&mut client, json!({ "keys": { "k2": key("2b") } })).expect("identical re-add");
3624
3625        let malformed = add(&mut client, json!({ "keys": { "k3": { "$bytes": "zz" } } }))
3626            .expect_err("malformed hex");
3627        assert_eq!(malformed.code, "sync.invalid_request");
3628        assert_eq!(malformed.details, Some(json!({ "keyId": "k3" })));
3629        // Two bad keys: the first in key-id order is named, whatever the input order.
3630        let first = add(
3631            &mut client,
3632            json!({ "keys": { "k9": { "$bytes": "2a2a" }, "k4": { "$bytes": "zz" } } }),
3633        )
3634        .expect_err("two bad keys");
3635        assert_eq!(first.details, Some(json!({ "keyId": "k4" })));
3636        let short = add(
3637            &mut client,
3638            json!({ "keys": { "k3": { "$bytes": "2a2a" } } }),
3639        )
3640        .expect_err("wrong length");
3641        assert_eq!(short.message, "encryption key must be 32 bytes (AES-256)");
3642        assert_eq!(short.details, Some(json!({ "keyId": "k3" })));
3643        for params in [json!({}), json!({ "keys": [] })] {
3644            assert_eq!(
3645                add(&mut client, params).expect_err("keys object").code,
3646                "sync.invalid_request"
3647            );
3648        }
3649
3650        dispatch(
3651            &mut transport,
3652            &mut client,
3653            &mut effects,
3654            "beginSecurityPreflight",
3655            &json!({}),
3656        )
3657        .expect("preflight");
3658        let gated = dispatch(
3659            &mut transport,
3660            &mut client,
3661            &mut effects,
3662            "addEncryptionKeys",
3663            &json!({ "keys": { "k3": key("2d") } }),
3664        )
3665        .expect_err("preflight refuses the addition");
3666        assert_eq!(gated.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
3667    }
3668
3669    fn schema_v2() -> Value {
3670        json!({
3671            "version": 2,
3672            "tables": [{
3673                "name": "todos",
3674                "columns": [
3675                    { "name": "id", "type": "string", "nullable": false },
3676                    { "name": "list_id", "type": "string", "nullable": false },
3677                    { "name": "note", "type": "string", "nullable": true }
3678                ],
3679                "primaryKey": "id",
3680                "scopes": [{ "pattern": "list:{list_id}", "column": "list_id" }]
3681            }]
3682        })
3683    }
3684
3685    fn previous_version_enabled() -> Value {
3686        json!({ "enabled": true })
3687    }
3688
3689    fn container_path(db_path: &str) -> String {
3690        format!("{db_path}.prev-context")
3691    }
3692
3693    #[test]
3694    fn previous_version_config_parser_matches_ts_keys_and_defaults() {
3695        assert_eq!(parse_previous_version_context(None).expect("absent"), None);
3696        let defaults = parse_previous_version_context(Some(&json!({})))
3697            .expect("empty")
3698            .expect("present");
3699        assert!(!defaults.enabled);
3700        assert_eq!(defaults.max_bytes, 8 * 1024 * 1024);
3701        assert_eq!(defaults.max_rows, 20_000);
3702        assert_eq!(defaults.max_tables, 32);
3703        assert_eq!(defaults.max_row_bytes, 1024 * 1024);
3704        assert_eq!(defaults.max_age_ms, 24 * 60 * 60 * 1000);
3705
3706        let configured = parse_previous_version_context(Some(&json!({
3707            "enabled": true,
3708            "maxBytes": 1024,
3709            "maxRows": 3,
3710            "maxTables": 2,
3711            "maxRowBytes": 5,
3712            "maxAgeMs": 7
3713        })))
3714        .expect("configured")
3715        .expect("present");
3716        assert!(configured.enabled);
3717        assert_eq!(configured.max_bytes, 1024);
3718        assert_eq!(configured.max_rows, 3);
3719        assert_eq!(configured.max_tables, 2);
3720        assert_eq!(configured.max_row_bytes, 5);
3721        assert_eq!(configured.max_age_ms, 7);
3722
3723        // Invalid values fail loudly instead of silently defaulting.
3724        for (value, expected) in [
3725            (json!([]), "must be an object"),
3726            (json!({ "enabled": "yes" }), "enabled must be a boolean"),
3727            (
3728                json!({ "maxBytes": 0 }),
3729                "maxBytes must be a positive safe integer",
3730            ),
3731            (
3732                json!({ "maxRows": -1 }),
3733                "maxRows must be a positive safe integer",
3734            ),
3735            (
3736                json!({ "maxTables": 1.5 }),
3737                "maxTables must be a positive safe integer",
3738            ),
3739            (
3740                json!({ "maxRowBytes": "1" }),
3741                "maxRowBytes must be a positive safe integer",
3742            ),
3743            (
3744                json!({ "maxAgeMs": 0 }),
3745                "maxAgeMs must be a positive safe integer",
3746            ),
3747        ] {
3748            let error = parse_previous_version_context(Some(&value)).expect_err("must fail");
3749            assert_eq!(error.code, "sync.invalid_request", "{value}");
3750            assert!(
3751                error.message.contains(expected),
3752                "{value}: {}",
3753                error.message
3754            );
3755        }
3756    }
3757
3758    #[test]
3759    fn invalid_previous_version_config_fails_create_loudly() {
3760        let mut transport = NoNetwork::default();
3761        let mut client: Option<SyncClient> = None;
3762        let mut effects = CreateEffects::default();
3763        let error = dispatch(
3764            &mut transport,
3765            &mut client,
3766            &mut effects,
3767            "create",
3768            &json!({ "schema": schema(), "previousVersionContext": { "enabled": true, "maxRows": 0 } }),
3769        )
3770        .expect_err("invalid config must fail the create");
3771        assert_eq!(error.code, "sync.invalid_request");
3772        assert!(error.message.contains("maxRows"), "{}", error.message);
3773        assert!(client.is_none(), "no client may be installed");
3774    }
3775
3776    #[test]
3777    fn previous_version_snapshot_reports_not_configured_by_default() {
3778        let mut transport = NoNetwork::default();
3779        let mut client: Option<SyncClient> = None;
3780        let mut effects = CreateEffects::default();
3781        dispatch(
3782            &mut transport,
3783            &mut client,
3784            &mut effects,
3785            "create",
3786            &json!({ "schema": schema() }),
3787        )
3788        .expect("create");
3789        let snapshot = dispatch(
3790            &mut transport,
3791            &mut client,
3792            &mut effects,
3793            "previousVersionSnapshot",
3794            &json!({ "table": "todos" }),
3795        )
3796        .expect("snapshot");
3797        assert_eq!(snapshot["state"], json!("previousVersion"));
3798        assert_eq!(snapshot["available"], json!(false));
3799        assert_eq!(snapshot["reason"], json!("not-configured"));
3800        assert_eq!(snapshot["rows"], json!([]));
3801        assert_eq!(snapshot["truncated"], json!(false));
3802        assert_eq!(snapshot["currentVersion"], json!(1));
3803        let discarded = dispatch(
3804            &mut transport,
3805            &mut client,
3806            &mut effects,
3807            "previousVersionDiscard",
3808            &json!({}),
3809        )
3810        .expect("discard");
3811        assert_eq!(discarded, json!({ "present": false, "discarded": false }));
3812        assert_eq!(
3813            dispatch(
3814                &mut transport,
3815                &mut client,
3816                &mut effects,
3817                "previousVersionAudit",
3818                &json!({}),
3819            )
3820            .expect("audit"),
3821            Value::Null
3822        );
3823    }
3824
3825    #[test]
3826    fn previous_version_commands_round_trip_through_the_dispatcher() {
3827        let path = temp_db_path("previous-version");
3828        let mut transport = NoNetwork::default();
3829        let mut client: Option<SyncClient> = None;
3830        let mut effects = CreateEffects::default();
3831
3832        // A v1 replica with one pending local row and the feature on.
3833        dispatch(
3834            &mut transport,
3835            &mut client,
3836            &mut effects,
3837            "create",
3838            &json!({
3839                "schema": schema(),
3840                "dbPath": path,
3841                "previousVersionContext": previous_version_enabled()
3842            }),
3843        )
3844        .expect("create v1");
3845        client
3846            .as_mut()
3847            .expect("client")
3848            .mutate(vec![Mutation::Upsert {
3849                table: "todos".to_owned(),
3850                values: serde_json::Map::from_iter([
3851                    ("id".to_owned(), json!("t1")),
3852                    ("list_id".to_owned(), json!("l1")),
3853                ]),
3854                base_version: None,
3855            }])
3856            .expect("seed a local row");
3857        dispatch(
3858            &mut transport,
3859            &mut client,
3860            &mut effects,
3861            "shutdown",
3862            &json!({}),
3863        )
3864        .expect("shutdown");
3865
3866        // The bump captures into the sibling file.
3867        dispatch(
3868            &mut transport,
3869            &mut client,
3870            &mut effects,
3871            "create",
3872            &json!({
3873                "schema": schema_v2(),
3874                "dbPath": path,
3875                "previousVersionContext": previous_version_enabled()
3876            }),
3877        )
3878        .expect("create v2");
3879        assert!(
3880            std::path::Path::new(&container_path(&path)).exists(),
3881            "the bump must leave a container file"
3882        );
3883        let status = dispatch(
3884            &mut transport,
3885            &mut client,
3886            &mut effects,
3887            "statusSnapshot",
3888            &json!({}),
3889        )
3890        .expect("status");
3891        assert_eq!(
3892            status["previousVersionContext"]["present"],
3893            json!(true),
3894            "{status}"
3895        );
3896        assert!(
3897            status["previousVersionContext"]["createdAtMs"].is_i64(),
3898            "{status}"
3899        );
3900
3901        let snapshot = dispatch(
3902            &mut transport,
3903            &mut client,
3904            &mut effects,
3905            "previousVersionSnapshot",
3906            &json!({ "table": "todos" }),
3907        )
3908        .expect("snapshot");
3909        assert_eq!(snapshot["state"], json!("previousVersion"));
3910        assert_eq!(snapshot["available"], json!(true));
3911        assert_eq!(snapshot["previousVersion"], json!(1));
3912        assert_eq!(snapshot["currentVersion"], json!(2));
3913        assert_eq!(snapshot["truncated"], json!(false));
3914        assert_eq!(snapshot["rows"][0]["id"], json!("t1"));
3915        assert_eq!(snapshot["rows"][0]["list_id"], json!("l1"));
3916
3917        // Unknown previous table and a bad limit are loud request errors.
3918        let unknown = dispatch(
3919            &mut transport,
3920            &mut client,
3921            &mut effects,
3922            "previousVersionSnapshot",
3923            &json!({ "table": "absent" }),
3924        )
3925        .expect_err("unknown previous table");
3926        assert_eq!(unknown.code, "sync.invalid_request");
3927        let bad_limit = dispatch(
3928            &mut transport,
3929            &mut client,
3930            &mut effects,
3931            "previousVersionSnapshot",
3932            &json!({ "table": "todos", "limit": 0 }),
3933        )
3934        .expect_err("bad limit");
3935        assert_eq!(bad_limit.code, "sync.invalid_request");
3936
3937        // D6: the audit names the pending commit's classification, with no
3938        // envelope and nothing dropped.
3939        let audit = dispatch(
3940            &mut transport,
3941            &mut client,
3942            &mut effects,
3943            "previousVersionAudit",
3944            &json!({}),
3945        )
3946        .expect("audit");
3947        assert_eq!(audit["v"], json!(1));
3948        assert_eq!(audit["fromVersion"], json!(1));
3949        assert_eq!(audit["toVersion"], json!(2));
3950        assert_eq!(audit["pending"], json!(1));
3951        assert_eq!(audit["encodable"], json!(1));
3952        assert_eq!(audit["incompatible"], json!([]));
3953        assert!(audit.get("operations").is_none());
3954
3955        // The executable downgrade step, idempotent.
3956        let discarded = dispatch(
3957            &mut transport,
3958            &mut client,
3959            &mut effects,
3960            "previousVersionDiscard",
3961            &json!({}),
3962        )
3963        .expect("discard");
3964        assert_eq!(discarded, json!({ "present": true, "discarded": true }));
3965        assert!(!std::path::Path::new(&container_path(&path)).exists());
3966        let again = dispatch(
3967            &mut transport,
3968            &mut client,
3969            &mut effects,
3970            "previousVersionDiscard",
3971            &json!({}),
3972        )
3973        .expect("idempotent discard");
3974        assert_eq!(again, json!({ "present": false, "discarded": false }));
3975
3976        // Storage read directly: both metadata records are gone.
3977        let inspect = rusqlite::Connection::open(&path).expect("inspect replica");
3978        let remaining: i64 = inspect
3979            .query_row(
3980                "SELECT COUNT(*) FROM _syncular_meta WHERE key IN (?1, ?2)",
3981                rusqlite::params!["previousVersionContext", "previousVersionAudit"],
3982                |row| row.get(0),
3983            )
3984            .expect("count meta");
3985        assert_eq!(remaining, 0);
3986
3987        let _ = std::fs::remove_file(&path);
3988    }
3989
3990    #[test]
3991    fn previous_version_ttl_expires_at_read_through_the_dispatcher() {
3992        let path = temp_db_path("previous-version-ttl");
3993        let mut transport = NoNetwork::default();
3994        let mut client: Option<SyncClient> = None;
3995        let mut effects = CreateEffects::default();
3996        dispatch(
3997            &mut transport,
3998            &mut client,
3999            &mut effects,
4000            "create",
4001            &json!({
4002                "schema": schema(),
4003                "dbPath": path,
4004                "previousVersionContext": previous_version_enabled()
4005            }),
4006        )
4007        .expect("create v1");
4008        dispatch(
4009            &mut transport,
4010            &mut client,
4011            &mut effects,
4012            "shutdown",
4013            &json!({}),
4014        )
4015        .expect("shutdown");
4016
4017        // The injected clock is two seconds past the capture, with a TTL far
4018        // larger than the boot gap but far smaller than the skew, so the boot
4019        // reconcile keeps the container and the read expires it.
4020        let now_ms = std::time::SystemTime::now()
4021            .duration_since(std::time::UNIX_EPOCH)
4022            .expect("clock")
4023            .as_millis() as i64
4024            + 2_000;
4025        dispatch(
4026            &mut transport,
4027            &mut client,
4028            &mut effects,
4029            "create",
4030            &json!({
4031                "schema": schema_v2(),
4032                "dbPath": path,
4033                "nowMs": now_ms,
4034                "previousVersionContext": { "enabled": true, "maxAgeMs": 500 }
4035            }),
4036        )
4037        .expect("create v2");
4038        assert!(std::path::Path::new(&container_path(&path)).exists());
4039        let snapshot = dispatch(
4040            &mut transport,
4041            &mut client,
4042            &mut effects,
4043            "previousVersionSnapshot",
4044            &json!({ "table": "todos" }),
4045        )
4046        .expect("snapshot");
4047        assert_eq!(snapshot["available"], json!(false));
4048        assert_eq!(snapshot["reason"], json!("expired"));
4049        assert_eq!(snapshot["rows"], json!([]));
4050        // The TTL discards, and the FILE is what must be gone.
4051        assert!(!std::path::Path::new(&container_path(&path)).exists());
4052
4053        let _ = std::fs::remove_file(&path);
4054    }
4055
4056    #[test]
4057    fn presence_event_carries_the_fanout_scope_and_the_publish_refusal() {
4058        assert_eq!(
4059            super::presence_event(
4060                r#"{"event":"presence","data":{"scopeKey":"room:42","kind":"leave","actorId":"a","clientId":"c","doc":null,"timestamp":1}}"#
4061            ),
4062            Some(json!({ "type": "presence", "scopeKey": "room:42" }))
4063        );
4064        for code in ["presence.too_large", "presence.forbidden"] {
4065            let frame = format!(
4066                r#"{{"event":"presence","data":{{"scopeKey":"room:42","error":"{code}"}}}}"#
4067            );
4068            assert_eq!(
4069                super::presence_event(&frame),
4070                Some(json!({ "type": "presence", "scopeKey": "room:42", "error": code }))
4071            );
4072        }
4073    }
4074
4075    #[test]
4076    fn presence_event_ignores_malformed_frames_and_unknown_codes() {
4077        for frame in [
4078            r#"{"event":"presence","data":{}}"#,
4079            r#"{"event":"presence","data":{"scopeKey":"room:42","error":"presence.nope"}}"#,
4080            r#"{"event":"presence","data":{"scopeKey":"room:42","error":7}}"#,
4081            r#"{"event":"sync","data":{}}"#,
4082            "not json",
4083        ] {
4084            assert_eq!(super::presence_event(frame), None, "{frame}");
4085        }
4086    }
4087}