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 = 1024;
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    /// §7.6: only a code of a protocol family (§6.7, §10.3) is published. A
4002    /// server or host transport may answer any code-like text, which can
4003    /// carry application data.
4004    fn diagnostic_code(code: &str) -> String {
4005        let valid = code.len() <= 96
4006            && code.split_once('.').is_some_and(|(family, _)| {
4007                matches!(
4008                    family,
4009                    "sync"
4010                        | "blob"
4011                        | "client"
4012                        | "operation"
4013                        | "presence"
4014                        | "realtime"
4015                        | "transport"
4016                        | "storage"
4017                )
4018            })
4019            && code
4020                .bytes()
4021                .next()
4022                .is_some_and(|byte| byte.is_ascii_lowercase())
4023            && code.bytes().all(|byte| {
4024                byte.is_ascii_lowercase()
4025                    || byte.is_ascii_digit()
4026                    || matches!(byte, b'.' | b'_' | b'-')
4027            });
4028        if valid {
4029            code.to_owned()
4030        } else {
4031            "client.unknown_failure".to_owned()
4032        }
4033    }
4034
4035    fn set_sync_needed(&mut self, value: bool, interactive: bool) {
4036        if self.sync_needed != value {
4037            if self.begin_observation("syncular_status").is_ok() {
4038                self.sync_needed = value;
4039                let batch = ChangeAccumulator {
4040                    status: true,
4041                    ..ChangeAccumulator::default()
4042                };
4043                if self.finish_observation("syncular_status", batch).is_err() {
4044                    self.rollback_observation("syncular_status");
4045                }
4046            } else {
4047                self.sync_needed = value;
4048            }
4049        }
4050        if value && interactive {
4051            self.sync_intent_queue.push_back(SyncIntent::Interactive);
4052        }
4053    }
4054
4055    /// A unit-store result: a row that does not parse is `sync.local_corrupt`;
4056    /// every other SQLite error keeps its storage classification.
4057    fn stored<T>(&self, result: rusqlite::Result<T>) -> Result<T, String> {
4058        result.map_err(|error| match error {
4059            rusqlite::Error::FromSqlConversionFailure(..) => {
4060                "sync.local_corrupt: persisted unit state is invalid".to_owned()
4061            }
4062            error => Self::sqlite_failure(&self.storage_failure, error),
4063        })
4064    }
4065
4066    fn sqlite_failure(
4067        storage_failure: &RefCell<Option<QueryReadFailure>>,
4068        error: rusqlite::Error,
4069    ) -> String {
4070        let message = error.to_string();
4071        let failure = QueryReadFailure::from(error);
4072        let code = failure.code;
4073        if code.is_some() && storage_failure.borrow().is_none() {
4074            *storage_failure.borrow_mut() = Some(failure);
4075        }
4076        match code {
4077            Some(code) => format!("{code}: {message}"),
4078            None => message,
4079        }
4080    }
4081
4082    fn begin_observation(&self, name: &str) -> Result<(), String> {
4083        if let Some(failure) = &self.coalesced_failure {
4084            return Err(failure.clone());
4085        }
4086        // SQLite rolls a whole transaction back on some I/O and capacity
4087        // errors; later frames must not commit on their own after that.
4088        if self.coalesced.is_some() && self.conn.is_autocommit() {
4089            return Err("the coalesced apply transaction was rolled back".to_owned());
4090        }
4091        self.conn
4092            .execute_batch(&format!("SAVEPOINT {name}"))
4093            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
4094    }
4095
4096    /// SPEC §1.4 rule 4: open a coalesced apply transaction unless a caller
4097    /// already owns one.
4098    fn begin_coalesced_apply(&mut self) -> Result<(), String> {
4099        if self.coalesced.is_some() || !self.conn.is_autocommit() {
4100            return Ok(());
4101        }
4102        self.conn
4103            .execute_batch("BEGIN")
4104            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4105        self.coalesced = Some(CoalescedApply {
4106            rows: 0,
4107            rollback: self.capture(),
4108        });
4109        Ok(())
4110    }
4111
4112    fn capture(&self) -> Rollback {
4113        Rollback {
4114            outbox: self.outbox.clone(),
4115            failed_commits: self.failed_commits.clone(),
4116            conflicts: self.conflicts.clone(),
4117            rejections: self.rejections.clone(),
4118            schema_floor: self.schema_floor.clone(),
4119            lease_state: self.lease_state.clone(),
4120            stopped: self.stopped,
4121            upgrading: self.upgrading,
4122            upgrade_kept_tables: self.upgrade_kept_tables,
4123            sync_needed: self.sync_needed,
4124            active_round: self.active_round,
4125            overlay_dirty: self.overlay_dirty.snapshot(),
4126            transport_gate: self.transport_gate.clone(),
4127            transport_epoch: self.transport_epoch,
4128            change_queue: self.change_queue.len(),
4129            projection_pending_queue: self.projection_pending_queue.len(),
4130            sync_intent_queue: self.sync_intent_queue.len(),
4131            last_change: self.last_change.clone(),
4132        }
4133    }
4134
4135    fn restore(&mut self, rollback: Rollback) {
4136        self.outbox = rollback.outbox;
4137        self.failed_commits = rollback.failed_commits;
4138        self.conflicts = rollback.conflicts;
4139        self.rejections = rollback.rejections;
4140        self.schema_floor = rollback.schema_floor;
4141        self.lease_state = rollback.lease_state;
4142        self.stopped = rollback.stopped;
4143        self.upgrading = rollback.upgrading;
4144        self.upgrade_kept_tables = rollback.upgrade_kept_tables;
4145        self.sync_needed = rollback.sync_needed;
4146        self.active_round = rollback.active_round;
4147        self.transport_gate = rollback.transport_gate;
4148        self.transport_epoch = rollback.transport_epoch;
4149        self.overlay_dirty.restore(rollback.overlay_dirty);
4150        self.change_queue.truncate(rollback.change_queue);
4151        self.projection_pending_queue
4152            .truncate(rollback.projection_pending_queue);
4153        self.sync_intent_queue.truncate(rollback.sync_intent_queue);
4154        self.last_change = rollback.last_change;
4155    }
4156
4157    /// Account the rows of the next frame or block. A unit that would take the
4158    /// coalesced transaction past the bound commits the earlier units first.
4159    fn coalesce_unit(&mut self, rows: usize) -> Result<(), String> {
4160        let Some(open) = &self.coalesced else {
4161            return Ok(());
4162        };
4163        if open.rows > 0 && open.rows + rows > COALESCED_APPLY_ROWS {
4164            self.commit_coalesced_apply()?;
4165            self.begin_coalesced_apply()?;
4166        }
4167        if let Some(open) = &mut self.coalesced {
4168            open.rows += rows;
4169        }
4170        Ok(())
4171    }
4172
4173    /// COMMIT the coalesced transaction. A failed COMMIT rolls every coalesced
4174    /// frame back, restores the in-memory state of its `BEGIN`, drops the
4175    /// change batches and sync intents queued since, and fails the rest of the
4176    /// response.
4177    fn commit_coalesced_apply(&mut self) -> Result<(), String> {
4178        let Some(open) = self.coalesced.take() else {
4179            return Ok(());
4180        };
4181        let committed = if self.conn.is_autocommit() {
4182            Err("the coalesced apply transaction was rolled back".to_owned())
4183        } else {
4184            self.collect_projection_pending().and_then(|pending| {
4185                self.stored(self.conn.execute_batch("COMMIT"))?;
4186                self.projection_pending_queue.extend(pending);
4187                Ok(())
4188            })
4189        };
4190        let Err(error) = committed else {
4191            return Ok(());
4192        };
4193        if !self.conn.is_autocommit() {
4194            if let Err(rollback) = self.conn.execute_batch("ROLLBACK") {
4195                let _ = Self::sqlite_failure(&self.storage_failure, rollback);
4196            }
4197        }
4198        self.restore(open.rollback);
4199        self.coalesced_failure = Some(error.clone());
4200        Err(error)
4201    }
4202
4203    /// End the response's coalescing: COMMIT what is open and clear a failure.
4204    fn finish_coalesced_apply(&mut self) -> Result<(), String> {
4205        let committed = self.commit_coalesced_apply();
4206        match self.coalesced_failure.take() {
4207            Some(failure) => Err(failure),
4208            None => committed,
4209        }
4210    }
4211
4212    fn rollback_observation(&self, name: &str) {
4213        if let Err(error) = self
4214            .conn
4215            .execute_batch(&format!("ROLLBACK TO {name}; RELEASE {name}"))
4216        {
4217            if let Some(failure) = self.storage_failure.borrow_mut().as_mut() {
4218                if failure.rollback_failure.is_none() {
4219                    failure.rollback_failure = Some(Box::new(QueryReadFailure::from(error)));
4220                }
4221            }
4222        }
4223    }
4224
4225    fn finish_observation(
4226        &mut self,
4227        name: &str,
4228        mut batch: ChangeAccumulator,
4229    ) -> Result<(), String> {
4230        #[cfg(feature = "bench-internals")]
4231        let _phase = self.benchmark_phases.start(Phase::ObservationCommit);
4232        // §8.8: an acknowledged boundary ends a `through` gate.
4233        if matches!(self.transport_gate, crate::TransportGate::Through(_))
4234            && self.pushable_commits() == 0
4235        {
4236            self.move_transport_gate(crate::TransportGate::Pull);
4237        }
4238        for table in &self.schema.tables {
4239            for projection in &table.local_projections {
4240                if batch.tables.contains_key(&table.name)
4241                    || projection
4242                        .dependencies
4243                        .iter()
4244                        .any(|dep| batch.tables.contains_key(&dep.table))
4245                {
4246                    batch.table(&projection.name);
4247                }
4248            }
4249        }
4250        if self.failed_commits.iter().any(|(commit, _)| {
4251            commit
4252                .ops
4253                .iter()
4254                .any(|operation| batch.tables.contains_key(&operation.table))
4255        }) {
4256            batch.outcomes = true;
4257        }
4258        let projection_pending = if self.coalesced.is_none() && !self.opening_replica {
4259            self.collect_projection_pending()?
4260        } else {
4261            Vec::new()
4262        };
4263        if !batch.touched() {
4264            self.conn
4265                .execute_batch(&format!("RELEASE {name}"))
4266                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4267            self.projection_pending_queue.extend(projection_pending);
4268            return Ok(());
4269        }
4270        let revision = self
4271            .local_revision()?
4272            .checked_add(1)
4273            .ok_or_else(|| "local revision exhausted u64".to_owned())?;
4274        self.conn
4275            .execute(
4276                "INSERT OR REPLACE INTO _syncular_meta(key, value) VALUES (?1, ?2)",
4277                rusqlite::params![LOCAL_REVISION_KEY, revision.to_string()],
4278            )
4279            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4280        let status = batch.status.then(|| self.status_snapshot());
4281        let event = ClientChangeBatch {
4282            revision: revision.to_string(),
4283            tables: batch
4284                .tables
4285                .into_iter()
4286                .map(|(table, scope_keys)| TableChange {
4287                    table,
4288                    scope_keys: scope_keys.map(|keys| keys.into_iter().collect()),
4289                })
4290                .collect(),
4291            windows: batch
4292                .windows
4293                .into_iter()
4294                .map(|(base_key, units)| WindowChange {
4295                    base_key,
4296                    units: units.into_iter().collect(),
4297                })
4298                .collect(),
4299            status,
4300            conflicts_changed: batch.conflicts,
4301            rejections_changed: batch.rejections,
4302            outcomes_changed: batch.outcomes,
4303            applied_commits: Vec::new(),
4304        };
4305        self.conn
4306            .execute_batch(&format!("RELEASE {name}"))
4307            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4308        let mut diagnostic_tables = event
4309            .tables
4310            .iter()
4311            .map(|entry| entry.table.clone())
4312            .collect::<BTreeSet<_>>()
4313            .into_iter()
4314            .collect::<Vec<_>>();
4315        // §7.6: the selected variables of the changed window bases.
4316        let mut diagnostic_windows = event
4317            .windows
4318            .iter()
4319            .map(|entry| {
4320                entry
4321                    .base_key
4322                    .split('\0')
4323                    .next()
4324                    .unwrap_or_default()
4325                    .to_owned()
4326            })
4327            .collect::<BTreeSet<_>>()
4328            .into_iter()
4329            .collect::<Vec<_>>();
4330        let domains_truncated = diagnostic_tables.len() > MAX_DIAGNOSTIC_DOMAINS
4331            || diagnostic_windows.len() > MAX_DIAGNOSTIC_DOMAINS;
4332        diagnostic_tables.truncate(MAX_DIAGNOSTIC_DOMAINS);
4333        diagnostic_windows.truncate(MAX_DIAGNOSTIC_DOMAINS);
4334        self.last_change = Some(DiagnosticLastChange {
4335            revision: event.revision.clone(),
4336            recorded_at_ms: self.clock_now_ms(),
4337            tables: diagnostic_tables,
4338            windows: diagnostic_windows,
4339            domains_truncated,
4340            status_changed: event.status.is_some(),
4341            conflicts_changed: event.conflicts_changed,
4342            rejections_changed: event.rejections_changed,
4343            outcomes_changed: event.outcomes_changed,
4344        });
4345        self.change_queue.push_back(event);
4346        self.projection_pending_queue.extend(projection_pending);
4347        Ok(())
4348    }
4349
4350    fn record_scope_map(
4351        &self,
4352        batch: &mut ChangeAccumulator,
4353        table_name: &str,
4354        scopes: &[(String, Vec<String>)],
4355    ) {
4356        let Some(table) = self.schema.table(table_name) else {
4357            return;
4358        };
4359        // A bulk scoped delete whose map leaves a declared variable unnamed
4360        // cannot list the deleted rows' keys for it: the change is table-wide.
4361        if table.scope_variables.iter().any(|scope| {
4362            !scopes
4363                .iter()
4364                .any(|(variable, _)| *variable == scope.variable)
4365        }) {
4366            batch.table(table_name);
4367            return;
4368        }
4369        for (variable, values) in scopes {
4370            let Some(scope) = table
4371                .scope_variables
4372                .iter()
4373                .find(|scope| &scope.variable == variable)
4374            else {
4375                continue;
4376            };
4377            for value in values {
4378                batch.scope(table_name, format!("{}:{value}", scope.prefix));
4379            }
4380        }
4381    }
4382
4383    /// Record a row's current scope keys from the base or visible table.
4384    fn record_row_scopes(
4385        &self,
4386        batch: &mut ChangeAccumulator,
4387        table_name: &str,
4388        row_id: &str,
4389        base: bool,
4390    ) -> bool {
4391        let Some(table) = self.schema.table(table_name) else {
4392            return false;
4393        };
4394        if table.scope_variables.is_empty() {
4395            return false;
4396        }
4397        let columns = table
4398            .scope_variables
4399            .iter()
4400            .map(|scope| quote_ident(&scope.column))
4401            .collect::<Vec<_>>()
4402            .join(", ");
4403        let full_table = if base {
4404            base_table(table_name)
4405        } else {
4406            visible_table(table_name)
4407        };
4408        let sql = format!(
4409            "SELECT {columns} FROM {full_table} WHERE {} LIMIT 1",
4410            row_id_predicate(table)
4411        );
4412        let Ok(mut stmt) = self.conn.prepare_cached(&sql) else {
4413            return false;
4414        };
4415        let values = stmt.query_row(rusqlite::params![row_id], |row| {
4416            let mut values = Vec::with_capacity(table.scope_variables.len());
4417            for index in 0..table.scope_variables.len() {
4418                values.push(row.get::<_, Option<String>>(index)?);
4419            }
4420            Ok(values)
4421        });
4422        let Ok(values) = values else {
4423            return false;
4424        };
4425        let mut recorded = false;
4426        for (scope, value) in table.scope_variables.iter().zip(values) {
4427            if let Some(value) = value {
4428                batch.scope(table_name, format!("{}:{value}", scope.prefix));
4429                recorded = true;
4430            }
4431        }
4432        recorded
4433    }
4434
4435    fn record_commit_changes(
4436        &self,
4437        batch: &mut ChangeAccumulator,
4438        tables: &[String],
4439        changes: &[ssp2::model::Change],
4440    ) {
4441        #[cfg(feature = "bench-internals")]
4442        let _phase = self.benchmark_phases.start(Phase::ObservationPrepare);
4443        for change in changes {
4444            let Some(table_name) = tables.get(change.table_index as usize) else {
4445                continue;
4446            };
4447            let mut precise = self.record_row_scopes(batch, table_name, &change.row_id, true);
4448            if let Some(table) = self.schema.table(table_name) {
4449                for (variable, value) in &change.scopes {
4450                    if let Some(scope) = table
4451                        .scope_variables
4452                        .iter()
4453                        .find(|scope| &scope.variable == variable)
4454                    {
4455                        batch.scope(table_name, format!("{}:{value}", scope.prefix));
4456                        precise = true;
4457                    }
4458                }
4459            }
4460            if !precise {
4461                batch.table(table_name);
4462            }
4463        }
4464    }
4465
4466    /// Whether a base or visible row matches the scope predicate; `false`
4467    /// without a local scope-column mapping. A SQLite failure is an error.
4468    fn scoped_rows_exist(
4469        &self,
4470        table_name: &str,
4471        effective: &[(String, Vec<String>)],
4472        owners: &[Vec<(String, Vec<String>)>],
4473    ) -> Result<bool, String> {
4474        let Some(table) = self.schema.table(table_name) else {
4475            return Ok(false);
4476        };
4477        let Ok(Some((predicate, params))) = local_scope_predicate(table, effective, owners) else {
4478            return Ok(false);
4479        };
4480        for source in [base_table(table_name), visible_table(table_name)] {
4481            if self
4482                .conn
4483                .query_row(
4484                    &format!("SELECT EXISTS(SELECT 1 FROM {source} WHERE {predicate})"),
4485                    rusqlite::params_from_iter(&params),
4486                    |row| row.get::<_, bool>(0),
4487                )
4488                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
4489            {
4490                return Ok(true);
4491            }
4492        }
4493        Ok(false)
4494    }
4495
4496    /// §5.6 first-page clear of `unit_id`'s pair: delete its rows except
4497    /// those another owner covers (§3.3), failing closed without a local
4498    /// scope-column mapping. Owners are read only when a row matches, inside
4499    /// the caller's transaction. Returns whether rows matched.
4500    fn clear_scope(
4501        &mut self,
4502        table: &TableSchema,
4503        effective: &[(String, Vec<String>)],
4504        unit_id: &str,
4505    ) -> Result<bool, SectionError> {
4506        let storage = |message| SectionError::Abort("storage.failed".to_owned(), message);
4507        let matched = self
4508            .scoped_rows_exist(&table.name, effective, &[])
4509            .map_err(storage)?;
4510        let owners = if matched {
4511            unit_owners(
4512                &self.stored(load_units(&self.conn)).map_err(storage)?,
4513                table,
4514                unit_id,
4515            )
4516        } else {
4517            Vec::new()
4518        };
4519        let changed = matched
4520            && (owners.is_empty()
4521                || self
4522                    .scoped_rows_exist(&table.name, effective, &owners)
4523                    .map_err(storage)?);
4524        if !self
4525            .purge_scope_rows(&table.name, effective, &owners)
4526            .map_err(storage)?
4527        {
4528            return Err(SectionError::FailClosed);
4529        }
4530        Ok(changed)
4531    }
4532
4533    /// §7.4.5: true while a schema-bump reset + first re-bootstrap runs.
4534    pub fn upgrading(&self) -> bool {
4535        self.upgrading
4536    }
4537
4538    /// §7.4.2 "app ships new code": swap to a NEW generated schema while
4539    /// keeping this client's local database (identity, outbox, tables). The
4540    /// §7.4.1 marker check then fires the wipe/re-bootstrap flow when the
4541    /// version increases. Recreation runs the same marker guard as opening
4542    /// a durable replica, holds the guard and every write it authorizes under
4543    /// one write transaction, and preserves the current client (compiled
4544    /// schema, outbox, tables) on refusal.
4545    pub fn recreate_with_schema(&mut self, schema_json: &Value) -> Result<(), ClientError> {
4546        (|| -> Result<(), ClientError> {
4547            let new_schema = parse_schema_json(schema_json)?;
4548            validate_authority_reads(&new_schema, &self.limits.authority_reads)
4549                .map_err(|error| error.to_string())?;
4550            // §3.3: a reopened client remembers no re-armed window unit.
4551            self.window_armed.clear();
4552            self.conn
4553                .execute_batch("BEGIN IMMEDIATE")
4554                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4555            self.opening_replica = true;
4556            let prior_schema = std::mem::replace(&mut self.schema, new_schema);
4557            // §7.4.3/§7.4.4: a reset inside this transaction mutates in-memory
4558            // state (dropped outbox commits, rejections, upgrade and floor flags,
4559            // overlay dirtiness) and appends change/intent batches. A COMMIT that
4560            // fails after the reset succeeded rolls the database back, so every
4561            // one of those fields is captured here and restored with it.
4562            let rollback = self.capture();
4563            let guarded = (|| -> Result<(), ClientError> {
4564                // §7.4.2: the marker is re-read under the write lock the caller
4565                // holds, so a replica another process upgraded meanwhile refuses
4566                // this recreation instead of having its marker and tables
4567                // downgraded.
4568                let marker = read_local_schema_version(&self.conn, self.schema.version)?;
4569                self.create_bookkeeping_tables()?;
4570                match marker {
4571                    Some(version) if version < self.schema.version => self.run_schema_reset()?,
4572                    None => {
4573                        self.detach_projections(None)?;
4574                        self.create_synced_tables()?;
4575                        self.persist_schema_version()?;
4576                    }
4577                    Some(_) => {
4578                        self.detach_projections(None)?;
4579                        self.create_synced_tables()?;
4580                    }
4581                }
4582                // §7.4.2: recreation IS the boot for the in-memory core, so reload the
4583                // durable outbox the same-version path is about to replay. Only the
4584                // outbox is reloaded: the recovery below reads it, and the caller's
4585                // rollback snapshot already covers this field.
4586                self.outbox = self.load_outbox()?.into();
4587                // §7.1/§7.4.4: recover intrinsically codec-invalid persisted values at
4588                // this guarded boundary once the schema and marker agree. A bump went
4589                // through `run_schema_reset`, which performs the same recovery after
4590                // it creates the new physical tables and before its final replay.
4591                self.drop_unencodable_outbox(false, None)?;
4592                if marker == Some(self.schema.version)
4593                    && (!self.outbox.is_empty()
4594                        || !self.failed_commits.is_empty()
4595                        || self.has_acknowledged_rows()?)
4596                {
4597                    self.overlay_dirty.set(true);
4598                    self.rebuild_overlay()?;
4599                }
4600                self.prune_unknown_units(false)?;
4601                self.save_unit_scope_schema()?;
4602                // The conformance recreate is the in-memory equivalent of reopening
4603                // a durable client. Apply the same startup catch-up contract even
4604                // when the schema itself did not change; a client in preflight
4605                // gets it at activation (§5.11).
4606                if !self.security_preflight {
4607                    self.enqueue_startup_sync_if_needed()?;
4608                }
4609                self.projection_pending_queue
4610                    .extend(self.collect_projection_pending()?);
4611                Ok(())
4612            })();
4613            self.opening_replica = false;
4614            let outcome = match guarded {
4615                Ok(()) => self
4616                    .conn
4617                    .execute_batch("COMMIT")
4618                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error).into()),
4619                Err(error) => Err(error),
4620            };
4621            if let Err(error) = outcome {
4622                if let Err(rollback) = self.conn.execute_batch("ROLLBACK") {
4623                    // Keep a failed rollback's typed storage classification.
4624                    let _ = Self::sqlite_failure(&self.storage_failure, rollback);
4625                }
4626                self.schema = prior_schema;
4627                self.restore(rollback);
4628                // Prepared insert statements were derived from the reverted schema.
4629                self.insert_sql.borrow_mut().clear();
4630                return Err(error);
4631            }
4632            if !self.security_preflight {
4633                self.drain_pending_evictions()?;
4634            }
4635            Ok(())
4636        })()
4637        .map_err(open_failure)
4638    }
4639
4640    fn enqueue_startup_sync_if_needed(&mut self) -> Result<(), String> {
4641        let startup_work = !self.stopped
4642            && (!self.outbox.is_empty()
4643                || self.has_acknowledged_rows()?
4644                || !self.load_pending_evictions()?.is_empty()
4645                || self
4646                    .stored(load_units(&self.conn))?
4647                    .iter()
4648                    .any(|unit| unit.status == UnitStatus::Active));
4649        if startup_work {
4650            self.sync_needed = true;
4651            self.sync_intent_queue.push_back(SyncIntent::Interactive);
4652        }
4653        Ok(())
4654    }
4655
4656    /// A native client persists schema-floor stops across process restarts.
4657    /// Once the running app already satisfies that floor, the persisted stop
4658    /// is only stale evidence from an older server round (for example, the
4659    /// server was restarted after catching up to an app that was ahead).
4660    /// Clear it and let the normal startup pull re-negotiate. If the server is
4661    /// still incompatible it will return the floor again in that first round.
4662    fn clear_satisfied_persisted_schema_floor(&mut self) -> Result<(), String> {
4663        let satisfied = self
4664            .schema_floor
4665            .as_ref()
4666            .and_then(|floor| floor.required_schema_version)
4667            .is_some_and(|required| self.schema.version >= required);
4668        if !satisfied {
4669            return Ok(());
4670        }
4671        self.delete_meta(SCHEMA_FLOOR_KEY)?;
4672        self.schema_floor = None;
4673        self.stopped = false;
4674        Ok(())
4675    }
4676
4677    /// RFC 0005 D1: discard an orphan or stale container at boot. The reset
4678    /// path already swept it; this covers a same-version or fresh-install open,
4679    /// which runs no reset and therefore no sweep — plus the D7 TTL, which only
4680    /// an aware binary can apply.
4681    fn reconcile_previous_version_at_boot(&self) -> Result<(), String> {
4682        let Some(replica_path) = self.previous_version_replica_path() else {
4683            return Ok(());
4684        };
4685        let max_age_ms = self
4686            .previous_version
4687            .filter(|config| config.enabled)
4688            .map(|config| config.max_age_ms);
4689        reconcile_previous_version_at_boot(
4690            &self.conn,
4691            &replica_path,
4692            self.schema.version,
4693            max_age_ms,
4694            self.clock_now_ms(),
4695        )
4696    }
4697
4698    /// RFC 0005 D3: the sibling container path, or `None` when the replica has
4699    /// no file — an in-memory replica returns an empty path, and a `file:` URI
4700    /// has no plain sibling path — so the feature resolves as off there.
4701    fn previous_version_replica_path(&self) -> Option<String> {
4702        let path = self.conn.path()?;
4703        if path.is_empty() || path.starts_with("file:") {
4704            return None;
4705        }
4706        Some(path.to_owned())
4707    }
4708
4709    /// §7.4.3 reset: whole-database local reset EXCEPT the outbox, clientId,
4710    /// and leaseState. Drops/recreates every synced table from the new
4711    /// schema, resets unit sync state (keeping registrations), clears
4712    /// the schema-floor stop state, rewrites the marker, drops outbox commits
4713    /// that cannot re-encode (§7.4.4), and replays the survivors on top.
4714    fn run_schema_reset(&mut self) -> Result<(), String> {
4715        self.begin_observation("syncular_schema_reset")?;
4716        let rollback = self.capture();
4717        let mut batch = ChangeAccumulator::default();
4718        let result = self
4719            .run_schema_reset_observed(&mut batch, true)
4720            .and_then(|()| self.finish_observation("syncular_schema_reset", batch));
4721        if let Err(error) = result {
4722            self.rollback_observation("syncular_schema_reset");
4723            self.restore(rollback);
4724            return Err(error);
4725        }
4726        // After the commit: a rolled-back reset keeps the in-flight round.
4727        self.cancel_sync_round();
4728        Ok(())
4729    }
4730
4731    fn run_log_epoch_reset(&mut self, log_epoch: &str) -> Result<Vec<String>, String> {
4732        if self.get_meta(LOG_EPOCH_KEY)?.is_none() {
4733            self.begin_observation("syncular_epoch_acquisition")?;
4734            let rollback = self.capture();
4735            if let Err(error) = self.conn.execute(
4736                "INSERT OR REPLACE INTO _syncular_meta(key,value) VALUES (?1,?2)",
4737                rusqlite::params![LOG_EPOCH_KEY, log_epoch],
4738            ) {
4739                self.rollback_observation("syncular_epoch_acquisition");
4740                return Err(Self::sqlite_failure(&self.storage_failure, error));
4741            }
4742            self.sync_needed = true;
4743            let batch = ChangeAccumulator {
4744                status: true,
4745                ..ChangeAccumulator::default()
4746            };
4747            if let Err(error) = self.finish_observation("syncular_epoch_acquisition", batch) {
4748                self.rollback_observation("syncular_epoch_acquisition");
4749                self.restore(rollback);
4750                return Err(error);
4751            }
4752            self.sync_intent_queue.push_back(SyncIntent::Interactive);
4753            return Ok(Vec::new());
4754        }
4755        let resets = self
4756            .stored(load_units(&self.conn))?
4757            .into_iter()
4758            .map(|unit| unit.id)
4759            .collect();
4760        self.begin_observation("syncular_log_epoch_reset")?;
4761        let rollback = self.capture();
4762        let mut batch = ChangeAccumulator::default();
4763        let result = self
4764            .run_schema_reset_observed(&mut batch, false)
4765            .and_then(|()| {
4766                self.conn
4767                    .execute(
4768                        "INSERT OR REPLACE INTO _syncular_meta(key,value) VALUES (?1,?2)",
4769                        rusqlite::params![LOG_EPOCH_KEY, log_epoch],
4770                    )
4771                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4772                self.sync_needed = true;
4773                batch.status = true;
4774                self.finish_observation("syncular_log_epoch_reset", batch)
4775            });
4776        if let Err(error) = result {
4777            self.rollback_observation("syncular_log_epoch_reset");
4778            self.restore(rollback);
4779            return Err(error);
4780        }
4781        self.cancel_sync_round();
4782        self.sync_intent_queue.push_back(SyncIntent::Interactive);
4783        Ok(resets)
4784    }
4785
4786    fn run_schema_reset_observed(
4787        &mut self,
4788        batch: &mut ChangeAccumulator,
4789        capture: bool,
4790    ) -> Result<(), String> {
4791        // §7.4.2: the reset is the only path that wipes local tables for a
4792        // version bump, and it rewrites the marker last. Re-read the marker
4793        // under this reset's transaction: a replica another process upgraded
4794        // meanwhile refuses here instead of being reset to this client's
4795        // older schema.
4796        read_local_schema_version(&self.conn, self.schema.version)
4797            .map_err(|error| error.to_string())?;
4798        // §7.4.3: a schema bump keeps every table whose generation or one of
4799        // its equivalent generations equals the persisted one; the log-epoch
4800        // reset keeps nothing. The previous
4801        // declaration evidence decides which units cover only kept tables.
4802        let mut kept = BTreeSet::new();
4803        let mut previous_declarations: Option<BTreeMap<String, BTreeMap<String, Value>>> = None;
4804        if capture {
4805            let persisted: BTreeMap<String, String> = self
4806                .get_meta(TABLE_GENERATIONS_KEY)?
4807                .map(|raw| serde_json::from_str(&raw))
4808                .transpose()
4809                .map_err(|_| "sync.local_corrupt: invalid persisted table generations".to_owned())?
4810                .unwrap_or_default();
4811            kept = self
4812                .schema
4813                .tables
4814                .iter()
4815                .filter(|table| {
4816                    table.generation.is_some()
4817                        && persisted.get(&table.name).is_some_and(|stored| {
4818                            table.generation.as_ref() == Some(stored)
4819                                || table.equivalent_generations.contains(stored)
4820                        })
4821                })
4822                .map(|table| table.name.clone())
4823                .collect();
4824            previous_declarations = self
4825                .get_meta("subscriptionScopeSchema")?
4826                .map(|raw| serde_json::from_str(&raw))
4827                .transpose()
4828                .map_err(|_| "sync.local_corrupt: invalid persisted scope schema".to_owned())?;
4829        }
4830        // Kept tables keep both halves and their row-level bookkeeping; the
4831        // projections of kept tables keep their storage.
4832        let mut kept_objects = BTreeSet::new();
4833        for table in self
4834            .schema
4835            .tables
4836            .iter()
4837            .filter(|table| kept.contains(&table.name))
4838        {
4839            kept_objects.insert(table.name.clone());
4840            kept_objects.insert(format!("_syncular_base_{}", table.name));
4841        }
4842        kept_objects.extend(self.detach_projections(Some(&kept))?);
4843        let kept_json = serde_json::to_string(&kept).expect("table names serialize");
4844        for sql in [
4845            "DELETE FROM _syncular_acked_rows WHERE tbl NOT IN (SELECT value FROM json_each(?1))",
4846            "DELETE FROM _syncular_row_deliveries WHERE tbl NOT IN (SELECT value FROM json_each(?1))",
4847        ] {
4848            self.conn
4849                .execute(sql, [&kept_json])
4850                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4851        }
4852        self.upgrading = true;
4853        self.upgrade_kept_tables = !kept.is_empty();
4854        batch.status = true;
4855        // RFC 0005 D6: classify the pending outbox against the NEW compiled
4856        // schema BEFORE the wipe, and record the advisory audit. This pass
4857        // drops nothing, so the audit sees the original pending intent; the
4858        // §7.4.4 send-time drop and the intrinsic value recovery later in this
4859        // reset are the paths that remove a commit. The classification is
4860        // shared with the send-time drop so the two cannot disagree about what
4861        // is incompatible.
4862        if self.previous_version.is_some_and(|config| config.enabled) {
4863            let previous_version = self
4864                .get_meta(LOCAL_SCHEMA_VERSION_KEY)?
4865                .and_then(|value| value.parse::<i32>().ok())
4866                .unwrap_or(self.schema.version);
4867            let pending = self
4868                .outbox
4869                .iter()
4870                .map(|commit| PendingCommitAudit {
4871                    commit_id: &commit.client_commit_id,
4872                    operations: commit_audit_operations(commit),
4873                })
4874                .collect::<Vec<_>>();
4875            crate::previous_version::write_previous_version_audit(
4876                &self.conn,
4877                &crate::previous_version::build_previous_version_audit(
4878                    &self.schema,
4879                    &pending,
4880                    previous_version,
4881                    self.schema.version,
4882                    self.clock_now_ms(),
4883                ),
4884            )?;
4885        }
4886        // RFC 0005 D5: the container lives in its own FILE, so the reset can
4887        // never reach it. Sweep first (unconditional — also on the log-epoch
4888        // reset, which captures nothing), then capture BEFORE the wipe drops
4889        // any row. A refused capture records its reason and leaves no file.
4890        if let Some(replica_path) = self.previous_version_replica_path() {
4891            sweep_previous_version_container(&self.conn, &replica_path)?;
4892            if capture {
4893                if let Some(config) = self.previous_version.filter(|config| config.enabled) {
4894                    let previous_version = self
4895                        .get_meta(LOCAL_SCHEMA_VERSION_KEY)?
4896                        .and_then(|value| value.parse::<i32>().ok())
4897                        .unwrap_or(self.schema.version);
4898                    capture_previous_version_from_replica(
4899                        &self.conn,
4900                        &replica_path,
4901                        previous_version,
4902                        self.schema.version,
4903                        &config,
4904                        self.clock_now_ms(),
4905                    )?;
4906                }
4907            }
4908        }
4909        for table in self
4910            .schema
4911            .tables
4912            .iter()
4913            .filter(|table| !kept.contains(&table.name))
4914        {
4915            batch.table(&table.name);
4916        }
4917        for unit in self.stored(load_units(&self.conn))? {
4918            self.record_unit_windows(batch, &unit)?;
4919        }
4920        if capture {
4921            self.prune_unknown_units(true)?;
4922        }
4923        // The per-table insert SQL is derived from the OLD column lists.
4924        self.insert_sql.borrow_mut().clear();
4925        self.overlay_dirty.set(true);
4926        // Drop every synced table (base + visible) that currently exists —
4927        // discovered from sqlite_master so a bump that adds/removes tables is
4928        // handled. Bookkeeping tables (`_syncular_outbox/_units/_meta`
4929        // and the blob cache) are preserved; base tables are `_syncular_base_*`
4930        // so they are matched explicitly, not by the bookkeeping filter.
4931        // Drop virtual tables first so SQLite removes every FTS shadow table
4932        // atomically instead of the generic discovery tearing it apart.
4933        let virtual_tables: Vec<String> = {
4934            let mut stmt = self
4935                .conn
4936                .prepare(
4937                    "SELECT name FROM sqlite_master WHERE type = 'table' AND sql LIKE 'CREATE VIRTUAL TABLE%'",
4938                )
4939                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4940            let rows = stmt
4941                .query_map([], |row| row.get::<_, String>(0))
4942                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4943            rows.filter_map(Result::ok)
4944                .filter(|name| is_synced_table_name(name) && !kept_objects.contains(name))
4945                .collect()
4946        };
4947        for name in virtual_tables {
4948            self.conn
4949                .execute_batch(&format!(
4950                    "DROP TABLE IF EXISTS {}",
4951                    quote_ident(&format!("_syncular_fts_{name}"))
4952                ))
4953                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4954            self.conn
4955                .execute(&format!("DROP TABLE IF EXISTS {}", quote_ident(&name)), [])
4956                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4957        }
4958        let existing: Vec<String> = {
4959            let mut stmt = self
4960                .conn
4961                .prepare("SELECT name FROM sqlite_master WHERE type = 'table'")
4962                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4963            let rows = stmt
4964                .query_map([], |row| row.get::<_, String>(0))
4965                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4966            rows.filter_map(Result::ok)
4967                .filter(|name| is_synced_table_name(name) && !kept_objects.contains(name))
4968                .collect()
4969        };
4970        for name in &existing {
4971            if let Some(table) = name.strip_prefix("_syncular_base_") {
4972                batch.table(table);
4973            } else if !name.starts_with("_syncular_") {
4974                batch.table(name);
4975            }
4976        }
4977        for name in existing {
4978            self.conn
4979                .execute(&format!("DROP TABLE IF EXISTS {}", quote_ident(&name)), [])
4980                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4981        }
4982        // Recreate the synced tables from the NEW schema.
4983        self.create_synced_tables()?;
4984        // Reset the sync state of every unit that covers a table the reset
4985        // did not keep, under the previous declarations or the new schema,
4986        // keeping the registration.
4987        let keep_units = match &previous_declarations {
4988            Some(previous) if !kept.is_empty() => self
4989                .stored(load_units(&self.conn))?
4990                .into_iter()
4991                .filter(|unit| {
4992                    previous.iter().all(|(name, old)| {
4993                        kept.contains(name) || !unit.scopes.keys().all(|v| old.contains_key(v))
4994                    }) && self
4995                        .schema
4996                        .tables
4997                        .iter()
4998                        .all(|table| kept.contains(&table.name) || !covers(table, &unit.scopes))
4999                })
5000                .map(|unit| unit.id)
5001                .collect(),
5002            _ => BTreeSet::new(),
5003        };
5004        // §7.4.3 restriction: an active unit that is not kept and whose rows
5005        // of a kept table are complete through a cursor C (its restriction's,
5006        // its post-bootstrap P, or the replica cursor it is live under)
5007        // bootstraps only its other covered tables and joins at C.
5008        let restrictions = if capture {
5009            let replica = self.stored(replica_cursor(&self.conn))?;
5010            let mut restrictions = BTreeMap::new();
5011            for unit in self.stored(load_units(&self.conn))? {
5012                if keep_units.contains(&unit.id) || unit.status != UnitStatus::Active {
5013                    continue;
5014                }
5015                let cursor = match (&unit.restriction, unit.cursor) {
5016                    (Some(restriction), _) => restriction.cursor,
5017                    (None, Some(cursor)) if cursor >= 0 && unit.bootstrap_state.is_none() => cursor,
5018                    (None, None) if replica >= 0 => replica,
5019                    _ => continue,
5020                };
5021                let covered: Vec<&String> = self
5022                    .schema
5023                    .tables
5024                    .iter()
5025                    .filter(|table| covers(table, &unit.scopes))
5026                    .map(|table| &table.name)
5027                    .collect();
5028                let mut tables: Vec<String> = covered
5029                    .iter()
5030                    .filter(|name| {
5031                        !kept.contains(**name)
5032                            || unit
5033                                .restriction
5034                                .as_ref()
5035                                .is_some_and(|restriction| restriction.tables.contains(name))
5036                    })
5037                    .map(|name| (*name).clone())
5038                    .collect();
5039                if tables.is_empty() || tables.len() == covered.len() {
5040                    continue;
5041                }
5042                tables.sort_by(|a, b| a.encode_utf16().cmp(b.encode_utf16()));
5043                restrictions.insert(unit.id, UnitRestriction { cursor, tables });
5044            }
5045            Some(restrictions)
5046        } else {
5047            None
5048        };
5049        reset_units(&self.conn, &keep_units, restrictions.as_ref())
5050            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5051        // The stop state is over: this client now ships a servable schema.
5052        self.stopped = false;
5053        self.schema_floor = None;
5054        self.delete_meta(SCHEMA_FLOOR_KEY)?;
5055        // Rewrite the marker LAST so a crash mid-reset re-runs the reset.
5056        self.persist_schema_version()?;
5057        self.save_unit_scope_schema()?;
5058        // §7.1/§7.4.4: the previous-version capture and audit above saw the
5059        // original pending intent; the synced tables now carry the new schema, so
5060        // recover intrinsically codec-invalid persisted values here, before the
5061        // final replay. A pending upsert that names a column the new schema
5062        // removed stays pending for the send-time `drop_incompatible_outbox`
5063        // prepass. The reset wrapper snapshots and restores the outbox,
5064        // rejections, and change queues, so a failed commit rolls this recovery
5065        // back with the rest of the reset.
5066        // §7.4.4: the enclosing reset observation owns the publication, so the
5067        // recovery contributes its rejection, outcome, and table domains to it.
5068        self.drop_unencodable_outbox(false, Some(batch))?;
5069        // Re-apply the surviving outbox optimistically over the empty tables.
5070        self.rebuild_overlay()?;
5071        Ok(())
5072    }
5073
5074    /// §7.4.4 send-time prepass: a persisted upsert whose values reference a
5075    /// column the current schema lacks (or a removed table) cannot be encoded
5076    /// (`commit_audit_operations` inspects upserts, so a value-free delete stays
5077    /// encodable and is validated by the server), nor can an insert-intent
5078    /// upsert that lacks a non-nullable column (§7.1, the audit's
5079    /// `missing-required-column`). Drop the commit, undo
5080    /// its optimistic projection, and raise a client-local
5081    /// `sync.outbox_incompatible` rejection.
5082    fn drop_incompatible_outbox(&mut self) -> Result<bool, String> {
5083        // §8.8: only the commits this round pushes; a held commit waits.
5084        let incompatible = self
5085            .outbox
5086            .iter()
5087            .take(self.pushable_commits())
5088            .filter(|commit| {
5089                first_incompatibility(&self.schema, &commit_audit_operations(commit)).is_some()
5090            })
5091            .cloned()
5092            .collect::<Vec<_>>();
5093        if incompatible.is_empty() {
5094            return Ok(false);
5095        }
5096        self.drop_outbox_commits(
5097            &incompatible,
5098            OUTBOX_INCOMPATIBLE_CODE,
5099            "the persisted commit cannot encode under the current schema",
5100        )?;
5101        Ok(true)
5102    }
5103
5104    /// §7.4.4 incompatible-commit path, also taken by a refused blob upload
5105    /// (§5.9.7) with the server's code: reject every operation of `commits`,
5106    /// remove them from the outbox, and undo their optimistic rows.
5107    fn drop_outbox_commits(
5108        &mut self,
5109        incompatible: &[Arc<OutboxCommit>],
5110        code: &str,
5111        message: &str,
5112    ) -> Result<(), String> {
5113        // §7.4.4: one observation covers the durable outcome writes, the outbox
5114        // removal, the in-memory drop, and the overlay rebuild, so a storage
5115        // fault leaves the replica and the client unchanged and publishes no
5116        // change; a successful drop publishes exactly one batch carrying the
5117        // rejections, outcomes, status, and the tables whose projection changed.
5118        let rollback = self.capture();
5119        let owns_transaction = self.conn.is_autocommit();
5120        self.begin_observation("syncular_outbox_drop")?;
5121        let mut batch = ChangeAccumulator::default();
5122        let dropped = (|| -> Result<(), String> {
5123            let mut rejections = Vec::new();
5124            for commit in incompatible {
5125                let results = commit
5126                    .ops
5127                    .iter()
5128                    .enumerate()
5129                    .map(|(op_index, operation)| {
5130                        let rejection = RejectionRecord {
5131                            client_commit_id: commit.client_commit_id.clone(),
5132                            op_index: op_index as i32,
5133                            code: code.to_owned(),
5134                            message: message.to_owned(),
5135                            retryable: false,
5136                            details: None,
5137                            operation: Some(CommitOperation::from(operation)),
5138                        };
5139                        rejections.push(rejection.clone());
5140                        CommitOperationOutcome::Error { rejection }
5141                    })
5142                    .collect::<Vec<_>>();
5143                self.persist_commit_outcome(
5144                    &commit.client_commit_id,
5145                    CommitOutcomeStatus::Rejected,
5146                    &results,
5147                    Some(&commit.ops),
5148                )?;
5149                self.leave_through(&commit.client_commit_id);
5150                self.delete_outbox_persisted(&commit.client_commit_id)?;
5151                // A removed table has no local projection to invalidate; every
5152                // surviving table the dropped commit touched does.
5153                for operation in &commit.ops {
5154                    if self.schema.table(&operation.table).is_some() {
5155                        batch.table(&operation.table);
5156                    }
5157                }
5158            }
5159            self.prune_commit_outcomes()?;
5160            let incompatible_ids = incompatible
5161                .iter()
5162                .map(|commit| commit.client_commit_id.as_str())
5163                .collect::<BTreeSet<_>>();
5164            self.outbox
5165                .retain(|commit| !incompatible_ids.contains(commit.client_commit_id.as_str()));
5166            self.rejections.extend(rejections);
5167            // The dropped commits' purely-optimistic rows are undone: the
5168            // visible projection is re-derived from the surviving base + outbox.
5169            self.overlay_dirty.set(true);
5170            self.rebuild_overlay()?;
5171            batch.status = true;
5172            batch.rejections = true;
5173            batch.outcomes = true;
5174            Ok(())
5175        })();
5176        let result = dropped.and_then(|()| self.finish_observation("syncular_outbox_drop", batch));
5177        if let Err(error) = result {
5178            // An outer RELEASE is the COMMIT. Roll back that transaction
5179            // directly: retrying RELEASE after ROLLBACK TO still needs the
5180            // reader's lock. A nested observation only rolls back its savepoint.
5181            if owns_transaction {
5182                if let Err(rollback) = self.conn.execute_batch("ROLLBACK") {
5183                    let mut failure = self.storage_failure.borrow_mut();
5184                    let failure =
5185                        failure.get_or_insert_with(|| QueryReadFailure::from(error.clone()));
5186                    failure.rollback_failure = Some(Box::new(QueryReadFailure::from(rollback)));
5187                }
5188            } else {
5189                self.rollback_observation("syncular_outbox_drop");
5190            }
5191            self.restore(rollback);
5192            return Err(error);
5193        }
5194        Ok(())
5195    }
5196
5197    /// §7.4.3: (re)create the base + visible table pair for every synced
5198    /// table in the CURRENT schema (idempotent — `IF NOT EXISTS`).
5199    fn create_synced_tables(&self) -> Result<(), String> {
5200        for table in &self.schema.tables {
5201            // The base half + the visible half form the synced-table pair. An
5202            // index name is global in SQLite, so the base half's indexes are
5203            // name-prefixed (`_syncular_base_<index>`) to stay distinct.
5204            for (full, index_prefix) in [
5205                (base_table(&table.name), "_syncular_base_"),
5206                (visible_table(&table.name), ""),
5207            ] {
5208                let mut cols: Vec<String> =
5209                    table.columns.iter().map(|c| quote_ident(&c.name)).collect();
5210                cols.push("\"_syncular_version\" INTEGER NOT NULL".to_owned());
5211                cols.extend(
5212                    table
5213                        .sealed_columns()
5214                        .iter()
5215                        .map(|name| format!("{} TEXT", quote_ident(name))),
5216                );
5217                let sql = format!(
5218                    "CREATE TABLE IF NOT EXISTS {full} ({} , PRIMARY KEY ({}))",
5219                    cols.join(", "),
5220                    quote_ident(&table.primary_key)
5221                );
5222                self.conn
5223                    .execute(&sql, [])
5224                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5225                // §5.11: a replica created before sealed apply gains the
5226                // reserved columns in place, on both halves in the same order,
5227                // so data, indexes and the FTS projection stay.
5228                for name in table.sealed_columns() {
5229                    let present: bool = self
5230                        .conn
5231                        .query_row(
5232                            "SELECT EXISTS(SELECT 1 FROM pragma_table_info(?1) WHERE name = ?2)",
5233                            rusqlite::params![format!("{index_prefix}{}", table.name), name],
5234                            |row| row.get(0),
5235                        )
5236                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5237                    if !present {
5238                        self.conn
5239                            .execute(
5240                                &format!(
5241                                    "ALTER TABLE {full} ADD COLUMN {} TEXT",
5242                                    quote_ident(name)
5243                                ),
5244                                [],
5245                            )
5246                            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5247                    }
5248                }
5249                // The reveal at every round start reads the sealed rows of the
5250                // base half through this partial index.
5251                if table.has_encrypted_columns() && !index_prefix.is_empty() {
5252                    self.conn
5253                        .execute(
5254                            &format!(
5255                                "CREATE INDEX IF NOT EXISTS {} ON {full} (\"_sync_sealed_key\") WHERE \"_sync_sealed_key\" IS NOT NULL",
5256                                quote_ident(&format!("_syncular_sealed_{}", table.name))
5257                            ),
5258                            [],
5259                        )
5260                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5261                }
5262            }
5263        }
5264        // §7.4.3 declared indexes: reconciled in place on both halves (the
5265        // base half's names carry the `_syncular_base_` prefix) at every open
5266        // and at the end of every reset. `localIndexes` records the declared
5267        // names Syncular created; only those are ever dropped.
5268        let recorded: BTreeMap<String, BTreeSet<String>> = match self.get_meta("localIndexes")? {
5269            Some(raw) => serde_json::from_str(&raw)
5270                .map_err(|_| "sync.local_corrupt: invalid persisted local indexes".to_owned())?,
5271            // A replica without the record: every declared index that exists
5272            // counts as created by Syncular, so nothing is stale.
5273            None => BTreeMap::new(),
5274        };
5275        let declared: BTreeMap<String, BTreeSet<String>> = self
5276            .schema
5277            .tables
5278            .iter()
5279            .filter(|table| !table.indexes.is_empty())
5280            .map(|table| {
5281                let names = table.indexes.iter().map(|index| index.name.clone());
5282                (table.name.clone(), names.collect())
5283            })
5284            .collect();
5285        for (table, names) in &recorded {
5286            for name in names.iter().filter(|name| {
5287                !declared
5288                    .get(table)
5289                    .is_some_and(|declared| declared.contains(*name))
5290            }) {
5291                self.stored(self.conn.execute_batch(&format!(
5292                    "DROP INDEX IF EXISTS {}; DROP INDEX IF EXISTS {}",
5293                    quote_ident(name),
5294                    quote_ident(&format!("_syncular_base_{name}"))
5295                )))?;
5296            }
5297        }
5298        for table in &self.schema.tables {
5299            for index in &table.indexes {
5300                for (owner, name) in [
5301                    (
5302                        format!("_syncular_base_{}", table.name),
5303                        format!("_syncular_base_{}", index.name),
5304                    ),
5305                    (table.name.clone(), index.name.clone()),
5306                ] {
5307                    let current: Option<(String, bool, bool)> = self.stored(
5308                        self.conn
5309                            .query_row(
5310                                "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",
5311                                [&name],
5312                                |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
5313                            )
5314                            .optional(),
5315                    )?;
5316                    if let Some((current_owner, unique, partial)) = current {
5317                        let mut stmt = self
5318                            .stored(self.conn.prepare(
5319                                "SELECT name FROM pragma_index_info(?1) ORDER BY seqno",
5320                            ))?;
5321                        let columns = self.stored(
5322                            self.stored(
5323                                stmt.query_map([&name], |row| row.get::<_, Option<String>>(0)),
5324                            )?
5325                            .collect::<Result<Vec<_>, _>>(),
5326                        )?;
5327                        if current_owner == owner
5328                            && unique == index.unique
5329                            && !partial
5330                            && columns
5331                                .iter()
5332                                .map(Option::as_deref)
5333                                .eq(index.columns.iter().map(|column| Some(column.as_str())))
5334                        {
5335                            continue;
5336                        }
5337                        self.stored(
5338                            self.conn
5339                                .execute(&format!("DROP INDEX {}", quote_ident(&name)), []),
5340                        )?;
5341                    }
5342                    self.stored(self.conn.execute(
5343                        &format!(
5344                            "CREATE {}INDEX {} ON {} ({})",
5345                            if index.unique { "UNIQUE " } else { "" },
5346                            quote_ident(&name),
5347                            quote_ident(&owner),
5348                            index
5349                                .columns
5350                                .iter()
5351                                .map(|column| quote_ident(column))
5352                                .collect::<Vec<_>>()
5353                                .join(", ")
5354                        ),
5355                        [],
5356                    ))?;
5357                }
5358            }
5359        }
5360        self.set_meta(
5361            "localIndexes",
5362            &serde_json::to_string(&declared).expect("index names serialize"),
5363        )?;
5364        self.open_projections()
5365    }
5366
5367    fn create_fts_storage(
5368        &self,
5369        name: &str,
5370        columns: &str,
5371        tokenize: &str,
5372        options: &str,
5373    ) -> Result<(), String> {
5374        let tokenizer = tokenize.replace('\'', "''");
5375        let sql = format!(
5376            "CREATE VIRTUAL TABLE IF NOT EXISTS {} USING fts5({} UNINDEXED, {columns}, tokenize='{tokenizer}'{options})",
5377            quote_ident(name),
5378            quote_ident(FTS_SOURCE_ID_COLUMN),
5379        );
5380        self.conn
5381            .execute(&sql, [])
5382            .map_err(|error| format!("cannot create local FTS5 projection {name:?}: {error}"))?;
5383        let mapping = quote_ident(&format!("_syncular_fts_{name}"));
5384        self.stored(self.conn.execute_batch(&format!("CREATE TABLE IF NOT EXISTS {mapping}(id INTEGER PRIMARY KEY, source_id TEXT NOT NULL UNIQUE)")))
5385    }
5386
5387    // -- persistence write-through --------------------------------------------
5388
5389    fn persist_outbox_insert(&self, commit: &OutboxCommit) -> Result<(), String> {
5390        let ops: Vec<Value> = commit
5391            .ops
5392            .iter()
5393            .map(|op| {
5394                let mut entry = serde_json::json!({
5395                    "op": if op.upsert { "upsert" } else { "delete" },
5396                    "table": op.table,
5397                    "rowId": op.row_id,
5398                    "baseVersion": op.base_version,
5399                    "values": op.values.clone().map(Value::Object),
5400                });
5401                if op.insert {
5402                    entry["insert"] = Value::Bool(true);
5403                }
5404                entry
5405            })
5406            .collect();
5407        self.conn
5408            .execute(
5409                "INSERT OR REPLACE INTO _syncular_outbox (commit_id, ops_json, created_at_ms, attempted) VALUES (?1, ?2, ?3, 0)",
5410                rusqlite::params![
5411                    commit.client_commit_id,
5412                    Value::Array(ops).to_string(),
5413                    self.clock_now_ms()
5414                ],
5415            )
5416            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5417        for operation in &commit.ops {
5418            let Some(values) = &operation.values else {
5419                continue;
5420            };
5421            let Some(table) = self.schema.table(&operation.table) else {
5422                continue;
5423            };
5424            for column in table
5425                .columns
5426                .iter()
5427                .filter(|column| column.ty == ColumnType::BlobRef)
5428            {
5429                let Some(Value::String(raw)) = values.get(&column.name) else {
5430                    continue;
5431                };
5432                let Ok(blob_ref) = serde_json::from_str::<Value>(raw) else {
5433                    continue;
5434                };
5435                let Some(blob_id) = blob_ref.get("blobId").and_then(Value::as_str) else {
5436                    continue;
5437                };
5438                self.conn
5439                    .execute(
5440                        "INSERT OR IGNORE INTO _syncular_blob_commit_refs(commit_id, blob_id)
5441                         SELECT ?1, ?2 WHERE EXISTS (SELECT 1 FROM _syncular_blobs WHERE blob_id = ?2)",
5442                        rusqlite::params![commit.client_commit_id, blob_id],
5443                    )
5444                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5445            }
5446        }
5447        Ok(())
5448    }
5449
5450    fn delete_outbox_persisted(&self, client_commit_id: &str) -> Result<(), String> {
5451        self.conn
5452            .execute(
5453                "DELETE FROM _syncular_blob_commit_refs WHERE commit_id = ?1",
5454                rusqlite::params![client_commit_id],
5455            )
5456            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5457        self.conn
5458            .execute(
5459                "DELETE FROM _syncular_outbox WHERE commit_id = ?1",
5460                rusqlite::params![client_commit_id],
5461            )
5462            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5463        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)", [])
5464            .map(|_| ())
5465            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
5466    }
5467
5468    fn outcome_status_name(status: CommitOutcomeStatus) -> &'static str {
5469        match status {
5470            CommitOutcomeStatus::Applied => "applied",
5471            CommitOutcomeStatus::Cached => "cached",
5472            CommitOutcomeStatus::Conflict => "conflict",
5473            // §7.2.1: a replaced commit is stored as a decided rejection.
5474            CommitOutcomeStatus::Rejected | CommitOutcomeStatus::Replaced => "rejected",
5475        }
5476    }
5477
5478    fn outcome_resolution_name(resolution: CommitOutcomeResolution) -> &'static str {
5479        match resolution {
5480            CommitOutcomeResolution::Active => "active",
5481            CommitOutcomeResolution::ResolvedKeepServer => "resolved_keep_server",
5482            CommitOutcomeResolution::Superseded => "superseded",
5483            CommitOutcomeResolution::Dismissed => "dismissed",
5484        }
5485    }
5486
5487    fn parse_outcome_status(value: &str) -> Result<CommitOutcomeStatus, String> {
5488        match value {
5489            "applied" => Ok(CommitOutcomeStatus::Applied),
5490            "cached" => Ok(CommitOutcomeStatus::Cached),
5491            "conflict" => Ok(CommitOutcomeStatus::Conflict),
5492            "rejected" => Ok(CommitOutcomeStatus::Rejected),
5493            _ => Err(format!("invalid persisted commit outcome status {value:?}")),
5494        }
5495    }
5496
5497    fn parse_outcome_resolution(value: &str) -> Result<CommitOutcomeResolution, String> {
5498        match value {
5499            "active" => Ok(CommitOutcomeResolution::Active),
5500            "resolved_keep_server" => Ok(CommitOutcomeResolution::ResolvedKeepServer),
5501            "superseded" => Ok(CommitOutcomeResolution::Superseded),
5502            "dismissed" => Ok(CommitOutcomeResolution::Dismissed),
5503            _ => Err(format!(
5504                "invalid persisted commit outcome resolution {value:?}"
5505            )),
5506        }
5507    }
5508
5509    fn persist_commit_outcome(
5510        &self,
5511        client_commit_id: &str,
5512        status: CommitOutcomeStatus,
5513        results: &[CommitOperationOutcome],
5514        operations: Option<&[OutboxOp]>,
5515    ) -> Result<(), String> {
5516        let results_json = serde_json::to_string(results).map_err(|error| error.to_string())?;
5517        let operations_json = operations
5518            .map(|items| {
5519                serde_json::to_string(&items.iter().map(CommitOperation::from).collect::<Vec<_>>())
5520            })
5521            .transpose()
5522            .map_err(|error| error.to_string())?;
5523        self.conn
5524            .execute(
5525                "INSERT INTO _syncular_commit_outcomes (
5526                   client_commit_id, status, recorded_at_ms, results_json,
5527                   operations_json, resolution
5528                 ) VALUES (?1, ?2, ?3, ?4, ?5, 'active')",
5529                rusqlite::params![
5530                    client_commit_id,
5531                    Self::outcome_status_name(status),
5532                    self.clock_now_ms(),
5533                    results_json,
5534                    operations_json
5535                ],
5536            )
5537            .map(|_| ())
5538            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
5539    }
5540
5541    /// §7.2: the journal holds a stored cell only in its canonical shape. A cell
5542    /// the byte-envelope rule refuses cannot be journaled verbatim.
5543    fn stored_cell_is_representable(cell: &Value) -> bool {
5544        cell.is_null()
5545            || cell.is_string()
5546            || cell.is_boolean()
5547            || cell.is_number()
5548            || is_canonical_bytes_envelope(cell)
5549    }
5550
5551    fn stored_row_is_representable(value: &Value) -> bool {
5552        value
5553            .as_object()
5554            .is_some_and(|row| row.values().all(Self::stored_cell_is_representable))
5555    }
5556
5557    fn stored_operation_is_representable(value: &Value) -> bool {
5558        value.get("table").is_some_and(Value::is_string)
5559            && value.get("rowId").is_some_and(Value::is_string)
5560            && value.get("baseVersion").is_none_or(|v| {
5561                v.as_i64()
5562                    .is_some_and(|n| n.unsigned_abs() <= MAX_JS_SAFE_INTEGER)
5563            })
5564            && match value.get("op").and_then(Value::as_str) {
5565                Some("upsert") => {
5566                    value
5567                        .get("values")
5568                        .is_some_and(Self::stored_row_is_representable)
5569                        && value
5570                            .get("insert")
5571                            .is_none_or(|insert| *insert == Value::Bool(true))
5572                }
5573                Some("delete") => value.get("values").is_none() && value.get("insert").is_none(),
5574                _ => false,
5575            }
5576    }
5577
5578    /// §7.2/§7.4.4: a dropped commit keeps its operation envelope in the journal
5579    /// only when the journal reader accepts the serialized operation, which is the
5580    /// rule `outcome_from_row` applies to this same row later.
5581    fn outbox_op_is_journalable(operation: &OutboxOp) -> bool {
5582        serde_json::to_value(CommitOperation::from(operation))
5583            .is_ok_and(|value| Self::stored_operation_is_representable(&value))
5584    }
5585
5586    /// §7.2.1: the one predicate for a replaced commit: a rejection whose
5587    /// every result is `client.commit_replaced` and that names its replacement.
5588    fn is_replaced(outcome: &CommitOutcome) -> bool {
5589        outcome.status == CommitOutcomeStatus::Rejected
5590            && outcome.replacement_client_commit_id.is_some()
5591            && !outcome.results.is_empty()
5592            && outcome.results.iter().all(|result| {
5593                matches!(result, CommitOperationOutcome::Error { rejection }
5594                    if rejection.code == COMMIT_REPLACED_CODE)
5595            })
5596    }
5597
5598    /// §7.2.1: `commitOutcomes` and `commitDelivery` report a replaced
5599    /// commit as `replaced`; every other journal surface reads the rejection.
5600    fn reported_outcome(mut outcome: CommitOutcome) -> CommitOutcome {
5601        if Self::is_replaced(&outcome) {
5602            outcome.status = CommitOutcomeStatus::Replaced;
5603        }
5604        outcome
5605    }
5606
5607    fn outcome_from_row(row: StoredCommitOutcomeRow) -> Result<CommitOutcome, String> {
5608        let StoredCommitOutcomeRow {
5609            sequence,
5610            client_commit_id,
5611            status,
5612            recorded_at_ms,
5613            results_json,
5614            operations_json,
5615            resolution,
5616            resolved_at_ms,
5617            replacement_client_commit_id,
5618        } = row;
5619        if sequence.unsigned_abs() > MAX_JS_SAFE_INTEGER
5620            || recorded_at_ms.unsigned_abs() > MAX_JS_SAFE_INTEGER
5621            || resolved_at_ms.is_some_and(|value| value.unsigned_abs() > MAX_JS_SAFE_INTEGER)
5622        {
5623            return Err("sync.local_corrupt: persisted commit outcome is invalid".to_owned());
5624        }
5625        let invalid = || "sync.local_corrupt: persisted commit outcome is invalid".to_owned();
5626        let stored: Vec<Value> = serde_json::from_str(&results_json).map_err(|_| invalid())?;
5627        for result in &stored {
5628            let nested = match result.get("status").and_then(Value::as_str) {
5629                Some("conflict") => result.get("conflict"),
5630                Some("error") => result.get("rejection"),
5631                _ => None,
5632            };
5633            if nested
5634                .and_then(|record| record.get("operation"))
5635                .is_some_and(|op| !Self::stored_operation_is_representable(op))
5636                || (result.get("status").and_then(Value::as_str) == Some("conflict")
5637                    && nested
5638                        .and_then(|record| record.get("serverRow"))
5639                        .is_some_and(|row| !Self::stored_row_is_representable(row)))
5640            {
5641                return Err(invalid());
5642            }
5643        }
5644        let results: Vec<CommitOperationOutcome> =
5645            serde_json::from_value(Value::Array(stored)).map_err(|_| invalid())?;
5646        let has_conflict = results
5647            .iter()
5648            .any(|result| matches!(result, CommitOperationOutcome::Conflict { .. }));
5649        let has_error = results
5650            .iter()
5651            .any(|result| matches!(result, CommitOperationOutcome::Error { .. }));
5652        let status = Self::parse_outcome_status(&status).map_err(|_| invalid())?;
5653        let redacted = results.is_empty() && operations_json.is_none();
5654        if match status {
5655            CommitOutcomeStatus::Applied | CommitOutcomeStatus::Cached => has_conflict || has_error,
5656            CommitOutcomeStatus::Replaced => true,
5657            CommitOutcomeStatus::Conflict => !(has_conflict || redacted),
5658            CommitOutcomeStatus::Rejected => has_conflict || !(has_error || redacted),
5659        } {
5660            return Err(invalid());
5661        }
5662        let operations: Option<Vec<CommitOperation>> = operations_json
5663            .map(|raw| {
5664                let stored: Vec<Value> = serde_json::from_str(&raw).map_err(|_| invalid())?;
5665                if !stored.iter().all(Self::stored_operation_is_representable) {
5666                    return Err(invalid());
5667                }
5668                serde_json::from_value(Value::Array(stored)).map_err(|_| invalid())
5669            })
5670            .transpose()?;
5671        for result in &results {
5672            match result {
5673                CommitOperationOutcome::Conflict { conflict }
5674                    if conflict.server_version.unsigned_abs() > MAX_JS_SAFE_INTEGER =>
5675                {
5676                    return Err("sync.local_corrupt: persisted commit outcome is invalid".to_owned())
5677                }
5678                CommitOperationOutcome::Error { rejection } => {
5679                    if let Some(details) = &rejection.details {
5680                        let encoded = serde_json::to_string(details).map_err(|_| {
5681                            "sync.local_corrupt: persisted commit outcome is invalid".to_owned()
5682                        })?;
5683                        RejectionDetails::parse(&encoded).map_err(|_| {
5684                            "sync.local_corrupt: persisted commit outcome is invalid".to_owned()
5685                        })?;
5686                    }
5687                }
5688                _ => {}
5689            }
5690        }
5691        Ok(CommitOutcome {
5692            sequence,
5693            client_commit_id,
5694            status,
5695            recorded_at_ms,
5696            results,
5697            operations,
5698            retained_rows: None,
5699            resolution: Self::parse_outcome_resolution(&resolution)?,
5700            resolved_at_ms,
5701            replacement_client_commit_id,
5702        })
5703    }
5704
5705    /// Resolve declared unique keys through SQLite, including affinity and NULL semantics.
5706    fn unique_conflicts(
5707        &self,
5708        table: &TableSchema,
5709        values: &Map<String, Value>,
5710        base: bool,
5711    ) -> Result<Vec<RetainedUniqueConflict>, String> {
5712        let source = if base {
5713            base_table(&table.name)
5714        } else {
5715            visible_table(&table.name)
5716        };
5717        let mut conflicts = Vec::new();
5718        for index in table.indexes.iter().filter(|index| index.unique) {
5719            let mut params = vec![json_param_to_sql(
5720                values.get(&table.primary_key).ok_or("sync.local_corrupt")?,
5721            )?];
5722            for name in &index.columns {
5723                let column = table
5724                    .columns
5725                    .iter()
5726                    .find(|column| column.name == *name)
5727                    .ok_or("sync.local_corrupt")?;
5728                let cell = json_to_column_value(column, values.get(name))?;
5729                params.push(owned_sql_value(RowParam::Cell(&cell))?);
5730            }
5731            let sql = format!(
5732                "SELECT * FROM {source} WHERE {} != ? AND {}",
5733                quote_ident(&table.primary_key),
5734                index
5735                    .columns
5736                    .iter()
5737                    .map(|column| format!("{} = ?", quote_ident(column)))
5738                    .collect::<Vec<_>>()
5739                    .join(" AND ")
5740            );
5741            let mut statement = self
5742                .conn
5743                .prepare_cached(&sql)
5744                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5745            let records = statement
5746                .query_map(rusqlite::params_from_iter(params), |record| {
5747                    let values = table
5748                        .columns
5749                        .iter()
5750                        .enumerate()
5751                        .map(|(index, column)| {
5752                            let value = sql_ref_to_json(column, record.get_ref(index)?);
5753                            json_to_column_value(column, Some(&value)).map_err(|message| {
5754                                rusqlite::Error::ToSqlConversionFailure(message.into())
5755                            })
5756                        })
5757                        .collect::<Result<Row, _>>()?;
5758                    Ok((values, record.get::<_, i64>(table.columns.len())?))
5759                })
5760                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5761            for record in records {
5762                let (row, version) =
5763                    record.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5764                let row_id = render_row_id_json(Some(&column_value_to_json(&row[table.pk_index])))?;
5765                conflicts.push(RetainedUniqueConflict {
5766                    index: index.name.clone(),
5767                    columns: index.columns.clone(),
5768                    row_id,
5769                    server_row: table
5770                        .columns
5771                        .iter()
5772                        .zip(&row)
5773                        .map(|(column, value)| (column.name.clone(), column_value_to_json(value)))
5774                        .collect(),
5775                    server_version: version,
5776                });
5777            }
5778        }
5779        Ok(conflicts)
5780    }
5781
5782    fn attach_retained_rows(&self, mut outcome: CommitOutcome) -> Result<CommitOutcome, String> {
5783        if let Some((commit, initial)) = self
5784            .failed_commits
5785            .iter()
5786            .find(|(commit, _)| commit.client_commit_id == outcome.client_commit_id)
5787        {
5788            let mut rows = Vec::new();
5789            for operation in &commit.ops {
5790                // A table the current schema removed has no rows to retain.
5791                let Some(table) = self.schema.table(&operation.table) else {
5792                    continue;
5793                };
5794                let key =
5795                    serde_json::to_string(&(operation.table.clone(), operation.row_id.clone()))
5796                        .map_err(|_| "sync.local_corrupt".to_owned())?;
5797                let base = self.stored_row(table, &operation.row_id, true)?;
5798                rows.push(RetainedCommitRow {
5799                    table: operation.table.clone(),
5800                    row_id: operation.row_id.clone(),
5801                    unique_conflicts: if operation.upsert {
5802                        self.unique_conflicts(
5803                            table,
5804                            initial
5805                                .get(&key)
5806                                .and_then(Value::as_object)
5807                                .or(operation.values.as_ref())
5808                                .ok_or("sync.local_corrupt")?,
5809                            true,
5810                        )?
5811                    } else {
5812                        Vec::new()
5813                    },
5814                    local_row: if operation.upsert {
5815                        initial
5816                            .get(&key)
5817                            .and_then(Value::as_object)
5818                            .cloned()
5819                            .or_else(|| operation.values.clone())
5820                    } else {
5821                        None
5822                    },
5823                    server_row: base.as_ref().map(|(values, _)| {
5824                        table
5825                            .columns
5826                            .iter()
5827                            .zip(values)
5828                            .map(|(column, value)| {
5829                                (column.name.clone(), column_value_to_json(value))
5830                            })
5831                            .collect()
5832                    }),
5833                    server_version: base.map(|(_, version)| version),
5834                });
5835            }
5836            outcome.retained_rows = Some(rows);
5837        }
5838        Ok(outcome)
5839    }
5840
5841    fn commit_outcome(&self, client_commit_id: &str) -> Result<Option<CommitOutcome>, String> {
5842        let row = self
5843            .conn
5844            .query_row(
5845                "SELECT seq, client_commit_id, status, recorded_at_ms, results_json, operations_json,
5846                        resolution, resolved_at_ms, replacement_client_commit_id
5847                   FROM _syncular_commit_outcomes WHERE client_commit_id = ?1",
5848                rusqlite::params![client_commit_id],
5849                |row| {
5850                    Ok(StoredCommitOutcomeRow {
5851                        sequence: row.get(0)?,
5852                        client_commit_id: row.get(1)?,
5853                        status: row.get(2)?,
5854                        recorded_at_ms: row.get(3)?,
5855                        results_json: row.get(4)?,
5856                        operations_json: row.get(5)?,
5857                        resolution: row.get(6)?,
5858                        resolved_at_ms: row.get(7)?,
5859                        replacement_client_commit_id: row.get(8)?,
5860                    })
5861                },
5862            )
5863            .optional()
5864            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5865        row.map(|row| self.attach_retained_rows(Self::outcome_from_row(row)?))
5866            .transpose()
5867    }
5868
5869    /// Internal host step. The host must run its idle drive before finishing.
5870    #[doc(hidden)]
5871    pub fn prepare_current_base(
5872        &self,
5873        client_commit_id: &str,
5874        sequence: i64,
5875    ) -> Result<CurrentBasePreparation, CurrentBaseProof> {
5876        let outcome = self
5877            .commit_outcome(client_commit_id)
5878            .map_err(|_| CurrentBaseProof::failure(CurrentBaseProofReason::SnapshotFailed))?;
5879        let valid = outcome.as_ref().is_some_and(|outcome| {
5880            outcome.sequence == sequence
5881                && outcome.resolution == CommitOutcomeResolution::Active
5882                && matches!(
5883                    outcome.status,
5884                    CommitOutcomeStatus::Conflict | CommitOutcomeStatus::Rejected
5885                )
5886                && outcome
5887                    .operations
5888                    .as_ref()
5889                    .zip(outcome.retained_rows.as_ref())
5890                    .is_some_and(|(operations, rows)| {
5891                        !rows.is_empty() && operations.len() == rows.len()
5892                    })
5893        });
5894        if !valid {
5895            return Err(CurrentBaseProof::failure(
5896                CurrentBaseProofReason::OutcomeUnavailable,
5897            ));
5898        }
5899        if self.transport_closed() {
5900            return Err(CurrentBaseProof::failure(CurrentBaseProofReason::Offline));
5901        }
5902        Ok(CurrentBasePreparation {
5903            client_commit_id: client_commit_id.to_owned(),
5904            sequence,
5905            replacement: None,
5906            units: load_units(&self.conn)
5907                .map_err(|_| CurrentBaseProof::failure(CurrentBaseProofReason::SnapshotFailed))?,
5908            transport_epoch: self.transport_epoch,
5909            registration_epoch: self.registration_epoch,
5910            security_epoch: self.security_epoch,
5911        })
5912    }
5913
5914    /// Internal host step after the completed post-rejection idle drive.
5915    #[doc(hidden)]
5916    pub fn finish_current_base(
5917        &mut self,
5918        prepared: CurrentBasePreparation,
5919        drive: SyncOutcome,
5920    ) -> CurrentBaseProof {
5921        if self.transport_closed() || self.transport_epoch != prepared.transport_epoch {
5922            return CurrentBaseProof::failure(CurrentBaseProofReason::Offline);
5923        }
5924        if self.registration_epoch != prepared.registration_epoch {
5925            return CurrentBaseProof::failure(CurrentBaseProofReason::MissingCoverage);
5926        }
5927        if self.security_preflight || self.security_epoch != prepared.security_epoch {
5928            return CurrentBaseProof::failure(CurrentBaseProofReason::SyncFailed);
5929        }
5930        let report = match drive {
5931            SyncOutcome::Ok(report) => report,
5932            SyncOutcome::BudgetExhausted(_) => {
5933                return CurrentBaseProof::failure(CurrentBaseProofReason::BudgetExhausted)
5934            }
5935            _ => return CurrentBaseProof::failure(CurrentBaseProofReason::SyncFailed),
5936        };
5937        if report.schema_floor.is_some() {
5938            return CurrentBaseProof::failure(CurrentBaseProofReason::SchemaFloor);
5939        }
5940        if self
5941            .conn
5942            .execute_batch("SAVEPOINT syncular_base_proof")
5943            .is_err()
5944        {
5945            return CurrentBaseProof::failure(CurrentBaseProofReason::SnapshotFailed);
5946        }
5947        let proof = (|| {
5948            let snapshot = snapshot_read_connection(
5949                &self.conn,
5950                Some(&self.schema),
5951                &SnapshotReadRequest {
5952                    units: prepared.units.iter().map(|unit| unit.id.clone()).collect(),
5953                    commit_ids: vec![prepared.client_commit_id.clone()],
5954                    ..Default::default()
5955                },
5956            )
5957            .map_err(|_| CurrentBaseProofReason::SnapshotFailed)?;
5958            let current = self
5959                .commit_outcome(&prepared.client_commit_id)
5960                .map_err(|_| CurrentBaseProofReason::SnapshotFailed)?;
5961            let unavailable = if report.revoked.is_empty() {
5962                CurrentBaseProofReason::OutcomeUnavailable
5963            } else {
5964                CurrentBaseProofReason::Revoked
5965            };
5966            let Some(outcome) = current else {
5967                return Err(unavailable);
5968            };
5969            if !matches!(
5970                snapshot.deliveries.first(),
5971                Some(CommitDelivery::Known { .. })
5972            ) || outcome.sequence != prepared.sequence
5973                || outcome.resolution != CommitOutcomeResolution::Active
5974                || !matches!(
5975                    outcome.status,
5976                    CommitOutcomeStatus::Conflict | CommitOutcomeStatus::Rejected
5977                )
5978            {
5979                return Err(unavailable);
5980            }
5981            let (Some(operations), Some(rows)) = (outcome.operations, outcome.retained_rows) else {
5982                return Err(unavailable);
5983            };
5984            if rows.is_empty() || operations.len() != rows.len() {
5985                return Err(unavailable);
5986            }
5987            let after =
5988                load_units(&self.conn).map_err(|_| CurrentBaseProofReason::SnapshotFailed)?;
5989            let complete: HashSet<&str> = snapshot
5990                .units
5991                .iter()
5992                .filter_map(|unit| match unit {
5993                    UnitCatchup::Known {
5994                        id,
5995                        bootstrap_complete: true,
5996                        ..
5997                    } => Some(id.as_str()),
5998                    _ => None,
5999                })
6000                .collect();
6001            // A unit id names one scope map (§4.1), so the same id before and
6002            // after the drive is the same registration.
6003            let candidates: Vec<&UnitRecord> = after
6004                .iter()
6005                .filter(|unit| {
6006                    complete.contains(unit.id.as_str())
6007                        && prepared.units.iter().any(|before| before.id == unit.id)
6008                })
6009                .collect();
6010            let covered = |table_name: &str, row: &Map<String, Value>| {
6011                let Some(table) = self.schema.table(table_name) else {
6012                    return false;
6013                };
6014                candidates.iter().any(|unit| {
6015                    covers(table, &unit.scopes)
6016                        && pair_scopes(&unit.scopes, table_name, unit.echo.as_deref()).is_some_and(
6017                            |scopes| {
6018                                scopes.iter().all(|(variable, allowed)| {
6019                                    table
6020                                        .scope_column(variable)
6021                                        .and_then(|column| match row.get(column) {
6022                                            Some(Value::String(value)) => Some(value.clone()),
6023                                            Some(Value::Bool(value)) => Some(value.to_string()),
6024                                            Some(Value::Number(value)) => {
6025                                                value.as_f64().map(|number| {
6026                                                    ryu_js::Buffer::new()
6027                                                        .format_finite(number)
6028                                                        .to_owned()
6029                                                })
6030                                            }
6031                                            _ => None,
6032                                        })
6033                                        .is_some_and(|value| {
6034                                            !value.is_empty() && allowed.contains(&value)
6035                                        })
6036                                })
6037                            },
6038                        )
6039                })
6040            };
6041            for row in &rows {
6042                let Some(base) = row.server_row.as_ref().or(row.local_row.as_ref()) else {
6043                    return Err(if report.revoked.is_empty() {
6044                        CurrentBaseProofReason::MissingCoverage
6045                    } else {
6046                        CurrentBaseProofReason::Revoked
6047                    });
6048                };
6049                if !covered(&row.table, base)
6050                    || row
6051                        .unique_conflicts
6052                        .iter()
6053                        .any(|conflict| !covered(&row.table, &conflict.server_row))
6054                {
6055                    return Err(if report.revoked.is_empty() {
6056                        CurrentBaseProofReason::MissingCoverage
6057                    } else {
6058                        CurrentBaseProofReason::Revoked
6059                    });
6060                }
6061            }
6062            Ok(rows)
6063        })();
6064        if self
6065            .conn
6066            .execute_batch("RELEASE syncular_base_proof")
6067            .is_err()
6068        {
6069            return CurrentBaseProof::failure(CurrentBaseProofReason::SnapshotFailed);
6070        }
6071        match proof {
6072            Ok(rows) => CurrentBaseProof {
6073                proven: true,
6074                rows: Some(rows),
6075                reason: None,
6076            },
6077            Err(reason) => CurrentBaseProof::failure(reason),
6078        }
6079    }
6080
6081    pub fn prove_current_base(
6082        &mut self,
6083        transport: &mut dyn Transport,
6084        client_commit_id: &str,
6085        sequence: i64,
6086        max_rounds: Option<u32>,
6087    ) -> CurrentBaseProof {
6088        let prepared = match self.prepare_current_base(client_commit_id, sequence) {
6089            Ok(prepared) => prepared,
6090            Err(proof) => return proof,
6091        };
6092        let drive = self.sync_until_idle(transport, max_rounds);
6093        self.finish_current_base(prepared, drive)
6094    }
6095
6096    pub fn commit_outcomes(&self, query: CommitOutcomeQuery) -> Result<Vec<CommitOutcome>, String> {
6097        if query.limit == Some(0) {
6098            return Err("sync.invalid_request: commit outcome limit must be positive".to_owned());
6099        }
6100        let mut sql = String::from(
6101            "SELECT seq, client_commit_id, status, recorded_at_ms, results_json, operations_json,
6102                    resolution, resolved_at_ms, replacement_client_commit_id
6103               FROM _syncular_commit_outcomes",
6104        );
6105        if query.active_only {
6106            sql.push_str(" WHERE resolution = 'active' AND status IN ('conflict', 'rejected')");
6107        }
6108        sql.push_str(" ORDER BY seq DESC");
6109        if let Some(limit) = query.limit {
6110            sql.push_str(&format!(" LIMIT {limit}"));
6111        }
6112        let mut stmt = self
6113            .conn
6114            .prepare(&sql)
6115            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6116        let rows = stmt
6117            .query_map([], |row| {
6118                Ok(StoredCommitOutcomeRow {
6119                    sequence: row.get(0)?,
6120                    client_commit_id: row.get(1)?,
6121                    status: row.get(2)?,
6122                    recorded_at_ms: row.get(3)?,
6123                    results_json: row.get(4)?,
6124                    operations_json: row.get(5)?,
6125                    resolution: row.get(6)?,
6126                    resolved_at_ms: row.get(7)?,
6127                    replacement_client_commit_id: row.get(8)?,
6128                })
6129            })
6130            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6131        let mut outcomes = Vec::new();
6132        for row in rows {
6133            let row = row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6134            outcomes.push(Self::reported_outcome(
6135                self.attach_retained_rows(Self::outcome_from_row(row)?)?,
6136            ));
6137        }
6138        Ok(outcomes)
6139    }
6140
6141    fn prune_commit_outcomes(&self) -> Result<(), String> {
6142        #[cfg(test)]
6143        self.outcome_prune_count
6144            .set(self.outcome_prune_count.get() + 1);
6145        let max_entries = self.limits.outcome_retention_max_entries.unwrap_or(1_000);
6146        let count = self
6147            .conn
6148            .query_row(
6149                "SELECT COUNT(*) FROM _syncular_commit_outcomes",
6150                [],
6151                |row| row.get::<_, i64>(0),
6152            )
6153            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
6154            as usize;
6155        let excess = count.saturating_sub(max_entries);
6156        if excess == 0 {
6157            return Ok(());
6158        }
6159        let mut stmt = self
6160            .conn
6161            .prepare(
6162                "SELECT seq FROM _syncular_commit_outcomes
6163                  WHERE status IN ('applied', 'cached') OR resolution != 'active'
6164                  ORDER BY seq ASC LIMIT ?1",
6165            )
6166            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6167        let rows = stmt
6168            .query_map(rusqlite::params![excess as i64], |row| row.get::<_, i64>(0))
6169            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6170        let sequences = rows
6171            .collect::<Result<Vec<_>, _>>()
6172            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6173        drop(stmt);
6174        for sequence in sequences {
6175            self.conn
6176                .execute(
6177                    "DELETE FROM _syncular_commit_outcomes WHERE seq = ?1",
6178                    rusqlite::params![sequence],
6179                )
6180                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6181        }
6182        Ok(())
6183    }
6184
6185    // -- units (§4.1) ------------------------------------------------------------
6186
6187    /// Every registered unit in registration order (§4.1).
6188    pub fn units(&self) -> Result<Vec<UnitRecord>, String> {
6189        self.stored(load_units(&self.conn))
6190    }
6191
6192    pub fn unit(&self, id: &str) -> Result<Option<UnitRecord>, String> {
6193        self.stored(get_unit(&self.conn, id))
6194    }
6195
6196    /// Register one unit (§4.1) and return its id.
6197    pub fn subscribe(&mut self, scopes: UnitScopes) -> Result<String, String> {
6198        Ok(self.subscribe_many(vec![scopes])?.remove(0))
6199    }
6200
6201    /// Register several units in one local transaction and return their ids:
6202    /// one commit for all of them (on OPFS a commit costs milliseconds, so a
6203    /// cold start with hundreds of units pays it once). An error rolls back
6204    /// every registration of the call. Registering an active unit again
6205    /// changes nothing; a revoked unit re-arms (§3.3). A call that registers or
6206    /// re-arms a unit raises sync-needed with an interactive intent.
6207    pub fn subscribe_many(&mut self, units: Vec<UnitScopes>) -> Result<Vec<String>, String> {
6208        let rollback = self.capture();
6209        self.begin_observation("syncular_subscribe")?;
6210        let mut changed = false;
6211        let registered = (|| {
6212            let mut ids = Vec::with_capacity(units.len());
6213            let mut batch = ChangeAccumulator::default();
6214            for scopes in units {
6215                let (id, held) = self.hold_unit(scopes, true)?;
6216                if held {
6217                    if let Some(unit) = self.stored(get_unit(&self.conn, &id))? {
6218                        self.record_unit_windows(&mut batch, &unit)?;
6219                    }
6220                }
6221                changed |= held;
6222                ids.push(id);
6223            }
6224            self.finish_observation("syncular_subscribe", batch)?;
6225            Ok(ids)
6226        })();
6227        let ids = match registered {
6228            Ok(ids) => ids,
6229            Err(error) => {
6230                self.rollback_observation("syncular_subscribe");
6231                self.restore(rollback);
6232                return Err(error);
6233            }
6234        };
6235        if changed {
6236            self.registration_epoch = self.registration_epoch.wrapping_add(1);
6237            self.set_sync_needed(true, true);
6238        }
6239        Ok(ids)
6240    }
6241
6242    /// Release the explicit reference to a unit. The unit leaves the
6243    /// registration list when no window base holds it (§4.1); its rows stay.
6244    pub fn unsubscribe(&mut self, id: &str) -> Result<(), String> {
6245        let Some(unit) = self.stored(get_unit(&self.conn, id))? else {
6246            return Ok(());
6247        };
6248        if !unit.explicit {
6249            return Ok(());
6250        }
6251        if !self.stored(window_refs(&self.conn, id))?.is_empty() {
6252            return self.stored(save_unit(
6253                &self.conn,
6254                &UnitRecord {
6255                    explicit: false,
6256                    ..unit
6257                },
6258            ));
6259        }
6260        let rollback = self.capture();
6261        self.begin_observation("syncular_unsubscribe")?;
6262        let removed = (|| {
6263            self.conn
6264                .execute("DELETE FROM _syncular_units WHERE id = ?1", [id])
6265                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6266            let mut batch = ChangeAccumulator::default();
6267            self.record_unit_windows(&mut batch, &unit)?;
6268            self.finish_observation("syncular_unsubscribe", batch)
6269        })();
6270        if let Err(error) = removed {
6271            self.rollback_observation("syncular_unsubscribe");
6272            self.restore(rollback);
6273            return Err(error);
6274        }
6275        self.registration_epoch = self.registration_epoch.wrapping_add(1);
6276        if unit.status == UnitStatus::Active {
6277            self.set_sync_needed(true, true);
6278        }
6279        Ok(())
6280    }
6281
6282    /// Take one reference on a unit (§4.1): validate the scope map, register a
6283    /// new unit catching up with cursor `-1`, re-arm a revoked one (§3.3).
6284    /// Returns the id and whether the registration list changed.
6285    fn hold_unit(&mut self, scopes: UnitScopes, explicit: bool) -> Result<(String, bool), String> {
6286        if scopes.is_empty()
6287            || scopes.values().any(|value| value == "*")
6288            || !self
6289                .schema
6290                .tables
6291                .iter()
6292                .any(|table| covers(table, &scopes))
6293        {
6294            return Err("sync.invalid_subscription: a unit names one non-wildcard value per variable and covers a table".to_owned());
6295        }
6296        let id = ssp2::registration::unit_id(&scope_pairs(&scopes));
6297        let existing = self.stored(get_unit(&self.conn, &id))?;
6298        if let Some(existing) = existing
6299            .as_ref()
6300            .filter(|unit| unit.status != UnitStatus::Revoked)
6301        {
6302            if explicit && !existing.explicit {
6303                self.stored(save_unit(
6304                    &self.conn,
6305                    &UnitRecord {
6306                        explicit,
6307                        ..existing.clone()
6308                    },
6309                ))?;
6310            }
6311            return Ok((id, false));
6312        }
6313        self.delete_pending_evict(&id)?;
6314        self.stored(save_unit(
6315            &self.conn,
6316            &UnitRecord {
6317                id: id.clone(),
6318                scopes,
6319                explicit: explicit || existing.is_some_and(|unit| unit.explicit),
6320                status: UnitStatus::Active,
6321                reason_code: None,
6322                cursor: Some(-1),
6323                bootstrap_state: None,
6324                seeded: Vec::new(),
6325                echo: None,
6326                restriction: None,
6327            },
6328        ))?;
6329        Ok((id, true))
6330    }
6331
6332    // -- windows (§4.8) -----------------------------------------------------------
6333
6334    /// §4.8: set the windowed-in values of a base, one unit per value. Added
6335    /// values take a reference on their unit (a new unit bootstraps on the
6336    /// next sync); removed values release theirs, and a unit no reference
6337    /// holds leaves the registration list fused with its first eviction chunk
6338    /// (E1–E4). Idempotent; re-entry cancels a deferred eviction.
6339    pub fn set_window(
6340        &mut self,
6341        base: &WindowBase,
6342        units: &[String],
6343    ) -> Result<CommandEffects, String> {
6344        let base_key = window_base_key(base);
6345        let live = self.load_window_units(&base_key)?;
6346        let mut changed = false;
6347        // §7.8: the added values register in one transaction. §3.3: a held
6348        // value whose unit is revoked re-arms once per open core.
6349        let mut added: Vec<&String> = Vec::new();
6350        for value in units {
6351            let held = live.iter().find(|(held, _)| held == value);
6352            let rearm = match held {
6353                None => true,
6354                Some((_, id)) => {
6355                    !self.window_armed.contains(id)
6356                        && self
6357                            .stored(get_unit(&self.conn, id))?
6358                            .is_some_and(|unit| unit.status == UnitStatus::Revoked)
6359                }
6360            };
6361            if rearm {
6362                added.push(value);
6363            }
6364        }
6365        if !added.is_empty() {
6366            let rollback = self.capture();
6367            self.begin_observation("syncular_window")?;
6368            let widened = (|| {
6369                let mut batch = ChangeAccumulator::default();
6370                for value in &added {
6371                    let (id, registered) =
6372                        self.hold_unit(window_unit_scopes(base, value), false)?;
6373                    self.sync_needed |= registered;
6374                    if registered {
6375                        self.window_armed.insert(id.clone());
6376                    }
6377                    self.conn
6378                        .execute(
6379                            "INSERT OR REPLACE INTO _syncular_windows(base, unit, sub_id) VALUES (?1, ?2, ?3)",
6380                            rusqlite::params![base_key, value, id],
6381                        )
6382                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6383                    batch.window(&base_key, value);
6384                    // A registered or re-armed unit is a transition for every
6385                    // window value that references it.
6386                    if registered {
6387                        if let Some(unit) = self.stored(get_unit(&self.conn, &id))? {
6388                            self.record_unit_windows(&mut batch, &unit)?;
6389                        }
6390                    }
6391                }
6392                batch.status = true;
6393                self.finish_observation("syncular_window", batch)
6394            })();
6395            if let Err(error) = widened {
6396                self.rollback_observation("syncular_window");
6397                self.restore(rollback);
6398                return Err(error);
6399            }
6400            changed = true;
6401            self.registration_epoch = self.registration_epoch.wrapping_add(1);
6402        }
6403        for (value, id) in live {
6404            if units.contains(&value) {
6405                continue;
6406            }
6407            self.rebuild_overlay_if_dirty()?;
6408            let rollback = self.capture();
6409            self.begin_observation("syncular_window")?;
6410            let remaining = self.release_window_unit(&base_key, &value, &id);
6411            let remaining = match remaining {
6412                Ok(remaining) => remaining,
6413                Err(error) => {
6414                    self.rollback_observation("syncular_window");
6415                    self.restore(rollback);
6416                    return Err(error);
6417                }
6418            };
6419            changed = true;
6420            self.registration_epoch = self.registration_epoch.wrapping_add(1);
6421            if remaining {
6422                self.drain_pending_evictions()?;
6423            }
6424        }
6425        Ok(if changed && !self.transport_closed() {
6426            CommandEffects::interactive()
6427        } else {
6428            CommandEffects::none()
6429        })
6430    }
6431
6432    /// §4.8 completeness oracle: the windowed-in values of a base and those
6433    /// whose unit is not complete. A value is complete once its unit is active
6434    /// and no longer bootstrapping; registration alone is not completeness.
6435    pub fn window_state(&self, base: &WindowBase) -> Result<WindowState, String> {
6436        persisted_window_state(&self.conn, base).map_err(|failure| failure.message)
6437    }
6438
6439    /// Registry rows for a base, ordered by value: (value, unit id).
6440    fn load_window_units(&self, base_key: &str) -> Result<Vec<(String, String)>, String> {
6441        let mut statement = self
6442            .conn
6443            .prepare_cached(
6444                "SELECT unit, sub_id FROM _syncular_windows WHERE base = ?1 ORDER BY unit ASC",
6445            )
6446            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6447        let rows = statement
6448            .query_map([base_key], |row| Ok((row.get(0)?, row.get(1)?)))
6449            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6450        rows.collect::<Result<_, _>>()
6451            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
6452    }
6453
6454    /// §4.8: the window-domain changes of one unit transition, the one path
6455    /// every transition site takes: one per window value that references the
6456    /// unit or, when none does, one for the base derived from its scope map
6457    /// (the variable first in code-unit order and its value; the other
6458    /// variables its fixed scopes). A transition adds no table change.
6459    fn record_unit_windows(
6460        &self,
6461        batch: &mut ChangeAccumulator,
6462        unit: &UnitRecord,
6463    ) -> Result<(), String> {
6464        let refs = self.stored(window_refs(&self.conn, &unit.id))?;
6465        if refs.is_empty() {
6466            let mut pairs = scope_pairs(&unit.scopes).into_iter();
6467            if let Some((variable, value)) = pairs.next() {
6468                let base = WindowBase {
6469                    variable,
6470                    fixed_scopes: pairs.collect(),
6471                };
6472                batch.window(&window_base_key(&base), &value);
6473            }
6474        }
6475        for (base_key, value) in refs {
6476            batch.window(&base_key, &value);
6477        }
6478        Ok(())
6479    }
6480
6481    /// §4.8: release a window value's reference inside the caller's
6482    /// observation. When no reference holds the unit, unregister it fused with
6483    /// its first eviction chunk (E3): delete the rows of every covered table
6484    /// matching the persisted echo, except rows pinned by the outbox (E1) or
6485    /// owned by another unit (§3.3), and park the per-table scopes of what
6486    /// remains in the pending-eviction registry. Fails closed without a local
6487    /// scope-column mapping. Returns whether unpinned rows remain.
6488    fn release_window_unit(
6489        &mut self,
6490        base_key: &str,
6491        value: &str,
6492        id: &str,
6493    ) -> Result<bool, String> {
6494        self.conn
6495            .execute(
6496                "DELETE FROM _syncular_windows WHERE base = ?1 AND unit = ?2",
6497                rusqlite::params![base_key, value],
6498            )
6499            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6500        self.window_armed.remove(id);
6501        let mut batch = ChangeAccumulator::default();
6502        batch.window(base_key, value);
6503        batch.status = true;
6504        let unit = self.stored(get_unit(&self.conn, id))?;
6505        let mut remaining = false;
6506        if let Some(unit) = unit.filter(|unit| !unit.explicit) {
6507            if self.stored(window_refs(&self.conn, id))?.is_empty() {
6508                let units = self.stored(load_units(&self.conn))?;
6509                self.conn
6510                    .execute("DELETE FROM _syncular_units WHERE id = ?1", [id])
6511                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6512                self.sync_needed = true;
6513                for table in self.schema.tables.clone() {
6514                    let Some(effective) = unit
6515                        .echo
6516                        .as_deref()
6517                        .filter(|_| covers(&table, &unit.scopes))
6518                        .and_then(|echo| pair_scopes(&unit.scopes, &table.name, Some(echo)))
6519                    else {
6520                        continue;
6521                    };
6522                    let pinned = self.pinned_row_ids(&table.name);
6523                    let owners = unit_owners(&units, &table, id);
6524                    let (more, deferred) =
6525                        self.evict_scope_rows(&table.name, &effective, &owners, &pinned)?;
6526                    remaining |= more;
6527                    if deferred {
6528                        self.save_pending_evict(id, &table.name, &effective)?;
6529                    }
6530                    self.record_scope_map(&mut batch, &table.name, &effective);
6531                }
6532            }
6533        }
6534        self.finish_observation("syncular_window", batch)?;
6535        Ok(remaining)
6536    }
6537
6538    /// §4.8 E1: delete base rows owned by the effective scopes
6539    /// ([`local_scope_predicate`]) EXCEPT pinned primary keys. Returns (more
6540    /// unpinned work, any scoped rows remain). A missing scope-column mapping
6541    /// fails without deleting rows.
6542    fn evict_scope_rows(
6543        &self,
6544        table_name: &str,
6545        effective: &[(String, Vec<String>)],
6546        owners: &[Vec<(String, Vec<String>)>],
6547        pinned: &std::collections::HashSet<String>,
6548    ) -> Result<(bool, bool), String> {
6549        let table = self.schema.table(table_name).ok_or("sync.unknown_table")?;
6550        let Some((scope, mut params)) = local_scope_predicate(table, effective, owners)
6551            .map_err(|()| "sync.scope_revoked".to_owned())?
6552        else {
6553            return Ok((false, false));
6554        };
6555        let scope_params = params.len();
6556        let pk = quote_ident(&table.primary_key);
6557        // Pinned ids are rowId text; the text form matches every key type.
6558        let predicate = if pinned.is_empty() {
6559            scope.clone()
6560        } else {
6561            params.extend(pinned.iter().cloned().map(SqlValue::Text));
6562            let holes = vec!["?"; pinned.len()].join(", ");
6563            format!("{scope} AND CAST({pk} AS TEXT) NOT IN ({holes})")
6564        };
6565        let base = base_table(table_name);
6566        let visible = visible_table(table_name);
6567        let mut ids: Vec<SqlValue> = Vec::new();
6568        for source in [&base, &visible] {
6569            let mut stmt = self
6570                .conn
6571                .prepare_cached(&format!(
6572                    "SELECT {pk} FROM {source} WHERE {predicate} LIMIT 1024"
6573                ))
6574                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6575            ids = stmt
6576                .query_map(rusqlite::params_from_iter(&params), |row| row.get(0))
6577                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
6578                .collect::<Result<_, _>>()
6579                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6580            if !ids.is_empty() {
6581                break;
6582            }
6583        }
6584        if !ids.is_empty() {
6585            for id in &ids {
6586                self.conn
6587                    .execute(
6588                        "DELETE FROM _syncular_acked_rows WHERE tbl=?1 AND id=?2",
6589                        rusqlite::params![table_name, id],
6590                    )
6591                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6592            }
6593            let holes = vec!["?"; ids.len()].join(", ");
6594            for source in [&base, &visible] {
6595                self.conn
6596                    .execute(
6597                        &format!("DELETE FROM {source} WHERE {pk} IN ({holes})"),
6598                        rusqlite::params_from_iter(&ids),
6599                    )
6600                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6601            }
6602        }
6603        let mut remaining = false;
6604        let mut deferred = false;
6605        for source in [&base, &visible] {
6606            remaining |= self
6607                .conn
6608                .query_row(
6609                    &format!("SELECT EXISTS(SELECT 1 FROM {source} WHERE {predicate})"),
6610                    rusqlite::params_from_iter(&params),
6611                    |row| row.get::<_, bool>(0),
6612                )
6613                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6614            deferred |= self
6615                .conn
6616                .query_row(
6617                    &format!("SELECT EXISTS(SELECT 1 FROM {source} WHERE {scope})"),
6618                    rusqlite::params_from_iter(&params[..scope_params]),
6619                    |row| row.get::<_, bool>(0),
6620                )
6621                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6622        }
6623        Ok((remaining, deferred))
6624    }
6625
6626    /// §4.8 E1: continue deferred evictions after the outbox drains or between
6627    /// chunks, retaining outbox pins and their durable marker. A unit that
6628    /// re-entered the window has no pending entry left.
6629    fn drain_pending_evictions(&mut self) -> Result<(), String> {
6630        let pending = self.load_pending_evictions()?;
6631        if pending.is_empty() {
6632            return Ok(());
6633        }
6634        self.rebuild_overlay_if_dirty()?;
6635        for (unit_id, table_name, effective) in pending {
6636            let Some(table) = self.schema.table(&table_name).cloned() else {
6637                self.delete_pending_evict_table(&unit_id, &table_name)?;
6638                continue;
6639            };
6640            loop {
6641                std::thread::yield_now();
6642                self.begin_observation("syncular_evict")?;
6643                let chunk = (|| {
6644                    let pinned = self.pinned_row_ids(&table_name);
6645                    let owners =
6646                        unit_owners(&self.stored(load_units(&self.conn))?, &table, &unit_id);
6647                    let (remaining, deferred) =
6648                        self.evict_scope_rows(&table_name, &effective, &owners, &pinned)?;
6649                    if !deferred {
6650                        self.delete_pending_evict_table(&unit_id, &table_name)?;
6651                    }
6652                    let mut batch = ChangeAccumulator::default();
6653                    self.record_scope_map(&mut batch, &table_name, &effective);
6654                    self.finish_observation("syncular_evict", batch)?;
6655                    Ok(remaining)
6656                })();
6657                match chunk {
6658                    Ok(true) => {}
6659                    Ok(false) => break,
6660                    Err(error) => {
6661                        self.rollback_observation("syncular_evict");
6662                        return Err(error);
6663                    }
6664                }
6665            }
6666        }
6667        Ok(())
6668    }
6669
6670    /// §4.8 E1: primary keys of `table` referenced by a pending outbox
6671    /// commit — rows that MUST NOT be evicted until the commit drains.
6672    fn pinned_row_ids(&self, table: &str) -> std::collections::HashSet<String> {
6673        let mut pinned = std::collections::HashSet::new();
6674        for commit in self
6675            .outbox
6676            .iter()
6677            .map(|commit| &**commit)
6678            .chain(self.failed_commits.iter().map(|(commit, _)| commit))
6679        {
6680            for op in &commit.ops {
6681                if op.table == table {
6682                    pinned.insert(op.row_id.clone());
6683                }
6684            }
6685        }
6686        pinned
6687    }
6688
6689    fn save_pending_evict(
6690        &self,
6691        unit_id: &str,
6692        table: &str,
6693        effective: &[(String, Vec<String>)],
6694    ) -> Result<(), String> {
6695        self.conn.execute(
6696            "INSERT OR REPLACE INTO _syncular_pending_evictions(unit_id, tbl, effective_scopes) VALUES (?1, ?2, ?3)",
6697            rusqlite::params![unit_id, table, scope_map_to_json(effective).to_string()],
6698        ).map(|_| ()).map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
6699    }
6700
6701    /// Re-entry cancels every pending eviction of the unit.
6702    fn delete_pending_evict(&self, unit_id: &str) -> Result<(), String> {
6703        self.conn
6704            .execute(
6705                "DELETE FROM _syncular_pending_evictions WHERE unit_id = ?1",
6706                [unit_id],
6707            )
6708            .map(|_| ())
6709            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
6710    }
6711
6712    fn delete_pending_evict_table(&self, unit_id: &str, table: &str) -> Result<(), String> {
6713        self.conn
6714            .execute(
6715                "DELETE FROM _syncular_pending_evictions WHERE unit_id = ?1 AND tbl = ?2",
6716                [unit_id, table],
6717            )
6718            .map(|_| ())
6719            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
6720    }
6721
6722    fn load_pending_evictions(&self) -> Result<Vec<PendingEvict>, String> {
6723        let mut stmt = self
6724            .conn
6725            .prepare("SELECT unit_id, tbl, effective_scopes FROM _syncular_pending_evictions")
6726            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6727        let rows = stmt
6728            .query_map([], |row| {
6729                Ok((
6730                    row.get::<_, String>(0)?,
6731                    row.get::<_, String>(1)?,
6732                    row.get::<_, String>(2)?,
6733                ))
6734            })
6735            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6736        rows.map(|row| {
6737            let (unit_id, table, json) =
6738                row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6739            let value: Value = serde_json::from_str(&json)
6740                .map_err(|_| "sync.local_corrupt: invalid pending eviction scopes".to_owned())?;
6741            let effective = json_to_scope_map(&value)
6742                .map_err(|_| "sync.local_corrupt: invalid pending eviction scopes".to_owned())?;
6743            Ok((unit_id, table, effective))
6744        })
6745        .collect()
6746    }
6747
6748    /// Select failed-intent retention; reload durable retained aggregates.
6749    pub fn set_retain_failed_commits(&mut self, enabled: bool) -> Result<(), String> {
6750        self.retain_failed_commits = enabled;
6751        for (commit, _) in self.failed_commits.iter() {
6752            for operation in &commit.ops {
6753                self.overlay_dirty.table(&operation.table);
6754            }
6755        }
6756        self.failed_commits = self.load_failed_commits()?.into();
6757        for (commit, _) in self.failed_commits.iter() {
6758            for operation in &commit.ops {
6759                self.overlay_dirty.table(&operation.table);
6760            }
6761        }
6762        Ok(())
6763    }
6764
6765    fn load_failed_commits(&self) -> Result<Vec<FailedCommit>, String> {
6766        let mut statement = self.conn.prepare("SELECT client_commit_id, operations_json, initial_json FROM _syncular_failed_commits ORDER BY seq")
6767            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6768        let rows = statement
6769            .query_map([], |row| {
6770                Ok((
6771                    row.get::<_, String>(0)?,
6772                    row.get::<_, String>(1)?,
6773                    row.get::<_, String>(2)?,
6774                ))
6775            })
6776            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6777        rows.map(|row| {
6778            let (id, operations, initial) =
6779                row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6780            let operations: Vec<CommitOperation> =
6781                serde_json::from_str(&operations).map_err(|_| "sync.local_corrupt".to_owned())?;
6782            let initial =
6783                serde_json::from_str(&initial).map_err(|_| "sync.local_corrupt".to_owned())?;
6784            Ok((
6785                OutboxCommit {
6786                    client_commit_id: id,
6787                    ops: operations
6788                        .into_iter()
6789                        .map(|op| OutboxOp {
6790                            upsert: op.op == "upsert",
6791                            table: op.table,
6792                            row_id: op.row_id,
6793                            base_version: op.base_version,
6794                            values: op.values,
6795                            insert: op.insert,
6796                        })
6797                        .collect(),
6798                },
6799                initial,
6800            ))
6801        })
6802        .collect()
6803    }
6804
6805    fn retain_failed_commit(&mut self, id: &str, operations: &[OutboxOp]) -> Result<(), String> {
6806        let mut initial = Map::new();
6807        for operation in operations {
6808            // A table the current schema removed has no rows to retain.
6809            let Some(table) = self.schema.table(&operation.table) else {
6810                continue;
6811            };
6812            let initial_row = match self.stored_row(table, &operation.row_id, true)? {
6813                Some(row) => Some(row),
6814                None => self.visible_row(table, &operation.row_id)?,
6815            };
6816            if let Some((values, _)) = initial_row {
6817                let mut intended: Map<String, Value> = table
6818                    .columns
6819                    .iter()
6820                    .zip(values.iter())
6821                    .map(|(column, value)| (column.name.clone(), column_value_to_json(value)))
6822                    .collect();
6823                if let Some(patch) = &operation.values {
6824                    intended.extend(patch.clone());
6825                }
6826                initial.insert(
6827                    serde_json::to_string(&(operation.table.clone(), operation.row_id.clone()))
6828                        .map_err(|_| "sync.local_corrupt".to_owned())?,
6829                    Value::Object(intended),
6830                );
6831            }
6832        }
6833        self.conn.execute("INSERT INTO _syncular_failed_commits(client_commit_id, operations_json, initial_json) VALUES (?1, ?2, ?3)", rusqlite::params![id,
6834            serde_json::to_string(&operations.iter().map(CommitOperation::from).collect::<Vec<_>>()).map_err(|_| "sync.local_corrupt".to_owned())?,
6835            serde_json::to_string(&initial).map_err(|_| "sync.local_corrupt".to_owned())?])
6836            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6837        self.failed_commits.push((
6838            OutboxCommit {
6839                client_commit_id: id.to_owned(),
6840                ops: operations.to_vec(),
6841            },
6842            initial,
6843        ));
6844        Ok(())
6845    }
6846
6847    fn drop_failed_commits(
6848        &mut self,
6849        matches: impl Fn(&str, &Map<String, Value>) -> bool,
6850    ) -> Result<Vec<OutboxCommit>, String> {
6851        let mut doomed = self.drop_acknowledged_rows(&matches)?;
6852        for (commit, initial) in self.failed_commits.iter() {
6853            for operation in &commit.ops {
6854                let key =
6855                    serde_json::to_string(&(operation.table.clone(), operation.row_id.clone()))
6856                        .map_err(|_| "sync.local_corrupt".to_owned())?;
6857                if initial
6858                    .get(&key)
6859                    .and_then(Value::as_object)
6860                    .is_some_and(|values| matches(&operation.table, values))
6861                {
6862                    doomed.push(commit.clone());
6863                    break;
6864                }
6865            }
6866        }
6867        for commit in &doomed {
6868            self.conn
6869                .execute(
6870                    "DELETE FROM _syncular_failed_commits WHERE client_commit_id = ?1",
6871                    rusqlite::params![commit.client_commit_id],
6872                )
6873                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6874        }
6875        for commit in &doomed {
6876            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))?;
6877        }
6878        self.conflicts.retain(|record| {
6879            !doomed
6880                .iter()
6881                .any(|commit| commit.client_commit_id == record.client_commit_id)
6882        });
6883        self.rejections.retain(|record| {
6884            !doomed
6885                .iter()
6886                .any(|commit| commit.client_commit_id == record.client_commit_id)
6887        });
6888        self.failed_commits.retain(|(commit, _)| {
6889            !doomed
6890                .iter()
6891                .any(|dropped| dropped.client_commit_id == commit.client_commit_id)
6892        });
6893        for commit in &doomed {
6894            for operation in &commit.ops {
6895                self.overlay_dirty.table(&operation.table);
6896            }
6897        }
6898        Ok(doomed)
6899    }
6900
6901    /// Record one commit of local mutations. The returned commit ID is the
6902    /// §2.3 idempotency key. Failures are structured so callers read
6903    /// `code`/`message`/`details` instead of parsing a string prefix.
6904    pub fn mutate(&mut self, mutations: Vec<Mutation>) -> Result<String, ClientError> {
6905        let prior = self.storage_failure.borrow_mut().take();
6906        let outcome = self
6907            .prepare_mutations(mutations)
6908            .and_then(|ops| Ok(self.record_outbox_commit(ops, None)?));
6909        self.finish_authoring(prior, outcome)
6910    }
6911
6912    /// §7.1: validate one commit's mutations into outbox operations.
6913    fn prepare_mutations(&self, mutations: Vec<Mutation>) -> Result<Vec<OutboxOp>, ClientError> {
6914        {
6915            if mutations.is_empty() {
6916                return Err(
6917                    "sync.invalid_request: a commit must contain at least one operation (§6.1)"
6918                        .to_owned()
6919                        .into(),
6920                );
6921            }
6922            let mut ops = Vec::with_capacity(mutations.len());
6923            // §7.1: a patch reads the row as the commit's earlier operations
6924            // leave it: the values an earlier upsert wrote, or None after an
6925            // earlier delete. A patch changes neither presence nor a scope
6926            // column, so it records nothing.
6927            let mut staged: HashMap<(String, String), Option<Map<String, Value>>> = HashMap::new();
6928            for mutation in mutations {
6929                match mutation {
6930                    Mutation::Patch {
6931                        table,
6932                        values,
6933                        base_version,
6934                    } => {
6935                        let schema_table = self
6936                            .schema
6937                            .table(&table)
6938                            .ok_or_else(|| "sync.unknown_table".to_owned())?;
6939                        let values = normalize_values_casing(schema_table, values)?;
6940                        let row_id = render_row_id_json(values.get(&schema_table.primary_key))?;
6941                        let base = staged.get(&(table.clone(), row_id.clone()));
6942                        ops.push(self.prepare_patch(
6943                            &table,
6944                            &row_id,
6945                            values,
6946                            base_version,
6947                            base,
6948                        )?);
6949                    }
6950                    Mutation::Upsert {
6951                        table,
6952                        values,
6953                        base_version,
6954                    } => {
6955                        let schema_table = self.schema.table(&table).ok_or_else(|| {
6956                            format!("sync.unknown_table: unknown table {table:?}")
6957                        })?;
6958                        // §5: value keys are accepted in snake_case AND the
6959                        // generated row types' camelCase; normalize to SQL truth
6960                        // before the pk lookup / codec see them.
6961                        let values = normalize_values_casing(schema_table, values)?;
6962                        let row_id = render_row_id_json(values.get(&schema_table.primary_key))?;
6963                        // §6.7 `mutate` marks every column present: fill missing
6964                        // nullable columns with NULL before the payload is built.
6965                        let values = full_row_values(schema_table, values)?;
6966                        self.refuse_sealed_row(schema_table, &row_id)?;
6967                        // §5.11: validate the payload encodes with the current
6968                        // codec. A key-selection or unknown-key failure is a
6969                        // durable rejection at the push seam (§10.3), never an
6970                        // author-time error. Full-row `mutate` presents every
6971                        // column, so no stored fallback is needed.
6972                        self.validate_author_encode(schema_table, &row_id, &values)?;
6973                        // §7.1 insert intent: the row is absent from the
6974                        // visible replica at call time, before this batch
6975                        // applies anything.
6976                        let insert = !self.visible_row_exists(schema_table, &row_id)?;
6977                        staged.insert((table.clone(), row_id.clone()), Some(values.clone()));
6978                        ops.push(OutboxOp {
6979                            upsert: true,
6980                            table,
6981                            row_id,
6982                            base_version,
6983                            values: Some(values),
6984                            insert,
6985                        });
6986                    }
6987                    Mutation::Delete {
6988                        table,
6989                        row_id,
6990                        base_version,
6991                    } => {
6992                        let schema_table = self.schema.table(&table).ok_or_else(|| {
6993                            format!("sync.unknown_table: unknown table {table:?}")
6994                        })?;
6995                        self.refuse_sealed_row(schema_table, &row_id)?;
6996                        // §2.4: the server rejects a rowId holding U+0000.
6997                        if row_id.contains('\0') {
6998                            return Err("sync.invalid_request: rowId holds U+0000 (§2.4)"
6999                                .to_owned()
7000                                .into());
7001                        }
7002                        staged.insert((table.clone(), row_id.clone()), None);
7003                        ops.push(OutboxOp {
7004                            upsert: false,
7005                            table,
7006                            row_id,
7007                            base_version,
7008                            values: None,
7009                            insert: false,
7010                        });
7011                    }
7012                }
7013            }
7014            Ok(ops)
7015        }
7016    }
7017
7018    /// Scope the retained `storage_failure` diagnostic to this call so an
7019    /// earlier operation's failure cannot classify a new one, and surface the
7020    /// call's own classified failure with its details. A fresh classified
7021    /// failure replaces the retained diagnostic; otherwise the earlier one is
7022    /// kept for the next sync.
7023    fn finish_authoring<T>(
7024        &self,
7025        prior: Option<QueryReadFailure>,
7026        outcome: Result<T, ClientError>,
7027    ) -> Result<T, ClientError> {
7028        let fresh = self.storage_failure.borrow_mut().take();
7029        *self.storage_failure.borrow_mut() = fresh.clone().or(prior);
7030        outcome.map_err(|error| fresh.map(ClientError::from).unwrap_or(error))
7031    }
7032
7033    /// `decides` names the active outcome this commit replaces (§7.2.2); the
7034    /// outcome records it as its pending decision in the same transaction.
7035    fn record_outbox_commit(
7036        &mut self,
7037        ops: Vec<OutboxOp>,
7038        decides: Option<&str>,
7039    ) -> Result<String, String> {
7040        let commit = OutboxCommit {
7041            client_commit_id: uuid::Uuid::new_v4().to_string(),
7042            ops,
7043        };
7044        self.begin_observation("syncular_mutation")?;
7045        let mut batch = ChangeAccumulator::default();
7046        for op in &commit.ops {
7047            let mut precise = self.record_row_scopes(&mut batch, &op.table, &op.row_id, false);
7048            if let Some(values) = &op.values {
7049                if let Some(table) = self.schema.table(&op.table) {
7050                    for scope in &table.scope_variables {
7051                        if let Some(Value::String(value)) = values.get(&scope.column) {
7052                            batch.scope(&op.table, format!("{}:{value}", scope.prefix));
7053                            precise = true;
7054                        }
7055                    }
7056                }
7057            }
7058            if !precise {
7059                batch.table(&op.table);
7060            }
7061        }
7062        let persisted = self.persist_outbox_insert(&commit).and_then(|()| {
7063            let Some(outcome) = decides else {
7064                return Ok(());
7065            };
7066            batch.outcomes = true;
7067            let updated = self
7068                .conn
7069                .execute(
7070                    "UPDATE _syncular_commit_outcomes SET replacement_client_commit_id = ?1
7071                      WHERE client_commit_id = ?2 AND resolution = 'active'
7072                        AND replacement_client_commit_id IS NULL",
7073                    rusqlite::params![commit.client_commit_id, outcome],
7074                )
7075                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
7076            if updated == 1 {
7077                Ok(())
7078            } else {
7079                Err(REPLACEMENT_PENDING.to_owned())
7080            }
7081        });
7082        if let Err(error) = persisted {
7083            self.rollback_observation("syncular_mutation");
7084            return Err(error);
7085        }
7086        // A clean overlay contains the FIFO fold of every previous commit, so
7087        // the new commit applies over it. §7.1: an operation that does not
7088        // apply (a secondary unique collision) fails the whole commit; the
7089        // savepoint rollback removes the outbox entry and every visible write.
7090        // The append undoes itself: a rollback capture would copy the outbox.
7091        let was_dirty = self.overlay_dirty.snapshot();
7092        let id = commit.client_commit_id.clone();
7093        let appended = self.rebuild_overlay_if_dirty().and_then(|()| {
7094            commit
7095                .ops
7096                .iter()
7097                .try_for_each(|op| self.apply_outbox_op(op))?;
7098            self.outbox.push(Arc::new(commit));
7099            batch.status = true;
7100            self.finish_observation("syncular_mutation", batch)
7101                .inspect_err(|_| drop(self.outbox.pop()))
7102        });
7103        if let Err(error) = appended {
7104            self.rollback_observation("syncular_mutation");
7105            self.overlay_dirty.restore(was_dirty);
7106            return Err(error);
7107        }
7108        Ok(id)
7109    }
7110
7111    /// Record one §6.1 sparse upsert: the primary key plus the supplied
7112    /// non-scope columns are present; every other column is absent and stays
7113    /// untouched on the server and in the local overlay. An absent local base
7114    /// refuses the whole batch with sync.row_missing before enqueueing (§7.1).
7115    /// Failures are structured so callers read `code`/`message`/`details`.
7116    pub fn patch(
7117        &mut self,
7118        table: &str,
7119        row_id: &str,
7120        partial: Map<String, Value>,
7121        base_version: Option<i64>,
7122    ) -> Result<String, ClientError> {
7123        let prior = self.storage_failure.borrow_mut().take();
7124        let outcome = self.perform_patch(table, row_id, partial, base_version);
7125        self.finish_authoring(prior, outcome)
7126    }
7127
7128    /// The unscoped patch body. Public authoring entry points scope
7129    /// `storage_failure` around the whole operation, including any pre-read.
7130    fn perform_patch(
7131        &mut self,
7132        table: &str,
7133        row_id: &str,
7134        partial: Map<String, Value>,
7135        base_version: Option<i64>,
7136    ) -> Result<String, ClientError> {
7137        let operation = self.prepare_patch(table, row_id, partial, base_version, None)?;
7138        Ok(self.record_outbox_commit(vec![operation], None)?)
7139    }
7140
7141    /// `staged` is the row as the batch's earlier operations leave it
7142    /// (`Some(None)` after a delete); `None` reads the visible replica.
7143    fn prepare_patch(
7144        &self,
7145        table: &str,
7146        row_id: &str,
7147        partial: Map<String, Value>,
7148        base_version: Option<i64>,
7149        staged: Option<&Option<Map<String, Value>>>,
7150    ) -> Result<OutboxOp, ClientError> {
7151        let schema_table = self
7152            .schema
7153            .table(table)
7154            .ok_or_else(|| format!("sync.unknown_table: unknown table {table:?}"))?;
7155        let partial = normalize_values_casing(schema_table, partial)?;
7156        if let Some(pk) = partial.get(&schema_table.primary_key) {
7157            if render_row_id_json(Some(pk)).ok().as_deref() != Some(row_id) {
7158                return Err(invalid_authoring(
7159                    "patch cannot change the primary key",
7160                    json!({ "table": table }),
7161                ));
7162            }
7163        }
7164        let exists = match staged {
7165            Some(row) => row.is_some(),
7166            None => self.visible_row_exists(schema_table, row_id)?,
7167        };
7168        if !exists {
7169            return Err("sync.row_missing: a sparse patch requires a local row"
7170                .to_owned()
7171                .into());
7172        }
7173        self.refuse_sealed_row(schema_table, row_id)?;
7174        // §3.4 rule 5 / §6.2: scope columns are immutable on update. The
7175        // server accepts a present scope column whose value equals the
7176        // stored row and applies it as a no-op, so a decoded envelope
7177        // round-trips. The local row is the only value the client can prove
7178        // equality against; when the row is absent locally the client cannot
7179        // prove equality against the server's stored row and fails closed.
7180        // A primary key that is also a scope column needs no stored-row
7181        // read: the primary key in a sparse payload is by construction the
7182        // row id being patched (§6.1), so its value is proven equal already.
7183        for scope in &schema_table.scope_variables {
7184            if !partial.contains_key(&scope.column) || scope.column == schema_table.primary_key {
7185                continue;
7186            }
7187            let Some(column) = schema_table
7188                .columns
7189                .iter()
7190                .find(|column| column.name == scope.column)
7191            else {
7192                continue;
7193            };
7194            let stored = match staged {
7195                Some(row) => row.as_ref().and_then(|row| {
7196                    json_to_column_value(column, row.get(&scope.column))
7197                        .ok()
7198                        .map(|value| column_value_to_json(&value))
7199                }),
7200                None => self
7201                    .conn
7202                    .query_row(
7203                        &format!(
7204                            "SELECT {} FROM {} WHERE {}",
7205                            quote_ident(&scope.column),
7206                            visible_table(&schema_table.name),
7207                            row_id_predicate(schema_table)
7208                        ),
7209                        rusqlite::params![row_id],
7210                        |row| Ok(sql_ref_to_json(column, row.get_ref(0)?)),
7211                    )
7212                    .optional()
7213                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?,
7214            };
7215            // Decode the supplied value through the same column-type path the
7216            // rest of the patch encoding uses, so a value that only equals
7217            // the stored one in another number representation still compares
7218            // equal.
7219            let incoming = json_to_column_value(column, partial.get(&scope.column))
7220                .ok()
7221                .map(|value| column_value_to_json(&value));
7222            // A stored blob never equals a patch value, matching the server's
7223            // scope-column comparison (§3.4): bytes are unstorable as scope
7224            // values.
7225            let equal = stored.as_ref().is_some_and(|stored| {
7226                stored.get("$bytes").is_none() && incoming.as_ref() == Some(stored)
7227            });
7228            if !equal {
7229                return Err(invalid_authoring(
7230                    "patch cannot write a scope column (§3.4)",
7231                    json!({ "table": table, "column": scope.column }),
7232                ));
7233            }
7234        }
7235        let mut values = partial;
7236        // Presence-set semantics: a proven-equal scope column is dropped, so
7237        // the patch leaves the stored value untouched (§6.2).
7238        for scope in &schema_table.scope_variables {
7239            values.remove(&scope.column);
7240        }
7241        let pk_value = match schema_table.columns[schema_table.pk_index].ty {
7242            // §2.4: the rowId of an integer key is its canonical decimal form.
7243            ColumnType::Integer => match row_id.parse::<i64>() {
7244                Ok(v)
7245                    if v.to_string() == row_id
7246                        && (-ssp2::primitives::I64_SAFE_MAX..=ssp2::primitives::I64_SAFE_MAX)
7247                            .contains(&v) =>
7248                {
7249                    Value::from(v)
7250                }
7251                _ => {
7252                    return Err(format!(
7253                    "sync.invalid_request: table {table:?}: invalid integer primary key {row_id:?}"
7254                )
7255                    .into())
7256                }
7257            },
7258            ColumnType::Boolean => match row_id {
7259                "true" => Value::Bool(true),
7260                "false" => Value::Bool(false),
7261                _ => {
7262                    return Err(format!(
7263                    "sync.invalid_request: table {table:?}: invalid boolean primary key {row_id:?}"
7264                )
7265                    .into())
7266                }
7267            },
7268            _ => Value::from(row_id.to_owned()),
7269        };
7270        values.insert(schema_table.primary_key.clone(), pk_value);
7271        // §6.1: a patch cannot null a non-nullable column.
7272        if let Some(column) = schema_table
7273            .columns
7274            .iter()
7275            .find(|column| !column.nullable && values.get(&column.name) == Some(&Value::Null))
7276        {
7277            return Err(invalid_authoring(
7278                "a non-nullable column is null (§6.1)",
7279                json!({ "table": table, "column": column.name }),
7280            ));
7281        }
7282        // §5.11: structural validation only; an absent key-id selector is
7283        // resolved at the push seam from the stored local row, and a
7284        // key-selection or unknown-key failure becomes a durable
7285        // `client.encrypt_failed` rejection there (§10.3), never an
7286        // author-time error.
7287        self.validate_author_encode(schema_table, row_id, &values)?;
7288        Ok(OutboxOp {
7289            upsert: true,
7290            table: table.to_owned(),
7291            row_id: row_id.to_owned(),
7292            base_version,
7293            values: Some(values),
7294            insert: false,
7295        })
7296    }
7297
7298    /// §5.11 key-id fallback: the stored local row's selector value as a
7299    /// positional row (only the selector slot filled). Returns None when no
7300    /// selector is configured, the row is locally absent, or the stored
7301    /// value is not a usable key id. A failed storage read is an error.
7302    fn stored_key_fallback(
7303        &self,
7304        table: &TableSchema,
7305        row_id: &str,
7306    ) -> Result<Option<Row>, String> {
7307        let Some(selector) = self.encryption.key_id_columns.get(&table.name) else {
7308            return Ok(None);
7309        };
7310        let Some(index) = table
7311            .columns
7312            .iter()
7313            .position(|column| &column.name == selector)
7314        else {
7315            return Ok(None);
7316        };
7317        let sql = format!(
7318            "SELECT {} FROM {} WHERE {}",
7319            quote_ident(selector),
7320            visible_table(&table.name),
7321            row_id_predicate(table)
7322        );
7323        let key = self
7324            .conn
7325            .query_row(&sql, rusqlite::params![row_id], |row| {
7326                row.get::<_, Option<String>>(0)
7327            })
7328            .optional()
7329            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
7330            .flatten()
7331            .filter(|key| !key.is_empty());
7332        let Some(key) = key else {
7333            return Ok(None);
7334        };
7335        let mut fallback: Row = vec![None; table.columns.len()];
7336        fallback[index] = Some(ColumnValue::String(key));
7337        Ok(Some(fallback))
7338    }
7339
7340    /// §5.11/§10.3 author-time encode check: a structural failure (a
7341    /// non-nullable NULL, a value the codec rejects) is an author-time
7342    /// error; a key-selection or unknown-key failure is deferred to the push
7343    /// seam, where it becomes a durable `client.encrypt_failed` rejection.
7344    fn validate_author_encode(
7345        &self,
7346        table: &TableSchema,
7347        row_id: &str,
7348        values: &Map<String, Value>,
7349    ) -> Result<(), String> {
7350        match encode_sparse_row_json(table, row_id, values, &self.encryption, None) {
7351            Err(error) if error.starts_with(ENCRYPT_FAILED_CODE) => Ok(()),
7352            result => result.map(|_| ()),
7353        }
7354    }
7355
7356    /// §5.11/§10.3: drop every pending commit whose push encode fails with
7357    /// `client.encrypt_failed` (an unresolvable key id or an unknown key) and
7358    /// raise one durable rejection per commit. `sync()` never aborts for an
7359    /// encode failure. Mirrors §7.4.4's `drop_incompatible_outbox`, including
7360    /// undoing the dropped commit's purely-optimistic rows.
7361    /// §7.1/§7.4.4: drop pending commits whose values the current codec refuses
7362    /// (an envelope or a type an earlier version accepted). `with_encryption`
7363    /// additionally drops commits whose §5.11 encryption cannot resolve a key;
7364    /// the startup boundary leaves those to the send seam, where hosts configure
7365    /// keys after open. The send path checks only the commits this round pushes
7366    /// (§8.8): a held commit is never encoded or dropped before it is due.
7367    /// Recovery runs as one observation. An enclosing observation (the guarded
7368    /// schema reset) passes its `batch`, so the rejection, outcome, and table
7369    /// domains join that change event instead of publishing a second one.
7370    fn drop_unencodable_outbox(
7371        &mut self,
7372        with_encryption: bool,
7373        batch: Option<&mut ChangeAccumulator>,
7374    ) -> Result<bool, String> {
7375        let mut failures = Vec::new();
7376        let due = if with_encryption {
7377            self.pushable_commits()
7378        } else {
7379            self.outbox.len()
7380        };
7381        for commit in self.outbox.iter().take(due) {
7382            for op in &commit.ops {
7383                let Some(table) = self.schema.table(&op.table).filter(|_| op.upsert) else {
7384                    continue;
7385                };
7386                // An insert lacking a non-nullable column is left to
7387                // `drop_incompatible_outbox` (§7.4.4).
7388                let Some(values) = op.presented_values(table) else {
7389                    continue;
7390                };
7391                let fallback = self.stored_key_fallback(table, &op.row_id)?;
7392                let failure = match encode_sparse_row_json(
7393                    table,
7394                    &op.row_id,
7395                    &values,
7396                    &self.encryption,
7397                    fallback.as_ref(),
7398                ) {
7399                    Err(error) if error.starts_with(ENCRYPT_FAILED_CODE) => {
7400                        with_encryption.then_some((error, ENCRYPT_FAILED_CODE))
7401                    }
7402                    // §7.1/§7.4.4: a value the current codec refuses was
7403                    // persisted by a version that accepted it; it leaves
7404                    // through the incompatible-outbox path, so the FIFO
7405                    // queue never wedges.
7406                    Err(error) if error.starts_with(INVALID_REQUEST_CODE) => Some((
7407                        LEGACY_VALUE_REFUSAL_MESSAGE.to_owned(),
7408                        OUTBOX_INCOMPATIBLE_CODE,
7409                    )),
7410                    _ => None,
7411                };
7412                if let Some((error, code)) = failure {
7413                    failures.push((commit.clone(), error, code));
7414                    break;
7415                }
7416            }
7417        }
7418        if failures.is_empty() {
7419            return Ok(false);
7420        }
7421        self.reject_outbox_commits(
7422            failures
7423                .into_iter()
7424                .map(|(commit, message, code)| {
7425                    let details = (code == OUTBOX_INCOMPATIBLE_CODE).then(|| RejectionDetails {
7426                        field_paths: None,
7427                        reason: Some(INVALID_STORED_VALUES_REASON.to_owned()),
7428                        required_action: None,
7429                        references: None,
7430                    });
7431                    (commit, message, code, details)
7432                })
7433                .collect(),
7434            batch,
7435        )?;
7436        Ok(true)
7437    }
7438
7439    /// §7.4.4 client-local terminal drop of pending commits, each journaled as a
7440    /// rejection with `code` and `details`. Every code except
7441    /// `sync.outbox_incompatible` keeps the retained intent.
7442    #[allow(clippy::type_complexity)]
7443    fn reject_outbox_commits(
7444        &mut self,
7445        failures: Vec<(
7446            Arc<OutboxCommit>,
7447            String,
7448            &'static str,
7449            Option<RejectionDetails>,
7450        )>,
7451        batch: Option<&mut ChangeAccumulator>,
7452    ) -> Result<(), String> {
7453        // §7.4.4: one observation covers the durable outcome writes, the outbox
7454        // removal, the in-memory drop, and the overlay rebuild, so a storage fault
7455        // leaves the replica and the client unchanged, a successful recovery
7456        // publishes one batch with the rejection, outcome, and table domains, and
7457        // an ordinary open with nothing to recover publishes nothing.
7458        let rollback = self.capture();
7459        let owns_observation = batch.is_none();
7460        let owns_transaction = self.conn.is_autocommit();
7461        let mut domains = ChangeAccumulator::default();
7462        if owns_observation {
7463            self.begin_observation("syncular_value_recovery")?;
7464        }
7465        let dropped = (|| -> Result<(), String> {
7466            for (commit, message, code, details) in failures {
7467                if self.retain_failed_commits && code != OUTBOX_INCOMPATIBLE_CODE {
7468                    self.retain_failed_commit(&commit.client_commit_id, &commit.ops)?;
7469                }
7470                let representable = commit.ops.iter().all(Self::outbox_op_is_journalable);
7471                let rejection = RejectionRecord {
7472                    client_commit_id: commit.client_commit_id.clone(),
7473                    op_index: 0,
7474                    code: code.to_owned(),
7475                    message,
7476                    retryable: false,
7477                    details,
7478                    operation: representable
7479                        .then(|| commit.ops.first())
7480                        .flatten()
7481                        .map(CommitOperation::from),
7482                };
7483                self.persist_commit_outcome(
7484                    &commit.client_commit_id,
7485                    CommitOutcomeStatus::Rejected,
7486                    &[CommitOperationOutcome::Error {
7487                        rejection: rejection.clone(),
7488                    }],
7489                    representable.then_some(commit.ops.as_slice()),
7490                )?;
7491                self.leave_through(&commit.client_commit_id);
7492                self.delete_outbox_persisted(&commit.client_commit_id)?;
7493                self.outbox
7494                    .retain(|candidate| candidate.client_commit_id != commit.client_commit_id);
7495                self.rejections.push(rejection);
7496                for operation in &commit.ops {
7497                    domains.table(operation.table.as_str());
7498                }
7499            }
7500            domains.status = true;
7501            domains.rejections = true;
7502            domains.outcomes = true;
7503            self.prune_commit_outcomes()?;
7504            // The visible projection is re-derived from the surviving base + outbox.
7505            self.overlay_dirty.set(true);
7506            self.rebuild_overlay()?;
7507            Ok(())
7508        })();
7509        let result = match batch {
7510            Some(batch) => {
7511                if dropped.is_ok() {
7512                    for table in domains.tables.keys() {
7513                        batch.table(table.as_str());
7514                    }
7515                    batch.status |= domains.status;
7516                    batch.rejections |= domains.rejections;
7517                    batch.outcomes |= domains.outcomes;
7518                }
7519                dropped
7520            }
7521            None => {
7522                dropped.and_then(|()| self.finish_observation("syncular_value_recovery", domains))
7523            }
7524        };
7525        if let Err(error) = result {
7526            if owns_observation {
7527                if owns_transaction {
7528                    if let Err(rollback) = self.conn.execute_batch("ROLLBACK") {
7529                        let mut failure = self.storage_failure.borrow_mut();
7530                        let failure =
7531                            failure.get_or_insert_with(|| QueryReadFailure::from(error.clone()));
7532                        failure.rollback_failure = Some(Box::new(QueryReadFailure::from(rollback)));
7533                    }
7534                } else {
7535                    self.rollback_observation("syncular_value_recovery");
7536                }
7537            }
7538            self.restore(rollback);
7539            return Err(error);
7540        }
7541        Ok(())
7542    }
7543
7544    pub fn pending_commit_ids(&self) -> Vec<String> {
7545        self.outbox
7546            .iter()
7547            .map(|c| c.client_commit_id.clone())
7548            .collect()
7549    }
7550
7551    /// §7.1: every pending commit in FIFO order, as the TypeScript client's
7552    /// `pendingCommits()` returns it.
7553    pub fn pending_commits(&self) -> Result<Vec<PendingCommit>, String> {
7554        let mut stmt = self
7555            .conn
7556            .prepare_cached(
7557                "SELECT seq, commit_id, created_at_ms, ops_json FROM _syncular_outbox ORDER BY seq",
7558            )
7559            .map_err(|error| error.to_string())?;
7560        let rows = stmt
7561            .query_map([], |row| {
7562                Ok((
7563                    row.get(0)?,
7564                    row.get(1)?,
7565                    row.get(2)?,
7566                    row.get::<_, String>(3)?,
7567                ))
7568            })
7569            .map_err(|error| error.to_string())?;
7570        rows.map(|row| {
7571            let (seq, client_commit_id, created_at_ms, raw) =
7572                row.map_err(|error| error.to_string())?;
7573            let operations = serde_json::from_str(&raw).map_err(|error| {
7574                format!("invalid persisted outbox {client_commit_id:?}: {error}")
7575            })?;
7576            Ok(PendingCommit {
7577                seq,
7578                client_commit_id,
7579                created_at_ms,
7580                operations,
7581            })
7582        })
7583        .collect()
7584    }
7585
7586    /// §6.1: the sparse push payload bytes of every pending upsert operation,
7587    /// FIFO — exactly what the next push round would put on the wire. Used by
7588    /// conformance B.21(h) to pin cross-core byte identity.
7589    pub fn pending_payloads(&self) -> Result<Vec<Vec<u8>>, String> {
7590        let mut payloads = Vec::new();
7591        for commit in self.outbox.iter() {
7592            for op in &commit.ops {
7593                let Some(table) = self.schema.table(&op.table).filter(|_| op.upsert) else {
7594                    continue;
7595                };
7596                let Some(values) = op.presented_values(table) else {
7597                    continue;
7598                };
7599                let fallback = self.stored_key_fallback(table, &op.row_id)?;
7600                if let Ok(payload) = encode_sparse_row_json(
7601                    table,
7602                    &op.row_id,
7603                    &values,
7604                    &self.encryption,
7605                    fallback.as_ref(),
7606                ) {
7607                    payloads.push(payload);
7608                }
7609            }
7610        }
7611        Ok(payloads)
7612    }
7613
7614    pub fn conflicts(&self) -> &[ConflictRecord] {
7615        &self.conflicts
7616    }
7617
7618    pub fn rejections(&self) -> &[RejectionRecord] {
7619        &self.rejections
7620    }
7621
7622    pub fn resolve_commit_outcome(
7623        &mut self,
7624        input: ResolveCommitOutcomeInput,
7625    ) -> Result<CommitOutcome, String> {
7626        let current = self
7627            .commit_outcome(&input.client_commit_id)?
7628            .ok_or_else(|| {
7629                format!(
7630                    "sync.outcome_not_found: no durable outcome exists for {:?}",
7631                    input.client_commit_id
7632                )
7633            })?;
7634        if current.resolution != CommitOutcomeResolution::Active {
7635            return Ok(current);
7636        }
7637        if current.replacement_client_commit_id.is_some() {
7638            return Err(REPLACEMENT_PENDING.to_owned());
7639        }
7640        if input.resolution == CommitOutcomeResolution::Active {
7641            return Err("sync.invalid_request: resolution must leave active state".to_owned());
7642        }
7643        match input.resolution {
7644            CommitOutcomeResolution::Superseded => {
7645                let replacement = input
7646                    .replacement_client_commit_id
7647                    .as_deref()
7648                    .filter(|value| !value.is_empty() && *value != input.client_commit_id)
7649                    .ok_or_else(|| {
7650                        "sync.invalid_request: superseded outcomes require a distinct replacementClientCommitId"
7651                            .to_owned()
7652                    })?;
7653                let _ = replacement;
7654            }
7655            _ if input.replacement_client_commit_id.is_some() => {
7656                return Err(
7657                    "sync.invalid_request: replacementClientCommitId is valid only for superseded outcomes"
7658                        .to_owned(),
7659                );
7660            }
7661            _ => {}
7662        }
7663        let allowed = match current.status {
7664            CommitOutcomeStatus::Conflict => matches!(
7665                input.resolution,
7666                CommitOutcomeResolution::ResolvedKeepServer | CommitOutcomeResolution::Superseded
7667            ),
7668            CommitOutcomeStatus::Rejected => {
7669                matches!(
7670                    input.resolution,
7671                    CommitOutcomeResolution::Superseded
7672                        | CommitOutcomeResolution::ResolvedKeepServer
7673                )
7674            }
7675            CommitOutcomeStatus::Applied | CommitOutcomeStatus::Cached => {
7676                input.resolution == CommitOutcomeResolution::Dismissed
7677            }
7678            CommitOutcomeStatus::Replaced => false,
7679        };
7680        if !allowed {
7681            return Err(format!(
7682                "sync.invalid_request: resolution {:?} is invalid for {:?} outcome",
7683                input.resolution, current.status
7684            ));
7685        }
7686
7687        let rollback = self.capture();
7688        self.begin_observation("syncular_outcome_resolution")?;
7689        let mut batch = ChangeAccumulator::default();
7690        let result = self
7691            .release_outcome(
7692                &current,
7693                input.resolution,
7694                input.replacement_client_commit_id.as_deref(),
7695                &mut batch,
7696            )
7697            .and_then(|()| self.rebuild_overlay_if_dirty())
7698            .and_then(|()| self.finish_observation("syncular_outcome_resolution", batch));
7699        if let Err(error) = result {
7700            self.rollback_observation("syncular_outcome_resolution");
7701            self.restore(rollback);
7702            return Err(error);
7703        }
7704        self.commit_outcome(&current.client_commit_id)?
7705            .ok_or_else(|| "sync.outcome_not_found: outcome disappeared".to_owned())
7706    }
7707
7708    /// §7.2.2: record a decision against an active conflict or rejection as a
7709    /// held replacement commit and return its client commit id. Without
7710    /// `replacement` the retained envelope is kept ("keep mine"); every
7711    /// operation on a retained row takes that row's base version.
7712    pub fn replace_commit_outcome(
7713        &mut self,
7714        client_commit_id: &str,
7715        sequence: i64,
7716        replacement: Option<Vec<Mutation>>,
7717    ) -> Result<String, ClientError> {
7718        let prior = self.storage_failure.borrow_mut().take();
7719        let outcome = (|| -> Result<String, ClientError> {
7720            let Some(current) = self.commit_outcome(client_commit_id)? else {
7721                return Err(ClientError {
7722                    code: "sync.outcome_not_found".to_owned(),
7723                    message: "no durable outcome exists for the commit".to_owned(),
7724                    details: Some(json!({ "clientCommitId": client_commit_id })),
7725                    retryable: false,
7726                });
7727            };
7728            if current.resolution == CommitOutcomeResolution::Active
7729                && current.replacement_client_commit_id.is_some()
7730            {
7731                return Err(ClientError {
7732                    code: "client.replacement_pending".to_owned(),
7733                    message: "the outcome has a pending replacement".to_owned(),
7734                    details: Some(json!({ "clientCommitId": client_commit_id })),
7735                    retryable: false,
7736                });
7737            }
7738            let (Some(envelope), Some(rows)) = (current.operations, current.retained_rows) else {
7739                return Err(invalid_authoring(
7740                    "the outcome cannot be replaced",
7741                    json!({ "clientCommitId": client_commit_id }),
7742                ));
7743            };
7744            if current.sequence != sequence
7745                || current.resolution != CommitOutcomeResolution::Active
7746                || !matches!(
7747                    current.status,
7748                    CommitOutcomeStatus::Conflict | CommitOutcomeStatus::Rejected
7749                )
7750                || rows.is_empty()
7751                || envelope.len() != rows.len()
7752            {
7753                return Err(invalid_authoring(
7754                    "the outcome cannot be replaced",
7755                    json!({ "clientCommitId": client_commit_id }),
7756                ));
7757            }
7758            let ops = match replacement {
7759                None => envelope
7760                    .into_iter()
7761                    .zip(&rows)
7762                    .map(|(operation, row)| OutboxOp {
7763                        base_version: Some(row.server_version.unwrap_or(0)),
7764                        ..OutboxOp::from(operation)
7765                    })
7766                    .collect(),
7767                Some(mutations) => {
7768                    let mut ops = self.prepare_mutations(mutations)?;
7769                    for op in &mut ops {
7770                        let Some(row) = rows
7771                            .iter()
7772                            .find(|row| row.table == op.table && row.row_id == op.row_id)
7773                        else {
7774                            continue;
7775                        };
7776                        if op.base_version.is_some() {
7777                            return Err(invalid_authoring(
7778                                "an operation on a retained row takes its base version",
7779                                json!({ "table": op.table }),
7780                            ));
7781                        }
7782                        op.base_version = Some(row.server_version.unwrap_or(0));
7783                    }
7784                    ops
7785                }
7786            };
7787            Ok(self.record_outbox_commit(ops, Some(client_commit_id))?)
7788        })();
7789        self.finish_authoring(prior, outcome)
7790    }
7791
7792    /// §7.2.3: replace the operations of the pending commit `client_commit_id`
7793    /// and return `replacement_client_commit_id`. An attempted commit is fenced
7794    /// first (§6.12) over `transport`; a never-attempted one needs none.
7795    pub fn replace_pending_commit(
7796        &mut self,
7797        transport: &mut dyn Transport,
7798        client_commit_id: &str,
7799        mutations: Vec<Mutation>,
7800        replacement_client_commit_id: &str,
7801    ) -> Result<String, ClientError> {
7802        match self.prepare_pending_commit_replacement(
7803            client_commit_id,
7804            mutations,
7805            replacement_client_commit_id,
7806        )? {
7807            None => Ok(replacement_client_commit_id.to_owned()),
7808            Some(prepared) => {
7809                let reply = prepared.exchange(transport);
7810                self.apply_fence_round(prepared, reply)
7811            }
7812        }
7813    }
7814
7815    /// The owner half of [`SyncClient::replace_pending_commit`]. `None` means
7816    /// the replacement is complete (or an earlier call with the same
7817    /// replacement id completed it); otherwise send the fence round and apply
7818    /// its reply with [`SyncClient::apply_fence_round`].
7819    pub fn prepare_pending_commit_replacement(
7820        &mut self,
7821        client_commit_id: &str,
7822        mutations: Vec<Mutation>,
7823        replacement_client_commit_id: &str,
7824    ) -> Result<Option<PreparedFenceRound>, ClientError> {
7825        let prior = self.storage_failure.borrow_mut().take();
7826        let outcome = (|| -> Result<Option<PreparedFenceRound>, ClientError> {
7827            let Some(original) = self
7828                .outbox
7829                .iter()
7830                .find(|commit| commit.client_commit_id == client_commit_id)
7831                .cloned()
7832            else {
7833                return match self.commit_outcome(client_commit_id)? {
7834                    Some(outcome)
7835                        if Self::is_replaced(&outcome)
7836                            && outcome.replacement_client_commit_id.as_deref()
7837                                == Some(replacement_client_commit_id) =>
7838                    {
7839                        Ok(None)
7840                    }
7841                    _ => Err(ClientError {
7842                        code: "sync.outcome_not_found".to_owned(),
7843                        message: "no pending commit exists for the id".to_owned(),
7844                        details: Some(json!({ "clientCommitId": client_commit_id })),
7845                        retryable: false,
7846                    }),
7847                };
7848            };
7849            if replacement_client_commit_id.is_empty()
7850                || self
7851                    .outbox
7852                    .iter()
7853                    .any(|commit| commit.client_commit_id == replacement_client_commit_id)
7854                || self.commit_outcome(replacement_client_commit_id)?.is_some()
7855            {
7856                return Err(invalid_authoring(
7857                    "the replacement client commit id must be unused",
7858                    json!({ "replacementClientCommitId": replacement_client_commit_id }),
7859                ));
7860            }
7861            // §7.2.2: a held replacement waits for its proof under its own id.
7862            let held: bool = self
7863                .conn
7864                .query_row(
7865                    "SELECT EXISTS(SELECT 1 FROM _syncular_commit_outcomes
7866                      WHERE resolution = 'active' AND replacement_client_commit_id = ?1)",
7867                    [client_commit_id],
7868                    |row| row.get(0),
7869                )
7870                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
7871            if held {
7872                return Err(REPLACEMENT_PENDING.to_owned().into());
7873            }
7874            let full_rows: Vec<bool> = mutations
7875                .iter()
7876                .map(|mutation| matches!(mutation, Mutation::Upsert { .. }))
7877                .collect();
7878            let mut operations = self.prepare_mutations(mutations)?;
7879            for (operation, full_row) in operations.iter_mut().zip(full_rows) {
7880                let touched: Vec<&OutboxOp> = original
7881                    .ops
7882                    .iter()
7883                    .filter(|op| op.table == operation.table && op.row_id == operation.row_id)
7884                    .collect();
7885                // §7.1: a full-row upsert of a row the original inserted keeps
7886                // the insert intent the original recorded.
7887                operation.insert |= full_row && touched.iter().any(|op| op.insert);
7888                if let Some(first) = touched.first() {
7889                    operation.base_version = first.base_version;
7890                }
7891            }
7892            let attempted: bool = self
7893                .conn
7894                .query_row(
7895                    "SELECT attempted FROM _syncular_outbox WHERE commit_id = ?1",
7896                    [client_commit_id],
7897                    |row| row.get(0),
7898                )
7899                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
7900            if !attempted {
7901                self.replace_outbox_commit(
7902                    client_commit_id,
7903                    operations,
7904                    replacement_client_commit_id,
7905                )?;
7906                return Ok(None);
7907            }
7908            if self.transport_closed() {
7909                return Err(ClientError {
7910                    code: "sync.offline".to_owned(),
7911                    message: "transport gate is closed".to_owned(),
7912                    details: None,
7913                    retryable: false,
7914                });
7915            }
7916            if self.active_round.is_some() || self.fence_round.is_some() {
7917                return Err(ClientError {
7918                    code: "client.round_in_progress".to_owned(),
7919                    message: "a sync round is already in flight".to_owned(),
7920                    details: None,
7921                    retryable: false,
7922                });
7923            }
7924            if self.realtime_policy == RealtimePolicy::Required
7925                && self.realtime_state != RealtimeState::Connected
7926            {
7927                return Err(ClientError {
7928                    code: REALTIME_UNAVAILABLE_CODE.to_owned(),
7929                    message: "the realtime socket is not connected".to_owned(),
7930                    details: None,
7931                    retryable: true,
7932                });
7933            }
7934            let header = Frame::ReqHeader {
7935                client_id: self.client_id.clone(),
7936                schema_version: self.schema.version,
7937                log_epoch: self.get_meta(LOG_EPOCH_KEY)?,
7938                outbox_id: self.get_meta(OUTBOX_ID_KEY)?,
7939            };
7940            let id = uuid::Uuid::new_v4();
7941            self.fence_round = Some(id);
7942            Ok(Some(PreparedFenceRound {
7943                id,
7944                client_commit_id: client_commit_id.to_owned(),
7945                replacement_client_commit_id: replacement_client_commit_id.to_owned(),
7946                operations,
7947                request: encode_message(&Message {
7948                    wire_version: WIRE_VERSION,
7949                    msg_kind: MsgKind::Request,
7950                    frames: vec![
7951                        header,
7952                        Frame::FenceCommit {
7953                            client_commit_id: client_commit_id.to_owned(),
7954                        },
7955                    ],
7956                }),
7957                realtime: self.realtime_state == RealtimeState::Connected,
7958            }))
7959        })();
7960        self.finish_authoring(prior, outcome)
7961    }
7962
7963    /// Apply the reply of a [`PreparedFenceRound`] on the owner (§6.12,
7964    /// §7.2.3) and return the replacement's id. No network I/O. A stored
7965    /// result settles the original through the push-result path and fails
7966    /// with `client.commit_settled`.
7967    pub fn apply_fence_round(
7968        &mut self,
7969        prepared: PreparedFenceRound,
7970        reply: Result<Vec<u8>, TransportError>,
7971    ) -> Result<String, ClientError> {
7972        if self.fence_round != Some(prepared.id) {
7973            return Err(ClientError {
7974                code: "client.round_cancelled".to_owned(),
7975                message: "fence round belongs to a released client context".to_owned(),
7976                details: None,
7977                retryable: false,
7978            });
7979        }
7980        self.fence_round = None;
7981        let prior = self.storage_failure.borrow_mut().take();
7982        let outcome = (|| -> Result<String, ClientError> {
7983            let id = prepared.client_commit_id.as_str();
7984            let invalid = || ClientError {
7985                code: "client.invalid_host_response".to_owned(),
7986                message: "the fence response does not answer the fenced commit".to_owned(),
7987                details: Some(json!({ "clientCommitId": id })),
7988                retryable: false,
7989            };
7990            let bytes = reply.map_err(|error| ClientError {
7991                retryable: error
7992                    .details
7993                    .as_ref()
7994                    .and_then(|details| details.get("retryable"))
7995                    == Some(&Value::Bool(true)),
7996                code: error.code,
7997                message: error.message,
7998                details: error.details,
7999            })?;
8000            let response = decode_message(&bytes).map_err(|_| invalid())?;
8001            if response.msg_kind != MsgKind::Response {
8002                return Err(invalid());
8003            }
8004            let mut frames = response
8005                .frames
8006                .into_iter()
8007                .filter(|frame| !matches!(frame, Frame::Keepalive));
8008            match frames.next() {
8009                // §1.6: a schema-floor response; the client stops syncing as
8010                // a sync round's floor stops it.
8011                Some(Frame::RespHeader {
8012                    required_schema_version: Some(required),
8013                    latest_schema_version,
8014                    ..
8015                }) => {
8016                    self.set_schema_floor(Some(SchemaFloor {
8017                        required_schema_version: Some(required),
8018                        latest_schema_version,
8019                    }))?;
8020                    return Err(ClientError {
8021                        code: "sync.schema_mismatch".to_owned(),
8022                        message: "the server requires a newer schema version".to_owned(),
8023                        details: Some(json!({ "requiredSchemaVersion": required })),
8024                        retryable: false,
8025                    });
8026                }
8027                Some(Frame::RespHeader {
8028                    reset_required: false,
8029                    ..
8030                }) => {}
8031                _ => return Err(invalid()),
8032            }
8033            let answer = frames.next();
8034            let rest: Vec<Frame> = frames.collect();
8035            match answer {
8036                // A server that predates the frame refuses the request.
8037                Some(Frame::Error {
8038                    code,
8039                    message,
8040                    retryable,
8041                    details,
8042                    ..
8043                }) => Err(ClientError {
8044                    code,
8045                    message,
8046                    details: details.and_then(|details| serde_json::from_str(&details.0).ok()),
8047                    retryable,
8048                }),
8049                Some(Frame::CommitFenced { client_commit_id })
8050                    if client_commit_id == id && rest.is_empty() =>
8051                {
8052                    self.replace_outbox_commit(
8053                        id,
8054                        prepared.operations,
8055                        &prepared.replacement_client_commit_id,
8056                    )?;
8057                    Ok(prepared.replacement_client_commit_id)
8058                }
8059                Some(Frame::PushResult {
8060                    client_commit_id,
8061                    status,
8062                    commit_seq,
8063                    results,
8064                }) if client_commit_id == id => {
8065                    let mut details = HashMap::new();
8066                    match rest.as_slice() {
8067                        [] => {}
8068                        [Frame::PushResultDetails {
8069                            client_commit_id: owner,
8070                            entries,
8071                        }] if owner == id => {
8072                            let parsed = entries
8073                                .iter()
8074                                .map(|entry| -> Result<_, String> {
8075                                    Ok((entry.op_index, RejectionDetails::parse(&entry.details.0)?))
8076                                })
8077                                .collect::<Result<BTreeMap<i32, RejectionDetails>, String>>()
8078                                .map_err(|_| invalid())?;
8079                            details.insert(id.to_owned(), parsed);
8080                        }
8081                        _ => return Err(invalid()),
8082                    }
8083                    let settled = if status == PushStatus::Rejected {
8084                        "rejected"
8085                    } else {
8086                        "applied"
8087                    };
8088                    let mut report = SyncReport::default();
8089                    self.handle_push_results(
8090                        &[Frame::PushResult {
8091                            client_commit_id,
8092                            status,
8093                            commit_seq,
8094                            results,
8095                        }],
8096                        &HashSet::from([id]),
8097                        &details,
8098                        &mut report,
8099                        Some(id),
8100                    )
8101                    .map_err(|_| ClientError {
8102                        code: "client.outcome_persistence_failed".to_owned(),
8103                        message: "local commit outcome could not be persisted".to_owned(),
8104                        details: None,
8105                        retryable: false,
8106                    })?;
8107                    // §6.3: a serving failure is no outcome; the commit stays.
8108                    if !report.retryable.is_empty() {
8109                        return Err(ClientError {
8110                            code: "sync.idempotency_cache_miss".to_owned(),
8111                            message: "the server could not serve the stored result".to_owned(),
8112                            details: Some(json!({ "clientCommitId": id })),
8113                            retryable: true,
8114                        });
8115                    }
8116                    Err(ClientError {
8117                        code: "client.commit_settled".to_owned(),
8118                        message: "the commit already has a server outcome".to_owned(),
8119                        details: Some(json!({ "clientCommitId": id, "status": settled })),
8120                        retryable: false,
8121                    })
8122                }
8123                _ => Err(invalid()),
8124            }
8125        })();
8126        self.finish_authoring(prior, outcome)
8127    }
8128
8129    /// §7.2.3: swap a pending commit's operations and id in place (same
8130    /// outbox sequence), re-derive the overlay of its rows and every later
8131    /// commit, and journal the original as `replaced`, in one transaction
8132    /// with one change batch.
8133    fn replace_outbox_commit(
8134        &mut self,
8135        client_commit_id: &str,
8136        ops: Vec<OutboxOp>,
8137        replacement: &str,
8138    ) -> Result<(), ClientError> {
8139        let Some(index) = self
8140            .outbox
8141            .iter()
8142            .position(|commit| commit.client_commit_id == client_commit_id)
8143        else {
8144            return Err(ClientError {
8145                code: "sync.outcome_not_found".to_owned(),
8146                message: "no pending commit exists for the id".to_owned(),
8147                details: Some(json!({ "clientCommitId": client_commit_id })),
8148                retryable: false,
8149            });
8150        };
8151        let original = self.outbox[index].clone();
8152        let commit = OutboxCommit {
8153            client_commit_id: replacement.to_owned(),
8154            ops,
8155        };
8156        let rollback = self.capture();
8157        self.begin_observation("syncular_pending_replacement")?;
8158        let mut batch = ChangeAccumulator::default();
8159        let replaced = (|| {
8160            let (seq, created_at_ms): (i64, i64) = self
8161                .conn
8162                .query_row(
8163                    "SELECT seq, created_at_ms FROM _syncular_outbox WHERE commit_id = ?1",
8164                    [client_commit_id],
8165                    |row| Ok((row.get(0)?, row.get(1)?)),
8166                )
8167                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8168            self.persist_outbox_insert(&commit)?;
8169            self.leave_through(client_commit_id);
8170            self.delete_outbox_persisted(client_commit_id)?;
8171            // §7.2.1: journaled as a purge journals its drops, decided.
8172            let results = (0..original.ops.len())
8173                .map(|op_index| CommitOperationOutcome::Error {
8174                    rejection: RejectionRecord {
8175                        client_commit_id: client_commit_id.to_owned(),
8176                        op_index: op_index as i32,
8177                        code: COMMIT_REPLACED_CODE.to_owned(),
8178                        message: "the commit was replaced before the server applied it".to_owned(),
8179                        retryable: false,
8180                        details: None,
8181                        operation: None,
8182                    },
8183                })
8184                .collect::<Vec<_>>();
8185            let results_json =
8186                serde_json::to_string(&results).map_err(|error| error.to_string())?;
8187            self.conn
8188                .execute(
8189                    "UPDATE _syncular_outbox SET seq = ?1, created_at_ms = ?2 WHERE commit_id = ?3",
8190                    rusqlite::params![seq, created_at_ms, replacement],
8191                )
8192                .and_then(|_| {
8193                    self.conn.execute(
8194                        "INSERT INTO _syncular_commit_outcomes (
8195                           client_commit_id, status, recorded_at_ms, results_json, resolution,
8196                           resolved_at_ms, replacement_client_commit_id
8197                         ) VALUES (?1, 'rejected', ?2, ?3, 'superseded', ?2, ?4)",
8198                        rusqlite::params![
8199                            client_commit_id,
8200                            self.clock_now_ms(),
8201                            results_json,
8202                            replacement
8203                        ],
8204                    )
8205                })
8206                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8207            self.prune_commit_outcomes()?;
8208            for op in original.ops.iter().chain(&commit.ops) {
8209                self.overlay_dirty.table(&op.table);
8210                batch.table(&op.table);
8211            }
8212            self.outbox[index] = Arc::new(commit);
8213            batch.status = true;
8214            batch.outcomes = true;
8215            self.rebuild_overlay_if_dirty()?;
8216            self.finish_observation("syncular_pending_replacement", batch)
8217        })();
8218        if let Err(error) = replaced {
8219            self.rollback_observation("syncular_pending_replacement");
8220            self.restore(rollback);
8221            return Err(error.into());
8222        }
8223        Ok(())
8224    }
8225
8226    /// Internal host step at the start of an idle drive (§7.2.2): capture
8227    /// every pending decision with the units and epochs of this drive.
8228    #[doc(hidden)]
8229    pub fn prepare_replacements(&self) -> Result<Vec<CurrentBasePreparation>, String> {
8230        let mut stmt = self
8231            .conn
8232            .prepare_cached(
8233                "SELECT client_commit_id, seq, replacement_client_commit_id
8234                   FROM _syncular_commit_outcomes
8235                  WHERE resolution = 'active' AND replacement_client_commit_id IS NOT NULL
8236                  ORDER BY seq ASC",
8237            )
8238            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8239        let decisions = stmt
8240            .query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
8241            .and_then(|rows| rows.collect::<Result<Vec<(String, i64, String)>, _>>())
8242            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8243        if decisions.is_empty() {
8244            return Ok(Vec::new());
8245        }
8246        let units = self.stored(load_units(&self.conn))?;
8247        Ok(decisions
8248            .into_iter()
8249            .map(
8250                |(client_commit_id, sequence, replacement)| CurrentBasePreparation {
8251                    client_commit_id,
8252                    sequence,
8253                    replacement: Some(replacement),
8254                    units: units.clone(),
8255                    transport_epoch: self.transport_epoch,
8256                    registration_epoch: self.registration_epoch,
8257                    security_epoch: self.security_epoch,
8258                },
8259            )
8260            .collect())
8261    }
8262
8263    /// Internal host step when an idle drive reaches idle (§7.2.2): write,
8264    /// refuse, or keep each decision captured at the drive's start. Returns
8265    /// whether a decision was written, so the drive runs another round.
8266    #[doc(hidden)]
8267    pub fn settle_replacements(
8268        &mut self,
8269        decisions: &[CurrentBasePreparation],
8270        drive: &SyncOutcome,
8271    ) -> Result<bool, String> {
8272        if self.transport_closed() {
8273            return Ok(false);
8274        }
8275        let mut written = false;
8276        for decision in decisions {
8277            // A registration change during the drive says nothing about the
8278            // base; the decision waits for the next drive.
8279            if decision.registration_epoch != self.registration_epoch {
8280                continue;
8281            }
8282            let Some(replacement) = decision.replacement.as_deref() else {
8283                continue;
8284            };
8285            let Some(current) =
8286                self.commit_outcome(&decision.client_commit_id)?
8287                    .filter(|current| {
8288                        current.resolution == CommitOutcomeResolution::Active
8289                            && current.replacement_client_commit_id.as_deref() == Some(replacement)
8290                    })
8291            else {
8292                continue;
8293            };
8294            let held = self
8295                .outbox
8296                .iter()
8297                .find(|commit| commit.client_commit_id == replacement)
8298                .cloned();
8299            let refused = match &held {
8300                // A revocation drop (§3.3) or a crash already ended the
8301                // replacement; its own journal entry records what happened.
8302                None => None,
8303                Some(commit) => match self.finish_current_base(decision.clone(), drive.clone()) {
8304                    CurrentBaseProof {
8305                        rows: Some(rows), ..
8306                    } => {
8307                        let proven = commit.ops.iter().all(|op| {
8308                            rows.iter()
8309                                .find(|row| row.table == op.table && row.row_id == op.row_id)
8310                                .is_none_or(|row| {
8311                                    op.base_version == Some(row.server_version.unwrap_or(0))
8312                                })
8313                        });
8314                        written |= proven;
8315                        (!proven).then(|| "base_moved".to_owned())
8316                    }
8317                    CurrentBaseProof {
8318                        reason:
8319                            Some(
8320                                reason @ (CurrentBaseProofReason::SchemaFloor
8321                                | CurrentBaseProofReason::MissingCoverage
8322                                | CurrentBaseProofReason::Revoked
8323                                | CurrentBaseProofReason::OutcomeUnavailable),
8324                            ),
8325                        ..
8326                    } => Some(
8327                        serde_json::to_value(reason)
8328                            .ok()
8329                            .and_then(|reason| reason.as_str().map(str::to_owned))
8330                            .ok_or("sync.local_corrupt")?,
8331                    ),
8332                    _ => continue,
8333                },
8334            };
8335            // One transaction: the original outcome is superseded first, so
8336            // the refused replacement retains its intent over the restored
8337            // server base.
8338            let rollback = self.capture();
8339            self.begin_observation("syncular_replacement")?;
8340            let mut batch = ChangeAccumulator::default();
8341            let result = self
8342                .release_outcome(
8343                    &current,
8344                    CommitOutcomeResolution::Superseded,
8345                    Some(replacement),
8346                    &mut batch,
8347                )
8348                .and_then(|()| self.rebuild_overlay_if_dirty())
8349                .and_then(|()| match (refused, held) {
8350                    (Some(reason), Some(commit)) => self.reject_outbox_commits(
8351                        vec![(
8352                            commit,
8353                            "the replacement could not be written on a proven base".to_owned(),
8354                            REPLACEMENT_REFUSED_CODE,
8355                            Some(RejectionDetails {
8356                                field_paths: None,
8357                                reason: Some(reason),
8358                                required_action: None,
8359                                references: None,
8360                            }),
8361                        )],
8362                        Some(&mut batch),
8363                    ),
8364                    _ => Ok(()),
8365                })
8366                .and_then(|()| self.finish_observation("syncular_replacement", batch));
8367            if let Err(error) = result {
8368                self.rollback_observation("syncular_replacement");
8369                self.restore(rollback);
8370                return Err(error);
8371            }
8372        }
8373        if written {
8374            self.set_sync_needed(true, true);
8375        }
8376        Ok(written)
8377    }
8378
8379    /// §7.2.1 explicit resolution inside the caller's observation: record the
8380    /// resolution, release the retained aggregate and mark its tables for the
8381    /// overlay rebuild, which restores the server base and replays what
8382    /// remains over it.
8383    fn release_outcome(
8384        &mut self,
8385        current: &CommitOutcome,
8386        resolution: CommitOutcomeResolution,
8387        replacement: Option<&str>,
8388        batch: &mut ChangeAccumulator,
8389    ) -> Result<(), String> {
8390        self.conn
8391            .execute(
8392                "UPDATE _syncular_commit_outcomes
8393                    SET resolution = ?1, resolved_at_ms = ?2,
8394                        replacement_client_commit_id = ?3
8395                  WHERE client_commit_id = ?4 AND resolution = 'active'",
8396                rusqlite::params![
8397                    Self::outcome_resolution_name(resolution),
8398                    self.clock_now_ms(),
8399                    replacement,
8400                    current.client_commit_id
8401                ],
8402            )
8403            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8404        self.conn
8405            .execute(
8406                "DELETE FROM _syncular_failed_commits WHERE client_commit_id = ?1",
8407                rusqlite::params![current.client_commit_id],
8408            )
8409            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8410        for (commit, _) in self.failed_commits.iter() {
8411            if commit.client_commit_id == current.client_commit_id {
8412                for operation in &commit.ops {
8413                    self.overlay_dirty.table(&operation.table);
8414                }
8415            }
8416        }
8417        self.failed_commits
8418            .retain(|(commit, _)| commit.client_commit_id != current.client_commit_id);
8419        self.prune_commit_outcomes()?;
8420        self.conflicts
8421            .retain(|record| record.client_commit_id != current.client_commit_id);
8422        self.rejections
8423            .retain(|record| record.client_commit_id != current.client_commit_id);
8424        batch.conflicts |= current.status == CommitOutcomeStatus::Conflict;
8425        batch.rejections |= current.status == CommitOutcomeStatus::Rejected;
8426        batch.outcomes = true;
8427        for operation in current.operations.iter().flatten() {
8428            batch.table(&operation.table);
8429        }
8430        Ok(())
8431    }
8432
8433    pub fn schema_floor(&self) -> Option<&SchemaFloor> {
8434        self.schema_floor.as_ref()
8435    }
8436
8437    /// §7.3.5: the client's opaque auth-lease state, if any.
8438    pub fn lease_state(&self) -> Option<&LeaseState> {
8439        self.lease_state.as_ref()
8440    }
8441
8442    /// §7.3.5: record a request-level lease error (stop-and-surface). Only
8443    /// the two lease codes set it; other errors leave leaseState untouched.
8444    fn record_lease_error(&mut self, code: &str) -> Result<(), String> {
8445        if code != "sync.auth_lease_required" && code != "sync.auth_lease_revoked" {
8446            return Ok(());
8447        }
8448        let mut next = self.lease_state.clone().unwrap_or_default();
8449        next.error_code = Some(code.to_owned());
8450        self.set_lease_state(Some(next))
8451    }
8452
8453    fn set_lease_state(&mut self, next: Option<LeaseState>) -> Result<(), String> {
8454        if self.lease_state == next {
8455            return Ok(());
8456        }
8457        self.begin_observation("syncular_lease")?;
8458        let rollback = self.capture();
8459        self.lease_state = next;
8460        let persisted = match &self.lease_state {
8461            Some(lease) => serde_json::to_string(lease)
8462                .map_err(|error| error.to_string())
8463                .and_then(|json| self.set_meta(LEASE_STATE_KEY, &json)),
8464            None => self.delete_meta(LEASE_STATE_KEY),
8465        };
8466        let batch = ChangeAccumulator {
8467            status: true,
8468            ..ChangeAccumulator::default()
8469        };
8470        if let Err(error) =
8471            persisted.and_then(|()| self.finish_observation("syncular_lease", batch))
8472        {
8473            self.rollback_observation("syncular_lease");
8474            self.restore(rollback);
8475            return Err(error);
8476        }
8477        Ok(())
8478    }
8479
8480    fn set_schema_floor(&mut self, next: Option<SchemaFloor>) -> Result<(), String> {
8481        if self.schema_floor == next {
8482            return Ok(());
8483        }
8484        self.begin_observation("syncular_schema_floor")?;
8485        let rollback = self.capture();
8486        self.stopped = next.is_some();
8487        self.schema_floor = next;
8488        let persisted = match &self.schema_floor {
8489            Some(floor) => serde_json::to_string(floor)
8490                .map_err(|error| error.to_string())
8491                .and_then(|json| self.set_meta(SCHEMA_FLOOR_KEY, &json)),
8492            None => self.delete_meta(SCHEMA_FLOOR_KEY),
8493        };
8494        let batch = ChangeAccumulator {
8495            status: true,
8496            ..ChangeAccumulator::default()
8497        };
8498        if let Err(error) =
8499            persisted.and_then(|()| self.finish_observation("syncular_schema_floor", batch))
8500        {
8501            self.rollback_observation("syncular_schema_floor");
8502            self.restore(rollback);
8503            return Err(error);
8504        }
8505        Ok(())
8506    }
8507
8508    fn set_upgrading(&mut self, value: bool) {
8509        if self.upgrading == value {
8510            return;
8511        }
8512        if self.begin_observation("syncular_upgrading").is_err() {
8513            return;
8514        }
8515        self.upgrading = value;
8516        self.upgrade_kept_tables &= value;
8517        let batch = ChangeAccumulator {
8518            status: true,
8519            ..ChangeAccumulator::default()
8520        };
8521        if self
8522            .finish_observation("syncular_upgrading", batch)
8523            .is_err()
8524        {
8525            self.rollback_observation("syncular_upgrading");
8526        }
8527    }
8528
8529    pub fn sync_needed(&self) -> bool {
8530        self.sync_needed
8531    }
8532
8533    pub fn read_rows(&self, table: &str) -> Result<Vec<RowState>, String> {
8534        let schema_table = self
8535            .schema
8536            .table(table)
8537            .ok_or_else(|| format!("unknown table {table:?}"))?;
8538        let sql = format!(
8539            "SELECT * FROM {} ORDER BY {} ASC",
8540            visible_table(table),
8541            quote_ident(&schema_table.primary_key)
8542        );
8543        let mut stmt = self
8544            .conn
8545            .prepare(&sql)
8546            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8547        let mut rows = stmt
8548            .query([])
8549            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8550        let mut out = Vec::new();
8551        while let Some(row) = rows
8552            .next()
8553            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
8554        {
8555            let mut values = Map::new();
8556            for (i, column) in schema_table.columns.iter().enumerate() {
8557                let value = row
8558                    .get_ref(i)
8559                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8560                values.insert(column.name.clone(), sql_ref_to_json(column, value));
8561            }
8562            let version: i64 = row
8563                .get(schema_table.columns.len())
8564                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8565            let row_id = match values.get(&schema_table.primary_key) {
8566                Some(Value::String(s)) => s.clone(),
8567                Some(Value::Number(n)) => n.to_string(),
8568                Some(Value::Bool(b)) => b.to_string(),
8569                other => format!("{}", other.cloned().unwrap_or(Value::Null)),
8570            };
8571            let sealed_key = if schema_table.has_encrypted_columns() {
8572                row.get(schema_table.columns.len() + 1)
8573                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
8574            } else {
8575                None
8576            };
8577            out.push(RowState {
8578                row_id,
8579                version,
8580                values,
8581                sealed_key,
8582            });
8583        }
8584        Ok(out)
8585    }
8586
8587    // -- §5.10.5 native CRDT (the `crdt-yjs` feature) --------------------------
8588    //
8589    // The Rust face of the §5.10.4 client model: a local crdt edit loads the
8590    // current stored (server-merged ⊕ pending-overlay) column bytes, applies
8591    // the op with `yrs`, re-encodes the whole doc state, and records a
8592    // baseVersion-less sparse upsert carrying only the primary key and the
8593    // crdt column (§5.10.3, §6.6). No local merge — merging is server-side;
8594    // the overlay re-materializes the edit immediately (optimistic apply,
8595    // §7.1) and the server-merged bytes arrive on the next pull, idempotently.
8596    // Byte-compatible with `@syncular/crdt-yjs`.
8597
8598    /// The current stored value of a `crdt` column for one row — the visible
8599    /// (optimistic) bytes, or `None` when the row is absent or the column is
8600    /// NULL (the empty document, §5.10.1). Errors if the column is not a
8601    /// `crdt` column (guards the app against a typo'd column name).
8602    #[cfg(feature = "crdt-yjs")]
8603    fn crdt_column_bytes(
8604        &self,
8605        table: &str,
8606        row_id: &str,
8607        column: &str,
8608    ) -> Result<Option<Vec<u8>>, String> {
8609        let schema_table = self
8610            .schema
8611            .table(table)
8612            .ok_or_else(|| format!("unknown table {table:?}"))?;
8613        let col = schema_table
8614            .columns
8615            .iter()
8616            .find(|c| c.name == column)
8617            .ok_or_else(|| format!("table {table:?} has no column {column:?}"))?;
8618        if col.ty != ColumnType::Crdt {
8619            return Err(format!("column {column:?} is not a crdt column (§5.10.1)"));
8620        }
8621        let sql = format!(
8622            "SELECT {} FROM {} WHERE {}",
8623            quote_ident(column),
8624            visible_table(table),
8625            row_id_predicate(schema_table)
8626        );
8627        let bytes: Option<Vec<u8>> = self
8628            .conn
8629            .prepare_cached(&sql)
8630            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
8631            .query_row(rusqlite::params![row_id], |row| {
8632                row.get::<_, Option<Vec<u8>>>(0)
8633            })
8634            .map_err(|e| match e {
8635                rusqlite::Error::QueryReturnedNoRows => "no such row".to_owned(),
8636                other => Self::sqlite_failure(&self.storage_failure, other),
8637            })?;
8638        Ok(bytes)
8639    }
8640
8641    /// §5.10.4 materialize: the collaborative text of a `crdt` column, decoded
8642    /// from the stored bytes with `yrs` — `YjsColumn.text(name).toString()`.
8643    /// An absent row / NULL column is the empty document (empty string).
8644    #[cfg(feature = "crdt-yjs")]
8645    pub fn crdt_text(
8646        &self,
8647        table: &str,
8648        row_id: &str,
8649        column: &str,
8650        name: &str,
8651    ) -> Result<String, String> {
8652        let bytes = self
8653            .crdt_column_bytes(table, row_id, column)?
8654            .unwrap_or_default();
8655        crate::crdt::text(&bytes, name)
8656    }
8657
8658    /// §5.10.4 push-an-update: apply a text insert to a `crdt` column and
8659    /// record the resulting crdt-only sparse operation. Returns the enqueued
8660    /// `clientCommitId`.
8661    #[cfg(feature = "crdt-yjs")]
8662    pub fn crdt_insert_text(
8663        &mut self,
8664        table: &str,
8665        row_id: &str,
8666        column: &str,
8667        name: &str,
8668        index: u32,
8669        value: &str,
8670    ) -> Result<String, ClientError> {
8671        let prior = self.storage_failure.borrow_mut().take();
8672        let outcome = (|| -> Result<String, ClientError> {
8673            let current = self
8674                .crdt_column_bytes(table, row_id, column)?
8675                .unwrap_or_default();
8676            let update = crate::crdt::insert_text(&current, name, index, value)?;
8677            self.perform_crdt_push_update(table, row_id, column, &update)
8678        })();
8679        self.finish_authoring(prior, outcome)
8680    }
8681
8682    /// §5.10.4 push-an-update: apply a text delete to a `crdt` column and
8683    /// record the resulting crdt-only sparse operation. Returns the enqueued
8684    /// `clientCommitId`.
8685    #[cfg(feature = "crdt-yjs")]
8686    pub fn crdt_delete_text(
8687        &mut self,
8688        table: &str,
8689        row_id: &str,
8690        column: &str,
8691        name: &str,
8692        index: u32,
8693        len: u32,
8694    ) -> Result<String, ClientError> {
8695        let prior = self.storage_failure.borrow_mut().take();
8696        let outcome = (|| -> Result<String, ClientError> {
8697            let current = self
8698                .crdt_column_bytes(table, row_id, column)?
8699                .unwrap_or_default();
8700            let update = crate::crdt::delete_text(&current, name, index, len)?;
8701            self.perform_crdt_push_update(table, row_id, column, &update)
8702        })();
8703        self.finish_authoring(prior, outcome)
8704    }
8705
8706    /// §5.10.4 generic escape hatch: apply an arbitrary Yjs update onto a
8707    /// `crdt` column's current state and record the resulting crdt-only sparse
8708    /// operation. The app authored the update with its own `yrs` model.
8709    /// Returns the enqueued `clientCommitId`.
8710    #[cfg(feature = "crdt-yjs")]
8711    pub fn crdt_apply_update(
8712        &mut self,
8713        table: &str,
8714        row_id: &str,
8715        column: &str,
8716        update: &[u8],
8717    ) -> Result<String, ClientError> {
8718        let prior = self.storage_failure.borrow_mut().take();
8719        let outcome = (|| -> Result<String, ClientError> {
8720            let current = self
8721                .crdt_column_bytes(table, row_id, column)?
8722                .unwrap_or_default();
8723            let next = crate::crdt::apply_update(&current, update)?;
8724            self.perform_crdt_push_update(table, row_id, column, &next)
8725        })();
8726        self.finish_authoring(prior, outcome)
8727    }
8728
8729    /// Shared tail of the crdt edit methods: record a §6.1 sparse crdt-only
8730    /// upsert — the primary key plus the crdt column, no `baseVersion` — and
8731    /// enqueue it. The server merges the crdt column and leaves every other
8732    /// column untouched (§5.10.3), so a baseVersion-less crdt edit cannot
8733    /// clobber a concurrent edit to another column. A locally absent row
8734    /// records the same partial operation; the server answers per §6.2.
8735    #[cfg(feature = "crdt-yjs")]
8736    fn perform_crdt_push_update(
8737        &mut self,
8738        table: &str,
8739        row_id: &str,
8740        column: &str,
8741        crdt_bytes: &[u8],
8742    ) -> Result<String, ClientError> {
8743        let mut bytes_obj = Map::new();
8744        bytes_obj.insert("$bytes".to_owned(), Value::from(bytes_to_hex(crdt_bytes)));
8745        let mut partial = Map::new();
8746        partial.insert(column.to_owned(), Value::Object(bytes_obj));
8747        self.perform_patch(table, row_id, partial, None)
8748    }
8749
8750    /// Run an arbitrary read-only SQL query against the local database and
8751    /// return each row as a `column-name → JSON value` map. This is the seam
8752    /// the React `useSyncQuery` live-query API needs (it takes app-authored
8753    /// SQL over the visible tables/views, not a fixed table read like
8754    /// [`read_rows`]).
8755    ///
8756    /// Bound `params` are the driver value forms: JSON strings/numbers/bools/
8757    /// null bind directly; a `{"$bytes": hex}` object binds as a BLOB — the
8758    /// same envelope the command surface uses everywhere else. Output BLOB
8759    /// columns come back as `{"$bytes": hex}` to round-trip cleanly.
8760    ///
8761    /// The result column typing is dynamic (SQLite's stored affinity), because
8762    /// arbitrary SQL can alias, join, and compute — there is no schema column
8763    /// to consult per output cell, unlike [`read_rows`].
8764    pub fn query(&self, sql: &str, params: &[QueryValue]) -> Result<Vec<QueryRow>, String> {
8765        query_connection(&self.conn, sql, params).map_err(|failure| failure.to_string())
8766    }
8767
8768    /// Repository benchmark and conformance access, present only with `bench-internals`.
8769    #[cfg(feature = "bench-internals")]
8770    #[doc(hidden)]
8771    pub fn benchmark_connection(&mut self) -> &mut Connection {
8772        &mut self.conn
8773    }
8774
8775    /// Private benchmark intervals; absent from ordinary builds and diagnostics.
8776    #[cfg(feature = "bench-internals")]
8777    #[doc(hidden)]
8778    pub fn benchmark_phases(
8779        &self,
8780        enabled: Option<bool>,
8781        reset: bool,
8782    ) -> Result<Option<Value>, String> {
8783        self.benchmark_phases.configure(enabled, reset)?;
8784        Ok(self.benchmark_phases.snapshot())
8785    }
8786
8787    /// §5.11 native ceiling: refuse a declared authority query whose authored
8788    /// statement reads a table or column outside `ceiling` (table to permitted
8789    /// columns) or performs an action other than SELECT, READ, or a
8790    /// deterministic core function. The refusal is
8791    /// `client.authority_read_forbidden` with `{ query, reason: "ceiling",
8792    /// table, column }`.
8793    pub fn check_authority_ceiling(
8794        &mut self,
8795        ceiling: &BTreeMap<String, Vec<String>>,
8796    ) -> Result<(), ClientError> {
8797        for query in &self.limits.authority_reads {
8798            for (table, columns) in authority_read_set(&mut self.conn, query)? {
8799                let Some(allowed) = ceiling.get(&table) else {
8800                    return Err(authority_refusal(
8801                        &query.name,
8802                        "ceiling",
8803                        Some(table.as_str()),
8804                        None,
8805                    ));
8806                };
8807                if let Some(column) = columns
8808                    .iter()
8809                    .find(|column| !column.is_empty() && !allowed.contains(column))
8810                {
8811                    return Err(authority_refusal(
8812                        &query.name,
8813                        "ceiling",
8814                        Some(table.as_str()),
8815                        Some(column.as_str()),
8816                    ));
8817                }
8818            }
8819        }
8820        Ok(())
8821    }
8822
8823    /// §5.11: run declared authority queries over the accepted base in one
8824    /// SQLite read transaction. Each request is a query name and its params
8825    /// keyed by param name; each result carries its rows, its coverage per
8826    /// table and unit, whether every entry is complete, and every row of a
8827    /// read table with intent. A query reading an encrypted, `bytes` or
8828    /// `_sync_sealed_key` column fails with
8829    /// `client.security_preflight_required` while a preflight is pending.
8830    pub fn authority_read(
8831        &self,
8832        requests: &[(String, Map<String, Value>)],
8833    ) -> Result<AuthorityReadResult, ClientError> {
8834        if self.limits.authority_reads.is_empty() {
8835            return Err(authority_forbidden(None));
8836        }
8837        // Every request resolves and types its params before the read opens.
8838        let mut prepared = Vec::with_capacity(requests.len());
8839        for (name, params) in requests {
8840            let query = self
8841                .limits
8842                .authority_reads
8843                .iter()
8844                .find(|query| &query.name == name)
8845                .ok_or_else(|| ClientError {
8846                    code: "client.authority_query_unknown".to_owned(),
8847                    message: "authority query is not declared".to_owned(),
8848                    details: Some(json!({ "query": name })),
8849                    retryable: false,
8850                })?;
8851            let invalid = |param: &str| ClientError {
8852                code: "sync.invalid_request".to_owned(),
8853                message: "authority query parameter is missing, extra or mistyped".to_owned(),
8854                details: Some(json!({ "query": name, "param": param })),
8855                retryable: false,
8856            };
8857            if let Some(extra) = params
8858                .keys()
8859                .find(|key| !query.params.iter().any(|param| &param.name == *key))
8860            {
8861                return Err(invalid(extra.as_str()));
8862            }
8863            let mut bound = BTreeMap::new();
8864            for param in &query.params {
8865                let value = params
8866                    .get(&param.name)
8867                    .ok_or_else(|| invalid(param.name.as_str()))?;
8868                let sql = match (param.ty.as_str(), value) {
8869                    (_, Value::Null) if param.nullable => Value::Null,
8870                    ("string", Value::String(_)) | ("float", Value::Number(_)) => value.clone(),
8871                    ("integer", Value::Number(number))
8872                        if number
8873                            .as_i64()
8874                            .is_some_and(|n| n.unsigned_abs() <= MAX_JS_SAFE_INTEGER) =>
8875                    {
8876                        value.clone()
8877                    }
8878                    ("boolean", Value::Bool(flag)) => Value::from(i64::from(*flag)),
8879                    ("json", Value::String(text))
8880                        if serde_json::from_str::<Value>(text).is_ok() =>
8881                    {
8882                        value.clone()
8883                    }
8884                    _ => return Err(invalid(param.name.as_str())),
8885                };
8886                bound.insert(param.name.as_str(), sql);
8887            }
8888            // A coverage param names a unit value: a string or an integer.
8889            let scalar = |param: &str| match params.get(param) {
8890                Some(Value::String(text)) => Ok(text.clone()),
8891                Some(Value::Number(number))
8892                    if number
8893                        .as_i64()
8894                        .is_some_and(|n| n.unsigned_abs() <= MAX_JS_SAFE_INTEGER) =>
8895                {
8896                    Ok(number.to_string())
8897                }
8898                _ => Err(invalid(param)),
8899            };
8900            let mut coverage = Vec::new();
8901            for entry in &query.coverage {
8902                let base = WindowBase {
8903                    variable: entry.variable.clone(),
8904                    fixed_scopes: entry
8905                        .fixed_scopes
8906                        .iter()
8907                        .map(
8908                            |(variable, param)| -> Result<(String, String), ClientError> {
8909                                Ok((variable.clone(), scalar(param.as_str())?))
8910                            },
8911                        )
8912                        .collect::<Result<UnitScopes, ClientError>>()?,
8913                };
8914                for unit in &entry.units {
8915                    coverage.push((entry.table.as_str(), base.clone(), scalar(unit.as_str())?));
8916                }
8917            }
8918            prepared.push((query, bound, coverage));
8919        }
8920        self.conn
8921            .execute_batch("SAVEPOINT syncular_authority_read")
8922            .map_err(authority_stored)?;
8923        let result = (|| -> Result<AuthorityReadResult, ClientError> {
8924            let revision = meta_get(&self.conn, LOCAL_REVISION_KEY)
8925                .map_err(authority_stored)?
8926                .filter(|revision| {
8927                    revision
8928                        .parse::<u64>()
8929                        .is_ok_and(|parsed| &parsed.to_string() == revision)
8930                })
8931                .ok_or_else(authority_corrupt)?;
8932            if self.security_preflight {
8933                let protected = |(name, columns): (&String, &Vec<String>)| {
8934                    let table = self.schema.table(name).expect("validated authority table");
8935                    columns.iter().any(|column| {
8936                        column == "_sync_sealed_key"
8937                            || table.columns.iter().enumerate().any(|(index, held)| {
8938                                &held.name == column
8939                                    && (held.ty == ColumnType::Bytes
8940                                        || table.encrypted_columns.iter().any(|e| e.index == index))
8941                            })
8942                    })
8943                };
8944                if let Some((query, ..)) = prepared
8945                    .iter()
8946                    .find(|(query, ..)| query.reads.iter().any(protected))
8947                {
8948                    return Err(ClientError {
8949                        code: SECURITY_PREFLIGHT_REQUIRED_CODE.to_owned(),
8950                        message: "protected authority reads require activateSecurity".to_owned(),
8951                        details: Some(json!({ "query": query.name })),
8952                        retryable: false,
8953                    });
8954                }
8955            }
8956            let units = load_units(&self.conn).map_err(authority_stored)?;
8957            let mut results = Vec::with_capacity(prepared.len());
8958            for (query, bound, coverage) in &prepared {
8959                let (sql, mut params, intent) = self.authority_statement(query)?;
8960                params.extend(query.bind.iter().map(|name| bound[name.as_str()].clone()));
8961                let rows =
8962                    query_connection(&self.conn, &sql, &params).map_err(ClientError::from)?;
8963                let coverage = coverage
8964                    .iter()
8965                    .map(|(table, base, unit)| {
8966                        let mut json_base = json!({ "variable": base.variable });
8967                        if !base.fixed_scopes.is_empty() {
8968                            json_base["fixedScopes"] = json!(base.fixed_scopes);
8969                        }
8970                        AuthorityCoverageState {
8971                            table: (*table).to_owned(),
8972                            base: json_base,
8973                            unit: unit.clone(),
8974                            state: entry_coverage(
8975                                &units,
8976                                table,
8977                                self.schema.table(table),
8978                                base,
8979                                unit,
8980                            )
8981                            .0,
8982                        }
8983                    })
8984                    .collect::<Vec<_>>();
8985                results.push(AuthorityQueryResult {
8986                    query: query.name.clone(),
8987                    rows,
8988                    complete: coverage.iter().all(|entry| entry.state == "complete"),
8989                    coverage,
8990                    intent,
8991                });
8992            }
8993            Ok(AuthorityReadResult { revision, results })
8994        })();
8995        match result {
8996            Ok(read) => {
8997                self.conn
8998                    .execute_batch("RELEASE syncular_authority_read")
8999                    .map_err(authority_stored)?;
9000                Ok(read)
9001            }
9002            Err(error) => {
9003                self.conn
9004                    .execute_batch(
9005                        "ROLLBACK TO syncular_authority_read; RELEASE syncular_authority_read",
9006                    )
9007                    .map_err(authority_stored)?;
9008                Err(error)
9009            }
9010        }
9011    }
9012
9013    /// §5.11: the statement `authority_read` runs for `query`, its shadow
9014    /// params, which precede the authored binds, and the intent rows of its
9015    /// read tables, sorted by table and row id. Every read table with
9016    /// intent reads its accepted base through a common table expression of
9017    /// the same name; the text is identical in the TypeScript core. The Rust
9018    /// mirror keeps the accepted base in `_syncular_base_<table>`: retained,
9019    /// acknowledged and pending intent replay only onto the visible table, so
9020    /// the base row of an intent id is the earliest accepted state.
9021    fn authority_statement(
9022        &self,
9023        query: &AuthorityQuery,
9024    ) -> Result<(String, Vec<Value>, Vec<AuthorityIntent>), ClientError> {
9025        let mut shadows = Vec::new();
9026        let mut params = Vec::new();
9027        let mut intent = Vec::new();
9028        for (name, reads) in &query.reads {
9029            let table = self.schema.table(name).expect("validated authority table");
9030            // One kind per row by the base precedence: a retained entry, then
9031            // an acknowledged one, then pending outbox intent.
9032            let mut ids = Vec::new();
9033            let mut statement = self
9034                .conn
9035                .prepare_cached(
9036                    "SELECT id,min(k) FROM (\
9037                     SELECT json_extract(value,'$.table') AS tbl,json_extract(value,'$.rowId') AS id,2 AS k \
9038                     FROM _syncular_outbox,json_each(ops_json) \
9039                     UNION ALL SELECT json_extract(value,'$.table'),json_extract(value,'$.rowId'),0 \
9040                     FROM _syncular_failed_commits,json_each(operations_json) \
9041                     UNION ALL SELECT tbl,id,1 FROM _syncular_acked_rows) WHERE tbl=?1 GROUP BY id",
9042                )
9043                .map_err(authority_stored)?;
9044            let mut rows = statement.query([name]).map_err(authority_stored)?;
9045            while let Some(row) = rows.next().map_err(authority_stored)? {
9046                ids.push((
9047                    row.get::<_, String>(0).map_err(authority_stored)?,
9048                    row.get::<_, usize>(1).map_err(authority_stored)?,
9049                ));
9050            }
9051            if ids.is_empty() {
9052                continue;
9053            }
9054            ids.sort_by(|a, b| a.0.encode_utf16().cmp(b.0.encode_utf16()));
9055            intent.extend(ids.iter().map(|(row_id, kind)| AuthorityIntent {
9056                table: name.clone(),
9057                row_id: row_id.clone(),
9058                kind: ["retained", "acknowledged", "pending"][*kind],
9059            }));
9060            let ids: Vec<String> = ids.into_iter().map(|(id, _)| id).collect();
9061            let columns: Vec<&str> =
9062                std::iter::once(table.primary_key.as_str())
9063                    .chain(reads.iter().map(String::as_str).filter(|column| {
9064                        *column != table.primary_key && *column != "_sync_version"
9065                    }))
9066                    .chain(std::iter::once("_sync_version"))
9067                    .collect();
9068            let physical = columns
9069                .iter()
9070                .map(|column| {
9071                    if *column == "_sync_version" {
9072                        "_syncular_version".to_owned()
9073                    } else {
9074                        quote_ident(column)
9075                    }
9076                })
9077                .collect::<Vec<_>>()
9078                .join(",");
9079            let key = quote_ident(&table.primary_key);
9080            let mut statement = self
9081                .conn
9082                .prepare(&format!(
9083                    "SELECT CAST({key} AS TEXT),{physical} FROM {} \
9084                     WHERE CAST({key} AS TEXT) IN (SELECT value FROM json_each(?1))",
9085                    base_table(name),
9086                ))
9087                .map_err(authority_stored)?;
9088            let mut rows = statement
9089                .query([serde_json::to_string(&ids).expect("intent ids serialize")])
9090                .map_err(authority_stored)?;
9091            let mut bases = Vec::new();
9092            while let Some(row) = rows.next().map_err(authority_stored)? {
9093                let id = row.get::<_, String>(0).map_err(authority_stored)?;
9094                let mut values = Vec::with_capacity(columns.len());
9095                for index in 1..=columns.len() {
9096                    values.push(match row.get_ref(index).map_err(authority_stored)? {
9097                        ValueRef::Null => Value::Null,
9098                        ValueRef::Integer(integer) => Value::from(integer),
9099                        ValueRef::Real(real) => serde_json::Number::from_f64(real)
9100                            .map(Value::Number)
9101                            .ok_or_else(authority_corrupt)?,
9102                        ValueRef::Text(text) => {
9103                            Value::from(std::str::from_utf8(text).map_err(|_| authority_corrupt())?)
9104                        }
9105                        ValueRef::Blob(blob) => json!({ "$bytes": bytes_to_hex(blob) }),
9106                    });
9107                }
9108                let version = values
9109                    .last()
9110                    .and_then(Value::as_i64)
9111                    .ok_or_else(authority_corrupt)?;
9112                if version >= 0 {
9113                    bases.push((id, Value::Array(values)));
9114                }
9115            }
9116            bases.sort_by(|a, b| a.0.encode_utf16().cmp(b.0.encode_utf16()));
9117            let shadow = quote_ident(name);
9118            shadows.push(format!(
9119                "{shadow} AS (SELECT {} FROM main.{shadow} WHERE CAST({key} AS TEXT) NOT IN \
9120                 (SELECT value FROM json_each(?)) UNION ALL SELECT {} FROM json_each(?))",
9121                columns
9122                    .iter()
9123                    .map(|column| quote_ident(column))
9124                    .collect::<Vec<_>>()
9125                    .join(","),
9126                columns
9127                    .iter()
9128                    .enumerate()
9129                    .map(|(index, column)| {
9130                        if table
9131                            .columns
9132                            .iter()
9133                            .any(|held| held.name == *column && held.ty == ColumnType::Bytes)
9134                        {
9135                            format!("unhex(json_extract(value,'$[{index}].\"$bytes\"'))")
9136                        } else {
9137                            format!("json_extract(value,'$[{index}]')")
9138                        }
9139                    })
9140                    .collect::<Vec<_>>()
9141                    .join(","),
9142            ));
9143            params.push(Value::from(
9144                serde_json::to_string(&ids).expect("intent ids serialize"),
9145            ));
9146            params.push(Value::from(
9147                Value::from_iter(bases.into_iter().map(|(_, row)| row)).to_string(),
9148            ));
9149        }
9150        let sql = if shadows.is_empty() {
9151            query.sql.clone()
9152        } else {
9153            let keyword = |text: &str, word: &str| {
9154                text.get(..word.len())
9155                    .is_some_and(|head| head.eq_ignore_ascii_case(word))
9156                    && text[word.len()..].starts_with(char::is_whitespace)
9157            };
9158            let shadows = shadows.join(",");
9159            let authored = query.sql.trim_start();
9160            if keyword(authored, "WITH") {
9161                let rest = authored[4..].trim_start();
9162                if keyword(rest, "RECURSIVE") {
9163                    format!("WITH RECURSIVE {shadows}, {}", rest[9..].trim_start())
9164                } else {
9165                    format!("WITH {shadows}, {rest}")
9166                }
9167            } else {
9168                format!("WITH {shadows} {}", query.sql)
9169            }
9170        };
9171        Ok((sql, params, intent))
9172    }
9173
9174    /// Rows, coverage, and local revision from one SQLite read snapshot.
9175    /// §7.5 atomic snapshot read. An `owner` records a failure in
9176    /// `diagnostics_snapshot().query_failures` until its next successful read.
9177    pub fn query_snapshot(
9178        &mut self,
9179        sql: &str,
9180        params: &[QueryValue],
9181        coverage: &[WindowCoverage],
9182        owner: Option<QueryOwner<'_>>,
9183    ) -> Result<QuerySnapshot, String> {
9184        let result = snapshot_connection(&self.conn, Some(&self.schema), sql, params, coverage);
9185        if let Some(owner) = owner {
9186            self.record_query_read(owner, result.as_ref().err());
9187        }
9188        result.map_err(|failure| failure.to_string())
9189    }
9190
9191    /// §7.6: record the outcome of one owned snapshot read, including reads a
9192    /// host ran on a separate connection. A success removes the owner's entry;
9193    /// an identical failure leaves it unchanged; a changed failure moves last.
9194    pub fn record_query_read(&mut self, owner: QueryOwner<'_>, failure: Option<&QueryReadFailure>) {
9195        let position = self
9196            .query_failures
9197            .iter()
9198            .position(|entry| entry.id == owner.id);
9199        let Some(failure) = failure else {
9200            if let Some(index) = position {
9201                self.query_failures.remove(index);
9202            }
9203            return;
9204        };
9205        let tables: Vec<String> = BTreeSet::from_iter(owner.tables.iter().copied())
9206            .into_iter()
9207            .map(str::to_owned)
9208            .collect();
9209        let code = failure.code.unwrap_or("client.query_failed").to_owned();
9210        if position.is_some_and(|index| {
9211            let entry = &self.query_failures[index];
9212            entry.tables == tables && entry.code == code && entry.sqlite_code == failure.sqlite_code
9213        }) {
9214            return;
9215        }
9216        if let Some(index) = position {
9217            self.query_failures.remove(index);
9218        }
9219        self.query_failures.push(DiagnosticQueryFailure {
9220            id: owner.id.to_owned(),
9221            tables,
9222            code,
9223            sqlite_code: failure.sqlite_code,
9224            at_ms: self.clock_now_ms(),
9225        });
9226        if self.query_failures.len() > MAX_DIAGNOSTIC_QUERY_FAILURES {
9227            self.query_failures.remove(0);
9228        }
9229    }
9230
9231    // -- request building ---------------------------------------------------------
9232
9233    fn build_request(&self, url_capable: bool) -> Result<(Message, RequestMeta), Box<SyncOutcome>> {
9234        #[cfg(feature = "bench-internals")]
9235        let _phase = self.benchmark_phases.start(Phase::RequestPrepare);
9236        let log_epoch = self.get_meta(LOG_EPOCH_KEY).map_err(|message| {
9237            Box::new(SyncOutcome::Failed {
9238                error_code: "storage.failed".into(),
9239                message,
9240                details: None,
9241                recommended_action: None,
9242            })
9243        })?;
9244        let max_commits = self.limits.max_push_commits_per_request;
9245        let max_ops = self
9246            .limits
9247            .max_push_operations_per_request
9248            .unwrap_or(PUSH_OPS_PER_REQUEST);
9249        let byte_cap = self.limits.max_push_request_bytes;
9250        // §4.2/§5.4: bit 3 is advertised iff the transport can fetch a
9251        // bare URL — capability negotiation, decided per transport.
9252        let accept = self.limits.accept.unwrap_or(if url_capable {
9253            DEFAULT_ACCEPT | ACCEPT_SIGNED_URLS
9254        } else {
9255            DEFAULT_ACCEPT
9256        });
9257        let storage_failed = |message: String| {
9258            Box::new(SyncOutcome::Failed {
9259                error_code: "storage.failed".into(),
9260                message,
9261                details: None,
9262                recommended_action: None,
9263            })
9264        };
9265        let header = Frame::ReqHeader {
9266            client_id: self.client_id.clone(),
9267            schema_version: self.schema.version,
9268            log_epoch: log_epoch.clone(),
9269            outbox_id: self.get_meta(OUTBOX_ID_KEY).map_err(storage_failed)?,
9270        };
9271        // §1.5: the lead frames are REQ_HEADER plus the optional ROUND_FAILURE,
9272        // which stays ahead of every push, pull, unit and progress frame; the
9273        // byte-capacity probes below measure this exact sequence.
9274        let mut lead = vec![header];
9275        lead.extend(
9276            self.round_failure
9277                .iter()
9278                .map(|code| Frame::RoundFailure { code: code.clone() }),
9279        );
9280        // §2.1: a replica without an epoch holds nothing bound to one.
9281        if log_epoch.is_none() {
9282            lead.push(Frame::AdoptEpoch);
9283        }
9284        let registered: Vec<UnitRecord> = self
9285            .stored(load_units(&self.conn))
9286            .map_err(storage_failed)?
9287            .into_iter()
9288            .filter(|unit| unit.status == UnitStatus::Active)
9289            .collect();
9290        let registration_digest = ssp2::registration::registration_digest(
9291            registered
9292                .iter()
9293                .map(|unit| scope_pairs(&unit.scopes))
9294                .collect::<Vec<_>>()
9295                .iter()
9296                .map(Vec::as_slice),
9297        );
9298        let echo_digest = self
9299            .get_meta(ECHO_DIGEST_KEY)
9300            .map_err(storage_failed)?
9301            .filter(|hex| !hex.is_empty())
9302            .map(|hex| {
9303                crate::values::hex_to_bytes(&hex)
9304                    .ok()
9305                    .and_then(|bytes| <[u8; 32]>::try_from(bytes).ok())
9306                    .ok_or_else(|| {
9307                        "sync.local_corrupt: persisted echo digest is invalid".to_owned()
9308                    })
9309            })
9310            .transpose()
9311            .map_err(storage_failed)?;
9312        let pull = Frame::PullHeader {
9313            limit_commits: self.limits.limit_commits.unwrap_or(0),
9314            limit_snapshot_rows: self.limits.limit_snapshot_rows.unwrap_or(0),
9315            max_snapshot_pages: self.limits.max_snapshot_pages.unwrap_or(0),
9316            accept,
9317            cursor: self
9318                .stored(replica_cursor(&self.conn))
9319                .map_err(storage_failed)?,
9320            registration_digest,
9321            echo_digest,
9322        };
9323        let registration_digest = bytes_to_hex(&registration_digest);
9324        // §4.1: the list travels when it changed since the server stored it,
9325        // after `unregistered` and after a reset (both clear the stored digest).
9326        let travels = self
9327            .get_meta(REGISTERED_DIGEST_KEY)
9328            .map_err(storage_failed)?
9329            .as_deref()
9330            != Some(registration_digest.as_str());
9331        let mut sub_frames: Vec<Frame> = Vec::new();
9332        if travels {
9333            sub_frames.extend(registered.iter().map(|unit| Frame::Unit {
9334                scopes: scope_pairs(&unit.scopes),
9335            }));
9336        }
9337        // §4.3: one PROGRESS per catching-up unit, in registration order, each
9338        // followed by its RESTRICT while the unit holds a restriction.
9339        for unit in &registered {
9340            let Some(cursor) = unit.cursor else {
9341                continue;
9342            };
9343            sub_frames.push(Frame::Progress {
9344                id: unit.id.clone(),
9345                cursor,
9346                bootstrap_state: unit.bootstrap_state.clone().map(RawJson),
9347            });
9348            sub_frames.extend(
9349                unit.restriction
9350                    .as_ref()
9351                    .map(|restriction| Frame::Restrict {
9352                        cursor: restriction.cursor,
9353                        tables: restriction.tables.clone(),
9354                    }),
9355            );
9356        }
9357        // The fixed frames (order-independent size) and the header+pull probe
9358        // both encode canonically, so the byte budget is the exact wire size.
9359        let fixed_bytes = match byte_cap {
9360            Some(_) => {
9361                let mut frames = lead.clone();
9362                frames.push(pull.clone());
9363                frames.extend(sub_frames.iter().cloned());
9364                encode_message(&Message {
9365                    wire_version: WIRE_VERSION,
9366                    msg_kind: MsgKind::Request,
9367                    frames,
9368                })
9369                .len()
9370            }
9371            None => 0,
9372        };
9373        if let Some(cap) = byte_cap {
9374            if fixed_bytes > cap {
9375                return Err(Self::push_capacity_outcome("bytes", cap, fixed_bytes, None));
9376            }
9377        }
9378        let base_bytes = match byte_cap {
9379            Some(_) => {
9380                let mut frames = lead.clone();
9381                frames.push(pull.clone());
9382                encode_message(&Message {
9383                    wire_version: WIRE_VERSION,
9384                    msg_kind: MsgKind::Request,
9385                    frames,
9386                })
9387                .len()
9388            }
9389            None => 0,
9390        };
9391        // §8.8: a `pull` round carries no commit and defers none; a `through`
9392        // round pushes and defers only its prefix.
9393        let pushable = self.pushable_commits();
9394        let total_outbox = if log_epoch.is_some() { pushable } else { 0 };
9395        let mut push_frames: Vec<Frame> = Vec::new();
9396        let mut pushed_ids = Vec::new();
9397        let mut ops_in_request = 0usize;
9398        let mut bytes_in_request = 0usize;
9399        // §2.1: an epoch-less request withholds the whole outbox until the
9400        // next, epoch-bound request.
9401        let mut deferred_commits = pushable - total_outbox;
9402        // §7.2.2: a pending replacement is held; the push stops before it
9403        // without deferring work.
9404        let held: HashSet<String> = self
9405            .prepare_replacements()
9406            .map_err(storage_failed)?
9407            .into_iter()
9408            .filter_map(|decision| decision.replacement)
9409            .collect();
9410        #[cfg(feature = "bench-internals")]
9411        let outbox_phase = self.benchmark_phases.start(Phase::OutboxEncode);
9412        for (index, commit) in self.outbox.iter().take(total_outbox).enumerate() {
9413            if held.contains(&commit.client_commit_id) {
9414                break;
9415            }
9416            // §6.1/§7.1: the commit-count and operation caps are hard. A
9417            // first commit over the operation cap is a typed capacity error
9418            // and stays queued; a later one defers with the complete suffix.
9419            if max_commits.is_some_and(|cap| push_frames.len() >= cap) {
9420                deferred_commits = total_outbox - index;
9421                break;
9422            }
9423            if ops_in_request + commit.ops.len() > max_ops {
9424                if push_frames.is_empty() {
9425                    return Err(Self::push_capacity_outcome(
9426                        "operations",
9427                        max_ops,
9428                        commit.ops.len(),
9429                        Some(commit.client_commit_id.as_str()),
9430                    ));
9431                }
9432                deferred_commits = total_outbox - index;
9433                break;
9434            }
9435            // §7.1 chained base: the commit waits for the change of the commit
9436            // it chains on, which supplies its rebased version.
9437            if self.outbox[..index]
9438                .iter()
9439                .flat_map(|earlier| &earlier.ops)
9440                .any(|earlier| commit.ops.iter().any(|op| chains_on(earlier, op)))
9441            {
9442                deferred_commits = total_outbox - index;
9443                break;
9444            }
9445            let operations = commit
9446                .ops
9447                .iter()
9448                .map(|op| {
9449                    let payload = match self
9450                        .schema
9451                        .table(&op.table)
9452                        .and_then(|table| Some((table, op.presented_values(table)?)))
9453                    {
9454                        Some((table, values)) => {
9455                            // §0: outbox entries encode at send time with the
9456                            // current codec (validated at mutate()). §6.1: the
9457                            // values map's keys are the sparse presence set; an
9458                            // insert-intent operation presents every column (§7.1).
9459                            // §5.11: encrypted columns are encrypted here, with
9460                            // an absent key-id selector read from the stored row.
9461                            // `sync_inner` runs `drop_unencodable_outbox` first,
9462                            // so an encrypt failure cannot reach this encode; the
9463                            // author seam validated every other failure.
9464                            let fallback =
9465                                self.stored_key_fallback(table, &op.row_id)
9466                                    .map_err(|message| {
9467                                        Box::new(SyncOutcome::Failed {
9468                                            error_code: "storage.failed".into(),
9469                                            message,
9470                                            details: None,
9471                                            recommended_action: None,
9472                                        })
9473                                    })?;
9474                            encode_sparse_row_json(
9475                                table,
9476                                &op.row_id,
9477                                &values,
9478                                &self.encryption,
9479                                fallback.as_ref(),
9480                            )
9481                            .ok()
9482                        }
9483                        None => None,
9484                    };
9485                    Ok(ssp2::model::Operation {
9486                        table: op.table.clone(),
9487                        row_id: op.row_id.clone(),
9488                        op: if op.upsert { Op::Upsert } else { Op::Delete },
9489                        base_version: op.base_version,
9490                        payload,
9491                    })
9492                })
9493                .collect::<Result<Vec<_>, Box<SyncOutcome>>>()?;
9494            // §6.3.2, §7.1: the commit's outbox sequence.
9495            let client_seq = self
9496                .conn
9497                .prepare_cached("SELECT seq FROM _syncular_outbox WHERE commit_id = ?1")
9498                .and_then(|mut statement| {
9499                    statement.query_row([&commit.client_commit_id], |row| row.get(0))
9500                })
9501                .map_err(|error| {
9502                    storage_failed(Self::sqlite_failure(&self.storage_failure, error))
9503                })?;
9504            let frame = Frame::PushCommit {
9505                client_commit_id: commit.client_commit_id.clone(),
9506                client_seq,
9507                operations,
9508            };
9509            let frame_bytes = match byte_cap {
9510                Some(_) => {
9511                    let mut frames = lead.clone();
9512                    frames.push(frame.clone());
9513                    frames.push(pull.clone());
9514                    encode_message(&Message {
9515                        wire_version: WIRE_VERSION,
9516                        msg_kind: MsgKind::Request,
9517                        frames,
9518                    })
9519                    .len()
9520                        - base_bytes
9521                }
9522                None => 0,
9523            };
9524            // The head is always encoded so the caller can report the full
9525            // projected request size; a later commit defers once it no longer
9526            // fits.
9527            if let Some(cap) = byte_cap {
9528                if !push_frames.is_empty() && fixed_bytes + bytes_in_request + frame_bytes > cap {
9529                    deferred_commits = total_outbox - index;
9530                    break;
9531                }
9532            }
9533            push_frames.push(frame);
9534            pushed_ids.push(commit.client_commit_id.clone());
9535            ops_in_request += commit.ops.len();
9536            bytes_in_request += frame_bytes;
9537        }
9538        #[cfg(feature = "bench-internals")]
9539        drop(outbox_phase);
9540        if let Some(cap) = byte_cap {
9541            if fixed_bytes + bytes_in_request > cap {
9542                // The head alone does not fit this budget; the commit stays
9543                // queued and no transport round is attempted.
9544                let blocked = if push_frames.is_empty() {
9545                    None
9546                } else {
9547                    self.outbox.first().map(|c| c.client_commit_id.as_str())
9548                };
9549                return Err(Self::push_capacity_outcome(
9550                    "bytes",
9551                    cap,
9552                    fixed_bytes + bytes_in_request,
9553                    blocked,
9554                ));
9555            }
9556        }
9557        let mut frames = lead;
9558        frames.extend(push_frames);
9559        frames.push(pull);
9560        frames.extend(sub_frames);
9561        let message = Message {
9562            wire_version: WIRE_VERSION,
9563            msg_kind: MsgKind::Request,
9564            frames,
9565        };
9566        Ok((
9567            message,
9568            RequestMeta {
9569                pushed_ids,
9570                registration_digest,
9571                accept,
9572                deferred_commits,
9573                applied: BTreeMap::new(),
9574                deferred: BTreeSet::new(),
9575            },
9576        ))
9577    }
9578
9579    /// §7.1: a configured push capacity limit cannot carry this request.
9580    fn push_capacity_outcome(
9581        kind: &str,
9582        limit: usize,
9583        size: usize,
9584        client_commit_id: Option<&str>,
9585    ) -> Box<SyncOutcome> {
9586        let mut details = Map::new();
9587        details.insert("kind".to_owned(), Value::from(kind));
9588        details.insert("limit".to_owned(), Value::from(limit as u64));
9589        details.insert("size".to_owned(), Value::from(size as u64));
9590        if let Some(id) = client_commit_id {
9591            details.insert("clientCommitId".to_owned(), Value::from(id));
9592        }
9593        Box::new(SyncOutcome::Failed {
9594            error_code: "client.push_request_too_large".into(),
9595            message: "the push request exceeds a configured capacity limit".into(),
9596            details: Some(Value::Object(details)),
9597            recommended_action: None,
9598        })
9599    }
9600
9601    // -- sync -------------------------------------------------------------------
9602
9603    /// Cloneable observation handle; no client lock is needed to read it.
9604    pub fn progress(&self) -> ProgressObserver {
9605        self.progress.clone()
9606    }
9607
9608    pub fn sync(&mut self, transport: &mut dyn Transport) -> SyncOutcome {
9609        self.sync_bounded(transport, None)
9610    }
9611
9612    /// One round; `idle_bound` is the idle drive's round bound (§7.8).
9613    fn sync_bounded(
9614        &mut self,
9615        transport: &mut dyn Transport,
9616        idle_bound: Option<(u64, u32)>,
9617    ) -> SyncOutcome {
9618        let mut prepared = match self.prepare_sync_round(transport.supports_url_fetch()) {
9619            Ok(prepared) => prepared,
9620            Err(outcome) => return *outcome,
9621        };
9622        prepared.idle_bound = idle_bound;
9623        // The round's network deadline rides `PreparedSyncRound` and is scoped
9624        // to each exchange, so uploads, continuations, the main request, and
9625        // every segment fetch share one monotonic anchor without leaving
9626        // deadline state on a reused transport.
9627        let mut next = prepared;
9628        loop {
9629            match self.apply_sync_round(next.exchange(transport)) {
9630                crate::AppliedSyncRound::Continue(prepared) => next = prepared,
9631                crate::AppliedSyncRound::Complete {
9632                    outcome, controls, ..
9633                } => {
9634                    if !self.transport_closed() {
9635                        for text in controls {
9636                            let _ = transport.realtime_send(&text);
9637                        }
9638                    } else {
9639                        self.disconnect_realtime(transport);
9640                    }
9641                    return outcome;
9642                }
9643            }
9644        }
9645    }
9646
9647    fn finish_sync_round(
9648        &mut self,
9649        started_at_ms: i64,
9650        attempt: u64,
9651        mut outcome: SyncOutcome,
9652    ) -> SyncOutcome {
9653        if let SyncOutcome::Failed {
9654            error_code,
9655            message,
9656            details,
9657            ..
9658        } = &mut outcome
9659        {
9660            if let Some((failure, code)) = self
9661                .storage_failure
9662                .borrow()
9663                .as_ref()
9664                .and_then(|failure| failure.code.map(|code| (failure, code)))
9665            {
9666                *error_code = code.to_owned();
9667                *message = match code {
9668                    "client.storage_busy" => "local SQLite storage is busy",
9669                    "client.storage_full" => "local SQLite storage is full",
9670                    "client.storage_io" => "local SQLite storage I/O failed",
9671                    "client.storage_corrupt" => "local SQLite storage is corrupt",
9672                    _ => unreachable!("unrecognized classified storage failure"),
9673                }
9674                .to_owned();
9675                *details = failure.details();
9676            }
9677        }
9678        let details = match &outcome {
9679            SyncOutcome::Failed { details, .. } => details.as_ref(),
9680            _ => None,
9681        };
9682        let cause_kind = details
9683            .and_then(|details| details.get("causeKind"))
9684            .and_then(Value::as_str)
9685            .and_then(|cause| match cause {
9686                "network" => Some(crate::TransportCauseKind::Network),
9687                "connect" => Some(crate::TransportCauseKind::Connect),
9688                "tls" => Some(crate::TransportCauseKind::Tls),
9689                "io" => Some(crate::TransportCauseKind::Io),
9690                "request" => Some(crate::TransportCauseKind::Request),
9691                "protocol" => Some(crate::TransportCauseKind::Protocol),
9692                "timeout" => Some(crate::TransportCauseKind::Timeout),
9693                "round_deadline" => Some(crate::TransportCauseKind::RoundDeadline),
9694                "aborted" => Some(crate::TransportCauseKind::Aborted),
9695                "body" => Some(crate::TransportCauseKind::Body),
9696                "status" => Some(crate::TransportCauseKind::Status),
9697                "redirect" => Some(crate::TransportCauseKind::Redirect),
9698                "unknown" => Some(crate::TransportCauseKind::Unknown),
9699                _ => None,
9700            });
9701        let http_status = if matches!(
9702            cause_kind,
9703            Some(
9704                crate::TransportCauseKind::Status
9705                    | crate::TransportCauseKind::Body
9706                    | crate::TransportCauseKind::Redirect
9707            )
9708        ) {
9709            details
9710                .and_then(|details| details.get("httpStatus"))
9711                .and_then(Value::as_f64)
9712                .filter(|status| status.fract() == 0.0 && (100.0..=599.0).contains(status))
9713                .map(|status| status as u16)
9714        } else {
9715            None
9716        };
9717        let retry_delay_ms = self.round_retry_delay_ms;
9718        self.progress.update(|p| match &outcome {
9719            SyncOutcome::Ok(report) | SyncOutcome::BudgetExhausted(report)
9720                if report.failed.is_empty() =>
9721            {
9722                p.state = ProgressState::Complete
9723            }
9724            SyncOutcome::Ok(_) | SyncOutcome::BudgetExhausted(_) => {
9725                p.state = ProgressState::Failed;
9726                p.error_code = Some("sync.scope_revoked".into());
9727            }
9728            SyncOutcome::Failed { error_code, .. } => {
9729                p.state = ProgressState::Failed;
9730                p.error_code = Some(Self::diagnostic_code(error_code));
9731                p.cause_kind = cause_kind;
9732                p.http_status = http_status;
9733                p.retry_delay_ms = retry_delay_ms;
9734            }
9735            SyncOutcome::RealtimeUnavailable { .. } => {
9736                p.state = ProgressState::Failed;
9737                p.error_code = Some(REALTIME_UNAVAILABLE_CODE.to_owned());
9738                p.retry_delay_ms = retry_delay_ms;
9739            }
9740        });
9741        let completed_at_ms = self.clock_now_ms();
9742        self.last_round = Some(match &outcome {
9743            SyncOutcome::Ok(report) | SyncOutcome::BudgetExhausted(report) => DiagnosticLastRound {
9744                epoch: self.epoch.clone(),
9745                attempt,
9746                status: "succeeded".to_owned(),
9747                started_at_ms,
9748                completed_at_ms,
9749                duration_ms: completed_at_ms.saturating_sub(started_at_ms).max(0),
9750                counters: Some(DiagnosticRoundCounters {
9751                    pushed: report.pushed,
9752                    applied: report.applied.len(),
9753                    rejected: report.rejected.len(),
9754                    retryable: report.retryable.len(),
9755                    conflicts: report.conflicts,
9756                    commits_applied: report.commits_applied,
9757                    segment_rows_applied: report.segment_rows_applied,
9758                    bootstrapping: report.bootstrapping.len(),
9759                    resets: report.resets.len(),
9760                    revoked: report.revoked.len(),
9761                    failed: report.failed.len(),
9762                    deferred_commits: report.deferred_commits,
9763                }),
9764                error_code: None,
9765                cause_kind: None,
9766                http_status: None,
9767            },
9768            SyncOutcome::Failed { error_code, .. } => DiagnosticLastRound {
9769                epoch: self.epoch.clone(),
9770                attempt,
9771                status: "failed".to_owned(),
9772                started_at_ms,
9773                completed_at_ms,
9774                duration_ms: completed_at_ms.saturating_sub(started_at_ms).max(0),
9775                counters: None,
9776                error_code: Some(Self::diagnostic_code(error_code)),
9777                cause_kind,
9778                http_status,
9779            },
9780            SyncOutcome::RealtimeUnavailable { .. } => DiagnosticLastRound {
9781                epoch: self.epoch.clone(),
9782                attempt,
9783                status: "failed".to_owned(),
9784                started_at_ms,
9785                completed_at_ms,
9786                duration_ms: completed_at_ms.saturating_sub(started_at_ms).max(0),
9787                counters: None,
9788                error_code: Some(REALTIME_UNAVAILABLE_CODE.to_owned()),
9789                cause_kind: None,
9790                http_status: None,
9791            },
9792        });
9793        outcome
9794    }
9795
9796    /// Capture one request on the client owner. Mutations made after this
9797    /// call remain in the outbox for a later round; no network I/O occurs here.
9798    pub fn prepare_sync_round(
9799        &mut self,
9800        url_capable: bool,
9801    ) -> Result<crate::PreparedSyncRound, Box<SyncOutcome>> {
9802        if self.transport_closed() {
9803            return Err(Box::new(SyncOutcome::Failed {
9804                error_code: "sync.offline".into(),
9805                message: "transport gate is closed".into(),
9806                details: None,
9807                recommended_action: None,
9808            }));
9809        }
9810        if self.active_round.is_some() || self.fence_round.is_some() {
9811            return Err(Box::new(SyncOutcome::Failed {
9812                error_code: "client.round_in_progress".into(),
9813                message: "a sync round is already in flight".into(),
9814                details: None,
9815                recommended_action: None,
9816            }));
9817        }
9818        self.storage_failure.borrow_mut().take();
9819        let attempt = self.progress.start(&self.epoch);
9820        self.round_retry_delay_ms = None;
9821        let started_at_ms = self.clock_now_ms();
9822        let prepared = (|| {
9823            if self.stopped {
9824                return Err(Box::new(SyncOutcome::Ok(SyncReport {
9825                    schema_floor: self.schema_floor.clone(),
9826                    ..SyncReport::default()
9827                })));
9828            }
9829            if self.security_preflight {
9830                return Err(Box::new(SyncOutcome::Failed {
9831                    error_code: SECURITY_PREFLIGHT_REQUIRED_CODE.into(),
9832                    message: "security preflight must complete before syncing".into(),
9833                    details: None,
9834                    recommended_action: None,
9835                }));
9836            }
9837            self.set_sync_needed(false, false);
9838            self.drain_pending_evictions()
9839                .and_then(|_| self.drop_incompatible_outbox())
9840                .and_then(|_| self.drop_unencodable_outbox(true, None))
9841                .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            // §5.11: reveal rows sealed under a key the keyring gained since.
9850            self.reveal_sealed_rows().map_err(|error| {
9851                Box::new(SyncOutcome::Failed {
9852                    error_code: error.code,
9853                    message: error.message,
9854                    details: error.details,
9855                    recommended_action: None,
9856                })
9857            })?;
9858            let has_log_epoch = self.get_meta(LOG_EPOCH_KEY).map_err(|message| {
9859                Box::new(SyncOutcome::Failed {
9860                    error_code: "storage.failed".into(),
9861                    message,
9862                    details: None,
9863                    recommended_action: None,
9864                })
9865            })?;
9866            let mut uploads = if has_log_epoch.is_some()
9867                && matches!(
9868                    self.transport_gate,
9869                    crate::TransportGate::Open | crate::TransportGate::Through(_)
9870                )
9871                && self.schema_has_blobs()
9872            {
9873                self.pending_blob_uploads().map_err(|e| {
9874                    Box::new(SyncOutcome::Failed {
9875                        error_code: e.code,
9876                        message: e.message,
9877                        details: e.details,
9878                        recommended_action: None,
9879                    })
9880                })?
9881            } else {
9882                Vec::new()
9883            };
9884            // §8.8: a `through` round uploads only the blobs its prefix references.
9885            if matches!(self.transport_gate, crate::TransportGate::Through(_)) {
9886                let prefix = Value::Array(
9887                    self.outbox
9888                        .iter()
9889                        .take(self.pushable_commits())
9890                        .map(|commit| Value::String(commit.client_commit_id.clone()))
9891                        .collect(),
9892                );
9893                let referenced = self
9894                    .conn
9895                    .prepare(
9896                        "SELECT blob_id FROM _syncular_blob_commit_refs
9897                          WHERE commit_id IN (SELECT value FROM json_each(?1))",
9898                    )
9899                    .and_then(|mut statement| {
9900                        statement
9901                            .query_map([prefix.to_string()], |row| row.get::<_, String>(0))?
9902                            .collect::<Result<HashSet<_>, _>>()
9903                    })
9904                    .map_err(|error| {
9905                        Box::new(SyncOutcome::Failed {
9906                            error_code: "storage.failed".into(),
9907                            message: Self::sqlite_failure(&self.storage_failure, error),
9908                            details: None,
9909                            recommended_action: None,
9910                        })
9911                    })?;
9912                uploads.retain(|upload| referenced.contains(&upload.id));
9913            }
9914            if self.realtime_state != RealtimeState::Connected
9915                && self.realtime_policy == RealtimePolicy::Required
9916            {
9917                let retry_delay_ms = self.schedule_background_retry();
9918                self.realtime_retry_delay_ms = Some(retry_delay_ms);
9919                return Err(Box::new(SyncOutcome::RealtimeUnavailable {
9920                    state: self.realtime_state,
9921                    reason_code: self.realtime_reason_code.clone(),
9922                    retry_delay_ms,
9923                }));
9924            }
9925            let (message, mut meta) = self.build_request(url_capable)?;
9926            let units = self.stored(load_units(&self.conn)).map_err(|message| {
9927                Box::new(SyncOutcome::Failed {
9928                    error_code: "storage.failed".into(),
9929                    message,
9930                    details: None,
9931                    recommended_action: None,
9932                })
9933            })?;
9934            for unit in &units {
9935                let applied =
9936                    self.stored(applied_rows(&self.conn, &unit.id))
9937                        .map_err(|message| {
9938                            Box::new(SyncOutcome::Failed {
9939                                error_code: "storage.failed".into(),
9940                                message,
9941                                details: None,
9942                                recommended_action: None,
9943                            })
9944                        })?;
9945                if !applied.is_empty() {
9946                    meta.applied.insert(unit.id.clone(), applied);
9947                }
9948            }
9949            // §7.1: the send-attempt marker of every commit the request
9950            // carries commits before the round leaves the owner.
9951            let pushed: Vec<String> = message
9952                .frames
9953                .iter()
9954                .filter_map(|frame| match frame {
9955                    Frame::PushCommit { client_seq, .. } => Some(client_seq.to_string()),
9956                    _ => None,
9957                })
9958                .collect();
9959            if !pushed.is_empty() {
9960                self.conn
9961                    .execute(
9962                        &format!(
9963                            "UPDATE _syncular_outbox SET attempted = 1 WHERE seq IN ({})",
9964                            pushed.join(",")
9965                        ),
9966                        [],
9967                    )
9968                    .map_err(|error| {
9969                        Box::new(SyncOutcome::Failed {
9970                            error_code: "storage.failed".into(),
9971                            message: Self::sqlite_failure(&self.storage_failure, error),
9972                            details: None,
9973                            recommended_action: None,
9974                        })
9975                    })?;
9976            }
9977            let id = uuid::Uuid::new_v4();
9978            self.active_round = Some((id, started_at_ms, attempt));
9979            let phase = if uploads.is_empty() {
9980                crate::round::RoundPhase::Sync
9981            } else {
9982                crate::round::RoundPhase::UploadGrant
9983            };
9984            Ok(crate::PreparedSyncRound {
9985                id,
9986                started_at_ms,
9987                attempt,
9988                message,
9989                meta,
9990                uploads: uploads.into(),
9991                phase,
9992                encoded: None,
9993                continuation: None,
9994                completed: None,
9995                realtime: self.realtime_state == RealtimeState::Connected,
9996                // §5.5: the owning unit's scope map, each value a one-element list.
9997                scopes: units
9998                    .into_iter()
9999                    .map(|unit| {
10000                        (
10001                            unit.id,
10002                            canonical_scope_json(&unit_scope_lists(&unit.scopes)),
10003                        )
10004                    })
10005                    .collect(),
10006                #[cfg(feature = "bench-internals")]
10007                benchmark_phases: self.benchmark_phases.clone(),
10008                progress: self.progress.clone(),
10009                fixed_now: self
10010                    .now_ms
10011                    .as_ref()
10012                    .map(|clock| clock.load(std::sync::atomic::Ordering::Relaxed)),
10013                round_deadline_at: None,
10014                idle_bound: None,
10015                network_started_at: None,
10016            })
10017        })();
10018        prepared
10019            .map_err(|outcome| Box::new(self.finish_sync_round(started_at_ms, attempt, *outcome)))
10020    }
10021
10022    /// Discard the reply of an old authorization or registration context. Its
10023    /// submitted commits stay durable and can be retried with the same ids.
10024    /// §7.6: an abandoned in-flight round ends its attempt as failed.
10025    pub fn cancel_sync_round(&mut self) {
10026        self.fence_round = None;
10027        if let Some((_, started_at_ms, attempt)) = self.active_round.take() {
10028            // A storage failure recorded since the round started is not its cause.
10029            self.storage_failure.borrow_mut().take();
10030            self.finish_sync_round(
10031                started_at_ms,
10032                attempt,
10033                SyncOutcome::Failed {
10034                    error_code: "client.round_cancelled".into(),
10035                    message: "sync round belongs to a released client context".into(),
10036                    details: None,
10037                    recommended_action: None,
10038                },
10039            );
10040        }
10041    }
10042
10043    /// Apply captured network results on the owner, preserving all normal
10044    /// version, schema, content-address and cursor checks. No network I/O.
10045    pub fn apply_sync_round(
10046        &mut self,
10047        completed: crate::CompletedSyncRound,
10048    ) -> crate::AppliedSyncRound {
10049        let mut prepared = completed.prepared;
10050        if self.active_round.map(|(id, ..)| id) != Some(prepared.id) || self.security_preflight {
10051            return crate::AppliedSyncRound::Complete {
10052                outcome: SyncOutcome::Failed {
10053                    error_code: "client.round_cancelled".into(),
10054                    message: "sync round belongs to a released client context".into(),
10055                    details: None,
10056                    recommended_action: None,
10057                },
10058                controls: Vec::new(),
10059                more: false,
10060                bootstrap_advanced: false,
10061            };
10062        }
10063        self.storage_failure.borrow_mut().take();
10064        let (response, mut downloads, transport_failed) = match completed.exchange {
10065            crate::round::ExchangeResult::Upload { id, result } => {
10066                let result = match result {
10067                    // §5.9.7: a non-retryable server refusal (`blob.too_large`)
10068                    // is the body's final outcome. The commits naming it take
10069                    // the incompatible-commit path with the server's code and
10070                    // leave this round's request; the round continues.
10071                    Err(error)
10072                        if error
10073                            .details
10074                            .as_ref()
10075                            .and_then(|details| details.get("retryable"))
10076                            == Some(&Value::Bool(false)) =>
10077                    {
10078                        self.conn
10079                            .prepare(
10080                                "SELECT commit_id FROM _syncular_blob_commit_refs WHERE blob_id = ?",
10081                            )
10082                            .and_then(|mut statement| {
10083                                statement
10084                                    .query_map(rusqlite::params![id], |row| row.get::<_, String>(0))?
10085                                    .collect::<Result<HashSet<_>, _>>()
10086                            })
10087                            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
10088                            .and_then(|refused| {
10089                                // §8.8: only a commit the gate lets this round
10090                                // push takes the refusal. A held commit keeps
10091                                // the body queued and meets the refusal when a
10092                                // round pushes it.
10093                                let commits = self
10094                                    .outbox
10095                                    .iter()
10096                                    .take(self.pushable_commits())
10097                                    .filter(|commit| refused.contains(&commit.client_commit_id))
10098                                    .cloned()
10099                                    .collect::<Vec<_>>();
10100                                if !commits.is_empty() {
10101                                    self.drop_outbox_commits(&commits, &error.code, &error.message)?;
10102                                }
10103                                prepared.message.frames.retain(|frame| {
10104                                    !matches!(frame, Frame::PushCommit { client_commit_id, .. }
10105                                        if refused.contains(client_commit_id))
10106                                });
10107                                prepared.meta.pushed_ids.retain(|id| !refused.contains(id));
10108                                prepared.continuation = Some(crate::round::RoundPhase::UploadGrant);
10109                                Ok(true)
10110                            })
10111                            .map_err(|message| TransportError::new("client.failed", message))
10112                    }
10113                    result => result.map(|()| false),
10114                };
10115                // A refused body stays queued while a held commit names it.
10116                let result = result.and_then(|refused| {
10117                    self.conn
10118                        .execute(
10119                            if refused {
10120                                "DELETE FROM _syncular_blob_uploads WHERE blob_id = ?1
10121                                   AND NOT EXISTS (SELECT 1 FROM _syncular_blob_commit_refs
10122                                                    WHERE blob_id = ?1)"
10123                            } else {
10124                                "DELETE FROM _syncular_blob_uploads WHERE blob_id = ?1"
10125                            },
10126                            rusqlite::params![id],
10127                        )
10128                        .map(|_| ())
10129                        .map_err(|error| {
10130                            TransportError::new(
10131                                "client.failed",
10132                                Self::sqlite_failure(&self.storage_failure, error),
10133                            )
10134                        })
10135                });
10136                match result {
10137                    Ok(()) => return crate::AppliedSyncRound::Continue(prepared),
10138                    Err(TransportError {
10139                        code,
10140                        message,
10141                        details,
10142                    }) => {
10143                        self.active_round = None;
10144                        if Self::unreachable_transport(&details) {
10145                            // The round's work is still owed; the host's
10146                            // connectivity resume runs it.
10147                            self.set_sync_needed(true, false);
10148                        } else if Self::retryable_failure_code(&code) {
10149                            self.schedule_background_retry();
10150                        }
10151                        let recommended_action = recommended_action_of(&details);
10152                        let outcome = self.finish_sync_round(
10153                            prepared.started_at_ms,
10154                            prepared.attempt,
10155                            SyncOutcome::Failed {
10156                                error_code: code,
10157                                message,
10158                                details,
10159                                recommended_action,
10160                            },
10161                        );
10162                        return crate::AppliedSyncRound::Complete {
10163                            outcome,
10164                            controls: Vec::new(),
10165                            more: false,
10166                            bootstrap_advanced: false,
10167                        };
10168                    }
10169                }
10170            }
10171            crate::round::ExchangeResult::Reply {
10172                response,
10173                downloads,
10174                transport_failed,
10175            } => (response, downloads, transport_failed),
10176        };
10177        self.active_round = None;
10178        let before = self.resume_tokens();
10179        let outcome = (|| {
10180            let response = match response {
10181                Ok(response) => {
10182                    // §1.5: a complete, decodable response ends the report, an
10183                    // in-band ERROR included (the server already recorded it).
10184                    self.round_failure = None;
10185                    response
10186                }
10187                Err(TransportError {
10188                    code,
10189                    message,
10190                    details,
10191                }) => {
10192                    // §1.5: the server cannot see a round whose transport
10193                    // failed or whose response never decoded, so its code rides
10194                    // the following requests. A code the frame grammar rejects
10195                    // is not reportable, and the previous code stays; the
10196                    // client-local drive timeout never goes on the wire (§7.8).
10197                    if code != "sync.idle_timeout" && ssp2::model::valid_round_failure_code(&code) {
10198                        self.round_failure = Some(code.clone());
10199                    }
10200                    // §8.8: a prefix sent without a receipt is an uncertain delivery.
10201                    if !prepared.meta.pushed_ids.is_empty()
10202                        && matches!(self.transport_gate, crate::TransportGate::Through(_))
10203                    {
10204                        self.move_transport_gate(crate::TransportGate::Pull);
10205                    }
10206                    if transport_failed {
10207                        if prepared.realtime {
10208                            self.set_realtime_state(RealtimeState::Lost, Some(&code));
10209                        }
10210                        if let Err(message) = self.record_lease_error(&code) {
10211                            return SyncOutcome::Failed {
10212                                error_code: "storage.failed".to_owned(),
10213                                message,
10214                                details: None,
10215                                recommended_action: None,
10216                            };
10217                        }
10218                    }
10219                    if Self::retryable_failure_code(&code) && !Self::unreachable_transport(&details)
10220                    {
10221                        let delay = self.schedule_background_retry();
10222                        if prepared.realtime && transport_failed {
10223                            self.realtime_retry_delay_ms = Some(delay);
10224                        }
10225                    }
10226                    let recommended_action = recommended_action_of(&details);
10227                    return SyncOutcome::Failed {
10228                        error_code: code,
10229                        message,
10230                        details,
10231                        recommended_action,
10232                    };
10233                }
10234            };
10235            let mut outcome = self.process_response(&mut downloads, response, &prepared.meta);
10236            if let SyncOutcome::Ok(report) = &mut outcome {
10237                report.deferred_commits = prepared.meta.deferred_commits;
10238            }
10239            match &outcome {
10240                SyncOutcome::Ok(_) => self.reset_background_retry(),
10241                SyncOutcome::Failed {
10242                    error_code,
10243                    details,
10244                    ..
10245                } if Self::retryable_failure_code(error_code)
10246                    && !Self::unreachable_transport(details) =>
10247                {
10248                    self.schedule_background_retry();
10249                }
10250                _ => {}
10251            }
10252            if prepared.meta.deferred_commits > 0 {
10253                self.set_sync_needed(true, true);
10254            }
10255            self.previous_version_lifetime_check();
10256            outcome
10257        })();
10258        match &outcome {
10259            // §7.1: a unit still catching up needs another round, also when the
10260            // drive that started it ends early.
10261            SyncOutcome::Ok(report) if !report.bootstrapping.is_empty() => {
10262                self.set_sync_needed(true, false)
10263            }
10264            // The round's work is still owed; the host's connectivity resume
10265            // runs it.
10266            SyncOutcome::Failed { details, .. } if Self::unreachable_transport(details) => {
10267                self.set_sync_needed(true, false)
10268            }
10269            _ => {}
10270        }
10271        let more = !self.transport_closed()
10272            && matches!(&outcome, SyncOutcome::Ok(report)
10273                if report.schema_floor.is_none()
10274                    && (!report.bootstrapping.is_empty()
10275                        || report.commits_applied > 0
10276                        || report.segment_rows_applied > 0
10277                        || !report.resets.is_empty()
10278                        || report.deferred_commits > 0
10279                        || self.sync_needed));
10280        let bootstrap_advanced = matches!(&outcome, SyncOutcome::Ok(report) if report.segment_rows_applied > 0 && !report.bootstrapping.is_empty())
10281            && before != self.resume_tokens();
10282        crate::AppliedSyncRound::Complete {
10283            outcome: self.finish_sync_round(prepared.started_at_ms, prepared.attempt, outcome),
10284            controls: if !self.transport_closed() {
10285                downloads.controls
10286            } else {
10287                Vec::new()
10288            },
10289            more,
10290            bootstrap_advanced,
10291        }
10292    }
10293
10294    /// Every unit's resume token and applied-segment record: a bootstrap
10295    /// that advanced changes one (§4.7), also when it applied images of a
10296    /// section it deferred (§5.3, §5.6).
10297    #[allow(clippy::type_complexity)]
10298    fn resume_tokens(&self) -> Option<Vec<(String, Option<String>, Option<String>)>> {
10299        self.conn
10300            .prepare_cached(
10301                "SELECT id, bootstrap_state, applied FROM _syncular_units ORDER BY rowid",
10302            )
10303            .and_then(|mut stmt| {
10304                stmt.query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))?
10305                    .collect()
10306            })
10307            .ok()
10308    }
10309
10310    /// §7.8: one idle drive's default total deadline, the TS client's value.
10311    pub const SYNC_IDLE_TIMEOUT_MS: u64 = 60_000;
10312
10313    pub fn sync_until_idle(
10314        &mut self,
10315        transport: &mut dyn Transport,
10316        max_rounds: Option<u32>,
10317    ) -> SyncOutcome {
10318        self.sync_until_idle_with_deadline(transport, max_rounds, Some(Self::SYNC_IDLE_TIMEOUT_MS))
10319    }
10320
10321    /// As [`SyncClient::sync_until_idle`], with an explicit total deadline in
10322    /// milliseconds (`None` disables it). The deadline is checked against the
10323    /// client clock between rounds: a drive past it after a completed round
10324    /// ends as `BudgetExhausted`. Each round is bounded by `timeout_ms` on its
10325    /// own, or the transport's tighter whole-round deadline (§1.8); a round
10326    /// that reaches the drive bound fails with `sync.idle_timeout`.
10327    pub fn sync_until_idle_with_deadline(
10328        &mut self,
10329        transport: &mut dyn Transport,
10330        max_rounds: Option<u32>,
10331        timeout_ms: Option<u64>,
10332    ) -> SyncOutcome {
10333        // §7.8: an explicit budget is a strict positive round count. Zero is a
10334        // caller error, not an exhaustion.
10335        if max_rounds == Some(0) {
10336            return SyncOutcome::Failed {
10337                details: None,
10338                error_code: "sync.invalid_request".into(),
10339                message: "maxRounds must be a positive integer".into(),
10340                recommended_action: None,
10341            };
10342        }
10343        if timeout_ms.is_some_and(|ms| ms == 0 || i64::try_from(ms).is_err()) {
10344            return SyncOutcome::Failed {
10345                details: None,
10346                error_code: "sync.invalid_request".into(),
10347                message: "timeoutMs must be a positive integer".into(),
10348                recommended_action: None,
10349            };
10350        }
10351        let started_at_ms = self.clock_now_ms();
10352        let rounds = max_rounds.unwrap_or(20);
10353        let mut aggregate = SyncReport::default();
10354        // §7.2.2: decisions pending at the drive's start are evaluated when it
10355        // reaches idle.
10356        let decisions = match self.prepare_replacements() {
10357            Ok(decisions) => decisions,
10358            Err(message) => {
10359                return SyncOutcome::Failed {
10360                    details: None,
10361                    error_code: "storage.failed".into(),
10362                    message,
10363                    recommended_action: None,
10364                }
10365            }
10366        };
10367        let mut spent = 0;
10368        let mut completed = false;
10369        while spent < rounds {
10370            // §7.8: a deadline that elapsed across completed rounds ends the
10371            // drive like an exhausted round budget; the next drive resumes.
10372            if completed
10373                && timeout_ms.is_some_and(|ms| {
10374                    self.clock_now_ms() >= started_at_ms.saturating_add(ms as i64)
10375                })
10376            {
10377                return SyncOutcome::BudgetExhausted(aggregate);
10378            }
10379            let idle_bound = timeout_ms.map(|ms| (ms, spent));
10380            spent += 1;
10381            let before = self.resume_tokens();
10382            match self.sync_bounded(transport, idle_bound) {
10383                SyncOutcome::Failed {
10384                    error_code,
10385                    message,
10386                    details,
10387                    recommended_action,
10388                } => {
10389                    return SyncOutcome::Failed {
10390                        details,
10391                        error_code,
10392                        message,
10393                        recommended_action,
10394                    };
10395                }
10396                outcome @ SyncOutcome::RealtimeUnavailable { .. } => return outcome,
10397                SyncOutcome::BudgetExhausted(_) => {
10398                    unreachable!("sync() never exhausts a round budget")
10399                }
10400                SyncOutcome::Ok(report) => {
10401                    completed = true;
10402                    if max_rounds.is_none()
10403                        && report.segment_rows_applied > 0
10404                        && !report.bootstrapping.is_empty()
10405                        && before != self.resume_tokens()
10406                    {
10407                        spent = 0;
10408                    }
10409                    // TS parity: a closed transport or a schema floor ends
10410                    // the loop. The latest round still merges first.
10411                    let stop = self.transport_closed() || report.schema_floor.is_some();
10412                    aggregate.merge(&report);
10413                    // §4.5: pull again whenever the response contained
10414                    // commits or segments; resets re-bootstrap; a pending
10415                    // resume token continues paging (§4.7); deferred outbox
10416                    // commits and a raised sync-needed signal push on the next
10417                    // round.
10418                    let more = !stop
10419                        && (!report.bootstrapping.is_empty()
10420                            || report.commits_applied > 0
10421                            || report.segment_rows_applied > 0
10422                            || !report.resets.is_empty()
10423                            || report.deferred_commits > 0
10424                            || self.sync_needed);
10425                    if more {
10426                        continue;
10427                    }
10428                    // §7.2.2: a written decision runs another round, which
10429                    // pushes it.
10430                    match self.settle_replacements(&decisions, &SyncOutcome::Ok(aggregate.clone()))
10431                    {
10432                        Ok(true) if !stop => {}
10433                        Ok(_) => return SyncOutcome::Ok(aggregate),
10434                        Err(message) => {
10435                            return SyncOutcome::Failed {
10436                                details: None,
10437                                error_code: "storage.failed".into(),
10438                                message,
10439                                recommended_action: None,
10440                            }
10441                        }
10442                    }
10443                }
10444            }
10445        }
10446        // §7.8: partial success. The aggregate report is retained and the run
10447        // is explicitly not idle.
10448        SyncOutcome::BudgetExhausted(aggregate)
10449    }
10450
10451    fn process_response(
10452        &mut self,
10453        transport: &mut dyn Transport,
10454        response: Message,
10455        meta: &RequestMeta,
10456    ) -> SyncOutcome {
10457        #[cfg(feature = "bench-internals")]
10458        let _phase = self.benchmark_phases.start(Phase::ResponseApply);
10459        let mut report = SyncReport {
10460            pushed: meta.pushed_ids.len() as u32,
10461            ..SyncReport::default()
10462        };
10463        let mut rejection_details_by_commit: HashMap<String, BTreeMap<i32, RejectionDetails>> =
10464            HashMap::new();
10465        let pushed_ids = meta
10466            .pushed_ids
10467            .iter()
10468            .map(String::as_str)
10469            .collect::<HashSet<_>>();
10470        let mut last_final_push_result_id: Option<String> = None;
10471        for frame in &response.frames {
10472            match frame {
10473                Frame::PushResultDetails {
10474                    client_commit_id,
10475                    entries,
10476                } => {
10477                    let details = rejection_details_by_commit
10478                        .entry(client_commit_id.clone())
10479                        .or_default();
10480                    for entry in entries {
10481                        let parsed = match RejectionDetails::parse(&entry.details.0) {
10482                            Ok(value) => value,
10483                            Err(message) => {
10484                                return SyncOutcome::Failed {
10485                                    details: None,
10486                                    error_code: "sync.invalid_request".to_owned(),
10487                                    message,
10488                                    recommended_action: None,
10489                                };
10490                            }
10491                        };
10492                        details.insert(entry.op_index, parsed);
10493                    }
10494                }
10495                Frame::PushResult {
10496                    client_commit_id,
10497                    status,
10498                    results,
10499                    ..
10500                } if pushed_ids.contains(client_commit_id.as_str())
10501                    && Self::push_result_is_final(*status, results) =>
10502                {
10503                    last_final_push_result_id = Some(client_commit_id.clone());
10504                }
10505                _ => {}
10506            }
10507        }
10508        let mut frames = response.frames.into_iter().peekable();
10509        match frames.next() {
10510            Some(Frame::RespHeader {
10511                required_schema_version,
10512                latest_schema_version,
10513                log_epoch,
10514                reset_required,
10515            }) => {
10516                if let Some(required) = required_schema_version {
10517                    // §1.6 schema-floor response: nothing else is processed;
10518                    // stop syncing and surface the upgrade requirement.
10519                    let floor = SchemaFloor {
10520                        required_schema_version: Some(required),
10521                        latest_schema_version,
10522                    };
10523                    if let Err(message) = self.set_schema_floor(Some(floor.clone())) {
10524                        return SyncOutcome::Failed {
10525                            details: None,
10526                            error_code: "storage.failed".to_owned(),
10527                            message,
10528                            recommended_action: None,
10529                        };
10530                    }
10531                    report.schema_floor = Some(floor);
10532                    return SyncOutcome::Ok(report);
10533                }
10534                if reset_required {
10535                    if frames.next().is_some() {
10536                        return SyncOutcome::Failed {
10537                            details: None,
10538                            error_code: "client.invalid_host_response".to_owned(),
10539                            message: "log-epoch reset response contains body frames".to_owned(),
10540                            recommended_action: None,
10541                        };
10542                    }
10543                    match self.run_log_epoch_reset(&log_epoch) {
10544                        Ok(resets) => {
10545                            report.resets = resets;
10546                            return SyncOutcome::Ok(report);
10547                        }
10548                        Err(message) => {
10549                            return SyncOutcome::Failed {
10550                                details: None,
10551                                error_code: "sync.local_corrupt".to_owned(),
10552                                message,
10553                                recommended_action: None,
10554                            };
10555                        }
10556                    }
10557                }
10558                let stored_epoch = match self.get_meta(LOG_EPOCH_KEY) {
10559                    Ok(stored) => stored,
10560                    Err(message) => {
10561                        return SyncOutcome::Failed {
10562                            details: None,
10563                            error_code: "storage.failed".to_owned(),
10564                            message,
10565                            recommended_action: None,
10566                        };
10567                    }
10568                };
10569                // §2.1 adoption: the epoch is stored before any section applies.
10570                if stored_epoch.is_none() {
10571                    if let Err(message) = self.set_meta(LOG_EPOCH_KEY, &log_epoch) {
10572                        return SyncOutcome::Failed {
10573                            details: None,
10574                            error_code: "storage.failed".to_owned(),
10575                            message,
10576                            recommended_action: None,
10577                        };
10578                    }
10579                } else if stored_epoch.as_deref() != Some(log_epoch.as_str()) {
10580                    return SyncOutcome::Failed {
10581                        details: None,
10582                        error_code: "client.invalid_host_response".to_owned(),
10583                        message: "server changed logEpoch without requiring a reset".to_owned(),
10584                        recommended_action: None,
10585                    };
10586                }
10587            }
10588            _ => {
10589                return SyncOutcome::Failed {
10590                    details: None,
10591                    error_code: "sync.invalid_request".to_owned(),
10592                    message: "response does not start with RESP_HEADER".to_owned(),
10593                    recommended_action: None,
10594                };
10595            }
10596        }
10597
10598        if let Err(message) = self.begin_coalesced_apply() {
10599            return SyncOutcome::Failed {
10600                details: None,
10601                error_code: "storage.failed".into(),
10602                message,
10603                recommended_action: None,
10604            };
10605        }
10606        let mut failure: Option<(String, String, Option<String>, Option<Value>)> = None;
10607        // §4.5 client application: the units whose persisted echo a live
10608        // change must match, fixed at LIVE_START after every SUB_END persisted.
10609        let mut live: Option<(LiveStatus, String, Vec<UnitRecord>)> = None;
10610        let mut live_ended = false;
10611        while let Some(frame) = frames.next() {
10612            match frame {
10613                frame @ Frame::PushResult { .. } => {
10614                    let successful = matches!(
10615                        &frame,
10616                        Frame::PushResult {
10617                            status: PushStatus::Applied | PushStatus::Cached,
10618                            ..
10619                        }
10620                    );
10621                    let mut results = vec![frame];
10622                    if successful {
10623                        while matches!(
10624                            frames.peek(),
10625                            Some(Frame::PushResult {
10626                                status: PushStatus::Applied | PushStatus::Cached,
10627                                ..
10628                            })
10629                        ) {
10630                            if let Some(next) = frames.next() {
10631                                results.push(next);
10632                            }
10633                        }
10634                    }
10635                    if self
10636                        .handle_push_results(
10637                            &results,
10638                            &pushed_ids,
10639                            &rejection_details_by_commit,
10640                            &mut report,
10641                            last_final_push_result_id.as_deref(),
10642                        )
10643                        .is_err()
10644                    {
10645                        failure = Some((
10646                            "client.outcome_persistence_failed".to_owned(),
10647                            "local commit outcome could not be persisted".to_owned(),
10648                            None,
10649                            None,
10650                        ));
10651                        break;
10652                    }
10653                }
10654                Frame::PushResultDetails { .. } => {}
10655                Frame::SubStart {
10656                    id,
10657                    status,
10658                    reason_code,
10659                    bootstrap,
10660                    fenced,
10661                } => {
10662                    // §1.4 rule 5: an ERROR closes the section; its body still
10663                    // applied, its SUB_END values are never persisted.
10664                    let mut body = Vec::new();
10665                    let mut sub_end: Option<(i64, Option<String>)> = None;
10666                    let mut error: Option<Frame> = None;
10667                    for inner in frames.by_ref() {
10668                        match inner {
10669                            Frame::SubEnd {
10670                                next_cursor,
10671                                bootstrap_state,
10672                            } => {
10673                                sub_end = Some((next_cursor, bootstrap_state.map(|r| r.0)));
10674                                break;
10675                            }
10676                            inner @ Frame::Error { .. } => {
10677                                error = Some(inner);
10678                                break;
10679                            }
10680                            Frame::Unknown { .. } => {}
10681                            other => body.push(other),
10682                        }
10683                    }
10684                    let ended = sub_end.is_some();
10685                    let section = SectionStart {
10686                        id,
10687                        status,
10688                        reason_code,
10689                        bootstrap,
10690                        fenced,
10691                    };
10692                    let completed = match self.process_section(
10693                        transport,
10694                        &section,
10695                        body,
10696                        sub_end,
10697                        meta,
10698                        &mut report,
10699                    ) {
10700                        Err(SectionError::Abort(code, message)) => {
10701                            failure = Some((code, message, None, None));
10702                            break;
10703                        }
10704                        Err(SectionError::Transport(error)) => {
10705                            failure = Some((error.code, error.message, None, error.details));
10706                            break;
10707                        }
10708                        Ok(completed) => completed,
10709                        Err(_) => false,
10710                    };
10711                    if ended {
10712                        // The counters stay: `complete` and `failed` report them.
10713                        // §7.7: a completed bootstrap ends with the unit total
10714                        // equal to the rows processed.
10715                        self.progress.update(|p| {
10716                            p.unit_id = None;
10717                            p.table = None;
10718                            p.segment_id = None;
10719                            if completed && p.unit_rows_total.is_some() {
10720                                p.unit_rows_total = p.unit_rows_processed;
10721                            }
10722                        });
10723                    }
10724                    match error {
10725                        Some(Frame::Error {
10726                            code,
10727                            message,
10728                            recommended_action,
10729                            details,
10730                            ..
10731                        }) => {
10732                            failure = Some(Self::error_frame_failure(
10733                                code,
10734                                message,
10735                                recommended_action,
10736                                details,
10737                            ));
10738                            break;
10739                        }
10740                        Some(_) => unreachable!("only an ERROR closes a section early"),
10741                        None if !ended => {
10742                            failure = Some((
10743                                "sync.invalid_request".to_owned(),
10744                                "unit section without SUB_END".to_owned(),
10745                                None,
10746                                None,
10747                            ));
10748                            break;
10749                        }
10750                        None => {}
10751                    }
10752                }
10753                Frame::LiveStart {
10754                    status,
10755                    reason_code,
10756                } => {
10757                    let receivers = match self.stored(load_units(&self.conn)) {
10758                        Ok(units) => units
10759                            .into_iter()
10760                            .filter(|unit| {
10761                                unit.status == UnitStatus::Active
10762                                    && unit.echo.is_some()
10763                                    && !unit.bootstrapping()
10764                            })
10765                            .collect(),
10766                        Err(message) => {
10767                            failure = Some(("storage.failed".to_owned(), message, None, None));
10768                            break;
10769                        }
10770                    };
10771                    live = Some((status, reason_code, receivers));
10772                }
10773                Frame::Commit {
10774                    commit_seq,
10775                    tables,
10776                    changes,
10777                    ..
10778                } => {
10779                    let Some((LiveStatus::Active, _, receivers)) = &live else {
10780                        continue;
10781                    };
10782                    let receivers = receivers.clone();
10783                    match self.apply_live_commit(
10784                        &receivers,
10785                        &tables,
10786                        changes,
10787                        commit_seq,
10788                        AppliedServerCommitSource::Pull,
10789                    ) {
10790                        Ok(applied) => report.commits_applied += u32::from(applied),
10791                        Err(error) => {
10792                            failure = Some((error.code, error.message, None, error.details));
10793                            break;
10794                        }
10795                    }
10796                }
10797                Frame::LiveEnd {
10798                    through_seq,
10799                    echo_digest,
10800                } => {
10801                    let Some((status, reason_code, _)) = live.take() else {
10802                        continue;
10803                    };
10804                    live_ended = true;
10805                    live = Some((status, String::new(), Vec::new()));
10806                    if let Err(message) = self.finish_live_section(
10807                        status,
10808                        &reason_code,
10809                        through_seq,
10810                        echo_digest,
10811                        &meta.registration_digest,
10812                        &mut report,
10813                    ) {
10814                        failure = Some(("storage.failed".to_owned(), message, None, None));
10815                        break;
10816                    }
10817                }
10818                Frame::Lease {
10819                    lease_id,
10820                    expires_at_ms,
10821                } => {
10822                    // §7.3.5: persist the opaque lease; a fresh lease clears
10823                    // any prior lease error (the outage/revocation is over).
10824                    if let Err(message) = self.set_lease_state(Some(LeaseState {
10825                        lease_id: Some(lease_id),
10826                        expires_at_ms: Some(expires_at_ms),
10827                        error_code: None,
10828                    })) {
10829                        failure = Some(("storage.failed".to_owned(), message, None, None));
10830                        break;
10831                    }
10832                }
10833                Frame::Error {
10834                    code,
10835                    message,
10836                    recommended_action,
10837                    details,
10838                    ..
10839                } => {
10840                    // §1.6: the whole request failed; already-completed
10841                    // units keep their applied data and cursors.
10842                    failure = Some(Self::error_frame_failure(
10843                        code,
10844                        message,
10845                        recommended_action,
10846                        details,
10847                    ));
10848                    break;
10849                }
10850                Frame::Unknown { .. } => {}
10851                // §1.6: a building server's keepalive carries nothing to apply.
10852                Frame::Keepalive => {}
10853                _ => {
10854                    failure = Some((
10855                        "sync.invalid_request".to_owned(),
10856                        "unexpected frame in response".to_owned(),
10857                        None,
10858                        None,
10859                    ));
10860                    break;
10861                }
10862            }
10863        }
10864
10865        let applied = match failure {
10866            Some(failure) => Err(failure),
10867            // Local apply boundaries already reconciled their affected overlay.
10868            // Refuse round success if any remaining dirty work fails to
10869            // reconcile. §4.8 E1: the push half may have drained commits that
10870            // pinned rows of a shrunk window unit, so retry deferred evictions.
10871            None => self
10872                .rebuild_overlay_if_dirty()
10873                .and_then(|()| self.drain_pending_evictions())
10874                .map_err(|message| ("storage.failed".to_owned(), message, None, None)),
10875        };
10876        // §1.4 rule 4: frames completed before a failure stay committed; a
10877        // failed COMMIT of the coalesced transaction fails the round.
10878        if let Err(message) = self.finish_coalesced_apply() {
10879            return SyncOutcome::Failed {
10880                details: None,
10881                error_code: "storage.failed".into(),
10882                message,
10883                recommended_action: None,
10884            };
10885        }
10886        if let Err((error_code, message, recommended_action, details)) = applied {
10887            return SyncOutcome::Failed {
10888                details,
10889                error_code,
10890                message,
10891                recommended_action,
10892            };
10893        }
10894        let catching_up = match self.stored(load_units(&self.conn)) {
10895            Ok(units) => units
10896                .into_iter()
10897                .filter(|unit| unit.status == UnitStatus::Active && unit.cursor.is_some())
10898                .map(|unit| unit.id)
10899                .collect::<Vec<_>>(),
10900            Err(message) => {
10901                return SyncOutcome::Failed {
10902                    details: None,
10903                    error_code: "storage.failed".into(),
10904                    message,
10905                    recommended_action: None,
10906                }
10907            }
10908        };
10909        // §7.1: a response without LIVE_END, one answered `unregistered` or
10910        // `reset`, or a unit still catching up leaves sync-needed raised;
10911        // after `unregistered` the next round starts at once.
10912        let status = live.map(|(status, _, _)| status);
10913        if !live_ended || status != Some(LiveStatus::Active) || !catching_up.is_empty() {
10914            self.set_sync_needed(true, status == Some(LiveStatus::Unregistered));
10915        }
10916        self.ack_after_pull(transport);
10917        // §7.4.5: the reset is over once the first post-reset pull round
10918        // leaves no unit catching up: the tables are rebuilt and current.
10919        if self.upgrading && catching_up.is_empty() {
10920            self.set_upgrading(false);
10921        }
10922        report.bootstrapping = catching_up;
10923        SyncOutcome::Ok(report)
10924    }
10925
10926    /// §1.6 / §10.1: the failure an in-band `ERROR` frame reports.
10927    fn error_frame_failure(
10928        code: String,
10929        message: String,
10930        recommended_action: String,
10931        details: Option<RawJson>,
10932    ) -> (String, String, Option<String>, Option<Value>) {
10933        let recommended_action = (!recommended_action.is_empty()).then_some(recommended_action);
10934        let details = details
10935            .and_then(|details| serde_json::from_str::<Value>(&details.0).ok())
10936            .filter(Value::is_object);
10937        (code, message, recommended_action, details)
10938    }
10939
10940    /// §4.5 at `LIVE_END` of a pull: join rule J for an `active` section, the
10941    /// §4.6 replica reset for `reset`, nothing for `unregistered`; then the
10942    /// replica cursor, the echo digest and the digest of the list the server
10943    /// now stores.
10944    fn finish_live_section(
10945        &mut self,
10946        status: LiveStatus,
10947        reason_code: &str,
10948        through_seq: i64,
10949        echo_digest: Option<[u8; 32]>,
10950        registration_digest: &str,
10951        report: &mut SyncReport,
10952    ) -> Result<(), String> {
10953        let rollback = self.capture();
10954        let resets = report.resets.len();
10955        self.begin_observation("syncular_live_end")?;
10956        let finished = (|| {
10957            let mut batch = ChangeAccumulator::default();
10958            let before = self.stored(replica_cursor(&self.conn))?;
10959            let mut cursor = if status == LiveStatus::Unregistered {
10960                before
10961            } else {
10962                -1
10963            };
10964            let joined = before.max(through_seq);
10965            for unit in self.stored(load_units(&self.conn))? {
10966                if unit.status != UnitStatus::Active || unit.bootstrapping() {
10967                    continue;
10968                }
10969                match status {
10970                    // §4.6 replica reset: every live unit bootstraps again;
10971                    // post-bootstrap units keep their cursors.
10972                    LiveStatus::Reset if unit.cursor.is_none() => {
10973                        self.record_unit_windows(&mut batch, &unit)?;
10974                        report.resets.push(unit.id.clone());
10975                        self.stored(save_unit(
10976                            &self.conn,
10977                            &UnitRecord {
10978                                reason_code: Some(reason_code.to_owned()),
10979                                cursor: Some(-1),
10980                                seeded: Vec::new(),
10981                                ..unit
10982                            },
10983                        ))?;
10984                    }
10985                    // §4.5 join rule J.
10986                    LiveStatus::Active => {
10987                        let next = unit.cursor.unwrap_or(joined).max(through_seq);
10988                        if next >= joined {
10989                            cursor = joined;
10990                        }
10991                        if unit.cursor.is_some() {
10992                            // A post-bootstrap unit that joins live transitions.
10993                            if next >= joined {
10994                                self.record_unit_windows(&mut batch, &unit)?;
10995                            }
10996                            self.stored(save_unit(
10997                                &self.conn,
10998                                &UnitRecord {
10999                                    cursor: (next < joined).then_some(next),
11000                                    ..unit
11001                                },
11002                            ))?;
11003                        }
11004                    }
11005                    _ => {}
11006                }
11007            }
11008            self.set_meta(REPLICA_CURSOR_KEY, &cursor.to_string())?;
11009            self.set_meta(
11010                ECHO_DIGEST_KEY,
11011                &echo_digest
11012                    .map(|digest| bytes_to_hex(&digest))
11013                    .unwrap_or_default(),
11014            )?;
11015            if status == LiveStatus::Unregistered {
11016                self.delete_meta(REGISTERED_DIGEST_KEY)?;
11017            } else {
11018                self.set_meta(REGISTERED_DIGEST_KEY, registration_digest)?;
11019            }
11020            self.finish_observation("syncular_live_end", batch)
11021        })();
11022        if finished.is_err() {
11023            self.rollback_observation("syncular_live_end");
11024            self.restore(rollback);
11025            report.resets.truncate(resets);
11026        }
11027        finished
11028    }
11029
11030    // -- push results (§6.3, §7.2) ------------------------------------------------
11031
11032    fn handle_push_results(
11033        &mut self,
11034        frames: &[Frame],
11035        pushed_ids: &HashSet<&str>,
11036        rejection_details_by_commit: &HashMap<String, BTreeMap<i32, RejectionDetails>>,
11037        report: &mut SyncReport,
11038        last_final_push_result_id: Option<&str>,
11039    ) -> Result<(), String> {
11040        self.begin_observation("syncular_push_results")?;
11041        let rollback = self.capture();
11042        let conflict_count = self.conflicts.len();
11043        let applied_count = report.applied.len();
11044        let rejected_count = report.rejected.len();
11045        let retryable_count = report.retryable.len();
11046        let mut drained = Vec::new();
11047        let mut batch = ChangeAccumulator::default();
11048        let persisted = (|| {
11049            for frame in frames {
11050                let Frame::PushResult {
11051                    client_commit_id,
11052                    status,
11053                    results,
11054                    commit_seq,
11055                } = frame
11056                else {
11057                    return Err("unexpected acknowledgement frame".to_owned());
11058                };
11059                if !pushed_ids.contains(client_commit_id.as_str()) {
11060                    continue;
11061                }
11062                let Some(index) = self
11063                    .outbox
11064                    .iter()
11065                    .position(|commit| commit.client_commit_id == *client_commit_id)
11066                else {
11067                    continue;
11068                };
11069                let status = *status;
11070                let rejection_details = rejection_details_by_commit.get(client_commit_id);
11071                let operations = self.outbox[index].ops.clone();
11072                match status {
11073                    PushStatus::Applied | PushStatus::Cached => {
11074                        // §7.2: a lost ack replays as `cached` — proceed as if the
11075                        // ack had arrived.
11076                        let sequence =
11077                            commit_seq.ok_or_else(|| "ACK lacks a commit sequence".to_owned())?;
11078                        let affected: HashSet<_> = operations
11079                            .iter()
11080                            .map(|op| (op.table.as_str(), op.row_id.as_str()))
11081                            .collect();
11082                        let prior = self.acknowledged_operations(Some(&affected), None)?;
11083                        for (op_index, operation) in operations.iter().enumerate() {
11084                            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))
11085                                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11086                            if delivered {
11087                                continue;
11088                            }
11089                            let table = self
11090                                .schema
11091                                .table(&operation.table)
11092                                .ok_or_else(|| "sync.unknown_table".to_owned())?;
11093                            let mut intended: Map<String, Value> = self
11094                                .stored_row(table, &operation.row_id, true)?
11095                                .map(|(row, _)| {
11096                                    table
11097                                        .columns
11098                                        .iter()
11099                                        .zip(&row)
11100                                        .map(|(column, value)| {
11101                                            (column.name.clone(), column_value_to_json(value))
11102                                        })
11103                                        .collect()
11104                                })
11105                                .unwrap_or_default();
11106                            let mut scope_image = intended.clone();
11107                            for op in prior
11108                                .iter()
11109                                .chain(
11110                                    self.failed_commits
11111                                        .iter()
11112                                        .flat_map(|(commit, _)| &commit.ops),
11113                                )
11114                                .chain(
11115                                    self.outbox
11116                                        .iter()
11117                                        .take(index)
11118                                        .flat_map(|commit| &commit.ops),
11119                                )
11120                                .chain(operations.iter().take(op_index + 1))
11121                            {
11122                                if op.table != operation.table || op.row_id != operation.row_id {
11123                                    continue;
11124                                }
11125                                if let Some(values) = &op.values {
11126                                    intended.extend(values.clone());
11127                                } else {
11128                                    scope_image = intended.clone();
11129                                    intended.clear();
11130                                }
11131                            }
11132                            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)",
11133                                rusqlite::params![client_commit_id, op_index as i64, operation.table, operation.row_id, sequence,
11134                                    serde_json::to_string(&CommitOperation::from(operation)).map_err(|_| "sync.local_corrupt".to_owned())?,
11135                                    serde_json::to_string(if operation.upsert { &intended } else { &scope_image }).map_err(|_| "sync.local_corrupt".to_owned())?])
11136                                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11137                        }
11138                        let journal_results = results
11139                            .iter()
11140                            .map(|result| {
11141                                let op_index = match result {
11142                                    OpResult::Applied { op_index }
11143                                    | OpResult::Conflict { op_index, .. }
11144                                    | OpResult::Error { op_index, .. } => *op_index,
11145                                };
11146                                CommitOperationOutcome::Applied { op_index }
11147                            })
11148                            .collect::<Vec<_>>();
11149                        let outcome_status = if status == PushStatus::Applied {
11150                            CommitOutcomeStatus::Applied
11151                        } else {
11152                            CommitOutcomeStatus::Cached
11153                        };
11154                        let persisted = self
11155                            .persist_commit_outcome(
11156                                client_commit_id,
11157                                outcome_status,
11158                                &journal_results,
11159                                None,
11160                            )
11161                            .and_then(|()| self.delete_outbox_persisted(client_commit_id));
11162                        persisted?;
11163                        self.sync_needed = true;
11164                        batch.status = true;
11165                        batch.outcomes = true;
11166                    }
11167                    PushStatus::Rejected => {
11168                        if results.iter().any(|result| {
11169                            matches!(
11170                                result,
11171                                OpResult::Error {
11172                                    code,
11173                                    retryable: true,
11174                                    ..
11175                                } if code == "sync.idempotency_cache_miss"
11176                            )
11177                        }) {
11178                            // §6.3/§7.2: a serving failure, not an outcome — keep the
11179                            // exact commit queued for an identical retry.
11180                            report.retryable.push(client_commit_id.to_owned());
11181                            continue;
11182                        }
11183
11184                        let mut journal_results = Vec::with_capacity(results.len());
11185                        let mut conflicts = Vec::new();
11186                        let mut rejections = Vec::new();
11187                        for result in results {
11188                            match result {
11189                                OpResult::Applied { op_index } => {
11190                                    journal_results.push(CommitOperationOutcome::Applied {
11191                                        op_index: *op_index,
11192                                    });
11193                                }
11194                                OpResult::Conflict {
11195                                    op_index,
11196                                    code,
11197                                    message,
11198                                    server_version,
11199                                    server_row,
11200                                    conflict_columns: conflict_columns_bitmap,
11201                                } => {
11202                                    let operation = operations
11203                                        .get(*op_index as usize)
11204                                        .map(CommitOperation::from);
11205                                    let (table, row_id) = operation
11206                                        .as_ref()
11207                                        .map(|op| (op.table.clone(), op.row_id.clone()))
11208                                        .unwrap_or_default();
11209                                    let server_row_json = self
11210                                        .schema
11211                                        .table(&table)
11212                                        .and_then(|t| {
11213                                            decode_row_bytes(t, server_row, &self.encryption)
11214                                                .ok()
11215                                                .map(|(row, _)| (t, row))
11216                                        })
11217                                        .map(|(t, row)| {
11218                                            let mut map = Map::new();
11219                                            for (i, column) in t.columns.iter().enumerate() {
11220                                                map.insert(
11221                                                    column.name.clone(),
11222                                                    column_value_to_json(
11223                                                        row.get(i).unwrap_or(&None),
11224                                                    ),
11225                                                );
11226                                            }
11227                                            map
11228                                        })
11229                                        .unwrap_or_default();
11230                                    // §6.3: decode the presence-layout bitmap
11231                                    // into the marked column names.
11232                                    let conflict_columns = self
11233                                        .schema
11234                                        .table(&table)
11235                                        .map(|t| {
11236                                            t.columns
11237                                                .iter()
11238                                                .enumerate()
11239                                                .filter(|(index, _)| {
11240                                                    conflict_columns_bitmap
11241                                                        .get(index / 8)
11242                                                        .is_some_and(|byte| {
11243                                                            byte & (1 << (index % 8)) != 0
11244                                                        })
11245                                                })
11246                                                .map(|(_, column)| column.name.clone())
11247                                                .collect::<Vec<_>>()
11248                                        })
11249                                        .unwrap_or_default();
11250                                    let conflict = ConflictRecord {
11251                                        client_commit_id: client_commit_id.to_owned(),
11252                                        op_index: *op_index,
11253                                        table,
11254                                        row_id,
11255                                        code: code.clone(),
11256                                        message: message.clone(),
11257                                        server_version: *server_version,
11258                                        server_row: server_row_json,
11259                                        conflict_columns,
11260                                        operation,
11261                                    };
11262                                    journal_results.push(CommitOperationOutcome::Conflict {
11263                                        conflict: conflict.clone(),
11264                                    });
11265                                    conflicts.push(conflict);
11266                                }
11267                                OpResult::Error {
11268                                    op_index,
11269                                    code,
11270                                    message,
11271                                    retryable,
11272                                } => {
11273                                    let rejection = RejectionRecord {
11274                                        client_commit_id: client_commit_id.to_owned(),
11275                                        op_index: *op_index,
11276                                        code: code.clone(),
11277                                        message: message.clone(),
11278                                        retryable: *retryable,
11279                                        details: rejection_details
11280                                            .and_then(|details| details.get(op_index))
11281                                            .cloned(),
11282                                        operation: operations
11283                                            .get(*op_index as usize)
11284                                            .map(CommitOperation::from),
11285                                    };
11286                                    journal_results.push(CommitOperationOutcome::Error {
11287                                        rejection: rejection.clone(),
11288                                    });
11289                                    rejections.push(rejection);
11290                                }
11291                            }
11292                        }
11293                        if self.retain_failed_commits {
11294                            self.retain_failed_commit(client_commit_id, &operations)?;
11295                        }
11296                        let outcome_status = if conflicts.is_empty() {
11297                            CommitOutcomeStatus::Rejected
11298                        } else {
11299                            CommitOutcomeStatus::Conflict
11300                        };
11301                        self.leave_through(client_commit_id);
11302                        let persisted = self
11303                            .persist_commit_outcome(
11304                                client_commit_id,
11305                                outcome_status,
11306                                &journal_results,
11307                                Some(&operations),
11308                            )
11309                            .and_then(|()| self.delete_outbox_persisted(client_commit_id));
11310                        persisted?;
11311                        batch.conflicts = !conflicts.is_empty();
11312                        batch.rejections = !rejections.is_empty();
11313                        batch.status = true;
11314                        batch.outcomes = true;
11315                        self.conflicts.extend(conflicts);
11316                        self.rejections.extend(rejections);
11317                    }
11318                }
11319                drained.push(self.outbox.remove(index));
11320                if batch.status {
11321                    for operation in &operations {
11322                        if !self.record_row_scopes(
11323                            &mut batch,
11324                            &operation.table,
11325                            &operation.row_id,
11326                            false,
11327                        ) {
11328                            batch.table(&operation.table);
11329                        }
11330                    }
11331                }
11332                match status {
11333                    PushStatus::Applied | PushStatus::Cached => {
11334                        report.applied.push(client_commit_id.to_owned())
11335                    }
11336                    PushStatus::Rejected => report.rejected.push(client_commit_id.to_owned()),
11337                }
11338            }
11339            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)) {
11340                self.prune_commit_outcomes()?;
11341            }
11342            self.reconcile_rows(&drained)?;
11343            self.rebuild_overlay_if_dirty()?;
11344            self.finish_observation("syncular_push_results", batch)
11345        })();
11346        if let Err(error) = persisted {
11347            self.rollback_observation("syncular_push_results");
11348            self.restore(rollback);
11349            report.applied.truncate(applied_count);
11350            report.rejected.truncate(rejected_count);
11351            report.retryable.truncate(retryable_count);
11352            return Err(error);
11353        }
11354        if !rollback.sync_needed && self.sync_needed {
11355            self.sync_intent_queue.push_back(SyncIntent::Interactive);
11356        }
11357        report.conflicts += (self.conflicts.len() - conflict_count) as u32;
11358        Ok(())
11359    }
11360
11361    fn push_result_is_final(status: PushStatus, results: &[OpResult]) -> bool {
11362        status != PushStatus::Rejected
11363            || !results.iter().any(|result| {
11364                matches!(
11365                    result,
11366                    OpResult::Error {
11367                        code,
11368                        retryable: true,
11369                        ..
11370                    } if code == "sync.idempotency_cache_miss"
11371                )
11372            })
11373    }
11374
11375    // -- unit sections and the live section ------------------------------------------
11376
11377    /// One unit section (§4.4): apply its segments, then persist its
11378    /// `SUB_END` (§4.6 reset, §3.3 revocation and purge, the echo, cursor and
11379    /// resume token). A section of a unit the app released while the round was
11380    /// in flight is skipped; a fail-closed first page fails the unit and skips
11381    /// the rest of its section (§5.6). Returns whether its `SUB_END` completed
11382    /// a bootstrap (§7.7).
11383    fn process_section(
11384        &mut self,
11385        transport: &mut dyn Transport,
11386        start: &SectionStart,
11387        body: Vec<Frame>,
11388        sub_end: Option<(i64, Option<String>)>,
11389        meta: &RequestMeta,
11390        report: &mut SyncReport,
11391    ) -> Result<bool, SectionError> {
11392        let storage = |message| SectionError::Abort("storage.failed".to_owned(), message);
11393        let unit = self
11394            .stored(get_unit(&self.conn, &start.id))
11395            .map_err(storage)?
11396            .filter(|unit| unit.status == UnitStatus::Active);
11397        // §7.7: a section boundary ends the previous payload; the section's
11398        // UNIT_EXTENT starts the unit counters in the same snapshot.
11399        let extent = match (&unit, body.first()) {
11400            (
11401                Some(_),
11402                Some(Frame::UnitExtent {
11403                    rows_total,
11404                    rows_done,
11405                }),
11406            ) => u64::try_from(*rows_total)
11407                .ok()
11408                .zip(u64::try_from(*rows_done).ok()),
11409            _ => None,
11410        };
11411        self.progress.update(|p| {
11412            p.phase = ProgressPhase::Import;
11413            p.unit_id = unit.as_ref().map(|unit| unit.id.clone());
11414            p.unit_rows_total = extent.map(|(total, _)| total);
11415            p.unit_rows_processed = extent.map(|(_, done)| done);
11416            p.table = None;
11417            p.segment_id = None;
11418            p.bytes_received = 0;
11419            p.bytes_total = None;
11420            p.rows_processed = 0;
11421            p.rows_total = None;
11422            p.import_write_ms = None;
11423            p.import_commit_ms = None;
11424            p.download_ms = None;
11425        });
11426        let Some(unit) = unit else {
11427            return Ok(false);
11428        };
11429        let echo: Vec<EchoRecord> = start
11430            .fenced
11431            .iter()
11432            .map(|record| EchoRecord {
11433                table: record.table.clone(),
11434                status: record.status.name().to_owned(),
11435                scopes: record.scopes.iter().cloned().collect(),
11436            })
11437            .collect();
11438        // §5.6: rows earlier attempts at this position applied.
11439        let applied_record = self
11440            .stored(applied_rows(&self.conn, &unit.id))
11441            .map_err(storage)?;
11442        // §5.6: a resumed bootstrap keeps the tables it already seeded.
11443        let mut seeded: BTreeSet<String> = if unit.bootstrap_state.is_none() {
11444            BTreeSet::new()
11445        } else {
11446            unit.seeded.iter().cloned().collect()
11447        };
11448        let applied = (|| {
11449            for frame in body {
11450                match frame {
11451                    Frame::SegmentInline { payload } => {
11452                        let segment = decode_rows_segment(&payload).map_err(|e| {
11453                            SectionError::Abort(e.code.as_str().to_owned(), e.detail)
11454                        })?;
11455                        self.progress.update(|p| {
11456                            p.phase = ProgressPhase::Import;
11457                            p.unit_id = Some(unit.id.clone());
11458                            p.table = Some(segment.table.clone());
11459                            p.segment_id = None;
11460                            p.bytes_received = payload.len() as u64;
11461                            p.bytes_total = Some(payload.len() as u64);
11462                            p.rows_processed = 0;
11463                            p.rows_total =
11464                                Some(segment.blocks.iter().map(|block| block.len() as u64).sum());
11465                            p.import_write_ms = None;
11466                            p.import_commit_ms = None;
11467                            p.download_ms = None;
11468                        });
11469                        let (pair, clear, effective) =
11470                            self.segment_pair(&unit, &echo, &seeded, &segment.table)?;
11471                        report.segment_rows_applied +=
11472                            self.apply_segment(&pair, &segment, clear, &effective, &unit.id)?;
11473                        seeded.insert(segment.table);
11474                    }
11475                    Frame::SegmentRef {
11476                        segment_id,
11477                        byte_length,
11478                        media_type,
11479                        table,
11480                        row_count,
11481                        as_of_commit_seq,
11482                        scope_digest,
11483                        row_cursor,
11484                        next_row_cursor,
11485                        url,
11486                        url_expires_at_ms,
11487                        ..
11488                    } => {
11489                        // §4.2: reject a descriptor whose mediaType was not
11490                        // advertised — never skip or guess.
11491                        let advertised = match media_type {
11492                            MediaType::Rows => {
11493                                meta.accept & ACCEPT_EXTERNAL_ROWS != 0
11494                                    || meta.accept & ACCEPT_INLINE_ROWS != 0
11495                            }
11496                            MediaType::Sqlite => meta.accept & ACCEPT_SQLITE != 0,
11497                        };
11498                        if !advertised {
11499                            return Err(SectionError::Abort(
11500                                "sync.invalid_request".to_owned(),
11501                                format!(
11502                                    "SEGMENT_REF mediaType {} was not advertised in accept (§4.2)",
11503                                    media_type.name()
11504                                ),
11505                            ));
11506                        }
11507                        // §5.6 applied-segment rule: a partly applied image
11508                        // already ran its table's first-page clear.
11509                        let resumed = applied_record.get(&segment_id).copied();
11510                        if resumed.is_some() {
11511                            seeded.insert(table.clone());
11512                        }
11513                        if resumed == Some(row_count) {
11514                            // §7.7: an earlier attempt imported this payload;
11515                            // its rows still count toward the unit.
11516                            self.progress.update(|p| {
11517                                p.phase = ProgressPhase::Import;
11518                                p.unit_id = Some(unit.id.clone());
11519                                p.table = Some(table.clone());
11520                                p.segment_id = Some(segment_id.clone());
11521                                p.bytes_received = 0;
11522                                p.bytes_total = None;
11523                                p.rows_processed = 0;
11524                                p.rows_total = u64::try_from(row_count).ok();
11525                                p.import_write_ms = None;
11526                                p.import_commit_ms = None;
11527                                p.download_ms = None;
11528                            });
11529                            self.progress.update(|p| {
11530                                p.rows_processed = u64::try_from(row_count).unwrap_or(0)
11531                            });
11532                            continue;
11533                        }
11534                        if meta
11535                            .deferred
11536                            .contains(&(unit.id.clone(), segment_id.clone()))
11537                        {
11538                            return Err(SectionError::Deferred);
11539                        }
11540                        self.progress.update(|p| {
11541                            p.phase = ProgressPhase::Download;
11542                            p.unit_id = Some(unit.id.clone());
11543                            p.table = Some(table.clone());
11544                            p.segment_id = Some(segment_id.clone());
11545                            p.bytes_received = 0;
11546                            p.bytes_total = u64::try_from(byte_length).ok();
11547                            p.rows_processed = 0;
11548                            p.rows_total = u64::try_from(row_count).ok();
11549                            p.import_write_ms = None;
11550                            p.import_commit_ms = None;
11551                            p.download_ms = None;
11552                        });
11553                        let observer = self.progress.clone();
11554                        let mut on_progress = |bytes| observer.update(|p| p.bytes_received = bytes);
11555                        // §7.7: from the request's start to its last body byte.
11556                        let requested = std::time::Instant::now();
11557                        let bytes = if let Some(url) = url {
11558                            // §5.4: a url-carrying descriptor MUST be fetched
11559                            // from that URL; failure invalidates the whole
11560                            // descriptor (no fall-through to §5.5 — re-pull
11561                            // recovers, §1.4 rule 5).
11562                            if meta.accept & ACCEPT_SIGNED_URLS == 0 {
11563                                return Err(SectionError::Abort(
11564                                    "sync.invalid_request".to_owned(),
11565                                    "SEGMENT_REF carries a url but accept bit 3 was not advertised (§5.4)"
11566                                        .to_owned(),
11567                                ));
11568                            }
11569                            // §5.4: MUST NOT start a fetch at/past expiry.
11570                            if url_expires_at_ms.is_some_and(|exp| {
11571                                exp <= transport
11572                                    .segment_fetch_started_at(&url)
11573                                    .unwrap_or_else(|| self.clock_now_ms())
11574                            }) {
11575                                return Err(SectionError::Abort(
11576                                    "sync.segment_expired".to_owned(),
11577                                    format!(
11578                                        "signed URL for segment {segment_id} expired before fetch — re-pull mints fresh descriptors (§5.4)"
11579                                    ),
11580                                ));
11581                            }
11582                            transport
11583                                .fetch_url(
11584                                    &url,
11585                                    u64::try_from(byte_length).unwrap_or(0),
11586                                    &mut on_progress,
11587                                )
11588                                .map_err(|e| self.segment_fetch_failed(e))?
11589                        } else {
11590                            // §5.5: the owning unit's scope map, each value a one-element list.
11591                            let requested_scopes_json =
11592                                canonical_scope_json(&unit_scope_lists(&unit.scopes));
11593                            transport
11594                                .download_segment(
11595                                    &SegmentRequest {
11596                                        segment_id: segment_id.clone(),
11597                                        table: table.clone(),
11598                                        requested_scopes_json,
11599                                        byte_length: u64::try_from(byte_length).unwrap_or(0),
11600                                    },
11601                                    &mut on_progress,
11602                                )
11603                                .map_err(|e| {
11604                                    // §5.5: access changed since the response;
11605                                    // the next round's SUB_START settles the unit.
11606                                    if e.code == "sync.forbidden" {
11607                                        SectionError::Refused
11608                                    } else {
11609                                        self.segment_fetch_failed(e)
11610                                    }
11611                                })?
11612                        };
11613                        let download_ms = u64::try_from(requested.elapsed().as_millis()).ok();
11614                        // §5.4: the descriptor's byteLength caps the body before
11615                        // §5.1 verifies the content address; the client discards
11616                        // the segment and re-pulls on either failure.
11617                        if bytes.len() as i64 > byte_length {
11618                            self.schedule_background_retry();
11619                            return Err(SectionError::Abort(
11620                                "sync.invalid_request".to_owned(),
11621                                "segment exceeds its byteLength".to_owned(),
11622                            ));
11623                        }
11624                        on_progress(bytes.len() as u64);
11625                        let digest = Sha256::digest(&bytes);
11626                        let expected = segment_id
11627                            .strip_prefix("sha256:")
11628                            .unwrap_or(segment_id.as_str());
11629                        if bytes_to_hex(&digest) != expected {
11630                            // §5.1: the client discards the segment and re-pulls.
11631                            self.schedule_background_retry();
11632                            return Err(SectionError::Abort(
11633                                "sync.invalid_request".to_owned(),
11634                                "segment bytes do not match the content address (§5.1)".to_owned(),
11635                            ));
11636                        }
11637                        self.progress.update(|p| {
11638                            p.phase = ProgressPhase::Import;
11639                            p.download_ms = download_ms;
11640                        });
11641                        if media_type == MediaType::Sqlite {
11642                            // §5.3: a range image keeps its position in the resume
11643                            // token; a descriptor row cursor is invalid.
11644                            if row_cursor.is_some() || next_row_cursor.is_some() {
11645                                return Err(SectionError::Abort(
11646                                    "sync.invalid_request".to_owned(),
11647                                    "sqlite segments are whole-table: rowCursor/nextRowCursor must be absent (§5.3)"
11648                                        .to_owned(),
11649                                ));
11650                            }
11651                            let (pair, clear, effective) =
11652                                self.segment_pair(&unit, &echo, &seeded, &table)?;
11653                            report.segment_rows_applied += self.apply_sqlite_segment(
11654                                &pair,
11655                                &bytes,
11656                                clear,
11657                                &effective,
11658                                &unit.id,
11659                                &segment_id,
11660                                resumed.unwrap_or(0),
11661                                row_count,
11662                                as_of_commit_seq,
11663                                &scope_digest,
11664                            )?;
11665                            seeded.insert(table);
11666                        } else {
11667                            let segment = decode_rows_segment(&bytes).map_err(|e| {
11668                                SectionError::Abort(e.code.as_str().to_owned(), e.detail)
11669                            })?;
11670                            let (pair, clear, effective) =
11671                                self.segment_pair(&unit, &echo, &seeded, &segment.table)?;
11672                            report.segment_rows_applied +=
11673                                self.apply_segment(&pair, &segment, clear, &effective, &unit.id)?;
11674                            seeded.insert(segment.table);
11675                            // An image records its rows with each chunk.
11676                            self.stored(record_applied_rows(
11677                                &self.conn,
11678                                &unit.id,
11679                                &segment_id,
11680                                row_count,
11681                            ))
11682                            .map_err(storage)?;
11683                        }
11684                    }
11685                    Frame::UnitExtent { .. } => {}
11686                    _ => {
11687                        return Err(SectionError::Abort(
11688                            "sync.invalid_request".to_owned(),
11689                            "unexpected frame inside a unit section".to_owned(),
11690                        ));
11691                    }
11692                }
11693            }
11694            Ok(())
11695        })();
11696        match applied {
11697            Ok(()) => {}
11698            // The unit keeps catching up with its cursor unpersisted.
11699            Err(SectionError::Refused | SectionError::Deferred) => return Ok(false),
11700            Err(SectionError::FailClosed) => {
11701                // §5.6: the failure is unit-local; the rest of the response
11702                // still applies and the failed unit leaves the list.
11703                self.begin_observation("syncular_section_failure")
11704                    .map_err(storage)?;
11705                let failed = (|| {
11706                    let mut batch = ChangeAccumulator::default();
11707                    self.record_unit_windows(&mut batch, &unit)?;
11708                    batch.status = true;
11709                    self.stored(save_unit(
11710                        &self.conn,
11711                        &UnitRecord {
11712                            status: UnitStatus::Failed,
11713                            reason_code: Some("sync.scope_revoked".to_owned()),
11714                            restriction: None,
11715                            ..unit.clone()
11716                        },
11717                    ))?;
11718                    self.finish_observation("syncular_section_failure", batch)
11719                })();
11720                if let Err(message) = failed {
11721                    self.rollback_observation("syncular_section_failure");
11722                    return Err(storage(message));
11723                }
11724                report.failed.push(unit.id);
11725                return Ok(false);
11726            }
11727            Err(error) => return Err(error),
11728        }
11729        let Some((next_cursor, bootstrap_state)) = sub_end else {
11730            return Ok(false);
11731        };
11732        let completes = start.bootstrap && bootstrap_state.is_none();
11733        let rollback = self.capture();
11734        let counts = (
11735            report.resets.len(),
11736            report.revoked.len(),
11737            report.failed.len(),
11738        );
11739        self.begin_observation("syncular_sub_end")
11740            .map_err(storage)?;
11741        let finished = self
11742            .finish_section(start, echo, next_cursor, bootstrap_state, seeded, report)
11743            .and_then(|batch| {
11744                self.rebuild_overlay_if_dirty()?;
11745                self.finish_observation("syncular_sub_end", batch)
11746            });
11747        if let Err(message) = finished {
11748            self.rollback_observation("syncular_sub_end");
11749            self.restore(rollback);
11750            report.resets.truncate(counts.0);
11751            report.revoked.truncate(counts.1);
11752            report.failed.truncate(counts.2);
11753            return Err(storage(message));
11754        }
11755        Ok(completes)
11756    }
11757
11758    /// §5.6: the table, first-page flag and effective scopes of one segment
11759    /// of `unit`'s section. A first page outside the unit's restriction ends it.
11760    #[allow(clippy::type_complexity)]
11761    fn segment_pair(
11762        &self,
11763        unit: &UnitRecord,
11764        echo: &[EchoRecord],
11765        seeded: &BTreeSet<String>,
11766        name: &str,
11767    ) -> Result<(TableSchema, bool, Vec<(String, Vec<String>)>), SectionError> {
11768        let table = self.schema.table(name).cloned().ok_or_else(|| {
11769            SectionError::Abort(
11770                "sync.schema_mismatch".to_owned(),
11771                format!("segment table {name:?} is not in the client schema"),
11772            )
11773        })?;
11774        let effective = covers(&table, &unit.scopes)
11775            .then(|| pair_scopes(&unit.scopes, name, Some(echo)))
11776            .flatten()
11777            .ok_or_else(|| {
11778                SectionError::Abort(
11779                    "sync.invalid_request".to_owned(),
11780                    "a segment names no active pair of its unit".to_owned(),
11781                )
11782            })?;
11783        let first_page = !seeded.contains(name);
11784        // §5.6: a first page of a table outside the restriction is a whole
11785        // bootstrap from a server that predates RESTRICT; the restriction ends
11786        // before the clear runs.
11787        if first_page
11788            && unit
11789                .restriction
11790                .as_ref()
11791                .is_some_and(|restriction| !restriction.tables.iter().any(|t| t == name))
11792        {
11793            self.conn
11794                .execute(
11795                    "UPDATE _syncular_units SET restriction=NULL WHERE id=?1",
11796                    [&unit.id],
11797                )
11798                .map_err(|error| {
11799                    SectionError::Abort(
11800                        "storage.failed".to_owned(),
11801                        Self::sqlite_failure(&self.storage_failure, error),
11802                    )
11803                })?;
11804        }
11805        Ok((table, first_page, effective))
11806    }
11807
11808    /// §4.4 `SUB_END` of an active, revoked or reset section, inside the
11809    /// caller's observation: a reset discards cursor, resume token and
11810    /// first-page record and keeps the echo; a revoked pair purges by its last
11811    /// echo (§3.3); otherwise the echo replaces the persisted one, a revoked
11812    /// fenced record that turns active again re-bootstraps the unit, and a
11813    /// bootstrap section persists its pin, resume token and seeded tables.
11814    fn finish_section(
11815        &mut self,
11816        start: &SectionStart,
11817        echo: Vec<EchoRecord>,
11818        next_cursor: i64,
11819        bootstrap_state: Option<String>,
11820        seeded: BTreeSet<String>,
11821        report: &mut SyncReport,
11822    ) -> Result<ChangeAccumulator, String> {
11823        #[cfg(feature = "bench-internals")]
11824        let _phase = self.benchmark_phases.start(Phase::CursorPersist);
11825        let mut batch = ChangeAccumulator::default();
11826        // §4.4: SUB_END writes only into a unit that is still registered.
11827        let Some(unit) = self
11828            .stored(get_unit(&self.conn, &start.id))?
11829            .filter(|unit| unit.status == UnitStatus::Active)
11830        else {
11831            return Ok(batch);
11832        };
11833        self.record_unit_windows(&mut batch, &unit)?;
11834        if start.status == SubStatus::Reset {
11835            // §4.6: staleness, never a purge; the rows stay until the
11836            // bootstrap replaces them.
11837            report.resets.push(unit.id.clone());
11838            self.stored(save_unit(
11839                &self.conn,
11840                &UnitRecord {
11841                    reason_code: Some(start.reason_code.clone()),
11842                    cursor: Some(-1),
11843                    bootstrap_state: None,
11844                    seeded: Vec::new(),
11845                    restriction: None,
11846                    ..unit
11847                },
11848            ))?;
11849            return Ok(batch);
11850        }
11851        let revoked = start.status == SubStatus::Revoked;
11852        let mut units = None;
11853        let mut failed = false;
11854        let mut rearmed = false;
11855        for table in self.schema.tables.clone() {
11856            if !covers(&table, &unit.scopes) {
11857                continue;
11858            }
11859            let last = unit
11860                .echo
11861                .as_deref()
11862                .and_then(|last| pair_scopes(&unit.scopes, &table.name, Some(last)));
11863            let next = (!revoked)
11864                .then(|| pair_scopes(&unit.scopes, &table.name, Some(&echo)))
11865                .flatten();
11866            // §3.3: a revoked fenced record that turns active again re-bootstraps.
11867            rearmed |= unit.echo.is_some() && last.is_none() && next.is_some();
11868            // §3.3: purge a pair the response revokes, keyed on the echo the
11869            // client persisted while the pair was active.
11870            if let (Some(last), None) = (&last, &next) {
11871                let units = match units {
11872                    Some(ref units) => units,
11873                    None => units.insert(self.stored(load_units(&self.conn))?),
11874                };
11875                let owners = unit_owners(units, &table, &unit.id);
11876                failed |= !self.purge_pair(&mut batch, &table, last, &owners)?;
11877            }
11878        }
11879        if revoked || failed {
11880            if revoked {
11881                report.revoked.push(unit.id.clone());
11882            }
11883            if failed {
11884                report.failed.push(unit.id.clone());
11885            }
11886            batch.status = true;
11887            self.stored(save_unit(
11888                &self.conn,
11889                &UnitRecord {
11890                    status: if failed {
11891                        UnitStatus::Failed
11892                    } else {
11893                        UnitStatus::Revoked
11894                    },
11895                    reason_code: Some(if failed {
11896                        "sync.scope_revoked".to_owned()
11897                    } else {
11898                        start.reason_code.clone()
11899                    }),
11900                    cursor: Some(-1),
11901                    bootstrap_state: None,
11902                    seeded: Vec::new(),
11903                    echo: None,
11904                    restriction: None,
11905                    ..unit
11906                },
11907            ))?;
11908            return Ok(batch);
11909        }
11910        // §3.3: the server accepted the unit, so a later refusal re-arms once.
11911        self.window_armed.remove(&unit.id);
11912        let completed = start.bootstrap && !rearmed && bootstrap_state.is_none();
11913        let (cursor, bootstrap_state, seeded) = if rearmed {
11914            (Some(-1), None, Vec::new())
11915        } else if start.bootstrap {
11916            let seeded = if bootstrap_state.is_none() {
11917                Vec::new()
11918            } else {
11919                seeded.into_iter().collect()
11920            };
11921            (Some(next_cursor), bootstrap_state, seeded)
11922        } else {
11923            (
11924                unit.cursor,
11925                unit.bootstrap_state.clone(),
11926                unit.seeded.clone(),
11927            )
11928        };
11929        self.stored(save_unit(
11930            &self.conn,
11931            &UnitRecord {
11932                reason_code: None,
11933                echo: Some(echo.clone()),
11934                cursor,
11935                bootstrap_state,
11936                seeded,
11937                // §7.4.3: the restriction ends when the unit re-bootstraps or
11938                // completes its bootstrap.
11939                restriction: unit.restriction.clone().filter(|_| !rearmed && !completed),
11940                ..unit.clone()
11941            },
11942        ))?;
11943        if !completed {
11944            return Ok(batch);
11945        }
11946        // §7.1: a completed bootstrap covers acknowledged intent of its pairs
11947        // at or below its pin. The intent or the bootstrapped row proves the
11948        // pair: a patch omits its scope columns, and the base row it merged
11949        // over may be gone (a §7.4.4 reset before the ACK).
11950        for table in self.schema.tables.clone() {
11951            let Some(effective) = covers(&table, &unit.scopes)
11952                .then(|| pair_scopes(&unit.scopes, &table.name, Some(&echo)))
11953                .flatten()
11954            else {
11955                continue;
11956            };
11957            let mut statement = self
11958                .conn
11959                .prepare("SELECT id,intent_json FROM _syncular_acked_rows WHERE tbl=?1 AND commit_seq<=?2")
11960                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11961            let rows = statement
11962                .query_map(rusqlite::params![table.name, next_cursor], |row| {
11963                    Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
11964                })
11965                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11966            let mut covered = HashSet::new();
11967            for row in rows {
11968                let (id, intent) =
11969                    row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11970                let values: Map<String, Value> =
11971                    serde_json::from_str(&intent).map_err(|_| "sync.local_corrupt".to_owned())?;
11972                let base = self.stored_row(&table, &id, true)?.map(|(row, _)| {
11973                    table
11974                        .columns
11975                        .iter()
11976                        .zip(&row)
11977                        .map(|(column, value)| (column.name.clone(), column_value_to_json(value)))
11978                        .collect()
11979                });
11980                if [Some(values), base]
11981                    .iter()
11982                    .flatten()
11983                    .any(|values| owns_local_row(&table, &effective, &[], values))
11984                {
11985                    covered.insert(id);
11986                }
11987            }
11988            drop(statement);
11989            for id in covered {
11990                self.conn
11991                    .execute(
11992                        "DELETE FROM _syncular_acked_rows WHERE tbl=?1 AND id=?2 AND commit_seq<=?3",
11993                        rusqlite::params![table.name, id, next_cursor],
11994                    )
11995                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11996                self.overlay_dirty.table(&table.name);
11997                batch.table(&table.name);
11998            }
11999        }
12000        Ok(batch)
12001    }
12002
12003    /// §3.3: purge one revoked pair inside the caller's observation: delete
12004    /// the rows matching its last effective scopes that no owner holds, drop
12005    /// the retained intent and every pending commit that provably writes into
12006    /// them, and delete now-unauthorized blob bodies. `Ok(false)` when the
12007    /// table has no local scope-column mapping (fail closed: nothing deleted).
12008    fn purge_pair(
12009        &mut self,
12010        batch: &mut ChangeAccumulator,
12011        table: &TableSchema,
12012        last: &[(String, Vec<String>)],
12013        owners: &[Vec<(String, Vec<String>)>],
12014    ) -> Result<bool, String> {
12015        if local_scope_predicate(table, last, owners).is_err() {
12016            return Ok(false);
12017        }
12018        for commit in self.drop_failed_commits(|name, values| {
12019            name == table.name && owns_local_row(table, last, owners, values)
12020        })? {
12021            batch.conflicts = true;
12022            batch.rejections = true;
12023            batch.outcomes = true;
12024            for operation in commit.ops {
12025                batch.table(&operation.table);
12026            }
12027        }
12028        if !self.purge_scope_rows(&table.name, last, owners)? {
12029            return Err("storage.failed: the revoked scope purge failed".to_owned());
12030        }
12031        self.record_scope_map(batch, &table.name, last);
12032        if self.drop_doomed_outbox(table, last, owners)? {
12033            batch.status = true;
12034            batch.rejections = true;
12035            batch.outcomes = true;
12036        }
12037        // §5.9.7 B2: revocation deletes now-unauthorized blob bodies.
12038        self.delete_unreferenced_cached_blobs()?;
12039        Ok(true)
12040    }
12041
12042    /// §4.5 client application: apply one live-section or delta `COMMIT`
12043    /// with only the changes that match the persisted echo of a receiving
12044    /// unit; every applied change then goes through the version guard.
12045    /// Returns whether any change of the frame applied.
12046    fn apply_live_commit(
12047        &mut self,
12048        receivers: &[UnitRecord],
12049        tables: &[String],
12050        changes: Vec<ssp2::model::Change>,
12051        commit_seq: i64,
12052        source: AppliedServerCommitSource,
12053    ) -> Result<bool, TransportError> {
12054        let changes: Vec<ssp2::model::Change> = changes
12055            .into_iter()
12056            .filter(|change| {
12057                // An unknown table fails loud in the apply below.
12058                let Some(table) = tables
12059                    .get(change.table_index as usize)
12060                    .and_then(|name| self.schema.table(name))
12061                else {
12062                    return true;
12063                };
12064                receivers.iter().any(|unit| {
12065                    covers(table, &unit.scopes)
12066                        && pair_scopes(&unit.scopes, &table.name, unit.echo.as_deref()).is_some_and(
12067                            |scopes| {
12068                                scopes.iter().all(|(variable, values)| {
12069                                    change
12070                                        .scopes
12071                                        .iter()
12072                                        .find(|(key, _)| key == variable)
12073                                        .is_some_and(|(_, value)| values.contains(value))
12074                                })
12075                            },
12076                        )
12077                })
12078            })
12079            .collect();
12080        if changes.is_empty() {
12081            return Ok(false);
12082        }
12083        let affected_tables = changes
12084            .iter()
12085            .filter_map(|change| tables.get(change.table_index as usize))
12086            .cloned()
12087            .collect::<BTreeSet<_>>();
12088        let previous_batches = self.change_queue.len();
12089        self.apply_commit_frame(tables, &changes, commit_seq)?;
12090        if self.change_queue.len() > previous_batches {
12091            if let Some(batch) = self.change_queue.back_mut() {
12092                batch
12093                    .applied_commits
12094                    .extend(
12095                        affected_tables
12096                            .into_iter()
12097                            .map(|table| AppliedServerCommit {
12098                                table,
12099                                commit_seq,
12100                                source,
12101                            }),
12102                    );
12103            }
12104        }
12105        Ok(true)
12106    }
12107
12108    // Both pull and realtime frames use the same durable observation boundary.
12109    fn apply_commit_frame(
12110        &mut self,
12111        tables: &[String],
12112        changes: &[ssp2::model::Change],
12113        sequence: i64,
12114    ) -> Result<(), TransportError> {
12115        #[cfg(feature = "bench-internals")]
12116        let _phase = self.benchmark_phases.start(Phase::CommitApply);
12117        let rollback = self.capture();
12118        self.coalesce_unit(changes.len())
12119            .and_then(|()| self.begin_observation("syncular_commit"))
12120            .map_err(|message| TransportError::new("storage.failed", message))?;
12121        let applied = (|| {
12122            let mut batch = ChangeAccumulator::default();
12123            self.record_commit_changes(&mut batch, tables, changes);
12124            // §7.1 chained base: a change names the version an acknowledged own
12125            // commit wrote; pending upserts chained on it move to that version.
12126            for change in changes {
12127                let Some(table) = tables.get(change.table_index as usize) else {
12128                    continue;
12129                };
12130                let acknowledged = self
12131                    .conn
12132                    .prepare_cached("SELECT op_json FROM _syncular_acked_rows WHERE tbl=?1 AND id=?2 AND commit_seq=?3")
12133                    .and_then(|mut statement| {
12134                        statement
12135                            .query_map(rusqlite::params![table, change.row_id, sequence], |row| row.get::<_, String>(0))?
12136                            .collect::<Result<Vec<_>, _>>()
12137                    })
12138                    .map_err(|error| TransportError::new("storage.failed", Self::sqlite_failure(&self.storage_failure, error)))?
12139                    .iter()
12140                    .map(|op| serde_json::from_str::<CommitOperation>(op).map(OutboxOp::from))
12141                    .collect::<Result<Vec<_>, _>>()
12142                    .map_err(|_| TransportError::new("storage.failed", "sync.local_corrupt: invalid acknowledged operation".to_owned()))?;
12143                for index in 0..self.outbox.len() {
12144                    if !self.outbox[index]
12145                        .ops
12146                        .iter()
12147                        .any(|op| acknowledged.iter().any(|earlier| chains_on(earlier, op)))
12148                    {
12149                        continue;
12150                    }
12151                    let commit = Arc::make_mut(&mut self.outbox[index]);
12152                    for op in &mut commit.ops {
12153                        if acknowledged.iter().any(|earlier| chains_on(earlier, op)) {
12154                            op.base_version = Some(change.row_version);
12155                        }
12156                    }
12157                    let ops = serde_json::to_string(
12158                        &commit
12159                            .ops
12160                            .iter()
12161                            .map(CommitOperation::from)
12162                            .collect::<Vec<_>>(),
12163                    )
12164                    .map_err(|_| {
12165                        TransportError::new(
12166                            "storage.failed",
12167                            "sync.local_corrupt: unencodable outbox".to_owned(),
12168                        )
12169                    })?;
12170                    let id = commit.client_commit_id.clone();
12171                    self.conn
12172                        .execute(
12173                            "UPDATE _syncular_outbox SET ops_json=?1 WHERE commit_id=?2",
12174                            rusqlite::params![ops, id],
12175                        )
12176                        .map_err(|error| {
12177                            TransportError::new(
12178                                "storage.failed",
12179                                Self::sqlite_failure(&self.storage_failure, error),
12180                            )
12181                        })?;
12182                }
12183            }
12184            {
12185                let storage_failed = |error| {
12186                    TransportError::new(
12187                        "storage.failed",
12188                        Self::sqlite_failure(&self.storage_failure, error),
12189                    )
12190                };
12191                let pinned: HashSet<(&str, &str)> = self
12192                    .outbox
12193                    .iter()
12194                    .flat_map(|commit| &commit.ops)
12195                    .map(|op| (op.table.as_str(), op.row_id.as_str()))
12196                    .collect();
12197                for change in changes {
12198                    let table = tables.get(change.table_index as usize).ok_or_else(|| {
12199                        TransportError::new(
12200                            "sync.invalid_request",
12201                            "change tableIndex out of range".to_owned(),
12202                        )
12203                    })?;
12204                    if pinned.contains(&(table.as_str(), change.row_id.as_str())) {
12205                        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)")
12206                            .and_then(|mut statement| statement.execute(rusqlite::params![table, change.row_id, sequence]))
12207                            .map_err(storage_failed)?;
12208                    }
12209                    self.conn.prepare_cached("DELETE FROM _syncular_acked_rows WHERE tbl=?1 AND id=?2 AND commit_seq<=?3")
12210                        .and_then(|mut statement| statement.execute(rusqlite::params![table, change.row_id, sequence]))
12211                        .map_err(storage_failed)?;
12212                }
12213            }
12214            self.apply_commit_changes(tables, changes)?;
12215            self.rebuild_overlay_if_dirty()
12216                .map_err(|message| TransportError::new("storage.failed", message))?;
12217            self.finish_observation("syncular_commit", batch)
12218                .map_err(|message| TransportError::new("storage.failed", message))
12219        })();
12220        if applied.is_err() {
12221            self.rollback_observation("syncular_commit");
12222            self.restore(rollback);
12223        }
12224        applied
12225    }
12226
12227    fn apply_commit_changes(
12228        &mut self,
12229        tables: &[String],
12230        changes: &[ssp2::model::Change],
12231    ) -> Result<(), TransportError> {
12232        // A clean overlay can reconcile changed primary keys independently
12233        // when their tables have no secondary unique constraints. Such a
12234        // constraint can change whether another row's write succeeds, so a
12235        // table with one and any local intent takes the table rebuild.
12236        let changed_tables: BTreeSet<&str> = changes
12237            .iter()
12238            .filter_map(|change| tables.get(change.table_index as usize))
12239            .map(String::as_str)
12240            .collect();
12241        let mut mirror_visible = !self.overlay_dirty.get();
12242        for name in &changed_tables {
12243            if mirror_visible
12244                && self
12245                    .schema
12246                    .table(name)
12247                    .is_some_and(|table| table.indexes.iter().any(|index| index.unique))
12248            {
12249                let (pending, protected) = self
12250                    .table_intent(name)
12251                    .map_err(|message| TransportError::new("storage.failed", message))?;
12252                mirror_visible = !pending && !protected;
12253            }
12254        }
12255        for change in changes {
12256            let table_name = tables.get(change.table_index as usize).ok_or_else(|| {
12257                TransportError::new(
12258                    "sync.invalid_request",
12259                    "change tableIndex out of range".to_owned(),
12260                )
12261            })?;
12262            let table = self.schema.table(table_name).ok_or_else(|| {
12263                TransportError::new(
12264                    "sync.schema_mismatch",
12265                    format!("change targets unknown table {table_name:?}"),
12266                )
12267            })?;
12268            let landed = match change.op {
12269                Op::Upsert => {
12270                    let payload = change.row.as_ref().ok_or_else(|| {
12271                        TransportError::new(
12272                            "sync.invalid_request",
12273                            "upsert change without row payload".to_owned(),
12274                        )
12275                    })?;
12276                    // §5.11: decrypt encrypted columns on apply, or seal the row.
12277                    let (row, sealed) = {
12278                        #[cfg(feature = "bench-internals")]
12279                        let _phase = self.benchmark_phases.start(Phase::RowDecode);
12280                        // §5.11: a decrypt failure keeps its own identity.
12281                        decode_row_bytes(table, payload, &self.encryption)?
12282                    };
12283                    let table_name = table.name.clone();
12284                    // §4.5 version guard: only a newer upsert lands.
12285                    let landed = self
12286                        .write_base_row(&table_name, &row, change.row_version, sealed.as_ref())
12287                        .map_err(|m| TransportError::new("sync.invalid_request", m))?;
12288                    if mirror_visible && landed {
12289                        self.write_row(
12290                            &visible_table(&table_name),
12291                            &table_name,
12292                            &row,
12293                            change.row_version,
12294                            sealed.as_ref(),
12295                        )
12296                        .map_err(|m| TransportError::new("sync.invalid_request", m))?;
12297                    }
12298                    landed
12299                }
12300                // §4.5 version guard: a delete at or below the local version
12301                // is skipped, a delete of an absent row is a no-op.
12302                Op::Delete => self
12303                    .delete_base_row(table_name, &change.row_id, change.row_version)
12304                    .map_err(|m| TransportError::new("sync.invalid_request", m))?,
12305            };
12306            // The change dropped the row's acknowledged intent either way
12307            // (§7.1), so the overlay of a skipped change rebuilds from the
12308            // unchanged base.
12309            self.overlay_dirty.table(table_name);
12310            if mirror_visible && !(landed && change.op == Op::Upsert) {
12311                let predicate = row_id_predicate(table);
12312                let visible = visible_table(table_name);
12313                let mut statements = vec![format!("DELETE FROM {visible} WHERE {predicate}")];
12314                if !landed {
12315                    statements.push(format!(
12316                        "INSERT INTO {visible} SELECT * FROM {} WHERE {predicate}",
12317                        base_table(table_name)
12318                    ));
12319                }
12320                for statement in &statements {
12321                    self.conn
12322                        .prepare_cached(statement)
12323                        .and_then(|mut statement| {
12324                            statement.execute(rusqlite::params![change.row_id])
12325                        })
12326                        .map_err(|error| {
12327                            TransportError::new("sync.invalid_request", error.to_string())
12328                        })?;
12329                }
12330            }
12331        }
12332        if mirror_visible {
12333            let changed_rows: HashSet<(&str, &str)> = changes
12334                .iter()
12335                .map(|change| {
12336                    (
12337                        tables[change.table_index as usize].as_str(),
12338                        change.row_id.as_str(),
12339                    )
12340                })
12341                .collect();
12342            self.replay_overlay(&changed_tables, Some(&changed_rows))
12343                .map_err(|message| TransportError::new("storage.failed", message))?;
12344            self.overlay_dirty.set(false);
12345        }
12346        Ok(())
12347    }
12348
12349    /// §5.6 segment application: validate against the generated schema,
12350    /// clear the pair's scope on the table's first page (fail closed
12351    /// without a mapping), then upsert each row with its segment-carried
12352    /// server version under the §4.5 version guard (§5.2).
12353    fn apply_segment(
12354        &mut self,
12355        table: &TableSchema,
12356        segment: &RowsSegment,
12357        first_page: bool,
12358        effective: &[(String, Vec<String>)],
12359        unit_id: &str,
12360    ) -> Result<u32, SectionError> {
12361        // §5.2: the column table validates against the generated schema —
12362        // order, names, types, nullability; mismatch is fatal. §5.11: the
12363        // server sends the WIRE types (bytes for an encrypted column), so
12364        // validate against wire_columns.
12365        let column = if segment.columns.len() != table.wire_columns.len() {
12366            Some(Value::from("count"))
12367        } else {
12368            segment
12369                .columns
12370                .iter()
12371                .zip(table.wire_columns.iter())
12372                .position(|(a, b)| a.name != b.name || a.ty != b.ty || a.nullable != b.nullable)
12373                .map(Value::from)
12374        };
12375        if segment.table != table.name
12376            || segment.schema_version != self.schema.version
12377            || column.is_some()
12378        {
12379            let mut details = Map::new();
12380            details.insert("table".to_owned(), Value::from(table.name.as_str()));
12381            if let Some(column) = column {
12382                details.insert("column".to_owned(), column);
12383            }
12384            return Err(SectionError::Transport(TransportError {
12385                code: "sync.schema_mismatch".to_owned(),
12386                message: "rows segment columns do not match the generated schema (§5.2)".to_owned(),
12387                details: Some(Value::Object(details)),
12388            }));
12389        }
12390        let mut applied = 0u32;
12391        let (mut write, mut commit) = (std::time::Duration::ZERO, std::time::Duration::ZERO);
12392        let empty = Vec::new();
12393        let blocks = if segment.blocks.is_empty() {
12394            std::slice::from_ref(&empty)
12395        } else {
12396            &segment.blocks
12397        };
12398        for (index, block) in blocks.iter().enumerate() {
12399            let clear = first_page && index == 0;
12400            if !clear && block.is_empty() {
12401                continue;
12402            }
12403            let rollback = self.capture();
12404            let (pending, protected) = self
12405                .table_intent(&table.name)
12406                .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12407            let reconcile_pending =
12408                !protected && pending && table.indexes.iter().any(|index| index.unique);
12409            let mirror_visible = !protected && !reconcile_pending;
12410            self.coalesce_unit(block.len())
12411                .and_then(|()| self.begin_observation("syncular_segment_block"))
12412                .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12413            let started = std::time::Instant::now();
12414            let outcome = (|| {
12415                self.rebuild_overlay_if_dirty()
12416                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12417                let mut changed_keys = Vec::new();
12418                let mut batch = ChangeAccumulator::default();
12419                if clear && self.clear_scope(table, effective, unit_id)? || !block.is_empty() {
12420                    batch.table(&table.name);
12421                }
12422                for (row_index, row) in block.iter().enumerate() {
12423                    let decrypted;
12424                    let mut sealed = None;
12425                    let values = if table.has_encrypted_columns() {
12426                        let mut values = row.values.clone();
12427                        sealed = crate::values::decrypt_segment_row(
12428                            table,
12429                            &mut values,
12430                            &self.encryption,
12431                        )
12432                        .map_err(SectionError::Transport)?;
12433                        decrypted = values;
12434                        &decrypted
12435                    } else {
12436                        &row.values
12437                    };
12438                    if !self
12439                        .write_base_row(&table.name, values, row.server_version, sealed.as_ref())
12440                        .map_err(|message| {
12441                            SectionError::Abort("sync.invalid_request".into(), message)
12442                        })?
12443                    {
12444                        continue;
12445                    }
12446                    if reconcile_pending {
12447                        changed_keys.push(
12448                            owned_sql_value(RowParam::Cell(&values[table.pk_index])).map_err(
12449                                |message| SectionError::Abort("storage.failed".into(), message),
12450                            )?,
12451                        );
12452                    }
12453                    if mirror_visible {
12454                        self.write_row(
12455                            &visible_table(&table.name),
12456                            &table.name,
12457                            values,
12458                            row.server_version,
12459                            sealed.as_ref(),
12460                        )
12461                        .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12462                    }
12463                    let processed = u64::from(applied) + row_index as u64 + 1;
12464                    if processed.is_multiple_of(1024) {
12465                        self.progress.update(|p| p.rows_processed = processed);
12466                    }
12467                }
12468                self.reconcile_import(table, &mut changed_keys, protected, reconcile_pending)
12469                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12470                let written = std::time::Instant::now();
12471                self.finish_observation("syncular_segment_block", batch)
12472                    .map(|()| written)
12473                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))
12474            })();
12475            let written = match outcome {
12476                Ok(written) => written,
12477                Err(error) => {
12478                    self.rollback_observation("syncular_segment_block");
12479                    self.restore(rollback);
12480                    return Err(error);
12481                }
12482            };
12483            // §7.7: a payload reports its import cost.
12484            write += written - started;
12485            commit += written.elapsed();
12486            applied += block.len() as u32;
12487            self.progress.update(|p| {
12488                p.rows_processed = u64::from(applied);
12489                p.import_write_ms = u64::try_from(write.as_millis()).ok();
12490                p.import_commit_ms = u64::try_from(commit.as_millis()).ok();
12491            });
12492            std::thread::yield_now();
12493        }
12494        self.progress
12495            .update(|p| p.rows_processed = u64::from(applied));
12496        Ok(applied)
12497    }
12498
12499    /// §5.3 sqlite-image application: validate the in-file metadata
12500    /// against the descriptor, validate column names/order against the
12501    /// generated schema, run the §5.6 first-page clear when fresh, then
12502    /// replace-or-upsert every image row with its `_syncular_version`.
12503    /// Mechanics: the image lands in a temp file read through a second
12504    /// rusqlite connection, equivalent to ATTACH + INSERT…SELECT.
12505    /// Each image chunk commits its writes and revision before readers continue.
12506    #[allow(clippy::too_many_arguments)]
12507    fn apply_sqlite_segment(
12508        &mut self,
12509        table: &TableSchema,
12510        bytes: &[u8],
12511        first_page: bool,
12512        effective: &[(String, Vec<String>)],
12513        unit_id: &str,
12514        segment_id: &str,
12515        resumed: i64,
12516        row_count: i64,
12517        as_of_commit_seq: i64,
12518        scope_digest: &str,
12519    ) -> Result<u32, SectionError> {
12520        let invalid = |detail: &str| {
12521            SectionError::Abort(
12522                "sync.invalid_request".to_owned(),
12523                format!("sqlite segment rejected: {detail} (§5.3)"),
12524            )
12525        };
12526        // §5.11: an image bypasses the decrypt seam, so a server cannot serve
12527        // one for a table with encrypted columns.
12528        if table.has_encrypted_columns() {
12529            return Err(invalid("table has encrypted columns"));
12530        }
12531
12532        // The image lands beside the replica so it shares the replica's
12533        // directory permissions and volume; an in-memory replica has no
12534        // directory and uses the system temp dir. The file is owner-only.
12535        let directory = self
12536            .previous_version_replica_path()
12537            .and_then(|replica| std::path::Path::new(&replica).parent().map(Into::into))
12538            .unwrap_or_else(std::env::temp_dir);
12539        let path = directory.join(format!(".syncular-image-{}.tmp", uuid::Uuid::new_v4()));
12540        let outcome = (|| {
12541            let mut options = std::fs::OpenOptions::new();
12542            options.write(true).create_new(true);
12543            #[cfg(unix)]
12544            std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
12545            std::io::Write::write_all(
12546                &mut options
12547                    .open(&path)
12548                    .map_err(|_| invalid("image temp file write failed"))?,
12549                bytes,
12550            )
12551            .map_err(|_| invalid("image temp file write failed"))?;
12552            let img = rusqlite::Connection::open_with_flags(
12553                &path,
12554                rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
12555            )
12556            .map_err(|_| invalid("bytes do not open as a SQLite database"))?;
12557            self.apply_sqlite_image(
12558                &img,
12559                table,
12560                first_page,
12561                effective,
12562                unit_id,
12563                segment_id,
12564                resumed,
12565                row_count,
12566                as_of_commit_seq,
12567                scope_digest,
12568            )
12569        })();
12570        let _ = std::fs::remove_file(&path);
12571        outcome
12572    }
12573
12574    #[allow(clippy::too_many_arguments)]
12575    fn apply_sqlite_image(
12576        &mut self,
12577        img: &rusqlite::Connection,
12578        table: &crate::schema::TableSchema,
12579        first_fresh_page: bool,
12580        effective: &[(String, Vec<String>)],
12581        unit_id: &str,
12582        segment_id: &str,
12583        resumed: i64,
12584        row_count: i64,
12585        as_of_commit_seq: i64,
12586        scope_digest: &str,
12587    ) -> Result<u32, SectionError> {
12588        let invalid = |detail: String| {
12589            SectionError::Abort(
12590                "sync.invalid_request".to_owned(),
12591                format!("sqlite segment rejected: {detail} (§5.3)"),
12592            )
12593        };
12594
12595        // 1. Metadata vs descriptor + client state (§5.3 rule 2; exactly
12596        //    one row).
12597        type MetaRow = (i64, String, i64, i64, String, i64, i64);
12598        let meta: MetaRow = img
12599            .query_row(
12600                "SELECT format, \"table\", \"schemaVersion\", \"asOfCommitSeq\",
12601                        \"scopeDigest\", \"rowCount\",
12602                        (SELECT count(*) FROM _syncular_segment)
12603                 FROM _syncular_segment",
12604                [],
12605                |row| {
12606                    Ok((
12607                        row.get(0)?,
12608                        row.get(1)?,
12609                        row.get(2)?,
12610                        row.get(3)?,
12611                        row.get(4)?,
12612                        row.get(5)?,
12613                        row.get(6)?,
12614                    ))
12615                },
12616            )
12617            .map_err(|_| invalid("missing or unreadable _syncular_segment metadata".to_owned()))?;
12618        let (format, meta_table, schema_version, pin, digest, meta_rows, meta_count) = meta;
12619        if meta_count != 1 {
12620            return Err(invalid(format!(
12621                "_syncular_segment must contain exactly one row, found {meta_count}"
12622            )));
12623        }
12624        if format != 1 {
12625            return Err(invalid(format!("format {format}")));
12626        }
12627        if meta_table != table.name {
12628            return Err(invalid(format!("image table {meta_table:?}")));
12629        }
12630        if schema_version != i64::from(self.schema.version) {
12631            return Err(invalid(format!("schemaVersion {schema_version}")));
12632        }
12633        if pin != as_of_commit_seq {
12634            return Err(invalid(format!("asOfCommitSeq {pin}")));
12635        }
12636        if digest != scope_digest {
12637            return Err(invalid("scopeDigest mismatch".to_owned()));
12638        }
12639        if meta_rows != row_count {
12640            return Err(invalid(format!("rowCount {meta_rows}")));
12641        }
12642
12643        // 2. Column names and order vs the generated schema (§5.3 rule 3).
12644        let mut names: Vec<String> = Vec::new();
12645        let mut primary_keys: Vec<String> = Vec::new();
12646        {
12647            let mut stmt = img
12648                .prepare(&format!("PRAGMA table_info({})", quote_ident(&table.name)))
12649                .map_err(|_| invalid("image data table missing".to_owned()))?;
12650            let mut rows = stmt
12651                .query([])
12652                .map_err(|_| invalid("image data table unreadable".to_owned()))?;
12653            while let Some(row) = rows
12654                .next()
12655                .map_err(|_| invalid("image data table unreadable".to_owned()))?
12656            {
12657                if row
12658                    .get::<_, i64>(5)
12659                    .map_err(|error| invalid(Self::sqlite_failure(&self.storage_failure, error)))?
12660                    > 0
12661                {
12662                    primary_keys.push(row.get(1).map_err(|error| {
12663                        invalid(Self::sqlite_failure(&self.storage_failure, error))
12664                    })?);
12665                }
12666                names.push(
12667                    row.get::<_, String>(1)
12668                        .map_err(|_| invalid("image data table unreadable".to_owned()))?,
12669                );
12670            }
12671        }
12672        let mut expected: Vec<&str> = table.columns.iter().map(|c| c.name.as_str()).collect();
12673        expected.push("_syncular_version");
12674        if names.len() != expected.len() || names.iter().zip(expected.iter()).any(|(a, b)| a != b) {
12675            return Err(SectionError::Transport(TransportError {
12676                code: "sync.schema_mismatch".to_owned(),
12677                message: "sqlite segment columns do not match the generated schema (§5.3)"
12678                    .to_owned(),
12679                details: Some(serde_json::json!({ "table": table.name })),
12680            }));
12681        }
12682
12683        if primary_keys != vec![table.primary_key.clone()] {
12684            return Err(invalid(
12685                "image primary key does not match generated schema".into(),
12686            ));
12687        }
12688        let actual_count: i64 = img
12689            .query_row(
12690                &format!("SELECT count(*) FROM {}", quote_ident(&table.name)),
12691                [],
12692                |row| row.get(0),
12693            )
12694            .map_err(|error| invalid(Self::sqlite_failure(&self.storage_failure, error)))?;
12695        if actual_count != row_count {
12696            return Err(invalid("image row count does not match descriptor".into()));
12697        }
12698        let insert = self.insert_row_sql(&base_table(&table.name), table);
12699        let visible_insert = self.insert_row_sql(&visible_table(&table.name), table);
12700        let column_list = names
12701            .iter()
12702            .map(|n| quote_ident(n))
12703            .collect::<Vec<_>>()
12704            .join(", ");
12705        // §5.6: an earlier attempt at this position committed the first
12706        // `resumed` rows in primary-key order; the content address pins them.
12707        let mut stmt = img
12708            .prepare(&format!(
12709                "SELECT {column_list} FROM {} ORDER BY {} LIMIT -1 OFFSET ?1",
12710                quote_ident(&table.name),
12711                quote_ident(&table.primary_key)
12712            ))
12713            .map_err(|error| invalid(Self::sqlite_failure(&self.storage_failure, error)))?;
12714        let mut rows = stmt
12715            .query([resumed])
12716            .map_err(|error| invalid(Self::sqlite_failure(&self.storage_failure, error)))?;
12717        let resumed = u32::try_from(resumed)
12718            .ok()
12719            .filter(|rows| i64::from(*rows) <= actual_count)
12720            .ok_or_else(|| invalid("applied-segment record exceeds the image".into()))?;
12721        let mut applied = resumed;
12722        let carried = self.image_chunk_rows.get(&table.name).copied();
12723        let mut limit = if first_fresh_page {
12724            1024
12725        } else {
12726            carried.unwrap_or(1024)
12727        };
12728        let (mut write, mut commit) = (std::time::Duration::ZERO, std::time::Duration::ZERO);
12729        // Rows, write ms and per-row write ms of the chunk before.
12730        let mut model: Option<(u32, f64, Option<f64>)> = None;
12731        loop {
12732            let clear = applied == 0 && first_fresh_page;
12733            let rollback = self.capture();
12734            let (pending, protected) = self
12735                .table_intent(&table.name)
12736                .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12737            let reconcile_pending =
12738                !protected && pending && table.indexes.iter().any(|index| index.unique);
12739            let mirror_visible = !protected && !reconcile_pending;
12740            // §5.3: the first chunk of a table's first page holds 1,024 rows
12741            // and the next one the size the table's chunks reached before
12742            // (65,536 rows when none did); a later range image starts at that
12743            // size. A later chunk holds at least 1,024 rows, at most twice the
12744            // rows of the one before and at most 65,536. The second chunk of a
12745            // later range image holds twice the rows of the first. The two
12746            // latest chunks whose row counts differ by at least half the
12747            // smaller split write time into a per-row and a fixed part; while
12748            // sizes repeat, the last split's per-row time holds. A later chunk
12749            // then holds the rows whose per-row time fills the larger of
12750            // 250 ms, the time from the end of the writes of the chunk before
12751            // through its COMMIT, and the fixed part. A chunk that replays
12752            // local writes holds at most 1,024.
12753            let chunk = if pending || protected {
12754                limit.min(1024)
12755            } else {
12756                limit
12757            };
12758            self.coalesce_unit(chunk as usize)
12759                .and_then(|()| self.begin_observation("syncular_image_chunk"))
12760                .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12761            let started = std::time::Instant::now();
12762            let result = (|| {
12763                self.rebuild_overlay_if_dirty()
12764                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12765                let mut changed_keys = Vec::new();
12766                let mut batch = ChangeAccumulator::default();
12767                if clear && self.clear_scope(table, effective, unit_id)? {
12768                    batch.table(&table.name);
12769                }
12770                let mut processed = 0u32;
12771                {
12772                    let mut ins = self.conn.prepare_cached(&insert).map_err(|error| {
12773                        invalid(Self::sqlite_failure(&self.storage_failure, error))
12774                    })?;
12775                    let mut mirror = if mirror_visible {
12776                        Some(self.conn.prepare_cached(&visible_insert).map_err(|error| {
12777                            invalid(Self::sqlite_failure(&self.storage_failure, error))
12778                        })?)
12779                    } else {
12780                        None
12781                    };
12782                    for _ in 0..chunk {
12783                        let Some(row) = rows.next().map_err(|error| {
12784                            invalid(Self::sqlite_failure(&self.storage_failure, error))
12785                        })?
12786                        else {
12787                            break;
12788                        };
12789                        for (i, column) in table.columns.iter().enumerate() {
12790                            let cell = row.get_ref(i).map_err(|error| {
12791                                invalid(Self::sqlite_failure(&self.storage_failure, error))
12792                            })?;
12793                            let param = image_cell_param(column, cell).map_err(invalid)?;
12794                            ins.raw_bind_parameter(i + 1, &param).map_err(|error| {
12795                                invalid(Self::sqlite_failure(&self.storage_failure, error))
12796                            })?;
12797                            if let Some(mirror) = &mut mirror {
12798                                mirror.raw_bind_parameter(i + 1, &param).map_err(|error| {
12799                                    invalid(Self::sqlite_failure(&self.storage_failure, error))
12800                                })?;
12801                            }
12802                        }
12803                        let version_index = table.columns.len();
12804                        let version: i64 = row.get(version_index).map_err(|error| {
12805                            invalid(Self::sqlite_failure(&self.storage_failure, error))
12806                        })?;
12807                        if version < 1 {
12808                            return Err(invalid("image row version must be positive".into()));
12809                        }
12810                        ins.raw_bind_parameter(version_index + 1, version)
12811                            .map_err(|error| {
12812                                invalid(Self::sqlite_failure(&self.storage_failure, error))
12813                            })?;
12814                        // §4.5 version guard: the base upsert decides.
12815                        let landed = ins.raw_execute().map_err(|error| {
12816                            invalid(Self::sqlite_failure(&self.storage_failure, error))
12817                        })? > 0;
12818                        processed += 1;
12819                        if processed.is_multiple_of(1024) && processed < chunk {
12820                            self.progress
12821                                .update(|p| p.rows_processed = u64::from(applied + processed));
12822                        }
12823                        if !landed {
12824                            continue;
12825                        }
12826                        if let Some(mirror) = &mut mirror {
12827                            mirror
12828                                .raw_bind_parameter(version_index + 1, version)
12829                                .map_err(|error| {
12830                                    invalid(Self::sqlite_failure(&self.storage_failure, error))
12831                                })?;
12832                            mirror.raw_execute().map_err(|error| {
12833                                invalid(Self::sqlite_failure(&self.storage_failure, error))
12834                            })?;
12835                        }
12836                        if reconcile_pending {
12837                            changed_keys.push(row.get::<_, SqlValue>(table.pk_index).map_err(
12838                                |error| invalid(Self::sqlite_failure(&self.storage_failure, error)),
12839                            )?);
12840                        }
12841                    }
12842                }
12843                if processed > 0 {
12844                    batch.table(&table.name);
12845                    self.overlay_dirty.table(&table.name);
12846                }
12847                self.stored(record_applied_rows(
12848                    &self.conn,
12849                    unit_id,
12850                    segment_id,
12851                    i64::from(applied + processed),
12852                ))
12853                .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12854                self.reconcile_import(table, &mut changed_keys, protected, reconcile_pending)
12855                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12856                let written = std::time::Instant::now();
12857                self.finish_observation("syncular_image_chunk", batch)
12858                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12859                Ok((processed, written))
12860            })();
12861            let (processed, written) = match result {
12862                Ok(done) => done,
12863                Err(error) => {
12864                    self.rollback_observation("syncular_image_chunk");
12865                    self.restore(rollback);
12866                    return Err(error);
12867                }
12868            };
12869            // The chunk commits before the yield, also inside a coalesced apply.
12870            let coalesced = self.coalesced.is_some();
12871            if coalesced {
12872                self.commit_coalesced_apply()
12873                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12874            }
12875            let spent = (written - started, written.elapsed());
12876            #[cfg(test)]
12877            let spent = self
12878                .image_chunk_ms
12879                .get()
12880                .map_or(spent, |(fixed, row, commit)| {
12881                    (
12882                        std::time::Duration::from_secs_f64(
12883                            (fixed + row * f64::from(processed)) / 1000.0,
12884                        ),
12885                        std::time::Duration::from_secs_f64(commit / 1000.0),
12886                    )
12887                });
12888            write += spent.0;
12889            commit += spent.1;
12890            applied += processed;
12891            let last = processed < chunk || i64::from(applied) == actual_count;
12892            // A file replica's WAL keeps its high-water size until truncated.
12893            if last && self.conn.is_autocommit() {
12894                self.conn
12895                    .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
12896                    .map_err(|error| invalid(Self::sqlite_failure(&self.storage_failure, error)))?;
12897            }
12898            if coalesced {
12899                self.begin_coalesced_apply()
12900                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12901            }
12902            self.progress.update(|p| {
12903                p.rows_processed = u64::from(applied);
12904                p.import_write_ms = u64::try_from(write.as_millis()).ok();
12905                p.import_commit_ms = u64::try_from(commit.as_millis()).ok();
12906            });
12907            let write_ms = spent.0.as_secs_f64() * 1000.0;
12908            let per_row = match model {
12909                Some((rows, before, _)) if 2 * processed.abs_diff(rows) >= processed.min(rows) => {
12910                    Some((write_ms - before) / (f64::from(processed) - f64::from(rows)))
12911                }
12912                Some((_, _, per_row)) => per_row,
12913                None => None,
12914            };
12915            model = Some((processed, write_ms, per_row));
12916            let fixed = (write_ms - per_row.unwrap_or(0.0) * f64::from(processed)).max(0.0);
12917            let budget = (spent.1.as_secs_f64() * 1000.0).max(250.0).max(fixed);
12918            std::thread::yield_now();
12919            if last {
12920                break;
12921            }
12922            // Without a positive per-row time the chunk doubles.
12923            limit = if clear {
12924                carried.unwrap_or(65_536)
12925            } else {
12926                (processed * 2)
12927                    .min(65_536)
12928                    .min(match per_row {
12929                        Some(per_row) if per_row > 0.0 => (budget / per_row) as u32,
12930                        _ => u32::MAX,
12931                    })
12932                    .max(1024)
12933            };
12934            self.image_chunk_rows.insert(table.name.clone(), limit);
12935        }
12936        if i64::from(applied) != actual_count {
12937            return Err(invalid(format!(
12938                "image yielded {applied} rows, expected {actual_count}"
12939            )));
12940        }
12941        Ok(applied - resumed)
12942    }
12943
12944    /// §7.1 keyed reconciliation of the rows `drained` commits touch: restore
12945    /// them from the base and replay their remaining intent. A table with a
12946    /// secondary unique index restores and replays every row with intent,
12947    /// since one row's value can admit or defer another row's write.
12948    fn reconcile_rows(&self, drained: &[Arc<OutboxCommit>]) -> Result<(), String> {
12949        let names: BTreeSet<&str> = drained
12950            .iter()
12951            .flat_map(|commit| &commit.ops)
12952            .map(|op| op.table.as_str())
12953            .collect();
12954        for name in names {
12955            let Some(table) = self.schema.table(name) else {
12956                continue;
12957            };
12958            let ops = drained.iter().flat_map(|commit| &commit.ops);
12959            let tables = BTreeSet::from([name]);
12960            let rows: HashSet<_> = ops
12961                .clone()
12962                .map(|op| (op.table.as_str(), op.row_id.as_str()))
12963                .collect();
12964            let unique = table.indexes.iter().any(|index| index.unique);
12965            let acknowledged = if unique {
12966                self.acknowledged_operations(None, Some(&tables))?
12967            } else {
12968                Vec::new()
12969            };
12970            let peers = acknowledged
12971                .iter()
12972                .chain(
12973                    self.failed_commits
12974                        .iter()
12975                        .flat_map(|(commit, _)| &commit.ops),
12976                )
12977                .chain(self.outbox.iter().flat_map(|commit| &commit.ops))
12978                .filter(|_| unique);
12979            self.restore_base_rows(table, &mut Vec::new(), peers.chain(ops.clone()))?;
12980            self.replay_overlay(&tables, (!unique).then_some(&rows))?;
12981        }
12982        Ok(())
12983    }
12984
12985    /// Whether `table` has pending outbox intent, and whether it has protected
12986    /// (acknowledged or retained failed) intent.
12987    fn table_intent(&self, table: &str) -> Result<(bool, bool), String> {
12988        let touches = |op: &OutboxOp| op.table == table;
12989        Ok((
12990            self.outbox
12991                .iter()
12992                .flat_map(|commit| &commit.ops)
12993                .any(touches),
12994            self.failed_commits
12995                .iter()
12996                .flat_map(|(commit, _)| &commit.ops)
12997                .any(touches)
12998                || self
12999                    .conn
13000                    .query_row(
13001                        "SELECT EXISTS(SELECT 1 FROM _syncular_acked_rows WHERE tbl=?1)",
13002                        [table],
13003                        |row| row.get(0),
13004                    )
13005                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?,
13006        ))
13007    }
13008
13009    /// §7.1 reconciliation after an import block or chunk. Keyed replay covers
13010    /// only pending intent, so a table with protected intent rebuilds; a
13011    /// `restore` restores the imported `keys` and every pending row first.
13012    fn reconcile_import(
13013        &mut self,
13014        table: &TableSchema,
13015        keys: &mut Vec<SqlValue>,
13016        protected: bool,
13017        restore: bool,
13018    ) -> Result<(), String> {
13019        if protected {
13020            return self.rebuild_overlay_if_dirty();
13021        }
13022        let pending = self.outbox.iter().flat_map(|commit| &commit.ops);
13023        if restore {
13024            self.restore_base_rows(table, keys, pending.clone())?;
13025        }
13026        self.apply_outbox_ops(pending.filter(|op| op.table == table.name))?;
13027        self.overlay_dirty.set(false);
13028        Ok(())
13029    }
13030
13031    /// Restore the visible rows of `keys` and of the rows `ops` touch in
13032    /// `table` from the base before the caller replays their intent. The
13033    /// caller owns the transaction and publishes its revision after replay.
13034    fn restore_base_rows<'a>(
13035        &self,
13036        table: &TableSchema,
13037        keys: &mut Vec<SqlValue>,
13038        ops: impl IntoIterator<Item = &'a OutboxOp>,
13039    ) -> Result<(), String> {
13040        let visible = visible_table(&table.name);
13041        let base = base_table(&table.name);
13042        let pk = quote_ident(&table.primary_key);
13043        let predicate = row_id_predicate(table);
13044        let mut lookup = self.conn.prepare_cached(&format!(
13045            "SELECT {pk} FROM {base} WHERE {predicate} UNION SELECT {pk} FROM {visible} WHERE {predicate}"
13046        )).map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13047        let mut deleted = HashSet::new();
13048        for op in ops.into_iter().filter(|op| op.table == table.name) {
13049            if op.upsert {
13050                if let Some(values) = &op.values {
13051                    let key = json_to_column_value(
13052                        &table.columns[table.pk_index],
13053                        values.get(&table.primary_key),
13054                    )?;
13055                    keys.push(owned_sql_value(RowParam::Cell(&key))?);
13056                }
13057            } else if deleted.insert(&op.row_id) {
13058                keys.extend(
13059                    lookup
13060                        .query_map([&op.row_id], |row| row.get::<_, SqlValue>(0))
13061                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
13062                        .collect::<Result<Vec<_>, _>>()
13063                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?,
13064                );
13065            }
13066        }
13067        // Delete the complete affected set before restoring any base value, so
13068        // old optimistic unique values cannot collide with the new server rows.
13069        for chunk in keys.chunks(400) {
13070            let holes = vec!["?"; chunk.len()].join(",");
13071            self.conn
13072                .prepare_cached(&format!("DELETE FROM {visible} WHERE {pk} IN ({holes})"))
13073                .and_then(|mut statement| statement.execute(rusqlite::params_from_iter(chunk)))
13074                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13075        }
13076        let updates = table
13077            .columns
13078            .iter()
13079            .map(|column| column.name.as_str())
13080            .chain(std::iter::once("_syncular_version"))
13081            .chain(table.sealed_columns().iter().copied())
13082            .filter(|name| *name != table.primary_key)
13083            .map(|name| {
13084                let name = quote_ident(name);
13085                format!("{name}=excluded.{name}")
13086            })
13087            .collect::<Vec<_>>()
13088            .join(",");
13089        for chunk in keys.chunks(400) {
13090            let holes = vec!["?"; chunk.len()].join(",");
13091            self.conn.prepare_cached(&format!("INSERT INTO {visible} SELECT * FROM {base} WHERE {pk} IN ({holes}) ON CONFLICT ({pk}) DO UPDATE SET {updates}"))
13092                .and_then(|mut statement| statement.execute(rusqlite::params_from_iter(chunk)))
13093                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13094        }
13095        Ok(())
13096    }
13097
13098    // -- application-authorized local purge ---------------------------------------
13099
13100    fn compile_local_data_purge(
13101        &self,
13102        input: &LocalDataPurgeInput,
13103    ) -> Result<CompiledLocalDataPurge, String> {
13104        let invalid = |message: String| format!("sync.invalid_request: {message}");
13105        if input.purge_id.is_empty()
13106            || input.purge_id.len() > 128
13107            || !is_local_operation_code_like(&input.purge_id)
13108        {
13109            return Err(invalid(
13110                "local purge purgeId must be a 1–128 character code-like identifier".to_owned(),
13111            ));
13112        }
13113        if input.targets.is_empty() || input.targets.len() > MAX_LOCAL_PURGE_TARGETS {
13114            return Err(invalid(format!(
13115                "local purge needs between 1 and {MAX_LOCAL_PURGE_TARGETS} targets"
13116            )));
13117        }
13118
13119        let mut deduplicated: BTreeMap<
13120            String,
13121            (CompiledLocalDataPurgeTarget, LocalDataPurgeTarget),
13122        > = BTreeMap::new();
13123        let mut projections = BTreeSet::new();
13124        for target in &input.targets {
13125            let (table_name, raw_selectors) = match target {
13126                LocalDataPurgeTarget::Table { table, selectors } => (table, selectors),
13127                LocalDataPurgeTarget::Projection { projection } => {
13128                    projections.insert(projection.clone());
13129                    continue;
13130                }
13131            };
13132            let table = self.schema.table(table_name).ok_or_else(|| {
13133                invalid(format!("local purge names unknown table {:?}", table_name))
13134            })?;
13135            if raw_selectors.is_empty() || raw_selectors.len() > MAX_LOCAL_PURGE_SELECTORS {
13136                return Err(invalid(format!(
13137                    "local purge target {:?} needs between 1 and {MAX_LOCAL_PURGE_SELECTORS} selectors",
13138                    table_name
13139                )));
13140            }
13141            let mut selectors = Vec::with_capacity(raw_selectors.len());
13142            let mut canonical_selectors = BTreeMap::new();
13143            for (column_name, raw_values) in raw_selectors {
13144                let Some((column_index, column)) = table
13145                    .columns
13146                    .iter()
13147                    .enumerate()
13148                    .find(|(_, column)| column.name == *column_name)
13149                else {
13150                    return Err(invalid(format!(
13151                        "local purge target {:?} names unknown column {:?}",
13152                        table_name, column_name
13153                    )));
13154                };
13155                let encrypted = table
13156                    .encrypted_columns
13157                    .iter()
13158                    .any(|candidate| candidate.index == column_index);
13159                if column.ty != ColumnType::String || encrypted {
13160                    return Err(invalid(format!(
13161                        "local purge selector {:?}.{:?} must be a plaintext string column",
13162                        table_name, column_name
13163                    )));
13164                }
13165                if raw_values.is_empty() || raw_values.len() > MAX_LOCAL_PURGE_VALUES {
13166                    return Err(invalid(format!(
13167                        "local purge selector {:?}.{:?} needs between 1 and {MAX_LOCAL_PURGE_VALUES} values",
13168                        table_name, column_name
13169                    )));
13170                }
13171                let mut values = raw_values.clone();
13172                values.sort();
13173                values.dedup();
13174                if values.iter().any(|value| {
13175                    value.is_empty()
13176                        || value.len() > MAX_LOCAL_PURGE_VALUE_LENGTH
13177                        || !is_local_operation_code_like(value)
13178                }) {
13179                    return Err(invalid(format!(
13180                        "local purge selector values must be 1–{MAX_LOCAL_PURGE_VALUE_LENGTH} character code-like identifiers"
13181                    )));
13182                }
13183                selectors.push((column_name.clone(), values.clone()));
13184                canonical_selectors.insert(column_name.clone(), values);
13185            }
13186            let canonical = LocalDataPurgeTarget::Table {
13187                table: table_name.clone(),
13188                selectors: canonical_selectors,
13189            };
13190            let key = serde_json::to_string(&canonical).map_err(|error| error.to_string())?;
13191            deduplicated.insert(
13192                key,
13193                (
13194                    CompiledLocalDataPurgeTarget {
13195                        table: table_name.clone(),
13196                        selectors,
13197                    },
13198                    canonical,
13199                ),
13200            );
13201        }
13202        let (targets, mut canonical): (Vec<_>, Vec<_>) = deduplicated.into_values().unzip();
13203        canonical.extend(
13204            projections
13205                .iter()
13206                .map(|name| LocalDataPurgeTarget::Projection {
13207                    projection: name.clone(),
13208                }),
13209        );
13210        let canonical_plan =
13211            serde_json::to_string(&canonical).map_err(|error| error.to_string())?;
13212        Ok(CompiledLocalDataPurge {
13213            targets,
13214            projections,
13215            canonical_plan,
13216        })
13217    }
13218
13219    fn local_purge_base_row_ids(
13220        &self,
13221        targets: &[CompiledLocalDataPurgeTarget],
13222    ) -> Result<BTreeMap<String, BTreeSet<String>>, String> {
13223        let mut by_table: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
13224        for target in targets {
13225            let table = self
13226                .schema
13227                .table(&target.table)
13228                .ok_or_else(|| format!("sync.invalid_request: unknown table {:?}", target.table))?;
13229            let mut clauses = Vec::with_capacity(target.selectors.len());
13230            let mut params = Vec::new();
13231            for (column, values) in &target.selectors {
13232                clauses.push(format!(
13233                    "{} IN ({})",
13234                    quote_ident(column),
13235                    values.iter().map(|_| "?").collect::<Vec<_>>().join(", ")
13236                ));
13237                params.extend(values.iter().cloned().map(SqlValue::Text));
13238            }
13239            let sql = format!(
13240                "SELECT CAST({} AS TEXT) FROM {} WHERE {}",
13241                quote_ident(&table.primary_key),
13242                base_table(&target.table),
13243                clauses.join(" AND ")
13244            );
13245            let mut statement = self
13246                .conn
13247                .prepare(&sql)
13248                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13249            let rows = statement
13250                .query_map(rusqlite::params_from_iter(params), |row| {
13251                    let value = sql_ref_to_json(&table.columns[table.pk_index], row.get_ref(0)?);
13252                    render_row_id_json(Some(&value))
13253                        .map_err(|message| rusqlite::Error::ToSqlConversionFailure(message.into()))
13254                })
13255                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13256            let ids = by_table.entry(target.table.clone()).or_default();
13257            for row in rows {
13258                ids.insert(
13259                    row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?,
13260                );
13261            }
13262        }
13263        Ok(by_table)
13264    }
13265
13266    fn local_purge_values_match(
13267        target: &CompiledLocalDataPurgeTarget,
13268        values: &Map<String, Value>,
13269    ) -> bool {
13270        target.selectors.iter().all(|(column, allowed)| {
13271            values
13272                .get(column)
13273                .and_then(Value::as_str)
13274                .is_some_and(|value| allowed.iter().any(|candidate| candidate == value))
13275        })
13276    }
13277
13278    /// Apply one host-authorized local security purge. The host MUST gate the
13279    /// corresponding subscriptions first; this primitive owns local SQLite
13280    /// cleanup and never grants/revokes server authority by itself.
13281    pub fn purge_local_data(
13282        &mut self,
13283        input: &LocalDataPurgeInput,
13284    ) -> Result<LocalDataPurgeResult, ClientError> {
13285        let CompiledLocalDataPurge {
13286            targets,
13287            projections,
13288            canonical_plan,
13289        } = self.compile_local_data_purge(input)?;
13290        for name in &projections {
13291            self.lookup_projection(name)?;
13292        }
13293        let meta_key = format!("localPurge:{}", input.purge_id);
13294        let applied_plan = self
13295            .conn
13296            .query_row(
13297                "SELECT value FROM _syncular_meta WHERE key = ?1",
13298                rusqlite::params![meta_key],
13299                |row| row.get::<_, String>(0),
13300            )
13301            .optional()
13302            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13303        if let Some(applied_plan) = applied_plan {
13304            if applied_plan != canonical_plan {
13305                return Err(format!(
13306                    "sync.invalid_request: local purge id {:?} was already used with a different plan",
13307                    input.purge_id
13308                ).into());
13309            }
13310            // A retry after an unfinished rewrite finishes it.
13311            self.require_previous_version_gone()?;
13312            self.erase_purged_pages(&meta_key)?;
13313            return Ok(LocalDataPurgeResult {
13314                already_applied: true,
13315                purged_rows: 0,
13316                dropped_commits: 0,
13317            });
13318        }
13319
13320        // RFC 0005 D7: the container file cannot be a purge target (its name is
13321        // not in the running schema), so purge drops it as a fixed step, before
13322        // any mirror row is touched and unconditionally.
13323        let _ = self.drop_previous_version();
13324
13325        let rollback = self.capture();
13326        self.begin_observation("syncular_local_purge")?;
13327        let applied = (|| -> Result<(ChangeAccumulator, LocalDataPurgeResult), String> {
13328            let mut batch = ChangeAccumulator::default();
13329            let mut purged_rows = 0;
13330            for name in &projections {
13331                purged_rows += self.clear_projection(name, None)?;
13332                batch.table(name);
13333            }
13334            if targets.is_empty() {
13335                self.set_meta(&meta_key, &canonical_plan)?;
13336                return Ok((batch, LocalDataPurgeResult { already_applied: false, purged_rows, dropped_commits: 0 }));
13337            }
13338            let row_ids = self.local_purge_base_row_ids(&targets)?;
13339            let retained_dropped = self.drop_failed_commits(|table, values| {
13340                targets.iter().any(|target| {
13341                    target.table == table && Self::local_purge_values_match(target, values)
13342                })
13343            })?;
13344            let doomed = self
13345                .outbox
13346                .iter()
13347                .filter(|commit| {
13348                    commit.ops.iter().any(|operation| {
13349                        let matching_targets = targets
13350                            .iter()
13351                            .filter(|target| target.table == operation.table)
13352                            .collect::<Vec<_>>();
13353                        if matching_targets.is_empty() {
13354                            return false;
13355                        }
13356                        if row_ids
13357                            .get(&operation.table)
13358                            .is_some_and(|ids| ids.contains(&operation.row_id))
13359                        {
13360                            return true;
13361                        }
13362                        operation.values.as_ref().is_some_and(|values| {
13363                            matching_targets
13364                                .iter()
13365                                .any(|target| Self::local_purge_values_match(target, values))
13366                        })
13367                    })
13368                })
13369                .cloned()
13370                .collect::<Vec<_>>();
13371            let doomed_ids = doomed
13372                .iter()
13373                .map(|commit| commit.client_commit_id.clone())
13374                .collect::<BTreeSet<_>>();
13375            for commit in &retained_dropped {
13376                batch.conflicts = true;
13377                batch.rejections = true;
13378                batch.outcomes = true;
13379                for operation in &commit.ops {
13380                    batch.table(&operation.table);
13381                }
13382            }
13383            let mut rejections = Vec::new();
13384            // §5.11 purge erasure: the journal keeps a dropped commit's identity and
13385            // codes, never its operations, so no purged value survives in it.
13386            for commit in &doomed {
13387                for operation in &commit.ops {
13388                    batch.table(&operation.table);
13389                    self.overlay_dirty.table(&operation.table);
13390                }
13391                let results = (0..commit.ops.len())
13392                    .map(|op_index| {
13393                        let rejection = RejectionRecord {
13394                            client_commit_id: commit.client_commit_id.clone(),
13395                            op_index: op_index as i32,
13396                            code: "client.local_data_purged".to_owned(),
13397                            message: "the commit was dropped by an application-authorized local data purge".to_owned(),
13398                            retryable: false,
13399                            details: None,
13400                            operation: None,
13401                        };
13402                        rejections.push(rejection.clone());
13403                        CommitOperationOutcome::Error { rejection }
13404                    })
13405                    .collect::<Vec<_>>();
13406                self.persist_commit_outcome(
13407                    &commit.client_commit_id,
13408                    CommitOutcomeStatus::Rejected,
13409                    &results,
13410                    None,
13411                )?;
13412                self.leave_through(&commit.client_commit_id);
13413                self.delete_outbox_persisted(&commit.client_commit_id)?;
13414            }
13415            if !doomed.is_empty() {
13416                self.outbox
13417                    .retain(|commit| !doomed_ids.contains(&commit.client_commit_id));
13418                self.rejections.extend(rejections);
13419                self.prune_commit_outcomes()?;
13420                batch.status = true;
13421                batch.rejections = true;
13422                batch.outcomes = true;
13423            }
13424
13425            // §7.3.4: a unit whose cursor claims a purged row catches up from
13426            // -1, the §3.3 rule for rows a purge removed (§4.5 C1).
13427            for unit in self.stored(load_units(&self.conn))? {
13428                if unit.status != UnitStatus::Active
13429                    || (unit.cursor == Some(-1) && unit.bootstrap_state.is_none())
13430                {
13431                    continue;
13432                }
13433                let mut holds = false;
13434                for target in &targets {
13435                    let Some(table) = self.schema.table(&target.table) else {
13436                        continue;
13437                    };
13438                    let Some((scope, scope_params)) = covers(table, &unit.scopes)
13439                        .then(|| pair_scopes(&unit.scopes, &table.name, unit.echo.as_deref()))
13440                        .flatten()
13441                        .and_then(|effective| local_scope_predicate(table, &effective, &[]).ok().flatten())
13442                    else {
13443                        continue;
13444                    };
13445                    let clauses = target
13446                        .selectors
13447                        .iter()
13448                        .map(|(column, values)| {
13449                            format!("{} IN ({})", quote_ident(column), vec!["?"; values.len()].join(", "))
13450                        })
13451                        .collect::<Vec<_>>()
13452                        .join(" AND ");
13453                    let params = target
13454                        .selectors
13455                        .iter()
13456                        .flat_map(|(_, values)| values.iter().cloned().map(SqlValue::Text))
13457                        .chain(scope_params);
13458                    holds = self
13459                        .conn
13460                        .query_row(
13461                            &format!(
13462                                "SELECT 1 FROM {} WHERE {clauses} AND {scope} LIMIT 1",
13463                                base_table(&target.table)
13464                            ),
13465                            rusqlite::params_from_iter(params),
13466                            |_| Ok(()),
13467                        )
13468                        .optional()
13469                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
13470                        .is_some();
13471                    if holds {
13472                        break;
13473                    }
13474                }
13475                if holds {
13476                    self.record_unit_windows(&mut batch, &unit)?;
13477                    batch.status = true;
13478                    self.stored(save_unit(
13479                        &self.conn,
13480                        &UnitRecord {
13481                            cursor: Some(-1),
13482                            bootstrap_state: None,
13483                            seeded: Vec::new(),
13484                            restriction: None,
13485                            ..unit
13486                        },
13487                    ))?;
13488                }
13489            }
13490
13491            for (table, ids) in &row_ids {
13492                if ids.is_empty() {
13493                    continue;
13494                }
13495                batch.table(table);
13496                self.overlay_dirty.table(table);
13497                for row_id in ids {
13498                    self.delete_base_row(table, row_id, i64::MAX)?;
13499                    purged_rows += 1;
13500                }
13501            }
13502            // §5.11 purge erasure: a journaled outcome with an operation or
13503            // conflict row the purge reaches keeps its identity, status, ids
13504            // and codes only.
13505            let touches = |table: &str, row_id: &str, values: Option<&Map<String, Value>>| {
13506                targets.iter().any(|target| {
13507                    target.table == table
13508                        && (row_ids.get(table).is_some_and(|ids| ids.contains(row_id))
13509                            || values.is_some_and(|values| {
13510                                Self::local_purge_values_match(target, values)
13511                            }))
13512                })
13513            };
13514            let entries = self
13515                .conn
13516                .prepare("SELECT client_commit_id, results_json, operations_json FROM _syncular_commit_outcomes")
13517                .and_then(|mut statement| {
13518                    statement
13519                        .query_map([], |row| {
13520                            Ok((
13521                                row.get::<_, String>(0)?,
13522                                row.get::<_, String>(1)?,
13523                                row.get::<_, Option<String>>(2)?,
13524                            ))
13525                        })?
13526                        .collect::<Result<Vec<_>, _>>()
13527                })
13528                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13529            for (client_commit_id, results_json, operations_json) in entries {
13530                let corrupt = |_| "sync.local_corrupt: persisted commit outcome is invalid".to_owned();
13531                let mut results: Vec<CommitOperationOutcome> =
13532                    serde_json::from_str(&results_json).map_err(corrupt)?;
13533                let operations: Vec<CommitOperation> = operations_json
13534                    .map(|json| serde_json::from_str(&json))
13535                    .transpose()
13536                    .map_err(corrupt)?
13537                    .unwrap_or_default();
13538                let named = operations
13539                    .iter()
13540                    .chain(results.iter().filter_map(|result| match result {
13541                        CommitOperationOutcome::Conflict { conflict } => conflict.operation.as_ref(),
13542                        CommitOperationOutcome::Error { rejection } => rejection.operation.as_ref(),
13543                        CommitOperationOutcome::Applied { .. } => None,
13544                    }))
13545                    .any(|operation| touches(&operation.table, &operation.row_id, operation.values.as_ref()))
13546                    || results.iter().any(|result| {
13547                        matches!(result, CommitOperationOutcome::Conflict { conflict }
13548                            if touches(&conflict.table, &conflict.row_id, Some(&conflict.server_row)))
13549                    });
13550                if !named {
13551                    continue;
13552                }
13553                for result in &mut results {
13554                    match result {
13555                        CommitOperationOutcome::Conflict { conflict } => {
13556                            conflict.server_row = Map::new();
13557                            conflict.conflict_columns.clear();
13558                            conflict.operation = None;
13559                        }
13560                        CommitOperationOutcome::Error { rejection } => {
13561                            rejection.details = None;
13562                            rejection.operation = None;
13563                        }
13564                        CommitOperationOutcome::Applied { .. } => {}
13565                    }
13566                }
13567                let results_json = serde_json::to_string(&results).map_err(|error| error.to_string())?;
13568                self.conn
13569                    .execute(
13570                        "UPDATE _syncular_commit_outcomes SET results_json = ?1, operations_json = NULL WHERE client_commit_id = ?2",
13571                        rusqlite::params![results_json, client_commit_id],
13572                    )
13573                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13574                batch.outcomes = true;
13575            }
13576            self.rebuild_overlay_if_dirty()?;
13577            self.delete_unreferenced_cached_blobs()?;
13578            self.conn
13579                .execute(
13580                    "INSERT INTO _syncular_meta(key, value) VALUES (?1, ?2)",
13581                    rusqlite::params![meta_key, canonical_plan],
13582                )
13583                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13584            Ok((
13585                batch,
13586                LocalDataPurgeResult {
13587                    already_applied: false,
13588                    purged_rows,
13589                    dropped_commits: doomed.len(),
13590                },
13591            ))
13592        })()
13593        .and_then(|(batch, result)| {
13594            self.finish_observation("syncular_local_purge", batch)
13595                .map(|()| result)
13596        });
13597        let result = match applied {
13598            Ok(result) => result,
13599            Err(error) => {
13600                self.rollback_observation("syncular_local_purge");
13601                self.restore(rollback);
13602                return Err(error.into());
13603            }
13604        };
13605        self.cancel_sync_round();
13606        self.require_previous_version_gone()?;
13607        self.erase_purged_pages(&meta_key)?;
13608        Ok(result)
13609    }
13610
13611    /// §5.11: the previous-version container is a copy of earlier rows; its
13612    /// removal is best-effort elsewhere, so a container that survived the
13613    /// purge fails it before the erasure is recorded.
13614    fn require_previous_version_gone(&self) -> Result<(), String> {
13615        let Some(replica_path) = self.previous_version_replica_path() else {
13616            return Ok(());
13617        };
13618        let container = crate::previous_version::previous_version_container_path(&replica_path);
13619        if std::path::Path::new(&container).exists() {
13620            self.drop_previous_version()?;
13621        }
13622        if std::path::Path::new(&container).exists() {
13623            return Err(
13624                "client.storage_failure: the previous-version container survived the purge"
13625                    .to_owned(),
13626            );
13627        }
13628        Ok(())
13629    }
13630
13631    /// §5.11 purge erasure: SQLite leaves a deleted value in the freed pages of the
13632    /// database file, FTS5 keeps a deleted document's tokens in its index
13633    /// segments, and the WAL keeps the frames written before the purge, until
13634    /// each is rewritten. The FTS5 merge drops the deleted tokens, VACUUM
13635    /// rebuilds the file from the remaining rows, and the checkpoint truncates
13636    /// the WAL. The plan's completion marker follows the checkpoint, so only a
13637    /// finished rewrite lets a retry skip it.
13638    fn erase_purged_pages(&self, meta_key: &str) -> Result<(), String> {
13639        let marker = format!("{meta_key}:erased");
13640        let done = self.stored(
13641            self.conn
13642                .query_row(
13643                    "SELECT 1 FROM _syncular_meta WHERE key = ?1",
13644                    [&marker],
13645                    |_| Ok(()),
13646                )
13647                .optional(),
13648        )?;
13649        if done.is_some() {
13650            return Ok(());
13651        }
13652        let indexes: Vec<String> = self.stored(
13653            self.conn
13654                .prepare(
13655                    "SELECT name FROM sqlite_master WHERE type = 'table' AND sql LIKE 'CREATE VIRTUAL TABLE%USING fts5%'",
13656                )
13657                .and_then(|mut statement| {
13658                    statement
13659                        .query_map([], |row| row.get(0))?
13660                        .collect::<Result<Vec<String>, _>>()
13661                }),
13662        )?;
13663        let erased = self.stored(
13664            self.conn
13665                .execute_batch("PRAGMA secure_delete = ON;")
13666                .and_then(|()| {
13667                    for index in &indexes {
13668                        let name = quote_ident(index);
13669                        self.conn.execute_batch(&format!(
13670                            "INSERT INTO {name}({name}) VALUES('optimize');"
13671                        ))?;
13672                    }
13673                    self.conn.execute_batch("VACUUM;")
13674                })
13675                .and_then(|()| {
13676                    self.conn
13677                        .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| {
13678                            row.get::<_, bool>(0)
13679                        })
13680                }),
13681        );
13682        let reset = self.stored(self.conn.execute_batch("PRAGMA secure_delete = OFF"));
13683        if erased.and_then(|busy| reset.map(|()| busy))? {
13684            return Err("client.storage_busy: WAL checkpoint is busy".to_owned());
13685        }
13686        self.set_meta(&marker, "1")
13687    }
13688
13689    /// Application-authorized recovery of the replicated projection. Unlike a
13690    /// local security purge, this retains the entire outbox, device identity,
13691    /// lease, outcomes, unit registrations, and protected bookkeeping.
13692    /// The projection reset, unit rewind, optimistic replay, and
13693    /// idempotency marker share one savepoint for interruption safety.
13694    pub fn rebootstrap_local_data(
13695        &mut self,
13696        input: &LocalDataRebootstrapInput,
13697    ) -> Result<LocalDataRebootstrapResult, String> {
13698        if input.rebootstrap_id.is_empty()
13699            || input.rebootstrap_id.len() > 128
13700            || !is_local_operation_code_like(&input.rebootstrap_id)
13701        {
13702            return Err(
13703                "sync.invalid_request: local rebootstrap rebootstrapId must be a 1–128 character code-like identifier"
13704                    .to_owned(),
13705            );
13706        }
13707        let meta_key = format!("localRebootstrap:{}", input.rebootstrap_id);
13708        if let Some(persisted) = meta_get(&self.conn, &meta_key).map_err(|_| {
13709            "sync.local_corrupt: persisted local rebootstrap receipt is unreadable".to_owned()
13710        })? {
13711            let (retained_commits, reset_subscriptions) =
13712                decode_local_rebootstrap_receipt(&persisted)?;
13713            return Ok(LocalDataRebootstrapResult {
13714                already_applied: true,
13715                retained_commits,
13716                reset_subscriptions,
13717            });
13718        }
13719        if self.stopped || self.schema_floor.is_some() {
13720            return Err(
13721                "sync.invalid_request: local rebootstrap cannot bypass an active schema-floor stop; update the application first"
13722                    .to_owned(),
13723            );
13724        }
13725
13726        let retained_commits = self.outbox.len();
13727        let reset_subscriptions = self.stored(load_units(&self.conn))?.len();
13728        let receipt = encode_local_rebootstrap_receipt(retained_commits, reset_subscriptions)?;
13729        let rollback = self.capture();
13730        self.begin_observation("syncular_local_rebootstrap")?;
13731        let mut batch = ChangeAccumulator::default();
13732        let applied = (|| -> Result<(), String> {
13733            self.run_schema_reset_observed(&mut batch, false)?;
13734            self.conn
13735                .execute(
13736                    "INSERT INTO _syncular_meta(key, value) VALUES (?1, ?2)",
13737                    rusqlite::params![meta_key, receipt],
13738                )
13739                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13740            self.sync_needed = true;
13741            self.sync_intent_queue.push_back(SyncIntent::Interactive);
13742            batch.status = true;
13743            Ok(())
13744        })()
13745        .and_then(|()| self.finish_observation("syncular_local_rebootstrap", batch));
13746        if let Err(error) = applied {
13747            self.rollback_observation("syncular_local_rebootstrap");
13748            self.restore(rollback);
13749            return Err(error);
13750        }
13751        self.cancel_sync_round();
13752
13753        Ok(LocalDataRebootstrapResult {
13754            already_applied: false,
13755            retained_commits,
13756            reset_subscriptions,
13757        })
13758    }
13759
13760    // -- scope purge + doomed outbox (§3.3) ----------------------------------------
13761
13762    /// Delete base and visible rows owned by the effective scopes
13763    /// ([`local_scope_predicate`]); `Ok(false)` = no local scope-column
13764    /// mapping for a key (the fail-closed case). A SQLite failure is an error.
13765    fn purge_scope_rows(
13766        &mut self,
13767        table_name: &str,
13768        effective: &[(String, Vec<String>)],
13769        owners: &[Vec<(String, Vec<String>)>],
13770    ) -> Result<bool, String> {
13771        let Some(table) = self.schema.table(table_name) else {
13772            return Ok(false);
13773        };
13774        let Ok(predicate) = local_scope_predicate(table, effective, owners) else {
13775            return Ok(false);
13776        };
13777        let Some((predicate, params)) = predicate else {
13778            return Ok(true);
13779        };
13780        self.overlay_dirty.table(table_name);
13781        for source in [base_table(table_name), visible_table(table_name)] {
13782            self.conn
13783                .execute(
13784                    &format!("DELETE FROM {source} WHERE {predicate}"),
13785                    rusqlite::params_from_iter(&params),
13786                )
13787                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13788        }
13789        Ok(true)
13790    }
13791
13792    /// §3.3: drop pending commits whose upserts provably land in the
13793    /// revoked effective scopes and no other owner covers (row ownership)
13794    /// — whole-commit, never per-operation.
13795    fn drop_doomed_outbox(
13796        &mut self,
13797        table: &TableSchema,
13798        effective: &[(String, Vec<String>)],
13799        owners: &[Vec<(String, Vec<String>)>],
13800    ) -> Result<bool, String> {
13801        let doomed: Vec<_> =
13802            self.outbox
13803                .iter()
13804                .filter(|commit| {
13805                    commit.ops.iter().any(|op| {
13806                        op.upsert
13807                            && op.table == table.name
13808                            && op.values.as_ref().is_some_and(|values| {
13809                                owns_local_row(table, effective, owners, values)
13810                            })
13811                    })
13812                })
13813                .cloned()
13814                .collect();
13815        if doomed.is_empty() {
13816            return Ok(false);
13817        }
13818        let mut rejections = Vec::new();
13819        for commit in &doomed {
13820            let results = commit
13821                .ops
13822                .iter()
13823                .enumerate()
13824                .map(|(op_index, operation)| {
13825                    self.overlay_dirty.table(&operation.table);
13826                    let rejection = RejectionRecord {
13827                        client_commit_id: commit.client_commit_id.clone(),
13828                        op_index: op_index as i32,
13829                        code: "sync.scope_revoked".to_owned(),
13830                        message: "the commit was dropped because its effective scope was revoked"
13831                            .to_owned(),
13832                        retryable: false,
13833                        details: None,
13834                        operation: Some(CommitOperation::from(operation)),
13835                    };
13836                    rejections.push(rejection.clone());
13837                    CommitOperationOutcome::Error { rejection }
13838                })
13839                .collect::<Vec<_>>();
13840            self.persist_commit_outcome(
13841                &commit.client_commit_id,
13842                CommitOutcomeStatus::Rejected,
13843                &results,
13844                Some(&commit.ops),
13845            )?;
13846            self.leave_through(&commit.client_commit_id);
13847            self.delete_outbox_persisted(&commit.client_commit_id)?;
13848        }
13849        self.prune_commit_outcomes()?;
13850        let doomed_ids = doomed
13851            .iter()
13852            .map(|commit| commit.client_commit_id.as_str())
13853            .collect::<BTreeSet<_>>();
13854        self.outbox
13855            .retain(|commit| !doomed_ids.contains(commit.client_commit_id.as_str()));
13856        self.rejections.extend(rejections);
13857        Ok(true)
13858    }
13859
13860    // -- blobs (§5.9) ----------------------------------------------------------------
13861
13862    /// §5.9.7: hash bytes into the content address, cache them, queue the
13863    /// upload (flushed before the next push, B4). Returns the canonical
13864    /// BlobRef JSON `{blobId, byteLength, mediaType?}` for a `blob_ref`
13865    /// column value.
13866    pub fn upload_blob(
13867        &mut self,
13868        bytes: &[u8],
13869        media_type: Option<String>,
13870        name: Option<String>,
13871    ) -> Result<Value, String> {
13872        let blob_id = blob_id_for(bytes);
13873        let now = self.clock_now_ms();
13874        let tx = self
13875            .conn
13876            .transaction()
13877            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13878        tx.execute(
13879            "INSERT INTO _syncular_blobs(blob_id, bytes, byte_length, media_type, created_at_ms) VALUES (?,?,?,?,?)
13880             ON CONFLICT(blob_id) DO NOTHING",
13881            rusqlite::params![blob_id, bytes, bytes.len() as i64, media_type, now],
13882        )
13883        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13884        tx.execute(
13885            "INSERT OR IGNORE INTO _syncular_blob_uploads(blob_id, media_type, created_at_ms) VALUES (?,?,?)",
13886            rusqlite::params![blob_id, media_type, now],
13887        )
13888        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13889        tx.commit()
13890            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13891        self.enforce_blob_cache_cap();
13892        let mut obj = Map::new();
13893        obj.insert("blobId".to_owned(), Value::from(blob_id));
13894        obj.insert("byteLength".to_owned(), Value::from(bytes.len() as i64));
13895        if let Some(mt) = media_type {
13896            obj.insert("mediaType".to_owned(), Value::from(mt));
13897        }
13898        if let Some(n) = name {
13899            obj.insert("name".to_owned(), Value::from(n));
13900        }
13901        Ok(Value::Object(obj))
13902    }
13903
13904    /// §5.9.7: resolve an owned blob body without driver encoding. A
13905    /// content-addressed cache hit serves with no fetch (B1); a miss downloads
13906    /// (§5.9.5), verifies the address, caches the bytes, and returns them.
13907    pub fn fetch_blob_bytes(
13908        &mut self,
13909        transport: &mut dyn Transport,
13910        blob_id_or_ref: &str,
13911    ) -> Result<FetchedBlob, (String, String)> {
13912        let simple = |m: String| ("client.failed".to_owned(), m);
13913        // A BlobRef declares the size that caps the download (§5.9.5); a bare
13914        // blobId declares none.
13915        let (blob_id, byte_length) = if blob_id_or_ref.starts_with("sha256:") {
13916            (blob_id_or_ref.to_owned(), None)
13917        } else {
13918            let value: Value = serde_json::from_str(blob_id_or_ref)
13919                .map_err(|_| simple("blob ref is not JSON".to_owned()))?;
13920            (
13921                value
13922                    .get("blobId")
13923                    .and_then(Value::as_str)
13924                    .ok_or_else(|| simple("blob ref has no blobId".to_owned()))?
13925                    .to_owned(),
13926                value.get("byteLength").and_then(Value::as_u64),
13927            )
13928        };
13929        if let Some(cached) = self.get_cached_blob_bytes(&blob_id).map_err(simple)? {
13930            return Ok(cached);
13931        }
13932        if self.transport_closed() {
13933            return Err(("sync.offline".into(), "transport gate is closed".into()));
13934        }
13935        // §5.9.5: propagate the server's blob.* code (blob.forbidden /
13936        // blob.not_found) verbatim so the harness can assert on it. The
13937        // authorized endpoint serves bytes inline OR (always-issue, presign
13938        // configured) a signed url the client fetches directly — no host auth,
13939        // no fall-through: failure => re-request (the caller's next fetch_blob_bytes).
13940        #[cfg(feature = "bench-internals")]
13941        let download_phase = self.benchmark_phases.start(Phase::BlobDownload);
13942        let bytes = match transport
13943            .blob_download(&blob_id, byte_length)
13944            .map_err(|e| (e.code, e.message))?
13945        {
13946            BlobDownload::Bytes(bytes) => bytes,
13947            BlobDownload::Url {
13948                url,
13949                url_expires_at_ms,
13950            } => {
13951                // §5.9.5: MUST NOT start a fetch at/past expiry.
13952                if url_expires_at_ms.is_some_and(|exp| exp <= self.clock_now_ms()) {
13953                    return Err((
13954                        "sync.segment_expired".to_owned(),
13955                        format!(
13956                            "blob url for {blob_id} expired before fetch — re-request mints a fresh url (§5.9.5)"
13957                        ),
13958                    ));
13959                }
13960                transport
13961                    .fetch_blob_url(&url, byte_length)
13962                    .map_err(|e| (e.code, e.message))?
13963            }
13964        };
13965        #[cfg(feature = "bench-internals")]
13966        drop(download_phase);
13967        #[cfg(feature = "bench-internals")]
13968        let validate_phase = self.benchmark_phases.start(Phase::BlobValidate);
13969        // §5.9.5 inherits §5.1: the declared size caps the body before the
13970        // content address is verified.
13971        if byte_length.is_some_and(|cap| bytes.len() as u64 > cap) {
13972            return Err((
13973                "sync.invalid_request".to_owned(),
13974                "blob exceeds its byteLength".to_owned(),
13975            ));
13976        }
13977        if blob_id_for(&bytes) != blob_id {
13978            return Err(simple(format!(
13979                "blob content address mismatch for {blob_id}"
13980            )));
13981        }
13982        #[cfg(feature = "bench-internals")]
13983        drop(validate_phase);
13984        #[cfg(feature = "bench-internals")]
13985        let insert_phase = self.benchmark_phases.start(Phase::BlobCacheInsert);
13986        let now = self.clock_now_ms();
13987        self.conn
13988            .execute(
13989                "INSERT OR IGNORE INTO _syncular_blobs(blob_id, bytes, byte_length, media_type, created_at_ms) VALUES (?,?,?,NULL,?)",
13990                rusqlite::params![blob_id, bytes, bytes.len() as i64, now],
13991            )
13992            .map_err(|e| simple(e.to_string()))?;
13993        self.conn
13994            .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
13995            .map_err(|e| simple(e.to_string()))?;
13996        self.enforce_blob_cache_cap();
13997        #[cfg(feature = "bench-internals")]
13998        drop(insert_phase);
13999        self.get_cached_blob_bytes(&blob_id)
14000            .map_err(simple)?
14001            .ok_or_else(|| simple("blob cache write failed".to_owned()))
14002    }
14003
14004    fn get_cached_blob_bytes(&self, blob_id: &str) -> Result<Option<FetchedBlob>, String> {
14005        #[cfg(feature = "bench-internals")]
14006        let _phase = self.benchmark_phases.start(Phase::BlobCacheRead);
14007        let mut stmt = self
14008            .conn
14009            .prepare("SELECT bytes, byte_length, media_type FROM _syncular_blobs WHERE blob_id = ?")
14010            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14011        let mut rows = stmt
14012            .query(rusqlite::params![blob_id])
14013            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14014        if let Some(row) = rows
14015            .next()
14016            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
14017        {
14018            let bytes: Vec<u8> = row
14019                .get(0)
14020                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14021            let byte_length: i64 = row
14022                .get(1)
14023                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14024            let media_type: Option<String> = row
14025                .get(2)
14026                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14027            return Ok(Some(FetchedBlob {
14028                blob_id: blob_id.to_owned(),
14029                byte_length,
14030                bytes,
14031                media_type,
14032            }));
14033        }
14034        Ok(None)
14035    }
14036
14037    /// §5.9.7 B4: upload every queued blob before push.
14038    fn pending_blob_uploads(&self) -> Result<Vec<crate::round::PendingUpload>, TransportError> {
14039        let pending: Vec<(String, Option<String>)> = {
14040            let mut stmt = self
14041                .conn
14042                .prepare(
14043                    "SELECT blob_id, media_type FROM (
14044                      SELECT blob_id, media_type, created_at_ms FROM _syncular_blob_uploads
14045                      UNION ALL
14046                      SELECT DISTINCT r.blob_id, b.media_type, 9223372036854775807 AS created_at_ms
14047                      FROM _syncular_blob_commit_refs r LEFT JOIN _syncular_blobs b ON b.blob_id = r.blob_id
14048                      WHERE NOT EXISTS (SELECT 1 FROM _syncular_blob_uploads u WHERE u.blob_id = r.blob_id)
14049                    ) ORDER BY created_at_ms, blob_id",
14050                )
14051                .map_err(|e| TransportError::new("client.failed", e.to_string()))?;
14052            let rows = stmt
14053                .query_map([], |row| {
14054                    Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?))
14055                })
14056                .map_err(|e| TransportError::new("client.failed", e.to_string()))?;
14057            rows.collect::<Result<_, _>>()
14058                .map_err(|error| match error {
14059                    rusqlite::Error::InvalidColumnType(..)
14060                    | rusqlite::Error::FromSqlConversionFailure(..) => TransportError::new(
14061                        "sync.local_corrupt",
14062                        "Pending blob upload metadata is invalid",
14063                    ),
14064                    _ => TransportError::new("client.failed", error.to_string()),
14065                })?
14066        };
14067        let mut uploads = Vec::new();
14068        for (blob_id, media_type) in pending {
14069            let bytes = (|| {
14070                let stored: Option<(SqlValue, SqlValue)> = self
14071                    .conn
14072                    .query_row(
14073                        "SELECT bytes, byte_length FROM _syncular_blobs WHERE blob_id = ?",
14074                        rusqlite::params![blob_id],
14075                        |row| Ok((row.get(0)?, row.get(1)?)),
14076                    )
14077                    .optional()
14078                    .map_err(|e| TransportError::new("client.failed", e.to_string()))?;
14079                let Some((SqlValue::Blob(bytes), SqlValue::Integer(byte_length))) = stored else {
14080                    return Err(TransportError::new(
14081                        "sync.local_corrupt",
14082                        "Pending blob upload body is missing or corrupt",
14083                    ));
14084                };
14085                if byte_length != bytes.len() as i64 || blob_id_for(&bytes) != blob_id {
14086                    return Err(TransportError::new(
14087                        "sync.local_corrupt",
14088                        "Pending blob upload body is missing or corrupt",
14089                    ));
14090                }
14091                Ok(bytes)
14092            })();
14093            let failed = bytes.is_err();
14094            uploads.push(crate::round::PendingUpload {
14095                id: blob_id,
14096                bytes,
14097                media_type,
14098            });
14099            if failed {
14100                break;
14101            }
14102        }
14103        Ok(uploads)
14104    }
14105
14106    fn visible_blob_ids_sql(&self) -> String {
14107        let mut selects = Vec::new();
14108        for table in &self.schema.tables {
14109            for column in table
14110                .columns
14111                .iter()
14112                .filter(|column| column.ty == ColumnType::BlobRef)
14113            {
14114                let identifier = quote_ident(&column.name);
14115                selects.push(format!(
14116                    "SELECT json_extract({identifier}, '$.blobId') AS blob_id FROM {} \
14117                     WHERE typeof({identifier}) = 'text' AND json_valid({identifier}) \
14118                     AND json_type({identifier}, '$.blobId') = 'text'",
14119                    quote_ident(&table.name),
14120                ));
14121            }
14122        }
14123        if selects.is_empty() {
14124            "SELECT NULL AS blob_id WHERE 0".to_owned()
14125        } else {
14126            selects.join(" UNION ")
14127        }
14128    }
14129
14130    /// §5.9.7 B1 size cap. Visible rows, pending commits, and
14131    /// staged uploads pin bodies directly; no derived refcount is stored.
14132    fn enforce_blob_cache_cap(&self) {
14133        let Some(max_bytes) = self.limits.blob_cache_max_bytes else {
14134            return;
14135        };
14136        let mut total: i64 = self
14137            .conn
14138            .query_row(
14139                "SELECT COALESCE(SUM(byte_length), 0) FROM _syncular_blobs",
14140                [],
14141                |row| row.get(0),
14142            )
14143            .unwrap_or(0);
14144        if total <= max_bytes {
14145            return;
14146        }
14147        let query = format!(
14148            "SELECT blob_id, byte_length FROM _syncular_blobs
14149             WHERE blob_id NOT IN (SELECT blob_id FROM _syncular_blob_uploads)
14150               AND blob_id NOT IN (SELECT blob_id FROM _syncular_blob_commit_refs)
14151               AND blob_id NOT IN ({})
14152             ORDER BY created_at_ms ASC, blob_id ASC",
14153            self.visible_blob_ids_sql(),
14154        );
14155        let candidates: Vec<(String, i64)> = {
14156            let Ok(mut stmt) = self.conn.prepare(&query) else {
14157                return;
14158            };
14159            let Ok(rows) = stmt.query_map([], |row| {
14160                Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
14161            }) else {
14162                return;
14163            };
14164            rows.filter_map(Result::ok).collect()
14165        };
14166        for (blob_id, byte_length) in candidates {
14167            if total <= max_bytes {
14168                break;
14169            }
14170            let _ = self.conn.execute(
14171                "DELETE FROM _syncular_blobs WHERE blob_id = ?",
14172                rusqlite::params![blob_id],
14173            );
14174            total -= byte_length;
14175        }
14176    }
14177
14178    fn delete_unreferenced_cached_blobs(&mut self) -> Result<(), String> {
14179        #[cfg(feature = "bench-internals")]
14180        let _phase = self.benchmark_phases.start(Phase::BlobRetention);
14181        if !self.schema_has_blobs() {
14182            return Ok(());
14183        }
14184        self.rebuild_overlay_if_dirty()?;
14185        self.conn
14186            .execute(
14187                &format!(
14188                    "DELETE FROM _syncular_blobs
14189                 WHERE blob_id NOT IN (SELECT blob_id FROM _syncular_blob_uploads)
14190                   AND blob_id NOT IN (SELECT blob_id FROM _syncular_blob_commit_refs)
14191                   AND blob_id NOT IN ({})",
14192                    self.visible_blob_ids_sql(),
14193                ),
14194                [],
14195            )
14196            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14197        Ok(())
14198    }
14199
14200    // -- local row storage ----------------------------------------------------------
14201
14202    /// The cached per-table primary-key upsert SQL for `full_table` (see
14203    /// the `insert_sql` field: built once, reused per row).
14204    fn insert_row_sql(&self, full_table: &str, table: &crate::schema::TableSchema) -> String {
14205        if let Some(sql) = self.insert_sql.borrow().get(full_table) {
14206            return sql.clone();
14207        }
14208        let mut columns: Vec<String> = table.columns.iter().map(|c| quote_ident(&c.name)).collect();
14209        columns.push(quote_ident("_syncular_version"));
14210        columns.extend(table.sealed_columns().iter().map(|name| quote_ident(name)));
14211        let placeholders: Vec<&str> = columns.iter().map(|_| "?").collect();
14212        let primary_key = quote_ident(&table.primary_key);
14213        let updates = columns
14214            .iter()
14215            .filter(|column| **column != primary_key)
14216            .map(|column| format!("{column}=excluded.{column}"))
14217            .collect::<Vec<_>>()
14218            .join(", ");
14219        // §4.5 version guard: server state lands in the base table only above
14220        // the stored version; the visible overlay takes every write.
14221        let guard = if full_table == base_table(&table.name) {
14222            format!(" WHERE excluded._syncular_version > {full_table}._syncular_version")
14223        } else {
14224            String::new()
14225        };
14226        let sql = format!(
14227            "INSERT INTO {full_table} ({}) VALUES ({}) ON CONFLICT ({primary_key}) DO UPDATE SET {updates}{guard}",
14228            columns.join(", "),
14229            placeholders.join(", ")
14230        );
14231        self.insert_sql
14232            .borrow_mut()
14233            .insert(full_table.to_owned(), sql.clone());
14234        sql
14235    }
14236
14237    /// §4.5: write a server row under the version guard; returns whether it
14238    /// landed. `sealed` is its §5.11 sealed state, `None` for an unsealed row.
14239    fn write_base_row(
14240        &self,
14241        table_name: &str,
14242        row: &Row,
14243        version: i64,
14244        sealed: Option<&SealedRow>,
14245    ) -> Result<bool, String> {
14246        let landed = self.write_row(&base_table(table_name), table_name, row, version, sealed)?;
14247        if landed {
14248            self.overlay_dirty.table(table_name);
14249        }
14250        Ok(landed)
14251    }
14252
14253    fn write_row(
14254        &self,
14255        full_table: &str,
14256        table_name: &str,
14257        row: &Row,
14258        version: i64,
14259        sealed: Option<&SealedRow>,
14260    ) -> Result<bool, String> {
14261        #[cfg(feature = "bench-internals")]
14262        let _phase = self.benchmark_phases.start(Phase::RowWrite);
14263        let table = self
14264            .schema
14265            .table(table_name)
14266            .ok_or_else(|| format!("unknown table {table_name:?}"))?;
14267        let sql = self.insert_row_sql(full_table, table);
14268        let mut stmt = self
14269            .conn
14270            .prepare_cached(&sql)
14271            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14272        let params = row
14273            .iter()
14274            .map(RowParam::Cell)
14275            .chain(std::iter::once(RowParam::Version(version)))
14276            .chain(
14277                [
14278                    sealed.map(|sealed| sealed.key_id.as_str()),
14279                    sealed.map(|sealed| sealed.envelopes.as_str()),
14280                ]
14281                .into_iter()
14282                .take(table.sealed_columns().len())
14283                .map(RowParam::Text),
14284            );
14285        stmt.execute(rusqlite::params_from_iter(params))
14286            .map(|changed| changed > 0)
14287            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
14288    }
14289
14290    /// §4.5: delete a server row whose stored version lies below `version`;
14291    /// returns whether a row left.
14292    fn delete_base_row(
14293        &self,
14294        table_name: &str,
14295        row_id: &str,
14296        version: i64,
14297    ) -> Result<bool, String> {
14298        let table = self
14299            .schema
14300            .table(table_name)
14301            .ok_or_else(|| format!("unknown table {table_name:?}"))?;
14302        let sql = format!(
14303            "DELETE FROM {} WHERE {} AND _syncular_version < ?2",
14304            base_table(table_name),
14305            row_id_predicate(table)
14306        );
14307        let mut stmt = self
14308            .conn
14309            .prepare_cached(&sql)
14310            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14311        let landed = stmt
14312            .execute(rusqlite::params![row_id, version])
14313            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
14314            > 0;
14315        if landed {
14316            self.overlay_dirty.table(table_name);
14317        }
14318        Ok(landed)
14319    }
14320
14321    fn has_acknowledged_rows(&self) -> Result<bool, String> {
14322        self.conn
14323            .query_row(
14324                "SELECT EXISTS(SELECT 1 FROM _syncular_acked_rows)",
14325                [],
14326                |row| row.get(0),
14327            )
14328            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
14329    }
14330
14331    fn acknowledged_operations(
14332        &self,
14333        rows: Option<&HashSet<(&str, &str)>>,
14334        tables: Option<&BTreeSet<&str>>,
14335    ) -> Result<Vec<OutboxOp>, String> {
14336        let keys = rows.map(|rows| serde_json::to_string(&rows).expect("row keys"));
14337        let mut statement = self
14338            .conn
14339            .prepare_cached(if keys.is_some() {
14340                ACKED_ROWS_BY_ROW
14341            } else {
14342                "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"
14343            })
14344            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14345        let rows = statement
14346            .query_map(
14347                rusqlite::params![
14348                    keys,
14349                    tables.map(|tables| serde_json::to_string(tables).expect("table keys"))
14350                ],
14351                |row| {
14352                    #[cfg(test)]
14353                    self.acknowledged_replay_count
14354                        .set(self.acknowledged_replay_count.get() + 1);
14355                    Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
14356                },
14357            )
14358            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14359        rows.map(|row| {
14360            let (op, intent) =
14361                row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14362            let op: CommitOperation =
14363                serde_json::from_str(&op).map_err(|_| "sync.local_corrupt".to_owned())?;
14364            let table = self
14365                .schema
14366                .table(&op.table)
14367                .ok_or_else(|| "sync.unknown_table".to_owned())?;
14368            let values = if op.op == "upsert" && self.visible_row(table, &op.row_id)?.is_none() {
14369                Some(serde_json::from_str(&intent).map_err(|_| "sync.local_corrupt".to_owned())?)
14370            } else {
14371                op.values.clone()
14372            };
14373            Ok(OutboxOp {
14374                values,
14375                ..op.into()
14376            })
14377        })
14378        .collect()
14379    }
14380
14381    fn drop_acknowledged_rows(
14382        &self,
14383        matches: impl Fn(&str, &Map<String, Value>) -> bool,
14384    ) -> Result<Vec<OutboxCommit>, String> {
14385        let mut statement = self
14386            .conn
14387            .prepare("SELECT commit_id,tbl,intent_json,id FROM _syncular_acked_rows")
14388            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14389        let rows = statement
14390            .query_map([], |row| {
14391                Ok((
14392                    row.get::<_, String>(0)?,
14393                    row.get::<_, String>(1)?,
14394                    row.get::<_, String>(2)?,
14395                    row.get::<_, String>(3)?,
14396                ))
14397            })
14398            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14399        let mut doomed = HashSet::new();
14400        for row in rows {
14401            let (id, table, intent, row_id) =
14402                row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14403            let values =
14404                serde_json::from_str(&intent).map_err(|_| "sync.local_corrupt".to_owned())?;
14405            let base_matches = self
14406                .schema
14407                .table(&table)
14408                .map(|schema| self.stored_row(schema, &row_id, true))
14409                .transpose()?
14410                .flatten()
14411                .is_some_and(|(base, _)| {
14412                    let schema = self.schema.table(&table).expect("acknowledged table");
14413                    let values = schema
14414                        .columns
14415                        .iter()
14416                        .zip(base.iter())
14417                        .map(|(column, value)| (column.name.clone(), column_value_to_json(value)))
14418                        .collect();
14419                    matches(&table, &values)
14420                });
14421            if matches(&table, &values) || base_matches {
14422                doomed.insert(id);
14423            }
14424        }
14425        let mut dropped = Vec::new();
14426        for id in doomed {
14427            let mut statement = self
14428                .conn
14429                .prepare("SELECT op_json FROM _syncular_acked_rows WHERE commit_id=?1 ORDER BY idx")
14430                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14431            let operations = statement
14432                .query_map([&id], |row| row.get::<_, String>(0))
14433                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14434            let mut ops = Vec::new();
14435            for operation in operations {
14436                let json = operation
14437                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14438                let op: CommitOperation =
14439                    serde_json::from_str(&json).map_err(|_| "sync.local_corrupt".to_owned())?;
14440                self.overlay_dirty.table(&op.table);
14441                ops.push(OutboxOp {
14442                    table: op.table,
14443                    row_id: op.row_id,
14444                    upsert: op.op == "upsert",
14445                    base_version: op.base_version,
14446                    values: op.values,
14447                    insert: op.insert,
14448                });
14449            }
14450            dropped.push(OutboxCommit {
14451                client_commit_id: id.clone(),
14452                ops,
14453            });
14454            self.conn
14455                .execute("DELETE FROM _syncular_acked_rows WHERE commit_id=?1", [id])
14456                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14457        }
14458        Ok(dropped)
14459    }
14460
14461    /// [`Self::rebuild_overlay`], skipped when neither the base tables nor
14462    /// the outbox changed since the last rebuild (the no-op sync round).
14463    fn rebuild_overlay_if_dirty(&mut self) -> Result<(), String> {
14464        if self.overlay_dirty.get() {
14465            self.rebuild_overlay()?;
14466        }
14467        Ok(())
14468    }
14469
14470    /// §7.1: local reads see outbox state applied optimistically — rebuild
14471    /// every visible table as (base server state) + (pending outbox replay
14472    /// on top). Optimistic rows carry version `-1`.
14473    fn rebuild_overlay(&mut self) -> Result<(), String> {
14474        #[cfg(feature = "bench-internals")]
14475        let _phase = self.benchmark_phases.start(Phase::OverlayRebuild);
14476        #[cfg(test)]
14477        self.overlay_rebuild_count
14478            .set(self.overlay_rebuild_count.get() + 1);
14479        let dirty = self.overlay_dirty.snapshot();
14480        let tables: Vec<_> = self
14481            .schema
14482            .tables
14483            .iter()
14484            .filter(|table| {
14485                dirty
14486                    .as_ref()
14487                    .is_none_or(|names| names.is_empty() || names.contains(&table.name))
14488            })
14489            .cloned()
14490            .collect();
14491        let names: BTreeSet<_> = tables.iter().map(|table| table.name.as_str()).collect();
14492        // A built-in projection is refilled from the rebuilt rows once
14493        // instead of per row by its source triggers.
14494        let built_in: Vec<_> = tables
14495            .iter()
14496            .flat_map(|table| {
14497                table
14498                    .local_projections
14499                    .iter()
14500                    .filter(|spec| spec.built_in())
14501                    .map(move |spec| (spec, table))
14502            })
14503            .collect();
14504        self.begin_observation("syncular_overlay")?;
14505        let rebuilt = (|| {
14506            for (spec, _) in &built_in {
14507                for suffix in ["bi", "bu", "ai", "ad", "au"] {
14508                    self.stored(self.conn.execute(
14509                        &format!(
14510                            "DROP TRIGGER IF EXISTS {}",
14511                            quote_ident(&format!("_syncular_project_{}_{suffix}", spec.name))
14512                        ),
14513                        [],
14514                    ))?;
14515                }
14516            }
14517            for table in &tables {
14518                let visible = visible_table(&table.name);
14519                let base = base_table(&table.name);
14520                self.conn
14521                    .execute_batch(&format!(
14522                        "DELETE FROM {visible}; INSERT INTO {visible} SELECT * FROM {base}"
14523                    ))
14524                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14525            }
14526            self.replay_overlay(&names, None)?;
14527            for (spec, table) in &built_in {
14528                self.fill_built_in(spec, table)?;
14529                self.create_projection_triggers(spec, table)?;
14530            }
14531            self.conn
14532                .execute_batch("RELEASE syncular_overlay")
14533                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14534            Ok(())
14535        })();
14536        if rebuilt.is_err() {
14537            self.conn
14538                .execute_batch("ROLLBACK TO syncular_overlay; RELEASE syncular_overlay")
14539                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14540        } else {
14541            self.overlay_dirty.set(false);
14542        }
14543        rebuilt
14544    }
14545
14546    /// §7.1 replay of acknowledged, retained failed and pending intent, in
14547    /// that order, for the operations of `tables` on `rows` (every row for
14548    /// `None`) over their current visible state.
14549    fn replay_overlay(
14550        &self,
14551        tables: &BTreeSet<&str>,
14552        rows: Option<&HashSet<(&str, &str)>>,
14553    ) -> Result<(), String> {
14554        let replays = |op: &&OutboxOp| {
14555            tables.contains(op.table.as_str())
14556                && rows.is_none_or(|rows| rows.contains(&(op.table.as_str(), op.row_id.as_str())))
14557        };
14558        self.apply_outbox_ops(&self.acknowledged_operations(rows, Some(tables))?)?;
14559        for (commit, initial) in self.failed_commits.iter() {
14560            for operation in commit.ops.iter().filter(replays) {
14561                let Some(table) = self.schema.table(&operation.table) else {
14562                    continue;
14563                };
14564                if operation.upsert
14565                    && self.visible_row(table, &operation.row_id)?.is_none()
14566                    && operation.presented_values(table).is_some_and(|values| {
14567                        table
14568                            .columns
14569                            .iter()
14570                            .all(|column| values.contains_key(&column.name))
14571                    })
14572                {
14573                    let key = serde_json::to_string(&(&operation.table, &operation.row_id))
14574                        .expect("row key serialization");
14575                    if let Some(Value::Object(values)) = initial.get(&key) {
14576                        self.apply_outbox_ops(&[OutboxOp {
14577                            values: Some(values.clone()),
14578                            ..operation.clone()
14579                        }])?;
14580                    }
14581                }
14582            }
14583            self.apply_outbox_ops(commit.ops.iter().filter(replays))?;
14584        }
14585        self.apply_outbox_ops(
14586            self.outbox
14587                .iter()
14588                .flat_map(|commit| &commit.ops)
14589                .filter(replays),
14590        )
14591    }
14592
14593    /// §7.1 replay: every operation is applied over the current visible
14594    /// state. An operation that no longer applies (a server row now holds its
14595    /// unique value) stays pending and invisible until a later replay admits
14596    /// it or the server answers its push.
14597    fn apply_outbox_ops<'a>(
14598        &self,
14599        ops: impl IntoIterator<Item = &'a OutboxOp>,
14600    ) -> Result<(), String> {
14601        #[cfg(feature = "bench-internals")]
14602        let mut phase = self.benchmark_phases.start(Phase::PendingReplay);
14603        for op in ops {
14604            #[cfg(feature = "bench-internals")]
14605            if let Some(phase) = &mut phase {
14606                phase.unit();
14607            }
14608            if op.upsert {
14609                if let Some((table, values)) = self
14610                    .schema
14611                    .table(&op.table)
14612                    .filter(|table| table.indexes.iter().any(|index| index.unique))
14613                    .and_then(|table| Some((table, op.presented_values(table)?)))
14614                {
14615                    let mut intended: Map<String, Value> = self
14616                        .visible_row(table, &op.row_id)?
14617                        .map(|(row, _)| {
14618                            table
14619                                .columns
14620                                .iter()
14621                                .zip(&row)
14622                                .map(|(column, value)| {
14623                                    (column.name.clone(), column_value_to_json(value))
14624                                })
14625                                .collect()
14626                        })
14627                        .unwrap_or_default();
14628                    intended.extend(values.into_owned());
14629                    if !self.unique_conflicts(table, &intended, false)?.is_empty() {
14630                        continue;
14631                    }
14632                }
14633            }
14634            self.apply_outbox_op(op)?;
14635        }
14636        Ok(())
14637    }
14638
14639    fn apply_outbox_op(&self, op: &OutboxOp) -> Result<(), String> {
14640        let Some(table) = self.schema.table(&op.table) else {
14641            return Ok(());
14642        };
14643        let visible = visible_table(&table.name);
14644        if !op.upsert {
14645            let sql = format!("DELETE FROM {visible} WHERE {}", row_id_predicate(table));
14646            self.conn
14647                .prepare_cached(&sql)
14648                .and_then(|mut statement| statement.execute(rusqlite::params![op.row_id]))
14649                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14650            return Ok(());
14651        }
14652        // §7.1: an insert-intent operation that lacks a non-nullable column
14653        // cannot encode; it stays invisible until the send-time prepass drops
14654        // it as sync.outbox_incompatible (§7.4.4).
14655        let Some(values) = op.presented_values(table) else {
14656            return Ok(());
14657        };
14658        // §7.1: the overlay applies the operation's PRESENT columns
14659        // over the current local row. A partial operation over an
14660        // absent local row leaves it absent — the server answers it
14661        // with sync.row_deleted or sync.row_missing (§6.2). An
14662        // insert-intent operation presents every column.
14663        let full = table
14664            .columns
14665            .iter()
14666            .all(|column| values.contains_key(&column.name));
14667        let local = self.visible_row(table, &op.row_id)?;
14668        if local.is_none() && !full {
14669            return Ok(());
14670        }
14671        // §5.11: a row that arrived sealed stays sealed; the replay overlays
14672        // its non-encrypted columns and its encrypted columns stay NULL.
14673        let sealed = if local.is_some() && table.has_encrypted_columns() {
14674            let (key_id, envelopes) = self
14675                .conn
14676                .query_row(
14677                    &format!(
14678                        "SELECT \"_sync_sealed_key\",\"_sync_sealed\" FROM {visible} WHERE {}",
14679                        row_id_predicate(table)
14680                    ),
14681                    rusqlite::params![op.row_id],
14682                    |row| {
14683                        Ok((
14684                            row.get::<_, Option<String>>(0)?,
14685                            row.get::<_, Option<String>>(1)?,
14686                        ))
14687                    },
14688                )
14689                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14690            key_id
14691                .zip(envelopes)
14692                .map(|(key_id, envelopes)| SealedRow { key_id, envelopes })
14693        } else {
14694            None
14695        };
14696        let mut row: Row = Vec::with_capacity(table.columns.len());
14697        for (index, column) in table.columns.iter().enumerate() {
14698            let encrypted = table
14699                .encrypted_columns
14700                .iter()
14701                .any(|encrypted| encrypted.index == index);
14702            let incoming = match values
14703                .get(&column.name)
14704                .filter(|_| !(sealed.is_some() && encrypted))
14705            {
14706                Some(raw) => json_to_column_value(
14707                    if raw.get("$bytes").is_some() && encrypted {
14708                        &table.wire_columns[index]
14709                    } else {
14710                        column
14711                    },
14712                    Some(raw),
14713                ),
14714                None => Ok(local
14715                    .as_ref()
14716                    .and_then(|(values, _)| values.get(index).cloned())
14717                    .flatten()),
14718            };
14719            row.push(incoming.map_err(|_| {
14720                "sync.local_corrupt: persisted optimistic row value is invalid".to_owned()
14721            })?);
14722        }
14723        let version = local.as_ref().map_or(-1, |(_, version)| *version);
14724        self.write_row(&visible, &table.name, &row, version, sealed.as_ref())
14725            .map(|_| ())
14726            .map_err(|error| {
14727                if error.starts_with("UNIQUE constraint failed:") {
14728                    "sync.constraint_violation: local write violates a unique constraint".to_owned()
14729                } else {
14730                    error
14731                }
14732            })
14733    }
14734
14735    /// Whether the row is present in the overlay. Existence reads only the
14736    /// key: locked encrypted values stay opaque, and decoding the complete row
14737    /// would reject a valid plain write.
14738    fn visible_row_exists(&self, table: &TableSchema, row_id: &str) -> Result<bool, String> {
14739        self.conn
14740            .query_row(
14741                &format!(
14742                    "SELECT EXISTS(SELECT 1 FROM {} WHERE {})",
14743                    visible_table(&table.name),
14744                    row_id_predicate(table)
14745                ),
14746                rusqlite::params![row_id],
14747                |row| row.get(0),
14748            )
14749            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
14750    }
14751
14752    /// §5.11: a sealed row is read-only; a write could otherwise send NULL
14753    /// over ciphertext this device cannot see.
14754    fn refuse_sealed_row(&self, table: &TableSchema, row_id: &str) -> Result<(), ClientError> {
14755        if !table.has_encrypted_columns() {
14756            return Ok(());
14757        }
14758        let key_id: Option<String> = self
14759            .conn
14760            .query_row(
14761                &format!(
14762                    "SELECT \"_sync_sealed_key\" FROM {} WHERE {}",
14763                    visible_table(&table.name),
14764                    row_id_predicate(table)
14765                ),
14766                rusqlite::params![row_id],
14767                |row| row.get(0),
14768            )
14769            .optional()
14770            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
14771            .flatten();
14772        match key_id {
14773            None => Ok(()),
14774            Some(key_id) => Err(ClientError {
14775                code: "client.encryption_key_missing".to_owned(),
14776                message: "the row is sealed under a key this device does not hold".to_owned(),
14777                details: Some(json!({ "table": table.name, "keyId": key_id })),
14778                retryable: false,
14779            }),
14780        }
14781    }
14782
14783    /// §5.11 reveal: decrypt every sealed base row whose envelope keys the
14784    /// keyring now holds into its columns and clear both reserved columns,
14785    /// one change batch per table. `client.decrypt_failed` fails the caller.
14786    fn reveal_sealed_rows(&mut self) -> Result<(), TransportError> {
14787        let storage = |message: String| TransportError::new("storage.failed", message);
14788        let tables: Vec<TableSchema> = self
14789            .schema
14790            .tables
14791            .iter()
14792            .filter(|table| table.has_encrypted_columns())
14793            .cloned()
14794            .collect();
14795        for table in &tables {
14796            let base = base_table(&table.name);
14797            let pk = quote_ident(&table.primary_key);
14798            let sealed: Vec<(SqlValue, i64, String)> = self
14799                .conn
14800                .prepare_cached(&format!(
14801                    "SELECT {pk}, \"_syncular_version\", \"_sync_sealed\" FROM {base} WHERE \"_sync_sealed_key\" IS NOT NULL"
14802                ))
14803                .and_then(|mut statement| {
14804                    statement
14805                        .query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))?
14806                        .collect()
14807                })
14808                .map_err(|error| storage(Self::sqlite_failure(&self.storage_failure, error)))?;
14809            let mut revealed = Vec::new();
14810            for (key, version, envelopes) in sealed {
14811                if let Some(row) =
14812                    crate::values::reveal_sealed_row(table, &envelopes, &self.encryption)?
14813                {
14814                    revealed.push((key, version, row));
14815                }
14816            }
14817            if revealed.is_empty() {
14818                continue;
14819            }
14820            self.begin_observation("syncular_reveal").map_err(storage)?;
14821            let outcome = (|| {
14822                let assignments = table
14823                    .encrypted_columns
14824                    .iter()
14825                    .map(|enc| format!("{}=?", quote_ident(&table.columns[enc.index].name)))
14826                    .collect::<Vec<_>>()
14827                    .join(",");
14828                let mut statement = self
14829                    .conn
14830                    .prepare_cached(&format!(
14831                        "UPDATE {base} SET {assignments},\"_sync_sealed_key\"=NULL,\"_sync_sealed\"=NULL WHERE {pk}=? AND \"_syncular_version\"=?"
14832                    ))
14833                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14834                for (key, version, row) in &revealed {
14835                    let mut params = table
14836                        .encrypted_columns
14837                        .iter()
14838                        .map(|enc| owned_sql_value(RowParam::Cell(&row[enc.index])))
14839                        .collect::<Result<Vec<_>, _>>()?;
14840                    params.push(key.clone());
14841                    params.push(SqlValue::Integer(*version));
14842                    statement
14843                        .execute(rusqlite::params_from_iter(params))
14844                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14845                }
14846                drop(statement);
14847                self.overlay_dirty.table(&table.name);
14848                self.rebuild_overlay()?;
14849                let mut batch = ChangeAccumulator::default();
14850                batch.table(&table.name);
14851                self.finish_observation("syncular_reveal", batch)
14852            })();
14853            if outcome.is_err() {
14854                self.rollback_observation("syncular_reveal");
14855            }
14856            outcome.map_err(storage)?;
14857        }
14858        Ok(())
14859    }
14860
14861    /// The visible (optimistic) row's values plus version, or `None` when the
14862    /// row is absent from the overlay.
14863    fn visible_row(&self, table: &TableSchema, row_id: &str) -> Result<Option<(Row, i64)>, String> {
14864        self.stored_row(table, row_id, false)
14865    }
14866
14867    fn stored_row(
14868        &self,
14869        table: &TableSchema,
14870        row_id: &str,
14871        base: bool,
14872    ) -> Result<Option<(Row, i64)>, String> {
14873        let sql = format!(
14874            "SELECT * FROM {} WHERE {}",
14875            if base {
14876                base_table(&table.name)
14877            } else {
14878                visible_table(&table.name)
14879            },
14880            row_id_predicate(table)
14881        );
14882        let mut stmt = self
14883            .conn
14884            .prepare_cached(&sql)
14885            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14886        let mut rows = stmt
14887            .query(rusqlite::params![row_id])
14888            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14889        let Some(row) = rows
14890            .next()
14891            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
14892        else {
14893            return Ok(None);
14894        };
14895        let mut values = Vec::with_capacity(table.columns.len());
14896        for (index, column) in table.columns.iter().enumerate() {
14897            let raw = row
14898                .get_ref(index)
14899                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14900            if let rusqlite::types::ValueRef::Blob(bytes) = raw {
14901                if table
14902                    .encrypted_columns
14903                    .iter()
14904                    .any(|encrypted| encrypted.index == index)
14905                {
14906                    values.push(Some(ColumnValue::Bytes(bytes.to_vec())));
14907                    continue;
14908                }
14909            }
14910            let json = sql_ref_to_json(column, raw);
14911            values.push(json_to_column_value(column, Some(&json)).map_err(|_| {
14912                "sync.local_corrupt: persisted local row value is invalid".to_owned()
14913            })?);
14914        }
14915        let version: i64 = row
14916            .get(table.columns.len())
14917            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14918        Ok(Some((values, version)))
14919    }
14920
14921    // -- realtime (§8) ---------------------------------------------------------------
14922
14923    /// §8.8: the configured realtime policy.
14924    #[must_use]
14925    pub fn realtime_policy(&self) -> RealtimePolicy {
14926        self.realtime_policy
14927    }
14928
14929    /// §8.8: the explicit realtime availability state.
14930    #[must_use]
14931    pub fn realtime_state(&self) -> RealtimeState {
14932        self.realtime_state
14933    }
14934
14935    /// §8.8: set the realtime policy. Refused while the socket is connected:
14936    /// a policy change never silently re-routes an ownership state.
14937    pub fn set_realtime_policy(&mut self, policy: RealtimePolicy) -> Result<(), String> {
14938        if self.realtime_state == RealtimeState::Connected && policy != self.realtime_policy {
14939            return Err(
14940                "sync.invalid_request: disconnect realtime before changing the realtime policy"
14941                    .to_owned(),
14942            );
14943        }
14944        self.realtime_policy = policy;
14945        match policy {
14946            RealtimePolicy::Off => self.set_realtime_state(RealtimeState::Disabled, None),
14947            RealtimePolicy::Required | RealtimePolicy::Optional
14948                if self.realtime_state == RealtimeState::Disabled =>
14949            {
14950                self.set_realtime_state(RealtimeState::Disconnected, None);
14951            }
14952            RealtimePolicy::Required | RealtimePolicy::Optional => {}
14953        }
14954        Ok(())
14955    }
14956
14957    /// Record an availability transition, keeping the reason code bounded and
14958    /// code-like (§7.6) and clearing it where it cannot apply.
14959    fn set_realtime_state(&mut self, state: RealtimeState, reason_code: Option<&str>) {
14960        self.realtime_state = state;
14961        self.realtime_reason_code = reason_code.map(Self::diagnostic_code);
14962        if matches!(state, RealtimeState::Connected | RealtimeState::Disabled) {
14963            self.realtime_reason_code = None;
14964            self.realtime_retry_delay_ms = None;
14965        }
14966    }
14967
14968    #[must_use]
14969    fn realtime_connected(&self) -> bool {
14970        self.realtime_state == RealtimeState::Connected
14971    }
14972
14973    pub fn connect_realtime(&mut self, transport: &mut dyn Transport) -> Result<(), String> {
14974        if self.transport_closed() {
14975            return Err("sync.offline: transport gate is closed".into());
14976        }
14977        if self.realtime_policy == RealtimePolicy::Off {
14978            return Err(
14979                "sync.invalid_request: realtime is off; realtime connect is refused".to_owned(),
14980            );
14981        }
14982        if self.realtime_connected() {
14983            return Ok(());
14984        }
14985        self.realtime_state = RealtimeState::Connecting;
14986        match transport.realtime_connect(&self.client_id) {
14987            Ok(()) => {
14988                self.set_realtime_state(RealtimeState::Connected, None);
14989                Ok(())
14990            }
14991            Err(error) => {
14992                self.set_realtime_state(RealtimeState::Refused, Some(&error.code));
14993                Err(format!("{}: {}", error.code, error.message))
14994            }
14995        }
14996    }
14997
14998    pub fn disconnect_realtime(&mut self, transport: &mut dyn Transport) {
14999        self.cancel_sync_round();
15000        // A deliberately disconnected or policy-disabled client has nothing
15001        // to release; a `lost` socket still does (the host owns the handle).
15002        if self.realtime_state == RealtimeState::Disconnected
15003            || self.realtime_state == RealtimeState::Disabled
15004        {
15005            return;
15006        }
15007        let _ = transport.realtime_close();
15008        self.set_realtime_state(
15009            if self.realtime_policy == RealtimePolicy::Off {
15010                RealtimeState::Disabled
15011            } else {
15012                RealtimeState::Disconnected
15013            },
15014            None,
15015        );
15016        self.presence.clear(); // §8.6.1: presence is per-connection
15017    }
15018
15019    /// §8.8: the host observed the socket end without disconnecting it (a
15020    /// peer close, an I/O error, a failed send; the native transport reports
15021    /// these as `Inbound::Disconnected`). Releases the transport, moves a
15022    /// `Connected` state to `Lost` with the transport's code as the reason, and schedules
15023    /// one background retry intent so the host reconnects and catches up.
15024    pub fn realtime_lost(&mut self, transport: &mut dyn Transport, error: &TransportError) {
15025        if self.realtime_state != RealtimeState::Connected {
15026            return;
15027        }
15028        self.cancel_sync_round();
15029        let _ = transport.realtime_close();
15030        self.set_realtime_state(RealtimeState::Lost, Some(&error.code));
15031        self.realtime_retry_delay_ms = Some(self.schedule_background_retry());
15032        self.presence.clear();
15033    }
15034
15035    /// §8.6.2: publish (or clear, `doc: None`) this client's presence
15036    /// document for `scope_key`. Requires a live socket; the document is
15037    /// ephemeral (lost on disconnect). Authorization is the connection's
15038    /// registration (§8.6.3) — an unheld key is rejected loudly by the
15039    /// server with `presence.forbidden`.
15040    pub fn set_presence(
15041        &mut self,
15042        transport: &mut dyn Transport,
15043        scope_key: &str,
15044        doc: Option<&Value>,
15045    ) -> Result<(), String> {
15046        if self.transport_closed() {
15047            return Err("sync.offline: transport gate is closed".into());
15048        }
15049        if !self.realtime_connected() {
15050            return Err("setPresence requires a connected realtime socket (§8.6)".to_string());
15051        }
15052        let text = encode_presence_publish(scope_key, doc);
15053        transport
15054            .realtime_send(&text)
15055            .map_err(|e| format!("{}: {}", e.code, e.message))
15056    }
15057
15058    /// §8.6: the peers currently present on a scope key (ephemeral).
15059    pub fn presence(&self, scope_key: &str) -> Vec<PresencePeer> {
15060        self.presence
15061            .get(scope_key)
15062            .map(|peers| peers.values().cloned().collect())
15063            .unwrap_or_default()
15064    }
15065
15066    /// §8.6 apply an inbound presence fanout to the local map.
15067    fn apply_presence(
15068        &mut self,
15069        scope_key: String,
15070        kind: Option<PresenceKind>,
15071        actor_id: Option<String>,
15072        client_id: Option<String>,
15073        doc: Option<Value>,
15074        error: Option<String>,
15075    ) {
15076        // A refused publish (§8.6.2) changes no peer; the native host surfaces
15077        // it as a `presence` event carrying the server's `error` code.
15078        if error.is_some() {
15079            return;
15080        }
15081        let (Some(kind), Some(actor_id), Some(client_id)) = (kind, actor_id, client_id) else {
15082            return;
15083        };
15084        let peer_key = format!("{actor_id} {client_id}");
15085        match kind {
15086            PresenceKind::Leave => {
15087                if let Some(peers) = self.presence.get_mut(&scope_key) {
15088                    peers.remove(&peer_key);
15089                    if peers.is_empty() {
15090                        self.presence.remove(&scope_key);
15091                    }
15092                }
15093            }
15094            _ => {
15095                let doc = match doc {
15096                    Some(Value::Object(_)) => doc.unwrap(),
15097                    _ => return,
15098                };
15099                self.presence.entry(scope_key).or_default().insert(
15100                    peer_key,
15101                    PresencePeer {
15102                        actor_id,
15103                        client_id,
15104                        doc,
15105                    },
15106                );
15107            }
15108        }
15109    }
15110
15111    /// Inbound JSON control message (§8.1). Unknown events are tolerated.
15112    pub fn on_realtime_text(&mut self, text: &str) {
15113        if self.stopped || self.transport_closed() || self.security_preflight {
15114            return;
15115        }
15116        match parse_control(text) {
15117            Ok(ControlMessage::Hello { requires_sync, .. }) => {
15118                if requires_sync {
15119                    // §8.1: pull before trusting the socket for continuity.
15120                    self.set_sync_needed(true, true);
15121                }
15122            }
15123            Ok(ControlMessage::Presence {
15124                scope_key,
15125                kind,
15126                actor_id,
15127                client_id,
15128                doc,
15129                error,
15130                ..
15131            }) => {
15132                self.apply_presence(scope_key, kind, actor_id, client_id, doc, error);
15133            }
15134            Ok(ControlMessage::Wake { .. }) => {
15135                // §8.3: any wake-up means "run a pull soon", never data.
15136                self.set_sync_needed(true, true);
15137            }
15138            Ok(ControlMessage::Scopes { .. }) => {
15139                // §3.3/§8.7: the grants changed, so the next `set_window`
15140                // re-arms every revoked value it names. No sync-needed, no round.
15141                self.window_armed.clear();
15142                self.scopes_changed += 1;
15143            }
15144            _ => {}
15145        }
15146    }
15147
15148    /// Inbound binary delta: a complete SSP2 response (§8.2), applied like
15149    /// a pull response per section; an unapplied delta is a wake-up.
15150    /// Mailbox hosts send durable acknowledgements on their I/O executor.
15151    pub fn on_realtime_binary_queued(&mut self, bytes: &[u8]) -> Vec<String> {
15152        let mut transport = crate::round::DownloadResults::default();
15153        self.on_realtime_binary(&mut transport, bytes);
15154        transport.controls
15155    }
15156
15157    /// §8.2: a delta applies exactly like a live section and sets the replica
15158    /// cursor to its `throughSeq`; one at or below the replica cursor is a
15159    /// duplicate. A delta the client does not apply (no live unit, a status
15160    /// other than `active`, a decode or apply failure) is a drop and raises
15161    /// sync-needed.
15162    pub fn on_realtime_binary(&mut self, transport: &mut dyn Transport, bytes: &[u8]) {
15163        if self.stopped || self.transport_closed() || self.security_preflight {
15164            return;
15165        }
15166        #[cfg(feature = "bench-internals")]
15167        let decode_phase = self.benchmark_phases.start(Phase::ResponseDecode);
15168        let message = match decode_message(bytes) {
15169            Ok(m) if m.msg_kind == MsgKind::Response => m,
15170            _ => {
15171                self.set_sync_needed(true, true);
15172                return;
15173            }
15174        };
15175        #[cfg(feature = "bench-internals")]
15176        drop(decode_phase);
15177        // §8.2: a delta's header means what a pull response's header means. A
15178        // schema floor (§1.6) is recorded, stops syncing and applies nothing.
15179        if let Some(Frame::RespHeader {
15180            required_schema_version: Some(required),
15181            latest_schema_version,
15182            ..
15183        }) = message.frames.first()
15184        {
15185            let floor = SchemaFloor {
15186                required_schema_version: Some(*required),
15187                latest_schema_version: *latest_schema_version,
15188            };
15189            if self.set_schema_floor(Some(floor)).is_err() {
15190                self.set_sync_needed(true, true);
15191            }
15192            return;
15193        }
15194        let through = message.frames.iter().find_map(|frame| match frame {
15195            Frame::LiveEnd { through_seq, .. } => Some(*through_seq),
15196            _ => None,
15197        });
15198        let epoch = self.get_meta(LOG_EPOCH_KEY).ok().flatten();
15199        let mut dropped = !matches!(message.frames.first(), Some(Frame::RespHeader {
15200                reset_required: false,
15201                log_epoch,
15202                ..
15203            }) if Some(log_epoch) == epoch.as_ref());
15204        let mut applied: Option<i64> = None;
15205        dropped |= self.begin_coalesced_apply().is_err();
15206        let mut receivers: Option<Vec<UnitRecord>> = None;
15207        for frame in message.frames {
15208            if dropped {
15209                break;
15210            }
15211            match frame {
15212                Frame::LiveStart { status, .. } => {
15213                    let Ok(cursor) = self.stored(replica_cursor(&self.conn)) else {
15214                        dropped = true;
15215                        break;
15216                    };
15217                    if status != LiveStatus::Active || cursor < 0 {
15218                        dropped = true;
15219                    } else if !through.is_some_and(|through| through <= cursor) {
15220                        // A catching-up unit receives no delta (§8.2).
15221                        receivers = self.stored(load_units(&self.conn)).ok().map(|units| {
15222                            units
15223                                .into_iter()
15224                                .filter(|unit| {
15225                                    unit.status == UnitStatus::Active
15226                                        && unit.echo.is_some()
15227                                        && unit.cursor.is_none()
15228                                })
15229                                .collect()
15230                        });
15231                        dropped = receivers.is_none();
15232                    }
15233                }
15234                Frame::Commit {
15235                    commit_seq,
15236                    tables,
15237                    changes,
15238                    ..
15239                } => {
15240                    let Some(receivers) = receivers.clone() else {
15241                        continue;
15242                    };
15243                    dropped = self
15244                        .apply_live_commit(
15245                            &receivers,
15246                            &tables,
15247                            changes,
15248                            commit_seq,
15249                            AppliedServerCommitSource::Delta,
15250                        )
15251                        .is_err();
15252                }
15253                Frame::LiveEnd { through_seq, .. } if receivers.is_some() => {
15254                    dropped = self
15255                        .set_meta(REPLICA_CURSOR_KEY, &through_seq.to_string())
15256                        .is_err();
15257                    applied = Some(through_seq);
15258                }
15259                Frame::Error { .. } => dropped = true,
15260                _ => {}
15261            }
15262        }
15263        // §1.4 rule 4: the ack follows the COMMIT. A failed COMMIT restored
15264        // the replica cursor, so the delta counts as a drop.
15265        if self.finish_coalesced_apply().is_err() || dropped {
15266            applied = None;
15267            dropped = true;
15268        }
15269        if let Some(cursor) = applied {
15270            // §8.2 ack point: the delta's throughSeq.
15271            let ack = format!("{{\"type\":\"ack\",\"cursor\":{cursor}}}");
15272            let _ = transport.realtime_send(&ack);
15273        }
15274        if dropped {
15275            self.set_sync_needed(true, true);
15276        }
15277    }
15278
15279    /// §8.2 ack point after a pull round on a live connection: the replica
15280    /// cursor while it is at least `0`.
15281    fn ack_after_pull(&mut self, transport: &mut dyn Transport) {
15282        if !self.realtime_connected() {
15283            return;
15284        }
15285        if let Ok(cursor @ 0..) = self.stored(replica_cursor(&self.conn)) {
15286            let ack = format!("{{\"type\":\"ack\",\"cursor\":{cursor}}}");
15287            let _ = transport.realtime_send(&ack);
15288        }
15289    }
15290}
15291
15292#[cfg(test)]
15293mod previous_version_wiring_tests;
15294
15295#[cfg(test)]
15296mod identity_tests;
15297
15298#[cfg(test)]
15299mod insert_intent_tests;
15300
15301#[cfg(test)]
15302mod robustness_tests;
15303
15304#[cfg(test)]
15305mod range_image_tests;