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.
4591                self.enqueue_startup_sync_if_needed()?;
4592                self.projection_pending_queue
4593                    .extend(self.collect_projection_pending()?);
4594                Ok(())
4595            })();
4596            self.opening_replica = false;
4597            let outcome = match guarded {
4598                Ok(()) => self
4599                    .conn
4600                    .execute_batch("COMMIT")
4601                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error).into()),
4602                Err(error) => Err(error),
4603            };
4604            if let Err(error) = outcome {
4605                if let Err(rollback) = self.conn.execute_batch("ROLLBACK") {
4606                    // Keep a failed rollback's typed storage classification.
4607                    let _ = Self::sqlite_failure(&self.storage_failure, rollback);
4608                }
4609                self.schema = prior_schema;
4610                self.restore(rollback);
4611                // Prepared insert statements were derived from the reverted schema.
4612                self.insert_sql.borrow_mut().clear();
4613                return Err(error);
4614            }
4615            if !self.security_preflight {
4616                self.drain_pending_evictions()?;
4617            }
4618            Ok(())
4619        })()
4620        .map_err(open_failure)
4621    }
4622
4623    fn enqueue_startup_sync_if_needed(&mut self) -> Result<(), String> {
4624        let startup_work = !self.stopped
4625            && (!self.outbox.is_empty()
4626                || self.has_acknowledged_rows()?
4627                || !self.load_pending_evictions()?.is_empty()
4628                || self
4629                    .stored(load_units(&self.conn))?
4630                    .iter()
4631                    .any(|unit| unit.status == UnitStatus::Active));
4632        if startup_work {
4633            self.sync_needed = true;
4634            self.sync_intent_queue.push_back(SyncIntent::Interactive);
4635        }
4636        Ok(())
4637    }
4638
4639    /// A native client persists schema-floor stops across process restarts.
4640    /// Once the running app already satisfies that floor, the persisted stop
4641    /// is only stale evidence from an older server round (for example, the
4642    /// server was restarted after catching up to an app that was ahead).
4643    /// Clear it and let the normal startup pull re-negotiate. If the server is
4644    /// still incompatible it will return the floor again in that first round.
4645    fn clear_satisfied_persisted_schema_floor(&mut self) -> Result<(), String> {
4646        let satisfied = self
4647            .schema_floor
4648            .as_ref()
4649            .and_then(|floor| floor.required_schema_version)
4650            .is_some_and(|required| self.schema.version >= required);
4651        if !satisfied {
4652            return Ok(());
4653        }
4654        self.delete_meta(SCHEMA_FLOOR_KEY)?;
4655        self.schema_floor = None;
4656        self.stopped = false;
4657        Ok(())
4658    }
4659
4660    /// RFC 0005 D1: discard an orphan or stale container at boot. The reset
4661    /// path already swept it; this covers a same-version or fresh-install open,
4662    /// which runs no reset and therefore no sweep — plus the D7 TTL, which only
4663    /// an aware binary can apply.
4664    fn reconcile_previous_version_at_boot(&self) -> Result<(), String> {
4665        let Some(replica_path) = self.previous_version_replica_path() else {
4666            return Ok(());
4667        };
4668        let max_age_ms = self
4669            .previous_version
4670            .filter(|config| config.enabled)
4671            .map(|config| config.max_age_ms);
4672        reconcile_previous_version_at_boot(
4673            &self.conn,
4674            &replica_path,
4675            self.schema.version,
4676            max_age_ms,
4677            self.clock_now_ms(),
4678        )
4679    }
4680
4681    /// RFC 0005 D3: the sibling container path, or `None` when the replica has
4682    /// no file — an in-memory replica returns an empty path, and a `file:` URI
4683    /// has no plain sibling path — so the feature resolves as off there.
4684    fn previous_version_replica_path(&self) -> Option<String> {
4685        let path = self.conn.path()?;
4686        if path.is_empty() || path.starts_with("file:") {
4687            return None;
4688        }
4689        Some(path.to_owned())
4690    }
4691
4692    /// §7.4.3 reset: whole-database local reset EXCEPT the outbox, clientId,
4693    /// and leaseState. Drops/recreates every synced table from the new
4694    /// schema, resets unit sync state (keeping registrations), clears
4695    /// the schema-floor stop state, rewrites the marker, drops outbox commits
4696    /// that cannot re-encode (§7.4.4), and replays the survivors on top.
4697    fn run_schema_reset(&mut self) -> Result<(), String> {
4698        self.begin_observation("syncular_schema_reset")?;
4699        let rollback = self.capture();
4700        let mut batch = ChangeAccumulator::default();
4701        let result = self
4702            .run_schema_reset_observed(&mut batch, true)
4703            .and_then(|()| self.finish_observation("syncular_schema_reset", batch));
4704        if let Err(error) = result {
4705            self.rollback_observation("syncular_schema_reset");
4706            self.restore(rollback);
4707            return Err(error);
4708        }
4709        // After the commit: a rolled-back reset keeps the in-flight round.
4710        self.cancel_sync_round();
4711        Ok(())
4712    }
4713
4714    fn run_log_epoch_reset(&mut self, log_epoch: &str) -> Result<Vec<String>, String> {
4715        if self.get_meta(LOG_EPOCH_KEY)?.is_none() {
4716            self.begin_observation("syncular_epoch_acquisition")?;
4717            let rollback = self.capture();
4718            if let Err(error) = self.conn.execute(
4719                "INSERT OR REPLACE INTO _syncular_meta(key,value) VALUES (?1,?2)",
4720                rusqlite::params![LOG_EPOCH_KEY, log_epoch],
4721            ) {
4722                self.rollback_observation("syncular_epoch_acquisition");
4723                return Err(Self::sqlite_failure(&self.storage_failure, error));
4724            }
4725            self.sync_needed = true;
4726            let batch = ChangeAccumulator {
4727                status: true,
4728                ..ChangeAccumulator::default()
4729            };
4730            if let Err(error) = self.finish_observation("syncular_epoch_acquisition", batch) {
4731                self.rollback_observation("syncular_epoch_acquisition");
4732                self.restore(rollback);
4733                return Err(error);
4734            }
4735            self.sync_intent_queue.push_back(SyncIntent::Interactive);
4736            return Ok(Vec::new());
4737        }
4738        let resets = self
4739            .stored(load_units(&self.conn))?
4740            .into_iter()
4741            .map(|unit| unit.id)
4742            .collect();
4743        self.begin_observation("syncular_log_epoch_reset")?;
4744        let rollback = self.capture();
4745        let mut batch = ChangeAccumulator::default();
4746        let result = self
4747            .run_schema_reset_observed(&mut batch, false)
4748            .and_then(|()| {
4749                self.conn
4750                    .execute(
4751                        "INSERT OR REPLACE INTO _syncular_meta(key,value) VALUES (?1,?2)",
4752                        rusqlite::params![LOG_EPOCH_KEY, log_epoch],
4753                    )
4754                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4755                self.sync_needed = true;
4756                batch.status = true;
4757                self.finish_observation("syncular_log_epoch_reset", batch)
4758            });
4759        if let Err(error) = result {
4760            self.rollback_observation("syncular_log_epoch_reset");
4761            self.restore(rollback);
4762            return Err(error);
4763        }
4764        self.cancel_sync_round();
4765        self.sync_intent_queue.push_back(SyncIntent::Interactive);
4766        Ok(resets)
4767    }
4768
4769    fn run_schema_reset_observed(
4770        &mut self,
4771        batch: &mut ChangeAccumulator,
4772        capture: bool,
4773    ) -> Result<(), String> {
4774        // §7.4.2: the reset is the only path that wipes local tables for a
4775        // version bump, and it rewrites the marker last. Re-read the marker
4776        // under this reset's transaction: a replica another process upgraded
4777        // meanwhile refuses here instead of being reset to this client's
4778        // older schema.
4779        read_local_schema_version(&self.conn, self.schema.version)
4780            .map_err(|error| error.to_string())?;
4781        // §7.4.3: a schema bump keeps every table whose generation or one of
4782        // its equivalent generations equals the persisted one; the log-epoch
4783        // reset keeps nothing. The previous
4784        // declaration evidence decides which units cover only kept tables.
4785        let mut kept = BTreeSet::new();
4786        let mut previous_declarations: Option<BTreeMap<String, BTreeMap<String, Value>>> = None;
4787        if capture {
4788            let persisted: BTreeMap<String, String> = self
4789                .get_meta(TABLE_GENERATIONS_KEY)?
4790                .map(|raw| serde_json::from_str(&raw))
4791                .transpose()
4792                .map_err(|_| "sync.local_corrupt: invalid persisted table generations".to_owned())?
4793                .unwrap_or_default();
4794            kept = self
4795                .schema
4796                .tables
4797                .iter()
4798                .filter(|table| {
4799                    table.generation.is_some()
4800                        && persisted.get(&table.name).is_some_and(|stored| {
4801                            table.generation.as_ref() == Some(stored)
4802                                || table.equivalent_generations.contains(stored)
4803                        })
4804                })
4805                .map(|table| table.name.clone())
4806                .collect();
4807            previous_declarations = self
4808                .get_meta("subscriptionScopeSchema")?
4809                .map(|raw| serde_json::from_str(&raw))
4810                .transpose()
4811                .map_err(|_| "sync.local_corrupt: invalid persisted scope schema".to_owned())?;
4812        }
4813        // Kept tables keep both halves and their row-level bookkeeping; the
4814        // projections of kept tables keep their storage.
4815        let mut kept_objects = BTreeSet::new();
4816        for table in self
4817            .schema
4818            .tables
4819            .iter()
4820            .filter(|table| kept.contains(&table.name))
4821        {
4822            kept_objects.insert(table.name.clone());
4823            kept_objects.insert(format!("_syncular_base_{}", table.name));
4824        }
4825        kept_objects.extend(self.detach_projections(Some(&kept))?);
4826        let kept_json = serde_json::to_string(&kept).expect("table names serialize");
4827        for sql in [
4828            "DELETE FROM _syncular_acked_rows WHERE tbl NOT IN (SELECT value FROM json_each(?1))",
4829            "DELETE FROM _syncular_row_deliveries WHERE tbl NOT IN (SELECT value FROM json_each(?1))",
4830        ] {
4831            self.conn
4832                .execute(sql, [&kept_json])
4833                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4834        }
4835        self.upgrading = true;
4836        self.upgrade_kept_tables = !kept.is_empty();
4837        batch.status = true;
4838        // RFC 0005 D6: classify the pending outbox against the NEW compiled
4839        // schema BEFORE the wipe, and record the advisory audit. This pass
4840        // drops nothing, so the audit sees the original pending intent; the
4841        // §7.4.4 send-time drop and the intrinsic value recovery later in this
4842        // reset are the paths that remove a commit. The classification is
4843        // shared with the send-time drop so the two cannot disagree about what
4844        // is incompatible.
4845        if self.previous_version.is_some_and(|config| config.enabled) {
4846            let previous_version = self
4847                .get_meta(LOCAL_SCHEMA_VERSION_KEY)?
4848                .and_then(|value| value.parse::<i32>().ok())
4849                .unwrap_or(self.schema.version);
4850            let pending = self
4851                .outbox
4852                .iter()
4853                .map(|commit| PendingCommitAudit {
4854                    commit_id: &commit.client_commit_id,
4855                    operations: commit_audit_operations(commit),
4856                })
4857                .collect::<Vec<_>>();
4858            crate::previous_version::write_previous_version_audit(
4859                &self.conn,
4860                &crate::previous_version::build_previous_version_audit(
4861                    &self.schema,
4862                    &pending,
4863                    previous_version,
4864                    self.schema.version,
4865                    self.clock_now_ms(),
4866                ),
4867            )?;
4868        }
4869        // RFC 0005 D5: the container lives in its own FILE, so the reset can
4870        // never reach it. Sweep first (unconditional — also on the log-epoch
4871        // reset, which captures nothing), then capture BEFORE the wipe drops
4872        // any row. A refused capture records its reason and leaves no file.
4873        if let Some(replica_path) = self.previous_version_replica_path() {
4874            sweep_previous_version_container(&self.conn, &replica_path)?;
4875            if capture {
4876                if let Some(config) = self.previous_version.filter(|config| config.enabled) {
4877                    let previous_version = self
4878                        .get_meta(LOCAL_SCHEMA_VERSION_KEY)?
4879                        .and_then(|value| value.parse::<i32>().ok())
4880                        .unwrap_or(self.schema.version);
4881                    capture_previous_version_from_replica(
4882                        &self.conn,
4883                        &replica_path,
4884                        previous_version,
4885                        self.schema.version,
4886                        &config,
4887                        self.clock_now_ms(),
4888                    )?;
4889                }
4890            }
4891        }
4892        for table in self
4893            .schema
4894            .tables
4895            .iter()
4896            .filter(|table| !kept.contains(&table.name))
4897        {
4898            batch.table(&table.name);
4899        }
4900        for unit in self.stored(load_units(&self.conn))? {
4901            self.record_unit_windows(batch, &unit)?;
4902        }
4903        if capture {
4904            self.prune_unknown_units(true)?;
4905        }
4906        // The per-table insert SQL is derived from the OLD column lists.
4907        self.insert_sql.borrow_mut().clear();
4908        self.overlay_dirty.set(true);
4909        // Drop every synced table (base + visible) that currently exists —
4910        // discovered from sqlite_master so a bump that adds/removes tables is
4911        // handled. Bookkeeping tables (`_syncular_outbox/_units/_meta`
4912        // and the blob cache) are preserved; base tables are `_syncular_base_*`
4913        // so they are matched explicitly, not by the bookkeeping filter.
4914        // Drop virtual tables first so SQLite removes every FTS shadow table
4915        // atomically instead of the generic discovery tearing it apart.
4916        let virtual_tables: Vec<String> = {
4917            let mut stmt = self
4918                .conn
4919                .prepare(
4920                    "SELECT name FROM sqlite_master WHERE type = 'table' AND sql LIKE 'CREATE VIRTUAL TABLE%'",
4921                )
4922                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4923            let rows = stmt
4924                .query_map([], |row| row.get::<_, String>(0))
4925                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4926            rows.filter_map(Result::ok)
4927                .filter(|name| is_synced_table_name(name) && !kept_objects.contains(name))
4928                .collect()
4929        };
4930        for name in virtual_tables {
4931            self.conn
4932                .execute_batch(&format!(
4933                    "DROP TABLE IF EXISTS {}",
4934                    quote_ident(&format!("_syncular_fts_{name}"))
4935                ))
4936                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4937            self.conn
4938                .execute(&format!("DROP TABLE IF EXISTS {}", quote_ident(&name)), [])
4939                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4940        }
4941        let existing: Vec<String> = {
4942            let mut stmt = self
4943                .conn
4944                .prepare("SELECT name FROM sqlite_master WHERE type = 'table'")
4945                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4946            let rows = stmt
4947                .query_map([], |row| row.get::<_, String>(0))
4948                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4949            rows.filter_map(Result::ok)
4950                .filter(|name| is_synced_table_name(name) && !kept_objects.contains(name))
4951                .collect()
4952        };
4953        for name in &existing {
4954            if let Some(table) = name.strip_prefix("_syncular_base_") {
4955                batch.table(table);
4956            } else if !name.starts_with("_syncular_") {
4957                batch.table(name);
4958            }
4959        }
4960        for name in existing {
4961            self.conn
4962                .execute(&format!("DROP TABLE IF EXISTS {}", quote_ident(&name)), [])
4963                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4964        }
4965        // Recreate the synced tables from the NEW schema.
4966        self.create_synced_tables()?;
4967        // Reset the sync state of every unit that covers a table the reset
4968        // did not keep, under the previous declarations or the new schema,
4969        // keeping the registration.
4970        let keep_units = match &previous_declarations {
4971            Some(previous) if !kept.is_empty() => self
4972                .stored(load_units(&self.conn))?
4973                .into_iter()
4974                .filter(|unit| {
4975                    previous.iter().all(|(name, old)| {
4976                        kept.contains(name) || !unit.scopes.keys().all(|v| old.contains_key(v))
4977                    }) && self
4978                        .schema
4979                        .tables
4980                        .iter()
4981                        .all(|table| kept.contains(&table.name) || !covers(table, &unit.scopes))
4982                })
4983                .map(|unit| unit.id)
4984                .collect(),
4985            _ => BTreeSet::new(),
4986        };
4987        // §7.4.3 restriction: an active unit that is not kept and whose rows
4988        // of a kept table are complete through a cursor C (its restriction's,
4989        // its post-bootstrap P, or the replica cursor it is live under)
4990        // bootstraps only its other covered tables and joins at C.
4991        let restrictions = if capture {
4992            let replica = self.stored(replica_cursor(&self.conn))?;
4993            let mut restrictions = BTreeMap::new();
4994            for unit in self.stored(load_units(&self.conn))? {
4995                if keep_units.contains(&unit.id) || unit.status != UnitStatus::Active {
4996                    continue;
4997                }
4998                let cursor = match (&unit.restriction, unit.cursor) {
4999                    (Some(restriction), _) => restriction.cursor,
5000                    (None, Some(cursor)) if cursor >= 0 && unit.bootstrap_state.is_none() => cursor,
5001                    (None, None) if replica >= 0 => replica,
5002                    _ => continue,
5003                };
5004                let covered: Vec<&String> = self
5005                    .schema
5006                    .tables
5007                    .iter()
5008                    .filter(|table| covers(table, &unit.scopes))
5009                    .map(|table| &table.name)
5010                    .collect();
5011                let mut tables: Vec<String> = covered
5012                    .iter()
5013                    .filter(|name| {
5014                        !kept.contains(**name)
5015                            || unit
5016                                .restriction
5017                                .as_ref()
5018                                .is_some_and(|restriction| restriction.tables.contains(name))
5019                    })
5020                    .map(|name| (*name).clone())
5021                    .collect();
5022                if tables.is_empty() || tables.len() == covered.len() {
5023                    continue;
5024                }
5025                tables.sort_by(|a, b| a.encode_utf16().cmp(b.encode_utf16()));
5026                restrictions.insert(unit.id, UnitRestriction { cursor, tables });
5027            }
5028            Some(restrictions)
5029        } else {
5030            None
5031        };
5032        reset_units(&self.conn, &keep_units, restrictions.as_ref())
5033            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5034        // The stop state is over: this client now ships a servable schema.
5035        self.stopped = false;
5036        self.schema_floor = None;
5037        self.delete_meta(SCHEMA_FLOOR_KEY)?;
5038        // Rewrite the marker LAST so a crash mid-reset re-runs the reset.
5039        self.persist_schema_version()?;
5040        self.save_unit_scope_schema()?;
5041        // §7.1/§7.4.4: the previous-version capture and audit above saw the
5042        // original pending intent; the synced tables now carry the new schema, so
5043        // recover intrinsically codec-invalid persisted values here, before the
5044        // final replay. A pending upsert that names a column the new schema
5045        // removed stays pending for the send-time `drop_incompatible_outbox`
5046        // prepass. The reset wrapper snapshots and restores the outbox,
5047        // rejections, and change queues, so a failed commit rolls this recovery
5048        // back with the rest of the reset.
5049        // §7.4.4: the enclosing reset observation owns the publication, so the
5050        // recovery contributes its rejection, outcome, and table domains to it.
5051        self.drop_unencodable_outbox(false, Some(batch))?;
5052        // Re-apply the surviving outbox optimistically over the empty tables.
5053        self.rebuild_overlay()?;
5054        Ok(())
5055    }
5056
5057    /// §7.4.4 send-time prepass: a persisted upsert whose values reference a
5058    /// column the current schema lacks (or a removed table) cannot be encoded
5059    /// (`commit_audit_operations` inspects upserts, so a value-free delete stays
5060    /// encodable and is validated by the server), nor can an insert-intent
5061    /// upsert that lacks a non-nullable column (§7.1, the audit's
5062    /// `missing-required-column`). Drop the commit, undo
5063    /// its optimistic projection, and raise a client-local
5064    /// `sync.outbox_incompatible` rejection.
5065    fn drop_incompatible_outbox(&mut self) -> Result<bool, String> {
5066        // §8.8: only the commits this round pushes; a held commit waits.
5067        let incompatible = self
5068            .outbox
5069            .iter()
5070            .take(self.pushable_commits())
5071            .filter(|commit| {
5072                first_incompatibility(&self.schema, &commit_audit_operations(commit)).is_some()
5073            })
5074            .cloned()
5075            .collect::<Vec<_>>();
5076        if incompatible.is_empty() {
5077            return Ok(false);
5078        }
5079        self.drop_outbox_commits(
5080            &incompatible,
5081            OUTBOX_INCOMPATIBLE_CODE,
5082            "the persisted commit cannot encode under the current schema",
5083        )?;
5084        Ok(true)
5085    }
5086
5087    /// §7.4.4 incompatible-commit path, also taken by a refused blob upload
5088    /// (§5.9.7) with the server's code: reject every operation of `commits`,
5089    /// remove them from the outbox, and undo their optimistic rows.
5090    fn drop_outbox_commits(
5091        &mut self,
5092        incompatible: &[Arc<OutboxCommit>],
5093        code: &str,
5094        message: &str,
5095    ) -> Result<(), String> {
5096        // §7.4.4: one observation covers the durable outcome writes, the outbox
5097        // removal, the in-memory drop, and the overlay rebuild, so a storage
5098        // fault leaves the replica and the client unchanged and publishes no
5099        // change; a successful drop publishes exactly one batch carrying the
5100        // rejections, outcomes, status, and the tables whose projection changed.
5101        let rollback = self.capture();
5102        let owns_transaction = self.conn.is_autocommit();
5103        self.begin_observation("syncular_outbox_drop")?;
5104        let mut batch = ChangeAccumulator::default();
5105        let dropped = (|| -> Result<(), String> {
5106            let mut rejections = Vec::new();
5107            for commit in incompatible {
5108                let results = commit
5109                    .ops
5110                    .iter()
5111                    .enumerate()
5112                    .map(|(op_index, operation)| {
5113                        let rejection = RejectionRecord {
5114                            client_commit_id: commit.client_commit_id.clone(),
5115                            op_index: op_index as i32,
5116                            code: code.to_owned(),
5117                            message: message.to_owned(),
5118                            retryable: false,
5119                            details: None,
5120                            operation: Some(CommitOperation::from(operation)),
5121                        };
5122                        rejections.push(rejection.clone());
5123                        CommitOperationOutcome::Error { rejection }
5124                    })
5125                    .collect::<Vec<_>>();
5126                self.persist_commit_outcome(
5127                    &commit.client_commit_id,
5128                    CommitOutcomeStatus::Rejected,
5129                    &results,
5130                    Some(&commit.ops),
5131                )?;
5132                self.leave_through(&commit.client_commit_id);
5133                self.delete_outbox_persisted(&commit.client_commit_id)?;
5134                // A removed table has no local projection to invalidate; every
5135                // surviving table the dropped commit touched does.
5136                for operation in &commit.ops {
5137                    if self.schema.table(&operation.table).is_some() {
5138                        batch.table(&operation.table);
5139                    }
5140                }
5141            }
5142            self.prune_commit_outcomes()?;
5143            let incompatible_ids = incompatible
5144                .iter()
5145                .map(|commit| commit.client_commit_id.as_str())
5146                .collect::<BTreeSet<_>>();
5147            self.outbox
5148                .retain(|commit| !incompatible_ids.contains(commit.client_commit_id.as_str()));
5149            self.rejections.extend(rejections);
5150            // The dropped commits' purely-optimistic rows are undone: the
5151            // visible projection is re-derived from the surviving base + outbox.
5152            self.overlay_dirty.set(true);
5153            self.rebuild_overlay()?;
5154            batch.status = true;
5155            batch.rejections = true;
5156            batch.outcomes = true;
5157            Ok(())
5158        })();
5159        let result = dropped.and_then(|()| self.finish_observation("syncular_outbox_drop", batch));
5160        if let Err(error) = result {
5161            // An outer RELEASE is the COMMIT. Roll back that transaction
5162            // directly: retrying RELEASE after ROLLBACK TO still needs the
5163            // reader's lock. A nested observation only rolls back its savepoint.
5164            if owns_transaction {
5165                if let Err(rollback) = self.conn.execute_batch("ROLLBACK") {
5166                    let mut failure = self.storage_failure.borrow_mut();
5167                    let failure =
5168                        failure.get_or_insert_with(|| QueryReadFailure::from(error.clone()));
5169                    failure.rollback_failure = Some(Box::new(QueryReadFailure::from(rollback)));
5170                }
5171            } else {
5172                self.rollback_observation("syncular_outbox_drop");
5173            }
5174            self.restore(rollback);
5175            return Err(error);
5176        }
5177        Ok(())
5178    }
5179
5180    /// §7.4.3: (re)create the base + visible table pair for every synced
5181    /// table in the CURRENT schema (idempotent — `IF NOT EXISTS`).
5182    fn create_synced_tables(&self) -> Result<(), String> {
5183        for table in &self.schema.tables {
5184            // The base half + the visible half form the synced-table pair. An
5185            // index name is global in SQLite, so the base half's indexes are
5186            // name-prefixed (`_syncular_base_<index>`) to stay distinct.
5187            for (full, index_prefix) in [
5188                (base_table(&table.name), "_syncular_base_"),
5189                (visible_table(&table.name), ""),
5190            ] {
5191                let mut cols: Vec<String> =
5192                    table.columns.iter().map(|c| quote_ident(&c.name)).collect();
5193                cols.push("\"_syncular_version\" INTEGER NOT NULL".to_owned());
5194                cols.extend(
5195                    table
5196                        .sealed_columns()
5197                        .iter()
5198                        .map(|name| format!("{} TEXT", quote_ident(name))),
5199                );
5200                let sql = format!(
5201                    "CREATE TABLE IF NOT EXISTS {full} ({} , PRIMARY KEY ({}))",
5202                    cols.join(", "),
5203                    quote_ident(&table.primary_key)
5204                );
5205                self.conn
5206                    .execute(&sql, [])
5207                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5208                // §5.11: a replica created before sealed apply gains the
5209                // reserved columns in place, on both halves in the same order,
5210                // so data, indexes and the FTS projection stay.
5211                for name in table.sealed_columns() {
5212                    let present: bool = self
5213                        .conn
5214                        .query_row(
5215                            "SELECT EXISTS(SELECT 1 FROM pragma_table_info(?1) WHERE name = ?2)",
5216                            rusqlite::params![format!("{index_prefix}{}", table.name), name],
5217                            |row| row.get(0),
5218                        )
5219                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5220                    if !present {
5221                        self.conn
5222                            .execute(
5223                                &format!(
5224                                    "ALTER TABLE {full} ADD COLUMN {} TEXT",
5225                                    quote_ident(name)
5226                                ),
5227                                [],
5228                            )
5229                            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5230                    }
5231                }
5232                // The reveal at every round start reads the sealed rows of the
5233                // base half through this partial index.
5234                if table.has_encrypted_columns() && !index_prefix.is_empty() {
5235                    self.conn
5236                        .execute(
5237                            &format!(
5238                                "CREATE INDEX IF NOT EXISTS {} ON {full} (\"_sync_sealed_key\") WHERE \"_sync_sealed_key\" IS NOT NULL",
5239                                quote_ident(&format!("_syncular_sealed_{}", table.name))
5240                            ),
5241                            [],
5242                        )
5243                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5244                }
5245            }
5246        }
5247        // §7.4.3 declared indexes: reconciled in place on both halves (the
5248        // base half's names carry the `_syncular_base_` prefix) at every open
5249        // and at the end of every reset. `localIndexes` records the declared
5250        // names Syncular created; only those are ever dropped.
5251        let recorded: BTreeMap<String, BTreeSet<String>> = match self.get_meta("localIndexes")? {
5252            Some(raw) => serde_json::from_str(&raw)
5253                .map_err(|_| "sync.local_corrupt: invalid persisted local indexes".to_owned())?,
5254            // A replica without the record: every declared index that exists
5255            // counts as created by Syncular, so nothing is stale.
5256            None => BTreeMap::new(),
5257        };
5258        let declared: BTreeMap<String, BTreeSet<String>> = self
5259            .schema
5260            .tables
5261            .iter()
5262            .filter(|table| !table.indexes.is_empty())
5263            .map(|table| {
5264                let names = table.indexes.iter().map(|index| index.name.clone());
5265                (table.name.clone(), names.collect())
5266            })
5267            .collect();
5268        for (table, names) in &recorded {
5269            for name in names.iter().filter(|name| {
5270                !declared
5271                    .get(table)
5272                    .is_some_and(|declared| declared.contains(*name))
5273            }) {
5274                self.stored(self.conn.execute_batch(&format!(
5275                    "DROP INDEX IF EXISTS {}; DROP INDEX IF EXISTS {}",
5276                    quote_ident(name),
5277                    quote_ident(&format!("_syncular_base_{name}"))
5278                )))?;
5279            }
5280        }
5281        for table in &self.schema.tables {
5282            for index in &table.indexes {
5283                for (owner, name) in [
5284                    (
5285                        format!("_syncular_base_{}", table.name),
5286                        format!("_syncular_base_{}", index.name),
5287                    ),
5288                    (table.name.clone(), index.name.clone()),
5289                ] {
5290                    let current: Option<(String, bool, bool)> = self.stored(
5291                        self.conn
5292                            .query_row(
5293                                "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",
5294                                [&name],
5295                                |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
5296                            )
5297                            .optional(),
5298                    )?;
5299                    if let Some((current_owner, unique, partial)) = current {
5300                        let mut stmt = self
5301                            .stored(self.conn.prepare(
5302                                "SELECT name FROM pragma_index_info(?1) ORDER BY seqno",
5303                            ))?;
5304                        let columns = self.stored(
5305                            self.stored(
5306                                stmt.query_map([&name], |row| row.get::<_, Option<String>>(0)),
5307                            )?
5308                            .collect::<Result<Vec<_>, _>>(),
5309                        )?;
5310                        if current_owner == owner
5311                            && unique == index.unique
5312                            && !partial
5313                            && columns
5314                                .iter()
5315                                .map(Option::as_deref)
5316                                .eq(index.columns.iter().map(|column| Some(column.as_str())))
5317                        {
5318                            continue;
5319                        }
5320                        self.stored(
5321                            self.conn
5322                                .execute(&format!("DROP INDEX {}", quote_ident(&name)), []),
5323                        )?;
5324                    }
5325                    self.stored(self.conn.execute(
5326                        &format!(
5327                            "CREATE {}INDEX {} ON {} ({})",
5328                            if index.unique { "UNIQUE " } else { "" },
5329                            quote_ident(&name),
5330                            quote_ident(&owner),
5331                            index
5332                                .columns
5333                                .iter()
5334                                .map(|column| quote_ident(column))
5335                                .collect::<Vec<_>>()
5336                                .join(", ")
5337                        ),
5338                        [],
5339                    ))?;
5340                }
5341            }
5342        }
5343        self.set_meta(
5344            "localIndexes",
5345            &serde_json::to_string(&declared).expect("index names serialize"),
5346        )?;
5347        self.open_projections()
5348    }
5349
5350    fn create_fts_storage(
5351        &self,
5352        name: &str,
5353        columns: &str,
5354        tokenize: &str,
5355        options: &str,
5356    ) -> Result<(), String> {
5357        let tokenizer = tokenize.replace('\'', "''");
5358        let sql = format!(
5359            "CREATE VIRTUAL TABLE IF NOT EXISTS {} USING fts5({} UNINDEXED, {columns}, tokenize='{tokenizer}'{options})",
5360            quote_ident(name),
5361            quote_ident(FTS_SOURCE_ID_COLUMN),
5362        );
5363        self.conn
5364            .execute(&sql, [])
5365            .map_err(|error| format!("cannot create local FTS5 projection {name:?}: {error}"))?;
5366        let mapping = quote_ident(&format!("_syncular_fts_{name}"));
5367        self.stored(self.conn.execute_batch(&format!("CREATE TABLE IF NOT EXISTS {mapping}(id INTEGER PRIMARY KEY, source_id TEXT NOT NULL UNIQUE)")))
5368    }
5369
5370    // -- persistence write-through --------------------------------------------
5371
5372    fn persist_outbox_insert(&self, commit: &OutboxCommit) -> Result<(), String> {
5373        let ops: Vec<Value> = commit
5374            .ops
5375            .iter()
5376            .map(|op| {
5377                let mut entry = serde_json::json!({
5378                    "op": if op.upsert { "upsert" } else { "delete" },
5379                    "table": op.table,
5380                    "rowId": op.row_id,
5381                    "baseVersion": op.base_version,
5382                    "values": op.values.clone().map(Value::Object),
5383                });
5384                if op.insert {
5385                    entry["insert"] = Value::Bool(true);
5386                }
5387                entry
5388            })
5389            .collect();
5390        self.conn
5391            .execute(
5392                "INSERT OR REPLACE INTO _syncular_outbox (commit_id, ops_json, created_at_ms, attempted) VALUES (?1, ?2, ?3, 0)",
5393                rusqlite::params![
5394                    commit.client_commit_id,
5395                    Value::Array(ops).to_string(),
5396                    self.clock_now_ms()
5397                ],
5398            )
5399            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5400        for operation in &commit.ops {
5401            let Some(values) = &operation.values else {
5402                continue;
5403            };
5404            let Some(table) = self.schema.table(&operation.table) else {
5405                continue;
5406            };
5407            for column in table
5408                .columns
5409                .iter()
5410                .filter(|column| column.ty == ColumnType::BlobRef)
5411            {
5412                let Some(Value::String(raw)) = values.get(&column.name) else {
5413                    continue;
5414                };
5415                let Ok(blob_ref) = serde_json::from_str::<Value>(raw) else {
5416                    continue;
5417                };
5418                let Some(blob_id) = blob_ref.get("blobId").and_then(Value::as_str) else {
5419                    continue;
5420                };
5421                self.conn
5422                    .execute(
5423                        "INSERT OR IGNORE INTO _syncular_blob_commit_refs(commit_id, blob_id)
5424                         SELECT ?1, ?2 WHERE EXISTS (SELECT 1 FROM _syncular_blobs WHERE blob_id = ?2)",
5425                        rusqlite::params![commit.client_commit_id, blob_id],
5426                    )
5427                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5428            }
5429        }
5430        Ok(())
5431    }
5432
5433    fn delete_outbox_persisted(&self, client_commit_id: &str) -> Result<(), String> {
5434        self.conn
5435            .execute(
5436                "DELETE FROM _syncular_blob_commit_refs WHERE commit_id = ?1",
5437                rusqlite::params![client_commit_id],
5438            )
5439            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5440        self.conn
5441            .execute(
5442                "DELETE FROM _syncular_outbox WHERE commit_id = ?1",
5443                rusqlite::params![client_commit_id],
5444            )
5445            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5446        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)", [])
5447            .map(|_| ())
5448            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
5449    }
5450
5451    fn outcome_status_name(status: CommitOutcomeStatus) -> &'static str {
5452        match status {
5453            CommitOutcomeStatus::Applied => "applied",
5454            CommitOutcomeStatus::Cached => "cached",
5455            CommitOutcomeStatus::Conflict => "conflict",
5456            // §7.2.1: a replaced commit is stored as a decided rejection.
5457            CommitOutcomeStatus::Rejected | CommitOutcomeStatus::Replaced => "rejected",
5458        }
5459    }
5460
5461    fn outcome_resolution_name(resolution: CommitOutcomeResolution) -> &'static str {
5462        match resolution {
5463            CommitOutcomeResolution::Active => "active",
5464            CommitOutcomeResolution::ResolvedKeepServer => "resolved_keep_server",
5465            CommitOutcomeResolution::Superseded => "superseded",
5466            CommitOutcomeResolution::Dismissed => "dismissed",
5467        }
5468    }
5469
5470    fn parse_outcome_status(value: &str) -> Result<CommitOutcomeStatus, String> {
5471        match value {
5472            "applied" => Ok(CommitOutcomeStatus::Applied),
5473            "cached" => Ok(CommitOutcomeStatus::Cached),
5474            "conflict" => Ok(CommitOutcomeStatus::Conflict),
5475            "rejected" => Ok(CommitOutcomeStatus::Rejected),
5476            _ => Err(format!("invalid persisted commit outcome status {value:?}")),
5477        }
5478    }
5479
5480    fn parse_outcome_resolution(value: &str) -> Result<CommitOutcomeResolution, String> {
5481        match value {
5482            "active" => Ok(CommitOutcomeResolution::Active),
5483            "resolved_keep_server" => Ok(CommitOutcomeResolution::ResolvedKeepServer),
5484            "superseded" => Ok(CommitOutcomeResolution::Superseded),
5485            "dismissed" => Ok(CommitOutcomeResolution::Dismissed),
5486            _ => Err(format!(
5487                "invalid persisted commit outcome resolution {value:?}"
5488            )),
5489        }
5490    }
5491
5492    fn persist_commit_outcome(
5493        &self,
5494        client_commit_id: &str,
5495        status: CommitOutcomeStatus,
5496        results: &[CommitOperationOutcome],
5497        operations: Option<&[OutboxOp]>,
5498    ) -> Result<(), String> {
5499        let results_json = serde_json::to_string(results).map_err(|error| error.to_string())?;
5500        let operations_json = operations
5501            .map(|items| {
5502                serde_json::to_string(&items.iter().map(CommitOperation::from).collect::<Vec<_>>())
5503            })
5504            .transpose()
5505            .map_err(|error| error.to_string())?;
5506        self.conn
5507            .execute(
5508                "INSERT INTO _syncular_commit_outcomes (
5509                   client_commit_id, status, recorded_at_ms, results_json,
5510                   operations_json, resolution
5511                 ) VALUES (?1, ?2, ?3, ?4, ?5, 'active')",
5512                rusqlite::params![
5513                    client_commit_id,
5514                    Self::outcome_status_name(status),
5515                    self.clock_now_ms(),
5516                    results_json,
5517                    operations_json
5518                ],
5519            )
5520            .map(|_| ())
5521            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
5522    }
5523
5524    /// §7.2: the journal holds a stored cell only in its canonical shape. A cell
5525    /// the byte-envelope rule refuses cannot be journaled verbatim.
5526    fn stored_cell_is_representable(cell: &Value) -> bool {
5527        cell.is_null()
5528            || cell.is_string()
5529            || cell.is_boolean()
5530            || cell.is_number()
5531            || is_canonical_bytes_envelope(cell)
5532    }
5533
5534    fn stored_row_is_representable(value: &Value) -> bool {
5535        value
5536            .as_object()
5537            .is_some_and(|row| row.values().all(Self::stored_cell_is_representable))
5538    }
5539
5540    fn stored_operation_is_representable(value: &Value) -> bool {
5541        value.get("table").is_some_and(Value::is_string)
5542            && value.get("rowId").is_some_and(Value::is_string)
5543            && value.get("baseVersion").is_none_or(|v| {
5544                v.as_i64()
5545                    .is_some_and(|n| n.unsigned_abs() <= MAX_JS_SAFE_INTEGER)
5546            })
5547            && match value.get("op").and_then(Value::as_str) {
5548                Some("upsert") => {
5549                    value
5550                        .get("values")
5551                        .is_some_and(Self::stored_row_is_representable)
5552                        && value
5553                            .get("insert")
5554                            .is_none_or(|insert| *insert == Value::Bool(true))
5555                }
5556                Some("delete") => value.get("values").is_none() && value.get("insert").is_none(),
5557                _ => false,
5558            }
5559    }
5560
5561    /// §7.2/§7.4.4: a dropped commit keeps its operation envelope in the journal
5562    /// only when the journal reader accepts the serialized operation, which is the
5563    /// rule `outcome_from_row` applies to this same row later.
5564    fn outbox_op_is_journalable(operation: &OutboxOp) -> bool {
5565        serde_json::to_value(CommitOperation::from(operation))
5566            .is_ok_and(|value| Self::stored_operation_is_representable(&value))
5567    }
5568
5569    /// §7.2.1: the one predicate for a replaced commit: a rejection whose
5570    /// every result is `client.commit_replaced` and that names its replacement.
5571    fn is_replaced(outcome: &CommitOutcome) -> bool {
5572        outcome.status == CommitOutcomeStatus::Rejected
5573            && outcome.replacement_client_commit_id.is_some()
5574            && !outcome.results.is_empty()
5575            && outcome.results.iter().all(|result| {
5576                matches!(result, CommitOperationOutcome::Error { rejection }
5577                    if rejection.code == COMMIT_REPLACED_CODE)
5578            })
5579    }
5580
5581    /// §7.2.1: `commitOutcomes` and `commitDelivery` report a replaced
5582    /// commit as `replaced`; every other journal surface reads the rejection.
5583    fn reported_outcome(mut outcome: CommitOutcome) -> CommitOutcome {
5584        if Self::is_replaced(&outcome) {
5585            outcome.status = CommitOutcomeStatus::Replaced;
5586        }
5587        outcome
5588    }
5589
5590    fn outcome_from_row(row: StoredCommitOutcomeRow) -> Result<CommitOutcome, String> {
5591        let StoredCommitOutcomeRow {
5592            sequence,
5593            client_commit_id,
5594            status,
5595            recorded_at_ms,
5596            results_json,
5597            operations_json,
5598            resolution,
5599            resolved_at_ms,
5600            replacement_client_commit_id,
5601        } = row;
5602        if sequence.unsigned_abs() > MAX_JS_SAFE_INTEGER
5603            || recorded_at_ms.unsigned_abs() > MAX_JS_SAFE_INTEGER
5604            || resolved_at_ms.is_some_and(|value| value.unsigned_abs() > MAX_JS_SAFE_INTEGER)
5605        {
5606            return Err("sync.local_corrupt: persisted commit outcome is invalid".to_owned());
5607        }
5608        let invalid = || "sync.local_corrupt: persisted commit outcome is invalid".to_owned();
5609        let stored: Vec<Value> = serde_json::from_str(&results_json).map_err(|_| invalid())?;
5610        for result in &stored {
5611            let nested = match result.get("status").and_then(Value::as_str) {
5612                Some("conflict") => result.get("conflict"),
5613                Some("error") => result.get("rejection"),
5614                _ => None,
5615            };
5616            if nested
5617                .and_then(|record| record.get("operation"))
5618                .is_some_and(|op| !Self::stored_operation_is_representable(op))
5619                || (result.get("status").and_then(Value::as_str) == Some("conflict")
5620                    && nested
5621                        .and_then(|record| record.get("serverRow"))
5622                        .is_some_and(|row| !Self::stored_row_is_representable(row)))
5623            {
5624                return Err(invalid());
5625            }
5626        }
5627        let results: Vec<CommitOperationOutcome> =
5628            serde_json::from_value(Value::Array(stored)).map_err(|_| invalid())?;
5629        let has_conflict = results
5630            .iter()
5631            .any(|result| matches!(result, CommitOperationOutcome::Conflict { .. }));
5632        let has_error = results
5633            .iter()
5634            .any(|result| matches!(result, CommitOperationOutcome::Error { .. }));
5635        let status = Self::parse_outcome_status(&status).map_err(|_| invalid())?;
5636        let redacted = results.is_empty() && operations_json.is_none();
5637        if match status {
5638            CommitOutcomeStatus::Applied | CommitOutcomeStatus::Cached => has_conflict || has_error,
5639            CommitOutcomeStatus::Replaced => true,
5640            CommitOutcomeStatus::Conflict => !(has_conflict || redacted),
5641            CommitOutcomeStatus::Rejected => has_conflict || !(has_error || redacted),
5642        } {
5643            return Err(invalid());
5644        }
5645        let operations: Option<Vec<CommitOperation>> = operations_json
5646            .map(|raw| {
5647                let stored: Vec<Value> = serde_json::from_str(&raw).map_err(|_| invalid())?;
5648                if !stored.iter().all(Self::stored_operation_is_representable) {
5649                    return Err(invalid());
5650                }
5651                serde_json::from_value(Value::Array(stored)).map_err(|_| invalid())
5652            })
5653            .transpose()?;
5654        for result in &results {
5655            match result {
5656                CommitOperationOutcome::Conflict { conflict }
5657                    if conflict.server_version.unsigned_abs() > MAX_JS_SAFE_INTEGER =>
5658                {
5659                    return Err("sync.local_corrupt: persisted commit outcome is invalid".to_owned())
5660                }
5661                CommitOperationOutcome::Error { rejection } => {
5662                    if let Some(details) = &rejection.details {
5663                        let encoded = serde_json::to_string(details).map_err(|_| {
5664                            "sync.local_corrupt: persisted commit outcome is invalid".to_owned()
5665                        })?;
5666                        RejectionDetails::parse(&encoded).map_err(|_| {
5667                            "sync.local_corrupt: persisted commit outcome is invalid".to_owned()
5668                        })?;
5669                    }
5670                }
5671                _ => {}
5672            }
5673        }
5674        Ok(CommitOutcome {
5675            sequence,
5676            client_commit_id,
5677            status,
5678            recorded_at_ms,
5679            results,
5680            operations,
5681            retained_rows: None,
5682            resolution: Self::parse_outcome_resolution(&resolution)?,
5683            resolved_at_ms,
5684            replacement_client_commit_id,
5685        })
5686    }
5687
5688    /// Resolve declared unique keys through SQLite, including affinity and NULL semantics.
5689    fn unique_conflicts(
5690        &self,
5691        table: &TableSchema,
5692        values: &Map<String, Value>,
5693        base: bool,
5694    ) -> Result<Vec<RetainedUniqueConflict>, String> {
5695        let source = if base {
5696            base_table(&table.name)
5697        } else {
5698            visible_table(&table.name)
5699        };
5700        let mut conflicts = Vec::new();
5701        for index in table.indexes.iter().filter(|index| index.unique) {
5702            let mut params = vec![json_param_to_sql(
5703                values.get(&table.primary_key).ok_or("sync.local_corrupt")?,
5704            )?];
5705            for name in &index.columns {
5706                let column = table
5707                    .columns
5708                    .iter()
5709                    .find(|column| column.name == *name)
5710                    .ok_or("sync.local_corrupt")?;
5711                let cell = json_to_column_value(column, values.get(name))?;
5712                params.push(owned_sql_value(RowParam::Cell(&cell))?);
5713            }
5714            let sql = format!(
5715                "SELECT * FROM {source} WHERE {} != ? AND {}",
5716                quote_ident(&table.primary_key),
5717                index
5718                    .columns
5719                    .iter()
5720                    .map(|column| format!("{} = ?", quote_ident(column)))
5721                    .collect::<Vec<_>>()
5722                    .join(" AND ")
5723            );
5724            let mut statement = self
5725                .conn
5726                .prepare_cached(&sql)
5727                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5728            let records = statement
5729                .query_map(rusqlite::params_from_iter(params), |record| {
5730                    let values = table
5731                        .columns
5732                        .iter()
5733                        .enumerate()
5734                        .map(|(index, column)| {
5735                            let value = sql_ref_to_json(column, record.get_ref(index)?);
5736                            json_to_column_value(column, Some(&value)).map_err(|message| {
5737                                rusqlite::Error::ToSqlConversionFailure(message.into())
5738                            })
5739                        })
5740                        .collect::<Result<Row, _>>()?;
5741                    Ok((values, record.get::<_, i64>(table.columns.len())?))
5742                })
5743                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5744            for record in records {
5745                let (row, version) =
5746                    record.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5747                let row_id = render_row_id_json(Some(&column_value_to_json(&row[table.pk_index])))?;
5748                conflicts.push(RetainedUniqueConflict {
5749                    index: index.name.clone(),
5750                    columns: index.columns.clone(),
5751                    row_id,
5752                    server_row: table
5753                        .columns
5754                        .iter()
5755                        .zip(&row)
5756                        .map(|(column, value)| (column.name.clone(), column_value_to_json(value)))
5757                        .collect(),
5758                    server_version: version,
5759                });
5760            }
5761        }
5762        Ok(conflicts)
5763    }
5764
5765    fn attach_retained_rows(&self, mut outcome: CommitOutcome) -> Result<CommitOutcome, String> {
5766        if let Some((commit, initial)) = self
5767            .failed_commits
5768            .iter()
5769            .find(|(commit, _)| commit.client_commit_id == outcome.client_commit_id)
5770        {
5771            let mut rows = Vec::new();
5772            for operation in &commit.ops {
5773                // A table the current schema removed has no rows to retain.
5774                let Some(table) = self.schema.table(&operation.table) else {
5775                    continue;
5776                };
5777                let key =
5778                    serde_json::to_string(&(operation.table.clone(), operation.row_id.clone()))
5779                        .map_err(|_| "sync.local_corrupt".to_owned())?;
5780                let base = self.stored_row(table, &operation.row_id, true)?;
5781                rows.push(RetainedCommitRow {
5782                    table: operation.table.clone(),
5783                    row_id: operation.row_id.clone(),
5784                    unique_conflicts: if operation.upsert {
5785                        self.unique_conflicts(
5786                            table,
5787                            initial
5788                                .get(&key)
5789                                .and_then(Value::as_object)
5790                                .or(operation.values.as_ref())
5791                                .ok_or("sync.local_corrupt")?,
5792                            true,
5793                        )?
5794                    } else {
5795                        Vec::new()
5796                    },
5797                    local_row: if operation.upsert {
5798                        initial
5799                            .get(&key)
5800                            .and_then(Value::as_object)
5801                            .cloned()
5802                            .or_else(|| operation.values.clone())
5803                    } else {
5804                        None
5805                    },
5806                    server_row: base.as_ref().map(|(values, _)| {
5807                        table
5808                            .columns
5809                            .iter()
5810                            .zip(values)
5811                            .map(|(column, value)| {
5812                                (column.name.clone(), column_value_to_json(value))
5813                            })
5814                            .collect()
5815                    }),
5816                    server_version: base.map(|(_, version)| version),
5817                });
5818            }
5819            outcome.retained_rows = Some(rows);
5820        }
5821        Ok(outcome)
5822    }
5823
5824    fn commit_outcome(&self, client_commit_id: &str) -> Result<Option<CommitOutcome>, String> {
5825        let row = self
5826            .conn
5827            .query_row(
5828                "SELECT seq, client_commit_id, status, recorded_at_ms, results_json, operations_json,
5829                        resolution, resolved_at_ms, replacement_client_commit_id
5830                   FROM _syncular_commit_outcomes WHERE client_commit_id = ?1",
5831                rusqlite::params![client_commit_id],
5832                |row| {
5833                    Ok(StoredCommitOutcomeRow {
5834                        sequence: row.get(0)?,
5835                        client_commit_id: row.get(1)?,
5836                        status: row.get(2)?,
5837                        recorded_at_ms: row.get(3)?,
5838                        results_json: row.get(4)?,
5839                        operations_json: row.get(5)?,
5840                        resolution: row.get(6)?,
5841                        resolved_at_ms: row.get(7)?,
5842                        replacement_client_commit_id: row.get(8)?,
5843                    })
5844                },
5845            )
5846            .optional()
5847            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5848        row.map(|row| self.attach_retained_rows(Self::outcome_from_row(row)?))
5849            .transpose()
5850    }
5851
5852    /// Internal host step. The host must run its idle drive before finishing.
5853    #[doc(hidden)]
5854    pub fn prepare_current_base(
5855        &self,
5856        client_commit_id: &str,
5857        sequence: i64,
5858    ) -> Result<CurrentBasePreparation, CurrentBaseProof> {
5859        let outcome = self
5860            .commit_outcome(client_commit_id)
5861            .map_err(|_| CurrentBaseProof::failure(CurrentBaseProofReason::SnapshotFailed))?;
5862        let valid = outcome.as_ref().is_some_and(|outcome| {
5863            outcome.sequence == sequence
5864                && outcome.resolution == CommitOutcomeResolution::Active
5865                && matches!(
5866                    outcome.status,
5867                    CommitOutcomeStatus::Conflict | CommitOutcomeStatus::Rejected
5868                )
5869                && outcome
5870                    .operations
5871                    .as_ref()
5872                    .zip(outcome.retained_rows.as_ref())
5873                    .is_some_and(|(operations, rows)| {
5874                        !rows.is_empty() && operations.len() == rows.len()
5875                    })
5876        });
5877        if !valid {
5878            return Err(CurrentBaseProof::failure(
5879                CurrentBaseProofReason::OutcomeUnavailable,
5880            ));
5881        }
5882        if self.transport_closed() {
5883            return Err(CurrentBaseProof::failure(CurrentBaseProofReason::Offline));
5884        }
5885        Ok(CurrentBasePreparation {
5886            client_commit_id: client_commit_id.to_owned(),
5887            sequence,
5888            replacement: None,
5889            units: load_units(&self.conn)
5890                .map_err(|_| CurrentBaseProof::failure(CurrentBaseProofReason::SnapshotFailed))?,
5891            transport_epoch: self.transport_epoch,
5892            registration_epoch: self.registration_epoch,
5893            security_epoch: self.security_epoch,
5894        })
5895    }
5896
5897    /// Internal host step after the completed post-rejection idle drive.
5898    #[doc(hidden)]
5899    pub fn finish_current_base(
5900        &mut self,
5901        prepared: CurrentBasePreparation,
5902        drive: SyncOutcome,
5903    ) -> CurrentBaseProof {
5904        if self.transport_closed() || self.transport_epoch != prepared.transport_epoch {
5905            return CurrentBaseProof::failure(CurrentBaseProofReason::Offline);
5906        }
5907        if self.registration_epoch != prepared.registration_epoch {
5908            return CurrentBaseProof::failure(CurrentBaseProofReason::MissingCoverage);
5909        }
5910        if self.security_preflight || self.security_epoch != prepared.security_epoch {
5911            return CurrentBaseProof::failure(CurrentBaseProofReason::SyncFailed);
5912        }
5913        let report = match drive {
5914            SyncOutcome::Ok(report) => report,
5915            SyncOutcome::BudgetExhausted(_) => {
5916                return CurrentBaseProof::failure(CurrentBaseProofReason::BudgetExhausted)
5917            }
5918            _ => return CurrentBaseProof::failure(CurrentBaseProofReason::SyncFailed),
5919        };
5920        if report.schema_floor.is_some() {
5921            return CurrentBaseProof::failure(CurrentBaseProofReason::SchemaFloor);
5922        }
5923        if self
5924            .conn
5925            .execute_batch("SAVEPOINT syncular_base_proof")
5926            .is_err()
5927        {
5928            return CurrentBaseProof::failure(CurrentBaseProofReason::SnapshotFailed);
5929        }
5930        let proof = (|| {
5931            let snapshot = snapshot_read_connection(
5932                &self.conn,
5933                Some(&self.schema),
5934                &SnapshotReadRequest {
5935                    units: prepared.units.iter().map(|unit| unit.id.clone()).collect(),
5936                    commit_ids: vec![prepared.client_commit_id.clone()],
5937                    ..Default::default()
5938                },
5939            )
5940            .map_err(|_| CurrentBaseProofReason::SnapshotFailed)?;
5941            let current = self
5942                .commit_outcome(&prepared.client_commit_id)
5943                .map_err(|_| CurrentBaseProofReason::SnapshotFailed)?;
5944            let unavailable = if report.revoked.is_empty() {
5945                CurrentBaseProofReason::OutcomeUnavailable
5946            } else {
5947                CurrentBaseProofReason::Revoked
5948            };
5949            let Some(outcome) = current else {
5950                return Err(unavailable);
5951            };
5952            if !matches!(
5953                snapshot.deliveries.first(),
5954                Some(CommitDelivery::Known { .. })
5955            ) || outcome.sequence != prepared.sequence
5956                || outcome.resolution != CommitOutcomeResolution::Active
5957                || !matches!(
5958                    outcome.status,
5959                    CommitOutcomeStatus::Conflict | CommitOutcomeStatus::Rejected
5960                )
5961            {
5962                return Err(unavailable);
5963            }
5964            let (Some(operations), Some(rows)) = (outcome.operations, outcome.retained_rows) else {
5965                return Err(unavailable);
5966            };
5967            if rows.is_empty() || operations.len() != rows.len() {
5968                return Err(unavailable);
5969            }
5970            let after =
5971                load_units(&self.conn).map_err(|_| CurrentBaseProofReason::SnapshotFailed)?;
5972            let complete: HashSet<&str> = snapshot
5973                .units
5974                .iter()
5975                .filter_map(|unit| match unit {
5976                    UnitCatchup::Known {
5977                        id,
5978                        bootstrap_complete: true,
5979                        ..
5980                    } => Some(id.as_str()),
5981                    _ => None,
5982                })
5983                .collect();
5984            // A unit id names one scope map (§4.1), so the same id before and
5985            // after the drive is the same registration.
5986            let candidates: Vec<&UnitRecord> = after
5987                .iter()
5988                .filter(|unit| {
5989                    complete.contains(unit.id.as_str())
5990                        && prepared.units.iter().any(|before| before.id == unit.id)
5991                })
5992                .collect();
5993            let covered = |table_name: &str, row: &Map<String, Value>| {
5994                let Some(table) = self.schema.table(table_name) else {
5995                    return false;
5996                };
5997                candidates.iter().any(|unit| {
5998                    covers(table, &unit.scopes)
5999                        && pair_scopes(&unit.scopes, table_name, unit.echo.as_deref()).is_some_and(
6000                            |scopes| {
6001                                scopes.iter().all(|(variable, allowed)| {
6002                                    table
6003                                        .scope_column(variable)
6004                                        .and_then(|column| match row.get(column) {
6005                                            Some(Value::String(value)) => Some(value.clone()),
6006                                            Some(Value::Bool(value)) => Some(value.to_string()),
6007                                            Some(Value::Number(value)) => {
6008                                                value.as_f64().map(|number| {
6009                                                    ryu_js::Buffer::new()
6010                                                        .format_finite(number)
6011                                                        .to_owned()
6012                                                })
6013                                            }
6014                                            _ => None,
6015                                        })
6016                                        .is_some_and(|value| {
6017                                            !value.is_empty() && allowed.contains(&value)
6018                                        })
6019                                })
6020                            },
6021                        )
6022                })
6023            };
6024            for row in &rows {
6025                let Some(base) = row.server_row.as_ref().or(row.local_row.as_ref()) else {
6026                    return Err(if report.revoked.is_empty() {
6027                        CurrentBaseProofReason::MissingCoverage
6028                    } else {
6029                        CurrentBaseProofReason::Revoked
6030                    });
6031                };
6032                if !covered(&row.table, base)
6033                    || row
6034                        .unique_conflicts
6035                        .iter()
6036                        .any(|conflict| !covered(&row.table, &conflict.server_row))
6037                {
6038                    return Err(if report.revoked.is_empty() {
6039                        CurrentBaseProofReason::MissingCoverage
6040                    } else {
6041                        CurrentBaseProofReason::Revoked
6042                    });
6043                }
6044            }
6045            Ok(rows)
6046        })();
6047        if self
6048            .conn
6049            .execute_batch("RELEASE syncular_base_proof")
6050            .is_err()
6051        {
6052            return CurrentBaseProof::failure(CurrentBaseProofReason::SnapshotFailed);
6053        }
6054        match proof {
6055            Ok(rows) => CurrentBaseProof {
6056                proven: true,
6057                rows: Some(rows),
6058                reason: None,
6059            },
6060            Err(reason) => CurrentBaseProof::failure(reason),
6061        }
6062    }
6063
6064    pub fn prove_current_base(
6065        &mut self,
6066        transport: &mut dyn Transport,
6067        client_commit_id: &str,
6068        sequence: i64,
6069        max_rounds: Option<u32>,
6070    ) -> CurrentBaseProof {
6071        let prepared = match self.prepare_current_base(client_commit_id, sequence) {
6072            Ok(prepared) => prepared,
6073            Err(proof) => return proof,
6074        };
6075        let drive = self.sync_until_idle(transport, max_rounds);
6076        self.finish_current_base(prepared, drive)
6077    }
6078
6079    pub fn commit_outcomes(&self, query: CommitOutcomeQuery) -> Result<Vec<CommitOutcome>, String> {
6080        if query.limit == Some(0) {
6081            return Err("sync.invalid_request: commit outcome limit must be positive".to_owned());
6082        }
6083        let mut sql = String::from(
6084            "SELECT seq, client_commit_id, status, recorded_at_ms, results_json, operations_json,
6085                    resolution, resolved_at_ms, replacement_client_commit_id
6086               FROM _syncular_commit_outcomes",
6087        );
6088        if query.active_only {
6089            sql.push_str(" WHERE resolution = 'active' AND status IN ('conflict', 'rejected')");
6090        }
6091        sql.push_str(" ORDER BY seq DESC");
6092        if let Some(limit) = query.limit {
6093            sql.push_str(&format!(" LIMIT {limit}"));
6094        }
6095        let mut stmt = self
6096            .conn
6097            .prepare(&sql)
6098            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6099        let rows = stmt
6100            .query_map([], |row| {
6101                Ok(StoredCommitOutcomeRow {
6102                    sequence: row.get(0)?,
6103                    client_commit_id: row.get(1)?,
6104                    status: row.get(2)?,
6105                    recorded_at_ms: row.get(3)?,
6106                    results_json: row.get(4)?,
6107                    operations_json: row.get(5)?,
6108                    resolution: row.get(6)?,
6109                    resolved_at_ms: row.get(7)?,
6110                    replacement_client_commit_id: row.get(8)?,
6111                })
6112            })
6113            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6114        let mut outcomes = Vec::new();
6115        for row in rows {
6116            let row = row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6117            outcomes.push(Self::reported_outcome(
6118                self.attach_retained_rows(Self::outcome_from_row(row)?)?,
6119            ));
6120        }
6121        Ok(outcomes)
6122    }
6123
6124    fn prune_commit_outcomes(&self) -> Result<(), String> {
6125        #[cfg(test)]
6126        self.outcome_prune_count
6127            .set(self.outcome_prune_count.get() + 1);
6128        let max_entries = self.limits.outcome_retention_max_entries.unwrap_or(1_000);
6129        let count = self
6130            .conn
6131            .query_row(
6132                "SELECT COUNT(*) FROM _syncular_commit_outcomes",
6133                [],
6134                |row| row.get::<_, i64>(0),
6135            )
6136            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
6137            as usize;
6138        let excess = count.saturating_sub(max_entries);
6139        if excess == 0 {
6140            return Ok(());
6141        }
6142        let mut stmt = self
6143            .conn
6144            .prepare(
6145                "SELECT seq FROM _syncular_commit_outcomes
6146                  WHERE status IN ('applied', 'cached') OR resolution != 'active'
6147                  ORDER BY seq ASC LIMIT ?1",
6148            )
6149            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6150        let rows = stmt
6151            .query_map(rusqlite::params![excess as i64], |row| row.get::<_, i64>(0))
6152            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6153        let sequences = rows
6154            .collect::<Result<Vec<_>, _>>()
6155            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6156        drop(stmt);
6157        for sequence in sequences {
6158            self.conn
6159                .execute(
6160                    "DELETE FROM _syncular_commit_outcomes WHERE seq = ?1",
6161                    rusqlite::params![sequence],
6162                )
6163                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6164        }
6165        Ok(())
6166    }
6167
6168    // -- units (§4.1) ------------------------------------------------------------
6169
6170    /// Every registered unit in registration order (§4.1).
6171    pub fn units(&self) -> Result<Vec<UnitRecord>, String> {
6172        self.stored(load_units(&self.conn))
6173    }
6174
6175    pub fn unit(&self, id: &str) -> Result<Option<UnitRecord>, String> {
6176        self.stored(get_unit(&self.conn, id))
6177    }
6178
6179    /// Register one unit (§4.1) and return its id.
6180    pub fn subscribe(&mut self, scopes: UnitScopes) -> Result<String, String> {
6181        Ok(self.subscribe_many(vec![scopes])?.remove(0))
6182    }
6183
6184    /// Register several units in one local transaction and return their ids:
6185    /// one commit for all of them (on OPFS a commit costs milliseconds, so a
6186    /// cold start with hundreds of units pays it once). An error rolls back
6187    /// every registration of the call. Registering an active unit again
6188    /// changes nothing; a revoked unit re-arms (§3.3). A call that registers or
6189    /// re-arms a unit raises sync-needed with an interactive intent.
6190    pub fn subscribe_many(&mut self, units: Vec<UnitScopes>) -> Result<Vec<String>, String> {
6191        let rollback = self.capture();
6192        self.begin_observation("syncular_subscribe")?;
6193        let mut changed = false;
6194        let registered = (|| {
6195            let mut ids = Vec::with_capacity(units.len());
6196            let mut batch = ChangeAccumulator::default();
6197            for scopes in units {
6198                let (id, held) = self.hold_unit(scopes, true)?;
6199                if held {
6200                    if let Some(unit) = self.stored(get_unit(&self.conn, &id))? {
6201                        self.record_unit_windows(&mut batch, &unit)?;
6202                    }
6203                }
6204                changed |= held;
6205                ids.push(id);
6206            }
6207            self.finish_observation("syncular_subscribe", batch)?;
6208            Ok(ids)
6209        })();
6210        let ids = match registered {
6211            Ok(ids) => ids,
6212            Err(error) => {
6213                self.rollback_observation("syncular_subscribe");
6214                self.restore(rollback);
6215                return Err(error);
6216            }
6217        };
6218        if changed {
6219            self.registration_epoch = self.registration_epoch.wrapping_add(1);
6220            self.set_sync_needed(true, true);
6221        }
6222        Ok(ids)
6223    }
6224
6225    /// Release the explicit reference to a unit. The unit leaves the
6226    /// registration list when no window base holds it (§4.1); its rows stay.
6227    pub fn unsubscribe(&mut self, id: &str) -> Result<(), String> {
6228        let Some(unit) = self.stored(get_unit(&self.conn, id))? else {
6229            return Ok(());
6230        };
6231        if !unit.explicit {
6232            return Ok(());
6233        }
6234        if !self.stored(window_refs(&self.conn, id))?.is_empty() {
6235            return self.stored(save_unit(
6236                &self.conn,
6237                &UnitRecord {
6238                    explicit: false,
6239                    ..unit
6240                },
6241            ));
6242        }
6243        let rollback = self.capture();
6244        self.begin_observation("syncular_unsubscribe")?;
6245        let removed = (|| {
6246            self.conn
6247                .execute("DELETE FROM _syncular_units WHERE id = ?1", [id])
6248                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6249            let mut batch = ChangeAccumulator::default();
6250            self.record_unit_windows(&mut batch, &unit)?;
6251            self.finish_observation("syncular_unsubscribe", batch)
6252        })();
6253        if let Err(error) = removed {
6254            self.rollback_observation("syncular_unsubscribe");
6255            self.restore(rollback);
6256            return Err(error);
6257        }
6258        self.registration_epoch = self.registration_epoch.wrapping_add(1);
6259        if unit.status == UnitStatus::Active {
6260            self.set_sync_needed(true, true);
6261        }
6262        Ok(())
6263    }
6264
6265    /// Take one reference on a unit (§4.1): validate the scope map, register a
6266    /// new unit catching up with cursor `-1`, re-arm a revoked one (§3.3).
6267    /// Returns the id and whether the registration list changed.
6268    fn hold_unit(&mut self, scopes: UnitScopes, explicit: bool) -> Result<(String, bool), String> {
6269        if scopes.is_empty()
6270            || scopes.values().any(|value| value == "*")
6271            || !self
6272                .schema
6273                .tables
6274                .iter()
6275                .any(|table| covers(table, &scopes))
6276        {
6277            return Err("sync.invalid_subscription: a unit names one non-wildcard value per variable and covers a table".to_owned());
6278        }
6279        let id = ssp2::registration::unit_id(&scope_pairs(&scopes));
6280        let existing = self.stored(get_unit(&self.conn, &id))?;
6281        if let Some(existing) = existing
6282            .as_ref()
6283            .filter(|unit| unit.status != UnitStatus::Revoked)
6284        {
6285            if explicit && !existing.explicit {
6286                self.stored(save_unit(
6287                    &self.conn,
6288                    &UnitRecord {
6289                        explicit,
6290                        ..existing.clone()
6291                    },
6292                ))?;
6293            }
6294            return Ok((id, false));
6295        }
6296        self.delete_pending_evict(&id)?;
6297        self.stored(save_unit(
6298            &self.conn,
6299            &UnitRecord {
6300                id: id.clone(),
6301                scopes,
6302                explicit: explicit || existing.is_some_and(|unit| unit.explicit),
6303                status: UnitStatus::Active,
6304                reason_code: None,
6305                cursor: Some(-1),
6306                bootstrap_state: None,
6307                seeded: Vec::new(),
6308                echo: None,
6309                restriction: None,
6310            },
6311        ))?;
6312        Ok((id, true))
6313    }
6314
6315    // -- windows (§4.8) -----------------------------------------------------------
6316
6317    /// §4.8: set the windowed-in values of a base, one unit per value. Added
6318    /// values take a reference on their unit (a new unit bootstraps on the
6319    /// next sync); removed values release theirs, and a unit no reference
6320    /// holds leaves the registration list fused with its first eviction chunk
6321    /// (E1–E4). Idempotent; re-entry cancels a deferred eviction.
6322    pub fn set_window(
6323        &mut self,
6324        base: &WindowBase,
6325        units: &[String],
6326    ) -> Result<CommandEffects, String> {
6327        let base_key = window_base_key(base);
6328        let live = self.load_window_units(&base_key)?;
6329        let mut changed = false;
6330        // §7.8: the added values register in one transaction. §3.3: a held
6331        // value whose unit is revoked re-arms once per open core.
6332        let mut added: Vec<&String> = Vec::new();
6333        for value in units {
6334            let held = live.iter().find(|(held, _)| held == value);
6335            let rearm = match held {
6336                None => true,
6337                Some((_, id)) => {
6338                    !self.window_armed.contains(id)
6339                        && self
6340                            .stored(get_unit(&self.conn, id))?
6341                            .is_some_and(|unit| unit.status == UnitStatus::Revoked)
6342                }
6343            };
6344            if rearm {
6345                added.push(value);
6346            }
6347        }
6348        if !added.is_empty() {
6349            let rollback = self.capture();
6350            self.begin_observation("syncular_window")?;
6351            let widened = (|| {
6352                let mut batch = ChangeAccumulator::default();
6353                for value in &added {
6354                    let (id, registered) =
6355                        self.hold_unit(window_unit_scopes(base, value), false)?;
6356                    self.sync_needed |= registered;
6357                    if registered {
6358                        self.window_armed.insert(id.clone());
6359                    }
6360                    self.conn
6361                        .execute(
6362                            "INSERT OR REPLACE INTO _syncular_windows(base, unit, sub_id) VALUES (?1, ?2, ?3)",
6363                            rusqlite::params![base_key, value, id],
6364                        )
6365                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6366                    batch.window(&base_key, value);
6367                    // A registered or re-armed unit is a transition for every
6368                    // window value that references it.
6369                    if registered {
6370                        if let Some(unit) = self.stored(get_unit(&self.conn, &id))? {
6371                            self.record_unit_windows(&mut batch, &unit)?;
6372                        }
6373                    }
6374                }
6375                batch.status = true;
6376                self.finish_observation("syncular_window", batch)
6377            })();
6378            if let Err(error) = widened {
6379                self.rollback_observation("syncular_window");
6380                self.restore(rollback);
6381                return Err(error);
6382            }
6383            changed = true;
6384            self.registration_epoch = self.registration_epoch.wrapping_add(1);
6385        }
6386        for (value, id) in live {
6387            if units.contains(&value) {
6388                continue;
6389            }
6390            self.rebuild_overlay_if_dirty()?;
6391            let rollback = self.capture();
6392            self.begin_observation("syncular_window")?;
6393            let remaining = self.release_window_unit(&base_key, &value, &id);
6394            let remaining = match remaining {
6395                Ok(remaining) => remaining,
6396                Err(error) => {
6397                    self.rollback_observation("syncular_window");
6398                    self.restore(rollback);
6399                    return Err(error);
6400                }
6401            };
6402            changed = true;
6403            self.registration_epoch = self.registration_epoch.wrapping_add(1);
6404            if remaining {
6405                self.drain_pending_evictions()?;
6406            }
6407        }
6408        Ok(if changed && !self.transport_closed() {
6409            CommandEffects::interactive()
6410        } else {
6411            CommandEffects::none()
6412        })
6413    }
6414
6415    /// §4.8 completeness oracle: the windowed-in values of a base and those
6416    /// whose unit is not complete. A value is complete once its unit is active
6417    /// and no longer bootstrapping; registration alone is not completeness.
6418    pub fn window_state(&self, base: &WindowBase) -> Result<WindowState, String> {
6419        persisted_window_state(&self.conn, base).map_err(|failure| failure.message)
6420    }
6421
6422    /// Registry rows for a base, ordered by value: (value, unit id).
6423    fn load_window_units(&self, base_key: &str) -> Result<Vec<(String, String)>, String> {
6424        let mut statement = self
6425            .conn
6426            .prepare_cached(
6427                "SELECT unit, sub_id FROM _syncular_windows WHERE base = ?1 ORDER BY unit ASC",
6428            )
6429            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6430        let rows = statement
6431            .query_map([base_key], |row| Ok((row.get(0)?, row.get(1)?)))
6432            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6433        rows.collect::<Result<_, _>>()
6434            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
6435    }
6436
6437    /// §4.8: the window-domain changes of one unit transition, the one path
6438    /// every transition site takes: one per window value that references the
6439    /// unit or, when none does, one for the base derived from its scope map
6440    /// (the variable first in code-unit order and its value; the other
6441    /// variables its fixed scopes). A transition adds no table change.
6442    fn record_unit_windows(
6443        &self,
6444        batch: &mut ChangeAccumulator,
6445        unit: &UnitRecord,
6446    ) -> Result<(), String> {
6447        let refs = self.stored(window_refs(&self.conn, &unit.id))?;
6448        if refs.is_empty() {
6449            let mut pairs = scope_pairs(&unit.scopes).into_iter();
6450            if let Some((variable, value)) = pairs.next() {
6451                let base = WindowBase {
6452                    variable,
6453                    fixed_scopes: pairs.collect(),
6454                };
6455                batch.window(&window_base_key(&base), &value);
6456            }
6457        }
6458        for (base_key, value) in refs {
6459            batch.window(&base_key, &value);
6460        }
6461        Ok(())
6462    }
6463
6464    /// §4.8: release a window value's reference inside the caller's
6465    /// observation. When no reference holds the unit, unregister it fused with
6466    /// its first eviction chunk (E3): delete the rows of every covered table
6467    /// matching the persisted echo, except rows pinned by the outbox (E1) or
6468    /// owned by another unit (§3.3), and park the per-table scopes of what
6469    /// remains in the pending-eviction registry. Fails closed without a local
6470    /// scope-column mapping. Returns whether unpinned rows remain.
6471    fn release_window_unit(
6472        &mut self,
6473        base_key: &str,
6474        value: &str,
6475        id: &str,
6476    ) -> Result<bool, String> {
6477        self.conn
6478            .execute(
6479                "DELETE FROM _syncular_windows WHERE base = ?1 AND unit = ?2",
6480                rusqlite::params![base_key, value],
6481            )
6482            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6483        self.window_armed.remove(id);
6484        let mut batch = ChangeAccumulator::default();
6485        batch.window(base_key, value);
6486        batch.status = true;
6487        let unit = self.stored(get_unit(&self.conn, id))?;
6488        let mut remaining = false;
6489        if let Some(unit) = unit.filter(|unit| !unit.explicit) {
6490            if self.stored(window_refs(&self.conn, id))?.is_empty() {
6491                let units = self.stored(load_units(&self.conn))?;
6492                self.conn
6493                    .execute("DELETE FROM _syncular_units WHERE id = ?1", [id])
6494                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6495                self.sync_needed = true;
6496                for table in self.schema.tables.clone() {
6497                    let Some(effective) = unit
6498                        .echo
6499                        .as_deref()
6500                        .filter(|_| covers(&table, &unit.scopes))
6501                        .and_then(|echo| pair_scopes(&unit.scopes, &table.name, Some(echo)))
6502                    else {
6503                        continue;
6504                    };
6505                    let pinned = self.pinned_row_ids(&table.name);
6506                    let owners = unit_owners(&units, &table, id);
6507                    let (more, deferred) =
6508                        self.evict_scope_rows(&table.name, &effective, &owners, &pinned)?;
6509                    remaining |= more;
6510                    if deferred {
6511                        self.save_pending_evict(id, &table.name, &effective)?;
6512                    }
6513                    self.record_scope_map(&mut batch, &table.name, &effective);
6514                }
6515            }
6516        }
6517        self.finish_observation("syncular_window", batch)?;
6518        Ok(remaining)
6519    }
6520
6521    /// §4.8 E1: delete base rows owned by the effective scopes
6522    /// ([`local_scope_predicate`]) EXCEPT pinned primary keys. Returns (more
6523    /// unpinned work, any scoped rows remain). A missing scope-column mapping
6524    /// fails without deleting rows.
6525    fn evict_scope_rows(
6526        &self,
6527        table_name: &str,
6528        effective: &[(String, Vec<String>)],
6529        owners: &[Vec<(String, Vec<String>)>],
6530        pinned: &std::collections::HashSet<String>,
6531    ) -> Result<(bool, bool), String> {
6532        let table = self.schema.table(table_name).ok_or("sync.unknown_table")?;
6533        let Some((scope, mut params)) = local_scope_predicate(table, effective, owners)
6534            .map_err(|()| "sync.scope_revoked".to_owned())?
6535        else {
6536            return Ok((false, false));
6537        };
6538        let scope_params = params.len();
6539        let pk = quote_ident(&table.primary_key);
6540        // Pinned ids are rowId text; the text form matches every key type.
6541        let predicate = if pinned.is_empty() {
6542            scope.clone()
6543        } else {
6544            params.extend(pinned.iter().cloned().map(SqlValue::Text));
6545            let holes = vec!["?"; pinned.len()].join(", ");
6546            format!("{scope} AND CAST({pk} AS TEXT) NOT IN ({holes})")
6547        };
6548        let base = base_table(table_name);
6549        let visible = visible_table(table_name);
6550        let mut ids: Vec<SqlValue> = Vec::new();
6551        for source in [&base, &visible] {
6552            let mut stmt = self
6553                .conn
6554                .prepare_cached(&format!(
6555                    "SELECT {pk} FROM {source} WHERE {predicate} LIMIT 1024"
6556                ))
6557                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6558            ids = stmt
6559                .query_map(rusqlite::params_from_iter(&params), |row| row.get(0))
6560                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
6561                .collect::<Result<_, _>>()
6562                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6563            if !ids.is_empty() {
6564                break;
6565            }
6566        }
6567        if !ids.is_empty() {
6568            for id in &ids {
6569                self.conn
6570                    .execute(
6571                        "DELETE FROM _syncular_acked_rows WHERE tbl=?1 AND id=?2",
6572                        rusqlite::params![table_name, id],
6573                    )
6574                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6575            }
6576            let holes = vec!["?"; ids.len()].join(", ");
6577            for source in [&base, &visible] {
6578                self.conn
6579                    .execute(
6580                        &format!("DELETE FROM {source} WHERE {pk} IN ({holes})"),
6581                        rusqlite::params_from_iter(&ids),
6582                    )
6583                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6584            }
6585        }
6586        let mut remaining = false;
6587        let mut deferred = false;
6588        for source in [&base, &visible] {
6589            remaining |= self
6590                .conn
6591                .query_row(
6592                    &format!("SELECT EXISTS(SELECT 1 FROM {source} WHERE {predicate})"),
6593                    rusqlite::params_from_iter(&params),
6594                    |row| row.get::<_, bool>(0),
6595                )
6596                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6597            deferred |= self
6598                .conn
6599                .query_row(
6600                    &format!("SELECT EXISTS(SELECT 1 FROM {source} WHERE {scope})"),
6601                    rusqlite::params_from_iter(&params[..scope_params]),
6602                    |row| row.get::<_, bool>(0),
6603                )
6604                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6605        }
6606        Ok((remaining, deferred))
6607    }
6608
6609    /// §4.8 E1: continue deferred evictions after the outbox drains or between
6610    /// chunks, retaining outbox pins and their durable marker. A unit that
6611    /// re-entered the window has no pending entry left.
6612    fn drain_pending_evictions(&mut self) -> Result<(), String> {
6613        let pending = self.load_pending_evictions()?;
6614        if pending.is_empty() {
6615            return Ok(());
6616        }
6617        self.rebuild_overlay_if_dirty()?;
6618        for (unit_id, table_name, effective) in pending {
6619            let Some(table) = self.schema.table(&table_name).cloned() else {
6620                self.delete_pending_evict_table(&unit_id, &table_name)?;
6621                continue;
6622            };
6623            loop {
6624                std::thread::yield_now();
6625                self.begin_observation("syncular_evict")?;
6626                let chunk = (|| {
6627                    let pinned = self.pinned_row_ids(&table_name);
6628                    let owners =
6629                        unit_owners(&self.stored(load_units(&self.conn))?, &table, &unit_id);
6630                    let (remaining, deferred) =
6631                        self.evict_scope_rows(&table_name, &effective, &owners, &pinned)?;
6632                    if !deferred {
6633                        self.delete_pending_evict_table(&unit_id, &table_name)?;
6634                    }
6635                    let mut batch = ChangeAccumulator::default();
6636                    self.record_scope_map(&mut batch, &table_name, &effective);
6637                    self.finish_observation("syncular_evict", batch)?;
6638                    Ok(remaining)
6639                })();
6640                match chunk {
6641                    Ok(true) => {}
6642                    Ok(false) => break,
6643                    Err(error) => {
6644                        self.rollback_observation("syncular_evict");
6645                        return Err(error);
6646                    }
6647                }
6648            }
6649        }
6650        Ok(())
6651    }
6652
6653    /// §4.8 E1: primary keys of `table` referenced by a pending outbox
6654    /// commit — rows that MUST NOT be evicted until the commit drains.
6655    fn pinned_row_ids(&self, table: &str) -> std::collections::HashSet<String> {
6656        let mut pinned = std::collections::HashSet::new();
6657        for commit in self
6658            .outbox
6659            .iter()
6660            .map(|commit| &**commit)
6661            .chain(self.failed_commits.iter().map(|(commit, _)| commit))
6662        {
6663            for op in &commit.ops {
6664                if op.table == table {
6665                    pinned.insert(op.row_id.clone());
6666                }
6667            }
6668        }
6669        pinned
6670    }
6671
6672    fn save_pending_evict(
6673        &self,
6674        unit_id: &str,
6675        table: &str,
6676        effective: &[(String, Vec<String>)],
6677    ) -> Result<(), String> {
6678        self.conn.execute(
6679            "INSERT OR REPLACE INTO _syncular_pending_evictions(unit_id, tbl, effective_scopes) VALUES (?1, ?2, ?3)",
6680            rusqlite::params![unit_id, table, scope_map_to_json(effective).to_string()],
6681        ).map(|_| ()).map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
6682    }
6683
6684    /// Re-entry cancels every pending eviction of the unit.
6685    fn delete_pending_evict(&self, unit_id: &str) -> Result<(), String> {
6686        self.conn
6687            .execute(
6688                "DELETE FROM _syncular_pending_evictions WHERE unit_id = ?1",
6689                [unit_id],
6690            )
6691            .map(|_| ())
6692            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
6693    }
6694
6695    fn delete_pending_evict_table(&self, unit_id: &str, table: &str) -> Result<(), String> {
6696        self.conn
6697            .execute(
6698                "DELETE FROM _syncular_pending_evictions WHERE unit_id = ?1 AND tbl = ?2",
6699                [unit_id, table],
6700            )
6701            .map(|_| ())
6702            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
6703    }
6704
6705    fn load_pending_evictions(&self) -> Result<Vec<PendingEvict>, String> {
6706        let mut stmt = self
6707            .conn
6708            .prepare("SELECT unit_id, tbl, effective_scopes FROM _syncular_pending_evictions")
6709            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6710        let rows = stmt
6711            .query_map([], |row| {
6712                Ok((
6713                    row.get::<_, String>(0)?,
6714                    row.get::<_, String>(1)?,
6715                    row.get::<_, String>(2)?,
6716                ))
6717            })
6718            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6719        rows.map(|row| {
6720            let (unit_id, table, json) =
6721                row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6722            let value: Value = serde_json::from_str(&json)
6723                .map_err(|_| "sync.local_corrupt: invalid pending eviction scopes".to_owned())?;
6724            let effective = json_to_scope_map(&value)
6725                .map_err(|_| "sync.local_corrupt: invalid pending eviction scopes".to_owned())?;
6726            Ok((unit_id, table, effective))
6727        })
6728        .collect()
6729    }
6730
6731    /// Select failed-intent retention; reload durable retained aggregates.
6732    pub fn set_retain_failed_commits(&mut self, enabled: bool) -> Result<(), String> {
6733        self.retain_failed_commits = enabled;
6734        for (commit, _) in self.failed_commits.iter() {
6735            for operation in &commit.ops {
6736                self.overlay_dirty.table(&operation.table);
6737            }
6738        }
6739        self.failed_commits = self.load_failed_commits()?.into();
6740        for (commit, _) in self.failed_commits.iter() {
6741            for operation in &commit.ops {
6742                self.overlay_dirty.table(&operation.table);
6743            }
6744        }
6745        Ok(())
6746    }
6747
6748    fn load_failed_commits(&self) -> Result<Vec<FailedCommit>, String> {
6749        let mut statement = self.conn.prepare("SELECT client_commit_id, operations_json, initial_json FROM _syncular_failed_commits ORDER BY seq")
6750            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6751        let rows = statement
6752            .query_map([], |row| {
6753                Ok((
6754                    row.get::<_, String>(0)?,
6755                    row.get::<_, String>(1)?,
6756                    row.get::<_, String>(2)?,
6757                ))
6758            })
6759            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6760        rows.map(|row| {
6761            let (id, operations, initial) =
6762                row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6763            let operations: Vec<CommitOperation> =
6764                serde_json::from_str(&operations).map_err(|_| "sync.local_corrupt".to_owned())?;
6765            let initial =
6766                serde_json::from_str(&initial).map_err(|_| "sync.local_corrupt".to_owned())?;
6767            Ok((
6768                OutboxCommit {
6769                    client_commit_id: id,
6770                    ops: operations
6771                        .into_iter()
6772                        .map(|op| OutboxOp {
6773                            upsert: op.op == "upsert",
6774                            table: op.table,
6775                            row_id: op.row_id,
6776                            base_version: op.base_version,
6777                            values: op.values,
6778                            insert: op.insert,
6779                        })
6780                        .collect(),
6781                },
6782                initial,
6783            ))
6784        })
6785        .collect()
6786    }
6787
6788    fn retain_failed_commit(&mut self, id: &str, operations: &[OutboxOp]) -> Result<(), String> {
6789        let mut initial = Map::new();
6790        for operation in operations {
6791            // A table the current schema removed has no rows to retain.
6792            let Some(table) = self.schema.table(&operation.table) else {
6793                continue;
6794            };
6795            let initial_row = match self.stored_row(table, &operation.row_id, true)? {
6796                Some(row) => Some(row),
6797                None => self.visible_row(table, &operation.row_id)?,
6798            };
6799            if let Some((values, _)) = initial_row {
6800                let mut intended: Map<String, Value> = table
6801                    .columns
6802                    .iter()
6803                    .zip(values.iter())
6804                    .map(|(column, value)| (column.name.clone(), column_value_to_json(value)))
6805                    .collect();
6806                if let Some(patch) = &operation.values {
6807                    intended.extend(patch.clone());
6808                }
6809                initial.insert(
6810                    serde_json::to_string(&(operation.table.clone(), operation.row_id.clone()))
6811                        .map_err(|_| "sync.local_corrupt".to_owned())?,
6812                    Value::Object(intended),
6813                );
6814            }
6815        }
6816        self.conn.execute("INSERT INTO _syncular_failed_commits(client_commit_id, operations_json, initial_json) VALUES (?1, ?2, ?3)", rusqlite::params![id,
6817            serde_json::to_string(&operations.iter().map(CommitOperation::from).collect::<Vec<_>>()).map_err(|_| "sync.local_corrupt".to_owned())?,
6818            serde_json::to_string(&initial).map_err(|_| "sync.local_corrupt".to_owned())?])
6819            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6820        self.failed_commits.push((
6821            OutboxCommit {
6822                client_commit_id: id.to_owned(),
6823                ops: operations.to_vec(),
6824            },
6825            initial,
6826        ));
6827        Ok(())
6828    }
6829
6830    fn drop_failed_commits(
6831        &mut self,
6832        matches: impl Fn(&str, &Map<String, Value>) -> bool,
6833    ) -> Result<Vec<OutboxCommit>, String> {
6834        let mut doomed = self.drop_acknowledged_rows(&matches)?;
6835        for (commit, initial) in self.failed_commits.iter() {
6836            for operation in &commit.ops {
6837                let key =
6838                    serde_json::to_string(&(operation.table.clone(), operation.row_id.clone()))
6839                        .map_err(|_| "sync.local_corrupt".to_owned())?;
6840                if initial
6841                    .get(&key)
6842                    .and_then(Value::as_object)
6843                    .is_some_and(|values| matches(&operation.table, values))
6844                {
6845                    doomed.push(commit.clone());
6846                    break;
6847                }
6848            }
6849        }
6850        for commit in &doomed {
6851            self.conn
6852                .execute(
6853                    "DELETE FROM _syncular_failed_commits WHERE client_commit_id = ?1",
6854                    rusqlite::params![commit.client_commit_id],
6855                )
6856                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6857        }
6858        for commit in &doomed {
6859            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))?;
6860        }
6861        self.conflicts.retain(|record| {
6862            !doomed
6863                .iter()
6864                .any(|commit| commit.client_commit_id == record.client_commit_id)
6865        });
6866        self.rejections.retain(|record| {
6867            !doomed
6868                .iter()
6869                .any(|commit| commit.client_commit_id == record.client_commit_id)
6870        });
6871        self.failed_commits.retain(|(commit, _)| {
6872            !doomed
6873                .iter()
6874                .any(|dropped| dropped.client_commit_id == commit.client_commit_id)
6875        });
6876        for commit in &doomed {
6877            for operation in &commit.ops {
6878                self.overlay_dirty.table(&operation.table);
6879            }
6880        }
6881        Ok(doomed)
6882    }
6883
6884    /// Record one commit of local mutations. The returned commit ID is the
6885    /// §2.3 idempotency key. Failures are structured so callers read
6886    /// `code`/`message`/`details` instead of parsing a string prefix.
6887    pub fn mutate(&mut self, mutations: Vec<Mutation>) -> Result<String, ClientError> {
6888        let prior = self.storage_failure.borrow_mut().take();
6889        let outcome = self
6890            .prepare_mutations(mutations)
6891            .and_then(|ops| Ok(self.record_outbox_commit(ops, None)?));
6892        self.finish_authoring(prior, outcome)
6893    }
6894
6895    /// §7.1: validate one commit's mutations into outbox operations.
6896    fn prepare_mutations(&self, mutations: Vec<Mutation>) -> Result<Vec<OutboxOp>, ClientError> {
6897        {
6898            if mutations.is_empty() {
6899                return Err(
6900                    "sync.invalid_request: a commit must contain at least one operation (§6.1)"
6901                        .to_owned()
6902                        .into(),
6903                );
6904            }
6905            let mut ops = Vec::with_capacity(mutations.len());
6906            // §7.1: a patch reads the row as the commit's earlier operations
6907            // leave it: the values an earlier upsert wrote, or None after an
6908            // earlier delete. A patch changes neither presence nor a scope
6909            // column, so it records nothing.
6910            let mut staged: HashMap<(String, String), Option<Map<String, Value>>> = HashMap::new();
6911            for mutation in mutations {
6912                match mutation {
6913                    Mutation::Patch {
6914                        table,
6915                        values,
6916                        base_version,
6917                    } => {
6918                        let schema_table = self
6919                            .schema
6920                            .table(&table)
6921                            .ok_or_else(|| "sync.unknown_table".to_owned())?;
6922                        let values = normalize_values_casing(schema_table, values)?;
6923                        let row_id = render_row_id_json(values.get(&schema_table.primary_key))?;
6924                        let base = staged.get(&(table.clone(), row_id.clone()));
6925                        ops.push(self.prepare_patch(
6926                            &table,
6927                            &row_id,
6928                            values,
6929                            base_version,
6930                            base,
6931                        )?);
6932                    }
6933                    Mutation::Upsert {
6934                        table,
6935                        values,
6936                        base_version,
6937                    } => {
6938                        let schema_table = self.schema.table(&table).ok_or_else(|| {
6939                            format!("sync.unknown_table: unknown table {table:?}")
6940                        })?;
6941                        // §5: value keys are accepted in snake_case AND the
6942                        // generated row types' camelCase; normalize to SQL truth
6943                        // before the pk lookup / codec see them.
6944                        let values = normalize_values_casing(schema_table, values)?;
6945                        let row_id = render_row_id_json(values.get(&schema_table.primary_key))?;
6946                        // §6.7 `mutate` marks every column present: fill missing
6947                        // nullable columns with NULL before the payload is built.
6948                        let values = full_row_values(schema_table, values)?;
6949                        self.refuse_sealed_row(schema_table, &row_id)?;
6950                        // §5.11: validate the payload encodes with the current
6951                        // codec. A key-selection or unknown-key failure is a
6952                        // durable rejection at the push seam (§10.3), never an
6953                        // author-time error. Full-row `mutate` presents every
6954                        // column, so no stored fallback is needed.
6955                        self.validate_author_encode(schema_table, &row_id, &values)?;
6956                        // §7.1 insert intent: the row is absent from the
6957                        // visible replica at call time, before this batch
6958                        // applies anything.
6959                        let insert = !self.visible_row_exists(schema_table, &row_id)?;
6960                        staged.insert((table.clone(), row_id.clone()), Some(values.clone()));
6961                        ops.push(OutboxOp {
6962                            upsert: true,
6963                            table,
6964                            row_id,
6965                            base_version,
6966                            values: Some(values),
6967                            insert,
6968                        });
6969                    }
6970                    Mutation::Delete {
6971                        table,
6972                        row_id,
6973                        base_version,
6974                    } => {
6975                        let schema_table = self.schema.table(&table).ok_or_else(|| {
6976                            format!("sync.unknown_table: unknown table {table:?}")
6977                        })?;
6978                        self.refuse_sealed_row(schema_table, &row_id)?;
6979                        // §2.4: the server rejects a rowId holding U+0000.
6980                        if row_id.contains('\0') {
6981                            return Err("sync.invalid_request: rowId holds U+0000 (§2.4)"
6982                                .to_owned()
6983                                .into());
6984                        }
6985                        staged.insert((table.clone(), row_id.clone()), None);
6986                        ops.push(OutboxOp {
6987                            upsert: false,
6988                            table,
6989                            row_id,
6990                            base_version,
6991                            values: None,
6992                            insert: false,
6993                        });
6994                    }
6995                }
6996            }
6997            Ok(ops)
6998        }
6999    }
7000
7001    /// Scope the retained `storage_failure` diagnostic to this call so an
7002    /// earlier operation's failure cannot classify a new one, and surface the
7003    /// call's own classified failure with its details. A fresh classified
7004    /// failure replaces the retained diagnostic; otherwise the earlier one is
7005    /// kept for the next sync.
7006    fn finish_authoring<T>(
7007        &self,
7008        prior: Option<QueryReadFailure>,
7009        outcome: Result<T, ClientError>,
7010    ) -> Result<T, ClientError> {
7011        let fresh = self.storage_failure.borrow_mut().take();
7012        *self.storage_failure.borrow_mut() = fresh.clone().or(prior);
7013        outcome.map_err(|error| fresh.map(ClientError::from).unwrap_or(error))
7014    }
7015
7016    /// `decides` names the active outcome this commit replaces (§7.2.2); the
7017    /// outcome records it as its pending decision in the same transaction.
7018    fn record_outbox_commit(
7019        &mut self,
7020        ops: Vec<OutboxOp>,
7021        decides: Option<&str>,
7022    ) -> Result<String, String> {
7023        let commit = OutboxCommit {
7024            client_commit_id: uuid::Uuid::new_v4().to_string(),
7025            ops,
7026        };
7027        self.begin_observation("syncular_mutation")?;
7028        let mut batch = ChangeAccumulator::default();
7029        for op in &commit.ops {
7030            let mut precise = self.record_row_scopes(&mut batch, &op.table, &op.row_id, false);
7031            if let Some(values) = &op.values {
7032                if let Some(table) = self.schema.table(&op.table) {
7033                    for scope in &table.scope_variables {
7034                        if let Some(Value::String(value)) = values.get(&scope.column) {
7035                            batch.scope(&op.table, format!("{}:{value}", scope.prefix));
7036                            precise = true;
7037                        }
7038                    }
7039                }
7040            }
7041            if !precise {
7042                batch.table(&op.table);
7043            }
7044        }
7045        let persisted = self.persist_outbox_insert(&commit).and_then(|()| {
7046            let Some(outcome) = decides else {
7047                return Ok(());
7048            };
7049            batch.outcomes = true;
7050            let updated = self
7051                .conn
7052                .execute(
7053                    "UPDATE _syncular_commit_outcomes SET replacement_client_commit_id = ?1
7054                      WHERE client_commit_id = ?2 AND resolution = 'active'
7055                        AND replacement_client_commit_id IS NULL",
7056                    rusqlite::params![commit.client_commit_id, outcome],
7057                )
7058                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
7059            if updated == 1 {
7060                Ok(())
7061            } else {
7062                Err(REPLACEMENT_PENDING.to_owned())
7063            }
7064        });
7065        if let Err(error) = persisted {
7066            self.rollback_observation("syncular_mutation");
7067            return Err(error);
7068        }
7069        // A clean overlay contains the FIFO fold of every previous commit, so
7070        // the new commit applies over it. §7.1: an operation that does not
7071        // apply (a secondary unique collision) fails the whole commit; the
7072        // savepoint rollback removes the outbox entry and every visible write.
7073        // The append undoes itself: a rollback capture would copy the outbox.
7074        let was_dirty = self.overlay_dirty.snapshot();
7075        let id = commit.client_commit_id.clone();
7076        let appended = self.rebuild_overlay_if_dirty().and_then(|()| {
7077            commit
7078                .ops
7079                .iter()
7080                .try_for_each(|op| self.apply_outbox_op(op))?;
7081            self.outbox.push(Arc::new(commit));
7082            batch.status = true;
7083            self.finish_observation("syncular_mutation", batch)
7084                .inspect_err(|_| drop(self.outbox.pop()))
7085        });
7086        if let Err(error) = appended {
7087            self.rollback_observation("syncular_mutation");
7088            self.overlay_dirty.restore(was_dirty);
7089            return Err(error);
7090        }
7091        Ok(id)
7092    }
7093
7094    /// Record one §6.1 sparse upsert: the primary key plus the supplied
7095    /// non-scope columns are present; every other column is absent and stays
7096    /// untouched on the server and in the local overlay. An absent local base
7097    /// refuses the whole batch with sync.row_missing before enqueueing (§7.1).
7098    /// Failures are structured so callers read `code`/`message`/`details`.
7099    pub fn patch(
7100        &mut self,
7101        table: &str,
7102        row_id: &str,
7103        partial: Map<String, Value>,
7104        base_version: Option<i64>,
7105    ) -> Result<String, ClientError> {
7106        let prior = self.storage_failure.borrow_mut().take();
7107        let outcome = self.perform_patch(table, row_id, partial, base_version);
7108        self.finish_authoring(prior, outcome)
7109    }
7110
7111    /// The unscoped patch body. Public authoring entry points scope
7112    /// `storage_failure` around the whole operation, including any pre-read.
7113    fn perform_patch(
7114        &mut self,
7115        table: &str,
7116        row_id: &str,
7117        partial: Map<String, Value>,
7118        base_version: Option<i64>,
7119    ) -> Result<String, ClientError> {
7120        let operation = self.prepare_patch(table, row_id, partial, base_version, None)?;
7121        Ok(self.record_outbox_commit(vec![operation], None)?)
7122    }
7123
7124    /// `staged` is the row as the batch's earlier operations leave it
7125    /// (`Some(None)` after a delete); `None` reads the visible replica.
7126    fn prepare_patch(
7127        &self,
7128        table: &str,
7129        row_id: &str,
7130        partial: Map<String, Value>,
7131        base_version: Option<i64>,
7132        staged: Option<&Option<Map<String, Value>>>,
7133    ) -> Result<OutboxOp, ClientError> {
7134        let schema_table = self
7135            .schema
7136            .table(table)
7137            .ok_or_else(|| format!("sync.unknown_table: unknown table {table:?}"))?;
7138        let partial = normalize_values_casing(schema_table, partial)?;
7139        if let Some(pk) = partial.get(&schema_table.primary_key) {
7140            if render_row_id_json(Some(pk)).ok().as_deref() != Some(row_id) {
7141                return Err(invalid_authoring(
7142                    "patch cannot change the primary key",
7143                    json!({ "table": table }),
7144                ));
7145            }
7146        }
7147        let exists = match staged {
7148            Some(row) => row.is_some(),
7149            None => self.visible_row_exists(schema_table, row_id)?,
7150        };
7151        if !exists {
7152            return Err("sync.row_missing: a sparse patch requires a local row"
7153                .to_owned()
7154                .into());
7155        }
7156        self.refuse_sealed_row(schema_table, row_id)?;
7157        // §3.4 rule 5 / §6.2: scope columns are immutable on update. The
7158        // server accepts a present scope column whose value equals the
7159        // stored row and applies it as a no-op, so a decoded envelope
7160        // round-trips. The local row is the only value the client can prove
7161        // equality against; when the row is absent locally the client cannot
7162        // prove equality against the server's stored row and fails closed.
7163        // A primary key that is also a scope column needs no stored-row
7164        // read: the primary key in a sparse payload is by construction the
7165        // row id being patched (§6.1), so its value is proven equal already.
7166        for scope in &schema_table.scope_variables {
7167            if !partial.contains_key(&scope.column) || scope.column == schema_table.primary_key {
7168                continue;
7169            }
7170            let Some(column) = schema_table
7171                .columns
7172                .iter()
7173                .find(|column| column.name == scope.column)
7174            else {
7175                continue;
7176            };
7177            let stored = match staged {
7178                Some(row) => row.as_ref().and_then(|row| {
7179                    json_to_column_value(column, row.get(&scope.column))
7180                        .ok()
7181                        .map(|value| column_value_to_json(&value))
7182                }),
7183                None => self
7184                    .conn
7185                    .query_row(
7186                        &format!(
7187                            "SELECT {} FROM {} WHERE {}",
7188                            quote_ident(&scope.column),
7189                            visible_table(&schema_table.name),
7190                            row_id_predicate(schema_table)
7191                        ),
7192                        rusqlite::params![row_id],
7193                        |row| Ok(sql_ref_to_json(column, row.get_ref(0)?)),
7194                    )
7195                    .optional()
7196                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?,
7197            };
7198            // Decode the supplied value through the same column-type path the
7199            // rest of the patch encoding uses, so a value that only equals
7200            // the stored one in another number representation still compares
7201            // equal.
7202            let incoming = json_to_column_value(column, partial.get(&scope.column))
7203                .ok()
7204                .map(|value| column_value_to_json(&value));
7205            // A stored blob never equals a patch value, matching the server's
7206            // scope-column comparison (§3.4): bytes are unstorable as scope
7207            // values.
7208            let equal = stored.as_ref().is_some_and(|stored| {
7209                stored.get("$bytes").is_none() && incoming.as_ref() == Some(stored)
7210            });
7211            if !equal {
7212                return Err(invalid_authoring(
7213                    "patch cannot write a scope column (§3.4)",
7214                    json!({ "table": table, "column": scope.column }),
7215                ));
7216            }
7217        }
7218        let mut values = partial;
7219        // Presence-set semantics: a proven-equal scope column is dropped, so
7220        // the patch leaves the stored value untouched (§6.2).
7221        for scope in &schema_table.scope_variables {
7222            values.remove(&scope.column);
7223        }
7224        let pk_value = match schema_table.columns[schema_table.pk_index].ty {
7225            // §2.4: the rowId of an integer key is its canonical decimal form.
7226            ColumnType::Integer => match row_id.parse::<i64>() {
7227                Ok(v)
7228                    if v.to_string() == row_id
7229                        && (-ssp2::primitives::I64_SAFE_MAX..=ssp2::primitives::I64_SAFE_MAX)
7230                            .contains(&v) =>
7231                {
7232                    Value::from(v)
7233                }
7234                _ => {
7235                    return Err(format!(
7236                    "sync.invalid_request: table {table:?}: invalid integer primary key {row_id:?}"
7237                )
7238                    .into())
7239                }
7240            },
7241            ColumnType::Boolean => match row_id {
7242                "true" => Value::Bool(true),
7243                "false" => Value::Bool(false),
7244                _ => {
7245                    return Err(format!(
7246                    "sync.invalid_request: table {table:?}: invalid boolean primary key {row_id:?}"
7247                )
7248                    .into())
7249                }
7250            },
7251            _ => Value::from(row_id.to_owned()),
7252        };
7253        values.insert(schema_table.primary_key.clone(), pk_value);
7254        // §6.1: a patch cannot null a non-nullable column.
7255        if let Some(column) = schema_table
7256            .columns
7257            .iter()
7258            .find(|column| !column.nullable && values.get(&column.name) == Some(&Value::Null))
7259        {
7260            return Err(invalid_authoring(
7261                "a non-nullable column is null (§6.1)",
7262                json!({ "table": table, "column": column.name }),
7263            ));
7264        }
7265        // §5.11: structural validation only; an absent key-id selector is
7266        // resolved at the push seam from the stored local row, and a
7267        // key-selection or unknown-key failure becomes a durable
7268        // `client.encrypt_failed` rejection there (§10.3), never an
7269        // author-time error.
7270        self.validate_author_encode(schema_table, row_id, &values)?;
7271        Ok(OutboxOp {
7272            upsert: true,
7273            table: table.to_owned(),
7274            row_id: row_id.to_owned(),
7275            base_version,
7276            values: Some(values),
7277            insert: false,
7278        })
7279    }
7280
7281    /// §5.11 key-id fallback: the stored local row's selector value as a
7282    /// positional row (only the selector slot filled). Returns None when no
7283    /// selector is configured, the row is locally absent, or the stored
7284    /// value is not a usable key id. A failed storage read is an error.
7285    fn stored_key_fallback(
7286        &self,
7287        table: &TableSchema,
7288        row_id: &str,
7289    ) -> Result<Option<Row>, String> {
7290        let Some(selector) = self.encryption.key_id_columns.get(&table.name) else {
7291            return Ok(None);
7292        };
7293        let Some(index) = table
7294            .columns
7295            .iter()
7296            .position(|column| &column.name == selector)
7297        else {
7298            return Ok(None);
7299        };
7300        let sql = format!(
7301            "SELECT {} FROM {} WHERE {}",
7302            quote_ident(selector),
7303            visible_table(&table.name),
7304            row_id_predicate(table)
7305        );
7306        let key = self
7307            .conn
7308            .query_row(&sql, rusqlite::params![row_id], |row| {
7309                row.get::<_, Option<String>>(0)
7310            })
7311            .optional()
7312            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
7313            .flatten()
7314            .filter(|key| !key.is_empty());
7315        let Some(key) = key else {
7316            return Ok(None);
7317        };
7318        let mut fallback: Row = vec![None; table.columns.len()];
7319        fallback[index] = Some(ColumnValue::String(key));
7320        Ok(Some(fallback))
7321    }
7322
7323    /// §5.11/§10.3 author-time encode check: a structural failure (a
7324    /// non-nullable NULL, a value the codec rejects) is an author-time
7325    /// error; a key-selection or unknown-key failure is deferred to the push
7326    /// seam, where it becomes a durable `client.encrypt_failed` rejection.
7327    fn validate_author_encode(
7328        &self,
7329        table: &TableSchema,
7330        row_id: &str,
7331        values: &Map<String, Value>,
7332    ) -> Result<(), String> {
7333        match encode_sparse_row_json(table, row_id, values, &self.encryption, None) {
7334            Err(error) if error.starts_with(ENCRYPT_FAILED_CODE) => Ok(()),
7335            result => result.map(|_| ()),
7336        }
7337    }
7338
7339    /// §5.11/§10.3: drop every pending commit whose push encode fails with
7340    /// `client.encrypt_failed` (an unresolvable key id or an unknown key) and
7341    /// raise one durable rejection per commit. `sync()` never aborts for an
7342    /// encode failure. Mirrors §7.4.4's `drop_incompatible_outbox`, including
7343    /// undoing the dropped commit's purely-optimistic rows.
7344    /// §7.1/§7.4.4: drop pending commits whose values the current codec refuses
7345    /// (an envelope or a type an earlier version accepted). `with_encryption`
7346    /// additionally drops commits whose §5.11 encryption cannot resolve a key;
7347    /// the startup boundary leaves those to the send seam, where hosts configure
7348    /// keys after open. The send path checks only the commits this round pushes
7349    /// (§8.8): a held commit is never encoded or dropped before it is due.
7350    /// Recovery runs as one observation. An enclosing observation (the guarded
7351    /// schema reset) passes its `batch`, so the rejection, outcome, and table
7352    /// domains join that change event instead of publishing a second one.
7353    fn drop_unencodable_outbox(
7354        &mut self,
7355        with_encryption: bool,
7356        batch: Option<&mut ChangeAccumulator>,
7357    ) -> Result<bool, String> {
7358        let mut failures = Vec::new();
7359        let due = if with_encryption {
7360            self.pushable_commits()
7361        } else {
7362            self.outbox.len()
7363        };
7364        for commit in self.outbox.iter().take(due) {
7365            for op in &commit.ops {
7366                let Some(table) = self.schema.table(&op.table).filter(|_| op.upsert) else {
7367                    continue;
7368                };
7369                // An insert lacking a non-nullable column is left to
7370                // `drop_incompatible_outbox` (§7.4.4).
7371                let Some(values) = op.presented_values(table) else {
7372                    continue;
7373                };
7374                let fallback = self.stored_key_fallback(table, &op.row_id)?;
7375                let failure = match encode_sparse_row_json(
7376                    table,
7377                    &op.row_id,
7378                    &values,
7379                    &self.encryption,
7380                    fallback.as_ref(),
7381                ) {
7382                    Err(error) if error.starts_with(ENCRYPT_FAILED_CODE) => {
7383                        with_encryption.then_some((error, ENCRYPT_FAILED_CODE))
7384                    }
7385                    // §7.1/§7.4.4: a value the current codec refuses was
7386                    // persisted by a version that accepted it; it leaves
7387                    // through the incompatible-outbox path, so the FIFO
7388                    // queue never wedges.
7389                    Err(error) if error.starts_with(INVALID_REQUEST_CODE) => Some((
7390                        LEGACY_VALUE_REFUSAL_MESSAGE.to_owned(),
7391                        OUTBOX_INCOMPATIBLE_CODE,
7392                    )),
7393                    _ => None,
7394                };
7395                if let Some((error, code)) = failure {
7396                    failures.push((commit.clone(), error, code));
7397                    break;
7398                }
7399            }
7400        }
7401        if failures.is_empty() {
7402            return Ok(false);
7403        }
7404        self.reject_outbox_commits(
7405            failures
7406                .into_iter()
7407                .map(|(commit, message, code)| {
7408                    let details = (code == OUTBOX_INCOMPATIBLE_CODE).then(|| RejectionDetails {
7409                        field_paths: None,
7410                        reason: Some(INVALID_STORED_VALUES_REASON.to_owned()),
7411                        required_action: None,
7412                        references: None,
7413                    });
7414                    (commit, message, code, details)
7415                })
7416                .collect(),
7417            batch,
7418        )?;
7419        Ok(true)
7420    }
7421
7422    /// §7.4.4 client-local terminal drop of pending commits, each journaled as a
7423    /// rejection with `code` and `details`. Every code except
7424    /// `sync.outbox_incompatible` keeps the retained intent.
7425    #[allow(clippy::type_complexity)]
7426    fn reject_outbox_commits(
7427        &mut self,
7428        failures: Vec<(
7429            Arc<OutboxCommit>,
7430            String,
7431            &'static str,
7432            Option<RejectionDetails>,
7433        )>,
7434        batch: Option<&mut ChangeAccumulator>,
7435    ) -> Result<(), String> {
7436        // §7.4.4: one observation covers the durable outcome writes, the outbox
7437        // removal, the in-memory drop, and the overlay rebuild, so a storage fault
7438        // leaves the replica and the client unchanged, a successful recovery
7439        // publishes one batch with the rejection, outcome, and table domains, and
7440        // an ordinary open with nothing to recover publishes nothing.
7441        let rollback = self.capture();
7442        let owns_observation = batch.is_none();
7443        let owns_transaction = self.conn.is_autocommit();
7444        let mut domains = ChangeAccumulator::default();
7445        if owns_observation {
7446            self.begin_observation("syncular_value_recovery")?;
7447        }
7448        let dropped = (|| -> Result<(), String> {
7449            for (commit, message, code, details) in failures {
7450                if self.retain_failed_commits && code != OUTBOX_INCOMPATIBLE_CODE {
7451                    self.retain_failed_commit(&commit.client_commit_id, &commit.ops)?;
7452                }
7453                let representable = commit.ops.iter().all(Self::outbox_op_is_journalable);
7454                let rejection = RejectionRecord {
7455                    client_commit_id: commit.client_commit_id.clone(),
7456                    op_index: 0,
7457                    code: code.to_owned(),
7458                    message,
7459                    retryable: false,
7460                    details,
7461                    operation: representable
7462                        .then(|| commit.ops.first())
7463                        .flatten()
7464                        .map(CommitOperation::from),
7465                };
7466                self.persist_commit_outcome(
7467                    &commit.client_commit_id,
7468                    CommitOutcomeStatus::Rejected,
7469                    &[CommitOperationOutcome::Error {
7470                        rejection: rejection.clone(),
7471                    }],
7472                    representable.then_some(commit.ops.as_slice()),
7473                )?;
7474                self.leave_through(&commit.client_commit_id);
7475                self.delete_outbox_persisted(&commit.client_commit_id)?;
7476                self.outbox
7477                    .retain(|candidate| candidate.client_commit_id != commit.client_commit_id);
7478                self.rejections.push(rejection);
7479                for operation in &commit.ops {
7480                    domains.table(operation.table.as_str());
7481                }
7482            }
7483            domains.status = true;
7484            domains.rejections = true;
7485            domains.outcomes = true;
7486            self.prune_commit_outcomes()?;
7487            // The visible projection is re-derived from the surviving base + outbox.
7488            self.overlay_dirty.set(true);
7489            self.rebuild_overlay()?;
7490            Ok(())
7491        })();
7492        let result = match batch {
7493            Some(batch) => {
7494                if dropped.is_ok() {
7495                    for table in domains.tables.keys() {
7496                        batch.table(table.as_str());
7497                    }
7498                    batch.status |= domains.status;
7499                    batch.rejections |= domains.rejections;
7500                    batch.outcomes |= domains.outcomes;
7501                }
7502                dropped
7503            }
7504            None => {
7505                dropped.and_then(|()| self.finish_observation("syncular_value_recovery", domains))
7506            }
7507        };
7508        if let Err(error) = result {
7509            if owns_observation {
7510                if owns_transaction {
7511                    if let Err(rollback) = self.conn.execute_batch("ROLLBACK") {
7512                        let mut failure = self.storage_failure.borrow_mut();
7513                        let failure =
7514                            failure.get_or_insert_with(|| QueryReadFailure::from(error.clone()));
7515                        failure.rollback_failure = Some(Box::new(QueryReadFailure::from(rollback)));
7516                    }
7517                } else {
7518                    self.rollback_observation("syncular_value_recovery");
7519                }
7520            }
7521            self.restore(rollback);
7522            return Err(error);
7523        }
7524        Ok(())
7525    }
7526
7527    pub fn pending_commit_ids(&self) -> Vec<String> {
7528        self.outbox
7529            .iter()
7530            .map(|c| c.client_commit_id.clone())
7531            .collect()
7532    }
7533
7534    /// §7.1: every pending commit in FIFO order, as the TypeScript client's
7535    /// `pendingCommits()` returns it.
7536    pub fn pending_commits(&self) -> Result<Vec<PendingCommit>, String> {
7537        let mut stmt = self
7538            .conn
7539            .prepare_cached(
7540                "SELECT seq, commit_id, created_at_ms, ops_json FROM _syncular_outbox ORDER BY seq",
7541            )
7542            .map_err(|error| error.to_string())?;
7543        let rows = stmt
7544            .query_map([], |row| {
7545                Ok((
7546                    row.get(0)?,
7547                    row.get(1)?,
7548                    row.get(2)?,
7549                    row.get::<_, String>(3)?,
7550                ))
7551            })
7552            .map_err(|error| error.to_string())?;
7553        rows.map(|row| {
7554            let (seq, client_commit_id, created_at_ms, raw) =
7555                row.map_err(|error| error.to_string())?;
7556            let operations = serde_json::from_str(&raw).map_err(|error| {
7557                format!("invalid persisted outbox {client_commit_id:?}: {error}")
7558            })?;
7559            Ok(PendingCommit {
7560                seq,
7561                client_commit_id,
7562                created_at_ms,
7563                operations,
7564            })
7565        })
7566        .collect()
7567    }
7568
7569    /// §6.1: the sparse push payload bytes of every pending upsert operation,
7570    /// FIFO — exactly what the next push round would put on the wire. Used by
7571    /// conformance B.21(h) to pin cross-core byte identity.
7572    pub fn pending_payloads(&self) -> Result<Vec<Vec<u8>>, String> {
7573        let mut payloads = Vec::new();
7574        for commit in self.outbox.iter() {
7575            for op in &commit.ops {
7576                let Some(table) = self.schema.table(&op.table).filter(|_| op.upsert) else {
7577                    continue;
7578                };
7579                let Some(values) = op.presented_values(table) else {
7580                    continue;
7581                };
7582                let fallback = self.stored_key_fallback(table, &op.row_id)?;
7583                if let Ok(payload) = encode_sparse_row_json(
7584                    table,
7585                    &op.row_id,
7586                    &values,
7587                    &self.encryption,
7588                    fallback.as_ref(),
7589                ) {
7590                    payloads.push(payload);
7591                }
7592            }
7593        }
7594        Ok(payloads)
7595    }
7596
7597    pub fn conflicts(&self) -> &[ConflictRecord] {
7598        &self.conflicts
7599    }
7600
7601    pub fn rejections(&self) -> &[RejectionRecord] {
7602        &self.rejections
7603    }
7604
7605    pub fn resolve_commit_outcome(
7606        &mut self,
7607        input: ResolveCommitOutcomeInput,
7608    ) -> Result<CommitOutcome, String> {
7609        let current = self
7610            .commit_outcome(&input.client_commit_id)?
7611            .ok_or_else(|| {
7612                format!(
7613                    "sync.outcome_not_found: no durable outcome exists for {:?}",
7614                    input.client_commit_id
7615                )
7616            })?;
7617        if current.resolution != CommitOutcomeResolution::Active {
7618            return Ok(current);
7619        }
7620        if current.replacement_client_commit_id.is_some() {
7621            return Err(REPLACEMENT_PENDING.to_owned());
7622        }
7623        if input.resolution == CommitOutcomeResolution::Active {
7624            return Err("sync.invalid_request: resolution must leave active state".to_owned());
7625        }
7626        match input.resolution {
7627            CommitOutcomeResolution::Superseded => {
7628                let replacement = input
7629                    .replacement_client_commit_id
7630                    .as_deref()
7631                    .filter(|value| !value.is_empty() && *value != input.client_commit_id)
7632                    .ok_or_else(|| {
7633                        "sync.invalid_request: superseded outcomes require a distinct replacementClientCommitId"
7634                            .to_owned()
7635                    })?;
7636                let _ = replacement;
7637            }
7638            _ if input.replacement_client_commit_id.is_some() => {
7639                return Err(
7640                    "sync.invalid_request: replacementClientCommitId is valid only for superseded outcomes"
7641                        .to_owned(),
7642                );
7643            }
7644            _ => {}
7645        }
7646        let allowed = match current.status {
7647            CommitOutcomeStatus::Conflict => matches!(
7648                input.resolution,
7649                CommitOutcomeResolution::ResolvedKeepServer | CommitOutcomeResolution::Superseded
7650            ),
7651            CommitOutcomeStatus::Rejected => {
7652                matches!(
7653                    input.resolution,
7654                    CommitOutcomeResolution::Superseded
7655                        | CommitOutcomeResolution::ResolvedKeepServer
7656                )
7657            }
7658            CommitOutcomeStatus::Applied | CommitOutcomeStatus::Cached => {
7659                input.resolution == CommitOutcomeResolution::Dismissed
7660            }
7661            CommitOutcomeStatus::Replaced => false,
7662        };
7663        if !allowed {
7664            return Err(format!(
7665                "sync.invalid_request: resolution {:?} is invalid for {:?} outcome",
7666                input.resolution, current.status
7667            ));
7668        }
7669
7670        let rollback = self.capture();
7671        self.begin_observation("syncular_outcome_resolution")?;
7672        let mut batch = ChangeAccumulator::default();
7673        let result = self
7674            .release_outcome(
7675                &current,
7676                input.resolution,
7677                input.replacement_client_commit_id.as_deref(),
7678                &mut batch,
7679            )
7680            .and_then(|()| self.rebuild_overlay_if_dirty())
7681            .and_then(|()| self.finish_observation("syncular_outcome_resolution", batch));
7682        if let Err(error) = result {
7683            self.rollback_observation("syncular_outcome_resolution");
7684            self.restore(rollback);
7685            return Err(error);
7686        }
7687        self.commit_outcome(&current.client_commit_id)?
7688            .ok_or_else(|| "sync.outcome_not_found: outcome disappeared".to_owned())
7689    }
7690
7691    /// §7.2.2: record a decision against an active conflict or rejection as a
7692    /// held replacement commit and return its client commit id. Without
7693    /// `replacement` the retained envelope is kept ("keep mine"); every
7694    /// operation on a retained row takes that row's base version.
7695    pub fn replace_commit_outcome(
7696        &mut self,
7697        client_commit_id: &str,
7698        sequence: i64,
7699        replacement: Option<Vec<Mutation>>,
7700    ) -> Result<String, ClientError> {
7701        let prior = self.storage_failure.borrow_mut().take();
7702        let outcome = (|| -> Result<String, ClientError> {
7703            let Some(current) = self.commit_outcome(client_commit_id)? else {
7704                return Err(ClientError {
7705                    code: "sync.outcome_not_found".to_owned(),
7706                    message: "no durable outcome exists for the commit".to_owned(),
7707                    details: Some(json!({ "clientCommitId": client_commit_id })),
7708                    retryable: false,
7709                });
7710            };
7711            if current.resolution == CommitOutcomeResolution::Active
7712                && current.replacement_client_commit_id.is_some()
7713            {
7714                return Err(ClientError {
7715                    code: "client.replacement_pending".to_owned(),
7716                    message: "the outcome has a pending replacement".to_owned(),
7717                    details: Some(json!({ "clientCommitId": client_commit_id })),
7718                    retryable: false,
7719                });
7720            }
7721            let (Some(envelope), Some(rows)) = (current.operations, current.retained_rows) else {
7722                return Err(invalid_authoring(
7723                    "the outcome cannot be replaced",
7724                    json!({ "clientCommitId": client_commit_id }),
7725                ));
7726            };
7727            if current.sequence != sequence
7728                || current.resolution != CommitOutcomeResolution::Active
7729                || !matches!(
7730                    current.status,
7731                    CommitOutcomeStatus::Conflict | CommitOutcomeStatus::Rejected
7732                )
7733                || rows.is_empty()
7734                || envelope.len() != rows.len()
7735            {
7736                return Err(invalid_authoring(
7737                    "the outcome cannot be replaced",
7738                    json!({ "clientCommitId": client_commit_id }),
7739                ));
7740            }
7741            let ops = match replacement {
7742                None => envelope
7743                    .into_iter()
7744                    .zip(&rows)
7745                    .map(|(operation, row)| OutboxOp {
7746                        base_version: Some(row.server_version.unwrap_or(0)),
7747                        ..OutboxOp::from(operation)
7748                    })
7749                    .collect(),
7750                Some(mutations) => {
7751                    let mut ops = self.prepare_mutations(mutations)?;
7752                    for op in &mut ops {
7753                        let Some(row) = rows
7754                            .iter()
7755                            .find(|row| row.table == op.table && row.row_id == op.row_id)
7756                        else {
7757                            continue;
7758                        };
7759                        if op.base_version.is_some() {
7760                            return Err(invalid_authoring(
7761                                "an operation on a retained row takes its base version",
7762                                json!({ "table": op.table }),
7763                            ));
7764                        }
7765                        op.base_version = Some(row.server_version.unwrap_or(0));
7766                    }
7767                    ops
7768                }
7769            };
7770            Ok(self.record_outbox_commit(ops, Some(client_commit_id))?)
7771        })();
7772        self.finish_authoring(prior, outcome)
7773    }
7774
7775    /// §7.2.3: replace the operations of the pending commit `client_commit_id`
7776    /// and return `replacement_client_commit_id`. An attempted commit is fenced
7777    /// first (§6.12) over `transport`; a never-attempted one needs none.
7778    pub fn replace_pending_commit(
7779        &mut self,
7780        transport: &mut dyn Transport,
7781        client_commit_id: &str,
7782        mutations: Vec<Mutation>,
7783        replacement_client_commit_id: &str,
7784    ) -> Result<String, ClientError> {
7785        match self.prepare_pending_commit_replacement(
7786            client_commit_id,
7787            mutations,
7788            replacement_client_commit_id,
7789        )? {
7790            None => Ok(replacement_client_commit_id.to_owned()),
7791            Some(prepared) => {
7792                let reply = prepared.exchange(transport);
7793                self.apply_fence_round(prepared, reply)
7794            }
7795        }
7796    }
7797
7798    /// The owner half of [`SyncClient::replace_pending_commit`]. `None` means
7799    /// the replacement is complete (or an earlier call with the same
7800    /// replacement id completed it); otherwise send the fence round and apply
7801    /// its reply with [`SyncClient::apply_fence_round`].
7802    pub fn prepare_pending_commit_replacement(
7803        &mut self,
7804        client_commit_id: &str,
7805        mutations: Vec<Mutation>,
7806        replacement_client_commit_id: &str,
7807    ) -> Result<Option<PreparedFenceRound>, ClientError> {
7808        let prior = self.storage_failure.borrow_mut().take();
7809        let outcome = (|| -> Result<Option<PreparedFenceRound>, ClientError> {
7810            let Some(original) = self
7811                .outbox
7812                .iter()
7813                .find(|commit| commit.client_commit_id == client_commit_id)
7814                .cloned()
7815            else {
7816                return match self.commit_outcome(client_commit_id)? {
7817                    Some(outcome)
7818                        if Self::is_replaced(&outcome)
7819                            && outcome.replacement_client_commit_id.as_deref()
7820                                == Some(replacement_client_commit_id) =>
7821                    {
7822                        Ok(None)
7823                    }
7824                    _ => Err(ClientError {
7825                        code: "sync.outcome_not_found".to_owned(),
7826                        message: "no pending commit exists for the id".to_owned(),
7827                        details: Some(json!({ "clientCommitId": client_commit_id })),
7828                        retryable: false,
7829                    }),
7830                };
7831            };
7832            if replacement_client_commit_id.is_empty()
7833                || self
7834                    .outbox
7835                    .iter()
7836                    .any(|commit| commit.client_commit_id == replacement_client_commit_id)
7837                || self.commit_outcome(replacement_client_commit_id)?.is_some()
7838            {
7839                return Err(invalid_authoring(
7840                    "the replacement client commit id must be unused",
7841                    json!({ "replacementClientCommitId": replacement_client_commit_id }),
7842                ));
7843            }
7844            // §7.2.2: a held replacement waits for its proof under its own id.
7845            let held: bool = self
7846                .conn
7847                .query_row(
7848                    "SELECT EXISTS(SELECT 1 FROM _syncular_commit_outcomes
7849                      WHERE resolution = 'active' AND replacement_client_commit_id = ?1)",
7850                    [client_commit_id],
7851                    |row| row.get(0),
7852                )
7853                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
7854            if held {
7855                return Err(REPLACEMENT_PENDING.to_owned().into());
7856            }
7857            let full_rows: Vec<bool> = mutations
7858                .iter()
7859                .map(|mutation| matches!(mutation, Mutation::Upsert { .. }))
7860                .collect();
7861            let mut operations = self.prepare_mutations(mutations)?;
7862            for (operation, full_row) in operations.iter_mut().zip(full_rows) {
7863                let touched: Vec<&OutboxOp> = original
7864                    .ops
7865                    .iter()
7866                    .filter(|op| op.table == operation.table && op.row_id == operation.row_id)
7867                    .collect();
7868                // §7.1: a full-row upsert of a row the original inserted keeps
7869                // the insert intent the original recorded.
7870                operation.insert |= full_row && touched.iter().any(|op| op.insert);
7871                if let Some(first) = touched.first() {
7872                    operation.base_version = first.base_version;
7873                }
7874            }
7875            let attempted: bool = self
7876                .conn
7877                .query_row(
7878                    "SELECT attempted FROM _syncular_outbox WHERE commit_id = ?1",
7879                    [client_commit_id],
7880                    |row| row.get(0),
7881                )
7882                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
7883            if !attempted {
7884                self.replace_outbox_commit(
7885                    client_commit_id,
7886                    operations,
7887                    replacement_client_commit_id,
7888                )?;
7889                return Ok(None);
7890            }
7891            if self.transport_closed() {
7892                return Err(ClientError {
7893                    code: "sync.offline".to_owned(),
7894                    message: "transport gate is closed".to_owned(),
7895                    details: None,
7896                    retryable: false,
7897                });
7898            }
7899            if self.active_round.is_some() || self.fence_round.is_some() {
7900                return Err(ClientError {
7901                    code: "client.round_in_progress".to_owned(),
7902                    message: "a sync round is already in flight".to_owned(),
7903                    details: None,
7904                    retryable: false,
7905                });
7906            }
7907            if self.realtime_policy == RealtimePolicy::Required
7908                && self.realtime_state != RealtimeState::Connected
7909            {
7910                return Err(ClientError {
7911                    code: REALTIME_UNAVAILABLE_CODE.to_owned(),
7912                    message: "the realtime socket is not connected".to_owned(),
7913                    details: None,
7914                    retryable: true,
7915                });
7916            }
7917            let header = Frame::ReqHeader {
7918                client_id: self.client_id.clone(),
7919                schema_version: self.schema.version,
7920                log_epoch: self.get_meta(LOG_EPOCH_KEY)?,
7921                outbox_id: self.get_meta(OUTBOX_ID_KEY)?,
7922            };
7923            let id = uuid::Uuid::new_v4();
7924            self.fence_round = Some(id);
7925            Ok(Some(PreparedFenceRound {
7926                id,
7927                client_commit_id: client_commit_id.to_owned(),
7928                replacement_client_commit_id: replacement_client_commit_id.to_owned(),
7929                operations,
7930                request: encode_message(&Message {
7931                    wire_version: WIRE_VERSION,
7932                    msg_kind: MsgKind::Request,
7933                    frames: vec![
7934                        header,
7935                        Frame::FenceCommit {
7936                            client_commit_id: client_commit_id.to_owned(),
7937                        },
7938                    ],
7939                }),
7940                realtime: self.realtime_state == RealtimeState::Connected,
7941            }))
7942        })();
7943        self.finish_authoring(prior, outcome)
7944    }
7945
7946    /// Apply the reply of a [`PreparedFenceRound`] on the owner (§6.12,
7947    /// §7.2.3) and return the replacement's id. No network I/O. A stored
7948    /// result settles the original through the push-result path and fails
7949    /// with `client.commit_settled`.
7950    pub fn apply_fence_round(
7951        &mut self,
7952        prepared: PreparedFenceRound,
7953        reply: Result<Vec<u8>, TransportError>,
7954    ) -> Result<String, ClientError> {
7955        if self.fence_round != Some(prepared.id) {
7956            return Err(ClientError {
7957                code: "client.round_cancelled".to_owned(),
7958                message: "fence round belongs to a released client context".to_owned(),
7959                details: None,
7960                retryable: false,
7961            });
7962        }
7963        self.fence_round = None;
7964        let prior = self.storage_failure.borrow_mut().take();
7965        let outcome = (|| -> Result<String, ClientError> {
7966            let id = prepared.client_commit_id.as_str();
7967            let invalid = || ClientError {
7968                code: "client.invalid_host_response".to_owned(),
7969                message: "the fence response does not answer the fenced commit".to_owned(),
7970                details: Some(json!({ "clientCommitId": id })),
7971                retryable: false,
7972            };
7973            let bytes = reply.map_err(|error| ClientError {
7974                retryable: error
7975                    .details
7976                    .as_ref()
7977                    .and_then(|details| details.get("retryable"))
7978                    == Some(&Value::Bool(true)),
7979                code: error.code,
7980                message: error.message,
7981                details: error.details,
7982            })?;
7983            let response = decode_message(&bytes).map_err(|_| invalid())?;
7984            if response.msg_kind != MsgKind::Response {
7985                return Err(invalid());
7986            }
7987            let mut frames = response
7988                .frames
7989                .into_iter()
7990                .filter(|frame| !matches!(frame, Frame::Keepalive));
7991            match frames.next() {
7992                // §1.6: a schema-floor response; the client stops syncing as
7993                // a sync round's floor stops it.
7994                Some(Frame::RespHeader {
7995                    required_schema_version: Some(required),
7996                    latest_schema_version,
7997                    ..
7998                }) => {
7999                    self.set_schema_floor(Some(SchemaFloor {
8000                        required_schema_version: Some(required),
8001                        latest_schema_version,
8002                    }))?;
8003                    return Err(ClientError {
8004                        code: "sync.schema_mismatch".to_owned(),
8005                        message: "the server requires a newer schema version".to_owned(),
8006                        details: Some(json!({ "requiredSchemaVersion": required })),
8007                        retryable: false,
8008                    });
8009                }
8010                Some(Frame::RespHeader {
8011                    reset_required: false,
8012                    ..
8013                }) => {}
8014                _ => return Err(invalid()),
8015            }
8016            let answer = frames.next();
8017            let rest: Vec<Frame> = frames.collect();
8018            match answer {
8019                // A server that predates the frame refuses the request.
8020                Some(Frame::Error {
8021                    code,
8022                    message,
8023                    retryable,
8024                    details,
8025                    ..
8026                }) => Err(ClientError {
8027                    code,
8028                    message,
8029                    details: details.and_then(|details| serde_json::from_str(&details.0).ok()),
8030                    retryable,
8031                }),
8032                Some(Frame::CommitFenced { client_commit_id })
8033                    if client_commit_id == id && rest.is_empty() =>
8034                {
8035                    self.replace_outbox_commit(
8036                        id,
8037                        prepared.operations,
8038                        &prepared.replacement_client_commit_id,
8039                    )?;
8040                    Ok(prepared.replacement_client_commit_id)
8041                }
8042                Some(Frame::PushResult {
8043                    client_commit_id,
8044                    status,
8045                    commit_seq,
8046                    results,
8047                }) if client_commit_id == id => {
8048                    let mut details = HashMap::new();
8049                    match rest.as_slice() {
8050                        [] => {}
8051                        [Frame::PushResultDetails {
8052                            client_commit_id: owner,
8053                            entries,
8054                        }] if owner == id => {
8055                            let parsed = entries
8056                                .iter()
8057                                .map(|entry| -> Result<_, String> {
8058                                    Ok((entry.op_index, RejectionDetails::parse(&entry.details.0)?))
8059                                })
8060                                .collect::<Result<BTreeMap<i32, RejectionDetails>, String>>()
8061                                .map_err(|_| invalid())?;
8062                            details.insert(id.to_owned(), parsed);
8063                        }
8064                        _ => return Err(invalid()),
8065                    }
8066                    let settled = if status == PushStatus::Rejected {
8067                        "rejected"
8068                    } else {
8069                        "applied"
8070                    };
8071                    let mut report = SyncReport::default();
8072                    self.handle_push_results(
8073                        &[Frame::PushResult {
8074                            client_commit_id,
8075                            status,
8076                            commit_seq,
8077                            results,
8078                        }],
8079                        &HashSet::from([id]),
8080                        &details,
8081                        &mut report,
8082                        Some(id),
8083                    )
8084                    .map_err(|_| ClientError {
8085                        code: "client.outcome_persistence_failed".to_owned(),
8086                        message: "local commit outcome could not be persisted".to_owned(),
8087                        details: None,
8088                        retryable: false,
8089                    })?;
8090                    // §6.3: a serving failure is no outcome; the commit stays.
8091                    if !report.retryable.is_empty() {
8092                        return Err(ClientError {
8093                            code: "sync.idempotency_cache_miss".to_owned(),
8094                            message: "the server could not serve the stored result".to_owned(),
8095                            details: Some(json!({ "clientCommitId": id })),
8096                            retryable: true,
8097                        });
8098                    }
8099                    Err(ClientError {
8100                        code: "client.commit_settled".to_owned(),
8101                        message: "the commit already has a server outcome".to_owned(),
8102                        details: Some(json!({ "clientCommitId": id, "status": settled })),
8103                        retryable: false,
8104                    })
8105                }
8106                _ => Err(invalid()),
8107            }
8108        })();
8109        self.finish_authoring(prior, outcome)
8110    }
8111
8112    /// §7.2.3: swap a pending commit's operations and id in place (same
8113    /// outbox sequence), re-derive the overlay of its rows and every later
8114    /// commit, and journal the original as `replaced`, in one transaction
8115    /// with one change batch.
8116    fn replace_outbox_commit(
8117        &mut self,
8118        client_commit_id: &str,
8119        ops: Vec<OutboxOp>,
8120        replacement: &str,
8121    ) -> Result<(), ClientError> {
8122        let Some(index) = self
8123            .outbox
8124            .iter()
8125            .position(|commit| commit.client_commit_id == client_commit_id)
8126        else {
8127            return Err(ClientError {
8128                code: "sync.outcome_not_found".to_owned(),
8129                message: "no pending commit exists for the id".to_owned(),
8130                details: Some(json!({ "clientCommitId": client_commit_id })),
8131                retryable: false,
8132            });
8133        };
8134        let original = self.outbox[index].clone();
8135        let commit = OutboxCommit {
8136            client_commit_id: replacement.to_owned(),
8137            ops,
8138        };
8139        let rollback = self.capture();
8140        self.begin_observation("syncular_pending_replacement")?;
8141        let mut batch = ChangeAccumulator::default();
8142        let replaced = (|| {
8143            let (seq, created_at_ms): (i64, i64) = self
8144                .conn
8145                .query_row(
8146                    "SELECT seq, created_at_ms FROM _syncular_outbox WHERE commit_id = ?1",
8147                    [client_commit_id],
8148                    |row| Ok((row.get(0)?, row.get(1)?)),
8149                )
8150                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8151            self.persist_outbox_insert(&commit)?;
8152            self.leave_through(client_commit_id);
8153            self.delete_outbox_persisted(client_commit_id)?;
8154            // §7.2.1: journaled as a purge journals its drops, decided.
8155            let results = (0..original.ops.len())
8156                .map(|op_index| CommitOperationOutcome::Error {
8157                    rejection: RejectionRecord {
8158                        client_commit_id: client_commit_id.to_owned(),
8159                        op_index: op_index as i32,
8160                        code: COMMIT_REPLACED_CODE.to_owned(),
8161                        message: "the commit was replaced before the server applied it".to_owned(),
8162                        retryable: false,
8163                        details: None,
8164                        operation: None,
8165                    },
8166                })
8167                .collect::<Vec<_>>();
8168            let results_json =
8169                serde_json::to_string(&results).map_err(|error| error.to_string())?;
8170            self.conn
8171                .execute(
8172                    "UPDATE _syncular_outbox SET seq = ?1, created_at_ms = ?2 WHERE commit_id = ?3",
8173                    rusqlite::params![seq, created_at_ms, replacement],
8174                )
8175                .and_then(|_| {
8176                    self.conn.execute(
8177                        "INSERT INTO _syncular_commit_outcomes (
8178                           client_commit_id, status, recorded_at_ms, results_json, resolution,
8179                           resolved_at_ms, replacement_client_commit_id
8180                         ) VALUES (?1, 'rejected', ?2, ?3, 'superseded', ?2, ?4)",
8181                        rusqlite::params![
8182                            client_commit_id,
8183                            self.clock_now_ms(),
8184                            results_json,
8185                            replacement
8186                        ],
8187                    )
8188                })
8189                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8190            self.prune_commit_outcomes()?;
8191            for op in original.ops.iter().chain(&commit.ops) {
8192                self.overlay_dirty.table(&op.table);
8193                batch.table(&op.table);
8194            }
8195            self.outbox[index] = Arc::new(commit);
8196            batch.status = true;
8197            batch.outcomes = true;
8198            self.rebuild_overlay_if_dirty()?;
8199            self.finish_observation("syncular_pending_replacement", batch)
8200        })();
8201        if let Err(error) = replaced {
8202            self.rollback_observation("syncular_pending_replacement");
8203            self.restore(rollback);
8204            return Err(error.into());
8205        }
8206        Ok(())
8207    }
8208
8209    /// Internal host step at the start of an idle drive (§7.2.2): capture
8210    /// every pending decision with the units and epochs of this drive.
8211    #[doc(hidden)]
8212    pub fn prepare_replacements(&self) -> Result<Vec<CurrentBasePreparation>, String> {
8213        let mut stmt = self
8214            .conn
8215            .prepare_cached(
8216                "SELECT client_commit_id, seq, replacement_client_commit_id
8217                   FROM _syncular_commit_outcomes
8218                  WHERE resolution = 'active' AND replacement_client_commit_id IS NOT NULL
8219                  ORDER BY seq ASC",
8220            )
8221            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8222        let decisions = stmt
8223            .query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
8224            .and_then(|rows| rows.collect::<Result<Vec<(String, i64, String)>, _>>())
8225            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8226        if decisions.is_empty() {
8227            return Ok(Vec::new());
8228        }
8229        let units = self.stored(load_units(&self.conn))?;
8230        Ok(decisions
8231            .into_iter()
8232            .map(
8233                |(client_commit_id, sequence, replacement)| CurrentBasePreparation {
8234                    client_commit_id,
8235                    sequence,
8236                    replacement: Some(replacement),
8237                    units: units.clone(),
8238                    transport_epoch: self.transport_epoch,
8239                    registration_epoch: self.registration_epoch,
8240                    security_epoch: self.security_epoch,
8241                },
8242            )
8243            .collect())
8244    }
8245
8246    /// Internal host step when an idle drive reaches idle (§7.2.2): write,
8247    /// refuse, or keep each decision captured at the drive's start. Returns
8248    /// whether a decision was written, so the drive runs another round.
8249    #[doc(hidden)]
8250    pub fn settle_replacements(
8251        &mut self,
8252        decisions: &[CurrentBasePreparation],
8253        drive: &SyncOutcome,
8254    ) -> Result<bool, String> {
8255        if self.transport_closed() {
8256            return Ok(false);
8257        }
8258        let mut written = false;
8259        for decision in decisions {
8260            // A registration change during the drive says nothing about the
8261            // base; the decision waits for the next drive.
8262            if decision.registration_epoch != self.registration_epoch {
8263                continue;
8264            }
8265            let Some(replacement) = decision.replacement.as_deref() else {
8266                continue;
8267            };
8268            let Some(current) =
8269                self.commit_outcome(&decision.client_commit_id)?
8270                    .filter(|current| {
8271                        current.resolution == CommitOutcomeResolution::Active
8272                            && current.replacement_client_commit_id.as_deref() == Some(replacement)
8273                    })
8274            else {
8275                continue;
8276            };
8277            let held = self
8278                .outbox
8279                .iter()
8280                .find(|commit| commit.client_commit_id == replacement)
8281                .cloned();
8282            let refused = match &held {
8283                // A revocation drop (§3.3) or a crash already ended the
8284                // replacement; its own journal entry records what happened.
8285                None => None,
8286                Some(commit) => match self.finish_current_base(decision.clone(), drive.clone()) {
8287                    CurrentBaseProof {
8288                        rows: Some(rows), ..
8289                    } => {
8290                        let proven = commit.ops.iter().all(|op| {
8291                            rows.iter()
8292                                .find(|row| row.table == op.table && row.row_id == op.row_id)
8293                                .is_none_or(|row| {
8294                                    op.base_version == Some(row.server_version.unwrap_or(0))
8295                                })
8296                        });
8297                        written |= proven;
8298                        (!proven).then(|| "base_moved".to_owned())
8299                    }
8300                    CurrentBaseProof {
8301                        reason:
8302                            Some(
8303                                reason @ (CurrentBaseProofReason::SchemaFloor
8304                                | CurrentBaseProofReason::MissingCoverage
8305                                | CurrentBaseProofReason::Revoked
8306                                | CurrentBaseProofReason::OutcomeUnavailable),
8307                            ),
8308                        ..
8309                    } => Some(
8310                        serde_json::to_value(reason)
8311                            .ok()
8312                            .and_then(|reason| reason.as_str().map(str::to_owned))
8313                            .ok_or("sync.local_corrupt")?,
8314                    ),
8315                    _ => continue,
8316                },
8317            };
8318            // One transaction: the original outcome is superseded first, so
8319            // the refused replacement retains its intent over the restored
8320            // server base.
8321            let rollback = self.capture();
8322            self.begin_observation("syncular_replacement")?;
8323            let mut batch = ChangeAccumulator::default();
8324            let result = self
8325                .release_outcome(
8326                    &current,
8327                    CommitOutcomeResolution::Superseded,
8328                    Some(replacement),
8329                    &mut batch,
8330                )
8331                .and_then(|()| self.rebuild_overlay_if_dirty())
8332                .and_then(|()| match (refused, held) {
8333                    (Some(reason), Some(commit)) => self.reject_outbox_commits(
8334                        vec![(
8335                            commit,
8336                            "the replacement could not be written on a proven base".to_owned(),
8337                            REPLACEMENT_REFUSED_CODE,
8338                            Some(RejectionDetails {
8339                                field_paths: None,
8340                                reason: Some(reason),
8341                                required_action: None,
8342                                references: None,
8343                            }),
8344                        )],
8345                        Some(&mut batch),
8346                    ),
8347                    _ => Ok(()),
8348                })
8349                .and_then(|()| self.finish_observation("syncular_replacement", batch));
8350            if let Err(error) = result {
8351                self.rollback_observation("syncular_replacement");
8352                self.restore(rollback);
8353                return Err(error);
8354            }
8355        }
8356        if written {
8357            self.set_sync_needed(true, true);
8358        }
8359        Ok(written)
8360    }
8361
8362    /// §7.2.1 explicit resolution inside the caller's observation: record the
8363    /// resolution, release the retained aggregate and mark its tables for the
8364    /// overlay rebuild, which restores the server base and replays what
8365    /// remains over it.
8366    fn release_outcome(
8367        &mut self,
8368        current: &CommitOutcome,
8369        resolution: CommitOutcomeResolution,
8370        replacement: Option<&str>,
8371        batch: &mut ChangeAccumulator,
8372    ) -> Result<(), String> {
8373        self.conn
8374            .execute(
8375                "UPDATE _syncular_commit_outcomes
8376                    SET resolution = ?1, resolved_at_ms = ?2,
8377                        replacement_client_commit_id = ?3
8378                  WHERE client_commit_id = ?4 AND resolution = 'active'",
8379                rusqlite::params![
8380                    Self::outcome_resolution_name(resolution),
8381                    self.clock_now_ms(),
8382                    replacement,
8383                    current.client_commit_id
8384                ],
8385            )
8386            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8387        self.conn
8388            .execute(
8389                "DELETE FROM _syncular_failed_commits WHERE client_commit_id = ?1",
8390                rusqlite::params![current.client_commit_id],
8391            )
8392            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8393        for (commit, _) in self.failed_commits.iter() {
8394            if commit.client_commit_id == current.client_commit_id {
8395                for operation in &commit.ops {
8396                    self.overlay_dirty.table(&operation.table);
8397                }
8398            }
8399        }
8400        self.failed_commits
8401            .retain(|(commit, _)| commit.client_commit_id != current.client_commit_id);
8402        self.prune_commit_outcomes()?;
8403        self.conflicts
8404            .retain(|record| record.client_commit_id != current.client_commit_id);
8405        self.rejections
8406            .retain(|record| record.client_commit_id != current.client_commit_id);
8407        batch.conflicts |= current.status == CommitOutcomeStatus::Conflict;
8408        batch.rejections |= current.status == CommitOutcomeStatus::Rejected;
8409        batch.outcomes = true;
8410        for operation in current.operations.iter().flatten() {
8411            batch.table(&operation.table);
8412        }
8413        Ok(())
8414    }
8415
8416    pub fn schema_floor(&self) -> Option<&SchemaFloor> {
8417        self.schema_floor.as_ref()
8418    }
8419
8420    /// §7.3.5: the client's opaque auth-lease state, if any.
8421    pub fn lease_state(&self) -> Option<&LeaseState> {
8422        self.lease_state.as_ref()
8423    }
8424
8425    /// §7.3.5: record a request-level lease error (stop-and-surface). Only
8426    /// the two lease codes set it; other errors leave leaseState untouched.
8427    fn record_lease_error(&mut self, code: &str) -> Result<(), String> {
8428        if code != "sync.auth_lease_required" && code != "sync.auth_lease_revoked" {
8429            return Ok(());
8430        }
8431        let mut next = self.lease_state.clone().unwrap_or_default();
8432        next.error_code = Some(code.to_owned());
8433        self.set_lease_state(Some(next))
8434    }
8435
8436    fn set_lease_state(&mut self, next: Option<LeaseState>) -> Result<(), String> {
8437        if self.lease_state == next {
8438            return Ok(());
8439        }
8440        self.begin_observation("syncular_lease")?;
8441        let rollback = self.capture();
8442        self.lease_state = next;
8443        let persisted = match &self.lease_state {
8444            Some(lease) => serde_json::to_string(lease)
8445                .map_err(|error| error.to_string())
8446                .and_then(|json| self.set_meta(LEASE_STATE_KEY, &json)),
8447            None => self.delete_meta(LEASE_STATE_KEY),
8448        };
8449        let batch = ChangeAccumulator {
8450            status: true,
8451            ..ChangeAccumulator::default()
8452        };
8453        if let Err(error) =
8454            persisted.and_then(|()| self.finish_observation("syncular_lease", batch))
8455        {
8456            self.rollback_observation("syncular_lease");
8457            self.restore(rollback);
8458            return Err(error);
8459        }
8460        Ok(())
8461    }
8462
8463    fn set_schema_floor(&mut self, next: Option<SchemaFloor>) -> Result<(), String> {
8464        if self.schema_floor == next {
8465            return Ok(());
8466        }
8467        self.begin_observation("syncular_schema_floor")?;
8468        let rollback = self.capture();
8469        self.stopped = next.is_some();
8470        self.schema_floor = next;
8471        let persisted = match &self.schema_floor {
8472            Some(floor) => serde_json::to_string(floor)
8473                .map_err(|error| error.to_string())
8474                .and_then(|json| self.set_meta(SCHEMA_FLOOR_KEY, &json)),
8475            None => self.delete_meta(SCHEMA_FLOOR_KEY),
8476        };
8477        let batch = ChangeAccumulator {
8478            status: true,
8479            ..ChangeAccumulator::default()
8480        };
8481        if let Err(error) =
8482            persisted.and_then(|()| self.finish_observation("syncular_schema_floor", batch))
8483        {
8484            self.rollback_observation("syncular_schema_floor");
8485            self.restore(rollback);
8486            return Err(error);
8487        }
8488        Ok(())
8489    }
8490
8491    fn set_upgrading(&mut self, value: bool) {
8492        if self.upgrading == value {
8493            return;
8494        }
8495        if self.begin_observation("syncular_upgrading").is_err() {
8496            return;
8497        }
8498        self.upgrading = value;
8499        self.upgrade_kept_tables &= value;
8500        let batch = ChangeAccumulator {
8501            status: true,
8502            ..ChangeAccumulator::default()
8503        };
8504        if self
8505            .finish_observation("syncular_upgrading", batch)
8506            .is_err()
8507        {
8508            self.rollback_observation("syncular_upgrading");
8509        }
8510    }
8511
8512    pub fn sync_needed(&self) -> bool {
8513        self.sync_needed
8514    }
8515
8516    pub fn read_rows(&self, table: &str) -> Result<Vec<RowState>, String> {
8517        let schema_table = self
8518            .schema
8519            .table(table)
8520            .ok_or_else(|| format!("unknown table {table:?}"))?;
8521        let sql = format!(
8522            "SELECT * FROM {} ORDER BY {} ASC",
8523            visible_table(table),
8524            quote_ident(&schema_table.primary_key)
8525        );
8526        let mut stmt = self
8527            .conn
8528            .prepare(&sql)
8529            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8530        let mut rows = stmt
8531            .query([])
8532            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8533        let mut out = Vec::new();
8534        while let Some(row) = rows
8535            .next()
8536            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
8537        {
8538            let mut values = Map::new();
8539            for (i, column) in schema_table.columns.iter().enumerate() {
8540                let value = row
8541                    .get_ref(i)
8542                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8543                values.insert(column.name.clone(), sql_ref_to_json(column, value));
8544            }
8545            let version: i64 = row
8546                .get(schema_table.columns.len())
8547                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8548            let row_id = match values.get(&schema_table.primary_key) {
8549                Some(Value::String(s)) => s.clone(),
8550                Some(Value::Number(n)) => n.to_string(),
8551                Some(Value::Bool(b)) => b.to_string(),
8552                other => format!("{}", other.cloned().unwrap_or(Value::Null)),
8553            };
8554            let sealed_key = if schema_table.has_encrypted_columns() {
8555                row.get(schema_table.columns.len() + 1)
8556                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
8557            } else {
8558                None
8559            };
8560            out.push(RowState {
8561                row_id,
8562                version,
8563                values,
8564                sealed_key,
8565            });
8566        }
8567        Ok(out)
8568    }
8569
8570    // -- §5.10.5 native CRDT (the `crdt-yjs` feature) --------------------------
8571    //
8572    // The Rust face of the §5.10.4 client model: a local crdt edit loads the
8573    // current stored (server-merged ⊕ pending-overlay) column bytes, applies
8574    // the op with `yrs`, re-encodes the whole doc state, and records a
8575    // baseVersion-less sparse upsert carrying only the primary key and the
8576    // crdt column (§5.10.3, §6.6). No local merge — merging is server-side;
8577    // the overlay re-materializes the edit immediately (optimistic apply,
8578    // §7.1) and the server-merged bytes arrive on the next pull, idempotently.
8579    // Byte-compatible with `@syncular/crdt-yjs`.
8580
8581    /// The current stored value of a `crdt` column for one row — the visible
8582    /// (optimistic) bytes, or `None` when the row is absent or the column is
8583    /// NULL (the empty document, §5.10.1). Errors if the column is not a
8584    /// `crdt` column (guards the app against a typo'd column name).
8585    #[cfg(feature = "crdt-yjs")]
8586    fn crdt_column_bytes(
8587        &self,
8588        table: &str,
8589        row_id: &str,
8590        column: &str,
8591    ) -> Result<Option<Vec<u8>>, String> {
8592        let schema_table = self
8593            .schema
8594            .table(table)
8595            .ok_or_else(|| format!("unknown table {table:?}"))?;
8596        let col = schema_table
8597            .columns
8598            .iter()
8599            .find(|c| c.name == column)
8600            .ok_or_else(|| format!("table {table:?} has no column {column:?}"))?;
8601        if col.ty != ColumnType::Crdt {
8602            return Err(format!("column {column:?} is not a crdt column (§5.10.1)"));
8603        }
8604        let sql = format!(
8605            "SELECT {} FROM {} WHERE {}",
8606            quote_ident(column),
8607            visible_table(table),
8608            row_id_predicate(schema_table)
8609        );
8610        let bytes: Option<Vec<u8>> = self
8611            .conn
8612            .prepare_cached(&sql)
8613            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
8614            .query_row(rusqlite::params![row_id], |row| {
8615                row.get::<_, Option<Vec<u8>>>(0)
8616            })
8617            .map_err(|e| match e {
8618                rusqlite::Error::QueryReturnedNoRows => "no such row".to_owned(),
8619                other => Self::sqlite_failure(&self.storage_failure, other),
8620            })?;
8621        Ok(bytes)
8622    }
8623
8624    /// §5.10.4 materialize: the collaborative text of a `crdt` column, decoded
8625    /// from the stored bytes with `yrs` — `YjsColumn.text(name).toString()`.
8626    /// An absent row / NULL column is the empty document (empty string).
8627    #[cfg(feature = "crdt-yjs")]
8628    pub fn crdt_text(
8629        &self,
8630        table: &str,
8631        row_id: &str,
8632        column: &str,
8633        name: &str,
8634    ) -> Result<String, String> {
8635        let bytes = self
8636            .crdt_column_bytes(table, row_id, column)?
8637            .unwrap_or_default();
8638        crate::crdt::text(&bytes, name)
8639    }
8640
8641    /// §5.10.4 push-an-update: apply a text insert to a `crdt` column and
8642    /// record the resulting crdt-only sparse operation. Returns the enqueued
8643    /// `clientCommitId`.
8644    #[cfg(feature = "crdt-yjs")]
8645    pub fn crdt_insert_text(
8646        &mut self,
8647        table: &str,
8648        row_id: &str,
8649        column: &str,
8650        name: &str,
8651        index: u32,
8652        value: &str,
8653    ) -> Result<String, ClientError> {
8654        let prior = self.storage_failure.borrow_mut().take();
8655        let outcome = (|| -> Result<String, ClientError> {
8656            let current = self
8657                .crdt_column_bytes(table, row_id, column)?
8658                .unwrap_or_default();
8659            let update = crate::crdt::insert_text(&current, name, index, value)?;
8660            self.perform_crdt_push_update(table, row_id, column, &update)
8661        })();
8662        self.finish_authoring(prior, outcome)
8663    }
8664
8665    /// §5.10.4 push-an-update: apply a text delete to a `crdt` column and
8666    /// record the resulting crdt-only sparse operation. Returns the enqueued
8667    /// `clientCommitId`.
8668    #[cfg(feature = "crdt-yjs")]
8669    pub fn crdt_delete_text(
8670        &mut self,
8671        table: &str,
8672        row_id: &str,
8673        column: &str,
8674        name: &str,
8675        index: u32,
8676        len: u32,
8677    ) -> Result<String, ClientError> {
8678        let prior = self.storage_failure.borrow_mut().take();
8679        let outcome = (|| -> Result<String, ClientError> {
8680            let current = self
8681                .crdt_column_bytes(table, row_id, column)?
8682                .unwrap_or_default();
8683            let update = crate::crdt::delete_text(&current, name, index, len)?;
8684            self.perform_crdt_push_update(table, row_id, column, &update)
8685        })();
8686        self.finish_authoring(prior, outcome)
8687    }
8688
8689    /// §5.10.4 generic escape hatch: apply an arbitrary Yjs update onto a
8690    /// `crdt` column's current state and record the resulting crdt-only sparse
8691    /// operation. The app authored the update with its own `yrs` model.
8692    /// Returns the enqueued `clientCommitId`.
8693    #[cfg(feature = "crdt-yjs")]
8694    pub fn crdt_apply_update(
8695        &mut self,
8696        table: &str,
8697        row_id: &str,
8698        column: &str,
8699        update: &[u8],
8700    ) -> Result<String, ClientError> {
8701        let prior = self.storage_failure.borrow_mut().take();
8702        let outcome = (|| -> Result<String, ClientError> {
8703            let current = self
8704                .crdt_column_bytes(table, row_id, column)?
8705                .unwrap_or_default();
8706            let next = crate::crdt::apply_update(&current, update)?;
8707            self.perform_crdt_push_update(table, row_id, column, &next)
8708        })();
8709        self.finish_authoring(prior, outcome)
8710    }
8711
8712    /// Shared tail of the crdt edit methods: record a §6.1 sparse crdt-only
8713    /// upsert — the primary key plus the crdt column, no `baseVersion` — and
8714    /// enqueue it. The server merges the crdt column and leaves every other
8715    /// column untouched (§5.10.3), so a baseVersion-less crdt edit cannot
8716    /// clobber a concurrent edit to another column. A locally absent row
8717    /// records the same partial operation; the server answers per §6.2.
8718    #[cfg(feature = "crdt-yjs")]
8719    fn perform_crdt_push_update(
8720        &mut self,
8721        table: &str,
8722        row_id: &str,
8723        column: &str,
8724        crdt_bytes: &[u8],
8725    ) -> Result<String, ClientError> {
8726        let mut bytes_obj = Map::new();
8727        bytes_obj.insert("$bytes".to_owned(), Value::from(bytes_to_hex(crdt_bytes)));
8728        let mut partial = Map::new();
8729        partial.insert(column.to_owned(), Value::Object(bytes_obj));
8730        self.perform_patch(table, row_id, partial, None)
8731    }
8732
8733    /// Run an arbitrary read-only SQL query against the local database and
8734    /// return each row as a `column-name → JSON value` map. This is the seam
8735    /// the React `useSyncQuery` live-query API needs (it takes app-authored
8736    /// SQL over the visible tables/views, not a fixed table read like
8737    /// [`read_rows`]).
8738    ///
8739    /// Bound `params` are the driver value forms: JSON strings/numbers/bools/
8740    /// null bind directly; a `{"$bytes": hex}` object binds as a BLOB — the
8741    /// same envelope the command surface uses everywhere else. Output BLOB
8742    /// columns come back as `{"$bytes": hex}` to round-trip cleanly.
8743    ///
8744    /// The result column typing is dynamic (SQLite's stored affinity), because
8745    /// arbitrary SQL can alias, join, and compute — there is no schema column
8746    /// to consult per output cell, unlike [`read_rows`].
8747    pub fn query(&self, sql: &str, params: &[QueryValue]) -> Result<Vec<QueryRow>, String> {
8748        query_connection(&self.conn, sql, params).map_err(|failure| failure.to_string())
8749    }
8750
8751    /// Repository benchmark and conformance access, present only with `bench-internals`.
8752    #[cfg(feature = "bench-internals")]
8753    #[doc(hidden)]
8754    pub fn benchmark_connection(&mut self) -> &mut Connection {
8755        &mut self.conn
8756    }
8757
8758    /// Private benchmark intervals; absent from ordinary builds and diagnostics.
8759    #[cfg(feature = "bench-internals")]
8760    #[doc(hidden)]
8761    pub fn benchmark_phases(
8762        &self,
8763        enabled: Option<bool>,
8764        reset: bool,
8765    ) -> Result<Option<Value>, String> {
8766        self.benchmark_phases.configure(enabled, reset)?;
8767        Ok(self.benchmark_phases.snapshot())
8768    }
8769
8770    /// §5.11 native ceiling: refuse a declared authority query whose authored
8771    /// statement reads a table or column outside `ceiling` (table to permitted
8772    /// columns) or performs an action other than SELECT, READ, or a
8773    /// deterministic core function. The refusal is
8774    /// `client.authority_read_forbidden` with `{ query, reason: "ceiling",
8775    /// table, column }`.
8776    pub fn check_authority_ceiling(
8777        &mut self,
8778        ceiling: &BTreeMap<String, Vec<String>>,
8779    ) -> Result<(), ClientError> {
8780        for query in &self.limits.authority_reads {
8781            for (table, columns) in authority_read_set(&mut self.conn, query)? {
8782                let Some(allowed) = ceiling.get(&table) else {
8783                    return Err(authority_refusal(
8784                        &query.name,
8785                        "ceiling",
8786                        Some(table.as_str()),
8787                        None,
8788                    ));
8789                };
8790                if let Some(column) = columns
8791                    .iter()
8792                    .find(|column| !column.is_empty() && !allowed.contains(column))
8793                {
8794                    return Err(authority_refusal(
8795                        &query.name,
8796                        "ceiling",
8797                        Some(table.as_str()),
8798                        Some(column.as_str()),
8799                    ));
8800                }
8801            }
8802        }
8803        Ok(())
8804    }
8805
8806    /// §5.11: run declared authority queries over the accepted base in one
8807    /// SQLite read transaction. Each request is a query name and its params
8808    /// keyed by param name; each result carries its rows, its coverage per
8809    /// table and unit, whether every entry is complete, and every row of a
8810    /// read table with intent. A query reading an encrypted, `bytes` or
8811    /// `_sync_sealed_key` column fails with
8812    /// `client.security_preflight_required` while a preflight is pending.
8813    pub fn authority_read(
8814        &self,
8815        requests: &[(String, Map<String, Value>)],
8816    ) -> Result<AuthorityReadResult, ClientError> {
8817        if self.limits.authority_reads.is_empty() {
8818            return Err(authority_forbidden(None));
8819        }
8820        // Every request resolves and types its params before the read opens.
8821        let mut prepared = Vec::with_capacity(requests.len());
8822        for (name, params) in requests {
8823            let query = self
8824                .limits
8825                .authority_reads
8826                .iter()
8827                .find(|query| &query.name == name)
8828                .ok_or_else(|| ClientError {
8829                    code: "client.authority_query_unknown".to_owned(),
8830                    message: "authority query is not declared".to_owned(),
8831                    details: Some(json!({ "query": name })),
8832                    retryable: false,
8833                })?;
8834            let invalid = |param: &str| ClientError {
8835                code: "sync.invalid_request".to_owned(),
8836                message: "authority query parameter is missing, extra or mistyped".to_owned(),
8837                details: Some(json!({ "query": name, "param": param })),
8838                retryable: false,
8839            };
8840            if let Some(extra) = params
8841                .keys()
8842                .find(|key| !query.params.iter().any(|param| &param.name == *key))
8843            {
8844                return Err(invalid(extra.as_str()));
8845            }
8846            let mut bound = BTreeMap::new();
8847            for param in &query.params {
8848                let value = params
8849                    .get(&param.name)
8850                    .ok_or_else(|| invalid(param.name.as_str()))?;
8851                let sql = match (param.ty.as_str(), value) {
8852                    (_, Value::Null) if param.nullable => Value::Null,
8853                    ("string", Value::String(_)) | ("float", Value::Number(_)) => value.clone(),
8854                    ("integer", Value::Number(number))
8855                        if number
8856                            .as_i64()
8857                            .is_some_and(|n| n.unsigned_abs() <= MAX_JS_SAFE_INTEGER) =>
8858                    {
8859                        value.clone()
8860                    }
8861                    ("boolean", Value::Bool(flag)) => Value::from(i64::from(*flag)),
8862                    ("json", Value::String(text))
8863                        if serde_json::from_str::<Value>(text).is_ok() =>
8864                    {
8865                        value.clone()
8866                    }
8867                    _ => return Err(invalid(param.name.as_str())),
8868                };
8869                bound.insert(param.name.as_str(), sql);
8870            }
8871            // A coverage param names a unit value: a string or an integer.
8872            let scalar = |param: &str| match params.get(param) {
8873                Some(Value::String(text)) => Ok(text.clone()),
8874                Some(Value::Number(number))
8875                    if number
8876                        .as_i64()
8877                        .is_some_and(|n| n.unsigned_abs() <= MAX_JS_SAFE_INTEGER) =>
8878                {
8879                    Ok(number.to_string())
8880                }
8881                _ => Err(invalid(param)),
8882            };
8883            let mut coverage = Vec::new();
8884            for entry in &query.coverage {
8885                let base = WindowBase {
8886                    variable: entry.variable.clone(),
8887                    fixed_scopes: entry
8888                        .fixed_scopes
8889                        .iter()
8890                        .map(
8891                            |(variable, param)| -> Result<(String, String), ClientError> {
8892                                Ok((variable.clone(), scalar(param.as_str())?))
8893                            },
8894                        )
8895                        .collect::<Result<UnitScopes, ClientError>>()?,
8896                };
8897                for unit in &entry.units {
8898                    coverage.push((entry.table.as_str(), base.clone(), scalar(unit.as_str())?));
8899                }
8900            }
8901            prepared.push((query, bound, coverage));
8902        }
8903        self.conn
8904            .execute_batch("SAVEPOINT syncular_authority_read")
8905            .map_err(authority_stored)?;
8906        let result = (|| -> Result<AuthorityReadResult, ClientError> {
8907            let revision = meta_get(&self.conn, LOCAL_REVISION_KEY)
8908                .map_err(authority_stored)?
8909                .filter(|revision| {
8910                    revision
8911                        .parse::<u64>()
8912                        .is_ok_and(|parsed| &parsed.to_string() == revision)
8913                })
8914                .ok_or_else(authority_corrupt)?;
8915            if self.security_preflight {
8916                let protected = |(name, columns): (&String, &Vec<String>)| {
8917                    let table = self.schema.table(name).expect("validated authority table");
8918                    columns.iter().any(|column| {
8919                        column == "_sync_sealed_key"
8920                            || table.columns.iter().enumerate().any(|(index, held)| {
8921                                &held.name == column
8922                                    && (held.ty == ColumnType::Bytes
8923                                        || table.encrypted_columns.iter().any(|e| e.index == index))
8924                            })
8925                    })
8926                };
8927                if let Some((query, ..)) = prepared
8928                    .iter()
8929                    .find(|(query, ..)| query.reads.iter().any(protected))
8930                {
8931                    return Err(ClientError {
8932                        code: SECURITY_PREFLIGHT_REQUIRED_CODE.to_owned(),
8933                        message: "protected authority reads require activateSecurity".to_owned(),
8934                        details: Some(json!({ "query": query.name })),
8935                        retryable: false,
8936                    });
8937                }
8938            }
8939            let units = load_units(&self.conn).map_err(authority_stored)?;
8940            let mut results = Vec::with_capacity(prepared.len());
8941            for (query, bound, coverage) in &prepared {
8942                let (sql, mut params, intent) = self.authority_statement(query)?;
8943                params.extend(query.bind.iter().map(|name| bound[name.as_str()].clone()));
8944                let rows =
8945                    query_connection(&self.conn, &sql, &params).map_err(ClientError::from)?;
8946                let coverage = coverage
8947                    .iter()
8948                    .map(|(table, base, unit)| {
8949                        let mut json_base = json!({ "variable": base.variable });
8950                        if !base.fixed_scopes.is_empty() {
8951                            json_base["fixedScopes"] = json!(base.fixed_scopes);
8952                        }
8953                        AuthorityCoverageState {
8954                            table: (*table).to_owned(),
8955                            base: json_base,
8956                            unit: unit.clone(),
8957                            state: entry_coverage(
8958                                &units,
8959                                table,
8960                                self.schema.table(table),
8961                                base,
8962                                unit,
8963                            )
8964                            .0,
8965                        }
8966                    })
8967                    .collect::<Vec<_>>();
8968                results.push(AuthorityQueryResult {
8969                    query: query.name.clone(),
8970                    rows,
8971                    complete: coverage.iter().all(|entry| entry.state == "complete"),
8972                    coverage,
8973                    intent,
8974                });
8975            }
8976            Ok(AuthorityReadResult { revision, results })
8977        })();
8978        match result {
8979            Ok(read) => {
8980                self.conn
8981                    .execute_batch("RELEASE syncular_authority_read")
8982                    .map_err(authority_stored)?;
8983                Ok(read)
8984            }
8985            Err(error) => {
8986                self.conn
8987                    .execute_batch(
8988                        "ROLLBACK TO syncular_authority_read; RELEASE syncular_authority_read",
8989                    )
8990                    .map_err(authority_stored)?;
8991                Err(error)
8992            }
8993        }
8994    }
8995
8996    /// §5.11: the statement `authority_read` runs for `query`, its shadow
8997    /// params, which precede the authored binds, and the intent rows of its
8998    /// read tables, sorted by table and row id. Every read table with
8999    /// intent reads its accepted base through a common table expression of
9000    /// the same name; the text is identical in the TypeScript core. The Rust
9001    /// mirror keeps the accepted base in `_syncular_base_<table>`: retained,
9002    /// acknowledged and pending intent replay only onto the visible table, so
9003    /// the base row of an intent id is the earliest accepted state.
9004    fn authority_statement(
9005        &self,
9006        query: &AuthorityQuery,
9007    ) -> Result<(String, Vec<Value>, Vec<AuthorityIntent>), ClientError> {
9008        let mut shadows = Vec::new();
9009        let mut params = Vec::new();
9010        let mut intent = Vec::new();
9011        for (name, reads) in &query.reads {
9012            let table = self.schema.table(name).expect("validated authority table");
9013            // One kind per row by the base precedence: a retained entry, then
9014            // an acknowledged one, then pending outbox intent.
9015            let mut ids = Vec::new();
9016            let mut statement = self
9017                .conn
9018                .prepare_cached(
9019                    "SELECT id,min(k) FROM (\
9020                     SELECT json_extract(value,'$.table') AS tbl,json_extract(value,'$.rowId') AS id,2 AS k \
9021                     FROM _syncular_outbox,json_each(ops_json) \
9022                     UNION ALL SELECT json_extract(value,'$.table'),json_extract(value,'$.rowId'),0 \
9023                     FROM _syncular_failed_commits,json_each(operations_json) \
9024                     UNION ALL SELECT tbl,id,1 FROM _syncular_acked_rows) WHERE tbl=?1 GROUP BY id",
9025                )
9026                .map_err(authority_stored)?;
9027            let mut rows = statement.query([name]).map_err(authority_stored)?;
9028            while let Some(row) = rows.next().map_err(authority_stored)? {
9029                ids.push((
9030                    row.get::<_, String>(0).map_err(authority_stored)?,
9031                    row.get::<_, usize>(1).map_err(authority_stored)?,
9032                ));
9033            }
9034            if ids.is_empty() {
9035                continue;
9036            }
9037            ids.sort_by(|a, b| a.0.encode_utf16().cmp(b.0.encode_utf16()));
9038            intent.extend(ids.iter().map(|(row_id, kind)| AuthorityIntent {
9039                table: name.clone(),
9040                row_id: row_id.clone(),
9041                kind: ["retained", "acknowledged", "pending"][*kind],
9042            }));
9043            let ids: Vec<String> = ids.into_iter().map(|(id, _)| id).collect();
9044            let columns: Vec<&str> =
9045                std::iter::once(table.primary_key.as_str())
9046                    .chain(reads.iter().map(String::as_str).filter(|column| {
9047                        *column != table.primary_key && *column != "_sync_version"
9048                    }))
9049                    .chain(std::iter::once("_sync_version"))
9050                    .collect();
9051            let physical = columns
9052                .iter()
9053                .map(|column| {
9054                    if *column == "_sync_version" {
9055                        "_syncular_version".to_owned()
9056                    } else {
9057                        quote_ident(column)
9058                    }
9059                })
9060                .collect::<Vec<_>>()
9061                .join(",");
9062            let key = quote_ident(&table.primary_key);
9063            let mut statement = self
9064                .conn
9065                .prepare(&format!(
9066                    "SELECT CAST({key} AS TEXT),{physical} FROM {} \
9067                     WHERE CAST({key} AS TEXT) IN (SELECT value FROM json_each(?1))",
9068                    base_table(name),
9069                ))
9070                .map_err(authority_stored)?;
9071            let mut rows = statement
9072                .query([serde_json::to_string(&ids).expect("intent ids serialize")])
9073                .map_err(authority_stored)?;
9074            let mut bases = Vec::new();
9075            while let Some(row) = rows.next().map_err(authority_stored)? {
9076                let id = row.get::<_, String>(0).map_err(authority_stored)?;
9077                let mut values = Vec::with_capacity(columns.len());
9078                for index in 1..=columns.len() {
9079                    values.push(match row.get_ref(index).map_err(authority_stored)? {
9080                        ValueRef::Null => Value::Null,
9081                        ValueRef::Integer(integer) => Value::from(integer),
9082                        ValueRef::Real(real) => serde_json::Number::from_f64(real)
9083                            .map(Value::Number)
9084                            .ok_or_else(authority_corrupt)?,
9085                        ValueRef::Text(text) => {
9086                            Value::from(std::str::from_utf8(text).map_err(|_| authority_corrupt())?)
9087                        }
9088                        ValueRef::Blob(blob) => json!({ "$bytes": bytes_to_hex(blob) }),
9089                    });
9090                }
9091                let version = values
9092                    .last()
9093                    .and_then(Value::as_i64)
9094                    .ok_or_else(authority_corrupt)?;
9095                if version >= 0 {
9096                    bases.push((id, Value::Array(values)));
9097                }
9098            }
9099            bases.sort_by(|a, b| a.0.encode_utf16().cmp(b.0.encode_utf16()));
9100            let shadow = quote_ident(name);
9101            shadows.push(format!(
9102                "{shadow} AS (SELECT {} FROM main.{shadow} WHERE CAST({key} AS TEXT) NOT IN \
9103                 (SELECT value FROM json_each(?)) UNION ALL SELECT {} FROM json_each(?))",
9104                columns
9105                    .iter()
9106                    .map(|column| quote_ident(column))
9107                    .collect::<Vec<_>>()
9108                    .join(","),
9109                columns
9110                    .iter()
9111                    .enumerate()
9112                    .map(|(index, column)| {
9113                        if table
9114                            .columns
9115                            .iter()
9116                            .any(|held| held.name == *column && held.ty == ColumnType::Bytes)
9117                        {
9118                            format!("unhex(json_extract(value,'$[{index}].\"$bytes\"'))")
9119                        } else {
9120                            format!("json_extract(value,'$[{index}]')")
9121                        }
9122                    })
9123                    .collect::<Vec<_>>()
9124                    .join(","),
9125            ));
9126            params.push(Value::from(
9127                serde_json::to_string(&ids).expect("intent ids serialize"),
9128            ));
9129            params.push(Value::from(
9130                Value::from_iter(bases.into_iter().map(|(_, row)| row)).to_string(),
9131            ));
9132        }
9133        let sql = if shadows.is_empty() {
9134            query.sql.clone()
9135        } else {
9136            let keyword = |text: &str, word: &str| {
9137                text.get(..word.len())
9138                    .is_some_and(|head| head.eq_ignore_ascii_case(word))
9139                    && text[word.len()..].starts_with(char::is_whitespace)
9140            };
9141            let shadows = shadows.join(",");
9142            let authored = query.sql.trim_start();
9143            if keyword(authored, "WITH") {
9144                let rest = authored[4..].trim_start();
9145                if keyword(rest, "RECURSIVE") {
9146                    format!("WITH RECURSIVE {shadows}, {}", rest[9..].trim_start())
9147                } else {
9148                    format!("WITH {shadows}, {rest}")
9149                }
9150            } else {
9151                format!("WITH {shadows} {}", query.sql)
9152            }
9153        };
9154        Ok((sql, params, intent))
9155    }
9156
9157    /// Rows, coverage, and local revision from one SQLite read snapshot.
9158    /// §7.5 atomic snapshot read. An `owner` records a failure in
9159    /// `diagnostics_snapshot().query_failures` until its next successful read.
9160    pub fn query_snapshot(
9161        &mut self,
9162        sql: &str,
9163        params: &[QueryValue],
9164        coverage: &[WindowCoverage],
9165        owner: Option<QueryOwner<'_>>,
9166    ) -> Result<QuerySnapshot, String> {
9167        let result = snapshot_connection(&self.conn, Some(&self.schema), sql, params, coverage);
9168        if let Some(owner) = owner {
9169            self.record_query_read(owner, result.as_ref().err());
9170        }
9171        result.map_err(|failure| failure.to_string())
9172    }
9173
9174    /// §7.6: record the outcome of one owned snapshot read, including reads a
9175    /// host ran on a separate connection. A success removes the owner's entry;
9176    /// an identical failure leaves it unchanged; a changed failure moves last.
9177    pub fn record_query_read(&mut self, owner: QueryOwner<'_>, failure: Option<&QueryReadFailure>) {
9178        let position = self
9179            .query_failures
9180            .iter()
9181            .position(|entry| entry.id == owner.id);
9182        let Some(failure) = failure else {
9183            if let Some(index) = position {
9184                self.query_failures.remove(index);
9185            }
9186            return;
9187        };
9188        let tables: Vec<String> = BTreeSet::from_iter(owner.tables.iter().copied())
9189            .into_iter()
9190            .map(str::to_owned)
9191            .collect();
9192        let code = failure.code.unwrap_or("client.query_failed").to_owned();
9193        if position.is_some_and(|index| {
9194            let entry = &self.query_failures[index];
9195            entry.tables == tables && entry.code == code && entry.sqlite_code == failure.sqlite_code
9196        }) {
9197            return;
9198        }
9199        if let Some(index) = position {
9200            self.query_failures.remove(index);
9201        }
9202        self.query_failures.push(DiagnosticQueryFailure {
9203            id: owner.id.to_owned(),
9204            tables,
9205            code,
9206            sqlite_code: failure.sqlite_code,
9207            at_ms: self.clock_now_ms(),
9208        });
9209        if self.query_failures.len() > MAX_DIAGNOSTIC_QUERY_FAILURES {
9210            self.query_failures.remove(0);
9211        }
9212    }
9213
9214    // -- request building ---------------------------------------------------------
9215
9216    fn build_request(&self, url_capable: bool) -> Result<(Message, RequestMeta), Box<SyncOutcome>> {
9217        #[cfg(feature = "bench-internals")]
9218        let _phase = self.benchmark_phases.start(Phase::RequestPrepare);
9219        let log_epoch = self.get_meta(LOG_EPOCH_KEY).map_err(|message| {
9220            Box::new(SyncOutcome::Failed {
9221                error_code: "storage.failed".into(),
9222                message,
9223                details: None,
9224                recommended_action: None,
9225            })
9226        })?;
9227        let max_commits = self.limits.max_push_commits_per_request;
9228        let max_ops = self
9229            .limits
9230            .max_push_operations_per_request
9231            .unwrap_or(PUSH_OPS_PER_REQUEST);
9232        let byte_cap = self.limits.max_push_request_bytes;
9233        // §4.2/§5.4: bit 3 is advertised iff the transport can fetch a
9234        // bare URL — capability negotiation, decided per transport.
9235        let accept = self.limits.accept.unwrap_or(if url_capable {
9236            DEFAULT_ACCEPT | ACCEPT_SIGNED_URLS
9237        } else {
9238            DEFAULT_ACCEPT
9239        });
9240        let storage_failed = |message: String| {
9241            Box::new(SyncOutcome::Failed {
9242                error_code: "storage.failed".into(),
9243                message,
9244                details: None,
9245                recommended_action: None,
9246            })
9247        };
9248        let header = Frame::ReqHeader {
9249            client_id: self.client_id.clone(),
9250            schema_version: self.schema.version,
9251            log_epoch: log_epoch.clone(),
9252            outbox_id: self.get_meta(OUTBOX_ID_KEY).map_err(storage_failed)?,
9253        };
9254        // §1.5: the lead frames are REQ_HEADER plus the optional ROUND_FAILURE,
9255        // which stays ahead of every push, pull, unit and progress frame; the
9256        // byte-capacity probes below measure this exact sequence.
9257        let mut lead = vec![header];
9258        lead.extend(
9259            self.round_failure
9260                .iter()
9261                .map(|code| Frame::RoundFailure { code: code.clone() }),
9262        );
9263        // §2.1: a replica without an epoch holds nothing bound to one.
9264        if log_epoch.is_none() {
9265            lead.push(Frame::AdoptEpoch);
9266        }
9267        let registered: Vec<UnitRecord> = self
9268            .stored(load_units(&self.conn))
9269            .map_err(storage_failed)?
9270            .into_iter()
9271            .filter(|unit| unit.status == UnitStatus::Active)
9272            .collect();
9273        let registration_digest = ssp2::registration::registration_digest(
9274            registered
9275                .iter()
9276                .map(|unit| scope_pairs(&unit.scopes))
9277                .collect::<Vec<_>>()
9278                .iter()
9279                .map(Vec::as_slice),
9280        );
9281        let echo_digest = self
9282            .get_meta(ECHO_DIGEST_KEY)
9283            .map_err(storage_failed)?
9284            .filter(|hex| !hex.is_empty())
9285            .map(|hex| {
9286                crate::values::hex_to_bytes(&hex)
9287                    .ok()
9288                    .and_then(|bytes| <[u8; 32]>::try_from(bytes).ok())
9289                    .ok_or_else(|| {
9290                        "sync.local_corrupt: persisted echo digest is invalid".to_owned()
9291                    })
9292            })
9293            .transpose()
9294            .map_err(storage_failed)?;
9295        let pull = Frame::PullHeader {
9296            limit_commits: self.limits.limit_commits.unwrap_or(0),
9297            limit_snapshot_rows: self.limits.limit_snapshot_rows.unwrap_or(0),
9298            max_snapshot_pages: self.limits.max_snapshot_pages.unwrap_or(0),
9299            accept,
9300            cursor: self
9301                .stored(replica_cursor(&self.conn))
9302                .map_err(storage_failed)?,
9303            registration_digest,
9304            echo_digest,
9305        };
9306        let registration_digest = bytes_to_hex(&registration_digest);
9307        // §4.1: the list travels when it changed since the server stored it,
9308        // after `unregistered` and after a reset (both clear the stored digest).
9309        let travels = self
9310            .get_meta(REGISTERED_DIGEST_KEY)
9311            .map_err(storage_failed)?
9312            .as_deref()
9313            != Some(registration_digest.as_str());
9314        let mut sub_frames: Vec<Frame> = Vec::new();
9315        if travels {
9316            sub_frames.extend(registered.iter().map(|unit| Frame::Unit {
9317                scopes: scope_pairs(&unit.scopes),
9318            }));
9319        }
9320        // §4.3: one PROGRESS per catching-up unit, in registration order, each
9321        // followed by its RESTRICT while the unit holds a restriction.
9322        for unit in &registered {
9323            let Some(cursor) = unit.cursor else {
9324                continue;
9325            };
9326            sub_frames.push(Frame::Progress {
9327                id: unit.id.clone(),
9328                cursor,
9329                bootstrap_state: unit.bootstrap_state.clone().map(RawJson),
9330            });
9331            sub_frames.extend(
9332                unit.restriction
9333                    .as_ref()
9334                    .map(|restriction| Frame::Restrict {
9335                        cursor: restriction.cursor,
9336                        tables: restriction.tables.clone(),
9337                    }),
9338            );
9339        }
9340        // The fixed frames (order-independent size) and the header+pull probe
9341        // both encode canonically, so the byte budget is the exact wire size.
9342        let fixed_bytes = match byte_cap {
9343            Some(_) => {
9344                let mut frames = lead.clone();
9345                frames.push(pull.clone());
9346                frames.extend(sub_frames.iter().cloned());
9347                encode_message(&Message {
9348                    wire_version: WIRE_VERSION,
9349                    msg_kind: MsgKind::Request,
9350                    frames,
9351                })
9352                .len()
9353            }
9354            None => 0,
9355        };
9356        if let Some(cap) = byte_cap {
9357            if fixed_bytes > cap {
9358                return Err(Self::push_capacity_outcome("bytes", cap, fixed_bytes, None));
9359            }
9360        }
9361        let base_bytes = match byte_cap {
9362            Some(_) => {
9363                let mut frames = lead.clone();
9364                frames.push(pull.clone());
9365                encode_message(&Message {
9366                    wire_version: WIRE_VERSION,
9367                    msg_kind: MsgKind::Request,
9368                    frames,
9369                })
9370                .len()
9371            }
9372            None => 0,
9373        };
9374        // §8.8: a `pull` round carries no commit and defers none; a `through`
9375        // round pushes and defers only its prefix.
9376        let pushable = self.pushable_commits();
9377        let total_outbox = if log_epoch.is_some() { pushable } else { 0 };
9378        let mut push_frames: Vec<Frame> = Vec::new();
9379        let mut pushed_ids = Vec::new();
9380        let mut ops_in_request = 0usize;
9381        let mut bytes_in_request = 0usize;
9382        // §2.1: an epoch-less request withholds the whole outbox until the
9383        // next, epoch-bound request.
9384        let mut deferred_commits = pushable - total_outbox;
9385        // §7.2.2: a pending replacement is held; the push stops before it
9386        // without deferring work.
9387        let held: HashSet<String> = self
9388            .prepare_replacements()
9389            .map_err(storage_failed)?
9390            .into_iter()
9391            .filter_map(|decision| decision.replacement)
9392            .collect();
9393        #[cfg(feature = "bench-internals")]
9394        let outbox_phase = self.benchmark_phases.start(Phase::OutboxEncode);
9395        for (index, commit) in self.outbox.iter().take(total_outbox).enumerate() {
9396            if held.contains(&commit.client_commit_id) {
9397                break;
9398            }
9399            // §6.1/§7.1: the commit-count and operation caps are hard. A
9400            // first commit over the operation cap is a typed capacity error
9401            // and stays queued; a later one defers with the complete suffix.
9402            if max_commits.is_some_and(|cap| push_frames.len() >= cap) {
9403                deferred_commits = total_outbox - index;
9404                break;
9405            }
9406            if ops_in_request + commit.ops.len() > max_ops {
9407                if push_frames.is_empty() {
9408                    return Err(Self::push_capacity_outcome(
9409                        "operations",
9410                        max_ops,
9411                        commit.ops.len(),
9412                        Some(commit.client_commit_id.as_str()),
9413                    ));
9414                }
9415                deferred_commits = total_outbox - index;
9416                break;
9417            }
9418            // §7.1 chained base: the commit waits for the change of the commit
9419            // it chains on, which supplies its rebased version.
9420            if self.outbox[..index]
9421                .iter()
9422                .flat_map(|earlier| &earlier.ops)
9423                .any(|earlier| commit.ops.iter().any(|op| chains_on(earlier, op)))
9424            {
9425                deferred_commits = total_outbox - index;
9426                break;
9427            }
9428            let operations = commit
9429                .ops
9430                .iter()
9431                .map(|op| {
9432                    let payload = match self
9433                        .schema
9434                        .table(&op.table)
9435                        .and_then(|table| Some((table, op.presented_values(table)?)))
9436                    {
9437                        Some((table, values)) => {
9438                            // §0: outbox entries encode at send time with the
9439                            // current codec (validated at mutate()). §6.1: the
9440                            // values map's keys are the sparse presence set; an
9441                            // insert-intent operation presents every column (§7.1).
9442                            // §5.11: encrypted columns are encrypted here, with
9443                            // an absent key-id selector read from the stored row.
9444                            // `sync_inner` runs `drop_unencodable_outbox` first,
9445                            // so an encrypt failure cannot reach this encode; the
9446                            // author seam validated every other failure.
9447                            let fallback =
9448                                self.stored_key_fallback(table, &op.row_id)
9449                                    .map_err(|message| {
9450                                        Box::new(SyncOutcome::Failed {
9451                                            error_code: "storage.failed".into(),
9452                                            message,
9453                                            details: None,
9454                                            recommended_action: None,
9455                                        })
9456                                    })?;
9457                            encode_sparse_row_json(
9458                                table,
9459                                &op.row_id,
9460                                &values,
9461                                &self.encryption,
9462                                fallback.as_ref(),
9463                            )
9464                            .ok()
9465                        }
9466                        None => None,
9467                    };
9468                    Ok(ssp2::model::Operation {
9469                        table: op.table.clone(),
9470                        row_id: op.row_id.clone(),
9471                        op: if op.upsert { Op::Upsert } else { Op::Delete },
9472                        base_version: op.base_version,
9473                        payload,
9474                    })
9475                })
9476                .collect::<Result<Vec<_>, Box<SyncOutcome>>>()?;
9477            // §6.3.2, §7.1: the commit's outbox sequence.
9478            let client_seq = self
9479                .conn
9480                .prepare_cached("SELECT seq FROM _syncular_outbox WHERE commit_id = ?1")
9481                .and_then(|mut statement| {
9482                    statement.query_row([&commit.client_commit_id], |row| row.get(0))
9483                })
9484                .map_err(|error| {
9485                    storage_failed(Self::sqlite_failure(&self.storage_failure, error))
9486                })?;
9487            let frame = Frame::PushCommit {
9488                client_commit_id: commit.client_commit_id.clone(),
9489                client_seq,
9490                operations,
9491            };
9492            let frame_bytes = match byte_cap {
9493                Some(_) => {
9494                    let mut frames = lead.clone();
9495                    frames.push(frame.clone());
9496                    frames.push(pull.clone());
9497                    encode_message(&Message {
9498                        wire_version: WIRE_VERSION,
9499                        msg_kind: MsgKind::Request,
9500                        frames,
9501                    })
9502                    .len()
9503                        - base_bytes
9504                }
9505                None => 0,
9506            };
9507            // The head is always encoded so the caller can report the full
9508            // projected request size; a later commit defers once it no longer
9509            // fits.
9510            if let Some(cap) = byte_cap {
9511                if !push_frames.is_empty() && fixed_bytes + bytes_in_request + frame_bytes > cap {
9512                    deferred_commits = total_outbox - index;
9513                    break;
9514                }
9515            }
9516            push_frames.push(frame);
9517            pushed_ids.push(commit.client_commit_id.clone());
9518            ops_in_request += commit.ops.len();
9519            bytes_in_request += frame_bytes;
9520        }
9521        #[cfg(feature = "bench-internals")]
9522        drop(outbox_phase);
9523        if let Some(cap) = byte_cap {
9524            if fixed_bytes + bytes_in_request > cap {
9525                // The head alone does not fit this budget; the commit stays
9526                // queued and no transport round is attempted.
9527                let blocked = if push_frames.is_empty() {
9528                    None
9529                } else {
9530                    self.outbox.first().map(|c| c.client_commit_id.as_str())
9531                };
9532                return Err(Self::push_capacity_outcome(
9533                    "bytes",
9534                    cap,
9535                    fixed_bytes + bytes_in_request,
9536                    blocked,
9537                ));
9538            }
9539        }
9540        let mut frames = lead;
9541        frames.extend(push_frames);
9542        frames.push(pull);
9543        frames.extend(sub_frames);
9544        let message = Message {
9545            wire_version: WIRE_VERSION,
9546            msg_kind: MsgKind::Request,
9547            frames,
9548        };
9549        Ok((
9550            message,
9551            RequestMeta {
9552                pushed_ids,
9553                registration_digest,
9554                accept,
9555                deferred_commits,
9556                applied: BTreeMap::new(),
9557                deferred: BTreeSet::new(),
9558            },
9559        ))
9560    }
9561
9562    /// §7.1: a configured push capacity limit cannot carry this request.
9563    fn push_capacity_outcome(
9564        kind: &str,
9565        limit: usize,
9566        size: usize,
9567        client_commit_id: Option<&str>,
9568    ) -> Box<SyncOutcome> {
9569        let mut details = Map::new();
9570        details.insert("kind".to_owned(), Value::from(kind));
9571        details.insert("limit".to_owned(), Value::from(limit as u64));
9572        details.insert("size".to_owned(), Value::from(size as u64));
9573        if let Some(id) = client_commit_id {
9574            details.insert("clientCommitId".to_owned(), Value::from(id));
9575        }
9576        Box::new(SyncOutcome::Failed {
9577            error_code: "client.push_request_too_large".into(),
9578            message: "the push request exceeds a configured capacity limit".into(),
9579            details: Some(Value::Object(details)),
9580            recommended_action: None,
9581        })
9582    }
9583
9584    // -- sync -------------------------------------------------------------------
9585
9586    /// Cloneable observation handle; no client lock is needed to read it.
9587    pub fn progress(&self) -> ProgressObserver {
9588        self.progress.clone()
9589    }
9590
9591    pub fn sync(&mut self, transport: &mut dyn Transport) -> SyncOutcome {
9592        self.sync_bounded(transport, None)
9593    }
9594
9595    /// One round; `idle_bound` is the idle drive's round bound (§7.8).
9596    fn sync_bounded(
9597        &mut self,
9598        transport: &mut dyn Transport,
9599        idle_bound: Option<(u64, u32)>,
9600    ) -> SyncOutcome {
9601        let mut prepared = match self.prepare_sync_round(transport.supports_url_fetch()) {
9602            Ok(prepared) => prepared,
9603            Err(outcome) => return *outcome,
9604        };
9605        prepared.idle_bound = idle_bound;
9606        // The round's network deadline rides `PreparedSyncRound` and is scoped
9607        // to each exchange, so uploads, continuations, the main request, and
9608        // every segment fetch share one monotonic anchor without leaving
9609        // deadline state on a reused transport.
9610        let mut next = prepared;
9611        loop {
9612            match self.apply_sync_round(next.exchange(transport)) {
9613                crate::AppliedSyncRound::Continue(prepared) => next = prepared,
9614                crate::AppliedSyncRound::Complete {
9615                    outcome, controls, ..
9616                } => {
9617                    if !self.transport_closed() {
9618                        for text in controls {
9619                            let _ = transport.realtime_send(&text);
9620                        }
9621                    } else {
9622                        self.disconnect_realtime(transport);
9623                    }
9624                    return outcome;
9625                }
9626            }
9627        }
9628    }
9629
9630    fn finish_sync_round(
9631        &mut self,
9632        started_at_ms: i64,
9633        attempt: u64,
9634        mut outcome: SyncOutcome,
9635    ) -> SyncOutcome {
9636        if let SyncOutcome::Failed {
9637            error_code,
9638            message,
9639            details,
9640            ..
9641        } = &mut outcome
9642        {
9643            if let Some((failure, code)) = self
9644                .storage_failure
9645                .borrow()
9646                .as_ref()
9647                .and_then(|failure| failure.code.map(|code| (failure, code)))
9648            {
9649                *error_code = code.to_owned();
9650                *message = match code {
9651                    "client.storage_busy" => "local SQLite storage is busy",
9652                    "client.storage_full" => "local SQLite storage is full",
9653                    "client.storage_io" => "local SQLite storage I/O failed",
9654                    "client.storage_corrupt" => "local SQLite storage is corrupt",
9655                    _ => unreachable!("unrecognized classified storage failure"),
9656                }
9657                .to_owned();
9658                *details = failure.details();
9659            }
9660        }
9661        let details = match &outcome {
9662            SyncOutcome::Failed { details, .. } => details.as_ref(),
9663            _ => None,
9664        };
9665        let cause_kind = details
9666            .and_then(|details| details.get("causeKind"))
9667            .and_then(Value::as_str)
9668            .and_then(|cause| match cause {
9669                "network" => Some(crate::TransportCauseKind::Network),
9670                "connect" => Some(crate::TransportCauseKind::Connect),
9671                "tls" => Some(crate::TransportCauseKind::Tls),
9672                "io" => Some(crate::TransportCauseKind::Io),
9673                "request" => Some(crate::TransportCauseKind::Request),
9674                "protocol" => Some(crate::TransportCauseKind::Protocol),
9675                "timeout" => Some(crate::TransportCauseKind::Timeout),
9676                "round_deadline" => Some(crate::TransportCauseKind::RoundDeadline),
9677                "aborted" => Some(crate::TransportCauseKind::Aborted),
9678                "body" => Some(crate::TransportCauseKind::Body),
9679                "status" => Some(crate::TransportCauseKind::Status),
9680                "redirect" => Some(crate::TransportCauseKind::Redirect),
9681                "unknown" => Some(crate::TransportCauseKind::Unknown),
9682                _ => None,
9683            });
9684        let http_status = if matches!(
9685            cause_kind,
9686            Some(
9687                crate::TransportCauseKind::Status
9688                    | crate::TransportCauseKind::Body
9689                    | crate::TransportCauseKind::Redirect
9690            )
9691        ) {
9692            details
9693                .and_then(|details| details.get("httpStatus"))
9694                .and_then(Value::as_f64)
9695                .filter(|status| status.fract() == 0.0 && (100.0..=599.0).contains(status))
9696                .map(|status| status as u16)
9697        } else {
9698            None
9699        };
9700        let retry_delay_ms = self.round_retry_delay_ms;
9701        self.progress.update(|p| match &outcome {
9702            SyncOutcome::Ok(report) | SyncOutcome::BudgetExhausted(report)
9703                if report.failed.is_empty() =>
9704            {
9705                p.state = ProgressState::Complete
9706            }
9707            SyncOutcome::Ok(_) | SyncOutcome::BudgetExhausted(_) => {
9708                p.state = ProgressState::Failed;
9709                p.error_code = Some("sync.scope_revoked".into());
9710            }
9711            SyncOutcome::Failed { error_code, .. } => {
9712                p.state = ProgressState::Failed;
9713                p.error_code = Some(Self::diagnostic_code(error_code));
9714                p.cause_kind = cause_kind;
9715                p.http_status = http_status;
9716                p.retry_delay_ms = retry_delay_ms;
9717            }
9718            SyncOutcome::RealtimeUnavailable { .. } => {
9719                p.state = ProgressState::Failed;
9720                p.error_code = Some(REALTIME_UNAVAILABLE_CODE.to_owned());
9721                p.retry_delay_ms = retry_delay_ms;
9722            }
9723        });
9724        let completed_at_ms = self.clock_now_ms();
9725        self.last_round = Some(match &outcome {
9726            SyncOutcome::Ok(report) | SyncOutcome::BudgetExhausted(report) => DiagnosticLastRound {
9727                epoch: self.epoch.clone(),
9728                attempt,
9729                status: "succeeded".to_owned(),
9730                started_at_ms,
9731                completed_at_ms,
9732                duration_ms: completed_at_ms.saturating_sub(started_at_ms).max(0),
9733                counters: Some(DiagnosticRoundCounters {
9734                    pushed: report.pushed,
9735                    applied: report.applied.len(),
9736                    rejected: report.rejected.len(),
9737                    retryable: report.retryable.len(),
9738                    conflicts: report.conflicts,
9739                    commits_applied: report.commits_applied,
9740                    segment_rows_applied: report.segment_rows_applied,
9741                    bootstrapping: report.bootstrapping.len(),
9742                    resets: report.resets.len(),
9743                    revoked: report.revoked.len(),
9744                    failed: report.failed.len(),
9745                    deferred_commits: report.deferred_commits,
9746                }),
9747                error_code: None,
9748                cause_kind: None,
9749                http_status: None,
9750            },
9751            SyncOutcome::Failed { error_code, .. } => DiagnosticLastRound {
9752                epoch: self.epoch.clone(),
9753                attempt,
9754                status: "failed".to_owned(),
9755                started_at_ms,
9756                completed_at_ms,
9757                duration_ms: completed_at_ms.saturating_sub(started_at_ms).max(0),
9758                counters: None,
9759                error_code: Some(Self::diagnostic_code(error_code)),
9760                cause_kind,
9761                http_status,
9762            },
9763            SyncOutcome::RealtimeUnavailable { .. } => DiagnosticLastRound {
9764                epoch: self.epoch.clone(),
9765                attempt,
9766                status: "failed".to_owned(),
9767                started_at_ms,
9768                completed_at_ms,
9769                duration_ms: completed_at_ms.saturating_sub(started_at_ms).max(0),
9770                counters: None,
9771                error_code: Some(REALTIME_UNAVAILABLE_CODE.to_owned()),
9772                cause_kind: None,
9773                http_status: None,
9774            },
9775        });
9776        outcome
9777    }
9778
9779    /// Capture one request on the client owner. Mutations made after this
9780    /// call remain in the outbox for a later round; no network I/O occurs here.
9781    pub fn prepare_sync_round(
9782        &mut self,
9783        url_capable: bool,
9784    ) -> Result<crate::PreparedSyncRound, Box<SyncOutcome>> {
9785        if self.transport_closed() {
9786            return Err(Box::new(SyncOutcome::Failed {
9787                error_code: "sync.offline".into(),
9788                message: "transport gate is closed".into(),
9789                details: None,
9790                recommended_action: None,
9791            }));
9792        }
9793        if self.active_round.is_some() || self.fence_round.is_some() {
9794            return Err(Box::new(SyncOutcome::Failed {
9795                error_code: "client.round_in_progress".into(),
9796                message: "a sync round is already in flight".into(),
9797                details: None,
9798                recommended_action: None,
9799            }));
9800        }
9801        self.storage_failure.borrow_mut().take();
9802        let attempt = self.progress.start(&self.epoch);
9803        self.round_retry_delay_ms = None;
9804        let started_at_ms = self.clock_now_ms();
9805        let prepared = (|| {
9806            if self.stopped {
9807                return Err(Box::new(SyncOutcome::Ok(SyncReport {
9808                    schema_floor: self.schema_floor.clone(),
9809                    ..SyncReport::default()
9810                })));
9811            }
9812            if self.security_preflight {
9813                return Err(Box::new(SyncOutcome::Failed {
9814                    error_code: SECURITY_PREFLIGHT_REQUIRED_CODE.into(),
9815                    message: "security preflight must complete before syncing".into(),
9816                    details: None,
9817                    recommended_action: None,
9818                }));
9819            }
9820            self.set_sync_needed(false, false);
9821            self.drain_pending_evictions()
9822                .and_then(|_| self.drop_incompatible_outbox())
9823                .and_then(|_| self.drop_unencodable_outbox(true, None))
9824                .map_err(|message| {
9825                    Box::new(SyncOutcome::Failed {
9826                        error_code: "storage.failed".into(),
9827                        message,
9828                        details: None,
9829                        recommended_action: None,
9830                    })
9831                })?;
9832            // §5.11: reveal rows sealed under a key the keyring gained since.
9833            self.reveal_sealed_rows().map_err(|error| {
9834                Box::new(SyncOutcome::Failed {
9835                    error_code: error.code,
9836                    message: error.message,
9837                    details: error.details,
9838                    recommended_action: None,
9839                })
9840            })?;
9841            let has_log_epoch = self.get_meta(LOG_EPOCH_KEY).map_err(|message| {
9842                Box::new(SyncOutcome::Failed {
9843                    error_code: "storage.failed".into(),
9844                    message,
9845                    details: None,
9846                    recommended_action: None,
9847                })
9848            })?;
9849            let mut uploads = if has_log_epoch.is_some()
9850                && matches!(
9851                    self.transport_gate,
9852                    crate::TransportGate::Open | crate::TransportGate::Through(_)
9853                )
9854                && self.schema_has_blobs()
9855            {
9856                self.pending_blob_uploads().map_err(|e| {
9857                    Box::new(SyncOutcome::Failed {
9858                        error_code: e.code,
9859                        message: e.message,
9860                        details: e.details,
9861                        recommended_action: None,
9862                    })
9863                })?
9864            } else {
9865                Vec::new()
9866            };
9867            // §8.8: a `through` round uploads only the blobs its prefix references.
9868            if matches!(self.transport_gate, crate::TransportGate::Through(_)) {
9869                let prefix = Value::Array(
9870                    self.outbox
9871                        .iter()
9872                        .take(self.pushable_commits())
9873                        .map(|commit| Value::String(commit.client_commit_id.clone()))
9874                        .collect(),
9875                );
9876                let referenced = self
9877                    .conn
9878                    .prepare(
9879                        "SELECT blob_id FROM _syncular_blob_commit_refs
9880                          WHERE commit_id IN (SELECT value FROM json_each(?1))",
9881                    )
9882                    .and_then(|mut statement| {
9883                        statement
9884                            .query_map([prefix.to_string()], |row| row.get::<_, String>(0))?
9885                            .collect::<Result<HashSet<_>, _>>()
9886                    })
9887                    .map_err(|error| {
9888                        Box::new(SyncOutcome::Failed {
9889                            error_code: "storage.failed".into(),
9890                            message: Self::sqlite_failure(&self.storage_failure, error),
9891                            details: None,
9892                            recommended_action: None,
9893                        })
9894                    })?;
9895                uploads.retain(|upload| referenced.contains(&upload.id));
9896            }
9897            if self.realtime_state != RealtimeState::Connected
9898                && self.realtime_policy == RealtimePolicy::Required
9899            {
9900                let retry_delay_ms = self.schedule_background_retry();
9901                self.realtime_retry_delay_ms = Some(retry_delay_ms);
9902                return Err(Box::new(SyncOutcome::RealtimeUnavailable {
9903                    state: self.realtime_state,
9904                    reason_code: self.realtime_reason_code.clone(),
9905                    retry_delay_ms,
9906                }));
9907            }
9908            let (message, mut meta) = self.build_request(url_capable)?;
9909            let units = self.stored(load_units(&self.conn)).map_err(|message| {
9910                Box::new(SyncOutcome::Failed {
9911                    error_code: "storage.failed".into(),
9912                    message,
9913                    details: None,
9914                    recommended_action: None,
9915                })
9916            })?;
9917            for unit in &units {
9918                let applied =
9919                    self.stored(applied_rows(&self.conn, &unit.id))
9920                        .map_err(|message| {
9921                            Box::new(SyncOutcome::Failed {
9922                                error_code: "storage.failed".into(),
9923                                message,
9924                                details: None,
9925                                recommended_action: None,
9926                            })
9927                        })?;
9928                if !applied.is_empty() {
9929                    meta.applied.insert(unit.id.clone(), applied);
9930                }
9931            }
9932            // §7.1: the send-attempt marker of every commit the request
9933            // carries commits before the round leaves the owner.
9934            let pushed: Vec<String> = message
9935                .frames
9936                .iter()
9937                .filter_map(|frame| match frame {
9938                    Frame::PushCommit { client_seq, .. } => Some(client_seq.to_string()),
9939                    _ => None,
9940                })
9941                .collect();
9942            if !pushed.is_empty() {
9943                self.conn
9944                    .execute(
9945                        &format!(
9946                            "UPDATE _syncular_outbox SET attempted = 1 WHERE seq IN ({})",
9947                            pushed.join(",")
9948                        ),
9949                        [],
9950                    )
9951                    .map_err(|error| {
9952                        Box::new(SyncOutcome::Failed {
9953                            error_code: "storage.failed".into(),
9954                            message: Self::sqlite_failure(&self.storage_failure, error),
9955                            details: None,
9956                            recommended_action: None,
9957                        })
9958                    })?;
9959            }
9960            let id = uuid::Uuid::new_v4();
9961            self.active_round = Some((id, started_at_ms, attempt));
9962            let phase = if uploads.is_empty() {
9963                crate::round::RoundPhase::Sync
9964            } else {
9965                crate::round::RoundPhase::UploadGrant
9966            };
9967            Ok(crate::PreparedSyncRound {
9968                id,
9969                started_at_ms,
9970                attempt,
9971                message,
9972                meta,
9973                uploads: uploads.into(),
9974                phase,
9975                encoded: None,
9976                continuation: None,
9977                completed: None,
9978                realtime: self.realtime_state == RealtimeState::Connected,
9979                // §5.5: the owning unit's scope map, each value a one-element list.
9980                scopes: units
9981                    .into_iter()
9982                    .map(|unit| {
9983                        (
9984                            unit.id,
9985                            canonical_scope_json(&unit_scope_lists(&unit.scopes)),
9986                        )
9987                    })
9988                    .collect(),
9989                #[cfg(feature = "bench-internals")]
9990                benchmark_phases: self.benchmark_phases.clone(),
9991                progress: self.progress.clone(),
9992                fixed_now: self
9993                    .now_ms
9994                    .as_ref()
9995                    .map(|clock| clock.load(std::sync::atomic::Ordering::Relaxed)),
9996                round_deadline_at: None,
9997                idle_bound: None,
9998                network_started_at: None,
9999            })
10000        })();
10001        prepared
10002            .map_err(|outcome| Box::new(self.finish_sync_round(started_at_ms, attempt, *outcome)))
10003    }
10004
10005    /// Discard the reply of an old authorization or registration context. Its
10006    /// submitted commits stay durable and can be retried with the same ids.
10007    /// §7.6: an abandoned in-flight round ends its attempt as failed.
10008    pub fn cancel_sync_round(&mut self) {
10009        self.fence_round = None;
10010        if let Some((_, started_at_ms, attempt)) = self.active_round.take() {
10011            // A storage failure recorded since the round started is not its cause.
10012            self.storage_failure.borrow_mut().take();
10013            self.finish_sync_round(
10014                started_at_ms,
10015                attempt,
10016                SyncOutcome::Failed {
10017                    error_code: "client.round_cancelled".into(),
10018                    message: "sync round belongs to a released client context".into(),
10019                    details: None,
10020                    recommended_action: None,
10021                },
10022            );
10023        }
10024    }
10025
10026    /// Apply captured network results on the owner, preserving all normal
10027    /// version, schema, content-address and cursor checks. No network I/O.
10028    pub fn apply_sync_round(
10029        &mut self,
10030        completed: crate::CompletedSyncRound,
10031    ) -> crate::AppliedSyncRound {
10032        let mut prepared = completed.prepared;
10033        if self.active_round.map(|(id, ..)| id) != Some(prepared.id) || self.security_preflight {
10034            return crate::AppliedSyncRound::Complete {
10035                outcome: SyncOutcome::Failed {
10036                    error_code: "client.round_cancelled".into(),
10037                    message: "sync round belongs to a released client context".into(),
10038                    details: None,
10039                    recommended_action: None,
10040                },
10041                controls: Vec::new(),
10042                more: false,
10043                bootstrap_advanced: false,
10044            };
10045        }
10046        self.storage_failure.borrow_mut().take();
10047        let (response, mut downloads, transport_failed) = match completed.exchange {
10048            crate::round::ExchangeResult::Upload { id, result } => {
10049                let result = match result {
10050                    // §5.9.7: a non-retryable server refusal (`blob.too_large`)
10051                    // is the body's final outcome. The commits naming it take
10052                    // the incompatible-commit path with the server's code and
10053                    // leave this round's request; the round continues.
10054                    Err(error)
10055                        if error
10056                            .details
10057                            .as_ref()
10058                            .and_then(|details| details.get("retryable"))
10059                            == Some(&Value::Bool(false)) =>
10060                    {
10061                        self.conn
10062                            .prepare(
10063                                "SELECT commit_id FROM _syncular_blob_commit_refs WHERE blob_id = ?",
10064                            )
10065                            .and_then(|mut statement| {
10066                                statement
10067                                    .query_map(rusqlite::params![id], |row| row.get::<_, String>(0))?
10068                                    .collect::<Result<HashSet<_>, _>>()
10069                            })
10070                            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
10071                            .and_then(|refused| {
10072                                // §8.8: only a commit the gate lets this round
10073                                // push takes the refusal. A held commit keeps
10074                                // the body queued and meets the refusal when a
10075                                // round pushes it.
10076                                let commits = self
10077                                    .outbox
10078                                    .iter()
10079                                    .take(self.pushable_commits())
10080                                    .filter(|commit| refused.contains(&commit.client_commit_id))
10081                                    .cloned()
10082                                    .collect::<Vec<_>>();
10083                                if !commits.is_empty() {
10084                                    self.drop_outbox_commits(&commits, &error.code, &error.message)?;
10085                                }
10086                                prepared.message.frames.retain(|frame| {
10087                                    !matches!(frame, Frame::PushCommit { client_commit_id, .. }
10088                                        if refused.contains(client_commit_id))
10089                                });
10090                                prepared.meta.pushed_ids.retain(|id| !refused.contains(id));
10091                                prepared.continuation = Some(crate::round::RoundPhase::UploadGrant);
10092                                Ok(true)
10093                            })
10094                            .map_err(|message| TransportError::new("client.failed", message))
10095                    }
10096                    result => result.map(|()| false),
10097                };
10098                // A refused body stays queued while a held commit names it.
10099                let result = result.and_then(|refused| {
10100                    self.conn
10101                        .execute(
10102                            if refused {
10103                                "DELETE FROM _syncular_blob_uploads WHERE blob_id = ?1
10104                                   AND NOT EXISTS (SELECT 1 FROM _syncular_blob_commit_refs
10105                                                    WHERE blob_id = ?1)"
10106                            } else {
10107                                "DELETE FROM _syncular_blob_uploads WHERE blob_id = ?1"
10108                            },
10109                            rusqlite::params![id],
10110                        )
10111                        .map(|_| ())
10112                        .map_err(|error| {
10113                            TransportError::new(
10114                                "client.failed",
10115                                Self::sqlite_failure(&self.storage_failure, error),
10116                            )
10117                        })
10118                });
10119                match result {
10120                    Ok(()) => return crate::AppliedSyncRound::Continue(prepared),
10121                    Err(TransportError {
10122                        code,
10123                        message,
10124                        details,
10125                    }) => {
10126                        self.active_round = None;
10127                        if Self::unreachable_transport(&details) {
10128                            // The round's work is still owed; the host's
10129                            // connectivity resume runs it.
10130                            self.set_sync_needed(true, false);
10131                        } else if Self::retryable_failure_code(&code) {
10132                            self.schedule_background_retry();
10133                        }
10134                        let recommended_action = recommended_action_of(&details);
10135                        let outcome = self.finish_sync_round(
10136                            prepared.started_at_ms,
10137                            prepared.attempt,
10138                            SyncOutcome::Failed {
10139                                error_code: code,
10140                                message,
10141                                details,
10142                                recommended_action,
10143                            },
10144                        );
10145                        return crate::AppliedSyncRound::Complete {
10146                            outcome,
10147                            controls: Vec::new(),
10148                            more: false,
10149                            bootstrap_advanced: false,
10150                        };
10151                    }
10152                }
10153            }
10154            crate::round::ExchangeResult::Reply {
10155                response,
10156                downloads,
10157                transport_failed,
10158            } => (response, downloads, transport_failed),
10159        };
10160        self.active_round = None;
10161        let before = self.resume_tokens();
10162        let outcome = (|| {
10163            let response = match response {
10164                Ok(response) => {
10165                    // §1.5: a complete, decodable response ends the report, an
10166                    // in-band ERROR included (the server already recorded it).
10167                    self.round_failure = None;
10168                    response
10169                }
10170                Err(TransportError {
10171                    code,
10172                    message,
10173                    details,
10174                }) => {
10175                    // §1.5: the server cannot see a round whose transport
10176                    // failed or whose response never decoded, so its code rides
10177                    // the following requests. A code the frame grammar rejects
10178                    // is not reportable, and the previous code stays; the
10179                    // client-local drive timeout never goes on the wire (§7.8).
10180                    if code != "sync.idle_timeout" && ssp2::model::valid_round_failure_code(&code) {
10181                        self.round_failure = Some(code.clone());
10182                    }
10183                    // §8.8: a prefix sent without a receipt is an uncertain delivery.
10184                    if !prepared.meta.pushed_ids.is_empty()
10185                        && matches!(self.transport_gate, crate::TransportGate::Through(_))
10186                    {
10187                        self.move_transport_gate(crate::TransportGate::Pull);
10188                    }
10189                    if transport_failed {
10190                        if prepared.realtime {
10191                            self.set_realtime_state(RealtimeState::Lost, Some(&code));
10192                        }
10193                        if let Err(message) = self.record_lease_error(&code) {
10194                            return SyncOutcome::Failed {
10195                                error_code: "storage.failed".to_owned(),
10196                                message,
10197                                details: None,
10198                                recommended_action: None,
10199                            };
10200                        }
10201                    }
10202                    if Self::retryable_failure_code(&code) && !Self::unreachable_transport(&details)
10203                    {
10204                        let delay = self.schedule_background_retry();
10205                        if prepared.realtime && transport_failed {
10206                            self.realtime_retry_delay_ms = Some(delay);
10207                        }
10208                    }
10209                    let recommended_action = recommended_action_of(&details);
10210                    return SyncOutcome::Failed {
10211                        error_code: code,
10212                        message,
10213                        details,
10214                        recommended_action,
10215                    };
10216                }
10217            };
10218            let mut outcome = self.process_response(&mut downloads, response, &prepared.meta);
10219            if let SyncOutcome::Ok(report) = &mut outcome {
10220                report.deferred_commits = prepared.meta.deferred_commits;
10221            }
10222            match &outcome {
10223                SyncOutcome::Ok(_) => self.reset_background_retry(),
10224                SyncOutcome::Failed {
10225                    error_code,
10226                    details,
10227                    ..
10228                } if Self::retryable_failure_code(error_code)
10229                    && !Self::unreachable_transport(details) =>
10230                {
10231                    self.schedule_background_retry();
10232                }
10233                _ => {}
10234            }
10235            if prepared.meta.deferred_commits > 0 {
10236                self.set_sync_needed(true, true);
10237            }
10238            self.previous_version_lifetime_check();
10239            outcome
10240        })();
10241        match &outcome {
10242            // §7.1: a unit still catching up needs another round, also when the
10243            // drive that started it ends early.
10244            SyncOutcome::Ok(report) if !report.bootstrapping.is_empty() => {
10245                self.set_sync_needed(true, false)
10246            }
10247            // The round's work is still owed; the host's connectivity resume
10248            // runs it.
10249            SyncOutcome::Failed { details, .. } if Self::unreachable_transport(details) => {
10250                self.set_sync_needed(true, false)
10251            }
10252            _ => {}
10253        }
10254        let more = !self.transport_closed()
10255            && matches!(&outcome, SyncOutcome::Ok(report)
10256                if report.schema_floor.is_none()
10257                    && (!report.bootstrapping.is_empty()
10258                        || report.commits_applied > 0
10259                        || report.segment_rows_applied > 0
10260                        || !report.resets.is_empty()
10261                        || report.deferred_commits > 0
10262                        || self.sync_needed));
10263        let bootstrap_advanced = matches!(&outcome, SyncOutcome::Ok(report) if report.segment_rows_applied > 0 && !report.bootstrapping.is_empty())
10264            && before != self.resume_tokens();
10265        crate::AppliedSyncRound::Complete {
10266            outcome: self.finish_sync_round(prepared.started_at_ms, prepared.attempt, outcome),
10267            controls: if !self.transport_closed() {
10268                downloads.controls
10269            } else {
10270                Vec::new()
10271            },
10272            more,
10273            bootstrap_advanced,
10274        }
10275    }
10276
10277    /// Every unit's resume token and applied-segment record: a bootstrap
10278    /// that advanced changes one (§4.7), also when it applied images of a
10279    /// section it deferred (§5.3, §5.6).
10280    #[allow(clippy::type_complexity)]
10281    fn resume_tokens(&self) -> Option<Vec<(String, Option<String>, Option<String>)>> {
10282        self.conn
10283            .prepare_cached(
10284                "SELECT id, bootstrap_state, applied FROM _syncular_units ORDER BY rowid",
10285            )
10286            .and_then(|mut stmt| {
10287                stmt.query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))?
10288                    .collect()
10289            })
10290            .ok()
10291    }
10292
10293    /// §7.8: one idle drive's default total deadline, the TS client's value.
10294    pub const SYNC_IDLE_TIMEOUT_MS: u64 = 60_000;
10295
10296    pub fn sync_until_idle(
10297        &mut self,
10298        transport: &mut dyn Transport,
10299        max_rounds: Option<u32>,
10300    ) -> SyncOutcome {
10301        self.sync_until_idle_with_deadline(transport, max_rounds, Some(Self::SYNC_IDLE_TIMEOUT_MS))
10302    }
10303
10304    /// As [`SyncClient::sync_until_idle`], with an explicit total deadline in
10305    /// milliseconds (`None` disables it). The deadline is checked against the
10306    /// client clock between rounds: a drive past it after a completed round
10307    /// ends as `BudgetExhausted`. Each round is bounded by `timeout_ms` on its
10308    /// own, or the transport's tighter whole-round deadline (§1.8); a round
10309    /// that reaches the drive bound fails with `sync.idle_timeout`.
10310    pub fn sync_until_idle_with_deadline(
10311        &mut self,
10312        transport: &mut dyn Transport,
10313        max_rounds: Option<u32>,
10314        timeout_ms: Option<u64>,
10315    ) -> SyncOutcome {
10316        // §7.8: an explicit budget is a strict positive round count. Zero is a
10317        // caller error, not an exhaustion.
10318        if max_rounds == Some(0) {
10319            return SyncOutcome::Failed {
10320                details: None,
10321                error_code: "sync.invalid_request".into(),
10322                message: "maxRounds must be a positive integer".into(),
10323                recommended_action: None,
10324            };
10325        }
10326        if timeout_ms.is_some_and(|ms| ms == 0 || i64::try_from(ms).is_err()) {
10327            return SyncOutcome::Failed {
10328                details: None,
10329                error_code: "sync.invalid_request".into(),
10330                message: "timeoutMs must be a positive integer".into(),
10331                recommended_action: None,
10332            };
10333        }
10334        let started_at_ms = self.clock_now_ms();
10335        let rounds = max_rounds.unwrap_or(20);
10336        let mut aggregate = SyncReport::default();
10337        // §7.2.2: decisions pending at the drive's start are evaluated when it
10338        // reaches idle.
10339        let decisions = match self.prepare_replacements() {
10340            Ok(decisions) => decisions,
10341            Err(message) => {
10342                return SyncOutcome::Failed {
10343                    details: None,
10344                    error_code: "storage.failed".into(),
10345                    message,
10346                    recommended_action: None,
10347                }
10348            }
10349        };
10350        let mut spent = 0;
10351        let mut completed = false;
10352        while spent < rounds {
10353            // §7.8: a deadline that elapsed across completed rounds ends the
10354            // drive like an exhausted round budget; the next drive resumes.
10355            if completed
10356                && timeout_ms.is_some_and(|ms| {
10357                    self.clock_now_ms() >= started_at_ms.saturating_add(ms as i64)
10358                })
10359            {
10360                return SyncOutcome::BudgetExhausted(aggregate);
10361            }
10362            let idle_bound = timeout_ms.map(|ms| (ms, spent));
10363            spent += 1;
10364            let before = self.resume_tokens();
10365            match self.sync_bounded(transport, idle_bound) {
10366                SyncOutcome::Failed {
10367                    error_code,
10368                    message,
10369                    details,
10370                    recommended_action,
10371                } => {
10372                    return SyncOutcome::Failed {
10373                        details,
10374                        error_code,
10375                        message,
10376                        recommended_action,
10377                    };
10378                }
10379                outcome @ SyncOutcome::RealtimeUnavailable { .. } => return outcome,
10380                SyncOutcome::BudgetExhausted(_) => {
10381                    unreachable!("sync() never exhausts a round budget")
10382                }
10383                SyncOutcome::Ok(report) => {
10384                    completed = true;
10385                    if max_rounds.is_none()
10386                        && report.segment_rows_applied > 0
10387                        && !report.bootstrapping.is_empty()
10388                        && before != self.resume_tokens()
10389                    {
10390                        spent = 0;
10391                    }
10392                    // TS parity: a closed transport or a schema floor ends
10393                    // the loop. The latest round still merges first.
10394                    let stop = self.transport_closed() || report.schema_floor.is_some();
10395                    aggregate.merge(&report);
10396                    // §4.5: pull again whenever the response contained
10397                    // commits or segments; resets re-bootstrap; a pending
10398                    // resume token continues paging (§4.7); deferred outbox
10399                    // commits and a raised sync-needed signal push on the next
10400                    // round.
10401                    let more = !stop
10402                        && (!report.bootstrapping.is_empty()
10403                            || report.commits_applied > 0
10404                            || report.segment_rows_applied > 0
10405                            || !report.resets.is_empty()
10406                            || report.deferred_commits > 0
10407                            || self.sync_needed);
10408                    if more {
10409                        continue;
10410                    }
10411                    // §7.2.2: a written decision runs another round, which
10412                    // pushes it.
10413                    match self.settle_replacements(&decisions, &SyncOutcome::Ok(aggregate.clone()))
10414                    {
10415                        Ok(true) if !stop => {}
10416                        Ok(_) => return SyncOutcome::Ok(aggregate),
10417                        Err(message) => {
10418                            return SyncOutcome::Failed {
10419                                details: None,
10420                                error_code: "storage.failed".into(),
10421                                message,
10422                                recommended_action: None,
10423                            }
10424                        }
10425                    }
10426                }
10427            }
10428        }
10429        // §7.8: partial success. The aggregate report is retained and the run
10430        // is explicitly not idle.
10431        SyncOutcome::BudgetExhausted(aggregate)
10432    }
10433
10434    fn process_response(
10435        &mut self,
10436        transport: &mut dyn Transport,
10437        response: Message,
10438        meta: &RequestMeta,
10439    ) -> SyncOutcome {
10440        #[cfg(feature = "bench-internals")]
10441        let _phase = self.benchmark_phases.start(Phase::ResponseApply);
10442        let mut report = SyncReport {
10443            pushed: meta.pushed_ids.len() as u32,
10444            ..SyncReport::default()
10445        };
10446        let mut rejection_details_by_commit: HashMap<String, BTreeMap<i32, RejectionDetails>> =
10447            HashMap::new();
10448        let pushed_ids = meta
10449            .pushed_ids
10450            .iter()
10451            .map(String::as_str)
10452            .collect::<HashSet<_>>();
10453        let mut last_final_push_result_id: Option<String> = None;
10454        for frame in &response.frames {
10455            match frame {
10456                Frame::PushResultDetails {
10457                    client_commit_id,
10458                    entries,
10459                } => {
10460                    let details = rejection_details_by_commit
10461                        .entry(client_commit_id.clone())
10462                        .or_default();
10463                    for entry in entries {
10464                        let parsed = match RejectionDetails::parse(&entry.details.0) {
10465                            Ok(value) => value,
10466                            Err(message) => {
10467                                return SyncOutcome::Failed {
10468                                    details: None,
10469                                    error_code: "sync.invalid_request".to_owned(),
10470                                    message,
10471                                    recommended_action: None,
10472                                };
10473                            }
10474                        };
10475                        details.insert(entry.op_index, parsed);
10476                    }
10477                }
10478                Frame::PushResult {
10479                    client_commit_id,
10480                    status,
10481                    results,
10482                    ..
10483                } if pushed_ids.contains(client_commit_id.as_str())
10484                    && Self::push_result_is_final(*status, results) =>
10485                {
10486                    last_final_push_result_id = Some(client_commit_id.clone());
10487                }
10488                _ => {}
10489            }
10490        }
10491        let mut frames = response.frames.into_iter().peekable();
10492        match frames.next() {
10493            Some(Frame::RespHeader {
10494                required_schema_version,
10495                latest_schema_version,
10496                log_epoch,
10497                reset_required,
10498            }) => {
10499                if let Some(required) = required_schema_version {
10500                    // §1.6 schema-floor response: nothing else is processed;
10501                    // stop syncing and surface the upgrade requirement.
10502                    let floor = SchemaFloor {
10503                        required_schema_version: Some(required),
10504                        latest_schema_version,
10505                    };
10506                    if let Err(message) = self.set_schema_floor(Some(floor.clone())) {
10507                        return SyncOutcome::Failed {
10508                            details: None,
10509                            error_code: "storage.failed".to_owned(),
10510                            message,
10511                            recommended_action: None,
10512                        };
10513                    }
10514                    report.schema_floor = Some(floor);
10515                    return SyncOutcome::Ok(report);
10516                }
10517                if reset_required {
10518                    if frames.next().is_some() {
10519                        return SyncOutcome::Failed {
10520                            details: None,
10521                            error_code: "client.invalid_host_response".to_owned(),
10522                            message: "log-epoch reset response contains body frames".to_owned(),
10523                            recommended_action: None,
10524                        };
10525                    }
10526                    match self.run_log_epoch_reset(&log_epoch) {
10527                        Ok(resets) => {
10528                            report.resets = resets;
10529                            return SyncOutcome::Ok(report);
10530                        }
10531                        Err(message) => {
10532                            return SyncOutcome::Failed {
10533                                details: None,
10534                                error_code: "sync.local_corrupt".to_owned(),
10535                                message,
10536                                recommended_action: None,
10537                            };
10538                        }
10539                    }
10540                }
10541                let stored_epoch = match self.get_meta(LOG_EPOCH_KEY) {
10542                    Ok(stored) => stored,
10543                    Err(message) => {
10544                        return SyncOutcome::Failed {
10545                            details: None,
10546                            error_code: "storage.failed".to_owned(),
10547                            message,
10548                            recommended_action: None,
10549                        };
10550                    }
10551                };
10552                // §2.1 adoption: the epoch is stored before any section applies.
10553                if stored_epoch.is_none() {
10554                    if let Err(message) = self.set_meta(LOG_EPOCH_KEY, &log_epoch) {
10555                        return SyncOutcome::Failed {
10556                            details: None,
10557                            error_code: "storage.failed".to_owned(),
10558                            message,
10559                            recommended_action: None,
10560                        };
10561                    }
10562                } else if stored_epoch.as_deref() != Some(log_epoch.as_str()) {
10563                    return SyncOutcome::Failed {
10564                        details: None,
10565                        error_code: "client.invalid_host_response".to_owned(),
10566                        message: "server changed logEpoch without requiring a reset".to_owned(),
10567                        recommended_action: None,
10568                    };
10569                }
10570            }
10571            _ => {
10572                return SyncOutcome::Failed {
10573                    details: None,
10574                    error_code: "sync.invalid_request".to_owned(),
10575                    message: "response does not start with RESP_HEADER".to_owned(),
10576                    recommended_action: None,
10577                };
10578            }
10579        }
10580
10581        if let Err(message) = self.begin_coalesced_apply() {
10582            return SyncOutcome::Failed {
10583                details: None,
10584                error_code: "storage.failed".into(),
10585                message,
10586                recommended_action: None,
10587            };
10588        }
10589        let mut failure: Option<(String, String, Option<String>, Option<Value>)> = None;
10590        // §4.5 client application: the units whose persisted echo a live
10591        // change must match, fixed at LIVE_START after every SUB_END persisted.
10592        let mut live: Option<(LiveStatus, String, Vec<UnitRecord>)> = None;
10593        let mut live_ended = false;
10594        while let Some(frame) = frames.next() {
10595            match frame {
10596                frame @ Frame::PushResult { .. } => {
10597                    let successful = matches!(
10598                        &frame,
10599                        Frame::PushResult {
10600                            status: PushStatus::Applied | PushStatus::Cached,
10601                            ..
10602                        }
10603                    );
10604                    let mut results = vec![frame];
10605                    if successful {
10606                        while matches!(
10607                            frames.peek(),
10608                            Some(Frame::PushResult {
10609                                status: PushStatus::Applied | PushStatus::Cached,
10610                                ..
10611                            })
10612                        ) {
10613                            if let Some(next) = frames.next() {
10614                                results.push(next);
10615                            }
10616                        }
10617                    }
10618                    if self
10619                        .handle_push_results(
10620                            &results,
10621                            &pushed_ids,
10622                            &rejection_details_by_commit,
10623                            &mut report,
10624                            last_final_push_result_id.as_deref(),
10625                        )
10626                        .is_err()
10627                    {
10628                        failure = Some((
10629                            "client.outcome_persistence_failed".to_owned(),
10630                            "local commit outcome could not be persisted".to_owned(),
10631                            None,
10632                            None,
10633                        ));
10634                        break;
10635                    }
10636                }
10637                Frame::PushResultDetails { .. } => {}
10638                Frame::SubStart {
10639                    id,
10640                    status,
10641                    reason_code,
10642                    bootstrap,
10643                    fenced,
10644                } => {
10645                    // §1.4 rule 5: an ERROR closes the section; its body still
10646                    // applied, its SUB_END values are never persisted.
10647                    let mut body = Vec::new();
10648                    let mut sub_end: Option<(i64, Option<String>)> = None;
10649                    let mut error: Option<Frame> = None;
10650                    for inner in frames.by_ref() {
10651                        match inner {
10652                            Frame::SubEnd {
10653                                next_cursor,
10654                                bootstrap_state,
10655                            } => {
10656                                sub_end = Some((next_cursor, bootstrap_state.map(|r| r.0)));
10657                                break;
10658                            }
10659                            inner @ Frame::Error { .. } => {
10660                                error = Some(inner);
10661                                break;
10662                            }
10663                            Frame::Unknown { .. } => {}
10664                            other => body.push(other),
10665                        }
10666                    }
10667                    let ended = sub_end.is_some();
10668                    let section = SectionStart {
10669                        id,
10670                        status,
10671                        reason_code,
10672                        bootstrap,
10673                        fenced,
10674                    };
10675                    let completed = match self.process_section(
10676                        transport,
10677                        &section,
10678                        body,
10679                        sub_end,
10680                        meta,
10681                        &mut report,
10682                    ) {
10683                        Err(SectionError::Abort(code, message)) => {
10684                            failure = Some((code, message, None, None));
10685                            break;
10686                        }
10687                        Err(SectionError::Transport(error)) => {
10688                            failure = Some((error.code, error.message, None, error.details));
10689                            break;
10690                        }
10691                        Ok(completed) => completed,
10692                        Err(_) => false,
10693                    };
10694                    if ended {
10695                        // The counters stay: `complete` and `failed` report them.
10696                        // §7.7: a completed bootstrap ends with the unit total
10697                        // equal to the rows processed.
10698                        self.progress.update(|p| {
10699                            p.unit_id = None;
10700                            p.table = None;
10701                            p.segment_id = None;
10702                            if completed && p.unit_rows_total.is_some() {
10703                                p.unit_rows_total = p.unit_rows_processed;
10704                            }
10705                        });
10706                    }
10707                    match error {
10708                        Some(Frame::Error {
10709                            code,
10710                            message,
10711                            recommended_action,
10712                            details,
10713                            ..
10714                        }) => {
10715                            failure = Some(Self::error_frame_failure(
10716                                code,
10717                                message,
10718                                recommended_action,
10719                                details,
10720                            ));
10721                            break;
10722                        }
10723                        Some(_) => unreachable!("only an ERROR closes a section early"),
10724                        None if !ended => {
10725                            failure = Some((
10726                                "sync.invalid_request".to_owned(),
10727                                "unit section without SUB_END".to_owned(),
10728                                None,
10729                                None,
10730                            ));
10731                            break;
10732                        }
10733                        None => {}
10734                    }
10735                }
10736                Frame::LiveStart {
10737                    status,
10738                    reason_code,
10739                } => {
10740                    let receivers = match self.stored(load_units(&self.conn)) {
10741                        Ok(units) => units
10742                            .into_iter()
10743                            .filter(|unit| {
10744                                unit.status == UnitStatus::Active
10745                                    && unit.echo.is_some()
10746                                    && !unit.bootstrapping()
10747                            })
10748                            .collect(),
10749                        Err(message) => {
10750                            failure = Some(("storage.failed".to_owned(), message, None, None));
10751                            break;
10752                        }
10753                    };
10754                    live = Some((status, reason_code, receivers));
10755                }
10756                Frame::Commit {
10757                    commit_seq,
10758                    tables,
10759                    changes,
10760                    ..
10761                } => {
10762                    let Some((LiveStatus::Active, _, receivers)) = &live else {
10763                        continue;
10764                    };
10765                    let receivers = receivers.clone();
10766                    match self.apply_live_commit(
10767                        &receivers,
10768                        &tables,
10769                        changes,
10770                        commit_seq,
10771                        AppliedServerCommitSource::Pull,
10772                    ) {
10773                        Ok(applied) => report.commits_applied += u32::from(applied),
10774                        Err(error) => {
10775                            failure = Some((error.code, error.message, None, error.details));
10776                            break;
10777                        }
10778                    }
10779                }
10780                Frame::LiveEnd {
10781                    through_seq,
10782                    echo_digest,
10783                } => {
10784                    let Some((status, reason_code, _)) = live.take() else {
10785                        continue;
10786                    };
10787                    live_ended = true;
10788                    live = Some((status, String::new(), Vec::new()));
10789                    if let Err(message) = self.finish_live_section(
10790                        status,
10791                        &reason_code,
10792                        through_seq,
10793                        echo_digest,
10794                        &meta.registration_digest,
10795                        &mut report,
10796                    ) {
10797                        failure = Some(("storage.failed".to_owned(), message, None, None));
10798                        break;
10799                    }
10800                }
10801                Frame::Lease {
10802                    lease_id,
10803                    expires_at_ms,
10804                } => {
10805                    // §7.3.5: persist the opaque lease; a fresh lease clears
10806                    // any prior lease error (the outage/revocation is over).
10807                    if let Err(message) = self.set_lease_state(Some(LeaseState {
10808                        lease_id: Some(lease_id),
10809                        expires_at_ms: Some(expires_at_ms),
10810                        error_code: None,
10811                    })) {
10812                        failure = Some(("storage.failed".to_owned(), message, None, None));
10813                        break;
10814                    }
10815                }
10816                Frame::Error {
10817                    code,
10818                    message,
10819                    recommended_action,
10820                    details,
10821                    ..
10822                } => {
10823                    // §1.6: the whole request failed; already-completed
10824                    // units keep their applied data and cursors.
10825                    failure = Some(Self::error_frame_failure(
10826                        code,
10827                        message,
10828                        recommended_action,
10829                        details,
10830                    ));
10831                    break;
10832                }
10833                Frame::Unknown { .. } => {}
10834                // §1.6: a building server's keepalive carries nothing to apply.
10835                Frame::Keepalive => {}
10836                _ => {
10837                    failure = Some((
10838                        "sync.invalid_request".to_owned(),
10839                        "unexpected frame in response".to_owned(),
10840                        None,
10841                        None,
10842                    ));
10843                    break;
10844                }
10845            }
10846        }
10847
10848        let applied = match failure {
10849            Some(failure) => Err(failure),
10850            // Local apply boundaries already reconciled their affected overlay.
10851            // Refuse round success if any remaining dirty work fails to
10852            // reconcile. §4.8 E1: the push half may have drained commits that
10853            // pinned rows of a shrunk window unit, so retry deferred evictions.
10854            None => self
10855                .rebuild_overlay_if_dirty()
10856                .and_then(|()| self.drain_pending_evictions())
10857                .map_err(|message| ("storage.failed".to_owned(), message, None, None)),
10858        };
10859        // §1.4 rule 4: frames completed before a failure stay committed; a
10860        // failed COMMIT of the coalesced transaction fails the round.
10861        if let Err(message) = self.finish_coalesced_apply() {
10862            return SyncOutcome::Failed {
10863                details: None,
10864                error_code: "storage.failed".into(),
10865                message,
10866                recommended_action: None,
10867            };
10868        }
10869        if let Err((error_code, message, recommended_action, details)) = applied {
10870            return SyncOutcome::Failed {
10871                details,
10872                error_code,
10873                message,
10874                recommended_action,
10875            };
10876        }
10877        let catching_up = match self.stored(load_units(&self.conn)) {
10878            Ok(units) => units
10879                .into_iter()
10880                .filter(|unit| unit.status == UnitStatus::Active && unit.cursor.is_some())
10881                .map(|unit| unit.id)
10882                .collect::<Vec<_>>(),
10883            Err(message) => {
10884                return SyncOutcome::Failed {
10885                    details: None,
10886                    error_code: "storage.failed".into(),
10887                    message,
10888                    recommended_action: None,
10889                }
10890            }
10891        };
10892        // §7.1: a response without LIVE_END, one answered `unregistered` or
10893        // `reset`, or a unit still catching up leaves sync-needed raised;
10894        // after `unregistered` the next round starts at once.
10895        let status = live.map(|(status, _, _)| status);
10896        if !live_ended || status != Some(LiveStatus::Active) || !catching_up.is_empty() {
10897            self.set_sync_needed(true, status == Some(LiveStatus::Unregistered));
10898        }
10899        self.ack_after_pull(transport);
10900        // §7.4.5: the reset is over once the first post-reset pull round
10901        // leaves no unit catching up: the tables are rebuilt and current.
10902        if self.upgrading && catching_up.is_empty() {
10903            self.set_upgrading(false);
10904        }
10905        report.bootstrapping = catching_up;
10906        SyncOutcome::Ok(report)
10907    }
10908
10909    /// §1.6 / §10.1: the failure an in-band `ERROR` frame reports.
10910    fn error_frame_failure(
10911        code: String,
10912        message: String,
10913        recommended_action: String,
10914        details: Option<RawJson>,
10915    ) -> (String, String, Option<String>, Option<Value>) {
10916        let recommended_action = (!recommended_action.is_empty()).then_some(recommended_action);
10917        let details = details
10918            .and_then(|details| serde_json::from_str::<Value>(&details.0).ok())
10919            .filter(Value::is_object);
10920        (code, message, recommended_action, details)
10921    }
10922
10923    /// §4.5 at `LIVE_END` of a pull: join rule J for an `active` section, the
10924    /// §4.6 replica reset for `reset`, nothing for `unregistered`; then the
10925    /// replica cursor, the echo digest and the digest of the list the server
10926    /// now stores.
10927    fn finish_live_section(
10928        &mut self,
10929        status: LiveStatus,
10930        reason_code: &str,
10931        through_seq: i64,
10932        echo_digest: Option<[u8; 32]>,
10933        registration_digest: &str,
10934        report: &mut SyncReport,
10935    ) -> Result<(), String> {
10936        let rollback = self.capture();
10937        let resets = report.resets.len();
10938        self.begin_observation("syncular_live_end")?;
10939        let finished = (|| {
10940            let mut batch = ChangeAccumulator::default();
10941            let before = self.stored(replica_cursor(&self.conn))?;
10942            let mut cursor = if status == LiveStatus::Unregistered {
10943                before
10944            } else {
10945                -1
10946            };
10947            let joined = before.max(through_seq);
10948            for unit in self.stored(load_units(&self.conn))? {
10949                if unit.status != UnitStatus::Active || unit.bootstrapping() {
10950                    continue;
10951                }
10952                match status {
10953                    // §4.6 replica reset: every live unit bootstraps again;
10954                    // post-bootstrap units keep their cursors.
10955                    LiveStatus::Reset if unit.cursor.is_none() => {
10956                        self.record_unit_windows(&mut batch, &unit)?;
10957                        report.resets.push(unit.id.clone());
10958                        self.stored(save_unit(
10959                            &self.conn,
10960                            &UnitRecord {
10961                                reason_code: Some(reason_code.to_owned()),
10962                                cursor: Some(-1),
10963                                seeded: Vec::new(),
10964                                ..unit
10965                            },
10966                        ))?;
10967                    }
10968                    // §4.5 join rule J.
10969                    LiveStatus::Active => {
10970                        let next = unit.cursor.unwrap_or(joined).max(through_seq);
10971                        if next >= joined {
10972                            cursor = joined;
10973                        }
10974                        if unit.cursor.is_some() {
10975                            // A post-bootstrap unit that joins live transitions.
10976                            if next >= joined {
10977                                self.record_unit_windows(&mut batch, &unit)?;
10978                            }
10979                            self.stored(save_unit(
10980                                &self.conn,
10981                                &UnitRecord {
10982                                    cursor: (next < joined).then_some(next),
10983                                    ..unit
10984                                },
10985                            ))?;
10986                        }
10987                    }
10988                    _ => {}
10989                }
10990            }
10991            self.set_meta(REPLICA_CURSOR_KEY, &cursor.to_string())?;
10992            self.set_meta(
10993                ECHO_DIGEST_KEY,
10994                &echo_digest
10995                    .map(|digest| bytes_to_hex(&digest))
10996                    .unwrap_or_default(),
10997            )?;
10998            if status == LiveStatus::Unregistered {
10999                self.delete_meta(REGISTERED_DIGEST_KEY)?;
11000            } else {
11001                self.set_meta(REGISTERED_DIGEST_KEY, registration_digest)?;
11002            }
11003            self.finish_observation("syncular_live_end", batch)
11004        })();
11005        if finished.is_err() {
11006            self.rollback_observation("syncular_live_end");
11007            self.restore(rollback);
11008            report.resets.truncate(resets);
11009        }
11010        finished
11011    }
11012
11013    // -- push results (§6.3, §7.2) ------------------------------------------------
11014
11015    fn handle_push_results(
11016        &mut self,
11017        frames: &[Frame],
11018        pushed_ids: &HashSet<&str>,
11019        rejection_details_by_commit: &HashMap<String, BTreeMap<i32, RejectionDetails>>,
11020        report: &mut SyncReport,
11021        last_final_push_result_id: Option<&str>,
11022    ) -> Result<(), String> {
11023        self.begin_observation("syncular_push_results")?;
11024        let rollback = self.capture();
11025        let conflict_count = self.conflicts.len();
11026        let applied_count = report.applied.len();
11027        let rejected_count = report.rejected.len();
11028        let retryable_count = report.retryable.len();
11029        let mut drained = Vec::new();
11030        let mut batch = ChangeAccumulator::default();
11031        let persisted = (|| {
11032            for frame in frames {
11033                let Frame::PushResult {
11034                    client_commit_id,
11035                    status,
11036                    results,
11037                    commit_seq,
11038                } = frame
11039                else {
11040                    return Err("unexpected acknowledgement frame".to_owned());
11041                };
11042                if !pushed_ids.contains(client_commit_id.as_str()) {
11043                    continue;
11044                }
11045                let Some(index) = self
11046                    .outbox
11047                    .iter()
11048                    .position(|commit| commit.client_commit_id == *client_commit_id)
11049                else {
11050                    continue;
11051                };
11052                let status = *status;
11053                let rejection_details = rejection_details_by_commit.get(client_commit_id);
11054                let operations = self.outbox[index].ops.clone();
11055                match status {
11056                    PushStatus::Applied | PushStatus::Cached => {
11057                        // §7.2: a lost ack replays as `cached` — proceed as if the
11058                        // ack had arrived.
11059                        let sequence =
11060                            commit_seq.ok_or_else(|| "ACK lacks a commit sequence".to_owned())?;
11061                        let affected: HashSet<_> = operations
11062                            .iter()
11063                            .map(|op| (op.table.as_str(), op.row_id.as_str()))
11064                            .collect();
11065                        let prior = self.acknowledged_operations(Some(&affected), None)?;
11066                        for (op_index, operation) in operations.iter().enumerate() {
11067                            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))
11068                                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11069                            if delivered {
11070                                continue;
11071                            }
11072                            let table = self
11073                                .schema
11074                                .table(&operation.table)
11075                                .ok_or_else(|| "sync.unknown_table".to_owned())?;
11076                            let mut intended: Map<String, Value> = self
11077                                .stored_row(table, &operation.row_id, true)?
11078                                .map(|(row, _)| {
11079                                    table
11080                                        .columns
11081                                        .iter()
11082                                        .zip(&row)
11083                                        .map(|(column, value)| {
11084                                            (column.name.clone(), column_value_to_json(value))
11085                                        })
11086                                        .collect()
11087                                })
11088                                .unwrap_or_default();
11089                            let mut scope_image = intended.clone();
11090                            for op in prior
11091                                .iter()
11092                                .chain(
11093                                    self.failed_commits
11094                                        .iter()
11095                                        .flat_map(|(commit, _)| &commit.ops),
11096                                )
11097                                .chain(
11098                                    self.outbox
11099                                        .iter()
11100                                        .take(index)
11101                                        .flat_map(|commit| &commit.ops),
11102                                )
11103                                .chain(operations.iter().take(op_index + 1))
11104                            {
11105                                if op.table != operation.table || op.row_id != operation.row_id {
11106                                    continue;
11107                                }
11108                                if let Some(values) = &op.values {
11109                                    intended.extend(values.clone());
11110                                } else {
11111                                    scope_image = intended.clone();
11112                                    intended.clear();
11113                                }
11114                            }
11115                            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)",
11116                                rusqlite::params![client_commit_id, op_index as i64, operation.table, operation.row_id, sequence,
11117                                    serde_json::to_string(&CommitOperation::from(operation)).map_err(|_| "sync.local_corrupt".to_owned())?,
11118                                    serde_json::to_string(if operation.upsert { &intended } else { &scope_image }).map_err(|_| "sync.local_corrupt".to_owned())?])
11119                                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11120                        }
11121                        let journal_results = results
11122                            .iter()
11123                            .map(|result| {
11124                                let op_index = match result {
11125                                    OpResult::Applied { op_index }
11126                                    | OpResult::Conflict { op_index, .. }
11127                                    | OpResult::Error { op_index, .. } => *op_index,
11128                                };
11129                                CommitOperationOutcome::Applied { op_index }
11130                            })
11131                            .collect::<Vec<_>>();
11132                        let outcome_status = if status == PushStatus::Applied {
11133                            CommitOutcomeStatus::Applied
11134                        } else {
11135                            CommitOutcomeStatus::Cached
11136                        };
11137                        let persisted = self
11138                            .persist_commit_outcome(
11139                                client_commit_id,
11140                                outcome_status,
11141                                &journal_results,
11142                                None,
11143                            )
11144                            .and_then(|()| self.delete_outbox_persisted(client_commit_id));
11145                        persisted?;
11146                        self.sync_needed = true;
11147                        batch.status = true;
11148                        batch.outcomes = true;
11149                    }
11150                    PushStatus::Rejected => {
11151                        if results.iter().any(|result| {
11152                            matches!(
11153                                result,
11154                                OpResult::Error {
11155                                    code,
11156                                    retryable: true,
11157                                    ..
11158                                } if code == "sync.idempotency_cache_miss"
11159                            )
11160                        }) {
11161                            // §6.3/§7.2: a serving failure, not an outcome — keep the
11162                            // exact commit queued for an identical retry.
11163                            report.retryable.push(client_commit_id.to_owned());
11164                            continue;
11165                        }
11166
11167                        let mut journal_results = Vec::with_capacity(results.len());
11168                        let mut conflicts = Vec::new();
11169                        let mut rejections = Vec::new();
11170                        for result in results {
11171                            match result {
11172                                OpResult::Applied { op_index } => {
11173                                    journal_results.push(CommitOperationOutcome::Applied {
11174                                        op_index: *op_index,
11175                                    });
11176                                }
11177                                OpResult::Conflict {
11178                                    op_index,
11179                                    code,
11180                                    message,
11181                                    server_version,
11182                                    server_row,
11183                                    conflict_columns: conflict_columns_bitmap,
11184                                } => {
11185                                    let operation = operations
11186                                        .get(*op_index as usize)
11187                                        .map(CommitOperation::from);
11188                                    let (table, row_id) = operation
11189                                        .as_ref()
11190                                        .map(|op| (op.table.clone(), op.row_id.clone()))
11191                                        .unwrap_or_default();
11192                                    let server_row_json = self
11193                                        .schema
11194                                        .table(&table)
11195                                        .and_then(|t| {
11196                                            decode_row_bytes(t, server_row, &self.encryption)
11197                                                .ok()
11198                                                .map(|(row, _)| (t, row))
11199                                        })
11200                                        .map(|(t, row)| {
11201                                            let mut map = Map::new();
11202                                            for (i, column) in t.columns.iter().enumerate() {
11203                                                map.insert(
11204                                                    column.name.clone(),
11205                                                    column_value_to_json(
11206                                                        row.get(i).unwrap_or(&None),
11207                                                    ),
11208                                                );
11209                                            }
11210                                            map
11211                                        })
11212                                        .unwrap_or_default();
11213                                    // §6.3: decode the presence-layout bitmap
11214                                    // into the marked column names.
11215                                    let conflict_columns = self
11216                                        .schema
11217                                        .table(&table)
11218                                        .map(|t| {
11219                                            t.columns
11220                                                .iter()
11221                                                .enumerate()
11222                                                .filter(|(index, _)| {
11223                                                    conflict_columns_bitmap
11224                                                        .get(index / 8)
11225                                                        .is_some_and(|byte| {
11226                                                            byte & (1 << (index % 8)) != 0
11227                                                        })
11228                                                })
11229                                                .map(|(_, column)| column.name.clone())
11230                                                .collect::<Vec<_>>()
11231                                        })
11232                                        .unwrap_or_default();
11233                                    let conflict = ConflictRecord {
11234                                        client_commit_id: client_commit_id.to_owned(),
11235                                        op_index: *op_index,
11236                                        table,
11237                                        row_id,
11238                                        code: code.clone(),
11239                                        message: message.clone(),
11240                                        server_version: *server_version,
11241                                        server_row: server_row_json,
11242                                        conflict_columns,
11243                                        operation,
11244                                    };
11245                                    journal_results.push(CommitOperationOutcome::Conflict {
11246                                        conflict: conflict.clone(),
11247                                    });
11248                                    conflicts.push(conflict);
11249                                }
11250                                OpResult::Error {
11251                                    op_index,
11252                                    code,
11253                                    message,
11254                                    retryable,
11255                                } => {
11256                                    let rejection = RejectionRecord {
11257                                        client_commit_id: client_commit_id.to_owned(),
11258                                        op_index: *op_index,
11259                                        code: code.clone(),
11260                                        message: message.clone(),
11261                                        retryable: *retryable,
11262                                        details: rejection_details
11263                                            .and_then(|details| details.get(op_index))
11264                                            .cloned(),
11265                                        operation: operations
11266                                            .get(*op_index as usize)
11267                                            .map(CommitOperation::from),
11268                                    };
11269                                    journal_results.push(CommitOperationOutcome::Error {
11270                                        rejection: rejection.clone(),
11271                                    });
11272                                    rejections.push(rejection);
11273                                }
11274                            }
11275                        }
11276                        if self.retain_failed_commits {
11277                            self.retain_failed_commit(client_commit_id, &operations)?;
11278                        }
11279                        let outcome_status = if conflicts.is_empty() {
11280                            CommitOutcomeStatus::Rejected
11281                        } else {
11282                            CommitOutcomeStatus::Conflict
11283                        };
11284                        self.leave_through(client_commit_id);
11285                        let persisted = self
11286                            .persist_commit_outcome(
11287                                client_commit_id,
11288                                outcome_status,
11289                                &journal_results,
11290                                Some(&operations),
11291                            )
11292                            .and_then(|()| self.delete_outbox_persisted(client_commit_id));
11293                        persisted?;
11294                        batch.conflicts = !conflicts.is_empty();
11295                        batch.rejections = !rejections.is_empty();
11296                        batch.status = true;
11297                        batch.outcomes = true;
11298                        self.conflicts.extend(conflicts);
11299                        self.rejections.extend(rejections);
11300                    }
11301                }
11302                drained.push(self.outbox.remove(index));
11303                if batch.status {
11304                    for operation in &operations {
11305                        if !self.record_row_scopes(
11306                            &mut batch,
11307                            &operation.table,
11308                            &operation.row_id,
11309                            false,
11310                        ) {
11311                            batch.table(&operation.table);
11312                        }
11313                    }
11314                }
11315                match status {
11316                    PushStatus::Applied | PushStatus::Cached => {
11317                        report.applied.push(client_commit_id.to_owned())
11318                    }
11319                    PushStatus::Rejected => report.rejected.push(client_commit_id.to_owned()),
11320                }
11321            }
11322            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)) {
11323                self.prune_commit_outcomes()?;
11324            }
11325            self.reconcile_rows(&drained)?;
11326            self.rebuild_overlay_if_dirty()?;
11327            self.finish_observation("syncular_push_results", batch)
11328        })();
11329        if let Err(error) = persisted {
11330            self.rollback_observation("syncular_push_results");
11331            self.restore(rollback);
11332            report.applied.truncate(applied_count);
11333            report.rejected.truncate(rejected_count);
11334            report.retryable.truncate(retryable_count);
11335            return Err(error);
11336        }
11337        if !rollback.sync_needed && self.sync_needed {
11338            self.sync_intent_queue.push_back(SyncIntent::Interactive);
11339        }
11340        report.conflicts += (self.conflicts.len() - conflict_count) as u32;
11341        Ok(())
11342    }
11343
11344    fn push_result_is_final(status: PushStatus, results: &[OpResult]) -> bool {
11345        status != PushStatus::Rejected
11346            || !results.iter().any(|result| {
11347                matches!(
11348                    result,
11349                    OpResult::Error {
11350                        code,
11351                        retryable: true,
11352                        ..
11353                    } if code == "sync.idempotency_cache_miss"
11354                )
11355            })
11356    }
11357
11358    // -- unit sections and the live section ------------------------------------------
11359
11360    /// One unit section (§4.4): apply its segments, then persist its
11361    /// `SUB_END` (§4.6 reset, §3.3 revocation and purge, the echo, cursor and
11362    /// resume token). A section of a unit the app released while the round was
11363    /// in flight is skipped; a fail-closed first page fails the unit and skips
11364    /// the rest of its section (§5.6). Returns whether its `SUB_END` completed
11365    /// a bootstrap (§7.7).
11366    fn process_section(
11367        &mut self,
11368        transport: &mut dyn Transport,
11369        start: &SectionStart,
11370        body: Vec<Frame>,
11371        sub_end: Option<(i64, Option<String>)>,
11372        meta: &RequestMeta,
11373        report: &mut SyncReport,
11374    ) -> Result<bool, SectionError> {
11375        let storage = |message| SectionError::Abort("storage.failed".to_owned(), message);
11376        let unit = self
11377            .stored(get_unit(&self.conn, &start.id))
11378            .map_err(storage)?
11379            .filter(|unit| unit.status == UnitStatus::Active);
11380        // §7.7: a section boundary ends the previous payload; the section's
11381        // UNIT_EXTENT starts the unit counters in the same snapshot.
11382        let extent = match (&unit, body.first()) {
11383            (
11384                Some(_),
11385                Some(Frame::UnitExtent {
11386                    rows_total,
11387                    rows_done,
11388                }),
11389            ) => u64::try_from(*rows_total)
11390                .ok()
11391                .zip(u64::try_from(*rows_done).ok()),
11392            _ => None,
11393        };
11394        self.progress.update(|p| {
11395            p.phase = ProgressPhase::Import;
11396            p.unit_id = unit.as_ref().map(|unit| unit.id.clone());
11397            p.unit_rows_total = extent.map(|(total, _)| total);
11398            p.unit_rows_processed = extent.map(|(_, done)| done);
11399            p.table = None;
11400            p.segment_id = None;
11401            p.bytes_received = 0;
11402            p.bytes_total = None;
11403            p.rows_processed = 0;
11404            p.rows_total = None;
11405            p.import_write_ms = None;
11406            p.import_commit_ms = None;
11407            p.download_ms = None;
11408        });
11409        let Some(unit) = unit else {
11410            return Ok(false);
11411        };
11412        let echo: Vec<EchoRecord> = start
11413            .fenced
11414            .iter()
11415            .map(|record| EchoRecord {
11416                table: record.table.clone(),
11417                status: record.status.name().to_owned(),
11418                scopes: record.scopes.iter().cloned().collect(),
11419            })
11420            .collect();
11421        // §5.6: rows earlier attempts at this position applied.
11422        let applied_record = self
11423            .stored(applied_rows(&self.conn, &unit.id))
11424            .map_err(storage)?;
11425        // §5.6: a resumed bootstrap keeps the tables it already seeded.
11426        let mut seeded: BTreeSet<String> = if unit.bootstrap_state.is_none() {
11427            BTreeSet::new()
11428        } else {
11429            unit.seeded.iter().cloned().collect()
11430        };
11431        let applied = (|| {
11432            for frame in body {
11433                match frame {
11434                    Frame::SegmentInline { payload } => {
11435                        let segment = decode_rows_segment(&payload).map_err(|e| {
11436                            SectionError::Abort(e.code.as_str().to_owned(), e.detail)
11437                        })?;
11438                        self.progress.update(|p| {
11439                            p.phase = ProgressPhase::Import;
11440                            p.unit_id = Some(unit.id.clone());
11441                            p.table = Some(segment.table.clone());
11442                            p.segment_id = None;
11443                            p.bytes_received = payload.len() as u64;
11444                            p.bytes_total = Some(payload.len() as u64);
11445                            p.rows_processed = 0;
11446                            p.rows_total =
11447                                Some(segment.blocks.iter().map(|block| block.len() as u64).sum());
11448                            p.import_write_ms = None;
11449                            p.import_commit_ms = None;
11450                            p.download_ms = None;
11451                        });
11452                        let (pair, clear, effective) =
11453                            self.segment_pair(&unit, &echo, &seeded, &segment.table)?;
11454                        report.segment_rows_applied +=
11455                            self.apply_segment(&pair, &segment, clear, &effective, &unit.id)?;
11456                        seeded.insert(segment.table);
11457                    }
11458                    Frame::SegmentRef {
11459                        segment_id,
11460                        byte_length,
11461                        media_type,
11462                        table,
11463                        row_count,
11464                        as_of_commit_seq,
11465                        scope_digest,
11466                        row_cursor,
11467                        next_row_cursor,
11468                        url,
11469                        url_expires_at_ms,
11470                        ..
11471                    } => {
11472                        // §4.2: reject a descriptor whose mediaType was not
11473                        // advertised — never skip or guess.
11474                        let advertised = match media_type {
11475                            MediaType::Rows => {
11476                                meta.accept & ACCEPT_EXTERNAL_ROWS != 0
11477                                    || meta.accept & ACCEPT_INLINE_ROWS != 0
11478                            }
11479                            MediaType::Sqlite => meta.accept & ACCEPT_SQLITE != 0,
11480                        };
11481                        if !advertised {
11482                            return Err(SectionError::Abort(
11483                                "sync.invalid_request".to_owned(),
11484                                format!(
11485                                    "SEGMENT_REF mediaType {} was not advertised in accept (§4.2)",
11486                                    media_type.name()
11487                                ),
11488                            ));
11489                        }
11490                        // §5.6 applied-segment rule: a partly applied image
11491                        // already ran its table's first-page clear.
11492                        let resumed = applied_record.get(&segment_id).copied();
11493                        if resumed.is_some() {
11494                            seeded.insert(table.clone());
11495                        }
11496                        if resumed == Some(row_count) {
11497                            // §7.7: an earlier attempt imported this payload;
11498                            // its rows still count toward the unit.
11499                            self.progress.update(|p| {
11500                                p.phase = ProgressPhase::Import;
11501                                p.unit_id = Some(unit.id.clone());
11502                                p.table = Some(table.clone());
11503                                p.segment_id = Some(segment_id.clone());
11504                                p.bytes_received = 0;
11505                                p.bytes_total = None;
11506                                p.rows_processed = 0;
11507                                p.rows_total = u64::try_from(row_count).ok();
11508                                p.import_write_ms = None;
11509                                p.import_commit_ms = None;
11510                                p.download_ms = None;
11511                            });
11512                            self.progress.update(|p| {
11513                                p.rows_processed = u64::try_from(row_count).unwrap_or(0)
11514                            });
11515                            continue;
11516                        }
11517                        if meta
11518                            .deferred
11519                            .contains(&(unit.id.clone(), segment_id.clone()))
11520                        {
11521                            return Err(SectionError::Deferred);
11522                        }
11523                        self.progress.update(|p| {
11524                            p.phase = ProgressPhase::Download;
11525                            p.unit_id = Some(unit.id.clone());
11526                            p.table = Some(table.clone());
11527                            p.segment_id = Some(segment_id.clone());
11528                            p.bytes_received = 0;
11529                            p.bytes_total = u64::try_from(byte_length).ok();
11530                            p.rows_processed = 0;
11531                            p.rows_total = u64::try_from(row_count).ok();
11532                            p.import_write_ms = None;
11533                            p.import_commit_ms = None;
11534                            p.download_ms = None;
11535                        });
11536                        let observer = self.progress.clone();
11537                        let mut on_progress = |bytes| observer.update(|p| p.bytes_received = bytes);
11538                        // §7.7: from the request's start to its last body byte.
11539                        let requested = std::time::Instant::now();
11540                        let bytes = if let Some(url) = url {
11541                            // §5.4: a url-carrying descriptor MUST be fetched
11542                            // from that URL; failure invalidates the whole
11543                            // descriptor (no fall-through to §5.5 — re-pull
11544                            // recovers, §1.4 rule 5).
11545                            if meta.accept & ACCEPT_SIGNED_URLS == 0 {
11546                                return Err(SectionError::Abort(
11547                                    "sync.invalid_request".to_owned(),
11548                                    "SEGMENT_REF carries a url but accept bit 3 was not advertised (§5.4)"
11549                                        .to_owned(),
11550                                ));
11551                            }
11552                            // §5.4: MUST NOT start a fetch at/past expiry.
11553                            if url_expires_at_ms.is_some_and(|exp| {
11554                                exp <= transport
11555                                    .segment_fetch_started_at(&url)
11556                                    .unwrap_or_else(|| self.clock_now_ms())
11557                            }) {
11558                                return Err(SectionError::Abort(
11559                                    "sync.segment_expired".to_owned(),
11560                                    format!(
11561                                        "signed URL for segment {segment_id} expired before fetch — re-pull mints fresh descriptors (§5.4)"
11562                                    ),
11563                                ));
11564                            }
11565                            transport
11566                                .fetch_url(
11567                                    &url,
11568                                    u64::try_from(byte_length).unwrap_or(0),
11569                                    &mut on_progress,
11570                                )
11571                                .map_err(|e| self.segment_fetch_failed(e))?
11572                        } else {
11573                            // §5.5: the owning unit's scope map, each value a one-element list.
11574                            let requested_scopes_json =
11575                                canonical_scope_json(&unit_scope_lists(&unit.scopes));
11576                            transport
11577                                .download_segment(
11578                                    &SegmentRequest {
11579                                        segment_id: segment_id.clone(),
11580                                        table: table.clone(),
11581                                        requested_scopes_json,
11582                                        byte_length: u64::try_from(byte_length).unwrap_or(0),
11583                                    },
11584                                    &mut on_progress,
11585                                )
11586                                .map_err(|e| {
11587                                    // §5.5: access changed since the response;
11588                                    // the next round's SUB_START settles the unit.
11589                                    if e.code == "sync.forbidden" {
11590                                        SectionError::Refused
11591                                    } else {
11592                                        self.segment_fetch_failed(e)
11593                                    }
11594                                })?
11595                        };
11596                        let download_ms = u64::try_from(requested.elapsed().as_millis()).ok();
11597                        // §5.4: the descriptor's byteLength caps the body before
11598                        // §5.1 verifies the content address; the client discards
11599                        // the segment and re-pulls on either failure.
11600                        if bytes.len() as i64 > byte_length {
11601                            self.schedule_background_retry();
11602                            return Err(SectionError::Abort(
11603                                "sync.invalid_request".to_owned(),
11604                                "segment exceeds its byteLength".to_owned(),
11605                            ));
11606                        }
11607                        on_progress(bytes.len() as u64);
11608                        let digest = Sha256::digest(&bytes);
11609                        let expected = segment_id
11610                            .strip_prefix("sha256:")
11611                            .unwrap_or(segment_id.as_str());
11612                        if bytes_to_hex(&digest) != expected {
11613                            // §5.1: the client discards the segment and re-pulls.
11614                            self.schedule_background_retry();
11615                            return Err(SectionError::Abort(
11616                                "sync.invalid_request".to_owned(),
11617                                "segment bytes do not match the content address (§5.1)".to_owned(),
11618                            ));
11619                        }
11620                        self.progress.update(|p| {
11621                            p.phase = ProgressPhase::Import;
11622                            p.download_ms = download_ms;
11623                        });
11624                        if media_type == MediaType::Sqlite {
11625                            // §5.3: a range image keeps its position in the resume
11626                            // token; a descriptor row cursor is invalid.
11627                            if row_cursor.is_some() || next_row_cursor.is_some() {
11628                                return Err(SectionError::Abort(
11629                                    "sync.invalid_request".to_owned(),
11630                                    "sqlite segments are whole-table: rowCursor/nextRowCursor must be absent (§5.3)"
11631                                        .to_owned(),
11632                                ));
11633                            }
11634                            let (pair, clear, effective) =
11635                                self.segment_pair(&unit, &echo, &seeded, &table)?;
11636                            report.segment_rows_applied += self.apply_sqlite_segment(
11637                                &pair,
11638                                &bytes,
11639                                clear,
11640                                &effective,
11641                                &unit.id,
11642                                &segment_id,
11643                                resumed.unwrap_or(0),
11644                                row_count,
11645                                as_of_commit_seq,
11646                                &scope_digest,
11647                            )?;
11648                            seeded.insert(table);
11649                        } else {
11650                            let segment = decode_rows_segment(&bytes).map_err(|e| {
11651                                SectionError::Abort(e.code.as_str().to_owned(), e.detail)
11652                            })?;
11653                            let (pair, clear, effective) =
11654                                self.segment_pair(&unit, &echo, &seeded, &segment.table)?;
11655                            report.segment_rows_applied +=
11656                                self.apply_segment(&pair, &segment, clear, &effective, &unit.id)?;
11657                            seeded.insert(segment.table);
11658                            // An image records its rows with each chunk.
11659                            self.stored(record_applied_rows(
11660                                &self.conn,
11661                                &unit.id,
11662                                &segment_id,
11663                                row_count,
11664                            ))
11665                            .map_err(storage)?;
11666                        }
11667                    }
11668                    Frame::UnitExtent { .. } => {}
11669                    _ => {
11670                        return Err(SectionError::Abort(
11671                            "sync.invalid_request".to_owned(),
11672                            "unexpected frame inside a unit section".to_owned(),
11673                        ));
11674                    }
11675                }
11676            }
11677            Ok(())
11678        })();
11679        match applied {
11680            Ok(()) => {}
11681            // The unit keeps catching up with its cursor unpersisted.
11682            Err(SectionError::Refused | SectionError::Deferred) => return Ok(false),
11683            Err(SectionError::FailClosed) => {
11684                // §5.6: the failure is unit-local; the rest of the response
11685                // still applies and the failed unit leaves the list.
11686                self.begin_observation("syncular_section_failure")
11687                    .map_err(storage)?;
11688                let failed = (|| {
11689                    let mut batch = ChangeAccumulator::default();
11690                    self.record_unit_windows(&mut batch, &unit)?;
11691                    batch.status = true;
11692                    self.stored(save_unit(
11693                        &self.conn,
11694                        &UnitRecord {
11695                            status: UnitStatus::Failed,
11696                            reason_code: Some("sync.scope_revoked".to_owned()),
11697                            restriction: None,
11698                            ..unit.clone()
11699                        },
11700                    ))?;
11701                    self.finish_observation("syncular_section_failure", batch)
11702                })();
11703                if let Err(message) = failed {
11704                    self.rollback_observation("syncular_section_failure");
11705                    return Err(storage(message));
11706                }
11707                report.failed.push(unit.id);
11708                return Ok(false);
11709            }
11710            Err(error) => return Err(error),
11711        }
11712        let Some((next_cursor, bootstrap_state)) = sub_end else {
11713            return Ok(false);
11714        };
11715        let completes = start.bootstrap && bootstrap_state.is_none();
11716        let rollback = self.capture();
11717        let counts = (
11718            report.resets.len(),
11719            report.revoked.len(),
11720            report.failed.len(),
11721        );
11722        self.begin_observation("syncular_sub_end")
11723            .map_err(storage)?;
11724        let finished = self
11725            .finish_section(start, echo, next_cursor, bootstrap_state, seeded, report)
11726            .and_then(|batch| {
11727                self.rebuild_overlay_if_dirty()?;
11728                self.finish_observation("syncular_sub_end", batch)
11729            });
11730        if let Err(message) = finished {
11731            self.rollback_observation("syncular_sub_end");
11732            self.restore(rollback);
11733            report.resets.truncate(counts.0);
11734            report.revoked.truncate(counts.1);
11735            report.failed.truncate(counts.2);
11736            return Err(storage(message));
11737        }
11738        Ok(completes)
11739    }
11740
11741    /// §5.6: the table, first-page flag and effective scopes of one segment
11742    /// of `unit`'s section. A first page outside the unit's restriction ends it.
11743    #[allow(clippy::type_complexity)]
11744    fn segment_pair(
11745        &self,
11746        unit: &UnitRecord,
11747        echo: &[EchoRecord],
11748        seeded: &BTreeSet<String>,
11749        name: &str,
11750    ) -> Result<(TableSchema, bool, Vec<(String, Vec<String>)>), SectionError> {
11751        let table = self.schema.table(name).cloned().ok_or_else(|| {
11752            SectionError::Abort(
11753                "sync.schema_mismatch".to_owned(),
11754                format!("segment table {name:?} is not in the client schema"),
11755            )
11756        })?;
11757        let effective = covers(&table, &unit.scopes)
11758            .then(|| pair_scopes(&unit.scopes, name, Some(echo)))
11759            .flatten()
11760            .ok_or_else(|| {
11761                SectionError::Abort(
11762                    "sync.invalid_request".to_owned(),
11763                    "a segment names no active pair of its unit".to_owned(),
11764                )
11765            })?;
11766        let first_page = !seeded.contains(name);
11767        // §5.6: a first page of a table outside the restriction is a whole
11768        // bootstrap from a server that predates RESTRICT; the restriction ends
11769        // before the clear runs.
11770        if first_page
11771            && unit
11772                .restriction
11773                .as_ref()
11774                .is_some_and(|restriction| !restriction.tables.iter().any(|t| t == name))
11775        {
11776            self.conn
11777                .execute(
11778                    "UPDATE _syncular_units SET restriction=NULL WHERE id=?1",
11779                    [&unit.id],
11780                )
11781                .map_err(|error| {
11782                    SectionError::Abort(
11783                        "storage.failed".to_owned(),
11784                        Self::sqlite_failure(&self.storage_failure, error),
11785                    )
11786                })?;
11787        }
11788        Ok((table, first_page, effective))
11789    }
11790
11791    /// §4.4 `SUB_END` of an active, revoked or reset section, inside the
11792    /// caller's observation: a reset discards cursor, resume token and
11793    /// first-page record and keeps the echo; a revoked pair purges by its last
11794    /// echo (§3.3); otherwise the echo replaces the persisted one, a revoked
11795    /// fenced record that turns active again re-bootstraps the unit, and a
11796    /// bootstrap section persists its pin, resume token and seeded tables.
11797    fn finish_section(
11798        &mut self,
11799        start: &SectionStart,
11800        echo: Vec<EchoRecord>,
11801        next_cursor: i64,
11802        bootstrap_state: Option<String>,
11803        seeded: BTreeSet<String>,
11804        report: &mut SyncReport,
11805    ) -> Result<ChangeAccumulator, String> {
11806        #[cfg(feature = "bench-internals")]
11807        let _phase = self.benchmark_phases.start(Phase::CursorPersist);
11808        let mut batch = ChangeAccumulator::default();
11809        // §4.4: SUB_END writes only into a unit that is still registered.
11810        let Some(unit) = self
11811            .stored(get_unit(&self.conn, &start.id))?
11812            .filter(|unit| unit.status == UnitStatus::Active)
11813        else {
11814            return Ok(batch);
11815        };
11816        self.record_unit_windows(&mut batch, &unit)?;
11817        if start.status == SubStatus::Reset {
11818            // §4.6: staleness, never a purge; the rows stay until the
11819            // bootstrap replaces them.
11820            report.resets.push(unit.id.clone());
11821            self.stored(save_unit(
11822                &self.conn,
11823                &UnitRecord {
11824                    reason_code: Some(start.reason_code.clone()),
11825                    cursor: Some(-1),
11826                    bootstrap_state: None,
11827                    seeded: Vec::new(),
11828                    restriction: None,
11829                    ..unit
11830                },
11831            ))?;
11832            return Ok(batch);
11833        }
11834        let revoked = start.status == SubStatus::Revoked;
11835        let mut units = None;
11836        let mut failed = false;
11837        let mut rearmed = false;
11838        for table in self.schema.tables.clone() {
11839            if !covers(&table, &unit.scopes) {
11840                continue;
11841            }
11842            let last = unit
11843                .echo
11844                .as_deref()
11845                .and_then(|last| pair_scopes(&unit.scopes, &table.name, Some(last)));
11846            let next = (!revoked)
11847                .then(|| pair_scopes(&unit.scopes, &table.name, Some(&echo)))
11848                .flatten();
11849            // §3.3: a revoked fenced record that turns active again re-bootstraps.
11850            rearmed |= unit.echo.is_some() && last.is_none() && next.is_some();
11851            // §3.3: purge a pair the response revokes, keyed on the echo the
11852            // client persisted while the pair was active.
11853            if let (Some(last), None) = (&last, &next) {
11854                let units = match units {
11855                    Some(ref units) => units,
11856                    None => units.insert(self.stored(load_units(&self.conn))?),
11857                };
11858                let owners = unit_owners(units, &table, &unit.id);
11859                failed |= !self.purge_pair(&mut batch, &table, last, &owners)?;
11860            }
11861        }
11862        if revoked || failed {
11863            if revoked {
11864                report.revoked.push(unit.id.clone());
11865            }
11866            if failed {
11867                report.failed.push(unit.id.clone());
11868            }
11869            batch.status = true;
11870            self.stored(save_unit(
11871                &self.conn,
11872                &UnitRecord {
11873                    status: if failed {
11874                        UnitStatus::Failed
11875                    } else {
11876                        UnitStatus::Revoked
11877                    },
11878                    reason_code: Some(if failed {
11879                        "sync.scope_revoked".to_owned()
11880                    } else {
11881                        start.reason_code.clone()
11882                    }),
11883                    cursor: Some(-1),
11884                    bootstrap_state: None,
11885                    seeded: Vec::new(),
11886                    echo: None,
11887                    restriction: None,
11888                    ..unit
11889                },
11890            ))?;
11891            return Ok(batch);
11892        }
11893        // §3.3: the server accepted the unit, so a later refusal re-arms once.
11894        self.window_armed.remove(&unit.id);
11895        let completed = start.bootstrap && !rearmed && bootstrap_state.is_none();
11896        let (cursor, bootstrap_state, seeded) = if rearmed {
11897            (Some(-1), None, Vec::new())
11898        } else if start.bootstrap {
11899            let seeded = if bootstrap_state.is_none() {
11900                Vec::new()
11901            } else {
11902                seeded.into_iter().collect()
11903            };
11904            (Some(next_cursor), bootstrap_state, seeded)
11905        } else {
11906            (
11907                unit.cursor,
11908                unit.bootstrap_state.clone(),
11909                unit.seeded.clone(),
11910            )
11911        };
11912        self.stored(save_unit(
11913            &self.conn,
11914            &UnitRecord {
11915                reason_code: None,
11916                echo: Some(echo.clone()),
11917                cursor,
11918                bootstrap_state,
11919                seeded,
11920                // §7.4.3: the restriction ends when the unit re-bootstraps or
11921                // completes its bootstrap.
11922                restriction: unit.restriction.clone().filter(|_| !rearmed && !completed),
11923                ..unit.clone()
11924            },
11925        ))?;
11926        if !completed {
11927            return Ok(batch);
11928        }
11929        // §7.1: a completed bootstrap covers acknowledged intent of its pairs
11930        // at or below its pin. The intent or the bootstrapped row proves the
11931        // pair: a patch omits its scope columns, and the base row it merged
11932        // over may be gone (a §7.4.4 reset before the ACK).
11933        for table in self.schema.tables.clone() {
11934            let Some(effective) = covers(&table, &unit.scopes)
11935                .then(|| pair_scopes(&unit.scopes, &table.name, Some(&echo)))
11936                .flatten()
11937            else {
11938                continue;
11939            };
11940            let mut statement = self
11941                .conn
11942                .prepare("SELECT id,intent_json FROM _syncular_acked_rows WHERE tbl=?1 AND commit_seq<=?2")
11943                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11944            let rows = statement
11945                .query_map(rusqlite::params![table.name, next_cursor], |row| {
11946                    Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
11947                })
11948                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11949            let mut covered = HashSet::new();
11950            for row in rows {
11951                let (id, intent) =
11952                    row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11953                let values: Map<String, Value> =
11954                    serde_json::from_str(&intent).map_err(|_| "sync.local_corrupt".to_owned())?;
11955                let base = self.stored_row(&table, &id, true)?.map(|(row, _)| {
11956                    table
11957                        .columns
11958                        .iter()
11959                        .zip(&row)
11960                        .map(|(column, value)| (column.name.clone(), column_value_to_json(value)))
11961                        .collect()
11962                });
11963                if [Some(values), base]
11964                    .iter()
11965                    .flatten()
11966                    .any(|values| owns_local_row(&table, &effective, &[], values))
11967                {
11968                    covered.insert(id);
11969                }
11970            }
11971            drop(statement);
11972            for id in covered {
11973                self.conn
11974                    .execute(
11975                        "DELETE FROM _syncular_acked_rows WHERE tbl=?1 AND id=?2 AND commit_seq<=?3",
11976                        rusqlite::params![table.name, id, next_cursor],
11977                    )
11978                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11979                self.overlay_dirty.table(&table.name);
11980                batch.table(&table.name);
11981            }
11982        }
11983        Ok(batch)
11984    }
11985
11986    /// §3.3: purge one revoked pair inside the caller's observation: delete
11987    /// the rows matching its last effective scopes that no owner holds, drop
11988    /// the retained intent and every pending commit that provably writes into
11989    /// them, and delete now-unauthorized blob bodies. `Ok(false)` when the
11990    /// table has no local scope-column mapping (fail closed: nothing deleted).
11991    fn purge_pair(
11992        &mut self,
11993        batch: &mut ChangeAccumulator,
11994        table: &TableSchema,
11995        last: &[(String, Vec<String>)],
11996        owners: &[Vec<(String, Vec<String>)>],
11997    ) -> Result<bool, String> {
11998        if local_scope_predicate(table, last, owners).is_err() {
11999            return Ok(false);
12000        }
12001        for commit in self.drop_failed_commits(|name, values| {
12002            name == table.name && owns_local_row(table, last, owners, values)
12003        })? {
12004            batch.conflicts = true;
12005            batch.rejections = true;
12006            batch.outcomes = true;
12007            for operation in commit.ops {
12008                batch.table(&operation.table);
12009            }
12010        }
12011        if !self.purge_scope_rows(&table.name, last, owners)? {
12012            return Err("storage.failed: the revoked scope purge failed".to_owned());
12013        }
12014        self.record_scope_map(batch, &table.name, last);
12015        if self.drop_doomed_outbox(table, last, owners)? {
12016            batch.status = true;
12017            batch.rejections = true;
12018            batch.outcomes = true;
12019        }
12020        // §5.9.7 B2: revocation deletes now-unauthorized blob bodies.
12021        self.delete_unreferenced_cached_blobs()?;
12022        Ok(true)
12023    }
12024
12025    /// §4.5 client application: apply one live-section or delta `COMMIT`
12026    /// with only the changes that match the persisted echo of a receiving
12027    /// unit; every applied change then goes through the version guard.
12028    /// Returns whether any change of the frame applied.
12029    fn apply_live_commit(
12030        &mut self,
12031        receivers: &[UnitRecord],
12032        tables: &[String],
12033        changes: Vec<ssp2::model::Change>,
12034        commit_seq: i64,
12035        source: AppliedServerCommitSource,
12036    ) -> Result<bool, TransportError> {
12037        let changes: Vec<ssp2::model::Change> = changes
12038            .into_iter()
12039            .filter(|change| {
12040                // An unknown table fails loud in the apply below.
12041                let Some(table) = tables
12042                    .get(change.table_index as usize)
12043                    .and_then(|name| self.schema.table(name))
12044                else {
12045                    return true;
12046                };
12047                receivers.iter().any(|unit| {
12048                    covers(table, &unit.scopes)
12049                        && pair_scopes(&unit.scopes, &table.name, unit.echo.as_deref()).is_some_and(
12050                            |scopes| {
12051                                scopes.iter().all(|(variable, values)| {
12052                                    change
12053                                        .scopes
12054                                        .iter()
12055                                        .find(|(key, _)| key == variable)
12056                                        .is_some_and(|(_, value)| values.contains(value))
12057                                })
12058                            },
12059                        )
12060                })
12061            })
12062            .collect();
12063        if changes.is_empty() {
12064            return Ok(false);
12065        }
12066        let affected_tables = changes
12067            .iter()
12068            .filter_map(|change| tables.get(change.table_index as usize))
12069            .cloned()
12070            .collect::<BTreeSet<_>>();
12071        let previous_batches = self.change_queue.len();
12072        self.apply_commit_frame(tables, &changes, commit_seq)?;
12073        if self.change_queue.len() > previous_batches {
12074            if let Some(batch) = self.change_queue.back_mut() {
12075                batch
12076                    .applied_commits
12077                    .extend(
12078                        affected_tables
12079                            .into_iter()
12080                            .map(|table| AppliedServerCommit {
12081                                table,
12082                                commit_seq,
12083                                source,
12084                            }),
12085                    );
12086            }
12087        }
12088        Ok(true)
12089    }
12090
12091    // Both pull and realtime frames use the same durable observation boundary.
12092    fn apply_commit_frame(
12093        &mut self,
12094        tables: &[String],
12095        changes: &[ssp2::model::Change],
12096        sequence: i64,
12097    ) -> Result<(), TransportError> {
12098        #[cfg(feature = "bench-internals")]
12099        let _phase = self.benchmark_phases.start(Phase::CommitApply);
12100        let rollback = self.capture();
12101        self.coalesce_unit(changes.len())
12102            .and_then(|()| self.begin_observation("syncular_commit"))
12103            .map_err(|message| TransportError::new("storage.failed", message))?;
12104        let applied = (|| {
12105            let mut batch = ChangeAccumulator::default();
12106            self.record_commit_changes(&mut batch, tables, changes);
12107            // §7.1 chained base: a change names the version an acknowledged own
12108            // commit wrote; pending upserts chained on it move to that version.
12109            for change in changes {
12110                let Some(table) = tables.get(change.table_index as usize) else {
12111                    continue;
12112                };
12113                let acknowledged = self
12114                    .conn
12115                    .prepare_cached("SELECT op_json FROM _syncular_acked_rows WHERE tbl=?1 AND id=?2 AND commit_seq=?3")
12116                    .and_then(|mut statement| {
12117                        statement
12118                            .query_map(rusqlite::params![table, change.row_id, sequence], |row| row.get::<_, String>(0))?
12119                            .collect::<Result<Vec<_>, _>>()
12120                    })
12121                    .map_err(|error| TransportError::new("storage.failed", Self::sqlite_failure(&self.storage_failure, error)))?
12122                    .iter()
12123                    .map(|op| serde_json::from_str::<CommitOperation>(op).map(OutboxOp::from))
12124                    .collect::<Result<Vec<_>, _>>()
12125                    .map_err(|_| TransportError::new("storage.failed", "sync.local_corrupt: invalid acknowledged operation".to_owned()))?;
12126                for index in 0..self.outbox.len() {
12127                    if !self.outbox[index]
12128                        .ops
12129                        .iter()
12130                        .any(|op| acknowledged.iter().any(|earlier| chains_on(earlier, op)))
12131                    {
12132                        continue;
12133                    }
12134                    let commit = Arc::make_mut(&mut self.outbox[index]);
12135                    for op in &mut commit.ops {
12136                        if acknowledged.iter().any(|earlier| chains_on(earlier, op)) {
12137                            op.base_version = Some(change.row_version);
12138                        }
12139                    }
12140                    let ops = serde_json::to_string(
12141                        &commit
12142                            .ops
12143                            .iter()
12144                            .map(CommitOperation::from)
12145                            .collect::<Vec<_>>(),
12146                    )
12147                    .map_err(|_| {
12148                        TransportError::new(
12149                            "storage.failed",
12150                            "sync.local_corrupt: unencodable outbox".to_owned(),
12151                        )
12152                    })?;
12153                    let id = commit.client_commit_id.clone();
12154                    self.conn
12155                        .execute(
12156                            "UPDATE _syncular_outbox SET ops_json=?1 WHERE commit_id=?2",
12157                            rusqlite::params![ops, id],
12158                        )
12159                        .map_err(|error| {
12160                            TransportError::new(
12161                                "storage.failed",
12162                                Self::sqlite_failure(&self.storage_failure, error),
12163                            )
12164                        })?;
12165                }
12166            }
12167            {
12168                let storage_failed = |error| {
12169                    TransportError::new(
12170                        "storage.failed",
12171                        Self::sqlite_failure(&self.storage_failure, error),
12172                    )
12173                };
12174                let pinned: HashSet<(&str, &str)> = self
12175                    .outbox
12176                    .iter()
12177                    .flat_map(|commit| &commit.ops)
12178                    .map(|op| (op.table.as_str(), op.row_id.as_str()))
12179                    .collect();
12180                for change in changes {
12181                    let table = tables.get(change.table_index as usize).ok_or_else(|| {
12182                        TransportError::new(
12183                            "sync.invalid_request",
12184                            "change tableIndex out of range".to_owned(),
12185                        )
12186                    })?;
12187                    if pinned.contains(&(table.as_str(), change.row_id.as_str())) {
12188                        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)")
12189                            .and_then(|mut statement| statement.execute(rusqlite::params![table, change.row_id, sequence]))
12190                            .map_err(storage_failed)?;
12191                    }
12192                    self.conn.prepare_cached("DELETE FROM _syncular_acked_rows WHERE tbl=?1 AND id=?2 AND commit_seq<=?3")
12193                        .and_then(|mut statement| statement.execute(rusqlite::params![table, change.row_id, sequence]))
12194                        .map_err(storage_failed)?;
12195                }
12196            }
12197            self.apply_commit_changes(tables, changes)?;
12198            self.rebuild_overlay_if_dirty()
12199                .map_err(|message| TransportError::new("storage.failed", message))?;
12200            self.finish_observation("syncular_commit", batch)
12201                .map_err(|message| TransportError::new("storage.failed", message))
12202        })();
12203        if applied.is_err() {
12204            self.rollback_observation("syncular_commit");
12205            self.restore(rollback);
12206        }
12207        applied
12208    }
12209
12210    fn apply_commit_changes(
12211        &mut self,
12212        tables: &[String],
12213        changes: &[ssp2::model::Change],
12214    ) -> Result<(), TransportError> {
12215        // A clean overlay can reconcile changed primary keys independently
12216        // when their tables have no secondary unique constraints. Such a
12217        // constraint can change whether another row's write succeeds, so a
12218        // table with one and any local intent takes the table rebuild.
12219        let changed_tables: BTreeSet<&str> = changes
12220            .iter()
12221            .filter_map(|change| tables.get(change.table_index as usize))
12222            .map(String::as_str)
12223            .collect();
12224        let mut mirror_visible = !self.overlay_dirty.get();
12225        for name in &changed_tables {
12226            if mirror_visible
12227                && self
12228                    .schema
12229                    .table(name)
12230                    .is_some_and(|table| table.indexes.iter().any(|index| index.unique))
12231            {
12232                let (pending, protected) = self
12233                    .table_intent(name)
12234                    .map_err(|message| TransportError::new("storage.failed", message))?;
12235                mirror_visible = !pending && !protected;
12236            }
12237        }
12238        for change in changes {
12239            let table_name = tables.get(change.table_index as usize).ok_or_else(|| {
12240                TransportError::new(
12241                    "sync.invalid_request",
12242                    "change tableIndex out of range".to_owned(),
12243                )
12244            })?;
12245            let table = self.schema.table(table_name).ok_or_else(|| {
12246                TransportError::new(
12247                    "sync.schema_mismatch",
12248                    format!("change targets unknown table {table_name:?}"),
12249                )
12250            })?;
12251            let landed = match change.op {
12252                Op::Upsert => {
12253                    let payload = change.row.as_ref().ok_or_else(|| {
12254                        TransportError::new(
12255                            "sync.invalid_request",
12256                            "upsert change without row payload".to_owned(),
12257                        )
12258                    })?;
12259                    // §5.11: decrypt encrypted columns on apply, or seal the row.
12260                    let (row, sealed) = {
12261                        #[cfg(feature = "bench-internals")]
12262                        let _phase = self.benchmark_phases.start(Phase::RowDecode);
12263                        // §5.11: a decrypt failure keeps its own identity.
12264                        decode_row_bytes(table, payload, &self.encryption)?
12265                    };
12266                    let table_name = table.name.clone();
12267                    // §4.5 version guard: only a newer upsert lands.
12268                    let landed = self
12269                        .write_base_row(&table_name, &row, change.row_version, sealed.as_ref())
12270                        .map_err(|m| TransportError::new("sync.invalid_request", m))?;
12271                    if mirror_visible && landed {
12272                        self.write_row(
12273                            &visible_table(&table_name),
12274                            &table_name,
12275                            &row,
12276                            change.row_version,
12277                            sealed.as_ref(),
12278                        )
12279                        .map_err(|m| TransportError::new("sync.invalid_request", m))?;
12280                    }
12281                    landed
12282                }
12283                // §4.5 version guard: a delete at or below the local version
12284                // is skipped, a delete of an absent row is a no-op.
12285                Op::Delete => self
12286                    .delete_base_row(table_name, &change.row_id, change.row_version)
12287                    .map_err(|m| TransportError::new("sync.invalid_request", m))?,
12288            };
12289            // The change dropped the row's acknowledged intent either way
12290            // (§7.1), so the overlay of a skipped change rebuilds from the
12291            // unchanged base.
12292            self.overlay_dirty.table(table_name);
12293            if mirror_visible && !(landed && change.op == Op::Upsert) {
12294                let predicate = row_id_predicate(table);
12295                let visible = visible_table(table_name);
12296                let mut statements = vec![format!("DELETE FROM {visible} WHERE {predicate}")];
12297                if !landed {
12298                    statements.push(format!(
12299                        "INSERT INTO {visible} SELECT * FROM {} WHERE {predicate}",
12300                        base_table(table_name)
12301                    ));
12302                }
12303                for statement in &statements {
12304                    self.conn
12305                        .prepare_cached(statement)
12306                        .and_then(|mut statement| {
12307                            statement.execute(rusqlite::params![change.row_id])
12308                        })
12309                        .map_err(|error| {
12310                            TransportError::new("sync.invalid_request", error.to_string())
12311                        })?;
12312                }
12313            }
12314        }
12315        if mirror_visible {
12316            let changed_rows: HashSet<(&str, &str)> = changes
12317                .iter()
12318                .map(|change| {
12319                    (
12320                        tables[change.table_index as usize].as_str(),
12321                        change.row_id.as_str(),
12322                    )
12323                })
12324                .collect();
12325            self.replay_overlay(&changed_tables, Some(&changed_rows))
12326                .map_err(|message| TransportError::new("storage.failed", message))?;
12327            self.overlay_dirty.set(false);
12328        }
12329        Ok(())
12330    }
12331
12332    /// §5.6 segment application: validate against the generated schema,
12333    /// clear the pair's scope on the table's first page (fail closed
12334    /// without a mapping), then upsert each row with its segment-carried
12335    /// server version under the §4.5 version guard (§5.2).
12336    fn apply_segment(
12337        &mut self,
12338        table: &TableSchema,
12339        segment: &RowsSegment,
12340        first_page: bool,
12341        effective: &[(String, Vec<String>)],
12342        unit_id: &str,
12343    ) -> Result<u32, SectionError> {
12344        // §5.2: the column table validates against the generated schema —
12345        // order, names, types, nullability; mismatch is fatal. §5.11: the
12346        // server sends the WIRE types (bytes for an encrypted column), so
12347        // validate against wire_columns.
12348        let column = if segment.columns.len() != table.wire_columns.len() {
12349            Some(Value::from("count"))
12350        } else {
12351            segment
12352                .columns
12353                .iter()
12354                .zip(table.wire_columns.iter())
12355                .position(|(a, b)| a.name != b.name || a.ty != b.ty || a.nullable != b.nullable)
12356                .map(Value::from)
12357        };
12358        if segment.table != table.name
12359            || segment.schema_version != self.schema.version
12360            || column.is_some()
12361        {
12362            let mut details = Map::new();
12363            details.insert("table".to_owned(), Value::from(table.name.as_str()));
12364            if let Some(column) = column {
12365                details.insert("column".to_owned(), column);
12366            }
12367            return Err(SectionError::Transport(TransportError {
12368                code: "sync.schema_mismatch".to_owned(),
12369                message: "rows segment columns do not match the generated schema (§5.2)".to_owned(),
12370                details: Some(Value::Object(details)),
12371            }));
12372        }
12373        let mut applied = 0u32;
12374        let (mut write, mut commit) = (std::time::Duration::ZERO, std::time::Duration::ZERO);
12375        let empty = Vec::new();
12376        let blocks = if segment.blocks.is_empty() {
12377            std::slice::from_ref(&empty)
12378        } else {
12379            &segment.blocks
12380        };
12381        for (index, block) in blocks.iter().enumerate() {
12382            let clear = first_page && index == 0;
12383            if !clear && block.is_empty() {
12384                continue;
12385            }
12386            let rollback = self.capture();
12387            let (pending, protected) = self
12388                .table_intent(&table.name)
12389                .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12390            let reconcile_pending =
12391                !protected && pending && table.indexes.iter().any(|index| index.unique);
12392            let mirror_visible = !protected && !reconcile_pending;
12393            self.coalesce_unit(block.len())
12394                .and_then(|()| self.begin_observation("syncular_segment_block"))
12395                .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12396            let started = std::time::Instant::now();
12397            let outcome = (|| {
12398                self.rebuild_overlay_if_dirty()
12399                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12400                let mut changed_keys = Vec::new();
12401                let mut batch = ChangeAccumulator::default();
12402                if clear && self.clear_scope(table, effective, unit_id)? || !block.is_empty() {
12403                    batch.table(&table.name);
12404                }
12405                for (row_index, row) in block.iter().enumerate() {
12406                    let decrypted;
12407                    let mut sealed = None;
12408                    let values = if table.has_encrypted_columns() {
12409                        let mut values = row.values.clone();
12410                        sealed = crate::values::decrypt_segment_row(
12411                            table,
12412                            &mut values,
12413                            &self.encryption,
12414                        )
12415                        .map_err(SectionError::Transport)?;
12416                        decrypted = values;
12417                        &decrypted
12418                    } else {
12419                        &row.values
12420                    };
12421                    if !self
12422                        .write_base_row(&table.name, values, row.server_version, sealed.as_ref())
12423                        .map_err(|message| {
12424                            SectionError::Abort("sync.invalid_request".into(), message)
12425                        })?
12426                    {
12427                        continue;
12428                    }
12429                    if reconcile_pending {
12430                        changed_keys.push(
12431                            owned_sql_value(RowParam::Cell(&values[table.pk_index])).map_err(
12432                                |message| SectionError::Abort("storage.failed".into(), message),
12433                            )?,
12434                        );
12435                    }
12436                    if mirror_visible {
12437                        self.write_row(
12438                            &visible_table(&table.name),
12439                            &table.name,
12440                            values,
12441                            row.server_version,
12442                            sealed.as_ref(),
12443                        )
12444                        .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12445                    }
12446                    let processed = u64::from(applied) + row_index as u64 + 1;
12447                    if processed.is_multiple_of(1024) {
12448                        self.progress.update(|p| p.rows_processed = processed);
12449                    }
12450                }
12451                self.reconcile_import(table, &mut changed_keys, protected, reconcile_pending)
12452                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12453                let written = std::time::Instant::now();
12454                self.finish_observation("syncular_segment_block", batch)
12455                    .map(|()| written)
12456                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))
12457            })();
12458            let written = match outcome {
12459                Ok(written) => written,
12460                Err(error) => {
12461                    self.rollback_observation("syncular_segment_block");
12462                    self.restore(rollback);
12463                    return Err(error);
12464                }
12465            };
12466            // §7.7: a payload reports its import cost.
12467            write += written - started;
12468            commit += written.elapsed();
12469            applied += block.len() as u32;
12470            self.progress.update(|p| {
12471                p.rows_processed = u64::from(applied);
12472                p.import_write_ms = u64::try_from(write.as_millis()).ok();
12473                p.import_commit_ms = u64::try_from(commit.as_millis()).ok();
12474            });
12475            std::thread::yield_now();
12476        }
12477        self.progress
12478            .update(|p| p.rows_processed = u64::from(applied));
12479        Ok(applied)
12480    }
12481
12482    /// §5.3 sqlite-image application: validate the in-file metadata
12483    /// against the descriptor, validate column names/order against the
12484    /// generated schema, run the §5.6 first-page clear when fresh, then
12485    /// replace-or-upsert every image row with its `_syncular_version`.
12486    /// Mechanics: the image lands in a temp file read through a second
12487    /// rusqlite connection, equivalent to ATTACH + INSERT…SELECT.
12488    /// Each image chunk commits its writes and revision before readers continue.
12489    #[allow(clippy::too_many_arguments)]
12490    fn apply_sqlite_segment(
12491        &mut self,
12492        table: &TableSchema,
12493        bytes: &[u8],
12494        first_page: bool,
12495        effective: &[(String, Vec<String>)],
12496        unit_id: &str,
12497        segment_id: &str,
12498        resumed: i64,
12499        row_count: i64,
12500        as_of_commit_seq: i64,
12501        scope_digest: &str,
12502    ) -> Result<u32, SectionError> {
12503        let invalid = |detail: &str| {
12504            SectionError::Abort(
12505                "sync.invalid_request".to_owned(),
12506                format!("sqlite segment rejected: {detail} (§5.3)"),
12507            )
12508        };
12509        // §5.11: an image bypasses the decrypt seam, so a server cannot serve
12510        // one for a table with encrypted columns.
12511        if table.has_encrypted_columns() {
12512            return Err(invalid("table has encrypted columns"));
12513        }
12514
12515        // The image lands beside the replica so it shares the replica's
12516        // directory permissions and volume; an in-memory replica has no
12517        // directory and uses the system temp dir. The file is owner-only.
12518        let directory = self
12519            .previous_version_replica_path()
12520            .and_then(|replica| std::path::Path::new(&replica).parent().map(Into::into))
12521            .unwrap_or_else(std::env::temp_dir);
12522        let path = directory.join(format!(".syncular-image-{}.tmp", uuid::Uuid::new_v4()));
12523        let outcome = (|| {
12524            let mut options = std::fs::OpenOptions::new();
12525            options.write(true).create_new(true);
12526            #[cfg(unix)]
12527            std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
12528            std::io::Write::write_all(
12529                &mut options
12530                    .open(&path)
12531                    .map_err(|_| invalid("image temp file write failed"))?,
12532                bytes,
12533            )
12534            .map_err(|_| invalid("image temp file write failed"))?;
12535            let img = rusqlite::Connection::open_with_flags(
12536                &path,
12537                rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
12538            )
12539            .map_err(|_| invalid("bytes do not open as a SQLite database"))?;
12540            self.apply_sqlite_image(
12541                &img,
12542                table,
12543                first_page,
12544                effective,
12545                unit_id,
12546                segment_id,
12547                resumed,
12548                row_count,
12549                as_of_commit_seq,
12550                scope_digest,
12551            )
12552        })();
12553        let _ = std::fs::remove_file(&path);
12554        outcome
12555    }
12556
12557    #[allow(clippy::too_many_arguments)]
12558    fn apply_sqlite_image(
12559        &mut self,
12560        img: &rusqlite::Connection,
12561        table: &crate::schema::TableSchema,
12562        first_fresh_page: bool,
12563        effective: &[(String, Vec<String>)],
12564        unit_id: &str,
12565        segment_id: &str,
12566        resumed: i64,
12567        row_count: i64,
12568        as_of_commit_seq: i64,
12569        scope_digest: &str,
12570    ) -> Result<u32, SectionError> {
12571        let invalid = |detail: String| {
12572            SectionError::Abort(
12573                "sync.invalid_request".to_owned(),
12574                format!("sqlite segment rejected: {detail} (§5.3)"),
12575            )
12576        };
12577
12578        // 1. Metadata vs descriptor + client state (§5.3 rule 2; exactly
12579        //    one row).
12580        type MetaRow = (i64, String, i64, i64, String, i64, i64);
12581        let meta: MetaRow = img
12582            .query_row(
12583                "SELECT format, \"table\", \"schemaVersion\", \"asOfCommitSeq\",
12584                        \"scopeDigest\", \"rowCount\",
12585                        (SELECT count(*) FROM _syncular_segment)
12586                 FROM _syncular_segment",
12587                [],
12588                |row| {
12589                    Ok((
12590                        row.get(0)?,
12591                        row.get(1)?,
12592                        row.get(2)?,
12593                        row.get(3)?,
12594                        row.get(4)?,
12595                        row.get(5)?,
12596                        row.get(6)?,
12597                    ))
12598                },
12599            )
12600            .map_err(|_| invalid("missing or unreadable _syncular_segment metadata".to_owned()))?;
12601        let (format, meta_table, schema_version, pin, digest, meta_rows, meta_count) = meta;
12602        if meta_count != 1 {
12603            return Err(invalid(format!(
12604                "_syncular_segment must contain exactly one row, found {meta_count}"
12605            )));
12606        }
12607        if format != 1 {
12608            return Err(invalid(format!("format {format}")));
12609        }
12610        if meta_table != table.name {
12611            return Err(invalid(format!("image table {meta_table:?}")));
12612        }
12613        if schema_version != i64::from(self.schema.version) {
12614            return Err(invalid(format!("schemaVersion {schema_version}")));
12615        }
12616        if pin != as_of_commit_seq {
12617            return Err(invalid(format!("asOfCommitSeq {pin}")));
12618        }
12619        if digest != scope_digest {
12620            return Err(invalid("scopeDigest mismatch".to_owned()));
12621        }
12622        if meta_rows != row_count {
12623            return Err(invalid(format!("rowCount {meta_rows}")));
12624        }
12625
12626        // 2. Column names and order vs the generated schema (§5.3 rule 3).
12627        let mut names: Vec<String> = Vec::new();
12628        let mut primary_keys: Vec<String> = Vec::new();
12629        {
12630            let mut stmt = img
12631                .prepare(&format!("PRAGMA table_info({})", quote_ident(&table.name)))
12632                .map_err(|_| invalid("image data table missing".to_owned()))?;
12633            let mut rows = stmt
12634                .query([])
12635                .map_err(|_| invalid("image data table unreadable".to_owned()))?;
12636            while let Some(row) = rows
12637                .next()
12638                .map_err(|_| invalid("image data table unreadable".to_owned()))?
12639            {
12640                if row
12641                    .get::<_, i64>(5)
12642                    .map_err(|error| invalid(Self::sqlite_failure(&self.storage_failure, error)))?
12643                    > 0
12644                {
12645                    primary_keys.push(row.get(1).map_err(|error| {
12646                        invalid(Self::sqlite_failure(&self.storage_failure, error))
12647                    })?);
12648                }
12649                names.push(
12650                    row.get::<_, String>(1)
12651                        .map_err(|_| invalid("image data table unreadable".to_owned()))?,
12652                );
12653            }
12654        }
12655        let mut expected: Vec<&str> = table.columns.iter().map(|c| c.name.as_str()).collect();
12656        expected.push("_syncular_version");
12657        if names.len() != expected.len() || names.iter().zip(expected.iter()).any(|(a, b)| a != b) {
12658            return Err(SectionError::Transport(TransportError {
12659                code: "sync.schema_mismatch".to_owned(),
12660                message: "sqlite segment columns do not match the generated schema (§5.3)"
12661                    .to_owned(),
12662                details: Some(serde_json::json!({ "table": table.name })),
12663            }));
12664        }
12665
12666        if primary_keys != vec![table.primary_key.clone()] {
12667            return Err(invalid(
12668                "image primary key does not match generated schema".into(),
12669            ));
12670        }
12671        let actual_count: i64 = img
12672            .query_row(
12673                &format!("SELECT count(*) FROM {}", quote_ident(&table.name)),
12674                [],
12675                |row| row.get(0),
12676            )
12677            .map_err(|error| invalid(Self::sqlite_failure(&self.storage_failure, error)))?;
12678        if actual_count != row_count {
12679            return Err(invalid("image row count does not match descriptor".into()));
12680        }
12681        let insert = self.insert_row_sql(&base_table(&table.name), table);
12682        let visible_insert = self.insert_row_sql(&visible_table(&table.name), table);
12683        let column_list = names
12684            .iter()
12685            .map(|n| quote_ident(n))
12686            .collect::<Vec<_>>()
12687            .join(", ");
12688        // §5.6: an earlier attempt at this position committed the first
12689        // `resumed` rows in primary-key order; the content address pins them.
12690        let mut stmt = img
12691            .prepare(&format!(
12692                "SELECT {column_list} FROM {} ORDER BY {} LIMIT -1 OFFSET ?1",
12693                quote_ident(&table.name),
12694                quote_ident(&table.primary_key)
12695            ))
12696            .map_err(|error| invalid(Self::sqlite_failure(&self.storage_failure, error)))?;
12697        let mut rows = stmt
12698            .query([resumed])
12699            .map_err(|error| invalid(Self::sqlite_failure(&self.storage_failure, error)))?;
12700        let resumed = u32::try_from(resumed)
12701            .ok()
12702            .filter(|rows| i64::from(*rows) <= actual_count)
12703            .ok_or_else(|| invalid("applied-segment record exceeds the image".into()))?;
12704        let mut applied = resumed;
12705        let mut limit = if first_fresh_page {
12706            1024
12707        } else {
12708            self.image_chunk_rows
12709                .get(&table.name)
12710                .copied()
12711                .unwrap_or(1024)
12712        };
12713        let (mut write, mut commit) = (std::time::Duration::ZERO, std::time::Duration::ZERO);
12714        // Rows, write ms and per-row write ms of the chunk before.
12715        let mut model: Option<(u32, f64, Option<f64>)> = None;
12716        loop {
12717            let clear = applied == 0 && first_fresh_page;
12718            let rollback = self.capture();
12719            let (pending, protected) = self
12720                .table_intent(&table.name)
12721                .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12722            let reconcile_pending =
12723                !protected && pending && table.indexes.iter().any(|index| index.unique);
12724            let mirror_visible = !protected && !reconcile_pending;
12725            // §5.3: a table's first chunk holds 1,024 rows; a later range image
12726            // starts at the size its previous range reached. A later chunk holds at
12727            // least 1,024 rows, at most twice the rows of the one before and at
12728            // most 65,536. The second chunk of an image holds twice the rows of
12729            // the first. The two latest chunks whose row counts differ by at
12730            // least half the smaller split write time into a per-row and a
12731            // fixed part; while sizes repeat, the last split's per-row time
12732            // holds. A later chunk then holds the rows whose per-row time fills
12733            // the larger of 250 ms, the time from the end of the writes of the
12734            // chunk before through its COMMIT, and the fixed part. A chunk that
12735            // replays local writes holds at most 1,024.
12736            let chunk = if pending || protected {
12737                limit.min(1024)
12738            } else {
12739                limit
12740            };
12741            self.coalesce_unit(chunk as usize)
12742                .and_then(|()| self.begin_observation("syncular_image_chunk"))
12743                .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12744            let started = std::time::Instant::now();
12745            let result = (|| {
12746                self.rebuild_overlay_if_dirty()
12747                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12748                let mut changed_keys = Vec::new();
12749                let mut batch = ChangeAccumulator::default();
12750                if clear && self.clear_scope(table, effective, unit_id)? {
12751                    batch.table(&table.name);
12752                }
12753                let mut processed = 0u32;
12754                {
12755                    let mut ins = self.conn.prepare_cached(&insert).map_err(|error| {
12756                        invalid(Self::sqlite_failure(&self.storage_failure, error))
12757                    })?;
12758                    let mut mirror = if mirror_visible {
12759                        Some(self.conn.prepare_cached(&visible_insert).map_err(|error| {
12760                            invalid(Self::sqlite_failure(&self.storage_failure, error))
12761                        })?)
12762                    } else {
12763                        None
12764                    };
12765                    for _ in 0..chunk {
12766                        let Some(row) = rows.next().map_err(|error| {
12767                            invalid(Self::sqlite_failure(&self.storage_failure, error))
12768                        })?
12769                        else {
12770                            break;
12771                        };
12772                        for (i, column) in table.columns.iter().enumerate() {
12773                            let cell = row.get_ref(i).map_err(|error| {
12774                                invalid(Self::sqlite_failure(&self.storage_failure, error))
12775                            })?;
12776                            let param = image_cell_param(column, cell).map_err(invalid)?;
12777                            ins.raw_bind_parameter(i + 1, &param).map_err(|error| {
12778                                invalid(Self::sqlite_failure(&self.storage_failure, error))
12779                            })?;
12780                            if let Some(mirror) = &mut mirror {
12781                                mirror.raw_bind_parameter(i + 1, &param).map_err(|error| {
12782                                    invalid(Self::sqlite_failure(&self.storage_failure, error))
12783                                })?;
12784                            }
12785                        }
12786                        let version_index = table.columns.len();
12787                        let version: i64 = row.get(version_index).map_err(|error| {
12788                            invalid(Self::sqlite_failure(&self.storage_failure, error))
12789                        })?;
12790                        if version < 1 {
12791                            return Err(invalid("image row version must be positive".into()));
12792                        }
12793                        ins.raw_bind_parameter(version_index + 1, version)
12794                            .map_err(|error| {
12795                                invalid(Self::sqlite_failure(&self.storage_failure, error))
12796                            })?;
12797                        // §4.5 version guard: the base upsert decides.
12798                        let landed = ins.raw_execute().map_err(|error| {
12799                            invalid(Self::sqlite_failure(&self.storage_failure, error))
12800                        })? > 0;
12801                        processed += 1;
12802                        if processed.is_multiple_of(1024) && processed < chunk {
12803                            self.progress
12804                                .update(|p| p.rows_processed = u64::from(applied + processed));
12805                        }
12806                        if !landed {
12807                            continue;
12808                        }
12809                        if let Some(mirror) = &mut mirror {
12810                            mirror
12811                                .raw_bind_parameter(version_index + 1, version)
12812                                .map_err(|error| {
12813                                    invalid(Self::sqlite_failure(&self.storage_failure, error))
12814                                })?;
12815                            mirror.raw_execute().map_err(|error| {
12816                                invalid(Self::sqlite_failure(&self.storage_failure, error))
12817                            })?;
12818                        }
12819                        if reconcile_pending {
12820                            changed_keys.push(row.get::<_, SqlValue>(table.pk_index).map_err(
12821                                |error| invalid(Self::sqlite_failure(&self.storage_failure, error)),
12822                            )?);
12823                        }
12824                    }
12825                }
12826                if processed > 0 {
12827                    batch.table(&table.name);
12828                    self.overlay_dirty.table(&table.name);
12829                }
12830                self.stored(record_applied_rows(
12831                    &self.conn,
12832                    unit_id,
12833                    segment_id,
12834                    i64::from(applied + processed),
12835                ))
12836                .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12837                self.reconcile_import(table, &mut changed_keys, protected, reconcile_pending)
12838                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12839                let written = std::time::Instant::now();
12840                self.finish_observation("syncular_image_chunk", batch)
12841                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12842                Ok((processed, written))
12843            })();
12844            let (processed, written) = match result {
12845                Ok(done) => done,
12846                Err(error) => {
12847                    self.rollback_observation("syncular_image_chunk");
12848                    self.restore(rollback);
12849                    return Err(error);
12850                }
12851            };
12852            // The chunk commits before the yield, also inside a coalesced apply.
12853            let coalesced = self.coalesced.is_some();
12854            if coalesced {
12855                self.commit_coalesced_apply()
12856                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12857            }
12858            let spent = (written - started, written.elapsed());
12859            #[cfg(test)]
12860            let spent = self
12861                .image_chunk_ms
12862                .get()
12863                .map_or(spent, |(fixed, row, commit)| {
12864                    (
12865                        std::time::Duration::from_secs_f64(
12866                            (fixed + row * f64::from(processed)) / 1000.0,
12867                        ),
12868                        std::time::Duration::from_secs_f64(commit / 1000.0),
12869                    )
12870                });
12871            write += spent.0;
12872            commit += spent.1;
12873            applied += processed;
12874            let last = processed < chunk || i64::from(applied) == actual_count;
12875            // A file replica's WAL keeps its high-water size until truncated.
12876            if last && self.conn.is_autocommit() {
12877                self.conn
12878                    .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
12879                    .map_err(|error| invalid(Self::sqlite_failure(&self.storage_failure, error)))?;
12880            }
12881            if coalesced {
12882                self.begin_coalesced_apply()
12883                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12884            }
12885            self.progress.update(|p| {
12886                p.rows_processed = u64::from(applied);
12887                p.import_write_ms = u64::try_from(write.as_millis()).ok();
12888                p.import_commit_ms = u64::try_from(commit.as_millis()).ok();
12889            });
12890            let write_ms = spent.0.as_secs_f64() * 1000.0;
12891            let per_row = match model {
12892                Some((rows, before, _)) if 2 * processed.abs_diff(rows) >= processed.min(rows) => {
12893                    Some((write_ms - before) / (f64::from(processed) - f64::from(rows)))
12894                }
12895                Some((_, _, per_row)) => per_row,
12896                None => None,
12897            };
12898            model = Some((processed, write_ms, per_row));
12899            let fixed = (write_ms - per_row.unwrap_or(0.0) * f64::from(processed)).max(0.0);
12900            let budget = (spent.1.as_secs_f64() * 1000.0).max(250.0).max(fixed);
12901            std::thread::yield_now();
12902            if last {
12903                break;
12904            }
12905            // Without a positive per-row time the chunk doubles.
12906            limit = (processed * 2)
12907                .min(65_536)
12908                .min(match per_row {
12909                    Some(per_row) if per_row > 0.0 => (budget / per_row) as u32,
12910                    _ => u32::MAX,
12911                })
12912                .max(1024);
12913            self.image_chunk_rows.insert(table.name.clone(), limit);
12914        }
12915        if i64::from(applied) != actual_count {
12916            return Err(invalid(format!(
12917                "image yielded {applied} rows, expected {actual_count}"
12918            )));
12919        }
12920        Ok(applied - resumed)
12921    }
12922
12923    /// §7.1 keyed reconciliation of the rows `drained` commits touch: restore
12924    /// them from the base and replay their remaining intent. A table with a
12925    /// secondary unique index restores and replays every row with intent,
12926    /// since one row's value can admit or defer another row's write.
12927    fn reconcile_rows(&self, drained: &[Arc<OutboxCommit>]) -> Result<(), String> {
12928        let names: BTreeSet<&str> = drained
12929            .iter()
12930            .flat_map(|commit| &commit.ops)
12931            .map(|op| op.table.as_str())
12932            .collect();
12933        for name in names {
12934            let Some(table) = self.schema.table(name) else {
12935                continue;
12936            };
12937            let ops = drained.iter().flat_map(|commit| &commit.ops);
12938            let tables = BTreeSet::from([name]);
12939            let rows: HashSet<_> = ops
12940                .clone()
12941                .map(|op| (op.table.as_str(), op.row_id.as_str()))
12942                .collect();
12943            let unique = table.indexes.iter().any(|index| index.unique);
12944            let acknowledged = if unique {
12945                self.acknowledged_operations(None, Some(&tables))?
12946            } else {
12947                Vec::new()
12948            };
12949            let peers = acknowledged
12950                .iter()
12951                .chain(
12952                    self.failed_commits
12953                        .iter()
12954                        .flat_map(|(commit, _)| &commit.ops),
12955                )
12956                .chain(self.outbox.iter().flat_map(|commit| &commit.ops))
12957                .filter(|_| unique);
12958            self.restore_base_rows(table, &mut Vec::new(), peers.chain(ops.clone()))?;
12959            self.replay_overlay(&tables, (!unique).then_some(&rows))?;
12960        }
12961        Ok(())
12962    }
12963
12964    /// Whether `table` has pending outbox intent, and whether it has protected
12965    /// (acknowledged or retained failed) intent.
12966    fn table_intent(&self, table: &str) -> Result<(bool, bool), String> {
12967        let touches = |op: &OutboxOp| op.table == table;
12968        Ok((
12969            self.outbox
12970                .iter()
12971                .flat_map(|commit| &commit.ops)
12972                .any(touches),
12973            self.failed_commits
12974                .iter()
12975                .flat_map(|(commit, _)| &commit.ops)
12976                .any(touches)
12977                || self
12978                    .conn
12979                    .query_row(
12980                        "SELECT EXISTS(SELECT 1 FROM _syncular_acked_rows WHERE tbl=?1)",
12981                        [table],
12982                        |row| row.get(0),
12983                    )
12984                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?,
12985        ))
12986    }
12987
12988    /// §7.1 reconciliation after an import block or chunk. Keyed replay covers
12989    /// only pending intent, so a table with protected intent rebuilds; a
12990    /// `restore` restores the imported `keys` and every pending row first.
12991    fn reconcile_import(
12992        &mut self,
12993        table: &TableSchema,
12994        keys: &mut Vec<SqlValue>,
12995        protected: bool,
12996        restore: bool,
12997    ) -> Result<(), String> {
12998        if protected {
12999            return self.rebuild_overlay_if_dirty();
13000        }
13001        let pending = self.outbox.iter().flat_map(|commit| &commit.ops);
13002        if restore {
13003            self.restore_base_rows(table, keys, pending.clone())?;
13004        }
13005        self.apply_outbox_ops(pending.filter(|op| op.table == table.name))?;
13006        self.overlay_dirty.set(false);
13007        Ok(())
13008    }
13009
13010    /// Restore the visible rows of `keys` and of the rows `ops` touch in
13011    /// `table` from the base before the caller replays their intent. The
13012    /// caller owns the transaction and publishes its revision after replay.
13013    fn restore_base_rows<'a>(
13014        &self,
13015        table: &TableSchema,
13016        keys: &mut Vec<SqlValue>,
13017        ops: impl IntoIterator<Item = &'a OutboxOp>,
13018    ) -> Result<(), String> {
13019        let visible = visible_table(&table.name);
13020        let base = base_table(&table.name);
13021        let pk = quote_ident(&table.primary_key);
13022        let predicate = row_id_predicate(table);
13023        let mut lookup = self.conn.prepare_cached(&format!(
13024            "SELECT {pk} FROM {base} WHERE {predicate} UNION SELECT {pk} FROM {visible} WHERE {predicate}"
13025        )).map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13026        let mut deleted = HashSet::new();
13027        for op in ops.into_iter().filter(|op| op.table == table.name) {
13028            if op.upsert {
13029                if let Some(values) = &op.values {
13030                    let key = json_to_column_value(
13031                        &table.columns[table.pk_index],
13032                        values.get(&table.primary_key),
13033                    )?;
13034                    keys.push(owned_sql_value(RowParam::Cell(&key))?);
13035                }
13036            } else if deleted.insert(&op.row_id) {
13037                keys.extend(
13038                    lookup
13039                        .query_map([&op.row_id], |row| row.get::<_, SqlValue>(0))
13040                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
13041                        .collect::<Result<Vec<_>, _>>()
13042                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?,
13043                );
13044            }
13045        }
13046        // Delete the complete affected set before restoring any base value, so
13047        // old optimistic unique values cannot collide with the new server rows.
13048        for chunk in keys.chunks(400) {
13049            let holes = vec!["?"; chunk.len()].join(",");
13050            self.conn
13051                .prepare_cached(&format!("DELETE FROM {visible} WHERE {pk} IN ({holes})"))
13052                .and_then(|mut statement| statement.execute(rusqlite::params_from_iter(chunk)))
13053                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13054        }
13055        let updates = table
13056            .columns
13057            .iter()
13058            .map(|column| column.name.as_str())
13059            .chain(std::iter::once("_syncular_version"))
13060            .chain(table.sealed_columns().iter().copied())
13061            .filter(|name| *name != table.primary_key)
13062            .map(|name| {
13063                let name = quote_ident(name);
13064                format!("{name}=excluded.{name}")
13065            })
13066            .collect::<Vec<_>>()
13067            .join(",");
13068        for chunk in keys.chunks(400) {
13069            let holes = vec!["?"; chunk.len()].join(",");
13070            self.conn.prepare_cached(&format!("INSERT INTO {visible} SELECT * FROM {base} WHERE {pk} IN ({holes}) ON CONFLICT ({pk}) DO UPDATE SET {updates}"))
13071                .and_then(|mut statement| statement.execute(rusqlite::params_from_iter(chunk)))
13072                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13073        }
13074        Ok(())
13075    }
13076
13077    // -- application-authorized local purge ---------------------------------------
13078
13079    fn compile_local_data_purge(
13080        &self,
13081        input: &LocalDataPurgeInput,
13082    ) -> Result<CompiledLocalDataPurge, String> {
13083        let invalid = |message: String| format!("sync.invalid_request: {message}");
13084        if input.purge_id.is_empty()
13085            || input.purge_id.len() > 128
13086            || !is_local_operation_code_like(&input.purge_id)
13087        {
13088            return Err(invalid(
13089                "local purge purgeId must be a 1–128 character code-like identifier".to_owned(),
13090            ));
13091        }
13092        if input.targets.is_empty() || input.targets.len() > MAX_LOCAL_PURGE_TARGETS {
13093            return Err(invalid(format!(
13094                "local purge needs between 1 and {MAX_LOCAL_PURGE_TARGETS} targets"
13095            )));
13096        }
13097
13098        let mut deduplicated: BTreeMap<
13099            String,
13100            (CompiledLocalDataPurgeTarget, LocalDataPurgeTarget),
13101        > = BTreeMap::new();
13102        let mut projections = BTreeSet::new();
13103        for target in &input.targets {
13104            let (table_name, raw_selectors) = match target {
13105                LocalDataPurgeTarget::Table { table, selectors } => (table, selectors),
13106                LocalDataPurgeTarget::Projection { projection } => {
13107                    projections.insert(projection.clone());
13108                    continue;
13109                }
13110            };
13111            let table = self.schema.table(table_name).ok_or_else(|| {
13112                invalid(format!("local purge names unknown table {:?}", table_name))
13113            })?;
13114            if raw_selectors.is_empty() || raw_selectors.len() > MAX_LOCAL_PURGE_SELECTORS {
13115                return Err(invalid(format!(
13116                    "local purge target {:?} needs between 1 and {MAX_LOCAL_PURGE_SELECTORS} selectors",
13117                    table_name
13118                )));
13119            }
13120            let mut selectors = Vec::with_capacity(raw_selectors.len());
13121            let mut canonical_selectors = BTreeMap::new();
13122            for (column_name, raw_values) in raw_selectors {
13123                let Some((column_index, column)) = table
13124                    .columns
13125                    .iter()
13126                    .enumerate()
13127                    .find(|(_, column)| column.name == *column_name)
13128                else {
13129                    return Err(invalid(format!(
13130                        "local purge target {:?} names unknown column {:?}",
13131                        table_name, column_name
13132                    )));
13133                };
13134                let encrypted = table
13135                    .encrypted_columns
13136                    .iter()
13137                    .any(|candidate| candidate.index == column_index);
13138                if column.ty != ColumnType::String || encrypted {
13139                    return Err(invalid(format!(
13140                        "local purge selector {:?}.{:?} must be a plaintext string column",
13141                        table_name, column_name
13142                    )));
13143                }
13144                if raw_values.is_empty() || raw_values.len() > MAX_LOCAL_PURGE_VALUES {
13145                    return Err(invalid(format!(
13146                        "local purge selector {:?}.{:?} needs between 1 and {MAX_LOCAL_PURGE_VALUES} values",
13147                        table_name, column_name
13148                    )));
13149                }
13150                let mut values = raw_values.clone();
13151                values.sort();
13152                values.dedup();
13153                if values.iter().any(|value| {
13154                    value.is_empty()
13155                        || value.len() > MAX_LOCAL_PURGE_VALUE_LENGTH
13156                        || !is_local_operation_code_like(value)
13157                }) {
13158                    return Err(invalid(format!(
13159                        "local purge selector values must be 1–{MAX_LOCAL_PURGE_VALUE_LENGTH} character code-like identifiers"
13160                    )));
13161                }
13162                selectors.push((column_name.clone(), values.clone()));
13163                canonical_selectors.insert(column_name.clone(), values);
13164            }
13165            let canonical = LocalDataPurgeTarget::Table {
13166                table: table_name.clone(),
13167                selectors: canonical_selectors,
13168            };
13169            let key = serde_json::to_string(&canonical).map_err(|error| error.to_string())?;
13170            deduplicated.insert(
13171                key,
13172                (
13173                    CompiledLocalDataPurgeTarget {
13174                        table: table_name.clone(),
13175                        selectors,
13176                    },
13177                    canonical,
13178                ),
13179            );
13180        }
13181        let (targets, mut canonical): (Vec<_>, Vec<_>) = deduplicated.into_values().unzip();
13182        canonical.extend(
13183            projections
13184                .iter()
13185                .map(|name| LocalDataPurgeTarget::Projection {
13186                    projection: name.clone(),
13187                }),
13188        );
13189        let canonical_plan =
13190            serde_json::to_string(&canonical).map_err(|error| error.to_string())?;
13191        Ok(CompiledLocalDataPurge {
13192            targets,
13193            projections,
13194            canonical_plan,
13195        })
13196    }
13197
13198    fn local_purge_base_row_ids(
13199        &self,
13200        targets: &[CompiledLocalDataPurgeTarget],
13201    ) -> Result<BTreeMap<String, BTreeSet<String>>, String> {
13202        let mut by_table: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
13203        for target in targets {
13204            let table = self
13205                .schema
13206                .table(&target.table)
13207                .ok_or_else(|| format!("sync.invalid_request: unknown table {:?}", target.table))?;
13208            let mut clauses = Vec::with_capacity(target.selectors.len());
13209            let mut params = Vec::new();
13210            for (column, values) in &target.selectors {
13211                clauses.push(format!(
13212                    "{} IN ({})",
13213                    quote_ident(column),
13214                    values.iter().map(|_| "?").collect::<Vec<_>>().join(", ")
13215                ));
13216                params.extend(values.iter().cloned().map(SqlValue::Text));
13217            }
13218            let sql = format!(
13219                "SELECT CAST({} AS TEXT) FROM {} WHERE {}",
13220                quote_ident(&table.primary_key),
13221                base_table(&target.table),
13222                clauses.join(" AND ")
13223            );
13224            let mut statement = self
13225                .conn
13226                .prepare(&sql)
13227                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13228            let rows = statement
13229                .query_map(rusqlite::params_from_iter(params), |row| {
13230                    let value = sql_ref_to_json(&table.columns[table.pk_index], row.get_ref(0)?);
13231                    render_row_id_json(Some(&value))
13232                        .map_err(|message| rusqlite::Error::ToSqlConversionFailure(message.into()))
13233                })
13234                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13235            let ids = by_table.entry(target.table.clone()).or_default();
13236            for row in rows {
13237                ids.insert(
13238                    row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?,
13239                );
13240            }
13241        }
13242        Ok(by_table)
13243    }
13244
13245    fn local_purge_values_match(
13246        target: &CompiledLocalDataPurgeTarget,
13247        values: &Map<String, Value>,
13248    ) -> bool {
13249        target.selectors.iter().all(|(column, allowed)| {
13250            values
13251                .get(column)
13252                .and_then(Value::as_str)
13253                .is_some_and(|value| allowed.iter().any(|candidate| candidate == value))
13254        })
13255    }
13256
13257    /// Apply one host-authorized local security purge. The host MUST gate the
13258    /// corresponding subscriptions first; this primitive owns local SQLite
13259    /// cleanup and never grants/revokes server authority by itself.
13260    pub fn purge_local_data(
13261        &mut self,
13262        input: &LocalDataPurgeInput,
13263    ) -> Result<LocalDataPurgeResult, ClientError> {
13264        let CompiledLocalDataPurge {
13265            targets,
13266            projections,
13267            canonical_plan,
13268        } = self.compile_local_data_purge(input)?;
13269        for name in &projections {
13270            self.lookup_projection(name)?;
13271        }
13272        let meta_key = format!("localPurge:{}", input.purge_id);
13273        let applied_plan = self
13274            .conn
13275            .query_row(
13276                "SELECT value FROM _syncular_meta WHERE key = ?1",
13277                rusqlite::params![meta_key],
13278                |row| row.get::<_, String>(0),
13279            )
13280            .optional()
13281            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13282        if let Some(applied_plan) = applied_plan {
13283            if applied_plan != canonical_plan {
13284                return Err(format!(
13285                    "sync.invalid_request: local purge id {:?} was already used with a different plan",
13286                    input.purge_id
13287                ).into());
13288            }
13289            // A retry after an unfinished rewrite finishes it.
13290            self.require_previous_version_gone()?;
13291            self.erase_purged_pages(&meta_key)?;
13292            return Ok(LocalDataPurgeResult {
13293                already_applied: true,
13294                purged_rows: 0,
13295                dropped_commits: 0,
13296            });
13297        }
13298
13299        // RFC 0005 D7: the container file cannot be a purge target (its name is
13300        // not in the running schema), so purge drops it as a fixed step, before
13301        // any mirror row is touched and unconditionally.
13302        let _ = self.drop_previous_version();
13303
13304        let rollback = self.capture();
13305        self.begin_observation("syncular_local_purge")?;
13306        let applied = (|| -> Result<(ChangeAccumulator, LocalDataPurgeResult), String> {
13307            let mut batch = ChangeAccumulator::default();
13308            let mut purged_rows = 0;
13309            for name in &projections {
13310                purged_rows += self.clear_projection(name, None)?;
13311                batch.table(name);
13312            }
13313            if targets.is_empty() {
13314                self.set_meta(&meta_key, &canonical_plan)?;
13315                return Ok((batch, LocalDataPurgeResult { already_applied: false, purged_rows, dropped_commits: 0 }));
13316            }
13317            let row_ids = self.local_purge_base_row_ids(&targets)?;
13318            let retained_dropped = self.drop_failed_commits(|table, values| {
13319                targets.iter().any(|target| {
13320                    target.table == table && Self::local_purge_values_match(target, values)
13321                })
13322            })?;
13323            let doomed = self
13324                .outbox
13325                .iter()
13326                .filter(|commit| {
13327                    commit.ops.iter().any(|operation| {
13328                        let matching_targets = targets
13329                            .iter()
13330                            .filter(|target| target.table == operation.table)
13331                            .collect::<Vec<_>>();
13332                        if matching_targets.is_empty() {
13333                            return false;
13334                        }
13335                        if row_ids
13336                            .get(&operation.table)
13337                            .is_some_and(|ids| ids.contains(&operation.row_id))
13338                        {
13339                            return true;
13340                        }
13341                        operation.values.as_ref().is_some_and(|values| {
13342                            matching_targets
13343                                .iter()
13344                                .any(|target| Self::local_purge_values_match(target, values))
13345                        })
13346                    })
13347                })
13348                .cloned()
13349                .collect::<Vec<_>>();
13350            let doomed_ids = doomed
13351                .iter()
13352                .map(|commit| commit.client_commit_id.clone())
13353                .collect::<BTreeSet<_>>();
13354            for commit in &retained_dropped {
13355                batch.conflicts = true;
13356                batch.rejections = true;
13357                batch.outcomes = true;
13358                for operation in &commit.ops {
13359                    batch.table(&operation.table);
13360                }
13361            }
13362            let mut rejections = Vec::new();
13363            // §5.11 purge erasure: the journal keeps a dropped commit's identity and
13364            // codes, never its operations, so no purged value survives in it.
13365            for commit in &doomed {
13366                for operation in &commit.ops {
13367                    batch.table(&operation.table);
13368                    self.overlay_dirty.table(&operation.table);
13369                }
13370                let results = (0..commit.ops.len())
13371                    .map(|op_index| {
13372                        let rejection = RejectionRecord {
13373                            client_commit_id: commit.client_commit_id.clone(),
13374                            op_index: op_index as i32,
13375                            code: "client.local_data_purged".to_owned(),
13376                            message: "the commit was dropped by an application-authorized local data purge".to_owned(),
13377                            retryable: false,
13378                            details: None,
13379                            operation: None,
13380                        };
13381                        rejections.push(rejection.clone());
13382                        CommitOperationOutcome::Error { rejection }
13383                    })
13384                    .collect::<Vec<_>>();
13385                self.persist_commit_outcome(
13386                    &commit.client_commit_id,
13387                    CommitOutcomeStatus::Rejected,
13388                    &results,
13389                    None,
13390                )?;
13391                self.leave_through(&commit.client_commit_id);
13392                self.delete_outbox_persisted(&commit.client_commit_id)?;
13393            }
13394            if !doomed.is_empty() {
13395                self.outbox
13396                    .retain(|commit| !doomed_ids.contains(&commit.client_commit_id));
13397                self.rejections.extend(rejections);
13398                self.prune_commit_outcomes()?;
13399                batch.status = true;
13400                batch.rejections = true;
13401                batch.outcomes = true;
13402            }
13403
13404            // §7.3.4: a unit whose cursor claims a purged row catches up from
13405            // -1, the §3.3 rule for rows a purge removed (§4.5 C1).
13406            for unit in self.stored(load_units(&self.conn))? {
13407                if unit.status != UnitStatus::Active
13408                    || (unit.cursor == Some(-1) && unit.bootstrap_state.is_none())
13409                {
13410                    continue;
13411                }
13412                let mut holds = false;
13413                for target in &targets {
13414                    let Some(table) = self.schema.table(&target.table) else {
13415                        continue;
13416                    };
13417                    let Some((scope, scope_params)) = covers(table, &unit.scopes)
13418                        .then(|| pair_scopes(&unit.scopes, &table.name, unit.echo.as_deref()))
13419                        .flatten()
13420                        .and_then(|effective| local_scope_predicate(table, &effective, &[]).ok().flatten())
13421                    else {
13422                        continue;
13423                    };
13424                    let clauses = target
13425                        .selectors
13426                        .iter()
13427                        .map(|(column, values)| {
13428                            format!("{} IN ({})", quote_ident(column), vec!["?"; values.len()].join(", "))
13429                        })
13430                        .collect::<Vec<_>>()
13431                        .join(" AND ");
13432                    let params = target
13433                        .selectors
13434                        .iter()
13435                        .flat_map(|(_, values)| values.iter().cloned().map(SqlValue::Text))
13436                        .chain(scope_params);
13437                    holds = self
13438                        .conn
13439                        .query_row(
13440                            &format!(
13441                                "SELECT 1 FROM {} WHERE {clauses} AND {scope} LIMIT 1",
13442                                base_table(&target.table)
13443                            ),
13444                            rusqlite::params_from_iter(params),
13445                            |_| Ok(()),
13446                        )
13447                        .optional()
13448                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
13449                        .is_some();
13450                    if holds {
13451                        break;
13452                    }
13453                }
13454                if holds {
13455                    self.record_unit_windows(&mut batch, &unit)?;
13456                    batch.status = true;
13457                    self.stored(save_unit(
13458                        &self.conn,
13459                        &UnitRecord {
13460                            cursor: Some(-1),
13461                            bootstrap_state: None,
13462                            seeded: Vec::new(),
13463                            restriction: None,
13464                            ..unit
13465                        },
13466                    ))?;
13467                }
13468            }
13469
13470            for (table, ids) in &row_ids {
13471                if ids.is_empty() {
13472                    continue;
13473                }
13474                batch.table(table);
13475                self.overlay_dirty.table(table);
13476                for row_id in ids {
13477                    self.delete_base_row(table, row_id, i64::MAX)?;
13478                    purged_rows += 1;
13479                }
13480            }
13481            // §5.11 purge erasure: a journaled outcome with an operation or
13482            // conflict row the purge reaches keeps its identity, status, ids
13483            // and codes only.
13484            let touches = |table: &str, row_id: &str, values: Option<&Map<String, Value>>| {
13485                targets.iter().any(|target| {
13486                    target.table == table
13487                        && (row_ids.get(table).is_some_and(|ids| ids.contains(row_id))
13488                            || values.is_some_and(|values| {
13489                                Self::local_purge_values_match(target, values)
13490                            }))
13491                })
13492            };
13493            let entries = self
13494                .conn
13495                .prepare("SELECT client_commit_id, results_json, operations_json FROM _syncular_commit_outcomes")
13496                .and_then(|mut statement| {
13497                    statement
13498                        .query_map([], |row| {
13499                            Ok((
13500                                row.get::<_, String>(0)?,
13501                                row.get::<_, String>(1)?,
13502                                row.get::<_, Option<String>>(2)?,
13503                            ))
13504                        })?
13505                        .collect::<Result<Vec<_>, _>>()
13506                })
13507                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13508            for (client_commit_id, results_json, operations_json) in entries {
13509                let corrupt = |_| "sync.local_corrupt: persisted commit outcome is invalid".to_owned();
13510                let mut results: Vec<CommitOperationOutcome> =
13511                    serde_json::from_str(&results_json).map_err(corrupt)?;
13512                let operations: Vec<CommitOperation> = operations_json
13513                    .map(|json| serde_json::from_str(&json))
13514                    .transpose()
13515                    .map_err(corrupt)?
13516                    .unwrap_or_default();
13517                let named = operations
13518                    .iter()
13519                    .chain(results.iter().filter_map(|result| match result {
13520                        CommitOperationOutcome::Conflict { conflict } => conflict.operation.as_ref(),
13521                        CommitOperationOutcome::Error { rejection } => rejection.operation.as_ref(),
13522                        CommitOperationOutcome::Applied { .. } => None,
13523                    }))
13524                    .any(|operation| touches(&operation.table, &operation.row_id, operation.values.as_ref()))
13525                    || results.iter().any(|result| {
13526                        matches!(result, CommitOperationOutcome::Conflict { conflict }
13527                            if touches(&conflict.table, &conflict.row_id, Some(&conflict.server_row)))
13528                    });
13529                if !named {
13530                    continue;
13531                }
13532                for result in &mut results {
13533                    match result {
13534                        CommitOperationOutcome::Conflict { conflict } => {
13535                            conflict.server_row = Map::new();
13536                            conflict.conflict_columns.clear();
13537                            conflict.operation = None;
13538                        }
13539                        CommitOperationOutcome::Error { rejection } => {
13540                            rejection.details = None;
13541                            rejection.operation = None;
13542                        }
13543                        CommitOperationOutcome::Applied { .. } => {}
13544                    }
13545                }
13546                let results_json = serde_json::to_string(&results).map_err(|error| error.to_string())?;
13547                self.conn
13548                    .execute(
13549                        "UPDATE _syncular_commit_outcomes SET results_json = ?1, operations_json = NULL WHERE client_commit_id = ?2",
13550                        rusqlite::params![results_json, client_commit_id],
13551                    )
13552                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13553                batch.outcomes = true;
13554            }
13555            self.rebuild_overlay_if_dirty()?;
13556            self.delete_unreferenced_cached_blobs()?;
13557            self.conn
13558                .execute(
13559                    "INSERT INTO _syncular_meta(key, value) VALUES (?1, ?2)",
13560                    rusqlite::params![meta_key, canonical_plan],
13561                )
13562                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13563            Ok((
13564                batch,
13565                LocalDataPurgeResult {
13566                    already_applied: false,
13567                    purged_rows,
13568                    dropped_commits: doomed.len(),
13569                },
13570            ))
13571        })()
13572        .and_then(|(batch, result)| {
13573            self.finish_observation("syncular_local_purge", batch)
13574                .map(|()| result)
13575        });
13576        let result = match applied {
13577            Ok(result) => result,
13578            Err(error) => {
13579                self.rollback_observation("syncular_local_purge");
13580                self.restore(rollback);
13581                return Err(error.into());
13582            }
13583        };
13584        self.cancel_sync_round();
13585        self.require_previous_version_gone()?;
13586        self.erase_purged_pages(&meta_key)?;
13587        Ok(result)
13588    }
13589
13590    /// §5.11: the previous-version container is a copy of earlier rows; its
13591    /// removal is best-effort elsewhere, so a container that survived the
13592    /// purge fails it before the erasure is recorded.
13593    fn require_previous_version_gone(&self) -> Result<(), String> {
13594        let Some(replica_path) = self.previous_version_replica_path() else {
13595            return Ok(());
13596        };
13597        let container = crate::previous_version::previous_version_container_path(&replica_path);
13598        if std::path::Path::new(&container).exists() {
13599            self.drop_previous_version()?;
13600        }
13601        if std::path::Path::new(&container).exists() {
13602            return Err(
13603                "client.storage_failure: the previous-version container survived the purge"
13604                    .to_owned(),
13605            );
13606        }
13607        Ok(())
13608    }
13609
13610    /// §5.11 purge erasure: SQLite leaves a deleted value in the freed pages of the
13611    /// database file, FTS5 keeps a deleted document's tokens in its index
13612    /// segments, and the WAL keeps the frames written before the purge, until
13613    /// each is rewritten. The FTS5 merge drops the deleted tokens, VACUUM
13614    /// rebuilds the file from the remaining rows, and the checkpoint truncates
13615    /// the WAL. The plan's completion marker follows the checkpoint, so only a
13616    /// finished rewrite lets a retry skip it.
13617    fn erase_purged_pages(&self, meta_key: &str) -> Result<(), String> {
13618        let marker = format!("{meta_key}:erased");
13619        let done = self.stored(
13620            self.conn
13621                .query_row(
13622                    "SELECT 1 FROM _syncular_meta WHERE key = ?1",
13623                    [&marker],
13624                    |_| Ok(()),
13625                )
13626                .optional(),
13627        )?;
13628        if done.is_some() {
13629            return Ok(());
13630        }
13631        let indexes: Vec<String> = self.stored(
13632            self.conn
13633                .prepare(
13634                    "SELECT name FROM sqlite_master WHERE type = 'table' AND sql LIKE 'CREATE VIRTUAL TABLE%USING fts5%'",
13635                )
13636                .and_then(|mut statement| {
13637                    statement
13638                        .query_map([], |row| row.get(0))?
13639                        .collect::<Result<Vec<String>, _>>()
13640                }),
13641        )?;
13642        let erased = self.stored(
13643            self.conn
13644                .execute_batch("PRAGMA secure_delete = ON;")
13645                .and_then(|()| {
13646                    for index in &indexes {
13647                        let name = quote_ident(index);
13648                        self.conn.execute_batch(&format!(
13649                            "INSERT INTO {name}({name}) VALUES('optimize');"
13650                        ))?;
13651                    }
13652                    self.conn.execute_batch("VACUUM;")
13653                })
13654                .and_then(|()| {
13655                    self.conn
13656                        .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| {
13657                            row.get::<_, bool>(0)
13658                        })
13659                }),
13660        );
13661        let reset = self.stored(self.conn.execute_batch("PRAGMA secure_delete = OFF"));
13662        if erased.and_then(|busy| reset.map(|()| busy))? {
13663            return Err("client.storage_busy: WAL checkpoint is busy".to_owned());
13664        }
13665        self.set_meta(&marker, "1")
13666    }
13667
13668    /// Application-authorized recovery of the replicated projection. Unlike a
13669    /// local security purge, this retains the entire outbox, device identity,
13670    /// lease, outcomes, unit registrations, and protected bookkeeping.
13671    /// The projection reset, unit rewind, optimistic replay, and
13672    /// idempotency marker share one savepoint for interruption safety.
13673    pub fn rebootstrap_local_data(
13674        &mut self,
13675        input: &LocalDataRebootstrapInput,
13676    ) -> Result<LocalDataRebootstrapResult, String> {
13677        if input.rebootstrap_id.is_empty()
13678            || input.rebootstrap_id.len() > 128
13679            || !is_local_operation_code_like(&input.rebootstrap_id)
13680        {
13681            return Err(
13682                "sync.invalid_request: local rebootstrap rebootstrapId must be a 1–128 character code-like identifier"
13683                    .to_owned(),
13684            );
13685        }
13686        let meta_key = format!("localRebootstrap:{}", input.rebootstrap_id);
13687        if let Some(persisted) = meta_get(&self.conn, &meta_key).map_err(|_| {
13688            "sync.local_corrupt: persisted local rebootstrap receipt is unreadable".to_owned()
13689        })? {
13690            let (retained_commits, reset_subscriptions) =
13691                decode_local_rebootstrap_receipt(&persisted)?;
13692            return Ok(LocalDataRebootstrapResult {
13693                already_applied: true,
13694                retained_commits,
13695                reset_subscriptions,
13696            });
13697        }
13698        if self.stopped || self.schema_floor.is_some() {
13699            return Err(
13700                "sync.invalid_request: local rebootstrap cannot bypass an active schema-floor stop; update the application first"
13701                    .to_owned(),
13702            );
13703        }
13704
13705        let retained_commits = self.outbox.len();
13706        let reset_subscriptions = self.stored(load_units(&self.conn))?.len();
13707        let receipt = encode_local_rebootstrap_receipt(retained_commits, reset_subscriptions)?;
13708        let rollback = self.capture();
13709        self.begin_observation("syncular_local_rebootstrap")?;
13710        let mut batch = ChangeAccumulator::default();
13711        let applied = (|| -> Result<(), String> {
13712            self.run_schema_reset_observed(&mut batch, false)?;
13713            self.conn
13714                .execute(
13715                    "INSERT INTO _syncular_meta(key, value) VALUES (?1, ?2)",
13716                    rusqlite::params![meta_key, receipt],
13717                )
13718                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13719            self.sync_needed = true;
13720            self.sync_intent_queue.push_back(SyncIntent::Interactive);
13721            batch.status = true;
13722            Ok(())
13723        })()
13724        .and_then(|()| self.finish_observation("syncular_local_rebootstrap", batch));
13725        if let Err(error) = applied {
13726            self.rollback_observation("syncular_local_rebootstrap");
13727            self.restore(rollback);
13728            return Err(error);
13729        }
13730        self.cancel_sync_round();
13731
13732        Ok(LocalDataRebootstrapResult {
13733            already_applied: false,
13734            retained_commits,
13735            reset_subscriptions,
13736        })
13737    }
13738
13739    // -- scope purge + doomed outbox (§3.3) ----------------------------------------
13740
13741    /// Delete base and visible rows owned by the effective scopes
13742    /// ([`local_scope_predicate`]); `Ok(false)` = no local scope-column
13743    /// mapping for a key (the fail-closed case). A SQLite failure is an error.
13744    fn purge_scope_rows(
13745        &mut self,
13746        table_name: &str,
13747        effective: &[(String, Vec<String>)],
13748        owners: &[Vec<(String, Vec<String>)>],
13749    ) -> Result<bool, String> {
13750        let Some(table) = self.schema.table(table_name) else {
13751            return Ok(false);
13752        };
13753        let Ok(predicate) = local_scope_predicate(table, effective, owners) else {
13754            return Ok(false);
13755        };
13756        let Some((predicate, params)) = predicate else {
13757            return Ok(true);
13758        };
13759        self.overlay_dirty.table(table_name);
13760        for source in [base_table(table_name), visible_table(table_name)] {
13761            self.conn
13762                .execute(
13763                    &format!("DELETE FROM {source} WHERE {predicate}"),
13764                    rusqlite::params_from_iter(&params),
13765                )
13766                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13767        }
13768        Ok(true)
13769    }
13770
13771    /// §3.3: drop pending commits whose upserts provably land in the
13772    /// revoked effective scopes and no other owner covers (row ownership)
13773    /// — whole-commit, never per-operation.
13774    fn drop_doomed_outbox(
13775        &mut self,
13776        table: &TableSchema,
13777        effective: &[(String, Vec<String>)],
13778        owners: &[Vec<(String, Vec<String>)>],
13779    ) -> Result<bool, String> {
13780        let doomed: Vec<_> =
13781            self.outbox
13782                .iter()
13783                .filter(|commit| {
13784                    commit.ops.iter().any(|op| {
13785                        op.upsert
13786                            && op.table == table.name
13787                            && op.values.as_ref().is_some_and(|values| {
13788                                owns_local_row(table, effective, owners, values)
13789                            })
13790                    })
13791                })
13792                .cloned()
13793                .collect();
13794        if doomed.is_empty() {
13795            return Ok(false);
13796        }
13797        let mut rejections = Vec::new();
13798        for commit in &doomed {
13799            let results = commit
13800                .ops
13801                .iter()
13802                .enumerate()
13803                .map(|(op_index, operation)| {
13804                    self.overlay_dirty.table(&operation.table);
13805                    let rejection = RejectionRecord {
13806                        client_commit_id: commit.client_commit_id.clone(),
13807                        op_index: op_index as i32,
13808                        code: "sync.scope_revoked".to_owned(),
13809                        message: "the commit was dropped because its effective scope was revoked"
13810                            .to_owned(),
13811                        retryable: false,
13812                        details: None,
13813                        operation: Some(CommitOperation::from(operation)),
13814                    };
13815                    rejections.push(rejection.clone());
13816                    CommitOperationOutcome::Error { rejection }
13817                })
13818                .collect::<Vec<_>>();
13819            self.persist_commit_outcome(
13820                &commit.client_commit_id,
13821                CommitOutcomeStatus::Rejected,
13822                &results,
13823                Some(&commit.ops),
13824            )?;
13825            self.leave_through(&commit.client_commit_id);
13826            self.delete_outbox_persisted(&commit.client_commit_id)?;
13827        }
13828        self.prune_commit_outcomes()?;
13829        let doomed_ids = doomed
13830            .iter()
13831            .map(|commit| commit.client_commit_id.as_str())
13832            .collect::<BTreeSet<_>>();
13833        self.outbox
13834            .retain(|commit| !doomed_ids.contains(commit.client_commit_id.as_str()));
13835        self.rejections.extend(rejections);
13836        Ok(true)
13837    }
13838
13839    // -- blobs (§5.9) ----------------------------------------------------------------
13840
13841    /// §5.9.7: hash bytes into the content address, cache them, queue the
13842    /// upload (flushed before the next push, B4). Returns the canonical
13843    /// BlobRef JSON `{blobId, byteLength, mediaType?}` for a `blob_ref`
13844    /// column value.
13845    pub fn upload_blob(
13846        &mut self,
13847        bytes: &[u8],
13848        media_type: Option<String>,
13849        name: Option<String>,
13850    ) -> Result<Value, String> {
13851        let blob_id = blob_id_for(bytes);
13852        let now = self.clock_now_ms();
13853        let tx = self
13854            .conn
13855            .transaction()
13856            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13857        tx.execute(
13858            "INSERT INTO _syncular_blobs(blob_id, bytes, byte_length, media_type, created_at_ms) VALUES (?,?,?,?,?)
13859             ON CONFLICT(blob_id) DO NOTHING",
13860            rusqlite::params![blob_id, bytes, bytes.len() as i64, media_type, now],
13861        )
13862        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13863        tx.execute(
13864            "INSERT OR IGNORE INTO _syncular_blob_uploads(blob_id, media_type, created_at_ms) VALUES (?,?,?)",
13865            rusqlite::params![blob_id, media_type, now],
13866        )
13867        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13868        tx.commit()
13869            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13870        self.enforce_blob_cache_cap();
13871        let mut obj = Map::new();
13872        obj.insert("blobId".to_owned(), Value::from(blob_id));
13873        obj.insert("byteLength".to_owned(), Value::from(bytes.len() as i64));
13874        if let Some(mt) = media_type {
13875            obj.insert("mediaType".to_owned(), Value::from(mt));
13876        }
13877        if let Some(n) = name {
13878            obj.insert("name".to_owned(), Value::from(n));
13879        }
13880        Ok(Value::Object(obj))
13881    }
13882
13883    /// §5.9.7: resolve an owned blob body without driver encoding. A
13884    /// content-addressed cache hit serves with no fetch (B1); a miss downloads
13885    /// (§5.9.5), verifies the address, caches the bytes, and returns them.
13886    pub fn fetch_blob_bytes(
13887        &mut self,
13888        transport: &mut dyn Transport,
13889        blob_id_or_ref: &str,
13890    ) -> Result<FetchedBlob, (String, String)> {
13891        let simple = |m: String| ("client.failed".to_owned(), m);
13892        // A BlobRef declares the size that caps the download (§5.9.5); a bare
13893        // blobId declares none.
13894        let (blob_id, byte_length) = if blob_id_or_ref.starts_with("sha256:") {
13895            (blob_id_or_ref.to_owned(), None)
13896        } else {
13897            let value: Value = serde_json::from_str(blob_id_or_ref)
13898                .map_err(|_| simple("blob ref is not JSON".to_owned()))?;
13899            (
13900                value
13901                    .get("blobId")
13902                    .and_then(Value::as_str)
13903                    .ok_or_else(|| simple("blob ref has no blobId".to_owned()))?
13904                    .to_owned(),
13905                value.get("byteLength").and_then(Value::as_u64),
13906            )
13907        };
13908        if let Some(cached) = self.get_cached_blob_bytes(&blob_id).map_err(simple)? {
13909            return Ok(cached);
13910        }
13911        if self.transport_closed() {
13912            return Err(("sync.offline".into(), "transport gate is closed".into()));
13913        }
13914        // §5.9.5: propagate the server's blob.* code (blob.forbidden /
13915        // blob.not_found) verbatim so the harness can assert on it. The
13916        // authorized endpoint serves bytes inline OR (always-issue, presign
13917        // configured) a signed url the client fetches directly — no host auth,
13918        // no fall-through: failure => re-request (the caller's next fetch_blob_bytes).
13919        #[cfg(feature = "bench-internals")]
13920        let download_phase = self.benchmark_phases.start(Phase::BlobDownload);
13921        let bytes = match transport
13922            .blob_download(&blob_id, byte_length)
13923            .map_err(|e| (e.code, e.message))?
13924        {
13925            BlobDownload::Bytes(bytes) => bytes,
13926            BlobDownload::Url {
13927                url,
13928                url_expires_at_ms,
13929            } => {
13930                // §5.9.5: MUST NOT start a fetch at/past expiry.
13931                if url_expires_at_ms.is_some_and(|exp| exp <= self.clock_now_ms()) {
13932                    return Err((
13933                        "sync.segment_expired".to_owned(),
13934                        format!(
13935                            "blob url for {blob_id} expired before fetch — re-request mints a fresh url (§5.9.5)"
13936                        ),
13937                    ));
13938                }
13939                transport
13940                    .fetch_blob_url(&url, byte_length)
13941                    .map_err(|e| (e.code, e.message))?
13942            }
13943        };
13944        #[cfg(feature = "bench-internals")]
13945        drop(download_phase);
13946        #[cfg(feature = "bench-internals")]
13947        let validate_phase = self.benchmark_phases.start(Phase::BlobValidate);
13948        // §5.9.5 inherits §5.1: the declared size caps the body before the
13949        // content address is verified.
13950        if byte_length.is_some_and(|cap| bytes.len() as u64 > cap) {
13951            return Err((
13952                "sync.invalid_request".to_owned(),
13953                "blob exceeds its byteLength".to_owned(),
13954            ));
13955        }
13956        if blob_id_for(&bytes) != blob_id {
13957            return Err(simple(format!(
13958                "blob content address mismatch for {blob_id}"
13959            )));
13960        }
13961        #[cfg(feature = "bench-internals")]
13962        drop(validate_phase);
13963        #[cfg(feature = "bench-internals")]
13964        let insert_phase = self.benchmark_phases.start(Phase::BlobCacheInsert);
13965        let now = self.clock_now_ms();
13966        self.conn
13967            .execute(
13968                "INSERT OR IGNORE INTO _syncular_blobs(blob_id, bytes, byte_length, media_type, created_at_ms) VALUES (?,?,?,NULL,?)",
13969                rusqlite::params![blob_id, bytes, bytes.len() as i64, now],
13970            )
13971            .map_err(|e| simple(e.to_string()))?;
13972        self.conn
13973            .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
13974            .map_err(|e| simple(e.to_string()))?;
13975        self.enforce_blob_cache_cap();
13976        #[cfg(feature = "bench-internals")]
13977        drop(insert_phase);
13978        self.get_cached_blob_bytes(&blob_id)
13979            .map_err(simple)?
13980            .ok_or_else(|| simple("blob cache write failed".to_owned()))
13981    }
13982
13983    fn get_cached_blob_bytes(&self, blob_id: &str) -> Result<Option<FetchedBlob>, String> {
13984        #[cfg(feature = "bench-internals")]
13985        let _phase = self.benchmark_phases.start(Phase::BlobCacheRead);
13986        let mut stmt = self
13987            .conn
13988            .prepare("SELECT bytes, byte_length, media_type FROM _syncular_blobs WHERE blob_id = ?")
13989            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13990        let mut rows = stmt
13991            .query(rusqlite::params![blob_id])
13992            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13993        if let Some(row) = rows
13994            .next()
13995            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
13996        {
13997            let bytes: Vec<u8> = row
13998                .get(0)
13999                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14000            let byte_length: i64 = row
14001                .get(1)
14002                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14003            let media_type: Option<String> = row
14004                .get(2)
14005                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14006            return Ok(Some(FetchedBlob {
14007                blob_id: blob_id.to_owned(),
14008                byte_length,
14009                bytes,
14010                media_type,
14011            }));
14012        }
14013        Ok(None)
14014    }
14015
14016    /// §5.9.7 B4: upload every queued blob before push.
14017    fn pending_blob_uploads(&self) -> Result<Vec<crate::round::PendingUpload>, TransportError> {
14018        let pending: Vec<(String, Option<String>)> = {
14019            let mut stmt = self
14020                .conn
14021                .prepare(
14022                    "SELECT blob_id, media_type FROM (
14023                      SELECT blob_id, media_type, created_at_ms FROM _syncular_blob_uploads
14024                      UNION ALL
14025                      SELECT DISTINCT r.blob_id, b.media_type, 9223372036854775807 AS created_at_ms
14026                      FROM _syncular_blob_commit_refs r LEFT JOIN _syncular_blobs b ON b.blob_id = r.blob_id
14027                      WHERE NOT EXISTS (SELECT 1 FROM _syncular_blob_uploads u WHERE u.blob_id = r.blob_id)
14028                    ) ORDER BY created_at_ms, blob_id",
14029                )
14030                .map_err(|e| TransportError::new("client.failed", e.to_string()))?;
14031            let rows = stmt
14032                .query_map([], |row| {
14033                    Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?))
14034                })
14035                .map_err(|e| TransportError::new("client.failed", e.to_string()))?;
14036            rows.collect::<Result<_, _>>()
14037                .map_err(|error| match error {
14038                    rusqlite::Error::InvalidColumnType(..)
14039                    | rusqlite::Error::FromSqlConversionFailure(..) => TransportError::new(
14040                        "sync.local_corrupt",
14041                        "Pending blob upload metadata is invalid",
14042                    ),
14043                    _ => TransportError::new("client.failed", error.to_string()),
14044                })?
14045        };
14046        let mut uploads = Vec::new();
14047        for (blob_id, media_type) in pending {
14048            let bytes = (|| {
14049                let stored: Option<(SqlValue, SqlValue)> = self
14050                    .conn
14051                    .query_row(
14052                        "SELECT bytes, byte_length FROM _syncular_blobs WHERE blob_id = ?",
14053                        rusqlite::params![blob_id],
14054                        |row| Ok((row.get(0)?, row.get(1)?)),
14055                    )
14056                    .optional()
14057                    .map_err(|e| TransportError::new("client.failed", e.to_string()))?;
14058                let Some((SqlValue::Blob(bytes), SqlValue::Integer(byte_length))) = stored else {
14059                    return Err(TransportError::new(
14060                        "sync.local_corrupt",
14061                        "Pending blob upload body is missing or corrupt",
14062                    ));
14063                };
14064                if byte_length != bytes.len() as i64 || blob_id_for(&bytes) != blob_id {
14065                    return Err(TransportError::new(
14066                        "sync.local_corrupt",
14067                        "Pending blob upload body is missing or corrupt",
14068                    ));
14069                }
14070                Ok(bytes)
14071            })();
14072            let failed = bytes.is_err();
14073            uploads.push(crate::round::PendingUpload {
14074                id: blob_id,
14075                bytes,
14076                media_type,
14077            });
14078            if failed {
14079                break;
14080            }
14081        }
14082        Ok(uploads)
14083    }
14084
14085    fn visible_blob_ids_sql(&self) -> String {
14086        let mut selects = Vec::new();
14087        for table in &self.schema.tables {
14088            for column in table
14089                .columns
14090                .iter()
14091                .filter(|column| column.ty == ColumnType::BlobRef)
14092            {
14093                let identifier = quote_ident(&column.name);
14094                selects.push(format!(
14095                    "SELECT json_extract({identifier}, '$.blobId') AS blob_id FROM {} \
14096                     WHERE typeof({identifier}) = 'text' AND json_valid({identifier}) \
14097                     AND json_type({identifier}, '$.blobId') = 'text'",
14098                    quote_ident(&table.name),
14099                ));
14100            }
14101        }
14102        if selects.is_empty() {
14103            "SELECT NULL AS blob_id WHERE 0".to_owned()
14104        } else {
14105            selects.join(" UNION ")
14106        }
14107    }
14108
14109    /// §5.9.7 B1 size cap. Visible rows, pending commits, and
14110    /// staged uploads pin bodies directly; no derived refcount is stored.
14111    fn enforce_blob_cache_cap(&self) {
14112        let Some(max_bytes) = self.limits.blob_cache_max_bytes else {
14113            return;
14114        };
14115        let mut total: i64 = self
14116            .conn
14117            .query_row(
14118                "SELECT COALESCE(SUM(byte_length), 0) FROM _syncular_blobs",
14119                [],
14120                |row| row.get(0),
14121            )
14122            .unwrap_or(0);
14123        if total <= max_bytes {
14124            return;
14125        }
14126        let query = format!(
14127            "SELECT blob_id, byte_length FROM _syncular_blobs
14128             WHERE blob_id NOT IN (SELECT blob_id FROM _syncular_blob_uploads)
14129               AND blob_id NOT IN (SELECT blob_id FROM _syncular_blob_commit_refs)
14130               AND blob_id NOT IN ({})
14131             ORDER BY created_at_ms ASC, blob_id ASC",
14132            self.visible_blob_ids_sql(),
14133        );
14134        let candidates: Vec<(String, i64)> = {
14135            let Ok(mut stmt) = self.conn.prepare(&query) else {
14136                return;
14137            };
14138            let Ok(rows) = stmt.query_map([], |row| {
14139                Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
14140            }) else {
14141                return;
14142            };
14143            rows.filter_map(Result::ok).collect()
14144        };
14145        for (blob_id, byte_length) in candidates {
14146            if total <= max_bytes {
14147                break;
14148            }
14149            let _ = self.conn.execute(
14150                "DELETE FROM _syncular_blobs WHERE blob_id = ?",
14151                rusqlite::params![blob_id],
14152            );
14153            total -= byte_length;
14154        }
14155    }
14156
14157    fn delete_unreferenced_cached_blobs(&mut self) -> Result<(), String> {
14158        #[cfg(feature = "bench-internals")]
14159        let _phase = self.benchmark_phases.start(Phase::BlobRetention);
14160        if !self.schema_has_blobs() {
14161            return Ok(());
14162        }
14163        self.rebuild_overlay_if_dirty()?;
14164        self.conn
14165            .execute(
14166                &format!(
14167                    "DELETE FROM _syncular_blobs
14168                 WHERE blob_id NOT IN (SELECT blob_id FROM _syncular_blob_uploads)
14169                   AND blob_id NOT IN (SELECT blob_id FROM _syncular_blob_commit_refs)
14170                   AND blob_id NOT IN ({})",
14171                    self.visible_blob_ids_sql(),
14172                ),
14173                [],
14174            )
14175            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14176        Ok(())
14177    }
14178
14179    // -- local row storage ----------------------------------------------------------
14180
14181    /// The cached per-table primary-key upsert SQL for `full_table` (see
14182    /// the `insert_sql` field: built once, reused per row).
14183    fn insert_row_sql(&self, full_table: &str, table: &crate::schema::TableSchema) -> String {
14184        if let Some(sql) = self.insert_sql.borrow().get(full_table) {
14185            return sql.clone();
14186        }
14187        let mut columns: Vec<String> = table.columns.iter().map(|c| quote_ident(&c.name)).collect();
14188        columns.push(quote_ident("_syncular_version"));
14189        columns.extend(table.sealed_columns().iter().map(|name| quote_ident(name)));
14190        let placeholders: Vec<&str> = columns.iter().map(|_| "?").collect();
14191        let primary_key = quote_ident(&table.primary_key);
14192        let updates = columns
14193            .iter()
14194            .filter(|column| **column != primary_key)
14195            .map(|column| format!("{column}=excluded.{column}"))
14196            .collect::<Vec<_>>()
14197            .join(", ");
14198        // §4.5 version guard: server state lands in the base table only above
14199        // the stored version; the visible overlay takes every write.
14200        let guard = if full_table == base_table(&table.name) {
14201            format!(" WHERE excluded._syncular_version > {full_table}._syncular_version")
14202        } else {
14203            String::new()
14204        };
14205        let sql = format!(
14206            "INSERT INTO {full_table} ({}) VALUES ({}) ON CONFLICT ({primary_key}) DO UPDATE SET {updates}{guard}",
14207            columns.join(", "),
14208            placeholders.join(", ")
14209        );
14210        self.insert_sql
14211            .borrow_mut()
14212            .insert(full_table.to_owned(), sql.clone());
14213        sql
14214    }
14215
14216    /// §4.5: write a server row under the version guard; returns whether it
14217    /// landed. `sealed` is its §5.11 sealed state, `None` for an unsealed row.
14218    fn write_base_row(
14219        &self,
14220        table_name: &str,
14221        row: &Row,
14222        version: i64,
14223        sealed: Option<&SealedRow>,
14224    ) -> Result<bool, String> {
14225        let landed = self.write_row(&base_table(table_name), table_name, row, version, sealed)?;
14226        if landed {
14227            self.overlay_dirty.table(table_name);
14228        }
14229        Ok(landed)
14230    }
14231
14232    fn write_row(
14233        &self,
14234        full_table: &str,
14235        table_name: &str,
14236        row: &Row,
14237        version: i64,
14238        sealed: Option<&SealedRow>,
14239    ) -> Result<bool, String> {
14240        #[cfg(feature = "bench-internals")]
14241        let _phase = self.benchmark_phases.start(Phase::RowWrite);
14242        let table = self
14243            .schema
14244            .table(table_name)
14245            .ok_or_else(|| format!("unknown table {table_name:?}"))?;
14246        let sql = self.insert_row_sql(full_table, table);
14247        let mut stmt = self
14248            .conn
14249            .prepare_cached(&sql)
14250            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14251        let params = row
14252            .iter()
14253            .map(RowParam::Cell)
14254            .chain(std::iter::once(RowParam::Version(version)))
14255            .chain(
14256                [
14257                    sealed.map(|sealed| sealed.key_id.as_str()),
14258                    sealed.map(|sealed| sealed.envelopes.as_str()),
14259                ]
14260                .into_iter()
14261                .take(table.sealed_columns().len())
14262                .map(RowParam::Text),
14263            );
14264        stmt.execute(rusqlite::params_from_iter(params))
14265            .map(|changed| changed > 0)
14266            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
14267    }
14268
14269    /// §4.5: delete a server row whose stored version lies below `version`;
14270    /// returns whether a row left.
14271    fn delete_base_row(
14272        &self,
14273        table_name: &str,
14274        row_id: &str,
14275        version: i64,
14276    ) -> Result<bool, String> {
14277        let table = self
14278            .schema
14279            .table(table_name)
14280            .ok_or_else(|| format!("unknown table {table_name:?}"))?;
14281        let sql = format!(
14282            "DELETE FROM {} WHERE {} AND _syncular_version < ?2",
14283            base_table(table_name),
14284            row_id_predicate(table)
14285        );
14286        let mut stmt = self
14287            .conn
14288            .prepare_cached(&sql)
14289            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14290        let landed = stmt
14291            .execute(rusqlite::params![row_id, version])
14292            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
14293            > 0;
14294        if landed {
14295            self.overlay_dirty.table(table_name);
14296        }
14297        Ok(landed)
14298    }
14299
14300    fn has_acknowledged_rows(&self) -> Result<bool, String> {
14301        self.conn
14302            .query_row(
14303                "SELECT EXISTS(SELECT 1 FROM _syncular_acked_rows)",
14304                [],
14305                |row| row.get(0),
14306            )
14307            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
14308    }
14309
14310    fn acknowledged_operations(
14311        &self,
14312        rows: Option<&HashSet<(&str, &str)>>,
14313        tables: Option<&BTreeSet<&str>>,
14314    ) -> Result<Vec<OutboxOp>, String> {
14315        let keys = rows.map(|rows| serde_json::to_string(&rows).expect("row keys"));
14316        let mut statement = self
14317            .conn
14318            .prepare_cached(if keys.is_some() {
14319                ACKED_ROWS_BY_ROW
14320            } else {
14321                "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"
14322            })
14323            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14324        let rows = statement
14325            .query_map(
14326                rusqlite::params![
14327                    keys,
14328                    tables.map(|tables| serde_json::to_string(tables).expect("table keys"))
14329                ],
14330                |row| {
14331                    #[cfg(test)]
14332                    self.acknowledged_replay_count
14333                        .set(self.acknowledged_replay_count.get() + 1);
14334                    Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
14335                },
14336            )
14337            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14338        rows.map(|row| {
14339            let (op, intent) =
14340                row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14341            let op: CommitOperation =
14342                serde_json::from_str(&op).map_err(|_| "sync.local_corrupt".to_owned())?;
14343            let table = self
14344                .schema
14345                .table(&op.table)
14346                .ok_or_else(|| "sync.unknown_table".to_owned())?;
14347            let values = if op.op == "upsert" && self.visible_row(table, &op.row_id)?.is_none() {
14348                Some(serde_json::from_str(&intent).map_err(|_| "sync.local_corrupt".to_owned())?)
14349            } else {
14350                op.values.clone()
14351            };
14352            Ok(OutboxOp {
14353                values,
14354                ..op.into()
14355            })
14356        })
14357        .collect()
14358    }
14359
14360    fn drop_acknowledged_rows(
14361        &self,
14362        matches: impl Fn(&str, &Map<String, Value>) -> bool,
14363    ) -> Result<Vec<OutboxCommit>, String> {
14364        let mut statement = self
14365            .conn
14366            .prepare("SELECT commit_id,tbl,intent_json,id FROM _syncular_acked_rows")
14367            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14368        let rows = statement
14369            .query_map([], |row| {
14370                Ok((
14371                    row.get::<_, String>(0)?,
14372                    row.get::<_, String>(1)?,
14373                    row.get::<_, String>(2)?,
14374                    row.get::<_, String>(3)?,
14375                ))
14376            })
14377            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14378        let mut doomed = HashSet::new();
14379        for row in rows {
14380            let (id, table, intent, row_id) =
14381                row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14382            let values =
14383                serde_json::from_str(&intent).map_err(|_| "sync.local_corrupt".to_owned())?;
14384            let base_matches = self
14385                .schema
14386                .table(&table)
14387                .map(|schema| self.stored_row(schema, &row_id, true))
14388                .transpose()?
14389                .flatten()
14390                .is_some_and(|(base, _)| {
14391                    let schema = self.schema.table(&table).expect("acknowledged table");
14392                    let values = schema
14393                        .columns
14394                        .iter()
14395                        .zip(base.iter())
14396                        .map(|(column, value)| (column.name.clone(), column_value_to_json(value)))
14397                        .collect();
14398                    matches(&table, &values)
14399                });
14400            if matches(&table, &values) || base_matches {
14401                doomed.insert(id);
14402            }
14403        }
14404        let mut dropped = Vec::new();
14405        for id in doomed {
14406            let mut statement = self
14407                .conn
14408                .prepare("SELECT op_json FROM _syncular_acked_rows WHERE commit_id=?1 ORDER BY idx")
14409                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14410            let operations = statement
14411                .query_map([&id], |row| row.get::<_, String>(0))
14412                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14413            let mut ops = Vec::new();
14414            for operation in operations {
14415                let json = operation
14416                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14417                let op: CommitOperation =
14418                    serde_json::from_str(&json).map_err(|_| "sync.local_corrupt".to_owned())?;
14419                self.overlay_dirty.table(&op.table);
14420                ops.push(OutboxOp {
14421                    table: op.table,
14422                    row_id: op.row_id,
14423                    upsert: op.op == "upsert",
14424                    base_version: op.base_version,
14425                    values: op.values,
14426                    insert: op.insert,
14427                });
14428            }
14429            dropped.push(OutboxCommit {
14430                client_commit_id: id.clone(),
14431                ops,
14432            });
14433            self.conn
14434                .execute("DELETE FROM _syncular_acked_rows WHERE commit_id=?1", [id])
14435                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14436        }
14437        Ok(dropped)
14438    }
14439
14440    /// [`Self::rebuild_overlay`], skipped when neither the base tables nor
14441    /// the outbox changed since the last rebuild (the no-op sync round).
14442    fn rebuild_overlay_if_dirty(&mut self) -> Result<(), String> {
14443        if self.overlay_dirty.get() {
14444            self.rebuild_overlay()?;
14445        }
14446        Ok(())
14447    }
14448
14449    /// §7.1: local reads see outbox state applied optimistically — rebuild
14450    /// every visible table as (base server state) + (pending outbox replay
14451    /// on top). Optimistic rows carry version `-1`.
14452    fn rebuild_overlay(&mut self) -> Result<(), String> {
14453        #[cfg(feature = "bench-internals")]
14454        let _phase = self.benchmark_phases.start(Phase::OverlayRebuild);
14455        #[cfg(test)]
14456        self.overlay_rebuild_count
14457            .set(self.overlay_rebuild_count.get() + 1);
14458        let dirty = self.overlay_dirty.snapshot();
14459        let tables: Vec<_> = self
14460            .schema
14461            .tables
14462            .iter()
14463            .filter(|table| {
14464                dirty
14465                    .as_ref()
14466                    .is_none_or(|names| names.is_empty() || names.contains(&table.name))
14467            })
14468            .cloned()
14469            .collect();
14470        let names: BTreeSet<_> = tables.iter().map(|table| table.name.as_str()).collect();
14471        // A built-in projection is refilled from the rebuilt rows once
14472        // instead of per row by its source triggers.
14473        let built_in: Vec<_> = tables
14474            .iter()
14475            .flat_map(|table| {
14476                table
14477                    .local_projections
14478                    .iter()
14479                    .filter(|spec| spec.built_in())
14480                    .map(move |spec| (spec, table))
14481            })
14482            .collect();
14483        self.begin_observation("syncular_overlay")?;
14484        let rebuilt = (|| {
14485            for (spec, _) in &built_in {
14486                for suffix in ["bi", "bu", "ai", "ad", "au"] {
14487                    self.stored(self.conn.execute(
14488                        &format!(
14489                            "DROP TRIGGER IF EXISTS {}",
14490                            quote_ident(&format!("_syncular_project_{}_{suffix}", spec.name))
14491                        ),
14492                        [],
14493                    ))?;
14494                }
14495            }
14496            for table in &tables {
14497                let visible = visible_table(&table.name);
14498                let base = base_table(&table.name);
14499                self.conn
14500                    .execute_batch(&format!(
14501                        "DELETE FROM {visible}; INSERT INTO {visible} SELECT * FROM {base}"
14502                    ))
14503                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14504            }
14505            self.replay_overlay(&names, None)?;
14506            for (spec, table) in &built_in {
14507                self.fill_built_in(spec, table)?;
14508                self.create_projection_triggers(spec, table)?;
14509            }
14510            self.conn
14511                .execute_batch("RELEASE syncular_overlay")
14512                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14513            Ok(())
14514        })();
14515        if rebuilt.is_err() {
14516            self.conn
14517                .execute_batch("ROLLBACK TO syncular_overlay; RELEASE syncular_overlay")
14518                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14519        } else {
14520            self.overlay_dirty.set(false);
14521        }
14522        rebuilt
14523    }
14524
14525    /// §7.1 replay of acknowledged, retained failed and pending intent, in
14526    /// that order, for the operations of `tables` on `rows` (every row for
14527    /// `None`) over their current visible state.
14528    fn replay_overlay(
14529        &self,
14530        tables: &BTreeSet<&str>,
14531        rows: Option<&HashSet<(&str, &str)>>,
14532    ) -> Result<(), String> {
14533        let replays = |op: &&OutboxOp| {
14534            tables.contains(op.table.as_str())
14535                && rows.is_none_or(|rows| rows.contains(&(op.table.as_str(), op.row_id.as_str())))
14536        };
14537        self.apply_outbox_ops(&self.acknowledged_operations(rows, Some(tables))?)?;
14538        for (commit, initial) in self.failed_commits.iter() {
14539            for operation in commit.ops.iter().filter(replays) {
14540                let Some(table) = self.schema.table(&operation.table) else {
14541                    continue;
14542                };
14543                if operation.upsert
14544                    && self.visible_row(table, &operation.row_id)?.is_none()
14545                    && operation.presented_values(table).is_some_and(|values| {
14546                        table
14547                            .columns
14548                            .iter()
14549                            .all(|column| values.contains_key(&column.name))
14550                    })
14551                {
14552                    let key = serde_json::to_string(&(&operation.table, &operation.row_id))
14553                        .expect("row key serialization");
14554                    if let Some(Value::Object(values)) = initial.get(&key) {
14555                        self.apply_outbox_ops(&[OutboxOp {
14556                            values: Some(values.clone()),
14557                            ..operation.clone()
14558                        }])?;
14559                    }
14560                }
14561            }
14562            self.apply_outbox_ops(commit.ops.iter().filter(replays))?;
14563        }
14564        self.apply_outbox_ops(
14565            self.outbox
14566                .iter()
14567                .flat_map(|commit| &commit.ops)
14568                .filter(replays),
14569        )
14570    }
14571
14572    /// §7.1 replay: every operation is applied over the current visible
14573    /// state. An operation that no longer applies (a server row now holds its
14574    /// unique value) stays pending and invisible until a later replay admits
14575    /// it or the server answers its push.
14576    fn apply_outbox_ops<'a>(
14577        &self,
14578        ops: impl IntoIterator<Item = &'a OutboxOp>,
14579    ) -> Result<(), String> {
14580        #[cfg(feature = "bench-internals")]
14581        let mut phase = self.benchmark_phases.start(Phase::PendingReplay);
14582        for op in ops {
14583            #[cfg(feature = "bench-internals")]
14584            if let Some(phase) = &mut phase {
14585                phase.unit();
14586            }
14587            if op.upsert {
14588                if let Some((table, values)) = self
14589                    .schema
14590                    .table(&op.table)
14591                    .filter(|table| table.indexes.iter().any(|index| index.unique))
14592                    .and_then(|table| Some((table, op.presented_values(table)?)))
14593                {
14594                    let mut intended: Map<String, Value> = self
14595                        .visible_row(table, &op.row_id)?
14596                        .map(|(row, _)| {
14597                            table
14598                                .columns
14599                                .iter()
14600                                .zip(&row)
14601                                .map(|(column, value)| {
14602                                    (column.name.clone(), column_value_to_json(value))
14603                                })
14604                                .collect()
14605                        })
14606                        .unwrap_or_default();
14607                    intended.extend(values.into_owned());
14608                    if !self.unique_conflicts(table, &intended, false)?.is_empty() {
14609                        continue;
14610                    }
14611                }
14612            }
14613            self.apply_outbox_op(op)?;
14614        }
14615        Ok(())
14616    }
14617
14618    fn apply_outbox_op(&self, op: &OutboxOp) -> Result<(), String> {
14619        let Some(table) = self.schema.table(&op.table) else {
14620            return Ok(());
14621        };
14622        let visible = visible_table(&table.name);
14623        if !op.upsert {
14624            let sql = format!("DELETE FROM {visible} WHERE {}", row_id_predicate(table));
14625            self.conn
14626                .prepare_cached(&sql)
14627                .and_then(|mut statement| statement.execute(rusqlite::params![op.row_id]))
14628                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14629            return Ok(());
14630        }
14631        // §7.1: an insert-intent operation that lacks a non-nullable column
14632        // cannot encode; it stays invisible until the send-time prepass drops
14633        // it as sync.outbox_incompatible (§7.4.4).
14634        let Some(values) = op.presented_values(table) else {
14635            return Ok(());
14636        };
14637        // §7.1: the overlay applies the operation's PRESENT columns
14638        // over the current local row. A partial operation over an
14639        // absent local row leaves it absent — the server answers it
14640        // with sync.row_deleted or sync.row_missing (§6.2). An
14641        // insert-intent operation presents every column.
14642        let full = table
14643            .columns
14644            .iter()
14645            .all(|column| values.contains_key(&column.name));
14646        let local = self.visible_row(table, &op.row_id)?;
14647        if local.is_none() && !full {
14648            return Ok(());
14649        }
14650        // §5.11: a row that arrived sealed stays sealed; the replay overlays
14651        // its non-encrypted columns and its encrypted columns stay NULL.
14652        let sealed = if local.is_some() && table.has_encrypted_columns() {
14653            let (key_id, envelopes) = self
14654                .conn
14655                .query_row(
14656                    &format!(
14657                        "SELECT \"_sync_sealed_key\",\"_sync_sealed\" FROM {visible} WHERE {}",
14658                        row_id_predicate(table)
14659                    ),
14660                    rusqlite::params![op.row_id],
14661                    |row| {
14662                        Ok((
14663                            row.get::<_, Option<String>>(0)?,
14664                            row.get::<_, Option<String>>(1)?,
14665                        ))
14666                    },
14667                )
14668                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14669            key_id
14670                .zip(envelopes)
14671                .map(|(key_id, envelopes)| SealedRow { key_id, envelopes })
14672        } else {
14673            None
14674        };
14675        let mut row: Row = Vec::with_capacity(table.columns.len());
14676        for (index, column) in table.columns.iter().enumerate() {
14677            let encrypted = table
14678                .encrypted_columns
14679                .iter()
14680                .any(|encrypted| encrypted.index == index);
14681            let incoming = match values
14682                .get(&column.name)
14683                .filter(|_| !(sealed.is_some() && encrypted))
14684            {
14685                Some(raw) => json_to_column_value(
14686                    if raw.get("$bytes").is_some() && encrypted {
14687                        &table.wire_columns[index]
14688                    } else {
14689                        column
14690                    },
14691                    Some(raw),
14692                ),
14693                None => Ok(local
14694                    .as_ref()
14695                    .and_then(|(values, _)| values.get(index).cloned())
14696                    .flatten()),
14697            };
14698            row.push(incoming.map_err(|_| {
14699                "sync.local_corrupt: persisted optimistic row value is invalid".to_owned()
14700            })?);
14701        }
14702        let version = local.as_ref().map_or(-1, |(_, version)| *version);
14703        self.write_row(&visible, &table.name, &row, version, sealed.as_ref())
14704            .map(|_| ())
14705            .map_err(|error| {
14706                if error.starts_with("UNIQUE constraint failed:") {
14707                    "sync.constraint_violation: local write violates a unique constraint".to_owned()
14708                } else {
14709                    error
14710                }
14711            })
14712    }
14713
14714    /// Whether the row is present in the overlay. Existence reads only the
14715    /// key: locked encrypted values stay opaque, and decoding the complete row
14716    /// would reject a valid plain write.
14717    fn visible_row_exists(&self, table: &TableSchema, row_id: &str) -> Result<bool, String> {
14718        self.conn
14719            .query_row(
14720                &format!(
14721                    "SELECT EXISTS(SELECT 1 FROM {} WHERE {})",
14722                    visible_table(&table.name),
14723                    row_id_predicate(table)
14724                ),
14725                rusqlite::params![row_id],
14726                |row| row.get(0),
14727            )
14728            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
14729    }
14730
14731    /// §5.11: a sealed row is read-only; a write could otherwise send NULL
14732    /// over ciphertext this device cannot see.
14733    fn refuse_sealed_row(&self, table: &TableSchema, row_id: &str) -> Result<(), ClientError> {
14734        if !table.has_encrypted_columns() {
14735            return Ok(());
14736        }
14737        let key_id: Option<String> = self
14738            .conn
14739            .query_row(
14740                &format!(
14741                    "SELECT \"_sync_sealed_key\" FROM {} WHERE {}",
14742                    visible_table(&table.name),
14743                    row_id_predicate(table)
14744                ),
14745                rusqlite::params![row_id],
14746                |row| row.get(0),
14747            )
14748            .optional()
14749            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
14750            .flatten();
14751        match key_id {
14752            None => Ok(()),
14753            Some(key_id) => Err(ClientError {
14754                code: "client.encryption_key_missing".to_owned(),
14755                message: "the row is sealed under a key this device does not hold".to_owned(),
14756                details: Some(json!({ "table": table.name, "keyId": key_id })),
14757                retryable: false,
14758            }),
14759        }
14760    }
14761
14762    /// §5.11 reveal: decrypt every sealed base row whose envelope keys the
14763    /// keyring now holds into its columns and clear both reserved columns,
14764    /// one change batch per table. `client.decrypt_failed` fails the caller.
14765    fn reveal_sealed_rows(&mut self) -> Result<(), TransportError> {
14766        let storage = |message: String| TransportError::new("storage.failed", message);
14767        let tables: Vec<TableSchema> = self
14768            .schema
14769            .tables
14770            .iter()
14771            .filter(|table| table.has_encrypted_columns())
14772            .cloned()
14773            .collect();
14774        for table in &tables {
14775            let base = base_table(&table.name);
14776            let pk = quote_ident(&table.primary_key);
14777            let sealed: Vec<(SqlValue, i64, String)> = self
14778                .conn
14779                .prepare_cached(&format!(
14780                    "SELECT {pk}, \"_syncular_version\", \"_sync_sealed\" FROM {base} WHERE \"_sync_sealed_key\" IS NOT NULL"
14781                ))
14782                .and_then(|mut statement| {
14783                    statement
14784                        .query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))?
14785                        .collect()
14786                })
14787                .map_err(|error| storage(Self::sqlite_failure(&self.storage_failure, error)))?;
14788            let mut revealed = Vec::new();
14789            for (key, version, envelopes) in sealed {
14790                if let Some(row) =
14791                    crate::values::reveal_sealed_row(table, &envelopes, &self.encryption)?
14792                {
14793                    revealed.push((key, version, row));
14794                }
14795            }
14796            if revealed.is_empty() {
14797                continue;
14798            }
14799            self.begin_observation("syncular_reveal").map_err(storage)?;
14800            let outcome = (|| {
14801                let assignments = table
14802                    .encrypted_columns
14803                    .iter()
14804                    .map(|enc| format!("{}=?", quote_ident(&table.columns[enc.index].name)))
14805                    .collect::<Vec<_>>()
14806                    .join(",");
14807                let mut statement = self
14808                    .conn
14809                    .prepare_cached(&format!(
14810                        "UPDATE {base} SET {assignments},\"_sync_sealed_key\"=NULL,\"_sync_sealed\"=NULL WHERE {pk}=? AND \"_syncular_version\"=?"
14811                    ))
14812                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14813                for (key, version, row) in &revealed {
14814                    let mut params = table
14815                        .encrypted_columns
14816                        .iter()
14817                        .map(|enc| owned_sql_value(RowParam::Cell(&row[enc.index])))
14818                        .collect::<Result<Vec<_>, _>>()?;
14819                    params.push(key.clone());
14820                    params.push(SqlValue::Integer(*version));
14821                    statement
14822                        .execute(rusqlite::params_from_iter(params))
14823                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14824                }
14825                drop(statement);
14826                self.overlay_dirty.table(&table.name);
14827                self.rebuild_overlay()?;
14828                let mut batch = ChangeAccumulator::default();
14829                batch.table(&table.name);
14830                self.finish_observation("syncular_reveal", batch)
14831            })();
14832            if outcome.is_err() {
14833                self.rollback_observation("syncular_reveal");
14834            }
14835            outcome.map_err(storage)?;
14836        }
14837        Ok(())
14838    }
14839
14840    /// The visible (optimistic) row's values plus version, or `None` when the
14841    /// row is absent from the overlay.
14842    fn visible_row(&self, table: &TableSchema, row_id: &str) -> Result<Option<(Row, i64)>, String> {
14843        self.stored_row(table, row_id, false)
14844    }
14845
14846    fn stored_row(
14847        &self,
14848        table: &TableSchema,
14849        row_id: &str,
14850        base: bool,
14851    ) -> Result<Option<(Row, i64)>, String> {
14852        let sql = format!(
14853            "SELECT * FROM {} WHERE {}",
14854            if base {
14855                base_table(&table.name)
14856            } else {
14857                visible_table(&table.name)
14858            },
14859            row_id_predicate(table)
14860        );
14861        let mut stmt = self
14862            .conn
14863            .prepare_cached(&sql)
14864            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14865        let mut rows = stmt
14866            .query(rusqlite::params![row_id])
14867            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14868        let Some(row) = rows
14869            .next()
14870            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
14871        else {
14872            return Ok(None);
14873        };
14874        let mut values = Vec::with_capacity(table.columns.len());
14875        for (index, column) in table.columns.iter().enumerate() {
14876            let raw = row
14877                .get_ref(index)
14878                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14879            if let rusqlite::types::ValueRef::Blob(bytes) = raw {
14880                if table
14881                    .encrypted_columns
14882                    .iter()
14883                    .any(|encrypted| encrypted.index == index)
14884                {
14885                    values.push(Some(ColumnValue::Bytes(bytes.to_vec())));
14886                    continue;
14887                }
14888            }
14889            let json = sql_ref_to_json(column, raw);
14890            values.push(json_to_column_value(column, Some(&json)).map_err(|_| {
14891                "sync.local_corrupt: persisted local row value is invalid".to_owned()
14892            })?);
14893        }
14894        let version: i64 = row
14895            .get(table.columns.len())
14896            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14897        Ok(Some((values, version)))
14898    }
14899
14900    // -- realtime (§8) ---------------------------------------------------------------
14901
14902    /// §8.8: the configured realtime policy.
14903    #[must_use]
14904    pub fn realtime_policy(&self) -> RealtimePolicy {
14905        self.realtime_policy
14906    }
14907
14908    /// §8.8: the explicit realtime availability state.
14909    #[must_use]
14910    pub fn realtime_state(&self) -> RealtimeState {
14911        self.realtime_state
14912    }
14913
14914    /// §8.8: set the realtime policy. Refused while the socket is connected:
14915    /// a policy change never silently re-routes an ownership state.
14916    pub fn set_realtime_policy(&mut self, policy: RealtimePolicy) -> Result<(), String> {
14917        if self.realtime_state == RealtimeState::Connected && policy != self.realtime_policy {
14918            return Err(
14919                "sync.invalid_request: disconnect realtime before changing the realtime policy"
14920                    .to_owned(),
14921            );
14922        }
14923        self.realtime_policy = policy;
14924        match policy {
14925            RealtimePolicy::Off => self.set_realtime_state(RealtimeState::Disabled, None),
14926            RealtimePolicy::Required | RealtimePolicy::Optional
14927                if self.realtime_state == RealtimeState::Disabled =>
14928            {
14929                self.set_realtime_state(RealtimeState::Disconnected, None);
14930            }
14931            RealtimePolicy::Required | RealtimePolicy::Optional => {}
14932        }
14933        Ok(())
14934    }
14935
14936    /// Record an availability transition, keeping the reason code bounded and
14937    /// code-like (§7.6) and clearing it where it cannot apply.
14938    fn set_realtime_state(&mut self, state: RealtimeState, reason_code: Option<&str>) {
14939        self.realtime_state = state;
14940        self.realtime_reason_code = reason_code.map(Self::diagnostic_code);
14941        if matches!(state, RealtimeState::Connected | RealtimeState::Disabled) {
14942            self.realtime_reason_code = None;
14943            self.realtime_retry_delay_ms = None;
14944        }
14945    }
14946
14947    #[must_use]
14948    fn realtime_connected(&self) -> bool {
14949        self.realtime_state == RealtimeState::Connected
14950    }
14951
14952    pub fn connect_realtime(&mut self, transport: &mut dyn Transport) -> Result<(), String> {
14953        if self.transport_closed() {
14954            return Err("sync.offline: transport gate is closed".into());
14955        }
14956        if self.realtime_policy == RealtimePolicy::Off {
14957            return Err(
14958                "sync.invalid_request: realtime is off; realtime connect is refused".to_owned(),
14959            );
14960        }
14961        if self.realtime_connected() {
14962            return Ok(());
14963        }
14964        self.realtime_state = RealtimeState::Connecting;
14965        match transport.realtime_connect(&self.client_id) {
14966            Ok(()) => {
14967                self.set_realtime_state(RealtimeState::Connected, None);
14968                Ok(())
14969            }
14970            Err(error) => {
14971                self.set_realtime_state(RealtimeState::Refused, Some(&error.code));
14972                Err(format!("{}: {}", error.code, error.message))
14973            }
14974        }
14975    }
14976
14977    pub fn disconnect_realtime(&mut self, transport: &mut dyn Transport) {
14978        self.cancel_sync_round();
14979        // A deliberately disconnected or policy-disabled client has nothing
14980        // to release; a `lost` socket still does (the host owns the handle).
14981        if self.realtime_state == RealtimeState::Disconnected
14982            || self.realtime_state == RealtimeState::Disabled
14983        {
14984            return;
14985        }
14986        let _ = transport.realtime_close();
14987        self.set_realtime_state(
14988            if self.realtime_policy == RealtimePolicy::Off {
14989                RealtimeState::Disabled
14990            } else {
14991                RealtimeState::Disconnected
14992            },
14993            None,
14994        );
14995        self.presence.clear(); // §8.6.1: presence is per-connection
14996    }
14997
14998    /// §8.8: the host observed the socket end without disconnecting it (a
14999    /// peer close, an I/O error, a failed send; the native transport reports
15000    /// these as `Inbound::Disconnected`). Releases the transport, moves a
15001    /// `Connected` state to `Lost` with the transport's code as the reason, and schedules
15002    /// one background retry intent so the host reconnects and catches up.
15003    pub fn realtime_lost(&mut self, transport: &mut dyn Transport, error: &TransportError) {
15004        if self.realtime_state != RealtimeState::Connected {
15005            return;
15006        }
15007        self.cancel_sync_round();
15008        let _ = transport.realtime_close();
15009        self.set_realtime_state(RealtimeState::Lost, Some(&error.code));
15010        self.realtime_retry_delay_ms = Some(self.schedule_background_retry());
15011        self.presence.clear();
15012    }
15013
15014    /// §8.6.2: publish (or clear, `doc: None`) this client's presence
15015    /// document for `scope_key`. Requires a live socket; the document is
15016    /// ephemeral (lost on disconnect). Authorization is the connection's
15017    /// registration (§8.6.3) — an unheld key is rejected loudly by the
15018    /// server with `presence.forbidden`.
15019    pub fn set_presence(
15020        &mut self,
15021        transport: &mut dyn Transport,
15022        scope_key: &str,
15023        doc: Option<&Value>,
15024    ) -> Result<(), String> {
15025        if self.transport_closed() {
15026            return Err("sync.offline: transport gate is closed".into());
15027        }
15028        if !self.realtime_connected() {
15029            return Err("setPresence requires a connected realtime socket (§8.6)".to_string());
15030        }
15031        let text = encode_presence_publish(scope_key, doc);
15032        transport
15033            .realtime_send(&text)
15034            .map_err(|e| format!("{}: {}", e.code, e.message))
15035    }
15036
15037    /// §8.6: the peers currently present on a scope key (ephemeral).
15038    pub fn presence(&self, scope_key: &str) -> Vec<PresencePeer> {
15039        self.presence
15040            .get(scope_key)
15041            .map(|peers| peers.values().cloned().collect())
15042            .unwrap_or_default()
15043    }
15044
15045    /// §8.6 apply an inbound presence fanout to the local map.
15046    fn apply_presence(
15047        &mut self,
15048        scope_key: String,
15049        kind: Option<PresenceKind>,
15050        actor_id: Option<String>,
15051        client_id: Option<String>,
15052        doc: Option<Value>,
15053        error: Option<String>,
15054    ) {
15055        // A refused publish (§8.6.2) changes no peer; the native host surfaces
15056        // it as a `presence` event carrying the server's `error` code.
15057        if error.is_some() {
15058            return;
15059        }
15060        let (Some(kind), Some(actor_id), Some(client_id)) = (kind, actor_id, client_id) else {
15061            return;
15062        };
15063        let peer_key = format!("{actor_id} {client_id}");
15064        match kind {
15065            PresenceKind::Leave => {
15066                if let Some(peers) = self.presence.get_mut(&scope_key) {
15067                    peers.remove(&peer_key);
15068                    if peers.is_empty() {
15069                        self.presence.remove(&scope_key);
15070                    }
15071                }
15072            }
15073            _ => {
15074                let doc = match doc {
15075                    Some(Value::Object(_)) => doc.unwrap(),
15076                    _ => return,
15077                };
15078                self.presence.entry(scope_key).or_default().insert(
15079                    peer_key,
15080                    PresencePeer {
15081                        actor_id,
15082                        client_id,
15083                        doc,
15084                    },
15085                );
15086            }
15087        }
15088    }
15089
15090    /// Inbound JSON control message (§8.1). Unknown events are tolerated.
15091    pub fn on_realtime_text(&mut self, text: &str) {
15092        if self.stopped || self.transport_closed() || self.security_preflight {
15093            return;
15094        }
15095        match parse_control(text) {
15096            Ok(ControlMessage::Hello { requires_sync, .. }) => {
15097                if requires_sync {
15098                    // §8.1: pull before trusting the socket for continuity.
15099                    self.set_sync_needed(true, true);
15100                }
15101            }
15102            Ok(ControlMessage::Presence {
15103                scope_key,
15104                kind,
15105                actor_id,
15106                client_id,
15107                doc,
15108                error,
15109                ..
15110            }) => {
15111                self.apply_presence(scope_key, kind, actor_id, client_id, doc, error);
15112            }
15113            Ok(ControlMessage::Wake { .. }) => {
15114                // §8.3: any wake-up means "run a pull soon", never data.
15115                self.set_sync_needed(true, true);
15116            }
15117            Ok(ControlMessage::Scopes { .. }) => {
15118                // §3.3/§8.7: the grants changed, so the next `set_window`
15119                // re-arms every revoked value it names. No sync-needed, no round.
15120                self.window_armed.clear();
15121                self.scopes_changed += 1;
15122            }
15123            _ => {}
15124        }
15125    }
15126
15127    /// Inbound binary delta: a complete SSP2 response (§8.2), applied like
15128    /// a pull response per section; an unapplied delta is a wake-up.
15129    /// Mailbox hosts send durable acknowledgements on their I/O executor.
15130    pub fn on_realtime_binary_queued(&mut self, bytes: &[u8]) -> Vec<String> {
15131        let mut transport = crate::round::DownloadResults::default();
15132        self.on_realtime_binary(&mut transport, bytes);
15133        transport.controls
15134    }
15135
15136    /// §8.2: a delta applies exactly like a live section and sets the replica
15137    /// cursor to its `throughSeq`; one at or below the replica cursor is a
15138    /// duplicate. A delta the client does not apply (no live unit, a status
15139    /// other than `active`, a decode or apply failure) is a drop and raises
15140    /// sync-needed.
15141    pub fn on_realtime_binary(&mut self, transport: &mut dyn Transport, bytes: &[u8]) {
15142        if self.stopped || self.transport_closed() || self.security_preflight {
15143            return;
15144        }
15145        #[cfg(feature = "bench-internals")]
15146        let decode_phase = self.benchmark_phases.start(Phase::ResponseDecode);
15147        let message = match decode_message(bytes) {
15148            Ok(m) if m.msg_kind == MsgKind::Response => m,
15149            _ => {
15150                self.set_sync_needed(true, true);
15151                return;
15152            }
15153        };
15154        #[cfg(feature = "bench-internals")]
15155        drop(decode_phase);
15156        // §8.2: a delta's header means what a pull response's header means. A
15157        // schema floor (§1.6) is recorded, stops syncing and applies nothing.
15158        if let Some(Frame::RespHeader {
15159            required_schema_version: Some(required),
15160            latest_schema_version,
15161            ..
15162        }) = message.frames.first()
15163        {
15164            let floor = SchemaFloor {
15165                required_schema_version: Some(*required),
15166                latest_schema_version: *latest_schema_version,
15167            };
15168            if self.set_schema_floor(Some(floor)).is_err() {
15169                self.set_sync_needed(true, true);
15170            }
15171            return;
15172        }
15173        let through = message.frames.iter().find_map(|frame| match frame {
15174            Frame::LiveEnd { through_seq, .. } => Some(*through_seq),
15175            _ => None,
15176        });
15177        let epoch = self.get_meta(LOG_EPOCH_KEY).ok().flatten();
15178        let mut dropped = !matches!(message.frames.first(), Some(Frame::RespHeader {
15179                reset_required: false,
15180                log_epoch,
15181                ..
15182            }) if Some(log_epoch) == epoch.as_ref());
15183        let mut applied: Option<i64> = None;
15184        dropped |= self.begin_coalesced_apply().is_err();
15185        let mut receivers: Option<Vec<UnitRecord>> = None;
15186        for frame in message.frames {
15187            if dropped {
15188                break;
15189            }
15190            match frame {
15191                Frame::LiveStart { status, .. } => {
15192                    let Ok(cursor) = self.stored(replica_cursor(&self.conn)) else {
15193                        dropped = true;
15194                        break;
15195                    };
15196                    if status != LiveStatus::Active || cursor < 0 {
15197                        dropped = true;
15198                    } else if !through.is_some_and(|through| through <= cursor) {
15199                        // A catching-up unit receives no delta (§8.2).
15200                        receivers = self.stored(load_units(&self.conn)).ok().map(|units| {
15201                            units
15202                                .into_iter()
15203                                .filter(|unit| {
15204                                    unit.status == UnitStatus::Active
15205                                        && unit.echo.is_some()
15206                                        && unit.cursor.is_none()
15207                                })
15208                                .collect()
15209                        });
15210                        dropped = receivers.is_none();
15211                    }
15212                }
15213                Frame::Commit {
15214                    commit_seq,
15215                    tables,
15216                    changes,
15217                    ..
15218                } => {
15219                    let Some(receivers) = receivers.clone() else {
15220                        continue;
15221                    };
15222                    dropped = self
15223                        .apply_live_commit(
15224                            &receivers,
15225                            &tables,
15226                            changes,
15227                            commit_seq,
15228                            AppliedServerCommitSource::Delta,
15229                        )
15230                        .is_err();
15231                }
15232                Frame::LiveEnd { through_seq, .. } if receivers.is_some() => {
15233                    dropped = self
15234                        .set_meta(REPLICA_CURSOR_KEY, &through_seq.to_string())
15235                        .is_err();
15236                    applied = Some(through_seq);
15237                }
15238                Frame::Error { .. } => dropped = true,
15239                _ => {}
15240            }
15241        }
15242        // §1.4 rule 4: the ack follows the COMMIT. A failed COMMIT restored
15243        // the replica cursor, so the delta counts as a drop.
15244        if self.finish_coalesced_apply().is_err() || dropped {
15245            applied = None;
15246            dropped = true;
15247        }
15248        if let Some(cursor) = applied {
15249            // §8.2 ack point: the delta's throughSeq.
15250            let ack = format!("{{\"type\":\"ack\",\"cursor\":{cursor}}}");
15251            let _ = transport.realtime_send(&ack);
15252        }
15253        if dropped {
15254            self.set_sync_needed(true, true);
15255        }
15256    }
15257
15258    /// §8.2 ack point after a pull round on a live connection: the replica
15259    /// cursor while it is at least `0`.
15260    fn ack_after_pull(&mut self, transport: &mut dyn Transport) {
15261        if !self.realtime_connected() {
15262            return;
15263        }
15264        if let Ok(cursor @ 0..) = self.stored(replica_cursor(&self.conn)) {
15265            let ack = format!("{{\"type\":\"ack\",\"cursor\":{cursor}}}");
15266            let _ = transport.realtime_send(&ack);
15267        }
15268    }
15269}
15270
15271#[cfg(test)]
15272mod previous_version_wiring_tests;
15273
15274#[cfg(test)]
15275mod identity_tests;
15276
15277#[cfg(test)]
15278mod insert_intent_tests;
15279
15280#[cfg(test)]
15281mod robustness_tests;
15282
15283#[cfg(test)]
15284mod range_image_tests;