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