Skip to main content

syncular_client/
client.rs

1//! The Syncular v2 Rust client core (SPEC.md client-behavior contract):
2//! rusqlite local storage, §3.2/§3.3 effective-scope persistence + purge,
3//! §4 pull/cursor/bootstrap (§4.7 resume, §5.6 segment application), §6
4//! push with outbox order, §7 optimistic apply / rollback / replay-on-top,
5//! §2.3 clientCommitId idempotency, §8 realtime client rules, §10 errors.
6//!
7//! Built from `SPEC.md` and the committed `ssp2` codec alone — no
8//! reference to the v1 Rust tree or the v2 TypeScript client.
9
10use crate::{ProgressObserver, ProgressPhase, ProgressState};
11use ssp2::encode_message;
12use std::borrow::Cow;
13#[cfg(test)]
14use std::cell::Cell;
15use std::cell::RefCell;
16use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
17use std::sync::Arc;
18
19use rusqlite::types::{ToSqlOutput, Value as SqlValue, ValueRef};
20use rusqlite::{Connection, OpenFlags, OptionalExtension};
21use serde::{Deserialize, Serialize};
22use serde_json::{json, Map, Value};
23use sha2::{Digest, Sha256};
24use ssp2::decode::WIRE_VERSION;
25use ssp2::model::{
26    FencedRecord, Frame, LiveStatus, MediaType, Message, MsgKind, Op, OpResult, PushStatus,
27    SubStatus,
28};
29use ssp2::primitives::RawJson;
30use ssp2::registration::canonical_scope_json;
31use ssp2::segment::{decode_rows_segment, Column, ColumnType, ColumnValue, Row, RowsSegment};
32use ssp2::{decode_message, encode_presence_publish, parse_control, ControlMessage, PresenceKind};
33
34use crate::api::{
35    AppliedServerCommit, AppliedServerCommitSource, AuthorityCoverageState, AuthorityIntent,
36    AuthorityQuery, AuthorityQueryResult, AuthorityReadResult, ClientChangeBatch,
37    ClientDiagnosticsHost, ClientDiagnosticsLease, ClientDiagnosticsReplica,
38    ClientDiagnosticsSchema, ClientDiagnosticsSnapshot, ClientDiagnosticsStorage, ClientError,
39    ClientLimits, CommandEffects, CommitDelivery, CommitOperation, CommitOperationOutcome,
40    CommitOutcome, CommitOutcomeQuery, CommitOutcomeResolution, CommitOutcomeStatus,
41    ConflictRecord, CoverageSnapshot, CurrentBaseProof, CurrentBaseProofReason,
42    DiagnosticLastChange, DiagnosticLastRound, DiagnosticQueryFailure, DiagnosticRoundCounters,
43    DiagnosticUnits, EchoRecord, FetchedBlob, LeaseState, LocalDataPurgeInput,
44    LocalDataPurgeResult, LocalDataPurgeTarget, LocalDataRebootstrapInput,
45    LocalDataRebootstrapResult, Mutation, PendingCommit, PresencePeer, PreviousVersionStatus,
46    QueryOwner, QueryReadFailure, QueryRow, QuerySnapshot, QueryValue, RejectionDetails,
47    RejectionRecord, ResolveCommitOutcomeInput, RetainedCommitRow, RetainedUniqueConflict,
48    RowState, SchemaFloor, SnapshotRead, SyncIntent, SyncOutcome, SyncReport, SyncStatusSnapshot,
49    TableChange, UnitCatchup, UnitRecord, UnitRestriction, UnitScopes, UnitStatus, WindowBase,
50    WindowChange, WindowCoverage, WindowState, WindowUnitRef, CLIENT_DIAGNOSTICS_VERSION,
51    MAX_DIAGNOSTIC_QUERY_FAILURES,
52};
53use crate::api::{RealtimePolicy, RealtimeState, REALTIME_UNAVAILABLE_CODE};
54#[cfg(feature = "bench-internals")]
55use crate::bench::{Phase, Recorder};
56use crate::previous_version::{
57    capture_previous_version_from_replica, first_incompatibility,
58    reconcile_previous_version_at_boot, set_local_schema_descriptor,
59    sweep_previous_version_container, PendingCommitAudit, PreviousVersionContextConfig,
60    PreviousVersionLifecycle, PreviousVersionReadSpec, PreviousVersionSnapshot,
61};
62mod projection;
63pub use projection::ProjectionInput;
64
65use crate::schema::{parse_schema_json, ClientSchema, TableSchema};
66use crate::transport::{BlobDownload, SegmentRequest, Transport, TransportError};
67use crate::values::{
68    bytes_to_hex, column_value_to_json, decode_row_bytes, encode_sparse_row_json, full_row_values,
69    is_canonical_bytes_envelope, json_to_column_value, json_to_scope_map, normalize_values_casing,
70    render_row_id_json, scope_map_to_json, SealedRow,
71};
72
73/// §4.2 default: rows and SQLite images, both applied in committed chunks.
74/// Bit 3 (signed URLs, §5.4) is
75/// added per transport capability at request-build time.
76const DEFAULT_ACCEPT: u8 = 0b0111;
77const ACCEPT_INLINE_ROWS: u8 = 1 << 0;
78const ACCEPT_EXTERNAL_ROWS: u8 = 1 << 1;
79const ACCEPT_SQLITE: u8 = 1 << 2;
80const ACCEPT_SIGNED_URLS: u8 = 1 << 3;
81const MAX_DIAGNOSTIC_DOMAINS: usize = 256;
82
83/// §10.1 `recommendedAction` carried by a server HTTP error body.
84fn recommended_action_of(details: &Option<Value>) -> Option<String> {
85    details
86        .as_ref()?
87        .get("recommendedAction")?
88        .as_str()
89        .map(str::to_owned)
90}
91
92/// §7.4.1 persisted local schema-version marker (`_syncular_meta` key).
93pub(crate) const LOCAL_SCHEMA_VERSION_KEY: &str = "localSchemaVersion";
94const LOCAL_REVISION_KEY: &str = "localRevision";
95/// §4.5 replica cursor; absent means `-1`.
96const REPLICA_CURSOR_KEY: &str = "replicaCursor";
97/// Hex of the last pull `LIVE_END.echoDigest` (§4.2); absent means empty.
98const ECHO_DIGEST_KEY: &str = "echoDigest";
99/// Hex of the registration digest of the list the server stores (§4.1).
100const REGISTERED_DIGEST_KEY: &str = "registrationDigest";
101/// §7.4.3: table name → generation, persisted with the declaration evidence.
102const TABLE_GENERATIONS_KEY: &str = "localTableGenerations";
103/// §7.1: the identity of the outbox sequence.
104const OUTBOX_ID_KEY: &str = "outboxId";
105const CLIENT_ID_KEY: &str = "clientId";
106const LEASE_STATE_KEY: &str = "leaseState";
107const SCHEMA_FLOOR_KEY: &str = "schemaFloor";
108pub(crate) const LOG_EPOCH_KEY: &str = "logEpoch";
109/// Persisted fail-closed quarantine marker: present while a security preflight
110/// is pending and `activateSecurity` has yet to run. Storing it in the replica
111/// keeps the gate with the data it protects, so a rebuilt host handle reopening
112/// the same file returns in preflight even though its in-memory state is fresh.
113const SECURITY_PREFLIGHT_PENDING_KEY: &str = "securityPreflightPending";
114const LOCAL_REBOOTSTRAP_RECEIPT_VERSION: u8 = 2;
115const MAX_JS_SAFE_INTEGER: u64 = 9_007_199_254_740_991;
116/// §7.4.4 client-local code: a pending outbox commit cannot re-encode under
117/// the new schema after a bump. Never a wire code (§10.3).
118const OUTBOX_INCOMPATIBLE_CODE: &str = "sync.outbox_incompatible";
119/// §5.11: the first-open repair's erasure record (`<key>:erased`).
120const PURGE_REPAIR_KEY: &str = "localPurgeRepair";
121/// §5.11 client-local code: an encode at the push seam resolved no usable key
122/// id or named an unknown key. Never a wire code (§10.3).
123const ENCRYPT_FAILED_CODE: &str = "client.encrypt_failed";
124const INVALID_REQUEST_CODE: &str = "sync.invalid_request:";
125/// §7.4.4: static text for a persisted commit the current codec refuses.
126const LEGACY_VALUE_REFUSAL_MESSAGE: &str =
127    "the persisted commit carries values the current codec refuses";
128/// §7.4.4: bounded reason on every intrinsic value drop.
129const INVALID_STORED_VALUES_REASON: &str = "invalid_stored_values";
130/// §7.2.2: an outcome with a pending decision accepts no other resolution.
131const REPLACEMENT_PENDING: &str =
132    "client.replacement_pending: the outcome has a pending replacement";
133/// §7.2.2 client-local code: a pending replacement was not written.
134const REPLACEMENT_REFUSED_CODE: &str = "sync.replacement_refused";
135/// §7.2.1/§7.2.3 client-local journal result of a replaced commit's operations.
136const COMMIT_REPLACED_CODE: &str = "client.commit_replaced";
137
138#[derive(Debug, Serialize, Deserialize)]
139#[serde(rename_all = "camelCase", deny_unknown_fields)]
140struct PersistedLocalDataRebootstrapReceipt {
141    version: u8,
142    retained_commits: u64,
143    reset_subscriptions: u64,
144}
145
146fn invalid_local_rebootstrap_receipt() -> String {
147    "sync.local_corrupt: persisted local rebootstrap receipt is invalid".to_owned()
148}
149
150fn encode_local_rebootstrap_receipt(
151    retained_commits: usize,
152    reset_subscriptions: usize,
153) -> Result<String, String> {
154    let retained_commits =
155        u64::try_from(retained_commits).map_err(|_| invalid_local_rebootstrap_receipt())?;
156    let reset_subscriptions =
157        u64::try_from(reset_subscriptions).map_err(|_| invalid_local_rebootstrap_receipt())?;
158    if retained_commits > MAX_JS_SAFE_INTEGER || reset_subscriptions > MAX_JS_SAFE_INTEGER {
159        return Err(invalid_local_rebootstrap_receipt());
160    }
161    serde_json::to_string(&PersistedLocalDataRebootstrapReceipt {
162        version: LOCAL_REBOOTSTRAP_RECEIPT_VERSION,
163        retained_commits,
164        reset_subscriptions,
165    })
166    .map_err(|_| invalid_local_rebootstrap_receipt())
167}
168
169fn decode_local_rebootstrap_receipt(value: &str) -> Result<(usize, usize), String> {
170    // Pre-0.15.36 markers proved application but did not retain the receipt.
171    if value == "v1" {
172        return Ok((0, 0));
173    }
174    let receipt: PersistedLocalDataRebootstrapReceipt =
175        serde_json::from_str(value).map_err(|_| invalid_local_rebootstrap_receipt())?;
176    if receipt.version != LOCAL_REBOOTSTRAP_RECEIPT_VERSION
177        || receipt.retained_commits > MAX_JS_SAFE_INTEGER
178        || receipt.reset_subscriptions > MAX_JS_SAFE_INTEGER
179    {
180        return Err(invalid_local_rebootstrap_receipt());
181    }
182    Ok((
183        usize::try_from(receipt.retained_commits)
184            .map_err(|_| invalid_local_rebootstrap_receipt())?,
185        usize::try_from(receipt.reset_subscriptions)
186            .map_err(|_| invalid_local_rebootstrap_receipt())?,
187    ))
188}
189
190#[cfg(test)]
191mod observation_tests;
192
193/// Internal state for hosts that perform network I/O outside the client owner.
194#[doc(hidden)]
195#[derive(Clone)]
196pub struct CurrentBasePreparation {
197    client_commit_id: String,
198    sequence: i64,
199    /// §7.2.2: the pending replacement a drive evaluates; `None` for
200    /// `proveCurrentBase`.
201    replacement: Option<String>,
202    units: Vec<UnitRecord>,
203    transport_epoch: u64,
204    registration_epoch: u64,
205    security_epoch: u64,
206}
207
208#[cfg(test)]
209mod units_tests;
210
211#[cfg(test)]
212mod replace_outcome_tests;
213
214#[cfg(test)]
215mod pending_replacement_tests;
216
217/// A §6.12 fence round that [`SyncClient::prepare_pending_commit_replacement`]
218/// prepared on the owner. Send [`PreparedFenceRound::request_bytes`] as a sync
219/// request (over the realtime socket when [`PreparedFenceRound::realtime`] is
220/// set) and hand the reply to [`SyncClient::apply_fence_round`]; a host with a
221/// blocking [`Transport`] calls [`PreparedFenceRound::exchange`].
222pub struct PreparedFenceRound {
223    id: uuid::Uuid,
224    client_commit_id: String,
225    replacement_client_commit_id: String,
226    operations: Vec<OutboxOp>,
227    request: Vec<u8>,
228    realtime: bool,
229}
230
231impl PreparedFenceRound {
232    pub fn request_bytes(&self) -> &[u8] {
233        &self.request
234    }
235
236    pub fn realtime(&self) -> bool {
237        self.realtime
238    }
239
240    /// Send the request without accessing client state.
241    pub fn exchange(&self, transport: &mut dyn Transport) -> Result<Vec<u8>, TransportError> {
242        if self.realtime {
243            transport.realtime_sync(&self.request)
244        } else {
245            transport.sync(&self.request)
246        }
247    }
248}
249
250#[derive(Debug, Clone)]
251struct OutboxOp {
252    upsert: bool,
253    table: String,
254    row_id: String,
255    base_version: Option<i64>,
256    /// Schema-agnostic local form (§0): driver JSON values, encoded with
257    /// the current codec at send time. A key's presence IS the §6.1 sparse
258    /// presence set — both the overlay and the wire payload derive from it.
259    values: Option<Map<String, Value>>,
260    /// §7.1 insert intent: `mutate` recorded this upsert while the row was
261    /// absent from the visible replica. Replay and send-time encoding present
262    /// every current-schema column; a column `values` lacks is NULL.
263    insert: bool,
264}
265
266impl OutboxOp {
267    /// The values this upsert presents under the current `table` (§7.1). An
268    /// insert-intent operation presents every column, a missing one as NULL;
269    /// `None` when a missing column is non-nullable, which leaves the commit
270    /// unencodable (§7.4.4), or when the operation carries no values.
271    fn presented_values(&self, table: &TableSchema) -> Option<Cow<'_, Map<String, Value>>> {
272        let values = self.values.as_ref()?;
273        if !self.insert || table.columns.iter().all(|c| values.contains_key(&c.name)) {
274            return Some(Cow::Borrowed(values));
275        }
276        full_row_values(table, values.clone()).ok().map(Cow::Owned)
277    }
278}
279
280impl From<CommitOperation> for OutboxOp {
281    fn from(operation: CommitOperation) -> Self {
282        Self {
283            upsert: operation.op == "upsert",
284            table: operation.table,
285            row_id: operation.row_id,
286            base_version: operation.base_version,
287            values: operation.values,
288            insert: operation.insert,
289        }
290    }
291}
292
293/// §7.5 static authoring refusal; the table and column travel in details.
294fn invalid_authoring(message: &str, details: Value) -> ClientError {
295    ClientError {
296        code: "sync.invalid_request".to_owned(),
297        message: message.to_owned(),
298        details: Some(details),
299        retryable: false,
300    }
301}
302
303/// §7.1 chained base: `later` repeats `earlier`'s positive base on the same
304/// row and presents only columns `earlier` presents.
305fn chains_on(earlier: &OutboxOp, later: &OutboxOp) -> bool {
306    // Only an upsert carries values, and it always carries its primary key.
307    earlier.row_id == later.row_id
308        && earlier.table == later.table
309        && later.base_version.is_some_and(|base| base > 0)
310        && earlier.base_version == later.base_version
311        && later.values.as_ref().is_some_and(|values| {
312            values.keys().all(|column| {
313                earlier
314                    .values
315                    .as_ref()
316                    .is_some_and(|earlier| earlier.contains_key(column))
317            })
318        })
319}
320
321impl From<&OutboxOp> for CommitOperation {
322    fn from(operation: &OutboxOp) -> Self {
323        Self {
324            table: operation.table.clone(),
325            row_id: operation.row_id.clone(),
326            op: if operation.upsert { "upsert" } else { "delete" }.to_owned(),
327            base_version: operation.base_version,
328            values: operation.values.clone(),
329            insert: operation.insert,
330        }
331    }
332}
333
334#[derive(Debug, Clone)]
335struct OutboxCommit {
336    client_commit_id: String,
337    ops: Vec<OutboxOp>,
338}
339
340/// One commit's `(table, value keys, insert intent)` per upsert operation — the classification
341/// shape the §7.4.4 send-time drop and the RFC 0005 D6 audit share, so the two
342/// can never disagree about which commits cannot re-encode.
343fn commit_audit_operations(commit: &OutboxCommit) -> Vec<(&str, Vec<&str>, bool)> {
344    commit
345        .ops
346        .iter()
347        .filter(|operation| operation.upsert)
348        .map(|operation| {
349            (
350                operation.table.as_str(),
351                operation
352                    .values
353                    .as_ref()
354                    .map(|values| values.keys().map(String::as_str).collect())
355                    .unwrap_or_default(),
356                operation.insert,
357            )
358        })
359        .collect()
360}
361
362type FailedCommit = (OutboxCommit, Map<String, Value>);
363
364#[derive(Debug, Clone)]
365struct CompiledLocalDataPurgeTarget {
366    table: String,
367    selectors: Vec<(String, Vec<String>)>,
368}
369
370struct CompiledLocalDataPurge {
371    targets: Vec<CompiledLocalDataPurgeTarget>,
372    projections: BTreeSet<String>,
373    canonical_plan: String,
374}
375
376struct StoredCommitOutcomeRow {
377    sequence: i64,
378    client_commit_id: String,
379    status: String,
380    recorded_at_ms: i64,
381    results_json: String,
382    operations_json: Option<String>,
383    resolution: String,
384    resolved_at_ms: Option<i64>,
385    replacement_client_commit_id: Option<String>,
386}
387
388impl StoredCommitOutcomeRow {
389    fn from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Self> {
390        Ok(Self {
391            sequence: row.get(0)?,
392            client_commit_id: row.get(1)?,
393            status: row.get(2)?,
394            recorded_at_ms: row.get(3)?,
395            results_json: row.get(4)?,
396            operations_json: row.get(5)?,
397            resolution: row.get(6)?,
398            resolved_at_ms: row.get(7)?,
399            replacement_client_commit_id: row.get(8)?,
400        })
401    }
402}
403
404/// Section outcome distinguishing the §5.6 unit-local fail-closed
405/// path from a round-aborting failure (§1.4 rule 5).
406/// §4.4 a unit section's `SUB_START`.
407struct SectionStart {
408    id: String,
409    status: SubStatus,
410    reason_code: String,
411    bootstrap: bool,
412    fenced: Vec<FencedRecord>,
413}
414
415enum SectionError {
416    FailClosed,
417    /// §5.5: the server refused a segment with `sync.forbidden`.
418    Refused,
419    /// §5.3 client memory: the round deferred this image's body to a later
420    /// pull of the same resume token.
421    Deferred,
422    Abort(String, String),
423    Transport(TransportError),
424}
425
426#[derive(Debug)]
427pub(crate) struct RequestMeta {
428    pushed_ids: Vec<String>,
429    /// Hex of the registration digest this pull carried; the server stores
430    /// that list once the round completes (§4.1).
431    registration_digest: String,
432    pub(crate) accept: u8,
433    /// §6.1 splitBatch: outbox commits held back from THIS request because
434    /// the running operation count reached the push cap — the next round
435    /// pushes them (`sync_needed` stays set while any remain).
436    deferred_commits: usize,
437    /// §5.6 applied-segment record per unit: segment id → rows applied at
438    /// the unit's current cursor and token.
439    pub(crate) applied: BTreeMap<String, BTreeMap<String, i64>>,
440    /// §5.3 client memory: (unit, segment id) of the first image whose body
441    /// the round did not fetch because the batch already holds two images.
442    /// That unit's section stops there without persisting `SUB_END`.
443    pub(crate) deferred: BTreeSet<(String, String)>,
444}
445
446#[derive(Default)]
447struct ChangeAccumulator {
448    /// None means table-wide; Some is the exact scoped domain.
449    tables: BTreeMap<String, Option<BTreeSet<String>>>,
450    windows: BTreeMap<String, BTreeSet<String>>,
451    status: bool,
452    conflicts: bool,
453    rejections: bool,
454    outcomes: bool,
455}
456
457impl ChangeAccumulator {
458    fn table(&mut self, table: &str) {
459        self.tables.insert(table.to_owned(), None);
460    }
461
462    fn scope(&mut self, table: &str, key: String) {
463        match self.tables.get_mut(table) {
464            Some(None) => {}
465            Some(Some(keys)) => {
466                keys.insert(key);
467            }
468            None => {
469                self.tables
470                    .insert(table.to_owned(), Some(BTreeSet::from([key])));
471            }
472        }
473    }
474
475    fn window(&mut self, base_key: &str, value: &str) {
476        self.windows
477            .entry(base_key.to_owned())
478            .or_default()
479            .insert(value.to_owned());
480    }
481
482    fn touched(&self) -> bool {
483        !self.tables.is_empty()
484            || !self.windows.is_empty()
485            || self.status
486            || self.conflicts
487            || self.rejections
488            || self.outcomes
489    }
490}
491
492/// §6.1: the server caps total operations per request (reference default
493/// 500) and rejects the whole batch with `sync.too_many_operations`; the
494/// client "splits and retries". Splitting happens at build time: commits are
495/// included IN ORDER until the operation budget is spent, the rest wait for
496/// the next round.
497const PUSH_OPS_PER_REQUEST: usize = 500;
498const MAX_LOCAL_PURGE_TARGETS: usize = 64;
499const MAX_LOCAL_PURGE_SELECTORS: usize = 8;
500const MAX_LOCAL_PURGE_VALUES: usize = 128;
501const MAX_LOCAL_PURGE_VALUE_LENGTH: usize = 256;
502pub const SECURITY_PREFLIGHT_REQUIRED_CODE: &str = "client.security_preflight_required";
503
504/// Dirty visible tables; `None` means a whole-replica recovery/reset.
505struct OverlayDirty(RefCell<Option<BTreeSet<String>>>);
506
507impl OverlayDirty {
508    fn clean() -> Self {
509        Self(RefCell::new(Some(BTreeSet::new())))
510    }
511    fn get(&self) -> bool {
512        self.0
513            .borrow()
514            .as_ref()
515            .is_none_or(|tables| !tables.is_empty())
516    }
517    fn set(&self, dirty: bool) {
518        *self.0.borrow_mut() = if dirty { None } else { Some(BTreeSet::new()) };
519    }
520    fn table(&self, table: &str) {
521        if let Some(tables) = self.0.borrow_mut().as_mut() {
522            tables.insert(table.to_owned());
523        }
524    }
525    fn snapshot(&self) -> Option<BTreeSet<String>> {
526        self.0.borrow().clone()
527    }
528    fn restore(&self, tables: Option<BTreeSet<String>>) {
529        *self.0.borrow_mut() = tables;
530    }
531}
532
533/// A copy-on-write in-memory mirror: a [`Rollback`] shares it, and the first
534/// write after a capture copies it once.
535#[derive(Debug, Clone, Default)]
536struct Shared<T>(Arc<T>);
537
538impl<T> std::ops::Deref for Shared<T> {
539    type Target = T;
540    fn deref(&self) -> &T {
541        &self.0
542    }
543}
544
545impl<T: Clone> std::ops::DerefMut for Shared<T> {
546    fn deref_mut(&mut self) -> &mut T {
547        Arc::make_mut(&mut self.0)
548    }
549}
550
551impl<T> From<T> for Shared<T> {
552    fn from(value: T) -> Self {
553        Self(Arc::new(value))
554    }
555}
556
557/// The in-memory mirrors of durable state, captured before a local
558/// transaction and restored when it rolls back. Queues only grow inside a
559/// transaction, so their lengths suffice.
560#[derive(Debug, Clone)]
561struct Rollback {
562    outbox: Shared<Vec<Arc<OutboxCommit>>>,
563    failed_commits: Shared<Vec<FailedCommit>>,
564    conflicts: Shared<Vec<ConflictRecord>>,
565    rejections: Shared<Vec<RejectionRecord>>,
566    schema_floor: Option<SchemaFloor>,
567    lease_state: Option<LeaseState>,
568    stopped: bool,
569    upgrading: bool,
570    upgrade_kept_tables: bool,
571    sync_needed: bool,
572    active_round: Option<(uuid::Uuid, i64, u64)>,
573    overlay_dirty: Option<BTreeSet<String>>,
574    transport_gate: crate::TransportGate,
575    transport_epoch: u64,
576    change_queue: usize,
577    projection_pending_queue: usize,
578    sync_intent_queue: usize,
579    last_change: Option<DiagnosticLastChange>,
580}
581
582pub struct SyncClient {
583    #[cfg(feature = "bench-internals")]
584    benchmark_phases: Recorder,
585    conn: Connection,
586    schema: ClientSchema,
587    client_id: String,
588    limits: ClientLimits,
589    outbox: Shared<Vec<Arc<OutboxCommit>>>,
590    failed_commits: Shared<Vec<FailedCommit>>,
591    retain_failed_commits: bool,
592    conflicts: Shared<Vec<ConflictRecord>>,
593    rejections: Shared<Vec<RejectionRecord>>,
594    schema_floor: Option<SchemaFloor>,
595    /// §7.3.5: the opaque auth-lease state (from LEASE frames + lease errors).
596    lease_state: Option<LeaseState>,
597    /// §1.6: the schema-floor response stops syncing until an upgrade.
598    stopped: bool,
599    /// §7.4.5: true while a schema-bump reset + first re-bootstrap is in flight.
600    upgrading: bool,
601    /// §7.4.5: the running reset kept at least one table.
602    upgrade_kept_tables: bool,
603    /// §8.4 coalesced sync-needed signal.
604    sync_needed: bool,
605    /// §8.8: how sync rounds treat the realtime binding, and its exact
606    /// availability state with the evidence behind a lost or refused one.
607    realtime_policy: RealtimePolicy,
608    realtime_state: RealtimeState,
609    realtime_reason_code: Option<String>,
610    realtime_retry_delay_ms: Option<u64>,
611    /// §8.6 presence: scopeKey → (`actorId clientId` peer key → peer).
612    presence: HashMap<String, HashMap<String, PresencePeer>>,
613    /// Client clock (epoch ms) for the §5.4 `urlExpiresAtMs` check and the
614    /// §7.8 drive deadline; the host may pin it and move the pinned value
615    /// (conformance runs on a virtual clock).
616    now_ms: Option<std::sync::Arc<std::sync::atomic::AtomicI64>>,
617    /// §5.11 client-side encryption keys (`keyId → key bytes`). Empty ⇒ E2EE
618    /// off. The encrypt/decrypt seam (`values.rs`) is compiled only under the
619    /// `e2ee` feature; without it, a schema with encrypted columns fails loud.
620    encryption: crate::values::EncryptionConfig,
621    /// Fail-closed host bootstrap gate. While set, command hosts permit only
622    /// status/lifecycle inspection and an exact authorized local purge.
623    security_preflight: bool,
624    security_epoch: u64,
625    transport_gate: crate::TransportGate,
626    transport_epoch: u64,
627    /// Raised by every registration change; a current-base proof spanning
628    /// one reports missing coverage.
629    registration_epoch: u64,
630    /// RFC 0005 D2/D8: the previous-version capture config. `None` (default)
631    /// means the feature is off; the descriptor write and the container orphan
632    /// sweep still happen.
633    previous_version: Option<PreviousVersionContextConfig>,
634    /// Per-table primary-key upsert SQL, built once per (full table name) —
635    /// the row write path runs per row during bootstrap (§5.6), so the SQL
636    /// string (and, via `prepare_cached`, its compiled statement) is reused
637    /// instead of being rebuilt and re-prepared per row. Cleared on a §7.4.3
638    /// schema reset (the column lists may have changed).
639    insert_sql: RefCell<HashMap<String, String>>,
640    /// §7.1: reconcile only tables whose base/outbox changed. Whole-replica
641    /// reset and restart explicitly invalidate every table.
642    overlay_dirty: OverlayDirty,
643    // First SQLite failure of the current operation, before savepoint cleanup.
644    storage_failure: RefCell<Option<QueryReadFailure>>,
645    /// Test-only structural performance signal: response processing must not
646    /// turn a batch of acknowledgements into one full overlay rebuild each.
647    #[cfg(test)]
648    overlay_rebuild_count: Cell<usize>,
649    #[cfg(test)]
650    acknowledged_replay_count: Cell<usize>,
651    /// Test-only structural performance signal: outcome retention is enforced
652    /// once per response rather than once per acknowledgement.
653    #[cfg(test)]
654    outcome_prune_count: Cell<usize>,
655    /// Test-only pinned time of every §5.3 image chunk, in ms: fixed write
656    /// time, write time per row, and commit time.
657    #[cfg(test)]
658    image_chunk_ms: Cell<Option<(f64, f64, f64)>>,
659    /// Exact observer-transaction output drained by command/FFI hosts.
660    progress: ProgressObserver,
661    /// §7.6: random per core instance, never persisted or sent.
662    epoch: String,
663    change_queue: VecDeque<ClientChangeBatch>,
664    projection_pending_queue: VecDeque<String>,
665    opening_replica: bool,
666    sync_intent_queue: VecDeque<SyncIntent>,
667    /// §8.7 `scopes` events received since the last drain.
668    scopes_changed: usize,
669    /// §3.3: units `set_window` registered or re-armed and no round accepted since.
670    window_armed: HashSet<String>,
671    /// Explicit exponential retry policy for transient transport failures.
672    retry_delay_ms: u64,
673    /// §7.7: the background retry the current round scheduled, if any.
674    round_retry_delay_ms: Option<u64>,
675    /// §5.3: a table's next image chunk size, carried from one range image
676    /// of the table to the next.
677    image_chunk_rows: HashMap<String, u32>,
678    /// A round whose response never completed (§1.5): the client keeps its
679    /// code and reports it on every following request until a round receives a
680    /// complete, decodable response. The server already recorded the round, so
681    /// nothing else can tell it the round failed on this side.
682    round_failure: Option<String>,
683    /// The in-flight round: its id, `started_at_ms` and progress attempt.
684    active_round: Option<(uuid::Uuid, i64, u64)>,
685    /// The in-flight §6.12 fence round, serialized with sync rounds.
686    fence_round: Option<uuid::Uuid>,
687    last_round: Option<DiagnosticLastRound>,
688    last_change: Option<DiagnosticLastChange>,
689    /// §7.6: latest failed owned snapshot read per owner id, oldest first.
690    query_failures: Vec<DiagnosticQueryFailure>,
691    /// SPEC §1.4 rule 4: the open coalesced apply transaction of a response.
692    coalesced: Option<CoalescedApply>,
693    /// A coalesced apply transaction of the current response failed; every
694    /// later observation of that response fails until it ends.
695    coalesced_failure: Option<String>,
696}
697
698/// SPEC §1.4 rule 4: the frames and blocks of one response share one local
699/// write transaction of at most `COALESCED_APPLY_ROWS` rows. The in-memory
700/// state captured at its `BEGIN` is restored when its `COMMIT` fails.
701struct CoalescedApply {
702    rows: usize,
703    rollback: Rollback,
704}
705
706const COALESCED_APPLY_ROWS: usize = 1024;
707
708pub(crate) fn quote_ident(name: &str) -> String {
709    format!("\"{}\"", name.replace('"', "\"\""))
710}
711/// §7.4.1 `_syncular_meta` helpers. Free functions so RFC 0005's
712/// previous-version module reads and writes the SAME records as the client
713/// instead of growing a parallel meta layer.
714pub(crate) fn meta_get(conn: &Connection, key: &str) -> rusqlite::Result<Option<String>> {
715    conn.query_row(
716        "SELECT value FROM _syncular_meta WHERE key = ?1",
717        rusqlite::params![key],
718        |row| row.get::<_, String>(0),
719    )
720    .optional()
721}
722
723pub(crate) fn meta_set(conn: &Connection, key: &str, value: &str) -> rusqlite::Result<()> {
724    conn.execute(
725        "INSERT OR REPLACE INTO _syncular_meta (key, value) VALUES (?1, ?2)",
726        rusqlite::params![key, value],
727    )
728    .map(|_| ())
729}
730
731pub(crate) fn meta_delete(conn: &Connection, key: &str) -> rusqlite::Result<()> {
732    conn.execute(
733        "DELETE FROM _syncular_meta WHERE key = ?1",
734        rusqlite::params![key],
735    )
736    .map(|_| ())
737}
738
739/// Seek by the existing key while retaining the exact legacy text match.
740fn row_id_predicate(table: &TableSchema) -> String {
741    let key = quote_ident(&table.primary_key);
742    let text_match = format!("CAST({key} AS TEXT) = ?1");
743    match table.columns[table.pk_index].ty {
744        ColumnType::String | ColumnType::Json => {
745            format!("{key} = ?1 AND {text_match}")
746        }
747        // Native columns have no declared SQLite affinity. Match the stored
748        // integer bind type explicitly. Unary + removes expression affinity so
749        // SQLite can seek the typeless key; the text check preserves exact IDs.
750        ColumnType::Integer | ColumnType::Boolean => {
751            format!("{key} = +CAST(?1 AS INTEGER) AND {text_match}")
752        }
753        // REAL-to-text conversion can round distinct values to the same text.
754        // Narrowing those matches by numeric equality would change behavior.
755        _ => text_match,
756    }
757}
758
759/// §3.3/§4.8/§5.6 row ownership: rows whose local scope columns match
760/// `effective` and that no entry of `owners` matches. `owners` holds the
761/// pair scopes of every owner of the table (§3.3 row ownership); a scoped delete never removes a row one of them still covers.
762/// Scope values bind by the column's declared type, as `row_id_predicate`
763/// does. `Ok(None)` matches nothing (an empty map or value list); `Err(())`
764/// is a missing local scope-column mapping (the fail-closed case).
765fn local_scope_predicate(
766    table: &TableSchema,
767    effective: &[(String, Vec<String>)],
768    owners: &[Vec<(String, Vec<String>)>],
769) -> Result<Option<(String, Vec<SqlValue>)>, ()> {
770    if effective.is_empty() || effective.iter().any(|(_, values)| values.is_empty()) {
771        return Ok(None);
772    }
773    let column = |variable: &str| {
774        let name = table.scope_column(variable).ok_or(())?;
775        let column = table
776            .columns
777            .iter()
778            .find(|column| column.name == name)
779            .ok_or(())?;
780        Ok((quote_ident(name), column.ty == ColumnType::Integer))
781    };
782    let mut clauses = Vec::new();
783    let mut params = Vec::new();
784    for (variable, values) in effective {
785        let (key, integer) = column(variable)?;
786        let holes = vec!["?"; values.len()].join(", ");
787        clauses.push(if integer {
788            params.extend(values.iter().cloned().map(SqlValue::Text));
789            let seek = vec!["+CAST(? AS INTEGER)"; values.len()].join(", ");
790            format!("{key} IN ({seek}) AND CAST({key} AS TEXT) IN ({holes})")
791        } else {
792            format!("{key} IN ({holes})")
793        });
794        params.extend(values.iter().cloned().map(SqlValue::Text));
795    }
796    // Owners bind as one JSON parameter per variable set, so the statement
797    // keeps its size at any owner count; owners of one variable bind the
798    // union of their values. An owner holding other values of a variable
799    // `effective` names owns none of its rows and drops out. Values compare
800    // as text, the exact semantics of the effective clauses.
801    let mut groups: BTreeMap<Vec<&str>, Vec<Vec<&[String]>>> = BTreeMap::new();
802    for owner in owners {
803        if owner.is_empty()
804            || owner.iter().any(|(variable, values)| {
805                values.is_empty()
806                    || effective.iter().any(|(name, wanted)| {
807                        name == variable && wanted.iter().all(|value| !values.contains(value))
808                    })
809            })
810        {
811            continue;
812        }
813        let mut owner: Vec<_> = owner.iter().collect();
814        owner.sort_by(|a, b| a.0.cmp(&b.0));
815        groups
816            .entry(
817                owner
818                    .iter()
819                    .map(|(variable, _)| variable.as_str())
820                    .collect(),
821            )
822            .or_default()
823            .push(owner.iter().map(|(_, values)| values.as_slice()).collect());
824    }
825    let within = |variable: &str, list: &str| {
826        let (key, integer) = column(variable)?;
827        let key = if integer {
828            format!("CAST({key} AS TEXT)")
829        } else {
830            key
831        };
832        Ok(format!("{key} IN (SELECT value FROM json_each({list}))"))
833    };
834    for (variables, tuples) in groups {
835        if let [variable] = variables[..] {
836            let values: BTreeSet<&String> = tuples.iter().flatten().copied().flatten().collect();
837            params.push(SqlValue::Text(
838                Value::from_iter(values.into_iter().cloned()).to_string(),
839            ));
840            clauses.push(format!("NOT {}", within(variable, "?")?));
841        } else {
842            params.push(SqlValue::Text(
843                serde_json::to_string(&tuples).expect("owner tuples serialize"),
844            ));
845            let matches = variables
846                .iter()
847                .enumerate()
848                .map(|(index, variable)| within(variable, &format!("o.value,'$[{index}]'")))
849                .collect::<Result<Vec<_>, ()>>()?;
850            clauses.push(format!(
851                "NOT EXISTS (SELECT 1 FROM json_each(?) o WHERE {})",
852                matches.join(" AND ")
853            ));
854        }
855    }
856    Ok(Some((clauses.join(" AND "), params)))
857}
858
859/// [`local_scope_predicate`] over decoded row values (retained rows).
860fn owns_local_row(
861    table: &TableSchema,
862    effective: &[(String, Vec<String>)],
863    owners: &[Vec<(String, Vec<String>)>],
864    values: &Map<String, Value>,
865) -> bool {
866    let matches = |scopes: &[(String, Vec<String>)]| {
867        !scopes.is_empty()
868            && scopes.iter().all(|(variable, allowed)| {
869                table
870                    .scope_column(variable)
871                    .and_then(|column| values.get(column))
872                    .filter(|value| !value.is_null())
873                    .is_some_and(|value| {
874                        allowed.contains(
875                            &value
876                                .as_str()
877                                .map_or_else(|| value.to_string(), str::to_owned),
878                        )
879                    })
880            })
881    };
882    matches(effective) && !owners.iter().any(|owner| matches(owner))
883}
884
885fn is_local_operation_code_like(value: &str) -> bool {
886    let bytes = value.as_bytes();
887    bytes.first().is_some_and(u8::is_ascii_alphanumeric)
888        && bytes
889            .iter()
890            .all(|byte| byte.is_ascii_alphanumeric() || matches!(*byte, b'.' | b'_' | b':' | b'-'))
891}
892
893fn base_table(name: &str) -> String {
894    quote_ident(&format!("_syncular_base_{name}"))
895}
896
897/// §4.8 deferred eviction record: (unit id, table, effective scope map).
898type PendingEvict = (String, String, Vec<(String, Vec<String>)>);
899
900/// §4.8: a stable key for a window base: variable + canonical fixed scopes.
901fn window_base_key(base: &WindowBase) -> String {
902    format!(
903        "{}\0{}",
904        base.variable,
905        ssp2::registration::canonical_unit_json(&scope_pairs(&base.fixed_scopes))
906    )
907}
908
909/// The unit of one window value: the fixed scopes plus the value.
910fn window_unit_scopes(base: &WindowBase, value: &str) -> UnitScopes {
911    let mut scopes = base.fixed_scopes.clone();
912    scopes.insert(base.variable.clone(), value.to_owned());
913    scopes
914}
915
916/// A unit's scope map as the codec and the digests take it.
917fn scope_pairs(scopes: &UnitScopes) -> Vec<(String, String)> {
918    let mut pairs: Vec<(String, String)> = scopes
919        .iter()
920        .map(|(variable, value)| (variable.clone(), value.clone()))
921        .collect();
922    pairs.sort_by(|a, b| a.0.encode_utf16().cmp(b.0.encode_utf16()));
923    pairs
924}
925
926/// §4.1: the unit covers every table declaring all of its variables.
927fn covers(table: &TableSchema, scopes: &UnitScopes) -> bool {
928    scopes
929        .keys()
930        .all(|variable| table.scope_column(variable).is_some())
931}
932
933/// §4.4: the effective scopes of the (unit, table) pair under `echo`: the
934/// scope map as one-element lists plus the fenced lists. `None` when the
935/// fence revoked the pair.
936fn pair_scopes(
937    scopes: &UnitScopes,
938    table: &str,
939    echo: Option<&[EchoRecord]>,
940) -> Option<Vec<(String, Vec<String>)>> {
941    let fenced = echo.and_then(|echo| echo.iter().find(|record| record.table == table));
942    if fenced.is_some_and(|record| record.status == "revoked") {
943        return None;
944    }
945    let mut effective: BTreeMap<String, Vec<String>> = fenced
946        .map(|record| record.scopes.clone())
947        .unwrap_or_default();
948    for (variable, value) in scopes {
949        effective.insert(variable.clone(), vec![value.clone()]);
950    }
951    Some(effective.into_iter().collect())
952}
953
954/// §7.5 subset rule for one coverage value of `table`: its authority state
955/// (`complete`, `pending`, `missing` or `revoked`) and whether a candidate is
956/// `revoked`. A candidate is a persisted unit whose variables are a subset of
957/// the entry's and whose values equal the entry's on them. `declared` also
958/// requires that the table declares every variable of the unit; the read
959/// sidecar holds no schema, and there the subset of the entry's variables,
960/// which the table declares, implies it.
961fn entry_coverage(
962    units: &[UnitRecord],
963    table: &str,
964    declared: Option<&TableSchema>,
965    base: &WindowBase,
966    value: &str,
967) -> (&'static str, bool) {
968    let entry = window_unit_scopes(base, value);
969    let candidates: Vec<&UnitRecord> = units
970        .iter()
971        .filter(|unit| {
972            declared.is_none_or(|schema| covers(schema, &unit.scopes))
973                && unit
974                    .scopes
975                    .iter()
976                    .all(|(variable, held)| entry.get(variable) == Some(held))
977        })
978        .collect();
979    let complete = candidates.iter().any(|unit| {
980        unit.status == UnitStatus::Active
981            && !unit.bootstrapping()
982            && unit.echo.is_some()
983            && pair_scopes(&unit.scopes, table, unit.echo.as_deref()).is_some_and(|effective| {
984                entry
985                    .keys()
986                    .filter(|variable| !unit.scopes.contains_key(*variable))
987                    .all(|variable| {
988                        effective
989                            .iter()
990                            .find(|(name, _)| name == variable)
991                            .is_none_or(|(_, values)| values.iter().any(|held| held == "*"))
992                    })
993            })
994    });
995    let revoked = candidates
996        .iter()
997        .any(|unit| unit.status == UnitStatus::Revoked);
998    let state = if complete {
999        "complete"
1000    } else if candidates.is_empty() {
1001        "missing"
1002    } else if candidates
1003        .iter()
1004        .any(|unit| matches!(unit.status, UnitStatus::Revoked | UnitStatus::Failed))
1005    {
1006        "revoked"
1007    } else {
1008        "pending"
1009    };
1010    (state, revoked)
1011}
1012
1013/// §3.3 row ownership: the pair scopes of every owner of `table` except
1014/// `except_id`. An owner is active with a persisted echo and live or
1015/// post-bootstrap, or bootstrapping with a segment of the table in its
1016/// current bootstrap, or holding a restriction that excludes the table.
1017fn unit_owners(
1018    units: &[UnitRecord],
1019    table: &TableSchema,
1020    except_id: &str,
1021) -> Vec<Vec<(String, Vec<String>)>> {
1022    units
1023        .iter()
1024        .filter(|unit| {
1025            unit.id != except_id
1026                && unit.status == UnitStatus::Active
1027                && unit.echo.is_some()
1028                && (!unit.bootstrapping()
1029                    || unit.seeded.contains(&table.name)
1030                    || unit
1031                        .restriction
1032                        .as_ref()
1033                        .is_some_and(|restriction| !restriction.tables.contains(&table.name)))
1034                && covers(table, &unit.scopes)
1035        })
1036        .filter_map(|unit| pair_scopes(&unit.scopes, &table.name, unit.echo.as_deref()))
1037        .collect()
1038}
1039
1040/// §5.5 / §5.6: the unit's scope map, each value a one-element list.
1041fn unit_scope_lists(scopes: &UnitScopes) -> Vec<(String, Vec<String>)> {
1042    scopes
1043        .iter()
1044        .map(|(variable, value)| (variable.clone(), vec![value.clone()]))
1045        .collect()
1046}
1047
1048/// §7.1 acknowledged intent of the rows `?1` names (`[[table, id], ...]`).
1049/// It joins through the (tbl, id) index: a scan per acknowledgement would
1050/// make draining a batch quadratic.
1051const ACKED_ROWS_BY_ROW: &str = "SELECT a.op_json,a.intent_json FROM json_each(?1) k JOIN _syncular_acked_rows a ON a.tbl=json_extract(k.value,'$[0]') AND a.id=json_extract(k.value,'$[1]') WHERE ?2 IS NULL OR a.tbl IN(SELECT value FROM json_each(?2)) ORDER BY a.commit_seq,a.idx";
1052
1053const UNIT_COLUMNS: &str =
1054    "id, scopes, explicit, status, reason_code, cursor, bootstrap_state, seeded, echo, restriction";
1055
1056/// A unit row; a field that does not parse is a conversion failure, which
1057/// both read paths classify as `sync.local_corrupt`.
1058fn unit_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<UnitRecord> {
1059    fn json<T: serde::de::DeserializeOwned>(index: usize, raw: &str) -> rusqlite::Result<T> {
1060        serde_json::from_str(raw).map_err(|error| {
1061            rusqlite::Error::FromSqlConversionFailure(
1062                index,
1063                rusqlite::types::Type::Text,
1064                Box::new(error),
1065            )
1066        })
1067    }
1068    Ok(UnitRecord {
1069        id: row.get(0)?,
1070        scopes: json(1, &row.get::<_, String>(1)?)?,
1071        explicit: row.get::<_, i64>(2)? == 1,
1072        status: json(
1073            3,
1074            &serde_json::to_string(&row.get::<_, String>(3)?).expect("text"),
1075        )?,
1076        reason_code: row.get(4)?,
1077        cursor: row.get(5)?,
1078        bootstrap_state: row.get(6)?,
1079        seeded: json(7, &row.get::<_, String>(7)?)?,
1080        echo: row
1081            .get::<_, Option<String>>(8)?
1082            .map(|echo| json::<Vec<EchoRecord>>(8, &echo))
1083            .transpose()?
1084            .map(|echo| {
1085                if echo
1086                    .iter()
1087                    .all(|record| record.status == "active" || record.status == "revoked")
1088                {
1089                    Ok(echo)
1090                } else {
1091                    Err(rusqlite::Error::FromSqlConversionFailure(
1092                        8,
1093                        rusqlite::types::Type::Text,
1094                        "echo status is neither active nor revoked".into(),
1095                    ))
1096                }
1097            })
1098            .transpose()?,
1099        restriction: row
1100            .get::<_, Option<String>>(9)?
1101            .map(|raw| json::<UnitRestriction>(9, &raw))
1102            .transpose()?,
1103    })
1104}
1105
1106/// Every unit in registration order (§4.1).
1107fn load_units(conn: &Connection) -> rusqlite::Result<Vec<UnitRecord>> {
1108    conn.prepare_cached(&format!(
1109        "SELECT {UNIT_COLUMNS} FROM _syncular_units ORDER BY rowid"
1110    ))?
1111    .query_map([], unit_from_row)?
1112    .collect()
1113}
1114
1115fn get_unit(conn: &Connection, id: &str) -> rusqlite::Result<Option<UnitRecord>> {
1116    conn.query_row(
1117        &format!("SELECT {UNIT_COLUMNS} FROM _syncular_units WHERE id = ?1"),
1118        [id],
1119        unit_from_row,
1120    )
1121    .optional()
1122}
1123
1124/// Insert or update in place: an update keeps the registration order. The
1125/// §5.6 applied-segment record ends when the cursor or the token changes.
1126fn save_unit(conn: &Connection, unit: &UnitRecord) -> rusqlite::Result<()> {
1127    conn.prepare_cached(&format!(
1128        "INSERT INTO _syncular_units({UNIT_COLUMNS}) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10)
1129         ON CONFLICT(id) DO UPDATE SET explicit=excluded.explicit, status=excluded.status,
1130           reason_code=excluded.reason_code, cursor=excluded.cursor,
1131           bootstrap_state=excluded.bootstrap_state, seeded=excluded.seeded, echo=excluded.echo,
1132           restriction=excluded.restriction,
1133           applied=CASE WHEN cursor IS excluded.cursor
1134             AND bootstrap_state IS excluded.bootstrap_state THEN applied END"
1135    ))?
1136    .execute(rusqlite::params![
1137        unit.id,
1138        serde_json::to_string(&unit.scopes).expect("scope map serializes"),
1139        i64::from(unit.explicit),
1140        unit.status.name(),
1141        unit.reason_code,
1142        unit.cursor,
1143        unit.bootstrap_state,
1144        serde_json::to_string(&unit.seeded).expect("table list serializes"),
1145        unit.echo
1146            .as_ref()
1147            .map(|echo| serde_json::to_string(echo).expect("echo serializes")),
1148        unit.restriction
1149            .as_ref()
1150            .map(|restriction| serde_json::to_string(restriction).expect("restriction serializes")),
1151    ])
1152    .map(|_| ())
1153}
1154
1155/// §5.6 applied-segment record of unit `id`: segment id → rows applied at
1156/// its current cursor and token.
1157fn applied_rows(conn: &Connection, id: &str) -> rusqlite::Result<BTreeMap<String, i64>> {
1158    conn.query_row(
1159        "SELECT applied FROM _syncular_units WHERE id = ?1",
1160        [id],
1161        |row| row.get::<_, Option<String>>(0),
1162    )
1163    .optional()?
1164    .flatten()
1165    .map_or(Ok(BTreeMap::new()), |raw| {
1166        serde_json::from_str(&raw).map_err(|error| {
1167            rusqlite::Error::FromSqlConversionFailure(
1168                0,
1169                rusqlite::types::Type::Text,
1170                Box::new(error),
1171            )
1172        })
1173    })
1174}
1175
1176/// §5.6: `rows` rows of `segment_id` applied at unit `id`'s position. Runs
1177/// in the transaction that commits them.
1178fn record_applied_rows(
1179    conn: &Connection,
1180    id: &str,
1181    segment_id: &str,
1182    rows: i64,
1183) -> rusqlite::Result<()> {
1184    conn.prepare_cached(
1185        "UPDATE _syncular_units SET applied=json_patch(coalesce(applied,'{}'),?1) WHERE id=?2",
1186    )?
1187    .execute(rusqlite::params![
1188        serde_json::json!({ segment_id: rows }).to_string(),
1189        id
1190    ])
1191    .map(|_| ())
1192}
1193
1194/// §4.1 references: every window registry entry `(base, value)` holding a unit.
1195fn window_refs(conn: &Connection, unit_id: &str) -> rusqlite::Result<Vec<(String, String)>> {
1196    conn.prepare_cached("SELECT base, unit FROM _syncular_windows WHERE sub_id = ?1")?
1197        .query_map([unit_id], |row| Ok((row.get(0)?, row.get(1)?)))?
1198        .collect()
1199}
1200
1201/// §7.4.3 reset, §2.1 log reset and local rebootstrap: keep the unit
1202/// registrations and discard the synced state of every unit outside `keep`,
1203/// so the next round sends the list and bootstraps those units. A schema bump
1204/// passes `restrictions`: every reset unit keeps its echo and takes its
1205/// restriction from the map, if any (§7.4.3); the other resets discard both.
1206/// The replica cursor survives only while a kept unit is live. The caller
1207/// owns the transaction.
1208fn reset_units(
1209    conn: &Connection,
1210    keep: &BTreeSet<String>,
1211    restrictions: Option<&BTreeMap<String, UnitRestriction>>,
1212) -> rusqlite::Result<()> {
1213    conn.execute(
1214        "UPDATE _syncular_units SET status='active', reason_code=NULL, cursor=-1,
1215           bootstrap_state=NULL, seeded='[]', applied=NULL,
1216           echo=CASE WHEN ?2 IS NULL THEN NULL ELSE echo END,
1217           restriction=(SELECT value FROM json_each(?2) WHERE key=_syncular_units.id)
1218         WHERE id NOT IN (SELECT value FROM json_each(?1))",
1219        rusqlite::params![
1220            serde_json::to_string(keep).expect("unit ids serialize"),
1221            restrictions.map(|map| serde_json::to_string(map).expect("restrictions serialize")),
1222        ],
1223    )?;
1224    conn.execute_batch(
1225        "DELETE FROM _syncular_meta WHERE key IN ('echoDigest','registrationDigest');
1226         DELETE FROM _syncular_meta WHERE key='replicaCursor'
1227           AND NOT EXISTS (SELECT 1 FROM _syncular_units WHERE cursor IS NULL);",
1228    )
1229}
1230
1231/// §4.5: the replica cursor, `-1` while no unit is live.
1232fn replica_cursor(conn: &Connection) -> rusqlite::Result<i64> {
1233    meta_get(conn, REPLICA_CURSOR_KEY)?.map_or(Ok(-1), |raw| {
1234        raw.parse().map_err(|error| {
1235            rusqlite::Error::FromSqlConversionFailure(
1236                0,
1237                rusqlite::types::Type::Text,
1238                Box::new(error),
1239            )
1240        })
1241    })
1242}
1243
1244fn visible_table(name: &str) -> String {
1245    quote_ident(name)
1246}
1247
1248const FTS_SOURCE_ID_COLUMN: &str = "_syncular_source_id";
1249
1250/// §7.4.3: is a `sqlite_master` table name a synced table (visible or base),
1251/// i.e. NOT one of the durable bookkeeping tables the reset preserves?
1252fn is_synced_table_name(name: &str) -> bool {
1253    if name.starts_with("sqlite_") {
1254        return false;
1255    }
1256    if name.starts_with("_syncular_base_") {
1257        return true; // the base half of a synced table pair
1258    }
1259    // Bookkeeping: outbox, units, meta, blob cache/uploads.
1260    !name.starts_with("_syncular_")
1261}
1262
1263/// `"sha256:" + hex` of the bytes — the content address (§5.9.1).
1264fn blob_id_for(bytes: &[u8]) -> String {
1265    let digest = Sha256::digest(bytes);
1266    format!("sha256:{}", bytes_to_hex(&digest))
1267}
1268
1269/// One [`SyncClient::write_row`] bind parameter, borrowing the row-codec
1270/// value it wraps — strings/JSON/bytes bind as borrowed TEXT/BLOB (no copy
1271/// per row on the §5.6 bootstrap path), scalars bind owned.
1272enum RowParam<'a> {
1273    Cell(&'a Option<ColumnValue>),
1274    Version(i64),
1275    Text(Option<&'a str>),
1276}
1277
1278impl rusqlite::ToSql for RowParam<'_> {
1279    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
1280        Ok(match self {
1281            RowParam::Version(v) => ToSqlOutput::Owned(SqlValue::Integer(*v)),
1282            RowParam::Text(text) => match text {
1283                Some(text) => ToSqlOutput::Borrowed(ValueRef::Text(text.as_bytes())),
1284                None => ToSqlOutput::Owned(SqlValue::Null),
1285            },
1286            RowParam::Cell(cell) => match cell {
1287                None => ToSqlOutput::Owned(SqlValue::Null),
1288                Some(ColumnValue::String(s)) => ToSqlOutput::Borrowed(ValueRef::Text(s.as_bytes())),
1289                Some(ColumnValue::Integer(i)) => ToSqlOutput::Owned(SqlValue::Integer(*i)),
1290                Some(ColumnValue::Float(f)) => ToSqlOutput::Owned(SqlValue::Real(*f)),
1291                Some(ColumnValue::Boolean(b)) => {
1292                    ToSqlOutput::Owned(SqlValue::Integer(i64::from(*b)))
1293                }
1294                Some(ColumnValue::Json(raw)) | Some(ColumnValue::BlobRef(raw)) => {
1295                    ToSqlOutput::Borrowed(ValueRef::Text(raw.0.as_bytes()))
1296                }
1297                // §5.10: crdt bytes store as BLOB, like bytes.
1298                Some(ColumnValue::Bytes(b)) | Some(ColumnValue::Crdt(b)) => {
1299                    ToSqlOutput::Borrowed(ValueRef::Blob(b))
1300                }
1301            },
1302        })
1303    }
1304}
1305
1306// Retain a typed primary key across the current import chunk without copying row payloads.
1307fn owned_sql_value(param: impl rusqlite::ToSql) -> Result<SqlValue, String> {
1308    match param.to_sql().map_err(|error| error.to_string())? {
1309        ToSqlOutput::Owned(value) => Ok(value),
1310        ToSqlOutput::Borrowed(value) => {
1311            SqlValue::try_from(value).map_err(|error| error.to_string())
1312        }
1313        _ => Err("sync.invalid_request: unsupported SQLite key parameter".into()),
1314    }
1315}
1316
1317/// §5.3 image cell → bind parameter, strict per the declared column type
1318/// (`boolean` from INTEGER 0/1, `json` from its raw TEXT, NULL only when
1319/// nullable). Mismatches are image-producer violations. Returns the cell
1320/// borrowed when the stored representation already matches what the row
1321/// codec would write, or the normalized scalar (boolean → 0/1, float from
1322/// INTEGER → REAL) otherwise — the local write is byte-identical to the
1323/// old convert-then-insert path without allocating per cell.
1324fn image_cell_param<'a>(column: &Column, value: ValueRef<'a>) -> Result<ToSqlOutput<'a>, String> {
1325    use ssp2::segment::ColumnType;
1326    let mismatch = || {
1327        Err(format!(
1328            "image column {:?} holds a value of the wrong type",
1329            column.name
1330        ))
1331    };
1332    match value {
1333        ValueRef::Null => {
1334            if !column.nullable {
1335                return Err(format!(
1336                    "image column {:?} is NULL but not nullable",
1337                    column.name
1338                ));
1339            }
1340            Ok(ToSqlOutput::Owned(SqlValue::Null))
1341        }
1342        ValueRef::Integer(i) => match column.ty {
1343            ColumnType::Integer => Ok(ToSqlOutput::Borrowed(value)),
1344            ColumnType::Boolean => Ok(ToSqlOutput::Owned(SqlValue::Integer(i64::from(i != 0)))),
1345            ColumnType::Float => Ok(ToSqlOutput::Owned(SqlValue::Real(i as f64))),
1346            _ => mismatch(),
1347        },
1348        ValueRef::Real(_) => match column.ty {
1349            ColumnType::Float => Ok(ToSqlOutput::Borrowed(value)),
1350            _ => mismatch(),
1351        },
1352        ValueRef::Text(t) => {
1353            std::str::from_utf8(t)
1354                .map_err(|_| format!("image column {:?} is not UTF-8", column.name))?;
1355            match column.ty {
1356                ColumnType::String | ColumnType::Json | ColumnType::BlobRef => {
1357                    Ok(ToSqlOutput::Borrowed(value))
1358                }
1359                _ => mismatch(),
1360            }
1361        }
1362        ValueRef::Blob(_) => match column.ty {
1363            // §5.10: a crdt column stores its opaque bytes as BLOB, like bytes.
1364            ColumnType::Bytes | ColumnType::Crdt => Ok(ToSqlOutput::Borrowed(value)),
1365            _ => mismatch(),
1366        },
1367    }
1368}
1369
1370pub(crate) fn sql_ref_to_json(column: &Column, value: rusqlite::types::ValueRef<'_>) -> Value {
1371    use rusqlite::types::ValueRef;
1372    match value {
1373        ValueRef::Null => Value::Null,
1374        ValueRef::Integer(i) => match column.ty {
1375            ssp2::segment::ColumnType::Boolean => Value::Bool(i != 0),
1376            ssp2::segment::ColumnType::Float => {
1377                serde_json::Number::from_f64(i as f64).map_or(Value::Null, Value::Number)
1378            }
1379            _ => Value::from(i),
1380        },
1381        ValueRef::Real(f) => serde_json::Number::from_f64(f).map_or(Value::Null, Value::Number),
1382        ValueRef::Text(t) => Value::from(String::from_utf8_lossy(t).into_owned()),
1383        ValueRef::Blob(b) => {
1384            let mut map = Map::new();
1385            map.insert("$bytes".to_owned(), Value::from(bytes_to_hex(b)));
1386            Value::Object(map)
1387        }
1388    }
1389}
1390
1391/// Bind a driver JSON value form as a rusqlite parameter for [`SyncClient::query`].
1392/// Objects are accepted in lossless `{"$bytes": hex}` and
1393/// `{"$bigint": decimal}` envelope forms.
1394fn json_param_to_sql(value: &Value) -> Result<SqlValue, String> {
1395    Ok(match value {
1396        Value::Null => SqlValue::Null,
1397        Value::Bool(b) => SqlValue::Integer(i64::from(*b)),
1398        Value::Number(n) => {
1399            if let Some(i) = n.as_i64() {
1400                SqlValue::Integer(i)
1401            } else if let Some(f) = n.as_f64() {
1402                SqlValue::Real(f)
1403            } else {
1404                return Err(format!("query param number {n} is out of range"));
1405            }
1406        }
1407        Value::String(s) => SqlValue::Text(s.clone()),
1408        Value::Object(_) => {
1409            if let Some(hex) = value.get("$bytes").and_then(Value::as_str) {
1410                SqlValue::Blob(crate::values::hex_to_bytes(hex)?)
1411            } else if let Some(decimal) = value.get("$bigint").and_then(Value::as_str) {
1412                SqlValue::Integer(decimal.parse::<i64>().map_err(|_| {
1413                    format!("query bigint param {decimal:?} is outside SQLite's i64 range")
1414                })?)
1415            } else {
1416                return Err(
1417                    "query object param must be a {$bytes: hex} or {$bigint: decimal} value"
1418                        .to_owned(),
1419                );
1420            }
1421        }
1422        Value::Array(_) => return Err("query array params are not supported".to_owned()),
1423    })
1424}
1425
1426/// Map a rusqlite value with no schema column to consult (arbitrary query
1427/// output): integers/reals/text pass through by stored affinity, blobs ride
1428/// as `{"$bytes": hex}`. Distinct from [`sql_ref_to_json`], which uses the
1429/// schema column type to recover booleans/floats/json.
1430fn sql_ref_to_json_dynamic(value: rusqlite::types::ValueRef<'_>) -> Value {
1431    use rusqlite::types::ValueRef;
1432    match value {
1433        ValueRef::Null => Value::Null,
1434        ValueRef::Integer(i) => {
1435            // JSON/Tauri IPC cannot represent every SQLite i64 exactly. Keep
1436            // ordinary UI-sized integers ergonomic and envelope only values
1437            // beyond JavaScript's safe range.
1438            const MAX_SAFE_INTEGER: i64 = 9_007_199_254_740_991;
1439            if (-MAX_SAFE_INTEGER..=MAX_SAFE_INTEGER).contains(&i) {
1440                Value::from(i)
1441            } else {
1442                let mut map = Map::new();
1443                map.insert("$bigint".to_owned(), Value::from(i.to_string()));
1444                Value::Object(map)
1445            }
1446        }
1447        ValueRef::Real(f) => serde_json::Number::from_f64(f).map_or(Value::Null, Value::Number),
1448        ValueRef::Text(t) => Value::from(String::from_utf8_lossy(t).into_owned()),
1449        ValueRef::Blob(b) => {
1450            let mut map = Map::new();
1451            map.insert("$bytes".to_owned(), Value::from(bytes_to_hex(b)));
1452            Value::Object(map)
1453        }
1454    }
1455}
1456
1457/// §7.5: SQLite failures classify by result code into [`QueryReadFailure`].
1458fn query_connection(
1459    conn: &Connection,
1460    sql: &str,
1461    params: &[QueryValue],
1462) -> Result<Vec<QueryRow>, QueryReadFailure> {
1463    let lowered_sql = crate::query_guard::lower_public_query_sql(sql);
1464    let mut stmt = crate::query_guard::prepare_read_only(conn, &lowered_sql)?;
1465    let bound: Vec<SqlValue> = params
1466        .iter()
1467        .map(json_param_to_sql)
1468        .collect::<Result<_, _>>()?;
1469    // §2.4: an unaliased physical version column stays engine-internal, so a
1470    // `SELECT *` row feeds straight back into mutation values. An explicit
1471    // alias (`_sync_version AS v`) returns it as ordinary query data. The
1472    // §5.11 sealed columns follow the same rule.
1473    let columns: Vec<(usize, String)> = stmt
1474        .column_names()
1475        .enumerate()
1476        .filter(|(_, name)| {
1477            !matches!(
1478                *name,
1479                "_syncular_version" | "_sync_sealed_key" | "_sync_sealed"
1480            )
1481        })
1482        .map(|(i, name)| (i, name.to_owned()))
1483        .collect();
1484    let bound_refs: Vec<&dyn rusqlite::ToSql> =
1485        bound.iter().map(|v| v as &dyn rusqlite::ToSql).collect();
1486    let mut sql_rows = stmt.query(bound_refs.as_slice())?;
1487    let mut out = Vec::new();
1488    while let Some(row) = sql_rows.next()? {
1489        let mut record = Map::new();
1490        for (i, name) in &columns {
1491            let value = row.get_ref(*i)?;
1492            record.insert(name.clone(), sql_ref_to_json_dynamic(value));
1493        }
1494        out.push(record);
1495    }
1496    Ok(out)
1497}
1498
1499fn persisted_window_state(
1500    conn: &Connection,
1501    base: &WindowBase,
1502) -> Result<WindowState, QueryReadFailure> {
1503    let mut stmt = conn.prepare(
1504        "SELECT windows.unit, units.status, units.cursor, units.bootstrap_state
1505           FROM _syncular_windows AS windows
1506           LEFT JOIN _syncular_units AS units ON units.id = windows.sub_id
1507          WHERE windows.base = ?1
1508          ORDER BY windows.unit ASC",
1509    )?;
1510    let rows = stmt.query_map(rusqlite::params![window_base_key(base)], |row| {
1511        Ok((
1512            row.get::<_, String>(0)?,
1513            row.get::<_, Option<String>>(1)?,
1514            row.get::<_, Option<i64>>(2)?,
1515            row.get::<_, Option<String>>(3)?,
1516        ))
1517    })?;
1518    let mut units = Vec::new();
1519    let mut pending = Vec::new();
1520    let mut revoked = Vec::new();
1521    for row in rows {
1522        let (unit, status, cursor, bootstrap_state) = row?;
1523        if status.as_deref() == Some("revoked") {
1524            revoked.push(unit.clone());
1525        }
1526        // §4.8: complete iff registered, active and not bootstrapping.
1527        if status.as_deref() != Some("active")
1528            || cursor.is_some_and(|cursor| cursor < 0 || bootstrap_state.is_some())
1529        {
1530            pending.push(unit.clone());
1531        }
1532        units.push(unit);
1533    }
1534    Ok(WindowState {
1535        units,
1536        pending,
1537        revoked,
1538    })
1539}
1540
1541/// One read-only statement in a §7.5 snapshot read.
1542#[derive(Debug, Clone, Copy)]
1543pub struct SnapshotStatement<'a> {
1544    pub sql: &'a str,
1545    pub params: &'a [Value],
1546}
1547
1548/// A §7.5 atomic read request: read-only statements, window coverage, unit
1549/// catch-up states, and commit deliveries, all resolved from one SQLite read
1550/// transaction and one revision.
1551#[derive(Debug, Clone, Default)]
1552pub struct SnapshotReadRequest<'a> {
1553    pub statements: Vec<SnapshotStatement<'a>>,
1554    pub coverage: &'a [WindowCoverage],
1555    pub units: Vec<String>,
1556    pub commit_ids: Vec<String>,
1557}
1558
1559#[cfg(test)]
1560thread_local! {
1561    /// Test-only rendezvous that runs between the statements of one snapshot
1562    /// read. A test uses it to commit on another connection mid-read and prove
1563    /// the read transaction's snapshot and revision stay stable.
1564    static SNAPSHOT_READ_HOOK: std::cell::RefCell<Option<Box<dyn FnOnce()>>> =
1565        std::cell::RefCell::new(None);
1566}
1567
1568#[cfg(test)]
1569fn run_snapshot_read_hook() {
1570    SNAPSHOT_READ_HOOK.with(|slot| {
1571        if let Some(hook) = slot.borrow_mut().take() {
1572            hook();
1573        }
1574    });
1575}
1576
1577/// §7.5: resolve a request over one SQLite read transaction. The revision,
1578/// every statement's rows, coverage, catch-up states, and deliveries are
1579/// captured under one `SAVEPOINT`; any statement's failure rolls the whole
1580/// read back and releases the connection.
1581fn snapshot_read_connection(
1582    conn: &Connection,
1583    schema: Option<&ClientSchema>,
1584    request: &SnapshotReadRequest<'_>,
1585) -> Result<SnapshotRead, QueryReadFailure> {
1586    conn.execute_batch("SAVEPOINT syncular_snapshot_read")?;
1587    let corrupt = |message: &str| QueryReadFailure {
1588        code: Some("sync.local_corrupt"),
1589        sqlite_code: None,
1590        sqlite_message: None,
1591        rollback_failure: None,
1592        message: message.to_owned(),
1593    };
1594    let stored_failure = |error: rusqlite::Error, message: &str| match error {
1595        rusqlite::Error::Utf8Error(..)
1596        | rusqlite::Error::InvalidColumnType(..)
1597        | rusqlite::Error::FromSqlConversionFailure(..)
1598        | rusqlite::Error::IntegralValueOutOfRange(..) => corrupt(message),
1599        _ => QueryReadFailure::from(error),
1600    };
1601    let result: Result<SnapshotRead, QueryReadFailure> = (|| {
1602        // The durable revision as a canonical decimal `u64`; a missing marker
1603        // is the legacy zero, and any other non-canonical value is corrupt.
1604        let revision: Option<String> = conn
1605            .query_row(
1606                "SELECT value FROM _syncular_meta WHERE key = ?1",
1607                rusqlite::params![LOCAL_REVISION_KEY],
1608                |row| row.get(0),
1609            )
1610            .optional()
1611            .map_err(|error| stored_failure(error, "persisted local revision is invalid"))?;
1612        let revision = match revision {
1613            None => "0".to_owned(),
1614            Some(value)
1615                if value == "0"
1616                    || (matches!(value.as_bytes().first(), Some(b'1'..=b'9'))
1617                        && value.bytes().all(|b| b.is_ascii_digit())
1618                        && value.parse::<u64>().is_ok()) =>
1619            {
1620                value
1621            }
1622            Some(_) => return Err(corrupt("persisted local revision is invalid")),
1623        };
1624        let mut queries = Vec::with_capacity(request.statements.len());
1625        for statement in &request.statements {
1626            queries.push(query_connection(conn, statement.sql, statement.params)?);
1627            #[cfg(test)]
1628            run_snapshot_read_hook();
1629        }
1630        let mut pending = Vec::new();
1631        let mut missing = Vec::new();
1632        let mut revoked = Vec::new();
1633        let persisted = if request.coverage.is_empty() {
1634            Vec::new()
1635        } else {
1636            load_units(conn)
1637                .map_err(|error| stored_failure(error, "persisted unit state is invalid"))?
1638        };
1639        for requested in request.coverage {
1640            let declared = match schema {
1641                Some(schema) => {
1642                    Some(
1643                        schema
1644                            .table(&requested.table)
1645                            .ok_or_else(|| QueryReadFailure {
1646                                code: Some("sync.invalid_request"),
1647                                sqlite_code: None,
1648                                sqlite_message: None,
1649                                rollback_failure: None,
1650                                message: "unknown coverage table".to_owned(),
1651                            })?,
1652                    )
1653                }
1654                None => None,
1655            };
1656            let base_key = window_base_key(&requested.base);
1657            for unit in BTreeSet::from_iter(requested.units.iter().cloned()) {
1658                let (state, revoked_candidate) = entry_coverage(
1659                    &persisted,
1660                    &requested.table,
1661                    declared,
1662                    &requested.base,
1663                    &unit,
1664                );
1665                let reference = WindowUnitRef {
1666                    base_key: base_key.clone(),
1667                    unit,
1668                };
1669                // Refs dedupe across entries of several tables on one base.
1670                let add = |list: &mut Vec<WindowUnitRef>, reference: &WindowUnitRef| {
1671                    if !list.iter().any(|held| {
1672                        held.base_key == reference.base_key && held.unit == reference.unit
1673                    }) {
1674                        list.push(reference.clone());
1675                    }
1676                };
1677                match state {
1678                    "complete" => continue,
1679                    "missing" => add(&mut missing, &reference),
1680                    _ => add(&mut pending, &reference),
1681                }
1682                if revoked_candidate {
1683                    add(&mut revoked, &reference);
1684                }
1685            }
1686        }
1687        let mut units = Vec::with_capacity(request.units.len());
1688        for id in &request.units {
1689            let exists: bool = conn.query_row(
1690                "SELECT EXISTS(SELECT 1 FROM _syncular_units WHERE id = ?1)",
1691                [id],
1692                |row| row.get(0),
1693            )?;
1694            if !exists {
1695                units.push(UnitCatchup::Unknown { id: id.clone() });
1696                continue;
1697            }
1698            // Every persisted field is required to be well typed; a corrupt
1699            // record fails typed instead of inventing a state.
1700            let unit = get_unit(conn, id)
1701                .map_err(|error| stored_failure(error, "persisted unit state is invalid"))?
1702                .ok_or_else(|| corrupt("persisted unit state is invalid"))?;
1703            let cursor = match unit.cursor {
1704                Some(cursor) => cursor,
1705                None => replica_cursor(conn)
1706                    .map_err(|error| stored_failure(error, "persisted unit state is invalid"))?,
1707            };
1708            if cursor.unsigned_abs() > MAX_JS_SAFE_INTEGER {
1709                return Err(corrupt("persisted unit state is invalid"));
1710            }
1711            let active = unit.status == UnitStatus::Active;
1712            let pending = unit.bootstrapping();
1713            units.push(UnitCatchup::Known {
1714                id: id.clone(),
1715                status: unit.status,
1716                live: unit.cursor.is_none(),
1717                cursor,
1718                has_resume_token: unit.bootstrap_state.is_some(),
1719                bootstrap_complete: active && !pending,
1720                known_pending_pages: active && pending,
1721                reason_code: unit.reason_code,
1722            });
1723        }
1724        let mut deliveries = Vec::with_capacity(request.commit_ids.len());
1725        for id in &request.commit_ids {
1726            let pending: bool = conn.query_row(
1727                "SELECT EXISTS(SELECT 1 FROM _syncular_outbox WHERE commit_id = ?1)",
1728                rusqlite::params![id],
1729                |row| row.get(0),
1730            )?;
1731            if pending {
1732                deliveries.push(CommitDelivery::Pending {
1733                    client_commit_id: id.clone(),
1734                });
1735                continue;
1736            }
1737            let row = conn
1738                .query_row(
1739                    "SELECT seq, client_commit_id, status, recorded_at_ms, results_json, operations_json,
1740                            resolution, resolved_at_ms, replacement_client_commit_id
1741                       FROM _syncular_commit_outcomes WHERE client_commit_id = ?1",
1742                    rusqlite::params![id],
1743                    StoredCommitOutcomeRow::from_row,
1744                )
1745                .optional()
1746                .map_err(|error| stored_failure(error, "persisted commit outcome is invalid"))?;
1747            deliveries.push(match row {
1748                Some(row) => CommitDelivery::Known {
1749                    client_commit_id: id.clone(),
1750                    outcome: SyncClient::outcome_from_row(row)
1751                        .map(SyncClient::reported_outcome)
1752                        .map_err(|_| corrupt("persisted commit outcome is invalid"))?,
1753                },
1754                None => CommitDelivery::Unknown {
1755                    client_commit_id: id.clone(),
1756                },
1757            });
1758        }
1759        Ok(SnapshotRead {
1760            revision,
1761            queries,
1762            coverage: CoverageSnapshot {
1763                complete: pending.is_empty() && missing.is_empty(),
1764                pending,
1765                missing,
1766                revoked,
1767            },
1768            units,
1769            deliveries,
1770        })
1771    })();
1772    match result {
1773        Ok(read) => {
1774            conn.execute_batch("RELEASE syncular_snapshot_read")?;
1775            Ok(read)
1776        }
1777        Err(mut error) => {
1778            if let Err(rollback) = conn
1779                .execute_batch("ROLLBACK TO syncular_snapshot_read; RELEASE syncular_snapshot_read")
1780            {
1781                error.rollback_failure = Some(Box::new(QueryReadFailure::from(rollback)));
1782            }
1783            Err(error)
1784        }
1785    }
1786}
1787
1788fn snapshot_connection(
1789    conn: &Connection,
1790    schema: Option<&ClientSchema>,
1791    sql: &str,
1792    params: &[Value],
1793    coverage: &[WindowCoverage],
1794) -> Result<QuerySnapshot, QueryReadFailure> {
1795    let read = snapshot_read_connection(
1796        conn,
1797        schema,
1798        &SnapshotReadRequest {
1799            statements: vec![SnapshotStatement { sql, params }],
1800            coverage,
1801            units: Vec::new(),
1802            commit_ids: Vec::new(),
1803        },
1804    )?;
1805    Ok(QuerySnapshot {
1806        revision: read.revision,
1807        rows: read
1808            .queries
1809            .into_iter()
1810            .next()
1811            .expect("single-query snapshot returns one result"),
1812        coverage: read.coverage,
1813    })
1814}
1815
1816/// A long-lived read-only SQLite sidecar for latency-critical native views.
1817/// Network rounds stay serialized on the mutable core owner, while atomic
1818/// query snapshots use this independent connection and therefore never queue
1819/// behind HTTP/WebSocket latency.
1820pub struct FileQuerySnapshotReader {
1821    path: String,
1822    conn: Option<Connection>,
1823}
1824
1825impl FileQuerySnapshotReader {
1826    #[must_use]
1827    pub fn new(path: impl Into<String>) -> Self {
1828        Self {
1829            path: path.into(),
1830            conn: None,
1831        }
1832    }
1833
1834    fn connection(&mut self) -> Result<&Connection, QueryReadFailure> {
1835        if self.conn.is_none() {
1836            let conn = Connection::open_with_flags(
1837                &self.path,
1838                OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
1839            )
1840            .map_err(QueryReadFailure::from)?;
1841            conn.busy_timeout(std::time::Duration::from_millis(250))
1842                .map_err(QueryReadFailure::from)?;
1843            self.conn = Some(conn);
1844        }
1845        self.conn
1846            .as_ref()
1847            .ok_or_else(|| QueryReadFailure::from("read sidecar connection missing".to_owned()))
1848    }
1849
1850    /// One atomic read over the shared primitive: every statement, coverage,
1851    /// catch-up, and delivery under one `SAVEPOINT` and one revision.
1852    pub fn snapshot_read(
1853        &mut self,
1854        request: &SnapshotReadRequest<'_>,
1855    ) -> Result<SnapshotRead, QueryReadFailure> {
1856        snapshot_read_connection(self.connection()?, None, request)
1857    }
1858
1859    /// The current durable local revision. A host can skip a read when it is
1860    /// unchanged; a corrupt or unreadable marker fails typed.
1861    pub fn local_revision(&mut self) -> Result<String, QueryReadFailure> {
1862        Ok(self
1863            .snapshot_read(&SnapshotReadRequest::default())?
1864            .revision)
1865    }
1866
1867    /// One unit's persisted catch-up state (see the §7.5 contract).
1868    pub fn unit_catchup(&mut self, id: &str) -> Result<UnitCatchup, QueryReadFailure> {
1869        let read = self.snapshot_read(&SnapshotReadRequest {
1870            units: vec![id.to_owned()],
1871            ..Default::default()
1872        })?;
1873        Ok(read
1874            .units
1875            .into_iter()
1876            .next()
1877            .expect("one requested catch-up"))
1878    }
1879
1880    /// One client commit's delivery status: pending, its retained outcome, or
1881    /// an explicit unknown (never held, or pruned by retention).
1882    pub fn commit_delivery(&mut self, id: &str) -> Result<CommitDelivery, QueryReadFailure> {
1883        let read = self.snapshot_read(&SnapshotReadRequest {
1884            commit_ids: vec![id.to_owned()],
1885            ..Default::default()
1886        })?;
1887        Ok(read
1888            .deliveries
1889            .into_iter()
1890            .next()
1891            .expect("one requested delivery"))
1892    }
1893
1894    /// Hosts report an owned failure, and the first success after it, to the
1895    /// owning core through [`SyncClient::record_query_read`] (§7.6).
1896    pub fn query_snapshot(
1897        &mut self,
1898        sql: &str,
1899        params: &[Value],
1900        coverage: &[WindowCoverage],
1901    ) -> Result<QuerySnapshot, QueryReadFailure> {
1902        snapshot_connection(self.connection()?, None, sql, params, coverage)
1903    }
1904}
1905
1906/// `client.authority_read_forbidden` with static text; `details` carries the
1907/// query, the reason and, where one applies, the table and column (§5.11).
1908fn authority_forbidden(details: Option<Value>) -> ClientError {
1909    ClientError {
1910        code: "client.authority_read_forbidden".to_owned(),
1911        message: "authority read denied".to_owned(),
1912        details,
1913        retryable: false,
1914    }
1915}
1916
1917/// `sync.local_corrupt` for missing or invalid authority read evidence.
1918fn authority_corrupt() -> ClientError {
1919    ClientError {
1920        code: "sync.local_corrupt".to_owned(),
1921        message: "authority revision or base evidence is missing or invalid".to_owned(),
1922        details: None,
1923        retryable: false,
1924    }
1925}
1926
1927/// A storage failure of an authority read: a value that does not convert is
1928/// corrupt evidence; every other failure keeps its storage classification.
1929fn authority_stored(error: rusqlite::Error) -> ClientError {
1930    match error {
1931        rusqlite::Error::Utf8Error(..)
1932        | rusqlite::Error::InvalidColumnType(..)
1933        | rusqlite::Error::FromSqlConversionFailure(..)
1934        | rusqlite::Error::IntegralValueOutOfRange(..) => authority_corrupt(),
1935        other => ClientError::from(QueryReadFailure::from(other)),
1936    }
1937}
1938
1939fn authority_refusal(
1940    query: &str,
1941    reason: &str,
1942    table: Option<&str>,
1943    column: Option<&str>,
1944) -> ClientError {
1945    let mut details = json!({ "query": query, "reason": reason });
1946    if let Some(table) = table {
1947        details["table"] = Value::from(table);
1948    }
1949    if let Some(column) = column {
1950        details["column"] = Value::from(column);
1951    }
1952    authority_forbidden(Some(details))
1953}
1954
1955/// §5.11 creation check of every declared authority query against `schema`.
1956/// A refusal is `client.authority_read_forbidden` with the details
1957/// `{ query, reason, table?, column? }`.
1958pub fn validate_authority_reads(
1959    schema: &ClientSchema,
1960    queries: &[AuthorityQuery],
1961) -> Result<(), ClientError> {
1962    let mut names = BTreeSet::new();
1963    for query in queries {
1964        let refuse = |reason: &str, table: Option<&str>, column: Option<&str>| {
1965            authority_refusal(&query.name, reason, table, column)
1966        };
1967        let declared = |param: &String| query.params.iter().any(|held| &held.name == param);
1968        if !names.insert(query.name.as_str()) {
1969            return Err(refuse("shape", None, None));
1970        }
1971        if !query.params.iter().all(|param| {
1972            matches!(
1973                param.ty.as_str(),
1974                "string" | "integer" | "float" | "boolean" | "json"
1975            )
1976        }) {
1977            return Err(refuse("param", None, None));
1978        }
1979        let mut quoted = false;
1980        let holes = query
1981            .sql
1982            .chars()
1983            .filter(|c| {
1984                if *c == '\'' {
1985                    quoted = !quoted;
1986                }
1987                !quoted && *c == '?'
1988            })
1989            .count();
1990        if !query.bind.iter().all(declared) || holes != query.bind.len() {
1991            return Err(refuse("shape", None, None));
1992        }
1993        for entry in &query.coverage {
1994            let well_formed = schema.table(&entry.table).is_some_and(|table| {
1995                table.scope_column(&entry.variable).is_some()
1996                    && entry.fixed_scopes.iter().all(|(variable, param)| {
1997                        table.scope_column(variable).is_some() && declared(param)
1998                    })
1999                    && entry.units.iter().all(declared)
2000            });
2001            if !well_formed {
2002                return Err(refuse("shape", Some(entry.table.as_str()), None));
2003            }
2004        }
2005        for (name, columns) in &query.reads {
2006            let table = schema
2007                .table(name)
2008                .filter(|_| !name.starts_with("_syncular_"))
2009                .ok_or_else(|| refuse("column", Some(name.as_str()), None))?;
2010            for column in columns {
2011                if column == "_sync_version"
2012                    || (column == "_sync_sealed_key" && table.has_encrypted_columns())
2013                {
2014                    continue;
2015                }
2016                // `ty` is the local type: an encrypted column's declared type.
2017                let readable = !column.starts_with("_sync")
2018                    && table.columns.iter().any(|held| {
2019                        &held.name == column
2020                            && matches!(
2021                                held.ty,
2022                                ColumnType::String
2023                                    | ColumnType::Integer
2024                                    | ColumnType::Float
2025                                    | ColumnType::Boolean
2026                                    | ColumnType::Json
2027                                    | ColumnType::Bytes
2028                            )
2029                    });
2030                if !readable {
2031                    return Err(refuse("column", Some(name.as_str()), Some(column.as_str())));
2032                }
2033            }
2034        }
2035    }
2036    Ok(())
2037}
2038
2039/// §5.11 native ceiling: prepare the authored statement of `query` on `conn`
2040/// under the SQLite authorizer and return its read set, table to columns. An
2041/// empty column is a read of the table without a column (`count(*)`). Any
2042/// action other than SELECT, READ, or a deterministic core function refuses
2043/// with reason `ceiling`; a statement that does not prepare refuses with
2044/// reason `shape`. The authorizer sees the authored statement only, never
2045/// the accepted-base shadows `authority_read` adds.
2046pub fn authority_read_set(
2047    conn: &mut Connection,
2048    query: &AuthorityQuery,
2049) -> Result<BTreeMap<String, BTreeSet<String>>, ClientError> {
2050    const DETERMINISTIC: &[&str] = &[
2051        "abs",
2052        "avg",
2053        "char",
2054        "coalesce",
2055        "concat",
2056        "concat_ws",
2057        "count",
2058        "format",
2059        "glob",
2060        "group_concat",
2061        "hex",
2062        "if",
2063        "ifnull",
2064        "iif",
2065        "instr",
2066        "json",
2067        "json_array",
2068        "json_array_length",
2069        "json_extract",
2070        "json_group_array",
2071        "json_group_object",
2072        "json_object",
2073        "json_quote",
2074        "json_type",
2075        "json_valid",
2076        "length",
2077        "like",
2078        "likelihood",
2079        "likely",
2080        "lower",
2081        "ltrim",
2082        "max",
2083        "min",
2084        "nullif",
2085        "octet_length",
2086        "printf",
2087        "quote",
2088        "replace",
2089        "round",
2090        "rtrim",
2091        "sign",
2092        "string_agg",
2093        "substr",
2094        "substring",
2095        "sum",
2096        "total",
2097        "trim",
2098        "typeof",
2099        "unhex",
2100        "unicode",
2101        "unlikely",
2102        "upper",
2103        "->",
2104        "->>",
2105    ];
2106    let reads = Arc::new(std::sync::Mutex::new(
2107        BTreeMap::<String, BTreeSet<String>>::new(),
2108    ));
2109    let refused = Arc::new(std::sync::atomic::AtomicBool::new(false));
2110    let (seen, denied) = (Arc::clone(&reads), Arc::clone(&refused));
2111    let sqlite = |error: rusqlite::Error| ClientError::from(QueryReadFailure::from(error));
2112    conn.authorizer(Some(
2113        move |context: rusqlite::hooks::AuthContext<'_>| match context.action {
2114            rusqlite::hooks::AuthAction::Select => rusqlite::hooks::Authorization::Allow,
2115            rusqlite::hooks::AuthAction::Read {
2116                table_name,
2117                column_name,
2118            } => {
2119                // The Rust mirror stores the public `_sync_version` as
2120                // `_syncular_version` (query_guard lowers it).
2121                let column = if column_name == "_syncular_version" {
2122                    "_sync_version"
2123                } else {
2124                    column_name
2125                };
2126                seen.lock()
2127                    .expect("authority read set lock")
2128                    .entry(table_name.to_owned())
2129                    .or_default()
2130                    .insert(column.to_owned());
2131                rusqlite::hooks::Authorization::Allow
2132            }
2133            rusqlite::hooks::AuthAction::Function { function_name }
2134                if DETERMINISTIC
2135                    .iter()
2136                    .any(|name| name.eq_ignore_ascii_case(function_name)) =>
2137            {
2138                rusqlite::hooks::Authorization::Allow
2139            }
2140            _ => {
2141                denied.store(true, std::sync::atomic::Ordering::Relaxed);
2142                rusqlite::hooks::Authorization::Deny
2143            }
2144        },
2145    ))
2146    .map_err(sqlite)?;
2147    let prepared = crate::query_guard::prepare_read_only(
2148        conn,
2149        &crate::query_guard::lower_public_query_sql(&query.sql),
2150    )
2151    .map(drop);
2152    conn.authorizer(None::<fn(rusqlite::hooks::AuthContext<'_>) -> rusqlite::hooks::Authorization>)
2153        .map_err(sqlite)?;
2154    if refused.load(std::sync::atomic::Ordering::Relaxed) {
2155        return Err(authority_refusal(&query.name, "ceiling", None, None));
2156    }
2157    if prepared.is_err() {
2158        return Err(authority_refusal(&query.name, "shape", None, None));
2159    }
2160    let mut set = reads.lock().expect("authority read set lock");
2161    Ok(std::mem::take(&mut *set))
2162}
2163
2164// §7.4.2: every open and recreation checks before any persistent writes.
2165/// A marker read that hit a recognized SQLite storage failure keeps that
2166/// classification (BUSY/LOCKED stay retryable); only an unclassified read
2167/// failure is the invalid-marker `sync.local_corrupt`.
2168fn schema_marker_read_failure(error: rusqlite::Error) -> String {
2169    let failure = QueryReadFailure::from(error);
2170    if failure.code.is_some() {
2171        failure.to_string()
2172    } else {
2173        "sync.local_corrupt: persisted local schema marker is unreadable or invalid".to_owned()
2174    }
2175}
2176
2177/// §7.1: reject an invalid configured client limit before any storage is
2178/// opened or written. Zero would wedge the push queue and an out-of-range
2179/// value would differ per target; the TS core enforces the same bounds.
2180fn validate_client_limits(limits: &crate::api::ClientLimits) -> Result<(), String> {
2181    if limits.outcome_retention_max_entries == Some(0) {
2182        return Err("sync.invalid_request: outcomeRetentionMaxEntries must be positive".to_owned());
2183    }
2184    if [
2185        limits.max_push_commits_per_request,
2186        limits.max_push_operations_per_request,
2187        limits.max_push_request_bytes,
2188    ]
2189    .into_iter()
2190    .flatten()
2191    .any(|value| value == 0 || value > u32::MAX as usize)
2192    {
2193        return Err(
2194            "sync.invalid_request: push limit must be an integer in 1..=4294967295".to_owned(),
2195        );
2196    }
2197    Ok(())
2198}
2199
2200fn read_local_schema_version(
2201    conn: &Connection,
2202    requested: i32,
2203) -> Result<Option<i32>, ClientError> {
2204    let corrupt =
2205        || "sync.local_corrupt: persisted local schema marker is unreadable or invalid".to_owned();
2206    let table_type: Option<String> = conn
2207        .query_row(
2208            "SELECT type FROM sqlite_master WHERE name = '_syncular_meta'",
2209            [],
2210            |row| row.get(0),
2211        )
2212        .optional()
2213        .map_err(schema_marker_read_failure)?;
2214    let Some(table_type) = table_type else {
2215        return Ok(None);
2216    };
2217    if table_type != "table" {
2218        return Err(corrupt().into());
2219    }
2220    // §7.4.2: a duplicated marker cannot be resolved. `query_row` would take
2221    // whichever row SQLite returns first, and an older one would drive a
2222    // destructive reset over a newer replica.
2223    let mut statement = conn
2224        .prepare("SELECT value FROM _syncular_meta WHERE key = ?1")
2225        .map_err(schema_marker_read_failure)?;
2226    let mut rows = statement
2227        .query([LOCAL_SCHEMA_VERSION_KEY])
2228        .map_err(schema_marker_read_failure)?;
2229    let value: Option<String> = rows
2230        .next()
2231        .map_err(schema_marker_read_failure)?
2232        .map(|row| row.get(0))
2233        .transpose()
2234        .map_err(schema_marker_read_failure)?;
2235    if rows.next().map_err(schema_marker_read_failure)?.is_some() {
2236        return Err(corrupt().into());
2237    }
2238    let Some(value) = value else {
2239        let has_descriptor = conn
2240            .query_row(
2241                "SELECT 1 FROM _syncular_meta WHERE key = ?1 LIMIT 1",
2242                [crate::previous_version::LOCAL_SCHEMA_DESCRIPTOR_KEY],
2243                |_| Ok(()),
2244            )
2245            .optional()
2246            .map_err(schema_marker_read_failure)?
2247            .is_some();
2248        if has_descriptor {
2249            return Err(corrupt().into());
2250        }
2251        return Ok(None);
2252    };
2253    if !matches!(value.as_bytes().first(), Some(b'1'..=b'9'))
2254        || !value.bytes().all(|b| b.is_ascii_digit())
2255    {
2256        return Err(corrupt().into());
2257    }
2258    let version = value.parse::<i32>().map_err(|_| corrupt())?;
2259    if version > requested {
2260        return Err(ClientError {
2261            code: "client.schema_downgrade".to_owned(),
2262            message: "persisted local schema is newer than the requested schema".to_owned(),
2263            details: Some(json!({ "persistedVersion": version, "requestedVersion": requested })),
2264            retryable: false,
2265        });
2266    }
2267    Ok(Some(version))
2268}
2269
2270/// The open and recreate constructors' error: a converted core error keeps
2271/// `retryable` for `client.storage_busy` exactly as the String boundary did.
2272fn open_failure(mut error: ClientError) -> ClientError {
2273    error.retryable = error.code == "client.storage_busy";
2274    error
2275}
2276
2277/// Open a replica file. On a browser worker the file must recover a hot
2278/// journal before any statement reads it: `wasm_vfs` replaces the installed
2279/// OPFS VFS's reserved lock callback before the connection opens its file. A
2280/// new browser replica uses 64 KiB pages (§5.3), because every OPFS call costs
2281/// the same whatever its size; a database with tables keeps its page size. Its
2282/// page cache holds 64 MiB, because SQLite's 2,000 KiB default is 31 such pages
2283/// and every cache miss is an OPFS call.
2284fn open_replica(path: &str) -> Result<Connection, String> {
2285    let browser = cfg!(all(target_arch = "wasm32", target_os = "unknown"))
2286        && !path.is_empty()
2287        && path != ":memory:";
2288    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
2289    if browser {
2290        crate::wasm_vfs::disable_foreign_lock_check()?;
2291    }
2292    let conn = Connection::open(path).map_err(|e| format!("open db {path:?}: {e}"))?;
2293    if browser {
2294        conn.execute_batch("PRAGMA page_size = 65536; PRAGMA cache_size = -65536")
2295            .map_err(|e| format!("open db {path:?}: {e}"))?;
2296    }
2297    Ok(conn)
2298}
2299
2300impl SyncClient {
2301    pub fn new_with_identity(
2302        client_id: Option<String>,
2303        schema_json: &Value,
2304        limits: ClientLimits,
2305    ) -> Result<Self, String> {
2306        let resolved = client_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
2307        let conn = Connection::open_in_memory().map_err(|e| e.to_string())?;
2308        Self::with_connection(resolved, schema_json, limits, conn)
2309    }
2310
2311    pub fn new(
2312        client_id: String,
2313        schema_json: &Value,
2314        limits: ClientLimits,
2315    ) -> Result<Self, String> {
2316        let conn = Connection::open_in_memory().map_err(|e| e.to_string())?;
2317        Self::with_connection(client_id, schema_json, limits, conn)
2318    }
2319
2320    /// Build a client backed by an on-disk SQLite database at `path` — the
2321    /// seam a native host (Tauri plugin, FFI file-DB variant) uses to persist
2322    /// across process restarts. `create_tables` runs `IF NOT EXISTS`, so
2323    /// re-opening the same file reuses the persisted rows. Keeps rusqlite out
2324    /// of the command router's dependency set (the router only holds a path).
2325    pub fn open_path(
2326        client_id: String,
2327        schema_json: &Value,
2328        limits: ClientLimits,
2329        path: &str,
2330    ) -> Result<Self, ClientError> {
2331        (|| {
2332            validate_client_limits(&limits)?;
2333            parse_schema_json(schema_json)?;
2334            let conn = open_replica(path)?;
2335            Self::with_connection_identity(Some(client_id), schema_json, limits, conn)
2336        })()
2337        .map_err(open_failure)
2338    }
2339
2340    /// Open a file replica and resolve its client id. Native targets require
2341    /// WAL for the independent snapshot reader; `wasm32-unknown-unknown`
2342    /// accepts the sqlite-wasm worker journal instead. `":memory:"` and `""`
2343    /// name no file: they open an in-memory replica, which has no WAL and no
2344    /// snapshot reader.
2345    pub fn open_path_with_identity(
2346        client_id: Option<String>,
2347        schema_json: &Value,
2348        limits: ClientLimits,
2349        path: &str,
2350    ) -> Result<Self, ClientError> {
2351        Self::open_path_with_identity_journal(
2352            client_id,
2353            schema_json,
2354            limits,
2355            path,
2356            !cfg!(all(target_arch = "wasm32", target_os = "unknown"))
2357                && !path.is_empty()
2358                && path != ":memory:",
2359        )
2360        .map_err(open_failure)
2361    }
2362
2363    fn open_path_with_identity_journal(
2364        client_id: Option<String>,
2365        schema_json: &Value,
2366        limits: ClientLimits,
2367        path: &str,
2368        require_wal: bool,
2369    ) -> Result<Self, ClientError> {
2370        validate_client_limits(&limits)?;
2371        // §7.4.2: an invalid requested version is refused before the replica is
2372        // even created, so a rejected constructor leaves no file behind.
2373        parse_schema_json(schema_json)?;
2374        let conn = open_replica(path)?;
2375        // A file-backed native client uses an independent read connection for
2376        // latency-critical snapshots. WAL is SQLite's intended reader/writer
2377        // concurrency mode: a view read never holds a rollback-journal lock
2378        // that delays the client's next commit. The busy timeout must precede
2379        // this replica's own startup transaction; WAL is applied only after
2380        // startup succeeded, because a refused open must leave the replica's
2381        // journal mode and contents untouched (§7.4.2).
2382        conn.busy_timeout(std::time::Duration::from_millis(250))
2383            .map_err(|error| format!("configure db {path:?} busy timeout: {error}"))?;
2384        // Durability is the caller's contract here, not the VFS default: a
2385        // rollback-journal commit needs FULL before it writes the database
2386        // pages, or a killed worker can leave a half-written image behind.
2387        // WAL below inherits the same setting.
2388        conn.pragma_update(None, "synchronous", "FULL")
2389            .map_err(|error| format!("configure db {path:?} synchronous: {error}"))?;
2390        let client = Self::with_connection_identity(client_id, schema_json, limits, conn)?;
2391        // A browser worker's sqlite-wasm VFS has no WAL mode, and the wasm
2392        // host has no independent snapshot reader. The WAL requirement exists
2393        // for native file replicas, where it is the reader/writer boundary.
2394        if require_wal {
2395            let journal_mode: String = client
2396                .conn
2397                .pragma_update_and_check(None, "journal_mode", "WAL", |row| row.get(0))
2398                .map_err(|error| Self::sqlite_failure(&client.storage_failure, error))?;
2399            if journal_mode != "wal" {
2400                return Err(
2401                    "sync.invalid_request: file-backed client requires WAL journal mode"
2402                        .to_owned()
2403                        .into(),
2404                );
2405            }
2406        }
2407        Ok(client)
2408    }
2409
2410    /// Delete a file replica at `path`, including its `-journal`, `-wal`, and
2411    /// `-shm` sidecars, through the VFS that owns it. Use this after
2412    /// `client.storage_corrupt`: an OPFS SAH pool stores those files under
2413    /// opaque names, so deleting the pool directory behind SQLite bypasses the
2414    /// pool's slot accounting.
2415    ///
2416    /// Close the client and every [`FileQuerySnapshotReader`] on `path` first;
2417    /// a VFS cannot delete a file another handle still owns. A file that does
2418    /// not exist counts as deleted, so a cleanly closed replica without
2419    /// sidecars resets. The next open
2420    /// creates a fresh replica (new client id) and re-bootstraps from the
2421    /// server. A memory replica has nothing to delete and fails with
2422    /// `sync.invalid_request`.
2423    pub fn reset_replica(path: &str) -> Result<(), String> {
2424        if path.is_empty() || path == ":memory:" {
2425            return Err("sync.invalid_request: a memory replica has nothing to reset".to_owned());
2426        }
2427        // SAFETY: a null VFS name asks SQLite for its process-wide default VFS,
2428        // the same one `Connection::open(path)` above selects. `xDelete` is
2429        // that VFS's own function pointer, and `c_name` outlives the call.
2430        let vfs = unsafe { rusqlite::ffi::sqlite3_vfs_find(std::ptr::null()) };
2431        if vfs.is_null() {
2432            return Err("client.storage_io: no SQLite VFS is registered".to_owned());
2433        }
2434        let delete = unsafe { (*vfs).xDelete }
2435            .ok_or_else(|| "client.storage_io: the SQLite VFS cannot delete files".to_owned())?;
2436        for suffix in ["-wal", "-shm", "-journal", ""] {
2437            let file_name = format!("{path}{suffix}");
2438            let c_name = std::ffi::CString::new(file_name.as_str()).map_err(|_| {
2439                format!("sync.invalid_request: replica path {file_name:?} contains a NUL byte")
2440            })?;
2441            // SAFETY: `vfs` and its `xDelete` pointer come from the live
2442            // SQLite library; `c_name` is a valid NUL-terminated path.
2443            let code = unsafe { delete(vfs, c_name.as_ptr(), 1) };
2444            // A cleanly closed WAL replica has no sidecars; a missing file is
2445            // already deleted.
2446            if code != rusqlite::ffi::SQLITE_OK && code != rusqlite::ffi::SQLITE_IOERR_DELETE_NOENT
2447            {
2448                return Err(format!(
2449                    "client.storage_io: deleting replica file {file_name:?} failed with SQLite code {code}"
2450                ));
2451            }
2452        }
2453        Ok(())
2454    }
2455
2456    #[must_use]
2457    pub fn client_id(&self) -> &str {
2458        &self.client_id
2459    }
2460
2461    /// Rotate the caller's client id (§1.5) and return the new one. Use it
2462    /// after a `sync.invalid_client_id` refusal (`recommendedAction:
2463    /// resetClientId`): the next round carries the new id. A live realtime
2464    /// socket is closed so the next connection registers with the new id.
2465    /// The replica and its outbox stay in place; wipe them yourself when the
2466    /// stored data belongs to the account that signed out.
2467    pub fn reset_client_id(&mut self, transport: &mut dyn Transport) -> Result<String, String> {
2468        self.disconnect_realtime(transport);
2469        let client_id = uuid::Uuid::new_v4().to_string();
2470        self.set_meta(CLIENT_ID_KEY, &client_id)?;
2471        self.client_id.clone_from(&client_id);
2472        self.round_failure = None;
2473        Ok(client_id)
2474    }
2475
2476    /// Build a client over a caller-supplied rusqlite connection — the seam a
2477    /// native host (Tauri plugin, FFI file-DB variant) uses to back the core
2478    /// with an on-disk database (`Connection::open(path)`) rather than the
2479    /// default `:memory:`. The connection MUST be fresh (no pre-existing
2480    /// syncular tables); `create_tables` runs `IF NOT EXISTS`, so re-opening
2481    /// the same file across process restarts reuses the persisted rows.
2482    pub fn with_connection(
2483        client_id: String,
2484        schema_json: &Value,
2485        limits: ClientLimits,
2486        conn: Connection,
2487    ) -> Result<Self, String> {
2488        Self::with_connection_identity(Some(client_id), schema_json, limits, conn).map_err(
2489            |error| match error.details.as_ref().and_then(|d| d.get("legacyCause")) {
2490                Some(Value::String(cause)) => cause.clone(),
2491                _ => error.to_string(),
2492            },
2493        )
2494    }
2495
2496    /// [`Self::with_connection`] for `open_path_with_identity`: no requested id
2497    /// means a durable replica's persisted `clientId` wins over a fresh one.
2498    fn with_connection_identity(
2499        client_id: Option<String>,
2500        schema_json: &Value,
2501        limits: ClientLimits,
2502        conn: Connection,
2503    ) -> Result<Self, ClientError> {
2504        validate_client_limits(&limits)?;
2505        let schema = parse_schema_json(schema_json)?;
2506        validate_authority_reads(&schema, &limits.authority_reads)
2507            .map_err(|error| error.to_string())?;
2508        // RFC 0005 D8: resolve the previous-version config before the opening
2509        // reset runs — the capture happens inside it. Bad bounds fail loud.
2510        let previous_version = match limits.previous_version_context {
2511            Some(config) => {
2512                config.validate()?;
2513                Some(config)
2514            }
2515            None => None,
2516        };
2517        let mut client = SyncClient {
2518            #[cfg(feature = "bench-internals")]
2519            benchmark_phases: Recorder::default(),
2520            conn,
2521            schema,
2522            client_id: client_id
2523                .clone()
2524                .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()),
2525            limits,
2526            outbox: Shared::default(),
2527            failed_commits: Shared::default(),
2528            retain_failed_commits: false,
2529            conflicts: Shared::default(),
2530            rejections: Shared::default(),
2531            schema_floor: None,
2532            lease_state: None,
2533            stopped: false,
2534            upgrading: false,
2535            upgrade_kept_tables: false,
2536            sync_needed: false,
2537            realtime_policy: RealtimePolicy::Optional,
2538            realtime_state: RealtimeState::Disconnected,
2539            realtime_reason_code: None,
2540            realtime_retry_delay_ms: None,
2541            presence: HashMap::new(),
2542            now_ms: None,
2543            encryption: crate::values::EncryptionConfig::default(),
2544            security_preflight: false,
2545            security_epoch: 0,
2546            transport_gate: crate::TransportGate::Open,
2547            transport_epoch: 0,
2548            registration_epoch: 0,
2549            previous_version,
2550            insert_sql: RefCell::new(HashMap::new()),
2551            overlay_dirty: OverlayDirty::clean(),
2552            storage_failure: RefCell::new(None),
2553            #[cfg(test)]
2554            overlay_rebuild_count: Cell::new(0),
2555            #[cfg(test)]
2556            acknowledged_replay_count: Cell::new(0),
2557            #[cfg(test)]
2558            outcome_prune_count: Cell::new(0),
2559            #[cfg(test)]
2560            image_chunk_ms: Cell::new(None),
2561            progress: ProgressObserver::default(),
2562            epoch: uuid::Uuid::new_v4().to_string(),
2563            change_queue: VecDeque::new(),
2564            projection_pending_queue: VecDeque::new(),
2565            opening_replica: true,
2566            sync_intent_queue: VecDeque::new(),
2567            scopes_changed: 0,
2568            window_armed: HashSet::new(),
2569            retry_delay_ms: 250,
2570            round_retry_delay_ms: None,
2571            image_chunk_rows: HashMap::new(),
2572            round_failure: None,
2573            active_round: None,
2574            fence_round: None,
2575            last_round: None,
2576            last_change: None,
2577            query_failures: Vec::new(),
2578            coalesced: None,
2579            coalesced_failure: None,
2580        };
2581        // The row write path leans on the prepared-statement cache (two
2582        // insert statements per synced table, plus the bookkeeping
2583        // statements); size it so a multi-table schema never thrashes.
2584        client
2585            .conn
2586            .set_prepared_statement_cache_capacity(64.max(client.schema.tables.len() * 4));
2587        // §7.4.2: one write transaction (SQLite `BEGIN IMMEDIATE`, a reserved
2588        // writer) covers the marker read, the identity check, and every
2589        // bookkeeping/schema write, so a concurrent open that upgraded the
2590        // replica cannot interleave between the guard and the writes, and a
2591        // refusal leaves the replica unchanged.
2592        client
2593            .conn
2594            .execute_batch("BEGIN IMMEDIATE")
2595            .map_err(|error| Self::sqlite_failure(&client.storage_failure, error))?;
2596        let startup = (|| -> Result<(), ClientError> {
2597            // The marker guard runs inside the write transaction, so the version
2598            // it validates is the version every write below commits under.
2599            let marker = read_local_schema_version(&client.conn, client.schema.version)?;
2600            // New app indexes may reference columns that only exist after a
2601            // version-bump reset.
2602            client.create_bookkeeping_tables()?;
2603            match client.get_meta(CLIENT_ID_KEY)? {
2604                Some(existing) => match client_id {
2605                    Some(requested) if existing != requested => {
2606                        return Err(format!(
2607                            "client.identity_mismatch: this database belongs to {existing:?}; refusing to rebind it to {requested:?}"
2608                        )
2609                        .into())
2610                    }
2611                    _ => client.client_id = existing,
2612                },
2613                None => client.set_meta(CLIENT_ID_KEY, &client.client_id)?,
2614            }
2615            client.restore_persisted_state()?;
2616            client.failed_commits = client.load_failed_commits()?.into();
2617            match marker {
2618                None => {
2619                    client.detach_projections(None)?;
2620                    client.create_synced_tables()?;
2621                    client.persist_schema_version()?;
2622                    client.save_unit_scope_schema()?;
2623                }
2624                Some(version) if version == client.schema.version => {
2625                    client.detach_projections(None)?;
2626                    client.create_synced_tables()?;
2627                    // RFC 0005 D1: the same-version open backfills the descriptor
2628                    // for a database first opened by an unaware binary, so the
2629                    // NEXT bump can capture without needing a schema bump first.
2630                    set_local_schema_descriptor(&client.conn, &client.schema)
2631                        .map_err(|error| Self::sqlite_failure(&client.storage_failure, error))?;
2632                    client.save_unit_scope_schema()?;
2633                }
2634                Some(_) => client.run_schema_reset()?,
2635            }
2636            // RFC 0005 D9: the reset sweep cannot see a container whose capture
2637            // committed in its OWN file while the replica's savepoint never
2638            // released — a crash at that seam leaves a container beside a matching
2639            // OLD marker, and the next open at that version runs no reset. Discard
2640            // it before anything can read it. No-op when no container exists.
2641            client.reconcile_previous_version_at_boot()?;
2642            client.clear_satisfied_persisted_schema_floor()?;
2643            client.prune_unknown_units(false)?;
2644            // §7.1/§7.4.4: recover intrinsically codec-invalid persisted values at
2645            // the full startup/reset reconciliation boundary, inside this open
2646            // transaction and after the schema and identity guards, so a commit
2647            // an earlier version accepted is dropped with durable rejection
2648            // evidence before any replay. A table the current schema removed
2649            // keeps the §7.4.4 send-time classification, and an unresolved
2650            // encryption key stays with the send seam because hosts configure
2651            // keys after open.
2652            client.drop_unencodable_outbox(false, None)?;
2653            if marker == Some(client.schema.version)
2654                && (!client.outbox.is_empty()
2655                    || !client.failed_commits.is_empty()
2656                    || client.has_acknowledged_rows()?)
2657            {
2658                // Reconstruct the visible optimistic overlay from the durable
2659                // base plus outbox instead of trusting a process-interrupted
2660                // mirror.
2661                client.overlay_dirty.set(true);
2662                client.rebuild_overlay()?;
2663            }
2664            // Every persisted active unit needs one catch-up pull on
2665            // open: realtime only covers changes after connection, while an
2666            // idempotent setWindow correctly creates no fresh command effect.
2667            // Pending outbox work has the same restart requirement. The core
2668            // owns this intent so native hosts never poll or require an
2669            // application-issued sync().
2670            client.enqueue_startup_sync_if_needed()?;
2671            client
2672                .projection_pending_queue
2673                .extend(client.collect_projection_pending()?);
2674            Ok(())
2675        })();
2676        match startup {
2677            Ok(()) => match client.conn.execute_batch("COMMIT") {
2678                // §4.8: an eviction a crash interrupted finishes before any
2679                // read, with or without a transport; a replica reopened in
2680                // preflight finishes it at activation.
2681                Ok(()) => {
2682                    client.opening_replica = false;
2683                    // §5.11: a purge before 0.105.5 left its words in the
2684                    // full-text index; the first open of a replica that
2685                    // applied one erases it before any read. The record
2686                    // follows the erasure, so an interrupted repair runs
2687                    // again at the next open.
2688                    let purged = client.stored(
2689                        client
2690                            .conn
2691                            .query_row(
2692                                "SELECT 1 FROM _syncular_meta WHERE key LIKE 'localPurge:%' LIMIT 1",
2693                                [],
2694                                |_| Ok(()),
2695                            )
2696                            .optional(),
2697                    )?;
2698                    let repaired = format!("{PURGE_REPAIR_KEY}:erased");
2699                    if purged.is_some() {
2700                        client.erase_purged_pages(PURGE_REPAIR_KEY)?;
2701                    } else if client.get_meta(&repaired)?.is_none() {
2702                        client.set_meta(&repaired, "1")?;
2703                    }
2704                    // §7.3.4: a purge before 0.105.13 left the units over its
2705                    // rows at their cursors. The rows are gone, so once, every
2706                    // unit that covers a recorded target's table catches up
2707                    // from -1, unless a selector on a scope column names none
2708                    // of the unit's effective values.
2709                    let refill = format!("{PURGE_REPAIR_KEY}:refill");
2710                    if client.get_meta(&refill)?.is_none() {
2711                        let rows = client.stored(
2712                            client
2713                                .conn
2714                                .prepare(
2715                                    "SELECT m.key||' '||t.key, json_extract(t.value,'$.table'), s.key, v.value FROM _syncular_meta m, json_each(m.value) t, json_each(t.value,'$.selectors') s, json_each(s.value) v WHERE m.key LIKE 'localPurge:%' AND json_valid(m.value) AND json_type(m.value)='array' AND json_type(t.value)='object'",
2716                                )
2717                                .and_then(|mut statement| {
2718                                    statement
2719                                        .query_map([], |row| {
2720                                            Ok((
2721                                                row.get::<_, String>(0)?,
2722                                                row.get::<_, String>(1)?,
2723                                                row.get::<_, String>(2)?,
2724                                                row.get::<_, String>(3)?,
2725                                            ))
2726                                        })?
2727                                        .collect::<rusqlite::Result<Vec<_>>>()
2728                                }),
2729                        )?;
2730                        let mut targets: BTreeMap<String, (String, BTreeMap<String, Vec<String>>)> =
2731                            BTreeMap::new();
2732                        for (target, table, column, value) in rows {
2733                            targets
2734                                .entry(target)
2735                                .or_insert_with(|| (table, BTreeMap::new()))
2736                                .1
2737                                .entry(column)
2738                                .or_default()
2739                                .push(value);
2740                        }
2741                        for unit in client.stored(load_units(&client.conn))? {
2742                            if unit.status == UnitStatus::Active
2743                                && (unit.cursor != Some(-1) || unit.bootstrap_state.is_some())
2744                                && targets.values().any(|(name, selectors)| {
2745                                    let Some(table) = client.schema.table(name) else {
2746                                        return false;
2747                                    };
2748                                    let Some(effective) = covers(table, &unit.scopes)
2749                                        .then(|| {
2750                                            pair_scopes(&unit.scopes, name, unit.echo.as_deref())
2751                                        })
2752                                        .flatten()
2753                                    else {
2754                                        return false;
2755                                    };
2756                                    table.scope_variables.iter().all(|scope| {
2757                                        let held = effective
2758                                            .iter()
2759                                            .find(|(variable, _)| *variable == scope.variable);
2760                                        match (selectors.get(&scope.column), held) {
2761                                            (Some(values), Some((_, held))) => {
2762                                                held.iter().any(|value| {
2763                                                    value == "*" || values.contains(value)
2764                                                })
2765                                            }
2766                                            _ => true,
2767                                        }
2768                                    })
2769                                })
2770                            {
2771                                client.stored(save_unit(
2772                                    &client.conn,
2773                                    &UnitRecord {
2774                                        cursor: Some(-1),
2775                                        bootstrap_state: None,
2776                                        seeded: Vec::new(),
2777                                        restriction: None,
2778                                        ..unit
2779                                    },
2780                                ))?;
2781                            }
2782                        }
2783                        client.set_meta(&refill, "1")?;
2784                    }
2785                    if !client.security_preflight {
2786                        client.drain_pending_evictions()?;
2787                    }
2788                    Ok(client)
2789                }
2790                Err(error) => {
2791                    let failure = Self::sqlite_failure(&client.storage_failure, error);
2792                    if let Err(rollback) = client.conn.execute_batch("ROLLBACK") {
2793                        // Keep a failed rollback's typed storage classification.
2794                        let _ = Self::sqlite_failure(&client.storage_failure, rollback);
2795                    }
2796                    Err(failure.into())
2797                }
2798            },
2799            Err(error) => {
2800                if let Err(rollback) = client.conn.execute_batch("ROLLBACK") {
2801                    // Keep a failed rollback's typed storage classification.
2802                    let _ = Self::sqlite_failure(&client.storage_failure, rollback);
2803                }
2804                Err(error)
2805            }
2806        }
2807    }
2808
2809    /// Pin the client clock (epoch ms) — the §5.4 expiry check runs
2810    /// against this instead of system time (conformance virtual clock).
2811    pub fn set_now_ms(&mut self, now_ms: i64) {
2812        self.now_ms = Some(std::sync::Arc::new(now_ms.into()));
2813    }
2814
2815    /// The pinned clock, shared: a host that stores into it moves the client
2816    /// clock while a call runs (a virtual clock that advances per request).
2817    pub fn pinned_clock(&self) -> Option<std::sync::Arc<std::sync::atomic::AtomicI64>> {
2818        self.now_ms.clone()
2819    }
2820
2821    /// §5.11: install the client-side encryption keys (`keyId → key bytes`).
2822    /// The command router parses these from the `create` command's
2823    /// `encryption` config (keys as `{$bytes: hex}`).
2824    pub fn set_encryption(&mut self, encryption: crate::values::EncryptionConfig) {
2825        self.encryption = encryption;
2826    }
2827
2828    #[must_use]
2829    pub fn security_lifecycle(&self) -> &'static str {
2830        if self.security_preflight {
2831            "preflight"
2832        } else {
2833            "active"
2834        }
2835    }
2836
2837    #[must_use]
2838    pub fn security_preflight(&self) -> bool {
2839        self.security_preflight
2840    }
2841
2842    /// Host-owned, non-persisted network gate (§8.8). Local operations remain
2843    /// available. `Through` names a pending commit; any other id fails with
2844    /// `sync.outcome_not_found` and leaves the gate unchanged.
2845    pub fn set_transport_gate(
2846        &mut self,
2847        transport: &mut dyn Transport,
2848        state: crate::TransportGate,
2849    ) -> Result<(), ClientError> {
2850        if let crate::TransportGate::Through(id) = &state {
2851            if !self
2852                .outbox
2853                .iter()
2854                .any(|commit| commit.client_commit_id == *id)
2855            {
2856                return Err(ClientError {
2857                    code: "sync.outcome_not_found".to_owned(),
2858                    message: "the commit is not pending".to_owned(),
2859                    details: Some(json!({ "clientCommitId": id })),
2860                    retryable: false,
2861                });
2862            }
2863        }
2864        let closed = state == crate::TransportGate::Closed;
2865        if self.transport_gate != state {
2866            self.sync_intent_queue.clear();
2867            self.move_transport_gate(state);
2868        }
2869        // A captured reply keeps its normal apply/revocation semantics.
2870        if closed && self.active_round.is_none() {
2871            self.disconnect_realtime(transport);
2872        }
2873        Ok(())
2874    }
2875
2876    /// §8.8: a gate change, set by the host or by a `through` fallback. A
2877    /// change batch that rolls back restores the gate and epoch it captured.
2878    fn move_transport_gate(&mut self, state: crate::TransportGate) {
2879        use crate::TransportGate::{Closed, Open, Through};
2880        let wake = state != Closed
2881            && (self.transport_gate == Closed || matches!(state, Open | Through(_)))
2882            && !self.security_preflight;
2883        self.transport_gate = state;
2884        self.transport_epoch = self.transport_epoch.wrapping_add(1);
2885        self.sync_intent_queue.push_back(if wake {
2886            SyncIntent::Interactive
2887        } else {
2888            SyncIntent::None
2889        });
2890    }
2891
2892    /// §8.8: how many outbox commits, from the front, a round may push.
2893    fn pushable_commits(&self) -> usize {
2894        match &self.transport_gate {
2895            crate::TransportGate::Open => self.outbox.len(),
2896            crate::TransportGate::Through(boundary) => self
2897                .outbox
2898                .iter()
2899                .position(|commit| commit.client_commit_id == *boundary)
2900                .map_or(0, |index| index + 1),
2901            crate::TransportGate::Closed | crate::TransportGate::Pull => 0,
2902        }
2903    }
2904
2905    /// §8.8 through fallback: a commit of the prefix leaves the outbox other
2906    /// than by its acknowledgement. Called before the in-memory removal.
2907    fn leave_through(&mut self, client_commit_id: &str) {
2908        if matches!(self.transport_gate, crate::TransportGate::Through(_))
2909            && self
2910                .outbox
2911                .iter()
2912                .take(self.pushable_commits())
2913                .any(|commit| commit.client_commit_id == client_commit_id)
2914        {
2915            self.move_transport_gate(crate::TransportGate::Pull);
2916        }
2917    }
2918
2919    pub fn transport_gate(&self) -> crate::TransportGate {
2920        self.transport_gate.clone()
2921    }
2922
2923    fn transport_closed(&self) -> bool {
2924        self.transport_gate == crate::TransportGate::Closed
2925    }
2926
2927    /// Quarantine this replica: enter the fail-closed gate, release all
2928    /// core-owned key material, and record the gate in the database so
2929    /// reopening re-enters preflight until `activate_security` clears it.
2930    ///
2931    /// Use [`SyncClient::seal_security_on_teardown`] for the shutdown barrier,
2932    /// which must NOT leave that durable mark.
2933    pub fn begin_security_preflight(&mut self) -> Result<(), String> {
2934        let entering = !self.security_preflight;
2935        self.seal_security_on_teardown();
2936        // Persist the quarantine so it survives handle teardown and restart:
2937        // reopening this replica re-enters preflight until activation clears it.
2938        self.set_meta(SECURITY_PREFLIGHT_PENDING_KEY, "1")?;
2939        if entering {
2940            self.emit_status_batch()?;
2941        }
2942        Ok(())
2943    }
2944
2945    /// One change batch carrying the status snapshot (§5.11 lifecycle).
2946    fn emit_status_batch(&mut self) -> Result<(), String> {
2947        self.begin_observation("syncular_status")?;
2948        let batch = ChangeAccumulator {
2949            status: true,
2950            ..ChangeAccumulator::default()
2951        };
2952        self.finish_observation("syncular_status", batch)
2953            .inspect_err(|_| self.rollback_observation("syncular_status"))
2954    }
2955
2956    /// Release core-owned key material as a host tears the client down,
2957    /// WITHOUT recording a quarantine.
2958    ///
2959    /// Shutting an activated client down is not a quarantine event. Persisting
2960    /// the gate here marks every cleanly closed replica as pending, and the
2961    /// next plain `create` is then refused permanently: the reopen path
2962    /// restores the flag from the marker and the create guard rejects it. The
2963    /// in-memory flag still closes the gate for anything still holding this
2964    /// instance, which is all a teardown barrier needs.
2965    pub fn seal_security_on_teardown(&mut self) {
2966        self.cancel_sync_round();
2967        self.security_preflight = true;
2968        self.security_epoch = self.security_epoch.wrapping_add(1);
2969        self.encryption = crate::values::EncryptionConfig::default();
2970        self.sync_intent_queue.clear();
2971    }
2972
2973    /// Install the post-authentication keyring and release the host loop.
2974    pub fn activate_security(
2975        &mut self,
2976        encryption: crate::values::EncryptionConfig,
2977    ) -> Result<(), String> {
2978        if !self.security_preflight {
2979            return Err(
2980                "sync.invalid_request: activateSecurity requires security preflight".to_owned(),
2981            );
2982        }
2983        // §4.8: an interrupted eviction finishes before protected reads open.
2984        self.drain_pending_evictions()?;
2985        self.enqueue_startup_sync_if_needed()?;
2986        self.delete_meta(SECURITY_PREFLIGHT_PENDING_KEY)?;
2987        self.encryption = encryption;
2988        self.security_preflight = false;
2989        // §5.11: rows sealed under a key this keyring now holds open at once.
2990        self.reveal_sealed_rows()
2991            .map_err(|error| format!("{}: {}", error.code, error.message))?;
2992        self.emit_status_batch()
2993    }
2994
2995    /// §5.11: extend the installed keyring while active. The whole input is
2996    /// validated in key-id order before anything changes, so a refusal names
2997    /// the first bad key id in that order; lifecycle, realtime, and the round
2998    /// are untouched, and rows sealed under the new keys reveal at once.
2999    pub fn add_encryption_keys(
3000        &mut self,
3001        mut keys: std::collections::BTreeMap<String, Vec<u8>>,
3002    ) -> Result<(), ClientError> {
3003        let refusal = if self.security_preflight {
3004            Some(ClientError {
3005                code: SECURITY_PREFLIGHT_REQUIRED_CODE.to_owned(),
3006                message: "the local replica is in security preflight; complete quarantine checks and call activateSecurity before accessing protected data".to_owned(),
3007                details: None,
3008                retryable: false,
3009            })
3010        } else {
3011            keys.iter().find_map(|(key_id, bytes)| {
3012                if bytes.len() != 32 {
3013                    Some(invalid_authoring(
3014                        "encryption key must be 32 bytes (AES-256)",
3015                        json!({ "keyId": key_id }),
3016                    ))
3017                } else if self
3018                    .encryption
3019                    .keys
3020                    .get(key_id)
3021                    .is_some_and(|held| held != bytes)
3022                {
3023                    Some(invalid_authoring(
3024                        "encryption key id is already held with different key bytes",
3025                        json!({ "keyId": key_id }),
3026                    ))
3027                } else {
3028                    None
3029                }
3030            })
3031        };
3032        // Native key hygiene: every buffer that is not installed is zeroed
3033        // before drop.
3034        if let Some(error) = refusal {
3035            for bytes in keys.values_mut() {
3036                bytes.fill(0);
3037            }
3038            return Err(error);
3039        }
3040        for (key_id, mut bytes) in keys {
3041            match self.encryption.keys.entry(key_id) {
3042                std::collections::hash_map::Entry::Occupied(_) => bytes.fill(0),
3043                std::collections::hash_map::Entry::Vacant(slot) => {
3044                    slot.insert(bytes);
3045                }
3046            }
3047        }
3048        self.reveal_sealed_rows().map_err(|error| ClientError {
3049            code: error.code,
3050            message: error.message,
3051            details: error.details,
3052            retryable: false,
3053        })
3054    }
3055
3056    fn clock_now_ms(&self) -> i64 {
3057        self.now_ms
3058            .as_ref()
3059            .map_or_else(crate::wall_clock_ms, |clock| {
3060                clock.load(std::sync::atomic::Ordering::Relaxed)
3061            })
3062    }
3063
3064    fn create_bookkeeping_tables(&self) -> Result<(), String> {
3065        let exists = |name: &str| {
3066            self.conn
3067                .query_row(
3068                    "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?1)",
3069                    [name],
3070                    |row| row.get::<_, bool>(0),
3071                )
3072                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
3073        };
3074        let outbox_existed = exists("_syncular_outbox")?;
3075        // Durable client bookkeeping (outbox + units + meta). §7.1: a commit
3076        // queued before the send-attempt marker existed counts as attempted.
3077        self.conn
3078            .execute_batch(
3079                "CREATE TABLE IF NOT EXISTS _syncular_outbox (
3080                   seq INTEGER PRIMARY KEY AUTOINCREMENT,
3081                   commit_id TEXT NOT NULL UNIQUE, ops_json TEXT NOT NULL,
3082                   created_at_ms INTEGER NOT NULL DEFAULT 0,
3083                   attempted INTEGER NOT NULL DEFAULT 1);
3084                 CREATE TABLE IF NOT EXISTS _syncular_row_deliveries (
3085                   tbl TEXT NOT NULL, id TEXT NOT NULL, commit_seq INTEGER NOT NULL, PRIMARY KEY(tbl,id));
3086                 CREATE TABLE IF NOT EXISTS _syncular_acked_rows (
3087                   commit_id TEXT NOT NULL, idx INTEGER NOT NULL, tbl TEXT NOT NULL, id TEXT NOT NULL,
3088                   commit_seq INTEGER NOT NULL, op_json TEXT NOT NULL, intent_json TEXT,
3089                   PRIMARY KEY(commit_id, idx));
3090                 CREATE INDEX IF NOT EXISTS _syncular_acked_rows_row
3091                   ON _syncular_acked_rows(tbl, id);
3092                 CREATE TABLE IF NOT EXISTS _syncular_failed_commits (
3093                   seq INTEGER PRIMARY KEY AUTOINCREMENT, client_commit_id TEXT NOT NULL UNIQUE,
3094                   operations_json TEXT NOT NULL, initial_json TEXT NOT NULL);
3095                 CREATE TABLE IF NOT EXISTS _syncular_commit_outcomes (
3096                   seq INTEGER PRIMARY KEY AUTOINCREMENT,
3097                   client_commit_id TEXT NOT NULL UNIQUE,
3098                   status TEXT NOT NULL CHECK(status IN ('applied', 'cached', 'conflict', 'rejected')),
3099                   recorded_at_ms INTEGER NOT NULL,
3100                   results_json TEXT NOT NULL,
3101                   operations_json TEXT,
3102                   resolution TEXT NOT NULL DEFAULT 'active'
3103                     CHECK(resolution IN ('active', 'resolved_keep_server', 'superseded', 'dismissed')),
3104                   resolved_at_ms INTEGER,
3105                   replacement_client_commit_id TEXT);
3106                 CREATE INDEX IF NOT EXISTS _syncular_commit_outcomes_resolution_seq
3107                   ON _syncular_commit_outcomes(resolution, seq);
3108                 CREATE TABLE IF NOT EXISTS _syncular_units (
3109                   id TEXT PRIMARY KEY, scopes TEXT NOT NULL,
3110                   explicit INTEGER NOT NULL DEFAULT 0,
3111                   status TEXT NOT NULL DEFAULT 'active', reason_code TEXT,
3112                   cursor INTEGER DEFAULT -1, bootstrap_state TEXT,
3113                   seeded TEXT NOT NULL DEFAULT '[]', echo TEXT, applied TEXT, restriction TEXT);
3114                 CREATE TABLE IF NOT EXISTS _syncular_meta (
3115                   key TEXT PRIMARY KEY, value TEXT NOT NULL);
3116                 CREATE TABLE IF NOT EXISTS _syncular_windows (
3117                   base TEXT NOT NULL, unit TEXT NOT NULL, sub_id TEXT NOT NULL,
3118                   PRIMARY KEY (base, unit));
3119                 CREATE INDEX IF NOT EXISTS _syncular_windows_unit ON _syncular_windows(sub_id);
3120                 CREATE TABLE IF NOT EXISTS _syncular_pending_evictions (
3121                   unit_id TEXT NOT NULL, tbl TEXT NOT NULL,
3122                   effective_scopes TEXT NOT NULL, PRIMARY KEY (unit_id, tbl));
3123                 CREATE TABLE IF NOT EXISTS _syncular_blob_commit_refs(
3124                   commit_id TEXT NOT NULL, blob_id TEXT NOT NULL,
3125                   PRIMARY KEY(commit_id, blob_id));
3126                 CREATE INDEX IF NOT EXISTS _syncular_blob_commit_refs_body
3127                   ON _syncular_blob_commit_refs(blob_id);",
3128            )
3129            .map_err(|e| e.to_string())?;
3130        // The §5.6 applied-segment record and the §7.4.3 restriction, added
3131        // after the units table shipped.
3132        for column in ["applied", "restriction"] {
3133            if !self
3134                .conn
3135                .prepare("SELECT 1 FROM pragma_table_info('_syncular_units') WHERE name = ?1")
3136                .and_then(|mut stmt| stmt.exists([column]))
3137                .map_err(|e| e.to_string())?
3138            {
3139                self.conn
3140                    .execute_batch(&format!(
3141                        "ALTER TABLE _syncular_units ADD COLUMN {column} TEXT"
3142                    ))
3143                    .map_err(|e| e.to_string())?;
3144            }
3145        }
3146        // An outbox created before `pendingCommits` carried creation times.
3147        let _ = self.conn.execute_batch(
3148            "ALTER TABLE _syncular_outbox ADD COLUMN created_at_ms INTEGER NOT NULL DEFAULT 0",
3149        );
3150        // Migrate an outcome journal created before failed aggregate
3151        // envelopes were retained. Historical rows intentionally stay NULL.
3152        let _ = self
3153            .conn
3154            .execute_batch("ALTER TABLE _syncular_commit_outcomes ADD COLUMN operations_json TEXT");
3155        // §7.1: an outbox created before the send-attempt marker; every commit
3156        // it holds counts as attempted.
3157        if !self
3158            .conn
3159            .prepare("SELECT 1 FROM pragma_table_info('_syncular_outbox') WHERE name = 'attempted'")
3160            .and_then(|mut stmt| stmt.exists([]))
3161            .map_err(|e| e.to_string())?
3162        {
3163            self.conn
3164                .execute_batch(
3165                    "ALTER TABLE _syncular_outbox ADD COLUMN attempted INTEGER NOT NULL DEFAULT 1",
3166                )
3167                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
3168        }
3169        if self.get_meta(LOCAL_REVISION_KEY)?.is_none() {
3170            self.set_meta(LOCAL_REVISION_KEY, "0")?;
3171        }
3172        // §7.1: `outboxId` names the outbox sequence. A new outbox table starts
3173        // a new sequence, so it replaces the id in the same transaction.
3174        if !outbox_existed || self.get_meta(OUTBOX_ID_KEY)?.is_none() {
3175            self.set_meta(OUTBOX_ID_KEY, &uuid::Uuid::new_v4().to_string())?;
3176        }
3177        // §9: a replica written under wire version 3 keeps its outbox, journal,
3178        // rows and pending evictions and registers its units fresh. Its
3179        // subscriptions, cursors, echoes, resume tokens and window entries go;
3180        // units left from an earlier version 4 life restart.
3181        if exists("_syncular_window_pending_evict")? {
3182            let invalid: bool = self
3183                .conn
3184                .query_row(
3185                    "SELECT EXISTS(SELECT 1 FROM _syncular_window_pending_evict
3186                       WHERE NOT json_valid(effective_scopes)
3187                          OR json_type(effective_scopes) <> 'object'
3188                          OR EXISTS(SELECT 1 FROM json_each(effective_scopes)
3189                               WHERE type <> 'array'
3190                                  OR EXISTS(SELECT 1 FROM json_each(value) AS v
3191                                       WHERE v.type <> 'text')))",
3192                    [],
3193                    |row| row.get(0),
3194                )
3195                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
3196            if invalid {
3197                return Err(
3198                    "sync.local_corrupt: a version 3 pending eviction cannot be upgraded"
3199                        .to_owned(),
3200                );
3201            }
3202            self.conn
3203                .execute_batch(
3204                    "INSERT OR REPLACE INTO _syncular_pending_evictions
3205                       SELECT sub_id, tbl, effective_scopes FROM _syncular_window_pending_evict;
3206                     DROP TABLE _syncular_window_pending_evict;
3207                     DROP TABLE IF EXISTS _syncular_subscriptions;
3208                     DELETE FROM _syncular_windows;",
3209                )
3210                .and_then(|()| reset_units(&self.conn, &BTreeSet::new(), None))
3211                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
3212        }
3213        // §5.9.7 blob cache. Mutable upload state stays off the body row so
3214        // completing a large upload does not rewrite its BLOB record.
3215        if self.schema_has_blobs() {
3216            if exists("_syncular_blobs")? {
3217                let mut statement = self
3218                    .conn
3219                    .prepare("PRAGMA table_info(_syncular_blobs)")
3220                    .map_err(|e| e.to_string())?;
3221                let mut columns = statement
3222                    .query_map([], |row| row.get::<_, String>(1))
3223                    .map_err(|e| e.to_string())?
3224                    .collect::<Result<Vec<_>, _>>()
3225                    .map_err(|e| e.to_string())?;
3226                columns.sort();
3227                let mut expected = vec![
3228                    "blob_id",
3229                    "byte_length",
3230                    "bytes",
3231                    "created_at_ms",
3232                    "media_type",
3233                ];
3234                expected.sort_unstable();
3235                if columns != expected {
3236                    return Err(
3237                        "sync.schema_mismatch: Local blob schema is incompatible".to_owned()
3238                    );
3239                }
3240            } else {
3241                self.conn
3242                    .execute_batch(
3243                        "CREATE TABLE _syncular_blobs(
3244                           blob_id TEXT PRIMARY KEY,
3245                           bytes BLOB NOT NULL,
3246                           byte_length INTEGER NOT NULL,
3247                           media_type TEXT,
3248                           created_at_ms INTEGER NOT NULL);",
3249                    )
3250                    .map_err(|e| e.to_string())?;
3251            }
3252            self.conn
3253                .execute_batch(
3254                    "CREATE TABLE IF NOT EXISTS _syncular_blob_uploads(
3255                       blob_id TEXT PRIMARY KEY,
3256                       media_type TEXT,
3257                       created_at_ms INTEGER NOT NULL);",
3258                )
3259                .map_err(|e| e.to_string())?;
3260        }
3261        Ok(())
3262    }
3263
3264    /// True iff any synced table declares a `blob_ref` column (§5.9).
3265    fn schema_has_blobs(&self) -> bool {
3266        self.schema
3267            .tables
3268            .iter()
3269            .any(|t| t.columns.iter().any(|c| c.ty == ColumnType::BlobRef))
3270    }
3271
3272    // -- meta (§7.4.1 marker, bookkeeping) ------------------------------------
3273
3274    fn get_meta(&self, key: &str) -> Result<Option<String>, String> {
3275        meta_get(&self.conn, key)
3276            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
3277    }
3278
3279    // The caller holds the startup/reset transaction. Either both schema
3280    // records persist or the enclosing operation fails and rolls back.
3281    fn persist_schema_version(&self) -> Result<(), String> {
3282        self.conn
3283            .execute(
3284                "INSERT OR REPLACE INTO _syncular_meta(key,value) VALUES (?1,?2)",
3285                rusqlite::params![LOCAL_SCHEMA_VERSION_KEY, self.schema.version.to_string()],
3286            )
3287            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
3288        set_local_schema_descriptor(&self.conn, &self.schema)
3289            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
3290    }
3291
3292    pub(crate) fn set_meta(&self, key: &str, value: &str) -> Result<(), String> {
3293        meta_set(&self.conn, key, value)
3294            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
3295    }
3296
3297    fn delete_meta(&self, key: &str) -> Result<(), String> {
3298        meta_delete(&self.conn, key)
3299            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
3300    }
3301
3302    /// §7.1: the durable outbox in FIFO order, in schema-agnostic local form.
3303    fn load_outbox(&self) -> Result<Vec<Arc<OutboxCommit>>, String> {
3304        let mut stmt = self
3305            .conn
3306            .prepare("SELECT commit_id, ops_json FROM _syncular_outbox ORDER BY seq ASC")
3307            .map_err(|error| error.to_string())?;
3308        let rows = stmt
3309            .query_map([], |row| {
3310                Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
3311            })
3312            .map_err(|error| error.to_string())?;
3313        let mut commits = Vec::new();
3314        for row in rows {
3315            let (client_commit_id, raw) = row.map_err(|error| error.to_string())?;
3316            let entries: Vec<Value> = serde_json::from_str(&raw).map_err(|error| {
3317                format!("invalid persisted outbox {client_commit_id:?}: {error}")
3318            })?;
3319            let mut ops = Vec::with_capacity(entries.len());
3320            for entry in entries {
3321                let op = entry.get("op").and_then(Value::as_str).unwrap_or("delete");
3322                ops.push(OutboxOp {
3323                    upsert: op == "upsert",
3324                    table: entry
3325                        .get("table")
3326                        .and_then(Value::as_str)
3327                        .ok_or_else(|| "persisted outbox operation missing table".to_owned())?
3328                        .to_owned(),
3329                    row_id: entry
3330                        .get("rowId")
3331                        .and_then(Value::as_str)
3332                        .ok_or_else(|| "persisted outbox operation missing rowId".to_owned())?
3333                        .to_owned(),
3334                    base_version: entry.get("baseVersion").and_then(Value::as_i64),
3335                    // A legacy entry's `changedFields` key is ignored:
3336                    // the values map is the presence set (§6.1).
3337                    values: entry.get("values").and_then(Value::as_object).cloned(),
3338                    insert: entry.get("insert") == Some(&Value::Bool(true)),
3339                });
3340            }
3341            commits.push(Arc::new(OutboxCommit {
3342                client_commit_id,
3343                ops,
3344            }));
3345        }
3346        Ok(commits)
3347    }
3348
3349    fn restore_persisted_state(&mut self) -> Result<(), String> {
3350        self.outbox = self.load_outbox()?.into();
3351
3352        self.prune_commit_outcomes()?;
3353        let active = self.commit_outcomes(CommitOutcomeQuery {
3354            active_only: true,
3355            ..CommitOutcomeQuery::default()
3356        })?;
3357        self.conflicts = active
3358            .iter()
3359            .flat_map(|outcome| outcome.results.iter())
3360            .filter_map(|result| match result {
3361                CommitOperationOutcome::Conflict { conflict } => Some(conflict.clone()),
3362                _ => None,
3363            })
3364            .collect::<Vec<_>>()
3365            .into();
3366        self.rejections = active
3367            .iter()
3368            .flat_map(|outcome| outcome.results.iter())
3369            .filter_map(|result| match result {
3370                CommitOperationOutcome::Error { rejection } => Some(rejection.clone()),
3371                _ => None,
3372            })
3373            .collect::<Vec<_>>()
3374            .into();
3375
3376        self.lease_state = self
3377            .get_meta(LEASE_STATE_KEY)?
3378            .map(|raw| serde_json::from_str(&raw))
3379            .transpose()
3380            .map_err(|error| format!("invalid persisted lease state: {error}"))?;
3381        self.schema_floor = self
3382            .get_meta(SCHEMA_FLOOR_KEY)?
3383            .map(|raw| serde_json::from_str(&raw))
3384            .transpose()
3385            .map_err(|error| format!("invalid persisted schema floor: {error}"))?;
3386        self.stopped = self.schema_floor.is_some();
3387        // A replica left in unactivated preflight reopens gated: the quarantine
3388        // decision persists with the data across handle teardown and restart.
3389        if self.get_meta(SECURITY_PREFLIGHT_PENDING_KEY)?.as_deref() == Some("1") {
3390            self.security_preflight = true;
3391        }
3392        Ok(())
3393    }
3394
3395    fn save_unit_scope_schema(&self) -> Result<(), String> {
3396        let declarations: BTreeMap<_, BTreeMap<_, _>> = self
3397            .schema
3398            .tables
3399            .iter()
3400            .map(|table| {
3401                (
3402                    table.name.clone(),
3403                    table
3404                        .scope_variables
3405                        .iter()
3406                        .map(|scope| {
3407                            (
3408                                scope.variable.clone(),
3409                                [scope.prefix.clone(), scope.column.clone()],
3410                            )
3411                        })
3412                        .collect(),
3413                )
3414            })
3415            .collect();
3416        self.set_meta(
3417            "subscriptionScopeSchema",
3418            &serde_json::to_string(&declarations).expect("scope schema serialization"),
3419        )?;
3420        let generations: BTreeMap<_, _> = self
3421            .schema
3422            .tables
3423            .iter()
3424            .filter_map(|table| Some((&table.name, table.generation.as_ref()?)))
3425            .collect();
3426        self.set_meta(
3427            TABLE_GENERATIONS_KEY,
3428            &serde_json::to_string(&generations).expect("generations serialize"),
3429        )
3430    }
3431
3432    /// Drop units that cover no table of the running schema, with their window
3433    /// registry rows and pending evictions; never translate scopes. At a bump
3434    /// (§7.4.3) a unit also needs every variable unchanged in prefix and column
3435    /// on every table it covered before.
3436    fn prune_unknown_units(&mut self, bump: bool) -> Result<(), String> {
3437        let previous: Option<BTreeMap<String, BTreeMap<String, [String; 2]>>> = if bump {
3438            self.get_meta("subscriptionScopeSchema")?
3439                .map(|raw| serde_json::from_str(&raw))
3440                .transpose()
3441                .map_err(|_| "sync.local_corrupt: invalid persisted scope schema".to_owned())?
3442        } else {
3443            None
3444        };
3445        // A table keeps the variables' meaning when each has the same prefix
3446        // and column as before. An old binary stored no declaration evidence;
3447        // matching names cannot prove unchanged meaning, so the app registers
3448        // again.
3449        let unchanged = |name: &str, variables: &[&String]| {
3450            let (Some(old), Some(table)) = (
3451                previous.as_ref().and_then(|previous| previous.get(name)),
3452                self.schema.table(name),
3453            ) else {
3454                return false;
3455            };
3456            variables.iter().all(|variable| {
3457                table
3458                    .scope_variables
3459                    .iter()
3460                    .find(|scope| &scope.variable == *variable)
3461                    .is_some_and(|scope| {
3462                        old.get(*variable) == Some(&[scope.prefix.clone(), scope.column.clone()])
3463                    })
3464            })
3465        };
3466        let compatible = |scopes: &UnitScopes| {
3467            if !self.schema.tables.iter().any(|table| covers(table, scopes)) {
3468                return false;
3469            }
3470            if !bump {
3471                return true;
3472            }
3473            let Some(previous) = &previous else {
3474                return false;
3475            };
3476            previous.iter().all(|(name, old)| {
3477                !scopes.keys().all(|variable| old.contains_key(variable))
3478                    || unchanged(name, &scopes.keys().collect::<Vec<_>>())
3479            })
3480        };
3481        let mut stale: BTreeSet<String> = self
3482            .stored(load_units(&self.conn))?
3483            .into_iter()
3484            .filter(|unit| !compatible(&unit.scopes))
3485            .map(|unit| unit.id)
3486            .collect();
3487        // A shrunk window's deferred eviction outlives its unit row and keeps
3488        // its per-table scopes. A table the schema no longer has cannot be
3489        // evicted, and at a bump a table whose scope declarations changed must
3490        // not be evicted by the outdated rule.
3491        for (id, table, effective) in self.load_pending_evictions()? {
3492            if self.schema.table(&table).is_none()
3493                || (bump
3494                    && !unchanged(
3495                        &table,
3496                        &effective
3497                            .iter()
3498                            .map(|(variable, _)| variable)
3499                            .collect::<Vec<_>>(),
3500                    ))
3501            {
3502                stale.insert(id);
3503            }
3504        }
3505        for id in &stale {
3506            for sql in [
3507                "DELETE FROM _syncular_windows WHERE sub_id = ?1",
3508                "DELETE FROM _syncular_pending_evictions WHERE unit_id = ?1",
3509                "DELETE FROM _syncular_units WHERE id = ?1",
3510            ] {
3511                self.conn
3512                    .execute(sql, rusqlite::params![id])
3513                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
3514            }
3515        }
3516        Ok(())
3517    }
3518
3519    pub fn local_revision(&self) -> Result<u64, String> {
3520        Ok(self
3521            .get_meta(LOCAL_REVISION_KEY)?
3522            .and_then(|value| value.parse().ok())
3523            .unwrap_or(0))
3524    }
3525
3526    /// §7.5: resolve a snapshot read on the mutable owner connection through
3527    /// the same primitive the read-only sidecar uses, so the command surface
3528    /// and the file sidecar return one revision, rows, coverage, catch-up, and
3529    /// delivery shape. The structured [`QueryReadFailure`] is preserved; an
3530    /// `owner` records its failure (and its next success) in diagnostics.
3531    pub fn snapshot_read(
3532        &mut self,
3533        request: &SnapshotReadRequest<'_>,
3534        owner: Option<QueryOwner<'_>>,
3535    ) -> Result<SnapshotRead, QueryReadFailure> {
3536        let result = snapshot_read_connection(&self.conn, Some(&self.schema), request).and_then(
3537            |mut read| {
3538                for delivery in &mut read.deliveries {
3539                    if let CommitDelivery::Known { outcome, .. } = delivery {
3540                        *outcome = self
3541                            .attach_retained_rows(outcome.clone())
3542                            .map_err(QueryReadFailure::from)?;
3543                    }
3544                }
3545                Ok(read)
3546            },
3547        );
3548        if let Some(owner) = owner {
3549            self.record_query_read(owner, result.as_ref().err());
3550        }
3551        result
3552    }
3553
3554    /// §7.5: one client commit's delivery status with the owner's retained
3555    /// rows: pending, its journal outcome, or an explicit unknown.
3556    pub fn commit_delivery(&mut self, id: &str) -> Result<CommitDelivery, QueryReadFailure> {
3557        let read = self.snapshot_read(
3558            &SnapshotReadRequest {
3559                commit_ids: vec![id.to_owned()],
3560                ..Default::default()
3561            },
3562            None,
3563        )?;
3564        Ok(read
3565            .deliveries
3566            .into_iter()
3567            .next()
3568            .expect("one requested delivery"))
3569    }
3570
3571    #[must_use]
3572    pub fn status_snapshot(&self) -> SyncStatusSnapshot {
3573        SyncStatusSnapshot {
3574            current_schema_version: self.schema.version,
3575            outbox: self.outbox.len(),
3576            upgrading: self.upgrading,
3577            upgrade_kept_tables: self.upgrade_kept_tables,
3578            lease_state: self.lease_state.clone(),
3579            schema_floor: self.schema_floor.clone(),
3580            sync_needed: self.sync_needed,
3581            previous_version_context: self.previous_version_status(),
3582            security_lifecycle: self.security_lifecycle(),
3583        }
3584    }
3585
3586    /// RFC 0005 A2: container presence for a host that must act on it (Diego's
3587    /// rollback precondition), read without creating the file.
3588    fn previous_version_status(&self) -> PreviousVersionStatus {
3589        let Some(replica_path) = self.previous_version_replica_path() else {
3590            return PreviousVersionStatus {
3591                present: false,
3592                created_at_ms: None,
3593            };
3594        };
3595        match crate::previous_version::read_previous_version_record(&replica_path) {
3596            Ok(Some(record)) => PreviousVersionStatus {
3597                present: true,
3598                created_at_ms: Some(record.created_at_ms),
3599            },
3600            _ => PreviousVersionStatus {
3601                present: std::path::Path::new(
3602                    &crate::previous_version::previous_version_container_path(&replica_path),
3603                )
3604                .exists(),
3605                created_at_ms: None,
3606            },
3607        }
3608    }
3609
3610    /// RFC 0005 D7: read captured rows from the previous local schema. `state`
3611    /// is always `previousVersion`; the container never makes
3612    /// `query_snapshot()` coverage complete. Lease stop/expiry, scope
3613    /// revocation, coverage completion and the TTL DISCARD the container and
3614    /// close the read with their own reason.
3615    pub fn previous_version_snapshot(
3616        &self,
3617        spec: &PreviousVersionReadSpec,
3618    ) -> Result<PreviousVersionSnapshot, String> {
3619        let now_ms = self.clock_now_ms();
3620        crate::previous_version::previous_version_snapshot(
3621            &self.conn,
3622            self.previous_version_replica_path().as_deref(),
3623            self.previous_version.as_ref(),
3624            PreviousVersionLifecycle {
3625                lease_inactive: self.previous_version_lease_inactive(now_ms),
3626                scope_revoked: self
3627                    .stored(load_units(&self.conn))?
3628                    .iter()
3629                    .any(|unit| unit.status == UnitStatus::Revoked),
3630                coverage_complete: self.previous_version_coverage_complete()?,
3631            },
3632            now_ms,
3633            self.schema.version,
3634            spec,
3635        )
3636    }
3637
3638    /// RFC 0005 D6: the advisory pre-reset compatibility audit.
3639    pub fn previous_version_audit(
3640        &self,
3641    ) -> Result<Option<crate::previous_version::PreviousVersionAudit>, String> {
3642        crate::previous_version::stored_previous_version_audit(&self.conn)
3643            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
3644    }
3645
3646    /// RFC 0005 A2/D9: the executable downgrade step. Drop the container file
3647    /// and both metadata records, and report whether anything was present.
3648    /// Idempotent: absence is a successful no-op.
3649    pub fn previous_version_discard(
3650        &self,
3651    ) -> Result<crate::previous_version::PreviousVersionDiscardOutcome, String> {
3652        self.drop_previous_version()
3653    }
3654
3655    fn drop_previous_version(
3656        &self,
3657    ) -> Result<crate::previous_version::PreviousVersionDiscardOutcome, String> {
3658        let Some(replica_path) = self.previous_version_replica_path() else {
3659            return Ok(crate::previous_version::PreviousVersionDiscardOutcome {
3660                present: false,
3661                discarded: false,
3662            });
3663        };
3664        crate::previous_version::discard_previous_version(&self.conn, &replica_path)
3665    }
3666
3667    /// RFC 0005 D7: `leaseState.errorCode` or an expired lease.
3668    fn previous_version_lease_inactive(&self, now_ms: i64) -> bool {
3669        let Some(lease) = &self.lease_state else {
3670            return false;
3671        };
3672        if lease.error_code.is_some() {
3673            return true;
3674        }
3675        lease.expires_at_ms.is_some_and(|expires| expires <= now_ms)
3676    }
3677
3678    /// RFC 0005 D7: §7.4.5 replacement coverage — no active unit is
3679    /// bootstrapping. An empty active set is not completion (mirrors the TS
3680    /// predicate exactly).
3681    fn previous_version_coverage_complete(&self) -> Result<bool, String> {
3682        let units = self.stored(load_units(&self.conn))?;
3683        let mut active = units
3684            .iter()
3685            .filter(|unit| unit.status == UnitStatus::Active)
3686            .peekable();
3687        Ok(active.peek().is_some() && !active.any(UnitRecord::bootstrapping))
3688    }
3689
3690    /// RFC 0005 D7: lifetime triggers evaluated once per sync round, after the
3691    /// apply. A container that no longer has a reason to exist is discarded so
3692    /// the rows do not outlive the window they were kept for.
3693    fn previous_version_lifetime_check(&self) {
3694        let Some(config) = self.previous_version.filter(|config| config.enabled) else {
3695            return;
3696        };
3697        let now_ms = self.clock_now_ms();
3698        if self.previous_version_lease_inactive(now_ms) {
3699            let _ = self.drop_previous_version();
3700            return;
3701        }
3702        let Some(replica_path) = self.previous_version_replica_path() else {
3703            return;
3704        };
3705        let Ok(Some(record)) = crate::previous_version::read_previous_version_record(&replica_path)
3706        else {
3707            return;
3708        };
3709        let Ok(units) = load_units(&self.conn) else {
3710            return;
3711        };
3712        if units.iter().any(|unit| unit.status == UnitStatus::Revoked) {
3713            let _ = self.drop_previous_version();
3714            return;
3715        }
3716        if now_ms - record.created_at_ms > config.max_age_ms {
3717            let _ = self.drop_previous_version();
3718            return;
3719        }
3720        if self.previous_version_coverage_complete() == Ok(true) {
3721            let _ = self.drop_previous_version();
3722        }
3723    }
3724
3725    pub fn diagnostics_snapshot(&self) -> Result<ClientDiagnosticsSnapshot, String> {
3726        let registered = self.stored(load_units(&self.conn))?;
3727        // Both meta values in one statement: the FFI host recomputes
3728        // diagnostics after every command.
3729        let (local_revision, replica_cursor): (Option<String>, Option<String>) = self.stored(
3730            self.conn
3731                .prepare_cached(
3732                    "SELECT (SELECT value FROM _syncular_meta WHERE key = ?1),
3733                            (SELECT value FROM _syncular_meta WHERE key = ?2)",
3734                )
3735                .and_then(|mut statement| {
3736                    statement.query_row([LOCAL_REVISION_KEY, REPLICA_CURSOR_KEY], |row| {
3737                        Ok((row.get(0)?, row.get(1)?))
3738                    })
3739                }),
3740        )?;
3741        let mut units = DiagnosticUnits::default();
3742        for unit in &registered {
3743            *match unit.status {
3744                UnitStatus::Revoked => &mut units.revoked,
3745                UnitStatus::Failed => &mut units.failed,
3746                UnitStatus::Active if !unit.bootstrapping() => &mut units.complete,
3747                UnitStatus::Active
3748                    if unit.reason_code.as_deref() == Some("sync.cursor_expired") =>
3749                {
3750                    &mut units.reset
3751                }
3752                UnitStatus::Active => &mut units.bootstrapping,
3753            } += 1;
3754        }
3755        units.reason_codes = registered
3756            .iter()
3757            .filter_map(|unit| unit.reason_code.as_deref().map(Self::diagnostic_code))
3758            .collect::<BTreeSet<_>>()
3759            .into_iter()
3760            .collect();
3761        let captured_at_ms = self.clock_now_ms();
3762        let lease = if let Some(error_code) = self
3763            .lease_state
3764            .as_ref()
3765            .and_then(|state| state.error_code.clone())
3766        {
3767            ClientDiagnosticsLease {
3768                state: "stopped".to_owned(),
3769                expires_at_ms: self
3770                    .lease_state
3771                    .as_ref()
3772                    .and_then(|state| state.expires_at_ms),
3773                error_code: Some(Self::diagnostic_code(&error_code)),
3774            }
3775        } else if let Some(expires_at_ms) = self
3776            .lease_state
3777            .as_ref()
3778            .and_then(|state| state.expires_at_ms)
3779        {
3780            ClientDiagnosticsLease {
3781                state: if expires_at_ms <= captured_at_ms {
3782                    "expired".to_owned()
3783                } else {
3784                    "active".to_owned()
3785                },
3786                expires_at_ms: Some(expires_at_ms),
3787                error_code: None,
3788            }
3789        } else {
3790            ClientDiagnosticsLease {
3791                state: "none".to_owned(),
3792                expires_at_ms: None,
3793                error_code: None,
3794            }
3795        };
3796        let connectivity = match self.last_round.as_ref() {
3797            _ if self.transport_closed() && self.active_round.is_none() => "offline",
3798            Some(round) if round.status == "succeeded" => "online",
3799            Some(round)
3800                if round.status == "failed"
3801                    && matches!(
3802                        round.cause_kind,
3803                        Some(
3804                            crate::TransportCauseKind::Network | crate::TransportCauseKind::Connect
3805                        )
3806                    ) =>
3807            {
3808                "offline"
3809            }
3810            Some(round) if round.status == "failed" && round.http_status.is_some() => "online",
3811            _ => "unknown",
3812        };
3813        Ok(ClientDiagnosticsSnapshot {
3814            version: CLIENT_DIAGNOSTICS_VERSION,
3815            captured_at_ms,
3816            host: ClientDiagnosticsHost {
3817                kind: "direct".to_owned(),
3818                role: "single".to_owned(),
3819                connectivity: connectivity.to_owned(),
3820                realtime: self.realtime_state,
3821                realtime_policy: self.realtime_policy,
3822                realtime_reason_code: self.realtime_reason_code.clone(),
3823                realtime_retry_delay_ms: self.realtime_retry_delay_ms,
3824            },
3825            security_lifecycle: self.security_lifecycle().to_owned(),
3826            schema: ClientDiagnosticsSchema {
3827                current_version: self.schema.version,
3828                upgrading: self.upgrading,
3829                required_version: self
3830                    .schema_floor
3831                    .as_ref()
3832                    .and_then(|floor| floor.required_schema_version),
3833                latest_version: self
3834                    .schema_floor
3835                    .as_ref()
3836                    .and_then(|floor| floor.latest_schema_version),
3837            },
3838            replica: ClientDiagnosticsReplica {
3839                local_revision: local_revision
3840                    .and_then(|value| value.parse::<u64>().ok())
3841                    .unwrap_or(0)
3842                    .to_string(),
3843                sync_needed: self.sync_needed,
3844                pending_outbox: self.outbox.len(),
3845            },
3846            lease,
3847            active_units: registered
3848                .iter()
3849                .filter(|unit| unit.status == UnitStatus::Active)
3850                .count(),
3851            units,
3852            replica_cursor: replica_cursor.map_or(Ok(-1), |raw| {
3853                raw.parse()
3854                    .map_err(|_| "sync.local_corrupt: persisted unit state is invalid".to_owned())
3855            })?,
3856            last_round: self.last_round.clone(),
3857            last_change: self.last_change.clone(),
3858            storage: self.diagnostics_storage(),
3859            query_failures: self.query_failures.clone(),
3860        })
3861    }
3862
3863    fn diagnostics_storage(&self) -> ClientDiagnosticsStorage {
3864        let read = || -> Result<ClientDiagnosticsStorage, rusqlite::Error> {
3865            let page_count: i64 = self
3866                .conn
3867                .query_row("PRAGMA page_count", [], |row| row.get(0))?;
3868            let page_size: i64 = self
3869                .conn
3870                .query_row("PRAGMA page_size", [], |row| row.get(0))?;
3871            // One cached aggregate, since the FFI host recomputes diagnostics
3872            // after every command; every invocation still reads current storage.
3873            let (outbox_bytes, outcome_entries, outcome_bytes): (i64, i64, i64) = self
3874                .conn
3875                .prepare_cached(
3876                    "SELECT (SELECT COALESCE(SUM(LENGTH(ops_json)), 0) FROM _syncular_outbox),
3877                            COUNT(*), COALESCE(SUM(LENGTH(results_json) + COALESCE(LENGTH(operations_json), 0)), 0)
3878                       FROM _syncular_commit_outcomes",
3879                )?
3880                .query_row([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))?;
3881            let blob_bytes = if self.schema_has_blobs() {
3882                self.conn
3883                    .prepare_cached("SELECT COALESCE(SUM(byte_length), 0) FROM _syncular_blobs")?
3884                    .query_row([], |row| row.get(0))?
3885            } else {
3886                0
3887            };
3888            let pressure = self
3889                .limits
3890                .blob_cache_max_bytes
3891                .is_some_and(|limit| blob_bytes > limit);
3892            Ok(ClientDiagnosticsStorage {
3893                status: if pressure { "pressure" } else { "healthy" }.to_owned(),
3894                database_bytes_approx: Some(page_count.saturating_mul(page_size).max(0)),
3895                pending_outbox_bytes_approx: Some(outbox_bytes.max(0)),
3896                retained_outcome_bytes_approx: Some(outcome_bytes.max(0)),
3897                retained_outcome_entries: Some(outcome_entries.max(0)),
3898                blob_cache_bytes_approx: Some(blob_bytes.max(0)),
3899                pressure_reason_code: pressure.then(|| "client.blob_cache_over_limit".to_owned()),
3900            })
3901        };
3902        read().unwrap_or_else(|_| ClientDiagnosticsStorage {
3903            status: "unreadable".to_owned(),
3904            database_bytes_approx: None,
3905            pending_outbox_bytes_approx: None,
3906            retained_outcome_bytes_approx: None,
3907            retained_outcome_entries: None,
3908            blob_cache_bytes_approx: None,
3909            pressure_reason_code: None,
3910        })
3911    }
3912
3913    pub fn drain_change_batches(&mut self) -> Vec<ClientChangeBatch> {
3914        self.change_queue.drain(..).collect()
3915    }
3916
3917    pub fn drain_sync_intents(&mut self) -> Vec<SyncIntent> {
3918        let intents = self.sync_intent_queue.drain(..).collect();
3919        if !self.transport_closed() {
3920            intents
3921        } else {
3922            vec![SyncIntent::None]
3923        }
3924    }
3925
3926    /// §8.7 host announcement: the number of `scopes` events received since
3927    /// the last drain. The event changes no sync state; the host surfaces each
3928    /// one to the app, whose discovery registers the newly readable units.
3929    pub fn drain_scopes_changed(&mut self) -> usize {
3930        std::mem::take(&mut self.scopes_changed)
3931    }
3932
3933    fn schedule_background_retry(&mut self) -> u64 {
3934        let delay_ms = self.retry_delay_ms;
3935        self.sync_intent_queue
3936            .push_back(SyncIntent::Background { delay_ms });
3937        self.retry_delay_ms = (self.retry_delay_ms * 2).min(30_000);
3938        self.round_retry_delay_ms = Some(delay_ms);
3939        delay_ms
3940    }
3941
3942    fn reset_background_retry(&mut self) {
3943        self.retry_delay_ms = 250;
3944    }
3945
3946    fn retryable_transport_code(code: &str) -> bool {
3947        code == "transport.failed"
3948            || code == "transport.timeout"
3949            || code == "transport.unavailable"
3950            || code == "sync.transport_failed"
3951    }
3952
3953    /// §1.8: the transport reported a refused or unreachable endpoint. The
3954    /// native transport says `connect` (DNS failure, connection refused,
3955    /// reset, or aborted); a browser fetch transport says `network`. Repeating
3956    /// the request on a backoff repairs neither, so no retry is scheduled.
3957    fn unreachable_transport(details: &Option<serde_json::Value>) -> bool {
3958        matches!(
3959            details
3960                .as_ref()
3961                .and_then(|details| details.get("causeKind"))
3962                .and_then(serde_json::Value::as_str),
3963            Some("connect" | "network")
3964        )
3965    }
3966
3967    /// §1.5: a segment fetch that fails inside an otherwise complete round is
3968    /// invisible to the server (the round response arrived whole), so its code
3969    /// rides the following requests like a socket-round failure. A code the
3970    /// frame grammar rejects is not reportable and the previous code stays.
3971    fn segment_fetch_failed(&mut self, error: TransportError) -> SectionError {
3972        if ssp2::model::valid_round_failure_code(&error.code) {
3973            self.round_failure = Some(error.code.clone());
3974        }
3975        SectionError::Transport(error)
3976    }
3977
3978    /// A failed round worth a background retry: a transport failure, or a
3979    /// §10.2 code the catalog marks retryable (clients may hardcode the
3980    /// catalog metadata, §10.1). Matches the TypeScript core, which retries
3981    /// on the server's `retryable` flag.
3982    fn retryable_failure_code(code: &str) -> bool {
3983        Self::retryable_transport_code(code)
3984            || matches!(
3985                code,
3986                "sync.auth_required"
3987                    | "sync.auth_lease_required"
3988                    | "sync.auth_lease_revoked"
3989                    | "sync.internal_error"
3990                    | "sync.idempotency_cache_miss"
3991                    | "sync.schema_not_ready"
3992                    | "sync.segment_build_timeout"
3993                    | "sync.segment_store_unavailable"
3994                    | "sync.segment_expired"
3995                    | "sync.rate_limited"
3996                    | "sync.websocket_connection_limit"
3997                    | "sync.idle_timeout"
3998            )
3999    }
4000
4001    fn diagnostic_code(code: &str) -> String {
4002        let valid = !code.is_empty()
4003            && code.len() <= 96
4004            && code.contains('.')
4005            && code
4006                .bytes()
4007                .next()
4008                .is_some_and(|byte| byte.is_ascii_lowercase())
4009            && code.bytes().all(|byte| {
4010                byte.is_ascii_lowercase()
4011                    || byte.is_ascii_digit()
4012                    || matches!(byte, b'.' | b'_' | b'-')
4013            });
4014        if valid {
4015            code.to_owned()
4016        } else {
4017            "client.unknown_failure".to_owned()
4018        }
4019    }
4020
4021    fn set_sync_needed(&mut self, value: bool, interactive: bool) {
4022        if self.sync_needed != value {
4023            if self.begin_observation("syncular_status").is_ok() {
4024                self.sync_needed = value;
4025                let batch = ChangeAccumulator {
4026                    status: true,
4027                    ..ChangeAccumulator::default()
4028                };
4029                if self.finish_observation("syncular_status", batch).is_err() {
4030                    self.rollback_observation("syncular_status");
4031                }
4032            } else {
4033                self.sync_needed = value;
4034            }
4035        }
4036        if value && interactive {
4037            self.sync_intent_queue.push_back(SyncIntent::Interactive);
4038        }
4039    }
4040
4041    /// A unit-store result: a row that does not parse is `sync.local_corrupt`;
4042    /// every other SQLite error keeps its storage classification.
4043    fn stored<T>(&self, result: rusqlite::Result<T>) -> Result<T, String> {
4044        result.map_err(|error| match error {
4045            rusqlite::Error::FromSqlConversionFailure(..) => {
4046                "sync.local_corrupt: persisted unit state is invalid".to_owned()
4047            }
4048            error => Self::sqlite_failure(&self.storage_failure, error),
4049        })
4050    }
4051
4052    fn sqlite_failure(
4053        storage_failure: &RefCell<Option<QueryReadFailure>>,
4054        error: rusqlite::Error,
4055    ) -> String {
4056        let message = error.to_string();
4057        let failure = QueryReadFailure::from(error);
4058        let code = failure.code;
4059        if code.is_some() && storage_failure.borrow().is_none() {
4060            *storage_failure.borrow_mut() = Some(failure);
4061        }
4062        match code {
4063            Some(code) => format!("{code}: {message}"),
4064            None => message,
4065        }
4066    }
4067
4068    fn begin_observation(&self, name: &str) -> Result<(), String> {
4069        if let Some(failure) = &self.coalesced_failure {
4070            return Err(failure.clone());
4071        }
4072        // SQLite rolls a whole transaction back on some I/O and capacity
4073        // errors; later frames must not commit on their own after that.
4074        if self.coalesced.is_some() && self.conn.is_autocommit() {
4075            return Err("the coalesced apply transaction was rolled back".to_owned());
4076        }
4077        self.conn
4078            .execute_batch(&format!("SAVEPOINT {name}"))
4079            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
4080    }
4081
4082    /// SPEC §1.4 rule 4: open a coalesced apply transaction unless a caller
4083    /// already owns one.
4084    fn begin_coalesced_apply(&mut self) -> Result<(), String> {
4085        if self.coalesced.is_some() || !self.conn.is_autocommit() {
4086            return Ok(());
4087        }
4088        self.conn
4089            .execute_batch("BEGIN")
4090            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4091        self.coalesced = Some(CoalescedApply {
4092            rows: 0,
4093            rollback: self.capture(),
4094        });
4095        Ok(())
4096    }
4097
4098    fn capture(&self) -> Rollback {
4099        Rollback {
4100            outbox: self.outbox.clone(),
4101            failed_commits: self.failed_commits.clone(),
4102            conflicts: self.conflicts.clone(),
4103            rejections: self.rejections.clone(),
4104            schema_floor: self.schema_floor.clone(),
4105            lease_state: self.lease_state.clone(),
4106            stopped: self.stopped,
4107            upgrading: self.upgrading,
4108            upgrade_kept_tables: self.upgrade_kept_tables,
4109            sync_needed: self.sync_needed,
4110            active_round: self.active_round,
4111            overlay_dirty: self.overlay_dirty.snapshot(),
4112            transport_gate: self.transport_gate.clone(),
4113            transport_epoch: self.transport_epoch,
4114            change_queue: self.change_queue.len(),
4115            projection_pending_queue: self.projection_pending_queue.len(),
4116            sync_intent_queue: self.sync_intent_queue.len(),
4117            last_change: self.last_change.clone(),
4118        }
4119    }
4120
4121    fn restore(&mut self, rollback: Rollback) {
4122        self.outbox = rollback.outbox;
4123        self.failed_commits = rollback.failed_commits;
4124        self.conflicts = rollback.conflicts;
4125        self.rejections = rollback.rejections;
4126        self.schema_floor = rollback.schema_floor;
4127        self.lease_state = rollback.lease_state;
4128        self.stopped = rollback.stopped;
4129        self.upgrading = rollback.upgrading;
4130        self.upgrade_kept_tables = rollback.upgrade_kept_tables;
4131        self.sync_needed = rollback.sync_needed;
4132        self.active_round = rollback.active_round;
4133        self.transport_gate = rollback.transport_gate;
4134        self.transport_epoch = rollback.transport_epoch;
4135        self.overlay_dirty.restore(rollback.overlay_dirty);
4136        self.change_queue.truncate(rollback.change_queue);
4137        self.projection_pending_queue
4138            .truncate(rollback.projection_pending_queue);
4139        self.sync_intent_queue.truncate(rollback.sync_intent_queue);
4140        self.last_change = rollback.last_change;
4141    }
4142
4143    /// Account the rows of the next frame or block. A unit that would take the
4144    /// coalesced transaction past the bound commits the earlier units first.
4145    fn coalesce_unit(&mut self, rows: usize) -> Result<(), String> {
4146        let Some(open) = &self.coalesced else {
4147            return Ok(());
4148        };
4149        if open.rows > 0 && open.rows + rows > COALESCED_APPLY_ROWS {
4150            self.commit_coalesced_apply()?;
4151            self.begin_coalesced_apply()?;
4152        }
4153        if let Some(open) = &mut self.coalesced {
4154            open.rows += rows;
4155        }
4156        Ok(())
4157    }
4158
4159    /// COMMIT the coalesced transaction. A failed COMMIT rolls every coalesced
4160    /// frame back, restores the in-memory state of its `BEGIN`, drops the
4161    /// change batches and sync intents queued since, and fails the rest of the
4162    /// response.
4163    fn commit_coalesced_apply(&mut self) -> Result<(), String> {
4164        let Some(open) = self.coalesced.take() else {
4165            return Ok(());
4166        };
4167        let committed = if self.conn.is_autocommit() {
4168            Err("the coalesced apply transaction was rolled back".to_owned())
4169        } else {
4170            self.collect_projection_pending().and_then(|pending| {
4171                self.stored(self.conn.execute_batch("COMMIT"))?;
4172                self.projection_pending_queue.extend(pending);
4173                Ok(())
4174            })
4175        };
4176        let Err(error) = committed else {
4177            return Ok(());
4178        };
4179        if !self.conn.is_autocommit() {
4180            if let Err(rollback) = self.conn.execute_batch("ROLLBACK") {
4181                let _ = Self::sqlite_failure(&self.storage_failure, rollback);
4182            }
4183        }
4184        self.restore(open.rollback);
4185        self.coalesced_failure = Some(error.clone());
4186        Err(error)
4187    }
4188
4189    /// End the response's coalescing: COMMIT what is open and clear a failure.
4190    fn finish_coalesced_apply(&mut self) -> Result<(), String> {
4191        let committed = self.commit_coalesced_apply();
4192        match self.coalesced_failure.take() {
4193            Some(failure) => Err(failure),
4194            None => committed,
4195        }
4196    }
4197
4198    fn rollback_observation(&self, name: &str) {
4199        if let Err(error) = self
4200            .conn
4201            .execute_batch(&format!("ROLLBACK TO {name}; RELEASE {name}"))
4202        {
4203            if let Some(failure) = self.storage_failure.borrow_mut().as_mut() {
4204                if failure.rollback_failure.is_none() {
4205                    failure.rollback_failure = Some(Box::new(QueryReadFailure::from(error)));
4206                }
4207            }
4208        }
4209    }
4210
4211    fn finish_observation(
4212        &mut self,
4213        name: &str,
4214        mut batch: ChangeAccumulator,
4215    ) -> Result<(), String> {
4216        #[cfg(feature = "bench-internals")]
4217        let _phase = self.benchmark_phases.start(Phase::ObservationCommit);
4218        // §8.8: an acknowledged boundary ends a `through` gate.
4219        if matches!(self.transport_gate, crate::TransportGate::Through(_))
4220            && self.pushable_commits() == 0
4221        {
4222            self.move_transport_gate(crate::TransportGate::Pull);
4223        }
4224        for table in &self.schema.tables {
4225            for projection in &table.local_projections {
4226                if batch.tables.contains_key(&table.name)
4227                    || projection
4228                        .dependencies
4229                        .iter()
4230                        .any(|dep| batch.tables.contains_key(&dep.table))
4231                {
4232                    batch.table(&projection.name);
4233                }
4234            }
4235        }
4236        if self.failed_commits.iter().any(|(commit, _)| {
4237            commit
4238                .ops
4239                .iter()
4240                .any(|operation| batch.tables.contains_key(&operation.table))
4241        }) {
4242            batch.outcomes = true;
4243        }
4244        let projection_pending = if self.coalesced.is_none() && !self.opening_replica {
4245            self.collect_projection_pending()?
4246        } else {
4247            Vec::new()
4248        };
4249        if !batch.touched() {
4250            self.conn
4251                .execute_batch(&format!("RELEASE {name}"))
4252                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4253            self.projection_pending_queue.extend(projection_pending);
4254            return Ok(());
4255        }
4256        let revision = self
4257            .local_revision()?
4258            .checked_add(1)
4259            .ok_or_else(|| "local revision exhausted u64".to_owned())?;
4260        self.conn
4261            .execute(
4262                "INSERT OR REPLACE INTO _syncular_meta(key, value) VALUES (?1, ?2)",
4263                rusqlite::params![LOCAL_REVISION_KEY, revision.to_string()],
4264            )
4265            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4266        let status = batch.status.then(|| self.status_snapshot());
4267        let event = ClientChangeBatch {
4268            revision: revision.to_string(),
4269            tables: batch
4270                .tables
4271                .into_iter()
4272                .map(|(table, scope_keys)| TableChange {
4273                    table,
4274                    scope_keys: scope_keys.map(|keys| keys.into_iter().collect()),
4275                })
4276                .collect(),
4277            windows: batch
4278                .windows
4279                .into_iter()
4280                .map(|(base_key, units)| WindowChange {
4281                    base_key,
4282                    units: units.into_iter().collect(),
4283                })
4284                .collect(),
4285            status,
4286            conflicts_changed: batch.conflicts,
4287            rejections_changed: batch.rejections,
4288            outcomes_changed: batch.outcomes,
4289            applied_commits: Vec::new(),
4290        };
4291        self.conn
4292            .execute_batch(&format!("RELEASE {name}"))
4293            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4294        let mut diagnostic_tables = event
4295            .tables
4296            .iter()
4297            .map(|entry| entry.table.clone())
4298            .collect::<BTreeSet<_>>()
4299            .into_iter()
4300            .collect::<Vec<_>>();
4301        // §7.6: the selected variables of the changed window bases.
4302        let mut diagnostic_windows = event
4303            .windows
4304            .iter()
4305            .map(|entry| {
4306                entry
4307                    .base_key
4308                    .split('\0')
4309                    .next()
4310                    .unwrap_or_default()
4311                    .to_owned()
4312            })
4313            .collect::<BTreeSet<_>>()
4314            .into_iter()
4315            .collect::<Vec<_>>();
4316        let domains_truncated = diagnostic_tables.len() > MAX_DIAGNOSTIC_DOMAINS
4317            || diagnostic_windows.len() > MAX_DIAGNOSTIC_DOMAINS;
4318        diagnostic_tables.truncate(MAX_DIAGNOSTIC_DOMAINS);
4319        diagnostic_windows.truncate(MAX_DIAGNOSTIC_DOMAINS);
4320        self.last_change = Some(DiagnosticLastChange {
4321            revision: event.revision.clone(),
4322            recorded_at_ms: self.clock_now_ms(),
4323            tables: diagnostic_tables,
4324            windows: diagnostic_windows,
4325            domains_truncated,
4326            status_changed: event.status.is_some(),
4327            conflicts_changed: event.conflicts_changed,
4328            rejections_changed: event.rejections_changed,
4329            outcomes_changed: event.outcomes_changed,
4330        });
4331        self.change_queue.push_back(event);
4332        self.projection_pending_queue.extend(projection_pending);
4333        Ok(())
4334    }
4335
4336    fn record_scope_map(
4337        &self,
4338        batch: &mut ChangeAccumulator,
4339        table_name: &str,
4340        scopes: &[(String, Vec<String>)],
4341    ) {
4342        let Some(table) = self.schema.table(table_name) else {
4343            return;
4344        };
4345        // A bulk scoped delete whose map leaves a declared variable unnamed
4346        // cannot list the deleted rows' keys for it: the change is table-wide.
4347        if table.scope_variables.iter().any(|scope| {
4348            !scopes
4349                .iter()
4350                .any(|(variable, _)| *variable == scope.variable)
4351        }) {
4352            batch.table(table_name);
4353            return;
4354        }
4355        for (variable, values) in scopes {
4356            let Some(scope) = table
4357                .scope_variables
4358                .iter()
4359                .find(|scope| &scope.variable == variable)
4360            else {
4361                continue;
4362            };
4363            for value in values {
4364                batch.scope(table_name, format!("{}:{value}", scope.prefix));
4365            }
4366        }
4367    }
4368
4369    /// Record a row's current scope keys from the base or visible table.
4370    fn record_row_scopes(
4371        &self,
4372        batch: &mut ChangeAccumulator,
4373        table_name: &str,
4374        row_id: &str,
4375        base: bool,
4376    ) -> bool {
4377        let Some(table) = self.schema.table(table_name) else {
4378            return false;
4379        };
4380        if table.scope_variables.is_empty() {
4381            return false;
4382        }
4383        let columns = table
4384            .scope_variables
4385            .iter()
4386            .map(|scope| quote_ident(&scope.column))
4387            .collect::<Vec<_>>()
4388            .join(", ");
4389        let full_table = if base {
4390            base_table(table_name)
4391        } else {
4392            visible_table(table_name)
4393        };
4394        let sql = format!(
4395            "SELECT {columns} FROM {full_table} WHERE {} LIMIT 1",
4396            row_id_predicate(table)
4397        );
4398        let Ok(mut stmt) = self.conn.prepare_cached(&sql) else {
4399            return false;
4400        };
4401        let values = stmt.query_row(rusqlite::params![row_id], |row| {
4402            let mut values = Vec::with_capacity(table.scope_variables.len());
4403            for index in 0..table.scope_variables.len() {
4404                values.push(row.get::<_, Option<String>>(index)?);
4405            }
4406            Ok(values)
4407        });
4408        let Ok(values) = values else {
4409            return false;
4410        };
4411        let mut recorded = false;
4412        for (scope, value) in table.scope_variables.iter().zip(values) {
4413            if let Some(value) = value {
4414                batch.scope(table_name, format!("{}:{value}", scope.prefix));
4415                recorded = true;
4416            }
4417        }
4418        recorded
4419    }
4420
4421    fn record_commit_changes(
4422        &self,
4423        batch: &mut ChangeAccumulator,
4424        tables: &[String],
4425        changes: &[ssp2::model::Change],
4426    ) {
4427        #[cfg(feature = "bench-internals")]
4428        let _phase = self.benchmark_phases.start(Phase::ObservationPrepare);
4429        for change in changes {
4430            let Some(table_name) = tables.get(change.table_index as usize) else {
4431                continue;
4432            };
4433            let mut precise = self.record_row_scopes(batch, table_name, &change.row_id, true);
4434            if let Some(table) = self.schema.table(table_name) {
4435                for (variable, value) in &change.scopes {
4436                    if let Some(scope) = table
4437                        .scope_variables
4438                        .iter()
4439                        .find(|scope| &scope.variable == variable)
4440                    {
4441                        batch.scope(table_name, format!("{}:{value}", scope.prefix));
4442                        precise = true;
4443                    }
4444                }
4445            }
4446            if !precise {
4447                batch.table(table_name);
4448            }
4449        }
4450    }
4451
4452    /// Whether a base or visible row matches the scope predicate; `false`
4453    /// without a local scope-column mapping. A SQLite failure is an error.
4454    fn scoped_rows_exist(
4455        &self,
4456        table_name: &str,
4457        effective: &[(String, Vec<String>)],
4458        owners: &[Vec<(String, Vec<String>)>],
4459    ) -> Result<bool, String> {
4460        let Some(table) = self.schema.table(table_name) else {
4461            return Ok(false);
4462        };
4463        let Ok(Some((predicate, params))) = local_scope_predicate(table, effective, owners) else {
4464            return Ok(false);
4465        };
4466        for source in [base_table(table_name), visible_table(table_name)] {
4467            if self
4468                .conn
4469                .query_row(
4470                    &format!("SELECT EXISTS(SELECT 1 FROM {source} WHERE {predicate})"),
4471                    rusqlite::params_from_iter(&params),
4472                    |row| row.get::<_, bool>(0),
4473                )
4474                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
4475            {
4476                return Ok(true);
4477            }
4478        }
4479        Ok(false)
4480    }
4481
4482    /// §5.6 first-page clear of `unit_id`'s pair: delete its rows except
4483    /// those another owner covers (§3.3), failing closed without a local
4484    /// scope-column mapping. Owners are read only when a row matches, inside
4485    /// the caller's transaction. Returns whether rows matched.
4486    fn clear_scope(
4487        &mut self,
4488        table: &TableSchema,
4489        effective: &[(String, Vec<String>)],
4490        unit_id: &str,
4491    ) -> Result<bool, SectionError> {
4492        let storage = |message| SectionError::Abort("storage.failed".to_owned(), message);
4493        let matched = self
4494            .scoped_rows_exist(&table.name, effective, &[])
4495            .map_err(storage)?;
4496        let owners = if matched {
4497            unit_owners(
4498                &self.stored(load_units(&self.conn)).map_err(storage)?,
4499                table,
4500                unit_id,
4501            )
4502        } else {
4503            Vec::new()
4504        };
4505        let changed = matched
4506            && (owners.is_empty()
4507                || self
4508                    .scoped_rows_exist(&table.name, effective, &owners)
4509                    .map_err(storage)?);
4510        if !self
4511            .purge_scope_rows(&table.name, effective, &owners)
4512            .map_err(storage)?
4513        {
4514            return Err(SectionError::FailClosed);
4515        }
4516        Ok(changed)
4517    }
4518
4519    /// §7.4.5: true while a schema-bump reset + first re-bootstrap runs.
4520    pub fn upgrading(&self) -> bool {
4521        self.upgrading
4522    }
4523
4524    /// §7.4.2 "app ships new code": swap to a NEW generated schema while
4525    /// keeping this client's local database (identity, outbox, tables). The
4526    /// §7.4.1 marker check then fires the wipe/re-bootstrap flow when the
4527    /// version increases. Recreation runs the same marker guard as opening
4528    /// a durable replica, holds the guard and every write it authorizes under
4529    /// one write transaction, and preserves the current client (compiled
4530    /// schema, outbox, tables) on refusal.
4531    pub fn recreate_with_schema(&mut self, schema_json: &Value) -> Result<(), ClientError> {
4532        (|| -> Result<(), ClientError> {
4533            let new_schema = parse_schema_json(schema_json)?;
4534            validate_authority_reads(&new_schema, &self.limits.authority_reads)
4535                .map_err(|error| error.to_string())?;
4536            // §3.3: a reopened client remembers no re-armed window unit.
4537            self.window_armed.clear();
4538            self.conn
4539                .execute_batch("BEGIN IMMEDIATE")
4540                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4541            self.opening_replica = true;
4542            let prior_schema = std::mem::replace(&mut self.schema, new_schema);
4543            // §7.4.3/§7.4.4: a reset inside this transaction mutates in-memory
4544            // state (dropped outbox commits, rejections, upgrade and floor flags,
4545            // overlay dirtiness) and appends change/intent batches. A COMMIT that
4546            // fails after the reset succeeded rolls the database back, so every
4547            // one of those fields is captured here and restored with it.
4548            let rollback = self.capture();
4549            let guarded = (|| -> Result<(), ClientError> {
4550                // §7.4.2: the marker is re-read under the write lock the caller
4551                // holds, so a replica another process upgraded meanwhile refuses
4552                // this recreation instead of having its marker and tables
4553                // downgraded.
4554                let marker = read_local_schema_version(&self.conn, self.schema.version)?;
4555                self.create_bookkeeping_tables()?;
4556                match marker {
4557                    Some(version) if version < self.schema.version => self.run_schema_reset()?,
4558                    None => {
4559                        self.detach_projections(None)?;
4560                        self.create_synced_tables()?;
4561                        self.persist_schema_version()?;
4562                    }
4563                    Some(_) => {
4564                        self.detach_projections(None)?;
4565                        self.create_synced_tables()?;
4566                    }
4567                }
4568                // §7.4.2: recreation IS the boot for the in-memory core, so reload the
4569                // durable outbox the same-version path is about to replay. Only the
4570                // outbox is reloaded: the recovery below reads it, and the caller's
4571                // rollback snapshot already covers this field.
4572                self.outbox = self.load_outbox()?.into();
4573                // §7.1/§7.4.4: recover intrinsically codec-invalid persisted values at
4574                // this guarded boundary once the schema and marker agree. A bump went
4575                // through `run_schema_reset`, which performs the same recovery after
4576                // it creates the new physical tables and before its final replay.
4577                self.drop_unencodable_outbox(false, None)?;
4578                if marker == Some(self.schema.version)
4579                    && (!self.outbox.is_empty()
4580                        || !self.failed_commits.is_empty()
4581                        || self.has_acknowledged_rows()?)
4582                {
4583                    self.overlay_dirty.set(true);
4584                    self.rebuild_overlay()?;
4585                }
4586                self.prune_unknown_units(false)?;
4587                self.save_unit_scope_schema()?;
4588                // The conformance recreate is the in-memory equivalent of reopening
4589                // a durable client. Apply the same startup catch-up contract even
4590                // when the schema itself did not change; a client in preflight
4591                // gets it at activation (§5.11).
4592                if !self.security_preflight {
4593                    self.enqueue_startup_sync_if_needed()?;
4594                }
4595                self.projection_pending_queue
4596                    .extend(self.collect_projection_pending()?);
4597                Ok(())
4598            })();
4599            self.opening_replica = false;
4600            let outcome = match guarded {
4601                Ok(()) => self
4602                    .conn
4603                    .execute_batch("COMMIT")
4604                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error).into()),
4605                Err(error) => Err(error),
4606            };
4607            if let Err(error) = outcome {
4608                if let Err(rollback) = self.conn.execute_batch("ROLLBACK") {
4609                    // Keep a failed rollback's typed storage classification.
4610                    let _ = Self::sqlite_failure(&self.storage_failure, rollback);
4611                }
4612                self.schema = prior_schema;
4613                self.restore(rollback);
4614                // Prepared insert statements were derived from the reverted schema.
4615                self.insert_sql.borrow_mut().clear();
4616                return Err(error);
4617            }
4618            if !self.security_preflight {
4619                self.drain_pending_evictions()?;
4620            }
4621            Ok(())
4622        })()
4623        .map_err(open_failure)
4624    }
4625
4626    fn enqueue_startup_sync_if_needed(&mut self) -> Result<(), String> {
4627        let startup_work = !self.stopped
4628            && (!self.outbox.is_empty()
4629                || self.has_acknowledged_rows()?
4630                || !self.load_pending_evictions()?.is_empty()
4631                || self
4632                    .stored(load_units(&self.conn))?
4633                    .iter()
4634                    .any(|unit| unit.status == UnitStatus::Active));
4635        if startup_work {
4636            self.sync_needed = true;
4637            self.sync_intent_queue.push_back(SyncIntent::Interactive);
4638        }
4639        Ok(())
4640    }
4641
4642    /// A native client persists schema-floor stops across process restarts.
4643    /// Once the running app already satisfies that floor, the persisted stop
4644    /// is only stale evidence from an older server round (for example, the
4645    /// server was restarted after catching up to an app that was ahead).
4646    /// Clear it and let the normal startup pull re-negotiate. If the server is
4647    /// still incompatible it will return the floor again in that first round.
4648    fn clear_satisfied_persisted_schema_floor(&mut self) -> Result<(), String> {
4649        let satisfied = self
4650            .schema_floor
4651            .as_ref()
4652            .and_then(|floor| floor.required_schema_version)
4653            .is_some_and(|required| self.schema.version >= required);
4654        if !satisfied {
4655            return Ok(());
4656        }
4657        self.delete_meta(SCHEMA_FLOOR_KEY)?;
4658        self.schema_floor = None;
4659        self.stopped = false;
4660        Ok(())
4661    }
4662
4663    /// RFC 0005 D1: discard an orphan or stale container at boot. The reset
4664    /// path already swept it; this covers a same-version or fresh-install open,
4665    /// which runs no reset and therefore no sweep — plus the D7 TTL, which only
4666    /// an aware binary can apply.
4667    fn reconcile_previous_version_at_boot(&self) -> Result<(), String> {
4668        let Some(replica_path) = self.previous_version_replica_path() else {
4669            return Ok(());
4670        };
4671        let max_age_ms = self
4672            .previous_version
4673            .filter(|config| config.enabled)
4674            .map(|config| config.max_age_ms);
4675        reconcile_previous_version_at_boot(
4676            &self.conn,
4677            &replica_path,
4678            self.schema.version,
4679            max_age_ms,
4680            self.clock_now_ms(),
4681        )
4682    }
4683
4684    /// RFC 0005 D3: the sibling container path, or `None` when the replica has
4685    /// no file — an in-memory replica returns an empty path, and a `file:` URI
4686    /// has no plain sibling path — so the feature resolves as off there.
4687    fn previous_version_replica_path(&self) -> Option<String> {
4688        let path = self.conn.path()?;
4689        if path.is_empty() || path.starts_with("file:") {
4690            return None;
4691        }
4692        Some(path.to_owned())
4693    }
4694
4695    /// §7.4.3 reset: whole-database local reset EXCEPT the outbox, clientId,
4696    /// and leaseState. Drops/recreates every synced table from the new
4697    /// schema, resets unit sync state (keeping registrations), clears
4698    /// the schema-floor stop state, rewrites the marker, drops outbox commits
4699    /// that cannot re-encode (§7.4.4), and replays the survivors on top.
4700    fn run_schema_reset(&mut self) -> Result<(), String> {
4701        self.begin_observation("syncular_schema_reset")?;
4702        let rollback = self.capture();
4703        let mut batch = ChangeAccumulator::default();
4704        let result = self
4705            .run_schema_reset_observed(&mut batch, true)
4706            .and_then(|()| self.finish_observation("syncular_schema_reset", batch));
4707        if let Err(error) = result {
4708            self.rollback_observation("syncular_schema_reset");
4709            self.restore(rollback);
4710            return Err(error);
4711        }
4712        // After the commit: a rolled-back reset keeps the in-flight round.
4713        self.cancel_sync_round();
4714        Ok(())
4715    }
4716
4717    fn run_log_epoch_reset(&mut self, log_epoch: &str) -> Result<Vec<String>, String> {
4718        if self.get_meta(LOG_EPOCH_KEY)?.is_none() {
4719            self.begin_observation("syncular_epoch_acquisition")?;
4720            let rollback = self.capture();
4721            if let Err(error) = self.conn.execute(
4722                "INSERT OR REPLACE INTO _syncular_meta(key,value) VALUES (?1,?2)",
4723                rusqlite::params![LOG_EPOCH_KEY, log_epoch],
4724            ) {
4725                self.rollback_observation("syncular_epoch_acquisition");
4726                return Err(Self::sqlite_failure(&self.storage_failure, error));
4727            }
4728            self.sync_needed = true;
4729            let batch = ChangeAccumulator {
4730                status: true,
4731                ..ChangeAccumulator::default()
4732            };
4733            if let Err(error) = self.finish_observation("syncular_epoch_acquisition", batch) {
4734                self.rollback_observation("syncular_epoch_acquisition");
4735                self.restore(rollback);
4736                return Err(error);
4737            }
4738            self.sync_intent_queue.push_back(SyncIntent::Interactive);
4739            return Ok(Vec::new());
4740        }
4741        let resets = self
4742            .stored(load_units(&self.conn))?
4743            .into_iter()
4744            .map(|unit| unit.id)
4745            .collect();
4746        self.begin_observation("syncular_log_epoch_reset")?;
4747        let rollback = self.capture();
4748        let mut batch = ChangeAccumulator::default();
4749        let result = self
4750            .run_schema_reset_observed(&mut batch, false)
4751            .and_then(|()| {
4752                self.conn
4753                    .execute(
4754                        "INSERT OR REPLACE INTO _syncular_meta(key,value) VALUES (?1,?2)",
4755                        rusqlite::params![LOG_EPOCH_KEY, log_epoch],
4756                    )
4757                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4758                self.sync_needed = true;
4759                batch.status = true;
4760                self.finish_observation("syncular_log_epoch_reset", batch)
4761            });
4762        if let Err(error) = result {
4763            self.rollback_observation("syncular_log_epoch_reset");
4764            self.restore(rollback);
4765            return Err(error);
4766        }
4767        self.cancel_sync_round();
4768        self.sync_intent_queue.push_back(SyncIntent::Interactive);
4769        Ok(resets)
4770    }
4771
4772    fn run_schema_reset_observed(
4773        &mut self,
4774        batch: &mut ChangeAccumulator,
4775        capture: bool,
4776    ) -> Result<(), String> {
4777        // §7.4.2: the reset is the only path that wipes local tables for a
4778        // version bump, and it rewrites the marker last. Re-read the marker
4779        // under this reset's transaction: a replica another process upgraded
4780        // meanwhile refuses here instead of being reset to this client's
4781        // older schema.
4782        read_local_schema_version(&self.conn, self.schema.version)
4783            .map_err(|error| error.to_string())?;
4784        // §7.4.3: a schema bump keeps every table whose generation or one of
4785        // its equivalent generations equals the persisted one; the log-epoch
4786        // reset keeps nothing. The previous
4787        // declaration evidence decides which units cover only kept tables.
4788        let mut kept = BTreeSet::new();
4789        let mut previous_declarations: Option<BTreeMap<String, BTreeMap<String, Value>>> = None;
4790        if capture {
4791            let persisted: BTreeMap<String, String> = self
4792                .get_meta(TABLE_GENERATIONS_KEY)?
4793                .map(|raw| serde_json::from_str(&raw))
4794                .transpose()
4795                .map_err(|_| "sync.local_corrupt: invalid persisted table generations".to_owned())?
4796                .unwrap_or_default();
4797            kept = self
4798                .schema
4799                .tables
4800                .iter()
4801                .filter(|table| {
4802                    table.generation.is_some()
4803                        && persisted.get(&table.name).is_some_and(|stored| {
4804                            table.generation.as_ref() == Some(stored)
4805                                || table.equivalent_generations.contains(stored)
4806                        })
4807                })
4808                .map(|table| table.name.clone())
4809                .collect();
4810            previous_declarations = self
4811                .get_meta("subscriptionScopeSchema")?
4812                .map(|raw| serde_json::from_str(&raw))
4813                .transpose()
4814                .map_err(|_| "sync.local_corrupt: invalid persisted scope schema".to_owned())?;
4815        }
4816        // Kept tables keep both halves and their row-level bookkeeping; the
4817        // projections of kept tables keep their storage.
4818        let mut kept_objects = BTreeSet::new();
4819        for table in self
4820            .schema
4821            .tables
4822            .iter()
4823            .filter(|table| kept.contains(&table.name))
4824        {
4825            kept_objects.insert(table.name.clone());
4826            kept_objects.insert(format!("_syncular_base_{}", table.name));
4827        }
4828        kept_objects.extend(self.detach_projections(Some(&kept))?);
4829        let kept_json = serde_json::to_string(&kept).expect("table names serialize");
4830        for sql in [
4831            "DELETE FROM _syncular_acked_rows WHERE tbl NOT IN (SELECT value FROM json_each(?1))",
4832            "DELETE FROM _syncular_row_deliveries WHERE tbl NOT IN (SELECT value FROM json_each(?1))",
4833        ] {
4834            self.conn
4835                .execute(sql, [&kept_json])
4836                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4837        }
4838        self.upgrading = true;
4839        self.upgrade_kept_tables = !kept.is_empty();
4840        batch.status = true;
4841        // RFC 0005 D6: classify the pending outbox against the NEW compiled
4842        // schema BEFORE the wipe, and record the advisory audit. This pass
4843        // drops nothing, so the audit sees the original pending intent; the
4844        // §7.4.4 send-time drop and the intrinsic value recovery later in this
4845        // reset are the paths that remove a commit. The classification is
4846        // shared with the send-time drop so the two cannot disagree about what
4847        // is incompatible.
4848        if self.previous_version.is_some_and(|config| config.enabled) {
4849            let previous_version = self
4850                .get_meta(LOCAL_SCHEMA_VERSION_KEY)?
4851                .and_then(|value| value.parse::<i32>().ok())
4852                .unwrap_or(self.schema.version);
4853            let pending = self
4854                .outbox
4855                .iter()
4856                .map(|commit| PendingCommitAudit {
4857                    commit_id: &commit.client_commit_id,
4858                    operations: commit_audit_operations(commit),
4859                })
4860                .collect::<Vec<_>>();
4861            crate::previous_version::write_previous_version_audit(
4862                &self.conn,
4863                &crate::previous_version::build_previous_version_audit(
4864                    &self.schema,
4865                    &pending,
4866                    previous_version,
4867                    self.schema.version,
4868                    self.clock_now_ms(),
4869                ),
4870            )?;
4871        }
4872        // RFC 0005 D5: the container lives in its own FILE, so the reset can
4873        // never reach it. Sweep first (unconditional — also on the log-epoch
4874        // reset, which captures nothing), then capture BEFORE the wipe drops
4875        // any row. A refused capture records its reason and leaves no file.
4876        if let Some(replica_path) = self.previous_version_replica_path() {
4877            sweep_previous_version_container(&self.conn, &replica_path)?;
4878            if capture {
4879                if let Some(config) = self.previous_version.filter(|config| config.enabled) {
4880                    let previous_version = self
4881                        .get_meta(LOCAL_SCHEMA_VERSION_KEY)?
4882                        .and_then(|value| value.parse::<i32>().ok())
4883                        .unwrap_or(self.schema.version);
4884                    capture_previous_version_from_replica(
4885                        &self.conn,
4886                        &replica_path,
4887                        previous_version,
4888                        self.schema.version,
4889                        &config,
4890                        self.clock_now_ms(),
4891                    )?;
4892                }
4893            }
4894        }
4895        for table in self
4896            .schema
4897            .tables
4898            .iter()
4899            .filter(|table| !kept.contains(&table.name))
4900        {
4901            batch.table(&table.name);
4902        }
4903        for unit in self.stored(load_units(&self.conn))? {
4904            self.record_unit_windows(batch, &unit)?;
4905        }
4906        if capture {
4907            self.prune_unknown_units(true)?;
4908        }
4909        // The per-table insert SQL is derived from the OLD column lists.
4910        self.insert_sql.borrow_mut().clear();
4911        self.overlay_dirty.set(true);
4912        // Drop every synced table (base + visible) that currently exists —
4913        // discovered from sqlite_master so a bump that adds/removes tables is
4914        // handled. Bookkeeping tables (`_syncular_outbox/_units/_meta`
4915        // and the blob cache) are preserved; base tables are `_syncular_base_*`
4916        // so they are matched explicitly, not by the bookkeeping filter.
4917        // Drop virtual tables first so SQLite removes every FTS shadow table
4918        // atomically instead of the generic discovery tearing it apart.
4919        let virtual_tables: Vec<String> = {
4920            let mut stmt = self
4921                .conn
4922                .prepare(
4923                    "SELECT name FROM sqlite_master WHERE type = 'table' AND sql LIKE 'CREATE VIRTUAL TABLE%'",
4924                )
4925                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4926            let rows = stmt
4927                .query_map([], |row| row.get::<_, String>(0))
4928                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4929            rows.filter_map(Result::ok)
4930                .filter(|name| is_synced_table_name(name) && !kept_objects.contains(name))
4931                .collect()
4932        };
4933        for name in virtual_tables {
4934            self.conn
4935                .execute_batch(&format!(
4936                    "DROP TABLE IF EXISTS {}",
4937                    quote_ident(&format!("_syncular_fts_{name}"))
4938                ))
4939                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4940            self.conn
4941                .execute(&format!("DROP TABLE IF EXISTS {}", quote_ident(&name)), [])
4942                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4943        }
4944        let existing: Vec<String> = {
4945            let mut stmt = self
4946                .conn
4947                .prepare("SELECT name FROM sqlite_master WHERE type = 'table'")
4948                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4949            let rows = stmt
4950                .query_map([], |row| row.get::<_, String>(0))
4951                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4952            rows.filter_map(Result::ok)
4953                .filter(|name| is_synced_table_name(name) && !kept_objects.contains(name))
4954                .collect()
4955        };
4956        for name in &existing {
4957            if let Some(table) = name.strip_prefix("_syncular_base_") {
4958                batch.table(table);
4959            } else if !name.starts_with("_syncular_") {
4960                batch.table(name);
4961            }
4962        }
4963        for name in existing {
4964            self.conn
4965                .execute(&format!("DROP TABLE IF EXISTS {}", quote_ident(&name)), [])
4966                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4967        }
4968        // Recreate the synced tables from the NEW schema.
4969        self.create_synced_tables()?;
4970        // Reset the sync state of every unit that covers a table the reset
4971        // did not keep, under the previous declarations or the new schema,
4972        // keeping the registration.
4973        let keep_units = match &previous_declarations {
4974            Some(previous) if !kept.is_empty() => self
4975                .stored(load_units(&self.conn))?
4976                .into_iter()
4977                .filter(|unit| {
4978                    previous.iter().all(|(name, old)| {
4979                        kept.contains(name) || !unit.scopes.keys().all(|v| old.contains_key(v))
4980                    }) && self
4981                        .schema
4982                        .tables
4983                        .iter()
4984                        .all(|table| kept.contains(&table.name) || !covers(table, &unit.scopes))
4985                })
4986                .map(|unit| unit.id)
4987                .collect(),
4988            _ => BTreeSet::new(),
4989        };
4990        // §7.4.3 restriction: an active unit that is not kept and whose rows
4991        // of a kept table are complete through a cursor C (its restriction's,
4992        // its post-bootstrap P, or the replica cursor it is live under)
4993        // bootstraps only its other covered tables and joins at C.
4994        let restrictions = if capture {
4995            let replica = self.stored(replica_cursor(&self.conn))?;
4996            let mut restrictions = BTreeMap::new();
4997            for unit in self.stored(load_units(&self.conn))? {
4998                if keep_units.contains(&unit.id) || unit.status != UnitStatus::Active {
4999                    continue;
5000                }
5001                let cursor = match (&unit.restriction, unit.cursor) {
5002                    (Some(restriction), _) => restriction.cursor,
5003                    (None, Some(cursor)) if cursor >= 0 && unit.bootstrap_state.is_none() => cursor,
5004                    (None, None) if replica >= 0 => replica,
5005                    _ => continue,
5006                };
5007                let covered: Vec<&String> = self
5008                    .schema
5009                    .tables
5010                    .iter()
5011                    .filter(|table| covers(table, &unit.scopes))
5012                    .map(|table| &table.name)
5013                    .collect();
5014                let mut tables: Vec<String> = covered
5015                    .iter()
5016                    .filter(|name| {
5017                        !kept.contains(**name)
5018                            || unit
5019                                .restriction
5020                                .as_ref()
5021                                .is_some_and(|restriction| restriction.tables.contains(name))
5022                    })
5023                    .map(|name| (*name).clone())
5024                    .collect();
5025                if tables.is_empty() || tables.len() == covered.len() {
5026                    continue;
5027                }
5028                tables.sort_by(|a, b| a.encode_utf16().cmp(b.encode_utf16()));
5029                restrictions.insert(unit.id, UnitRestriction { cursor, tables });
5030            }
5031            Some(restrictions)
5032        } else {
5033            None
5034        };
5035        reset_units(&self.conn, &keep_units, restrictions.as_ref())
5036            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5037        // The stop state is over: this client now ships a servable schema.
5038        self.stopped = false;
5039        self.schema_floor = None;
5040        self.delete_meta(SCHEMA_FLOOR_KEY)?;
5041        // Rewrite the marker LAST so a crash mid-reset re-runs the reset.
5042        self.persist_schema_version()?;
5043        self.save_unit_scope_schema()?;
5044        // §7.1/§7.4.4: the previous-version capture and audit above saw the
5045        // original pending intent; the synced tables now carry the new schema, so
5046        // recover intrinsically codec-invalid persisted values here, before the
5047        // final replay. A pending upsert that names a column the new schema
5048        // removed stays pending for the send-time `drop_incompatible_outbox`
5049        // prepass. The reset wrapper snapshots and restores the outbox,
5050        // rejections, and change queues, so a failed commit rolls this recovery
5051        // back with the rest of the reset.
5052        // §7.4.4: the enclosing reset observation owns the publication, so the
5053        // recovery contributes its rejection, outcome, and table domains to it.
5054        self.drop_unencodable_outbox(false, Some(batch))?;
5055        // Re-apply the surviving outbox optimistically over the empty tables.
5056        self.rebuild_overlay()?;
5057        Ok(())
5058    }
5059
5060    /// §7.4.4 send-time prepass: a persisted upsert whose values reference a
5061    /// column the current schema lacks (or a removed table) cannot be encoded
5062    /// (`commit_audit_operations` inspects upserts, so a value-free delete stays
5063    /// encodable and is validated by the server), nor can an insert-intent
5064    /// upsert that lacks a non-nullable column (§7.1, the audit's
5065    /// `missing-required-column`). Drop the commit, undo
5066    /// its optimistic projection, and raise a client-local
5067    /// `sync.outbox_incompatible` rejection.
5068    fn drop_incompatible_outbox(&mut self) -> Result<bool, String> {
5069        // §8.8: only the commits this round pushes; a held commit waits.
5070        let incompatible = self
5071            .outbox
5072            .iter()
5073            .take(self.pushable_commits())
5074            .filter(|commit| {
5075                first_incompatibility(&self.schema, &commit_audit_operations(commit)).is_some()
5076            })
5077            .cloned()
5078            .collect::<Vec<_>>();
5079        if incompatible.is_empty() {
5080            return Ok(false);
5081        }
5082        self.drop_outbox_commits(
5083            &incompatible,
5084            OUTBOX_INCOMPATIBLE_CODE,
5085            "the persisted commit cannot encode under the current schema",
5086        )?;
5087        Ok(true)
5088    }
5089
5090    /// §7.4.4 incompatible-commit path, also taken by a refused blob upload
5091    /// (§5.9.7) with the server's code: reject every operation of `commits`,
5092    /// remove them from the outbox, and undo their optimistic rows.
5093    fn drop_outbox_commits(
5094        &mut self,
5095        incompatible: &[Arc<OutboxCommit>],
5096        code: &str,
5097        message: &str,
5098    ) -> Result<(), String> {
5099        // §7.4.4: one observation covers the durable outcome writes, the outbox
5100        // removal, the in-memory drop, and the overlay rebuild, so a storage
5101        // fault leaves the replica and the client unchanged and publishes no
5102        // change; a successful drop publishes exactly one batch carrying the
5103        // rejections, outcomes, status, and the tables whose projection changed.
5104        let rollback = self.capture();
5105        let owns_transaction = self.conn.is_autocommit();
5106        self.begin_observation("syncular_outbox_drop")?;
5107        let mut batch = ChangeAccumulator::default();
5108        let dropped = (|| -> Result<(), String> {
5109            let mut rejections = Vec::new();
5110            for commit in incompatible {
5111                let results = commit
5112                    .ops
5113                    .iter()
5114                    .enumerate()
5115                    .map(|(op_index, operation)| {
5116                        let rejection = RejectionRecord {
5117                            client_commit_id: commit.client_commit_id.clone(),
5118                            op_index: op_index as i32,
5119                            code: code.to_owned(),
5120                            message: message.to_owned(),
5121                            retryable: false,
5122                            details: None,
5123                            operation: Some(CommitOperation::from(operation)),
5124                        };
5125                        rejections.push(rejection.clone());
5126                        CommitOperationOutcome::Error { rejection }
5127                    })
5128                    .collect::<Vec<_>>();
5129                self.persist_commit_outcome(
5130                    &commit.client_commit_id,
5131                    CommitOutcomeStatus::Rejected,
5132                    &results,
5133                    Some(&commit.ops),
5134                )?;
5135                self.leave_through(&commit.client_commit_id);
5136                self.delete_outbox_persisted(&commit.client_commit_id)?;
5137                // A removed table has no local projection to invalidate; every
5138                // surviving table the dropped commit touched does.
5139                for operation in &commit.ops {
5140                    if self.schema.table(&operation.table).is_some() {
5141                        batch.table(&operation.table);
5142                    }
5143                }
5144            }
5145            self.prune_commit_outcomes()?;
5146            let incompatible_ids = incompatible
5147                .iter()
5148                .map(|commit| commit.client_commit_id.as_str())
5149                .collect::<BTreeSet<_>>();
5150            self.outbox
5151                .retain(|commit| !incompatible_ids.contains(commit.client_commit_id.as_str()));
5152            self.rejections.extend(rejections);
5153            // The dropped commits' purely-optimistic rows are undone: the
5154            // visible projection is re-derived from the surviving base + outbox.
5155            self.overlay_dirty.set(true);
5156            self.rebuild_overlay()?;
5157            batch.status = true;
5158            batch.rejections = true;
5159            batch.outcomes = true;
5160            Ok(())
5161        })();
5162        let result = dropped.and_then(|()| self.finish_observation("syncular_outbox_drop", batch));
5163        if let Err(error) = result {
5164            // An outer RELEASE is the COMMIT. Roll back that transaction
5165            // directly: retrying RELEASE after ROLLBACK TO still needs the
5166            // reader's lock. A nested observation only rolls back its savepoint.
5167            if owns_transaction {
5168                if let Err(rollback) = self.conn.execute_batch("ROLLBACK") {
5169                    let mut failure = self.storage_failure.borrow_mut();
5170                    let failure =
5171                        failure.get_or_insert_with(|| QueryReadFailure::from(error.clone()));
5172                    failure.rollback_failure = Some(Box::new(QueryReadFailure::from(rollback)));
5173                }
5174            } else {
5175                self.rollback_observation("syncular_outbox_drop");
5176            }
5177            self.restore(rollback);
5178            return Err(error);
5179        }
5180        Ok(())
5181    }
5182
5183    /// §7.4.3: (re)create the base + visible table pair for every synced
5184    /// table in the CURRENT schema (idempotent — `IF NOT EXISTS`).
5185    fn create_synced_tables(&self) -> Result<(), String> {
5186        for table in &self.schema.tables {
5187            // The base half + the visible half form the synced-table pair. An
5188            // index name is global in SQLite, so the base half's indexes are
5189            // name-prefixed (`_syncular_base_<index>`) to stay distinct.
5190            for (full, index_prefix) in [
5191                (base_table(&table.name), "_syncular_base_"),
5192                (visible_table(&table.name), ""),
5193            ] {
5194                let mut cols: Vec<String> =
5195                    table.columns.iter().map(|c| quote_ident(&c.name)).collect();
5196                cols.push("\"_syncular_version\" INTEGER NOT NULL".to_owned());
5197                cols.extend(
5198                    table
5199                        .sealed_columns()
5200                        .iter()
5201                        .map(|name| format!("{} TEXT", quote_ident(name))),
5202                );
5203                let sql = format!(
5204                    "CREATE TABLE IF NOT EXISTS {full} ({} , PRIMARY KEY ({}))",
5205                    cols.join(", "),
5206                    quote_ident(&table.primary_key)
5207                );
5208                self.conn
5209                    .execute(&sql, [])
5210                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5211                // §5.11: a replica created before sealed apply gains the
5212                // reserved columns in place, on both halves in the same order,
5213                // so data, indexes and the FTS projection stay.
5214                for name in table.sealed_columns() {
5215                    let present: bool = self
5216                        .conn
5217                        .query_row(
5218                            "SELECT EXISTS(SELECT 1 FROM pragma_table_info(?1) WHERE name = ?2)",
5219                            rusqlite::params![format!("{index_prefix}{}", table.name), name],
5220                            |row| row.get(0),
5221                        )
5222                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5223                    if !present {
5224                        self.conn
5225                            .execute(
5226                                &format!(
5227                                    "ALTER TABLE {full} ADD COLUMN {} TEXT",
5228                                    quote_ident(name)
5229                                ),
5230                                [],
5231                            )
5232                            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5233                    }
5234                }
5235                // The reveal at every round start reads the sealed rows of the
5236                // base half through this partial index.
5237                if table.has_encrypted_columns() && !index_prefix.is_empty() {
5238                    self.conn
5239                        .execute(
5240                            &format!(
5241                                "CREATE INDEX IF NOT EXISTS {} ON {full} (\"_sync_sealed_key\") WHERE \"_sync_sealed_key\" IS NOT NULL",
5242                                quote_ident(&format!("_syncular_sealed_{}", table.name))
5243                            ),
5244                            [],
5245                        )
5246                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5247                }
5248            }
5249        }
5250        // §7.4.3 declared indexes: reconciled in place on both halves (the
5251        // base half's names carry the `_syncular_base_` prefix) at every open
5252        // and at the end of every reset. `localIndexes` records the declared
5253        // names Syncular created; only those are ever dropped.
5254        let recorded: BTreeMap<String, BTreeSet<String>> = match self.get_meta("localIndexes")? {
5255            Some(raw) => serde_json::from_str(&raw)
5256                .map_err(|_| "sync.local_corrupt: invalid persisted local indexes".to_owned())?,
5257            // A replica without the record: every declared index that exists
5258            // counts as created by Syncular, so nothing is stale.
5259            None => BTreeMap::new(),
5260        };
5261        let declared: BTreeMap<String, BTreeSet<String>> = self
5262            .schema
5263            .tables
5264            .iter()
5265            .filter(|table| !table.indexes.is_empty())
5266            .map(|table| {
5267                let names = table.indexes.iter().map(|index| index.name.clone());
5268                (table.name.clone(), names.collect())
5269            })
5270            .collect();
5271        for (table, names) in &recorded {
5272            for name in names.iter().filter(|name| {
5273                !declared
5274                    .get(table)
5275                    .is_some_and(|declared| declared.contains(*name))
5276            }) {
5277                self.stored(self.conn.execute_batch(&format!(
5278                    "DROP INDEX IF EXISTS {}; DROP INDEX IF EXISTS {}",
5279                    quote_ident(name),
5280                    quote_ident(&format!("_syncular_base_{name}"))
5281                )))?;
5282            }
5283        }
5284        for table in &self.schema.tables {
5285            for index in &table.indexes {
5286                for (owner, name) in [
5287                    (
5288                        format!("_syncular_base_{}", table.name),
5289                        format!("_syncular_base_{}", index.name),
5290                    ),
5291                    (table.name.clone(), index.name.clone()),
5292                ] {
5293                    let current: Option<(String, bool, bool)> = self.stored(
5294                        self.conn
5295                            .query_row(
5296                                "SELECT m.tbl_name, l.\"unique\", l.partial FROM sqlite_master AS m JOIN pragma_index_list(m.tbl_name) AS l ON l.name = m.name WHERE m.type = 'index' AND m.name = ?1",
5297                                [&name],
5298                                |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
5299                            )
5300                            .optional(),
5301                    )?;
5302                    if let Some((current_owner, unique, partial)) = current {
5303                        let mut stmt = self
5304                            .stored(self.conn.prepare(
5305                                "SELECT name FROM pragma_index_info(?1) ORDER BY seqno",
5306                            ))?;
5307                        let columns = self.stored(
5308                            self.stored(
5309                                stmt.query_map([&name], |row| row.get::<_, Option<String>>(0)),
5310                            )?
5311                            .collect::<Result<Vec<_>, _>>(),
5312                        )?;
5313                        if current_owner == owner
5314                            && unique == index.unique
5315                            && !partial
5316                            && columns
5317                                .iter()
5318                                .map(Option::as_deref)
5319                                .eq(index.columns.iter().map(|column| Some(column.as_str())))
5320                        {
5321                            continue;
5322                        }
5323                        self.stored(
5324                            self.conn
5325                                .execute(&format!("DROP INDEX {}", quote_ident(&name)), []),
5326                        )?;
5327                    }
5328                    self.stored(self.conn.execute(
5329                        &format!(
5330                            "CREATE {}INDEX {} ON {} ({})",
5331                            if index.unique { "UNIQUE " } else { "" },
5332                            quote_ident(&name),
5333                            quote_ident(&owner),
5334                            index
5335                                .columns
5336                                .iter()
5337                                .map(|column| quote_ident(column))
5338                                .collect::<Vec<_>>()
5339                                .join(", ")
5340                        ),
5341                        [],
5342                    ))?;
5343                }
5344            }
5345        }
5346        self.set_meta(
5347            "localIndexes",
5348            &serde_json::to_string(&declared).expect("index names serialize"),
5349        )?;
5350        self.open_projections()
5351    }
5352
5353    fn create_fts_storage(
5354        &self,
5355        name: &str,
5356        columns: &str,
5357        tokenize: &str,
5358        options: &str,
5359    ) -> Result<(), String> {
5360        let tokenizer = tokenize.replace('\'', "''");
5361        let sql = format!(
5362            "CREATE VIRTUAL TABLE IF NOT EXISTS {} USING fts5({} UNINDEXED, {columns}, tokenize='{tokenizer}'{options})",
5363            quote_ident(name),
5364            quote_ident(FTS_SOURCE_ID_COLUMN),
5365        );
5366        self.conn
5367            .execute(&sql, [])
5368            .map_err(|error| format!("cannot create local FTS5 projection {name:?}: {error}"))?;
5369        let mapping = quote_ident(&format!("_syncular_fts_{name}"));
5370        self.stored(self.conn.execute_batch(&format!("CREATE TABLE IF NOT EXISTS {mapping}(id INTEGER PRIMARY KEY, source_id TEXT NOT NULL UNIQUE)")))
5371    }
5372
5373    // -- persistence write-through --------------------------------------------
5374
5375    fn persist_outbox_insert(&self, commit: &OutboxCommit) -> Result<(), String> {
5376        let ops: Vec<Value> = commit
5377            .ops
5378            .iter()
5379            .map(|op| {
5380                let mut entry = serde_json::json!({
5381                    "op": if op.upsert { "upsert" } else { "delete" },
5382                    "table": op.table,
5383                    "rowId": op.row_id,
5384                    "baseVersion": op.base_version,
5385                    "values": op.values.clone().map(Value::Object),
5386                });
5387                if op.insert {
5388                    entry["insert"] = Value::Bool(true);
5389                }
5390                entry
5391            })
5392            .collect();
5393        self.conn
5394            .execute(
5395                "INSERT OR REPLACE INTO _syncular_outbox (commit_id, ops_json, created_at_ms, attempted) VALUES (?1, ?2, ?3, 0)",
5396                rusqlite::params![
5397                    commit.client_commit_id,
5398                    Value::Array(ops).to_string(),
5399                    self.clock_now_ms()
5400                ],
5401            )
5402            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5403        for operation in &commit.ops {
5404            let Some(values) = &operation.values else {
5405                continue;
5406            };
5407            let Some(table) = self.schema.table(&operation.table) else {
5408                continue;
5409            };
5410            for column in table
5411                .columns
5412                .iter()
5413                .filter(|column| column.ty == ColumnType::BlobRef)
5414            {
5415                let Some(Value::String(raw)) = values.get(&column.name) else {
5416                    continue;
5417                };
5418                let Ok(blob_ref) = serde_json::from_str::<Value>(raw) else {
5419                    continue;
5420                };
5421                let Some(blob_id) = blob_ref.get("blobId").and_then(Value::as_str) else {
5422                    continue;
5423                };
5424                self.conn
5425                    .execute(
5426                        "INSERT OR IGNORE INTO _syncular_blob_commit_refs(commit_id, blob_id)
5427                         SELECT ?1, ?2 WHERE EXISTS (SELECT 1 FROM _syncular_blobs WHERE blob_id = ?2)",
5428                        rusqlite::params![commit.client_commit_id, blob_id],
5429                    )
5430                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5431            }
5432        }
5433        Ok(())
5434    }
5435
5436    fn delete_outbox_persisted(&self, client_commit_id: &str) -> Result<(), String> {
5437        self.conn
5438            .execute(
5439                "DELETE FROM _syncular_blob_commit_refs WHERE commit_id = ?1",
5440                rusqlite::params![client_commit_id],
5441            )
5442            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5443        self.conn
5444            .execute(
5445                "DELETE FROM _syncular_outbox WHERE commit_id = ?1",
5446                rusqlite::params![client_commit_id],
5447            )
5448            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5449        self.conn.execute("DELETE FROM _syncular_row_deliveries WHERE NOT EXISTS(SELECT 1 FROM _syncular_outbox,json_each(ops_json) WHERE json_extract(json_each.value,'$.table')=tbl AND json_extract(json_each.value,'$.rowId')=id)", [])
5450            .map(|_| ())
5451            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
5452    }
5453
5454    fn outcome_status_name(status: CommitOutcomeStatus) -> &'static str {
5455        match status {
5456            CommitOutcomeStatus::Applied => "applied",
5457            CommitOutcomeStatus::Cached => "cached",
5458            CommitOutcomeStatus::Conflict => "conflict",
5459            // §7.2.1: a replaced commit is stored as a decided rejection.
5460            CommitOutcomeStatus::Rejected | CommitOutcomeStatus::Replaced => "rejected",
5461        }
5462    }
5463
5464    fn outcome_resolution_name(resolution: CommitOutcomeResolution) -> &'static str {
5465        match resolution {
5466            CommitOutcomeResolution::Active => "active",
5467            CommitOutcomeResolution::ResolvedKeepServer => "resolved_keep_server",
5468            CommitOutcomeResolution::Superseded => "superseded",
5469            CommitOutcomeResolution::Dismissed => "dismissed",
5470        }
5471    }
5472
5473    fn parse_outcome_status(value: &str) -> Result<CommitOutcomeStatus, String> {
5474        match value {
5475            "applied" => Ok(CommitOutcomeStatus::Applied),
5476            "cached" => Ok(CommitOutcomeStatus::Cached),
5477            "conflict" => Ok(CommitOutcomeStatus::Conflict),
5478            "rejected" => Ok(CommitOutcomeStatus::Rejected),
5479            _ => Err(format!("invalid persisted commit outcome status {value:?}")),
5480        }
5481    }
5482
5483    fn parse_outcome_resolution(value: &str) -> Result<CommitOutcomeResolution, String> {
5484        match value {
5485            "active" => Ok(CommitOutcomeResolution::Active),
5486            "resolved_keep_server" => Ok(CommitOutcomeResolution::ResolvedKeepServer),
5487            "superseded" => Ok(CommitOutcomeResolution::Superseded),
5488            "dismissed" => Ok(CommitOutcomeResolution::Dismissed),
5489            _ => Err(format!(
5490                "invalid persisted commit outcome resolution {value:?}"
5491            )),
5492        }
5493    }
5494
5495    fn persist_commit_outcome(
5496        &self,
5497        client_commit_id: &str,
5498        status: CommitOutcomeStatus,
5499        results: &[CommitOperationOutcome],
5500        operations: Option<&[OutboxOp]>,
5501    ) -> Result<(), String> {
5502        let results_json = serde_json::to_string(results).map_err(|error| error.to_string())?;
5503        let operations_json = operations
5504            .map(|items| {
5505                serde_json::to_string(&items.iter().map(CommitOperation::from).collect::<Vec<_>>())
5506            })
5507            .transpose()
5508            .map_err(|error| error.to_string())?;
5509        self.conn
5510            .execute(
5511                "INSERT INTO _syncular_commit_outcomes (
5512                   client_commit_id, status, recorded_at_ms, results_json,
5513                   operations_json, resolution
5514                 ) VALUES (?1, ?2, ?3, ?4, ?5, 'active')",
5515                rusqlite::params![
5516                    client_commit_id,
5517                    Self::outcome_status_name(status),
5518                    self.clock_now_ms(),
5519                    results_json,
5520                    operations_json
5521                ],
5522            )
5523            .map(|_| ())
5524            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
5525    }
5526
5527    /// §7.2: the journal holds a stored cell only in its canonical shape. A cell
5528    /// the byte-envelope rule refuses cannot be journaled verbatim.
5529    fn stored_cell_is_representable(cell: &Value) -> bool {
5530        cell.is_null()
5531            || cell.is_string()
5532            || cell.is_boolean()
5533            || cell.is_number()
5534            || is_canonical_bytes_envelope(cell)
5535    }
5536
5537    fn stored_row_is_representable(value: &Value) -> bool {
5538        value
5539            .as_object()
5540            .is_some_and(|row| row.values().all(Self::stored_cell_is_representable))
5541    }
5542
5543    fn stored_operation_is_representable(value: &Value) -> bool {
5544        value.get("table").is_some_and(Value::is_string)
5545            && value.get("rowId").is_some_and(Value::is_string)
5546            && value.get("baseVersion").is_none_or(|v| {
5547                v.as_i64()
5548                    .is_some_and(|n| n.unsigned_abs() <= MAX_JS_SAFE_INTEGER)
5549            })
5550            && match value.get("op").and_then(Value::as_str) {
5551                Some("upsert") => {
5552                    value
5553                        .get("values")
5554                        .is_some_and(Self::stored_row_is_representable)
5555                        && value
5556                            .get("insert")
5557                            .is_none_or(|insert| *insert == Value::Bool(true))
5558                }
5559                Some("delete") => value.get("values").is_none() && value.get("insert").is_none(),
5560                _ => false,
5561            }
5562    }
5563
5564    /// §7.2/§7.4.4: a dropped commit keeps its operation envelope in the journal
5565    /// only when the journal reader accepts the serialized operation, which is the
5566    /// rule `outcome_from_row` applies to this same row later.
5567    fn outbox_op_is_journalable(operation: &OutboxOp) -> bool {
5568        serde_json::to_value(CommitOperation::from(operation))
5569            .is_ok_and(|value| Self::stored_operation_is_representable(&value))
5570    }
5571
5572    /// §7.2.1: the one predicate for a replaced commit: a rejection whose
5573    /// every result is `client.commit_replaced` and that names its replacement.
5574    fn is_replaced(outcome: &CommitOutcome) -> bool {
5575        outcome.status == CommitOutcomeStatus::Rejected
5576            && outcome.replacement_client_commit_id.is_some()
5577            && !outcome.results.is_empty()
5578            && outcome.results.iter().all(|result| {
5579                matches!(result, CommitOperationOutcome::Error { rejection }
5580                    if rejection.code == COMMIT_REPLACED_CODE)
5581            })
5582    }
5583
5584    /// §7.2.1: `commitOutcomes` and `commitDelivery` report a replaced
5585    /// commit as `replaced`; every other journal surface reads the rejection.
5586    fn reported_outcome(mut outcome: CommitOutcome) -> CommitOutcome {
5587        if Self::is_replaced(&outcome) {
5588            outcome.status = CommitOutcomeStatus::Replaced;
5589        }
5590        outcome
5591    }
5592
5593    fn outcome_from_row(row: StoredCommitOutcomeRow) -> Result<CommitOutcome, String> {
5594        let StoredCommitOutcomeRow {
5595            sequence,
5596            client_commit_id,
5597            status,
5598            recorded_at_ms,
5599            results_json,
5600            operations_json,
5601            resolution,
5602            resolved_at_ms,
5603            replacement_client_commit_id,
5604        } = row;
5605        if sequence.unsigned_abs() > MAX_JS_SAFE_INTEGER
5606            || recorded_at_ms.unsigned_abs() > MAX_JS_SAFE_INTEGER
5607            || resolved_at_ms.is_some_and(|value| value.unsigned_abs() > MAX_JS_SAFE_INTEGER)
5608        {
5609            return Err("sync.local_corrupt: persisted commit outcome is invalid".to_owned());
5610        }
5611        let invalid = || "sync.local_corrupt: persisted commit outcome is invalid".to_owned();
5612        let stored: Vec<Value> = serde_json::from_str(&results_json).map_err(|_| invalid())?;
5613        for result in &stored {
5614            let nested = match result.get("status").and_then(Value::as_str) {
5615                Some("conflict") => result.get("conflict"),
5616                Some("error") => result.get("rejection"),
5617                _ => None,
5618            };
5619            if nested
5620                .and_then(|record| record.get("operation"))
5621                .is_some_and(|op| !Self::stored_operation_is_representable(op))
5622                || (result.get("status").and_then(Value::as_str) == Some("conflict")
5623                    && nested
5624                        .and_then(|record| record.get("serverRow"))
5625                        .is_some_and(|row| !Self::stored_row_is_representable(row)))
5626            {
5627                return Err(invalid());
5628            }
5629        }
5630        let results: Vec<CommitOperationOutcome> =
5631            serde_json::from_value(Value::Array(stored)).map_err(|_| invalid())?;
5632        let has_conflict = results
5633            .iter()
5634            .any(|result| matches!(result, CommitOperationOutcome::Conflict { .. }));
5635        let has_error = results
5636            .iter()
5637            .any(|result| matches!(result, CommitOperationOutcome::Error { .. }));
5638        let status = Self::parse_outcome_status(&status).map_err(|_| invalid())?;
5639        let redacted = results.is_empty() && operations_json.is_none();
5640        if match status {
5641            CommitOutcomeStatus::Applied | CommitOutcomeStatus::Cached => has_conflict || has_error,
5642            CommitOutcomeStatus::Replaced => true,
5643            CommitOutcomeStatus::Conflict => !(has_conflict || redacted),
5644            CommitOutcomeStatus::Rejected => has_conflict || !(has_error || redacted),
5645        } {
5646            return Err(invalid());
5647        }
5648        let operations: Option<Vec<CommitOperation>> = operations_json
5649            .map(|raw| {
5650                let stored: Vec<Value> = serde_json::from_str(&raw).map_err(|_| invalid())?;
5651                if !stored.iter().all(Self::stored_operation_is_representable) {
5652                    return Err(invalid());
5653                }
5654                serde_json::from_value(Value::Array(stored)).map_err(|_| invalid())
5655            })
5656            .transpose()?;
5657        for result in &results {
5658            match result {
5659                CommitOperationOutcome::Conflict { conflict }
5660                    if conflict.server_version.unsigned_abs() > MAX_JS_SAFE_INTEGER =>
5661                {
5662                    return Err("sync.local_corrupt: persisted commit outcome is invalid".to_owned())
5663                }
5664                CommitOperationOutcome::Error { rejection } => {
5665                    if let Some(details) = &rejection.details {
5666                        let encoded = serde_json::to_string(details).map_err(|_| {
5667                            "sync.local_corrupt: persisted commit outcome is invalid".to_owned()
5668                        })?;
5669                        RejectionDetails::parse(&encoded).map_err(|_| {
5670                            "sync.local_corrupt: persisted commit outcome is invalid".to_owned()
5671                        })?;
5672                    }
5673                }
5674                _ => {}
5675            }
5676        }
5677        Ok(CommitOutcome {
5678            sequence,
5679            client_commit_id,
5680            status,
5681            recorded_at_ms,
5682            results,
5683            operations,
5684            retained_rows: None,
5685            resolution: Self::parse_outcome_resolution(&resolution)?,
5686            resolved_at_ms,
5687            replacement_client_commit_id,
5688        })
5689    }
5690
5691    /// Resolve declared unique keys through SQLite, including affinity and NULL semantics.
5692    fn unique_conflicts(
5693        &self,
5694        table: &TableSchema,
5695        values: &Map<String, Value>,
5696        base: bool,
5697    ) -> Result<Vec<RetainedUniqueConflict>, String> {
5698        let source = if base {
5699            base_table(&table.name)
5700        } else {
5701            visible_table(&table.name)
5702        };
5703        let mut conflicts = Vec::new();
5704        for index in table.indexes.iter().filter(|index| index.unique) {
5705            let mut params = vec![json_param_to_sql(
5706                values.get(&table.primary_key).ok_or("sync.local_corrupt")?,
5707            )?];
5708            for name in &index.columns {
5709                let column = table
5710                    .columns
5711                    .iter()
5712                    .find(|column| column.name == *name)
5713                    .ok_or("sync.local_corrupt")?;
5714                let cell = json_to_column_value(column, values.get(name))?;
5715                params.push(owned_sql_value(RowParam::Cell(&cell))?);
5716            }
5717            let sql = format!(
5718                "SELECT * FROM {source} WHERE {} != ? AND {}",
5719                quote_ident(&table.primary_key),
5720                index
5721                    .columns
5722                    .iter()
5723                    .map(|column| format!("{} = ?", quote_ident(column)))
5724                    .collect::<Vec<_>>()
5725                    .join(" AND ")
5726            );
5727            let mut statement = self
5728                .conn
5729                .prepare_cached(&sql)
5730                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5731            let records = statement
5732                .query_map(rusqlite::params_from_iter(params), |record| {
5733                    let values = table
5734                        .columns
5735                        .iter()
5736                        .enumerate()
5737                        .map(|(index, column)| {
5738                            let value = sql_ref_to_json(column, record.get_ref(index)?);
5739                            json_to_column_value(column, Some(&value)).map_err(|message| {
5740                                rusqlite::Error::ToSqlConversionFailure(message.into())
5741                            })
5742                        })
5743                        .collect::<Result<Row, _>>()?;
5744                    Ok((values, record.get::<_, i64>(table.columns.len())?))
5745                })
5746                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5747            for record in records {
5748                let (row, version) =
5749                    record.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5750                let row_id = render_row_id_json(Some(&column_value_to_json(&row[table.pk_index])))?;
5751                conflicts.push(RetainedUniqueConflict {
5752                    index: index.name.clone(),
5753                    columns: index.columns.clone(),
5754                    row_id,
5755                    server_row: table
5756                        .columns
5757                        .iter()
5758                        .zip(&row)
5759                        .map(|(column, value)| (column.name.clone(), column_value_to_json(value)))
5760                        .collect(),
5761                    server_version: version,
5762                });
5763            }
5764        }
5765        Ok(conflicts)
5766    }
5767
5768    fn attach_retained_rows(&self, mut outcome: CommitOutcome) -> Result<CommitOutcome, String> {
5769        if let Some((commit, initial)) = self
5770            .failed_commits
5771            .iter()
5772            .find(|(commit, _)| commit.client_commit_id == outcome.client_commit_id)
5773        {
5774            let mut rows = Vec::new();
5775            for operation in &commit.ops {
5776                // A table the current schema removed has no rows to retain.
5777                let Some(table) = self.schema.table(&operation.table) else {
5778                    continue;
5779                };
5780                let key =
5781                    serde_json::to_string(&(operation.table.clone(), operation.row_id.clone()))
5782                        .map_err(|_| "sync.local_corrupt".to_owned())?;
5783                let base = self.stored_row(table, &operation.row_id, true)?;
5784                rows.push(RetainedCommitRow {
5785                    table: operation.table.clone(),
5786                    row_id: operation.row_id.clone(),
5787                    unique_conflicts: if operation.upsert {
5788                        self.unique_conflicts(
5789                            table,
5790                            initial
5791                                .get(&key)
5792                                .and_then(Value::as_object)
5793                                .or(operation.values.as_ref())
5794                                .ok_or("sync.local_corrupt")?,
5795                            true,
5796                        )?
5797                    } else {
5798                        Vec::new()
5799                    },
5800                    local_row: if operation.upsert {
5801                        initial
5802                            .get(&key)
5803                            .and_then(Value::as_object)
5804                            .cloned()
5805                            .or_else(|| operation.values.clone())
5806                    } else {
5807                        None
5808                    },
5809                    server_row: base.as_ref().map(|(values, _)| {
5810                        table
5811                            .columns
5812                            .iter()
5813                            .zip(values)
5814                            .map(|(column, value)| {
5815                                (column.name.clone(), column_value_to_json(value))
5816                            })
5817                            .collect()
5818                    }),
5819                    server_version: base.map(|(_, version)| version),
5820                });
5821            }
5822            outcome.retained_rows = Some(rows);
5823        }
5824        Ok(outcome)
5825    }
5826
5827    fn commit_outcome(&self, client_commit_id: &str) -> Result<Option<CommitOutcome>, String> {
5828        let row = self
5829            .conn
5830            .query_row(
5831                "SELECT seq, client_commit_id, status, recorded_at_ms, results_json, operations_json,
5832                        resolution, resolved_at_ms, replacement_client_commit_id
5833                   FROM _syncular_commit_outcomes WHERE client_commit_id = ?1",
5834                rusqlite::params![client_commit_id],
5835                |row| {
5836                    Ok(StoredCommitOutcomeRow {
5837                        sequence: row.get(0)?,
5838                        client_commit_id: row.get(1)?,
5839                        status: row.get(2)?,
5840                        recorded_at_ms: row.get(3)?,
5841                        results_json: row.get(4)?,
5842                        operations_json: row.get(5)?,
5843                        resolution: row.get(6)?,
5844                        resolved_at_ms: row.get(7)?,
5845                        replacement_client_commit_id: row.get(8)?,
5846                    })
5847                },
5848            )
5849            .optional()
5850            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5851        row.map(|row| self.attach_retained_rows(Self::outcome_from_row(row)?))
5852            .transpose()
5853    }
5854
5855    /// Internal host step. The host must run its idle drive before finishing.
5856    #[doc(hidden)]
5857    pub fn prepare_current_base(
5858        &self,
5859        client_commit_id: &str,
5860        sequence: i64,
5861    ) -> Result<CurrentBasePreparation, CurrentBaseProof> {
5862        let outcome = self
5863            .commit_outcome(client_commit_id)
5864            .map_err(|_| CurrentBaseProof::failure(CurrentBaseProofReason::SnapshotFailed))?;
5865        let valid = outcome.as_ref().is_some_and(|outcome| {
5866            outcome.sequence == sequence
5867                && outcome.resolution == CommitOutcomeResolution::Active
5868                && matches!(
5869                    outcome.status,
5870                    CommitOutcomeStatus::Conflict | CommitOutcomeStatus::Rejected
5871                )
5872                && outcome
5873                    .operations
5874                    .as_ref()
5875                    .zip(outcome.retained_rows.as_ref())
5876                    .is_some_and(|(operations, rows)| {
5877                        !rows.is_empty() && operations.len() == rows.len()
5878                    })
5879        });
5880        if !valid {
5881            return Err(CurrentBaseProof::failure(
5882                CurrentBaseProofReason::OutcomeUnavailable,
5883            ));
5884        }
5885        if self.transport_closed() {
5886            return Err(CurrentBaseProof::failure(CurrentBaseProofReason::Offline));
5887        }
5888        Ok(CurrentBasePreparation {
5889            client_commit_id: client_commit_id.to_owned(),
5890            sequence,
5891            replacement: None,
5892            units: load_units(&self.conn)
5893                .map_err(|_| CurrentBaseProof::failure(CurrentBaseProofReason::SnapshotFailed))?,
5894            transport_epoch: self.transport_epoch,
5895            registration_epoch: self.registration_epoch,
5896            security_epoch: self.security_epoch,
5897        })
5898    }
5899
5900    /// Internal host step after the completed post-rejection idle drive.
5901    #[doc(hidden)]
5902    pub fn finish_current_base(
5903        &mut self,
5904        prepared: CurrentBasePreparation,
5905        drive: SyncOutcome,
5906    ) -> CurrentBaseProof {
5907        if self.transport_closed() || self.transport_epoch != prepared.transport_epoch {
5908            return CurrentBaseProof::failure(CurrentBaseProofReason::Offline);
5909        }
5910        if self.registration_epoch != prepared.registration_epoch {
5911            return CurrentBaseProof::failure(CurrentBaseProofReason::MissingCoverage);
5912        }
5913        if self.security_preflight || self.security_epoch != prepared.security_epoch {
5914            return CurrentBaseProof::failure(CurrentBaseProofReason::SyncFailed);
5915        }
5916        let report = match drive {
5917            SyncOutcome::Ok(report) => report,
5918            SyncOutcome::BudgetExhausted(_) => {
5919                return CurrentBaseProof::failure(CurrentBaseProofReason::BudgetExhausted)
5920            }
5921            _ => return CurrentBaseProof::failure(CurrentBaseProofReason::SyncFailed),
5922        };
5923        if report.schema_floor.is_some() {
5924            return CurrentBaseProof::failure(CurrentBaseProofReason::SchemaFloor);
5925        }
5926        if self
5927            .conn
5928            .execute_batch("SAVEPOINT syncular_base_proof")
5929            .is_err()
5930        {
5931            return CurrentBaseProof::failure(CurrentBaseProofReason::SnapshotFailed);
5932        }
5933        let proof = (|| {
5934            let snapshot = snapshot_read_connection(
5935                &self.conn,
5936                Some(&self.schema),
5937                &SnapshotReadRequest {
5938                    units: prepared.units.iter().map(|unit| unit.id.clone()).collect(),
5939                    commit_ids: vec![prepared.client_commit_id.clone()],
5940                    ..Default::default()
5941                },
5942            )
5943            .map_err(|_| CurrentBaseProofReason::SnapshotFailed)?;
5944            let current = self
5945                .commit_outcome(&prepared.client_commit_id)
5946                .map_err(|_| CurrentBaseProofReason::SnapshotFailed)?;
5947            let unavailable = if report.revoked.is_empty() {
5948                CurrentBaseProofReason::OutcomeUnavailable
5949            } else {
5950                CurrentBaseProofReason::Revoked
5951            };
5952            let Some(outcome) = current else {
5953                return Err(unavailable);
5954            };
5955            if !matches!(
5956                snapshot.deliveries.first(),
5957                Some(CommitDelivery::Known { .. })
5958            ) || outcome.sequence != prepared.sequence
5959                || outcome.resolution != CommitOutcomeResolution::Active
5960                || !matches!(
5961                    outcome.status,
5962                    CommitOutcomeStatus::Conflict | CommitOutcomeStatus::Rejected
5963                )
5964            {
5965                return Err(unavailable);
5966            }
5967            let (Some(operations), Some(rows)) = (outcome.operations, outcome.retained_rows) else {
5968                return Err(unavailable);
5969            };
5970            if rows.is_empty() || operations.len() != rows.len() {
5971                return Err(unavailable);
5972            }
5973            let after =
5974                load_units(&self.conn).map_err(|_| CurrentBaseProofReason::SnapshotFailed)?;
5975            let complete: HashSet<&str> = snapshot
5976                .units
5977                .iter()
5978                .filter_map(|unit| match unit {
5979                    UnitCatchup::Known {
5980                        id,
5981                        bootstrap_complete: true,
5982                        ..
5983                    } => Some(id.as_str()),
5984                    _ => None,
5985                })
5986                .collect();
5987            // A unit id names one scope map (§4.1), so the same id before and
5988            // after the drive is the same registration.
5989            let candidates: Vec<&UnitRecord> = after
5990                .iter()
5991                .filter(|unit| {
5992                    complete.contains(unit.id.as_str())
5993                        && prepared.units.iter().any(|before| before.id == unit.id)
5994                })
5995                .collect();
5996            let covered = |table_name: &str, row: &Map<String, Value>| {
5997                let Some(table) = self.schema.table(table_name) else {
5998                    return false;
5999                };
6000                candidates.iter().any(|unit| {
6001                    covers(table, &unit.scopes)
6002                        && pair_scopes(&unit.scopes, table_name, unit.echo.as_deref()).is_some_and(
6003                            |scopes| {
6004                                scopes.iter().all(|(variable, allowed)| {
6005                                    table
6006                                        .scope_column(variable)
6007                                        .and_then(|column| match row.get(column) {
6008                                            Some(Value::String(value)) => Some(value.clone()),
6009                                            Some(Value::Bool(value)) => Some(value.to_string()),
6010                                            Some(Value::Number(value)) => {
6011                                                value.as_f64().map(|number| {
6012                                                    ryu_js::Buffer::new()
6013                                                        .format_finite(number)
6014                                                        .to_owned()
6015                                                })
6016                                            }
6017                                            _ => None,
6018                                        })
6019                                        .is_some_and(|value| {
6020                                            !value.is_empty() && allowed.contains(&value)
6021                                        })
6022                                })
6023                            },
6024                        )
6025                })
6026            };
6027            for row in &rows {
6028                let Some(base) = row.server_row.as_ref().or(row.local_row.as_ref()) else {
6029                    return Err(if report.revoked.is_empty() {
6030                        CurrentBaseProofReason::MissingCoverage
6031                    } else {
6032                        CurrentBaseProofReason::Revoked
6033                    });
6034                };
6035                if !covered(&row.table, base)
6036                    || row
6037                        .unique_conflicts
6038                        .iter()
6039                        .any(|conflict| !covered(&row.table, &conflict.server_row))
6040                {
6041                    return Err(if report.revoked.is_empty() {
6042                        CurrentBaseProofReason::MissingCoverage
6043                    } else {
6044                        CurrentBaseProofReason::Revoked
6045                    });
6046                }
6047            }
6048            Ok(rows)
6049        })();
6050        if self
6051            .conn
6052            .execute_batch("RELEASE syncular_base_proof")
6053            .is_err()
6054        {
6055            return CurrentBaseProof::failure(CurrentBaseProofReason::SnapshotFailed);
6056        }
6057        match proof {
6058            Ok(rows) => CurrentBaseProof {
6059                proven: true,
6060                rows: Some(rows),
6061                reason: None,
6062            },
6063            Err(reason) => CurrentBaseProof::failure(reason),
6064        }
6065    }
6066
6067    pub fn prove_current_base(
6068        &mut self,
6069        transport: &mut dyn Transport,
6070        client_commit_id: &str,
6071        sequence: i64,
6072        max_rounds: Option<u32>,
6073    ) -> CurrentBaseProof {
6074        let prepared = match self.prepare_current_base(client_commit_id, sequence) {
6075            Ok(prepared) => prepared,
6076            Err(proof) => return proof,
6077        };
6078        let drive = self.sync_until_idle(transport, max_rounds);
6079        self.finish_current_base(prepared, drive)
6080    }
6081
6082    pub fn commit_outcomes(&self, query: CommitOutcomeQuery) -> Result<Vec<CommitOutcome>, String> {
6083        if query.limit == Some(0) {
6084            return Err("sync.invalid_request: commit outcome limit must be positive".to_owned());
6085        }
6086        let mut sql = String::from(
6087            "SELECT seq, client_commit_id, status, recorded_at_ms, results_json, operations_json,
6088                    resolution, resolved_at_ms, replacement_client_commit_id
6089               FROM _syncular_commit_outcomes",
6090        );
6091        if query.active_only {
6092            sql.push_str(" WHERE resolution = 'active' AND status IN ('conflict', 'rejected')");
6093        }
6094        sql.push_str(" ORDER BY seq DESC");
6095        if let Some(limit) = query.limit {
6096            sql.push_str(&format!(" LIMIT {limit}"));
6097        }
6098        let mut stmt = self
6099            .conn
6100            .prepare(&sql)
6101            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6102        let rows = stmt
6103            .query_map([], |row| {
6104                Ok(StoredCommitOutcomeRow {
6105                    sequence: row.get(0)?,
6106                    client_commit_id: row.get(1)?,
6107                    status: row.get(2)?,
6108                    recorded_at_ms: row.get(3)?,
6109                    results_json: row.get(4)?,
6110                    operations_json: row.get(5)?,
6111                    resolution: row.get(6)?,
6112                    resolved_at_ms: row.get(7)?,
6113                    replacement_client_commit_id: row.get(8)?,
6114                })
6115            })
6116            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6117        let mut outcomes = Vec::new();
6118        for row in rows {
6119            let row = row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6120            outcomes.push(Self::reported_outcome(
6121                self.attach_retained_rows(Self::outcome_from_row(row)?)?,
6122            ));
6123        }
6124        Ok(outcomes)
6125    }
6126
6127    fn prune_commit_outcomes(&self) -> Result<(), String> {
6128        #[cfg(test)]
6129        self.outcome_prune_count
6130            .set(self.outcome_prune_count.get() + 1);
6131        let max_entries = self.limits.outcome_retention_max_entries.unwrap_or(1_000);
6132        let count = self
6133            .conn
6134            .query_row(
6135                "SELECT COUNT(*) FROM _syncular_commit_outcomes",
6136                [],
6137                |row| row.get::<_, i64>(0),
6138            )
6139            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
6140            as usize;
6141        let excess = count.saturating_sub(max_entries);
6142        if excess == 0 {
6143            return Ok(());
6144        }
6145        let mut stmt = self
6146            .conn
6147            .prepare(
6148                "SELECT seq FROM _syncular_commit_outcomes
6149                  WHERE status IN ('applied', 'cached') OR resolution != 'active'
6150                  ORDER BY seq ASC LIMIT ?1",
6151            )
6152            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6153        let rows = stmt
6154            .query_map(rusqlite::params![excess as i64], |row| row.get::<_, i64>(0))
6155            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6156        let sequences = rows
6157            .collect::<Result<Vec<_>, _>>()
6158            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6159        drop(stmt);
6160        for sequence in sequences {
6161            self.conn
6162                .execute(
6163                    "DELETE FROM _syncular_commit_outcomes WHERE seq = ?1",
6164                    rusqlite::params![sequence],
6165                )
6166                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6167        }
6168        Ok(())
6169    }
6170
6171    // -- units (§4.1) ------------------------------------------------------------
6172
6173    /// Every registered unit in registration order (§4.1).
6174    pub fn units(&self) -> Result<Vec<UnitRecord>, String> {
6175        self.stored(load_units(&self.conn))
6176    }
6177
6178    pub fn unit(&self, id: &str) -> Result<Option<UnitRecord>, String> {
6179        self.stored(get_unit(&self.conn, id))
6180    }
6181
6182    /// Register one unit (§4.1) and return its id.
6183    pub fn subscribe(&mut self, scopes: UnitScopes) -> Result<String, String> {
6184        Ok(self.subscribe_many(vec![scopes])?.remove(0))
6185    }
6186
6187    /// Register several units in one local transaction and return their ids:
6188    /// one commit for all of them (on OPFS a commit costs milliseconds, so a
6189    /// cold start with hundreds of units pays it once). An error rolls back
6190    /// every registration of the call. Registering an active unit again
6191    /// changes nothing; a revoked unit re-arms (§3.3). A call that registers or
6192    /// re-arms a unit raises sync-needed with an interactive intent.
6193    pub fn subscribe_many(&mut self, units: Vec<UnitScopes>) -> Result<Vec<String>, String> {
6194        let rollback = self.capture();
6195        self.begin_observation("syncular_subscribe")?;
6196        let mut changed = false;
6197        let registered = (|| {
6198            let mut ids = Vec::with_capacity(units.len());
6199            let mut batch = ChangeAccumulator::default();
6200            for scopes in units {
6201                let (id, held) = self.hold_unit(scopes, true)?;
6202                if held {
6203                    if let Some(unit) = self.stored(get_unit(&self.conn, &id))? {
6204                        self.record_unit_windows(&mut batch, &unit)?;
6205                    }
6206                }
6207                changed |= held;
6208                ids.push(id);
6209            }
6210            self.finish_observation("syncular_subscribe", batch)?;
6211            Ok(ids)
6212        })();
6213        let ids = match registered {
6214            Ok(ids) => ids,
6215            Err(error) => {
6216                self.rollback_observation("syncular_subscribe");
6217                self.restore(rollback);
6218                return Err(error);
6219            }
6220        };
6221        if changed {
6222            self.registration_epoch = self.registration_epoch.wrapping_add(1);
6223            self.set_sync_needed(true, true);
6224        }
6225        Ok(ids)
6226    }
6227
6228    /// Release the explicit reference to a unit. The unit leaves the
6229    /// registration list when no window base holds it (§4.1); its rows stay.
6230    pub fn unsubscribe(&mut self, id: &str) -> Result<(), String> {
6231        let Some(unit) = self.stored(get_unit(&self.conn, id))? else {
6232            return Ok(());
6233        };
6234        if !unit.explicit {
6235            return Ok(());
6236        }
6237        if !self.stored(window_refs(&self.conn, id))?.is_empty() {
6238            return self.stored(save_unit(
6239                &self.conn,
6240                &UnitRecord {
6241                    explicit: false,
6242                    ..unit
6243                },
6244            ));
6245        }
6246        let rollback = self.capture();
6247        self.begin_observation("syncular_unsubscribe")?;
6248        let removed = (|| {
6249            self.conn
6250                .execute("DELETE FROM _syncular_units WHERE id = ?1", [id])
6251                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6252            let mut batch = ChangeAccumulator::default();
6253            self.record_unit_windows(&mut batch, &unit)?;
6254            self.finish_observation("syncular_unsubscribe", batch)
6255        })();
6256        if let Err(error) = removed {
6257            self.rollback_observation("syncular_unsubscribe");
6258            self.restore(rollback);
6259            return Err(error);
6260        }
6261        self.registration_epoch = self.registration_epoch.wrapping_add(1);
6262        if unit.status == UnitStatus::Active {
6263            self.set_sync_needed(true, true);
6264        }
6265        Ok(())
6266    }
6267
6268    /// Take one reference on a unit (§4.1): validate the scope map, register a
6269    /// new unit catching up with cursor `-1`, re-arm a revoked one (§3.3).
6270    /// Returns the id and whether the registration list changed.
6271    fn hold_unit(&mut self, scopes: UnitScopes, explicit: bool) -> Result<(String, bool), String> {
6272        if scopes.is_empty()
6273            || scopes.values().any(|value| value == "*")
6274            || !self
6275                .schema
6276                .tables
6277                .iter()
6278                .any(|table| covers(table, &scopes))
6279        {
6280            return Err("sync.invalid_subscription: a unit names one non-wildcard value per variable and covers a table".to_owned());
6281        }
6282        let id = ssp2::registration::unit_id(&scope_pairs(&scopes));
6283        let existing = self.stored(get_unit(&self.conn, &id))?;
6284        if let Some(existing) = existing
6285            .as_ref()
6286            .filter(|unit| unit.status != UnitStatus::Revoked)
6287        {
6288            if explicit && !existing.explicit {
6289                self.stored(save_unit(
6290                    &self.conn,
6291                    &UnitRecord {
6292                        explicit,
6293                        ..existing.clone()
6294                    },
6295                ))?;
6296            }
6297            return Ok((id, false));
6298        }
6299        self.delete_pending_evict(&id)?;
6300        self.stored(save_unit(
6301            &self.conn,
6302            &UnitRecord {
6303                id: id.clone(),
6304                scopes,
6305                explicit: explicit || existing.is_some_and(|unit| unit.explicit),
6306                status: UnitStatus::Active,
6307                reason_code: None,
6308                cursor: Some(-1),
6309                bootstrap_state: None,
6310                seeded: Vec::new(),
6311                echo: None,
6312                restriction: None,
6313            },
6314        ))?;
6315        Ok((id, true))
6316    }
6317
6318    // -- windows (§4.8) -----------------------------------------------------------
6319
6320    /// §4.8: set the windowed-in values of a base, one unit per value. Added
6321    /// values take a reference on their unit (a new unit bootstraps on the
6322    /// next sync); removed values release theirs, and a unit no reference
6323    /// holds leaves the registration list fused with its first eviction chunk
6324    /// (E1–E4). Idempotent; re-entry cancels a deferred eviction.
6325    pub fn set_window(
6326        &mut self,
6327        base: &WindowBase,
6328        units: &[String],
6329    ) -> Result<CommandEffects, String> {
6330        let base_key = window_base_key(base);
6331        let live = self.load_window_units(&base_key)?;
6332        let mut changed = false;
6333        // §7.8: the added values register in one transaction. §3.3: a held
6334        // value whose unit is revoked re-arms once per open core.
6335        let mut added: Vec<&String> = Vec::new();
6336        for value in units {
6337            let held = live.iter().find(|(held, _)| held == value);
6338            let rearm = match held {
6339                None => true,
6340                Some((_, id)) => {
6341                    !self.window_armed.contains(id)
6342                        && self
6343                            .stored(get_unit(&self.conn, id))?
6344                            .is_some_and(|unit| unit.status == UnitStatus::Revoked)
6345                }
6346            };
6347            if rearm {
6348                added.push(value);
6349            }
6350        }
6351        if !added.is_empty() {
6352            let rollback = self.capture();
6353            self.begin_observation("syncular_window")?;
6354            let widened = (|| {
6355                let mut batch = ChangeAccumulator::default();
6356                for value in &added {
6357                    let (id, registered) =
6358                        self.hold_unit(window_unit_scopes(base, value), false)?;
6359                    self.sync_needed |= registered;
6360                    if registered {
6361                        self.window_armed.insert(id.clone());
6362                    }
6363                    self.conn
6364                        .execute(
6365                            "INSERT OR REPLACE INTO _syncular_windows(base, unit, sub_id) VALUES (?1, ?2, ?3)",
6366                            rusqlite::params![base_key, value, id],
6367                        )
6368                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6369                    batch.window(&base_key, value);
6370                    // A registered or re-armed unit is a transition for every
6371                    // window value that references it.
6372                    if registered {
6373                        if let Some(unit) = self.stored(get_unit(&self.conn, &id))? {
6374                            self.record_unit_windows(&mut batch, &unit)?;
6375                        }
6376                    }
6377                }
6378                batch.status = true;
6379                self.finish_observation("syncular_window", batch)
6380            })();
6381            if let Err(error) = widened {
6382                self.rollback_observation("syncular_window");
6383                self.restore(rollback);
6384                return Err(error);
6385            }
6386            changed = true;
6387            self.registration_epoch = self.registration_epoch.wrapping_add(1);
6388        }
6389        for (value, id) in live {
6390            if units.contains(&value) {
6391                continue;
6392            }
6393            self.rebuild_overlay_if_dirty()?;
6394            let rollback = self.capture();
6395            self.begin_observation("syncular_window")?;
6396            let remaining = self.release_window_unit(&base_key, &value, &id);
6397            let remaining = match remaining {
6398                Ok(remaining) => remaining,
6399                Err(error) => {
6400                    self.rollback_observation("syncular_window");
6401                    self.restore(rollback);
6402                    return Err(error);
6403                }
6404            };
6405            changed = true;
6406            self.registration_epoch = self.registration_epoch.wrapping_add(1);
6407            if remaining {
6408                self.drain_pending_evictions()?;
6409            }
6410        }
6411        Ok(if changed && !self.transport_closed() {
6412            CommandEffects::interactive()
6413        } else {
6414            CommandEffects::none()
6415        })
6416    }
6417
6418    /// §4.8 completeness oracle: the windowed-in values of a base and those
6419    /// whose unit is not complete. A value is complete once its unit is active
6420    /// and no longer bootstrapping; registration alone is not completeness.
6421    pub fn window_state(&self, base: &WindowBase) -> Result<WindowState, String> {
6422        persisted_window_state(&self.conn, base).map_err(|failure| failure.message)
6423    }
6424
6425    /// Registry rows for a base, ordered by value: (value, unit id).
6426    fn load_window_units(&self, base_key: &str) -> Result<Vec<(String, String)>, String> {
6427        let mut statement = self
6428            .conn
6429            .prepare_cached(
6430                "SELECT unit, sub_id FROM _syncular_windows WHERE base = ?1 ORDER BY unit ASC",
6431            )
6432            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6433        let rows = statement
6434            .query_map([base_key], |row| Ok((row.get(0)?, row.get(1)?)))
6435            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6436        rows.collect::<Result<_, _>>()
6437            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
6438    }
6439
6440    /// §4.8: the window-domain changes of one unit transition, the one path
6441    /// every transition site takes: one per window value that references the
6442    /// unit or, when none does, one for the base derived from its scope map
6443    /// (the variable first in code-unit order and its value; the other
6444    /// variables its fixed scopes). A transition adds no table change.
6445    fn record_unit_windows(
6446        &self,
6447        batch: &mut ChangeAccumulator,
6448        unit: &UnitRecord,
6449    ) -> Result<(), String> {
6450        let refs = self.stored(window_refs(&self.conn, &unit.id))?;
6451        if refs.is_empty() {
6452            let mut pairs = scope_pairs(&unit.scopes).into_iter();
6453            if let Some((variable, value)) = pairs.next() {
6454                let base = WindowBase {
6455                    variable,
6456                    fixed_scopes: pairs.collect(),
6457                };
6458                batch.window(&window_base_key(&base), &value);
6459            }
6460        }
6461        for (base_key, value) in refs {
6462            batch.window(&base_key, &value);
6463        }
6464        Ok(())
6465    }
6466
6467    /// §4.8: release a window value's reference inside the caller's
6468    /// observation. When no reference holds the unit, unregister it fused with
6469    /// its first eviction chunk (E3): delete the rows of every covered table
6470    /// matching the persisted echo, except rows pinned by the outbox (E1) or
6471    /// owned by another unit (§3.3), and park the per-table scopes of what
6472    /// remains in the pending-eviction registry. Fails closed without a local
6473    /// scope-column mapping. Returns whether unpinned rows remain.
6474    fn release_window_unit(
6475        &mut self,
6476        base_key: &str,
6477        value: &str,
6478        id: &str,
6479    ) -> Result<bool, String> {
6480        self.conn
6481            .execute(
6482                "DELETE FROM _syncular_windows WHERE base = ?1 AND unit = ?2",
6483                rusqlite::params![base_key, value],
6484            )
6485            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6486        self.window_armed.remove(id);
6487        let mut batch = ChangeAccumulator::default();
6488        batch.window(base_key, value);
6489        batch.status = true;
6490        let unit = self.stored(get_unit(&self.conn, id))?;
6491        let mut remaining = false;
6492        if let Some(unit) = unit.filter(|unit| !unit.explicit) {
6493            if self.stored(window_refs(&self.conn, id))?.is_empty() {
6494                let units = self.stored(load_units(&self.conn))?;
6495                self.conn
6496                    .execute("DELETE FROM _syncular_units WHERE id = ?1", [id])
6497                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6498                self.sync_needed = true;
6499                for table in self.schema.tables.clone() {
6500                    let Some(effective) = unit
6501                        .echo
6502                        .as_deref()
6503                        .filter(|_| covers(&table, &unit.scopes))
6504                        .and_then(|echo| pair_scopes(&unit.scopes, &table.name, Some(echo)))
6505                    else {
6506                        continue;
6507                    };
6508                    let pinned = self.pinned_row_ids(&table.name);
6509                    let owners = unit_owners(&units, &table, id);
6510                    let (more, deferred) =
6511                        self.evict_scope_rows(&table.name, &effective, &owners, &pinned)?;
6512                    remaining |= more;
6513                    if deferred {
6514                        self.save_pending_evict(id, &table.name, &effective)?;
6515                    }
6516                    self.record_scope_map(&mut batch, &table.name, &effective);
6517                }
6518            }
6519        }
6520        self.finish_observation("syncular_window", batch)?;
6521        Ok(remaining)
6522    }
6523
6524    /// §4.8 E1: delete base rows owned by the effective scopes
6525    /// ([`local_scope_predicate`]) EXCEPT pinned primary keys. Returns (more
6526    /// unpinned work, any scoped rows remain). A missing scope-column mapping
6527    /// fails without deleting rows.
6528    fn evict_scope_rows(
6529        &self,
6530        table_name: &str,
6531        effective: &[(String, Vec<String>)],
6532        owners: &[Vec<(String, Vec<String>)>],
6533        pinned: &std::collections::HashSet<String>,
6534    ) -> Result<(bool, bool), String> {
6535        let table = self.schema.table(table_name).ok_or("sync.unknown_table")?;
6536        let Some((scope, mut params)) = local_scope_predicate(table, effective, owners)
6537            .map_err(|()| "sync.scope_revoked".to_owned())?
6538        else {
6539            return Ok((false, false));
6540        };
6541        let scope_params = params.len();
6542        let pk = quote_ident(&table.primary_key);
6543        // Pinned ids are rowId text; the text form matches every key type.
6544        let predicate = if pinned.is_empty() {
6545            scope.clone()
6546        } else {
6547            params.extend(pinned.iter().cloned().map(SqlValue::Text));
6548            let holes = vec!["?"; pinned.len()].join(", ");
6549            format!("{scope} AND CAST({pk} AS TEXT) NOT IN ({holes})")
6550        };
6551        let base = base_table(table_name);
6552        let visible = visible_table(table_name);
6553        let mut ids: Vec<SqlValue> = Vec::new();
6554        for source in [&base, &visible] {
6555            let mut stmt = self
6556                .conn
6557                .prepare_cached(&format!(
6558                    "SELECT {pk} FROM {source} WHERE {predicate} LIMIT 1024"
6559                ))
6560                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6561            ids = stmt
6562                .query_map(rusqlite::params_from_iter(&params), |row| row.get(0))
6563                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
6564                .collect::<Result<_, _>>()
6565                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6566            if !ids.is_empty() {
6567                break;
6568            }
6569        }
6570        if !ids.is_empty() {
6571            for id in &ids {
6572                self.conn
6573                    .execute(
6574                        "DELETE FROM _syncular_acked_rows WHERE tbl=?1 AND id=?2",
6575                        rusqlite::params![table_name, id],
6576                    )
6577                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6578            }
6579            let holes = vec!["?"; ids.len()].join(", ");
6580            for source in [&base, &visible] {
6581                self.conn
6582                    .execute(
6583                        &format!("DELETE FROM {source} WHERE {pk} IN ({holes})"),
6584                        rusqlite::params_from_iter(&ids),
6585                    )
6586                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6587            }
6588        }
6589        let mut remaining = false;
6590        let mut deferred = false;
6591        for source in [&base, &visible] {
6592            remaining |= self
6593                .conn
6594                .query_row(
6595                    &format!("SELECT EXISTS(SELECT 1 FROM {source} WHERE {predicate})"),
6596                    rusqlite::params_from_iter(&params),
6597                    |row| row.get::<_, bool>(0),
6598                )
6599                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6600            deferred |= self
6601                .conn
6602                .query_row(
6603                    &format!("SELECT EXISTS(SELECT 1 FROM {source} WHERE {scope})"),
6604                    rusqlite::params_from_iter(&params[..scope_params]),
6605                    |row| row.get::<_, bool>(0),
6606                )
6607                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6608        }
6609        Ok((remaining, deferred))
6610    }
6611
6612    /// §4.8 E1: continue deferred evictions after the outbox drains or between
6613    /// chunks, retaining outbox pins and their durable marker. A unit that
6614    /// re-entered the window has no pending entry left.
6615    fn drain_pending_evictions(&mut self) -> Result<(), String> {
6616        let pending = self.load_pending_evictions()?;
6617        if pending.is_empty() {
6618            return Ok(());
6619        }
6620        self.rebuild_overlay_if_dirty()?;
6621        for (unit_id, table_name, effective) in pending {
6622            let Some(table) = self.schema.table(&table_name).cloned() else {
6623                self.delete_pending_evict_table(&unit_id, &table_name)?;
6624                continue;
6625            };
6626            loop {
6627                std::thread::yield_now();
6628                self.begin_observation("syncular_evict")?;
6629                let chunk = (|| {
6630                    let pinned = self.pinned_row_ids(&table_name);
6631                    let owners =
6632                        unit_owners(&self.stored(load_units(&self.conn))?, &table, &unit_id);
6633                    let (remaining, deferred) =
6634                        self.evict_scope_rows(&table_name, &effective, &owners, &pinned)?;
6635                    if !deferred {
6636                        self.delete_pending_evict_table(&unit_id, &table_name)?;
6637                    }
6638                    let mut batch = ChangeAccumulator::default();
6639                    self.record_scope_map(&mut batch, &table_name, &effective);
6640                    self.finish_observation("syncular_evict", batch)?;
6641                    Ok(remaining)
6642                })();
6643                match chunk {
6644                    Ok(true) => {}
6645                    Ok(false) => break,
6646                    Err(error) => {
6647                        self.rollback_observation("syncular_evict");
6648                        return Err(error);
6649                    }
6650                }
6651            }
6652        }
6653        Ok(())
6654    }
6655
6656    /// §4.8 E1: primary keys of `table` referenced by a pending outbox
6657    /// commit — rows that MUST NOT be evicted until the commit drains.
6658    fn pinned_row_ids(&self, table: &str) -> std::collections::HashSet<String> {
6659        let mut pinned = std::collections::HashSet::new();
6660        for commit in self
6661            .outbox
6662            .iter()
6663            .map(|commit| &**commit)
6664            .chain(self.failed_commits.iter().map(|(commit, _)| commit))
6665        {
6666            for op in &commit.ops {
6667                if op.table == table {
6668                    pinned.insert(op.row_id.clone());
6669                }
6670            }
6671        }
6672        pinned
6673    }
6674
6675    fn save_pending_evict(
6676        &self,
6677        unit_id: &str,
6678        table: &str,
6679        effective: &[(String, Vec<String>)],
6680    ) -> Result<(), String> {
6681        self.conn.execute(
6682            "INSERT OR REPLACE INTO _syncular_pending_evictions(unit_id, tbl, effective_scopes) VALUES (?1, ?2, ?3)",
6683            rusqlite::params![unit_id, table, scope_map_to_json(effective).to_string()],
6684        ).map(|_| ()).map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
6685    }
6686
6687    /// Re-entry cancels every pending eviction of the unit.
6688    fn delete_pending_evict(&self, unit_id: &str) -> Result<(), String> {
6689        self.conn
6690            .execute(
6691                "DELETE FROM _syncular_pending_evictions WHERE unit_id = ?1",
6692                [unit_id],
6693            )
6694            .map(|_| ())
6695            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
6696    }
6697
6698    fn delete_pending_evict_table(&self, unit_id: &str, table: &str) -> Result<(), String> {
6699        self.conn
6700            .execute(
6701                "DELETE FROM _syncular_pending_evictions WHERE unit_id = ?1 AND tbl = ?2",
6702                [unit_id, table],
6703            )
6704            .map(|_| ())
6705            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
6706    }
6707
6708    fn load_pending_evictions(&self) -> Result<Vec<PendingEvict>, String> {
6709        let mut stmt = self
6710            .conn
6711            .prepare("SELECT unit_id, tbl, effective_scopes FROM _syncular_pending_evictions")
6712            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6713        let rows = stmt
6714            .query_map([], |row| {
6715                Ok((
6716                    row.get::<_, String>(0)?,
6717                    row.get::<_, String>(1)?,
6718                    row.get::<_, String>(2)?,
6719                ))
6720            })
6721            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6722        rows.map(|row| {
6723            let (unit_id, table, json) =
6724                row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6725            let value: Value = serde_json::from_str(&json)
6726                .map_err(|_| "sync.local_corrupt: invalid pending eviction scopes".to_owned())?;
6727            let effective = json_to_scope_map(&value)
6728                .map_err(|_| "sync.local_corrupt: invalid pending eviction scopes".to_owned())?;
6729            Ok((unit_id, table, effective))
6730        })
6731        .collect()
6732    }
6733
6734    /// Select failed-intent retention; reload durable retained aggregates.
6735    pub fn set_retain_failed_commits(&mut self, enabled: bool) -> Result<(), String> {
6736        self.retain_failed_commits = enabled;
6737        for (commit, _) in self.failed_commits.iter() {
6738            for operation in &commit.ops {
6739                self.overlay_dirty.table(&operation.table);
6740            }
6741        }
6742        self.failed_commits = self.load_failed_commits()?.into();
6743        for (commit, _) in self.failed_commits.iter() {
6744            for operation in &commit.ops {
6745                self.overlay_dirty.table(&operation.table);
6746            }
6747        }
6748        Ok(())
6749    }
6750
6751    fn load_failed_commits(&self) -> Result<Vec<FailedCommit>, String> {
6752        let mut statement = self.conn.prepare("SELECT client_commit_id, operations_json, initial_json FROM _syncular_failed_commits ORDER BY seq")
6753            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6754        let rows = statement
6755            .query_map([], |row| {
6756                Ok((
6757                    row.get::<_, String>(0)?,
6758                    row.get::<_, String>(1)?,
6759                    row.get::<_, String>(2)?,
6760                ))
6761            })
6762            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6763        rows.map(|row| {
6764            let (id, operations, initial) =
6765                row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6766            let operations: Vec<CommitOperation> =
6767                serde_json::from_str(&operations).map_err(|_| "sync.local_corrupt".to_owned())?;
6768            let initial =
6769                serde_json::from_str(&initial).map_err(|_| "sync.local_corrupt".to_owned())?;
6770            Ok((
6771                OutboxCommit {
6772                    client_commit_id: id,
6773                    ops: operations
6774                        .into_iter()
6775                        .map(|op| OutboxOp {
6776                            upsert: op.op == "upsert",
6777                            table: op.table,
6778                            row_id: op.row_id,
6779                            base_version: op.base_version,
6780                            values: op.values,
6781                            insert: op.insert,
6782                        })
6783                        .collect(),
6784                },
6785                initial,
6786            ))
6787        })
6788        .collect()
6789    }
6790
6791    fn retain_failed_commit(&mut self, id: &str, operations: &[OutboxOp]) -> Result<(), String> {
6792        let mut initial = Map::new();
6793        for operation in operations {
6794            // A table the current schema removed has no rows to retain.
6795            let Some(table) = self.schema.table(&operation.table) else {
6796                continue;
6797            };
6798            let initial_row = match self.stored_row(table, &operation.row_id, true)? {
6799                Some(row) => Some(row),
6800                None => self.visible_row(table, &operation.row_id)?,
6801            };
6802            if let Some((values, _)) = initial_row {
6803                let mut intended: Map<String, Value> = table
6804                    .columns
6805                    .iter()
6806                    .zip(values.iter())
6807                    .map(|(column, value)| (column.name.clone(), column_value_to_json(value)))
6808                    .collect();
6809                if let Some(patch) = &operation.values {
6810                    intended.extend(patch.clone());
6811                }
6812                initial.insert(
6813                    serde_json::to_string(&(operation.table.clone(), operation.row_id.clone()))
6814                        .map_err(|_| "sync.local_corrupt".to_owned())?,
6815                    Value::Object(intended),
6816                );
6817            }
6818        }
6819        self.conn.execute("INSERT INTO _syncular_failed_commits(client_commit_id, operations_json, initial_json) VALUES (?1, ?2, ?3)", rusqlite::params![id,
6820            serde_json::to_string(&operations.iter().map(CommitOperation::from).collect::<Vec<_>>()).map_err(|_| "sync.local_corrupt".to_owned())?,
6821            serde_json::to_string(&initial).map_err(|_| "sync.local_corrupt".to_owned())?])
6822            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6823        self.failed_commits.push((
6824            OutboxCommit {
6825                client_commit_id: id.to_owned(),
6826                ops: operations.to_vec(),
6827            },
6828            initial,
6829        ));
6830        Ok(())
6831    }
6832
6833    fn drop_failed_commits(
6834        &mut self,
6835        matches: impl Fn(&str, &Map<String, Value>) -> bool,
6836    ) -> Result<Vec<OutboxCommit>, String> {
6837        let mut doomed = self.drop_acknowledged_rows(&matches)?;
6838        for (commit, initial) in self.failed_commits.iter() {
6839            for operation in &commit.ops {
6840                let key =
6841                    serde_json::to_string(&(operation.table.clone(), operation.row_id.clone()))
6842                        .map_err(|_| "sync.local_corrupt".to_owned())?;
6843                if initial
6844                    .get(&key)
6845                    .and_then(Value::as_object)
6846                    .is_some_and(|values| matches(&operation.table, values))
6847                {
6848                    doomed.push(commit.clone());
6849                    break;
6850                }
6851            }
6852        }
6853        for commit in &doomed {
6854            self.conn
6855                .execute(
6856                    "DELETE FROM _syncular_failed_commits WHERE client_commit_id = ?1",
6857                    rusqlite::params![commit.client_commit_id],
6858                )
6859                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6860        }
6861        for commit in &doomed {
6862            self.conn.execute("UPDATE _syncular_commit_outcomes SET operations_json = NULL, results_json = '[]' WHERE client_commit_id = ?1", rusqlite::params![commit.client_commit_id]).map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6863        }
6864        self.conflicts.retain(|record| {
6865            !doomed
6866                .iter()
6867                .any(|commit| commit.client_commit_id == record.client_commit_id)
6868        });
6869        self.rejections.retain(|record| {
6870            !doomed
6871                .iter()
6872                .any(|commit| commit.client_commit_id == record.client_commit_id)
6873        });
6874        self.failed_commits.retain(|(commit, _)| {
6875            !doomed
6876                .iter()
6877                .any(|dropped| dropped.client_commit_id == commit.client_commit_id)
6878        });
6879        for commit in &doomed {
6880            for operation in &commit.ops {
6881                self.overlay_dirty.table(&operation.table);
6882            }
6883        }
6884        Ok(doomed)
6885    }
6886
6887    /// Record one commit of local mutations. The returned commit ID is the
6888    /// §2.3 idempotency key. Failures are structured so callers read
6889    /// `code`/`message`/`details` instead of parsing a string prefix.
6890    pub fn mutate(&mut self, mutations: Vec<Mutation>) -> Result<String, ClientError> {
6891        let prior = self.storage_failure.borrow_mut().take();
6892        let outcome = self
6893            .prepare_mutations(mutations)
6894            .and_then(|ops| Ok(self.record_outbox_commit(ops, None)?));
6895        self.finish_authoring(prior, outcome)
6896    }
6897
6898    /// §7.1: validate one commit's mutations into outbox operations.
6899    fn prepare_mutations(&self, mutations: Vec<Mutation>) -> Result<Vec<OutboxOp>, ClientError> {
6900        {
6901            if mutations.is_empty() {
6902                return Err(
6903                    "sync.invalid_request: a commit must contain at least one operation (§6.1)"
6904                        .to_owned()
6905                        .into(),
6906                );
6907            }
6908            let mut ops = Vec::with_capacity(mutations.len());
6909            // §7.1: a patch reads the row as the commit's earlier operations
6910            // leave it: the values an earlier upsert wrote, or None after an
6911            // earlier delete. A patch changes neither presence nor a scope
6912            // column, so it records nothing.
6913            let mut staged: HashMap<(String, String), Option<Map<String, Value>>> = HashMap::new();
6914            for mutation in mutations {
6915                match mutation {
6916                    Mutation::Patch {
6917                        table,
6918                        values,
6919                        base_version,
6920                    } => {
6921                        let schema_table = self
6922                            .schema
6923                            .table(&table)
6924                            .ok_or_else(|| "sync.unknown_table".to_owned())?;
6925                        let values = normalize_values_casing(schema_table, values)?;
6926                        let row_id = render_row_id_json(values.get(&schema_table.primary_key))?;
6927                        let base = staged.get(&(table.clone(), row_id.clone()));
6928                        ops.push(self.prepare_patch(
6929                            &table,
6930                            &row_id,
6931                            values,
6932                            base_version,
6933                            base,
6934                        )?);
6935                    }
6936                    Mutation::Upsert {
6937                        table,
6938                        values,
6939                        base_version,
6940                    } => {
6941                        let schema_table = self.schema.table(&table).ok_or_else(|| {
6942                            format!("sync.unknown_table: unknown table {table:?}")
6943                        })?;
6944                        // §5: value keys are accepted in snake_case AND the
6945                        // generated row types' camelCase; normalize to SQL truth
6946                        // before the pk lookup / codec see them.
6947                        let values = normalize_values_casing(schema_table, values)?;
6948                        let row_id = render_row_id_json(values.get(&schema_table.primary_key))?;
6949                        // §6.7 `mutate` marks every column present: fill missing
6950                        // nullable columns with NULL before the payload is built.
6951                        let values = full_row_values(schema_table, values)?;
6952                        self.refuse_sealed_row(schema_table, &row_id)?;
6953                        // §5.11: validate the payload encodes with the current
6954                        // codec. A key-selection or unknown-key failure is a
6955                        // durable rejection at the push seam (§10.3), never an
6956                        // author-time error. Full-row `mutate` presents every
6957                        // column, so no stored fallback is needed.
6958                        self.validate_author_encode(schema_table, &row_id, &values)?;
6959                        // §7.1 insert intent: the row is absent from the
6960                        // visible replica at call time, before this batch
6961                        // applies anything.
6962                        let insert = !self.visible_row_exists(schema_table, &row_id)?;
6963                        staged.insert((table.clone(), row_id.clone()), Some(values.clone()));
6964                        ops.push(OutboxOp {
6965                            upsert: true,
6966                            table,
6967                            row_id,
6968                            base_version,
6969                            values: Some(values),
6970                            insert,
6971                        });
6972                    }
6973                    Mutation::Delete {
6974                        table,
6975                        row_id,
6976                        base_version,
6977                    } => {
6978                        let schema_table = self.schema.table(&table).ok_or_else(|| {
6979                            format!("sync.unknown_table: unknown table {table:?}")
6980                        })?;
6981                        self.refuse_sealed_row(schema_table, &row_id)?;
6982                        // §2.4: the server rejects a rowId holding U+0000.
6983                        if row_id.contains('\0') {
6984                            return Err("sync.invalid_request: rowId holds U+0000 (§2.4)"
6985                                .to_owned()
6986                                .into());
6987                        }
6988                        staged.insert((table.clone(), row_id.clone()), None);
6989                        ops.push(OutboxOp {
6990                            upsert: false,
6991                            table,
6992                            row_id,
6993                            base_version,
6994                            values: None,
6995                            insert: false,
6996                        });
6997                    }
6998                }
6999            }
7000            Ok(ops)
7001        }
7002    }
7003
7004    /// Scope the retained `storage_failure` diagnostic to this call so an
7005    /// earlier operation's failure cannot classify a new one, and surface the
7006    /// call's own classified failure with its details. A fresh classified
7007    /// failure replaces the retained diagnostic; otherwise the earlier one is
7008    /// kept for the next sync.
7009    fn finish_authoring<T>(
7010        &self,
7011        prior: Option<QueryReadFailure>,
7012        outcome: Result<T, ClientError>,
7013    ) -> Result<T, ClientError> {
7014        let fresh = self.storage_failure.borrow_mut().take();
7015        *self.storage_failure.borrow_mut() = fresh.clone().or(prior);
7016        outcome.map_err(|error| fresh.map(ClientError::from).unwrap_or(error))
7017    }
7018
7019    /// `decides` names the active outcome this commit replaces (§7.2.2); the
7020    /// outcome records it as its pending decision in the same transaction.
7021    fn record_outbox_commit(
7022        &mut self,
7023        ops: Vec<OutboxOp>,
7024        decides: Option<&str>,
7025    ) -> Result<String, String> {
7026        let commit = OutboxCommit {
7027            client_commit_id: uuid::Uuid::new_v4().to_string(),
7028            ops,
7029        };
7030        self.begin_observation("syncular_mutation")?;
7031        let mut batch = ChangeAccumulator::default();
7032        for op in &commit.ops {
7033            let mut precise = self.record_row_scopes(&mut batch, &op.table, &op.row_id, false);
7034            if let Some(values) = &op.values {
7035                if let Some(table) = self.schema.table(&op.table) {
7036                    for scope in &table.scope_variables {
7037                        if let Some(Value::String(value)) = values.get(&scope.column) {
7038                            batch.scope(&op.table, format!("{}:{value}", scope.prefix));
7039                            precise = true;
7040                        }
7041                    }
7042                }
7043            }
7044            if !precise {
7045                batch.table(&op.table);
7046            }
7047        }
7048        let persisted = self.persist_outbox_insert(&commit).and_then(|()| {
7049            let Some(outcome) = decides else {
7050                return Ok(());
7051            };
7052            batch.outcomes = true;
7053            let updated = self
7054                .conn
7055                .execute(
7056                    "UPDATE _syncular_commit_outcomes SET replacement_client_commit_id = ?1
7057                      WHERE client_commit_id = ?2 AND resolution = 'active'
7058                        AND replacement_client_commit_id IS NULL",
7059                    rusqlite::params![commit.client_commit_id, outcome],
7060                )
7061                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
7062            if updated == 1 {
7063                Ok(())
7064            } else {
7065                Err(REPLACEMENT_PENDING.to_owned())
7066            }
7067        });
7068        if let Err(error) = persisted {
7069            self.rollback_observation("syncular_mutation");
7070            return Err(error);
7071        }
7072        // A clean overlay contains the FIFO fold of every previous commit, so
7073        // the new commit applies over it. §7.1: an operation that does not
7074        // apply (a secondary unique collision) fails the whole commit; the
7075        // savepoint rollback removes the outbox entry and every visible write.
7076        // The append undoes itself: a rollback capture would copy the outbox.
7077        let was_dirty = self.overlay_dirty.snapshot();
7078        let id = commit.client_commit_id.clone();
7079        let appended = self.rebuild_overlay_if_dirty().and_then(|()| {
7080            commit
7081                .ops
7082                .iter()
7083                .try_for_each(|op| self.apply_outbox_op(op))?;
7084            self.outbox.push(Arc::new(commit));
7085            batch.status = true;
7086            self.finish_observation("syncular_mutation", batch)
7087                .inspect_err(|_| drop(self.outbox.pop()))
7088        });
7089        if let Err(error) = appended {
7090            self.rollback_observation("syncular_mutation");
7091            self.overlay_dirty.restore(was_dirty);
7092            return Err(error);
7093        }
7094        Ok(id)
7095    }
7096
7097    /// Record one §6.1 sparse upsert: the primary key plus the supplied
7098    /// non-scope columns are present; every other column is absent and stays
7099    /// untouched on the server and in the local overlay. An absent local base
7100    /// refuses the whole batch with sync.row_missing before enqueueing (§7.1).
7101    /// Failures are structured so callers read `code`/`message`/`details`.
7102    pub fn patch(
7103        &mut self,
7104        table: &str,
7105        row_id: &str,
7106        partial: Map<String, Value>,
7107        base_version: Option<i64>,
7108    ) -> Result<String, ClientError> {
7109        let prior = self.storage_failure.borrow_mut().take();
7110        let outcome = self.perform_patch(table, row_id, partial, base_version);
7111        self.finish_authoring(prior, outcome)
7112    }
7113
7114    /// The unscoped patch body. Public authoring entry points scope
7115    /// `storage_failure` around the whole operation, including any pre-read.
7116    fn perform_patch(
7117        &mut self,
7118        table: &str,
7119        row_id: &str,
7120        partial: Map<String, Value>,
7121        base_version: Option<i64>,
7122    ) -> Result<String, ClientError> {
7123        let operation = self.prepare_patch(table, row_id, partial, base_version, None)?;
7124        Ok(self.record_outbox_commit(vec![operation], None)?)
7125    }
7126
7127    /// `staged` is the row as the batch's earlier operations leave it
7128    /// (`Some(None)` after a delete); `None` reads the visible replica.
7129    fn prepare_patch(
7130        &self,
7131        table: &str,
7132        row_id: &str,
7133        partial: Map<String, Value>,
7134        base_version: Option<i64>,
7135        staged: Option<&Option<Map<String, Value>>>,
7136    ) -> Result<OutboxOp, ClientError> {
7137        let schema_table = self
7138            .schema
7139            .table(table)
7140            .ok_or_else(|| format!("sync.unknown_table: unknown table {table:?}"))?;
7141        let partial = normalize_values_casing(schema_table, partial)?;
7142        if let Some(pk) = partial.get(&schema_table.primary_key) {
7143            if render_row_id_json(Some(pk)).ok().as_deref() != Some(row_id) {
7144                return Err(invalid_authoring(
7145                    "patch cannot change the primary key",
7146                    json!({ "table": table }),
7147                ));
7148            }
7149        }
7150        let exists = match staged {
7151            Some(row) => row.is_some(),
7152            None => self.visible_row_exists(schema_table, row_id)?,
7153        };
7154        if !exists {
7155            return Err("sync.row_missing: a sparse patch requires a local row"
7156                .to_owned()
7157                .into());
7158        }
7159        self.refuse_sealed_row(schema_table, row_id)?;
7160        // §3.4 rule 5 / §6.2: scope columns are immutable on update. The
7161        // server accepts a present scope column whose value equals the
7162        // stored row and applies it as a no-op, so a decoded envelope
7163        // round-trips. The local row is the only value the client can prove
7164        // equality against; when the row is absent locally the client cannot
7165        // prove equality against the server's stored row and fails closed.
7166        // A primary key that is also a scope column needs no stored-row
7167        // read: the primary key in a sparse payload is by construction the
7168        // row id being patched (§6.1), so its value is proven equal already.
7169        for scope in &schema_table.scope_variables {
7170            if !partial.contains_key(&scope.column) || scope.column == schema_table.primary_key {
7171                continue;
7172            }
7173            let Some(column) = schema_table
7174                .columns
7175                .iter()
7176                .find(|column| column.name == scope.column)
7177            else {
7178                continue;
7179            };
7180            let stored = match staged {
7181                Some(row) => row.as_ref().and_then(|row| {
7182                    json_to_column_value(column, row.get(&scope.column))
7183                        .ok()
7184                        .map(|value| column_value_to_json(&value))
7185                }),
7186                None => self
7187                    .conn
7188                    .query_row(
7189                        &format!(
7190                            "SELECT {} FROM {} WHERE {}",
7191                            quote_ident(&scope.column),
7192                            visible_table(&schema_table.name),
7193                            row_id_predicate(schema_table)
7194                        ),
7195                        rusqlite::params![row_id],
7196                        |row| Ok(sql_ref_to_json(column, row.get_ref(0)?)),
7197                    )
7198                    .optional()
7199                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?,
7200            };
7201            // Decode the supplied value through the same column-type path the
7202            // rest of the patch encoding uses, so a value that only equals
7203            // the stored one in another number representation still compares
7204            // equal.
7205            let incoming = json_to_column_value(column, partial.get(&scope.column))
7206                .ok()
7207                .map(|value| column_value_to_json(&value));
7208            // A stored blob never equals a patch value, matching the server's
7209            // scope-column comparison (§3.4): bytes are unstorable as scope
7210            // values.
7211            let equal = stored.as_ref().is_some_and(|stored| {
7212                stored.get("$bytes").is_none() && incoming.as_ref() == Some(stored)
7213            });
7214            if !equal {
7215                return Err(invalid_authoring(
7216                    "patch cannot write a scope column (§3.4)",
7217                    json!({ "table": table, "column": scope.column }),
7218                ));
7219            }
7220        }
7221        let mut values = partial;
7222        // Presence-set semantics: a proven-equal scope column is dropped, so
7223        // the patch leaves the stored value untouched (§6.2).
7224        for scope in &schema_table.scope_variables {
7225            values.remove(&scope.column);
7226        }
7227        let pk_value = match schema_table.columns[schema_table.pk_index].ty {
7228            // §2.4: the rowId of an integer key is its canonical decimal form.
7229            ColumnType::Integer => match row_id.parse::<i64>() {
7230                Ok(v)
7231                    if v.to_string() == row_id
7232                        && (-ssp2::primitives::I64_SAFE_MAX..=ssp2::primitives::I64_SAFE_MAX)
7233                            .contains(&v) =>
7234                {
7235                    Value::from(v)
7236                }
7237                _ => {
7238                    return Err(format!(
7239                    "sync.invalid_request: table {table:?}: invalid integer primary key {row_id:?}"
7240                )
7241                    .into())
7242                }
7243            },
7244            ColumnType::Boolean => match row_id {
7245                "true" => Value::Bool(true),
7246                "false" => Value::Bool(false),
7247                _ => {
7248                    return Err(format!(
7249                    "sync.invalid_request: table {table:?}: invalid boolean primary key {row_id:?}"
7250                )
7251                    .into())
7252                }
7253            },
7254            _ => Value::from(row_id.to_owned()),
7255        };
7256        values.insert(schema_table.primary_key.clone(), pk_value);
7257        // §6.1: a patch cannot null a non-nullable column.
7258        if let Some(column) = schema_table
7259            .columns
7260            .iter()
7261            .find(|column| !column.nullable && values.get(&column.name) == Some(&Value::Null))
7262        {
7263            return Err(invalid_authoring(
7264                "a non-nullable column is null (§6.1)",
7265                json!({ "table": table, "column": column.name }),
7266            ));
7267        }
7268        // §5.11: structural validation only; an absent key-id selector is
7269        // resolved at the push seam from the stored local row, and a
7270        // key-selection or unknown-key failure becomes a durable
7271        // `client.encrypt_failed` rejection there (§10.3), never an
7272        // author-time error.
7273        self.validate_author_encode(schema_table, row_id, &values)?;
7274        Ok(OutboxOp {
7275            upsert: true,
7276            table: table.to_owned(),
7277            row_id: row_id.to_owned(),
7278            base_version,
7279            values: Some(values),
7280            insert: false,
7281        })
7282    }
7283
7284    /// §5.11 key-id fallback: the stored local row's selector value as a
7285    /// positional row (only the selector slot filled). Returns None when no
7286    /// selector is configured, the row is locally absent, or the stored
7287    /// value is not a usable key id. A failed storage read is an error.
7288    fn stored_key_fallback(
7289        &self,
7290        table: &TableSchema,
7291        row_id: &str,
7292    ) -> Result<Option<Row>, String> {
7293        let Some(selector) = self.encryption.key_id_columns.get(&table.name) else {
7294            return Ok(None);
7295        };
7296        let Some(index) = table
7297            .columns
7298            .iter()
7299            .position(|column| &column.name == selector)
7300        else {
7301            return Ok(None);
7302        };
7303        let sql = format!(
7304            "SELECT {} FROM {} WHERE {}",
7305            quote_ident(selector),
7306            visible_table(&table.name),
7307            row_id_predicate(table)
7308        );
7309        let key = self
7310            .conn
7311            .query_row(&sql, rusqlite::params![row_id], |row| {
7312                row.get::<_, Option<String>>(0)
7313            })
7314            .optional()
7315            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
7316            .flatten()
7317            .filter(|key| !key.is_empty());
7318        let Some(key) = key else {
7319            return Ok(None);
7320        };
7321        let mut fallback: Row = vec![None; table.columns.len()];
7322        fallback[index] = Some(ColumnValue::String(key));
7323        Ok(Some(fallback))
7324    }
7325
7326    /// §5.11/§10.3 author-time encode check: a structural failure (a
7327    /// non-nullable NULL, a value the codec rejects) is an author-time
7328    /// error; a key-selection or unknown-key failure is deferred to the push
7329    /// seam, where it becomes a durable `client.encrypt_failed` rejection.
7330    fn validate_author_encode(
7331        &self,
7332        table: &TableSchema,
7333        row_id: &str,
7334        values: &Map<String, Value>,
7335    ) -> Result<(), String> {
7336        match encode_sparse_row_json(table, row_id, values, &self.encryption, None) {
7337            Err(error) if error.starts_with(ENCRYPT_FAILED_CODE) => Ok(()),
7338            result => result.map(|_| ()),
7339        }
7340    }
7341
7342    /// §5.11/§10.3: drop every pending commit whose push encode fails with
7343    /// `client.encrypt_failed` (an unresolvable key id or an unknown key) and
7344    /// raise one durable rejection per commit. `sync()` never aborts for an
7345    /// encode failure. Mirrors §7.4.4's `drop_incompatible_outbox`, including
7346    /// undoing the dropped commit's purely-optimistic rows.
7347    /// §7.1/§7.4.4: drop pending commits whose values the current codec refuses
7348    /// (an envelope or a type an earlier version accepted). `with_encryption`
7349    /// additionally drops commits whose §5.11 encryption cannot resolve a key;
7350    /// the startup boundary leaves those to the send seam, where hosts configure
7351    /// keys after open. The send path checks only the commits this round pushes
7352    /// (§8.8): a held commit is never encoded or dropped before it is due.
7353    /// Recovery runs as one observation. An enclosing observation (the guarded
7354    /// schema reset) passes its `batch`, so the rejection, outcome, and table
7355    /// domains join that change event instead of publishing a second one.
7356    fn drop_unencodable_outbox(
7357        &mut self,
7358        with_encryption: bool,
7359        batch: Option<&mut ChangeAccumulator>,
7360    ) -> Result<bool, String> {
7361        let mut failures = Vec::new();
7362        let due = if with_encryption {
7363            self.pushable_commits()
7364        } else {
7365            self.outbox.len()
7366        };
7367        for commit in self.outbox.iter().take(due) {
7368            for op in &commit.ops {
7369                let Some(table) = self.schema.table(&op.table).filter(|_| op.upsert) else {
7370                    continue;
7371                };
7372                // An insert lacking a non-nullable column is left to
7373                // `drop_incompatible_outbox` (§7.4.4).
7374                let Some(values) = op.presented_values(table) else {
7375                    continue;
7376                };
7377                let fallback = self.stored_key_fallback(table, &op.row_id)?;
7378                let failure = match encode_sparse_row_json(
7379                    table,
7380                    &op.row_id,
7381                    &values,
7382                    &self.encryption,
7383                    fallback.as_ref(),
7384                ) {
7385                    Err(error) if error.starts_with(ENCRYPT_FAILED_CODE) => {
7386                        with_encryption.then_some((error, ENCRYPT_FAILED_CODE))
7387                    }
7388                    // §7.1/§7.4.4: a value the current codec refuses was
7389                    // persisted by a version that accepted it; it leaves
7390                    // through the incompatible-outbox path, so the FIFO
7391                    // queue never wedges.
7392                    Err(error) if error.starts_with(INVALID_REQUEST_CODE) => Some((
7393                        LEGACY_VALUE_REFUSAL_MESSAGE.to_owned(),
7394                        OUTBOX_INCOMPATIBLE_CODE,
7395                    )),
7396                    _ => None,
7397                };
7398                if let Some((error, code)) = failure {
7399                    failures.push((commit.clone(), error, code));
7400                    break;
7401                }
7402            }
7403        }
7404        if failures.is_empty() {
7405            return Ok(false);
7406        }
7407        self.reject_outbox_commits(
7408            failures
7409                .into_iter()
7410                .map(|(commit, message, code)| {
7411                    let details = (code == OUTBOX_INCOMPATIBLE_CODE).then(|| RejectionDetails {
7412                        field_paths: None,
7413                        reason: Some(INVALID_STORED_VALUES_REASON.to_owned()),
7414                        required_action: None,
7415                        references: None,
7416                    });
7417                    (commit, message, code, details)
7418                })
7419                .collect(),
7420            batch,
7421        )?;
7422        Ok(true)
7423    }
7424
7425    /// §7.4.4 client-local terminal drop of pending commits, each journaled as a
7426    /// rejection with `code` and `details`. Every code except
7427    /// `sync.outbox_incompatible` keeps the retained intent.
7428    #[allow(clippy::type_complexity)]
7429    fn reject_outbox_commits(
7430        &mut self,
7431        failures: Vec<(
7432            Arc<OutboxCommit>,
7433            String,
7434            &'static str,
7435            Option<RejectionDetails>,
7436        )>,
7437        batch: Option<&mut ChangeAccumulator>,
7438    ) -> Result<(), String> {
7439        // §7.4.4: one observation covers the durable outcome writes, the outbox
7440        // removal, the in-memory drop, and the overlay rebuild, so a storage fault
7441        // leaves the replica and the client unchanged, a successful recovery
7442        // publishes one batch with the rejection, outcome, and table domains, and
7443        // an ordinary open with nothing to recover publishes nothing.
7444        let rollback = self.capture();
7445        let owns_observation = batch.is_none();
7446        let owns_transaction = self.conn.is_autocommit();
7447        let mut domains = ChangeAccumulator::default();
7448        if owns_observation {
7449            self.begin_observation("syncular_value_recovery")?;
7450        }
7451        let dropped = (|| -> Result<(), String> {
7452            for (commit, message, code, details) in failures {
7453                if self.retain_failed_commits && code != OUTBOX_INCOMPATIBLE_CODE {
7454                    self.retain_failed_commit(&commit.client_commit_id, &commit.ops)?;
7455                }
7456                let representable = commit.ops.iter().all(Self::outbox_op_is_journalable);
7457                let rejection = RejectionRecord {
7458                    client_commit_id: commit.client_commit_id.clone(),
7459                    op_index: 0,
7460                    code: code.to_owned(),
7461                    message,
7462                    retryable: false,
7463                    details,
7464                    operation: representable
7465                        .then(|| commit.ops.first())
7466                        .flatten()
7467                        .map(CommitOperation::from),
7468                };
7469                self.persist_commit_outcome(
7470                    &commit.client_commit_id,
7471                    CommitOutcomeStatus::Rejected,
7472                    &[CommitOperationOutcome::Error {
7473                        rejection: rejection.clone(),
7474                    }],
7475                    representable.then_some(commit.ops.as_slice()),
7476                )?;
7477                self.leave_through(&commit.client_commit_id);
7478                self.delete_outbox_persisted(&commit.client_commit_id)?;
7479                self.outbox
7480                    .retain(|candidate| candidate.client_commit_id != commit.client_commit_id);
7481                self.rejections.push(rejection);
7482                for operation in &commit.ops {
7483                    domains.table(operation.table.as_str());
7484                }
7485            }
7486            domains.status = true;
7487            domains.rejections = true;
7488            domains.outcomes = true;
7489            self.prune_commit_outcomes()?;
7490            // The visible projection is re-derived from the surviving base + outbox.
7491            self.overlay_dirty.set(true);
7492            self.rebuild_overlay()?;
7493            Ok(())
7494        })();
7495        let result = match batch {
7496            Some(batch) => {
7497                if dropped.is_ok() {
7498                    for table in domains.tables.keys() {
7499                        batch.table(table.as_str());
7500                    }
7501                    batch.status |= domains.status;
7502                    batch.rejections |= domains.rejections;
7503                    batch.outcomes |= domains.outcomes;
7504                }
7505                dropped
7506            }
7507            None => {
7508                dropped.and_then(|()| self.finish_observation("syncular_value_recovery", domains))
7509            }
7510        };
7511        if let Err(error) = result {
7512            if owns_observation {
7513                if owns_transaction {
7514                    if let Err(rollback) = self.conn.execute_batch("ROLLBACK") {
7515                        let mut failure = self.storage_failure.borrow_mut();
7516                        let failure =
7517                            failure.get_or_insert_with(|| QueryReadFailure::from(error.clone()));
7518                        failure.rollback_failure = Some(Box::new(QueryReadFailure::from(rollback)));
7519                    }
7520                } else {
7521                    self.rollback_observation("syncular_value_recovery");
7522                }
7523            }
7524            self.restore(rollback);
7525            return Err(error);
7526        }
7527        Ok(())
7528    }
7529
7530    pub fn pending_commit_ids(&self) -> Vec<String> {
7531        self.outbox
7532            .iter()
7533            .map(|c| c.client_commit_id.clone())
7534            .collect()
7535    }
7536
7537    /// §7.1: every pending commit in FIFO order, as the TypeScript client's
7538    /// `pendingCommits()` returns it.
7539    pub fn pending_commits(&self) -> Result<Vec<PendingCommit>, String> {
7540        let mut stmt = self
7541            .conn
7542            .prepare_cached(
7543                "SELECT seq, commit_id, created_at_ms, ops_json FROM _syncular_outbox ORDER BY seq",
7544            )
7545            .map_err(|error| error.to_string())?;
7546        let rows = stmt
7547            .query_map([], |row| {
7548                Ok((
7549                    row.get(0)?,
7550                    row.get(1)?,
7551                    row.get(2)?,
7552                    row.get::<_, String>(3)?,
7553                ))
7554            })
7555            .map_err(|error| error.to_string())?;
7556        rows.map(|row| {
7557            let (seq, client_commit_id, created_at_ms, raw) =
7558                row.map_err(|error| error.to_string())?;
7559            let operations = serde_json::from_str(&raw).map_err(|error| {
7560                format!("invalid persisted outbox {client_commit_id:?}: {error}")
7561            })?;
7562            Ok(PendingCommit {
7563                seq,
7564                client_commit_id,
7565                created_at_ms,
7566                operations,
7567            })
7568        })
7569        .collect()
7570    }
7571
7572    /// §6.1: the sparse push payload bytes of every pending upsert operation,
7573    /// FIFO — exactly what the next push round would put on the wire. Used by
7574    /// conformance B.21(h) to pin cross-core byte identity.
7575    pub fn pending_payloads(&self) -> Result<Vec<Vec<u8>>, String> {
7576        let mut payloads = Vec::new();
7577        for commit in self.outbox.iter() {
7578            for op in &commit.ops {
7579                let Some(table) = self.schema.table(&op.table).filter(|_| op.upsert) else {
7580                    continue;
7581                };
7582                let Some(values) = op.presented_values(table) else {
7583                    continue;
7584                };
7585                let fallback = self.stored_key_fallback(table, &op.row_id)?;
7586                if let Ok(payload) = encode_sparse_row_json(
7587                    table,
7588                    &op.row_id,
7589                    &values,
7590                    &self.encryption,
7591                    fallback.as_ref(),
7592                ) {
7593                    payloads.push(payload);
7594                }
7595            }
7596        }
7597        Ok(payloads)
7598    }
7599
7600    pub fn conflicts(&self) -> &[ConflictRecord] {
7601        &self.conflicts
7602    }
7603
7604    pub fn rejections(&self) -> &[RejectionRecord] {
7605        &self.rejections
7606    }
7607
7608    pub fn resolve_commit_outcome(
7609        &mut self,
7610        input: ResolveCommitOutcomeInput,
7611    ) -> Result<CommitOutcome, String> {
7612        let current = self
7613            .commit_outcome(&input.client_commit_id)?
7614            .ok_or_else(|| {
7615                format!(
7616                    "sync.outcome_not_found: no durable outcome exists for {:?}",
7617                    input.client_commit_id
7618                )
7619            })?;
7620        if current.resolution != CommitOutcomeResolution::Active {
7621            return Ok(current);
7622        }
7623        if current.replacement_client_commit_id.is_some() {
7624            return Err(REPLACEMENT_PENDING.to_owned());
7625        }
7626        if input.resolution == CommitOutcomeResolution::Active {
7627            return Err("sync.invalid_request: resolution must leave active state".to_owned());
7628        }
7629        match input.resolution {
7630            CommitOutcomeResolution::Superseded => {
7631                let replacement = input
7632                    .replacement_client_commit_id
7633                    .as_deref()
7634                    .filter(|value| !value.is_empty() && *value != input.client_commit_id)
7635                    .ok_or_else(|| {
7636                        "sync.invalid_request: superseded outcomes require a distinct replacementClientCommitId"
7637                            .to_owned()
7638                    })?;
7639                let _ = replacement;
7640            }
7641            _ if input.replacement_client_commit_id.is_some() => {
7642                return Err(
7643                    "sync.invalid_request: replacementClientCommitId is valid only for superseded outcomes"
7644                        .to_owned(),
7645                );
7646            }
7647            _ => {}
7648        }
7649        let allowed = match current.status {
7650            CommitOutcomeStatus::Conflict => matches!(
7651                input.resolution,
7652                CommitOutcomeResolution::ResolvedKeepServer | CommitOutcomeResolution::Superseded
7653            ),
7654            CommitOutcomeStatus::Rejected => {
7655                matches!(
7656                    input.resolution,
7657                    CommitOutcomeResolution::Superseded
7658                        | CommitOutcomeResolution::ResolvedKeepServer
7659                )
7660            }
7661            CommitOutcomeStatus::Applied | CommitOutcomeStatus::Cached => {
7662                input.resolution == CommitOutcomeResolution::Dismissed
7663            }
7664            CommitOutcomeStatus::Replaced => false,
7665        };
7666        if !allowed {
7667            return Err(format!(
7668                "sync.invalid_request: resolution {:?} is invalid for {:?} outcome",
7669                input.resolution, current.status
7670            ));
7671        }
7672
7673        let rollback = self.capture();
7674        self.begin_observation("syncular_outcome_resolution")?;
7675        let mut batch = ChangeAccumulator::default();
7676        let result = self
7677            .release_outcome(
7678                &current,
7679                input.resolution,
7680                input.replacement_client_commit_id.as_deref(),
7681                &mut batch,
7682            )
7683            .and_then(|()| self.rebuild_overlay_if_dirty())
7684            .and_then(|()| self.finish_observation("syncular_outcome_resolution", batch));
7685        if let Err(error) = result {
7686            self.rollback_observation("syncular_outcome_resolution");
7687            self.restore(rollback);
7688            return Err(error);
7689        }
7690        self.commit_outcome(&current.client_commit_id)?
7691            .ok_or_else(|| "sync.outcome_not_found: outcome disappeared".to_owned())
7692    }
7693
7694    /// §7.2.2: record a decision against an active conflict or rejection as a
7695    /// held replacement commit and return its client commit id. Without
7696    /// `replacement` the retained envelope is kept ("keep mine"); every
7697    /// operation on a retained row takes that row's base version.
7698    pub fn replace_commit_outcome(
7699        &mut self,
7700        client_commit_id: &str,
7701        sequence: i64,
7702        replacement: Option<Vec<Mutation>>,
7703    ) -> Result<String, ClientError> {
7704        let prior = self.storage_failure.borrow_mut().take();
7705        let outcome = (|| -> Result<String, ClientError> {
7706            let Some(current) = self.commit_outcome(client_commit_id)? else {
7707                return Err(ClientError {
7708                    code: "sync.outcome_not_found".to_owned(),
7709                    message: "no durable outcome exists for the commit".to_owned(),
7710                    details: Some(json!({ "clientCommitId": client_commit_id })),
7711                    retryable: false,
7712                });
7713            };
7714            if current.resolution == CommitOutcomeResolution::Active
7715                && current.replacement_client_commit_id.is_some()
7716            {
7717                return Err(ClientError {
7718                    code: "client.replacement_pending".to_owned(),
7719                    message: "the outcome has a pending replacement".to_owned(),
7720                    details: Some(json!({ "clientCommitId": client_commit_id })),
7721                    retryable: false,
7722                });
7723            }
7724            let (Some(envelope), Some(rows)) = (current.operations, current.retained_rows) else {
7725                return Err(invalid_authoring(
7726                    "the outcome cannot be replaced",
7727                    json!({ "clientCommitId": client_commit_id }),
7728                ));
7729            };
7730            if current.sequence != sequence
7731                || current.resolution != CommitOutcomeResolution::Active
7732                || !matches!(
7733                    current.status,
7734                    CommitOutcomeStatus::Conflict | CommitOutcomeStatus::Rejected
7735                )
7736                || rows.is_empty()
7737                || envelope.len() != rows.len()
7738            {
7739                return Err(invalid_authoring(
7740                    "the outcome cannot be replaced",
7741                    json!({ "clientCommitId": client_commit_id }),
7742                ));
7743            }
7744            let ops = match replacement {
7745                None => envelope
7746                    .into_iter()
7747                    .zip(&rows)
7748                    .map(|(operation, row)| OutboxOp {
7749                        base_version: Some(row.server_version.unwrap_or(0)),
7750                        ..OutboxOp::from(operation)
7751                    })
7752                    .collect(),
7753                Some(mutations) => {
7754                    let mut ops = self.prepare_mutations(mutations)?;
7755                    for op in &mut ops {
7756                        let Some(row) = rows
7757                            .iter()
7758                            .find(|row| row.table == op.table && row.row_id == op.row_id)
7759                        else {
7760                            continue;
7761                        };
7762                        if op.base_version.is_some() {
7763                            return Err(invalid_authoring(
7764                                "an operation on a retained row takes its base version",
7765                                json!({ "table": op.table }),
7766                            ));
7767                        }
7768                        op.base_version = Some(row.server_version.unwrap_or(0));
7769                    }
7770                    ops
7771                }
7772            };
7773            Ok(self.record_outbox_commit(ops, Some(client_commit_id))?)
7774        })();
7775        self.finish_authoring(prior, outcome)
7776    }
7777
7778    /// §7.2.3: replace the operations of the pending commit `client_commit_id`
7779    /// and return `replacement_client_commit_id`. An attempted commit is fenced
7780    /// first (§6.12) over `transport`; a never-attempted one needs none.
7781    pub fn replace_pending_commit(
7782        &mut self,
7783        transport: &mut dyn Transport,
7784        client_commit_id: &str,
7785        mutations: Vec<Mutation>,
7786        replacement_client_commit_id: &str,
7787    ) -> Result<String, ClientError> {
7788        match self.prepare_pending_commit_replacement(
7789            client_commit_id,
7790            mutations,
7791            replacement_client_commit_id,
7792        )? {
7793            None => Ok(replacement_client_commit_id.to_owned()),
7794            Some(prepared) => {
7795                let reply = prepared.exchange(transport);
7796                self.apply_fence_round(prepared, reply)
7797            }
7798        }
7799    }
7800
7801    /// The owner half of [`SyncClient::replace_pending_commit`]. `None` means
7802    /// the replacement is complete (or an earlier call with the same
7803    /// replacement id completed it); otherwise send the fence round and apply
7804    /// its reply with [`SyncClient::apply_fence_round`].
7805    pub fn prepare_pending_commit_replacement(
7806        &mut self,
7807        client_commit_id: &str,
7808        mutations: Vec<Mutation>,
7809        replacement_client_commit_id: &str,
7810    ) -> Result<Option<PreparedFenceRound>, ClientError> {
7811        let prior = self.storage_failure.borrow_mut().take();
7812        let outcome = (|| -> Result<Option<PreparedFenceRound>, ClientError> {
7813            let Some(original) = self
7814                .outbox
7815                .iter()
7816                .find(|commit| commit.client_commit_id == client_commit_id)
7817                .cloned()
7818            else {
7819                return match self.commit_outcome(client_commit_id)? {
7820                    Some(outcome)
7821                        if Self::is_replaced(&outcome)
7822                            && outcome.replacement_client_commit_id.as_deref()
7823                                == Some(replacement_client_commit_id) =>
7824                    {
7825                        Ok(None)
7826                    }
7827                    _ => Err(ClientError {
7828                        code: "sync.outcome_not_found".to_owned(),
7829                        message: "no pending commit exists for the id".to_owned(),
7830                        details: Some(json!({ "clientCommitId": client_commit_id })),
7831                        retryable: false,
7832                    }),
7833                };
7834            };
7835            if replacement_client_commit_id.is_empty()
7836                || self
7837                    .outbox
7838                    .iter()
7839                    .any(|commit| commit.client_commit_id == replacement_client_commit_id)
7840                || self.commit_outcome(replacement_client_commit_id)?.is_some()
7841            {
7842                return Err(invalid_authoring(
7843                    "the replacement client commit id must be unused",
7844                    json!({ "replacementClientCommitId": replacement_client_commit_id }),
7845                ));
7846            }
7847            // §7.2.2: a held replacement waits for its proof under its own id.
7848            let held: bool = self
7849                .conn
7850                .query_row(
7851                    "SELECT EXISTS(SELECT 1 FROM _syncular_commit_outcomes
7852                      WHERE resolution = 'active' AND replacement_client_commit_id = ?1)",
7853                    [client_commit_id],
7854                    |row| row.get(0),
7855                )
7856                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
7857            if held {
7858                return Err(REPLACEMENT_PENDING.to_owned().into());
7859            }
7860            let full_rows: Vec<bool> = mutations
7861                .iter()
7862                .map(|mutation| matches!(mutation, Mutation::Upsert { .. }))
7863                .collect();
7864            let mut operations = self.prepare_mutations(mutations)?;
7865            for (operation, full_row) in operations.iter_mut().zip(full_rows) {
7866                let touched: Vec<&OutboxOp> = original
7867                    .ops
7868                    .iter()
7869                    .filter(|op| op.table == operation.table && op.row_id == operation.row_id)
7870                    .collect();
7871                // §7.1: a full-row upsert of a row the original inserted keeps
7872                // the insert intent the original recorded.
7873                operation.insert |= full_row && touched.iter().any(|op| op.insert);
7874                if let Some(first) = touched.first() {
7875                    operation.base_version = first.base_version;
7876                }
7877            }
7878            let attempted: bool = self
7879                .conn
7880                .query_row(
7881                    "SELECT attempted FROM _syncular_outbox WHERE commit_id = ?1",
7882                    [client_commit_id],
7883                    |row| row.get(0),
7884                )
7885                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
7886            if !attempted {
7887                self.replace_outbox_commit(
7888                    client_commit_id,
7889                    operations,
7890                    replacement_client_commit_id,
7891                )?;
7892                return Ok(None);
7893            }
7894            if self.transport_closed() {
7895                return Err(ClientError {
7896                    code: "sync.offline".to_owned(),
7897                    message: "transport gate is closed".to_owned(),
7898                    details: None,
7899                    retryable: false,
7900                });
7901            }
7902            if self.active_round.is_some() || self.fence_round.is_some() {
7903                return Err(ClientError {
7904                    code: "client.round_in_progress".to_owned(),
7905                    message: "a sync round is already in flight".to_owned(),
7906                    details: None,
7907                    retryable: false,
7908                });
7909            }
7910            if self.realtime_policy == RealtimePolicy::Required
7911                && self.realtime_state != RealtimeState::Connected
7912            {
7913                return Err(ClientError {
7914                    code: REALTIME_UNAVAILABLE_CODE.to_owned(),
7915                    message: "the realtime socket is not connected".to_owned(),
7916                    details: None,
7917                    retryable: true,
7918                });
7919            }
7920            let header = Frame::ReqHeader {
7921                client_id: self.client_id.clone(),
7922                schema_version: self.schema.version,
7923                log_epoch: self.get_meta(LOG_EPOCH_KEY)?,
7924                outbox_id: self.get_meta(OUTBOX_ID_KEY)?,
7925            };
7926            let id = uuid::Uuid::new_v4();
7927            self.fence_round = Some(id);
7928            Ok(Some(PreparedFenceRound {
7929                id,
7930                client_commit_id: client_commit_id.to_owned(),
7931                replacement_client_commit_id: replacement_client_commit_id.to_owned(),
7932                operations,
7933                request: encode_message(&Message {
7934                    wire_version: WIRE_VERSION,
7935                    msg_kind: MsgKind::Request,
7936                    frames: vec![
7937                        header,
7938                        Frame::FenceCommit {
7939                            client_commit_id: client_commit_id.to_owned(),
7940                        },
7941                    ],
7942                }),
7943                realtime: self.realtime_state == RealtimeState::Connected,
7944            }))
7945        })();
7946        self.finish_authoring(prior, outcome)
7947    }
7948
7949    /// Apply the reply of a [`PreparedFenceRound`] on the owner (§6.12,
7950    /// §7.2.3) and return the replacement's id. No network I/O. A stored
7951    /// result settles the original through the push-result path and fails
7952    /// with `client.commit_settled`.
7953    pub fn apply_fence_round(
7954        &mut self,
7955        prepared: PreparedFenceRound,
7956        reply: Result<Vec<u8>, TransportError>,
7957    ) -> Result<String, ClientError> {
7958        if self.fence_round != Some(prepared.id) {
7959            return Err(ClientError {
7960                code: "client.round_cancelled".to_owned(),
7961                message: "fence round belongs to a released client context".to_owned(),
7962                details: None,
7963                retryable: false,
7964            });
7965        }
7966        self.fence_round = None;
7967        let prior = self.storage_failure.borrow_mut().take();
7968        let outcome = (|| -> Result<String, ClientError> {
7969            let id = prepared.client_commit_id.as_str();
7970            let invalid = || ClientError {
7971                code: "client.invalid_host_response".to_owned(),
7972                message: "the fence response does not answer the fenced commit".to_owned(),
7973                details: Some(json!({ "clientCommitId": id })),
7974                retryable: false,
7975            };
7976            let bytes = reply.map_err(|error| ClientError {
7977                retryable: error
7978                    .details
7979                    .as_ref()
7980                    .and_then(|details| details.get("retryable"))
7981                    == Some(&Value::Bool(true)),
7982                code: error.code,
7983                message: error.message,
7984                details: error.details,
7985            })?;
7986            let response = decode_message(&bytes).map_err(|_| invalid())?;
7987            if response.msg_kind != MsgKind::Response {
7988                return Err(invalid());
7989            }
7990            let mut frames = response
7991                .frames
7992                .into_iter()
7993                .filter(|frame| !matches!(frame, Frame::Keepalive));
7994            match frames.next() {
7995                // §1.6: a schema-floor response; the client stops syncing as
7996                // a sync round's floor stops it.
7997                Some(Frame::RespHeader {
7998                    required_schema_version: Some(required),
7999                    latest_schema_version,
8000                    ..
8001                }) => {
8002                    self.set_schema_floor(Some(SchemaFloor {
8003                        required_schema_version: Some(required),
8004                        latest_schema_version,
8005                    }))?;
8006                    return Err(ClientError {
8007                        code: "sync.schema_mismatch".to_owned(),
8008                        message: "the server requires a newer schema version".to_owned(),
8009                        details: Some(json!({ "requiredSchemaVersion": required })),
8010                        retryable: false,
8011                    });
8012                }
8013                Some(Frame::RespHeader {
8014                    reset_required: false,
8015                    ..
8016                }) => {}
8017                _ => return Err(invalid()),
8018            }
8019            let answer = frames.next();
8020            let rest: Vec<Frame> = frames.collect();
8021            match answer {
8022                // A server that predates the frame refuses the request.
8023                Some(Frame::Error {
8024                    code,
8025                    message,
8026                    retryable,
8027                    details,
8028                    ..
8029                }) => Err(ClientError {
8030                    code,
8031                    message,
8032                    details: details.and_then(|details| serde_json::from_str(&details.0).ok()),
8033                    retryable,
8034                }),
8035                Some(Frame::CommitFenced { client_commit_id })
8036                    if client_commit_id == id && rest.is_empty() =>
8037                {
8038                    self.replace_outbox_commit(
8039                        id,
8040                        prepared.operations,
8041                        &prepared.replacement_client_commit_id,
8042                    )?;
8043                    Ok(prepared.replacement_client_commit_id)
8044                }
8045                Some(Frame::PushResult {
8046                    client_commit_id,
8047                    status,
8048                    commit_seq,
8049                    results,
8050                }) if client_commit_id == id => {
8051                    let mut details = HashMap::new();
8052                    match rest.as_slice() {
8053                        [] => {}
8054                        [Frame::PushResultDetails {
8055                            client_commit_id: owner,
8056                            entries,
8057                        }] if owner == id => {
8058                            let parsed = entries
8059                                .iter()
8060                                .map(|entry| -> Result<_, String> {
8061                                    Ok((entry.op_index, RejectionDetails::parse(&entry.details.0)?))
8062                                })
8063                                .collect::<Result<BTreeMap<i32, RejectionDetails>, String>>()
8064                                .map_err(|_| invalid())?;
8065                            details.insert(id.to_owned(), parsed);
8066                        }
8067                        _ => return Err(invalid()),
8068                    }
8069                    let settled = if status == PushStatus::Rejected {
8070                        "rejected"
8071                    } else {
8072                        "applied"
8073                    };
8074                    let mut report = SyncReport::default();
8075                    self.handle_push_results(
8076                        &[Frame::PushResult {
8077                            client_commit_id,
8078                            status,
8079                            commit_seq,
8080                            results,
8081                        }],
8082                        &HashSet::from([id]),
8083                        &details,
8084                        &mut report,
8085                        Some(id),
8086                    )
8087                    .map_err(|_| ClientError {
8088                        code: "client.outcome_persistence_failed".to_owned(),
8089                        message: "local commit outcome could not be persisted".to_owned(),
8090                        details: None,
8091                        retryable: false,
8092                    })?;
8093                    // §6.3: a serving failure is no outcome; the commit stays.
8094                    if !report.retryable.is_empty() {
8095                        return Err(ClientError {
8096                            code: "sync.idempotency_cache_miss".to_owned(),
8097                            message: "the server could not serve the stored result".to_owned(),
8098                            details: Some(json!({ "clientCommitId": id })),
8099                            retryable: true,
8100                        });
8101                    }
8102                    Err(ClientError {
8103                        code: "client.commit_settled".to_owned(),
8104                        message: "the commit already has a server outcome".to_owned(),
8105                        details: Some(json!({ "clientCommitId": id, "status": settled })),
8106                        retryable: false,
8107                    })
8108                }
8109                _ => Err(invalid()),
8110            }
8111        })();
8112        self.finish_authoring(prior, outcome)
8113    }
8114
8115    /// §7.2.3: swap a pending commit's operations and id in place (same
8116    /// outbox sequence), re-derive the overlay of its rows and every later
8117    /// commit, and journal the original as `replaced`, in one transaction
8118    /// with one change batch.
8119    fn replace_outbox_commit(
8120        &mut self,
8121        client_commit_id: &str,
8122        ops: Vec<OutboxOp>,
8123        replacement: &str,
8124    ) -> Result<(), ClientError> {
8125        let Some(index) = self
8126            .outbox
8127            .iter()
8128            .position(|commit| commit.client_commit_id == client_commit_id)
8129        else {
8130            return Err(ClientError {
8131                code: "sync.outcome_not_found".to_owned(),
8132                message: "no pending commit exists for the id".to_owned(),
8133                details: Some(json!({ "clientCommitId": client_commit_id })),
8134                retryable: false,
8135            });
8136        };
8137        let original = self.outbox[index].clone();
8138        let commit = OutboxCommit {
8139            client_commit_id: replacement.to_owned(),
8140            ops,
8141        };
8142        let rollback = self.capture();
8143        self.begin_observation("syncular_pending_replacement")?;
8144        let mut batch = ChangeAccumulator::default();
8145        let replaced = (|| {
8146            let (seq, created_at_ms): (i64, i64) = self
8147                .conn
8148                .query_row(
8149                    "SELECT seq, created_at_ms FROM _syncular_outbox WHERE commit_id = ?1",
8150                    [client_commit_id],
8151                    |row| Ok((row.get(0)?, row.get(1)?)),
8152                )
8153                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8154            self.persist_outbox_insert(&commit)?;
8155            self.leave_through(client_commit_id);
8156            self.delete_outbox_persisted(client_commit_id)?;
8157            // §7.2.1: journaled as a purge journals its drops, decided.
8158            let results = (0..original.ops.len())
8159                .map(|op_index| CommitOperationOutcome::Error {
8160                    rejection: RejectionRecord {
8161                        client_commit_id: client_commit_id.to_owned(),
8162                        op_index: op_index as i32,
8163                        code: COMMIT_REPLACED_CODE.to_owned(),
8164                        message: "the commit was replaced before the server applied it".to_owned(),
8165                        retryable: false,
8166                        details: None,
8167                        operation: None,
8168                    },
8169                })
8170                .collect::<Vec<_>>();
8171            let results_json =
8172                serde_json::to_string(&results).map_err(|error| error.to_string())?;
8173            self.conn
8174                .execute(
8175                    "UPDATE _syncular_outbox SET seq = ?1, created_at_ms = ?2 WHERE commit_id = ?3",
8176                    rusqlite::params![seq, created_at_ms, replacement],
8177                )
8178                .and_then(|_| {
8179                    self.conn.execute(
8180                        "INSERT INTO _syncular_commit_outcomes (
8181                           client_commit_id, status, recorded_at_ms, results_json, resolution,
8182                           resolved_at_ms, replacement_client_commit_id
8183                         ) VALUES (?1, 'rejected', ?2, ?3, 'superseded', ?2, ?4)",
8184                        rusqlite::params![
8185                            client_commit_id,
8186                            self.clock_now_ms(),
8187                            results_json,
8188                            replacement
8189                        ],
8190                    )
8191                })
8192                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8193            self.prune_commit_outcomes()?;
8194            for op in original.ops.iter().chain(&commit.ops) {
8195                self.overlay_dirty.table(&op.table);
8196                batch.table(&op.table);
8197            }
8198            self.outbox[index] = Arc::new(commit);
8199            batch.status = true;
8200            batch.outcomes = true;
8201            self.rebuild_overlay_if_dirty()?;
8202            self.finish_observation("syncular_pending_replacement", batch)
8203        })();
8204        if let Err(error) = replaced {
8205            self.rollback_observation("syncular_pending_replacement");
8206            self.restore(rollback);
8207            return Err(error.into());
8208        }
8209        Ok(())
8210    }
8211
8212    /// Internal host step at the start of an idle drive (§7.2.2): capture
8213    /// every pending decision with the units and epochs of this drive.
8214    #[doc(hidden)]
8215    pub fn prepare_replacements(&self) -> Result<Vec<CurrentBasePreparation>, String> {
8216        let mut stmt = self
8217            .conn
8218            .prepare_cached(
8219                "SELECT client_commit_id, seq, replacement_client_commit_id
8220                   FROM _syncular_commit_outcomes
8221                  WHERE resolution = 'active' AND replacement_client_commit_id IS NOT NULL
8222                  ORDER BY seq ASC",
8223            )
8224            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8225        let decisions = stmt
8226            .query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
8227            .and_then(|rows| rows.collect::<Result<Vec<(String, i64, String)>, _>>())
8228            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8229        if decisions.is_empty() {
8230            return Ok(Vec::new());
8231        }
8232        let units = self.stored(load_units(&self.conn))?;
8233        Ok(decisions
8234            .into_iter()
8235            .map(
8236                |(client_commit_id, sequence, replacement)| CurrentBasePreparation {
8237                    client_commit_id,
8238                    sequence,
8239                    replacement: Some(replacement),
8240                    units: units.clone(),
8241                    transport_epoch: self.transport_epoch,
8242                    registration_epoch: self.registration_epoch,
8243                    security_epoch: self.security_epoch,
8244                },
8245            )
8246            .collect())
8247    }
8248
8249    /// Internal host step when an idle drive reaches idle (§7.2.2): write,
8250    /// refuse, or keep each decision captured at the drive's start. Returns
8251    /// whether a decision was written, so the drive runs another round.
8252    #[doc(hidden)]
8253    pub fn settle_replacements(
8254        &mut self,
8255        decisions: &[CurrentBasePreparation],
8256        drive: &SyncOutcome,
8257    ) -> Result<bool, String> {
8258        if self.transport_closed() {
8259            return Ok(false);
8260        }
8261        let mut written = false;
8262        for decision in decisions {
8263            // A registration change during the drive says nothing about the
8264            // base; the decision waits for the next drive.
8265            if decision.registration_epoch != self.registration_epoch {
8266                continue;
8267            }
8268            let Some(replacement) = decision.replacement.as_deref() else {
8269                continue;
8270            };
8271            let Some(current) =
8272                self.commit_outcome(&decision.client_commit_id)?
8273                    .filter(|current| {
8274                        current.resolution == CommitOutcomeResolution::Active
8275                            && current.replacement_client_commit_id.as_deref() == Some(replacement)
8276                    })
8277            else {
8278                continue;
8279            };
8280            let held = self
8281                .outbox
8282                .iter()
8283                .find(|commit| commit.client_commit_id == replacement)
8284                .cloned();
8285            let refused = match &held {
8286                // A revocation drop (§3.3) or a crash already ended the
8287                // replacement; its own journal entry records what happened.
8288                None => None,
8289                Some(commit) => match self.finish_current_base(decision.clone(), drive.clone()) {
8290                    CurrentBaseProof {
8291                        rows: Some(rows), ..
8292                    } => {
8293                        let proven = commit.ops.iter().all(|op| {
8294                            rows.iter()
8295                                .find(|row| row.table == op.table && row.row_id == op.row_id)
8296                                .is_none_or(|row| {
8297                                    op.base_version == Some(row.server_version.unwrap_or(0))
8298                                })
8299                        });
8300                        written |= proven;
8301                        (!proven).then(|| "base_moved".to_owned())
8302                    }
8303                    CurrentBaseProof {
8304                        reason:
8305                            Some(
8306                                reason @ (CurrentBaseProofReason::SchemaFloor
8307                                | CurrentBaseProofReason::MissingCoverage
8308                                | CurrentBaseProofReason::Revoked
8309                                | CurrentBaseProofReason::OutcomeUnavailable),
8310                            ),
8311                        ..
8312                    } => Some(
8313                        serde_json::to_value(reason)
8314                            .ok()
8315                            .and_then(|reason| reason.as_str().map(str::to_owned))
8316                            .ok_or("sync.local_corrupt")?,
8317                    ),
8318                    _ => continue,
8319                },
8320            };
8321            // One transaction: the original outcome is superseded first, so
8322            // the refused replacement retains its intent over the restored
8323            // server base.
8324            let rollback = self.capture();
8325            self.begin_observation("syncular_replacement")?;
8326            let mut batch = ChangeAccumulator::default();
8327            let result = self
8328                .release_outcome(
8329                    &current,
8330                    CommitOutcomeResolution::Superseded,
8331                    Some(replacement),
8332                    &mut batch,
8333                )
8334                .and_then(|()| self.rebuild_overlay_if_dirty())
8335                .and_then(|()| match (refused, held) {
8336                    (Some(reason), Some(commit)) => self.reject_outbox_commits(
8337                        vec![(
8338                            commit,
8339                            "the replacement could not be written on a proven base".to_owned(),
8340                            REPLACEMENT_REFUSED_CODE,
8341                            Some(RejectionDetails {
8342                                field_paths: None,
8343                                reason: Some(reason),
8344                                required_action: None,
8345                                references: None,
8346                            }),
8347                        )],
8348                        Some(&mut batch),
8349                    ),
8350                    _ => Ok(()),
8351                })
8352                .and_then(|()| self.finish_observation("syncular_replacement", batch));
8353            if let Err(error) = result {
8354                self.rollback_observation("syncular_replacement");
8355                self.restore(rollback);
8356                return Err(error);
8357            }
8358        }
8359        if written {
8360            self.set_sync_needed(true, true);
8361        }
8362        Ok(written)
8363    }
8364
8365    /// §7.2.1 explicit resolution inside the caller's observation: record the
8366    /// resolution, release the retained aggregate and mark its tables for the
8367    /// overlay rebuild, which restores the server base and replays what
8368    /// remains over it.
8369    fn release_outcome(
8370        &mut self,
8371        current: &CommitOutcome,
8372        resolution: CommitOutcomeResolution,
8373        replacement: Option<&str>,
8374        batch: &mut ChangeAccumulator,
8375    ) -> Result<(), String> {
8376        self.conn
8377            .execute(
8378                "UPDATE _syncular_commit_outcomes
8379                    SET resolution = ?1, resolved_at_ms = ?2,
8380                        replacement_client_commit_id = ?3
8381                  WHERE client_commit_id = ?4 AND resolution = 'active'",
8382                rusqlite::params![
8383                    Self::outcome_resolution_name(resolution),
8384                    self.clock_now_ms(),
8385                    replacement,
8386                    current.client_commit_id
8387                ],
8388            )
8389            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8390        self.conn
8391            .execute(
8392                "DELETE FROM _syncular_failed_commits WHERE client_commit_id = ?1",
8393                rusqlite::params![current.client_commit_id],
8394            )
8395            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8396        for (commit, _) in self.failed_commits.iter() {
8397            if commit.client_commit_id == current.client_commit_id {
8398                for operation in &commit.ops {
8399                    self.overlay_dirty.table(&operation.table);
8400                }
8401            }
8402        }
8403        self.failed_commits
8404            .retain(|(commit, _)| commit.client_commit_id != current.client_commit_id);
8405        self.prune_commit_outcomes()?;
8406        self.conflicts
8407            .retain(|record| record.client_commit_id != current.client_commit_id);
8408        self.rejections
8409            .retain(|record| record.client_commit_id != current.client_commit_id);
8410        batch.conflicts |= current.status == CommitOutcomeStatus::Conflict;
8411        batch.rejections |= current.status == CommitOutcomeStatus::Rejected;
8412        batch.outcomes = true;
8413        for operation in current.operations.iter().flatten() {
8414            batch.table(&operation.table);
8415        }
8416        Ok(())
8417    }
8418
8419    pub fn schema_floor(&self) -> Option<&SchemaFloor> {
8420        self.schema_floor.as_ref()
8421    }
8422
8423    /// §7.3.5: the client's opaque auth-lease state, if any.
8424    pub fn lease_state(&self) -> Option<&LeaseState> {
8425        self.lease_state.as_ref()
8426    }
8427
8428    /// §7.3.5: record a request-level lease error (stop-and-surface). Only
8429    /// the two lease codes set it; other errors leave leaseState untouched.
8430    fn record_lease_error(&mut self, code: &str) -> Result<(), String> {
8431        if code != "sync.auth_lease_required" && code != "sync.auth_lease_revoked" {
8432            return Ok(());
8433        }
8434        let mut next = self.lease_state.clone().unwrap_or_default();
8435        next.error_code = Some(code.to_owned());
8436        self.set_lease_state(Some(next))
8437    }
8438
8439    fn set_lease_state(&mut self, next: Option<LeaseState>) -> Result<(), String> {
8440        if self.lease_state == next {
8441            return Ok(());
8442        }
8443        self.begin_observation("syncular_lease")?;
8444        let rollback = self.capture();
8445        self.lease_state = next;
8446        let persisted = match &self.lease_state {
8447            Some(lease) => serde_json::to_string(lease)
8448                .map_err(|error| error.to_string())
8449                .and_then(|json| self.set_meta(LEASE_STATE_KEY, &json)),
8450            None => self.delete_meta(LEASE_STATE_KEY),
8451        };
8452        let batch = ChangeAccumulator {
8453            status: true,
8454            ..ChangeAccumulator::default()
8455        };
8456        if let Err(error) =
8457            persisted.and_then(|()| self.finish_observation("syncular_lease", batch))
8458        {
8459            self.rollback_observation("syncular_lease");
8460            self.restore(rollback);
8461            return Err(error);
8462        }
8463        Ok(())
8464    }
8465
8466    fn set_schema_floor(&mut self, next: Option<SchemaFloor>) -> Result<(), String> {
8467        if self.schema_floor == next {
8468            return Ok(());
8469        }
8470        self.begin_observation("syncular_schema_floor")?;
8471        let rollback = self.capture();
8472        self.stopped = next.is_some();
8473        self.schema_floor = next;
8474        let persisted = match &self.schema_floor {
8475            Some(floor) => serde_json::to_string(floor)
8476                .map_err(|error| error.to_string())
8477                .and_then(|json| self.set_meta(SCHEMA_FLOOR_KEY, &json)),
8478            None => self.delete_meta(SCHEMA_FLOOR_KEY),
8479        };
8480        let batch = ChangeAccumulator {
8481            status: true,
8482            ..ChangeAccumulator::default()
8483        };
8484        if let Err(error) =
8485            persisted.and_then(|()| self.finish_observation("syncular_schema_floor", batch))
8486        {
8487            self.rollback_observation("syncular_schema_floor");
8488            self.restore(rollback);
8489            return Err(error);
8490        }
8491        Ok(())
8492    }
8493
8494    fn set_upgrading(&mut self, value: bool) {
8495        if self.upgrading == value {
8496            return;
8497        }
8498        if self.begin_observation("syncular_upgrading").is_err() {
8499            return;
8500        }
8501        self.upgrading = value;
8502        self.upgrade_kept_tables &= value;
8503        let batch = ChangeAccumulator {
8504            status: true,
8505            ..ChangeAccumulator::default()
8506        };
8507        if self
8508            .finish_observation("syncular_upgrading", batch)
8509            .is_err()
8510        {
8511            self.rollback_observation("syncular_upgrading");
8512        }
8513    }
8514
8515    pub fn sync_needed(&self) -> bool {
8516        self.sync_needed
8517    }
8518
8519    pub fn read_rows(&self, table: &str) -> Result<Vec<RowState>, String> {
8520        let schema_table = self
8521            .schema
8522            .table(table)
8523            .ok_or_else(|| format!("unknown table {table:?}"))?;
8524        let sql = format!(
8525            "SELECT * FROM {} ORDER BY {} ASC",
8526            visible_table(table),
8527            quote_ident(&schema_table.primary_key)
8528        );
8529        let mut stmt = self
8530            .conn
8531            .prepare(&sql)
8532            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8533        let mut rows = stmt
8534            .query([])
8535            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8536        let mut out = Vec::new();
8537        while let Some(row) = rows
8538            .next()
8539            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
8540        {
8541            let mut values = Map::new();
8542            for (i, column) in schema_table.columns.iter().enumerate() {
8543                let value = row
8544                    .get_ref(i)
8545                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8546                values.insert(column.name.clone(), sql_ref_to_json(column, value));
8547            }
8548            let version: i64 = row
8549                .get(schema_table.columns.len())
8550                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8551            let row_id = match values.get(&schema_table.primary_key) {
8552                Some(Value::String(s)) => s.clone(),
8553                Some(Value::Number(n)) => n.to_string(),
8554                Some(Value::Bool(b)) => b.to_string(),
8555                other => format!("{}", other.cloned().unwrap_or(Value::Null)),
8556            };
8557            let sealed_key = if schema_table.has_encrypted_columns() {
8558                row.get(schema_table.columns.len() + 1)
8559                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
8560            } else {
8561                None
8562            };
8563            out.push(RowState {
8564                row_id,
8565                version,
8566                values,
8567                sealed_key,
8568            });
8569        }
8570        Ok(out)
8571    }
8572
8573    // -- §5.10.5 native CRDT (the `crdt-yjs` feature) --------------------------
8574    //
8575    // The Rust face of the §5.10.4 client model: a local crdt edit loads the
8576    // current stored (server-merged ⊕ pending-overlay) column bytes, applies
8577    // the op with `yrs`, re-encodes the whole doc state, and records a
8578    // baseVersion-less sparse upsert carrying only the primary key and the
8579    // crdt column (§5.10.3, §6.6). No local merge — merging is server-side;
8580    // the overlay re-materializes the edit immediately (optimistic apply,
8581    // §7.1) and the server-merged bytes arrive on the next pull, idempotently.
8582    // Byte-compatible with `@syncular/crdt-yjs`.
8583
8584    /// The current stored value of a `crdt` column for one row — the visible
8585    /// (optimistic) bytes, or `None` when the row is absent or the column is
8586    /// NULL (the empty document, §5.10.1). Errors if the column is not a
8587    /// `crdt` column (guards the app against a typo'd column name).
8588    #[cfg(feature = "crdt-yjs")]
8589    fn crdt_column_bytes(
8590        &self,
8591        table: &str,
8592        row_id: &str,
8593        column: &str,
8594    ) -> Result<Option<Vec<u8>>, String> {
8595        let schema_table = self
8596            .schema
8597            .table(table)
8598            .ok_or_else(|| format!("unknown table {table:?}"))?;
8599        let col = schema_table
8600            .columns
8601            .iter()
8602            .find(|c| c.name == column)
8603            .ok_or_else(|| format!("table {table:?} has no column {column:?}"))?;
8604        if col.ty != ColumnType::Crdt {
8605            return Err(format!("column {column:?} is not a crdt column (§5.10.1)"));
8606        }
8607        let sql = format!(
8608            "SELECT {} FROM {} WHERE {}",
8609            quote_ident(column),
8610            visible_table(table),
8611            row_id_predicate(schema_table)
8612        );
8613        let bytes: Option<Vec<u8>> = self
8614            .conn
8615            .prepare_cached(&sql)
8616            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
8617            .query_row(rusqlite::params![row_id], |row| {
8618                row.get::<_, Option<Vec<u8>>>(0)
8619            })
8620            .map_err(|e| match e {
8621                rusqlite::Error::QueryReturnedNoRows => "no such row".to_owned(),
8622                other => Self::sqlite_failure(&self.storage_failure, other),
8623            })?;
8624        Ok(bytes)
8625    }
8626
8627    /// §5.10.4 materialize: the collaborative text of a `crdt` column, decoded
8628    /// from the stored bytes with `yrs` — `YjsColumn.text(name).toString()`.
8629    /// An absent row / NULL column is the empty document (empty string).
8630    #[cfg(feature = "crdt-yjs")]
8631    pub fn crdt_text(
8632        &self,
8633        table: &str,
8634        row_id: &str,
8635        column: &str,
8636        name: &str,
8637    ) -> Result<String, String> {
8638        let bytes = self
8639            .crdt_column_bytes(table, row_id, column)?
8640            .unwrap_or_default();
8641        crate::crdt::text(&bytes, name)
8642    }
8643
8644    /// §5.10.4 push-an-update: apply a text insert to a `crdt` column and
8645    /// record the resulting crdt-only sparse operation. Returns the enqueued
8646    /// `clientCommitId`.
8647    #[cfg(feature = "crdt-yjs")]
8648    pub fn crdt_insert_text(
8649        &mut self,
8650        table: &str,
8651        row_id: &str,
8652        column: &str,
8653        name: &str,
8654        index: u32,
8655        value: &str,
8656    ) -> Result<String, ClientError> {
8657        let prior = self.storage_failure.borrow_mut().take();
8658        let outcome = (|| -> Result<String, ClientError> {
8659            let current = self
8660                .crdt_column_bytes(table, row_id, column)?
8661                .unwrap_or_default();
8662            let update = crate::crdt::insert_text(&current, name, index, value)?;
8663            self.perform_crdt_push_update(table, row_id, column, &update)
8664        })();
8665        self.finish_authoring(prior, outcome)
8666    }
8667
8668    /// §5.10.4 push-an-update: apply a text delete to a `crdt` column and
8669    /// record the resulting crdt-only sparse operation. Returns the enqueued
8670    /// `clientCommitId`.
8671    #[cfg(feature = "crdt-yjs")]
8672    pub fn crdt_delete_text(
8673        &mut self,
8674        table: &str,
8675        row_id: &str,
8676        column: &str,
8677        name: &str,
8678        index: u32,
8679        len: u32,
8680    ) -> Result<String, ClientError> {
8681        let prior = self.storage_failure.borrow_mut().take();
8682        let outcome = (|| -> Result<String, ClientError> {
8683            let current = self
8684                .crdt_column_bytes(table, row_id, column)?
8685                .unwrap_or_default();
8686            let update = crate::crdt::delete_text(&current, name, index, len)?;
8687            self.perform_crdt_push_update(table, row_id, column, &update)
8688        })();
8689        self.finish_authoring(prior, outcome)
8690    }
8691
8692    /// §5.10.4 generic escape hatch: apply an arbitrary Yjs update onto a
8693    /// `crdt` column's current state and record the resulting crdt-only sparse
8694    /// operation. The app authored the update with its own `yrs` model.
8695    /// Returns the enqueued `clientCommitId`.
8696    #[cfg(feature = "crdt-yjs")]
8697    pub fn crdt_apply_update(
8698        &mut self,
8699        table: &str,
8700        row_id: &str,
8701        column: &str,
8702        update: &[u8],
8703    ) -> Result<String, ClientError> {
8704        let prior = self.storage_failure.borrow_mut().take();
8705        let outcome = (|| -> Result<String, ClientError> {
8706            let current = self
8707                .crdt_column_bytes(table, row_id, column)?
8708                .unwrap_or_default();
8709            let next = crate::crdt::apply_update(&current, update)?;
8710            self.perform_crdt_push_update(table, row_id, column, &next)
8711        })();
8712        self.finish_authoring(prior, outcome)
8713    }
8714
8715    /// Shared tail of the crdt edit methods: record a §6.1 sparse crdt-only
8716    /// upsert — the primary key plus the crdt column, no `baseVersion` — and
8717    /// enqueue it. The server merges the crdt column and leaves every other
8718    /// column untouched (§5.10.3), so a baseVersion-less crdt edit cannot
8719    /// clobber a concurrent edit to another column. A locally absent row
8720    /// records the same partial operation; the server answers per §6.2.
8721    #[cfg(feature = "crdt-yjs")]
8722    fn perform_crdt_push_update(
8723        &mut self,
8724        table: &str,
8725        row_id: &str,
8726        column: &str,
8727        crdt_bytes: &[u8],
8728    ) -> Result<String, ClientError> {
8729        let mut bytes_obj = Map::new();
8730        bytes_obj.insert("$bytes".to_owned(), Value::from(bytes_to_hex(crdt_bytes)));
8731        let mut partial = Map::new();
8732        partial.insert(column.to_owned(), Value::Object(bytes_obj));
8733        self.perform_patch(table, row_id, partial, None)
8734    }
8735
8736    /// Run an arbitrary read-only SQL query against the local database and
8737    /// return each row as a `column-name → JSON value` map. This is the seam
8738    /// the React `useSyncQuery` live-query API needs (it takes app-authored
8739    /// SQL over the visible tables/views, not a fixed table read like
8740    /// [`read_rows`]).
8741    ///
8742    /// Bound `params` are the driver value forms: JSON strings/numbers/bools/
8743    /// null bind directly; a `{"$bytes": hex}` object binds as a BLOB — the
8744    /// same envelope the command surface uses everywhere else. Output BLOB
8745    /// columns come back as `{"$bytes": hex}` to round-trip cleanly.
8746    ///
8747    /// The result column typing is dynamic (SQLite's stored affinity), because
8748    /// arbitrary SQL can alias, join, and compute — there is no schema column
8749    /// to consult per output cell, unlike [`read_rows`].
8750    pub fn query(&self, sql: &str, params: &[QueryValue]) -> Result<Vec<QueryRow>, String> {
8751        query_connection(&self.conn, sql, params).map_err(|failure| failure.to_string())
8752    }
8753
8754    /// Repository benchmark and conformance access, present only with `bench-internals`.
8755    #[cfg(feature = "bench-internals")]
8756    #[doc(hidden)]
8757    pub fn benchmark_connection(&mut self) -> &mut Connection {
8758        &mut self.conn
8759    }
8760
8761    /// Private benchmark intervals; absent from ordinary builds and diagnostics.
8762    #[cfg(feature = "bench-internals")]
8763    #[doc(hidden)]
8764    pub fn benchmark_phases(
8765        &self,
8766        enabled: Option<bool>,
8767        reset: bool,
8768    ) -> Result<Option<Value>, String> {
8769        self.benchmark_phases.configure(enabled, reset)?;
8770        Ok(self.benchmark_phases.snapshot())
8771    }
8772
8773    /// §5.11 native ceiling: refuse a declared authority query whose authored
8774    /// statement reads a table or column outside `ceiling` (table to permitted
8775    /// columns) or performs an action other than SELECT, READ, or a
8776    /// deterministic core function. The refusal is
8777    /// `client.authority_read_forbidden` with `{ query, reason: "ceiling",
8778    /// table, column }`.
8779    pub fn check_authority_ceiling(
8780        &mut self,
8781        ceiling: &BTreeMap<String, Vec<String>>,
8782    ) -> Result<(), ClientError> {
8783        for query in &self.limits.authority_reads {
8784            for (table, columns) in authority_read_set(&mut self.conn, query)? {
8785                let Some(allowed) = ceiling.get(&table) else {
8786                    return Err(authority_refusal(
8787                        &query.name,
8788                        "ceiling",
8789                        Some(table.as_str()),
8790                        None,
8791                    ));
8792                };
8793                if let Some(column) = columns
8794                    .iter()
8795                    .find(|column| !column.is_empty() && !allowed.contains(column))
8796                {
8797                    return Err(authority_refusal(
8798                        &query.name,
8799                        "ceiling",
8800                        Some(table.as_str()),
8801                        Some(column.as_str()),
8802                    ));
8803                }
8804            }
8805        }
8806        Ok(())
8807    }
8808
8809    /// §5.11: run declared authority queries over the accepted base in one
8810    /// SQLite read transaction. Each request is a query name and its params
8811    /// keyed by param name; each result carries its rows, its coverage per
8812    /// table and unit, whether every entry is complete, and every row of a
8813    /// read table with intent. A query reading an encrypted, `bytes` or
8814    /// `_sync_sealed_key` column fails with
8815    /// `client.security_preflight_required` while a preflight is pending.
8816    pub fn authority_read(
8817        &self,
8818        requests: &[(String, Map<String, Value>)],
8819    ) -> Result<AuthorityReadResult, ClientError> {
8820        if self.limits.authority_reads.is_empty() {
8821            return Err(authority_forbidden(None));
8822        }
8823        // Every request resolves and types its params before the read opens.
8824        let mut prepared = Vec::with_capacity(requests.len());
8825        for (name, params) in requests {
8826            let query = self
8827                .limits
8828                .authority_reads
8829                .iter()
8830                .find(|query| &query.name == name)
8831                .ok_or_else(|| ClientError {
8832                    code: "client.authority_query_unknown".to_owned(),
8833                    message: "authority query is not declared".to_owned(),
8834                    details: Some(json!({ "query": name })),
8835                    retryable: false,
8836                })?;
8837            let invalid = |param: &str| ClientError {
8838                code: "sync.invalid_request".to_owned(),
8839                message: "authority query parameter is missing, extra or mistyped".to_owned(),
8840                details: Some(json!({ "query": name, "param": param })),
8841                retryable: false,
8842            };
8843            if let Some(extra) = params
8844                .keys()
8845                .find(|key| !query.params.iter().any(|param| &param.name == *key))
8846            {
8847                return Err(invalid(extra.as_str()));
8848            }
8849            let mut bound = BTreeMap::new();
8850            for param in &query.params {
8851                let value = params
8852                    .get(&param.name)
8853                    .ok_or_else(|| invalid(param.name.as_str()))?;
8854                let sql = match (param.ty.as_str(), value) {
8855                    (_, Value::Null) if param.nullable => Value::Null,
8856                    ("string", Value::String(_)) | ("float", Value::Number(_)) => value.clone(),
8857                    ("integer", Value::Number(number))
8858                        if number
8859                            .as_i64()
8860                            .is_some_and(|n| n.unsigned_abs() <= MAX_JS_SAFE_INTEGER) =>
8861                    {
8862                        value.clone()
8863                    }
8864                    ("boolean", Value::Bool(flag)) => Value::from(i64::from(*flag)),
8865                    ("json", Value::String(text))
8866                        if serde_json::from_str::<Value>(text).is_ok() =>
8867                    {
8868                        value.clone()
8869                    }
8870                    _ => return Err(invalid(param.name.as_str())),
8871                };
8872                bound.insert(param.name.as_str(), sql);
8873            }
8874            // A coverage param names a unit value: a string or an integer.
8875            let scalar = |param: &str| match params.get(param) {
8876                Some(Value::String(text)) => Ok(text.clone()),
8877                Some(Value::Number(number))
8878                    if number
8879                        .as_i64()
8880                        .is_some_and(|n| n.unsigned_abs() <= MAX_JS_SAFE_INTEGER) =>
8881                {
8882                    Ok(number.to_string())
8883                }
8884                _ => Err(invalid(param)),
8885            };
8886            let mut coverage = Vec::new();
8887            for entry in &query.coverage {
8888                let base = WindowBase {
8889                    variable: entry.variable.clone(),
8890                    fixed_scopes: entry
8891                        .fixed_scopes
8892                        .iter()
8893                        .map(
8894                            |(variable, param)| -> Result<(String, String), ClientError> {
8895                                Ok((variable.clone(), scalar(param.as_str())?))
8896                            },
8897                        )
8898                        .collect::<Result<UnitScopes, ClientError>>()?,
8899                };
8900                for unit in &entry.units {
8901                    coverage.push((entry.table.as_str(), base.clone(), scalar(unit.as_str())?));
8902                }
8903            }
8904            prepared.push((query, bound, coverage));
8905        }
8906        self.conn
8907            .execute_batch("SAVEPOINT syncular_authority_read")
8908            .map_err(authority_stored)?;
8909        let result = (|| -> Result<AuthorityReadResult, ClientError> {
8910            let revision = meta_get(&self.conn, LOCAL_REVISION_KEY)
8911                .map_err(authority_stored)?
8912                .filter(|revision| {
8913                    revision
8914                        .parse::<u64>()
8915                        .is_ok_and(|parsed| &parsed.to_string() == revision)
8916                })
8917                .ok_or_else(authority_corrupt)?;
8918            if self.security_preflight {
8919                let protected = |(name, columns): (&String, &Vec<String>)| {
8920                    let table = self.schema.table(name).expect("validated authority table");
8921                    columns.iter().any(|column| {
8922                        column == "_sync_sealed_key"
8923                            || table.columns.iter().enumerate().any(|(index, held)| {
8924                                &held.name == column
8925                                    && (held.ty == ColumnType::Bytes
8926                                        || table.encrypted_columns.iter().any(|e| e.index == index))
8927                            })
8928                    })
8929                };
8930                if let Some((query, ..)) = prepared
8931                    .iter()
8932                    .find(|(query, ..)| query.reads.iter().any(protected))
8933                {
8934                    return Err(ClientError {
8935                        code: SECURITY_PREFLIGHT_REQUIRED_CODE.to_owned(),
8936                        message: "protected authority reads require activateSecurity".to_owned(),
8937                        details: Some(json!({ "query": query.name })),
8938                        retryable: false,
8939                    });
8940                }
8941            }
8942            let units = load_units(&self.conn).map_err(authority_stored)?;
8943            let mut results = Vec::with_capacity(prepared.len());
8944            for (query, bound, coverage) in &prepared {
8945                let (sql, mut params, intent) = self.authority_statement(query)?;
8946                params.extend(query.bind.iter().map(|name| bound[name.as_str()].clone()));
8947                let rows =
8948                    query_connection(&self.conn, &sql, &params).map_err(ClientError::from)?;
8949                let coverage = coverage
8950                    .iter()
8951                    .map(|(table, base, unit)| {
8952                        let mut json_base = json!({ "variable": base.variable });
8953                        if !base.fixed_scopes.is_empty() {
8954                            json_base["fixedScopes"] = json!(base.fixed_scopes);
8955                        }
8956                        AuthorityCoverageState {
8957                            table: (*table).to_owned(),
8958                            base: json_base,
8959                            unit: unit.clone(),
8960                            state: entry_coverage(
8961                                &units,
8962                                table,
8963                                self.schema.table(table),
8964                                base,
8965                                unit,
8966                            )
8967                            .0,
8968                        }
8969                    })
8970                    .collect::<Vec<_>>();
8971                results.push(AuthorityQueryResult {
8972                    query: query.name.clone(),
8973                    rows,
8974                    complete: coverage.iter().all(|entry| entry.state == "complete"),
8975                    coverage,
8976                    intent,
8977                });
8978            }
8979            Ok(AuthorityReadResult { revision, results })
8980        })();
8981        match result {
8982            Ok(read) => {
8983                self.conn
8984                    .execute_batch("RELEASE syncular_authority_read")
8985                    .map_err(authority_stored)?;
8986                Ok(read)
8987            }
8988            Err(error) => {
8989                self.conn
8990                    .execute_batch(
8991                        "ROLLBACK TO syncular_authority_read; RELEASE syncular_authority_read",
8992                    )
8993                    .map_err(authority_stored)?;
8994                Err(error)
8995            }
8996        }
8997    }
8998
8999    /// §5.11: the statement `authority_read` runs for `query`, its shadow
9000    /// params, which precede the authored binds, and the intent rows of its
9001    /// read tables, sorted by table and row id. Every read table with
9002    /// intent reads its accepted base through a common table expression of
9003    /// the same name; the text is identical in the TypeScript core. The Rust
9004    /// mirror keeps the accepted base in `_syncular_base_<table>`: retained,
9005    /// acknowledged and pending intent replay only onto the visible table, so
9006    /// the base row of an intent id is the earliest accepted state.
9007    fn authority_statement(
9008        &self,
9009        query: &AuthorityQuery,
9010    ) -> Result<(String, Vec<Value>, Vec<AuthorityIntent>), ClientError> {
9011        let mut shadows = Vec::new();
9012        let mut params = Vec::new();
9013        let mut intent = Vec::new();
9014        for (name, reads) in &query.reads {
9015            let table = self.schema.table(name).expect("validated authority table");
9016            // One kind per row by the base precedence: a retained entry, then
9017            // an acknowledged one, then pending outbox intent.
9018            let mut ids = Vec::new();
9019            let mut statement = self
9020                .conn
9021                .prepare_cached(
9022                    "SELECT id,min(k) FROM (\
9023                     SELECT json_extract(value,'$.table') AS tbl,json_extract(value,'$.rowId') AS id,2 AS k \
9024                     FROM _syncular_outbox,json_each(ops_json) \
9025                     UNION ALL SELECT json_extract(value,'$.table'),json_extract(value,'$.rowId'),0 \
9026                     FROM _syncular_failed_commits,json_each(operations_json) \
9027                     UNION ALL SELECT tbl,id,1 FROM _syncular_acked_rows) WHERE tbl=?1 GROUP BY id",
9028                )
9029                .map_err(authority_stored)?;
9030            let mut rows = statement.query([name]).map_err(authority_stored)?;
9031            while let Some(row) = rows.next().map_err(authority_stored)? {
9032                ids.push((
9033                    row.get::<_, String>(0).map_err(authority_stored)?,
9034                    row.get::<_, usize>(1).map_err(authority_stored)?,
9035                ));
9036            }
9037            if ids.is_empty() {
9038                continue;
9039            }
9040            ids.sort_by(|a, b| a.0.encode_utf16().cmp(b.0.encode_utf16()));
9041            intent.extend(ids.iter().map(|(row_id, kind)| AuthorityIntent {
9042                table: name.clone(),
9043                row_id: row_id.clone(),
9044                kind: ["retained", "acknowledged", "pending"][*kind],
9045            }));
9046            let ids: Vec<String> = ids.into_iter().map(|(id, _)| id).collect();
9047            let columns: Vec<&str> =
9048                std::iter::once(table.primary_key.as_str())
9049                    .chain(reads.iter().map(String::as_str).filter(|column| {
9050                        *column != table.primary_key && *column != "_sync_version"
9051                    }))
9052                    .chain(std::iter::once("_sync_version"))
9053                    .collect();
9054            let physical = columns
9055                .iter()
9056                .map(|column| {
9057                    if *column == "_sync_version" {
9058                        "_syncular_version".to_owned()
9059                    } else {
9060                        quote_ident(column)
9061                    }
9062                })
9063                .collect::<Vec<_>>()
9064                .join(",");
9065            let key = quote_ident(&table.primary_key);
9066            let mut statement = self
9067                .conn
9068                .prepare(&format!(
9069                    "SELECT CAST({key} AS TEXT),{physical} FROM {} \
9070                     WHERE CAST({key} AS TEXT) IN (SELECT value FROM json_each(?1))",
9071                    base_table(name),
9072                ))
9073                .map_err(authority_stored)?;
9074            let mut rows = statement
9075                .query([serde_json::to_string(&ids).expect("intent ids serialize")])
9076                .map_err(authority_stored)?;
9077            let mut bases = Vec::new();
9078            while let Some(row) = rows.next().map_err(authority_stored)? {
9079                let id = row.get::<_, String>(0).map_err(authority_stored)?;
9080                let mut values = Vec::with_capacity(columns.len());
9081                for index in 1..=columns.len() {
9082                    values.push(match row.get_ref(index).map_err(authority_stored)? {
9083                        ValueRef::Null => Value::Null,
9084                        ValueRef::Integer(integer) => Value::from(integer),
9085                        ValueRef::Real(real) => serde_json::Number::from_f64(real)
9086                            .map(Value::Number)
9087                            .ok_or_else(authority_corrupt)?,
9088                        ValueRef::Text(text) => {
9089                            Value::from(std::str::from_utf8(text).map_err(|_| authority_corrupt())?)
9090                        }
9091                        ValueRef::Blob(blob) => json!({ "$bytes": bytes_to_hex(blob) }),
9092                    });
9093                }
9094                let version = values
9095                    .last()
9096                    .and_then(Value::as_i64)
9097                    .ok_or_else(authority_corrupt)?;
9098                if version >= 0 {
9099                    bases.push((id, Value::Array(values)));
9100                }
9101            }
9102            bases.sort_by(|a, b| a.0.encode_utf16().cmp(b.0.encode_utf16()));
9103            let shadow = quote_ident(name);
9104            shadows.push(format!(
9105                "{shadow} AS (SELECT {} FROM main.{shadow} WHERE CAST({key} AS TEXT) NOT IN \
9106                 (SELECT value FROM json_each(?)) UNION ALL SELECT {} FROM json_each(?))",
9107                columns
9108                    .iter()
9109                    .map(|column| quote_ident(column))
9110                    .collect::<Vec<_>>()
9111                    .join(","),
9112                columns
9113                    .iter()
9114                    .enumerate()
9115                    .map(|(index, column)| {
9116                        if table
9117                            .columns
9118                            .iter()
9119                            .any(|held| held.name == *column && held.ty == ColumnType::Bytes)
9120                        {
9121                            format!("unhex(json_extract(value,'$[{index}].\"$bytes\"'))")
9122                        } else {
9123                            format!("json_extract(value,'$[{index}]')")
9124                        }
9125                    })
9126                    .collect::<Vec<_>>()
9127                    .join(","),
9128            ));
9129            params.push(Value::from(
9130                serde_json::to_string(&ids).expect("intent ids serialize"),
9131            ));
9132            params.push(Value::from(
9133                Value::from_iter(bases.into_iter().map(|(_, row)| row)).to_string(),
9134            ));
9135        }
9136        let sql = if shadows.is_empty() {
9137            query.sql.clone()
9138        } else {
9139            let keyword = |text: &str, word: &str| {
9140                text.get(..word.len())
9141                    .is_some_and(|head| head.eq_ignore_ascii_case(word))
9142                    && text[word.len()..].starts_with(char::is_whitespace)
9143            };
9144            let shadows = shadows.join(",");
9145            let authored = query.sql.trim_start();
9146            if keyword(authored, "WITH") {
9147                let rest = authored[4..].trim_start();
9148                if keyword(rest, "RECURSIVE") {
9149                    format!("WITH RECURSIVE {shadows}, {}", rest[9..].trim_start())
9150                } else {
9151                    format!("WITH {shadows}, {rest}")
9152                }
9153            } else {
9154                format!("WITH {shadows} {}", query.sql)
9155            }
9156        };
9157        Ok((sql, params, intent))
9158    }
9159
9160    /// Rows, coverage, and local revision from one SQLite read snapshot.
9161    /// §7.5 atomic snapshot read. An `owner` records a failure in
9162    /// `diagnostics_snapshot().query_failures` until its next successful read.
9163    pub fn query_snapshot(
9164        &mut self,
9165        sql: &str,
9166        params: &[QueryValue],
9167        coverage: &[WindowCoverage],
9168        owner: Option<QueryOwner<'_>>,
9169    ) -> Result<QuerySnapshot, String> {
9170        let result = snapshot_connection(&self.conn, Some(&self.schema), sql, params, coverage);
9171        if let Some(owner) = owner {
9172            self.record_query_read(owner, result.as_ref().err());
9173        }
9174        result.map_err(|failure| failure.to_string())
9175    }
9176
9177    /// §7.6: record the outcome of one owned snapshot read, including reads a
9178    /// host ran on a separate connection. A success removes the owner's entry;
9179    /// an identical failure leaves it unchanged; a changed failure moves last.
9180    pub fn record_query_read(&mut self, owner: QueryOwner<'_>, failure: Option<&QueryReadFailure>) {
9181        let position = self
9182            .query_failures
9183            .iter()
9184            .position(|entry| entry.id == owner.id);
9185        let Some(failure) = failure else {
9186            if let Some(index) = position {
9187                self.query_failures.remove(index);
9188            }
9189            return;
9190        };
9191        let tables: Vec<String> = BTreeSet::from_iter(owner.tables.iter().copied())
9192            .into_iter()
9193            .map(str::to_owned)
9194            .collect();
9195        let code = failure.code.unwrap_or("client.query_failed").to_owned();
9196        if position.is_some_and(|index| {
9197            let entry = &self.query_failures[index];
9198            entry.tables == tables && entry.code == code && entry.sqlite_code == failure.sqlite_code
9199        }) {
9200            return;
9201        }
9202        if let Some(index) = position {
9203            self.query_failures.remove(index);
9204        }
9205        self.query_failures.push(DiagnosticQueryFailure {
9206            id: owner.id.to_owned(),
9207            tables,
9208            code,
9209            sqlite_code: failure.sqlite_code,
9210            at_ms: self.clock_now_ms(),
9211        });
9212        if self.query_failures.len() > MAX_DIAGNOSTIC_QUERY_FAILURES {
9213            self.query_failures.remove(0);
9214        }
9215    }
9216
9217    // -- request building ---------------------------------------------------------
9218
9219    fn build_request(&self, url_capable: bool) -> Result<(Message, RequestMeta), Box<SyncOutcome>> {
9220        #[cfg(feature = "bench-internals")]
9221        let _phase = self.benchmark_phases.start(Phase::RequestPrepare);
9222        let log_epoch = self.get_meta(LOG_EPOCH_KEY).map_err(|message| {
9223            Box::new(SyncOutcome::Failed {
9224                error_code: "storage.failed".into(),
9225                message,
9226                details: None,
9227                recommended_action: None,
9228            })
9229        })?;
9230        let max_commits = self.limits.max_push_commits_per_request;
9231        let max_ops = self
9232            .limits
9233            .max_push_operations_per_request
9234            .unwrap_or(PUSH_OPS_PER_REQUEST);
9235        let byte_cap = self.limits.max_push_request_bytes;
9236        // §4.2/§5.4: bit 3 is advertised iff the transport can fetch a
9237        // bare URL — capability negotiation, decided per transport.
9238        let accept = self.limits.accept.unwrap_or(if url_capable {
9239            DEFAULT_ACCEPT | ACCEPT_SIGNED_URLS
9240        } else {
9241            DEFAULT_ACCEPT
9242        });
9243        let storage_failed = |message: String| {
9244            Box::new(SyncOutcome::Failed {
9245                error_code: "storage.failed".into(),
9246                message,
9247                details: None,
9248                recommended_action: None,
9249            })
9250        };
9251        let header = Frame::ReqHeader {
9252            client_id: self.client_id.clone(),
9253            schema_version: self.schema.version,
9254            log_epoch: log_epoch.clone(),
9255            outbox_id: self.get_meta(OUTBOX_ID_KEY).map_err(storage_failed)?,
9256        };
9257        // §1.5: the lead frames are REQ_HEADER plus the optional ROUND_FAILURE,
9258        // which stays ahead of every push, pull, unit and progress frame; the
9259        // byte-capacity probes below measure this exact sequence.
9260        let mut lead = vec![header];
9261        lead.extend(
9262            self.round_failure
9263                .iter()
9264                .map(|code| Frame::RoundFailure { code: code.clone() }),
9265        );
9266        // §2.1: a replica without an epoch holds nothing bound to one.
9267        if log_epoch.is_none() {
9268            lead.push(Frame::AdoptEpoch);
9269        }
9270        let registered: Vec<UnitRecord> = self
9271            .stored(load_units(&self.conn))
9272            .map_err(storage_failed)?
9273            .into_iter()
9274            .filter(|unit| unit.status == UnitStatus::Active)
9275            .collect();
9276        let registration_digest = ssp2::registration::registration_digest(
9277            registered
9278                .iter()
9279                .map(|unit| scope_pairs(&unit.scopes))
9280                .collect::<Vec<_>>()
9281                .iter()
9282                .map(Vec::as_slice),
9283        );
9284        let echo_digest = self
9285            .get_meta(ECHO_DIGEST_KEY)
9286            .map_err(storage_failed)?
9287            .filter(|hex| !hex.is_empty())
9288            .map(|hex| {
9289                crate::values::hex_to_bytes(&hex)
9290                    .ok()
9291                    .and_then(|bytes| <[u8; 32]>::try_from(bytes).ok())
9292                    .ok_or_else(|| {
9293                        "sync.local_corrupt: persisted echo digest is invalid".to_owned()
9294                    })
9295            })
9296            .transpose()
9297            .map_err(storage_failed)?;
9298        let pull = Frame::PullHeader {
9299            limit_commits: self.limits.limit_commits.unwrap_or(0),
9300            limit_snapshot_rows: self.limits.limit_snapshot_rows.unwrap_or(0),
9301            max_snapshot_pages: self.limits.max_snapshot_pages.unwrap_or(0),
9302            accept,
9303            cursor: self
9304                .stored(replica_cursor(&self.conn))
9305                .map_err(storage_failed)?,
9306            registration_digest,
9307            echo_digest,
9308        };
9309        let registration_digest = bytes_to_hex(&registration_digest);
9310        // §4.1: the list travels when it changed since the server stored it,
9311        // after `unregistered` and after a reset (both clear the stored digest).
9312        let travels = self
9313            .get_meta(REGISTERED_DIGEST_KEY)
9314            .map_err(storage_failed)?
9315            .as_deref()
9316            != Some(registration_digest.as_str());
9317        let mut sub_frames: Vec<Frame> = Vec::new();
9318        if travels {
9319            sub_frames.extend(registered.iter().map(|unit| Frame::Unit {
9320                scopes: scope_pairs(&unit.scopes),
9321            }));
9322        }
9323        // §4.3: one PROGRESS per catching-up unit, in registration order, each
9324        // followed by its RESTRICT while the unit holds a restriction.
9325        for unit in &registered {
9326            let Some(cursor) = unit.cursor else {
9327                continue;
9328            };
9329            sub_frames.push(Frame::Progress {
9330                id: unit.id.clone(),
9331                cursor,
9332                bootstrap_state: unit.bootstrap_state.clone().map(RawJson),
9333            });
9334            sub_frames.extend(
9335                unit.restriction
9336                    .as_ref()
9337                    .map(|restriction| Frame::Restrict {
9338                        cursor: restriction.cursor,
9339                        tables: restriction.tables.clone(),
9340                    }),
9341            );
9342        }
9343        // The fixed frames (order-independent size) and the header+pull probe
9344        // both encode canonically, so the byte budget is the exact wire size.
9345        let fixed_bytes = match byte_cap {
9346            Some(_) => {
9347                let mut frames = lead.clone();
9348                frames.push(pull.clone());
9349                frames.extend(sub_frames.iter().cloned());
9350                encode_message(&Message {
9351                    wire_version: WIRE_VERSION,
9352                    msg_kind: MsgKind::Request,
9353                    frames,
9354                })
9355                .len()
9356            }
9357            None => 0,
9358        };
9359        if let Some(cap) = byte_cap {
9360            if fixed_bytes > cap {
9361                return Err(Self::push_capacity_outcome("bytes", cap, fixed_bytes, None));
9362            }
9363        }
9364        let base_bytes = match byte_cap {
9365            Some(_) => {
9366                let mut frames = lead.clone();
9367                frames.push(pull.clone());
9368                encode_message(&Message {
9369                    wire_version: WIRE_VERSION,
9370                    msg_kind: MsgKind::Request,
9371                    frames,
9372                })
9373                .len()
9374            }
9375            None => 0,
9376        };
9377        // §8.8: a `pull` round carries no commit and defers none; a `through`
9378        // round pushes and defers only its prefix.
9379        let pushable = self.pushable_commits();
9380        let total_outbox = if log_epoch.is_some() { pushable } else { 0 };
9381        let mut push_frames: Vec<Frame> = Vec::new();
9382        let mut pushed_ids = Vec::new();
9383        let mut ops_in_request = 0usize;
9384        let mut bytes_in_request = 0usize;
9385        // §2.1: an epoch-less request withholds the whole outbox until the
9386        // next, epoch-bound request.
9387        let mut deferred_commits = pushable - total_outbox;
9388        // §7.2.2: a pending replacement is held; the push stops before it
9389        // without deferring work.
9390        let held: HashSet<String> = self
9391            .prepare_replacements()
9392            .map_err(storage_failed)?
9393            .into_iter()
9394            .filter_map(|decision| decision.replacement)
9395            .collect();
9396        #[cfg(feature = "bench-internals")]
9397        let outbox_phase = self.benchmark_phases.start(Phase::OutboxEncode);
9398        for (index, commit) in self.outbox.iter().take(total_outbox).enumerate() {
9399            if held.contains(&commit.client_commit_id) {
9400                break;
9401            }
9402            // §6.1/§7.1: the commit-count and operation caps are hard. A
9403            // first commit over the operation cap is a typed capacity error
9404            // and stays queued; a later one defers with the complete suffix.
9405            if max_commits.is_some_and(|cap| push_frames.len() >= cap) {
9406                deferred_commits = total_outbox - index;
9407                break;
9408            }
9409            if ops_in_request + commit.ops.len() > max_ops {
9410                if push_frames.is_empty() {
9411                    return Err(Self::push_capacity_outcome(
9412                        "operations",
9413                        max_ops,
9414                        commit.ops.len(),
9415                        Some(commit.client_commit_id.as_str()),
9416                    ));
9417                }
9418                deferred_commits = total_outbox - index;
9419                break;
9420            }
9421            // §7.1 chained base: the commit waits for the change of the commit
9422            // it chains on, which supplies its rebased version.
9423            if self.outbox[..index]
9424                .iter()
9425                .flat_map(|earlier| &earlier.ops)
9426                .any(|earlier| commit.ops.iter().any(|op| chains_on(earlier, op)))
9427            {
9428                deferred_commits = total_outbox - index;
9429                break;
9430            }
9431            let operations = commit
9432                .ops
9433                .iter()
9434                .map(|op| {
9435                    let payload = match self
9436                        .schema
9437                        .table(&op.table)
9438                        .and_then(|table| Some((table, op.presented_values(table)?)))
9439                    {
9440                        Some((table, values)) => {
9441                            // §0: outbox entries encode at send time with the
9442                            // current codec (validated at mutate()). §6.1: the
9443                            // values map's keys are the sparse presence set; an
9444                            // insert-intent operation presents every column (§7.1).
9445                            // §5.11: encrypted columns are encrypted here, with
9446                            // an absent key-id selector read from the stored row.
9447                            // `sync_inner` runs `drop_unencodable_outbox` first,
9448                            // so an encrypt failure cannot reach this encode; the
9449                            // author seam validated every other failure.
9450                            let fallback =
9451                                self.stored_key_fallback(table, &op.row_id)
9452                                    .map_err(|message| {
9453                                        Box::new(SyncOutcome::Failed {
9454                                            error_code: "storage.failed".into(),
9455                                            message,
9456                                            details: None,
9457                                            recommended_action: None,
9458                                        })
9459                                    })?;
9460                            encode_sparse_row_json(
9461                                table,
9462                                &op.row_id,
9463                                &values,
9464                                &self.encryption,
9465                                fallback.as_ref(),
9466                            )
9467                            .ok()
9468                        }
9469                        None => None,
9470                    };
9471                    Ok(ssp2::model::Operation {
9472                        table: op.table.clone(),
9473                        row_id: op.row_id.clone(),
9474                        op: if op.upsert { Op::Upsert } else { Op::Delete },
9475                        base_version: op.base_version,
9476                        payload,
9477                    })
9478                })
9479                .collect::<Result<Vec<_>, Box<SyncOutcome>>>()?;
9480            // §6.3.2, §7.1: the commit's outbox sequence.
9481            let client_seq = self
9482                .conn
9483                .prepare_cached("SELECT seq FROM _syncular_outbox WHERE commit_id = ?1")
9484                .and_then(|mut statement| {
9485                    statement.query_row([&commit.client_commit_id], |row| row.get(0))
9486                })
9487                .map_err(|error| {
9488                    storage_failed(Self::sqlite_failure(&self.storage_failure, error))
9489                })?;
9490            let frame = Frame::PushCommit {
9491                client_commit_id: commit.client_commit_id.clone(),
9492                client_seq,
9493                operations,
9494            };
9495            let frame_bytes = match byte_cap {
9496                Some(_) => {
9497                    let mut frames = lead.clone();
9498                    frames.push(frame.clone());
9499                    frames.push(pull.clone());
9500                    encode_message(&Message {
9501                        wire_version: WIRE_VERSION,
9502                        msg_kind: MsgKind::Request,
9503                        frames,
9504                    })
9505                    .len()
9506                        - base_bytes
9507                }
9508                None => 0,
9509            };
9510            // The head is always encoded so the caller can report the full
9511            // projected request size; a later commit defers once it no longer
9512            // fits.
9513            if let Some(cap) = byte_cap {
9514                if !push_frames.is_empty() && fixed_bytes + bytes_in_request + frame_bytes > cap {
9515                    deferred_commits = total_outbox - index;
9516                    break;
9517                }
9518            }
9519            push_frames.push(frame);
9520            pushed_ids.push(commit.client_commit_id.clone());
9521            ops_in_request += commit.ops.len();
9522            bytes_in_request += frame_bytes;
9523        }
9524        #[cfg(feature = "bench-internals")]
9525        drop(outbox_phase);
9526        if let Some(cap) = byte_cap {
9527            if fixed_bytes + bytes_in_request > cap {
9528                // The head alone does not fit this budget; the commit stays
9529                // queued and no transport round is attempted.
9530                let blocked = if push_frames.is_empty() {
9531                    None
9532                } else {
9533                    self.outbox.first().map(|c| c.client_commit_id.as_str())
9534                };
9535                return Err(Self::push_capacity_outcome(
9536                    "bytes",
9537                    cap,
9538                    fixed_bytes + bytes_in_request,
9539                    blocked,
9540                ));
9541            }
9542        }
9543        let mut frames = lead;
9544        frames.extend(push_frames);
9545        frames.push(pull);
9546        frames.extend(sub_frames);
9547        let message = Message {
9548            wire_version: WIRE_VERSION,
9549            msg_kind: MsgKind::Request,
9550            frames,
9551        };
9552        Ok((
9553            message,
9554            RequestMeta {
9555                pushed_ids,
9556                registration_digest,
9557                accept,
9558                deferred_commits,
9559                applied: BTreeMap::new(),
9560                deferred: BTreeSet::new(),
9561            },
9562        ))
9563    }
9564
9565    /// §7.1: a configured push capacity limit cannot carry this request.
9566    fn push_capacity_outcome(
9567        kind: &str,
9568        limit: usize,
9569        size: usize,
9570        client_commit_id: Option<&str>,
9571    ) -> Box<SyncOutcome> {
9572        let mut details = Map::new();
9573        details.insert("kind".to_owned(), Value::from(kind));
9574        details.insert("limit".to_owned(), Value::from(limit as u64));
9575        details.insert("size".to_owned(), Value::from(size as u64));
9576        if let Some(id) = client_commit_id {
9577            details.insert("clientCommitId".to_owned(), Value::from(id));
9578        }
9579        Box::new(SyncOutcome::Failed {
9580            error_code: "client.push_request_too_large".into(),
9581            message: "the push request exceeds a configured capacity limit".into(),
9582            details: Some(Value::Object(details)),
9583            recommended_action: None,
9584        })
9585    }
9586
9587    // -- sync -------------------------------------------------------------------
9588
9589    /// Cloneable observation handle; no client lock is needed to read it.
9590    pub fn progress(&self) -> ProgressObserver {
9591        self.progress.clone()
9592    }
9593
9594    pub fn sync(&mut self, transport: &mut dyn Transport) -> SyncOutcome {
9595        self.sync_bounded(transport, None)
9596    }
9597
9598    /// One round; `idle_bound` is the idle drive's round bound (§7.8).
9599    fn sync_bounded(
9600        &mut self,
9601        transport: &mut dyn Transport,
9602        idle_bound: Option<(u64, u32)>,
9603    ) -> SyncOutcome {
9604        let mut prepared = match self.prepare_sync_round(transport.supports_url_fetch()) {
9605            Ok(prepared) => prepared,
9606            Err(outcome) => return *outcome,
9607        };
9608        prepared.idle_bound = idle_bound;
9609        // The round's network deadline rides `PreparedSyncRound` and is scoped
9610        // to each exchange, so uploads, continuations, the main request, and
9611        // every segment fetch share one monotonic anchor without leaving
9612        // deadline state on a reused transport.
9613        let mut next = prepared;
9614        loop {
9615            match self.apply_sync_round(next.exchange(transport)) {
9616                crate::AppliedSyncRound::Continue(prepared) => next = prepared,
9617                crate::AppliedSyncRound::Complete {
9618                    outcome, controls, ..
9619                } => {
9620                    if !self.transport_closed() {
9621                        for text in controls {
9622                            let _ = transport.realtime_send(&text);
9623                        }
9624                    } else {
9625                        self.disconnect_realtime(transport);
9626                    }
9627                    return outcome;
9628                }
9629            }
9630        }
9631    }
9632
9633    fn finish_sync_round(
9634        &mut self,
9635        started_at_ms: i64,
9636        attempt: u64,
9637        mut outcome: SyncOutcome,
9638    ) -> SyncOutcome {
9639        if let SyncOutcome::Failed {
9640            error_code,
9641            message,
9642            details,
9643            ..
9644        } = &mut outcome
9645        {
9646            if let Some((failure, code)) = self
9647                .storage_failure
9648                .borrow()
9649                .as_ref()
9650                .and_then(|failure| failure.code.map(|code| (failure, code)))
9651            {
9652                *error_code = code.to_owned();
9653                *message = match code {
9654                    "client.storage_busy" => "local SQLite storage is busy",
9655                    "client.storage_full" => "local SQLite storage is full",
9656                    "client.storage_io" => "local SQLite storage I/O failed",
9657                    "client.storage_corrupt" => "local SQLite storage is corrupt",
9658                    _ => unreachable!("unrecognized classified storage failure"),
9659                }
9660                .to_owned();
9661                *details = failure.details();
9662            }
9663        }
9664        let details = match &outcome {
9665            SyncOutcome::Failed { details, .. } => details.as_ref(),
9666            _ => None,
9667        };
9668        let cause_kind = details
9669            .and_then(|details| details.get("causeKind"))
9670            .and_then(Value::as_str)
9671            .and_then(|cause| match cause {
9672                "network" => Some(crate::TransportCauseKind::Network),
9673                "connect" => Some(crate::TransportCauseKind::Connect),
9674                "tls" => Some(crate::TransportCauseKind::Tls),
9675                "io" => Some(crate::TransportCauseKind::Io),
9676                "request" => Some(crate::TransportCauseKind::Request),
9677                "protocol" => Some(crate::TransportCauseKind::Protocol),
9678                "timeout" => Some(crate::TransportCauseKind::Timeout),
9679                "round_deadline" => Some(crate::TransportCauseKind::RoundDeadline),
9680                "aborted" => Some(crate::TransportCauseKind::Aborted),
9681                "body" => Some(crate::TransportCauseKind::Body),
9682                "status" => Some(crate::TransportCauseKind::Status),
9683                "redirect" => Some(crate::TransportCauseKind::Redirect),
9684                "unknown" => Some(crate::TransportCauseKind::Unknown),
9685                _ => None,
9686            });
9687        let http_status = if matches!(
9688            cause_kind,
9689            Some(
9690                crate::TransportCauseKind::Status
9691                    | crate::TransportCauseKind::Body
9692                    | crate::TransportCauseKind::Redirect
9693            )
9694        ) {
9695            details
9696                .and_then(|details| details.get("httpStatus"))
9697                .and_then(Value::as_f64)
9698                .filter(|status| status.fract() == 0.0 && (100.0..=599.0).contains(status))
9699                .map(|status| status as u16)
9700        } else {
9701            None
9702        };
9703        let retry_delay_ms = self.round_retry_delay_ms;
9704        self.progress.update(|p| match &outcome {
9705            SyncOutcome::Ok(report) | SyncOutcome::BudgetExhausted(report)
9706                if report.failed.is_empty() =>
9707            {
9708                p.state = ProgressState::Complete
9709            }
9710            SyncOutcome::Ok(_) | SyncOutcome::BudgetExhausted(_) => {
9711                p.state = ProgressState::Failed;
9712                p.error_code = Some("sync.scope_revoked".into());
9713            }
9714            SyncOutcome::Failed { error_code, .. } => {
9715                p.state = ProgressState::Failed;
9716                p.error_code = Some(Self::diagnostic_code(error_code));
9717                p.cause_kind = cause_kind;
9718                p.http_status = http_status;
9719                p.retry_delay_ms = retry_delay_ms;
9720            }
9721            SyncOutcome::RealtimeUnavailable { .. } => {
9722                p.state = ProgressState::Failed;
9723                p.error_code = Some(REALTIME_UNAVAILABLE_CODE.to_owned());
9724                p.retry_delay_ms = retry_delay_ms;
9725            }
9726        });
9727        let completed_at_ms = self.clock_now_ms();
9728        self.last_round = Some(match &outcome {
9729            SyncOutcome::Ok(report) | SyncOutcome::BudgetExhausted(report) => DiagnosticLastRound {
9730                epoch: self.epoch.clone(),
9731                attempt,
9732                status: "succeeded".to_owned(),
9733                started_at_ms,
9734                completed_at_ms,
9735                duration_ms: completed_at_ms.saturating_sub(started_at_ms).max(0),
9736                counters: Some(DiagnosticRoundCounters {
9737                    pushed: report.pushed,
9738                    applied: report.applied.len(),
9739                    rejected: report.rejected.len(),
9740                    retryable: report.retryable.len(),
9741                    conflicts: report.conflicts,
9742                    commits_applied: report.commits_applied,
9743                    segment_rows_applied: report.segment_rows_applied,
9744                    bootstrapping: report.bootstrapping.len(),
9745                    resets: report.resets.len(),
9746                    revoked: report.revoked.len(),
9747                    failed: report.failed.len(),
9748                    deferred_commits: report.deferred_commits,
9749                }),
9750                error_code: None,
9751                cause_kind: None,
9752                http_status: None,
9753            },
9754            SyncOutcome::Failed { error_code, .. } => DiagnosticLastRound {
9755                epoch: self.epoch.clone(),
9756                attempt,
9757                status: "failed".to_owned(),
9758                started_at_ms,
9759                completed_at_ms,
9760                duration_ms: completed_at_ms.saturating_sub(started_at_ms).max(0),
9761                counters: None,
9762                error_code: Some(Self::diagnostic_code(error_code)),
9763                cause_kind,
9764                http_status,
9765            },
9766            SyncOutcome::RealtimeUnavailable { .. } => DiagnosticLastRound {
9767                epoch: self.epoch.clone(),
9768                attempt,
9769                status: "failed".to_owned(),
9770                started_at_ms,
9771                completed_at_ms,
9772                duration_ms: completed_at_ms.saturating_sub(started_at_ms).max(0),
9773                counters: None,
9774                error_code: Some(REALTIME_UNAVAILABLE_CODE.to_owned()),
9775                cause_kind: None,
9776                http_status: None,
9777            },
9778        });
9779        outcome
9780    }
9781
9782    /// Capture one request on the client owner. Mutations made after this
9783    /// call remain in the outbox for a later round; no network I/O occurs here.
9784    pub fn prepare_sync_round(
9785        &mut self,
9786        url_capable: bool,
9787    ) -> Result<crate::PreparedSyncRound, Box<SyncOutcome>> {
9788        if self.transport_closed() {
9789            return Err(Box::new(SyncOutcome::Failed {
9790                error_code: "sync.offline".into(),
9791                message: "transport gate is closed".into(),
9792                details: None,
9793                recommended_action: None,
9794            }));
9795        }
9796        if self.active_round.is_some() || self.fence_round.is_some() {
9797            return Err(Box::new(SyncOutcome::Failed {
9798                error_code: "client.round_in_progress".into(),
9799                message: "a sync round is already in flight".into(),
9800                details: None,
9801                recommended_action: None,
9802            }));
9803        }
9804        self.storage_failure.borrow_mut().take();
9805        let attempt = self.progress.start(&self.epoch);
9806        self.round_retry_delay_ms = None;
9807        let started_at_ms = self.clock_now_ms();
9808        let prepared = (|| {
9809            if self.stopped {
9810                return Err(Box::new(SyncOutcome::Ok(SyncReport {
9811                    schema_floor: self.schema_floor.clone(),
9812                    ..SyncReport::default()
9813                })));
9814            }
9815            if self.security_preflight {
9816                return Err(Box::new(SyncOutcome::Failed {
9817                    error_code: SECURITY_PREFLIGHT_REQUIRED_CODE.into(),
9818                    message: "security preflight must complete before syncing".into(),
9819                    details: None,
9820                    recommended_action: None,
9821                }));
9822            }
9823            self.set_sync_needed(false, false);
9824            self.drain_pending_evictions()
9825                .and_then(|_| self.drop_incompatible_outbox())
9826                .and_then(|_| self.drop_unencodable_outbox(true, None))
9827                .map_err(|message| {
9828                    Box::new(SyncOutcome::Failed {
9829                        error_code: "storage.failed".into(),
9830                        message,
9831                        details: None,
9832                        recommended_action: None,
9833                    })
9834                })?;
9835            // §5.11: reveal rows sealed under a key the keyring gained since.
9836            self.reveal_sealed_rows().map_err(|error| {
9837                Box::new(SyncOutcome::Failed {
9838                    error_code: error.code,
9839                    message: error.message,
9840                    details: error.details,
9841                    recommended_action: None,
9842                })
9843            })?;
9844            let has_log_epoch = self.get_meta(LOG_EPOCH_KEY).map_err(|message| {
9845                Box::new(SyncOutcome::Failed {
9846                    error_code: "storage.failed".into(),
9847                    message,
9848                    details: None,
9849                    recommended_action: None,
9850                })
9851            })?;
9852            let mut uploads = if has_log_epoch.is_some()
9853                && matches!(
9854                    self.transport_gate,
9855                    crate::TransportGate::Open | crate::TransportGate::Through(_)
9856                )
9857                && self.schema_has_blobs()
9858            {
9859                self.pending_blob_uploads().map_err(|e| {
9860                    Box::new(SyncOutcome::Failed {
9861                        error_code: e.code,
9862                        message: e.message,
9863                        details: e.details,
9864                        recommended_action: None,
9865                    })
9866                })?
9867            } else {
9868                Vec::new()
9869            };
9870            // §8.8: a `through` round uploads only the blobs its prefix references.
9871            if matches!(self.transport_gate, crate::TransportGate::Through(_)) {
9872                let prefix = Value::Array(
9873                    self.outbox
9874                        .iter()
9875                        .take(self.pushable_commits())
9876                        .map(|commit| Value::String(commit.client_commit_id.clone()))
9877                        .collect(),
9878                );
9879                let referenced = self
9880                    .conn
9881                    .prepare(
9882                        "SELECT blob_id FROM _syncular_blob_commit_refs
9883                          WHERE commit_id IN (SELECT value FROM json_each(?1))",
9884                    )
9885                    .and_then(|mut statement| {
9886                        statement
9887                            .query_map([prefix.to_string()], |row| row.get::<_, String>(0))?
9888                            .collect::<Result<HashSet<_>, _>>()
9889                    })
9890                    .map_err(|error| {
9891                        Box::new(SyncOutcome::Failed {
9892                            error_code: "storage.failed".into(),
9893                            message: Self::sqlite_failure(&self.storage_failure, error),
9894                            details: None,
9895                            recommended_action: None,
9896                        })
9897                    })?;
9898                uploads.retain(|upload| referenced.contains(&upload.id));
9899            }
9900            if self.realtime_state != RealtimeState::Connected
9901                && self.realtime_policy == RealtimePolicy::Required
9902            {
9903                let retry_delay_ms = self.schedule_background_retry();
9904                self.realtime_retry_delay_ms = Some(retry_delay_ms);
9905                return Err(Box::new(SyncOutcome::RealtimeUnavailable {
9906                    state: self.realtime_state,
9907                    reason_code: self.realtime_reason_code.clone(),
9908                    retry_delay_ms,
9909                }));
9910            }
9911            let (message, mut meta) = self.build_request(url_capable)?;
9912            let units = self.stored(load_units(&self.conn)).map_err(|message| {
9913                Box::new(SyncOutcome::Failed {
9914                    error_code: "storage.failed".into(),
9915                    message,
9916                    details: None,
9917                    recommended_action: None,
9918                })
9919            })?;
9920            for unit in &units {
9921                let applied =
9922                    self.stored(applied_rows(&self.conn, &unit.id))
9923                        .map_err(|message| {
9924                            Box::new(SyncOutcome::Failed {
9925                                error_code: "storage.failed".into(),
9926                                message,
9927                                details: None,
9928                                recommended_action: None,
9929                            })
9930                        })?;
9931                if !applied.is_empty() {
9932                    meta.applied.insert(unit.id.clone(), applied);
9933                }
9934            }
9935            // §7.1: the send-attempt marker of every commit the request
9936            // carries commits before the round leaves the owner.
9937            let pushed: Vec<String> = message
9938                .frames
9939                .iter()
9940                .filter_map(|frame| match frame {
9941                    Frame::PushCommit { client_seq, .. } => Some(client_seq.to_string()),
9942                    _ => None,
9943                })
9944                .collect();
9945            if !pushed.is_empty() {
9946                self.conn
9947                    .execute(
9948                        &format!(
9949                            "UPDATE _syncular_outbox SET attempted = 1 WHERE seq IN ({})",
9950                            pushed.join(",")
9951                        ),
9952                        [],
9953                    )
9954                    .map_err(|error| {
9955                        Box::new(SyncOutcome::Failed {
9956                            error_code: "storage.failed".into(),
9957                            message: Self::sqlite_failure(&self.storage_failure, error),
9958                            details: None,
9959                            recommended_action: None,
9960                        })
9961                    })?;
9962            }
9963            let id = uuid::Uuid::new_v4();
9964            self.active_round = Some((id, started_at_ms, attempt));
9965            let phase = if uploads.is_empty() {
9966                crate::round::RoundPhase::Sync
9967            } else {
9968                crate::round::RoundPhase::UploadGrant
9969            };
9970            Ok(crate::PreparedSyncRound {
9971                id,
9972                started_at_ms,
9973                attempt,
9974                message,
9975                meta,
9976                uploads: uploads.into(),
9977                phase,
9978                encoded: None,
9979                continuation: None,
9980                completed: None,
9981                realtime: self.realtime_state == RealtimeState::Connected,
9982                // §5.5: the owning unit's scope map, each value a one-element list.
9983                scopes: units
9984                    .into_iter()
9985                    .map(|unit| {
9986                        (
9987                            unit.id,
9988                            canonical_scope_json(&unit_scope_lists(&unit.scopes)),
9989                        )
9990                    })
9991                    .collect(),
9992                #[cfg(feature = "bench-internals")]
9993                benchmark_phases: self.benchmark_phases.clone(),
9994                progress: self.progress.clone(),
9995                fixed_now: self
9996                    .now_ms
9997                    .as_ref()
9998                    .map(|clock| clock.load(std::sync::atomic::Ordering::Relaxed)),
9999                round_deadline_at: None,
10000                idle_bound: None,
10001                network_started_at: None,
10002            })
10003        })();
10004        prepared
10005            .map_err(|outcome| Box::new(self.finish_sync_round(started_at_ms, attempt, *outcome)))
10006    }
10007
10008    /// Discard the reply of an old authorization or registration context. Its
10009    /// submitted commits stay durable and can be retried with the same ids.
10010    /// §7.6: an abandoned in-flight round ends its attempt as failed.
10011    pub fn cancel_sync_round(&mut self) {
10012        self.fence_round = None;
10013        if let Some((_, started_at_ms, attempt)) = self.active_round.take() {
10014            // A storage failure recorded since the round started is not its cause.
10015            self.storage_failure.borrow_mut().take();
10016            self.finish_sync_round(
10017                started_at_ms,
10018                attempt,
10019                SyncOutcome::Failed {
10020                    error_code: "client.round_cancelled".into(),
10021                    message: "sync round belongs to a released client context".into(),
10022                    details: None,
10023                    recommended_action: None,
10024                },
10025            );
10026        }
10027    }
10028
10029    /// Apply captured network results on the owner, preserving all normal
10030    /// version, schema, content-address and cursor checks. No network I/O.
10031    pub fn apply_sync_round(
10032        &mut self,
10033        completed: crate::CompletedSyncRound,
10034    ) -> crate::AppliedSyncRound {
10035        let mut prepared = completed.prepared;
10036        if self.active_round.map(|(id, ..)| id) != Some(prepared.id) || self.security_preflight {
10037            return crate::AppliedSyncRound::Complete {
10038                outcome: SyncOutcome::Failed {
10039                    error_code: "client.round_cancelled".into(),
10040                    message: "sync round belongs to a released client context".into(),
10041                    details: None,
10042                    recommended_action: None,
10043                },
10044                controls: Vec::new(),
10045                more: false,
10046                bootstrap_advanced: false,
10047            };
10048        }
10049        self.storage_failure.borrow_mut().take();
10050        let (response, mut downloads, transport_failed) = match completed.exchange {
10051            crate::round::ExchangeResult::Upload { id, result } => {
10052                let result = match result {
10053                    // §5.9.7: a non-retryable server refusal (`blob.too_large`)
10054                    // is the body's final outcome. The commits naming it take
10055                    // the incompatible-commit path with the server's code and
10056                    // leave this round's request; the round continues.
10057                    Err(error)
10058                        if error
10059                            .details
10060                            .as_ref()
10061                            .and_then(|details| details.get("retryable"))
10062                            == Some(&Value::Bool(false)) =>
10063                    {
10064                        self.conn
10065                            .prepare(
10066                                "SELECT commit_id FROM _syncular_blob_commit_refs WHERE blob_id = ?",
10067                            )
10068                            .and_then(|mut statement| {
10069                                statement
10070                                    .query_map(rusqlite::params![id], |row| row.get::<_, String>(0))?
10071                                    .collect::<Result<HashSet<_>, _>>()
10072                            })
10073                            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
10074                            .and_then(|refused| {
10075                                // §8.8: only a commit the gate lets this round
10076                                // push takes the refusal. A held commit keeps
10077                                // the body queued and meets the refusal when a
10078                                // round pushes it.
10079                                let commits = self
10080                                    .outbox
10081                                    .iter()
10082                                    .take(self.pushable_commits())
10083                                    .filter(|commit| refused.contains(&commit.client_commit_id))
10084                                    .cloned()
10085                                    .collect::<Vec<_>>();
10086                                if !commits.is_empty() {
10087                                    self.drop_outbox_commits(&commits, &error.code, &error.message)?;
10088                                }
10089                                prepared.message.frames.retain(|frame| {
10090                                    !matches!(frame, Frame::PushCommit { client_commit_id, .. }
10091                                        if refused.contains(client_commit_id))
10092                                });
10093                                prepared.meta.pushed_ids.retain(|id| !refused.contains(id));
10094                                prepared.continuation = Some(crate::round::RoundPhase::UploadGrant);
10095                                Ok(true)
10096                            })
10097                            .map_err(|message| TransportError::new("client.failed", message))
10098                    }
10099                    result => result.map(|()| false),
10100                };
10101                // A refused body stays queued while a held commit names it.
10102                let result = result.and_then(|refused| {
10103                    self.conn
10104                        .execute(
10105                            if refused {
10106                                "DELETE FROM _syncular_blob_uploads WHERE blob_id = ?1
10107                                   AND NOT EXISTS (SELECT 1 FROM _syncular_blob_commit_refs
10108                                                    WHERE blob_id = ?1)"
10109                            } else {
10110                                "DELETE FROM _syncular_blob_uploads WHERE blob_id = ?1"
10111                            },
10112                            rusqlite::params![id],
10113                        )
10114                        .map(|_| ())
10115                        .map_err(|error| {
10116                            TransportError::new(
10117                                "client.failed",
10118                                Self::sqlite_failure(&self.storage_failure, error),
10119                            )
10120                        })
10121                });
10122                match result {
10123                    Ok(()) => return crate::AppliedSyncRound::Continue(prepared),
10124                    Err(TransportError {
10125                        code,
10126                        message,
10127                        details,
10128                    }) => {
10129                        self.active_round = None;
10130                        if Self::unreachable_transport(&details) {
10131                            // The round's work is still owed; the host's
10132                            // connectivity resume runs it.
10133                            self.set_sync_needed(true, false);
10134                        } else if Self::retryable_failure_code(&code) {
10135                            self.schedule_background_retry();
10136                        }
10137                        let recommended_action = recommended_action_of(&details);
10138                        let outcome = self.finish_sync_round(
10139                            prepared.started_at_ms,
10140                            prepared.attempt,
10141                            SyncOutcome::Failed {
10142                                error_code: code,
10143                                message,
10144                                details,
10145                                recommended_action,
10146                            },
10147                        );
10148                        return crate::AppliedSyncRound::Complete {
10149                            outcome,
10150                            controls: Vec::new(),
10151                            more: false,
10152                            bootstrap_advanced: false,
10153                        };
10154                    }
10155                }
10156            }
10157            crate::round::ExchangeResult::Reply {
10158                response,
10159                downloads,
10160                transport_failed,
10161            } => (response, downloads, transport_failed),
10162        };
10163        self.active_round = None;
10164        let before = self.resume_tokens();
10165        let outcome = (|| {
10166            let response = match response {
10167                Ok(response) => {
10168                    // §1.5: a complete, decodable response ends the report, an
10169                    // in-band ERROR included (the server already recorded it).
10170                    self.round_failure = None;
10171                    response
10172                }
10173                Err(TransportError {
10174                    code,
10175                    message,
10176                    details,
10177                }) => {
10178                    // §1.5: the server cannot see a round whose transport
10179                    // failed or whose response never decoded, so its code rides
10180                    // the following requests. A code the frame grammar rejects
10181                    // is not reportable, and the previous code stays; the
10182                    // client-local drive timeout never goes on the wire (§7.8).
10183                    if code != "sync.idle_timeout" && ssp2::model::valid_round_failure_code(&code) {
10184                        self.round_failure = Some(code.clone());
10185                    }
10186                    // §8.8: a prefix sent without a receipt is an uncertain delivery.
10187                    if !prepared.meta.pushed_ids.is_empty()
10188                        && matches!(self.transport_gate, crate::TransportGate::Through(_))
10189                    {
10190                        self.move_transport_gate(crate::TransportGate::Pull);
10191                    }
10192                    if transport_failed {
10193                        if prepared.realtime {
10194                            self.set_realtime_state(RealtimeState::Lost, Some(&code));
10195                        }
10196                        if let Err(message) = self.record_lease_error(&code) {
10197                            return SyncOutcome::Failed {
10198                                error_code: "storage.failed".to_owned(),
10199                                message,
10200                                details: None,
10201                                recommended_action: None,
10202                            };
10203                        }
10204                    }
10205                    if Self::retryable_failure_code(&code) && !Self::unreachable_transport(&details)
10206                    {
10207                        let delay = self.schedule_background_retry();
10208                        if prepared.realtime && transport_failed {
10209                            self.realtime_retry_delay_ms = Some(delay);
10210                        }
10211                    }
10212                    let recommended_action = recommended_action_of(&details);
10213                    return SyncOutcome::Failed {
10214                        error_code: code,
10215                        message,
10216                        details,
10217                        recommended_action,
10218                    };
10219                }
10220            };
10221            let mut outcome = self.process_response(&mut downloads, response, &prepared.meta);
10222            if let SyncOutcome::Ok(report) = &mut outcome {
10223                report.deferred_commits = prepared.meta.deferred_commits;
10224            }
10225            match &outcome {
10226                SyncOutcome::Ok(_) => self.reset_background_retry(),
10227                SyncOutcome::Failed {
10228                    error_code,
10229                    details,
10230                    ..
10231                } if Self::retryable_failure_code(error_code)
10232                    && !Self::unreachable_transport(details) =>
10233                {
10234                    self.schedule_background_retry();
10235                }
10236                _ => {}
10237            }
10238            if prepared.meta.deferred_commits > 0 {
10239                self.set_sync_needed(true, true);
10240            }
10241            self.previous_version_lifetime_check();
10242            outcome
10243        })();
10244        match &outcome {
10245            // §7.1: a unit still catching up needs another round, also when the
10246            // drive that started it ends early.
10247            SyncOutcome::Ok(report) if !report.bootstrapping.is_empty() => {
10248                self.set_sync_needed(true, false)
10249            }
10250            // The round's work is still owed; the host's connectivity resume
10251            // runs it.
10252            SyncOutcome::Failed { details, .. } if Self::unreachable_transport(details) => {
10253                self.set_sync_needed(true, false)
10254            }
10255            _ => {}
10256        }
10257        let more = !self.transport_closed()
10258            && matches!(&outcome, SyncOutcome::Ok(report)
10259                if report.schema_floor.is_none()
10260                    && (!report.bootstrapping.is_empty()
10261                        || report.commits_applied > 0
10262                        || report.segment_rows_applied > 0
10263                        || !report.resets.is_empty()
10264                        || report.deferred_commits > 0
10265                        || self.sync_needed));
10266        let bootstrap_advanced = matches!(&outcome, SyncOutcome::Ok(report) if report.segment_rows_applied > 0 && !report.bootstrapping.is_empty())
10267            && before != self.resume_tokens();
10268        crate::AppliedSyncRound::Complete {
10269            outcome: self.finish_sync_round(prepared.started_at_ms, prepared.attempt, outcome),
10270            controls: if !self.transport_closed() {
10271                downloads.controls
10272            } else {
10273                Vec::new()
10274            },
10275            more,
10276            bootstrap_advanced,
10277        }
10278    }
10279
10280    /// Every unit's resume token and applied-segment record: a bootstrap
10281    /// that advanced changes one (§4.7), also when it applied images of a
10282    /// section it deferred (§5.3, §5.6).
10283    #[allow(clippy::type_complexity)]
10284    fn resume_tokens(&self) -> Option<Vec<(String, Option<String>, Option<String>)>> {
10285        self.conn
10286            .prepare_cached(
10287                "SELECT id, bootstrap_state, applied FROM _syncular_units ORDER BY rowid",
10288            )
10289            .and_then(|mut stmt| {
10290                stmt.query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))?
10291                    .collect()
10292            })
10293            .ok()
10294    }
10295
10296    /// §7.8: one idle drive's default total deadline, the TS client's value.
10297    pub const SYNC_IDLE_TIMEOUT_MS: u64 = 60_000;
10298
10299    pub fn sync_until_idle(
10300        &mut self,
10301        transport: &mut dyn Transport,
10302        max_rounds: Option<u32>,
10303    ) -> SyncOutcome {
10304        self.sync_until_idle_with_deadline(transport, max_rounds, Some(Self::SYNC_IDLE_TIMEOUT_MS))
10305    }
10306
10307    /// As [`SyncClient::sync_until_idle`], with an explicit total deadline in
10308    /// milliseconds (`None` disables it). The deadline is checked against the
10309    /// client clock between rounds: a drive past it after a completed round
10310    /// ends as `BudgetExhausted`. Each round is bounded by `timeout_ms` on its
10311    /// own, or the transport's tighter whole-round deadline (§1.8); a round
10312    /// that reaches the drive bound fails with `sync.idle_timeout`.
10313    pub fn sync_until_idle_with_deadline(
10314        &mut self,
10315        transport: &mut dyn Transport,
10316        max_rounds: Option<u32>,
10317        timeout_ms: Option<u64>,
10318    ) -> SyncOutcome {
10319        // §7.8: an explicit budget is a strict positive round count. Zero is a
10320        // caller error, not an exhaustion.
10321        if max_rounds == Some(0) {
10322            return SyncOutcome::Failed {
10323                details: None,
10324                error_code: "sync.invalid_request".into(),
10325                message: "maxRounds must be a positive integer".into(),
10326                recommended_action: None,
10327            };
10328        }
10329        if timeout_ms.is_some_and(|ms| ms == 0 || i64::try_from(ms).is_err()) {
10330            return SyncOutcome::Failed {
10331                details: None,
10332                error_code: "sync.invalid_request".into(),
10333                message: "timeoutMs must be a positive integer".into(),
10334                recommended_action: None,
10335            };
10336        }
10337        let started_at_ms = self.clock_now_ms();
10338        let rounds = max_rounds.unwrap_or(20);
10339        let mut aggregate = SyncReport::default();
10340        // §7.2.2: decisions pending at the drive's start are evaluated when it
10341        // reaches idle.
10342        let decisions = match self.prepare_replacements() {
10343            Ok(decisions) => decisions,
10344            Err(message) => {
10345                return SyncOutcome::Failed {
10346                    details: None,
10347                    error_code: "storage.failed".into(),
10348                    message,
10349                    recommended_action: None,
10350                }
10351            }
10352        };
10353        let mut spent = 0;
10354        let mut completed = false;
10355        while spent < rounds {
10356            // §7.8: a deadline that elapsed across completed rounds ends the
10357            // drive like an exhausted round budget; the next drive resumes.
10358            if completed
10359                && timeout_ms.is_some_and(|ms| {
10360                    self.clock_now_ms() >= started_at_ms.saturating_add(ms as i64)
10361                })
10362            {
10363                return SyncOutcome::BudgetExhausted(aggregate);
10364            }
10365            let idle_bound = timeout_ms.map(|ms| (ms, spent));
10366            spent += 1;
10367            let before = self.resume_tokens();
10368            match self.sync_bounded(transport, idle_bound) {
10369                SyncOutcome::Failed {
10370                    error_code,
10371                    message,
10372                    details,
10373                    recommended_action,
10374                } => {
10375                    return SyncOutcome::Failed {
10376                        details,
10377                        error_code,
10378                        message,
10379                        recommended_action,
10380                    };
10381                }
10382                outcome @ SyncOutcome::RealtimeUnavailable { .. } => return outcome,
10383                SyncOutcome::BudgetExhausted(_) => {
10384                    unreachable!("sync() never exhausts a round budget")
10385                }
10386                SyncOutcome::Ok(report) => {
10387                    completed = true;
10388                    if max_rounds.is_none()
10389                        && report.segment_rows_applied > 0
10390                        && !report.bootstrapping.is_empty()
10391                        && before != self.resume_tokens()
10392                    {
10393                        spent = 0;
10394                    }
10395                    // TS parity: a closed transport or a schema floor ends
10396                    // the loop. The latest round still merges first.
10397                    let stop = self.transport_closed() || report.schema_floor.is_some();
10398                    aggregate.merge(&report);
10399                    // §4.5: pull again whenever the response contained
10400                    // commits or segments; resets re-bootstrap; a pending
10401                    // resume token continues paging (§4.7); deferred outbox
10402                    // commits and a raised sync-needed signal push on the next
10403                    // round.
10404                    let more = !stop
10405                        && (!report.bootstrapping.is_empty()
10406                            || report.commits_applied > 0
10407                            || report.segment_rows_applied > 0
10408                            || !report.resets.is_empty()
10409                            || report.deferred_commits > 0
10410                            || self.sync_needed);
10411                    if more {
10412                        continue;
10413                    }
10414                    // §7.2.2: a written decision runs another round, which
10415                    // pushes it.
10416                    match self.settle_replacements(&decisions, &SyncOutcome::Ok(aggregate.clone()))
10417                    {
10418                        Ok(true) if !stop => {}
10419                        Ok(_) => return SyncOutcome::Ok(aggregate),
10420                        Err(message) => {
10421                            return SyncOutcome::Failed {
10422                                details: None,
10423                                error_code: "storage.failed".into(),
10424                                message,
10425                                recommended_action: None,
10426                            }
10427                        }
10428                    }
10429                }
10430            }
10431        }
10432        // §7.8: partial success. The aggregate report is retained and the run
10433        // is explicitly not idle.
10434        SyncOutcome::BudgetExhausted(aggregate)
10435    }
10436
10437    fn process_response(
10438        &mut self,
10439        transport: &mut dyn Transport,
10440        response: Message,
10441        meta: &RequestMeta,
10442    ) -> SyncOutcome {
10443        #[cfg(feature = "bench-internals")]
10444        let _phase = self.benchmark_phases.start(Phase::ResponseApply);
10445        let mut report = SyncReport {
10446            pushed: meta.pushed_ids.len() as u32,
10447            ..SyncReport::default()
10448        };
10449        let mut rejection_details_by_commit: HashMap<String, BTreeMap<i32, RejectionDetails>> =
10450            HashMap::new();
10451        let pushed_ids = meta
10452            .pushed_ids
10453            .iter()
10454            .map(String::as_str)
10455            .collect::<HashSet<_>>();
10456        let mut last_final_push_result_id: Option<String> = None;
10457        for frame in &response.frames {
10458            match frame {
10459                Frame::PushResultDetails {
10460                    client_commit_id,
10461                    entries,
10462                } => {
10463                    let details = rejection_details_by_commit
10464                        .entry(client_commit_id.clone())
10465                        .or_default();
10466                    for entry in entries {
10467                        let parsed = match RejectionDetails::parse(&entry.details.0) {
10468                            Ok(value) => value,
10469                            Err(message) => {
10470                                return SyncOutcome::Failed {
10471                                    details: None,
10472                                    error_code: "sync.invalid_request".to_owned(),
10473                                    message,
10474                                    recommended_action: None,
10475                                };
10476                            }
10477                        };
10478                        details.insert(entry.op_index, parsed);
10479                    }
10480                }
10481                Frame::PushResult {
10482                    client_commit_id,
10483                    status,
10484                    results,
10485                    ..
10486                } if pushed_ids.contains(client_commit_id.as_str())
10487                    && Self::push_result_is_final(*status, results) =>
10488                {
10489                    last_final_push_result_id = Some(client_commit_id.clone());
10490                }
10491                _ => {}
10492            }
10493        }
10494        let mut frames = response.frames.into_iter().peekable();
10495        match frames.next() {
10496            Some(Frame::RespHeader {
10497                required_schema_version,
10498                latest_schema_version,
10499                log_epoch,
10500                reset_required,
10501            }) => {
10502                if let Some(required) = required_schema_version {
10503                    // §1.6 schema-floor response: nothing else is processed;
10504                    // stop syncing and surface the upgrade requirement.
10505                    let floor = SchemaFloor {
10506                        required_schema_version: Some(required),
10507                        latest_schema_version,
10508                    };
10509                    if let Err(message) = self.set_schema_floor(Some(floor.clone())) {
10510                        return SyncOutcome::Failed {
10511                            details: None,
10512                            error_code: "storage.failed".to_owned(),
10513                            message,
10514                            recommended_action: None,
10515                        };
10516                    }
10517                    report.schema_floor = Some(floor);
10518                    return SyncOutcome::Ok(report);
10519                }
10520                if reset_required {
10521                    if frames.next().is_some() {
10522                        return SyncOutcome::Failed {
10523                            details: None,
10524                            error_code: "client.invalid_host_response".to_owned(),
10525                            message: "log-epoch reset response contains body frames".to_owned(),
10526                            recommended_action: None,
10527                        };
10528                    }
10529                    match self.run_log_epoch_reset(&log_epoch) {
10530                        Ok(resets) => {
10531                            report.resets = resets;
10532                            return SyncOutcome::Ok(report);
10533                        }
10534                        Err(message) => {
10535                            return SyncOutcome::Failed {
10536                                details: None,
10537                                error_code: "sync.local_corrupt".to_owned(),
10538                                message,
10539                                recommended_action: None,
10540                            };
10541                        }
10542                    }
10543                }
10544                let stored_epoch = match self.get_meta(LOG_EPOCH_KEY) {
10545                    Ok(stored) => stored,
10546                    Err(message) => {
10547                        return SyncOutcome::Failed {
10548                            details: None,
10549                            error_code: "storage.failed".to_owned(),
10550                            message,
10551                            recommended_action: None,
10552                        };
10553                    }
10554                };
10555                // §2.1 adoption: the epoch is stored before any section applies.
10556                if stored_epoch.is_none() {
10557                    if let Err(message) = self.set_meta(LOG_EPOCH_KEY, &log_epoch) {
10558                        return SyncOutcome::Failed {
10559                            details: None,
10560                            error_code: "storage.failed".to_owned(),
10561                            message,
10562                            recommended_action: None,
10563                        };
10564                    }
10565                } else if stored_epoch.as_deref() != Some(log_epoch.as_str()) {
10566                    return SyncOutcome::Failed {
10567                        details: None,
10568                        error_code: "client.invalid_host_response".to_owned(),
10569                        message: "server changed logEpoch without requiring a reset".to_owned(),
10570                        recommended_action: None,
10571                    };
10572                }
10573            }
10574            _ => {
10575                return SyncOutcome::Failed {
10576                    details: None,
10577                    error_code: "sync.invalid_request".to_owned(),
10578                    message: "response does not start with RESP_HEADER".to_owned(),
10579                    recommended_action: None,
10580                };
10581            }
10582        }
10583
10584        if let Err(message) = self.begin_coalesced_apply() {
10585            return SyncOutcome::Failed {
10586                details: None,
10587                error_code: "storage.failed".into(),
10588                message,
10589                recommended_action: None,
10590            };
10591        }
10592        let mut failure: Option<(String, String, Option<String>, Option<Value>)> = None;
10593        // §4.5 client application: the units whose persisted echo a live
10594        // change must match, fixed at LIVE_START after every SUB_END persisted.
10595        let mut live: Option<(LiveStatus, String, Vec<UnitRecord>)> = None;
10596        let mut live_ended = false;
10597        while let Some(frame) = frames.next() {
10598            match frame {
10599                frame @ Frame::PushResult { .. } => {
10600                    let successful = matches!(
10601                        &frame,
10602                        Frame::PushResult {
10603                            status: PushStatus::Applied | PushStatus::Cached,
10604                            ..
10605                        }
10606                    );
10607                    let mut results = vec![frame];
10608                    if successful {
10609                        while matches!(
10610                            frames.peek(),
10611                            Some(Frame::PushResult {
10612                                status: PushStatus::Applied | PushStatus::Cached,
10613                                ..
10614                            })
10615                        ) {
10616                            if let Some(next) = frames.next() {
10617                                results.push(next);
10618                            }
10619                        }
10620                    }
10621                    if self
10622                        .handle_push_results(
10623                            &results,
10624                            &pushed_ids,
10625                            &rejection_details_by_commit,
10626                            &mut report,
10627                            last_final_push_result_id.as_deref(),
10628                        )
10629                        .is_err()
10630                    {
10631                        failure = Some((
10632                            "client.outcome_persistence_failed".to_owned(),
10633                            "local commit outcome could not be persisted".to_owned(),
10634                            None,
10635                            None,
10636                        ));
10637                        break;
10638                    }
10639                }
10640                Frame::PushResultDetails { .. } => {}
10641                Frame::SubStart {
10642                    id,
10643                    status,
10644                    reason_code,
10645                    bootstrap,
10646                    fenced,
10647                } => {
10648                    // §1.4 rule 5: an ERROR closes the section; its body still
10649                    // applied, its SUB_END values are never persisted.
10650                    let mut body = Vec::new();
10651                    let mut sub_end: Option<(i64, Option<String>)> = None;
10652                    let mut error: Option<Frame> = None;
10653                    for inner in frames.by_ref() {
10654                        match inner {
10655                            Frame::SubEnd {
10656                                next_cursor,
10657                                bootstrap_state,
10658                            } => {
10659                                sub_end = Some((next_cursor, bootstrap_state.map(|r| r.0)));
10660                                break;
10661                            }
10662                            inner @ Frame::Error { .. } => {
10663                                error = Some(inner);
10664                                break;
10665                            }
10666                            Frame::Unknown { .. } => {}
10667                            other => body.push(other),
10668                        }
10669                    }
10670                    let ended = sub_end.is_some();
10671                    let section = SectionStart {
10672                        id,
10673                        status,
10674                        reason_code,
10675                        bootstrap,
10676                        fenced,
10677                    };
10678                    let completed = match self.process_section(
10679                        transport,
10680                        &section,
10681                        body,
10682                        sub_end,
10683                        meta,
10684                        &mut report,
10685                    ) {
10686                        Err(SectionError::Abort(code, message)) => {
10687                            failure = Some((code, message, None, None));
10688                            break;
10689                        }
10690                        Err(SectionError::Transport(error)) => {
10691                            failure = Some((error.code, error.message, None, error.details));
10692                            break;
10693                        }
10694                        Ok(completed) => completed,
10695                        Err(_) => false,
10696                    };
10697                    if ended {
10698                        // The counters stay: `complete` and `failed` report them.
10699                        // §7.7: a completed bootstrap ends with the unit total
10700                        // equal to the rows processed.
10701                        self.progress.update(|p| {
10702                            p.unit_id = None;
10703                            p.table = None;
10704                            p.segment_id = None;
10705                            if completed && p.unit_rows_total.is_some() {
10706                                p.unit_rows_total = p.unit_rows_processed;
10707                            }
10708                        });
10709                    }
10710                    match error {
10711                        Some(Frame::Error {
10712                            code,
10713                            message,
10714                            recommended_action,
10715                            details,
10716                            ..
10717                        }) => {
10718                            failure = Some(Self::error_frame_failure(
10719                                code,
10720                                message,
10721                                recommended_action,
10722                                details,
10723                            ));
10724                            break;
10725                        }
10726                        Some(_) => unreachable!("only an ERROR closes a section early"),
10727                        None if !ended => {
10728                            failure = Some((
10729                                "sync.invalid_request".to_owned(),
10730                                "unit section without SUB_END".to_owned(),
10731                                None,
10732                                None,
10733                            ));
10734                            break;
10735                        }
10736                        None => {}
10737                    }
10738                }
10739                Frame::LiveStart {
10740                    status,
10741                    reason_code,
10742                } => {
10743                    let receivers = match self.stored(load_units(&self.conn)) {
10744                        Ok(units) => units
10745                            .into_iter()
10746                            .filter(|unit| {
10747                                unit.status == UnitStatus::Active
10748                                    && unit.echo.is_some()
10749                                    && !unit.bootstrapping()
10750                            })
10751                            .collect(),
10752                        Err(message) => {
10753                            failure = Some(("storage.failed".to_owned(), message, None, None));
10754                            break;
10755                        }
10756                    };
10757                    live = Some((status, reason_code, receivers));
10758                }
10759                Frame::Commit {
10760                    commit_seq,
10761                    tables,
10762                    changes,
10763                    ..
10764                } => {
10765                    let Some((LiveStatus::Active, _, receivers)) = &live else {
10766                        continue;
10767                    };
10768                    let receivers = receivers.clone();
10769                    match self.apply_live_commit(
10770                        &receivers,
10771                        &tables,
10772                        changes,
10773                        commit_seq,
10774                        AppliedServerCommitSource::Pull,
10775                    ) {
10776                        Ok(applied) => report.commits_applied += u32::from(applied),
10777                        Err(error) => {
10778                            failure = Some((error.code, error.message, None, error.details));
10779                            break;
10780                        }
10781                    }
10782                }
10783                Frame::LiveEnd {
10784                    through_seq,
10785                    echo_digest,
10786                } => {
10787                    let Some((status, reason_code, _)) = live.take() else {
10788                        continue;
10789                    };
10790                    live_ended = true;
10791                    live = Some((status, String::new(), Vec::new()));
10792                    if let Err(message) = self.finish_live_section(
10793                        status,
10794                        &reason_code,
10795                        through_seq,
10796                        echo_digest,
10797                        &meta.registration_digest,
10798                        &mut report,
10799                    ) {
10800                        failure = Some(("storage.failed".to_owned(), message, None, None));
10801                        break;
10802                    }
10803                }
10804                Frame::Lease {
10805                    lease_id,
10806                    expires_at_ms,
10807                } => {
10808                    // §7.3.5: persist the opaque lease; a fresh lease clears
10809                    // any prior lease error (the outage/revocation is over).
10810                    if let Err(message) = self.set_lease_state(Some(LeaseState {
10811                        lease_id: Some(lease_id),
10812                        expires_at_ms: Some(expires_at_ms),
10813                        error_code: None,
10814                    })) {
10815                        failure = Some(("storage.failed".to_owned(), message, None, None));
10816                        break;
10817                    }
10818                }
10819                Frame::Error {
10820                    code,
10821                    message,
10822                    recommended_action,
10823                    details,
10824                    ..
10825                } => {
10826                    // §1.6: the whole request failed; already-completed
10827                    // units keep their applied data and cursors.
10828                    failure = Some(Self::error_frame_failure(
10829                        code,
10830                        message,
10831                        recommended_action,
10832                        details,
10833                    ));
10834                    break;
10835                }
10836                Frame::Unknown { .. } => {}
10837                // §1.6: a building server's keepalive carries nothing to apply.
10838                Frame::Keepalive => {}
10839                _ => {
10840                    failure = Some((
10841                        "sync.invalid_request".to_owned(),
10842                        "unexpected frame in response".to_owned(),
10843                        None,
10844                        None,
10845                    ));
10846                    break;
10847                }
10848            }
10849        }
10850
10851        let applied = match failure {
10852            Some(failure) => Err(failure),
10853            // Local apply boundaries already reconciled their affected overlay.
10854            // Refuse round success if any remaining dirty work fails to
10855            // reconcile. §4.8 E1: the push half may have drained commits that
10856            // pinned rows of a shrunk window unit, so retry deferred evictions.
10857            None => self
10858                .rebuild_overlay_if_dirty()
10859                .and_then(|()| self.drain_pending_evictions())
10860                .map_err(|message| ("storage.failed".to_owned(), message, None, None)),
10861        };
10862        // §1.4 rule 4: frames completed before a failure stay committed; a
10863        // failed COMMIT of the coalesced transaction fails the round.
10864        if let Err(message) = self.finish_coalesced_apply() {
10865            return SyncOutcome::Failed {
10866                details: None,
10867                error_code: "storage.failed".into(),
10868                message,
10869                recommended_action: None,
10870            };
10871        }
10872        if let Err((error_code, message, recommended_action, details)) = applied {
10873            return SyncOutcome::Failed {
10874                details,
10875                error_code,
10876                message,
10877                recommended_action,
10878            };
10879        }
10880        let catching_up = match self.stored(load_units(&self.conn)) {
10881            Ok(units) => units
10882                .into_iter()
10883                .filter(|unit| unit.status == UnitStatus::Active && unit.cursor.is_some())
10884                .map(|unit| unit.id)
10885                .collect::<Vec<_>>(),
10886            Err(message) => {
10887                return SyncOutcome::Failed {
10888                    details: None,
10889                    error_code: "storage.failed".into(),
10890                    message,
10891                    recommended_action: None,
10892                }
10893            }
10894        };
10895        // §7.1: a response without LIVE_END, one answered `unregistered` or
10896        // `reset`, or a unit still catching up leaves sync-needed raised;
10897        // after `unregistered` the next round starts at once.
10898        let status = live.map(|(status, _, _)| status);
10899        if !live_ended || status != Some(LiveStatus::Active) || !catching_up.is_empty() {
10900            self.set_sync_needed(true, status == Some(LiveStatus::Unregistered));
10901        }
10902        self.ack_after_pull(transport);
10903        // §7.4.5: the reset is over once the first post-reset pull round
10904        // leaves no unit catching up: the tables are rebuilt and current.
10905        if self.upgrading && catching_up.is_empty() {
10906            self.set_upgrading(false);
10907        }
10908        report.bootstrapping = catching_up;
10909        SyncOutcome::Ok(report)
10910    }
10911
10912    /// §1.6 / §10.1: the failure an in-band `ERROR` frame reports.
10913    fn error_frame_failure(
10914        code: String,
10915        message: String,
10916        recommended_action: String,
10917        details: Option<RawJson>,
10918    ) -> (String, String, Option<String>, Option<Value>) {
10919        let recommended_action = (!recommended_action.is_empty()).then_some(recommended_action);
10920        let details = details
10921            .and_then(|details| serde_json::from_str::<Value>(&details.0).ok())
10922            .filter(Value::is_object);
10923        (code, message, recommended_action, details)
10924    }
10925
10926    /// §4.5 at `LIVE_END` of a pull: join rule J for an `active` section, the
10927    /// §4.6 replica reset for `reset`, nothing for `unregistered`; then the
10928    /// replica cursor, the echo digest and the digest of the list the server
10929    /// now stores.
10930    fn finish_live_section(
10931        &mut self,
10932        status: LiveStatus,
10933        reason_code: &str,
10934        through_seq: i64,
10935        echo_digest: Option<[u8; 32]>,
10936        registration_digest: &str,
10937        report: &mut SyncReport,
10938    ) -> Result<(), String> {
10939        let rollback = self.capture();
10940        let resets = report.resets.len();
10941        self.begin_observation("syncular_live_end")?;
10942        let finished = (|| {
10943            let mut batch = ChangeAccumulator::default();
10944            let before = self.stored(replica_cursor(&self.conn))?;
10945            let mut cursor = if status == LiveStatus::Unregistered {
10946                before
10947            } else {
10948                -1
10949            };
10950            let joined = before.max(through_seq);
10951            for unit in self.stored(load_units(&self.conn))? {
10952                if unit.status != UnitStatus::Active || unit.bootstrapping() {
10953                    continue;
10954                }
10955                match status {
10956                    // §4.6 replica reset: every live unit bootstraps again;
10957                    // post-bootstrap units keep their cursors.
10958                    LiveStatus::Reset if unit.cursor.is_none() => {
10959                        self.record_unit_windows(&mut batch, &unit)?;
10960                        report.resets.push(unit.id.clone());
10961                        self.stored(save_unit(
10962                            &self.conn,
10963                            &UnitRecord {
10964                                reason_code: Some(reason_code.to_owned()),
10965                                cursor: Some(-1),
10966                                seeded: Vec::new(),
10967                                ..unit
10968                            },
10969                        ))?;
10970                    }
10971                    // §4.5 join rule J.
10972                    LiveStatus::Active => {
10973                        let next = unit.cursor.unwrap_or(joined).max(through_seq);
10974                        if next >= joined {
10975                            cursor = joined;
10976                        }
10977                        if unit.cursor.is_some() {
10978                            // A post-bootstrap unit that joins live transitions.
10979                            if next >= joined {
10980                                self.record_unit_windows(&mut batch, &unit)?;
10981                            }
10982                            self.stored(save_unit(
10983                                &self.conn,
10984                                &UnitRecord {
10985                                    cursor: (next < joined).then_some(next),
10986                                    ..unit
10987                                },
10988                            ))?;
10989                        }
10990                    }
10991                    _ => {}
10992                }
10993            }
10994            self.set_meta(REPLICA_CURSOR_KEY, &cursor.to_string())?;
10995            self.set_meta(
10996                ECHO_DIGEST_KEY,
10997                &echo_digest
10998                    .map(|digest| bytes_to_hex(&digest))
10999                    .unwrap_or_default(),
11000            )?;
11001            if status == LiveStatus::Unregistered {
11002                self.delete_meta(REGISTERED_DIGEST_KEY)?;
11003            } else {
11004                self.set_meta(REGISTERED_DIGEST_KEY, registration_digest)?;
11005            }
11006            self.finish_observation("syncular_live_end", batch)
11007        })();
11008        if finished.is_err() {
11009            self.rollback_observation("syncular_live_end");
11010            self.restore(rollback);
11011            report.resets.truncate(resets);
11012        }
11013        finished
11014    }
11015
11016    // -- push results (§6.3, §7.2) ------------------------------------------------
11017
11018    fn handle_push_results(
11019        &mut self,
11020        frames: &[Frame],
11021        pushed_ids: &HashSet<&str>,
11022        rejection_details_by_commit: &HashMap<String, BTreeMap<i32, RejectionDetails>>,
11023        report: &mut SyncReport,
11024        last_final_push_result_id: Option<&str>,
11025    ) -> Result<(), String> {
11026        self.begin_observation("syncular_push_results")?;
11027        let rollback = self.capture();
11028        let conflict_count = self.conflicts.len();
11029        let applied_count = report.applied.len();
11030        let rejected_count = report.rejected.len();
11031        let retryable_count = report.retryable.len();
11032        let mut drained = Vec::new();
11033        let mut batch = ChangeAccumulator::default();
11034        let persisted = (|| {
11035            for frame in frames {
11036                let Frame::PushResult {
11037                    client_commit_id,
11038                    status,
11039                    results,
11040                    commit_seq,
11041                } = frame
11042                else {
11043                    return Err("unexpected acknowledgement frame".to_owned());
11044                };
11045                if !pushed_ids.contains(client_commit_id.as_str()) {
11046                    continue;
11047                }
11048                let Some(index) = self
11049                    .outbox
11050                    .iter()
11051                    .position(|commit| commit.client_commit_id == *client_commit_id)
11052                else {
11053                    continue;
11054                };
11055                let status = *status;
11056                let rejection_details = rejection_details_by_commit.get(client_commit_id);
11057                let operations = self.outbox[index].ops.clone();
11058                match status {
11059                    PushStatus::Applied | PushStatus::Cached => {
11060                        // §7.2: a lost ack replays as `cached` — proceed as if the
11061                        // ack had arrived.
11062                        let sequence =
11063                            commit_seq.ok_or_else(|| "ACK lacks a commit sequence".to_owned())?;
11064                        let affected: HashSet<_> = operations
11065                            .iter()
11066                            .map(|op| (op.table.as_str(), op.row_id.as_str()))
11067                            .collect();
11068                        let prior = self.acknowledged_operations(Some(&affected), None)?;
11069                        for (op_index, operation) in operations.iter().enumerate() {
11070                            let delivered: bool = self.conn.query_row("SELECT EXISTS(SELECT 1 FROM _syncular_row_deliveries WHERE tbl=?1 AND id=?2 AND commit_seq>=?3)", rusqlite::params![operation.table, operation.row_id, sequence], |row| row.get(0))
11071                                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11072                            if delivered {
11073                                continue;
11074                            }
11075                            let table = self
11076                                .schema
11077                                .table(&operation.table)
11078                                .ok_or_else(|| "sync.unknown_table".to_owned())?;
11079                            let mut intended: Map<String, Value> = self
11080                                .stored_row(table, &operation.row_id, true)?
11081                                .map(|(row, _)| {
11082                                    table
11083                                        .columns
11084                                        .iter()
11085                                        .zip(&row)
11086                                        .map(|(column, value)| {
11087                                            (column.name.clone(), column_value_to_json(value))
11088                                        })
11089                                        .collect()
11090                                })
11091                                .unwrap_or_default();
11092                            let mut scope_image = intended.clone();
11093                            for op in prior
11094                                .iter()
11095                                .chain(
11096                                    self.failed_commits
11097                                        .iter()
11098                                        .flat_map(|(commit, _)| &commit.ops),
11099                                )
11100                                .chain(
11101                                    self.outbox
11102                                        .iter()
11103                                        .take(index)
11104                                        .flat_map(|commit| &commit.ops),
11105                                )
11106                                .chain(operations.iter().take(op_index + 1))
11107                            {
11108                                if op.table != operation.table || op.row_id != operation.row_id {
11109                                    continue;
11110                                }
11111                                if let Some(values) = &op.values {
11112                                    intended.extend(values.clone());
11113                                } else {
11114                                    scope_image = intended.clone();
11115                                    intended.clear();
11116                                }
11117                            }
11118                            self.conn.execute("INSERT INTO _syncular_acked_rows(commit_id,idx,tbl,id,commit_seq,op_json,intent_json) VALUES (?1,?2,?3,?4,?5,?6,?7)",
11119                                rusqlite::params![client_commit_id, op_index as i64, operation.table, operation.row_id, sequence,
11120                                    serde_json::to_string(&CommitOperation::from(operation)).map_err(|_| "sync.local_corrupt".to_owned())?,
11121                                    serde_json::to_string(if operation.upsert { &intended } else { &scope_image }).map_err(|_| "sync.local_corrupt".to_owned())?])
11122                                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11123                        }
11124                        let journal_results = results
11125                            .iter()
11126                            .map(|result| {
11127                                let op_index = match result {
11128                                    OpResult::Applied { op_index }
11129                                    | OpResult::Conflict { op_index, .. }
11130                                    | OpResult::Error { op_index, .. } => *op_index,
11131                                };
11132                                CommitOperationOutcome::Applied { op_index }
11133                            })
11134                            .collect::<Vec<_>>();
11135                        let outcome_status = if status == PushStatus::Applied {
11136                            CommitOutcomeStatus::Applied
11137                        } else {
11138                            CommitOutcomeStatus::Cached
11139                        };
11140                        let persisted = self
11141                            .persist_commit_outcome(
11142                                client_commit_id,
11143                                outcome_status,
11144                                &journal_results,
11145                                None,
11146                            )
11147                            .and_then(|()| self.delete_outbox_persisted(client_commit_id));
11148                        persisted?;
11149                        self.sync_needed = true;
11150                        batch.status = true;
11151                        batch.outcomes = true;
11152                    }
11153                    PushStatus::Rejected => {
11154                        if results.iter().any(|result| {
11155                            matches!(
11156                                result,
11157                                OpResult::Error {
11158                                    code,
11159                                    retryable: true,
11160                                    ..
11161                                } if code == "sync.idempotency_cache_miss"
11162                            )
11163                        }) {
11164                            // §6.3/§7.2: a serving failure, not an outcome — keep the
11165                            // exact commit queued for an identical retry.
11166                            report.retryable.push(client_commit_id.to_owned());
11167                            continue;
11168                        }
11169
11170                        let mut journal_results = Vec::with_capacity(results.len());
11171                        let mut conflicts = Vec::new();
11172                        let mut rejections = Vec::new();
11173                        for result in results {
11174                            match result {
11175                                OpResult::Applied { op_index } => {
11176                                    journal_results.push(CommitOperationOutcome::Applied {
11177                                        op_index: *op_index,
11178                                    });
11179                                }
11180                                OpResult::Conflict {
11181                                    op_index,
11182                                    code,
11183                                    message,
11184                                    server_version,
11185                                    server_row,
11186                                    conflict_columns: conflict_columns_bitmap,
11187                                } => {
11188                                    let operation = operations
11189                                        .get(*op_index as usize)
11190                                        .map(CommitOperation::from);
11191                                    let (table, row_id) = operation
11192                                        .as_ref()
11193                                        .map(|op| (op.table.clone(), op.row_id.clone()))
11194                                        .unwrap_or_default();
11195                                    let server_row_json = self
11196                                        .schema
11197                                        .table(&table)
11198                                        .and_then(|t| {
11199                                            decode_row_bytes(t, server_row, &self.encryption)
11200                                                .ok()
11201                                                .map(|(row, _)| (t, row))
11202                                        })
11203                                        .map(|(t, row)| {
11204                                            let mut map = Map::new();
11205                                            for (i, column) in t.columns.iter().enumerate() {
11206                                                map.insert(
11207                                                    column.name.clone(),
11208                                                    column_value_to_json(
11209                                                        row.get(i).unwrap_or(&None),
11210                                                    ),
11211                                                );
11212                                            }
11213                                            map
11214                                        })
11215                                        .unwrap_or_default();
11216                                    // §6.3: decode the presence-layout bitmap
11217                                    // into the marked column names.
11218                                    let conflict_columns = self
11219                                        .schema
11220                                        .table(&table)
11221                                        .map(|t| {
11222                                            t.columns
11223                                                .iter()
11224                                                .enumerate()
11225                                                .filter(|(index, _)| {
11226                                                    conflict_columns_bitmap
11227                                                        .get(index / 8)
11228                                                        .is_some_and(|byte| {
11229                                                            byte & (1 << (index % 8)) != 0
11230                                                        })
11231                                                })
11232                                                .map(|(_, column)| column.name.clone())
11233                                                .collect::<Vec<_>>()
11234                                        })
11235                                        .unwrap_or_default();
11236                                    let conflict = ConflictRecord {
11237                                        client_commit_id: client_commit_id.to_owned(),
11238                                        op_index: *op_index,
11239                                        table,
11240                                        row_id,
11241                                        code: code.clone(),
11242                                        message: message.clone(),
11243                                        server_version: *server_version,
11244                                        server_row: server_row_json,
11245                                        conflict_columns,
11246                                        operation,
11247                                    };
11248                                    journal_results.push(CommitOperationOutcome::Conflict {
11249                                        conflict: conflict.clone(),
11250                                    });
11251                                    conflicts.push(conflict);
11252                                }
11253                                OpResult::Error {
11254                                    op_index,
11255                                    code,
11256                                    message,
11257                                    retryable,
11258                                } => {
11259                                    let rejection = RejectionRecord {
11260                                        client_commit_id: client_commit_id.to_owned(),
11261                                        op_index: *op_index,
11262                                        code: code.clone(),
11263                                        message: message.clone(),
11264                                        retryable: *retryable,
11265                                        details: rejection_details
11266                                            .and_then(|details| details.get(op_index))
11267                                            .cloned(),
11268                                        operation: operations
11269                                            .get(*op_index as usize)
11270                                            .map(CommitOperation::from),
11271                                    };
11272                                    journal_results.push(CommitOperationOutcome::Error {
11273                                        rejection: rejection.clone(),
11274                                    });
11275                                    rejections.push(rejection);
11276                                }
11277                            }
11278                        }
11279                        if self.retain_failed_commits {
11280                            self.retain_failed_commit(client_commit_id, &operations)?;
11281                        }
11282                        let outcome_status = if conflicts.is_empty() {
11283                            CommitOutcomeStatus::Rejected
11284                        } else {
11285                            CommitOutcomeStatus::Conflict
11286                        };
11287                        self.leave_through(client_commit_id);
11288                        let persisted = self
11289                            .persist_commit_outcome(
11290                                client_commit_id,
11291                                outcome_status,
11292                                &journal_results,
11293                                Some(&operations),
11294                            )
11295                            .and_then(|()| self.delete_outbox_persisted(client_commit_id));
11296                        persisted?;
11297                        batch.conflicts = !conflicts.is_empty();
11298                        batch.rejections = !rejections.is_empty();
11299                        batch.status = true;
11300                        batch.outcomes = true;
11301                        self.conflicts.extend(conflicts);
11302                        self.rejections.extend(rejections);
11303                    }
11304                }
11305                drained.push(self.outbox.remove(index));
11306                if batch.status {
11307                    for operation in &operations {
11308                        if !self.record_row_scopes(
11309                            &mut batch,
11310                            &operation.table,
11311                            &operation.row_id,
11312                            false,
11313                        ) {
11314                            batch.table(&operation.table);
11315                        }
11316                    }
11317                }
11318                match status {
11319                    PushStatus::Applied | PushStatus::Cached => {
11320                        report.applied.push(client_commit_id.to_owned())
11321                    }
11322                    PushStatus::Rejected => report.rejected.push(client_commit_id.to_owned()),
11323                }
11324            }
11325            if batch.outcomes && frames.iter().any(|frame| matches!(frame, Frame::PushResult { client_commit_id, .. } if Some(client_commit_id.as_str()) == last_final_push_result_id)) {
11326                self.prune_commit_outcomes()?;
11327            }
11328            self.reconcile_rows(&drained)?;
11329            self.rebuild_overlay_if_dirty()?;
11330            self.finish_observation("syncular_push_results", batch)
11331        })();
11332        if let Err(error) = persisted {
11333            self.rollback_observation("syncular_push_results");
11334            self.restore(rollback);
11335            report.applied.truncate(applied_count);
11336            report.rejected.truncate(rejected_count);
11337            report.retryable.truncate(retryable_count);
11338            return Err(error);
11339        }
11340        if !rollback.sync_needed && self.sync_needed {
11341            self.sync_intent_queue.push_back(SyncIntent::Interactive);
11342        }
11343        report.conflicts += (self.conflicts.len() - conflict_count) as u32;
11344        Ok(())
11345    }
11346
11347    fn push_result_is_final(status: PushStatus, results: &[OpResult]) -> bool {
11348        status != PushStatus::Rejected
11349            || !results.iter().any(|result| {
11350                matches!(
11351                    result,
11352                    OpResult::Error {
11353                        code,
11354                        retryable: true,
11355                        ..
11356                    } if code == "sync.idempotency_cache_miss"
11357                )
11358            })
11359    }
11360
11361    // -- unit sections and the live section ------------------------------------------
11362
11363    /// One unit section (§4.4): apply its segments, then persist its
11364    /// `SUB_END` (§4.6 reset, §3.3 revocation and purge, the echo, cursor and
11365    /// resume token). A section of a unit the app released while the round was
11366    /// in flight is skipped; a fail-closed first page fails the unit and skips
11367    /// the rest of its section (§5.6). Returns whether its `SUB_END` completed
11368    /// a bootstrap (§7.7).
11369    fn process_section(
11370        &mut self,
11371        transport: &mut dyn Transport,
11372        start: &SectionStart,
11373        body: Vec<Frame>,
11374        sub_end: Option<(i64, Option<String>)>,
11375        meta: &RequestMeta,
11376        report: &mut SyncReport,
11377    ) -> Result<bool, SectionError> {
11378        let storage = |message| SectionError::Abort("storage.failed".to_owned(), message);
11379        let unit = self
11380            .stored(get_unit(&self.conn, &start.id))
11381            .map_err(storage)?
11382            .filter(|unit| unit.status == UnitStatus::Active);
11383        // §7.7: a section boundary ends the previous payload; the section's
11384        // UNIT_EXTENT starts the unit counters in the same snapshot.
11385        let extent = match (&unit, body.first()) {
11386            (
11387                Some(_),
11388                Some(Frame::UnitExtent {
11389                    rows_total,
11390                    rows_done,
11391                }),
11392            ) => u64::try_from(*rows_total)
11393                .ok()
11394                .zip(u64::try_from(*rows_done).ok()),
11395            _ => None,
11396        };
11397        self.progress.update(|p| {
11398            p.phase = ProgressPhase::Import;
11399            p.unit_id = unit.as_ref().map(|unit| unit.id.clone());
11400            p.unit_rows_total = extent.map(|(total, _)| total);
11401            p.unit_rows_processed = extent.map(|(_, done)| done);
11402            p.table = None;
11403            p.segment_id = None;
11404            p.bytes_received = 0;
11405            p.bytes_total = None;
11406            p.rows_processed = 0;
11407            p.rows_total = None;
11408            p.import_write_ms = None;
11409            p.import_commit_ms = None;
11410            p.download_ms = None;
11411        });
11412        let Some(unit) = unit else {
11413            return Ok(false);
11414        };
11415        let echo: Vec<EchoRecord> = start
11416            .fenced
11417            .iter()
11418            .map(|record| EchoRecord {
11419                table: record.table.clone(),
11420                status: record.status.name().to_owned(),
11421                scopes: record.scopes.iter().cloned().collect(),
11422            })
11423            .collect();
11424        // §5.6: rows earlier attempts at this position applied.
11425        let applied_record = self
11426            .stored(applied_rows(&self.conn, &unit.id))
11427            .map_err(storage)?;
11428        // §5.6: a resumed bootstrap keeps the tables it already seeded.
11429        let mut seeded: BTreeSet<String> = if unit.bootstrap_state.is_none() {
11430            BTreeSet::new()
11431        } else {
11432            unit.seeded.iter().cloned().collect()
11433        };
11434        let applied = (|| {
11435            for frame in body {
11436                match frame {
11437                    Frame::SegmentInline { payload } => {
11438                        let segment = decode_rows_segment(&payload).map_err(|e| {
11439                            SectionError::Abort(e.code.as_str().to_owned(), e.detail)
11440                        })?;
11441                        self.progress.update(|p| {
11442                            p.phase = ProgressPhase::Import;
11443                            p.unit_id = Some(unit.id.clone());
11444                            p.table = Some(segment.table.clone());
11445                            p.segment_id = None;
11446                            p.bytes_received = payload.len() as u64;
11447                            p.bytes_total = Some(payload.len() as u64);
11448                            p.rows_processed = 0;
11449                            p.rows_total =
11450                                Some(segment.blocks.iter().map(|block| block.len() as u64).sum());
11451                            p.import_write_ms = None;
11452                            p.import_commit_ms = None;
11453                            p.download_ms = None;
11454                        });
11455                        let (pair, clear, effective) =
11456                            self.segment_pair(&unit, &echo, &seeded, &segment.table)?;
11457                        report.segment_rows_applied +=
11458                            self.apply_segment(&pair, &segment, clear, &effective, &unit.id)?;
11459                        seeded.insert(segment.table);
11460                    }
11461                    Frame::SegmentRef {
11462                        segment_id,
11463                        byte_length,
11464                        media_type,
11465                        table,
11466                        row_count,
11467                        as_of_commit_seq,
11468                        scope_digest,
11469                        row_cursor,
11470                        next_row_cursor,
11471                        url,
11472                        url_expires_at_ms,
11473                        ..
11474                    } => {
11475                        // §4.2: reject a descriptor whose mediaType was not
11476                        // advertised — never skip or guess.
11477                        let advertised = match media_type {
11478                            MediaType::Rows => {
11479                                meta.accept & ACCEPT_EXTERNAL_ROWS != 0
11480                                    || meta.accept & ACCEPT_INLINE_ROWS != 0
11481                            }
11482                            MediaType::Sqlite => meta.accept & ACCEPT_SQLITE != 0,
11483                        };
11484                        if !advertised {
11485                            return Err(SectionError::Abort(
11486                                "sync.invalid_request".to_owned(),
11487                                format!(
11488                                    "SEGMENT_REF mediaType {} was not advertised in accept (§4.2)",
11489                                    media_type.name()
11490                                ),
11491                            ));
11492                        }
11493                        // §5.6 applied-segment rule: a partly applied image
11494                        // already ran its table's first-page clear.
11495                        let resumed = applied_record.get(&segment_id).copied();
11496                        if resumed.is_some() {
11497                            seeded.insert(table.clone());
11498                        }
11499                        if resumed == Some(row_count) {
11500                            // §7.7: an earlier attempt imported this payload;
11501                            // its rows still count toward the unit.
11502                            self.progress.update(|p| {
11503                                p.phase = ProgressPhase::Import;
11504                                p.unit_id = Some(unit.id.clone());
11505                                p.table = Some(table.clone());
11506                                p.segment_id = Some(segment_id.clone());
11507                                p.bytes_received = 0;
11508                                p.bytes_total = None;
11509                                p.rows_processed = 0;
11510                                p.rows_total = u64::try_from(row_count).ok();
11511                                p.import_write_ms = None;
11512                                p.import_commit_ms = None;
11513                                p.download_ms = None;
11514                            });
11515                            self.progress.update(|p| {
11516                                p.rows_processed = u64::try_from(row_count).unwrap_or(0)
11517                            });
11518                            continue;
11519                        }
11520                        if meta
11521                            .deferred
11522                            .contains(&(unit.id.clone(), segment_id.clone()))
11523                        {
11524                            return Err(SectionError::Deferred);
11525                        }
11526                        self.progress.update(|p| {
11527                            p.phase = ProgressPhase::Download;
11528                            p.unit_id = Some(unit.id.clone());
11529                            p.table = Some(table.clone());
11530                            p.segment_id = Some(segment_id.clone());
11531                            p.bytes_received = 0;
11532                            p.bytes_total = u64::try_from(byte_length).ok();
11533                            p.rows_processed = 0;
11534                            p.rows_total = u64::try_from(row_count).ok();
11535                            p.import_write_ms = None;
11536                            p.import_commit_ms = None;
11537                            p.download_ms = None;
11538                        });
11539                        let observer = self.progress.clone();
11540                        let mut on_progress = |bytes| observer.update(|p| p.bytes_received = bytes);
11541                        // §7.7: from the request's start to its last body byte.
11542                        let requested = std::time::Instant::now();
11543                        let bytes = if let Some(url) = url {
11544                            // §5.4: a url-carrying descriptor MUST be fetched
11545                            // from that URL; failure invalidates the whole
11546                            // descriptor (no fall-through to §5.5 — re-pull
11547                            // recovers, §1.4 rule 5).
11548                            if meta.accept & ACCEPT_SIGNED_URLS == 0 {
11549                                return Err(SectionError::Abort(
11550                                    "sync.invalid_request".to_owned(),
11551                                    "SEGMENT_REF carries a url but accept bit 3 was not advertised (§5.4)"
11552                                        .to_owned(),
11553                                ));
11554                            }
11555                            // §5.4: MUST NOT start a fetch at/past expiry.
11556                            if url_expires_at_ms.is_some_and(|exp| {
11557                                exp <= transport
11558                                    .segment_fetch_started_at(&url)
11559                                    .unwrap_or_else(|| self.clock_now_ms())
11560                            }) {
11561                                return Err(SectionError::Abort(
11562                                    "sync.segment_expired".to_owned(),
11563                                    format!(
11564                                        "signed URL for segment {segment_id} expired before fetch — re-pull mints fresh descriptors (§5.4)"
11565                                    ),
11566                                ));
11567                            }
11568                            transport
11569                                .fetch_url(
11570                                    &url,
11571                                    u64::try_from(byte_length).unwrap_or(0),
11572                                    &mut on_progress,
11573                                )
11574                                .map_err(|e| self.segment_fetch_failed(e))?
11575                        } else {
11576                            // §5.5: the owning unit's scope map, each value a one-element list.
11577                            let requested_scopes_json =
11578                                canonical_scope_json(&unit_scope_lists(&unit.scopes));
11579                            transport
11580                                .download_segment(
11581                                    &SegmentRequest {
11582                                        segment_id: segment_id.clone(),
11583                                        table: table.clone(),
11584                                        requested_scopes_json,
11585                                        byte_length: u64::try_from(byte_length).unwrap_or(0),
11586                                    },
11587                                    &mut on_progress,
11588                                )
11589                                .map_err(|e| {
11590                                    // §5.5: access changed since the response;
11591                                    // the next round's SUB_START settles the unit.
11592                                    if e.code == "sync.forbidden" {
11593                                        SectionError::Refused
11594                                    } else {
11595                                        self.segment_fetch_failed(e)
11596                                    }
11597                                })?
11598                        };
11599                        let download_ms = u64::try_from(requested.elapsed().as_millis()).ok();
11600                        // §5.4: the descriptor's byteLength caps the body before
11601                        // §5.1 verifies the content address; the client discards
11602                        // the segment and re-pulls on either failure.
11603                        if bytes.len() as i64 > byte_length {
11604                            self.schedule_background_retry();
11605                            return Err(SectionError::Abort(
11606                                "sync.invalid_request".to_owned(),
11607                                "segment exceeds its byteLength".to_owned(),
11608                            ));
11609                        }
11610                        on_progress(bytes.len() as u64);
11611                        let digest = Sha256::digest(&bytes);
11612                        let expected = segment_id
11613                            .strip_prefix("sha256:")
11614                            .unwrap_or(segment_id.as_str());
11615                        if bytes_to_hex(&digest) != expected {
11616                            // §5.1: the client discards the segment and re-pulls.
11617                            self.schedule_background_retry();
11618                            return Err(SectionError::Abort(
11619                                "sync.invalid_request".to_owned(),
11620                                "segment bytes do not match the content address (§5.1)".to_owned(),
11621                            ));
11622                        }
11623                        self.progress.update(|p| {
11624                            p.phase = ProgressPhase::Import;
11625                            p.download_ms = download_ms;
11626                        });
11627                        if media_type == MediaType::Sqlite {
11628                            // §5.3: a range image keeps its position in the resume
11629                            // token; a descriptor row cursor is invalid.
11630                            if row_cursor.is_some() || next_row_cursor.is_some() {
11631                                return Err(SectionError::Abort(
11632                                    "sync.invalid_request".to_owned(),
11633                                    "sqlite segments are whole-table: rowCursor/nextRowCursor must be absent (§5.3)"
11634                                        .to_owned(),
11635                                ));
11636                            }
11637                            let (pair, clear, effective) =
11638                                self.segment_pair(&unit, &echo, &seeded, &table)?;
11639                            report.segment_rows_applied += self.apply_sqlite_segment(
11640                                &pair,
11641                                &bytes,
11642                                clear,
11643                                &effective,
11644                                &unit.id,
11645                                &segment_id,
11646                                resumed.unwrap_or(0),
11647                                row_count,
11648                                as_of_commit_seq,
11649                                &scope_digest,
11650                            )?;
11651                            seeded.insert(table);
11652                        } else {
11653                            let segment = decode_rows_segment(&bytes).map_err(|e| {
11654                                SectionError::Abort(e.code.as_str().to_owned(), e.detail)
11655                            })?;
11656                            let (pair, clear, effective) =
11657                                self.segment_pair(&unit, &echo, &seeded, &segment.table)?;
11658                            report.segment_rows_applied +=
11659                                self.apply_segment(&pair, &segment, clear, &effective, &unit.id)?;
11660                            seeded.insert(segment.table);
11661                            // An image records its rows with each chunk.
11662                            self.stored(record_applied_rows(
11663                                &self.conn,
11664                                &unit.id,
11665                                &segment_id,
11666                                row_count,
11667                            ))
11668                            .map_err(storage)?;
11669                        }
11670                    }
11671                    Frame::UnitExtent { .. } => {}
11672                    _ => {
11673                        return Err(SectionError::Abort(
11674                            "sync.invalid_request".to_owned(),
11675                            "unexpected frame inside a unit section".to_owned(),
11676                        ));
11677                    }
11678                }
11679            }
11680            Ok(())
11681        })();
11682        match applied {
11683            Ok(()) => {}
11684            // The unit keeps catching up with its cursor unpersisted.
11685            Err(SectionError::Refused | SectionError::Deferred) => return Ok(false),
11686            Err(SectionError::FailClosed) => {
11687                // §5.6: the failure is unit-local; the rest of the response
11688                // still applies and the failed unit leaves the list.
11689                self.begin_observation("syncular_section_failure")
11690                    .map_err(storage)?;
11691                let failed = (|| {
11692                    let mut batch = ChangeAccumulator::default();
11693                    self.record_unit_windows(&mut batch, &unit)?;
11694                    batch.status = true;
11695                    self.stored(save_unit(
11696                        &self.conn,
11697                        &UnitRecord {
11698                            status: UnitStatus::Failed,
11699                            reason_code: Some("sync.scope_revoked".to_owned()),
11700                            restriction: None,
11701                            ..unit.clone()
11702                        },
11703                    ))?;
11704                    self.finish_observation("syncular_section_failure", batch)
11705                })();
11706                if let Err(message) = failed {
11707                    self.rollback_observation("syncular_section_failure");
11708                    return Err(storage(message));
11709                }
11710                report.failed.push(unit.id);
11711                return Ok(false);
11712            }
11713            Err(error) => return Err(error),
11714        }
11715        let Some((next_cursor, bootstrap_state)) = sub_end else {
11716            return Ok(false);
11717        };
11718        let completes = start.bootstrap && bootstrap_state.is_none();
11719        let rollback = self.capture();
11720        let counts = (
11721            report.resets.len(),
11722            report.revoked.len(),
11723            report.failed.len(),
11724        );
11725        self.begin_observation("syncular_sub_end")
11726            .map_err(storage)?;
11727        let finished = self
11728            .finish_section(start, echo, next_cursor, bootstrap_state, seeded, report)
11729            .and_then(|batch| {
11730                self.rebuild_overlay_if_dirty()?;
11731                self.finish_observation("syncular_sub_end", batch)
11732            });
11733        if let Err(message) = finished {
11734            self.rollback_observation("syncular_sub_end");
11735            self.restore(rollback);
11736            report.resets.truncate(counts.0);
11737            report.revoked.truncate(counts.1);
11738            report.failed.truncate(counts.2);
11739            return Err(storage(message));
11740        }
11741        Ok(completes)
11742    }
11743
11744    /// §5.6: the table, first-page flag and effective scopes of one segment
11745    /// of `unit`'s section. A first page outside the unit's restriction ends it.
11746    #[allow(clippy::type_complexity)]
11747    fn segment_pair(
11748        &self,
11749        unit: &UnitRecord,
11750        echo: &[EchoRecord],
11751        seeded: &BTreeSet<String>,
11752        name: &str,
11753    ) -> Result<(TableSchema, bool, Vec<(String, Vec<String>)>), SectionError> {
11754        let table = self.schema.table(name).cloned().ok_or_else(|| {
11755            SectionError::Abort(
11756                "sync.schema_mismatch".to_owned(),
11757                format!("segment table {name:?} is not in the client schema"),
11758            )
11759        })?;
11760        let effective = covers(&table, &unit.scopes)
11761            .then(|| pair_scopes(&unit.scopes, name, Some(echo)))
11762            .flatten()
11763            .ok_or_else(|| {
11764                SectionError::Abort(
11765                    "sync.invalid_request".to_owned(),
11766                    "a segment names no active pair of its unit".to_owned(),
11767                )
11768            })?;
11769        let first_page = !seeded.contains(name);
11770        // §5.6: a first page of a table outside the restriction is a whole
11771        // bootstrap from a server that predates RESTRICT; the restriction ends
11772        // before the clear runs.
11773        if first_page
11774            && unit
11775                .restriction
11776                .as_ref()
11777                .is_some_and(|restriction| !restriction.tables.iter().any(|t| t == name))
11778        {
11779            self.conn
11780                .execute(
11781                    "UPDATE _syncular_units SET restriction=NULL WHERE id=?1",
11782                    [&unit.id],
11783                )
11784                .map_err(|error| {
11785                    SectionError::Abort(
11786                        "storage.failed".to_owned(),
11787                        Self::sqlite_failure(&self.storage_failure, error),
11788                    )
11789                })?;
11790        }
11791        Ok((table, first_page, effective))
11792    }
11793
11794    /// §4.4 `SUB_END` of an active, revoked or reset section, inside the
11795    /// caller's observation: a reset discards cursor, resume token and
11796    /// first-page record and keeps the echo; a revoked pair purges by its last
11797    /// echo (§3.3); otherwise the echo replaces the persisted one, a revoked
11798    /// fenced record that turns active again re-bootstraps the unit, and a
11799    /// bootstrap section persists its pin, resume token and seeded tables.
11800    fn finish_section(
11801        &mut self,
11802        start: &SectionStart,
11803        echo: Vec<EchoRecord>,
11804        next_cursor: i64,
11805        bootstrap_state: Option<String>,
11806        seeded: BTreeSet<String>,
11807        report: &mut SyncReport,
11808    ) -> Result<ChangeAccumulator, String> {
11809        #[cfg(feature = "bench-internals")]
11810        let _phase = self.benchmark_phases.start(Phase::CursorPersist);
11811        let mut batch = ChangeAccumulator::default();
11812        // §4.4: SUB_END writes only into a unit that is still registered.
11813        let Some(unit) = self
11814            .stored(get_unit(&self.conn, &start.id))?
11815            .filter(|unit| unit.status == UnitStatus::Active)
11816        else {
11817            return Ok(batch);
11818        };
11819        self.record_unit_windows(&mut batch, &unit)?;
11820        if start.status == SubStatus::Reset {
11821            // §4.6: staleness, never a purge; the rows stay until the
11822            // bootstrap replaces them.
11823            report.resets.push(unit.id.clone());
11824            self.stored(save_unit(
11825                &self.conn,
11826                &UnitRecord {
11827                    reason_code: Some(start.reason_code.clone()),
11828                    cursor: Some(-1),
11829                    bootstrap_state: None,
11830                    seeded: Vec::new(),
11831                    restriction: None,
11832                    ..unit
11833                },
11834            ))?;
11835            return Ok(batch);
11836        }
11837        let revoked = start.status == SubStatus::Revoked;
11838        let mut units = None;
11839        let mut failed = false;
11840        let mut rearmed = false;
11841        for table in self.schema.tables.clone() {
11842            if !covers(&table, &unit.scopes) {
11843                continue;
11844            }
11845            let last = unit
11846                .echo
11847                .as_deref()
11848                .and_then(|last| pair_scopes(&unit.scopes, &table.name, Some(last)));
11849            let next = (!revoked)
11850                .then(|| pair_scopes(&unit.scopes, &table.name, Some(&echo)))
11851                .flatten();
11852            // §3.3: a revoked fenced record that turns active again re-bootstraps.
11853            rearmed |= unit.echo.is_some() && last.is_none() && next.is_some();
11854            // §3.3: purge a pair the response revokes, keyed on the echo the
11855            // client persisted while the pair was active.
11856            if let (Some(last), None) = (&last, &next) {
11857                let units = match units {
11858                    Some(ref units) => units,
11859                    None => units.insert(self.stored(load_units(&self.conn))?),
11860                };
11861                let owners = unit_owners(units, &table, &unit.id);
11862                failed |= !self.purge_pair(&mut batch, &table, last, &owners)?;
11863            }
11864        }
11865        if revoked || failed {
11866            if revoked {
11867                report.revoked.push(unit.id.clone());
11868            }
11869            if failed {
11870                report.failed.push(unit.id.clone());
11871            }
11872            batch.status = true;
11873            self.stored(save_unit(
11874                &self.conn,
11875                &UnitRecord {
11876                    status: if failed {
11877                        UnitStatus::Failed
11878                    } else {
11879                        UnitStatus::Revoked
11880                    },
11881                    reason_code: Some(if failed {
11882                        "sync.scope_revoked".to_owned()
11883                    } else {
11884                        start.reason_code.clone()
11885                    }),
11886                    cursor: Some(-1),
11887                    bootstrap_state: None,
11888                    seeded: Vec::new(),
11889                    echo: None,
11890                    restriction: None,
11891                    ..unit
11892                },
11893            ))?;
11894            return Ok(batch);
11895        }
11896        // §3.3: the server accepted the unit, so a later refusal re-arms once.
11897        self.window_armed.remove(&unit.id);
11898        let completed = start.bootstrap && !rearmed && bootstrap_state.is_none();
11899        let (cursor, bootstrap_state, seeded) = if rearmed {
11900            (Some(-1), None, Vec::new())
11901        } else if start.bootstrap {
11902            let seeded = if bootstrap_state.is_none() {
11903                Vec::new()
11904            } else {
11905                seeded.into_iter().collect()
11906            };
11907            (Some(next_cursor), bootstrap_state, seeded)
11908        } else {
11909            (
11910                unit.cursor,
11911                unit.bootstrap_state.clone(),
11912                unit.seeded.clone(),
11913            )
11914        };
11915        self.stored(save_unit(
11916            &self.conn,
11917            &UnitRecord {
11918                reason_code: None,
11919                echo: Some(echo.clone()),
11920                cursor,
11921                bootstrap_state,
11922                seeded,
11923                // §7.4.3: the restriction ends when the unit re-bootstraps or
11924                // completes its bootstrap.
11925                restriction: unit.restriction.clone().filter(|_| !rearmed && !completed),
11926                ..unit.clone()
11927            },
11928        ))?;
11929        if !completed {
11930            return Ok(batch);
11931        }
11932        // §7.1: a completed bootstrap covers acknowledged intent of its pairs
11933        // at or below its pin. The intent or the bootstrapped row proves the
11934        // pair: a patch omits its scope columns, and the base row it merged
11935        // over may be gone (a §7.4.4 reset before the ACK).
11936        for table in self.schema.tables.clone() {
11937            let Some(effective) = covers(&table, &unit.scopes)
11938                .then(|| pair_scopes(&unit.scopes, &table.name, Some(&echo)))
11939                .flatten()
11940            else {
11941                continue;
11942            };
11943            let mut statement = self
11944                .conn
11945                .prepare("SELECT id,intent_json FROM _syncular_acked_rows WHERE tbl=?1 AND commit_seq<=?2")
11946                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11947            let rows = statement
11948                .query_map(rusqlite::params![table.name, next_cursor], |row| {
11949                    Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
11950                })
11951                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11952            let mut covered = HashSet::new();
11953            for row in rows {
11954                let (id, intent) =
11955                    row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11956                let values: Map<String, Value> =
11957                    serde_json::from_str(&intent).map_err(|_| "sync.local_corrupt".to_owned())?;
11958                let base = self.stored_row(&table, &id, true)?.map(|(row, _)| {
11959                    table
11960                        .columns
11961                        .iter()
11962                        .zip(&row)
11963                        .map(|(column, value)| (column.name.clone(), column_value_to_json(value)))
11964                        .collect()
11965                });
11966                if [Some(values), base]
11967                    .iter()
11968                    .flatten()
11969                    .any(|values| owns_local_row(&table, &effective, &[], values))
11970                {
11971                    covered.insert(id);
11972                }
11973            }
11974            drop(statement);
11975            for id in covered {
11976                self.conn
11977                    .execute(
11978                        "DELETE FROM _syncular_acked_rows WHERE tbl=?1 AND id=?2 AND commit_seq<=?3",
11979                        rusqlite::params![table.name, id, next_cursor],
11980                    )
11981                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11982                self.overlay_dirty.table(&table.name);
11983                batch.table(&table.name);
11984            }
11985        }
11986        Ok(batch)
11987    }
11988
11989    /// §3.3: purge one revoked pair inside the caller's observation: delete
11990    /// the rows matching its last effective scopes that no owner holds, drop
11991    /// the retained intent and every pending commit that provably writes into
11992    /// them, and delete now-unauthorized blob bodies. `Ok(false)` when the
11993    /// table has no local scope-column mapping (fail closed: nothing deleted).
11994    fn purge_pair(
11995        &mut self,
11996        batch: &mut ChangeAccumulator,
11997        table: &TableSchema,
11998        last: &[(String, Vec<String>)],
11999        owners: &[Vec<(String, Vec<String>)>],
12000    ) -> Result<bool, String> {
12001        if local_scope_predicate(table, last, owners).is_err() {
12002            return Ok(false);
12003        }
12004        for commit in self.drop_failed_commits(|name, values| {
12005            name == table.name && owns_local_row(table, last, owners, values)
12006        })? {
12007            batch.conflicts = true;
12008            batch.rejections = true;
12009            batch.outcomes = true;
12010            for operation in commit.ops {
12011                batch.table(&operation.table);
12012            }
12013        }
12014        if !self.purge_scope_rows(&table.name, last, owners)? {
12015            return Err("storage.failed: the revoked scope purge failed".to_owned());
12016        }
12017        self.record_scope_map(batch, &table.name, last);
12018        if self.drop_doomed_outbox(table, last, owners)? {
12019            batch.status = true;
12020            batch.rejections = true;
12021            batch.outcomes = true;
12022        }
12023        // §5.9.7 B2: revocation deletes now-unauthorized blob bodies.
12024        self.delete_unreferenced_cached_blobs()?;
12025        Ok(true)
12026    }
12027
12028    /// §4.5 client application: apply one live-section or delta `COMMIT`
12029    /// with only the changes that match the persisted echo of a receiving
12030    /// unit; every applied change then goes through the version guard.
12031    /// Returns whether any change of the frame applied.
12032    fn apply_live_commit(
12033        &mut self,
12034        receivers: &[UnitRecord],
12035        tables: &[String],
12036        changes: Vec<ssp2::model::Change>,
12037        commit_seq: i64,
12038        source: AppliedServerCommitSource,
12039    ) -> Result<bool, TransportError> {
12040        let changes: Vec<ssp2::model::Change> = changes
12041            .into_iter()
12042            .filter(|change| {
12043                // An unknown table fails loud in the apply below.
12044                let Some(table) = tables
12045                    .get(change.table_index as usize)
12046                    .and_then(|name| self.schema.table(name))
12047                else {
12048                    return true;
12049                };
12050                receivers.iter().any(|unit| {
12051                    covers(table, &unit.scopes)
12052                        && pair_scopes(&unit.scopes, &table.name, unit.echo.as_deref()).is_some_and(
12053                            |scopes| {
12054                                scopes.iter().all(|(variable, values)| {
12055                                    change
12056                                        .scopes
12057                                        .iter()
12058                                        .find(|(key, _)| key == variable)
12059                                        .is_some_and(|(_, value)| values.contains(value))
12060                                })
12061                            },
12062                        )
12063                })
12064            })
12065            .collect();
12066        if changes.is_empty() {
12067            return Ok(false);
12068        }
12069        let affected_tables = changes
12070            .iter()
12071            .filter_map(|change| tables.get(change.table_index as usize))
12072            .cloned()
12073            .collect::<BTreeSet<_>>();
12074        let previous_batches = self.change_queue.len();
12075        self.apply_commit_frame(tables, &changes, commit_seq)?;
12076        if self.change_queue.len() > previous_batches {
12077            if let Some(batch) = self.change_queue.back_mut() {
12078                batch
12079                    .applied_commits
12080                    .extend(
12081                        affected_tables
12082                            .into_iter()
12083                            .map(|table| AppliedServerCommit {
12084                                table,
12085                                commit_seq,
12086                                source,
12087                            }),
12088                    );
12089            }
12090        }
12091        Ok(true)
12092    }
12093
12094    // Both pull and realtime frames use the same durable observation boundary.
12095    fn apply_commit_frame(
12096        &mut self,
12097        tables: &[String],
12098        changes: &[ssp2::model::Change],
12099        sequence: i64,
12100    ) -> Result<(), TransportError> {
12101        #[cfg(feature = "bench-internals")]
12102        let _phase = self.benchmark_phases.start(Phase::CommitApply);
12103        let rollback = self.capture();
12104        self.coalesce_unit(changes.len())
12105            .and_then(|()| self.begin_observation("syncular_commit"))
12106            .map_err(|message| TransportError::new("storage.failed", message))?;
12107        let applied = (|| {
12108            let mut batch = ChangeAccumulator::default();
12109            self.record_commit_changes(&mut batch, tables, changes);
12110            // §7.1 chained base: a change names the version an acknowledged own
12111            // commit wrote; pending upserts chained on it move to that version.
12112            for change in changes {
12113                let Some(table) = tables.get(change.table_index as usize) else {
12114                    continue;
12115                };
12116                let acknowledged = self
12117                    .conn
12118                    .prepare_cached("SELECT op_json FROM _syncular_acked_rows WHERE tbl=?1 AND id=?2 AND commit_seq=?3")
12119                    .and_then(|mut statement| {
12120                        statement
12121                            .query_map(rusqlite::params![table, change.row_id, sequence], |row| row.get::<_, String>(0))?
12122                            .collect::<Result<Vec<_>, _>>()
12123                    })
12124                    .map_err(|error| TransportError::new("storage.failed", Self::sqlite_failure(&self.storage_failure, error)))?
12125                    .iter()
12126                    .map(|op| serde_json::from_str::<CommitOperation>(op).map(OutboxOp::from))
12127                    .collect::<Result<Vec<_>, _>>()
12128                    .map_err(|_| TransportError::new("storage.failed", "sync.local_corrupt: invalid acknowledged operation".to_owned()))?;
12129                for index in 0..self.outbox.len() {
12130                    if !self.outbox[index]
12131                        .ops
12132                        .iter()
12133                        .any(|op| acknowledged.iter().any(|earlier| chains_on(earlier, op)))
12134                    {
12135                        continue;
12136                    }
12137                    let commit = Arc::make_mut(&mut self.outbox[index]);
12138                    for op in &mut commit.ops {
12139                        if acknowledged.iter().any(|earlier| chains_on(earlier, op)) {
12140                            op.base_version = Some(change.row_version);
12141                        }
12142                    }
12143                    let ops = serde_json::to_string(
12144                        &commit
12145                            .ops
12146                            .iter()
12147                            .map(CommitOperation::from)
12148                            .collect::<Vec<_>>(),
12149                    )
12150                    .map_err(|_| {
12151                        TransportError::new(
12152                            "storage.failed",
12153                            "sync.local_corrupt: unencodable outbox".to_owned(),
12154                        )
12155                    })?;
12156                    let id = commit.client_commit_id.clone();
12157                    self.conn
12158                        .execute(
12159                            "UPDATE _syncular_outbox SET ops_json=?1 WHERE commit_id=?2",
12160                            rusqlite::params![ops, id],
12161                        )
12162                        .map_err(|error| {
12163                            TransportError::new(
12164                                "storage.failed",
12165                                Self::sqlite_failure(&self.storage_failure, error),
12166                            )
12167                        })?;
12168                }
12169            }
12170            {
12171                let storage_failed = |error| {
12172                    TransportError::new(
12173                        "storage.failed",
12174                        Self::sqlite_failure(&self.storage_failure, error),
12175                    )
12176                };
12177                let pinned: HashSet<(&str, &str)> = self
12178                    .outbox
12179                    .iter()
12180                    .flat_map(|commit| &commit.ops)
12181                    .map(|op| (op.table.as_str(), op.row_id.as_str()))
12182                    .collect();
12183                for change in changes {
12184                    let table = tables.get(change.table_index as usize).ok_or_else(|| {
12185                        TransportError::new(
12186                            "sync.invalid_request",
12187                            "change tableIndex out of range".to_owned(),
12188                        )
12189                    })?;
12190                    if pinned.contains(&(table.as_str(), change.row_id.as_str())) {
12191                        self.conn.prepare_cached("INSERT INTO _syncular_row_deliveries(tbl,id,commit_seq) VALUES (?1,?2,?3) ON CONFLICT(tbl,id) DO UPDATE SET commit_seq=MAX(commit_seq,excluded.commit_seq)")
12192                            .and_then(|mut statement| statement.execute(rusqlite::params![table, change.row_id, sequence]))
12193                            .map_err(storage_failed)?;
12194                    }
12195                    self.conn.prepare_cached("DELETE FROM _syncular_acked_rows WHERE tbl=?1 AND id=?2 AND commit_seq<=?3")
12196                        .and_then(|mut statement| statement.execute(rusqlite::params![table, change.row_id, sequence]))
12197                        .map_err(storage_failed)?;
12198                }
12199            }
12200            self.apply_commit_changes(tables, changes)?;
12201            self.rebuild_overlay_if_dirty()
12202                .map_err(|message| TransportError::new("storage.failed", message))?;
12203            self.finish_observation("syncular_commit", batch)
12204                .map_err(|message| TransportError::new("storage.failed", message))
12205        })();
12206        if applied.is_err() {
12207            self.rollback_observation("syncular_commit");
12208            self.restore(rollback);
12209        }
12210        applied
12211    }
12212
12213    fn apply_commit_changes(
12214        &mut self,
12215        tables: &[String],
12216        changes: &[ssp2::model::Change],
12217    ) -> Result<(), TransportError> {
12218        // A clean overlay can reconcile changed primary keys independently
12219        // when their tables have no secondary unique constraints. Such a
12220        // constraint can change whether another row's write succeeds, so a
12221        // table with one and any local intent takes the table rebuild.
12222        let changed_tables: BTreeSet<&str> = changes
12223            .iter()
12224            .filter_map(|change| tables.get(change.table_index as usize))
12225            .map(String::as_str)
12226            .collect();
12227        let mut mirror_visible = !self.overlay_dirty.get();
12228        for name in &changed_tables {
12229            if mirror_visible
12230                && self
12231                    .schema
12232                    .table(name)
12233                    .is_some_and(|table| table.indexes.iter().any(|index| index.unique))
12234            {
12235                let (pending, protected) = self
12236                    .table_intent(name)
12237                    .map_err(|message| TransportError::new("storage.failed", message))?;
12238                mirror_visible = !pending && !protected;
12239            }
12240        }
12241        for change in changes {
12242            let table_name = tables.get(change.table_index as usize).ok_or_else(|| {
12243                TransportError::new(
12244                    "sync.invalid_request",
12245                    "change tableIndex out of range".to_owned(),
12246                )
12247            })?;
12248            let table = self.schema.table(table_name).ok_or_else(|| {
12249                TransportError::new(
12250                    "sync.schema_mismatch",
12251                    format!("change targets unknown table {table_name:?}"),
12252                )
12253            })?;
12254            let landed = match change.op {
12255                Op::Upsert => {
12256                    let payload = change.row.as_ref().ok_or_else(|| {
12257                        TransportError::new(
12258                            "sync.invalid_request",
12259                            "upsert change without row payload".to_owned(),
12260                        )
12261                    })?;
12262                    // §5.11: decrypt encrypted columns on apply, or seal the row.
12263                    let (row, sealed) = {
12264                        #[cfg(feature = "bench-internals")]
12265                        let _phase = self.benchmark_phases.start(Phase::RowDecode);
12266                        // §5.11: a decrypt failure keeps its own identity.
12267                        decode_row_bytes(table, payload, &self.encryption)?
12268                    };
12269                    let table_name = table.name.clone();
12270                    // §4.5 version guard: only a newer upsert lands.
12271                    let landed = self
12272                        .write_base_row(&table_name, &row, change.row_version, sealed.as_ref())
12273                        .map_err(|m| TransportError::new("sync.invalid_request", m))?;
12274                    if mirror_visible && landed {
12275                        self.write_row(
12276                            &visible_table(&table_name),
12277                            &table_name,
12278                            &row,
12279                            change.row_version,
12280                            sealed.as_ref(),
12281                        )
12282                        .map_err(|m| TransportError::new("sync.invalid_request", m))?;
12283                    }
12284                    landed
12285                }
12286                // §4.5 version guard: a delete at or below the local version
12287                // is skipped, a delete of an absent row is a no-op.
12288                Op::Delete => self
12289                    .delete_base_row(table_name, &change.row_id, change.row_version)
12290                    .map_err(|m| TransportError::new("sync.invalid_request", m))?,
12291            };
12292            // The change dropped the row's acknowledged intent either way
12293            // (§7.1), so the overlay of a skipped change rebuilds from the
12294            // unchanged base.
12295            self.overlay_dirty.table(table_name);
12296            if mirror_visible && !(landed && change.op == Op::Upsert) {
12297                let predicate = row_id_predicate(table);
12298                let visible = visible_table(table_name);
12299                let mut statements = vec![format!("DELETE FROM {visible} WHERE {predicate}")];
12300                if !landed {
12301                    statements.push(format!(
12302                        "INSERT INTO {visible} SELECT * FROM {} WHERE {predicate}",
12303                        base_table(table_name)
12304                    ));
12305                }
12306                for statement in &statements {
12307                    self.conn
12308                        .prepare_cached(statement)
12309                        .and_then(|mut statement| {
12310                            statement.execute(rusqlite::params![change.row_id])
12311                        })
12312                        .map_err(|error| {
12313                            TransportError::new("sync.invalid_request", error.to_string())
12314                        })?;
12315                }
12316            }
12317        }
12318        if mirror_visible {
12319            let changed_rows: HashSet<(&str, &str)> = changes
12320                .iter()
12321                .map(|change| {
12322                    (
12323                        tables[change.table_index as usize].as_str(),
12324                        change.row_id.as_str(),
12325                    )
12326                })
12327                .collect();
12328            self.replay_overlay(&changed_tables, Some(&changed_rows))
12329                .map_err(|message| TransportError::new("storage.failed", message))?;
12330            self.overlay_dirty.set(false);
12331        }
12332        Ok(())
12333    }
12334
12335    /// §5.6 segment application: validate against the generated schema,
12336    /// clear the pair's scope on the table's first page (fail closed
12337    /// without a mapping), then upsert each row with its segment-carried
12338    /// server version under the §4.5 version guard (§5.2).
12339    fn apply_segment(
12340        &mut self,
12341        table: &TableSchema,
12342        segment: &RowsSegment,
12343        first_page: bool,
12344        effective: &[(String, Vec<String>)],
12345        unit_id: &str,
12346    ) -> Result<u32, SectionError> {
12347        // §5.2: the column table validates against the generated schema —
12348        // order, names, types, nullability; mismatch is fatal. §5.11: the
12349        // server sends the WIRE types (bytes for an encrypted column), so
12350        // validate against wire_columns.
12351        let column = if segment.columns.len() != table.wire_columns.len() {
12352            Some(Value::from("count"))
12353        } else {
12354            segment
12355                .columns
12356                .iter()
12357                .zip(table.wire_columns.iter())
12358                .position(|(a, b)| a.name != b.name || a.ty != b.ty || a.nullable != b.nullable)
12359                .map(Value::from)
12360        };
12361        if segment.table != table.name
12362            || segment.schema_version != self.schema.version
12363            || column.is_some()
12364        {
12365            let mut details = Map::new();
12366            details.insert("table".to_owned(), Value::from(table.name.as_str()));
12367            if let Some(column) = column {
12368                details.insert("column".to_owned(), column);
12369            }
12370            return Err(SectionError::Transport(TransportError {
12371                code: "sync.schema_mismatch".to_owned(),
12372                message: "rows segment columns do not match the generated schema (§5.2)".to_owned(),
12373                details: Some(Value::Object(details)),
12374            }));
12375        }
12376        let mut applied = 0u32;
12377        let (mut write, mut commit) = (std::time::Duration::ZERO, std::time::Duration::ZERO);
12378        let empty = Vec::new();
12379        let blocks = if segment.blocks.is_empty() {
12380            std::slice::from_ref(&empty)
12381        } else {
12382            &segment.blocks
12383        };
12384        for (index, block) in blocks.iter().enumerate() {
12385            let clear = first_page && index == 0;
12386            if !clear && block.is_empty() {
12387                continue;
12388            }
12389            let rollback = self.capture();
12390            let (pending, protected) = self
12391                .table_intent(&table.name)
12392                .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12393            let reconcile_pending =
12394                !protected && pending && table.indexes.iter().any(|index| index.unique);
12395            let mirror_visible = !protected && !reconcile_pending;
12396            self.coalesce_unit(block.len())
12397                .and_then(|()| self.begin_observation("syncular_segment_block"))
12398                .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12399            let started = std::time::Instant::now();
12400            let outcome = (|| {
12401                self.rebuild_overlay_if_dirty()
12402                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12403                let mut changed_keys = Vec::new();
12404                let mut batch = ChangeAccumulator::default();
12405                if clear && self.clear_scope(table, effective, unit_id)? || !block.is_empty() {
12406                    batch.table(&table.name);
12407                }
12408                for (row_index, row) in block.iter().enumerate() {
12409                    let decrypted;
12410                    let mut sealed = None;
12411                    let values = if table.has_encrypted_columns() {
12412                        let mut values = row.values.clone();
12413                        sealed = crate::values::decrypt_segment_row(
12414                            table,
12415                            &mut values,
12416                            &self.encryption,
12417                        )
12418                        .map_err(SectionError::Transport)?;
12419                        decrypted = values;
12420                        &decrypted
12421                    } else {
12422                        &row.values
12423                    };
12424                    if !self
12425                        .write_base_row(&table.name, values, row.server_version, sealed.as_ref())
12426                        .map_err(|message| {
12427                            SectionError::Abort("sync.invalid_request".into(), message)
12428                        })?
12429                    {
12430                        continue;
12431                    }
12432                    if reconcile_pending {
12433                        changed_keys.push(
12434                            owned_sql_value(RowParam::Cell(&values[table.pk_index])).map_err(
12435                                |message| SectionError::Abort("storage.failed".into(), message),
12436                            )?,
12437                        );
12438                    }
12439                    if mirror_visible {
12440                        self.write_row(
12441                            &visible_table(&table.name),
12442                            &table.name,
12443                            values,
12444                            row.server_version,
12445                            sealed.as_ref(),
12446                        )
12447                        .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12448                    }
12449                    let processed = u64::from(applied) + row_index as u64 + 1;
12450                    if processed.is_multiple_of(1024) {
12451                        self.progress.update(|p| p.rows_processed = processed);
12452                    }
12453                }
12454                self.reconcile_import(table, &mut changed_keys, protected, reconcile_pending)
12455                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12456                let written = std::time::Instant::now();
12457                self.finish_observation("syncular_segment_block", batch)
12458                    .map(|()| written)
12459                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))
12460            })();
12461            let written = match outcome {
12462                Ok(written) => written,
12463                Err(error) => {
12464                    self.rollback_observation("syncular_segment_block");
12465                    self.restore(rollback);
12466                    return Err(error);
12467                }
12468            };
12469            // §7.7: a payload reports its import cost.
12470            write += written - started;
12471            commit += written.elapsed();
12472            applied += block.len() as u32;
12473            self.progress.update(|p| {
12474                p.rows_processed = u64::from(applied);
12475                p.import_write_ms = u64::try_from(write.as_millis()).ok();
12476                p.import_commit_ms = u64::try_from(commit.as_millis()).ok();
12477            });
12478            std::thread::yield_now();
12479        }
12480        self.progress
12481            .update(|p| p.rows_processed = u64::from(applied));
12482        Ok(applied)
12483    }
12484
12485    /// §5.3 sqlite-image application: validate the in-file metadata
12486    /// against the descriptor, validate column names/order against the
12487    /// generated schema, run the §5.6 first-page clear when fresh, then
12488    /// replace-or-upsert every image row with its `_syncular_version`.
12489    /// Mechanics: the image lands in a temp file read through a second
12490    /// rusqlite connection, equivalent to ATTACH + INSERT…SELECT.
12491    /// Each image chunk commits its writes and revision before readers continue.
12492    #[allow(clippy::too_many_arguments)]
12493    fn apply_sqlite_segment(
12494        &mut self,
12495        table: &TableSchema,
12496        bytes: &[u8],
12497        first_page: bool,
12498        effective: &[(String, Vec<String>)],
12499        unit_id: &str,
12500        segment_id: &str,
12501        resumed: i64,
12502        row_count: i64,
12503        as_of_commit_seq: i64,
12504        scope_digest: &str,
12505    ) -> Result<u32, SectionError> {
12506        let invalid = |detail: &str| {
12507            SectionError::Abort(
12508                "sync.invalid_request".to_owned(),
12509                format!("sqlite segment rejected: {detail} (§5.3)"),
12510            )
12511        };
12512        // §5.11: an image bypasses the decrypt seam, so a server cannot serve
12513        // one for a table with encrypted columns.
12514        if table.has_encrypted_columns() {
12515            return Err(invalid("table has encrypted columns"));
12516        }
12517
12518        // The image lands beside the replica so it shares the replica's
12519        // directory permissions and volume; an in-memory replica has no
12520        // directory and uses the system temp dir. The file is owner-only.
12521        let directory = self
12522            .previous_version_replica_path()
12523            .and_then(|replica| std::path::Path::new(&replica).parent().map(Into::into))
12524            .unwrap_or_else(std::env::temp_dir);
12525        let path = directory.join(format!(".syncular-image-{}.tmp", uuid::Uuid::new_v4()));
12526        let outcome = (|| {
12527            let mut options = std::fs::OpenOptions::new();
12528            options.write(true).create_new(true);
12529            #[cfg(unix)]
12530            std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
12531            std::io::Write::write_all(
12532                &mut options
12533                    .open(&path)
12534                    .map_err(|_| invalid("image temp file write failed"))?,
12535                bytes,
12536            )
12537            .map_err(|_| invalid("image temp file write failed"))?;
12538            let img = rusqlite::Connection::open_with_flags(
12539                &path,
12540                rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
12541            )
12542            .map_err(|_| invalid("bytes do not open as a SQLite database"))?;
12543            self.apply_sqlite_image(
12544                &img,
12545                table,
12546                first_page,
12547                effective,
12548                unit_id,
12549                segment_id,
12550                resumed,
12551                row_count,
12552                as_of_commit_seq,
12553                scope_digest,
12554            )
12555        })();
12556        let _ = std::fs::remove_file(&path);
12557        outcome
12558    }
12559
12560    #[allow(clippy::too_many_arguments)]
12561    fn apply_sqlite_image(
12562        &mut self,
12563        img: &rusqlite::Connection,
12564        table: &crate::schema::TableSchema,
12565        first_fresh_page: bool,
12566        effective: &[(String, Vec<String>)],
12567        unit_id: &str,
12568        segment_id: &str,
12569        resumed: i64,
12570        row_count: i64,
12571        as_of_commit_seq: i64,
12572        scope_digest: &str,
12573    ) -> Result<u32, SectionError> {
12574        let invalid = |detail: String| {
12575            SectionError::Abort(
12576                "sync.invalid_request".to_owned(),
12577                format!("sqlite segment rejected: {detail} (§5.3)"),
12578            )
12579        };
12580
12581        // 1. Metadata vs descriptor + client state (§5.3 rule 2; exactly
12582        //    one row).
12583        type MetaRow = (i64, String, i64, i64, String, i64, i64);
12584        let meta: MetaRow = img
12585            .query_row(
12586                "SELECT format, \"table\", \"schemaVersion\", \"asOfCommitSeq\",
12587                        \"scopeDigest\", \"rowCount\",
12588                        (SELECT count(*) FROM _syncular_segment)
12589                 FROM _syncular_segment",
12590                [],
12591                |row| {
12592                    Ok((
12593                        row.get(0)?,
12594                        row.get(1)?,
12595                        row.get(2)?,
12596                        row.get(3)?,
12597                        row.get(4)?,
12598                        row.get(5)?,
12599                        row.get(6)?,
12600                    ))
12601                },
12602            )
12603            .map_err(|_| invalid("missing or unreadable _syncular_segment metadata".to_owned()))?;
12604        let (format, meta_table, schema_version, pin, digest, meta_rows, meta_count) = meta;
12605        if meta_count != 1 {
12606            return Err(invalid(format!(
12607                "_syncular_segment must contain exactly one row, found {meta_count}"
12608            )));
12609        }
12610        if format != 1 {
12611            return Err(invalid(format!("format {format}")));
12612        }
12613        if meta_table != table.name {
12614            return Err(invalid(format!("image table {meta_table:?}")));
12615        }
12616        if schema_version != i64::from(self.schema.version) {
12617            return Err(invalid(format!("schemaVersion {schema_version}")));
12618        }
12619        if pin != as_of_commit_seq {
12620            return Err(invalid(format!("asOfCommitSeq {pin}")));
12621        }
12622        if digest != scope_digest {
12623            return Err(invalid("scopeDigest mismatch".to_owned()));
12624        }
12625        if meta_rows != row_count {
12626            return Err(invalid(format!("rowCount {meta_rows}")));
12627        }
12628
12629        // 2. Column names and order vs the generated schema (§5.3 rule 3).
12630        let mut names: Vec<String> = Vec::new();
12631        let mut primary_keys: Vec<String> = Vec::new();
12632        {
12633            let mut stmt = img
12634                .prepare(&format!("PRAGMA table_info({})", quote_ident(&table.name)))
12635                .map_err(|_| invalid("image data table missing".to_owned()))?;
12636            let mut rows = stmt
12637                .query([])
12638                .map_err(|_| invalid("image data table unreadable".to_owned()))?;
12639            while let Some(row) = rows
12640                .next()
12641                .map_err(|_| invalid("image data table unreadable".to_owned()))?
12642            {
12643                if row
12644                    .get::<_, i64>(5)
12645                    .map_err(|error| invalid(Self::sqlite_failure(&self.storage_failure, error)))?
12646                    > 0
12647                {
12648                    primary_keys.push(row.get(1).map_err(|error| {
12649                        invalid(Self::sqlite_failure(&self.storage_failure, error))
12650                    })?);
12651                }
12652                names.push(
12653                    row.get::<_, String>(1)
12654                        .map_err(|_| invalid("image data table unreadable".to_owned()))?,
12655                );
12656            }
12657        }
12658        let mut expected: Vec<&str> = table.columns.iter().map(|c| c.name.as_str()).collect();
12659        expected.push("_syncular_version");
12660        if names.len() != expected.len() || names.iter().zip(expected.iter()).any(|(a, b)| a != b) {
12661            return Err(SectionError::Transport(TransportError {
12662                code: "sync.schema_mismatch".to_owned(),
12663                message: "sqlite segment columns do not match the generated schema (§5.3)"
12664                    .to_owned(),
12665                details: Some(serde_json::json!({ "table": table.name })),
12666            }));
12667        }
12668
12669        if primary_keys != vec![table.primary_key.clone()] {
12670            return Err(invalid(
12671                "image primary key does not match generated schema".into(),
12672            ));
12673        }
12674        let actual_count: i64 = img
12675            .query_row(
12676                &format!("SELECT count(*) FROM {}", quote_ident(&table.name)),
12677                [],
12678                |row| row.get(0),
12679            )
12680            .map_err(|error| invalid(Self::sqlite_failure(&self.storage_failure, error)))?;
12681        if actual_count != row_count {
12682            return Err(invalid("image row count does not match descriptor".into()));
12683        }
12684        let insert = self.insert_row_sql(&base_table(&table.name), table);
12685        let visible_insert = self.insert_row_sql(&visible_table(&table.name), table);
12686        let column_list = names
12687            .iter()
12688            .map(|n| quote_ident(n))
12689            .collect::<Vec<_>>()
12690            .join(", ");
12691        // §5.6: an earlier attempt at this position committed the first
12692        // `resumed` rows in primary-key order; the content address pins them.
12693        let mut stmt = img
12694            .prepare(&format!(
12695                "SELECT {column_list} FROM {} ORDER BY {} LIMIT -1 OFFSET ?1",
12696                quote_ident(&table.name),
12697                quote_ident(&table.primary_key)
12698            ))
12699            .map_err(|error| invalid(Self::sqlite_failure(&self.storage_failure, error)))?;
12700        let mut rows = stmt
12701            .query([resumed])
12702            .map_err(|error| invalid(Self::sqlite_failure(&self.storage_failure, error)))?;
12703        let resumed = u32::try_from(resumed)
12704            .ok()
12705            .filter(|rows| i64::from(*rows) <= actual_count)
12706            .ok_or_else(|| invalid("applied-segment record exceeds the image".into()))?;
12707        let mut applied = resumed;
12708        let mut limit = if first_fresh_page {
12709            1024
12710        } else {
12711            self.image_chunk_rows
12712                .get(&table.name)
12713                .copied()
12714                .unwrap_or(1024)
12715        };
12716        let (mut write, mut commit) = (std::time::Duration::ZERO, std::time::Duration::ZERO);
12717        // Rows, write ms and per-row write ms of the chunk before.
12718        let mut model: Option<(u32, f64, Option<f64>)> = None;
12719        loop {
12720            let clear = applied == 0 && first_fresh_page;
12721            let rollback = self.capture();
12722            let (pending, protected) = self
12723                .table_intent(&table.name)
12724                .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12725            let reconcile_pending =
12726                !protected && pending && table.indexes.iter().any(|index| index.unique);
12727            let mirror_visible = !protected && !reconcile_pending;
12728            // §5.3: a table's first chunk holds 1,024 rows; a later range image
12729            // starts at the size its previous range reached. A later chunk holds at
12730            // least 1,024 rows, at most twice the rows of the one before and at
12731            // most 65,536. The second chunk of an image holds twice the rows of
12732            // the first. The two latest chunks whose row counts differ by at
12733            // least half the smaller split write time into a per-row and a
12734            // fixed part; while sizes repeat, the last split's per-row time
12735            // holds. A later chunk then holds the rows whose per-row time fills
12736            // the larger of 250 ms, the time from the end of the writes of the
12737            // chunk before through its COMMIT, and the fixed part. A chunk that
12738            // replays local writes holds at most 1,024.
12739            let chunk = if pending || protected {
12740                limit.min(1024)
12741            } else {
12742                limit
12743            };
12744            self.coalesce_unit(chunk as usize)
12745                .and_then(|()| self.begin_observation("syncular_image_chunk"))
12746                .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12747            let started = std::time::Instant::now();
12748            let result = (|| {
12749                self.rebuild_overlay_if_dirty()
12750                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12751                let mut changed_keys = Vec::new();
12752                let mut batch = ChangeAccumulator::default();
12753                if clear && self.clear_scope(table, effective, unit_id)? {
12754                    batch.table(&table.name);
12755                }
12756                let mut processed = 0u32;
12757                {
12758                    let mut ins = self.conn.prepare_cached(&insert).map_err(|error| {
12759                        invalid(Self::sqlite_failure(&self.storage_failure, error))
12760                    })?;
12761                    let mut mirror = if mirror_visible {
12762                        Some(self.conn.prepare_cached(&visible_insert).map_err(|error| {
12763                            invalid(Self::sqlite_failure(&self.storage_failure, error))
12764                        })?)
12765                    } else {
12766                        None
12767                    };
12768                    for _ in 0..chunk {
12769                        let Some(row) = rows.next().map_err(|error| {
12770                            invalid(Self::sqlite_failure(&self.storage_failure, error))
12771                        })?
12772                        else {
12773                            break;
12774                        };
12775                        for (i, column) in table.columns.iter().enumerate() {
12776                            let cell = row.get_ref(i).map_err(|error| {
12777                                invalid(Self::sqlite_failure(&self.storage_failure, error))
12778                            })?;
12779                            let param = image_cell_param(column, cell).map_err(invalid)?;
12780                            ins.raw_bind_parameter(i + 1, &param).map_err(|error| {
12781                                invalid(Self::sqlite_failure(&self.storage_failure, error))
12782                            })?;
12783                            if let Some(mirror) = &mut mirror {
12784                                mirror.raw_bind_parameter(i + 1, &param).map_err(|error| {
12785                                    invalid(Self::sqlite_failure(&self.storage_failure, error))
12786                                })?;
12787                            }
12788                        }
12789                        let version_index = table.columns.len();
12790                        let version: i64 = row.get(version_index).map_err(|error| {
12791                            invalid(Self::sqlite_failure(&self.storage_failure, error))
12792                        })?;
12793                        if version < 1 {
12794                            return Err(invalid("image row version must be positive".into()));
12795                        }
12796                        ins.raw_bind_parameter(version_index + 1, version)
12797                            .map_err(|error| {
12798                                invalid(Self::sqlite_failure(&self.storage_failure, error))
12799                            })?;
12800                        // §4.5 version guard: the base upsert decides.
12801                        let landed = ins.raw_execute().map_err(|error| {
12802                            invalid(Self::sqlite_failure(&self.storage_failure, error))
12803                        })? > 0;
12804                        processed += 1;
12805                        if processed.is_multiple_of(1024) && processed < chunk {
12806                            self.progress
12807                                .update(|p| p.rows_processed = u64::from(applied + processed));
12808                        }
12809                        if !landed {
12810                            continue;
12811                        }
12812                        if let Some(mirror) = &mut mirror {
12813                            mirror
12814                                .raw_bind_parameter(version_index + 1, version)
12815                                .map_err(|error| {
12816                                    invalid(Self::sqlite_failure(&self.storage_failure, error))
12817                                })?;
12818                            mirror.raw_execute().map_err(|error| {
12819                                invalid(Self::sqlite_failure(&self.storage_failure, error))
12820                            })?;
12821                        }
12822                        if reconcile_pending {
12823                            changed_keys.push(row.get::<_, SqlValue>(table.pk_index).map_err(
12824                                |error| invalid(Self::sqlite_failure(&self.storage_failure, error)),
12825                            )?);
12826                        }
12827                    }
12828                }
12829                if processed > 0 {
12830                    batch.table(&table.name);
12831                    self.overlay_dirty.table(&table.name);
12832                }
12833                self.stored(record_applied_rows(
12834                    &self.conn,
12835                    unit_id,
12836                    segment_id,
12837                    i64::from(applied + processed),
12838                ))
12839                .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12840                self.reconcile_import(table, &mut changed_keys, protected, reconcile_pending)
12841                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12842                let written = std::time::Instant::now();
12843                self.finish_observation("syncular_image_chunk", batch)
12844                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12845                Ok((processed, written))
12846            })();
12847            let (processed, written) = match result {
12848                Ok(done) => done,
12849                Err(error) => {
12850                    self.rollback_observation("syncular_image_chunk");
12851                    self.restore(rollback);
12852                    return Err(error);
12853                }
12854            };
12855            // The chunk commits before the yield, also inside a coalesced apply.
12856            let coalesced = self.coalesced.is_some();
12857            if coalesced {
12858                self.commit_coalesced_apply()
12859                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12860            }
12861            let spent = (written - started, written.elapsed());
12862            #[cfg(test)]
12863            let spent = self
12864                .image_chunk_ms
12865                .get()
12866                .map_or(spent, |(fixed, row, commit)| {
12867                    (
12868                        std::time::Duration::from_secs_f64(
12869                            (fixed + row * f64::from(processed)) / 1000.0,
12870                        ),
12871                        std::time::Duration::from_secs_f64(commit / 1000.0),
12872                    )
12873                });
12874            write += spent.0;
12875            commit += spent.1;
12876            applied += processed;
12877            let last = processed < chunk || i64::from(applied) == actual_count;
12878            // A file replica's WAL keeps its high-water size until truncated.
12879            if last && self.conn.is_autocommit() {
12880                self.conn
12881                    .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
12882                    .map_err(|error| invalid(Self::sqlite_failure(&self.storage_failure, error)))?;
12883            }
12884            if coalesced {
12885                self.begin_coalesced_apply()
12886                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12887            }
12888            self.progress.update(|p| {
12889                p.rows_processed = u64::from(applied);
12890                p.import_write_ms = u64::try_from(write.as_millis()).ok();
12891                p.import_commit_ms = u64::try_from(commit.as_millis()).ok();
12892            });
12893            let write_ms = spent.0.as_secs_f64() * 1000.0;
12894            let per_row = match model {
12895                Some((rows, before, _)) if 2 * processed.abs_diff(rows) >= processed.min(rows) => {
12896                    Some((write_ms - before) / (f64::from(processed) - f64::from(rows)))
12897                }
12898                Some((_, _, per_row)) => per_row,
12899                None => None,
12900            };
12901            model = Some((processed, write_ms, per_row));
12902            let fixed = (write_ms - per_row.unwrap_or(0.0) * f64::from(processed)).max(0.0);
12903            let budget = (spent.1.as_secs_f64() * 1000.0).max(250.0).max(fixed);
12904            std::thread::yield_now();
12905            if last {
12906                break;
12907            }
12908            // Without a positive per-row time the chunk doubles.
12909            limit = (processed * 2)
12910                .min(65_536)
12911                .min(match per_row {
12912                    Some(per_row) if per_row > 0.0 => (budget / per_row) as u32,
12913                    _ => u32::MAX,
12914                })
12915                .max(1024);
12916            self.image_chunk_rows.insert(table.name.clone(), limit);
12917        }
12918        if i64::from(applied) != actual_count {
12919            return Err(invalid(format!(
12920                "image yielded {applied} rows, expected {actual_count}"
12921            )));
12922        }
12923        Ok(applied - resumed)
12924    }
12925
12926    /// §7.1 keyed reconciliation of the rows `drained` commits touch: restore
12927    /// them from the base and replay their remaining intent. A table with a
12928    /// secondary unique index restores and replays every row with intent,
12929    /// since one row's value can admit or defer another row's write.
12930    fn reconcile_rows(&self, drained: &[Arc<OutboxCommit>]) -> Result<(), String> {
12931        let names: BTreeSet<&str> = drained
12932            .iter()
12933            .flat_map(|commit| &commit.ops)
12934            .map(|op| op.table.as_str())
12935            .collect();
12936        for name in names {
12937            let Some(table) = self.schema.table(name) else {
12938                continue;
12939            };
12940            let ops = drained.iter().flat_map(|commit| &commit.ops);
12941            let tables = BTreeSet::from([name]);
12942            let rows: HashSet<_> = ops
12943                .clone()
12944                .map(|op| (op.table.as_str(), op.row_id.as_str()))
12945                .collect();
12946            let unique = table.indexes.iter().any(|index| index.unique);
12947            let acknowledged = if unique {
12948                self.acknowledged_operations(None, Some(&tables))?
12949            } else {
12950                Vec::new()
12951            };
12952            let peers = acknowledged
12953                .iter()
12954                .chain(
12955                    self.failed_commits
12956                        .iter()
12957                        .flat_map(|(commit, _)| &commit.ops),
12958                )
12959                .chain(self.outbox.iter().flat_map(|commit| &commit.ops))
12960                .filter(|_| unique);
12961            self.restore_base_rows(table, &mut Vec::new(), peers.chain(ops.clone()))?;
12962            self.replay_overlay(&tables, (!unique).then_some(&rows))?;
12963        }
12964        Ok(())
12965    }
12966
12967    /// Whether `table` has pending outbox intent, and whether it has protected
12968    /// (acknowledged or retained failed) intent.
12969    fn table_intent(&self, table: &str) -> Result<(bool, bool), String> {
12970        let touches = |op: &OutboxOp| op.table == table;
12971        Ok((
12972            self.outbox
12973                .iter()
12974                .flat_map(|commit| &commit.ops)
12975                .any(touches),
12976            self.failed_commits
12977                .iter()
12978                .flat_map(|(commit, _)| &commit.ops)
12979                .any(touches)
12980                || self
12981                    .conn
12982                    .query_row(
12983                        "SELECT EXISTS(SELECT 1 FROM _syncular_acked_rows WHERE tbl=?1)",
12984                        [table],
12985                        |row| row.get(0),
12986                    )
12987                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?,
12988        ))
12989    }
12990
12991    /// §7.1 reconciliation after an import block or chunk. Keyed replay covers
12992    /// only pending intent, so a table with protected intent rebuilds; a
12993    /// `restore` restores the imported `keys` and every pending row first.
12994    fn reconcile_import(
12995        &mut self,
12996        table: &TableSchema,
12997        keys: &mut Vec<SqlValue>,
12998        protected: bool,
12999        restore: bool,
13000    ) -> Result<(), String> {
13001        if protected {
13002            return self.rebuild_overlay_if_dirty();
13003        }
13004        let pending = self.outbox.iter().flat_map(|commit| &commit.ops);
13005        if restore {
13006            self.restore_base_rows(table, keys, pending.clone())?;
13007        }
13008        self.apply_outbox_ops(pending.filter(|op| op.table == table.name))?;
13009        self.overlay_dirty.set(false);
13010        Ok(())
13011    }
13012
13013    /// Restore the visible rows of `keys` and of the rows `ops` touch in
13014    /// `table` from the base before the caller replays their intent. The
13015    /// caller owns the transaction and publishes its revision after replay.
13016    fn restore_base_rows<'a>(
13017        &self,
13018        table: &TableSchema,
13019        keys: &mut Vec<SqlValue>,
13020        ops: impl IntoIterator<Item = &'a OutboxOp>,
13021    ) -> Result<(), String> {
13022        let visible = visible_table(&table.name);
13023        let base = base_table(&table.name);
13024        let pk = quote_ident(&table.primary_key);
13025        let predicate = row_id_predicate(table);
13026        let mut lookup = self.conn.prepare_cached(&format!(
13027            "SELECT {pk} FROM {base} WHERE {predicate} UNION SELECT {pk} FROM {visible} WHERE {predicate}"
13028        )).map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13029        let mut deleted = HashSet::new();
13030        for op in ops.into_iter().filter(|op| op.table == table.name) {
13031            if op.upsert {
13032                if let Some(values) = &op.values {
13033                    let key = json_to_column_value(
13034                        &table.columns[table.pk_index],
13035                        values.get(&table.primary_key),
13036                    )?;
13037                    keys.push(owned_sql_value(RowParam::Cell(&key))?);
13038                }
13039            } else if deleted.insert(&op.row_id) {
13040                keys.extend(
13041                    lookup
13042                        .query_map([&op.row_id], |row| row.get::<_, SqlValue>(0))
13043                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
13044                        .collect::<Result<Vec<_>, _>>()
13045                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?,
13046                );
13047            }
13048        }
13049        // Delete the complete affected set before restoring any base value, so
13050        // old optimistic unique values cannot collide with the new server rows.
13051        for chunk in keys.chunks(400) {
13052            let holes = vec!["?"; chunk.len()].join(",");
13053            self.conn
13054                .prepare_cached(&format!("DELETE FROM {visible} WHERE {pk} IN ({holes})"))
13055                .and_then(|mut statement| statement.execute(rusqlite::params_from_iter(chunk)))
13056                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13057        }
13058        let updates = table
13059            .columns
13060            .iter()
13061            .map(|column| column.name.as_str())
13062            .chain(std::iter::once("_syncular_version"))
13063            .chain(table.sealed_columns().iter().copied())
13064            .filter(|name| *name != table.primary_key)
13065            .map(|name| {
13066                let name = quote_ident(name);
13067                format!("{name}=excluded.{name}")
13068            })
13069            .collect::<Vec<_>>()
13070            .join(",");
13071        for chunk in keys.chunks(400) {
13072            let holes = vec!["?"; chunk.len()].join(",");
13073            self.conn.prepare_cached(&format!("INSERT INTO {visible} SELECT * FROM {base} WHERE {pk} IN ({holes}) ON CONFLICT ({pk}) DO UPDATE SET {updates}"))
13074                .and_then(|mut statement| statement.execute(rusqlite::params_from_iter(chunk)))
13075                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13076        }
13077        Ok(())
13078    }
13079
13080    // -- application-authorized local purge ---------------------------------------
13081
13082    fn compile_local_data_purge(
13083        &self,
13084        input: &LocalDataPurgeInput,
13085    ) -> Result<CompiledLocalDataPurge, String> {
13086        let invalid = |message: String| format!("sync.invalid_request: {message}");
13087        if input.purge_id.is_empty()
13088            || input.purge_id.len() > 128
13089            || !is_local_operation_code_like(&input.purge_id)
13090        {
13091            return Err(invalid(
13092                "local purge purgeId must be a 1–128 character code-like identifier".to_owned(),
13093            ));
13094        }
13095        if input.targets.is_empty() || input.targets.len() > MAX_LOCAL_PURGE_TARGETS {
13096            return Err(invalid(format!(
13097                "local purge needs between 1 and {MAX_LOCAL_PURGE_TARGETS} targets"
13098            )));
13099        }
13100
13101        let mut deduplicated: BTreeMap<
13102            String,
13103            (CompiledLocalDataPurgeTarget, LocalDataPurgeTarget),
13104        > = BTreeMap::new();
13105        let mut projections = BTreeSet::new();
13106        for target in &input.targets {
13107            let (table_name, raw_selectors) = match target {
13108                LocalDataPurgeTarget::Table { table, selectors } => (table, selectors),
13109                LocalDataPurgeTarget::Projection { projection } => {
13110                    projections.insert(projection.clone());
13111                    continue;
13112                }
13113            };
13114            let table = self.schema.table(table_name).ok_or_else(|| {
13115                invalid(format!("local purge names unknown table {:?}", table_name))
13116            })?;
13117            if raw_selectors.is_empty() || raw_selectors.len() > MAX_LOCAL_PURGE_SELECTORS {
13118                return Err(invalid(format!(
13119                    "local purge target {:?} needs between 1 and {MAX_LOCAL_PURGE_SELECTORS} selectors",
13120                    table_name
13121                )));
13122            }
13123            let mut selectors = Vec::with_capacity(raw_selectors.len());
13124            let mut canonical_selectors = BTreeMap::new();
13125            for (column_name, raw_values) in raw_selectors {
13126                let Some((column_index, column)) = table
13127                    .columns
13128                    .iter()
13129                    .enumerate()
13130                    .find(|(_, column)| column.name == *column_name)
13131                else {
13132                    return Err(invalid(format!(
13133                        "local purge target {:?} names unknown column {:?}",
13134                        table_name, column_name
13135                    )));
13136                };
13137                let encrypted = table
13138                    .encrypted_columns
13139                    .iter()
13140                    .any(|candidate| candidate.index == column_index);
13141                if column.ty != ColumnType::String || encrypted {
13142                    return Err(invalid(format!(
13143                        "local purge selector {:?}.{:?} must be a plaintext string column",
13144                        table_name, column_name
13145                    )));
13146                }
13147                if raw_values.is_empty() || raw_values.len() > MAX_LOCAL_PURGE_VALUES {
13148                    return Err(invalid(format!(
13149                        "local purge selector {:?}.{:?} needs between 1 and {MAX_LOCAL_PURGE_VALUES} values",
13150                        table_name, column_name
13151                    )));
13152                }
13153                let mut values = raw_values.clone();
13154                values.sort();
13155                values.dedup();
13156                if values.iter().any(|value| {
13157                    value.is_empty()
13158                        || value.len() > MAX_LOCAL_PURGE_VALUE_LENGTH
13159                        || !is_local_operation_code_like(value)
13160                }) {
13161                    return Err(invalid(format!(
13162                        "local purge selector values must be 1–{MAX_LOCAL_PURGE_VALUE_LENGTH} character code-like identifiers"
13163                    )));
13164                }
13165                selectors.push((column_name.clone(), values.clone()));
13166                canonical_selectors.insert(column_name.clone(), values);
13167            }
13168            let canonical = LocalDataPurgeTarget::Table {
13169                table: table_name.clone(),
13170                selectors: canonical_selectors,
13171            };
13172            let key = serde_json::to_string(&canonical).map_err(|error| error.to_string())?;
13173            deduplicated.insert(
13174                key,
13175                (
13176                    CompiledLocalDataPurgeTarget {
13177                        table: table_name.clone(),
13178                        selectors,
13179                    },
13180                    canonical,
13181                ),
13182            );
13183        }
13184        let (targets, mut canonical): (Vec<_>, Vec<_>) = deduplicated.into_values().unzip();
13185        canonical.extend(
13186            projections
13187                .iter()
13188                .map(|name| LocalDataPurgeTarget::Projection {
13189                    projection: name.clone(),
13190                }),
13191        );
13192        let canonical_plan =
13193            serde_json::to_string(&canonical).map_err(|error| error.to_string())?;
13194        Ok(CompiledLocalDataPurge {
13195            targets,
13196            projections,
13197            canonical_plan,
13198        })
13199    }
13200
13201    fn local_purge_base_row_ids(
13202        &self,
13203        targets: &[CompiledLocalDataPurgeTarget],
13204    ) -> Result<BTreeMap<String, BTreeSet<String>>, String> {
13205        let mut by_table: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
13206        for target in targets {
13207            let table = self
13208                .schema
13209                .table(&target.table)
13210                .ok_or_else(|| format!("sync.invalid_request: unknown table {:?}", target.table))?;
13211            let mut clauses = Vec::with_capacity(target.selectors.len());
13212            let mut params = Vec::new();
13213            for (column, values) in &target.selectors {
13214                clauses.push(format!(
13215                    "{} IN ({})",
13216                    quote_ident(column),
13217                    values.iter().map(|_| "?").collect::<Vec<_>>().join(", ")
13218                ));
13219                params.extend(values.iter().cloned().map(SqlValue::Text));
13220            }
13221            let sql = format!(
13222                "SELECT CAST({} AS TEXT) FROM {} WHERE {}",
13223                quote_ident(&table.primary_key),
13224                base_table(&target.table),
13225                clauses.join(" AND ")
13226            );
13227            let mut statement = self
13228                .conn
13229                .prepare(&sql)
13230                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13231            let rows = statement
13232                .query_map(rusqlite::params_from_iter(params), |row| {
13233                    let value = sql_ref_to_json(&table.columns[table.pk_index], row.get_ref(0)?);
13234                    render_row_id_json(Some(&value))
13235                        .map_err(|message| rusqlite::Error::ToSqlConversionFailure(message.into()))
13236                })
13237                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13238            let ids = by_table.entry(target.table.clone()).or_default();
13239            for row in rows {
13240                ids.insert(
13241                    row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?,
13242                );
13243            }
13244        }
13245        Ok(by_table)
13246    }
13247
13248    fn local_purge_values_match(
13249        target: &CompiledLocalDataPurgeTarget,
13250        values: &Map<String, Value>,
13251    ) -> bool {
13252        target.selectors.iter().all(|(column, allowed)| {
13253            values
13254                .get(column)
13255                .and_then(Value::as_str)
13256                .is_some_and(|value| allowed.iter().any(|candidate| candidate == value))
13257        })
13258    }
13259
13260    /// Apply one host-authorized local security purge. The host MUST gate the
13261    /// corresponding subscriptions first; this primitive owns local SQLite
13262    /// cleanup and never grants/revokes server authority by itself.
13263    pub fn purge_local_data(
13264        &mut self,
13265        input: &LocalDataPurgeInput,
13266    ) -> Result<LocalDataPurgeResult, ClientError> {
13267        let CompiledLocalDataPurge {
13268            targets,
13269            projections,
13270            canonical_plan,
13271        } = self.compile_local_data_purge(input)?;
13272        for name in &projections {
13273            self.lookup_projection(name)?;
13274        }
13275        let meta_key = format!("localPurge:{}", input.purge_id);
13276        let applied_plan = self
13277            .conn
13278            .query_row(
13279                "SELECT value FROM _syncular_meta WHERE key = ?1",
13280                rusqlite::params![meta_key],
13281                |row| row.get::<_, String>(0),
13282            )
13283            .optional()
13284            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13285        if let Some(applied_plan) = applied_plan {
13286            if applied_plan != canonical_plan {
13287                return Err(format!(
13288                    "sync.invalid_request: local purge id {:?} was already used with a different plan",
13289                    input.purge_id
13290                ).into());
13291            }
13292            // A retry after an unfinished rewrite finishes it.
13293            self.require_previous_version_gone()?;
13294            self.erase_purged_pages(&meta_key)?;
13295            return Ok(LocalDataPurgeResult {
13296                already_applied: true,
13297                purged_rows: 0,
13298                dropped_commits: 0,
13299            });
13300        }
13301
13302        // RFC 0005 D7: the container file cannot be a purge target (its name is
13303        // not in the running schema), so purge drops it as a fixed step, before
13304        // any mirror row is touched and unconditionally.
13305        let _ = self.drop_previous_version();
13306
13307        let rollback = self.capture();
13308        self.begin_observation("syncular_local_purge")?;
13309        let applied = (|| -> Result<(ChangeAccumulator, LocalDataPurgeResult), String> {
13310            let mut batch = ChangeAccumulator::default();
13311            let mut purged_rows = 0;
13312            for name in &projections {
13313                purged_rows += self.clear_projection(name, None)?;
13314                batch.table(name);
13315            }
13316            if targets.is_empty() {
13317                self.set_meta(&meta_key, &canonical_plan)?;
13318                return Ok((batch, LocalDataPurgeResult { already_applied: false, purged_rows, dropped_commits: 0 }));
13319            }
13320            let row_ids = self.local_purge_base_row_ids(&targets)?;
13321            let retained_dropped = self.drop_failed_commits(|table, values| {
13322                targets.iter().any(|target| {
13323                    target.table == table && Self::local_purge_values_match(target, values)
13324                })
13325            })?;
13326            let doomed = self
13327                .outbox
13328                .iter()
13329                .filter(|commit| {
13330                    commit.ops.iter().any(|operation| {
13331                        let matching_targets = targets
13332                            .iter()
13333                            .filter(|target| target.table == operation.table)
13334                            .collect::<Vec<_>>();
13335                        if matching_targets.is_empty() {
13336                            return false;
13337                        }
13338                        if row_ids
13339                            .get(&operation.table)
13340                            .is_some_and(|ids| ids.contains(&operation.row_id))
13341                        {
13342                            return true;
13343                        }
13344                        operation.values.as_ref().is_some_and(|values| {
13345                            matching_targets
13346                                .iter()
13347                                .any(|target| Self::local_purge_values_match(target, values))
13348                        })
13349                    })
13350                })
13351                .cloned()
13352                .collect::<Vec<_>>();
13353            let doomed_ids = doomed
13354                .iter()
13355                .map(|commit| commit.client_commit_id.clone())
13356                .collect::<BTreeSet<_>>();
13357            for commit in &retained_dropped {
13358                batch.conflicts = true;
13359                batch.rejections = true;
13360                batch.outcomes = true;
13361                for operation in &commit.ops {
13362                    batch.table(&operation.table);
13363                }
13364            }
13365            let mut rejections = Vec::new();
13366            // §5.11 purge erasure: the journal keeps a dropped commit's identity and
13367            // codes, never its operations, so no purged value survives in it.
13368            for commit in &doomed {
13369                for operation in &commit.ops {
13370                    batch.table(&operation.table);
13371                    self.overlay_dirty.table(&operation.table);
13372                }
13373                let results = (0..commit.ops.len())
13374                    .map(|op_index| {
13375                        let rejection = RejectionRecord {
13376                            client_commit_id: commit.client_commit_id.clone(),
13377                            op_index: op_index as i32,
13378                            code: "client.local_data_purged".to_owned(),
13379                            message: "the commit was dropped by an application-authorized local data purge".to_owned(),
13380                            retryable: false,
13381                            details: None,
13382                            operation: None,
13383                        };
13384                        rejections.push(rejection.clone());
13385                        CommitOperationOutcome::Error { rejection }
13386                    })
13387                    .collect::<Vec<_>>();
13388                self.persist_commit_outcome(
13389                    &commit.client_commit_id,
13390                    CommitOutcomeStatus::Rejected,
13391                    &results,
13392                    None,
13393                )?;
13394                self.leave_through(&commit.client_commit_id);
13395                self.delete_outbox_persisted(&commit.client_commit_id)?;
13396            }
13397            if !doomed.is_empty() {
13398                self.outbox
13399                    .retain(|commit| !doomed_ids.contains(&commit.client_commit_id));
13400                self.rejections.extend(rejections);
13401                self.prune_commit_outcomes()?;
13402                batch.status = true;
13403                batch.rejections = true;
13404                batch.outcomes = true;
13405            }
13406
13407            // §7.3.4: a unit whose cursor claims a purged row catches up from
13408            // -1, the §3.3 rule for rows a purge removed (§4.5 C1).
13409            for unit in self.stored(load_units(&self.conn))? {
13410                if unit.status != UnitStatus::Active
13411                    || (unit.cursor == Some(-1) && unit.bootstrap_state.is_none())
13412                {
13413                    continue;
13414                }
13415                let mut holds = false;
13416                for target in &targets {
13417                    let Some(table) = self.schema.table(&target.table) else {
13418                        continue;
13419                    };
13420                    let Some((scope, scope_params)) = covers(table, &unit.scopes)
13421                        .then(|| pair_scopes(&unit.scopes, &table.name, unit.echo.as_deref()))
13422                        .flatten()
13423                        .and_then(|effective| local_scope_predicate(table, &effective, &[]).ok().flatten())
13424                    else {
13425                        continue;
13426                    };
13427                    let clauses = target
13428                        .selectors
13429                        .iter()
13430                        .map(|(column, values)| {
13431                            format!("{} IN ({})", quote_ident(column), vec!["?"; values.len()].join(", "))
13432                        })
13433                        .collect::<Vec<_>>()
13434                        .join(" AND ");
13435                    let params = target
13436                        .selectors
13437                        .iter()
13438                        .flat_map(|(_, values)| values.iter().cloned().map(SqlValue::Text))
13439                        .chain(scope_params);
13440                    holds = self
13441                        .conn
13442                        .query_row(
13443                            &format!(
13444                                "SELECT 1 FROM {} WHERE {clauses} AND {scope} LIMIT 1",
13445                                base_table(&target.table)
13446                            ),
13447                            rusqlite::params_from_iter(params),
13448                            |_| Ok(()),
13449                        )
13450                        .optional()
13451                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
13452                        .is_some();
13453                    if holds {
13454                        break;
13455                    }
13456                }
13457                if holds {
13458                    self.record_unit_windows(&mut batch, &unit)?;
13459                    batch.status = true;
13460                    self.stored(save_unit(
13461                        &self.conn,
13462                        &UnitRecord {
13463                            cursor: Some(-1),
13464                            bootstrap_state: None,
13465                            seeded: Vec::new(),
13466                            restriction: None,
13467                            ..unit
13468                        },
13469                    ))?;
13470                }
13471            }
13472
13473            for (table, ids) in &row_ids {
13474                if ids.is_empty() {
13475                    continue;
13476                }
13477                batch.table(table);
13478                self.overlay_dirty.table(table);
13479                for row_id in ids {
13480                    self.delete_base_row(table, row_id, i64::MAX)?;
13481                    purged_rows += 1;
13482                }
13483            }
13484            // §5.11 purge erasure: a journaled outcome with an operation or
13485            // conflict row the purge reaches keeps its identity, status, ids
13486            // and codes only.
13487            let touches = |table: &str, row_id: &str, values: Option<&Map<String, Value>>| {
13488                targets.iter().any(|target| {
13489                    target.table == table
13490                        && (row_ids.get(table).is_some_and(|ids| ids.contains(row_id))
13491                            || values.is_some_and(|values| {
13492                                Self::local_purge_values_match(target, values)
13493                            }))
13494                })
13495            };
13496            let entries = self
13497                .conn
13498                .prepare("SELECT client_commit_id, results_json, operations_json FROM _syncular_commit_outcomes")
13499                .and_then(|mut statement| {
13500                    statement
13501                        .query_map([], |row| {
13502                            Ok((
13503                                row.get::<_, String>(0)?,
13504                                row.get::<_, String>(1)?,
13505                                row.get::<_, Option<String>>(2)?,
13506                            ))
13507                        })?
13508                        .collect::<Result<Vec<_>, _>>()
13509                })
13510                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13511            for (client_commit_id, results_json, operations_json) in entries {
13512                let corrupt = |_| "sync.local_corrupt: persisted commit outcome is invalid".to_owned();
13513                let mut results: Vec<CommitOperationOutcome> =
13514                    serde_json::from_str(&results_json).map_err(corrupt)?;
13515                let operations: Vec<CommitOperation> = operations_json
13516                    .map(|json| serde_json::from_str(&json))
13517                    .transpose()
13518                    .map_err(corrupt)?
13519                    .unwrap_or_default();
13520                let named = operations
13521                    .iter()
13522                    .chain(results.iter().filter_map(|result| match result {
13523                        CommitOperationOutcome::Conflict { conflict } => conflict.operation.as_ref(),
13524                        CommitOperationOutcome::Error { rejection } => rejection.operation.as_ref(),
13525                        CommitOperationOutcome::Applied { .. } => None,
13526                    }))
13527                    .any(|operation| touches(&operation.table, &operation.row_id, operation.values.as_ref()))
13528                    || results.iter().any(|result| {
13529                        matches!(result, CommitOperationOutcome::Conflict { conflict }
13530                            if touches(&conflict.table, &conflict.row_id, Some(&conflict.server_row)))
13531                    });
13532                if !named {
13533                    continue;
13534                }
13535                for result in &mut results {
13536                    match result {
13537                        CommitOperationOutcome::Conflict { conflict } => {
13538                            conflict.server_row = Map::new();
13539                            conflict.conflict_columns.clear();
13540                            conflict.operation = None;
13541                        }
13542                        CommitOperationOutcome::Error { rejection } => {
13543                            rejection.details = None;
13544                            rejection.operation = None;
13545                        }
13546                        CommitOperationOutcome::Applied { .. } => {}
13547                    }
13548                }
13549                let results_json = serde_json::to_string(&results).map_err(|error| error.to_string())?;
13550                self.conn
13551                    .execute(
13552                        "UPDATE _syncular_commit_outcomes SET results_json = ?1, operations_json = NULL WHERE client_commit_id = ?2",
13553                        rusqlite::params![results_json, client_commit_id],
13554                    )
13555                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13556                batch.outcomes = true;
13557            }
13558            self.rebuild_overlay_if_dirty()?;
13559            self.delete_unreferenced_cached_blobs()?;
13560            self.conn
13561                .execute(
13562                    "INSERT INTO _syncular_meta(key, value) VALUES (?1, ?2)",
13563                    rusqlite::params![meta_key, canonical_plan],
13564                )
13565                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13566            Ok((
13567                batch,
13568                LocalDataPurgeResult {
13569                    already_applied: false,
13570                    purged_rows,
13571                    dropped_commits: doomed.len(),
13572                },
13573            ))
13574        })()
13575        .and_then(|(batch, result)| {
13576            self.finish_observation("syncular_local_purge", batch)
13577                .map(|()| result)
13578        });
13579        let result = match applied {
13580            Ok(result) => result,
13581            Err(error) => {
13582                self.rollback_observation("syncular_local_purge");
13583                self.restore(rollback);
13584                return Err(error.into());
13585            }
13586        };
13587        self.cancel_sync_round();
13588        self.require_previous_version_gone()?;
13589        self.erase_purged_pages(&meta_key)?;
13590        Ok(result)
13591    }
13592
13593    /// §5.11: the previous-version container is a copy of earlier rows; its
13594    /// removal is best-effort elsewhere, so a container that survived the
13595    /// purge fails it before the erasure is recorded.
13596    fn require_previous_version_gone(&self) -> Result<(), String> {
13597        let Some(replica_path) = self.previous_version_replica_path() else {
13598            return Ok(());
13599        };
13600        let container = crate::previous_version::previous_version_container_path(&replica_path);
13601        if std::path::Path::new(&container).exists() {
13602            self.drop_previous_version()?;
13603        }
13604        if std::path::Path::new(&container).exists() {
13605            return Err(
13606                "client.storage_failure: the previous-version container survived the purge"
13607                    .to_owned(),
13608            );
13609        }
13610        Ok(())
13611    }
13612
13613    /// §5.11 purge erasure: SQLite leaves a deleted value in the freed pages of the
13614    /// database file, FTS5 keeps a deleted document's tokens in its index
13615    /// segments, and the WAL keeps the frames written before the purge, until
13616    /// each is rewritten. The FTS5 merge drops the deleted tokens, VACUUM
13617    /// rebuilds the file from the remaining rows, and the checkpoint truncates
13618    /// the WAL. The plan's completion marker follows the checkpoint, so only a
13619    /// finished rewrite lets a retry skip it.
13620    fn erase_purged_pages(&self, meta_key: &str) -> Result<(), String> {
13621        let marker = format!("{meta_key}:erased");
13622        let done = self.stored(
13623            self.conn
13624                .query_row(
13625                    "SELECT 1 FROM _syncular_meta WHERE key = ?1",
13626                    [&marker],
13627                    |_| Ok(()),
13628                )
13629                .optional(),
13630        )?;
13631        if done.is_some() {
13632            return Ok(());
13633        }
13634        let indexes: Vec<String> = self.stored(
13635            self.conn
13636                .prepare(
13637                    "SELECT name FROM sqlite_master WHERE type = 'table' AND sql LIKE 'CREATE VIRTUAL TABLE%USING fts5%'",
13638                )
13639                .and_then(|mut statement| {
13640                    statement
13641                        .query_map([], |row| row.get(0))?
13642                        .collect::<Result<Vec<String>, _>>()
13643                }),
13644        )?;
13645        let erased = self.stored(
13646            self.conn
13647                .execute_batch("PRAGMA secure_delete = ON;")
13648                .and_then(|()| {
13649                    for index in &indexes {
13650                        let name = quote_ident(index);
13651                        self.conn.execute_batch(&format!(
13652                            "INSERT INTO {name}({name}) VALUES('optimize');"
13653                        ))?;
13654                    }
13655                    self.conn.execute_batch("VACUUM;")
13656                })
13657                .and_then(|()| {
13658                    self.conn
13659                        .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| {
13660                            row.get::<_, bool>(0)
13661                        })
13662                }),
13663        );
13664        let reset = self.stored(self.conn.execute_batch("PRAGMA secure_delete = OFF"));
13665        if erased.and_then(|busy| reset.map(|()| busy))? {
13666            return Err("client.storage_busy: WAL checkpoint is busy".to_owned());
13667        }
13668        self.set_meta(&marker, "1")
13669    }
13670
13671    /// Application-authorized recovery of the replicated projection. Unlike a
13672    /// local security purge, this retains the entire outbox, device identity,
13673    /// lease, outcomes, unit registrations, and protected bookkeeping.
13674    /// The projection reset, unit rewind, optimistic replay, and
13675    /// idempotency marker share one savepoint for interruption safety.
13676    pub fn rebootstrap_local_data(
13677        &mut self,
13678        input: &LocalDataRebootstrapInput,
13679    ) -> Result<LocalDataRebootstrapResult, String> {
13680        if input.rebootstrap_id.is_empty()
13681            || input.rebootstrap_id.len() > 128
13682            || !is_local_operation_code_like(&input.rebootstrap_id)
13683        {
13684            return Err(
13685                "sync.invalid_request: local rebootstrap rebootstrapId must be a 1–128 character code-like identifier"
13686                    .to_owned(),
13687            );
13688        }
13689        let meta_key = format!("localRebootstrap:{}", input.rebootstrap_id);
13690        if let Some(persisted) = meta_get(&self.conn, &meta_key).map_err(|_| {
13691            "sync.local_corrupt: persisted local rebootstrap receipt is unreadable".to_owned()
13692        })? {
13693            let (retained_commits, reset_subscriptions) =
13694                decode_local_rebootstrap_receipt(&persisted)?;
13695            return Ok(LocalDataRebootstrapResult {
13696                already_applied: true,
13697                retained_commits,
13698                reset_subscriptions,
13699            });
13700        }
13701        if self.stopped || self.schema_floor.is_some() {
13702            return Err(
13703                "sync.invalid_request: local rebootstrap cannot bypass an active schema-floor stop; update the application first"
13704                    .to_owned(),
13705            );
13706        }
13707
13708        let retained_commits = self.outbox.len();
13709        let reset_subscriptions = self.stored(load_units(&self.conn))?.len();
13710        let receipt = encode_local_rebootstrap_receipt(retained_commits, reset_subscriptions)?;
13711        let rollback = self.capture();
13712        self.begin_observation("syncular_local_rebootstrap")?;
13713        let mut batch = ChangeAccumulator::default();
13714        let applied = (|| -> Result<(), String> {
13715            self.run_schema_reset_observed(&mut batch, false)?;
13716            self.conn
13717                .execute(
13718                    "INSERT INTO _syncular_meta(key, value) VALUES (?1, ?2)",
13719                    rusqlite::params![meta_key, receipt],
13720                )
13721                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13722            self.sync_needed = true;
13723            self.sync_intent_queue.push_back(SyncIntent::Interactive);
13724            batch.status = true;
13725            Ok(())
13726        })()
13727        .and_then(|()| self.finish_observation("syncular_local_rebootstrap", batch));
13728        if let Err(error) = applied {
13729            self.rollback_observation("syncular_local_rebootstrap");
13730            self.restore(rollback);
13731            return Err(error);
13732        }
13733        self.cancel_sync_round();
13734
13735        Ok(LocalDataRebootstrapResult {
13736            already_applied: false,
13737            retained_commits,
13738            reset_subscriptions,
13739        })
13740    }
13741
13742    // -- scope purge + doomed outbox (§3.3) ----------------------------------------
13743
13744    /// Delete base and visible rows owned by the effective scopes
13745    /// ([`local_scope_predicate`]); `Ok(false)` = no local scope-column
13746    /// mapping for a key (the fail-closed case). A SQLite failure is an error.
13747    fn purge_scope_rows(
13748        &mut self,
13749        table_name: &str,
13750        effective: &[(String, Vec<String>)],
13751        owners: &[Vec<(String, Vec<String>)>],
13752    ) -> Result<bool, String> {
13753        let Some(table) = self.schema.table(table_name) else {
13754            return Ok(false);
13755        };
13756        let Ok(predicate) = local_scope_predicate(table, effective, owners) else {
13757            return Ok(false);
13758        };
13759        let Some((predicate, params)) = predicate else {
13760            return Ok(true);
13761        };
13762        self.overlay_dirty.table(table_name);
13763        for source in [base_table(table_name), visible_table(table_name)] {
13764            self.conn
13765                .execute(
13766                    &format!("DELETE FROM {source} WHERE {predicate}"),
13767                    rusqlite::params_from_iter(&params),
13768                )
13769                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13770        }
13771        Ok(true)
13772    }
13773
13774    /// §3.3: drop pending commits whose upserts provably land in the
13775    /// revoked effective scopes and no other owner covers (row ownership)
13776    /// — whole-commit, never per-operation.
13777    fn drop_doomed_outbox(
13778        &mut self,
13779        table: &TableSchema,
13780        effective: &[(String, Vec<String>)],
13781        owners: &[Vec<(String, Vec<String>)>],
13782    ) -> Result<bool, String> {
13783        let doomed: Vec<_> =
13784            self.outbox
13785                .iter()
13786                .filter(|commit| {
13787                    commit.ops.iter().any(|op| {
13788                        op.upsert
13789                            && op.table == table.name
13790                            && op.values.as_ref().is_some_and(|values| {
13791                                owns_local_row(table, effective, owners, values)
13792                            })
13793                    })
13794                })
13795                .cloned()
13796                .collect();
13797        if doomed.is_empty() {
13798            return Ok(false);
13799        }
13800        let mut rejections = Vec::new();
13801        for commit in &doomed {
13802            let results = commit
13803                .ops
13804                .iter()
13805                .enumerate()
13806                .map(|(op_index, operation)| {
13807                    self.overlay_dirty.table(&operation.table);
13808                    let rejection = RejectionRecord {
13809                        client_commit_id: commit.client_commit_id.clone(),
13810                        op_index: op_index as i32,
13811                        code: "sync.scope_revoked".to_owned(),
13812                        message: "the commit was dropped because its effective scope was revoked"
13813                            .to_owned(),
13814                        retryable: false,
13815                        details: None,
13816                        operation: Some(CommitOperation::from(operation)),
13817                    };
13818                    rejections.push(rejection.clone());
13819                    CommitOperationOutcome::Error { rejection }
13820                })
13821                .collect::<Vec<_>>();
13822            self.persist_commit_outcome(
13823                &commit.client_commit_id,
13824                CommitOutcomeStatus::Rejected,
13825                &results,
13826                Some(&commit.ops),
13827            )?;
13828            self.leave_through(&commit.client_commit_id);
13829            self.delete_outbox_persisted(&commit.client_commit_id)?;
13830        }
13831        self.prune_commit_outcomes()?;
13832        let doomed_ids = doomed
13833            .iter()
13834            .map(|commit| commit.client_commit_id.as_str())
13835            .collect::<BTreeSet<_>>();
13836        self.outbox
13837            .retain(|commit| !doomed_ids.contains(commit.client_commit_id.as_str()));
13838        self.rejections.extend(rejections);
13839        Ok(true)
13840    }
13841
13842    // -- blobs (§5.9) ----------------------------------------------------------------
13843
13844    /// §5.9.7: hash bytes into the content address, cache them, queue the
13845    /// upload (flushed before the next push, B4). Returns the canonical
13846    /// BlobRef JSON `{blobId, byteLength, mediaType?}` for a `blob_ref`
13847    /// column value.
13848    pub fn upload_blob(
13849        &mut self,
13850        bytes: &[u8],
13851        media_type: Option<String>,
13852        name: Option<String>,
13853    ) -> Result<Value, String> {
13854        let blob_id = blob_id_for(bytes);
13855        let now = self.clock_now_ms();
13856        let tx = self
13857            .conn
13858            .transaction()
13859            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13860        tx.execute(
13861            "INSERT INTO _syncular_blobs(blob_id, bytes, byte_length, media_type, created_at_ms) VALUES (?,?,?,?,?)
13862             ON CONFLICT(blob_id) DO NOTHING",
13863            rusqlite::params![blob_id, bytes, bytes.len() as i64, media_type, now],
13864        )
13865        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13866        tx.execute(
13867            "INSERT OR IGNORE INTO _syncular_blob_uploads(blob_id, media_type, created_at_ms) VALUES (?,?,?)",
13868            rusqlite::params![blob_id, media_type, now],
13869        )
13870        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13871        tx.commit()
13872            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13873        self.enforce_blob_cache_cap();
13874        let mut obj = Map::new();
13875        obj.insert("blobId".to_owned(), Value::from(blob_id));
13876        obj.insert("byteLength".to_owned(), Value::from(bytes.len() as i64));
13877        if let Some(mt) = media_type {
13878            obj.insert("mediaType".to_owned(), Value::from(mt));
13879        }
13880        if let Some(n) = name {
13881            obj.insert("name".to_owned(), Value::from(n));
13882        }
13883        Ok(Value::Object(obj))
13884    }
13885
13886    /// §5.9.7: resolve an owned blob body without driver encoding. A
13887    /// content-addressed cache hit serves with no fetch (B1); a miss downloads
13888    /// (§5.9.5), verifies the address, caches the bytes, and returns them.
13889    pub fn fetch_blob_bytes(
13890        &mut self,
13891        transport: &mut dyn Transport,
13892        blob_id_or_ref: &str,
13893    ) -> Result<FetchedBlob, (String, String)> {
13894        let simple = |m: String| ("client.failed".to_owned(), m);
13895        // A BlobRef declares the size that caps the download (§5.9.5); a bare
13896        // blobId declares none.
13897        let (blob_id, byte_length) = if blob_id_or_ref.starts_with("sha256:") {
13898            (blob_id_or_ref.to_owned(), None)
13899        } else {
13900            let value: Value = serde_json::from_str(blob_id_or_ref)
13901                .map_err(|_| simple("blob ref is not JSON".to_owned()))?;
13902            (
13903                value
13904                    .get("blobId")
13905                    .and_then(Value::as_str)
13906                    .ok_or_else(|| simple("blob ref has no blobId".to_owned()))?
13907                    .to_owned(),
13908                value.get("byteLength").and_then(Value::as_u64),
13909            )
13910        };
13911        if let Some(cached) = self.get_cached_blob_bytes(&blob_id).map_err(simple)? {
13912            return Ok(cached);
13913        }
13914        if self.transport_closed() {
13915            return Err(("sync.offline".into(), "transport gate is closed".into()));
13916        }
13917        // §5.9.5: propagate the server's blob.* code (blob.forbidden /
13918        // blob.not_found) verbatim so the harness can assert on it. The
13919        // authorized endpoint serves bytes inline OR (always-issue, presign
13920        // configured) a signed url the client fetches directly — no host auth,
13921        // no fall-through: failure => re-request (the caller's next fetch_blob_bytes).
13922        #[cfg(feature = "bench-internals")]
13923        let download_phase = self.benchmark_phases.start(Phase::BlobDownload);
13924        let bytes = match transport
13925            .blob_download(&blob_id, byte_length)
13926            .map_err(|e| (e.code, e.message))?
13927        {
13928            BlobDownload::Bytes(bytes) => bytes,
13929            BlobDownload::Url {
13930                url,
13931                url_expires_at_ms,
13932            } => {
13933                // §5.9.5: MUST NOT start a fetch at/past expiry.
13934                if url_expires_at_ms.is_some_and(|exp| exp <= self.clock_now_ms()) {
13935                    return Err((
13936                        "sync.segment_expired".to_owned(),
13937                        format!(
13938                            "blob url for {blob_id} expired before fetch — re-request mints a fresh url (§5.9.5)"
13939                        ),
13940                    ));
13941                }
13942                transport
13943                    .fetch_blob_url(&url, byte_length)
13944                    .map_err(|e| (e.code, e.message))?
13945            }
13946        };
13947        #[cfg(feature = "bench-internals")]
13948        drop(download_phase);
13949        #[cfg(feature = "bench-internals")]
13950        let validate_phase = self.benchmark_phases.start(Phase::BlobValidate);
13951        // §5.9.5 inherits §5.1: the declared size caps the body before the
13952        // content address is verified.
13953        if byte_length.is_some_and(|cap| bytes.len() as u64 > cap) {
13954            return Err((
13955                "sync.invalid_request".to_owned(),
13956                "blob exceeds its byteLength".to_owned(),
13957            ));
13958        }
13959        if blob_id_for(&bytes) != blob_id {
13960            return Err(simple(format!(
13961                "blob content address mismatch for {blob_id}"
13962            )));
13963        }
13964        #[cfg(feature = "bench-internals")]
13965        drop(validate_phase);
13966        #[cfg(feature = "bench-internals")]
13967        let insert_phase = self.benchmark_phases.start(Phase::BlobCacheInsert);
13968        let now = self.clock_now_ms();
13969        self.conn
13970            .execute(
13971                "INSERT OR IGNORE INTO _syncular_blobs(blob_id, bytes, byte_length, media_type, created_at_ms) VALUES (?,?,?,NULL,?)",
13972                rusqlite::params![blob_id, bytes, bytes.len() as i64, now],
13973            )
13974            .map_err(|e| simple(e.to_string()))?;
13975        self.conn
13976            .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
13977            .map_err(|e| simple(e.to_string()))?;
13978        self.enforce_blob_cache_cap();
13979        #[cfg(feature = "bench-internals")]
13980        drop(insert_phase);
13981        self.get_cached_blob_bytes(&blob_id)
13982            .map_err(simple)?
13983            .ok_or_else(|| simple("blob cache write failed".to_owned()))
13984    }
13985
13986    fn get_cached_blob_bytes(&self, blob_id: &str) -> Result<Option<FetchedBlob>, String> {
13987        #[cfg(feature = "bench-internals")]
13988        let _phase = self.benchmark_phases.start(Phase::BlobCacheRead);
13989        let mut stmt = self
13990            .conn
13991            .prepare("SELECT bytes, byte_length, media_type FROM _syncular_blobs WHERE blob_id = ?")
13992            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13993        let mut rows = stmt
13994            .query(rusqlite::params![blob_id])
13995            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13996        if let Some(row) = rows
13997            .next()
13998            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
13999        {
14000            let bytes: Vec<u8> = row
14001                .get(0)
14002                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14003            let byte_length: i64 = row
14004                .get(1)
14005                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14006            let media_type: Option<String> = row
14007                .get(2)
14008                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14009            return Ok(Some(FetchedBlob {
14010                blob_id: blob_id.to_owned(),
14011                byte_length,
14012                bytes,
14013                media_type,
14014            }));
14015        }
14016        Ok(None)
14017    }
14018
14019    /// §5.9.7 B4: upload every queued blob before push.
14020    fn pending_blob_uploads(&self) -> Result<Vec<crate::round::PendingUpload>, TransportError> {
14021        let pending: Vec<(String, Option<String>)> = {
14022            let mut stmt = self
14023                .conn
14024                .prepare(
14025                    "SELECT blob_id, media_type FROM (
14026                      SELECT blob_id, media_type, created_at_ms FROM _syncular_blob_uploads
14027                      UNION ALL
14028                      SELECT DISTINCT r.blob_id, b.media_type, 9223372036854775807 AS created_at_ms
14029                      FROM _syncular_blob_commit_refs r LEFT JOIN _syncular_blobs b ON b.blob_id = r.blob_id
14030                      WHERE NOT EXISTS (SELECT 1 FROM _syncular_blob_uploads u WHERE u.blob_id = r.blob_id)
14031                    ) ORDER BY created_at_ms, blob_id",
14032                )
14033                .map_err(|e| TransportError::new("client.failed", e.to_string()))?;
14034            let rows = stmt
14035                .query_map([], |row| {
14036                    Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?))
14037                })
14038                .map_err(|e| TransportError::new("client.failed", e.to_string()))?;
14039            rows.collect::<Result<_, _>>()
14040                .map_err(|error| match error {
14041                    rusqlite::Error::InvalidColumnType(..)
14042                    | rusqlite::Error::FromSqlConversionFailure(..) => TransportError::new(
14043                        "sync.local_corrupt",
14044                        "Pending blob upload metadata is invalid",
14045                    ),
14046                    _ => TransportError::new("client.failed", error.to_string()),
14047                })?
14048        };
14049        let mut uploads = Vec::new();
14050        for (blob_id, media_type) in pending {
14051            let bytes = (|| {
14052                let stored: Option<(SqlValue, SqlValue)> = self
14053                    .conn
14054                    .query_row(
14055                        "SELECT bytes, byte_length FROM _syncular_blobs WHERE blob_id = ?",
14056                        rusqlite::params![blob_id],
14057                        |row| Ok((row.get(0)?, row.get(1)?)),
14058                    )
14059                    .optional()
14060                    .map_err(|e| TransportError::new("client.failed", e.to_string()))?;
14061                let Some((SqlValue::Blob(bytes), SqlValue::Integer(byte_length))) = stored else {
14062                    return Err(TransportError::new(
14063                        "sync.local_corrupt",
14064                        "Pending blob upload body is missing or corrupt",
14065                    ));
14066                };
14067                if byte_length != bytes.len() as i64 || blob_id_for(&bytes) != blob_id {
14068                    return Err(TransportError::new(
14069                        "sync.local_corrupt",
14070                        "Pending blob upload body is missing or corrupt",
14071                    ));
14072                }
14073                Ok(bytes)
14074            })();
14075            let failed = bytes.is_err();
14076            uploads.push(crate::round::PendingUpload {
14077                id: blob_id,
14078                bytes,
14079                media_type,
14080            });
14081            if failed {
14082                break;
14083            }
14084        }
14085        Ok(uploads)
14086    }
14087
14088    fn visible_blob_ids_sql(&self) -> String {
14089        let mut selects = Vec::new();
14090        for table in &self.schema.tables {
14091            for column in table
14092                .columns
14093                .iter()
14094                .filter(|column| column.ty == ColumnType::BlobRef)
14095            {
14096                let identifier = quote_ident(&column.name);
14097                selects.push(format!(
14098                    "SELECT json_extract({identifier}, '$.blobId') AS blob_id FROM {} \
14099                     WHERE typeof({identifier}) = 'text' AND json_valid({identifier}) \
14100                     AND json_type({identifier}, '$.blobId') = 'text'",
14101                    quote_ident(&table.name),
14102                ));
14103            }
14104        }
14105        if selects.is_empty() {
14106            "SELECT NULL AS blob_id WHERE 0".to_owned()
14107        } else {
14108            selects.join(" UNION ")
14109        }
14110    }
14111
14112    /// §5.9.7 B1 size cap. Visible rows, pending commits, and
14113    /// staged uploads pin bodies directly; no derived refcount is stored.
14114    fn enforce_blob_cache_cap(&self) {
14115        let Some(max_bytes) = self.limits.blob_cache_max_bytes else {
14116            return;
14117        };
14118        let mut total: i64 = self
14119            .conn
14120            .query_row(
14121                "SELECT COALESCE(SUM(byte_length), 0) FROM _syncular_blobs",
14122                [],
14123                |row| row.get(0),
14124            )
14125            .unwrap_or(0);
14126        if total <= max_bytes {
14127            return;
14128        }
14129        let query = format!(
14130            "SELECT blob_id, byte_length FROM _syncular_blobs
14131             WHERE blob_id NOT IN (SELECT blob_id FROM _syncular_blob_uploads)
14132               AND blob_id NOT IN (SELECT blob_id FROM _syncular_blob_commit_refs)
14133               AND blob_id NOT IN ({})
14134             ORDER BY created_at_ms ASC, blob_id ASC",
14135            self.visible_blob_ids_sql(),
14136        );
14137        let candidates: Vec<(String, i64)> = {
14138            let Ok(mut stmt) = self.conn.prepare(&query) else {
14139                return;
14140            };
14141            let Ok(rows) = stmt.query_map([], |row| {
14142                Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
14143            }) else {
14144                return;
14145            };
14146            rows.filter_map(Result::ok).collect()
14147        };
14148        for (blob_id, byte_length) in candidates {
14149            if total <= max_bytes {
14150                break;
14151            }
14152            let _ = self.conn.execute(
14153                "DELETE FROM _syncular_blobs WHERE blob_id = ?",
14154                rusqlite::params![blob_id],
14155            );
14156            total -= byte_length;
14157        }
14158    }
14159
14160    fn delete_unreferenced_cached_blobs(&mut self) -> Result<(), String> {
14161        #[cfg(feature = "bench-internals")]
14162        let _phase = self.benchmark_phases.start(Phase::BlobRetention);
14163        if !self.schema_has_blobs() {
14164            return Ok(());
14165        }
14166        self.rebuild_overlay_if_dirty()?;
14167        self.conn
14168            .execute(
14169                &format!(
14170                    "DELETE FROM _syncular_blobs
14171                 WHERE blob_id NOT IN (SELECT blob_id FROM _syncular_blob_uploads)
14172                   AND blob_id NOT IN (SELECT blob_id FROM _syncular_blob_commit_refs)
14173                   AND blob_id NOT IN ({})",
14174                    self.visible_blob_ids_sql(),
14175                ),
14176                [],
14177            )
14178            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14179        Ok(())
14180    }
14181
14182    // -- local row storage ----------------------------------------------------------
14183
14184    /// The cached per-table primary-key upsert SQL for `full_table` (see
14185    /// the `insert_sql` field: built once, reused per row).
14186    fn insert_row_sql(&self, full_table: &str, table: &crate::schema::TableSchema) -> String {
14187        if let Some(sql) = self.insert_sql.borrow().get(full_table) {
14188            return sql.clone();
14189        }
14190        let mut columns: Vec<String> = table.columns.iter().map(|c| quote_ident(&c.name)).collect();
14191        columns.push(quote_ident("_syncular_version"));
14192        columns.extend(table.sealed_columns().iter().map(|name| quote_ident(name)));
14193        let placeholders: Vec<&str> = columns.iter().map(|_| "?").collect();
14194        let primary_key = quote_ident(&table.primary_key);
14195        let updates = columns
14196            .iter()
14197            .filter(|column| **column != primary_key)
14198            .map(|column| format!("{column}=excluded.{column}"))
14199            .collect::<Vec<_>>()
14200            .join(", ");
14201        // §4.5 version guard: server state lands in the base table only above
14202        // the stored version; the visible overlay takes every write.
14203        let guard = if full_table == base_table(&table.name) {
14204            format!(" WHERE excluded._syncular_version > {full_table}._syncular_version")
14205        } else {
14206            String::new()
14207        };
14208        let sql = format!(
14209            "INSERT INTO {full_table} ({}) VALUES ({}) ON CONFLICT ({primary_key}) DO UPDATE SET {updates}{guard}",
14210            columns.join(", "),
14211            placeholders.join(", ")
14212        );
14213        self.insert_sql
14214            .borrow_mut()
14215            .insert(full_table.to_owned(), sql.clone());
14216        sql
14217    }
14218
14219    /// §4.5: write a server row under the version guard; returns whether it
14220    /// landed. `sealed` is its §5.11 sealed state, `None` for an unsealed row.
14221    fn write_base_row(
14222        &self,
14223        table_name: &str,
14224        row: &Row,
14225        version: i64,
14226        sealed: Option<&SealedRow>,
14227    ) -> Result<bool, String> {
14228        let landed = self.write_row(&base_table(table_name), table_name, row, version, sealed)?;
14229        if landed {
14230            self.overlay_dirty.table(table_name);
14231        }
14232        Ok(landed)
14233    }
14234
14235    fn write_row(
14236        &self,
14237        full_table: &str,
14238        table_name: &str,
14239        row: &Row,
14240        version: i64,
14241        sealed: Option<&SealedRow>,
14242    ) -> Result<bool, String> {
14243        #[cfg(feature = "bench-internals")]
14244        let _phase = self.benchmark_phases.start(Phase::RowWrite);
14245        let table = self
14246            .schema
14247            .table(table_name)
14248            .ok_or_else(|| format!("unknown table {table_name:?}"))?;
14249        let sql = self.insert_row_sql(full_table, table);
14250        let mut stmt = self
14251            .conn
14252            .prepare_cached(&sql)
14253            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14254        let params = row
14255            .iter()
14256            .map(RowParam::Cell)
14257            .chain(std::iter::once(RowParam::Version(version)))
14258            .chain(
14259                [
14260                    sealed.map(|sealed| sealed.key_id.as_str()),
14261                    sealed.map(|sealed| sealed.envelopes.as_str()),
14262                ]
14263                .into_iter()
14264                .take(table.sealed_columns().len())
14265                .map(RowParam::Text),
14266            );
14267        stmt.execute(rusqlite::params_from_iter(params))
14268            .map(|changed| changed > 0)
14269            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
14270    }
14271
14272    /// §4.5: delete a server row whose stored version lies below `version`;
14273    /// returns whether a row left.
14274    fn delete_base_row(
14275        &self,
14276        table_name: &str,
14277        row_id: &str,
14278        version: i64,
14279    ) -> Result<bool, String> {
14280        let table = self
14281            .schema
14282            .table(table_name)
14283            .ok_or_else(|| format!("unknown table {table_name:?}"))?;
14284        let sql = format!(
14285            "DELETE FROM {} WHERE {} AND _syncular_version < ?2",
14286            base_table(table_name),
14287            row_id_predicate(table)
14288        );
14289        let mut stmt = self
14290            .conn
14291            .prepare_cached(&sql)
14292            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14293        let landed = stmt
14294            .execute(rusqlite::params![row_id, version])
14295            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
14296            > 0;
14297        if landed {
14298            self.overlay_dirty.table(table_name);
14299        }
14300        Ok(landed)
14301    }
14302
14303    fn has_acknowledged_rows(&self) -> Result<bool, String> {
14304        self.conn
14305            .query_row(
14306                "SELECT EXISTS(SELECT 1 FROM _syncular_acked_rows)",
14307                [],
14308                |row| row.get(0),
14309            )
14310            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
14311    }
14312
14313    fn acknowledged_operations(
14314        &self,
14315        rows: Option<&HashSet<(&str, &str)>>,
14316        tables: Option<&BTreeSet<&str>>,
14317    ) -> Result<Vec<OutboxOp>, String> {
14318        let keys = rows.map(|rows| serde_json::to_string(&rows).expect("row keys"));
14319        let mut statement = self
14320            .conn
14321            .prepare_cached(if keys.is_some() {
14322                ACKED_ROWS_BY_ROW
14323            } else {
14324                "SELECT op_json,intent_json FROM _syncular_acked_rows WHERE ?1 IS NULL AND (?2 IS NULL OR tbl IN(SELECT value FROM json_each(?2))) ORDER BY commit_seq,idx"
14325            })
14326            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14327        let rows = statement
14328            .query_map(
14329                rusqlite::params![
14330                    keys,
14331                    tables.map(|tables| serde_json::to_string(tables).expect("table keys"))
14332                ],
14333                |row| {
14334                    #[cfg(test)]
14335                    self.acknowledged_replay_count
14336                        .set(self.acknowledged_replay_count.get() + 1);
14337                    Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
14338                },
14339            )
14340            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14341        rows.map(|row| {
14342            let (op, intent) =
14343                row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14344            let op: CommitOperation =
14345                serde_json::from_str(&op).map_err(|_| "sync.local_corrupt".to_owned())?;
14346            let table = self
14347                .schema
14348                .table(&op.table)
14349                .ok_or_else(|| "sync.unknown_table".to_owned())?;
14350            let values = if op.op == "upsert" && self.visible_row(table, &op.row_id)?.is_none() {
14351                Some(serde_json::from_str(&intent).map_err(|_| "sync.local_corrupt".to_owned())?)
14352            } else {
14353                op.values.clone()
14354            };
14355            Ok(OutboxOp {
14356                values,
14357                ..op.into()
14358            })
14359        })
14360        .collect()
14361    }
14362
14363    fn drop_acknowledged_rows(
14364        &self,
14365        matches: impl Fn(&str, &Map<String, Value>) -> bool,
14366    ) -> Result<Vec<OutboxCommit>, String> {
14367        let mut statement = self
14368            .conn
14369            .prepare("SELECT commit_id,tbl,intent_json,id FROM _syncular_acked_rows")
14370            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14371        let rows = statement
14372            .query_map([], |row| {
14373                Ok((
14374                    row.get::<_, String>(0)?,
14375                    row.get::<_, String>(1)?,
14376                    row.get::<_, String>(2)?,
14377                    row.get::<_, String>(3)?,
14378                ))
14379            })
14380            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14381        let mut doomed = HashSet::new();
14382        for row in rows {
14383            let (id, table, intent, row_id) =
14384                row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14385            let values =
14386                serde_json::from_str(&intent).map_err(|_| "sync.local_corrupt".to_owned())?;
14387            let base_matches = self
14388                .schema
14389                .table(&table)
14390                .map(|schema| self.stored_row(schema, &row_id, true))
14391                .transpose()?
14392                .flatten()
14393                .is_some_and(|(base, _)| {
14394                    let schema = self.schema.table(&table).expect("acknowledged table");
14395                    let values = schema
14396                        .columns
14397                        .iter()
14398                        .zip(base.iter())
14399                        .map(|(column, value)| (column.name.clone(), column_value_to_json(value)))
14400                        .collect();
14401                    matches(&table, &values)
14402                });
14403            if matches(&table, &values) || base_matches {
14404                doomed.insert(id);
14405            }
14406        }
14407        let mut dropped = Vec::new();
14408        for id in doomed {
14409            let mut statement = self
14410                .conn
14411                .prepare("SELECT op_json FROM _syncular_acked_rows WHERE commit_id=?1 ORDER BY idx")
14412                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14413            let operations = statement
14414                .query_map([&id], |row| row.get::<_, String>(0))
14415                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14416            let mut ops = Vec::new();
14417            for operation in operations {
14418                let json = operation
14419                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14420                let op: CommitOperation =
14421                    serde_json::from_str(&json).map_err(|_| "sync.local_corrupt".to_owned())?;
14422                self.overlay_dirty.table(&op.table);
14423                ops.push(OutboxOp {
14424                    table: op.table,
14425                    row_id: op.row_id,
14426                    upsert: op.op == "upsert",
14427                    base_version: op.base_version,
14428                    values: op.values,
14429                    insert: op.insert,
14430                });
14431            }
14432            dropped.push(OutboxCommit {
14433                client_commit_id: id.clone(),
14434                ops,
14435            });
14436            self.conn
14437                .execute("DELETE FROM _syncular_acked_rows WHERE commit_id=?1", [id])
14438                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14439        }
14440        Ok(dropped)
14441    }
14442
14443    /// [`Self::rebuild_overlay`], skipped when neither the base tables nor
14444    /// the outbox changed since the last rebuild (the no-op sync round).
14445    fn rebuild_overlay_if_dirty(&mut self) -> Result<(), String> {
14446        if self.overlay_dirty.get() {
14447            self.rebuild_overlay()?;
14448        }
14449        Ok(())
14450    }
14451
14452    /// §7.1: local reads see outbox state applied optimistically — rebuild
14453    /// every visible table as (base server state) + (pending outbox replay
14454    /// on top). Optimistic rows carry version `-1`.
14455    fn rebuild_overlay(&mut self) -> Result<(), String> {
14456        #[cfg(feature = "bench-internals")]
14457        let _phase = self.benchmark_phases.start(Phase::OverlayRebuild);
14458        #[cfg(test)]
14459        self.overlay_rebuild_count
14460            .set(self.overlay_rebuild_count.get() + 1);
14461        let dirty = self.overlay_dirty.snapshot();
14462        let tables: Vec<_> = self
14463            .schema
14464            .tables
14465            .iter()
14466            .filter(|table| {
14467                dirty
14468                    .as_ref()
14469                    .is_none_or(|names| names.is_empty() || names.contains(&table.name))
14470            })
14471            .cloned()
14472            .collect();
14473        let names: BTreeSet<_> = tables.iter().map(|table| table.name.as_str()).collect();
14474        // A built-in projection is refilled from the rebuilt rows once
14475        // instead of per row by its source triggers.
14476        let built_in: Vec<_> = tables
14477            .iter()
14478            .flat_map(|table| {
14479                table
14480                    .local_projections
14481                    .iter()
14482                    .filter(|spec| spec.built_in())
14483                    .map(move |spec| (spec, table))
14484            })
14485            .collect();
14486        self.begin_observation("syncular_overlay")?;
14487        let rebuilt = (|| {
14488            for (spec, _) in &built_in {
14489                for suffix in ["bi", "bu", "ai", "ad", "au"] {
14490                    self.stored(self.conn.execute(
14491                        &format!(
14492                            "DROP TRIGGER IF EXISTS {}",
14493                            quote_ident(&format!("_syncular_project_{}_{suffix}", spec.name))
14494                        ),
14495                        [],
14496                    ))?;
14497                }
14498            }
14499            for table in &tables {
14500                let visible = visible_table(&table.name);
14501                let base = base_table(&table.name);
14502                self.conn
14503                    .execute_batch(&format!(
14504                        "DELETE FROM {visible}; INSERT INTO {visible} SELECT * FROM {base}"
14505                    ))
14506                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14507            }
14508            self.replay_overlay(&names, None)?;
14509            for (spec, table) in &built_in {
14510                self.fill_built_in(spec, table)?;
14511                self.create_projection_triggers(spec, table)?;
14512            }
14513            self.conn
14514                .execute_batch("RELEASE syncular_overlay")
14515                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14516            Ok(())
14517        })();
14518        if rebuilt.is_err() {
14519            self.conn
14520                .execute_batch("ROLLBACK TO syncular_overlay; RELEASE syncular_overlay")
14521                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14522        } else {
14523            self.overlay_dirty.set(false);
14524        }
14525        rebuilt
14526    }
14527
14528    /// §7.1 replay of acknowledged, retained failed and pending intent, in
14529    /// that order, for the operations of `tables` on `rows` (every row for
14530    /// `None`) over their current visible state.
14531    fn replay_overlay(
14532        &self,
14533        tables: &BTreeSet<&str>,
14534        rows: Option<&HashSet<(&str, &str)>>,
14535    ) -> Result<(), String> {
14536        let replays = |op: &&OutboxOp| {
14537            tables.contains(op.table.as_str())
14538                && rows.is_none_or(|rows| rows.contains(&(op.table.as_str(), op.row_id.as_str())))
14539        };
14540        self.apply_outbox_ops(&self.acknowledged_operations(rows, Some(tables))?)?;
14541        for (commit, initial) in self.failed_commits.iter() {
14542            for operation in commit.ops.iter().filter(replays) {
14543                let Some(table) = self.schema.table(&operation.table) else {
14544                    continue;
14545                };
14546                if operation.upsert
14547                    && self.visible_row(table, &operation.row_id)?.is_none()
14548                    && operation.presented_values(table).is_some_and(|values| {
14549                        table
14550                            .columns
14551                            .iter()
14552                            .all(|column| values.contains_key(&column.name))
14553                    })
14554                {
14555                    let key = serde_json::to_string(&(&operation.table, &operation.row_id))
14556                        .expect("row key serialization");
14557                    if let Some(Value::Object(values)) = initial.get(&key) {
14558                        self.apply_outbox_ops(&[OutboxOp {
14559                            values: Some(values.clone()),
14560                            ..operation.clone()
14561                        }])?;
14562                    }
14563                }
14564            }
14565            self.apply_outbox_ops(commit.ops.iter().filter(replays))?;
14566        }
14567        self.apply_outbox_ops(
14568            self.outbox
14569                .iter()
14570                .flat_map(|commit| &commit.ops)
14571                .filter(replays),
14572        )
14573    }
14574
14575    /// §7.1 replay: every operation is applied over the current visible
14576    /// state. An operation that no longer applies (a server row now holds its
14577    /// unique value) stays pending and invisible until a later replay admits
14578    /// it or the server answers its push.
14579    fn apply_outbox_ops<'a>(
14580        &self,
14581        ops: impl IntoIterator<Item = &'a OutboxOp>,
14582    ) -> Result<(), String> {
14583        #[cfg(feature = "bench-internals")]
14584        let mut phase = self.benchmark_phases.start(Phase::PendingReplay);
14585        for op in ops {
14586            #[cfg(feature = "bench-internals")]
14587            if let Some(phase) = &mut phase {
14588                phase.unit();
14589            }
14590            if op.upsert {
14591                if let Some((table, values)) = self
14592                    .schema
14593                    .table(&op.table)
14594                    .filter(|table| table.indexes.iter().any(|index| index.unique))
14595                    .and_then(|table| Some((table, op.presented_values(table)?)))
14596                {
14597                    let mut intended: Map<String, Value> = self
14598                        .visible_row(table, &op.row_id)?
14599                        .map(|(row, _)| {
14600                            table
14601                                .columns
14602                                .iter()
14603                                .zip(&row)
14604                                .map(|(column, value)| {
14605                                    (column.name.clone(), column_value_to_json(value))
14606                                })
14607                                .collect()
14608                        })
14609                        .unwrap_or_default();
14610                    intended.extend(values.into_owned());
14611                    if !self.unique_conflicts(table, &intended, false)?.is_empty() {
14612                        continue;
14613                    }
14614                }
14615            }
14616            self.apply_outbox_op(op)?;
14617        }
14618        Ok(())
14619    }
14620
14621    fn apply_outbox_op(&self, op: &OutboxOp) -> Result<(), String> {
14622        let Some(table) = self.schema.table(&op.table) else {
14623            return Ok(());
14624        };
14625        let visible = visible_table(&table.name);
14626        if !op.upsert {
14627            let sql = format!("DELETE FROM {visible} WHERE {}", row_id_predicate(table));
14628            self.conn
14629                .prepare_cached(&sql)
14630                .and_then(|mut statement| statement.execute(rusqlite::params![op.row_id]))
14631                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14632            return Ok(());
14633        }
14634        // §7.1: an insert-intent operation that lacks a non-nullable column
14635        // cannot encode; it stays invisible until the send-time prepass drops
14636        // it as sync.outbox_incompatible (§7.4.4).
14637        let Some(values) = op.presented_values(table) else {
14638            return Ok(());
14639        };
14640        // §7.1: the overlay applies the operation's PRESENT columns
14641        // over the current local row. A partial operation over an
14642        // absent local row leaves it absent — the server answers it
14643        // with sync.row_deleted or sync.row_missing (§6.2). An
14644        // insert-intent operation presents every column.
14645        let full = table
14646            .columns
14647            .iter()
14648            .all(|column| values.contains_key(&column.name));
14649        let local = self.visible_row(table, &op.row_id)?;
14650        if local.is_none() && !full {
14651            return Ok(());
14652        }
14653        // §5.11: a row that arrived sealed stays sealed; the replay overlays
14654        // its non-encrypted columns and its encrypted columns stay NULL.
14655        let sealed = if local.is_some() && table.has_encrypted_columns() {
14656            let (key_id, envelopes) = self
14657                .conn
14658                .query_row(
14659                    &format!(
14660                        "SELECT \"_sync_sealed_key\",\"_sync_sealed\" FROM {visible} WHERE {}",
14661                        row_id_predicate(table)
14662                    ),
14663                    rusqlite::params![op.row_id],
14664                    |row| {
14665                        Ok((
14666                            row.get::<_, Option<String>>(0)?,
14667                            row.get::<_, Option<String>>(1)?,
14668                        ))
14669                    },
14670                )
14671                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14672            key_id
14673                .zip(envelopes)
14674                .map(|(key_id, envelopes)| SealedRow { key_id, envelopes })
14675        } else {
14676            None
14677        };
14678        let mut row: Row = Vec::with_capacity(table.columns.len());
14679        for (index, column) in table.columns.iter().enumerate() {
14680            let encrypted = table
14681                .encrypted_columns
14682                .iter()
14683                .any(|encrypted| encrypted.index == index);
14684            let incoming = match values
14685                .get(&column.name)
14686                .filter(|_| !(sealed.is_some() && encrypted))
14687            {
14688                Some(raw) => json_to_column_value(
14689                    if raw.get("$bytes").is_some() && encrypted {
14690                        &table.wire_columns[index]
14691                    } else {
14692                        column
14693                    },
14694                    Some(raw),
14695                ),
14696                None => Ok(local
14697                    .as_ref()
14698                    .and_then(|(values, _)| values.get(index).cloned())
14699                    .flatten()),
14700            };
14701            row.push(incoming.map_err(|_| {
14702                "sync.local_corrupt: persisted optimistic row value is invalid".to_owned()
14703            })?);
14704        }
14705        let version = local.as_ref().map_or(-1, |(_, version)| *version);
14706        self.write_row(&visible, &table.name, &row, version, sealed.as_ref())
14707            .map(|_| ())
14708            .map_err(|error| {
14709                if error.starts_with("UNIQUE constraint failed:") {
14710                    "sync.constraint_violation: local write violates a unique constraint".to_owned()
14711                } else {
14712                    error
14713                }
14714            })
14715    }
14716
14717    /// Whether the row is present in the overlay. Existence reads only the
14718    /// key: locked encrypted values stay opaque, and decoding the complete row
14719    /// would reject a valid plain write.
14720    fn visible_row_exists(&self, table: &TableSchema, row_id: &str) -> Result<bool, String> {
14721        self.conn
14722            .query_row(
14723                &format!(
14724                    "SELECT EXISTS(SELECT 1 FROM {} WHERE {})",
14725                    visible_table(&table.name),
14726                    row_id_predicate(table)
14727                ),
14728                rusqlite::params![row_id],
14729                |row| row.get(0),
14730            )
14731            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
14732    }
14733
14734    /// §5.11: a sealed row is read-only; a write could otherwise send NULL
14735    /// over ciphertext this device cannot see.
14736    fn refuse_sealed_row(&self, table: &TableSchema, row_id: &str) -> Result<(), ClientError> {
14737        if !table.has_encrypted_columns() {
14738            return Ok(());
14739        }
14740        let key_id: Option<String> = self
14741            .conn
14742            .query_row(
14743                &format!(
14744                    "SELECT \"_sync_sealed_key\" FROM {} WHERE {}",
14745                    visible_table(&table.name),
14746                    row_id_predicate(table)
14747                ),
14748                rusqlite::params![row_id],
14749                |row| row.get(0),
14750            )
14751            .optional()
14752            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
14753            .flatten();
14754        match key_id {
14755            None => Ok(()),
14756            Some(key_id) => Err(ClientError {
14757                code: "client.encryption_key_missing".to_owned(),
14758                message: "the row is sealed under a key this device does not hold".to_owned(),
14759                details: Some(json!({ "table": table.name, "keyId": key_id })),
14760                retryable: false,
14761            }),
14762        }
14763    }
14764
14765    /// §5.11 reveal: decrypt every sealed base row whose envelope keys the
14766    /// keyring now holds into its columns and clear both reserved columns,
14767    /// one change batch per table. `client.decrypt_failed` fails the caller.
14768    fn reveal_sealed_rows(&mut self) -> Result<(), TransportError> {
14769        let storage = |message: String| TransportError::new("storage.failed", message);
14770        let tables: Vec<TableSchema> = self
14771            .schema
14772            .tables
14773            .iter()
14774            .filter(|table| table.has_encrypted_columns())
14775            .cloned()
14776            .collect();
14777        for table in &tables {
14778            let base = base_table(&table.name);
14779            let pk = quote_ident(&table.primary_key);
14780            let sealed: Vec<(SqlValue, i64, String)> = self
14781                .conn
14782                .prepare_cached(&format!(
14783                    "SELECT {pk}, \"_syncular_version\", \"_sync_sealed\" FROM {base} WHERE \"_sync_sealed_key\" IS NOT NULL"
14784                ))
14785                .and_then(|mut statement| {
14786                    statement
14787                        .query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))?
14788                        .collect()
14789                })
14790                .map_err(|error| storage(Self::sqlite_failure(&self.storage_failure, error)))?;
14791            let mut revealed = Vec::new();
14792            for (key, version, envelopes) in sealed {
14793                if let Some(row) =
14794                    crate::values::reveal_sealed_row(table, &envelopes, &self.encryption)?
14795                {
14796                    revealed.push((key, version, row));
14797                }
14798            }
14799            if revealed.is_empty() {
14800                continue;
14801            }
14802            self.begin_observation("syncular_reveal").map_err(storage)?;
14803            let outcome = (|| {
14804                let assignments = table
14805                    .encrypted_columns
14806                    .iter()
14807                    .map(|enc| format!("{}=?", quote_ident(&table.columns[enc.index].name)))
14808                    .collect::<Vec<_>>()
14809                    .join(",");
14810                let mut statement = self
14811                    .conn
14812                    .prepare_cached(&format!(
14813                        "UPDATE {base} SET {assignments},\"_sync_sealed_key\"=NULL,\"_sync_sealed\"=NULL WHERE {pk}=? AND \"_syncular_version\"=?"
14814                    ))
14815                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14816                for (key, version, row) in &revealed {
14817                    let mut params = table
14818                        .encrypted_columns
14819                        .iter()
14820                        .map(|enc| owned_sql_value(RowParam::Cell(&row[enc.index])))
14821                        .collect::<Result<Vec<_>, _>>()?;
14822                    params.push(key.clone());
14823                    params.push(SqlValue::Integer(*version));
14824                    statement
14825                        .execute(rusqlite::params_from_iter(params))
14826                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14827                }
14828                drop(statement);
14829                self.overlay_dirty.table(&table.name);
14830                self.rebuild_overlay()?;
14831                let mut batch = ChangeAccumulator::default();
14832                batch.table(&table.name);
14833                self.finish_observation("syncular_reveal", batch)
14834            })();
14835            if outcome.is_err() {
14836                self.rollback_observation("syncular_reveal");
14837            }
14838            outcome.map_err(storage)?;
14839        }
14840        Ok(())
14841    }
14842
14843    /// The visible (optimistic) row's values plus version, or `None` when the
14844    /// row is absent from the overlay.
14845    fn visible_row(&self, table: &TableSchema, row_id: &str) -> Result<Option<(Row, i64)>, String> {
14846        self.stored_row(table, row_id, false)
14847    }
14848
14849    fn stored_row(
14850        &self,
14851        table: &TableSchema,
14852        row_id: &str,
14853        base: bool,
14854    ) -> Result<Option<(Row, i64)>, String> {
14855        let sql = format!(
14856            "SELECT * FROM {} WHERE {}",
14857            if base {
14858                base_table(&table.name)
14859            } else {
14860                visible_table(&table.name)
14861            },
14862            row_id_predicate(table)
14863        );
14864        let mut stmt = self
14865            .conn
14866            .prepare_cached(&sql)
14867            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14868        let mut rows = stmt
14869            .query(rusqlite::params![row_id])
14870            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14871        let Some(row) = rows
14872            .next()
14873            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
14874        else {
14875            return Ok(None);
14876        };
14877        let mut values = Vec::with_capacity(table.columns.len());
14878        for (index, column) in table.columns.iter().enumerate() {
14879            let raw = row
14880                .get_ref(index)
14881                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14882            if let rusqlite::types::ValueRef::Blob(bytes) = raw {
14883                if table
14884                    .encrypted_columns
14885                    .iter()
14886                    .any(|encrypted| encrypted.index == index)
14887                {
14888                    values.push(Some(ColumnValue::Bytes(bytes.to_vec())));
14889                    continue;
14890                }
14891            }
14892            let json = sql_ref_to_json(column, raw);
14893            values.push(json_to_column_value(column, Some(&json)).map_err(|_| {
14894                "sync.local_corrupt: persisted local row value is invalid".to_owned()
14895            })?);
14896        }
14897        let version: i64 = row
14898            .get(table.columns.len())
14899            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14900        Ok(Some((values, version)))
14901    }
14902
14903    // -- realtime (§8) ---------------------------------------------------------------
14904
14905    /// §8.8: the configured realtime policy.
14906    #[must_use]
14907    pub fn realtime_policy(&self) -> RealtimePolicy {
14908        self.realtime_policy
14909    }
14910
14911    /// §8.8: the explicit realtime availability state.
14912    #[must_use]
14913    pub fn realtime_state(&self) -> RealtimeState {
14914        self.realtime_state
14915    }
14916
14917    /// §8.8: set the realtime policy. Refused while the socket is connected:
14918    /// a policy change never silently re-routes an ownership state.
14919    pub fn set_realtime_policy(&mut self, policy: RealtimePolicy) -> Result<(), String> {
14920        if self.realtime_state == RealtimeState::Connected && policy != self.realtime_policy {
14921            return Err(
14922                "sync.invalid_request: disconnect realtime before changing the realtime policy"
14923                    .to_owned(),
14924            );
14925        }
14926        self.realtime_policy = policy;
14927        match policy {
14928            RealtimePolicy::Off => self.set_realtime_state(RealtimeState::Disabled, None),
14929            RealtimePolicy::Required | RealtimePolicy::Optional
14930                if self.realtime_state == RealtimeState::Disabled =>
14931            {
14932                self.set_realtime_state(RealtimeState::Disconnected, None);
14933            }
14934            RealtimePolicy::Required | RealtimePolicy::Optional => {}
14935        }
14936        Ok(())
14937    }
14938
14939    /// Record an availability transition, keeping the reason code bounded and
14940    /// code-like (§7.6) and clearing it where it cannot apply.
14941    fn set_realtime_state(&mut self, state: RealtimeState, reason_code: Option<&str>) {
14942        self.realtime_state = state;
14943        self.realtime_reason_code = reason_code.map(Self::diagnostic_code);
14944        if matches!(state, RealtimeState::Connected | RealtimeState::Disabled) {
14945            self.realtime_reason_code = None;
14946            self.realtime_retry_delay_ms = None;
14947        }
14948    }
14949
14950    #[must_use]
14951    fn realtime_connected(&self) -> bool {
14952        self.realtime_state == RealtimeState::Connected
14953    }
14954
14955    pub fn connect_realtime(&mut self, transport: &mut dyn Transport) -> Result<(), String> {
14956        if self.transport_closed() {
14957            return Err("sync.offline: transport gate is closed".into());
14958        }
14959        if self.realtime_policy == RealtimePolicy::Off {
14960            return Err(
14961                "sync.invalid_request: realtime is off; realtime connect is refused".to_owned(),
14962            );
14963        }
14964        if self.realtime_connected() {
14965            return Ok(());
14966        }
14967        self.realtime_state = RealtimeState::Connecting;
14968        match transport.realtime_connect(&self.client_id) {
14969            Ok(()) => {
14970                self.set_realtime_state(RealtimeState::Connected, None);
14971                Ok(())
14972            }
14973            Err(error) => {
14974                self.set_realtime_state(RealtimeState::Refused, Some(&error.code));
14975                Err(format!("{}: {}", error.code, error.message))
14976            }
14977        }
14978    }
14979
14980    pub fn disconnect_realtime(&mut self, transport: &mut dyn Transport) {
14981        self.cancel_sync_round();
14982        // A deliberately disconnected or policy-disabled client has nothing
14983        // to release; a `lost` socket still does (the host owns the handle).
14984        if self.realtime_state == RealtimeState::Disconnected
14985            || self.realtime_state == RealtimeState::Disabled
14986        {
14987            return;
14988        }
14989        let _ = transport.realtime_close();
14990        self.set_realtime_state(
14991            if self.realtime_policy == RealtimePolicy::Off {
14992                RealtimeState::Disabled
14993            } else {
14994                RealtimeState::Disconnected
14995            },
14996            None,
14997        );
14998        self.presence.clear(); // §8.6.1: presence is per-connection
14999    }
15000
15001    /// §8.8: the host observed the socket end without disconnecting it (a
15002    /// peer close, an I/O error, a failed send; the native transport reports
15003    /// these as `Inbound::Disconnected`). Releases the transport, moves a
15004    /// `Connected` state to `Lost` with the transport's code as the reason, and schedules
15005    /// one background retry intent so the host reconnects and catches up.
15006    pub fn realtime_lost(&mut self, transport: &mut dyn Transport, error: &TransportError) {
15007        if self.realtime_state != RealtimeState::Connected {
15008            return;
15009        }
15010        self.cancel_sync_round();
15011        let _ = transport.realtime_close();
15012        self.set_realtime_state(RealtimeState::Lost, Some(&error.code));
15013        self.realtime_retry_delay_ms = Some(self.schedule_background_retry());
15014        self.presence.clear();
15015    }
15016
15017    /// §8.6.2: publish (or clear, `doc: None`) this client's presence
15018    /// document for `scope_key`. Requires a live socket; the document is
15019    /// ephemeral (lost on disconnect). Authorization is the connection's
15020    /// registration (§8.6.3) — an unheld key is rejected loudly by the
15021    /// server with `presence.forbidden`.
15022    pub fn set_presence(
15023        &mut self,
15024        transport: &mut dyn Transport,
15025        scope_key: &str,
15026        doc: Option<&Value>,
15027    ) -> Result<(), String> {
15028        if self.transport_closed() {
15029            return Err("sync.offline: transport gate is closed".into());
15030        }
15031        if !self.realtime_connected() {
15032            return Err("setPresence requires a connected realtime socket (§8.6)".to_string());
15033        }
15034        let text = encode_presence_publish(scope_key, doc);
15035        transport
15036            .realtime_send(&text)
15037            .map_err(|e| format!("{}: {}", e.code, e.message))
15038    }
15039
15040    /// §8.6: the peers currently present on a scope key (ephemeral).
15041    pub fn presence(&self, scope_key: &str) -> Vec<PresencePeer> {
15042        self.presence
15043            .get(scope_key)
15044            .map(|peers| peers.values().cloned().collect())
15045            .unwrap_or_default()
15046    }
15047
15048    /// §8.6 apply an inbound presence fanout to the local map.
15049    fn apply_presence(
15050        &mut self,
15051        scope_key: String,
15052        kind: Option<PresenceKind>,
15053        actor_id: Option<String>,
15054        client_id: Option<String>,
15055        doc: Option<Value>,
15056        error: Option<String>,
15057    ) {
15058        // A refused publish (§8.6.2) changes no peer; the native host surfaces
15059        // it as a `presence` event carrying the server's `error` code.
15060        if error.is_some() {
15061            return;
15062        }
15063        let (Some(kind), Some(actor_id), Some(client_id)) = (kind, actor_id, client_id) else {
15064            return;
15065        };
15066        let peer_key = format!("{actor_id} {client_id}");
15067        match kind {
15068            PresenceKind::Leave => {
15069                if let Some(peers) = self.presence.get_mut(&scope_key) {
15070                    peers.remove(&peer_key);
15071                    if peers.is_empty() {
15072                        self.presence.remove(&scope_key);
15073                    }
15074                }
15075            }
15076            _ => {
15077                let doc = match doc {
15078                    Some(Value::Object(_)) => doc.unwrap(),
15079                    _ => return,
15080                };
15081                self.presence.entry(scope_key).or_default().insert(
15082                    peer_key,
15083                    PresencePeer {
15084                        actor_id,
15085                        client_id,
15086                        doc,
15087                    },
15088                );
15089            }
15090        }
15091    }
15092
15093    /// Inbound JSON control message (§8.1). Unknown events are tolerated.
15094    pub fn on_realtime_text(&mut self, text: &str) {
15095        if self.stopped || self.transport_closed() || self.security_preflight {
15096            return;
15097        }
15098        match parse_control(text) {
15099            Ok(ControlMessage::Hello { requires_sync, .. }) => {
15100                if requires_sync {
15101                    // §8.1: pull before trusting the socket for continuity.
15102                    self.set_sync_needed(true, true);
15103                }
15104            }
15105            Ok(ControlMessage::Presence {
15106                scope_key,
15107                kind,
15108                actor_id,
15109                client_id,
15110                doc,
15111                error,
15112                ..
15113            }) => {
15114                self.apply_presence(scope_key, kind, actor_id, client_id, doc, error);
15115            }
15116            Ok(ControlMessage::Wake { .. }) => {
15117                // §8.3: any wake-up means "run a pull soon", never data.
15118                self.set_sync_needed(true, true);
15119            }
15120            Ok(ControlMessage::Scopes { .. }) => {
15121                // §3.3/§8.7: the grants changed, so the next `set_window`
15122                // re-arms every revoked value it names. No sync-needed, no round.
15123                self.window_armed.clear();
15124                self.scopes_changed += 1;
15125            }
15126            _ => {}
15127        }
15128    }
15129
15130    /// Inbound binary delta: a complete SSP2 response (§8.2), applied like
15131    /// a pull response per section; an unapplied delta is a wake-up.
15132    /// Mailbox hosts send durable acknowledgements on their I/O executor.
15133    pub fn on_realtime_binary_queued(&mut self, bytes: &[u8]) -> Vec<String> {
15134        let mut transport = crate::round::DownloadResults::default();
15135        self.on_realtime_binary(&mut transport, bytes);
15136        transport.controls
15137    }
15138
15139    /// §8.2: a delta applies exactly like a live section and sets the replica
15140    /// cursor to its `throughSeq`; one at or below the replica cursor is a
15141    /// duplicate. A delta the client does not apply (no live unit, a status
15142    /// other than `active`, a decode or apply failure) is a drop and raises
15143    /// sync-needed.
15144    pub fn on_realtime_binary(&mut self, transport: &mut dyn Transport, bytes: &[u8]) {
15145        if self.stopped || self.transport_closed() || self.security_preflight {
15146            return;
15147        }
15148        #[cfg(feature = "bench-internals")]
15149        let decode_phase = self.benchmark_phases.start(Phase::ResponseDecode);
15150        let message = match decode_message(bytes) {
15151            Ok(m) if m.msg_kind == MsgKind::Response => m,
15152            _ => {
15153                self.set_sync_needed(true, true);
15154                return;
15155            }
15156        };
15157        #[cfg(feature = "bench-internals")]
15158        drop(decode_phase);
15159        // §8.2: a delta's header means what a pull response's header means. A
15160        // schema floor (§1.6) is recorded, stops syncing and applies nothing.
15161        if let Some(Frame::RespHeader {
15162            required_schema_version: Some(required),
15163            latest_schema_version,
15164            ..
15165        }) = message.frames.first()
15166        {
15167            let floor = SchemaFloor {
15168                required_schema_version: Some(*required),
15169                latest_schema_version: *latest_schema_version,
15170            };
15171            if self.set_schema_floor(Some(floor)).is_err() {
15172                self.set_sync_needed(true, true);
15173            }
15174            return;
15175        }
15176        let through = message.frames.iter().find_map(|frame| match frame {
15177            Frame::LiveEnd { through_seq, .. } => Some(*through_seq),
15178            _ => None,
15179        });
15180        let epoch = self.get_meta(LOG_EPOCH_KEY).ok().flatten();
15181        let mut dropped = !matches!(message.frames.first(), Some(Frame::RespHeader {
15182                reset_required: false,
15183                log_epoch,
15184                ..
15185            }) if Some(log_epoch) == epoch.as_ref());
15186        let mut applied: Option<i64> = None;
15187        dropped |= self.begin_coalesced_apply().is_err();
15188        let mut receivers: Option<Vec<UnitRecord>> = None;
15189        for frame in message.frames {
15190            if dropped {
15191                break;
15192            }
15193            match frame {
15194                Frame::LiveStart { status, .. } => {
15195                    let Ok(cursor) = self.stored(replica_cursor(&self.conn)) else {
15196                        dropped = true;
15197                        break;
15198                    };
15199                    if status != LiveStatus::Active || cursor < 0 {
15200                        dropped = true;
15201                    } else if !through.is_some_and(|through| through <= cursor) {
15202                        // A catching-up unit receives no delta (§8.2).
15203                        receivers = self.stored(load_units(&self.conn)).ok().map(|units| {
15204                            units
15205                                .into_iter()
15206                                .filter(|unit| {
15207                                    unit.status == UnitStatus::Active
15208                                        && unit.echo.is_some()
15209                                        && unit.cursor.is_none()
15210                                })
15211                                .collect()
15212                        });
15213                        dropped = receivers.is_none();
15214                    }
15215                }
15216                Frame::Commit {
15217                    commit_seq,
15218                    tables,
15219                    changes,
15220                    ..
15221                } => {
15222                    let Some(receivers) = receivers.clone() else {
15223                        continue;
15224                    };
15225                    dropped = self
15226                        .apply_live_commit(
15227                            &receivers,
15228                            &tables,
15229                            changes,
15230                            commit_seq,
15231                            AppliedServerCommitSource::Delta,
15232                        )
15233                        .is_err();
15234                }
15235                Frame::LiveEnd { through_seq, .. } if receivers.is_some() => {
15236                    dropped = self
15237                        .set_meta(REPLICA_CURSOR_KEY, &through_seq.to_string())
15238                        .is_err();
15239                    applied = Some(through_seq);
15240                }
15241                Frame::Error { .. } => dropped = true,
15242                _ => {}
15243            }
15244        }
15245        // §1.4 rule 4: the ack follows the COMMIT. A failed COMMIT restored
15246        // the replica cursor, so the delta counts as a drop.
15247        if self.finish_coalesced_apply().is_err() || dropped {
15248            applied = None;
15249            dropped = true;
15250        }
15251        if let Some(cursor) = applied {
15252            // §8.2 ack point: the delta's throughSeq.
15253            let ack = format!("{{\"type\":\"ack\",\"cursor\":{cursor}}}");
15254            let _ = transport.realtime_send(&ack);
15255        }
15256        if dropped {
15257            self.set_sync_needed(true, true);
15258        }
15259    }
15260
15261    /// §8.2 ack point after a pull round on a live connection: the replica
15262    /// cursor while it is at least `0`.
15263    fn ack_after_pull(&mut self, transport: &mut dyn Transport) {
15264        if !self.realtime_connected() {
15265            return;
15266        }
15267        if let Ok(cursor @ 0..) = self.stored(replica_cursor(&self.conn)) {
15268            let ack = format!("{{\"type\":\"ack\",\"cursor\":{cursor}}}");
15269            let _ = transport.realtime_send(&ack);
15270        }
15271    }
15272}
15273
15274#[cfg(test)]
15275mod previous_version_wiring_tests;
15276
15277#[cfg(test)]
15278mod identity_tests;
15279
15280#[cfg(test)]
15281mod insert_intent_tests;
15282
15283#[cfg(test)]
15284mod robustness_tests;
15285
15286#[cfg(test)]
15287mod range_image_tests;