Skip to main content

syncular_client/
api.rs

1//! Driver-facing API shapes (JSON-able), mirroring the conformance
2//! `ClientInstance` contract: sync reports, conflicts, rejections, row
3//! states, unit states. Serialized as camelCase to cross the shim
4//! boundary unchanged.
5
6use std::collections::BTreeMap;
7
8use serde::{Deserialize, Serialize};
9use serde_json::{Map, Value};
10
11use crate::previous_version::PreviousVersionContextConfig;
12/// Stable dynamic value boundary used by generated named queries.
13pub type QueryValue = Value;
14/// One dynamic query result row, keyed by QueryIR runtime projection name.
15pub type QueryRow = Map<String, QueryValue>;
16
17/// An owned blob body returned by the Rust client without driver encoding.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct FetchedBlob {
20    pub blob_id: String,
21    pub byte_length: i64,
22    pub bytes: Vec<u8>,
23    pub media_type: Option<String>,
24}
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum TimeBucketUnit {
28    Month,
29}
30
31const MAX_TIME_BUCKET_MS: i64 = 253_402_300_799_999;
32
33fn utc_year_month(timestamp_ms: i64) -> Result<(i64, i64), String> {
34    if !(0..=MAX_TIME_BUCKET_MS).contains(&timestamp_ms) {
35        return Err(
36            "sync.invalid_request: time bucket timestamps must fall from 1970 through 9999"
37                .to_owned(),
38        );
39    }
40    let z = timestamp_ms / 86_400_000 + 719_468;
41    let era = z.div_euclid(146_097);
42    let day_of_era = z - era * 146_097;
43    let year_of_era =
44        (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
45    let mut year = year_of_era + era * 400;
46    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
47    let month_prime = (5 * day_of_year + 2) / 153;
48    let month = month_prime + if month_prime < 10 { 3 } else { -9 };
49    if month <= 2 {
50        year += 1;
51    }
52    Ok((year, month))
53}
54
55/// Derive the immutable UTC scope value stored when a row is created.
56pub fn creation_time_bucket(created_at_ms: i64, unit: TimeBucketUnit) -> Result<String, String> {
57    match unit {
58        TimeBucketUnit::Month => {
59            let (year, month) = utc_year_month(created_at_ms)?;
60            Ok(format!("{year:04}-{month:02}"))
61        }
62    }
63}
64
65/// Return a rolling UTC month window ordered from oldest to newest.
66pub fn last(count: usize, unit: TimeBucketUnit, now_ms: i64) -> Result<Vec<String>, String> {
67    if !(1..=1_200).contains(&count) {
68        return Err(
69            "sync.invalid_request: time bucket count must be from 1 through 1200".to_owned(),
70        );
71    }
72    match unit {
73        TimeBucketUnit::Month => {
74            let (year, month) = utc_year_month(now_ms)?;
75            let current = year * 12 + month - 1;
76            if current - (count as i64 - 1) < 1970 * 12 {
77                return Err(
78                    "sync.invalid_request: every returned UTC month must fall from 1970 through 9999"
79                        .to_owned(),
80                );
81            }
82            Ok((0..count)
83                .rev()
84                .map(|offset| {
85                    let value = current - offset as i64;
86                    format!(
87                        "{:04}-{:02}",
88                        value.div_euclid(12),
89                        value.rem_euclid(12) + 1
90                    )
91                })
92                .collect())
93        }
94    }
95}
96
97/// §4.1: a unit's scope map, one value per requested scope variable.
98pub type UnitScopes = BTreeMap<String, String>;
99
100/// §4.1 persisted unit status.
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
102#[serde(rename_all = "lowercase")]
103pub enum UnitStatus {
104    Active,
105    Revoked,
106    Failed,
107}
108
109impl UnitStatus {
110    pub fn name(self) -> &'static str {
111        match self {
112            UnitStatus::Active => "active",
113            UnitStatus::Revoked => "revoked",
114            UnitStatus::Failed => "failed",
115        }
116    }
117}
118
119/// §4.4 one fenced record of a persisted echo: the effective lists the
120/// wildcard fence added for a covered table, or its revocation.
121#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
122pub struct EchoRecord {
123    pub table: String,
124    /// `active` or `revoked`.
125    pub status: String,
126    pub scopes: BTreeMap<String, Vec<String>>,
127}
128
129/// §7.4.3 a unit's restriction: the kept cursor `C` through which its other
130/// covered tables hold every change, and the tables it bootstraps, in
131/// ascending code-unit order. It travels as `RESTRICT` (§4.3).
132#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
133pub struct UnitRestriction {
134    pub cursor: i64,
135    pub tables: Vec<String>,
136}
137
138/// §4.1 one registered unit as the client persists it.
139#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
140#[serde(rename_all = "camelCase")]
141pub struct UnitRecord {
142    /// §4.1: derived from the scope map.
143    pub id: String,
144    pub scopes: UnitScopes,
145    /// An explicit `subscribe` holds the unit; window bases hold it through
146    /// the window registry (§4.1 references).
147    pub explicit: bool,
148    pub status: UnitStatus,
149    /// §10 code when not active, or `sync.cursor_expired` after a reset.
150    #[serde(skip_serializing_if = "Option::is_none")]
151    pub reason_code: Option<String>,
152    /// Absent while the unit is live (§4.5); otherwise `-1`, the pin, or the
153    /// post-bootstrap cursor `P`.
154    #[serde(skip_serializing_if = "Option::is_none")]
155    pub cursor: Option<i64>,
156    /// Opaque resume token from `SUB_END` (§4.7); present mid-bootstrap.
157    #[serde(skip_serializing_if = "Option::is_none")]
158    pub bootstrap_state: Option<String>,
159    /// Tables that received a segment in the current bootstrap (§5.6).
160    pub seeded: Vec<String>,
161    /// The echo persisted at the last `SUB_END` (§4.4).
162    #[serde(skip_serializing_if = "Option::is_none")]
163    pub echo: Option<Vec<EchoRecord>>,
164    /// §7.4.3: the restriction a schema bump gave the unit, while it holds one.
165    #[serde(skip_serializing_if = "Option::is_none")]
166    pub restriction: Option<UnitRestriction>,
167}
168
169impl UnitRecord {
170    /// §4.1: a catching-up unit holding cursor `-1` or a resume token.
171    pub fn bootstrapping(&self) -> bool {
172        self.cursor
173            .is_some_and(|cursor| cursor < 0 || self.bootstrap_state.is_some())
174    }
175}
176
177/// §4.8 window base: the selected scope variable plus the fixed scope values
178/// every unit of its family shares. A base names no table: each unit covers
179/// every table declaring its variables (§4.1).
180#[derive(Debug, Clone, Default)]
181pub struct WindowBase {
182    pub variable: String,
183    /// One value per other variable, shared by every unit.
184    pub fixed_scopes: UnitScopes,
185}
186
187/// §4.8 completeness oracle (I3): the windowed-in units for a base, plus
188/// the subset whose bootstrap has not yet completed. Registration alone is
189/// not completeness — a `pending` unit's local replica may be empty or
190/// partial (it still has `cursor: -1` or holds a resume token), and MUST NOT
191/// be rendered as complete. A unit with zero server
192/// rows still completes once its bootstrap round finishes.
193#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
194#[serde(rename_all = "camelCase")]
195pub struct WindowState {
196    /// Windowed-in units for this base, ordered by value.
197    pub units: Vec<String>,
198    /// Registered units whose bootstrap has not yet completed.
199    pub pending: Vec<String>,
200}
201
202#[cfg(test)]
203mod time_bucket_tests {
204    use super::{creation_time_bucket, last, TimeBucketUnit};
205
206    #[test]
207    fn utc_month_buckets_cross_year_boundaries() {
208        let now = 1_770_508_800_000; // 2026-02-08T00:00:00Z
209        assert_eq!(
210            creation_time_bucket(now, TimeBucketUnit::Month).unwrap(),
211            "2026-02"
212        );
213        assert_eq!(
214            last(3, TimeBucketUnit::Month, now).unwrap(),
215            vec!["2025-12", "2026-01", "2026-02"]
216        );
217    }
218
219    #[test]
220    fn utc_month_buckets_reject_unbounded_input() {
221        assert!(last(0, TimeBucketUnit::Month, 0).is_err());
222        assert!(last(1_201, TimeBucketUnit::Month, 0).is_err());
223        assert!(last(2, TimeBucketUnit::Month, 0).is_err());
224        assert!(creation_time_bucket(-1, TimeBucketUnit::Month).is_err());
225    }
226}
227
228#[derive(Debug, Clone, Serialize)]
229#[serde(rename_all = "camelCase")]
230pub struct TableChange {
231    pub table: String,
232    #[serde(skip_serializing_if = "Option::is_none")]
233    pub scope_keys: Option<Vec<String>>,
234}
235
236#[derive(Debug, Clone, Serialize)]
237#[serde(rename_all = "camelCase")]
238pub struct WindowChange {
239    pub base_key: String,
240    /// Changed values of the base.
241    pub units: Vec<String>,
242}
243
244#[derive(Debug, Clone, Serialize)]
245#[serde(rename_all = "camelCase")]
246pub struct SyncStatusSnapshot {
247    pub current_schema_version: i32,
248    pub outbox: usize,
249    pub upgrading: bool,
250    /// §7.4.5: `upgrading` and the reset kept at least one readable table.
251    pub upgrade_kept_tables: bool,
252    #[serde(skip_serializing_if = "Option::is_none")]
253    pub lease_state: Option<LeaseState>,
254    #[serde(skip_serializing_if = "Option::is_none")]
255    pub schema_floor: Option<SchemaFloor>,
256    pub sync_needed: bool,
257    /// RFC 0005 A2: container presence, so a host can enforce the downgrade
258    /// precondition (`previousVersionDiscard`) instead of documenting it.
259    pub previous_version_context: PreviousVersionStatus,
260    /// §5.11: "preflight" while protected reads, claims and sync are refused;
261    /// a change batch carries the snapshot at each transition.
262    pub security_lifecycle: &'static str,
263}
264
265/// RFC 0005 A2: presence of the previous-version container file.
266#[derive(Debug, Clone, Copy, Default, Serialize, PartialEq, Eq)]
267#[serde(rename_all = "camelCase")]
268pub struct PreviousVersionStatus {
269    pub present: bool,
270    #[serde(skip_serializing_if = "Option::is_none")]
271    pub created_at_ms: Option<i64>,
272}
273
274pub const CLIENT_DIAGNOSTICS_VERSION: u8 = 2;
275pub const MAX_DIAGNOSTIC_QUERY_FAILURES: usize = 256;
276
277/// §8.8 client-local code: the `required` policy refused a sync round because
278/// the realtime socket is not connected. Never a wire code (§10.3).
279pub const REALTIME_UNAVAILABLE_CODE: &str = "sync.realtime_unavailable";
280/// §8.8 client-local code: a connected socket ended without a deliberate
281/// disconnect and the round reported no transport code. Never a wire code.
282pub const REALTIME_LOST_CODE: &str = "client.realtime_lost";
283/// §12 client-local code: a local-authority call or config on a host that
284/// has no local authority (the build lacks the `local-authority` feature, the
285/// config names no `localAuthorityPath`, or attach has no remote server).
286pub const LOCAL_AUTHORITY_UNCONFIGURED_CODE: &str = "client.local_authority_unconfigured";
287
288#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
289#[serde(rename_all = "camelCase")]
290pub struct ClientDiagnosticsHost {
291    pub kind: String,
292    pub role: String,
293    pub connectivity: String,
294    pub realtime: RealtimeState,
295    pub realtime_policy: RealtimePolicy,
296    #[serde(skip_serializing_if = "Option::is_none")]
297    pub realtime_reason_code: Option<String>,
298    #[serde(skip_serializing_if = "Option::is_none")]
299    pub realtime_retry_delay_ms: Option<u64>,
300}
301
302/// §7.6: registered units per state; a unit id never enters diagnostics.
303#[derive(Debug, Clone, Serialize, Default, PartialEq, Eq)]
304#[serde(rename_all = "camelCase")]
305pub struct DiagnosticUnits {
306    pub bootstrapping: usize,
307    pub complete: usize,
308    pub reset: usize,
309    pub revoked: usize,
310    pub failed: usize,
311    /// Distinct stable reason codes of registered units, ascending.
312    pub reason_codes: Vec<String>,
313}
314
315#[derive(Debug, Clone, Serialize, Default, PartialEq, Eq)]
316#[serde(rename_all = "camelCase")]
317pub struct DiagnosticRoundCounters {
318    pub pushed: u32,
319    pub applied: usize,
320    pub rejected: usize,
321    pub retryable: usize,
322    pub conflicts: u32,
323    pub commits_applied: u32,
324    pub segment_rows_applied: u32,
325    pub bootstrapping: usize,
326    pub resets: usize,
327    pub revoked: usize,
328    pub failed: usize,
329    pub deferred_commits: usize,
330}
331
332/// Bounded transport classification for progress and diagnostics (§1.8).
333#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
334#[serde(rename_all = "snake_case")]
335pub enum TransportCauseKind {
336    Network,
337    Connect,
338    Tls,
339    Io,
340    Request,
341    Protocol,
342    Timeout,
343    RoundDeadline,
344    Aborted,
345    Body,
346    Status,
347    Redirect,
348    Unknown,
349}
350
351#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
352#[serde(rename_all = "camelCase")]
353pub struct DiagnosticLastRound {
354    /// §7.6: (`epoch`, `attempt`) identifies the round; it equals its §7.7 progress pair.
355    pub epoch: String,
356    pub attempt: u64,
357    pub status: String,
358    pub started_at_ms: i64,
359    pub completed_at_ms: i64,
360    pub duration_ms: i64,
361    #[serde(skip_serializing_if = "Option::is_none")]
362    pub counters: Option<DiagnosticRoundCounters>,
363    #[serde(skip_serializing_if = "Option::is_none")]
364    pub error_code: Option<String>,
365    #[serde(skip_serializing_if = "Option::is_none")]
366    pub cause_kind: Option<TransportCauseKind>,
367    #[serde(skip_serializing_if = "Option::is_none")]
368    pub http_status: Option<u16>,
369}
370
371#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
372#[serde(rename_all = "camelCase")]
373pub struct DiagnosticLastChange {
374    pub revision: String,
375    pub recorded_at_ms: i64,
376    pub tables: Vec<String>,
377    pub windows: Vec<String>,
378    pub domains_truncated: bool,
379    pub status_changed: bool,
380    pub conflicts_changed: bool,
381    pub rejections_changed: bool,
382    pub outcomes_changed: bool,
383}
384
385#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
386#[serde(rename_all = "camelCase")]
387pub struct ClientDiagnosticsStorage {
388    pub status: String,
389    #[serde(skip_serializing_if = "Option::is_none")]
390    pub database_bytes_approx: Option<i64>,
391    #[serde(skip_serializing_if = "Option::is_none")]
392    pub pending_outbox_bytes_approx: Option<i64>,
393    #[serde(skip_serializing_if = "Option::is_none")]
394    pub retained_outcome_bytes_approx: Option<i64>,
395    #[serde(skip_serializing_if = "Option::is_none")]
396    pub retained_outcome_entries: Option<i64>,
397    #[serde(skip_serializing_if = "Option::is_none")]
398    pub blob_cache_bytes_approx: Option<i64>,
399    #[serde(skip_serializing_if = "Option::is_none")]
400    pub pressure_reason_code: Option<String>,
401}
402
403/// §7.6: the latest owned snapshot read of one query id failed.
404#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
405#[serde(rename_all = "camelCase")]
406pub struct DiagnosticQueryFailure {
407    pub id: String,
408    /// Distinct generated table names, ascending.
409    pub tables: Vec<String>,
410    /// `client.storage_corrupt`, `client.storage_io`, or `client.query_failed`.
411    pub code: String,
412    /// SQLite extended result code, when the driver exposed one.
413    #[serde(skip_serializing_if = "Option::is_none")]
414    pub sqlite_code: Option<i32>,
415    /// First failure since this id's last successful read.
416    pub at_ms: i64,
417}
418
419#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
420#[serde(rename_all = "camelCase")]
421pub struct ClientDiagnosticsSnapshot {
422    pub version: u8,
423    pub captured_at_ms: i64,
424    pub host: ClientDiagnosticsHost,
425    pub security_lifecycle: String,
426    pub schema: ClientDiagnosticsSchema,
427    pub replica: ClientDiagnosticsReplica,
428    pub lease: ClientDiagnosticsLease,
429    pub units: DiagnosticUnits,
430    /// Units the next registration list carries; the server limit counts
431    /// these (§4.1).
432    pub active_units: usize,
433    /// §4.5 replica cursor; `-1` while no unit is live.
434    pub replica_cursor: i64,
435    #[serde(skip_serializing_if = "Option::is_none")]
436    pub last_round: Option<DiagnosticLastRound>,
437    #[serde(skip_serializing_if = "Option::is_none")]
438    pub last_change: Option<DiagnosticLastChange>,
439    pub storage: ClientDiagnosticsStorage,
440    pub query_failures: Vec<DiagnosticQueryFailure>,
441}
442
443#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
444#[serde(rename_all = "camelCase")]
445pub struct ClientDiagnosticsSchema {
446    pub current_version: i32,
447    pub upgrading: bool,
448    #[serde(skip_serializing_if = "Option::is_none")]
449    pub required_version: Option<i32>,
450    #[serde(skip_serializing_if = "Option::is_none")]
451    pub latest_version: Option<i32>,
452}
453
454#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
455#[serde(rename_all = "camelCase")]
456pub struct ClientDiagnosticsReplica {
457    pub local_revision: String,
458    pub sync_needed: bool,
459    pub pending_outbox: usize,
460}
461
462/// §8.8: how this client treats the realtime binding for sync rounds.
463#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
464#[serde(rename_all = "lowercase")]
465pub enum RealtimePolicy {
466    Required,
467    #[default]
468    Optional,
469    Off,
470}
471
472impl RealtimePolicy {
473    #[must_use]
474    pub fn as_str(self) -> &'static str {
475        match self {
476            RealtimePolicy::Required => "required",
477            RealtimePolicy::Optional => "optional",
478            RealtimePolicy::Off => "off",
479        }
480    }
481}
482
483/// §8.8: the explicit availability state of the realtime binding. The
484/// TypeScript host adds `unsupported` (no connector configured) and `unknown`
485/// (a wrapper without evidence); the Rust core reaches neither because a
486/// transport always carries a connect path.
487#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
488#[serde(rename_all = "lowercase")]
489pub enum RealtimeState {
490    Connected,
491    Connecting,
492    #[default]
493    Disconnected,
494    Lost,
495    Refused,
496    Disabled,
497}
498
499#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
500#[serde(rename_all = "camelCase")]
501pub struct ClientDiagnosticsLease {
502    pub state: String,
503    #[serde(skip_serializing_if = "Option::is_none")]
504    pub expires_at_ms: Option<i64>,
505    #[serde(skip_serializing_if = "Option::is_none")]
506    pub error_code: Option<String>,
507}
508
509/// JSON bindings carry the u64 revision as a decimal string (§7.5).
510#[derive(Debug, Clone, Serialize)]
511#[serde(rename_all = "camelCase")]
512pub struct AppliedServerCommit {
513    pub table: String,
514    pub commit_seq: i64,
515    pub source: AppliedServerCommitSource,
516}
517
518#[derive(Debug, Clone, Copy, Serialize)]
519#[serde(rename_all = "camelCase")]
520pub enum AppliedServerCommitSource {
521    Delta,
522    Pull,
523}
524
525#[derive(Debug, Clone, Serialize)]
526#[serde(rename_all = "camelCase")]
527pub struct ClientChangeBatch {
528    pub revision: String,
529    pub tables: Vec<TableChange>,
530    pub windows: Vec<WindowChange>,
531    #[serde(skip_serializing_if = "Option::is_none")]
532    pub status: Option<SyncStatusSnapshot>,
533    pub conflicts_changed: bool,
534    pub rejections_changed: bool,
535    pub outcomes_changed: bool,
536    #[serde(skip_serializing_if = "Vec::is_empty")]
537    pub applied_commits: Vec<AppliedServerCommit>,
538}
539
540#[derive(Debug, Clone, Serialize)]
541#[serde(tag = "kind", rename_all = "camelCase")]
542pub enum SyncIntent {
543    None,
544    Interactive,
545    Background {
546        #[serde(rename = "delayMs")]
547        delay_ms: u64,
548    },
549}
550
551#[derive(Debug, Clone, Serialize)]
552pub struct CommandEffects {
553    pub sync: SyncIntent,
554}
555
556impl CommandEffects {
557    #[must_use]
558    pub fn none() -> Self {
559        Self {
560            sync: SyncIntent::None,
561        }
562    }
563
564    #[must_use]
565    pub fn interactive() -> Self {
566        Self {
567            sync: SyncIntent::Interactive,
568        }
569    }
570}
571
572#[derive(Debug, Clone)]
573pub struct WindowCoverage {
574    pub base: WindowBase,
575    pub units: Vec<String>,
576}
577
578#[derive(Debug, Clone, Serialize)]
579#[serde(rename_all = "camelCase")]
580pub struct WindowUnitRef {
581    pub base_key: String,
582    pub unit: String,
583}
584
585#[derive(Debug, Clone, Serialize)]
586#[serde(rename_all = "camelCase")]
587pub struct CoverageSnapshot {
588    pub complete: bool,
589    pub pending: Vec<WindowUnitRef>,
590    pub missing: Vec<WindowUnitRef>,
591}
592
593/// §7.5: the query that owns a snapshot read. The id is application-owned,
594/// stable, and PHI-free; generated named queries pass their `ID` and `TABLES`.
595#[derive(Debug, Clone, Copy)]
596pub struct QueryOwner<'a> {
597    pub id: &'a str,
598    pub tables: &'a [&'a str],
599}
600
601/// §7.5: a failed snapshot read or a failed local authoring write. `code` is
602/// `client.storage_corrupt`, `client.storage_io`, `client.storage_full`, or
603/// `client.storage_busy` when SQLite reported that condition, and `None` for
604/// every other failure, which keeps its existing message.
605#[derive(Debug, Clone, PartialEq, Eq)]
606pub struct QueryReadFailure {
607    pub code: Option<&'static str>,
608    pub sqlite_code: Option<i32>,
609    pub sqlite_message: Option<String>,
610    pub rollback_failure: Option<Box<QueryReadFailure>>,
611    pub message: String,
612}
613
614impl std::fmt::Display for QueryReadFailure {
615    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
616        match self.code {
617            Some(code) => write!(f, "{code}: {}", self.message),
618            None => f.write_str(&self.message),
619        }
620    }
621}
622
623impl From<String> for QueryReadFailure {
624    fn from(message: String) -> Self {
625        Self {
626            code: None,
627            sqlite_code: None,
628            sqlite_message: None,
629            rollback_failure: None,
630            message,
631        }
632    }
633}
634
635impl From<rusqlite::Error> for QueryReadFailure {
636    /// Classify by SQLite's primary result code, never by message text.
637    fn from(error: rusqlite::Error) -> Self {
638        let sqlite_code = match &error {
639            rusqlite::Error::SqliteFailure(failure, _) => Some(failure.extended_code),
640            _ => None,
641        };
642        match sqlite_code.map(|code| code & 0xff) {
643            Some(11 | 26) => Self {
644                code: Some("client.storage_corrupt"),
645                sqlite_code,
646                sqlite_message: Some(error.to_string()),
647                rollback_failure: None,
648                message: "local SQLite storage is corrupt".to_owned(),
649            },
650            Some(13) => Self {
651                code: Some("client.storage_full"),
652                sqlite_code,
653                sqlite_message: Some(error.to_string()),
654                rollback_failure: None,
655                message: "local SQLite storage is full".to_owned(),
656            },
657            Some(10) => Self {
658                code: Some("client.storage_io"),
659                sqlite_code,
660                sqlite_message: Some(error.to_string()),
661                rollback_failure: None,
662                message: "local SQLite storage I/O failed".to_owned(),
663            },
664            // SQLITE_BUSY (5) and SQLITE_LOCKED (6), including every extended
665            // code, are transient lock contention: the same operation can
666            // succeed after the conflicting operation releases its lock.
667            Some(5 | 6) => Self {
668                code: Some("client.storage_busy"),
669                sqlite_code,
670                sqlite_message: Some(error.to_string()),
671                rollback_failure: None,
672                message: "local SQLite storage is busy".to_owned(),
673            },
674            _ => Self {
675                code: None,
676                sqlite_code,
677                sqlite_message: Some(error.to_string()),
678                rollback_failure: None,
679                message: error.to_string(),
680            },
681        }
682    }
683}
684
685impl QueryReadFailure {
686    /// The operation can be retried after lock contention is resolved.
687    /// SQLITE_LOCKED can involve another statement on the same connection.
688    pub fn retryable(&self) -> bool {
689        self.code == Some("client.storage_busy")
690    }
691
692    pub fn details(&self) -> Option<Value> {
693        self.sqlite_code.map(|code| {
694            let mut details =
695                serde_json::json!({ "sqliteCode": code, "sqliteMessage": self.sqlite_message });
696            if let Some(rollback) = &self.rollback_failure {
697                details["rollbackFailure"] = serde_json::json!({
698                    "sqliteCode": rollback.sqlite_code, "message": rollback.sqlite_message
699                });
700            }
701            details
702        })
703    }
704}
705
706/// A structured failure from a local authoring API (`mutate`/`patch`). `code`
707/// is always a stable `client.*`/`sync.*` identity, `message` is static text
708/// with no table/row/column values, `details` carries SQLite classification
709/// evidence or the preserved legacy cause, and `retryable` is true only for
710/// transient storage contention. Callers read these fields instead of parsing
711/// a `"<code>: "` prefix.
712#[derive(Debug, Clone, PartialEq, Eq)]
713pub struct ClientError {
714    pub code: String,
715    pub message: String,
716    pub details: Option<Value>,
717    pub retryable: bool,
718}
719
720/// The stable default for an authoring failure with no recognized code.
721const DEFAULT_CLIENT_ERROR_CODE: &str = "client.failed";
722
723/// The static text used when no specific static authoring message exists.
724const GENERIC_AUTHORING_MESSAGE: &str = "the local authoring operation failed";
725
726/// The fixed user-facing text for a known authoring code. Dynamic values from
727/// a legacy cause string move to `details.legacyCause` instead.
728fn static_authoring_message(code: &str) -> Option<&'static str> {
729    match code {
730        "sync.unknown_table" => Some("the commit targets an unknown table"),
731        "sync.invalid_request" => Some("the authoring request is invalid"),
732        "sync.row_missing" => Some("a sparse patch requires a local row"),
733        "sync.constraint_violation" => Some("local write violates a unique constraint"),
734        DEFAULT_CLIENT_ERROR_CODE => Some(GENERIC_AUTHORING_MESSAGE),
735        _ => None,
736    }
737}
738
739fn is_client_code(candidate: &str) -> bool {
740    candidate.starts_with("client.") || candidate.starts_with("sync.")
741}
742
743impl std::fmt::Display for ClientError {
744    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
745        write!(f, "{}: {}", self.code, self.message)
746    }
747}
748
749impl std::error::Error for ClientError {}
750
751impl From<QueryReadFailure> for ClientError {
752    fn from(failure: QueryReadFailure) -> Self {
753        match failure.code {
754            // Classified storage messages are already static.
755            Some(code) => {
756                let details = failure.details();
757                let retryable = failure.retryable();
758                Self {
759                    code: code.to_owned(),
760                    message: failure.message,
761                    details,
762                    retryable,
763                }
764            }
765            None => {
766                let mut details = failure.details().unwrap_or_else(|| serde_json::json!({}));
767                if let Some(object) = details.as_object_mut() {
768                    object.insert("legacyCause".to_owned(), Value::String(failure.message));
769                }
770                Self {
771                    code: DEFAULT_CLIENT_ERROR_CODE.to_owned(),
772                    message: GENERIC_AUTHORING_MESSAGE.to_owned(),
773                    details: Some(details),
774                    retryable: false,
775                }
776            }
777        }
778    }
779}
780
781impl From<String> for ClientError {
782    /// Split a core error into structured fields. A recognized code identity
783    /// is preserved and gets static text; any dynamic cause stays in
784    /// `details.legacyCause`. Everything else defaults to `client.failed` with
785    /// the generic message.
786    fn from(message: String) -> Self {
787        // A code-only identity, e.g. `sync.unknown_table`.
788        if !message.contains(": ") && is_client_code(&message) {
789            return Self {
790                code: message.clone(),
791                message: static_authoring_message(&message)
792                    .unwrap_or(GENERIC_AUTHORING_MESSAGE)
793                    .to_owned(),
794                details: None,
795                retryable: false,
796            };
797        }
798        let (code, rest) = match message.split_once(": ") {
799            Some((code, rest)) if is_client_code(code) => (code, Some(rest)),
800            _ => (DEFAULT_CLIENT_ERROR_CODE, None),
801        };
802        match static_authoring_message(code) {
803            Some(fixed) => Self {
804                code: code.to_owned(),
805                message: fixed.to_owned(),
806                details: (rest != Some(fixed))
807                    .then(|| serde_json::json!({ "legacyCause": message })),
808                retryable: false,
809            },
810            None => Self {
811                code: code.to_owned(),
812                message: GENERIC_AUTHORING_MESSAGE.to_owned(),
813                details: Some(serde_json::json!({ "legacyCause": message })),
814                retryable: false,
815            },
816        }
817    }
818}
819
820#[derive(Debug, Clone, Serialize)]
821#[serde(rename_all = "camelCase")]
822pub struct QuerySnapshot {
823    pub revision: String,
824    pub rows: Vec<QueryRow>,
825    pub coverage: CoverageSnapshot,
826}
827
828impl WindowState {
829    /// The per-unit verdict: registered AND bootstrap-complete.
830    #[must_use]
831    pub fn complete(&self, unit: &str) -> bool {
832        self.units.iter().any(|u| u == unit) && !self.pending.iter().any(|u| u == unit)
833    }
834}
835
836/// One local mutation (§6.1 shapes, schema-agnostic local form per §0).
837#[derive(Debug, Clone)]
838pub enum Mutation {
839    Patch {
840        table: String,
841        values: Map<String, Value>,
842        base_version: Option<i64>,
843    },
844    Upsert {
845        table: String,
846        values: Map<String, Value>,
847        base_version: Option<i64>,
848    },
849    Delete {
850        table: String,
851        row_id: String,
852        base_version: Option<i64>,
853    },
854}
855
856#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
857#[serde(rename_all = "camelCase")]
858pub struct SchemaFloor {
859    #[serde(skip_serializing_if = "Option::is_none")]
860    pub required_schema_version: Option<i32>,
861    #[serde(skip_serializing_if = "Option::is_none")]
862    pub latest_schema_version: Option<i32>,
863}
864
865/// §7.3.5: the client's opaque auth-lease state — `leaseId`/`expiresAtMs`
866/// from the last `LEASE` frame, and `errorCode` once a round was rejected
867/// with a request-level lease code (stop-and-surface; no data purge).
868#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
869#[serde(rename_all = "camelCase")]
870pub struct LeaseState {
871    #[serde(skip_serializing_if = "Option::is_none")]
872    pub lease_id: Option<String>,
873    #[serde(skip_serializing_if = "Option::is_none")]
874    pub expires_at_ms: Option<i64>,
875    #[serde(skip_serializing_if = "Option::is_none")]
876    pub error_code: Option<String>,
877}
878
879/// §8.6 a peer's ephemeral presence document on a scope key.
880#[derive(Debug, Clone, Serialize)]
881#[serde(rename_all = "camelCase")]
882pub struct PresencePeer {
883    pub actor_id: String,
884    pub client_id: String,
885    pub doc: serde_json::Value,
886}
887
888#[derive(Debug, Clone, Serialize, Default)]
889#[serde(rename_all = "camelCase")]
890pub struct SyncReport {
891    pub pushed: u32,
892    pub applied: Vec<String>,
893    pub rejected: Vec<String>,
894    pub retryable: Vec<String>,
895    pub conflicts: u32,
896    pub commits_applied: u32,
897    pub segment_rows_applied: u32,
898    pub bootstrapping: Vec<String>,
899    pub resets: Vec<String>,
900    pub revoked: Vec<String>,
901    pub failed: Vec<String>,
902    pub deferred_commits: usize,
903    #[serde(skip_serializing_if = "Option::is_none")]
904    pub schema_floor: Option<SchemaFloor>,
905}
906
907impl SyncReport {
908    /// Aggregate completed rounds. Historical counters and outcome lists
909    /// accumulate; current readiness (`bootstrapping`, `deferred_commits`,
910    /// `schema_floor`) describes the latest round. A schema floor stops the
911    /// loop, so it can only arrive from the latest round.
912    pub fn merge(&mut self, report: &Self) {
913        self.pushed += report.pushed;
914        self.applied.extend(report.applied.iter().cloned());
915        self.rejected.extend(report.rejected.iter().cloned());
916        self.retryable.extend(report.retryable.iter().cloned());
917        self.conflicts += report.conflicts;
918        self.commits_applied += report.commits_applied;
919        self.segment_rows_applied += report.segment_rows_applied;
920        self.bootstrapping = report.bootstrapping.clone();
921        self.resets.extend(report.resets.iter().cloned());
922        self.revoked.extend(report.revoked.iter().cloned());
923        self.failed.extend(report.failed.iter().cloned());
924        self.deferred_commits = report.deferred_commits;
925        self.schema_floor = report.schema_floor.clone();
926    }
927}
928
929/// `sync()` never panics or errors out-of-band: transport and protocol
930/// failures come back as `Failed` (the driver's `{ ok: false }`).
931#[derive(Debug, Clone)]
932pub enum SyncOutcome {
933    Ok(SyncReport),
934    Failed {
935        error_code: String,
936        message: String,
937        details: Option<Value>,
938        /// §10.1 `recommendedAction` from the server's error body, when the
939        /// transport preserved one. Client-local and storage failures carry
940        /// `None`.
941        recommended_action: Option<String>,
942    },
943    /// §8.8: the `required` policy refused a round because the socket is not
944    /// connected. `reason_code` is present for `lost` and `refused` states,
945    /// and `retry_delay_ms` is the delay of the background retry intent this
946    /// outcome scheduled.
947    RealtimeUnavailable {
948        state: RealtimeState,
949        reason_code: Option<String>,
950        retry_delay_ms: u64,
951    },
952    /// §7.8: the round budget ran out while the client was still not idle.
953    /// The aggregate report of every round that ran is retained. This is a
954    /// partial success, not a failure, and MUST NOT be read as idle.
955    BudgetExhausted(SyncReport),
956}
957
958impl SyncOutcome {
959    pub fn to_json(&self) -> Value {
960        match self {
961            SyncOutcome::Ok(report) => {
962                let mut map = Map::new();
963                map.insert("ok".to_owned(), Value::Bool(true));
964                map.insert(
965                    "report".to_owned(),
966                    serde_json::to_value(report).expect("report serializes"),
967                );
968                Value::Object(map)
969            }
970            SyncOutcome::Failed {
971                error_code,
972                message,
973                details,
974                recommended_action,
975            } => {
976                let mut map = Map::new();
977                map.insert("ok".to_owned(), Value::Bool(false));
978                map.insert("errorCode".to_owned(), Value::from(error_code.clone()));
979                map.insert("message".to_owned(), Value::from(message.clone()));
980                if let Some(details) = details {
981                    map.insert("details".to_owned(), details.clone());
982                }
983                if let Some(recommended_action) = recommended_action {
984                    map.insert(
985                        "recommendedAction".to_owned(),
986                        Value::from(recommended_action.clone()),
987                    );
988                }
989                Value::Object(map)
990            }
991            SyncOutcome::RealtimeUnavailable {
992                state,
993                reason_code,
994                retry_delay_ms,
995            } => {
996                let mut map = Map::new();
997                map.insert("ok".to_owned(), Value::Bool(false));
998                map.insert(
999                    "errorCode".to_owned(),
1000                    Value::from(REALTIME_UNAVAILABLE_CODE),
1001                );
1002                map.insert(
1003                    "message".to_owned(),
1004                    Value::from("realtime is required and the realtime socket is not connected"),
1005                );
1006                map.insert(
1007                    "realtimeState".to_owned(),
1008                    serde_json::to_value(state).expect("state serializes"),
1009                );
1010                if let Some(reason_code) = reason_code {
1011                    map.insert(
1012                        "realtimeReasonCode".to_owned(),
1013                        Value::from(reason_code.clone()),
1014                    );
1015                }
1016                map.insert("retryDelayMs".to_owned(), Value::from(*retry_delay_ms));
1017                Value::Object(map)
1018            }
1019            SyncOutcome::BudgetExhausted(report) => {
1020                let mut map = Map::new();
1021                map.insert("ok".to_owned(), Value::Bool(true));
1022                map.insert("budgetExhausted".to_owned(), Value::Bool(true));
1023                map.insert(
1024                    "report".to_owned(),
1025                    serde_json::to_value(report).expect("report serializes"),
1026                );
1027                Value::Object(map)
1028            }
1029        }
1030    }
1031}
1032
1033#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1034#[serde(rename_all = "camelCase")]
1035pub struct ConflictRecord {
1036    pub client_commit_id: String,
1037    pub op_index: i32,
1038    pub table: String,
1039    pub row_id: String,
1040    pub code: String,
1041    pub message: String,
1042    pub server_version: i64,
1043    /// Driver row (bytes as `{"$bytes": hex}`), decoded from the conflict
1044    /// record's `serverRow` (§6.3).
1045    pub server_row: Map<String, Value>,
1046    /// §6.3 `conflictColumns`: the present columns whose `column_version`
1047    /// exceeded `baseVersion`, decoded from the bitmap into column names in
1048    /// declaration order. Absent on a legacy journal entry, which reads as an
1049    /// empty list.
1050    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1051    pub conflict_columns: Vec<String>,
1052    #[serde(skip_serializing_if = "Option::is_none")]
1053    pub operation: Option<CommitOperation>,
1054}
1055
1056/// Bounded code-like metadata explicitly declared safe for authorized client
1057/// recovery UI. Diagnostic prose remains in `RejectionRecord.message`.
1058#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1059#[serde(rename_all = "camelCase", deny_unknown_fields)]
1060pub struct RejectionDetails {
1061    #[serde(skip_serializing_if = "Option::is_none")]
1062    pub field_paths: Option<Vec<String>>,
1063    #[serde(skip_serializing_if = "Option::is_none")]
1064    pub reason: Option<String>,
1065    #[serde(skip_serializing_if = "Option::is_none")]
1066    pub required_action: Option<String>,
1067    #[serde(skip_serializing_if = "Option::is_none")]
1068    pub references: Option<BTreeMap<String, String>>,
1069}
1070
1071impl RejectionDetails {
1072    pub(crate) fn parse(raw: &str) -> Result<Self, String> {
1073        if raw.len() > 4_096 {
1074            return Err("rejection details exceed 4096 encoded bytes".to_owned());
1075        }
1076        let details: Self = serde_json::from_str(raw)
1077            .map_err(|error| format!("invalid rejection details: {error}"))?;
1078        details.validate()?;
1079        Ok(details)
1080    }
1081
1082    fn validate(&self) -> Result<(), String> {
1083        let mut members = 0;
1084        if let Some(paths) = &self.field_paths {
1085            members += 1;
1086            if paths.is_empty() || paths.len() > 32 {
1087                return Err("fieldPaths must contain 1-32 paths".to_owned());
1088            }
1089            let mut seen = std::collections::BTreeSet::new();
1090            for path in paths {
1091                if path.len() > 160 || !path.split('.').all(valid_identifier) || !seen.insert(path)
1092                {
1093                    return Err("fieldPaths contains an invalid or duplicate path".to_owned());
1094                }
1095            }
1096        }
1097        if let Some(reason) = &self.reason {
1098            members += 1;
1099            if !valid_token(reason, 96) {
1100                return Err("reason must be a lowercase stable token".to_owned());
1101            }
1102        }
1103        if let Some(action) = &self.required_action {
1104            members += 1;
1105            if !valid_token(action, 96) {
1106                return Err("requiredAction must be a lowercase stable token".to_owned());
1107            }
1108        }
1109        if let Some(references) = &self.references {
1110            members += 1;
1111            if references.is_empty() || references.len() > 16 {
1112                return Err("references must contain 1-16 entries".to_owned());
1113            }
1114            for (key, value) in references {
1115                if !valid_token(key, 64)
1116                    || value.is_empty()
1117                    || value.len() > 256
1118                    || value.trim() != value
1119                    || value.chars().any(char::is_control)
1120                {
1121                    return Err("references contains an invalid key or value".to_owned());
1122                }
1123            }
1124        }
1125        if members == 0 {
1126            return Err("rejection details must not be empty".to_owned());
1127        }
1128        Ok(())
1129    }
1130}
1131
1132fn valid_identifier(segment: &str) -> bool {
1133    let mut chars = segment.chars();
1134    matches!(chars.next(), Some(first) if first == '_' || first.is_ascii_alphabetic())
1135        && chars.all(|character| character == '_' || character.is_ascii_alphanumeric())
1136}
1137
1138fn valid_token(token: &str, max: usize) -> bool {
1139    if token.is_empty() || token.len() > max || !token.starts_with(|c: char| c.is_ascii_lowercase())
1140    {
1141        return false;
1142    }
1143    let mut previous_separator = false;
1144    for character in token.chars() {
1145        if character.is_ascii_lowercase() || character.is_ascii_digit() {
1146            previous_separator = false;
1147        } else if matches!(character, '.' | '_' | '-') && !previous_separator {
1148            previous_separator = true;
1149        } else {
1150            return false;
1151        }
1152    }
1153    !previous_separator
1154}
1155
1156#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1157#[serde(rename_all = "camelCase")]
1158pub struct RejectionRecord {
1159    pub client_commit_id: String,
1160    pub op_index: i32,
1161    pub code: String,
1162    pub message: String,
1163    pub retryable: bool,
1164    #[serde(skip_serializing_if = "Option::is_none")]
1165    pub details: Option<RejectionDetails>,
1166    #[serde(skip_serializing_if = "Option::is_none")]
1167    pub operation: Option<CommitOperation>,
1168}
1169
1170/// Schema-agnostic local operation retained with a failed final outcome.
1171#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1172#[serde(rename_all = "camelCase")]
1173pub struct CommitOperation {
1174    pub table: String,
1175    pub row_id: String,
1176    pub op: String,
1177    #[serde(skip_serializing_if = "Option::is_none")]
1178    pub base_version: Option<i64>,
1179    #[serde(skip_serializing_if = "Option::is_none")]
1180    pub values: Option<Map<String, Value>>,
1181    /// §7.1 insert intent: serialized as `"insert": true`, absent otherwise.
1182    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1183    pub insert: bool,
1184}
1185
1186/// One pending outbox commit (§7.1), in the shape the TypeScript client's
1187/// `pendingCommits()` returns.
1188#[derive(Debug, Clone, Serialize, PartialEq)]
1189#[serde(rename_all = "camelCase")]
1190pub struct PendingCommit {
1191    /// The outbox sequence number; FIFO send order.
1192    pub seq: i64,
1193    pub client_commit_id: String,
1194    /// Local clock at `mutate`; 0 for a commit queued before 0.89.
1195    pub created_at_ms: i64,
1196    pub operations: Vec<CommitOperation>,
1197}
1198
1199#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1200#[serde(rename_all = "snake_case")]
1201pub enum CommitOutcomeStatus {
1202    Applied,
1203    Cached,
1204    Conflict,
1205    Rejected,
1206}
1207
1208#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1209#[serde(rename_all = "snake_case")]
1210pub enum CommitOutcomeResolution {
1211    Active,
1212    ResolvedKeepServer,
1213    Superseded,
1214    Dismissed,
1215}
1216
1217#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1218#[serde(tag = "status", rename_all = "snake_case")]
1219pub enum CommitOperationOutcome {
1220    Applied {
1221        #[serde(rename = "opIndex")]
1222        op_index: i32,
1223    },
1224    Conflict {
1225        conflict: ConflictRecord,
1226    },
1227    Error {
1228        rejection: RejectionRecord,
1229    },
1230}
1231
1232#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1233#[serde(rename_all = "camelCase")]
1234pub struct RetainedUniqueConflict {
1235    pub index: String,
1236    pub columns: Vec<String>,
1237    pub row_id: String,
1238    pub server_row: Map<String, Value>,
1239    pub server_version: i64,
1240}
1241
1242#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1243#[serde(rename_all = "camelCase")]
1244pub struct RetainedCommitRow {
1245    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1246    pub unique_conflicts: Vec<RetainedUniqueConflict>,
1247    pub table: String,
1248    pub row_id: String,
1249    pub local_row: Option<Map<String, Value>>,
1250    /// The latest delivered authorized base; rejection can precede the pull.
1251    pub server_row: Option<Map<String, Value>>,
1252    pub server_version: Option<i64>,
1253}
1254
1255/// Result of proving every retained base after a completed pull (§7.2.1).
1256#[derive(Debug, Clone, Serialize, PartialEq)]
1257#[serde(rename_all = "camelCase")]
1258pub struct CurrentBaseProof {
1259    pub proven: bool,
1260    #[serde(skip_serializing_if = "Option::is_none")]
1261    pub rows: Option<Vec<RetainedCommitRow>>,
1262    #[serde(skip_serializing_if = "Option::is_none")]
1263    pub reason: Option<CurrentBaseProofReason>,
1264}
1265
1266#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
1267#[serde(rename_all = "snake_case")]
1268pub enum CurrentBaseProofReason {
1269    Offline,
1270    SyncFailed,
1271    SchemaFloor,
1272    BudgetExhausted,
1273    SnapshotFailed,
1274    MissingCoverage,
1275    Revoked,
1276    OutcomeUnavailable,
1277}
1278
1279impl CurrentBaseProof {
1280    pub fn failure(reason: CurrentBaseProofReason) -> Self {
1281        Self {
1282            proven: false,
1283            rows: None,
1284            reason: Some(reason),
1285        }
1286    }
1287}
1288
1289#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1290#[serde(rename_all = "camelCase")]
1291pub struct CommitOutcome {
1292    pub sequence: i64,
1293    pub client_commit_id: String,
1294    pub status: CommitOutcomeStatus,
1295    pub recorded_at_ms: i64,
1296    pub results: Vec<CommitOperationOutcome>,
1297    /// Complete local failed-commit envelope retained after outbox drain.
1298    /// Absent for successful and historical outcomes; never sent over wire.
1299    #[serde(skip_serializing_if = "Option::is_none")]
1300    pub operations: Option<Vec<CommitOperation>>,
1301    #[serde(skip_serializing_if = "Option::is_none")]
1302    pub retained_rows: Option<Vec<RetainedCommitRow>>,
1303    pub resolution: CommitOutcomeResolution,
1304    #[serde(skip_serializing_if = "Option::is_none")]
1305    pub resolved_at_ms: Option<i64>,
1306    #[serde(skip_serializing_if = "Option::is_none")]
1307    pub replacement_client_commit_id: Option<String>,
1308}
1309
1310#[derive(Debug, Clone, Deserialize, Default)]
1311#[serde(rename_all = "camelCase")]
1312pub struct CommitOutcomeQuery {
1313    pub limit: Option<usize>,
1314    #[serde(default)]
1315    pub active_only: bool,
1316}
1317
1318/// §7.5: the catch-up state of one unit as persisted in the snapshot, never
1319/// the mutable owner cache. `Unknown` means the client does not currently
1320/// hold the unit (never registered, released, or removed).
1321#[derive(Debug, Clone, Serialize)]
1322#[serde(
1323    tag = "state",
1324    rename_all = "camelCase",
1325    rename_all_fields = "camelCase"
1326)]
1327pub enum UnitCatchup {
1328    Unknown {
1329        id: String,
1330    },
1331    Known {
1332        id: String,
1333        status: UnitStatus,
1334        live: bool,
1335        /// The unit's cursor while it catches up, the replica cursor while live.
1336        cursor: i64,
1337        has_resume_token: bool,
1338        /// True only for an `active` unit that is live or post-bootstrap.
1339        bootstrap_complete: bool,
1340        /// True only for an `active` unit with cursor `-1` or a resume token.
1341        known_pending_pages: bool,
1342        #[serde(skip_serializing_if = "Option::is_none")]
1343        reason_code: Option<String>,
1344    },
1345}
1346
1347/// §7.5: delivery status for one client commit id. A commit still in the
1348/// outbox is `pending`; a drained commit carries its persisted retained
1349/// outcome; an id the client never held, or whose outcome was pruned by
1350/// retention, is `unknown`. The outcome preserves every operation result,
1351/// rejection code, and conflict. The owning core attaches the retained-row
1352/// images of its in-memory failed-commit cache; the read-only sidecar reports
1353/// the persisted fields.
1354#[derive(Debug, Clone, Serialize)]
1355#[serde(tag = "status", rename_all = "snake_case")]
1356pub enum CommitDelivery {
1357    Pending {
1358        #[serde(rename = "clientCommitId")]
1359        client_commit_id: String,
1360    },
1361    Known {
1362        #[serde(rename = "clientCommitId")]
1363        client_commit_id: String,
1364        outcome: CommitOutcome,
1365    },
1366    Unknown {
1367        #[serde(rename = "clientCommitId")]
1368        client_commit_id: String,
1369    },
1370}
1371
1372/// §7.5: the result of one atomic snapshot read over a single SQLite read
1373/// transaction: one revision, every requested read-only statement's rows,
1374/// requested window coverage, requested unit catch-up states, and requested
1375/// commit deliveries.
1376#[derive(Debug, Clone, Serialize)]
1377#[serde(rename_all = "camelCase")]
1378pub struct SnapshotRead {
1379    pub revision: String,
1380    pub queries: Vec<Vec<QueryRow>>,
1381    pub coverage: CoverageSnapshot,
1382    pub units: Vec<UnitCatchup>,
1383    pub deliveries: Vec<CommitDelivery>,
1384}
1385
1386#[derive(Debug, Clone, Deserialize)]
1387#[serde(rename_all = "camelCase")]
1388pub struct ResolveCommitOutcomeInput {
1389    pub client_commit_id: String,
1390    pub resolution: CommitOutcomeResolution,
1391    pub replacement_client_commit_id: Option<String>,
1392}
1393
1394#[derive(Debug, Clone, Serialize)]
1395#[serde(rename_all = "camelCase")]
1396pub struct RowState {
1397    pub row_id: String,
1398    /// Local synced version: `-1` = optimistic, else the server version
1399    /// (from a `COMMIT` change or a segment row record, §5.2/§5.6).
1400    pub version: i64,
1401    pub values: Map<String, Value>,
1402    /// §5.11 `_sync_sealed_key` of a sealed row; absent on an unsealed row.
1403    #[serde(skip_serializing_if = "Option::is_none")]
1404    pub sealed_key: Option<String>,
1405}
1406
1407/// One AND-combined application-authorized local purge target. Targets in
1408/// one input are OR-combined. Selector columns must compile to plaintext
1409/// strings; values are bounded code-like routing identifiers.
1410#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1411#[serde(rename_all = "camelCase", deny_unknown_fields)]
1412pub struct LocalDataPurgeTarget {
1413    pub table: String,
1414    pub selectors: BTreeMap<String, Vec<String>>,
1415}
1416
1417/// Durable local idempotency key plus exact routing targets. The host owns
1418/// directive authenticity and subscription gating; the client owns SQLite.
1419#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1420#[serde(rename_all = "camelCase", deny_unknown_fields)]
1421pub struct LocalDataPurgeInput {
1422    pub purge_id: String,
1423    pub targets: Vec<LocalDataPurgeTarget>,
1424}
1425
1426/// Privacy-safe local purge acknowledgement; row ids never cross the bridge.
1427#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1428#[serde(rename_all = "camelCase")]
1429pub struct LocalDataPurgeResult {
1430    pub already_applied: bool,
1431    pub purged_rows: usize,
1432    pub dropped_commits: usize,
1433}
1434
1435/// Durable application repair id. Reusing the id is an exact no-op.
1436#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1437#[serde(rename_all = "camelCase", deny_unknown_fields)]
1438pub struct LocalDataRebootstrapInput {
1439    pub rebootstrap_id: String,
1440}
1441
1442/// Privacy-safe acknowledgement for a replicated-projection recovery.
1443#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1444#[serde(rename_all = "camelCase")]
1445pub struct LocalDataRebootstrapResult {
1446    pub already_applied: bool,
1447    pub retained_commits: usize,
1448    pub reset_subscriptions: usize,
1449}
1450
1451/// Client limits (§4.2 request knobs).
1452#[derive(Debug, Clone, Default)]
1453pub struct ClientLimits {
1454    pub limit_commits: Option<i32>,
1455    pub limit_snapshot_rows: Option<i32>,
1456    pub max_snapshot_pages: Option<i32>,
1457    /// §4.2 accept bitmask; this client defaults to `0b0111` (rows
1458    /// baseline + sqlite images, §5.3 — rusqlite can always import).
1459    pub accept: Option<u8>,
1460    /// §5.9.7 B1 blob-cache size cap (bytes). When set and the sum of cached
1461    /// body sizes exceeds it, unreferenced bodies without pending work are
1462    /// evicted by creation timestamp after each cache write. `None` retains bodies
1463    /// until storage pressure (default).
1464    pub blob_cache_max_bytes: Option<i64>,
1465    /// Maximum durable final outcomes. Active conflicts/rejections are never
1466    /// pruned to satisfy the cap. Defaults to 1,000.
1467    pub outcome_retention_max_entries: Option<usize>,
1468    /// §7.1: maximum whole commits in one push request. `None` is unbounded.
1469    pub max_push_commits_per_request: Option<usize>,
1470    /// §7.1: maximum operations across the push commits in one request. `None`
1471    /// uses the reference default of 500. A first commit that alone exceeds it
1472    /// is a typed `client.push_request_too_large` capacity error and stays
1473    /// queued.
1474    pub max_push_operations_per_request: Option<usize>,
1475    /// §7.1: maximum bytes of the complete encoded SSP2 request (8-byte
1476    /// envelope, request header, push commits, pull header, units and progress frames,
1477    /// framing, and any §5.11 ciphertext). `None` is unbounded. A request whose
1478    /// fixed frames alone exceed it, or whose first commit alone does not fit,
1479    /// fails with `client.push_request_too_large` and keeps its intent.
1480    pub max_push_request_bytes: Option<usize>,
1481    /// RFC 0005 D8: the previous-version capture config. Absent or
1482    /// `enabled: false` runs the feature off (default); the descriptor write
1483    /// and the container orphan sweep still happen.
1484    pub previous_version_context: Option<PreviousVersionContextConfig>,
1485    /// Immutable, explicit preflight authority read policy.
1486    pub authority_reads: Vec<AuthorityReadDeclaration>,
1487}
1488
1489/// Static read policy; never accepted as snapshot parameters.
1490#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
1491#[serde(rename_all = "camelCase", deny_unknown_fields)]
1492pub struct AuthorityReadDeclaration {
1493    pub table: String,
1494    pub columns: Vec<String>,
1495    pub scopes: std::collections::BTreeMap<String, Vec<String>>,
1496}