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