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, AuthorityQuery,
36    AuthorityQueryResult, AuthorityReadResult, ClientChangeBatch, ClientDiagnosticsHost,
37    ClientDiagnosticsLease, ClientDiagnosticsReplica, ClientDiagnosticsSchema,
38    ClientDiagnosticsSnapshot, ClientDiagnosticsStorage, ClientError, ClientLimits, CommandEffects,
39    CommitDelivery, CommitOperation, CommitOperationOutcome, CommitOutcome, CommitOutcomeQuery,
40    CommitOutcomeResolution, CommitOutcomeStatus, ConflictRecord, CoverageSnapshot,
41    CurrentBaseProof, CurrentBaseProofReason, DiagnosticLastChange, DiagnosticLastRound,
42    DiagnosticQueryFailure, DiagnosticRoundCounters, DiagnosticUnits, EchoRecord, FetchedBlob,
43    LeaseState, LocalDataPurgeInput, LocalDataPurgeResult, LocalDataPurgeTarget,
44    LocalDataRebootstrapInput, LocalDataRebootstrapResult, Mutation, PendingCommit, PresencePeer,
45    PreviousVersionStatus, QueryOwner, QueryReadFailure, QueryRow, QuerySnapshot, QueryValue,
46    RejectionDetails, RejectionRecord, ResolveCommitOutcomeInput, RetainedCommitRow,
47    RetainedUniqueConflict, RowState, SchemaFloor, SnapshotRead, SyncIntent, SyncOutcome,
48    SyncReport, SyncStatusSnapshot, TableChange, UnitCatchup, UnitRecord, UnitRestriction,
49    UnitScopes, UnitStatus, WindowBase, WindowChange, WindowCoverage, WindowState, WindowUnitRef,
50    CLIENT_DIAGNOSTICS_VERSION, MAX_DIAGNOSTIC_QUERY_FAILURES,
51};
52use crate::api::{RealtimePolicy, RealtimeState, REALTIME_UNAVAILABLE_CODE};
53#[cfg(feature = "bench-internals")]
54use crate::bench::{Phase, Recorder};
55use crate::previous_version::{
56    capture_previous_version_from_replica, first_incompatibility,
57    reconcile_previous_version_at_boot, set_local_schema_descriptor,
58    sweep_previous_version_container, PendingCommitAudit, PreviousVersionContextConfig,
59    PreviousVersionLifecycle, PreviousVersionReadSpec, PreviousVersionSnapshot,
60};
61mod projection;
62pub use projection::ProjectionInput;
63
64use crate::schema::{parse_schema_json, ClientSchema, TableSchema};
65use crate::transport::{BlobDownload, SegmentRequest, Transport, TransportError};
66use crate::values::{
67    bytes_to_hex, column_value_to_json, decode_row_bytes, encode_sparse_row_json, full_row_values,
68    is_canonical_bytes_envelope, json_to_column_value, json_to_scope_map, normalize_values_casing,
69    render_row_id_json, scope_map_to_json, SealedRow,
70};
71
72/// §4.2 default: rows and SQLite images, both applied in committed chunks.
73/// Bit 3 (signed URLs, §5.4) is
74/// added per transport capability at request-build time.
75const DEFAULT_ACCEPT: u8 = 0b0111;
76const ACCEPT_INLINE_ROWS: u8 = 1 << 0;
77const ACCEPT_EXTERNAL_ROWS: u8 = 1 << 1;
78const ACCEPT_SQLITE: u8 = 1 << 2;
79const ACCEPT_SIGNED_URLS: u8 = 1 << 3;
80const MAX_DIAGNOSTIC_DOMAINS: usize = 256;
81
82/// §10.1 `recommendedAction` carried by a server HTTP error body.
83fn recommended_action_of(details: &Option<Value>) -> Option<String> {
84    details
85        .as_ref()?
86        .get("recommendedAction")?
87        .as_str()
88        .map(str::to_owned)
89}
90
91/// §7.4.1 persisted local schema-version marker (`_syncular_meta` key).
92pub(crate) const LOCAL_SCHEMA_VERSION_KEY: &str = "localSchemaVersion";
93const LOCAL_REVISION_KEY: &str = "localRevision";
94/// §4.5 replica cursor; absent means `-1`.
95const REPLICA_CURSOR_KEY: &str = "replicaCursor";
96/// Hex of the last pull `LIVE_END.echoDigest` (§4.2); absent means empty.
97const ECHO_DIGEST_KEY: &str = "echoDigest";
98/// Hex of the registration digest of the list the server stores (§4.1).
99const REGISTERED_DIGEST_KEY: &str = "registrationDigest";
100/// §7.4.3: table name → generation, persisted with the declaration evidence.
101const TABLE_GENERATIONS_KEY: &str = "localTableGenerations";
102/// §7.1: the identity of the outbox sequence.
103const OUTBOX_ID_KEY: &str = "outboxId";
104const CLIENT_ID_KEY: &str = "clientId";
105const LEASE_STATE_KEY: &str = "leaseState";
106const SCHEMA_FLOOR_KEY: &str = "schemaFloor";
107pub(crate) const LOG_EPOCH_KEY: &str = "logEpoch";
108/// Persisted fail-closed quarantine marker: present while a security preflight
109/// is pending and `activateSecurity` has yet to run. Storing it in the replica
110/// keeps the gate with the data it protects, so a rebuilt host handle reopening
111/// the same file returns in preflight even though its in-memory state is fresh.
112const SECURITY_PREFLIGHT_PENDING_KEY: &str = "securityPreflightPending";
113const LOCAL_REBOOTSTRAP_RECEIPT_VERSION: u8 = 2;
114const MAX_JS_SAFE_INTEGER: u64 = 9_007_199_254_740_991;
115/// §7.4.4 client-local code: a pending outbox commit cannot re-encode under
116/// the new schema after a bump. Never a wire code (§10.3).
117const OUTBOX_INCOMPATIBLE_CODE: &str = "sync.outbox_incompatible";
118/// §5.11 client-local code: an encode at the push seam resolved no usable key
119/// id or named an unknown key. Never a wire code (§10.3).
120const ENCRYPT_FAILED_CODE: &str = "client.encrypt_failed";
121const INVALID_REQUEST_CODE: &str = "sync.invalid_request:";
122/// §7.4.4: static text for a persisted commit the current codec refuses.
123const LEGACY_VALUE_REFUSAL_MESSAGE: &str =
124    "the persisted commit carries values the current codec refuses";
125/// §7.4.4: bounded reason on every intrinsic value drop.
126const INVALID_STORED_VALUES_REASON: &str = "invalid_stored_values";
127/// §7.2.2: an outcome with a pending decision accepts no other resolution.
128const REPLACEMENT_PENDING: &str =
129    "client.replacement_pending: the outcome has a pending replacement";
130/// §7.2.2 client-local code: a pending replacement was not written.
131const REPLACEMENT_REFUSED_CODE: &str = "sync.replacement_refused";
132/// §7.2.1/§7.2.3 client-local journal result of a replaced commit's operations.
133const COMMIT_REPLACED_CODE: &str = "client.commit_replaced";
134
135#[derive(Debug, Serialize, Deserialize)]
136#[serde(rename_all = "camelCase", deny_unknown_fields)]
137struct PersistedLocalDataRebootstrapReceipt {
138    version: u8,
139    retained_commits: u64,
140    reset_subscriptions: u64,
141}
142
143fn invalid_local_rebootstrap_receipt() -> String {
144    "sync.local_corrupt: persisted local rebootstrap receipt is invalid".to_owned()
145}
146
147fn encode_local_rebootstrap_receipt(
148    retained_commits: usize,
149    reset_subscriptions: usize,
150) -> Result<String, String> {
151    let retained_commits =
152        u64::try_from(retained_commits).map_err(|_| invalid_local_rebootstrap_receipt())?;
153    let reset_subscriptions =
154        u64::try_from(reset_subscriptions).map_err(|_| invalid_local_rebootstrap_receipt())?;
155    if retained_commits > MAX_JS_SAFE_INTEGER || reset_subscriptions > MAX_JS_SAFE_INTEGER {
156        return Err(invalid_local_rebootstrap_receipt());
157    }
158    serde_json::to_string(&PersistedLocalDataRebootstrapReceipt {
159        version: LOCAL_REBOOTSTRAP_RECEIPT_VERSION,
160        retained_commits,
161        reset_subscriptions,
162    })
163    .map_err(|_| invalid_local_rebootstrap_receipt())
164}
165
166fn decode_local_rebootstrap_receipt(value: &str) -> Result<(usize, usize), String> {
167    // Pre-0.15.36 markers proved application but did not retain the receipt.
168    if value == "v1" {
169        return Ok((0, 0));
170    }
171    let receipt: PersistedLocalDataRebootstrapReceipt =
172        serde_json::from_str(value).map_err(|_| invalid_local_rebootstrap_receipt())?;
173    if receipt.version != LOCAL_REBOOTSTRAP_RECEIPT_VERSION
174        || receipt.retained_commits > MAX_JS_SAFE_INTEGER
175        || receipt.reset_subscriptions > MAX_JS_SAFE_INTEGER
176    {
177        return Err(invalid_local_rebootstrap_receipt());
178    }
179    Ok((
180        usize::try_from(receipt.retained_commits)
181            .map_err(|_| invalid_local_rebootstrap_receipt())?,
182        usize::try_from(receipt.reset_subscriptions)
183            .map_err(|_| invalid_local_rebootstrap_receipt())?,
184    ))
185}
186
187#[cfg(test)]
188mod observation_tests;
189
190/// Internal state for hosts that perform network I/O outside the client owner.
191#[doc(hidden)]
192#[derive(Clone)]
193pub struct CurrentBasePreparation {
194    client_commit_id: String,
195    sequence: i64,
196    /// §7.2.2: the pending replacement a drive evaluates; `None` for
197    /// `proveCurrentBase`.
198    replacement: Option<String>,
199    units: Vec<UnitRecord>,
200    transport_epoch: u64,
201    registration_epoch: u64,
202    security_epoch: u64,
203}
204
205#[cfg(test)]
206mod units_tests;
207
208#[cfg(test)]
209mod replace_outcome_tests;
210
211#[cfg(test)]
212mod pending_replacement_tests;
213
214/// A §6.12 fence round that [`SyncClient::prepare_pending_commit_replacement`]
215/// prepared on the owner. Send [`PreparedFenceRound::request_bytes`] as a sync
216/// request (over the realtime socket when [`PreparedFenceRound::realtime`] is
217/// set) and hand the reply to [`SyncClient::apply_fence_round`]; a host with a
218/// blocking [`Transport`] calls [`PreparedFenceRound::exchange`].
219pub struct PreparedFenceRound {
220    id: uuid::Uuid,
221    client_commit_id: String,
222    replacement_client_commit_id: String,
223    operations: Vec<OutboxOp>,
224    request: Vec<u8>,
225    realtime: bool,
226}
227
228impl PreparedFenceRound {
229    pub fn request_bytes(&self) -> &[u8] {
230        &self.request
231    }
232
233    pub fn realtime(&self) -> bool {
234        self.realtime
235    }
236
237    /// Send the request without accessing client state.
238    pub fn exchange(&self, transport: &mut dyn Transport) -> Result<Vec<u8>, TransportError> {
239        if self.realtime {
240            transport.realtime_sync(&self.request)
241        } else {
242            transport.sync(&self.request)
243        }
244    }
245}
246
247#[derive(Debug, Clone)]
248struct OutboxOp {
249    upsert: bool,
250    table: String,
251    row_id: String,
252    base_version: Option<i64>,
253    /// Schema-agnostic local form (§0): driver JSON values, encoded with
254    /// the current codec at send time. A key's presence IS the §6.1 sparse
255    /// presence set — both the overlay and the wire payload derive from it.
256    values: Option<Map<String, Value>>,
257    /// §7.1 insert intent: `mutate` recorded this upsert while the row was
258    /// absent from the visible replica. Replay and send-time encoding present
259    /// every current-schema column; a column `values` lacks is NULL.
260    insert: bool,
261}
262
263impl OutboxOp {
264    /// The values this upsert presents under the current `table` (§7.1). An
265    /// insert-intent operation presents every column, a missing one as NULL;
266    /// `None` when a missing column is non-nullable, which leaves the commit
267    /// unencodable (§7.4.4), or when the operation carries no values.
268    fn presented_values(&self, table: &TableSchema) -> Option<Cow<'_, Map<String, Value>>> {
269        let values = self.values.as_ref()?;
270        if !self.insert || table.columns.iter().all(|c| values.contains_key(&c.name)) {
271            return Some(Cow::Borrowed(values));
272        }
273        full_row_values(table, values.clone()).ok().map(Cow::Owned)
274    }
275}
276
277impl From<CommitOperation> for OutboxOp {
278    fn from(operation: CommitOperation) -> Self {
279        Self {
280            upsert: operation.op == "upsert",
281            table: operation.table,
282            row_id: operation.row_id,
283            base_version: operation.base_version,
284            values: operation.values,
285            insert: operation.insert,
286        }
287    }
288}
289
290/// §7.5 static authoring refusal; the table and column travel in details.
291fn invalid_authoring(message: &str, details: Value) -> ClientError {
292    ClientError {
293        code: "sync.invalid_request".to_owned(),
294        message: message.to_owned(),
295        details: Some(details),
296        retryable: false,
297    }
298}
299
300/// §7.1 chained base: `later` repeats `earlier`'s positive base on the same
301/// row and presents only columns `earlier` presents.
302fn chains_on(earlier: &OutboxOp, later: &OutboxOp) -> bool {
303    // Only an upsert carries values, and it always carries its primary key.
304    earlier.row_id == later.row_id
305        && earlier.table == later.table
306        && later.base_version.is_some_and(|base| base > 0)
307        && earlier.base_version == later.base_version
308        && later.values.as_ref().is_some_and(|values| {
309            values.keys().all(|column| {
310                earlier
311                    .values
312                    .as_ref()
313                    .is_some_and(|earlier| earlier.contains_key(column))
314            })
315        })
316}
317
318impl From<&OutboxOp> for CommitOperation {
319    fn from(operation: &OutboxOp) -> Self {
320        Self {
321            table: operation.table.clone(),
322            row_id: operation.row_id.clone(),
323            op: if operation.upsert { "upsert" } else { "delete" }.to_owned(),
324            base_version: operation.base_version,
325            values: operation.values.clone(),
326            insert: operation.insert,
327        }
328    }
329}
330
331#[derive(Debug, Clone)]
332struct OutboxCommit {
333    client_commit_id: String,
334    ops: Vec<OutboxOp>,
335}
336
337/// One commit's `(table, value keys, insert intent)` per upsert operation — the classification
338/// shape the §7.4.4 send-time drop and the RFC 0005 D6 audit share, so the two
339/// can never disagree about which commits cannot re-encode.
340fn commit_audit_operations(commit: &OutboxCommit) -> Vec<(&str, Vec<&str>, bool)> {
341    commit
342        .ops
343        .iter()
344        .filter(|operation| operation.upsert)
345        .map(|operation| {
346            (
347                operation.table.as_str(),
348                operation
349                    .values
350                    .as_ref()
351                    .map(|values| values.keys().map(String::as_str).collect())
352                    .unwrap_or_default(),
353                operation.insert,
354            )
355        })
356        .collect()
357}
358
359type FailedCommit = (OutboxCommit, Map<String, Value>);
360
361#[derive(Debug, Clone)]
362struct CompiledLocalDataPurgeTarget {
363    table: String,
364    selectors: Vec<(String, Vec<String>)>,
365}
366
367struct CompiledLocalDataPurge {
368    targets: Vec<CompiledLocalDataPurgeTarget>,
369    projections: BTreeSet<String>,
370    canonical_plan: String,
371}
372
373struct StoredCommitOutcomeRow {
374    sequence: i64,
375    client_commit_id: String,
376    status: String,
377    recorded_at_ms: i64,
378    results_json: String,
379    operations_json: Option<String>,
380    resolution: String,
381    resolved_at_ms: Option<i64>,
382    replacement_client_commit_id: Option<String>,
383}
384
385impl StoredCommitOutcomeRow {
386    fn from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Self> {
387        Ok(Self {
388            sequence: row.get(0)?,
389            client_commit_id: row.get(1)?,
390            status: row.get(2)?,
391            recorded_at_ms: row.get(3)?,
392            results_json: row.get(4)?,
393            operations_json: row.get(5)?,
394            resolution: row.get(6)?,
395            resolved_at_ms: row.get(7)?,
396            replacement_client_commit_id: row.get(8)?,
397        })
398    }
399}
400
401/// Section outcome distinguishing the §5.6 unit-local fail-closed
402/// path from a round-aborting failure (§1.4 rule 5).
403/// §4.4 a unit section's `SUB_START`.
404struct SectionStart {
405    id: String,
406    status: SubStatus,
407    reason_code: String,
408    bootstrap: bool,
409    fenced: Vec<FencedRecord>,
410}
411
412enum SectionError {
413    FailClosed,
414    /// §5.5: the server refused a segment with `sync.forbidden`.
415    Refused,
416    /// §5.3 client memory: the round deferred this image's body to a later
417    /// pull of the same resume token.
418    Deferred,
419    Abort(String, String),
420    Transport(TransportError),
421}
422
423#[derive(Debug)]
424pub(crate) struct RequestMeta {
425    pushed_ids: Vec<String>,
426    /// Hex of the registration digest this pull carried; the server stores
427    /// that list once the round completes (§4.1).
428    registration_digest: String,
429    pub(crate) accept: u8,
430    /// §6.1 splitBatch: outbox commits held back from THIS request because
431    /// the running operation count reached the push cap — the next round
432    /// pushes them (`sync_needed` stays set while any remain).
433    deferred_commits: usize,
434    /// §5.6 applied-segment record per unit: segment id → rows applied at
435    /// the unit's current cursor and token.
436    pub(crate) applied: BTreeMap<String, BTreeMap<String, i64>>,
437    /// §5.3 client memory: (unit, segment id) of the first image whose body
438    /// the round did not fetch because the batch already holds two images.
439    /// That unit's section stops there without persisting `SUB_END`.
440    pub(crate) deferred: BTreeSet<(String, String)>,
441}
442
443#[derive(Default)]
444struct ChangeAccumulator {
445    /// None means table-wide; Some is the exact scoped domain.
446    tables: BTreeMap<String, Option<BTreeSet<String>>>,
447    windows: BTreeMap<String, BTreeSet<String>>,
448    status: bool,
449    conflicts: bool,
450    rejections: bool,
451    outcomes: bool,
452}
453
454impl ChangeAccumulator {
455    fn table(&mut self, table: &str) {
456        self.tables.insert(table.to_owned(), None);
457    }
458
459    fn scope(&mut self, table: &str, key: String) {
460        match self.tables.get_mut(table) {
461            Some(None) => {}
462            Some(Some(keys)) => {
463                keys.insert(key);
464            }
465            None => {
466                self.tables
467                    .insert(table.to_owned(), Some(BTreeSet::from([key])));
468            }
469        }
470    }
471
472    fn window(&mut self, base_key: &str, value: &str) {
473        self.windows
474            .entry(base_key.to_owned())
475            .or_default()
476            .insert(value.to_owned());
477    }
478
479    fn touched(&self) -> bool {
480        !self.tables.is_empty()
481            || !self.windows.is_empty()
482            || self.status
483            || self.conflicts
484            || self.rejections
485            || self.outcomes
486    }
487}
488
489/// §6.1: the server caps total operations per request (reference default
490/// 500) and rejects the whole batch with `sync.too_many_operations`; the
491/// client "splits and retries". Splitting happens at build time: commits are
492/// included IN ORDER until the operation budget is spent, the rest wait for
493/// the next round.
494const PUSH_OPS_PER_REQUEST: usize = 500;
495const MAX_LOCAL_PURGE_TARGETS: usize = 64;
496const MAX_LOCAL_PURGE_SELECTORS: usize = 8;
497const MAX_LOCAL_PURGE_VALUES: usize = 128;
498const MAX_LOCAL_PURGE_VALUE_LENGTH: usize = 256;
499pub const SECURITY_PREFLIGHT_REQUIRED_CODE: &str = "client.security_preflight_required";
500
501/// Dirty visible tables; `None` means a whole-replica recovery/reset.
502struct OverlayDirty(RefCell<Option<BTreeSet<String>>>);
503
504impl OverlayDirty {
505    fn clean() -> Self {
506        Self(RefCell::new(Some(BTreeSet::new())))
507    }
508    fn get(&self) -> bool {
509        self.0
510            .borrow()
511            .as_ref()
512            .is_none_or(|tables| !tables.is_empty())
513    }
514    fn set(&self, dirty: bool) {
515        *self.0.borrow_mut() = if dirty { None } else { Some(BTreeSet::new()) };
516    }
517    fn table(&self, table: &str) {
518        if let Some(tables) = self.0.borrow_mut().as_mut() {
519            tables.insert(table.to_owned());
520        }
521    }
522    fn snapshot(&self) -> Option<BTreeSet<String>> {
523        self.0.borrow().clone()
524    }
525    fn restore(&self, tables: Option<BTreeSet<String>>) {
526        *self.0.borrow_mut() = tables;
527    }
528}
529
530/// A copy-on-write in-memory mirror: a [`Rollback`] shares it, and the first
531/// write after a capture copies it once.
532#[derive(Debug, Clone, Default)]
533struct Shared<T>(Arc<T>);
534
535impl<T> std::ops::Deref for Shared<T> {
536    type Target = T;
537    fn deref(&self) -> &T {
538        &self.0
539    }
540}
541
542impl<T: Clone> std::ops::DerefMut for Shared<T> {
543    fn deref_mut(&mut self) -> &mut T {
544        Arc::make_mut(&mut self.0)
545    }
546}
547
548impl<T> From<T> for Shared<T> {
549    fn from(value: T) -> Self {
550        Self(Arc::new(value))
551    }
552}
553
554/// The in-memory mirrors of durable state, captured before a local
555/// transaction and restored when it rolls back. Queues only grow inside a
556/// transaction, so their lengths suffice.
557#[derive(Debug, Clone)]
558struct Rollback {
559    outbox: Shared<Vec<Arc<OutboxCommit>>>,
560    failed_commits: Shared<Vec<FailedCommit>>,
561    conflicts: Shared<Vec<ConflictRecord>>,
562    rejections: Shared<Vec<RejectionRecord>>,
563    schema_floor: Option<SchemaFloor>,
564    lease_state: Option<LeaseState>,
565    stopped: bool,
566    upgrading: bool,
567    upgrade_kept_tables: bool,
568    sync_needed: bool,
569    active_round: Option<(uuid::Uuid, i64, u64)>,
570    overlay_dirty: Option<BTreeSet<String>>,
571    transport_gate: crate::TransportGate,
572    transport_epoch: u64,
573    change_queue: usize,
574    projection_pending_queue: usize,
575    sync_intent_queue: usize,
576    last_change: Option<DiagnosticLastChange>,
577}
578
579pub struct SyncClient {
580    #[cfg(feature = "bench-internals")]
581    benchmark_phases: Recorder,
582    conn: Connection,
583    schema: ClientSchema,
584    client_id: String,
585    limits: ClientLimits,
586    outbox: Shared<Vec<Arc<OutboxCommit>>>,
587    failed_commits: Shared<Vec<FailedCommit>>,
588    retain_failed_commits: bool,
589    conflicts: Shared<Vec<ConflictRecord>>,
590    rejections: Shared<Vec<RejectionRecord>>,
591    schema_floor: Option<SchemaFloor>,
592    /// §7.3.5: the opaque auth-lease state (from LEASE frames + lease errors).
593    lease_state: Option<LeaseState>,
594    /// §1.6: the schema-floor response stops syncing until an upgrade.
595    stopped: bool,
596    /// §7.4.5: true while a schema-bump reset + first re-bootstrap is in flight.
597    upgrading: bool,
598    /// §7.4.5: the running reset kept at least one table.
599    upgrade_kept_tables: bool,
600    /// §8.4 coalesced sync-needed signal.
601    sync_needed: bool,
602    /// §8.8: how sync rounds treat the realtime binding, and its exact
603    /// availability state with the evidence behind a lost or refused one.
604    realtime_policy: RealtimePolicy,
605    realtime_state: RealtimeState,
606    realtime_reason_code: Option<String>,
607    realtime_retry_delay_ms: Option<u64>,
608    /// §8.6 presence: scopeKey → (`actorId clientId` peer key → peer).
609    presence: HashMap<String, HashMap<String, PresencePeer>>,
610    /// Client clock (epoch ms) for the §5.4 `urlExpiresAtMs` check and the
611    /// §7.8 drive deadline; the host may pin it and move the pinned value
612    /// (conformance runs on a virtual clock).
613    now_ms: Option<std::sync::Arc<std::sync::atomic::AtomicI64>>,
614    /// §5.11 client-side encryption keys (`keyId → key bytes`). Empty ⇒ E2EE
615    /// off. The encrypt/decrypt seam (`values.rs`) is compiled only under the
616    /// `e2ee` feature; without it, a schema with encrypted columns fails loud.
617    encryption: crate::values::EncryptionConfig,
618    /// Fail-closed host bootstrap gate. While set, command hosts permit only
619    /// status/lifecycle inspection and an exact authorized local purge.
620    security_preflight: bool,
621    security_epoch: u64,
622    transport_gate: crate::TransportGate,
623    transport_epoch: u64,
624    /// Raised by every registration change; a current-base proof spanning
625    /// one reports missing coverage.
626    registration_epoch: u64,
627    /// RFC 0005 D2/D8: the previous-version capture config. `None` (default)
628    /// means the feature is off; the descriptor write and the container orphan
629    /// sweep still happen.
630    previous_version: Option<PreviousVersionContextConfig>,
631    /// Per-table primary-key upsert SQL, built once per (full table name) —
632    /// the row write path runs per row during bootstrap (§5.6), so the SQL
633    /// string (and, via `prepare_cached`, its compiled statement) is reused
634    /// instead of being rebuilt and re-prepared per row. Cleared on a §7.4.3
635    /// schema reset (the column lists may have changed).
636    insert_sql: RefCell<HashMap<String, String>>,
637    /// §7.1: reconcile only tables whose base/outbox changed. Whole-replica
638    /// reset and restart explicitly invalidate every table.
639    overlay_dirty: OverlayDirty,
640    // First SQLite failure of the current operation, before savepoint cleanup.
641    storage_failure: RefCell<Option<QueryReadFailure>>,
642    /// Test-only structural performance signal: response processing must not
643    /// turn a batch of acknowledgements into one full overlay rebuild each.
644    #[cfg(test)]
645    overlay_rebuild_count: Cell<usize>,
646    #[cfg(test)]
647    acknowledged_replay_count: Cell<usize>,
648    /// Test-only structural performance signal: outcome retention is enforced
649    /// once per response rather than once per acknowledgement.
650    #[cfg(test)]
651    outcome_prune_count: Cell<usize>,
652    /// Test-only pinned write and commit time of every §5.3 image chunk, in ms.
653    #[cfg(test)]
654    image_chunk_ms: Cell<Option<(f64, f64)>>,
655    /// Exact observer-transaction output drained by command/FFI hosts.
656    progress: ProgressObserver,
657    /// §7.6: random per core instance, never persisted or sent.
658    epoch: String,
659    change_queue: VecDeque<ClientChangeBatch>,
660    projection_pending_queue: VecDeque<String>,
661    opening_replica: bool,
662    sync_intent_queue: VecDeque<SyncIntent>,
663    /// §8.7 `scopes` events received since the last drain.
664    scopes_changed: usize,
665    /// §3.3: units `set_window` registered or re-armed and no round accepted since.
666    window_armed: HashSet<String>,
667    /// Explicit exponential retry policy for transient transport failures.
668    retry_delay_ms: u64,
669    /// §7.7: the background retry the current round scheduled, if any.
670    round_retry_delay_ms: Option<u64>,
671    /// §5.3: a table's next image chunk size, carried from one range image
672    /// of the table to the next.
673    image_chunk_rows: HashMap<String, u32>,
674    /// A round whose response never completed (§1.5): the client keeps its
675    /// code and reports it on every following request until a round receives a
676    /// complete, decodable response. The server already recorded the round, so
677    /// nothing else can tell it the round failed on this side.
678    round_failure: Option<String>,
679    /// The in-flight round: its id, `started_at_ms` and progress attempt.
680    active_round: Option<(uuid::Uuid, i64, u64)>,
681    /// The in-flight §6.12 fence round, serialized with sync rounds.
682    fence_round: Option<uuid::Uuid>,
683    last_round: Option<DiagnosticLastRound>,
684    last_change: Option<DiagnosticLastChange>,
685    /// §7.6: latest failed owned snapshot read per owner id, oldest first.
686    query_failures: Vec<DiagnosticQueryFailure>,
687    /// SPEC §1.4 rule 4: the open coalesced apply transaction of a response.
688    coalesced: Option<CoalescedApply>,
689    /// A coalesced apply transaction of the current response failed; every
690    /// later observation of that response fails until it ends.
691    coalesced_failure: Option<String>,
692}
693
694/// SPEC §1.4 rule 4: the frames and blocks of one response share one local
695/// write transaction of at most `COALESCED_APPLY_ROWS` rows. The in-memory
696/// state captured at its `BEGIN` is restored when its `COMMIT` fails.
697struct CoalescedApply {
698    rows: usize,
699    rollback: Rollback,
700}
701
702const COALESCED_APPLY_ROWS: usize = 1024;
703
704pub(crate) fn quote_ident(name: &str) -> String {
705    format!("\"{}\"", name.replace('"', "\"\""))
706}
707/// §7.4.1 `_syncular_meta` helpers. Free functions so RFC 0005's
708/// previous-version module reads and writes the SAME records as the client
709/// instead of growing a parallel meta layer.
710pub(crate) fn meta_get(conn: &Connection, key: &str) -> rusqlite::Result<Option<String>> {
711    conn.query_row(
712        "SELECT value FROM _syncular_meta WHERE key = ?1",
713        rusqlite::params![key],
714        |row| row.get::<_, String>(0),
715    )
716    .optional()
717}
718
719pub(crate) fn meta_set(conn: &Connection, key: &str, value: &str) -> rusqlite::Result<()> {
720    conn.execute(
721        "INSERT OR REPLACE INTO _syncular_meta (key, value) VALUES (?1, ?2)",
722        rusqlite::params![key, value],
723    )
724    .map(|_| ())
725}
726
727pub(crate) fn meta_delete(conn: &Connection, key: &str) -> rusqlite::Result<()> {
728    conn.execute(
729        "DELETE FROM _syncular_meta WHERE key = ?1",
730        rusqlite::params![key],
731    )
732    .map(|_| ())
733}
734
735/// Seek by the existing key while retaining the exact legacy text match.
736fn row_id_predicate(table: &TableSchema) -> String {
737    let key = quote_ident(&table.primary_key);
738    let text_match = format!("CAST({key} AS TEXT) = ?1");
739    match table.columns[table.pk_index].ty {
740        ColumnType::String | ColumnType::Json => {
741            format!("{key} = ?1 AND {text_match}")
742        }
743        // Native columns have no declared SQLite affinity. Match the stored
744        // integer bind type explicitly. Unary + removes expression affinity so
745        // SQLite can seek the typeless key; the text check preserves exact IDs.
746        ColumnType::Integer | ColumnType::Boolean => {
747            format!("{key} = +CAST(?1 AS INTEGER) AND {text_match}")
748        }
749        // REAL-to-text conversion can round distinct values to the same text.
750        // Narrowing those matches by numeric equality would change behavior.
751        _ => text_match,
752    }
753}
754
755/// §3.3/§4.8/§5.6 row ownership: rows whose local scope columns match
756/// `effective` and that no entry of `owners` matches. `owners` holds the
757/// pair scopes of every owner of the table (§3.3 row ownership); a scoped delete never removes a row one of them still covers.
758/// Scope values bind by the column's declared type, as `row_id_predicate`
759/// does. `Ok(None)` matches nothing (an empty map or value list); `Err(())`
760/// is a missing local scope-column mapping (the fail-closed case).
761fn local_scope_predicate(
762    table: &TableSchema,
763    effective: &[(String, Vec<String>)],
764    owners: &[Vec<(String, Vec<String>)>],
765) -> Result<Option<(String, Vec<SqlValue>)>, ()> {
766    if effective.is_empty() || effective.iter().any(|(_, values)| values.is_empty()) {
767        return Ok(None);
768    }
769    let column = |variable: &str| {
770        let name = table.scope_column(variable).ok_or(())?;
771        let column = table
772            .columns
773            .iter()
774            .find(|column| column.name == name)
775            .ok_or(())?;
776        Ok((quote_ident(name), column.ty == ColumnType::Integer))
777    };
778    let mut clauses = Vec::new();
779    let mut params = Vec::new();
780    for (variable, values) in effective {
781        let (key, integer) = column(variable)?;
782        let holes = vec!["?"; values.len()].join(", ");
783        clauses.push(if integer {
784            params.extend(values.iter().cloned().map(SqlValue::Text));
785            let seek = vec!["+CAST(? AS INTEGER)"; values.len()].join(", ");
786            format!("{key} IN ({seek}) AND CAST({key} AS TEXT) IN ({holes})")
787        } else {
788            format!("{key} IN ({holes})")
789        });
790        params.extend(values.iter().cloned().map(SqlValue::Text));
791    }
792    // Owners bind as one JSON parameter per variable set, so the statement
793    // keeps its size at any owner count; owners of one variable bind the
794    // union of their values. An owner holding other values of a variable
795    // `effective` names owns none of its rows and drops out. Values compare
796    // as text, the exact semantics of the effective clauses.
797    let mut groups: BTreeMap<Vec<&str>, Vec<Vec<&[String]>>> = BTreeMap::new();
798    for owner in owners {
799        if owner.is_empty()
800            || owner.iter().any(|(variable, values)| {
801                values.is_empty()
802                    || effective.iter().any(|(name, wanted)| {
803                        name == variable && wanted.iter().all(|value| !values.contains(value))
804                    })
805            })
806        {
807            continue;
808        }
809        let mut owner: Vec<_> = owner.iter().collect();
810        owner.sort_by(|a, b| a.0.cmp(&b.0));
811        groups
812            .entry(
813                owner
814                    .iter()
815                    .map(|(variable, _)| variable.as_str())
816                    .collect(),
817            )
818            .or_default()
819            .push(owner.iter().map(|(_, values)| values.as_slice()).collect());
820    }
821    let within = |variable: &str, list: &str| {
822        let (key, integer) = column(variable)?;
823        let key = if integer {
824            format!("CAST({key} AS TEXT)")
825        } else {
826            key
827        };
828        Ok(format!("{key} IN (SELECT value FROM json_each({list}))"))
829    };
830    for (variables, tuples) in groups {
831        if let [variable] = variables[..] {
832            let values: BTreeSet<&String> = tuples.iter().flatten().copied().flatten().collect();
833            params.push(SqlValue::Text(
834                Value::from_iter(values.into_iter().cloned()).to_string(),
835            ));
836            clauses.push(format!("NOT {}", within(variable, "?")?));
837        } else {
838            params.push(SqlValue::Text(
839                serde_json::to_string(&tuples).expect("owner tuples serialize"),
840            ));
841            let matches = variables
842                .iter()
843                .enumerate()
844                .map(|(index, variable)| within(variable, &format!("o.value,'$[{index}]'")))
845                .collect::<Result<Vec<_>, ()>>()?;
846            clauses.push(format!(
847                "NOT EXISTS (SELECT 1 FROM json_each(?) o WHERE {})",
848                matches.join(" AND ")
849            ));
850        }
851    }
852    Ok(Some((clauses.join(" AND "), params)))
853}
854
855/// [`local_scope_predicate`] over decoded row values (retained rows).
856fn owns_local_row(
857    table: &TableSchema,
858    effective: &[(String, Vec<String>)],
859    owners: &[Vec<(String, Vec<String>)>],
860    values: &Map<String, Value>,
861) -> bool {
862    let matches = |scopes: &[(String, Vec<String>)]| {
863        !scopes.is_empty()
864            && scopes.iter().all(|(variable, allowed)| {
865                table
866                    .scope_column(variable)
867                    .and_then(|column| values.get(column))
868                    .filter(|value| !value.is_null())
869                    .is_some_and(|value| {
870                        allowed.contains(
871                            &value
872                                .as_str()
873                                .map_or_else(|| value.to_string(), str::to_owned),
874                        )
875                    })
876            })
877    };
878    matches(effective) && !owners.iter().any(|owner| matches(owner))
879}
880
881fn is_local_operation_code_like(value: &str) -> bool {
882    let bytes = value.as_bytes();
883    bytes.first().is_some_and(u8::is_ascii_alphanumeric)
884        && bytes
885            .iter()
886            .all(|byte| byte.is_ascii_alphanumeric() || matches!(*byte, b'.' | b'_' | b':' | b'-'))
887}
888
889fn base_table(name: &str) -> String {
890    quote_ident(&format!("_syncular_base_{name}"))
891}
892
893/// §4.8 deferred eviction record: (unit id, table, effective scope map).
894type PendingEvict = (String, String, Vec<(String, Vec<String>)>);
895
896/// §4.8: a stable key for a window base: variable + canonical fixed scopes.
897fn window_base_key(base: &WindowBase) -> String {
898    format!(
899        "{}\0{}",
900        base.variable,
901        ssp2::registration::canonical_unit_json(&scope_pairs(&base.fixed_scopes))
902    )
903}
904
905/// The unit of one window value: the fixed scopes plus the value.
906fn window_unit_scopes(base: &WindowBase, value: &str) -> UnitScopes {
907    let mut scopes = base.fixed_scopes.clone();
908    scopes.insert(base.variable.clone(), value.to_owned());
909    scopes
910}
911
912/// A unit's scope map as the codec and the digests take it.
913fn scope_pairs(scopes: &UnitScopes) -> Vec<(String, String)> {
914    let mut pairs: Vec<(String, String)> = scopes
915        .iter()
916        .map(|(variable, value)| (variable.clone(), value.clone()))
917        .collect();
918    pairs.sort_by(|a, b| a.0.encode_utf16().cmp(b.0.encode_utf16()));
919    pairs
920}
921
922/// §4.1: the unit covers every table declaring all of its variables.
923fn covers(table: &TableSchema, scopes: &UnitScopes) -> bool {
924    scopes
925        .keys()
926        .all(|variable| table.scope_column(variable).is_some())
927}
928
929/// §4.4: the effective scopes of the (unit, table) pair under `echo`: the
930/// scope map as one-element lists plus the fenced lists. `None` when the
931/// fence revoked the pair.
932fn pair_scopes(
933    scopes: &UnitScopes,
934    table: &str,
935    echo: Option<&[EchoRecord]>,
936) -> Option<Vec<(String, Vec<String>)>> {
937    let fenced = echo.and_then(|echo| echo.iter().find(|record| record.table == table));
938    if fenced.is_some_and(|record| record.status == "revoked") {
939        return None;
940    }
941    let mut effective: BTreeMap<String, Vec<String>> = fenced
942        .map(|record| record.scopes.clone())
943        .unwrap_or_default();
944    for (variable, value) in scopes {
945        effective.insert(variable.clone(), vec![value.clone()]);
946    }
947    Some(effective.into_iter().collect())
948}
949
950/// §7.5 subset rule for one coverage value of `table`: its authority state
951/// (`complete`, `pending`, `missing` or `revoked`) and whether a candidate is
952/// `revoked`. A candidate is a persisted unit whose variables are a subset of
953/// the entry's and whose values equal the entry's on them. `declared` also
954/// requires that the table declares every variable of the unit; the read
955/// sidecar holds no schema, and there the subset of the entry's variables,
956/// which the table declares, implies it.
957fn entry_coverage(
958    units: &[UnitRecord],
959    table: &str,
960    declared: Option<&TableSchema>,
961    base: &WindowBase,
962    value: &str,
963) -> (&'static str, bool) {
964    let entry = window_unit_scopes(base, value);
965    let candidates: Vec<&UnitRecord> = units
966        .iter()
967        .filter(|unit| {
968            declared.is_none_or(|schema| covers(schema, &unit.scopes))
969                && unit
970                    .scopes
971                    .iter()
972                    .all(|(variable, held)| entry.get(variable) == Some(held))
973        })
974        .collect();
975    let complete = candidates.iter().any(|unit| {
976        unit.status == UnitStatus::Active
977            && !unit.bootstrapping()
978            && unit.echo.is_some()
979            && pair_scopes(&unit.scopes, table, unit.echo.as_deref()).is_some_and(|effective| {
980                entry
981                    .keys()
982                    .filter(|variable| !unit.scopes.contains_key(*variable))
983                    .all(|variable| {
984                        effective
985                            .iter()
986                            .find(|(name, _)| name == variable)
987                            .is_none_or(|(_, values)| values.iter().any(|held| held == "*"))
988                    })
989            })
990    });
991    let revoked = candidates
992        .iter()
993        .any(|unit| unit.status == UnitStatus::Revoked);
994    let state = if complete {
995        "complete"
996    } else if candidates.is_empty() {
997        "missing"
998    } else if candidates
999        .iter()
1000        .any(|unit| matches!(unit.status, UnitStatus::Revoked | UnitStatus::Failed))
1001    {
1002        "revoked"
1003    } else {
1004        "pending"
1005    };
1006    (state, revoked)
1007}
1008
1009/// §3.3 row ownership: the pair scopes of every owner of `table` except
1010/// `except_id`. An owner is active with a persisted echo and live or
1011/// post-bootstrap, or bootstrapping with a segment of the table in its
1012/// current bootstrap, or holding a restriction that excludes the table.
1013fn unit_owners(
1014    units: &[UnitRecord],
1015    table: &TableSchema,
1016    except_id: &str,
1017) -> Vec<Vec<(String, Vec<String>)>> {
1018    units
1019        .iter()
1020        .filter(|unit| {
1021            unit.id != except_id
1022                && unit.status == UnitStatus::Active
1023                && unit.echo.is_some()
1024                && (!unit.bootstrapping()
1025                    || unit.seeded.contains(&table.name)
1026                    || unit
1027                        .restriction
1028                        .as_ref()
1029                        .is_some_and(|restriction| !restriction.tables.contains(&table.name)))
1030                && covers(table, &unit.scopes)
1031        })
1032        .filter_map(|unit| pair_scopes(&unit.scopes, &table.name, unit.echo.as_deref()))
1033        .collect()
1034}
1035
1036/// §5.5 / §5.6: the unit's scope map, each value a one-element list.
1037fn unit_scope_lists(scopes: &UnitScopes) -> Vec<(String, Vec<String>)> {
1038    scopes
1039        .iter()
1040        .map(|(variable, value)| (variable.clone(), vec![value.clone()]))
1041        .collect()
1042}
1043
1044/// §7.1 acknowledged intent of the rows `?1` names (`[[table, id], ...]`).
1045/// It joins through the (tbl, id) index: a scan per acknowledgement would
1046/// make draining a batch quadratic.
1047const 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";
1048
1049const UNIT_COLUMNS: &str =
1050    "id, scopes, explicit, status, reason_code, cursor, bootstrap_state, seeded, echo, restriction";
1051
1052/// A unit row; a field that does not parse is a conversion failure, which
1053/// both read paths classify as `sync.local_corrupt`.
1054fn unit_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<UnitRecord> {
1055    fn json<T: serde::de::DeserializeOwned>(index: usize, raw: &str) -> rusqlite::Result<T> {
1056        serde_json::from_str(raw).map_err(|error| {
1057            rusqlite::Error::FromSqlConversionFailure(
1058                index,
1059                rusqlite::types::Type::Text,
1060                Box::new(error),
1061            )
1062        })
1063    }
1064    Ok(UnitRecord {
1065        id: row.get(0)?,
1066        scopes: json(1, &row.get::<_, String>(1)?)?,
1067        explicit: row.get::<_, i64>(2)? == 1,
1068        status: json(
1069            3,
1070            &serde_json::to_string(&row.get::<_, String>(3)?).expect("text"),
1071        )?,
1072        reason_code: row.get(4)?,
1073        cursor: row.get(5)?,
1074        bootstrap_state: row.get(6)?,
1075        seeded: json(7, &row.get::<_, String>(7)?)?,
1076        echo: row
1077            .get::<_, Option<String>>(8)?
1078            .map(|echo| json::<Vec<EchoRecord>>(8, &echo))
1079            .transpose()?
1080            .map(|echo| {
1081                if echo
1082                    .iter()
1083                    .all(|record| record.status == "active" || record.status == "revoked")
1084                {
1085                    Ok(echo)
1086                } else {
1087                    Err(rusqlite::Error::FromSqlConversionFailure(
1088                        8,
1089                        rusqlite::types::Type::Text,
1090                        "echo status is neither active nor revoked".into(),
1091                    ))
1092                }
1093            })
1094            .transpose()?,
1095        restriction: row
1096            .get::<_, Option<String>>(9)?
1097            .map(|raw| json::<UnitRestriction>(9, &raw))
1098            .transpose()?,
1099    })
1100}
1101
1102/// Every unit in registration order (§4.1).
1103fn load_units(conn: &Connection) -> rusqlite::Result<Vec<UnitRecord>> {
1104    conn.prepare_cached(&format!(
1105        "SELECT {UNIT_COLUMNS} FROM _syncular_units ORDER BY rowid"
1106    ))?
1107    .query_map([], unit_from_row)?
1108    .collect()
1109}
1110
1111fn get_unit(conn: &Connection, id: &str) -> rusqlite::Result<Option<UnitRecord>> {
1112    conn.query_row(
1113        &format!("SELECT {UNIT_COLUMNS} FROM _syncular_units WHERE id = ?1"),
1114        [id],
1115        unit_from_row,
1116    )
1117    .optional()
1118}
1119
1120/// Insert or update in place: an update keeps the registration order. The
1121/// §5.6 applied-segment record ends when the cursor or the token changes.
1122fn save_unit(conn: &Connection, unit: &UnitRecord) -> rusqlite::Result<()> {
1123    conn.prepare_cached(&format!(
1124        "INSERT INTO _syncular_units({UNIT_COLUMNS}) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10)
1125         ON CONFLICT(id) DO UPDATE SET explicit=excluded.explicit, status=excluded.status,
1126           reason_code=excluded.reason_code, cursor=excluded.cursor,
1127           bootstrap_state=excluded.bootstrap_state, seeded=excluded.seeded, echo=excluded.echo,
1128           restriction=excluded.restriction,
1129           applied=CASE WHEN cursor IS excluded.cursor
1130             AND bootstrap_state IS excluded.bootstrap_state THEN applied END"
1131    ))?
1132    .execute(rusqlite::params![
1133        unit.id,
1134        serde_json::to_string(&unit.scopes).expect("scope map serializes"),
1135        i64::from(unit.explicit),
1136        unit.status.name(),
1137        unit.reason_code,
1138        unit.cursor,
1139        unit.bootstrap_state,
1140        serde_json::to_string(&unit.seeded).expect("table list serializes"),
1141        unit.echo
1142            .as_ref()
1143            .map(|echo| serde_json::to_string(echo).expect("echo serializes")),
1144        unit.restriction
1145            .as_ref()
1146            .map(|restriction| serde_json::to_string(restriction).expect("restriction serializes")),
1147    ])
1148    .map(|_| ())
1149}
1150
1151/// §5.6 applied-segment record of unit `id`: segment id → rows applied at
1152/// its current cursor and token.
1153fn applied_rows(conn: &Connection, id: &str) -> rusqlite::Result<BTreeMap<String, i64>> {
1154    conn.query_row(
1155        "SELECT applied FROM _syncular_units WHERE id = ?1",
1156        [id],
1157        |row| row.get::<_, Option<String>>(0),
1158    )
1159    .optional()?
1160    .flatten()
1161    .map_or(Ok(BTreeMap::new()), |raw| {
1162        serde_json::from_str(&raw).map_err(|error| {
1163            rusqlite::Error::FromSqlConversionFailure(
1164                0,
1165                rusqlite::types::Type::Text,
1166                Box::new(error),
1167            )
1168        })
1169    })
1170}
1171
1172/// §5.6: `rows` rows of `segment_id` applied at unit `id`'s position. Runs
1173/// in the transaction that commits them.
1174fn record_applied_rows(
1175    conn: &Connection,
1176    id: &str,
1177    segment_id: &str,
1178    rows: i64,
1179) -> rusqlite::Result<()> {
1180    conn.prepare_cached(
1181        "UPDATE _syncular_units SET applied=json_patch(coalesce(applied,'{}'),?1) WHERE id=?2",
1182    )?
1183    .execute(rusqlite::params![
1184        serde_json::json!({ segment_id: rows }).to_string(),
1185        id
1186    ])
1187    .map(|_| ())
1188}
1189
1190/// §4.1 references: every window registry entry `(base, value)` holding a unit.
1191fn window_refs(conn: &Connection, unit_id: &str) -> rusqlite::Result<Vec<(String, String)>> {
1192    conn.prepare_cached("SELECT base, unit FROM _syncular_windows WHERE sub_id = ?1")?
1193        .query_map([unit_id], |row| Ok((row.get(0)?, row.get(1)?)))?
1194        .collect()
1195}
1196
1197/// §7.4.3 reset, §2.1 log reset and local rebootstrap: keep the unit
1198/// registrations and discard the synced state of every unit outside `keep`,
1199/// so the next round sends the list and bootstraps those units. A schema bump
1200/// passes `restrictions`: every reset unit keeps its echo and takes its
1201/// restriction from the map, if any (§7.4.3); the other resets discard both.
1202/// The replica cursor survives only while a kept unit is live. The caller
1203/// owns the transaction.
1204fn reset_units(
1205    conn: &Connection,
1206    keep: &BTreeSet<String>,
1207    restrictions: Option<&BTreeMap<String, UnitRestriction>>,
1208) -> rusqlite::Result<()> {
1209    conn.execute(
1210        "UPDATE _syncular_units SET status='active', reason_code=NULL, cursor=-1,
1211           bootstrap_state=NULL, seeded='[]', applied=NULL,
1212           echo=CASE WHEN ?2 IS NULL THEN NULL ELSE echo END,
1213           restriction=(SELECT value FROM json_each(?2) WHERE key=_syncular_units.id)
1214         WHERE id NOT IN (SELECT value FROM json_each(?1))",
1215        rusqlite::params![
1216            serde_json::to_string(keep).expect("unit ids serialize"),
1217            restrictions.map(|map| serde_json::to_string(map).expect("restrictions serialize")),
1218        ],
1219    )?;
1220    conn.execute_batch(
1221        "DELETE FROM _syncular_meta WHERE key IN ('echoDigest','registrationDigest');
1222         DELETE FROM _syncular_meta WHERE key='replicaCursor'
1223           AND NOT EXISTS (SELECT 1 FROM _syncular_units WHERE cursor IS NULL);",
1224    )
1225}
1226
1227/// §4.5: the replica cursor, `-1` while no unit is live.
1228fn replica_cursor(conn: &Connection) -> rusqlite::Result<i64> {
1229    meta_get(conn, REPLICA_CURSOR_KEY)?.map_or(Ok(-1), |raw| {
1230        raw.parse().map_err(|error| {
1231            rusqlite::Error::FromSqlConversionFailure(
1232                0,
1233                rusqlite::types::Type::Text,
1234                Box::new(error),
1235            )
1236        })
1237    })
1238}
1239
1240fn visible_table(name: &str) -> String {
1241    quote_ident(name)
1242}
1243
1244const FTS_SOURCE_ID_COLUMN: &str = "_syncular_source_id";
1245
1246/// §7.4.3: is a `sqlite_master` table name a synced table (visible or base),
1247/// i.e. NOT one of the durable bookkeeping tables the reset preserves?
1248fn is_synced_table_name(name: &str) -> bool {
1249    if name.starts_with("sqlite_") {
1250        return false;
1251    }
1252    if name.starts_with("_syncular_base_") {
1253        return true; // the base half of a synced table pair
1254    }
1255    // Bookkeeping: outbox, units, meta, blob cache/uploads.
1256    !name.starts_with("_syncular_")
1257}
1258
1259/// `"sha256:" + hex` of the bytes — the content address (§5.9.1).
1260fn blob_id_for(bytes: &[u8]) -> String {
1261    let digest = Sha256::digest(bytes);
1262    format!("sha256:{}", bytes_to_hex(&digest))
1263}
1264
1265/// One [`SyncClient::write_row`] bind parameter, borrowing the row-codec
1266/// value it wraps — strings/JSON/bytes bind as borrowed TEXT/BLOB (no copy
1267/// per row on the §5.6 bootstrap path), scalars bind owned.
1268enum RowParam<'a> {
1269    Cell(&'a Option<ColumnValue>),
1270    Version(i64),
1271    Text(Option<&'a str>),
1272}
1273
1274impl rusqlite::ToSql for RowParam<'_> {
1275    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
1276        Ok(match self {
1277            RowParam::Version(v) => ToSqlOutput::Owned(SqlValue::Integer(*v)),
1278            RowParam::Text(text) => match text {
1279                Some(text) => ToSqlOutput::Borrowed(ValueRef::Text(text.as_bytes())),
1280                None => ToSqlOutput::Owned(SqlValue::Null),
1281            },
1282            RowParam::Cell(cell) => match cell {
1283                None => ToSqlOutput::Owned(SqlValue::Null),
1284                Some(ColumnValue::String(s)) => ToSqlOutput::Borrowed(ValueRef::Text(s.as_bytes())),
1285                Some(ColumnValue::Integer(i)) => ToSqlOutput::Owned(SqlValue::Integer(*i)),
1286                Some(ColumnValue::Float(f)) => ToSqlOutput::Owned(SqlValue::Real(*f)),
1287                Some(ColumnValue::Boolean(b)) => {
1288                    ToSqlOutput::Owned(SqlValue::Integer(i64::from(*b)))
1289                }
1290                Some(ColumnValue::Json(raw)) | Some(ColumnValue::BlobRef(raw)) => {
1291                    ToSqlOutput::Borrowed(ValueRef::Text(raw.0.as_bytes()))
1292                }
1293                // §5.10: crdt bytes store as BLOB, like bytes.
1294                Some(ColumnValue::Bytes(b)) | Some(ColumnValue::Crdt(b)) => {
1295                    ToSqlOutput::Borrowed(ValueRef::Blob(b))
1296                }
1297            },
1298        })
1299    }
1300}
1301
1302// Retain a typed primary key across the current import chunk without copying row payloads.
1303fn owned_sql_value(param: impl rusqlite::ToSql) -> Result<SqlValue, String> {
1304    match param.to_sql().map_err(|error| error.to_string())? {
1305        ToSqlOutput::Owned(value) => Ok(value),
1306        ToSqlOutput::Borrowed(value) => {
1307            SqlValue::try_from(value).map_err(|error| error.to_string())
1308        }
1309        _ => Err("sync.invalid_request: unsupported SQLite key parameter".into()),
1310    }
1311}
1312
1313/// §5.3 image cell → bind parameter, strict per the declared column type
1314/// (`boolean` from INTEGER 0/1, `json` from its raw TEXT, NULL only when
1315/// nullable). Mismatches are image-producer violations. Returns the cell
1316/// borrowed when the stored representation already matches what the row
1317/// codec would write, or the normalized scalar (boolean → 0/1, float from
1318/// INTEGER → REAL) otherwise — the local write is byte-identical to the
1319/// old convert-then-insert path without allocating per cell.
1320fn image_cell_param<'a>(column: &Column, value: ValueRef<'a>) -> Result<ToSqlOutput<'a>, String> {
1321    use ssp2::segment::ColumnType;
1322    let mismatch = || {
1323        Err(format!(
1324            "image column {:?} holds a value of the wrong type",
1325            column.name
1326        ))
1327    };
1328    match value {
1329        ValueRef::Null => {
1330            if !column.nullable {
1331                return Err(format!(
1332                    "image column {:?} is NULL but not nullable",
1333                    column.name
1334                ));
1335            }
1336            Ok(ToSqlOutput::Owned(SqlValue::Null))
1337        }
1338        ValueRef::Integer(i) => match column.ty {
1339            ColumnType::Integer => Ok(ToSqlOutput::Borrowed(value)),
1340            ColumnType::Boolean => Ok(ToSqlOutput::Owned(SqlValue::Integer(i64::from(i != 0)))),
1341            ColumnType::Float => Ok(ToSqlOutput::Owned(SqlValue::Real(i as f64))),
1342            _ => mismatch(),
1343        },
1344        ValueRef::Real(_) => match column.ty {
1345            ColumnType::Float => Ok(ToSqlOutput::Borrowed(value)),
1346            _ => mismatch(),
1347        },
1348        ValueRef::Text(t) => {
1349            std::str::from_utf8(t)
1350                .map_err(|_| format!("image column {:?} is not UTF-8", column.name))?;
1351            match column.ty {
1352                ColumnType::String | ColumnType::Json | ColumnType::BlobRef => {
1353                    Ok(ToSqlOutput::Borrowed(value))
1354                }
1355                _ => mismatch(),
1356            }
1357        }
1358        ValueRef::Blob(_) => match column.ty {
1359            // §5.10: a crdt column stores its opaque bytes as BLOB, like bytes.
1360            ColumnType::Bytes | ColumnType::Crdt => Ok(ToSqlOutput::Borrowed(value)),
1361            _ => mismatch(),
1362        },
1363    }
1364}
1365
1366pub(crate) fn sql_ref_to_json(column: &Column, value: rusqlite::types::ValueRef<'_>) -> Value {
1367    use rusqlite::types::ValueRef;
1368    match value {
1369        ValueRef::Null => Value::Null,
1370        ValueRef::Integer(i) => match column.ty {
1371            ssp2::segment::ColumnType::Boolean => Value::Bool(i != 0),
1372            ssp2::segment::ColumnType::Float => {
1373                serde_json::Number::from_f64(i as f64).map_or(Value::Null, Value::Number)
1374            }
1375            _ => Value::from(i),
1376        },
1377        ValueRef::Real(f) => serde_json::Number::from_f64(f).map_or(Value::Null, Value::Number),
1378        ValueRef::Text(t) => Value::from(String::from_utf8_lossy(t).into_owned()),
1379        ValueRef::Blob(b) => {
1380            let mut map = Map::new();
1381            map.insert("$bytes".to_owned(), Value::from(bytes_to_hex(b)));
1382            Value::Object(map)
1383        }
1384    }
1385}
1386
1387/// Bind a driver JSON value form as a rusqlite parameter for [`SyncClient::query`].
1388/// Objects are accepted in lossless `{"$bytes": hex}` and
1389/// `{"$bigint": decimal}` envelope forms.
1390fn json_param_to_sql(value: &Value) -> Result<SqlValue, String> {
1391    Ok(match value {
1392        Value::Null => SqlValue::Null,
1393        Value::Bool(b) => SqlValue::Integer(i64::from(*b)),
1394        Value::Number(n) => {
1395            if let Some(i) = n.as_i64() {
1396                SqlValue::Integer(i)
1397            } else if let Some(f) = n.as_f64() {
1398                SqlValue::Real(f)
1399            } else {
1400                return Err(format!("query param number {n} is out of range"));
1401            }
1402        }
1403        Value::String(s) => SqlValue::Text(s.clone()),
1404        Value::Object(_) => {
1405            if let Some(hex) = value.get("$bytes").and_then(Value::as_str) {
1406                SqlValue::Blob(crate::values::hex_to_bytes(hex)?)
1407            } else if let Some(decimal) = value.get("$bigint").and_then(Value::as_str) {
1408                SqlValue::Integer(decimal.parse::<i64>().map_err(|_| {
1409                    format!("query bigint param {decimal:?} is outside SQLite's i64 range")
1410                })?)
1411            } else {
1412                return Err(
1413                    "query object param must be a {$bytes: hex} or {$bigint: decimal} value"
1414                        .to_owned(),
1415                );
1416            }
1417        }
1418        Value::Array(_) => return Err("query array params are not supported".to_owned()),
1419    })
1420}
1421
1422/// Map a rusqlite value with no schema column to consult (arbitrary query
1423/// output): integers/reals/text pass through by stored affinity, blobs ride
1424/// as `{"$bytes": hex}`. Distinct from [`sql_ref_to_json`], which uses the
1425/// schema column type to recover booleans/floats/json.
1426fn sql_ref_to_json_dynamic(value: rusqlite::types::ValueRef<'_>) -> Value {
1427    use rusqlite::types::ValueRef;
1428    match value {
1429        ValueRef::Null => Value::Null,
1430        ValueRef::Integer(i) => {
1431            // JSON/Tauri IPC cannot represent every SQLite i64 exactly. Keep
1432            // ordinary UI-sized integers ergonomic and envelope only values
1433            // beyond JavaScript's safe range.
1434            const MAX_SAFE_INTEGER: i64 = 9_007_199_254_740_991;
1435            if (-MAX_SAFE_INTEGER..=MAX_SAFE_INTEGER).contains(&i) {
1436                Value::from(i)
1437            } else {
1438                let mut map = Map::new();
1439                map.insert("$bigint".to_owned(), Value::from(i.to_string()));
1440                Value::Object(map)
1441            }
1442        }
1443        ValueRef::Real(f) => serde_json::Number::from_f64(f).map_or(Value::Null, Value::Number),
1444        ValueRef::Text(t) => Value::from(String::from_utf8_lossy(t).into_owned()),
1445        ValueRef::Blob(b) => {
1446            let mut map = Map::new();
1447            map.insert("$bytes".to_owned(), Value::from(bytes_to_hex(b)));
1448            Value::Object(map)
1449        }
1450    }
1451}
1452
1453/// §7.5: SQLite failures classify by result code into [`QueryReadFailure`].
1454fn query_connection(
1455    conn: &Connection,
1456    sql: &str,
1457    params: &[QueryValue],
1458) -> Result<Vec<QueryRow>, QueryReadFailure> {
1459    let lowered_sql = crate::query_guard::lower_public_query_sql(sql);
1460    let mut stmt = crate::query_guard::prepare_read_only(conn, &lowered_sql)?;
1461    let bound: Vec<SqlValue> = params
1462        .iter()
1463        .map(json_param_to_sql)
1464        .collect::<Result<_, _>>()?;
1465    // §2.4: an unaliased physical version column stays engine-internal, so a
1466    // `SELECT *` row feeds straight back into mutation values. An explicit
1467    // alias (`_sync_version AS v`) returns it as ordinary query data. The
1468    // §5.11 sealed columns follow the same rule.
1469    let columns: Vec<(usize, String)> = stmt
1470        .column_names()
1471        .enumerate()
1472        .filter(|(_, name)| {
1473            !matches!(
1474                *name,
1475                "_syncular_version" | "_sync_sealed_key" | "_sync_sealed"
1476            )
1477        })
1478        .map(|(i, name)| (i, name.to_owned()))
1479        .collect();
1480    let bound_refs: Vec<&dyn rusqlite::ToSql> =
1481        bound.iter().map(|v| v as &dyn rusqlite::ToSql).collect();
1482    let mut sql_rows = stmt.query(bound_refs.as_slice())?;
1483    let mut out = Vec::new();
1484    while let Some(row) = sql_rows.next()? {
1485        let mut record = Map::new();
1486        for (i, name) in &columns {
1487            let value = row.get_ref(*i)?;
1488            record.insert(name.clone(), sql_ref_to_json_dynamic(value));
1489        }
1490        out.push(record);
1491    }
1492    Ok(out)
1493}
1494
1495fn persisted_window_state(
1496    conn: &Connection,
1497    base: &WindowBase,
1498) -> Result<WindowState, QueryReadFailure> {
1499    let mut stmt = conn.prepare(
1500        "SELECT windows.unit, units.status, units.cursor, units.bootstrap_state
1501           FROM _syncular_windows AS windows
1502           LEFT JOIN _syncular_units AS units ON units.id = windows.sub_id
1503          WHERE windows.base = ?1
1504          ORDER BY windows.unit ASC",
1505    )?;
1506    let rows = stmt.query_map(rusqlite::params![window_base_key(base)], |row| {
1507        Ok((
1508            row.get::<_, String>(0)?,
1509            row.get::<_, Option<String>>(1)?,
1510            row.get::<_, Option<i64>>(2)?,
1511            row.get::<_, Option<String>>(3)?,
1512        ))
1513    })?;
1514    let mut units = Vec::new();
1515    let mut pending = Vec::new();
1516    let mut revoked = Vec::new();
1517    for row in rows {
1518        let (unit, status, cursor, bootstrap_state) = row?;
1519        if status.as_deref() == Some("revoked") {
1520            revoked.push(unit.clone());
1521        }
1522        // §4.8: complete iff registered, active and not bootstrapping.
1523        if status.as_deref() != Some("active")
1524            || cursor.is_some_and(|cursor| cursor < 0 || bootstrap_state.is_some())
1525        {
1526            pending.push(unit.clone());
1527        }
1528        units.push(unit);
1529    }
1530    Ok(WindowState {
1531        units,
1532        pending,
1533        revoked,
1534    })
1535}
1536
1537/// One read-only statement in a §7.5 snapshot read.
1538#[derive(Debug, Clone, Copy)]
1539pub struct SnapshotStatement<'a> {
1540    pub sql: &'a str,
1541    pub params: &'a [Value],
1542}
1543
1544/// A §7.5 atomic read request: read-only statements, window coverage, unit
1545/// catch-up states, and commit deliveries, all resolved from one SQLite read
1546/// transaction and one revision.
1547#[derive(Debug, Clone, Default)]
1548pub struct SnapshotReadRequest<'a> {
1549    pub statements: Vec<SnapshotStatement<'a>>,
1550    pub coverage: &'a [WindowCoverage],
1551    pub units: Vec<String>,
1552    pub commit_ids: Vec<String>,
1553}
1554
1555#[cfg(test)]
1556thread_local! {
1557    /// Test-only rendezvous that runs between the statements of one snapshot
1558    /// read. A test uses it to commit on another connection mid-read and prove
1559    /// the read transaction's snapshot and revision stay stable.
1560    static SNAPSHOT_READ_HOOK: std::cell::RefCell<Option<Box<dyn FnOnce()>>> =
1561        std::cell::RefCell::new(None);
1562}
1563
1564#[cfg(test)]
1565fn run_snapshot_read_hook() {
1566    SNAPSHOT_READ_HOOK.with(|slot| {
1567        if let Some(hook) = slot.borrow_mut().take() {
1568            hook();
1569        }
1570    });
1571}
1572
1573/// §7.5: resolve a request over one SQLite read transaction. The revision,
1574/// every statement's rows, coverage, catch-up states, and deliveries are
1575/// captured under one `SAVEPOINT`; any statement's failure rolls the whole
1576/// read back and releases the connection.
1577fn snapshot_read_connection(
1578    conn: &Connection,
1579    schema: Option<&ClientSchema>,
1580    request: &SnapshotReadRequest<'_>,
1581) -> Result<SnapshotRead, QueryReadFailure> {
1582    conn.execute_batch("SAVEPOINT syncular_snapshot_read")?;
1583    let corrupt = |message: &str| QueryReadFailure {
1584        code: Some("sync.local_corrupt"),
1585        sqlite_code: None,
1586        sqlite_message: None,
1587        rollback_failure: None,
1588        message: message.to_owned(),
1589    };
1590    let stored_failure = |error: rusqlite::Error, message: &str| match error {
1591        rusqlite::Error::Utf8Error(..)
1592        | rusqlite::Error::InvalidColumnType(..)
1593        | rusqlite::Error::FromSqlConversionFailure(..)
1594        | rusqlite::Error::IntegralValueOutOfRange(..) => corrupt(message),
1595        _ => QueryReadFailure::from(error),
1596    };
1597    let result: Result<SnapshotRead, QueryReadFailure> = (|| {
1598        // The durable revision as a canonical decimal `u64`; a missing marker
1599        // is the legacy zero, and any other non-canonical value is corrupt.
1600        let revision: Option<String> = conn
1601            .query_row(
1602                "SELECT value FROM _syncular_meta WHERE key = ?1",
1603                rusqlite::params![LOCAL_REVISION_KEY],
1604                |row| row.get(0),
1605            )
1606            .optional()
1607            .map_err(|error| stored_failure(error, "persisted local revision is invalid"))?;
1608        let revision = match revision {
1609            None => "0".to_owned(),
1610            Some(value)
1611                if value == "0"
1612                    || (matches!(value.as_bytes().first(), Some(b'1'..=b'9'))
1613                        && value.bytes().all(|b| b.is_ascii_digit())
1614                        && value.parse::<u64>().is_ok()) =>
1615            {
1616                value
1617            }
1618            Some(_) => return Err(corrupt("persisted local revision is invalid")),
1619        };
1620        let mut queries = Vec::with_capacity(request.statements.len());
1621        for statement in &request.statements {
1622            queries.push(query_connection(conn, statement.sql, statement.params)?);
1623            #[cfg(test)]
1624            run_snapshot_read_hook();
1625        }
1626        let mut pending = Vec::new();
1627        let mut missing = Vec::new();
1628        let mut revoked = Vec::new();
1629        let persisted = if request.coverage.is_empty() {
1630            Vec::new()
1631        } else {
1632            load_units(conn)
1633                .map_err(|error| stored_failure(error, "persisted unit state is invalid"))?
1634        };
1635        for requested in request.coverage {
1636            let declared = match schema {
1637                Some(schema) => {
1638                    Some(
1639                        schema
1640                            .table(&requested.table)
1641                            .ok_or_else(|| QueryReadFailure {
1642                                code: Some("sync.invalid_request"),
1643                                sqlite_code: None,
1644                                sqlite_message: None,
1645                                rollback_failure: None,
1646                                message: "unknown coverage table".to_owned(),
1647                            })?,
1648                    )
1649                }
1650                None => None,
1651            };
1652            let base_key = window_base_key(&requested.base);
1653            for unit in BTreeSet::from_iter(requested.units.iter().cloned()) {
1654                let (state, revoked_candidate) = entry_coverage(
1655                    &persisted,
1656                    &requested.table,
1657                    declared,
1658                    &requested.base,
1659                    &unit,
1660                );
1661                let reference = WindowUnitRef {
1662                    base_key: base_key.clone(),
1663                    unit,
1664                };
1665                // Refs dedupe across entries of several tables on one base.
1666                let add = |list: &mut Vec<WindowUnitRef>, reference: &WindowUnitRef| {
1667                    if !list.iter().any(|held| {
1668                        held.base_key == reference.base_key && held.unit == reference.unit
1669                    }) {
1670                        list.push(reference.clone());
1671                    }
1672                };
1673                match state {
1674                    "complete" => continue,
1675                    "missing" => add(&mut missing, &reference),
1676                    _ => add(&mut pending, &reference),
1677                }
1678                if revoked_candidate {
1679                    add(&mut revoked, &reference);
1680                }
1681            }
1682        }
1683        let mut units = Vec::with_capacity(request.units.len());
1684        for id in &request.units {
1685            let exists: bool = conn.query_row(
1686                "SELECT EXISTS(SELECT 1 FROM _syncular_units WHERE id = ?1)",
1687                [id],
1688                |row| row.get(0),
1689            )?;
1690            if !exists {
1691                units.push(UnitCatchup::Unknown { id: id.clone() });
1692                continue;
1693            }
1694            // Every persisted field is required to be well typed; a corrupt
1695            // record fails typed instead of inventing a state.
1696            let unit = get_unit(conn, id)
1697                .map_err(|error| stored_failure(error, "persisted unit state is invalid"))?
1698                .ok_or_else(|| corrupt("persisted unit state is invalid"))?;
1699            let cursor = match unit.cursor {
1700                Some(cursor) => cursor,
1701                None => replica_cursor(conn)
1702                    .map_err(|error| stored_failure(error, "persisted unit state is invalid"))?,
1703            };
1704            if cursor.unsigned_abs() > MAX_JS_SAFE_INTEGER {
1705                return Err(corrupt("persisted unit state is invalid"));
1706            }
1707            let active = unit.status == UnitStatus::Active;
1708            let pending = unit.bootstrapping();
1709            units.push(UnitCatchup::Known {
1710                id: id.clone(),
1711                status: unit.status,
1712                live: unit.cursor.is_none(),
1713                cursor,
1714                has_resume_token: unit.bootstrap_state.is_some(),
1715                bootstrap_complete: active && !pending,
1716                known_pending_pages: active && pending,
1717                reason_code: unit.reason_code,
1718            });
1719        }
1720        let mut deliveries = Vec::with_capacity(request.commit_ids.len());
1721        for id in &request.commit_ids {
1722            let pending: bool = conn.query_row(
1723                "SELECT EXISTS(SELECT 1 FROM _syncular_outbox WHERE commit_id = ?1)",
1724                rusqlite::params![id],
1725                |row| row.get(0),
1726            )?;
1727            if pending {
1728                deliveries.push(CommitDelivery::Pending {
1729                    client_commit_id: id.clone(),
1730                });
1731                continue;
1732            }
1733            let row = conn
1734                .query_row(
1735                    "SELECT seq, client_commit_id, status, recorded_at_ms, results_json, operations_json,
1736                            resolution, resolved_at_ms, replacement_client_commit_id
1737                       FROM _syncular_commit_outcomes WHERE client_commit_id = ?1",
1738                    rusqlite::params![id],
1739                    StoredCommitOutcomeRow::from_row,
1740                )
1741                .optional()
1742                .map_err(|error| stored_failure(error, "persisted commit outcome is invalid"))?;
1743            deliveries.push(match row {
1744                Some(row) => CommitDelivery::Known {
1745                    client_commit_id: id.clone(),
1746                    outcome: SyncClient::outcome_from_row(row)
1747                        .map(SyncClient::reported_outcome)
1748                        .map_err(|_| corrupt("persisted commit outcome is invalid"))?,
1749                },
1750                None => CommitDelivery::Unknown {
1751                    client_commit_id: id.clone(),
1752                },
1753            });
1754        }
1755        Ok(SnapshotRead {
1756            revision,
1757            queries,
1758            coverage: CoverageSnapshot {
1759                complete: pending.is_empty() && missing.is_empty(),
1760                pending,
1761                missing,
1762                revoked,
1763            },
1764            units,
1765            deliveries,
1766        })
1767    })();
1768    match result {
1769        Ok(read) => {
1770            conn.execute_batch("RELEASE syncular_snapshot_read")?;
1771            Ok(read)
1772        }
1773        Err(mut error) => {
1774            if let Err(rollback) = conn
1775                .execute_batch("ROLLBACK TO syncular_snapshot_read; RELEASE syncular_snapshot_read")
1776            {
1777                error.rollback_failure = Some(Box::new(QueryReadFailure::from(rollback)));
1778            }
1779            Err(error)
1780        }
1781    }
1782}
1783
1784fn snapshot_connection(
1785    conn: &Connection,
1786    schema: Option<&ClientSchema>,
1787    sql: &str,
1788    params: &[Value],
1789    coverage: &[WindowCoverage],
1790) -> Result<QuerySnapshot, QueryReadFailure> {
1791    let read = snapshot_read_connection(
1792        conn,
1793        schema,
1794        &SnapshotReadRequest {
1795            statements: vec![SnapshotStatement { sql, params }],
1796            coverage,
1797            units: Vec::new(),
1798            commit_ids: Vec::new(),
1799        },
1800    )?;
1801    Ok(QuerySnapshot {
1802        revision: read.revision,
1803        rows: read
1804            .queries
1805            .into_iter()
1806            .next()
1807            .expect("single-query snapshot returns one result"),
1808        coverage: read.coverage,
1809    })
1810}
1811
1812/// A long-lived read-only SQLite sidecar for latency-critical native views.
1813/// Network rounds stay serialized on the mutable core owner, while atomic
1814/// query snapshots use this independent connection and therefore never queue
1815/// behind HTTP/WebSocket latency.
1816pub struct FileQuerySnapshotReader {
1817    path: String,
1818    conn: Option<Connection>,
1819}
1820
1821impl FileQuerySnapshotReader {
1822    #[must_use]
1823    pub fn new(path: impl Into<String>) -> Self {
1824        Self {
1825            path: path.into(),
1826            conn: None,
1827        }
1828    }
1829
1830    fn connection(&mut self) -> Result<&Connection, QueryReadFailure> {
1831        if self.conn.is_none() {
1832            let conn = Connection::open_with_flags(
1833                &self.path,
1834                OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
1835            )
1836            .map_err(QueryReadFailure::from)?;
1837            conn.busy_timeout(std::time::Duration::from_millis(250))
1838                .map_err(QueryReadFailure::from)?;
1839            self.conn = Some(conn);
1840        }
1841        self.conn
1842            .as_ref()
1843            .ok_or_else(|| QueryReadFailure::from("read sidecar connection missing".to_owned()))
1844    }
1845
1846    /// One atomic read over the shared primitive: every statement, coverage,
1847    /// catch-up, and delivery under one `SAVEPOINT` and one revision.
1848    pub fn snapshot_read(
1849        &mut self,
1850        request: &SnapshotReadRequest<'_>,
1851    ) -> Result<SnapshotRead, QueryReadFailure> {
1852        snapshot_read_connection(self.connection()?, None, request)
1853    }
1854
1855    /// The current durable local revision. A host can skip a read when it is
1856    /// unchanged; a corrupt or unreadable marker fails typed.
1857    pub fn local_revision(&mut self) -> Result<String, QueryReadFailure> {
1858        Ok(self
1859            .snapshot_read(&SnapshotReadRequest::default())?
1860            .revision)
1861    }
1862
1863    /// One unit's persisted catch-up state (see the §7.5 contract).
1864    pub fn unit_catchup(&mut self, id: &str) -> Result<UnitCatchup, QueryReadFailure> {
1865        let read = self.snapshot_read(&SnapshotReadRequest {
1866            units: vec![id.to_owned()],
1867            ..Default::default()
1868        })?;
1869        Ok(read
1870            .units
1871            .into_iter()
1872            .next()
1873            .expect("one requested catch-up"))
1874    }
1875
1876    /// One client commit's delivery status: pending, its retained outcome, or
1877    /// an explicit unknown (never held, or pruned by retention).
1878    pub fn commit_delivery(&mut self, id: &str) -> Result<CommitDelivery, QueryReadFailure> {
1879        let read = self.snapshot_read(&SnapshotReadRequest {
1880            commit_ids: vec![id.to_owned()],
1881            ..Default::default()
1882        })?;
1883        Ok(read
1884            .deliveries
1885            .into_iter()
1886            .next()
1887            .expect("one requested delivery"))
1888    }
1889
1890    /// Hosts report an owned failure, and the first success after it, to the
1891    /// owning core through [`SyncClient::record_query_read`] (§7.6).
1892    pub fn query_snapshot(
1893        &mut self,
1894        sql: &str,
1895        params: &[Value],
1896        coverage: &[WindowCoverage],
1897    ) -> Result<QuerySnapshot, QueryReadFailure> {
1898        snapshot_connection(self.connection()?, None, sql, params, coverage)
1899    }
1900}
1901
1902/// `client.authority_read_forbidden` with static text; `details` carries the
1903/// query, the reason and, where one applies, the table and column (§5.11).
1904fn authority_forbidden(details: Option<Value>) -> ClientError {
1905    ClientError {
1906        code: "client.authority_read_forbidden".to_owned(),
1907        message: "authority read denied".to_owned(),
1908        details,
1909        retryable: false,
1910    }
1911}
1912
1913/// `sync.local_corrupt` for missing or invalid authority read evidence.
1914fn authority_corrupt() -> ClientError {
1915    ClientError {
1916        code: "sync.local_corrupt".to_owned(),
1917        message: "authority revision or base evidence is missing or invalid".to_owned(),
1918        details: None,
1919        retryable: false,
1920    }
1921}
1922
1923/// A storage failure of an authority read: a value that does not convert is
1924/// corrupt evidence; every other failure keeps its storage classification.
1925fn authority_stored(error: rusqlite::Error) -> ClientError {
1926    match error {
1927        rusqlite::Error::Utf8Error(..)
1928        | rusqlite::Error::InvalidColumnType(..)
1929        | rusqlite::Error::FromSqlConversionFailure(..)
1930        | rusqlite::Error::IntegralValueOutOfRange(..) => authority_corrupt(),
1931        other => ClientError::from(QueryReadFailure::from(other)),
1932    }
1933}
1934
1935fn authority_refusal(
1936    query: &str,
1937    reason: &str,
1938    table: Option<&str>,
1939    column: Option<&str>,
1940) -> ClientError {
1941    let mut details = json!({ "query": query, "reason": reason });
1942    if let Some(table) = table {
1943        details["table"] = Value::from(table);
1944    }
1945    if let Some(column) = column {
1946        details["column"] = Value::from(column);
1947    }
1948    authority_forbidden(Some(details))
1949}
1950
1951/// §5.11 creation check of every declared authority query against `schema`.
1952/// A refusal is `client.authority_read_forbidden` with the details
1953/// `{ query, reason, table?, column? }`.
1954pub fn validate_authority_reads(
1955    schema: &ClientSchema,
1956    queries: &[AuthorityQuery],
1957) -> Result<(), ClientError> {
1958    let mut names = BTreeSet::new();
1959    for query in queries {
1960        let refuse = |reason: &str, table: Option<&str>, column: Option<&str>| {
1961            authority_refusal(&query.name, reason, table, column)
1962        };
1963        let declared = |param: &String| query.params.iter().any(|held| &held.name == param);
1964        if !names.insert(query.name.as_str()) {
1965            return Err(refuse("shape", None, None));
1966        }
1967        if !query.params.iter().all(|param| {
1968            matches!(
1969                param.ty.as_str(),
1970                "string" | "integer" | "float" | "boolean" | "json"
1971            )
1972        }) {
1973            return Err(refuse("param", None, None));
1974        }
1975        let mut quoted = false;
1976        let holes = query
1977            .sql
1978            .chars()
1979            .filter(|c| {
1980                if *c == '\'' {
1981                    quoted = !quoted;
1982                }
1983                !quoted && *c == '?'
1984            })
1985            .count();
1986        if !query.bind.iter().all(declared) || holes != query.bind.len() {
1987            return Err(refuse("shape", None, None));
1988        }
1989        for entry in &query.coverage {
1990            let well_formed = schema.table(&entry.table).is_some_and(|table| {
1991                table.scope_column(&entry.variable).is_some()
1992                    && entry.fixed_scopes.iter().all(|(variable, param)| {
1993                        table.scope_column(variable).is_some() && declared(param)
1994                    })
1995                    && entry.units.iter().all(declared)
1996            });
1997            if !well_formed {
1998                return Err(refuse("shape", Some(entry.table.as_str()), None));
1999            }
2000        }
2001        for (name, columns) in &query.reads {
2002            let table = schema
2003                .table(name)
2004                .filter(|_| !name.starts_with("_syncular_"))
2005                .ok_or_else(|| refuse("column", Some(name.as_str()), None))?;
2006            for column in columns {
2007                if column == "_sync_version" {
2008                    continue;
2009                }
2010                let plain = !column.starts_with("_sync")
2011                    && table.columns.iter().enumerate().any(|(index, held)| {
2012                        &held.name == column
2013                            && !table.encrypted_columns.iter().any(|e| e.index == index)
2014                            && matches!(
2015                                held.ty,
2016                                ColumnType::String
2017                                    | ColumnType::Integer
2018                                    | ColumnType::Float
2019                                    | ColumnType::Boolean
2020                                    | ColumnType::Json
2021                            )
2022                    });
2023                if !plain {
2024                    return Err(refuse("column", Some(name.as_str()), Some(column.as_str())));
2025                }
2026            }
2027        }
2028    }
2029    Ok(())
2030}
2031
2032/// §5.11 native ceiling: prepare the authored statement of `query` on `conn`
2033/// under the SQLite authorizer and return its read set, table to columns. An
2034/// empty column is a read of the table without a column (`count(*)`). Any
2035/// action other than SELECT, READ, or a deterministic core function refuses
2036/// with reason `ceiling`; a statement that does not prepare refuses with
2037/// reason `shape`. The authorizer sees the authored statement only, never
2038/// the accepted-base shadows `authority_read` adds.
2039pub fn authority_read_set(
2040    conn: &mut Connection,
2041    query: &AuthorityQuery,
2042) -> Result<BTreeMap<String, BTreeSet<String>>, ClientError> {
2043    const DETERMINISTIC: &[&str] = &[
2044        "abs",
2045        "avg",
2046        "char",
2047        "coalesce",
2048        "concat",
2049        "concat_ws",
2050        "count",
2051        "format",
2052        "glob",
2053        "group_concat",
2054        "hex",
2055        "if",
2056        "ifnull",
2057        "iif",
2058        "instr",
2059        "json",
2060        "json_array",
2061        "json_array_length",
2062        "json_extract",
2063        "json_group_array",
2064        "json_group_object",
2065        "json_object",
2066        "json_quote",
2067        "json_type",
2068        "json_valid",
2069        "length",
2070        "like",
2071        "likelihood",
2072        "likely",
2073        "lower",
2074        "ltrim",
2075        "max",
2076        "min",
2077        "nullif",
2078        "octet_length",
2079        "printf",
2080        "quote",
2081        "replace",
2082        "round",
2083        "rtrim",
2084        "sign",
2085        "string_agg",
2086        "substr",
2087        "substring",
2088        "sum",
2089        "total",
2090        "trim",
2091        "typeof",
2092        "unhex",
2093        "unicode",
2094        "unlikely",
2095        "upper",
2096        "->",
2097        "->>",
2098    ];
2099    let reads = Arc::new(std::sync::Mutex::new(
2100        BTreeMap::<String, BTreeSet<String>>::new(),
2101    ));
2102    let refused = Arc::new(std::sync::atomic::AtomicBool::new(false));
2103    let (seen, denied) = (Arc::clone(&reads), Arc::clone(&refused));
2104    let sqlite = |error: rusqlite::Error| ClientError::from(QueryReadFailure::from(error));
2105    conn.authorizer(Some(
2106        move |context: rusqlite::hooks::AuthContext<'_>| match context.action {
2107            rusqlite::hooks::AuthAction::Select => rusqlite::hooks::Authorization::Allow,
2108            rusqlite::hooks::AuthAction::Read {
2109                table_name,
2110                column_name,
2111            } => {
2112                // The Rust mirror stores the public `_sync_version` as
2113                // `_syncular_version` (query_guard lowers it).
2114                let column = if column_name == "_syncular_version" {
2115                    "_sync_version"
2116                } else {
2117                    column_name
2118                };
2119                seen.lock()
2120                    .expect("authority read set lock")
2121                    .entry(table_name.to_owned())
2122                    .or_default()
2123                    .insert(column.to_owned());
2124                rusqlite::hooks::Authorization::Allow
2125            }
2126            rusqlite::hooks::AuthAction::Function { function_name }
2127                if DETERMINISTIC
2128                    .iter()
2129                    .any(|name| name.eq_ignore_ascii_case(function_name)) =>
2130            {
2131                rusqlite::hooks::Authorization::Allow
2132            }
2133            _ => {
2134                denied.store(true, std::sync::atomic::Ordering::Relaxed);
2135                rusqlite::hooks::Authorization::Deny
2136            }
2137        },
2138    ))
2139    .map_err(sqlite)?;
2140    let prepared = crate::query_guard::prepare_read_only(
2141        conn,
2142        &crate::query_guard::lower_public_query_sql(&query.sql),
2143    )
2144    .map(drop);
2145    conn.authorizer(None::<fn(rusqlite::hooks::AuthContext<'_>) -> rusqlite::hooks::Authorization>)
2146        .map_err(sqlite)?;
2147    if refused.load(std::sync::atomic::Ordering::Relaxed) {
2148        return Err(authority_refusal(&query.name, "ceiling", None, None));
2149    }
2150    if prepared.is_err() {
2151        return Err(authority_refusal(&query.name, "shape", None, None));
2152    }
2153    let mut set = reads.lock().expect("authority read set lock");
2154    Ok(std::mem::take(&mut *set))
2155}
2156
2157// §7.4.2: every open and recreation checks before any persistent writes.
2158/// A marker read that hit a recognized SQLite storage failure keeps that
2159/// classification (BUSY/LOCKED stay retryable); only an unclassified read
2160/// failure is the invalid-marker `sync.local_corrupt`.
2161fn schema_marker_read_failure(error: rusqlite::Error) -> String {
2162    let failure = QueryReadFailure::from(error);
2163    if failure.code.is_some() {
2164        failure.to_string()
2165    } else {
2166        "sync.local_corrupt: persisted local schema marker is unreadable or invalid".to_owned()
2167    }
2168}
2169
2170/// §7.1: reject an invalid configured client limit before any storage is
2171/// opened or written. Zero would wedge the push queue and an out-of-range
2172/// value would differ per target; the TS core enforces the same bounds.
2173fn validate_client_limits(limits: &crate::api::ClientLimits) -> Result<(), String> {
2174    if limits.outcome_retention_max_entries == Some(0) {
2175        return Err("sync.invalid_request: outcomeRetentionMaxEntries must be positive".to_owned());
2176    }
2177    if [
2178        limits.max_push_commits_per_request,
2179        limits.max_push_operations_per_request,
2180        limits.max_push_request_bytes,
2181    ]
2182    .into_iter()
2183    .flatten()
2184    .any(|value| value == 0 || value > u32::MAX as usize)
2185    {
2186        return Err(
2187            "sync.invalid_request: push limit must be an integer in 1..=4294967295".to_owned(),
2188        );
2189    }
2190    Ok(())
2191}
2192
2193fn read_local_schema_version(conn: &Connection, requested: i32) -> Result<Option<i32>, String> {
2194    let corrupt =
2195        || "sync.local_corrupt: persisted local schema marker is unreadable or invalid".to_owned();
2196    let table_type: Option<String> = conn
2197        .query_row(
2198            "SELECT type FROM sqlite_master WHERE name = '_syncular_meta'",
2199            [],
2200            |row| row.get(0),
2201        )
2202        .optional()
2203        .map_err(schema_marker_read_failure)?;
2204    let Some(table_type) = table_type else {
2205        return Ok(None);
2206    };
2207    if table_type != "table" {
2208        return Err(corrupt());
2209    }
2210    // §7.4.2: a duplicated marker cannot be resolved. `query_row` would take
2211    // whichever row SQLite returns first, and an older one would drive a
2212    // destructive reset over a newer replica.
2213    let mut statement = conn
2214        .prepare("SELECT value FROM _syncular_meta WHERE key = ?1")
2215        .map_err(schema_marker_read_failure)?;
2216    let mut rows = statement
2217        .query([LOCAL_SCHEMA_VERSION_KEY])
2218        .map_err(schema_marker_read_failure)?;
2219    let value: Option<String> = rows
2220        .next()
2221        .map_err(schema_marker_read_failure)?
2222        .map(|row| row.get(0))
2223        .transpose()
2224        .map_err(schema_marker_read_failure)?;
2225    if rows.next().map_err(schema_marker_read_failure)?.is_some() {
2226        return Err(corrupt());
2227    }
2228    let Some(value) = value else {
2229        let has_descriptor = conn
2230            .query_row(
2231                "SELECT 1 FROM _syncular_meta WHERE key = ?1 LIMIT 1",
2232                [crate::previous_version::LOCAL_SCHEMA_DESCRIPTOR_KEY],
2233                |_| Ok(()),
2234            )
2235            .optional()
2236            .map_err(schema_marker_read_failure)?
2237            .is_some();
2238        if has_descriptor {
2239            return Err(corrupt());
2240        }
2241        return Ok(None);
2242    };
2243    if !matches!(value.as_bytes().first(), Some(b'1'..=b'9'))
2244        || !value.bytes().all(|b| b.is_ascii_digit())
2245    {
2246        return Err(corrupt());
2247    }
2248    let version = value.parse::<i32>().map_err(|_| corrupt())?;
2249    if version > requested {
2250        return Err(
2251            "client.schema_downgrade: persisted local schema is newer than the requested schema"
2252                .to_owned(),
2253        );
2254    }
2255    Ok(Some(version))
2256}
2257
2258/// Open a replica file. On a browser worker the file must recover a hot
2259/// journal before any statement reads it: `wasm_vfs` replaces the installed
2260/// OPFS VFS's reserved lock callback before the connection opens its file. A
2261/// new browser replica uses 64 KiB pages (§5.3), because every OPFS call costs
2262/// the same whatever its size; a database with tables keeps its page size. Its
2263/// page cache holds 64 MiB, because SQLite's 2,000 KiB default is 31 such pages
2264/// and every cache miss is an OPFS call.
2265fn open_replica(path: &str) -> Result<Connection, String> {
2266    let browser = cfg!(all(target_arch = "wasm32", target_os = "unknown"))
2267        && !path.is_empty()
2268        && path != ":memory:";
2269    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
2270    if browser {
2271        crate::wasm_vfs::disable_foreign_lock_check()?;
2272    }
2273    let conn = Connection::open(path).map_err(|e| format!("open db {path:?}: {e}"))?;
2274    if browser {
2275        conn.execute_batch("PRAGMA page_size = 65536; PRAGMA cache_size = -65536")
2276            .map_err(|e| format!("open db {path:?}: {e}"))?;
2277    }
2278    Ok(conn)
2279}
2280
2281impl SyncClient {
2282    pub fn new_with_identity(
2283        client_id: Option<String>,
2284        schema_json: &Value,
2285        limits: ClientLimits,
2286    ) -> Result<Self, String> {
2287        let resolved = client_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
2288        let conn = Connection::open_in_memory().map_err(|e| e.to_string())?;
2289        Self::with_connection(resolved, schema_json, limits, conn)
2290    }
2291
2292    pub fn new(
2293        client_id: String,
2294        schema_json: &Value,
2295        limits: ClientLimits,
2296    ) -> Result<Self, String> {
2297        let conn = Connection::open_in_memory().map_err(|e| e.to_string())?;
2298        Self::with_connection(client_id, schema_json, limits, conn)
2299    }
2300
2301    /// Build a client backed by an on-disk SQLite database at `path` — the
2302    /// seam a native host (Tauri plugin, FFI file-DB variant) uses to persist
2303    /// across process restarts. `create_tables` runs `IF NOT EXISTS`, so
2304    /// re-opening the same file reuses the persisted rows. Keeps rusqlite out
2305    /// of the command router's dependency set (the router only holds a path).
2306    pub fn open_path(
2307        client_id: String,
2308        schema_json: &Value,
2309        limits: ClientLimits,
2310        path: &str,
2311    ) -> Result<Self, String> {
2312        validate_client_limits(&limits)?;
2313        parse_schema_json(schema_json)?;
2314        let conn = open_replica(path)?;
2315        Self::with_connection(client_id, schema_json, limits, conn)
2316    }
2317
2318    /// Open a file replica and resolve its client id. Native targets require
2319    /// WAL for the independent snapshot reader; `wasm32-unknown-unknown`
2320    /// accepts the sqlite-wasm worker journal instead. `":memory:"` and `""`
2321    /// name no file: they open an in-memory replica, which has no WAL and no
2322    /// snapshot reader.
2323    pub fn open_path_with_identity(
2324        client_id: Option<String>,
2325        schema_json: &Value,
2326        limits: ClientLimits,
2327        path: &str,
2328    ) -> Result<Self, String> {
2329        Self::open_path_with_identity_journal(
2330            client_id,
2331            schema_json,
2332            limits,
2333            path,
2334            !cfg!(all(target_arch = "wasm32", target_os = "unknown"))
2335                && !path.is_empty()
2336                && path != ":memory:",
2337        )
2338    }
2339
2340    fn open_path_with_identity_journal(
2341        client_id: Option<String>,
2342        schema_json: &Value,
2343        limits: ClientLimits,
2344        path: &str,
2345        require_wal: bool,
2346    ) -> Result<Self, String> {
2347        validate_client_limits(&limits)?;
2348        // §7.4.2: an invalid requested version is refused before the replica is
2349        // even created, so a rejected constructor leaves no file behind.
2350        parse_schema_json(schema_json)?;
2351        let conn = open_replica(path)?;
2352        // A file-backed native client uses an independent read connection for
2353        // latency-critical snapshots. WAL is SQLite's intended reader/writer
2354        // concurrency mode: a view read never holds a rollback-journal lock
2355        // that delays the client's next commit. The busy timeout must precede
2356        // this replica's own startup transaction; WAL is applied only after
2357        // startup succeeded, because a refused open must leave the replica's
2358        // journal mode and contents untouched (§7.4.2).
2359        conn.busy_timeout(std::time::Duration::from_millis(250))
2360            .map_err(|error| format!("configure db {path:?} busy timeout: {error}"))?;
2361        // Durability is the caller's contract here, not the VFS default: a
2362        // rollback-journal commit needs FULL before it writes the database
2363        // pages, or a killed worker can leave a half-written image behind.
2364        // WAL below inherits the same setting.
2365        conn.pragma_update(None, "synchronous", "FULL")
2366            .map_err(|error| format!("configure db {path:?} synchronous: {error}"))?;
2367        let client = Self::with_connection_identity(client_id, schema_json, limits, conn)?;
2368        // A browser worker's sqlite-wasm VFS has no WAL mode, and the wasm
2369        // host has no independent snapshot reader. The WAL requirement exists
2370        // for native file replicas, where it is the reader/writer boundary.
2371        if require_wal {
2372            let journal_mode: String = client
2373                .conn
2374                .pragma_update_and_check(None, "journal_mode", "WAL", |row| row.get(0))
2375                .map_err(|error| Self::sqlite_failure(&client.storage_failure, error))?;
2376            if journal_mode != "wal" {
2377                return Err(
2378                    "sync.invalid_request: file-backed client requires WAL journal mode".to_owned(),
2379                );
2380            }
2381        }
2382        Ok(client)
2383    }
2384
2385    /// Delete a file replica at `path`, including its `-journal`, `-wal`, and
2386    /// `-shm` sidecars, through the VFS that owns it. Use this after
2387    /// `client.storage_corrupt`: an OPFS SAH pool stores those files under
2388    /// opaque names, so deleting the pool directory behind SQLite bypasses the
2389    /// pool's slot accounting.
2390    ///
2391    /// Close the client and every [`FileQuerySnapshotReader`] on `path` first;
2392    /// a VFS cannot delete a file another handle still owns. A file that does
2393    /// not exist counts as deleted, so a cleanly closed replica without
2394    /// sidecars resets. The next open
2395    /// creates a fresh replica (new client id) and re-bootstraps from the
2396    /// server. A memory replica has nothing to delete and fails with
2397    /// `sync.invalid_request`.
2398    pub fn reset_replica(path: &str) -> Result<(), String> {
2399        if path.is_empty() || path == ":memory:" {
2400            return Err("sync.invalid_request: a memory replica has nothing to reset".to_owned());
2401        }
2402        // SAFETY: a null VFS name asks SQLite for its process-wide default VFS,
2403        // the same one `Connection::open(path)` above selects. `xDelete` is
2404        // that VFS's own function pointer, and `c_name` outlives the call.
2405        let vfs = unsafe { rusqlite::ffi::sqlite3_vfs_find(std::ptr::null()) };
2406        if vfs.is_null() {
2407            return Err("client.storage_io: no SQLite VFS is registered".to_owned());
2408        }
2409        let delete = unsafe { (*vfs).xDelete }
2410            .ok_or_else(|| "client.storage_io: the SQLite VFS cannot delete files".to_owned())?;
2411        for suffix in ["-wal", "-shm", "-journal", ""] {
2412            let file_name = format!("{path}{suffix}");
2413            let c_name = std::ffi::CString::new(file_name.as_str()).map_err(|_| {
2414                format!("sync.invalid_request: replica path {file_name:?} contains a NUL byte")
2415            })?;
2416            // SAFETY: `vfs` and its `xDelete` pointer come from the live
2417            // SQLite library; `c_name` is a valid NUL-terminated path.
2418            let code = unsafe { delete(vfs, c_name.as_ptr(), 1) };
2419            // A cleanly closed WAL replica has no sidecars; a missing file is
2420            // already deleted.
2421            if code != rusqlite::ffi::SQLITE_OK && code != rusqlite::ffi::SQLITE_IOERR_DELETE_NOENT
2422            {
2423                return Err(format!(
2424                    "client.storage_io: deleting replica file {file_name:?} failed with SQLite code {code}"
2425                ));
2426            }
2427        }
2428        Ok(())
2429    }
2430
2431    #[must_use]
2432    pub fn client_id(&self) -> &str {
2433        &self.client_id
2434    }
2435
2436    /// Rotate the caller's client id (§1.5) and return the new one. Use it
2437    /// after a `sync.invalid_client_id` refusal (`recommendedAction:
2438    /// resetClientId`): the next round carries the new id. A live realtime
2439    /// socket is closed so the next connection registers with the new id.
2440    /// The replica and its outbox stay in place; wipe them yourself when the
2441    /// stored data belongs to the account that signed out.
2442    pub fn reset_client_id(&mut self, transport: &mut dyn Transport) -> Result<String, String> {
2443        self.disconnect_realtime(transport);
2444        let client_id = uuid::Uuid::new_v4().to_string();
2445        self.set_meta(CLIENT_ID_KEY, &client_id)?;
2446        self.client_id.clone_from(&client_id);
2447        self.round_failure = None;
2448        Ok(client_id)
2449    }
2450
2451    /// Build a client over a caller-supplied rusqlite connection — the seam a
2452    /// native host (Tauri plugin, FFI file-DB variant) uses to back the core
2453    /// with an on-disk database (`Connection::open(path)`) rather than the
2454    /// default `:memory:`. The connection MUST be fresh (no pre-existing
2455    /// syncular tables); `create_tables` runs `IF NOT EXISTS`, so re-opening
2456    /// the same file across process restarts reuses the persisted rows.
2457    pub fn with_connection(
2458        client_id: String,
2459        schema_json: &Value,
2460        limits: ClientLimits,
2461        conn: Connection,
2462    ) -> Result<Self, String> {
2463        Self::with_connection_identity(Some(client_id), schema_json, limits, conn)
2464    }
2465
2466    /// [`Self::with_connection`] for `open_path_with_identity`: no requested id
2467    /// means a durable replica's persisted `clientId` wins over a fresh one.
2468    fn with_connection_identity(
2469        client_id: Option<String>,
2470        schema_json: &Value,
2471        limits: ClientLimits,
2472        conn: Connection,
2473    ) -> Result<Self, String> {
2474        validate_client_limits(&limits)?;
2475        let schema = parse_schema_json(schema_json)?;
2476        validate_authority_reads(&schema, &limits.authority_reads)
2477            .map_err(|error| error.to_string())?;
2478        // RFC 0005 D8: resolve the previous-version config before the opening
2479        // reset runs — the capture happens inside it. Bad bounds fail loud.
2480        let previous_version = match limits.previous_version_context {
2481            Some(config) => {
2482                config.validate()?;
2483                Some(config)
2484            }
2485            None => None,
2486        };
2487        let mut client = SyncClient {
2488            #[cfg(feature = "bench-internals")]
2489            benchmark_phases: Recorder::default(),
2490            conn,
2491            schema,
2492            client_id: client_id
2493                .clone()
2494                .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()),
2495            limits,
2496            outbox: Shared::default(),
2497            failed_commits: Shared::default(),
2498            retain_failed_commits: false,
2499            conflicts: Shared::default(),
2500            rejections: Shared::default(),
2501            schema_floor: None,
2502            lease_state: None,
2503            stopped: false,
2504            upgrading: false,
2505            upgrade_kept_tables: false,
2506            sync_needed: false,
2507            realtime_policy: RealtimePolicy::Optional,
2508            realtime_state: RealtimeState::Disconnected,
2509            realtime_reason_code: None,
2510            realtime_retry_delay_ms: None,
2511            presence: HashMap::new(),
2512            now_ms: None,
2513            encryption: crate::values::EncryptionConfig::default(),
2514            security_preflight: false,
2515            security_epoch: 0,
2516            transport_gate: crate::TransportGate::Open,
2517            transport_epoch: 0,
2518            registration_epoch: 0,
2519            previous_version,
2520            insert_sql: RefCell::new(HashMap::new()),
2521            overlay_dirty: OverlayDirty::clean(),
2522            storage_failure: RefCell::new(None),
2523            #[cfg(test)]
2524            overlay_rebuild_count: Cell::new(0),
2525            #[cfg(test)]
2526            acknowledged_replay_count: Cell::new(0),
2527            #[cfg(test)]
2528            outcome_prune_count: Cell::new(0),
2529            #[cfg(test)]
2530            image_chunk_ms: Cell::new(None),
2531            progress: ProgressObserver::default(),
2532            epoch: uuid::Uuid::new_v4().to_string(),
2533            change_queue: VecDeque::new(),
2534            projection_pending_queue: VecDeque::new(),
2535            opening_replica: true,
2536            sync_intent_queue: VecDeque::new(),
2537            scopes_changed: 0,
2538            window_armed: HashSet::new(),
2539            retry_delay_ms: 250,
2540            round_retry_delay_ms: None,
2541            image_chunk_rows: HashMap::new(),
2542            round_failure: None,
2543            active_round: None,
2544            fence_round: None,
2545            last_round: None,
2546            last_change: None,
2547            query_failures: Vec::new(),
2548            coalesced: None,
2549            coalesced_failure: None,
2550        };
2551        // The row write path leans on the prepared-statement cache (two
2552        // insert statements per synced table, plus the bookkeeping
2553        // statements); size it so a multi-table schema never thrashes.
2554        client
2555            .conn
2556            .set_prepared_statement_cache_capacity(64.max(client.schema.tables.len() * 4));
2557        // §7.4.2: one write transaction (SQLite `BEGIN IMMEDIATE`, a reserved
2558        // writer) covers the marker read, the identity check, and every
2559        // bookkeeping/schema write, so a concurrent open that upgraded the
2560        // replica cannot interleave between the guard and the writes, and a
2561        // refusal leaves the replica unchanged.
2562        client
2563            .conn
2564            .execute_batch("BEGIN IMMEDIATE")
2565            .map_err(|error| Self::sqlite_failure(&client.storage_failure, error))?;
2566        let startup = (|| -> Result<(), String> {
2567            // The marker guard runs inside the write transaction, so the version
2568            // it validates is the version every write below commits under.
2569            let marker = read_local_schema_version(&client.conn, client.schema.version)?;
2570            // New app indexes may reference columns that only exist after a
2571            // version-bump reset.
2572            client.create_bookkeeping_tables()?;
2573            match client.get_meta(CLIENT_ID_KEY)? {
2574                Some(existing) => match client_id {
2575                    Some(requested) if existing != requested => {
2576                        return Err(format!(
2577                            "client.identity_mismatch: this database belongs to {existing:?}; refusing to rebind it to {requested:?}"
2578                        ))
2579                    }
2580                    _ => client.client_id = existing,
2581                },
2582                None => client.set_meta(CLIENT_ID_KEY, &client.client_id)?,
2583            }
2584            client.restore_persisted_state()?;
2585            client.failed_commits = client.load_failed_commits()?.into();
2586            match marker {
2587                None => {
2588                    client.detach_projections(None)?;
2589                    client.create_synced_tables()?;
2590                    client.persist_schema_version()?;
2591                    client.save_unit_scope_schema()?;
2592                }
2593                Some(version) if version == client.schema.version => {
2594                    client.detach_projections(None)?;
2595                    client.create_synced_tables()?;
2596                    // RFC 0005 D1: the same-version open backfills the descriptor
2597                    // for a database first opened by an unaware binary, so the
2598                    // NEXT bump can capture without needing a schema bump first.
2599                    set_local_schema_descriptor(&client.conn, &client.schema)
2600                        .map_err(|error| Self::sqlite_failure(&client.storage_failure, error))?;
2601                    client.save_unit_scope_schema()?;
2602                }
2603                Some(_) => client.run_schema_reset()?,
2604            }
2605            // RFC 0005 D9: the reset sweep cannot see a container whose capture
2606            // committed in its OWN file while the replica's savepoint never
2607            // released — a crash at that seam leaves a container beside a matching
2608            // OLD marker, and the next open at that version runs no reset. Discard
2609            // it before anything can read it. No-op when no container exists.
2610            client.reconcile_previous_version_at_boot()?;
2611            client.clear_satisfied_persisted_schema_floor()?;
2612            client.prune_unknown_units(false)?;
2613            // §7.1/§7.4.4: recover intrinsically codec-invalid persisted values at
2614            // the full startup/reset reconciliation boundary, inside this open
2615            // transaction and after the schema and identity guards, so a commit
2616            // an earlier version accepted is dropped with durable rejection
2617            // evidence before any replay. A table the current schema removed
2618            // keeps the §7.4.4 send-time classification, and an unresolved
2619            // encryption key stays with the send seam because hosts configure
2620            // keys after open.
2621            client.drop_unencodable_outbox(false, None)?;
2622            if marker == Some(client.schema.version)
2623                && (!client.outbox.is_empty()
2624                    || !client.failed_commits.is_empty()
2625                    || client.has_acknowledged_rows()?)
2626            {
2627                // Reconstruct the visible optimistic overlay from the durable
2628                // base plus outbox instead of trusting a process-interrupted
2629                // mirror.
2630                client.overlay_dirty.set(true);
2631                client.rebuild_overlay()?;
2632            }
2633            // Every persisted active unit needs one catch-up pull on
2634            // open: realtime only covers changes after connection, while an
2635            // idempotent setWindow correctly creates no fresh command effect.
2636            // Pending outbox work has the same restart requirement. The core
2637            // owns this intent so native hosts never poll or require an
2638            // application-issued sync().
2639            client.enqueue_startup_sync_if_needed()?;
2640            client
2641                .projection_pending_queue
2642                .extend(client.collect_projection_pending()?);
2643            Ok(())
2644        })();
2645        match startup {
2646            Ok(()) => match client.conn.execute_batch("COMMIT") {
2647                // §4.8: an eviction a crash interrupted finishes before any
2648                // read, with or without a transport; a replica reopened in
2649                // preflight finishes it at activation.
2650                Ok(()) => {
2651                    client.opening_replica = false;
2652                    if !client.security_preflight {
2653                        client.drain_pending_evictions()?;
2654                    }
2655                    Ok(client)
2656                }
2657                Err(error) => {
2658                    let failure = Self::sqlite_failure(&client.storage_failure, error);
2659                    if let Err(rollback) = client.conn.execute_batch("ROLLBACK") {
2660                        // Keep a failed rollback's typed storage classification.
2661                        let _ = Self::sqlite_failure(&client.storage_failure, rollback);
2662                    }
2663                    Err(failure)
2664                }
2665            },
2666            Err(error) => {
2667                if let Err(rollback) = client.conn.execute_batch("ROLLBACK") {
2668                    // Keep a failed rollback's typed storage classification.
2669                    let _ = Self::sqlite_failure(&client.storage_failure, rollback);
2670                }
2671                Err(error)
2672            }
2673        }
2674    }
2675
2676    /// Pin the client clock (epoch ms) — the §5.4 expiry check runs
2677    /// against this instead of system time (conformance virtual clock).
2678    pub fn set_now_ms(&mut self, now_ms: i64) {
2679        self.now_ms = Some(std::sync::Arc::new(now_ms.into()));
2680    }
2681
2682    /// The pinned clock, shared: a host that stores into it moves the client
2683    /// clock while a call runs (a virtual clock that advances per request).
2684    pub fn pinned_clock(&self) -> Option<std::sync::Arc<std::sync::atomic::AtomicI64>> {
2685        self.now_ms.clone()
2686    }
2687
2688    /// §5.11: install the client-side encryption keys (`keyId → key bytes`).
2689    /// The command router parses these from the `create` command's
2690    /// `encryption` config (keys as `{$bytes: hex}`).
2691    pub fn set_encryption(&mut self, encryption: crate::values::EncryptionConfig) {
2692        self.encryption = encryption;
2693    }
2694
2695    #[must_use]
2696    pub fn security_lifecycle(&self) -> &'static str {
2697        if self.security_preflight {
2698            "preflight"
2699        } else {
2700            "active"
2701        }
2702    }
2703
2704    #[must_use]
2705    pub fn security_preflight(&self) -> bool {
2706        self.security_preflight
2707    }
2708
2709    /// Host-owned, non-persisted network gate (§8.8). Local operations remain
2710    /// available. `Through` names a pending commit; any other id fails with
2711    /// `sync.outcome_not_found` and leaves the gate unchanged.
2712    pub fn set_transport_gate(
2713        &mut self,
2714        transport: &mut dyn Transport,
2715        state: crate::TransportGate,
2716    ) -> Result<(), ClientError> {
2717        if let crate::TransportGate::Through(id) = &state {
2718            if !self
2719                .outbox
2720                .iter()
2721                .any(|commit| commit.client_commit_id == *id)
2722            {
2723                return Err(ClientError {
2724                    code: "sync.outcome_not_found".to_owned(),
2725                    message: "the commit is not pending".to_owned(),
2726                    details: Some(json!({ "clientCommitId": id })),
2727                    retryable: false,
2728                });
2729            }
2730        }
2731        let closed = state == crate::TransportGate::Closed;
2732        if self.transport_gate != state {
2733            self.sync_intent_queue.clear();
2734            self.move_transport_gate(state);
2735        }
2736        // A captured reply keeps its normal apply/revocation semantics.
2737        if closed && self.active_round.is_none() {
2738            self.disconnect_realtime(transport);
2739        }
2740        Ok(())
2741    }
2742
2743    /// §8.8: a gate change, set by the host or by a `through` fallback. A
2744    /// change batch that rolls back restores the gate and epoch it captured.
2745    fn move_transport_gate(&mut self, state: crate::TransportGate) {
2746        use crate::TransportGate::{Closed, Open, Through};
2747        let wake = state != Closed
2748            && (self.transport_gate == Closed || matches!(state, Open | Through(_)))
2749            && !self.security_preflight;
2750        self.transport_gate = state;
2751        self.transport_epoch = self.transport_epoch.wrapping_add(1);
2752        self.sync_intent_queue.push_back(if wake {
2753            SyncIntent::Interactive
2754        } else {
2755            SyncIntent::None
2756        });
2757    }
2758
2759    /// §8.8: how many outbox commits, from the front, a round may push.
2760    fn pushable_commits(&self) -> usize {
2761        match &self.transport_gate {
2762            crate::TransportGate::Open => self.outbox.len(),
2763            crate::TransportGate::Through(boundary) => self
2764                .outbox
2765                .iter()
2766                .position(|commit| commit.client_commit_id == *boundary)
2767                .map_or(0, |index| index + 1),
2768            crate::TransportGate::Closed | crate::TransportGate::Pull => 0,
2769        }
2770    }
2771
2772    /// §8.8 through fallback: a commit of the prefix leaves the outbox other
2773    /// than by its acknowledgement. Called before the in-memory removal.
2774    fn leave_through(&mut self, client_commit_id: &str) {
2775        if matches!(self.transport_gate, crate::TransportGate::Through(_))
2776            && self
2777                .outbox
2778                .iter()
2779                .take(self.pushable_commits())
2780                .any(|commit| commit.client_commit_id == client_commit_id)
2781        {
2782            self.move_transport_gate(crate::TransportGate::Pull);
2783        }
2784    }
2785
2786    pub fn transport_gate(&self) -> crate::TransportGate {
2787        self.transport_gate.clone()
2788    }
2789
2790    fn transport_closed(&self) -> bool {
2791        self.transport_gate == crate::TransportGate::Closed
2792    }
2793
2794    /// Quarantine this replica: enter the fail-closed gate, release all
2795    /// core-owned key material, and record the gate in the database so
2796    /// reopening re-enters preflight until `activate_security` clears it.
2797    ///
2798    /// Use [`SyncClient::seal_security_on_teardown`] for the shutdown barrier,
2799    /// which must NOT leave that durable mark.
2800    pub fn begin_security_preflight(&mut self) -> Result<(), String> {
2801        let entering = !self.security_preflight;
2802        self.seal_security_on_teardown();
2803        // Persist the quarantine so it survives handle teardown and restart:
2804        // reopening this replica re-enters preflight until activation clears it.
2805        self.set_meta(SECURITY_PREFLIGHT_PENDING_KEY, "1")?;
2806        if entering {
2807            self.emit_status_batch()?;
2808        }
2809        Ok(())
2810    }
2811
2812    /// One change batch carrying the status snapshot (§5.11 lifecycle).
2813    fn emit_status_batch(&mut self) -> Result<(), String> {
2814        self.begin_observation("syncular_status")?;
2815        let batch = ChangeAccumulator {
2816            status: true,
2817            ..ChangeAccumulator::default()
2818        };
2819        self.finish_observation("syncular_status", batch)
2820            .inspect_err(|_| self.rollback_observation("syncular_status"))
2821    }
2822
2823    /// Release core-owned key material as a host tears the client down,
2824    /// WITHOUT recording a quarantine.
2825    ///
2826    /// Shutting an activated client down is not a quarantine event. Persisting
2827    /// the gate here marks every cleanly closed replica as pending, and the
2828    /// next plain `create` is then refused permanently: the reopen path
2829    /// restores the flag from the marker and the create guard rejects it. The
2830    /// in-memory flag still closes the gate for anything still holding this
2831    /// instance, which is all a teardown barrier needs.
2832    pub fn seal_security_on_teardown(&mut self) {
2833        self.cancel_sync_round();
2834        self.security_preflight = true;
2835        self.security_epoch = self.security_epoch.wrapping_add(1);
2836        self.encryption = crate::values::EncryptionConfig::default();
2837        self.sync_intent_queue.clear();
2838    }
2839
2840    /// Install the post-authentication keyring and release the host loop.
2841    pub fn activate_security(
2842        &mut self,
2843        encryption: crate::values::EncryptionConfig,
2844    ) -> Result<(), String> {
2845        if !self.security_preflight {
2846            return Err(
2847                "sync.invalid_request: activateSecurity requires security preflight".to_owned(),
2848            );
2849        }
2850        // §4.8: an interrupted eviction finishes before protected reads open.
2851        self.drain_pending_evictions()?;
2852        self.enqueue_startup_sync_if_needed()?;
2853        self.delete_meta(SECURITY_PREFLIGHT_PENDING_KEY)?;
2854        self.encryption = encryption;
2855        self.security_preflight = false;
2856        // §5.11: rows sealed under a key this keyring now holds open at once.
2857        self.reveal_sealed_rows()
2858            .map_err(|error| format!("{}: {}", error.code, error.message))?;
2859        self.emit_status_batch()
2860    }
2861
2862    /// §5.11: extend the installed keyring while active. The whole input is
2863    /// validated in key-id order before anything changes, so a refusal names
2864    /// the first bad key id in that order; lifecycle, realtime, and the round
2865    /// are untouched, and rows sealed under the new keys reveal at once.
2866    pub fn add_encryption_keys(
2867        &mut self,
2868        mut keys: std::collections::BTreeMap<String, Vec<u8>>,
2869    ) -> Result<(), ClientError> {
2870        let refusal = if self.security_preflight {
2871            Some(ClientError {
2872                code: SECURITY_PREFLIGHT_REQUIRED_CODE.to_owned(),
2873                message: "the local replica is in security preflight; complete quarantine checks and call activateSecurity before accessing protected data".to_owned(),
2874                details: None,
2875                retryable: false,
2876            })
2877        } else {
2878            keys.iter().find_map(|(key_id, bytes)| {
2879                if bytes.len() != 32 {
2880                    Some(invalid_authoring(
2881                        "encryption key must be 32 bytes (AES-256)",
2882                        json!({ "keyId": key_id }),
2883                    ))
2884                } else if self
2885                    .encryption
2886                    .keys
2887                    .get(key_id)
2888                    .is_some_and(|held| held != bytes)
2889                {
2890                    Some(invalid_authoring(
2891                        "encryption key id is already held with different key bytes",
2892                        json!({ "keyId": key_id }),
2893                    ))
2894                } else {
2895                    None
2896                }
2897            })
2898        };
2899        // Native key hygiene: every buffer that is not installed is zeroed
2900        // before drop.
2901        if let Some(error) = refusal {
2902            for bytes in keys.values_mut() {
2903                bytes.fill(0);
2904            }
2905            return Err(error);
2906        }
2907        for (key_id, mut bytes) in keys {
2908            match self.encryption.keys.entry(key_id) {
2909                std::collections::hash_map::Entry::Occupied(_) => bytes.fill(0),
2910                std::collections::hash_map::Entry::Vacant(slot) => {
2911                    slot.insert(bytes);
2912                }
2913            }
2914        }
2915        self.reveal_sealed_rows().map_err(|error| ClientError {
2916            code: error.code,
2917            message: error.message,
2918            details: error.details,
2919            retryable: false,
2920        })
2921    }
2922
2923    fn clock_now_ms(&self) -> i64 {
2924        self.now_ms
2925            .as_ref()
2926            .map_or_else(crate::wall_clock_ms, |clock| {
2927                clock.load(std::sync::atomic::Ordering::Relaxed)
2928            })
2929    }
2930
2931    fn create_bookkeeping_tables(&self) -> Result<(), String> {
2932        let exists = |name: &str| {
2933            self.conn
2934                .query_row(
2935                    "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?1)",
2936                    [name],
2937                    |row| row.get::<_, bool>(0),
2938                )
2939                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
2940        };
2941        let outbox_existed = exists("_syncular_outbox")?;
2942        // Durable client bookkeeping (outbox + units + meta). §7.1: a commit
2943        // queued before the send-attempt marker existed counts as attempted.
2944        self.conn
2945            .execute_batch(
2946                "CREATE TABLE IF NOT EXISTS _syncular_outbox (
2947                   seq INTEGER PRIMARY KEY AUTOINCREMENT,
2948                   commit_id TEXT NOT NULL UNIQUE, ops_json TEXT NOT NULL,
2949                   created_at_ms INTEGER NOT NULL DEFAULT 0,
2950                   attempted INTEGER NOT NULL DEFAULT 1);
2951                 CREATE TABLE IF NOT EXISTS _syncular_row_deliveries (
2952                   tbl TEXT NOT NULL, id TEXT NOT NULL, commit_seq INTEGER NOT NULL, PRIMARY KEY(tbl,id));
2953                 CREATE TABLE IF NOT EXISTS _syncular_acked_rows (
2954                   commit_id TEXT NOT NULL, idx INTEGER NOT NULL, tbl TEXT NOT NULL, id TEXT NOT NULL,
2955                   commit_seq INTEGER NOT NULL, op_json TEXT NOT NULL, intent_json TEXT,
2956                   PRIMARY KEY(commit_id, idx));
2957                 CREATE INDEX IF NOT EXISTS _syncular_acked_rows_row
2958                   ON _syncular_acked_rows(tbl, id);
2959                 CREATE TABLE IF NOT EXISTS _syncular_failed_commits (
2960                   seq INTEGER PRIMARY KEY AUTOINCREMENT, client_commit_id TEXT NOT NULL UNIQUE,
2961                   operations_json TEXT NOT NULL, initial_json TEXT NOT NULL);
2962                 CREATE TABLE IF NOT EXISTS _syncular_commit_outcomes (
2963                   seq INTEGER PRIMARY KEY AUTOINCREMENT,
2964                   client_commit_id TEXT NOT NULL UNIQUE,
2965                   status TEXT NOT NULL CHECK(status IN ('applied', 'cached', 'conflict', 'rejected')),
2966                   recorded_at_ms INTEGER NOT NULL,
2967                   results_json TEXT NOT NULL,
2968                   operations_json TEXT,
2969                   resolution TEXT NOT NULL DEFAULT 'active'
2970                     CHECK(resolution IN ('active', 'resolved_keep_server', 'superseded', 'dismissed')),
2971                   resolved_at_ms INTEGER,
2972                   replacement_client_commit_id TEXT);
2973                 CREATE INDEX IF NOT EXISTS _syncular_commit_outcomes_resolution_seq
2974                   ON _syncular_commit_outcomes(resolution, seq);
2975                 CREATE TABLE IF NOT EXISTS _syncular_units (
2976                   id TEXT PRIMARY KEY, scopes TEXT NOT NULL,
2977                   explicit INTEGER NOT NULL DEFAULT 0,
2978                   status TEXT NOT NULL DEFAULT 'active', reason_code TEXT,
2979                   cursor INTEGER DEFAULT -1, bootstrap_state TEXT,
2980                   seeded TEXT NOT NULL DEFAULT '[]', echo TEXT, applied TEXT, restriction TEXT);
2981                 CREATE TABLE IF NOT EXISTS _syncular_meta (
2982                   key TEXT PRIMARY KEY, value TEXT NOT NULL);
2983                 CREATE TABLE IF NOT EXISTS _syncular_windows (
2984                   base TEXT NOT NULL, unit TEXT NOT NULL, sub_id TEXT NOT NULL,
2985                   PRIMARY KEY (base, unit));
2986                 CREATE INDEX IF NOT EXISTS _syncular_windows_unit ON _syncular_windows(sub_id);
2987                 CREATE TABLE IF NOT EXISTS _syncular_pending_evictions (
2988                   unit_id TEXT NOT NULL, tbl TEXT NOT NULL,
2989                   effective_scopes TEXT NOT NULL, PRIMARY KEY (unit_id, tbl));
2990                 CREATE TABLE IF NOT EXISTS _syncular_blob_commit_refs(
2991                   commit_id TEXT NOT NULL, blob_id TEXT NOT NULL,
2992                   PRIMARY KEY(commit_id, blob_id));
2993                 CREATE INDEX IF NOT EXISTS _syncular_blob_commit_refs_body
2994                   ON _syncular_blob_commit_refs(blob_id);",
2995            )
2996            .map_err(|e| e.to_string())?;
2997        // The §5.6 applied-segment record and the §7.4.3 restriction, added
2998        // after the units table shipped.
2999        for column in ["applied", "restriction"] {
3000            if !self
3001                .conn
3002                .prepare("SELECT 1 FROM pragma_table_info('_syncular_units') WHERE name = ?1")
3003                .and_then(|mut stmt| stmt.exists([column]))
3004                .map_err(|e| e.to_string())?
3005            {
3006                self.conn
3007                    .execute_batch(&format!(
3008                        "ALTER TABLE _syncular_units ADD COLUMN {column} TEXT"
3009                    ))
3010                    .map_err(|e| e.to_string())?;
3011            }
3012        }
3013        // An outbox created before `pendingCommits` carried creation times.
3014        let _ = self.conn.execute_batch(
3015            "ALTER TABLE _syncular_outbox ADD COLUMN created_at_ms INTEGER NOT NULL DEFAULT 0",
3016        );
3017        // Migrate an outcome journal created before failed aggregate
3018        // envelopes were retained. Historical rows intentionally stay NULL.
3019        let _ = self
3020            .conn
3021            .execute_batch("ALTER TABLE _syncular_commit_outcomes ADD COLUMN operations_json TEXT");
3022        // §7.1: an outbox created before the send-attempt marker; every commit
3023        // it holds counts as attempted.
3024        if !self
3025            .conn
3026            .prepare("SELECT 1 FROM pragma_table_info('_syncular_outbox') WHERE name = 'attempted'")
3027            .and_then(|mut stmt| stmt.exists([]))
3028            .map_err(|e| e.to_string())?
3029        {
3030            self.conn
3031                .execute_batch(
3032                    "ALTER TABLE _syncular_outbox ADD COLUMN attempted INTEGER NOT NULL DEFAULT 1",
3033                )
3034                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
3035        }
3036        if self.get_meta(LOCAL_REVISION_KEY)?.is_none() {
3037            self.set_meta(LOCAL_REVISION_KEY, "0")?;
3038        }
3039        // §7.1: `outboxId` names the outbox sequence. A new outbox table starts
3040        // a new sequence, so it replaces the id in the same transaction.
3041        if !outbox_existed || self.get_meta(OUTBOX_ID_KEY)?.is_none() {
3042            self.set_meta(OUTBOX_ID_KEY, &uuid::Uuid::new_v4().to_string())?;
3043        }
3044        // §9: a replica written under wire version 3 keeps its outbox, journal,
3045        // rows and pending evictions and registers its units fresh. Its
3046        // subscriptions, cursors, echoes, resume tokens and window entries go;
3047        // units left from an earlier version 4 life restart.
3048        if exists("_syncular_window_pending_evict")? {
3049            let invalid: bool = self
3050                .conn
3051                .query_row(
3052                    "SELECT EXISTS(SELECT 1 FROM _syncular_window_pending_evict
3053                       WHERE NOT json_valid(effective_scopes)
3054                          OR json_type(effective_scopes) <> 'object'
3055                          OR EXISTS(SELECT 1 FROM json_each(effective_scopes)
3056                               WHERE type <> 'array'
3057                                  OR EXISTS(SELECT 1 FROM json_each(value) AS v
3058                                       WHERE v.type <> 'text')))",
3059                    [],
3060                    |row| row.get(0),
3061                )
3062                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
3063            if invalid {
3064                return Err(
3065                    "sync.local_corrupt: a version 3 pending eviction cannot be upgraded"
3066                        .to_owned(),
3067                );
3068            }
3069            self.conn
3070                .execute_batch(
3071                    "INSERT OR REPLACE INTO _syncular_pending_evictions
3072                       SELECT sub_id, tbl, effective_scopes FROM _syncular_window_pending_evict;
3073                     DROP TABLE _syncular_window_pending_evict;
3074                     DROP TABLE IF EXISTS _syncular_subscriptions;
3075                     DELETE FROM _syncular_windows;",
3076                )
3077                .and_then(|()| reset_units(&self.conn, &BTreeSet::new(), None))
3078                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
3079        }
3080        // §5.9.7 blob cache. Mutable upload state stays off the body row so
3081        // completing a large upload does not rewrite its BLOB record.
3082        if self.schema_has_blobs() {
3083            if exists("_syncular_blobs")? {
3084                let mut statement = self
3085                    .conn
3086                    .prepare("PRAGMA table_info(_syncular_blobs)")
3087                    .map_err(|e| e.to_string())?;
3088                let mut columns = statement
3089                    .query_map([], |row| row.get::<_, String>(1))
3090                    .map_err(|e| e.to_string())?
3091                    .collect::<Result<Vec<_>, _>>()
3092                    .map_err(|e| e.to_string())?;
3093                columns.sort();
3094                let mut expected = vec![
3095                    "blob_id",
3096                    "byte_length",
3097                    "bytes",
3098                    "created_at_ms",
3099                    "media_type",
3100                ];
3101                expected.sort_unstable();
3102                if columns != expected {
3103                    return Err(
3104                        "sync.schema_mismatch: Local blob schema is incompatible".to_owned()
3105                    );
3106                }
3107            } else {
3108                self.conn
3109                    .execute_batch(
3110                        "CREATE TABLE _syncular_blobs(
3111                           blob_id TEXT PRIMARY KEY,
3112                           bytes BLOB NOT NULL,
3113                           byte_length INTEGER NOT NULL,
3114                           media_type TEXT,
3115                           created_at_ms INTEGER NOT NULL);",
3116                    )
3117                    .map_err(|e| e.to_string())?;
3118            }
3119            self.conn
3120                .execute_batch(
3121                    "CREATE TABLE IF NOT EXISTS _syncular_blob_uploads(
3122                       blob_id TEXT PRIMARY KEY,
3123                       media_type TEXT,
3124                       created_at_ms INTEGER NOT NULL);",
3125                )
3126                .map_err(|e| e.to_string())?;
3127        }
3128        Ok(())
3129    }
3130
3131    /// True iff any synced table declares a `blob_ref` column (§5.9).
3132    fn schema_has_blobs(&self) -> bool {
3133        self.schema
3134            .tables
3135            .iter()
3136            .any(|t| t.columns.iter().any(|c| c.ty == ColumnType::BlobRef))
3137    }
3138
3139    // -- meta (§7.4.1 marker, bookkeeping) ------------------------------------
3140
3141    fn get_meta(&self, key: &str) -> Result<Option<String>, String> {
3142        meta_get(&self.conn, key)
3143            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
3144    }
3145
3146    // The caller holds the startup/reset transaction. Either both schema
3147    // records persist or the enclosing operation fails and rolls back.
3148    fn persist_schema_version(&self) -> Result<(), String> {
3149        self.conn
3150            .execute(
3151                "INSERT OR REPLACE INTO _syncular_meta(key,value) VALUES (?1,?2)",
3152                rusqlite::params![LOCAL_SCHEMA_VERSION_KEY, self.schema.version.to_string()],
3153            )
3154            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
3155        set_local_schema_descriptor(&self.conn, &self.schema)
3156            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
3157    }
3158
3159    pub(crate) fn set_meta(&self, key: &str, value: &str) -> Result<(), String> {
3160        meta_set(&self.conn, key, value)
3161            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
3162    }
3163
3164    fn delete_meta(&self, key: &str) -> Result<(), String> {
3165        meta_delete(&self.conn, key)
3166            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
3167    }
3168
3169    /// §7.1: the durable outbox in FIFO order, in schema-agnostic local form.
3170    fn load_outbox(&self) -> Result<Vec<Arc<OutboxCommit>>, String> {
3171        let mut stmt = self
3172            .conn
3173            .prepare("SELECT commit_id, ops_json FROM _syncular_outbox ORDER BY seq ASC")
3174            .map_err(|error| error.to_string())?;
3175        let rows = stmt
3176            .query_map([], |row| {
3177                Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
3178            })
3179            .map_err(|error| error.to_string())?;
3180        let mut commits = Vec::new();
3181        for row in rows {
3182            let (client_commit_id, raw) = row.map_err(|error| error.to_string())?;
3183            let entries: Vec<Value> = serde_json::from_str(&raw).map_err(|error| {
3184                format!("invalid persisted outbox {client_commit_id:?}: {error}")
3185            })?;
3186            let mut ops = Vec::with_capacity(entries.len());
3187            for entry in entries {
3188                let op = entry.get("op").and_then(Value::as_str).unwrap_or("delete");
3189                ops.push(OutboxOp {
3190                    upsert: op == "upsert",
3191                    table: entry
3192                        .get("table")
3193                        .and_then(Value::as_str)
3194                        .ok_or_else(|| "persisted outbox operation missing table".to_owned())?
3195                        .to_owned(),
3196                    row_id: entry
3197                        .get("rowId")
3198                        .and_then(Value::as_str)
3199                        .ok_or_else(|| "persisted outbox operation missing rowId".to_owned())?
3200                        .to_owned(),
3201                    base_version: entry.get("baseVersion").and_then(Value::as_i64),
3202                    // A legacy entry's `changedFields` key is ignored:
3203                    // the values map is the presence set (§6.1).
3204                    values: entry.get("values").and_then(Value::as_object).cloned(),
3205                    insert: entry.get("insert") == Some(&Value::Bool(true)),
3206                });
3207            }
3208            commits.push(Arc::new(OutboxCommit {
3209                client_commit_id,
3210                ops,
3211            }));
3212        }
3213        Ok(commits)
3214    }
3215
3216    fn restore_persisted_state(&mut self) -> Result<(), String> {
3217        self.outbox = self.load_outbox()?.into();
3218
3219        self.prune_commit_outcomes()?;
3220        let active = self.commit_outcomes(CommitOutcomeQuery {
3221            active_only: true,
3222            ..CommitOutcomeQuery::default()
3223        })?;
3224        self.conflicts = active
3225            .iter()
3226            .flat_map(|outcome| outcome.results.iter())
3227            .filter_map(|result| match result {
3228                CommitOperationOutcome::Conflict { conflict } => Some(conflict.clone()),
3229                _ => None,
3230            })
3231            .collect::<Vec<_>>()
3232            .into();
3233        self.rejections = active
3234            .iter()
3235            .flat_map(|outcome| outcome.results.iter())
3236            .filter_map(|result| match result {
3237                CommitOperationOutcome::Error { rejection } => Some(rejection.clone()),
3238                _ => None,
3239            })
3240            .collect::<Vec<_>>()
3241            .into();
3242
3243        self.lease_state = self
3244            .get_meta(LEASE_STATE_KEY)?
3245            .map(|raw| serde_json::from_str(&raw))
3246            .transpose()
3247            .map_err(|error| format!("invalid persisted lease state: {error}"))?;
3248        self.schema_floor = self
3249            .get_meta(SCHEMA_FLOOR_KEY)?
3250            .map(|raw| serde_json::from_str(&raw))
3251            .transpose()
3252            .map_err(|error| format!("invalid persisted schema floor: {error}"))?;
3253        self.stopped = self.schema_floor.is_some();
3254        // A replica left in unactivated preflight reopens gated: the quarantine
3255        // decision persists with the data across handle teardown and restart.
3256        if self.get_meta(SECURITY_PREFLIGHT_PENDING_KEY)?.as_deref() == Some("1") {
3257            self.security_preflight = true;
3258        }
3259        Ok(())
3260    }
3261
3262    fn save_unit_scope_schema(&self) -> Result<(), String> {
3263        let declarations: BTreeMap<_, BTreeMap<_, _>> = self
3264            .schema
3265            .tables
3266            .iter()
3267            .map(|table| {
3268                (
3269                    table.name.clone(),
3270                    table
3271                        .scope_variables
3272                        .iter()
3273                        .map(|scope| {
3274                            (
3275                                scope.variable.clone(),
3276                                [scope.prefix.clone(), scope.column.clone()],
3277                            )
3278                        })
3279                        .collect(),
3280                )
3281            })
3282            .collect();
3283        self.set_meta(
3284            "subscriptionScopeSchema",
3285            &serde_json::to_string(&declarations).expect("scope schema serialization"),
3286        )?;
3287        let generations: BTreeMap<_, _> = self
3288            .schema
3289            .tables
3290            .iter()
3291            .filter_map(|table| Some((&table.name, table.generation.as_ref()?)))
3292            .collect();
3293        self.set_meta(
3294            TABLE_GENERATIONS_KEY,
3295            &serde_json::to_string(&generations).expect("generations serialize"),
3296        )
3297    }
3298
3299    /// Drop units that cover no table of the running schema, with their window
3300    /// registry rows and pending evictions; never translate scopes. At a bump
3301    /// (§7.4.3) a unit also needs every variable unchanged in prefix and column
3302    /// on every table it covered before.
3303    fn prune_unknown_units(&mut self, bump: bool) -> Result<(), String> {
3304        let previous: Option<BTreeMap<String, BTreeMap<String, [String; 2]>>> = if bump {
3305            self.get_meta("subscriptionScopeSchema")?
3306                .map(|raw| serde_json::from_str(&raw))
3307                .transpose()
3308                .map_err(|_| "sync.local_corrupt: invalid persisted scope schema".to_owned())?
3309        } else {
3310            None
3311        };
3312        // A table keeps the variables' meaning when each has the same prefix
3313        // and column as before. An old binary stored no declaration evidence;
3314        // matching names cannot prove unchanged meaning, so the app registers
3315        // again.
3316        let unchanged = |name: &str, variables: &[&String]| {
3317            let (Some(old), Some(table)) = (
3318                previous.as_ref().and_then(|previous| previous.get(name)),
3319                self.schema.table(name),
3320            ) else {
3321                return false;
3322            };
3323            variables.iter().all(|variable| {
3324                table
3325                    .scope_variables
3326                    .iter()
3327                    .find(|scope| &scope.variable == *variable)
3328                    .is_some_and(|scope| {
3329                        old.get(*variable) == Some(&[scope.prefix.clone(), scope.column.clone()])
3330                    })
3331            })
3332        };
3333        let compatible = |scopes: &UnitScopes| {
3334            if !self.schema.tables.iter().any(|table| covers(table, scopes)) {
3335                return false;
3336            }
3337            if !bump {
3338                return true;
3339            }
3340            let Some(previous) = &previous else {
3341                return false;
3342            };
3343            previous.iter().all(|(name, old)| {
3344                !scopes.keys().all(|variable| old.contains_key(variable))
3345                    || unchanged(name, &scopes.keys().collect::<Vec<_>>())
3346            })
3347        };
3348        let mut stale: BTreeSet<String> = self
3349            .stored(load_units(&self.conn))?
3350            .into_iter()
3351            .filter(|unit| !compatible(&unit.scopes))
3352            .map(|unit| unit.id)
3353            .collect();
3354        // A shrunk window's deferred eviction outlives its unit row and keeps
3355        // its per-table scopes. A table the schema no longer has cannot be
3356        // evicted, and at a bump a table whose scope declarations changed must
3357        // not be evicted by the outdated rule.
3358        for (id, table, effective) in self.load_pending_evictions()? {
3359            if self.schema.table(&table).is_none()
3360                || (bump
3361                    && !unchanged(
3362                        &table,
3363                        &effective
3364                            .iter()
3365                            .map(|(variable, _)| variable)
3366                            .collect::<Vec<_>>(),
3367                    ))
3368            {
3369                stale.insert(id);
3370            }
3371        }
3372        for id in &stale {
3373            for sql in [
3374                "DELETE FROM _syncular_windows WHERE sub_id = ?1",
3375                "DELETE FROM _syncular_pending_evictions WHERE unit_id = ?1",
3376                "DELETE FROM _syncular_units WHERE id = ?1",
3377            ] {
3378                self.conn
3379                    .execute(sql, rusqlite::params![id])
3380                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
3381            }
3382        }
3383        Ok(())
3384    }
3385
3386    pub fn local_revision(&self) -> Result<u64, String> {
3387        Ok(self
3388            .get_meta(LOCAL_REVISION_KEY)?
3389            .and_then(|value| value.parse().ok())
3390            .unwrap_or(0))
3391    }
3392
3393    /// §7.5: resolve a snapshot read on the mutable owner connection through
3394    /// the same primitive the read-only sidecar uses, so the command surface
3395    /// and the file sidecar return one revision, rows, coverage, catch-up, and
3396    /// delivery shape. The structured [`QueryReadFailure`] is preserved; an
3397    /// `owner` records its failure (and its next success) in diagnostics.
3398    pub fn snapshot_read(
3399        &mut self,
3400        request: &SnapshotReadRequest<'_>,
3401        owner: Option<QueryOwner<'_>>,
3402    ) -> Result<SnapshotRead, QueryReadFailure> {
3403        let result = snapshot_read_connection(&self.conn, Some(&self.schema), request).and_then(
3404            |mut read| {
3405                for delivery in &mut read.deliveries {
3406                    if let CommitDelivery::Known { outcome, .. } = delivery {
3407                        *outcome = self
3408                            .attach_retained_rows(outcome.clone())
3409                            .map_err(QueryReadFailure::from)?;
3410                    }
3411                }
3412                Ok(read)
3413            },
3414        );
3415        if let Some(owner) = owner {
3416            self.record_query_read(owner, result.as_ref().err());
3417        }
3418        result
3419    }
3420
3421    /// §7.5: one client commit's delivery status with the owner's retained
3422    /// rows: pending, its journal outcome, or an explicit unknown.
3423    pub fn commit_delivery(&mut self, id: &str) -> Result<CommitDelivery, QueryReadFailure> {
3424        let read = self.snapshot_read(
3425            &SnapshotReadRequest {
3426                commit_ids: vec![id.to_owned()],
3427                ..Default::default()
3428            },
3429            None,
3430        )?;
3431        Ok(read
3432            .deliveries
3433            .into_iter()
3434            .next()
3435            .expect("one requested delivery"))
3436    }
3437
3438    #[must_use]
3439    pub fn status_snapshot(&self) -> SyncStatusSnapshot {
3440        SyncStatusSnapshot {
3441            current_schema_version: self.schema.version,
3442            outbox: self.outbox.len(),
3443            upgrading: self.upgrading,
3444            upgrade_kept_tables: self.upgrade_kept_tables,
3445            lease_state: self.lease_state.clone(),
3446            schema_floor: self.schema_floor.clone(),
3447            sync_needed: self.sync_needed,
3448            previous_version_context: self.previous_version_status(),
3449            security_lifecycle: self.security_lifecycle(),
3450        }
3451    }
3452
3453    /// RFC 0005 A2: container presence for a host that must act on it (Diego's
3454    /// rollback precondition), read without creating the file.
3455    fn previous_version_status(&self) -> PreviousVersionStatus {
3456        let Some(replica_path) = self.previous_version_replica_path() else {
3457            return PreviousVersionStatus {
3458                present: false,
3459                created_at_ms: None,
3460            };
3461        };
3462        match crate::previous_version::read_previous_version_record(&replica_path) {
3463            Ok(Some(record)) => PreviousVersionStatus {
3464                present: true,
3465                created_at_ms: Some(record.created_at_ms),
3466            },
3467            _ => PreviousVersionStatus {
3468                present: std::path::Path::new(
3469                    &crate::previous_version::previous_version_container_path(&replica_path),
3470                )
3471                .exists(),
3472                created_at_ms: None,
3473            },
3474        }
3475    }
3476
3477    /// RFC 0005 D7: read captured rows from the previous local schema. `state`
3478    /// is always `previousVersion`; the container never makes
3479    /// `query_snapshot()` coverage complete. Lease stop/expiry, scope
3480    /// revocation, coverage completion and the TTL DISCARD the container and
3481    /// close the read with their own reason.
3482    pub fn previous_version_snapshot(
3483        &self,
3484        spec: &PreviousVersionReadSpec,
3485    ) -> Result<PreviousVersionSnapshot, String> {
3486        let now_ms = self.clock_now_ms();
3487        crate::previous_version::previous_version_snapshot(
3488            &self.conn,
3489            self.previous_version_replica_path().as_deref(),
3490            self.previous_version.as_ref(),
3491            PreviousVersionLifecycle {
3492                lease_inactive: self.previous_version_lease_inactive(now_ms),
3493                scope_revoked: self
3494                    .stored(load_units(&self.conn))?
3495                    .iter()
3496                    .any(|unit| unit.status == UnitStatus::Revoked),
3497                coverage_complete: self.previous_version_coverage_complete()?,
3498            },
3499            now_ms,
3500            self.schema.version,
3501            spec,
3502        )
3503    }
3504
3505    /// RFC 0005 D6: the advisory pre-reset compatibility audit.
3506    pub fn previous_version_audit(
3507        &self,
3508    ) -> Result<Option<crate::previous_version::PreviousVersionAudit>, String> {
3509        crate::previous_version::stored_previous_version_audit(&self.conn)
3510            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
3511    }
3512
3513    /// RFC 0005 A2/D9: the executable downgrade step. Drop the container file
3514    /// and both metadata records, and report whether anything was present.
3515    /// Idempotent: absence is a successful no-op.
3516    pub fn previous_version_discard(
3517        &self,
3518    ) -> Result<crate::previous_version::PreviousVersionDiscardOutcome, String> {
3519        self.drop_previous_version()
3520    }
3521
3522    fn drop_previous_version(
3523        &self,
3524    ) -> Result<crate::previous_version::PreviousVersionDiscardOutcome, String> {
3525        let Some(replica_path) = self.previous_version_replica_path() else {
3526            return Ok(crate::previous_version::PreviousVersionDiscardOutcome {
3527                present: false,
3528                discarded: false,
3529            });
3530        };
3531        crate::previous_version::discard_previous_version(&self.conn, &replica_path)
3532    }
3533
3534    /// RFC 0005 D7: `leaseState.errorCode` or an expired lease.
3535    fn previous_version_lease_inactive(&self, now_ms: i64) -> bool {
3536        let Some(lease) = &self.lease_state else {
3537            return false;
3538        };
3539        if lease.error_code.is_some() {
3540            return true;
3541        }
3542        lease.expires_at_ms.is_some_and(|expires| expires <= now_ms)
3543    }
3544
3545    /// RFC 0005 D7: §7.4.5 replacement coverage — no active unit is
3546    /// bootstrapping. An empty active set is not completion (mirrors the TS
3547    /// predicate exactly).
3548    fn previous_version_coverage_complete(&self) -> Result<bool, String> {
3549        let units = self.stored(load_units(&self.conn))?;
3550        let mut active = units
3551            .iter()
3552            .filter(|unit| unit.status == UnitStatus::Active)
3553            .peekable();
3554        Ok(active.peek().is_some() && !active.any(UnitRecord::bootstrapping))
3555    }
3556
3557    /// RFC 0005 D7: lifetime triggers evaluated once per sync round, after the
3558    /// apply. A container that no longer has a reason to exist is discarded so
3559    /// the rows do not outlive the window they were kept for.
3560    fn previous_version_lifetime_check(&self) {
3561        let Some(config) = self.previous_version.filter(|config| config.enabled) else {
3562            return;
3563        };
3564        let now_ms = self.clock_now_ms();
3565        if self.previous_version_lease_inactive(now_ms) {
3566            let _ = self.drop_previous_version();
3567            return;
3568        }
3569        let Some(replica_path) = self.previous_version_replica_path() else {
3570            return;
3571        };
3572        let Ok(Some(record)) = crate::previous_version::read_previous_version_record(&replica_path)
3573        else {
3574            return;
3575        };
3576        let Ok(units) = load_units(&self.conn) else {
3577            return;
3578        };
3579        if units.iter().any(|unit| unit.status == UnitStatus::Revoked) {
3580            let _ = self.drop_previous_version();
3581            return;
3582        }
3583        if now_ms - record.created_at_ms > config.max_age_ms {
3584            let _ = self.drop_previous_version();
3585            return;
3586        }
3587        if self.previous_version_coverage_complete() == Ok(true) {
3588            let _ = self.drop_previous_version();
3589        }
3590    }
3591
3592    pub fn diagnostics_snapshot(&self) -> Result<ClientDiagnosticsSnapshot, String> {
3593        let registered = self.stored(load_units(&self.conn))?;
3594        // Both meta values in one statement: the FFI host recomputes
3595        // diagnostics after every command.
3596        let (local_revision, replica_cursor): (Option<String>, Option<String>) = self.stored(
3597            self.conn
3598                .prepare_cached(
3599                    "SELECT (SELECT value FROM _syncular_meta WHERE key = ?1),
3600                            (SELECT value FROM _syncular_meta WHERE key = ?2)",
3601                )
3602                .and_then(|mut statement| {
3603                    statement.query_row([LOCAL_REVISION_KEY, REPLICA_CURSOR_KEY], |row| {
3604                        Ok((row.get(0)?, row.get(1)?))
3605                    })
3606                }),
3607        )?;
3608        let mut units = DiagnosticUnits::default();
3609        for unit in &registered {
3610            *match unit.status {
3611                UnitStatus::Revoked => &mut units.revoked,
3612                UnitStatus::Failed => &mut units.failed,
3613                UnitStatus::Active if !unit.bootstrapping() => &mut units.complete,
3614                UnitStatus::Active
3615                    if unit.reason_code.as_deref() == Some("sync.cursor_expired") =>
3616                {
3617                    &mut units.reset
3618                }
3619                UnitStatus::Active => &mut units.bootstrapping,
3620            } += 1;
3621        }
3622        units.reason_codes = registered
3623            .iter()
3624            .filter_map(|unit| unit.reason_code.as_deref().map(Self::diagnostic_code))
3625            .collect::<BTreeSet<_>>()
3626            .into_iter()
3627            .collect();
3628        let captured_at_ms = self.clock_now_ms();
3629        let lease = if let Some(error_code) = self
3630            .lease_state
3631            .as_ref()
3632            .and_then(|state| state.error_code.clone())
3633        {
3634            ClientDiagnosticsLease {
3635                state: "stopped".to_owned(),
3636                expires_at_ms: self
3637                    .lease_state
3638                    .as_ref()
3639                    .and_then(|state| state.expires_at_ms),
3640                error_code: Some(Self::diagnostic_code(&error_code)),
3641            }
3642        } else if let Some(expires_at_ms) = self
3643            .lease_state
3644            .as_ref()
3645            .and_then(|state| state.expires_at_ms)
3646        {
3647            ClientDiagnosticsLease {
3648                state: if expires_at_ms <= captured_at_ms {
3649                    "expired".to_owned()
3650                } else {
3651                    "active".to_owned()
3652                },
3653                expires_at_ms: Some(expires_at_ms),
3654                error_code: None,
3655            }
3656        } else {
3657            ClientDiagnosticsLease {
3658                state: "none".to_owned(),
3659                expires_at_ms: None,
3660                error_code: None,
3661            }
3662        };
3663        let connectivity = match self.last_round.as_ref() {
3664            _ if self.transport_closed() && self.active_round.is_none() => "offline",
3665            Some(round) if round.status == "succeeded" => "online",
3666            Some(round)
3667                if round.status == "failed"
3668                    && matches!(
3669                        round.cause_kind,
3670                        Some(
3671                            crate::TransportCauseKind::Network | crate::TransportCauseKind::Connect
3672                        )
3673                    ) =>
3674            {
3675                "offline"
3676            }
3677            Some(round) if round.status == "failed" && round.http_status.is_some() => "online",
3678            _ => "unknown",
3679        };
3680        Ok(ClientDiagnosticsSnapshot {
3681            version: CLIENT_DIAGNOSTICS_VERSION,
3682            captured_at_ms,
3683            host: ClientDiagnosticsHost {
3684                kind: "direct".to_owned(),
3685                role: "single".to_owned(),
3686                connectivity: connectivity.to_owned(),
3687                realtime: self.realtime_state,
3688                realtime_policy: self.realtime_policy,
3689                realtime_reason_code: self.realtime_reason_code.clone(),
3690                realtime_retry_delay_ms: self.realtime_retry_delay_ms,
3691            },
3692            security_lifecycle: self.security_lifecycle().to_owned(),
3693            schema: ClientDiagnosticsSchema {
3694                current_version: self.schema.version,
3695                upgrading: self.upgrading,
3696                required_version: self
3697                    .schema_floor
3698                    .as_ref()
3699                    .and_then(|floor| floor.required_schema_version),
3700                latest_version: self
3701                    .schema_floor
3702                    .as_ref()
3703                    .and_then(|floor| floor.latest_schema_version),
3704            },
3705            replica: ClientDiagnosticsReplica {
3706                local_revision: local_revision
3707                    .and_then(|value| value.parse::<u64>().ok())
3708                    .unwrap_or(0)
3709                    .to_string(),
3710                sync_needed: self.sync_needed,
3711                pending_outbox: self.outbox.len(),
3712            },
3713            lease,
3714            active_units: registered
3715                .iter()
3716                .filter(|unit| unit.status == UnitStatus::Active)
3717                .count(),
3718            units,
3719            replica_cursor: replica_cursor.map_or(Ok(-1), |raw| {
3720                raw.parse()
3721                    .map_err(|_| "sync.local_corrupt: persisted unit state is invalid".to_owned())
3722            })?,
3723            last_round: self.last_round.clone(),
3724            last_change: self.last_change.clone(),
3725            storage: self.diagnostics_storage(),
3726            query_failures: self.query_failures.clone(),
3727        })
3728    }
3729
3730    fn diagnostics_storage(&self) -> ClientDiagnosticsStorage {
3731        let read = || -> Result<ClientDiagnosticsStorage, rusqlite::Error> {
3732            let page_count: i64 = self
3733                .conn
3734                .query_row("PRAGMA page_count", [], |row| row.get(0))?;
3735            let page_size: i64 = self
3736                .conn
3737                .query_row("PRAGMA page_size", [], |row| row.get(0))?;
3738            // One cached aggregate, since the FFI host recomputes diagnostics
3739            // after every command; every invocation still reads current storage.
3740            let (outbox_bytes, outcome_entries, outcome_bytes): (i64, i64, i64) = self
3741                .conn
3742                .prepare_cached(
3743                    "SELECT (SELECT COALESCE(SUM(LENGTH(ops_json)), 0) FROM _syncular_outbox),
3744                            COUNT(*), COALESCE(SUM(LENGTH(results_json) + COALESCE(LENGTH(operations_json), 0)), 0)
3745                       FROM _syncular_commit_outcomes",
3746                )?
3747                .query_row([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))?;
3748            let blob_bytes = if self.schema_has_blobs() {
3749                self.conn
3750                    .prepare_cached("SELECT COALESCE(SUM(byte_length), 0) FROM _syncular_blobs")?
3751                    .query_row([], |row| row.get(0))?
3752            } else {
3753                0
3754            };
3755            let pressure = self
3756                .limits
3757                .blob_cache_max_bytes
3758                .is_some_and(|limit| blob_bytes > limit);
3759            Ok(ClientDiagnosticsStorage {
3760                status: if pressure { "pressure" } else { "healthy" }.to_owned(),
3761                database_bytes_approx: Some(page_count.saturating_mul(page_size).max(0)),
3762                pending_outbox_bytes_approx: Some(outbox_bytes.max(0)),
3763                retained_outcome_bytes_approx: Some(outcome_bytes.max(0)),
3764                retained_outcome_entries: Some(outcome_entries.max(0)),
3765                blob_cache_bytes_approx: Some(blob_bytes.max(0)),
3766                pressure_reason_code: pressure.then(|| "client.blob_cache_over_limit".to_owned()),
3767            })
3768        };
3769        read().unwrap_or_else(|_| ClientDiagnosticsStorage {
3770            status: "unreadable".to_owned(),
3771            database_bytes_approx: None,
3772            pending_outbox_bytes_approx: None,
3773            retained_outcome_bytes_approx: None,
3774            retained_outcome_entries: None,
3775            blob_cache_bytes_approx: None,
3776            pressure_reason_code: None,
3777        })
3778    }
3779
3780    pub fn drain_change_batches(&mut self) -> Vec<ClientChangeBatch> {
3781        self.change_queue.drain(..).collect()
3782    }
3783
3784    pub fn drain_sync_intents(&mut self) -> Vec<SyncIntent> {
3785        let intents = self.sync_intent_queue.drain(..).collect();
3786        if !self.transport_closed() {
3787            intents
3788        } else {
3789            vec![SyncIntent::None]
3790        }
3791    }
3792
3793    /// §8.7 host announcement: the number of `scopes` events received since
3794    /// the last drain. The event changes no sync state; the host surfaces each
3795    /// one to the app, whose discovery registers the newly readable units.
3796    pub fn drain_scopes_changed(&mut self) -> usize {
3797        std::mem::take(&mut self.scopes_changed)
3798    }
3799
3800    fn schedule_background_retry(&mut self) -> u64 {
3801        let delay_ms = self.retry_delay_ms;
3802        self.sync_intent_queue
3803            .push_back(SyncIntent::Background { delay_ms });
3804        self.retry_delay_ms = (self.retry_delay_ms * 2).min(30_000);
3805        self.round_retry_delay_ms = Some(delay_ms);
3806        delay_ms
3807    }
3808
3809    fn reset_background_retry(&mut self) {
3810        self.retry_delay_ms = 250;
3811    }
3812
3813    fn retryable_transport_code(code: &str) -> bool {
3814        code == "transport.failed"
3815            || code == "transport.timeout"
3816            || code == "transport.unavailable"
3817            || code == "sync.transport_failed"
3818    }
3819
3820    /// §1.8: the transport reported a refused or unreachable endpoint. The
3821    /// native transport says `connect` (DNS failure, connection refused,
3822    /// reset, or aborted); a browser fetch transport says `network`. Repeating
3823    /// the request on a backoff repairs neither, so no retry is scheduled.
3824    fn unreachable_transport(details: &Option<serde_json::Value>) -> bool {
3825        matches!(
3826            details
3827                .as_ref()
3828                .and_then(|details| details.get("causeKind"))
3829                .and_then(serde_json::Value::as_str),
3830            Some("connect" | "network")
3831        )
3832    }
3833
3834    /// §1.5: a segment fetch that fails inside an otherwise complete round is
3835    /// invisible to the server (the round response arrived whole), so its code
3836    /// rides the following requests like a socket-round failure. A code the
3837    /// frame grammar rejects is not reportable and the previous code stays.
3838    fn segment_fetch_failed(&mut self, error: TransportError) -> SectionError {
3839        if ssp2::model::valid_round_failure_code(&error.code) {
3840            self.round_failure = Some(error.code.clone());
3841        }
3842        SectionError::Transport(error)
3843    }
3844
3845    /// A failed round worth a background retry: a transport failure, or a
3846    /// §10.2 code the catalog marks retryable (clients may hardcode the
3847    /// catalog metadata, §10.1). Matches the TypeScript core, which retries
3848    /// on the server's `retryable` flag.
3849    fn retryable_failure_code(code: &str) -> bool {
3850        Self::retryable_transport_code(code)
3851            || matches!(
3852                code,
3853                "sync.auth_required"
3854                    | "sync.auth_lease_required"
3855                    | "sync.auth_lease_revoked"
3856                    | "sync.internal_error"
3857                    | "sync.idempotency_cache_miss"
3858                    | "sync.schema_not_ready"
3859                    | "sync.segment_build_timeout"
3860                    | "sync.segment_store_unavailable"
3861                    | "sync.segment_expired"
3862                    | "sync.rate_limited"
3863                    | "sync.websocket_connection_limit"
3864                    | "sync.idle_timeout"
3865            )
3866    }
3867
3868    fn diagnostic_code(code: &str) -> String {
3869        let valid = !code.is_empty()
3870            && code.len() <= 96
3871            && code.contains('.')
3872            && code
3873                .bytes()
3874                .next()
3875                .is_some_and(|byte| byte.is_ascii_lowercase())
3876            && code.bytes().all(|byte| {
3877                byte.is_ascii_lowercase()
3878                    || byte.is_ascii_digit()
3879                    || matches!(byte, b'.' | b'_' | b'-')
3880            });
3881        if valid {
3882            code.to_owned()
3883        } else {
3884            "client.unknown_failure".to_owned()
3885        }
3886    }
3887
3888    fn set_sync_needed(&mut self, value: bool, interactive: bool) {
3889        if self.sync_needed != value {
3890            if self.begin_observation("syncular_status").is_ok() {
3891                self.sync_needed = value;
3892                let batch = ChangeAccumulator {
3893                    status: true,
3894                    ..ChangeAccumulator::default()
3895                };
3896                if self.finish_observation("syncular_status", batch).is_err() {
3897                    self.rollback_observation("syncular_status");
3898                }
3899            } else {
3900                self.sync_needed = value;
3901            }
3902        }
3903        if value && interactive {
3904            self.sync_intent_queue.push_back(SyncIntent::Interactive);
3905        }
3906    }
3907
3908    /// A unit-store result: a row that does not parse is `sync.local_corrupt`;
3909    /// every other SQLite error keeps its storage classification.
3910    fn stored<T>(&self, result: rusqlite::Result<T>) -> Result<T, String> {
3911        result.map_err(|error| match error {
3912            rusqlite::Error::FromSqlConversionFailure(..) => {
3913                "sync.local_corrupt: persisted unit state is invalid".to_owned()
3914            }
3915            error => Self::sqlite_failure(&self.storage_failure, error),
3916        })
3917    }
3918
3919    fn sqlite_failure(
3920        storage_failure: &RefCell<Option<QueryReadFailure>>,
3921        error: rusqlite::Error,
3922    ) -> String {
3923        let message = error.to_string();
3924        let failure = QueryReadFailure::from(error);
3925        let code = failure.code;
3926        if code.is_some() && storage_failure.borrow().is_none() {
3927            *storage_failure.borrow_mut() = Some(failure);
3928        }
3929        match code {
3930            Some(code) => format!("{code}: {message}"),
3931            None => message,
3932        }
3933    }
3934
3935    fn begin_observation(&self, name: &str) -> Result<(), String> {
3936        if let Some(failure) = &self.coalesced_failure {
3937            return Err(failure.clone());
3938        }
3939        // SQLite rolls a whole transaction back on some I/O and capacity
3940        // errors; later frames must not commit on their own after that.
3941        if self.coalesced.is_some() && self.conn.is_autocommit() {
3942            return Err("the coalesced apply transaction was rolled back".to_owned());
3943        }
3944        self.conn
3945            .execute_batch(&format!("SAVEPOINT {name}"))
3946            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
3947    }
3948
3949    /// SPEC §1.4 rule 4: open a coalesced apply transaction unless a caller
3950    /// already owns one.
3951    fn begin_coalesced_apply(&mut self) -> Result<(), String> {
3952        if self.coalesced.is_some() || !self.conn.is_autocommit() {
3953            return Ok(());
3954        }
3955        self.conn
3956            .execute_batch("BEGIN")
3957            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
3958        self.coalesced = Some(CoalescedApply {
3959            rows: 0,
3960            rollback: self.capture(),
3961        });
3962        Ok(())
3963    }
3964
3965    fn capture(&self) -> Rollback {
3966        Rollback {
3967            outbox: self.outbox.clone(),
3968            failed_commits: self.failed_commits.clone(),
3969            conflicts: self.conflicts.clone(),
3970            rejections: self.rejections.clone(),
3971            schema_floor: self.schema_floor.clone(),
3972            lease_state: self.lease_state.clone(),
3973            stopped: self.stopped,
3974            upgrading: self.upgrading,
3975            upgrade_kept_tables: self.upgrade_kept_tables,
3976            sync_needed: self.sync_needed,
3977            active_round: self.active_round,
3978            overlay_dirty: self.overlay_dirty.snapshot(),
3979            transport_gate: self.transport_gate.clone(),
3980            transport_epoch: self.transport_epoch,
3981            change_queue: self.change_queue.len(),
3982            projection_pending_queue: self.projection_pending_queue.len(),
3983            sync_intent_queue: self.sync_intent_queue.len(),
3984            last_change: self.last_change.clone(),
3985        }
3986    }
3987
3988    fn restore(&mut self, rollback: Rollback) {
3989        self.outbox = rollback.outbox;
3990        self.failed_commits = rollback.failed_commits;
3991        self.conflicts = rollback.conflicts;
3992        self.rejections = rollback.rejections;
3993        self.schema_floor = rollback.schema_floor;
3994        self.lease_state = rollback.lease_state;
3995        self.stopped = rollback.stopped;
3996        self.upgrading = rollback.upgrading;
3997        self.upgrade_kept_tables = rollback.upgrade_kept_tables;
3998        self.sync_needed = rollback.sync_needed;
3999        self.active_round = rollback.active_round;
4000        self.transport_gate = rollback.transport_gate;
4001        self.transport_epoch = rollback.transport_epoch;
4002        self.overlay_dirty.restore(rollback.overlay_dirty);
4003        self.change_queue.truncate(rollback.change_queue);
4004        self.projection_pending_queue
4005            .truncate(rollback.projection_pending_queue);
4006        self.sync_intent_queue.truncate(rollback.sync_intent_queue);
4007        self.last_change = rollback.last_change;
4008    }
4009
4010    /// Account the rows of the next frame or block. A unit that would take the
4011    /// coalesced transaction past the bound commits the earlier units first.
4012    fn coalesce_unit(&mut self, rows: usize) -> Result<(), String> {
4013        let Some(open) = &self.coalesced else {
4014            return Ok(());
4015        };
4016        if open.rows > 0 && open.rows + rows > COALESCED_APPLY_ROWS {
4017            self.commit_coalesced_apply()?;
4018            self.begin_coalesced_apply()?;
4019        }
4020        if let Some(open) = &mut self.coalesced {
4021            open.rows += rows;
4022        }
4023        Ok(())
4024    }
4025
4026    /// COMMIT the coalesced transaction. A failed COMMIT rolls every coalesced
4027    /// frame back, restores the in-memory state of its `BEGIN`, drops the
4028    /// change batches and sync intents queued since, and fails the rest of the
4029    /// response.
4030    fn commit_coalesced_apply(&mut self) -> Result<(), String> {
4031        let Some(open) = self.coalesced.take() else {
4032            return Ok(());
4033        };
4034        let committed = if self.conn.is_autocommit() {
4035            Err("the coalesced apply transaction was rolled back".to_owned())
4036        } else {
4037            self.collect_projection_pending().and_then(|pending| {
4038                self.stored(self.conn.execute_batch("COMMIT"))?;
4039                self.projection_pending_queue.extend(pending);
4040                Ok(())
4041            })
4042        };
4043        let Err(error) = committed else {
4044            return Ok(());
4045        };
4046        if !self.conn.is_autocommit() {
4047            if let Err(rollback) = self.conn.execute_batch("ROLLBACK") {
4048                let _ = Self::sqlite_failure(&self.storage_failure, rollback);
4049            }
4050        }
4051        self.restore(open.rollback);
4052        self.coalesced_failure = Some(error.clone());
4053        Err(error)
4054    }
4055
4056    /// End the response's coalescing: COMMIT what is open and clear a failure.
4057    fn finish_coalesced_apply(&mut self) -> Result<(), String> {
4058        let committed = self.commit_coalesced_apply();
4059        match self.coalesced_failure.take() {
4060            Some(failure) => Err(failure),
4061            None => committed,
4062        }
4063    }
4064
4065    fn rollback_observation(&self, name: &str) {
4066        if let Err(error) = self
4067            .conn
4068            .execute_batch(&format!("ROLLBACK TO {name}; RELEASE {name}"))
4069        {
4070            if let Some(failure) = self.storage_failure.borrow_mut().as_mut() {
4071                if failure.rollback_failure.is_none() {
4072                    failure.rollback_failure = Some(Box::new(QueryReadFailure::from(error)));
4073                }
4074            }
4075        }
4076    }
4077
4078    fn finish_observation(
4079        &mut self,
4080        name: &str,
4081        mut batch: ChangeAccumulator,
4082    ) -> Result<(), String> {
4083        #[cfg(feature = "bench-internals")]
4084        let _phase = self.benchmark_phases.start(Phase::ObservationCommit);
4085        // §8.8: an acknowledged boundary ends a `through` gate.
4086        if matches!(self.transport_gate, crate::TransportGate::Through(_))
4087            && self.pushable_commits() == 0
4088        {
4089            self.move_transport_gate(crate::TransportGate::Pull);
4090        }
4091        for table in &self.schema.tables {
4092            for projection in &table.local_projections {
4093                if batch.tables.contains_key(&table.name)
4094                    || projection
4095                        .dependencies
4096                        .iter()
4097                        .any(|dep| batch.tables.contains_key(&dep.table))
4098                {
4099                    batch.table(&projection.name);
4100                }
4101            }
4102        }
4103        if self.failed_commits.iter().any(|(commit, _)| {
4104            commit
4105                .ops
4106                .iter()
4107                .any(|operation| batch.tables.contains_key(&operation.table))
4108        }) {
4109            batch.outcomes = true;
4110        }
4111        let projection_pending = if self.coalesced.is_none() && !self.opening_replica {
4112            self.collect_projection_pending()?
4113        } else {
4114            Vec::new()
4115        };
4116        if !batch.touched() {
4117            self.conn
4118                .execute_batch(&format!("RELEASE {name}"))
4119                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4120            self.projection_pending_queue.extend(projection_pending);
4121            return Ok(());
4122        }
4123        let revision = self
4124            .local_revision()?
4125            .checked_add(1)
4126            .ok_or_else(|| "local revision exhausted u64".to_owned())?;
4127        self.conn
4128            .execute(
4129                "INSERT OR REPLACE INTO _syncular_meta(key, value) VALUES (?1, ?2)",
4130                rusqlite::params![LOCAL_REVISION_KEY, revision.to_string()],
4131            )
4132            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4133        let status = batch.status.then(|| self.status_snapshot());
4134        let event = ClientChangeBatch {
4135            revision: revision.to_string(),
4136            tables: batch
4137                .tables
4138                .into_iter()
4139                .map(|(table, scope_keys)| TableChange {
4140                    table,
4141                    scope_keys: scope_keys.map(|keys| keys.into_iter().collect()),
4142                })
4143                .collect(),
4144            windows: batch
4145                .windows
4146                .into_iter()
4147                .map(|(base_key, units)| WindowChange {
4148                    base_key,
4149                    units: units.into_iter().collect(),
4150                })
4151                .collect(),
4152            status,
4153            conflicts_changed: batch.conflicts,
4154            rejections_changed: batch.rejections,
4155            outcomes_changed: batch.outcomes,
4156            applied_commits: Vec::new(),
4157        };
4158        self.conn
4159            .execute_batch(&format!("RELEASE {name}"))
4160            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4161        let mut diagnostic_tables = event
4162            .tables
4163            .iter()
4164            .map(|entry| entry.table.clone())
4165            .collect::<BTreeSet<_>>()
4166            .into_iter()
4167            .collect::<Vec<_>>();
4168        // §7.6: the selected variables of the changed window bases.
4169        let mut diagnostic_windows = event
4170            .windows
4171            .iter()
4172            .map(|entry| {
4173                entry
4174                    .base_key
4175                    .split('\0')
4176                    .next()
4177                    .unwrap_or_default()
4178                    .to_owned()
4179            })
4180            .collect::<BTreeSet<_>>()
4181            .into_iter()
4182            .collect::<Vec<_>>();
4183        let domains_truncated = diagnostic_tables.len() > MAX_DIAGNOSTIC_DOMAINS
4184            || diagnostic_windows.len() > MAX_DIAGNOSTIC_DOMAINS;
4185        diagnostic_tables.truncate(MAX_DIAGNOSTIC_DOMAINS);
4186        diagnostic_windows.truncate(MAX_DIAGNOSTIC_DOMAINS);
4187        self.last_change = Some(DiagnosticLastChange {
4188            revision: event.revision.clone(),
4189            recorded_at_ms: self.clock_now_ms(),
4190            tables: diagnostic_tables,
4191            windows: diagnostic_windows,
4192            domains_truncated,
4193            status_changed: event.status.is_some(),
4194            conflicts_changed: event.conflicts_changed,
4195            rejections_changed: event.rejections_changed,
4196            outcomes_changed: event.outcomes_changed,
4197        });
4198        self.change_queue.push_back(event);
4199        self.projection_pending_queue.extend(projection_pending);
4200        Ok(())
4201    }
4202
4203    fn record_scope_map(
4204        &self,
4205        batch: &mut ChangeAccumulator,
4206        table_name: &str,
4207        scopes: &[(String, Vec<String>)],
4208    ) {
4209        let Some(table) = self.schema.table(table_name) else {
4210            return;
4211        };
4212        // A bulk scoped delete whose map leaves a declared variable unnamed
4213        // cannot list the deleted rows' keys for it: the change is table-wide.
4214        if table.scope_variables.iter().any(|scope| {
4215            !scopes
4216                .iter()
4217                .any(|(variable, _)| *variable == scope.variable)
4218        }) {
4219            batch.table(table_name);
4220            return;
4221        }
4222        for (variable, values) in scopes {
4223            let Some(scope) = table
4224                .scope_variables
4225                .iter()
4226                .find(|scope| &scope.variable == variable)
4227            else {
4228                continue;
4229            };
4230            for value in values {
4231                batch.scope(table_name, format!("{}:{value}", scope.prefix));
4232            }
4233        }
4234    }
4235
4236    /// Record a row's current scope keys from the base or visible table.
4237    fn record_row_scopes(
4238        &self,
4239        batch: &mut ChangeAccumulator,
4240        table_name: &str,
4241        row_id: &str,
4242        base: bool,
4243    ) -> bool {
4244        let Some(table) = self.schema.table(table_name) else {
4245            return false;
4246        };
4247        if table.scope_variables.is_empty() {
4248            return false;
4249        }
4250        let columns = table
4251            .scope_variables
4252            .iter()
4253            .map(|scope| quote_ident(&scope.column))
4254            .collect::<Vec<_>>()
4255            .join(", ");
4256        let full_table = if base {
4257            base_table(table_name)
4258        } else {
4259            visible_table(table_name)
4260        };
4261        let sql = format!(
4262            "SELECT {columns} FROM {full_table} WHERE {} LIMIT 1",
4263            row_id_predicate(table)
4264        );
4265        let Ok(mut stmt) = self.conn.prepare_cached(&sql) else {
4266            return false;
4267        };
4268        let values = stmt.query_row(rusqlite::params![row_id], |row| {
4269            let mut values = Vec::with_capacity(table.scope_variables.len());
4270            for index in 0..table.scope_variables.len() {
4271                values.push(row.get::<_, Option<String>>(index)?);
4272            }
4273            Ok(values)
4274        });
4275        let Ok(values) = values else {
4276            return false;
4277        };
4278        let mut recorded = false;
4279        for (scope, value) in table.scope_variables.iter().zip(values) {
4280            if let Some(value) = value {
4281                batch.scope(table_name, format!("{}:{value}", scope.prefix));
4282                recorded = true;
4283            }
4284        }
4285        recorded
4286    }
4287
4288    fn record_commit_changes(
4289        &self,
4290        batch: &mut ChangeAccumulator,
4291        tables: &[String],
4292        changes: &[ssp2::model::Change],
4293    ) {
4294        #[cfg(feature = "bench-internals")]
4295        let _phase = self.benchmark_phases.start(Phase::ObservationPrepare);
4296        for change in changes {
4297            let Some(table_name) = tables.get(change.table_index as usize) else {
4298                continue;
4299            };
4300            let mut precise = self.record_row_scopes(batch, table_name, &change.row_id, true);
4301            if let Some(table) = self.schema.table(table_name) {
4302                for (variable, value) in &change.scopes {
4303                    if let Some(scope) = table
4304                        .scope_variables
4305                        .iter()
4306                        .find(|scope| &scope.variable == variable)
4307                    {
4308                        batch.scope(table_name, format!("{}:{value}", scope.prefix));
4309                        precise = true;
4310                    }
4311                }
4312            }
4313            if !precise {
4314                batch.table(table_name);
4315            }
4316        }
4317    }
4318
4319    /// Whether a base or visible row matches the scope predicate; `false`
4320    /// without a local scope-column mapping. A SQLite failure is an error.
4321    fn scoped_rows_exist(
4322        &self,
4323        table_name: &str,
4324        effective: &[(String, Vec<String>)],
4325        owners: &[Vec<(String, Vec<String>)>],
4326    ) -> Result<bool, String> {
4327        let Some(table) = self.schema.table(table_name) else {
4328            return Ok(false);
4329        };
4330        let Ok(Some((predicate, params))) = local_scope_predicate(table, effective, owners) else {
4331            return Ok(false);
4332        };
4333        for source in [base_table(table_name), visible_table(table_name)] {
4334            if self
4335                .conn
4336                .query_row(
4337                    &format!("SELECT EXISTS(SELECT 1 FROM {source} WHERE {predicate})"),
4338                    rusqlite::params_from_iter(&params),
4339                    |row| row.get::<_, bool>(0),
4340                )
4341                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
4342            {
4343                return Ok(true);
4344            }
4345        }
4346        Ok(false)
4347    }
4348
4349    /// §5.6 first-page clear of `unit_id`'s pair: delete its rows except
4350    /// those another owner covers (§3.3), failing closed without a local
4351    /// scope-column mapping. Owners are read only when a row matches, inside
4352    /// the caller's transaction. Returns whether rows matched.
4353    fn clear_scope(
4354        &mut self,
4355        table: &TableSchema,
4356        effective: &[(String, Vec<String>)],
4357        unit_id: &str,
4358    ) -> Result<bool, SectionError> {
4359        let storage = |message| SectionError::Abort("storage.failed".to_owned(), message);
4360        let matched = self
4361            .scoped_rows_exist(&table.name, effective, &[])
4362            .map_err(storage)?;
4363        let owners = if matched {
4364            unit_owners(
4365                &self.stored(load_units(&self.conn)).map_err(storage)?,
4366                table,
4367                unit_id,
4368            )
4369        } else {
4370            Vec::new()
4371        };
4372        let changed = matched
4373            && (owners.is_empty()
4374                || self
4375                    .scoped_rows_exist(&table.name, effective, &owners)
4376                    .map_err(storage)?);
4377        if !self
4378            .purge_scope_rows(&table.name, effective, &owners)
4379            .map_err(storage)?
4380        {
4381            return Err(SectionError::FailClosed);
4382        }
4383        Ok(changed)
4384    }
4385
4386    /// §7.4.5: true while a schema-bump reset + first re-bootstrap runs.
4387    pub fn upgrading(&self) -> bool {
4388        self.upgrading
4389    }
4390
4391    /// §7.4.2 "app ships new code": swap to a NEW generated schema while
4392    /// keeping this client's local database (identity, outbox, tables). The
4393    /// §7.4.1 marker check then fires the wipe/re-bootstrap flow when the
4394    /// version increases. Recreation runs the same marker guard as opening
4395    /// a durable replica, holds the guard and every write it authorizes under
4396    /// one write transaction, and preserves the current client (compiled
4397    /// schema, outbox, tables) on refusal.
4398    pub fn recreate_with_schema(&mut self, schema_json: &Value) -> Result<(), String> {
4399        let new_schema = parse_schema_json(schema_json)?;
4400        validate_authority_reads(&new_schema, &self.limits.authority_reads)
4401            .map_err(|error| error.to_string())?;
4402        // §3.3: a reopened client remembers no re-armed window unit.
4403        self.window_armed.clear();
4404        self.conn
4405            .execute_batch("BEGIN IMMEDIATE")
4406            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4407        self.opening_replica = true;
4408        let prior_schema = std::mem::replace(&mut self.schema, new_schema);
4409        // §7.4.3/§7.4.4: a reset inside this transaction mutates in-memory
4410        // state (dropped outbox commits, rejections, upgrade and floor flags,
4411        // overlay dirtiness) and appends change/intent batches. A COMMIT that
4412        // fails after the reset succeeded rolls the database back, so every
4413        // one of those fields is captured here and restored with it.
4414        let rollback = self.capture();
4415        let guarded = (|| -> Result<(), String> {
4416            // §7.4.2: the marker is re-read under the write lock the caller
4417            // holds, so a replica another process upgraded meanwhile refuses
4418            // this recreation instead of having its marker and tables
4419            // downgraded.
4420            let marker = read_local_schema_version(&self.conn, self.schema.version)?;
4421            self.create_bookkeeping_tables()?;
4422            match marker {
4423                Some(version) if version < self.schema.version => self.run_schema_reset()?,
4424                None => {
4425                    self.detach_projections(None)?;
4426                    self.create_synced_tables()?;
4427                    self.persist_schema_version()?;
4428                }
4429                Some(_) => {
4430                    self.detach_projections(None)?;
4431                    self.create_synced_tables()?;
4432                }
4433            }
4434            // §7.4.2: recreation IS the boot for the in-memory core, so reload the
4435            // durable outbox the same-version path is about to replay. Only the
4436            // outbox is reloaded: the recovery below reads it, and the caller's
4437            // rollback snapshot already covers this field.
4438            self.outbox = self.load_outbox()?.into();
4439            // §7.1/§7.4.4: recover intrinsically codec-invalid persisted values at
4440            // this guarded boundary once the schema and marker agree. A bump went
4441            // through `run_schema_reset`, which performs the same recovery after
4442            // it creates the new physical tables and before its final replay.
4443            self.drop_unencodable_outbox(false, None)?;
4444            if marker == Some(self.schema.version)
4445                && (!self.outbox.is_empty()
4446                    || !self.failed_commits.is_empty()
4447                    || self.has_acknowledged_rows()?)
4448            {
4449                self.overlay_dirty.set(true);
4450                self.rebuild_overlay()?;
4451            }
4452            self.prune_unknown_units(false)?;
4453            self.save_unit_scope_schema()?;
4454            // The conformance recreate is the in-memory equivalent of reopening
4455            // a durable client. Apply the same startup catch-up contract even
4456            // when the schema itself did not change.
4457            self.enqueue_startup_sync_if_needed()?;
4458            self.projection_pending_queue
4459                .extend(self.collect_projection_pending()?);
4460            Ok(())
4461        })();
4462        self.opening_replica = false;
4463        let outcome = match guarded {
4464            Ok(()) => self
4465                .conn
4466                .execute_batch("COMMIT")
4467                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error)),
4468            Err(error) => Err(error),
4469        };
4470        if let Err(error) = outcome {
4471            if let Err(rollback) = self.conn.execute_batch("ROLLBACK") {
4472                // Keep a failed rollback's typed storage classification.
4473                let _ = Self::sqlite_failure(&self.storage_failure, rollback);
4474            }
4475            self.schema = prior_schema;
4476            self.restore(rollback);
4477            // Prepared insert statements were derived from the reverted schema.
4478            self.insert_sql.borrow_mut().clear();
4479            return Err(error);
4480        }
4481        if !self.security_preflight {
4482            self.drain_pending_evictions()?;
4483        }
4484        Ok(())
4485    }
4486
4487    fn enqueue_startup_sync_if_needed(&mut self) -> Result<(), String> {
4488        let startup_work = !self.stopped
4489            && (!self.outbox.is_empty()
4490                || self.has_acknowledged_rows()?
4491                || !self.load_pending_evictions()?.is_empty()
4492                || self
4493                    .stored(load_units(&self.conn))?
4494                    .iter()
4495                    .any(|unit| unit.status == UnitStatus::Active));
4496        if startup_work {
4497            self.sync_needed = true;
4498            self.sync_intent_queue.push_back(SyncIntent::Interactive);
4499        }
4500        Ok(())
4501    }
4502
4503    /// A native client persists schema-floor stops across process restarts.
4504    /// Once the running app already satisfies that floor, the persisted stop
4505    /// is only stale evidence from an older server round (for example, the
4506    /// server was restarted after catching up to an app that was ahead).
4507    /// Clear it and let the normal startup pull re-negotiate. If the server is
4508    /// still incompatible it will return the floor again in that first round.
4509    fn clear_satisfied_persisted_schema_floor(&mut self) -> Result<(), String> {
4510        let satisfied = self
4511            .schema_floor
4512            .as_ref()
4513            .and_then(|floor| floor.required_schema_version)
4514            .is_some_and(|required| self.schema.version >= required);
4515        if !satisfied {
4516            return Ok(());
4517        }
4518        self.delete_meta(SCHEMA_FLOOR_KEY)?;
4519        self.schema_floor = None;
4520        self.stopped = false;
4521        Ok(())
4522    }
4523
4524    /// RFC 0005 D1: discard an orphan or stale container at boot. The reset
4525    /// path already swept it; this covers a same-version or fresh-install open,
4526    /// which runs no reset and therefore no sweep — plus the D7 TTL, which only
4527    /// an aware binary can apply.
4528    fn reconcile_previous_version_at_boot(&self) -> Result<(), String> {
4529        let Some(replica_path) = self.previous_version_replica_path() else {
4530            return Ok(());
4531        };
4532        let max_age_ms = self
4533            .previous_version
4534            .filter(|config| config.enabled)
4535            .map(|config| config.max_age_ms);
4536        reconcile_previous_version_at_boot(
4537            &self.conn,
4538            &replica_path,
4539            self.schema.version,
4540            max_age_ms,
4541            self.clock_now_ms(),
4542        )
4543    }
4544
4545    /// RFC 0005 D3: the sibling container path, or `None` when the replica has
4546    /// no file — an in-memory replica returns an empty path, and a `file:` URI
4547    /// has no plain sibling path — so the feature resolves as off there.
4548    fn previous_version_replica_path(&self) -> Option<String> {
4549        let path = self.conn.path()?;
4550        if path.is_empty() || path.starts_with("file:") {
4551            return None;
4552        }
4553        Some(path.to_owned())
4554    }
4555
4556    /// §7.4.3 reset: whole-database local reset EXCEPT the outbox, clientId,
4557    /// and leaseState. Drops/recreates every synced table from the new
4558    /// schema, resets unit sync state (keeping registrations), clears
4559    /// the schema-floor stop state, rewrites the marker, drops outbox commits
4560    /// that cannot re-encode (§7.4.4), and replays the survivors on top.
4561    fn run_schema_reset(&mut self) -> Result<(), String> {
4562        self.begin_observation("syncular_schema_reset")?;
4563        let rollback = self.capture();
4564        let mut batch = ChangeAccumulator::default();
4565        let result = self
4566            .run_schema_reset_observed(&mut batch, true)
4567            .and_then(|()| self.finish_observation("syncular_schema_reset", batch));
4568        if let Err(error) = result {
4569            self.rollback_observation("syncular_schema_reset");
4570            self.restore(rollback);
4571            return Err(error);
4572        }
4573        // After the commit: a rolled-back reset keeps the in-flight round.
4574        self.cancel_sync_round();
4575        Ok(())
4576    }
4577
4578    fn run_log_epoch_reset(&mut self, log_epoch: &str) -> Result<Vec<String>, String> {
4579        if self.get_meta(LOG_EPOCH_KEY)?.is_none() {
4580            self.begin_observation("syncular_epoch_acquisition")?;
4581            let rollback = self.capture();
4582            if let Err(error) = self.conn.execute(
4583                "INSERT OR REPLACE INTO _syncular_meta(key,value) VALUES (?1,?2)",
4584                rusqlite::params![LOG_EPOCH_KEY, log_epoch],
4585            ) {
4586                self.rollback_observation("syncular_epoch_acquisition");
4587                return Err(Self::sqlite_failure(&self.storage_failure, error));
4588            }
4589            self.sync_needed = true;
4590            let batch = ChangeAccumulator {
4591                status: true,
4592                ..ChangeAccumulator::default()
4593            };
4594            if let Err(error) = self.finish_observation("syncular_epoch_acquisition", batch) {
4595                self.rollback_observation("syncular_epoch_acquisition");
4596                self.restore(rollback);
4597                return Err(error);
4598            }
4599            self.sync_intent_queue.push_back(SyncIntent::Interactive);
4600            return Ok(Vec::new());
4601        }
4602        let resets = self
4603            .stored(load_units(&self.conn))?
4604            .into_iter()
4605            .map(|unit| unit.id)
4606            .collect();
4607        self.begin_observation("syncular_log_epoch_reset")?;
4608        let rollback = self.capture();
4609        let mut batch = ChangeAccumulator::default();
4610        let result = self
4611            .run_schema_reset_observed(&mut batch, false)
4612            .and_then(|()| {
4613                self.conn
4614                    .execute(
4615                        "INSERT OR REPLACE INTO _syncular_meta(key,value) VALUES (?1,?2)",
4616                        rusqlite::params![LOG_EPOCH_KEY, log_epoch],
4617                    )
4618                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4619                self.sync_needed = true;
4620                batch.status = true;
4621                self.finish_observation("syncular_log_epoch_reset", batch)
4622            });
4623        if let Err(error) = result {
4624            self.rollback_observation("syncular_log_epoch_reset");
4625            self.restore(rollback);
4626            return Err(error);
4627        }
4628        self.cancel_sync_round();
4629        self.sync_intent_queue.push_back(SyncIntent::Interactive);
4630        Ok(resets)
4631    }
4632
4633    fn run_schema_reset_observed(
4634        &mut self,
4635        batch: &mut ChangeAccumulator,
4636        capture: bool,
4637    ) -> Result<(), String> {
4638        // §7.4.2: the reset is the only path that wipes local tables for a
4639        // version bump, and it rewrites the marker last. Re-read the marker
4640        // under this reset's transaction: a replica another process upgraded
4641        // meanwhile refuses here instead of being reset to this client's
4642        // older schema.
4643        read_local_schema_version(&self.conn, self.schema.version)?;
4644        // §7.4.3: a schema bump keeps every table whose generation equals the
4645        // persisted one; the log-epoch reset keeps nothing. The previous
4646        // declaration evidence decides which units cover only kept tables.
4647        let mut kept = BTreeSet::new();
4648        let mut previous_declarations: Option<BTreeMap<String, BTreeMap<String, Value>>> = None;
4649        if capture {
4650            let persisted: BTreeMap<String, String> = self
4651                .get_meta(TABLE_GENERATIONS_KEY)?
4652                .map(|raw| serde_json::from_str(&raw))
4653                .transpose()
4654                .map_err(|_| "sync.local_corrupt: invalid persisted table generations".to_owned())?
4655                .unwrap_or_default();
4656            kept = self
4657                .schema
4658                .tables
4659                .iter()
4660                .filter(|table| {
4661                    table.generation.is_some()
4662                        && table.generation.as_ref() == persisted.get(&table.name)
4663                })
4664                .map(|table| table.name.clone())
4665                .collect();
4666            previous_declarations = self
4667                .get_meta("subscriptionScopeSchema")?
4668                .map(|raw| serde_json::from_str(&raw))
4669                .transpose()
4670                .map_err(|_| "sync.local_corrupt: invalid persisted scope schema".to_owned())?;
4671        }
4672        // Kept tables keep both halves and their row-level bookkeeping; the
4673        // projections of kept tables keep their storage.
4674        let mut kept_objects = BTreeSet::new();
4675        for table in self
4676            .schema
4677            .tables
4678            .iter()
4679            .filter(|table| kept.contains(&table.name))
4680        {
4681            kept_objects.insert(table.name.clone());
4682            kept_objects.insert(format!("_syncular_base_{}", table.name));
4683        }
4684        kept_objects.extend(self.detach_projections(Some(&kept))?);
4685        let kept_json = serde_json::to_string(&kept).expect("table names serialize");
4686        for sql in [
4687            "DELETE FROM _syncular_acked_rows WHERE tbl NOT IN (SELECT value FROM json_each(?1))",
4688            "DELETE FROM _syncular_row_deliveries WHERE tbl NOT IN (SELECT value FROM json_each(?1))",
4689        ] {
4690            self.conn
4691                .execute(sql, [&kept_json])
4692                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4693        }
4694        self.upgrading = true;
4695        self.upgrade_kept_tables = !kept.is_empty();
4696        batch.status = true;
4697        // RFC 0005 D6: classify the pending outbox against the NEW compiled
4698        // schema BEFORE the wipe, and record the advisory audit. This pass
4699        // drops nothing, so the audit sees the original pending intent; the
4700        // §7.4.4 send-time drop and the intrinsic value recovery later in this
4701        // reset are the paths that remove a commit. The classification is
4702        // shared with the send-time drop so the two cannot disagree about what
4703        // is incompatible.
4704        if self.previous_version.is_some_and(|config| config.enabled) {
4705            let previous_version = self
4706                .get_meta(LOCAL_SCHEMA_VERSION_KEY)?
4707                .and_then(|value| value.parse::<i32>().ok())
4708                .unwrap_or(self.schema.version);
4709            let pending = self
4710                .outbox
4711                .iter()
4712                .map(|commit| PendingCommitAudit {
4713                    commit_id: &commit.client_commit_id,
4714                    operations: commit_audit_operations(commit),
4715                })
4716                .collect::<Vec<_>>();
4717            crate::previous_version::write_previous_version_audit(
4718                &self.conn,
4719                &crate::previous_version::build_previous_version_audit(
4720                    &self.schema,
4721                    &pending,
4722                    previous_version,
4723                    self.schema.version,
4724                    self.clock_now_ms(),
4725                ),
4726            )?;
4727        }
4728        // RFC 0005 D5: the container lives in its own FILE, so the reset can
4729        // never reach it. Sweep first (unconditional — also on the log-epoch
4730        // reset, which captures nothing), then capture BEFORE the wipe drops
4731        // any row. A refused capture records its reason and leaves no file.
4732        if let Some(replica_path) = self.previous_version_replica_path() {
4733            sweep_previous_version_container(&self.conn, &replica_path)?;
4734            if capture {
4735                if let Some(config) = self.previous_version.filter(|config| config.enabled) {
4736                    let previous_version = self
4737                        .get_meta(LOCAL_SCHEMA_VERSION_KEY)?
4738                        .and_then(|value| value.parse::<i32>().ok())
4739                        .unwrap_or(self.schema.version);
4740                    capture_previous_version_from_replica(
4741                        &self.conn,
4742                        &replica_path,
4743                        previous_version,
4744                        self.schema.version,
4745                        &config,
4746                        self.clock_now_ms(),
4747                    )?;
4748                }
4749            }
4750        }
4751        for table in self
4752            .schema
4753            .tables
4754            .iter()
4755            .filter(|table| !kept.contains(&table.name))
4756        {
4757            batch.table(&table.name);
4758        }
4759        for unit in self.stored(load_units(&self.conn))? {
4760            self.record_unit_windows(batch, &unit)?;
4761        }
4762        if capture {
4763            self.prune_unknown_units(true)?;
4764        }
4765        // The per-table insert SQL is derived from the OLD column lists.
4766        self.insert_sql.borrow_mut().clear();
4767        self.overlay_dirty.set(true);
4768        // Drop every synced table (base + visible) that currently exists —
4769        // discovered from sqlite_master so a bump that adds/removes tables is
4770        // handled. Bookkeeping tables (`_syncular_outbox/_units/_meta`
4771        // and the blob cache) are preserved; base tables are `_syncular_base_*`
4772        // so they are matched explicitly, not by the bookkeeping filter.
4773        // Drop virtual tables first so SQLite removes every FTS shadow table
4774        // atomically instead of the generic discovery tearing it apart.
4775        let virtual_tables: Vec<String> = {
4776            let mut stmt = self
4777                .conn
4778                .prepare(
4779                    "SELECT name FROM sqlite_master WHERE type = 'table' AND sql LIKE 'CREATE VIRTUAL TABLE%'",
4780                )
4781                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4782            let rows = stmt
4783                .query_map([], |row| row.get::<_, String>(0))
4784                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4785            rows.filter_map(Result::ok)
4786                .filter(|name| is_synced_table_name(name) && !kept_objects.contains(name))
4787                .collect()
4788        };
4789        for name in virtual_tables {
4790            self.conn
4791                .execute_batch(&format!(
4792                    "DROP TABLE IF EXISTS {}",
4793                    quote_ident(&format!("_syncular_fts_{name}"))
4794                ))
4795                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4796            self.conn
4797                .execute(&format!("DROP TABLE IF EXISTS {}", quote_ident(&name)), [])
4798                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4799        }
4800        let existing: Vec<String> = {
4801            let mut stmt = self
4802                .conn
4803                .prepare("SELECT name FROM sqlite_master WHERE type = 'table'")
4804                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4805            let rows = stmt
4806                .query_map([], |row| row.get::<_, String>(0))
4807                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4808            rows.filter_map(Result::ok)
4809                .filter(|name| is_synced_table_name(name) && !kept_objects.contains(name))
4810                .collect()
4811        };
4812        for name in &existing {
4813            if let Some(table) = name.strip_prefix("_syncular_base_") {
4814                batch.table(table);
4815            } else if !name.starts_with("_syncular_") {
4816                batch.table(name);
4817            }
4818        }
4819        for name in existing {
4820            self.conn
4821                .execute(&format!("DROP TABLE IF EXISTS {}", quote_ident(&name)), [])
4822                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4823        }
4824        // Recreate the synced tables from the NEW schema.
4825        self.create_synced_tables()?;
4826        // Reset the sync state of every unit that covers a table the reset
4827        // did not keep, under the previous declarations or the new schema,
4828        // keeping the registration.
4829        let keep_units = match &previous_declarations {
4830            Some(previous) if !kept.is_empty() => self
4831                .stored(load_units(&self.conn))?
4832                .into_iter()
4833                .filter(|unit| {
4834                    previous.iter().all(|(name, old)| {
4835                        kept.contains(name) || !unit.scopes.keys().all(|v| old.contains_key(v))
4836                    }) && self
4837                        .schema
4838                        .tables
4839                        .iter()
4840                        .all(|table| kept.contains(&table.name) || !covers(table, &unit.scopes))
4841                })
4842                .map(|unit| unit.id)
4843                .collect(),
4844            _ => BTreeSet::new(),
4845        };
4846        // §7.4.3 restriction: an active unit that is not kept and whose rows
4847        // of a kept table are complete through a cursor C (its restriction's,
4848        // its post-bootstrap P, or the replica cursor it is live under)
4849        // bootstraps only its other covered tables and joins at C.
4850        let restrictions = if capture {
4851            let replica = self.stored(replica_cursor(&self.conn))?;
4852            let mut restrictions = BTreeMap::new();
4853            for unit in self.stored(load_units(&self.conn))? {
4854                if keep_units.contains(&unit.id) || unit.status != UnitStatus::Active {
4855                    continue;
4856                }
4857                let cursor = match (&unit.restriction, unit.cursor) {
4858                    (Some(restriction), _) => restriction.cursor,
4859                    (None, Some(cursor)) if cursor >= 0 && unit.bootstrap_state.is_none() => cursor,
4860                    (None, None) if replica >= 0 => replica,
4861                    _ => continue,
4862                };
4863                let covered: Vec<&String> = self
4864                    .schema
4865                    .tables
4866                    .iter()
4867                    .filter(|table| covers(table, &unit.scopes))
4868                    .map(|table| &table.name)
4869                    .collect();
4870                let mut tables: Vec<String> = covered
4871                    .iter()
4872                    .filter(|name| {
4873                        !kept.contains(**name)
4874                            || unit
4875                                .restriction
4876                                .as_ref()
4877                                .is_some_and(|restriction| restriction.tables.contains(name))
4878                    })
4879                    .map(|name| (*name).clone())
4880                    .collect();
4881                if tables.is_empty() || tables.len() == covered.len() {
4882                    continue;
4883                }
4884                tables.sort_by(|a, b| a.encode_utf16().cmp(b.encode_utf16()));
4885                restrictions.insert(unit.id, UnitRestriction { cursor, tables });
4886            }
4887            Some(restrictions)
4888        } else {
4889            None
4890        };
4891        reset_units(&self.conn, &keep_units, restrictions.as_ref())
4892            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4893        // The stop state is over: this client now ships a servable schema.
4894        self.stopped = false;
4895        self.schema_floor = None;
4896        self.delete_meta(SCHEMA_FLOOR_KEY)?;
4897        // Rewrite the marker LAST so a crash mid-reset re-runs the reset.
4898        self.persist_schema_version()?;
4899        self.save_unit_scope_schema()?;
4900        // §7.1/§7.4.4: the previous-version capture and audit above saw the
4901        // original pending intent; the synced tables now carry the new schema, so
4902        // recover intrinsically codec-invalid persisted values here, before the
4903        // final replay. A pending upsert that names a column the new schema
4904        // removed stays pending for the send-time `drop_incompatible_outbox`
4905        // prepass. The reset wrapper snapshots and restores the outbox,
4906        // rejections, and change queues, so a failed commit rolls this recovery
4907        // back with the rest of the reset.
4908        // §7.4.4: the enclosing reset observation owns the publication, so the
4909        // recovery contributes its rejection, outcome, and table domains to it.
4910        self.drop_unencodable_outbox(false, Some(batch))?;
4911        // Re-apply the surviving outbox optimistically over the empty tables.
4912        self.rebuild_overlay()?;
4913        Ok(())
4914    }
4915
4916    /// §7.4.4 send-time prepass: a persisted upsert whose values reference a
4917    /// column the current schema lacks (or a removed table) cannot be encoded
4918    /// (`commit_audit_operations` inspects upserts, so a value-free delete stays
4919    /// encodable and is validated by the server), nor can an insert-intent
4920    /// upsert that lacks a non-nullable column (§7.1, the audit's
4921    /// `missing-required-column`). Drop the commit, undo
4922    /// its optimistic projection, and raise a client-local
4923    /// `sync.outbox_incompatible` rejection.
4924    fn drop_incompatible_outbox(&mut self) -> Result<bool, String> {
4925        let incompatible = self
4926            .outbox
4927            .iter()
4928            .filter(|commit| {
4929                first_incompatibility(&self.schema, &commit_audit_operations(commit)).is_some()
4930            })
4931            .cloned()
4932            .collect::<Vec<_>>();
4933        if incompatible.is_empty() {
4934            return Ok(false);
4935        }
4936        self.drop_outbox_commits(
4937            &incompatible,
4938            OUTBOX_INCOMPATIBLE_CODE,
4939            "the persisted commit cannot encode under the current schema",
4940        )?;
4941        Ok(true)
4942    }
4943
4944    /// §7.4.4 incompatible-commit path, also taken by a refused blob upload
4945    /// (§5.9.7) with the server's code: reject every operation of `commits`,
4946    /// remove them from the outbox, and undo their optimistic rows.
4947    fn drop_outbox_commits(
4948        &mut self,
4949        incompatible: &[Arc<OutboxCommit>],
4950        code: &str,
4951        message: &str,
4952    ) -> Result<(), String> {
4953        // §7.4.4: one observation covers the durable outcome writes, the outbox
4954        // removal, the in-memory drop, and the overlay rebuild, so a storage
4955        // fault leaves the replica and the client unchanged and publishes no
4956        // change; a successful drop publishes exactly one batch carrying the
4957        // rejections, outcomes, status, and the tables whose projection changed.
4958        let rollback = self.capture();
4959        let owns_transaction = self.conn.is_autocommit();
4960        self.begin_observation("syncular_outbox_drop")?;
4961        let mut batch = ChangeAccumulator::default();
4962        let dropped = (|| -> Result<(), String> {
4963            let mut rejections = Vec::new();
4964            for commit in incompatible {
4965                let results = commit
4966                    .ops
4967                    .iter()
4968                    .enumerate()
4969                    .map(|(op_index, operation)| {
4970                        let rejection = RejectionRecord {
4971                            client_commit_id: commit.client_commit_id.clone(),
4972                            op_index: op_index as i32,
4973                            code: code.to_owned(),
4974                            message: message.to_owned(),
4975                            retryable: false,
4976                            details: None,
4977                            operation: Some(CommitOperation::from(operation)),
4978                        };
4979                        rejections.push(rejection.clone());
4980                        CommitOperationOutcome::Error { rejection }
4981                    })
4982                    .collect::<Vec<_>>();
4983                self.persist_commit_outcome(
4984                    &commit.client_commit_id,
4985                    CommitOutcomeStatus::Rejected,
4986                    &results,
4987                    Some(&commit.ops),
4988                )?;
4989                self.leave_through(&commit.client_commit_id);
4990                self.delete_outbox_persisted(&commit.client_commit_id)?;
4991                // A removed table has no local projection to invalidate; every
4992                // surviving table the dropped commit touched does.
4993                for operation in &commit.ops {
4994                    if self.schema.table(&operation.table).is_some() {
4995                        batch.table(&operation.table);
4996                    }
4997                }
4998            }
4999            self.prune_commit_outcomes()?;
5000            let incompatible_ids = incompatible
5001                .iter()
5002                .map(|commit| commit.client_commit_id.as_str())
5003                .collect::<BTreeSet<_>>();
5004            self.outbox
5005                .retain(|commit| !incompatible_ids.contains(commit.client_commit_id.as_str()));
5006            self.rejections.extend(rejections);
5007            // The dropped commits' purely-optimistic rows are undone: the
5008            // visible projection is re-derived from the surviving base + outbox.
5009            self.overlay_dirty.set(true);
5010            self.rebuild_overlay()?;
5011            batch.status = true;
5012            batch.rejections = true;
5013            batch.outcomes = true;
5014            Ok(())
5015        })();
5016        let result = dropped.and_then(|()| self.finish_observation("syncular_outbox_drop", batch));
5017        if let Err(error) = result {
5018            // An outer RELEASE is the COMMIT. Roll back that transaction
5019            // directly: retrying RELEASE after ROLLBACK TO still needs the
5020            // reader's lock. A nested observation only rolls back its savepoint.
5021            if owns_transaction {
5022                if let Err(rollback) = self.conn.execute_batch("ROLLBACK") {
5023                    let mut failure = self.storage_failure.borrow_mut();
5024                    let failure =
5025                        failure.get_or_insert_with(|| QueryReadFailure::from(error.clone()));
5026                    failure.rollback_failure = Some(Box::new(QueryReadFailure::from(rollback)));
5027                }
5028            } else {
5029                self.rollback_observation("syncular_outbox_drop");
5030            }
5031            self.restore(rollback);
5032            return Err(error);
5033        }
5034        Ok(())
5035    }
5036
5037    /// §7.4.3: (re)create the base + visible table pair for every synced
5038    /// table in the CURRENT schema (idempotent — `IF NOT EXISTS`).
5039    fn create_synced_tables(&self) -> Result<(), String> {
5040        for table in &self.schema.tables {
5041            // The base half + the visible half form the synced-table pair. An
5042            // index name is global in SQLite, so the base half's indexes are
5043            // name-prefixed (`_syncular_base_<index>`) to stay distinct.
5044            for (full, index_prefix) in [
5045                (base_table(&table.name), "_syncular_base_"),
5046                (visible_table(&table.name), ""),
5047            ] {
5048                let mut cols: Vec<String> =
5049                    table.columns.iter().map(|c| quote_ident(&c.name)).collect();
5050                cols.push("\"_syncular_version\" INTEGER NOT NULL".to_owned());
5051                cols.extend(
5052                    table
5053                        .sealed_columns()
5054                        .iter()
5055                        .map(|name| format!("{} TEXT", quote_ident(name))),
5056                );
5057                let sql = format!(
5058                    "CREATE TABLE IF NOT EXISTS {full} ({} , PRIMARY KEY ({}))",
5059                    cols.join(", "),
5060                    quote_ident(&table.primary_key)
5061                );
5062                self.conn
5063                    .execute(&sql, [])
5064                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5065                // §5.11: a replica created before sealed apply gains the
5066                // reserved columns in place, on both halves in the same order,
5067                // so data, indexes and the FTS projection stay.
5068                for name in table.sealed_columns() {
5069                    let present: bool = self
5070                        .conn
5071                        .query_row(
5072                            "SELECT EXISTS(SELECT 1 FROM pragma_table_info(?1) WHERE name = ?2)",
5073                            rusqlite::params![format!("{index_prefix}{}", table.name), name],
5074                            |row| row.get(0),
5075                        )
5076                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5077                    if !present {
5078                        self.conn
5079                            .execute(
5080                                &format!(
5081                                    "ALTER TABLE {full} ADD COLUMN {} TEXT",
5082                                    quote_ident(name)
5083                                ),
5084                                [],
5085                            )
5086                            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5087                    }
5088                }
5089                // The reveal at every round start reads the sealed rows of the
5090                // base half through this partial index.
5091                if table.has_encrypted_columns() && !index_prefix.is_empty() {
5092                    self.conn
5093                        .execute(
5094                            &format!(
5095                                "CREATE INDEX IF NOT EXISTS {} ON {full} (\"_sync_sealed_key\") WHERE \"_sync_sealed_key\" IS NOT NULL",
5096                                quote_ident(&format!("_syncular_sealed_{}", table.name))
5097                            ),
5098                            [],
5099                        )
5100                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5101                }
5102            }
5103        }
5104        // §7.4.3 declared indexes: reconciled in place on both halves (the
5105        // base half's names carry the `_syncular_base_` prefix) at every open
5106        // and at the end of every reset. `localIndexes` records the declared
5107        // names Syncular created; only those are ever dropped.
5108        let recorded: BTreeMap<String, BTreeSet<String>> = match self.get_meta("localIndexes")? {
5109            Some(raw) => serde_json::from_str(&raw)
5110                .map_err(|_| "sync.local_corrupt: invalid persisted local indexes".to_owned())?,
5111            // A replica without the record: every declared index that exists
5112            // counts as created by Syncular, so nothing is stale.
5113            None => BTreeMap::new(),
5114        };
5115        let declared: BTreeMap<String, BTreeSet<String>> = self
5116            .schema
5117            .tables
5118            .iter()
5119            .filter(|table| !table.indexes.is_empty())
5120            .map(|table| {
5121                let names = table.indexes.iter().map(|index| index.name.clone());
5122                (table.name.clone(), names.collect())
5123            })
5124            .collect();
5125        for (table, names) in &recorded {
5126            for name in names.iter().filter(|name| {
5127                !declared
5128                    .get(table)
5129                    .is_some_and(|declared| declared.contains(*name))
5130            }) {
5131                self.stored(self.conn.execute_batch(&format!(
5132                    "DROP INDEX IF EXISTS {}; DROP INDEX IF EXISTS {}",
5133                    quote_ident(name),
5134                    quote_ident(&format!("_syncular_base_{name}"))
5135                )))?;
5136            }
5137        }
5138        for table in &self.schema.tables {
5139            for index in &table.indexes {
5140                for (owner, name) in [
5141                    (
5142                        format!("_syncular_base_{}", table.name),
5143                        format!("_syncular_base_{}", index.name),
5144                    ),
5145                    (table.name.clone(), index.name.clone()),
5146                ] {
5147                    let current: Option<(String, bool, bool)> = self.stored(
5148                        self.conn
5149                            .query_row(
5150                                "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",
5151                                [&name],
5152                                |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
5153                            )
5154                            .optional(),
5155                    )?;
5156                    if let Some((current_owner, unique, partial)) = current {
5157                        let mut stmt = self
5158                            .stored(self.conn.prepare(
5159                                "SELECT name FROM pragma_index_info(?1) ORDER BY seqno",
5160                            ))?;
5161                        let columns = self.stored(
5162                            self.stored(
5163                                stmt.query_map([&name], |row| row.get::<_, Option<String>>(0)),
5164                            )?
5165                            .collect::<Result<Vec<_>, _>>(),
5166                        )?;
5167                        if current_owner == owner
5168                            && unique == index.unique
5169                            && !partial
5170                            && columns
5171                                .iter()
5172                                .map(Option::as_deref)
5173                                .eq(index.columns.iter().map(|column| Some(column.as_str())))
5174                        {
5175                            continue;
5176                        }
5177                        self.stored(
5178                            self.conn
5179                                .execute(&format!("DROP INDEX {}", quote_ident(&name)), []),
5180                        )?;
5181                    }
5182                    self.stored(self.conn.execute(
5183                        &format!(
5184                            "CREATE {}INDEX {} ON {} ({})",
5185                            if index.unique { "UNIQUE " } else { "" },
5186                            quote_ident(&name),
5187                            quote_ident(&owner),
5188                            index
5189                                .columns
5190                                .iter()
5191                                .map(|column| quote_ident(column))
5192                                .collect::<Vec<_>>()
5193                                .join(", ")
5194                        ),
5195                        [],
5196                    ))?;
5197                }
5198            }
5199        }
5200        self.set_meta(
5201            "localIndexes",
5202            &serde_json::to_string(&declared).expect("index names serialize"),
5203        )?;
5204        self.open_projections()
5205    }
5206
5207    fn create_fts_storage(
5208        &self,
5209        name: &str,
5210        columns: &str,
5211        tokenize: &str,
5212        options: &str,
5213    ) -> Result<(), String> {
5214        let tokenizer = tokenize.replace('\'', "''");
5215        let sql = format!(
5216            "CREATE VIRTUAL TABLE IF NOT EXISTS {} USING fts5({} UNINDEXED, {columns}, tokenize='{tokenizer}'{options})",
5217            quote_ident(name),
5218            quote_ident(FTS_SOURCE_ID_COLUMN),
5219        );
5220        self.conn
5221            .execute(&sql, [])
5222            .map_err(|error| format!("cannot create local FTS5 projection {name:?}: {error}"))?;
5223        let mapping = quote_ident(&format!("_syncular_fts_{name}"));
5224        self.stored(self.conn.execute_batch(&format!("CREATE TABLE IF NOT EXISTS {mapping}(id INTEGER PRIMARY KEY, source_id TEXT NOT NULL UNIQUE)")))
5225    }
5226
5227    // -- persistence write-through --------------------------------------------
5228
5229    fn persist_outbox_insert(&self, commit: &OutboxCommit) -> Result<(), String> {
5230        let ops: Vec<Value> = commit
5231            .ops
5232            .iter()
5233            .map(|op| {
5234                let mut entry = serde_json::json!({
5235                    "op": if op.upsert { "upsert" } else { "delete" },
5236                    "table": op.table,
5237                    "rowId": op.row_id,
5238                    "baseVersion": op.base_version,
5239                    "values": op.values.clone().map(Value::Object),
5240                });
5241                if op.insert {
5242                    entry["insert"] = Value::Bool(true);
5243                }
5244                entry
5245            })
5246            .collect();
5247        self.conn
5248            .execute(
5249                "INSERT OR REPLACE INTO _syncular_outbox (commit_id, ops_json, created_at_ms, attempted) VALUES (?1, ?2, ?3, 0)",
5250                rusqlite::params![
5251                    commit.client_commit_id,
5252                    Value::Array(ops).to_string(),
5253                    self.clock_now_ms()
5254                ],
5255            )
5256            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5257        for operation in &commit.ops {
5258            let Some(values) = &operation.values else {
5259                continue;
5260            };
5261            let Some(table) = self.schema.table(&operation.table) else {
5262                continue;
5263            };
5264            for column in table
5265                .columns
5266                .iter()
5267                .filter(|column| column.ty == ColumnType::BlobRef)
5268            {
5269                let Some(Value::String(raw)) = values.get(&column.name) else {
5270                    continue;
5271                };
5272                let Ok(blob_ref) = serde_json::from_str::<Value>(raw) else {
5273                    continue;
5274                };
5275                let Some(blob_id) = blob_ref.get("blobId").and_then(Value::as_str) else {
5276                    continue;
5277                };
5278                self.conn
5279                    .execute(
5280                        "INSERT OR IGNORE INTO _syncular_blob_commit_refs(commit_id, blob_id)
5281                         SELECT ?1, ?2 WHERE EXISTS (SELECT 1 FROM _syncular_blobs WHERE blob_id = ?2)",
5282                        rusqlite::params![commit.client_commit_id, blob_id],
5283                    )
5284                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5285            }
5286        }
5287        Ok(())
5288    }
5289
5290    fn delete_outbox_persisted(&self, client_commit_id: &str) -> Result<(), String> {
5291        self.conn
5292            .execute(
5293                "DELETE FROM _syncular_blob_commit_refs WHERE commit_id = ?1",
5294                rusqlite::params![client_commit_id],
5295            )
5296            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5297        self.conn
5298            .execute(
5299                "DELETE FROM _syncular_outbox WHERE commit_id = ?1",
5300                rusqlite::params![client_commit_id],
5301            )
5302            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5303        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)", [])
5304            .map(|_| ())
5305            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
5306    }
5307
5308    fn outcome_status_name(status: CommitOutcomeStatus) -> &'static str {
5309        match status {
5310            CommitOutcomeStatus::Applied => "applied",
5311            CommitOutcomeStatus::Cached => "cached",
5312            CommitOutcomeStatus::Conflict => "conflict",
5313            // §7.2.1: a replaced commit is stored as a decided rejection.
5314            CommitOutcomeStatus::Rejected | CommitOutcomeStatus::Replaced => "rejected",
5315        }
5316    }
5317
5318    fn outcome_resolution_name(resolution: CommitOutcomeResolution) -> &'static str {
5319        match resolution {
5320            CommitOutcomeResolution::Active => "active",
5321            CommitOutcomeResolution::ResolvedKeepServer => "resolved_keep_server",
5322            CommitOutcomeResolution::Superseded => "superseded",
5323            CommitOutcomeResolution::Dismissed => "dismissed",
5324        }
5325    }
5326
5327    fn parse_outcome_status(value: &str) -> Result<CommitOutcomeStatus, String> {
5328        match value {
5329            "applied" => Ok(CommitOutcomeStatus::Applied),
5330            "cached" => Ok(CommitOutcomeStatus::Cached),
5331            "conflict" => Ok(CommitOutcomeStatus::Conflict),
5332            "rejected" => Ok(CommitOutcomeStatus::Rejected),
5333            _ => Err(format!("invalid persisted commit outcome status {value:?}")),
5334        }
5335    }
5336
5337    fn parse_outcome_resolution(value: &str) -> Result<CommitOutcomeResolution, String> {
5338        match value {
5339            "active" => Ok(CommitOutcomeResolution::Active),
5340            "resolved_keep_server" => Ok(CommitOutcomeResolution::ResolvedKeepServer),
5341            "superseded" => Ok(CommitOutcomeResolution::Superseded),
5342            "dismissed" => Ok(CommitOutcomeResolution::Dismissed),
5343            _ => Err(format!(
5344                "invalid persisted commit outcome resolution {value:?}"
5345            )),
5346        }
5347    }
5348
5349    fn persist_commit_outcome(
5350        &self,
5351        client_commit_id: &str,
5352        status: CommitOutcomeStatus,
5353        results: &[CommitOperationOutcome],
5354        operations: Option<&[OutboxOp]>,
5355    ) -> Result<(), String> {
5356        let results_json = serde_json::to_string(results).map_err(|error| error.to_string())?;
5357        let operations_json = operations
5358            .map(|items| {
5359                serde_json::to_string(&items.iter().map(CommitOperation::from).collect::<Vec<_>>())
5360            })
5361            .transpose()
5362            .map_err(|error| error.to_string())?;
5363        self.conn
5364            .execute(
5365                "INSERT INTO _syncular_commit_outcomes (
5366                   client_commit_id, status, recorded_at_ms, results_json,
5367                   operations_json, resolution
5368                 ) VALUES (?1, ?2, ?3, ?4, ?5, 'active')",
5369                rusqlite::params![
5370                    client_commit_id,
5371                    Self::outcome_status_name(status),
5372                    self.clock_now_ms(),
5373                    results_json,
5374                    operations_json
5375                ],
5376            )
5377            .map(|_| ())
5378            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
5379    }
5380
5381    /// §7.2: the journal holds a stored cell only in its canonical shape. A cell
5382    /// the byte-envelope rule refuses cannot be journaled verbatim.
5383    fn stored_cell_is_representable(cell: &Value) -> bool {
5384        cell.is_null()
5385            || cell.is_string()
5386            || cell.is_boolean()
5387            || cell.is_number()
5388            || is_canonical_bytes_envelope(cell)
5389    }
5390
5391    fn stored_row_is_representable(value: &Value) -> bool {
5392        value
5393            .as_object()
5394            .is_some_and(|row| row.values().all(Self::stored_cell_is_representable))
5395    }
5396
5397    fn stored_operation_is_representable(value: &Value) -> bool {
5398        value.get("table").is_some_and(Value::is_string)
5399            && value.get("rowId").is_some_and(Value::is_string)
5400            && value.get("baseVersion").is_none_or(|v| {
5401                v.as_i64()
5402                    .is_some_and(|n| n.unsigned_abs() <= MAX_JS_SAFE_INTEGER)
5403            })
5404            && match value.get("op").and_then(Value::as_str) {
5405                Some("upsert") => {
5406                    value
5407                        .get("values")
5408                        .is_some_and(Self::stored_row_is_representable)
5409                        && value
5410                            .get("insert")
5411                            .is_none_or(|insert| *insert == Value::Bool(true))
5412                }
5413                Some("delete") => value.get("values").is_none() && value.get("insert").is_none(),
5414                _ => false,
5415            }
5416    }
5417
5418    /// §7.2/§7.4.4: a dropped commit keeps its operation envelope in the journal
5419    /// only when the journal reader accepts the serialized operation, which is the
5420    /// rule `outcome_from_row` applies to this same row later.
5421    fn outbox_op_is_journalable(operation: &OutboxOp) -> bool {
5422        serde_json::to_value(CommitOperation::from(operation))
5423            .is_ok_and(|value| Self::stored_operation_is_representable(&value))
5424    }
5425
5426    /// §7.2.1: the one predicate for a replaced commit: a rejection whose
5427    /// every result is `client.commit_replaced` and that names its replacement.
5428    fn is_replaced(outcome: &CommitOutcome) -> bool {
5429        outcome.status == CommitOutcomeStatus::Rejected
5430            && outcome.replacement_client_commit_id.is_some()
5431            && !outcome.results.is_empty()
5432            && outcome.results.iter().all(|result| {
5433                matches!(result, CommitOperationOutcome::Error { rejection }
5434                    if rejection.code == COMMIT_REPLACED_CODE)
5435            })
5436    }
5437
5438    /// §7.2.1: `commitOutcomes` and `commitDelivery` report a replaced
5439    /// commit as `replaced`; every other journal surface reads the rejection.
5440    fn reported_outcome(mut outcome: CommitOutcome) -> CommitOutcome {
5441        if Self::is_replaced(&outcome) {
5442            outcome.status = CommitOutcomeStatus::Replaced;
5443        }
5444        outcome
5445    }
5446
5447    fn outcome_from_row(row: StoredCommitOutcomeRow) -> Result<CommitOutcome, String> {
5448        let StoredCommitOutcomeRow {
5449            sequence,
5450            client_commit_id,
5451            status,
5452            recorded_at_ms,
5453            results_json,
5454            operations_json,
5455            resolution,
5456            resolved_at_ms,
5457            replacement_client_commit_id,
5458        } = row;
5459        if sequence.unsigned_abs() > MAX_JS_SAFE_INTEGER
5460            || recorded_at_ms.unsigned_abs() > MAX_JS_SAFE_INTEGER
5461            || resolved_at_ms.is_some_and(|value| value.unsigned_abs() > MAX_JS_SAFE_INTEGER)
5462        {
5463            return Err("sync.local_corrupt: persisted commit outcome is invalid".to_owned());
5464        }
5465        let invalid = || "sync.local_corrupt: persisted commit outcome is invalid".to_owned();
5466        let stored: Vec<Value> = serde_json::from_str(&results_json).map_err(|_| invalid())?;
5467        for result in &stored {
5468            let nested = match result.get("status").and_then(Value::as_str) {
5469                Some("conflict") => result.get("conflict"),
5470                Some("error") => result.get("rejection"),
5471                _ => None,
5472            };
5473            if nested
5474                .and_then(|record| record.get("operation"))
5475                .is_some_and(|op| !Self::stored_operation_is_representable(op))
5476                || (result.get("status").and_then(Value::as_str) == Some("conflict")
5477                    && nested
5478                        .and_then(|record| record.get("serverRow"))
5479                        .is_some_and(|row| !Self::stored_row_is_representable(row)))
5480            {
5481                return Err(invalid());
5482            }
5483        }
5484        let results: Vec<CommitOperationOutcome> =
5485            serde_json::from_value(Value::Array(stored)).map_err(|_| invalid())?;
5486        let has_conflict = results
5487            .iter()
5488            .any(|result| matches!(result, CommitOperationOutcome::Conflict { .. }));
5489        let has_error = results
5490            .iter()
5491            .any(|result| matches!(result, CommitOperationOutcome::Error { .. }));
5492        let status = Self::parse_outcome_status(&status).map_err(|_| invalid())?;
5493        let redacted = results.is_empty() && operations_json.is_none();
5494        if match status {
5495            CommitOutcomeStatus::Applied | CommitOutcomeStatus::Cached => has_conflict || has_error,
5496            CommitOutcomeStatus::Replaced => true,
5497            CommitOutcomeStatus::Conflict => !(has_conflict || redacted),
5498            CommitOutcomeStatus::Rejected => has_conflict || !(has_error || redacted),
5499        } {
5500            return Err(invalid());
5501        }
5502        let operations: Option<Vec<CommitOperation>> = operations_json
5503            .map(|raw| {
5504                let stored: Vec<Value> = serde_json::from_str(&raw).map_err(|_| invalid())?;
5505                if !stored.iter().all(Self::stored_operation_is_representable) {
5506                    return Err(invalid());
5507                }
5508                serde_json::from_value(Value::Array(stored)).map_err(|_| invalid())
5509            })
5510            .transpose()?;
5511        for result in &results {
5512            match result {
5513                CommitOperationOutcome::Conflict { conflict }
5514                    if conflict.server_version.unsigned_abs() > MAX_JS_SAFE_INTEGER =>
5515                {
5516                    return Err("sync.local_corrupt: persisted commit outcome is invalid".to_owned())
5517                }
5518                CommitOperationOutcome::Error { rejection } => {
5519                    if let Some(details) = &rejection.details {
5520                        let encoded = serde_json::to_string(details).map_err(|_| {
5521                            "sync.local_corrupt: persisted commit outcome is invalid".to_owned()
5522                        })?;
5523                        RejectionDetails::parse(&encoded).map_err(|_| {
5524                            "sync.local_corrupt: persisted commit outcome is invalid".to_owned()
5525                        })?;
5526                    }
5527                }
5528                _ => {}
5529            }
5530        }
5531        Ok(CommitOutcome {
5532            sequence,
5533            client_commit_id,
5534            status,
5535            recorded_at_ms,
5536            results,
5537            operations,
5538            retained_rows: None,
5539            resolution: Self::parse_outcome_resolution(&resolution)?,
5540            resolved_at_ms,
5541            replacement_client_commit_id,
5542        })
5543    }
5544
5545    /// Resolve declared unique keys through SQLite, including affinity and NULL semantics.
5546    fn unique_conflicts(
5547        &self,
5548        table: &TableSchema,
5549        values: &Map<String, Value>,
5550        base: bool,
5551    ) -> Result<Vec<RetainedUniqueConflict>, String> {
5552        let source = if base {
5553            base_table(&table.name)
5554        } else {
5555            visible_table(&table.name)
5556        };
5557        let mut conflicts = Vec::new();
5558        for index in table.indexes.iter().filter(|index| index.unique) {
5559            let mut params = vec![json_param_to_sql(
5560                values.get(&table.primary_key).ok_or("sync.local_corrupt")?,
5561            )?];
5562            for name in &index.columns {
5563                let column = table
5564                    .columns
5565                    .iter()
5566                    .find(|column| column.name == *name)
5567                    .ok_or("sync.local_corrupt")?;
5568                let cell = json_to_column_value(column, values.get(name))?;
5569                params.push(owned_sql_value(RowParam::Cell(&cell))?);
5570            }
5571            let sql = format!(
5572                "SELECT * FROM {source} WHERE {} != ? AND {}",
5573                quote_ident(&table.primary_key),
5574                index
5575                    .columns
5576                    .iter()
5577                    .map(|column| format!("{} = ?", quote_ident(column)))
5578                    .collect::<Vec<_>>()
5579                    .join(" AND ")
5580            );
5581            let mut statement = self
5582                .conn
5583                .prepare_cached(&sql)
5584                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5585            let records = statement
5586                .query_map(rusqlite::params_from_iter(params), |record| {
5587                    let values = table
5588                        .columns
5589                        .iter()
5590                        .enumerate()
5591                        .map(|(index, column)| {
5592                            let value = sql_ref_to_json(column, record.get_ref(index)?);
5593                            json_to_column_value(column, Some(&value)).map_err(|message| {
5594                                rusqlite::Error::ToSqlConversionFailure(message.into())
5595                            })
5596                        })
5597                        .collect::<Result<Row, _>>()?;
5598                    Ok((values, record.get::<_, i64>(table.columns.len())?))
5599                })
5600                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5601            for record in records {
5602                let (row, version) =
5603                    record.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5604                let row_id = render_row_id_json(Some(&column_value_to_json(&row[table.pk_index])))?;
5605                conflicts.push(RetainedUniqueConflict {
5606                    index: index.name.clone(),
5607                    columns: index.columns.clone(),
5608                    row_id,
5609                    server_row: table
5610                        .columns
5611                        .iter()
5612                        .zip(&row)
5613                        .map(|(column, value)| (column.name.clone(), column_value_to_json(value)))
5614                        .collect(),
5615                    server_version: version,
5616                });
5617            }
5618        }
5619        Ok(conflicts)
5620    }
5621
5622    fn attach_retained_rows(&self, mut outcome: CommitOutcome) -> Result<CommitOutcome, String> {
5623        if let Some((commit, initial)) = self
5624            .failed_commits
5625            .iter()
5626            .find(|(commit, _)| commit.client_commit_id == outcome.client_commit_id)
5627        {
5628            let mut rows = Vec::new();
5629            for operation in &commit.ops {
5630                // A table the current schema removed has no rows to retain.
5631                let Some(table) = self.schema.table(&operation.table) else {
5632                    continue;
5633                };
5634                let key =
5635                    serde_json::to_string(&(operation.table.clone(), operation.row_id.clone()))
5636                        .map_err(|_| "sync.local_corrupt".to_owned())?;
5637                let base = self.stored_row(table, &operation.row_id, true)?;
5638                rows.push(RetainedCommitRow {
5639                    table: operation.table.clone(),
5640                    row_id: operation.row_id.clone(),
5641                    unique_conflicts: if operation.upsert {
5642                        self.unique_conflicts(
5643                            table,
5644                            initial
5645                                .get(&key)
5646                                .and_then(Value::as_object)
5647                                .or(operation.values.as_ref())
5648                                .ok_or("sync.local_corrupt")?,
5649                            true,
5650                        )?
5651                    } else {
5652                        Vec::new()
5653                    },
5654                    local_row: if operation.upsert {
5655                        initial
5656                            .get(&key)
5657                            .and_then(Value::as_object)
5658                            .cloned()
5659                            .or_else(|| operation.values.clone())
5660                    } else {
5661                        None
5662                    },
5663                    server_row: base.as_ref().map(|(values, _)| {
5664                        table
5665                            .columns
5666                            .iter()
5667                            .zip(values)
5668                            .map(|(column, value)| {
5669                                (column.name.clone(), column_value_to_json(value))
5670                            })
5671                            .collect()
5672                    }),
5673                    server_version: base.map(|(_, version)| version),
5674                });
5675            }
5676            outcome.retained_rows = Some(rows);
5677        }
5678        Ok(outcome)
5679    }
5680
5681    fn commit_outcome(&self, client_commit_id: &str) -> Result<Option<CommitOutcome>, String> {
5682        let row = self
5683            .conn
5684            .query_row(
5685                "SELECT seq, client_commit_id, status, recorded_at_ms, results_json, operations_json,
5686                        resolution, resolved_at_ms, replacement_client_commit_id
5687                   FROM _syncular_commit_outcomes WHERE client_commit_id = ?1",
5688                rusqlite::params![client_commit_id],
5689                |row| {
5690                    Ok(StoredCommitOutcomeRow {
5691                        sequence: row.get(0)?,
5692                        client_commit_id: row.get(1)?,
5693                        status: row.get(2)?,
5694                        recorded_at_ms: row.get(3)?,
5695                        results_json: row.get(4)?,
5696                        operations_json: row.get(5)?,
5697                        resolution: row.get(6)?,
5698                        resolved_at_ms: row.get(7)?,
5699                        replacement_client_commit_id: row.get(8)?,
5700                    })
5701                },
5702            )
5703            .optional()
5704            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5705        row.map(|row| self.attach_retained_rows(Self::outcome_from_row(row)?))
5706            .transpose()
5707    }
5708
5709    /// Internal host step. The host must run its idle drive before finishing.
5710    #[doc(hidden)]
5711    pub fn prepare_current_base(
5712        &self,
5713        client_commit_id: &str,
5714        sequence: i64,
5715    ) -> Result<CurrentBasePreparation, CurrentBaseProof> {
5716        let outcome = self
5717            .commit_outcome(client_commit_id)
5718            .map_err(|_| CurrentBaseProof::failure(CurrentBaseProofReason::SnapshotFailed))?;
5719        let valid = outcome.as_ref().is_some_and(|outcome| {
5720            outcome.sequence == sequence
5721                && outcome.resolution == CommitOutcomeResolution::Active
5722                && matches!(
5723                    outcome.status,
5724                    CommitOutcomeStatus::Conflict | CommitOutcomeStatus::Rejected
5725                )
5726                && outcome
5727                    .operations
5728                    .as_ref()
5729                    .zip(outcome.retained_rows.as_ref())
5730                    .is_some_and(|(operations, rows)| {
5731                        !rows.is_empty() && operations.len() == rows.len()
5732                    })
5733        });
5734        if !valid {
5735            return Err(CurrentBaseProof::failure(
5736                CurrentBaseProofReason::OutcomeUnavailable,
5737            ));
5738        }
5739        if self.transport_closed() {
5740            return Err(CurrentBaseProof::failure(CurrentBaseProofReason::Offline));
5741        }
5742        Ok(CurrentBasePreparation {
5743            client_commit_id: client_commit_id.to_owned(),
5744            sequence,
5745            replacement: None,
5746            units: load_units(&self.conn)
5747                .map_err(|_| CurrentBaseProof::failure(CurrentBaseProofReason::SnapshotFailed))?,
5748            transport_epoch: self.transport_epoch,
5749            registration_epoch: self.registration_epoch,
5750            security_epoch: self.security_epoch,
5751        })
5752    }
5753
5754    /// Internal host step after the completed post-rejection idle drive.
5755    #[doc(hidden)]
5756    pub fn finish_current_base(
5757        &mut self,
5758        prepared: CurrentBasePreparation,
5759        drive: SyncOutcome,
5760    ) -> CurrentBaseProof {
5761        if self.transport_closed() || self.transport_epoch != prepared.transport_epoch {
5762            return CurrentBaseProof::failure(CurrentBaseProofReason::Offline);
5763        }
5764        if self.registration_epoch != prepared.registration_epoch {
5765            return CurrentBaseProof::failure(CurrentBaseProofReason::MissingCoverage);
5766        }
5767        if self.security_preflight || self.security_epoch != prepared.security_epoch {
5768            return CurrentBaseProof::failure(CurrentBaseProofReason::SyncFailed);
5769        }
5770        let report = match drive {
5771            SyncOutcome::Ok(report) => report,
5772            SyncOutcome::BudgetExhausted(_) => {
5773                return CurrentBaseProof::failure(CurrentBaseProofReason::BudgetExhausted)
5774            }
5775            _ => return CurrentBaseProof::failure(CurrentBaseProofReason::SyncFailed),
5776        };
5777        if report.schema_floor.is_some() {
5778            return CurrentBaseProof::failure(CurrentBaseProofReason::SchemaFloor);
5779        }
5780        if self
5781            .conn
5782            .execute_batch("SAVEPOINT syncular_base_proof")
5783            .is_err()
5784        {
5785            return CurrentBaseProof::failure(CurrentBaseProofReason::SnapshotFailed);
5786        }
5787        let proof = (|| {
5788            let snapshot = snapshot_read_connection(
5789                &self.conn,
5790                Some(&self.schema),
5791                &SnapshotReadRequest {
5792                    units: prepared.units.iter().map(|unit| unit.id.clone()).collect(),
5793                    commit_ids: vec![prepared.client_commit_id.clone()],
5794                    ..Default::default()
5795                },
5796            )
5797            .map_err(|_| CurrentBaseProofReason::SnapshotFailed)?;
5798            let current = self
5799                .commit_outcome(&prepared.client_commit_id)
5800                .map_err(|_| CurrentBaseProofReason::SnapshotFailed)?;
5801            let unavailable = if report.revoked.is_empty() {
5802                CurrentBaseProofReason::OutcomeUnavailable
5803            } else {
5804                CurrentBaseProofReason::Revoked
5805            };
5806            let Some(outcome) = current else {
5807                return Err(unavailable);
5808            };
5809            if !matches!(
5810                snapshot.deliveries.first(),
5811                Some(CommitDelivery::Known { .. })
5812            ) || outcome.sequence != prepared.sequence
5813                || outcome.resolution != CommitOutcomeResolution::Active
5814                || !matches!(
5815                    outcome.status,
5816                    CommitOutcomeStatus::Conflict | CommitOutcomeStatus::Rejected
5817                )
5818            {
5819                return Err(unavailable);
5820            }
5821            let (Some(operations), Some(rows)) = (outcome.operations, outcome.retained_rows) else {
5822                return Err(unavailable);
5823            };
5824            if rows.is_empty() || operations.len() != rows.len() {
5825                return Err(unavailable);
5826            }
5827            let after =
5828                load_units(&self.conn).map_err(|_| CurrentBaseProofReason::SnapshotFailed)?;
5829            let complete: HashSet<&str> = snapshot
5830                .units
5831                .iter()
5832                .filter_map(|unit| match unit {
5833                    UnitCatchup::Known {
5834                        id,
5835                        bootstrap_complete: true,
5836                        ..
5837                    } => Some(id.as_str()),
5838                    _ => None,
5839                })
5840                .collect();
5841            // A unit id names one scope map (§4.1), so the same id before and
5842            // after the drive is the same registration.
5843            let candidates: Vec<&UnitRecord> = after
5844                .iter()
5845                .filter(|unit| {
5846                    complete.contains(unit.id.as_str())
5847                        && prepared.units.iter().any(|before| before.id == unit.id)
5848                })
5849                .collect();
5850            let covered = |table_name: &str, row: &Map<String, Value>| {
5851                let Some(table) = self.schema.table(table_name) else {
5852                    return false;
5853                };
5854                candidates.iter().any(|unit| {
5855                    covers(table, &unit.scopes)
5856                        && pair_scopes(&unit.scopes, table_name, unit.echo.as_deref()).is_some_and(
5857                            |scopes| {
5858                                scopes.iter().all(|(variable, allowed)| {
5859                                    table
5860                                        .scope_column(variable)
5861                                        .and_then(|column| match row.get(column) {
5862                                            Some(Value::String(value)) => Some(value.clone()),
5863                                            Some(Value::Bool(value)) => Some(value.to_string()),
5864                                            Some(Value::Number(value)) => {
5865                                                value.as_f64().map(|number| {
5866                                                    ryu_js::Buffer::new()
5867                                                        .format_finite(number)
5868                                                        .to_owned()
5869                                                })
5870                                            }
5871                                            _ => None,
5872                                        })
5873                                        .is_some_and(|value| {
5874                                            !value.is_empty() && allowed.contains(&value)
5875                                        })
5876                                })
5877                            },
5878                        )
5879                })
5880            };
5881            for row in &rows {
5882                let Some(base) = row.server_row.as_ref().or(row.local_row.as_ref()) else {
5883                    return Err(if report.revoked.is_empty() {
5884                        CurrentBaseProofReason::MissingCoverage
5885                    } else {
5886                        CurrentBaseProofReason::Revoked
5887                    });
5888                };
5889                if !covered(&row.table, base)
5890                    || row
5891                        .unique_conflicts
5892                        .iter()
5893                        .any(|conflict| !covered(&row.table, &conflict.server_row))
5894                {
5895                    return Err(if report.revoked.is_empty() {
5896                        CurrentBaseProofReason::MissingCoverage
5897                    } else {
5898                        CurrentBaseProofReason::Revoked
5899                    });
5900                }
5901            }
5902            Ok(rows)
5903        })();
5904        if self
5905            .conn
5906            .execute_batch("RELEASE syncular_base_proof")
5907            .is_err()
5908        {
5909            return CurrentBaseProof::failure(CurrentBaseProofReason::SnapshotFailed);
5910        }
5911        match proof {
5912            Ok(rows) => CurrentBaseProof {
5913                proven: true,
5914                rows: Some(rows),
5915                reason: None,
5916            },
5917            Err(reason) => CurrentBaseProof::failure(reason),
5918        }
5919    }
5920
5921    pub fn prove_current_base(
5922        &mut self,
5923        transport: &mut dyn Transport,
5924        client_commit_id: &str,
5925        sequence: i64,
5926        max_rounds: Option<u32>,
5927    ) -> CurrentBaseProof {
5928        let prepared = match self.prepare_current_base(client_commit_id, sequence) {
5929            Ok(prepared) => prepared,
5930            Err(proof) => return proof,
5931        };
5932        let drive = self.sync_until_idle(transport, max_rounds);
5933        self.finish_current_base(prepared, drive)
5934    }
5935
5936    pub fn commit_outcomes(&self, query: CommitOutcomeQuery) -> Result<Vec<CommitOutcome>, String> {
5937        if query.limit == Some(0) {
5938            return Err("sync.invalid_request: commit outcome limit must be positive".to_owned());
5939        }
5940        let mut sql = String::from(
5941            "SELECT seq, client_commit_id, status, recorded_at_ms, results_json, operations_json,
5942                    resolution, resolved_at_ms, replacement_client_commit_id
5943               FROM _syncular_commit_outcomes",
5944        );
5945        if query.active_only {
5946            sql.push_str(" WHERE resolution = 'active' AND status IN ('conflict', 'rejected')");
5947        }
5948        sql.push_str(" ORDER BY seq DESC");
5949        if let Some(limit) = query.limit {
5950            sql.push_str(&format!(" LIMIT {limit}"));
5951        }
5952        let mut stmt = self
5953            .conn
5954            .prepare(&sql)
5955            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5956        let rows = stmt
5957            .query_map([], |row| {
5958                Ok(StoredCommitOutcomeRow {
5959                    sequence: row.get(0)?,
5960                    client_commit_id: row.get(1)?,
5961                    status: row.get(2)?,
5962                    recorded_at_ms: row.get(3)?,
5963                    results_json: row.get(4)?,
5964                    operations_json: row.get(5)?,
5965                    resolution: row.get(6)?,
5966                    resolved_at_ms: row.get(7)?,
5967                    replacement_client_commit_id: row.get(8)?,
5968                })
5969            })
5970            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5971        let mut outcomes = Vec::new();
5972        for row in rows {
5973            let row = row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5974            outcomes.push(Self::reported_outcome(
5975                self.attach_retained_rows(Self::outcome_from_row(row)?)?,
5976            ));
5977        }
5978        Ok(outcomes)
5979    }
5980
5981    fn prune_commit_outcomes(&self) -> Result<(), String> {
5982        #[cfg(test)]
5983        self.outcome_prune_count
5984            .set(self.outcome_prune_count.get() + 1);
5985        let max_entries = self.limits.outcome_retention_max_entries.unwrap_or(1_000);
5986        let count = self
5987            .conn
5988            .query_row(
5989                "SELECT COUNT(*) FROM _syncular_commit_outcomes",
5990                [],
5991                |row| row.get::<_, i64>(0),
5992            )
5993            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
5994            as usize;
5995        let excess = count.saturating_sub(max_entries);
5996        if excess == 0 {
5997            return Ok(());
5998        }
5999        let mut stmt = self
6000            .conn
6001            .prepare(
6002                "SELECT seq FROM _syncular_commit_outcomes
6003                  WHERE status IN ('applied', 'cached') OR resolution != 'active'
6004                  ORDER BY seq ASC LIMIT ?1",
6005            )
6006            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6007        let rows = stmt
6008            .query_map(rusqlite::params![excess as i64], |row| row.get::<_, i64>(0))
6009            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6010        let sequences = rows
6011            .collect::<Result<Vec<_>, _>>()
6012            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6013        drop(stmt);
6014        for sequence in sequences {
6015            self.conn
6016                .execute(
6017                    "DELETE FROM _syncular_commit_outcomes WHERE seq = ?1",
6018                    rusqlite::params![sequence],
6019                )
6020                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6021        }
6022        Ok(())
6023    }
6024
6025    // -- units (§4.1) ------------------------------------------------------------
6026
6027    /// Every registered unit in registration order (§4.1).
6028    pub fn units(&self) -> Result<Vec<UnitRecord>, String> {
6029        self.stored(load_units(&self.conn))
6030    }
6031
6032    pub fn unit(&self, id: &str) -> Result<Option<UnitRecord>, String> {
6033        self.stored(get_unit(&self.conn, id))
6034    }
6035
6036    /// Register one unit (§4.1) and return its id.
6037    pub fn subscribe(&mut self, scopes: UnitScopes) -> Result<String, String> {
6038        Ok(self.subscribe_many(vec![scopes])?.remove(0))
6039    }
6040
6041    /// Register several units in one local transaction and return their ids:
6042    /// one commit for all of them (on OPFS a commit costs milliseconds, so a
6043    /// cold start with hundreds of units pays it once). An error rolls back
6044    /// every registration of the call. Registering an active unit again
6045    /// changes nothing; a revoked unit re-arms (§3.3). A call that registers or
6046    /// re-arms a unit raises sync-needed with an interactive intent.
6047    pub fn subscribe_many(&mut self, units: Vec<UnitScopes>) -> Result<Vec<String>, String> {
6048        let rollback = self.capture();
6049        self.begin_observation("syncular_subscribe")?;
6050        let mut changed = false;
6051        let registered = (|| {
6052            let mut ids = Vec::with_capacity(units.len());
6053            let mut batch = ChangeAccumulator::default();
6054            for scopes in units {
6055                let (id, held) = self.hold_unit(scopes, true)?;
6056                if held {
6057                    if let Some(unit) = self.stored(get_unit(&self.conn, &id))? {
6058                        self.record_unit_windows(&mut batch, &unit)?;
6059                    }
6060                }
6061                changed |= held;
6062                ids.push(id);
6063            }
6064            self.finish_observation("syncular_subscribe", batch)?;
6065            Ok(ids)
6066        })();
6067        let ids = match registered {
6068            Ok(ids) => ids,
6069            Err(error) => {
6070                self.rollback_observation("syncular_subscribe");
6071                self.restore(rollback);
6072                return Err(error);
6073            }
6074        };
6075        if changed {
6076            self.registration_epoch = self.registration_epoch.wrapping_add(1);
6077            self.set_sync_needed(true, true);
6078        }
6079        Ok(ids)
6080    }
6081
6082    /// Release the explicit reference to a unit. The unit leaves the
6083    /// registration list when no window base holds it (§4.1); its rows stay.
6084    pub fn unsubscribe(&mut self, id: &str) -> Result<(), String> {
6085        let Some(unit) = self.stored(get_unit(&self.conn, id))? else {
6086            return Ok(());
6087        };
6088        if !unit.explicit {
6089            return Ok(());
6090        }
6091        if !self.stored(window_refs(&self.conn, id))?.is_empty() {
6092            return self.stored(save_unit(
6093                &self.conn,
6094                &UnitRecord {
6095                    explicit: false,
6096                    ..unit
6097                },
6098            ));
6099        }
6100        let rollback = self.capture();
6101        self.begin_observation("syncular_unsubscribe")?;
6102        let removed = (|| {
6103            self.conn
6104                .execute("DELETE FROM _syncular_units WHERE id = ?1", [id])
6105                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6106            let mut batch = ChangeAccumulator::default();
6107            self.record_unit_windows(&mut batch, &unit)?;
6108            self.finish_observation("syncular_unsubscribe", batch)
6109        })();
6110        if let Err(error) = removed {
6111            self.rollback_observation("syncular_unsubscribe");
6112            self.restore(rollback);
6113            return Err(error);
6114        }
6115        self.registration_epoch = self.registration_epoch.wrapping_add(1);
6116        if unit.status == UnitStatus::Active {
6117            self.set_sync_needed(true, true);
6118        }
6119        Ok(())
6120    }
6121
6122    /// Take one reference on a unit (§4.1): validate the scope map, register a
6123    /// new unit catching up with cursor `-1`, re-arm a revoked one (§3.3).
6124    /// Returns the id and whether the registration list changed.
6125    fn hold_unit(&mut self, scopes: UnitScopes, explicit: bool) -> Result<(String, bool), String> {
6126        if scopes.is_empty()
6127            || scopes.values().any(|value| value == "*")
6128            || !self
6129                .schema
6130                .tables
6131                .iter()
6132                .any(|table| covers(table, &scopes))
6133        {
6134            return Err("sync.invalid_subscription: a unit names one non-wildcard value per variable and covers a table".to_owned());
6135        }
6136        let id = ssp2::registration::unit_id(&scope_pairs(&scopes));
6137        let existing = self.stored(get_unit(&self.conn, &id))?;
6138        if let Some(existing) = existing
6139            .as_ref()
6140            .filter(|unit| unit.status != UnitStatus::Revoked)
6141        {
6142            if explicit && !existing.explicit {
6143                self.stored(save_unit(
6144                    &self.conn,
6145                    &UnitRecord {
6146                        explicit,
6147                        ..existing.clone()
6148                    },
6149                ))?;
6150            }
6151            return Ok((id, false));
6152        }
6153        self.delete_pending_evict(&id)?;
6154        self.stored(save_unit(
6155            &self.conn,
6156            &UnitRecord {
6157                id: id.clone(),
6158                scopes,
6159                explicit: explicit || existing.is_some_and(|unit| unit.explicit),
6160                status: UnitStatus::Active,
6161                reason_code: None,
6162                cursor: Some(-1),
6163                bootstrap_state: None,
6164                seeded: Vec::new(),
6165                echo: None,
6166                restriction: None,
6167            },
6168        ))?;
6169        Ok((id, true))
6170    }
6171
6172    // -- windows (§4.8) -----------------------------------------------------------
6173
6174    /// §4.8: set the windowed-in values of a base, one unit per value. Added
6175    /// values take a reference on their unit (a new unit bootstraps on the
6176    /// next sync); removed values release theirs, and a unit no reference
6177    /// holds leaves the registration list fused with its first eviction chunk
6178    /// (E1–E4). Idempotent; re-entry cancels a deferred eviction.
6179    pub fn set_window(
6180        &mut self,
6181        base: &WindowBase,
6182        units: &[String],
6183    ) -> Result<CommandEffects, String> {
6184        let base_key = window_base_key(base);
6185        let live = self.load_window_units(&base_key)?;
6186        let mut changed = false;
6187        // §7.8: the added values register in one transaction. §3.3: a held
6188        // value whose unit is revoked re-arms once per open core.
6189        let mut added: Vec<&String> = Vec::new();
6190        for value in units {
6191            let held = live.iter().find(|(held, _)| held == value);
6192            let rearm = match held {
6193                None => true,
6194                Some((_, id)) => {
6195                    !self.window_armed.contains(id)
6196                        && self
6197                            .stored(get_unit(&self.conn, id))?
6198                            .is_some_and(|unit| unit.status == UnitStatus::Revoked)
6199                }
6200            };
6201            if rearm {
6202                added.push(value);
6203            }
6204        }
6205        if !added.is_empty() {
6206            let rollback = self.capture();
6207            self.begin_observation("syncular_window")?;
6208            let widened = (|| {
6209                let mut batch = ChangeAccumulator::default();
6210                for value in &added {
6211                    let (id, registered) =
6212                        self.hold_unit(window_unit_scopes(base, value), false)?;
6213                    self.sync_needed |= registered;
6214                    if registered {
6215                        self.window_armed.insert(id.clone());
6216                    }
6217                    self.conn
6218                        .execute(
6219                            "INSERT OR REPLACE INTO _syncular_windows(base, unit, sub_id) VALUES (?1, ?2, ?3)",
6220                            rusqlite::params![base_key, value, id],
6221                        )
6222                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6223                    batch.window(&base_key, value);
6224                    // A registered or re-armed unit is a transition for every
6225                    // window value that references it.
6226                    if registered {
6227                        if let Some(unit) = self.stored(get_unit(&self.conn, &id))? {
6228                            self.record_unit_windows(&mut batch, &unit)?;
6229                        }
6230                    }
6231                }
6232                batch.status = true;
6233                self.finish_observation("syncular_window", batch)
6234            })();
6235            if let Err(error) = widened {
6236                self.rollback_observation("syncular_window");
6237                self.restore(rollback);
6238                return Err(error);
6239            }
6240            changed = true;
6241            self.registration_epoch = self.registration_epoch.wrapping_add(1);
6242        }
6243        for (value, id) in live {
6244            if units.contains(&value) {
6245                continue;
6246            }
6247            self.rebuild_overlay_if_dirty()?;
6248            let rollback = self.capture();
6249            self.begin_observation("syncular_window")?;
6250            let remaining = self.release_window_unit(&base_key, &value, &id);
6251            let remaining = match remaining {
6252                Ok(remaining) => remaining,
6253                Err(error) => {
6254                    self.rollback_observation("syncular_window");
6255                    self.restore(rollback);
6256                    return Err(error);
6257                }
6258            };
6259            changed = true;
6260            self.registration_epoch = self.registration_epoch.wrapping_add(1);
6261            if remaining {
6262                self.drain_pending_evictions()?;
6263            }
6264        }
6265        Ok(if changed && !self.transport_closed() {
6266            CommandEffects::interactive()
6267        } else {
6268            CommandEffects::none()
6269        })
6270    }
6271
6272    /// §4.8 completeness oracle: the windowed-in values of a base and those
6273    /// whose unit is not complete. A value is complete once its unit is active
6274    /// and no longer bootstrapping; registration alone is not completeness.
6275    pub fn window_state(&self, base: &WindowBase) -> Result<WindowState, String> {
6276        persisted_window_state(&self.conn, base).map_err(|failure| failure.message)
6277    }
6278
6279    /// Registry rows for a base, ordered by value: (value, unit id).
6280    fn load_window_units(&self, base_key: &str) -> Result<Vec<(String, String)>, String> {
6281        let mut statement = self
6282            .conn
6283            .prepare_cached(
6284                "SELECT unit, sub_id FROM _syncular_windows WHERE base = ?1 ORDER BY unit ASC",
6285            )
6286            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6287        let rows = statement
6288            .query_map([base_key], |row| Ok((row.get(0)?, row.get(1)?)))
6289            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6290        rows.collect::<Result<_, _>>()
6291            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
6292    }
6293
6294    /// §4.8: the window-domain changes of one unit transition, the one path
6295    /// every transition site takes: one per window value that references the
6296    /// unit or, when none does, one for the base derived from its scope map
6297    /// (the variable first in code-unit order and its value; the other
6298    /// variables its fixed scopes). A transition adds no table change.
6299    fn record_unit_windows(
6300        &self,
6301        batch: &mut ChangeAccumulator,
6302        unit: &UnitRecord,
6303    ) -> Result<(), String> {
6304        let refs = self.stored(window_refs(&self.conn, &unit.id))?;
6305        if refs.is_empty() {
6306            let mut pairs = scope_pairs(&unit.scopes).into_iter();
6307            if let Some((variable, value)) = pairs.next() {
6308                let base = WindowBase {
6309                    variable,
6310                    fixed_scopes: pairs.collect(),
6311                };
6312                batch.window(&window_base_key(&base), &value);
6313            }
6314        }
6315        for (base_key, value) in refs {
6316            batch.window(&base_key, &value);
6317        }
6318        Ok(())
6319    }
6320
6321    /// §4.8: release a window value's reference inside the caller's
6322    /// observation. When no reference holds the unit, unregister it fused with
6323    /// its first eviction chunk (E3): delete the rows of every covered table
6324    /// matching the persisted echo, except rows pinned by the outbox (E1) or
6325    /// owned by another unit (§3.3), and park the per-table scopes of what
6326    /// remains in the pending-eviction registry. Fails closed without a local
6327    /// scope-column mapping. Returns whether unpinned rows remain.
6328    fn release_window_unit(
6329        &mut self,
6330        base_key: &str,
6331        value: &str,
6332        id: &str,
6333    ) -> Result<bool, String> {
6334        self.conn
6335            .execute(
6336                "DELETE FROM _syncular_windows WHERE base = ?1 AND unit = ?2",
6337                rusqlite::params![base_key, value],
6338            )
6339            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6340        self.window_armed.remove(id);
6341        let mut batch = ChangeAccumulator::default();
6342        batch.window(base_key, value);
6343        batch.status = true;
6344        let unit = self.stored(get_unit(&self.conn, id))?;
6345        let mut remaining = false;
6346        if let Some(unit) = unit.filter(|unit| !unit.explicit) {
6347            if self.stored(window_refs(&self.conn, id))?.is_empty() {
6348                let units = self.stored(load_units(&self.conn))?;
6349                self.conn
6350                    .execute("DELETE FROM _syncular_units WHERE id = ?1", [id])
6351                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6352                self.sync_needed = true;
6353                for table in self.schema.tables.clone() {
6354                    let Some(effective) = unit
6355                        .echo
6356                        .as_deref()
6357                        .filter(|_| covers(&table, &unit.scopes))
6358                        .and_then(|echo| pair_scopes(&unit.scopes, &table.name, Some(echo)))
6359                    else {
6360                        continue;
6361                    };
6362                    let pinned = self.pinned_row_ids(&table.name);
6363                    let owners = unit_owners(&units, &table, id);
6364                    let (more, deferred) =
6365                        self.evict_scope_rows(&table.name, &effective, &owners, &pinned)?;
6366                    remaining |= more;
6367                    if deferred {
6368                        self.save_pending_evict(id, &table.name, &effective)?;
6369                    }
6370                    self.record_scope_map(&mut batch, &table.name, &effective);
6371                }
6372            }
6373        }
6374        self.finish_observation("syncular_window", batch)?;
6375        Ok(remaining)
6376    }
6377
6378    /// §4.8 E1: delete base rows owned by the effective scopes
6379    /// ([`local_scope_predicate`]) EXCEPT pinned primary keys. Returns (more
6380    /// unpinned work, any scoped rows remain). A missing scope-column mapping
6381    /// fails without deleting rows.
6382    fn evict_scope_rows(
6383        &self,
6384        table_name: &str,
6385        effective: &[(String, Vec<String>)],
6386        owners: &[Vec<(String, Vec<String>)>],
6387        pinned: &std::collections::HashSet<String>,
6388    ) -> Result<(bool, bool), String> {
6389        let table = self.schema.table(table_name).ok_or("sync.unknown_table")?;
6390        let Some((scope, mut params)) = local_scope_predicate(table, effective, owners)
6391            .map_err(|()| "sync.scope_revoked".to_owned())?
6392        else {
6393            return Ok((false, false));
6394        };
6395        let scope_params = params.len();
6396        let pk = quote_ident(&table.primary_key);
6397        // Pinned ids are rowId text; the text form matches every key type.
6398        let predicate = if pinned.is_empty() {
6399            scope.clone()
6400        } else {
6401            params.extend(pinned.iter().cloned().map(SqlValue::Text));
6402            let holes = vec!["?"; pinned.len()].join(", ");
6403            format!("{scope} AND CAST({pk} AS TEXT) NOT IN ({holes})")
6404        };
6405        let base = base_table(table_name);
6406        let visible = visible_table(table_name);
6407        let mut ids: Vec<SqlValue> = Vec::new();
6408        for source in [&base, &visible] {
6409            let mut stmt = self
6410                .conn
6411                .prepare_cached(&format!(
6412                    "SELECT {pk} FROM {source} WHERE {predicate} LIMIT 1024"
6413                ))
6414                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6415            ids = stmt
6416                .query_map(rusqlite::params_from_iter(&params), |row| row.get(0))
6417                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
6418                .collect::<Result<_, _>>()
6419                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6420            if !ids.is_empty() {
6421                break;
6422            }
6423        }
6424        if !ids.is_empty() {
6425            for id in &ids {
6426                self.conn
6427                    .execute(
6428                        "DELETE FROM _syncular_acked_rows WHERE tbl=?1 AND id=?2",
6429                        rusqlite::params![table_name, id],
6430                    )
6431                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6432            }
6433            let holes = vec!["?"; ids.len()].join(", ");
6434            for source in [&base, &visible] {
6435                self.conn
6436                    .execute(
6437                        &format!("DELETE FROM {source} WHERE {pk} IN ({holes})"),
6438                        rusqlite::params_from_iter(&ids),
6439                    )
6440                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6441            }
6442        }
6443        let mut remaining = false;
6444        let mut deferred = false;
6445        for source in [&base, &visible] {
6446            remaining |= self
6447                .conn
6448                .query_row(
6449                    &format!("SELECT EXISTS(SELECT 1 FROM {source} WHERE {predicate})"),
6450                    rusqlite::params_from_iter(&params),
6451                    |row| row.get::<_, bool>(0),
6452                )
6453                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6454            deferred |= self
6455                .conn
6456                .query_row(
6457                    &format!("SELECT EXISTS(SELECT 1 FROM {source} WHERE {scope})"),
6458                    rusqlite::params_from_iter(&params[..scope_params]),
6459                    |row| row.get::<_, bool>(0),
6460                )
6461                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6462        }
6463        Ok((remaining, deferred))
6464    }
6465
6466    /// §4.8 E1: continue deferred evictions after the outbox drains or between
6467    /// chunks, retaining outbox pins and their durable marker. A unit that
6468    /// re-entered the window has no pending entry left.
6469    fn drain_pending_evictions(&mut self) -> Result<(), String> {
6470        let pending = self.load_pending_evictions()?;
6471        if pending.is_empty() {
6472            return Ok(());
6473        }
6474        self.rebuild_overlay_if_dirty()?;
6475        for (unit_id, table_name, effective) in pending {
6476            let Some(table) = self.schema.table(&table_name).cloned() else {
6477                self.delete_pending_evict_table(&unit_id, &table_name)?;
6478                continue;
6479            };
6480            loop {
6481                std::thread::yield_now();
6482                self.begin_observation("syncular_evict")?;
6483                let chunk = (|| {
6484                    let pinned = self.pinned_row_ids(&table_name);
6485                    let owners =
6486                        unit_owners(&self.stored(load_units(&self.conn))?, &table, &unit_id);
6487                    let (remaining, deferred) =
6488                        self.evict_scope_rows(&table_name, &effective, &owners, &pinned)?;
6489                    if !deferred {
6490                        self.delete_pending_evict_table(&unit_id, &table_name)?;
6491                    }
6492                    let mut batch = ChangeAccumulator::default();
6493                    self.record_scope_map(&mut batch, &table_name, &effective);
6494                    self.finish_observation("syncular_evict", batch)?;
6495                    Ok(remaining)
6496                })();
6497                match chunk {
6498                    Ok(true) => {}
6499                    Ok(false) => break,
6500                    Err(error) => {
6501                        self.rollback_observation("syncular_evict");
6502                        return Err(error);
6503                    }
6504                }
6505            }
6506        }
6507        Ok(())
6508    }
6509
6510    /// §4.8 E1: primary keys of `table` referenced by a pending outbox
6511    /// commit — rows that MUST NOT be evicted until the commit drains.
6512    fn pinned_row_ids(&self, table: &str) -> std::collections::HashSet<String> {
6513        let mut pinned = std::collections::HashSet::new();
6514        for commit in self
6515            .outbox
6516            .iter()
6517            .map(|commit| &**commit)
6518            .chain(self.failed_commits.iter().map(|(commit, _)| commit))
6519        {
6520            for op in &commit.ops {
6521                if op.table == table {
6522                    pinned.insert(op.row_id.clone());
6523                }
6524            }
6525        }
6526        pinned
6527    }
6528
6529    fn save_pending_evict(
6530        &self,
6531        unit_id: &str,
6532        table: &str,
6533        effective: &[(String, Vec<String>)],
6534    ) -> Result<(), String> {
6535        self.conn.execute(
6536            "INSERT OR REPLACE INTO _syncular_pending_evictions(unit_id, tbl, effective_scopes) VALUES (?1, ?2, ?3)",
6537            rusqlite::params![unit_id, table, scope_map_to_json(effective).to_string()],
6538        ).map(|_| ()).map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
6539    }
6540
6541    /// Re-entry cancels every pending eviction of the unit.
6542    fn delete_pending_evict(&self, unit_id: &str) -> Result<(), String> {
6543        self.conn
6544            .execute(
6545                "DELETE FROM _syncular_pending_evictions WHERE unit_id = ?1",
6546                [unit_id],
6547            )
6548            .map(|_| ())
6549            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
6550    }
6551
6552    fn delete_pending_evict_table(&self, unit_id: &str, table: &str) -> Result<(), String> {
6553        self.conn
6554            .execute(
6555                "DELETE FROM _syncular_pending_evictions WHERE unit_id = ?1 AND tbl = ?2",
6556                [unit_id, table],
6557            )
6558            .map(|_| ())
6559            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
6560    }
6561
6562    fn load_pending_evictions(&self) -> Result<Vec<PendingEvict>, String> {
6563        let mut stmt = self
6564            .conn
6565            .prepare("SELECT unit_id, tbl, effective_scopes FROM _syncular_pending_evictions")
6566            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6567        let rows = stmt
6568            .query_map([], |row| {
6569                Ok((
6570                    row.get::<_, String>(0)?,
6571                    row.get::<_, String>(1)?,
6572                    row.get::<_, String>(2)?,
6573                ))
6574            })
6575            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6576        rows.map(|row| {
6577            let (unit_id, table, json) =
6578                row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6579            let value: Value = serde_json::from_str(&json)
6580                .map_err(|_| "sync.local_corrupt: invalid pending eviction scopes".to_owned())?;
6581            let effective = json_to_scope_map(&value)
6582                .map_err(|_| "sync.local_corrupt: invalid pending eviction scopes".to_owned())?;
6583            Ok((unit_id, table, effective))
6584        })
6585        .collect()
6586    }
6587
6588    /// Select failed-intent retention; reload durable retained aggregates.
6589    pub fn set_retain_failed_commits(&mut self, enabled: bool) -> Result<(), String> {
6590        self.retain_failed_commits = enabled;
6591        for (commit, _) in self.failed_commits.iter() {
6592            for operation in &commit.ops {
6593                self.overlay_dirty.table(&operation.table);
6594            }
6595        }
6596        self.failed_commits = self.load_failed_commits()?.into();
6597        for (commit, _) in self.failed_commits.iter() {
6598            for operation in &commit.ops {
6599                self.overlay_dirty.table(&operation.table);
6600            }
6601        }
6602        Ok(())
6603    }
6604
6605    fn load_failed_commits(&self) -> Result<Vec<FailedCommit>, String> {
6606        let mut statement = self.conn.prepare("SELECT client_commit_id, operations_json, initial_json FROM _syncular_failed_commits ORDER BY seq")
6607            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6608        let rows = statement
6609            .query_map([], |row| {
6610                Ok((
6611                    row.get::<_, String>(0)?,
6612                    row.get::<_, String>(1)?,
6613                    row.get::<_, String>(2)?,
6614                ))
6615            })
6616            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6617        rows.map(|row| {
6618            let (id, operations, initial) =
6619                row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6620            let operations: Vec<CommitOperation> =
6621                serde_json::from_str(&operations).map_err(|_| "sync.local_corrupt".to_owned())?;
6622            let initial =
6623                serde_json::from_str(&initial).map_err(|_| "sync.local_corrupt".to_owned())?;
6624            Ok((
6625                OutboxCommit {
6626                    client_commit_id: id,
6627                    ops: operations
6628                        .into_iter()
6629                        .map(|op| OutboxOp {
6630                            upsert: op.op == "upsert",
6631                            table: op.table,
6632                            row_id: op.row_id,
6633                            base_version: op.base_version,
6634                            values: op.values,
6635                            insert: op.insert,
6636                        })
6637                        .collect(),
6638                },
6639                initial,
6640            ))
6641        })
6642        .collect()
6643    }
6644
6645    fn retain_failed_commit(&mut self, id: &str, operations: &[OutboxOp]) -> Result<(), String> {
6646        let mut initial = Map::new();
6647        for operation in operations {
6648            // A table the current schema removed has no rows to retain.
6649            let Some(table) = self.schema.table(&operation.table) else {
6650                continue;
6651            };
6652            let initial_row = match self.stored_row(table, &operation.row_id, true)? {
6653                Some(row) => Some(row),
6654                None => self.visible_row(table, &operation.row_id)?,
6655            };
6656            if let Some((values, _)) = initial_row {
6657                let mut intended: Map<String, Value> = table
6658                    .columns
6659                    .iter()
6660                    .zip(values.iter())
6661                    .map(|(column, value)| (column.name.clone(), column_value_to_json(value)))
6662                    .collect();
6663                if let Some(patch) = &operation.values {
6664                    intended.extend(patch.clone());
6665                }
6666                initial.insert(
6667                    serde_json::to_string(&(operation.table.clone(), operation.row_id.clone()))
6668                        .map_err(|_| "sync.local_corrupt".to_owned())?,
6669                    Value::Object(intended),
6670                );
6671            }
6672        }
6673        self.conn.execute("INSERT INTO _syncular_failed_commits(client_commit_id, operations_json, initial_json) VALUES (?1, ?2, ?3)", rusqlite::params![id,
6674            serde_json::to_string(&operations.iter().map(CommitOperation::from).collect::<Vec<_>>()).map_err(|_| "sync.local_corrupt".to_owned())?,
6675            serde_json::to_string(&initial).map_err(|_| "sync.local_corrupt".to_owned())?])
6676            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6677        self.failed_commits.push((
6678            OutboxCommit {
6679                client_commit_id: id.to_owned(),
6680                ops: operations.to_vec(),
6681            },
6682            initial,
6683        ));
6684        Ok(())
6685    }
6686
6687    fn drop_failed_commits(
6688        &mut self,
6689        matches: impl Fn(&str, &Map<String, Value>) -> bool,
6690    ) -> Result<Vec<OutboxCommit>, String> {
6691        let mut doomed = self.drop_acknowledged_rows(&matches)?;
6692        for (commit, initial) in self.failed_commits.iter() {
6693            for operation in &commit.ops {
6694                let key =
6695                    serde_json::to_string(&(operation.table.clone(), operation.row_id.clone()))
6696                        .map_err(|_| "sync.local_corrupt".to_owned())?;
6697                if initial
6698                    .get(&key)
6699                    .and_then(Value::as_object)
6700                    .is_some_and(|values| matches(&operation.table, values))
6701                {
6702                    doomed.push(commit.clone());
6703                    break;
6704                }
6705            }
6706        }
6707        for commit in &doomed {
6708            self.conn
6709                .execute(
6710                    "DELETE FROM _syncular_failed_commits WHERE client_commit_id = ?1",
6711                    rusqlite::params![commit.client_commit_id],
6712                )
6713                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6714        }
6715        for commit in &doomed {
6716            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))?;
6717        }
6718        self.conflicts.retain(|record| {
6719            !doomed
6720                .iter()
6721                .any(|commit| commit.client_commit_id == record.client_commit_id)
6722        });
6723        self.rejections.retain(|record| {
6724            !doomed
6725                .iter()
6726                .any(|commit| commit.client_commit_id == record.client_commit_id)
6727        });
6728        self.failed_commits.retain(|(commit, _)| {
6729            !doomed
6730                .iter()
6731                .any(|dropped| dropped.client_commit_id == commit.client_commit_id)
6732        });
6733        for commit in &doomed {
6734            for operation in &commit.ops {
6735                self.overlay_dirty.table(&operation.table);
6736            }
6737        }
6738        Ok(doomed)
6739    }
6740
6741    /// Record one commit of local mutations. The returned commit ID is the
6742    /// §2.3 idempotency key. Failures are structured so callers read
6743    /// `code`/`message`/`details` instead of parsing a string prefix.
6744    pub fn mutate(&mut self, mutations: Vec<Mutation>) -> Result<String, ClientError> {
6745        let prior = self.storage_failure.borrow_mut().take();
6746        let outcome = self
6747            .prepare_mutations(mutations)
6748            .and_then(|ops| Ok(self.record_outbox_commit(ops, None)?));
6749        self.finish_authoring(prior, outcome)
6750    }
6751
6752    /// §7.1: validate one commit's mutations into outbox operations.
6753    fn prepare_mutations(&self, mutations: Vec<Mutation>) -> Result<Vec<OutboxOp>, ClientError> {
6754        {
6755            if mutations.is_empty() {
6756                return Err(
6757                    "sync.invalid_request: a commit must contain at least one operation (§6.1)"
6758                        .to_owned()
6759                        .into(),
6760                );
6761            }
6762            let mut ops = Vec::with_capacity(mutations.len());
6763            // §7.1: a patch reads the row as the commit's earlier operations
6764            // leave it: the values an earlier upsert wrote, or None after an
6765            // earlier delete. A patch changes neither presence nor a scope
6766            // column, so it records nothing.
6767            let mut staged: HashMap<(String, String), Option<Map<String, Value>>> = HashMap::new();
6768            for mutation in mutations {
6769                match mutation {
6770                    Mutation::Patch {
6771                        table,
6772                        values,
6773                        base_version,
6774                    } => {
6775                        let schema_table = self
6776                            .schema
6777                            .table(&table)
6778                            .ok_or_else(|| "sync.unknown_table".to_owned())?;
6779                        let values = normalize_values_casing(schema_table, values)?;
6780                        let row_id = render_row_id_json(values.get(&schema_table.primary_key))?;
6781                        let base = staged.get(&(table.clone(), row_id.clone()));
6782                        ops.push(self.prepare_patch(
6783                            &table,
6784                            &row_id,
6785                            values,
6786                            base_version,
6787                            base,
6788                        )?);
6789                    }
6790                    Mutation::Upsert {
6791                        table,
6792                        values,
6793                        base_version,
6794                    } => {
6795                        let schema_table = self.schema.table(&table).ok_or_else(|| {
6796                            format!("sync.unknown_table: unknown table {table:?}")
6797                        })?;
6798                        // §5: value keys are accepted in snake_case AND the
6799                        // generated row types' camelCase; normalize to SQL truth
6800                        // before the pk lookup / codec see them.
6801                        let values = normalize_values_casing(schema_table, values)?;
6802                        let row_id = render_row_id_json(values.get(&schema_table.primary_key))?;
6803                        // §6.7 `mutate` marks every column present: fill missing
6804                        // nullable columns with NULL before the payload is built.
6805                        let values = full_row_values(schema_table, values)?;
6806                        self.refuse_sealed_row(schema_table, &row_id)?;
6807                        // §5.11: validate the payload encodes with the current
6808                        // codec. A key-selection or unknown-key failure is a
6809                        // durable rejection at the push seam (§10.3), never an
6810                        // author-time error. Full-row `mutate` presents every
6811                        // column, so no stored fallback is needed.
6812                        self.validate_author_encode(schema_table, &row_id, &values)?;
6813                        // §7.1 insert intent: the row is absent from the
6814                        // visible replica at call time, before this batch
6815                        // applies anything.
6816                        let insert = !self.visible_row_exists(schema_table, &row_id)?;
6817                        staged.insert((table.clone(), row_id.clone()), Some(values.clone()));
6818                        ops.push(OutboxOp {
6819                            upsert: true,
6820                            table,
6821                            row_id,
6822                            base_version,
6823                            values: Some(values),
6824                            insert,
6825                        });
6826                    }
6827                    Mutation::Delete {
6828                        table,
6829                        row_id,
6830                        base_version,
6831                    } => {
6832                        let schema_table = self.schema.table(&table).ok_or_else(|| {
6833                            format!("sync.unknown_table: unknown table {table:?}")
6834                        })?;
6835                        self.refuse_sealed_row(schema_table, &row_id)?;
6836                        // §2.4: the server rejects a rowId holding U+0000.
6837                        if row_id.contains('\0') {
6838                            return Err("sync.invalid_request: rowId holds U+0000 (§2.4)"
6839                                .to_owned()
6840                                .into());
6841                        }
6842                        staged.insert((table.clone(), row_id.clone()), None);
6843                        ops.push(OutboxOp {
6844                            upsert: false,
6845                            table,
6846                            row_id,
6847                            base_version,
6848                            values: None,
6849                            insert: false,
6850                        });
6851                    }
6852                }
6853            }
6854            Ok(ops)
6855        }
6856    }
6857
6858    /// Scope the retained `storage_failure` diagnostic to this call so an
6859    /// earlier operation's failure cannot classify a new one, and surface the
6860    /// call's own classified failure with its details. A fresh classified
6861    /// failure replaces the retained diagnostic; otherwise the earlier one is
6862    /// kept for the next sync.
6863    fn finish_authoring<T>(
6864        &self,
6865        prior: Option<QueryReadFailure>,
6866        outcome: Result<T, ClientError>,
6867    ) -> Result<T, ClientError> {
6868        let fresh = self.storage_failure.borrow_mut().take();
6869        *self.storage_failure.borrow_mut() = fresh.clone().or(prior);
6870        outcome.map_err(|error| fresh.map(ClientError::from).unwrap_or(error))
6871    }
6872
6873    /// `decides` names the active outcome this commit replaces (§7.2.2); the
6874    /// outcome records it as its pending decision in the same transaction.
6875    fn record_outbox_commit(
6876        &mut self,
6877        ops: Vec<OutboxOp>,
6878        decides: Option<&str>,
6879    ) -> Result<String, String> {
6880        let commit = OutboxCommit {
6881            client_commit_id: uuid::Uuid::new_v4().to_string(),
6882            ops,
6883        };
6884        self.begin_observation("syncular_mutation")?;
6885        let mut batch = ChangeAccumulator::default();
6886        for op in &commit.ops {
6887            let mut precise = self.record_row_scopes(&mut batch, &op.table, &op.row_id, false);
6888            if let Some(values) = &op.values {
6889                if let Some(table) = self.schema.table(&op.table) {
6890                    for scope in &table.scope_variables {
6891                        if let Some(Value::String(value)) = values.get(&scope.column) {
6892                            batch.scope(&op.table, format!("{}:{value}", scope.prefix));
6893                            precise = true;
6894                        }
6895                    }
6896                }
6897            }
6898            if !precise {
6899                batch.table(&op.table);
6900            }
6901        }
6902        let persisted = self.persist_outbox_insert(&commit).and_then(|()| {
6903            let Some(outcome) = decides else {
6904                return Ok(());
6905            };
6906            batch.outcomes = true;
6907            let updated = self
6908                .conn
6909                .execute(
6910                    "UPDATE _syncular_commit_outcomes SET replacement_client_commit_id = ?1
6911                      WHERE client_commit_id = ?2 AND resolution = 'active'
6912                        AND replacement_client_commit_id IS NULL",
6913                    rusqlite::params![commit.client_commit_id, outcome],
6914                )
6915                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6916            if updated == 1 {
6917                Ok(())
6918            } else {
6919                Err(REPLACEMENT_PENDING.to_owned())
6920            }
6921        });
6922        if let Err(error) = persisted {
6923            self.rollback_observation("syncular_mutation");
6924            return Err(error);
6925        }
6926        // A clean overlay contains the FIFO fold of every previous commit, so
6927        // the new commit applies over it. §7.1: an operation that does not
6928        // apply (a secondary unique collision) fails the whole commit; the
6929        // savepoint rollback removes the outbox entry and every visible write.
6930        // The append undoes itself: a rollback capture would copy the outbox.
6931        let was_dirty = self.overlay_dirty.snapshot();
6932        let id = commit.client_commit_id.clone();
6933        let appended = self.rebuild_overlay_if_dirty().and_then(|()| {
6934            commit
6935                .ops
6936                .iter()
6937                .try_for_each(|op| self.apply_outbox_op(op))?;
6938            self.outbox.push(Arc::new(commit));
6939            batch.status = true;
6940            self.finish_observation("syncular_mutation", batch)
6941                .inspect_err(|_| drop(self.outbox.pop()))
6942        });
6943        if let Err(error) = appended {
6944            self.rollback_observation("syncular_mutation");
6945            self.overlay_dirty.restore(was_dirty);
6946            return Err(error);
6947        }
6948        Ok(id)
6949    }
6950
6951    /// Record one §6.1 sparse upsert: the primary key plus the supplied
6952    /// non-scope columns are present; every other column is absent and stays
6953    /// untouched on the server and in the local overlay. An absent local base
6954    /// refuses the whole batch with sync.row_missing before enqueueing (§7.1).
6955    /// Failures are structured so callers read `code`/`message`/`details`.
6956    pub fn patch(
6957        &mut self,
6958        table: &str,
6959        row_id: &str,
6960        partial: Map<String, Value>,
6961        base_version: Option<i64>,
6962    ) -> Result<String, ClientError> {
6963        let prior = self.storage_failure.borrow_mut().take();
6964        let outcome = self.perform_patch(table, row_id, partial, base_version);
6965        self.finish_authoring(prior, outcome)
6966    }
6967
6968    /// The unscoped patch body. Public authoring entry points scope
6969    /// `storage_failure` around the whole operation, including any pre-read.
6970    fn perform_patch(
6971        &mut self,
6972        table: &str,
6973        row_id: &str,
6974        partial: Map<String, Value>,
6975        base_version: Option<i64>,
6976    ) -> Result<String, ClientError> {
6977        let operation = self.prepare_patch(table, row_id, partial, base_version, None)?;
6978        Ok(self.record_outbox_commit(vec![operation], None)?)
6979    }
6980
6981    /// `staged` is the row as the batch's earlier operations leave it
6982    /// (`Some(None)` after a delete); `None` reads the visible replica.
6983    fn prepare_patch(
6984        &self,
6985        table: &str,
6986        row_id: &str,
6987        partial: Map<String, Value>,
6988        base_version: Option<i64>,
6989        staged: Option<&Option<Map<String, Value>>>,
6990    ) -> Result<OutboxOp, ClientError> {
6991        let schema_table = self
6992            .schema
6993            .table(table)
6994            .ok_or_else(|| format!("sync.unknown_table: unknown table {table:?}"))?;
6995        let partial = normalize_values_casing(schema_table, partial)?;
6996        if let Some(pk) = partial.get(&schema_table.primary_key) {
6997            if render_row_id_json(Some(pk)).ok().as_deref() != Some(row_id) {
6998                return Err(invalid_authoring(
6999                    "patch cannot change the primary key",
7000                    json!({ "table": table }),
7001                ));
7002            }
7003        }
7004        let exists = match staged {
7005            Some(row) => row.is_some(),
7006            None => self.visible_row_exists(schema_table, row_id)?,
7007        };
7008        if !exists {
7009            return Err("sync.row_missing: a sparse patch requires a local row"
7010                .to_owned()
7011                .into());
7012        }
7013        self.refuse_sealed_row(schema_table, row_id)?;
7014        // §3.4 rule 5 / §6.2: scope columns are immutable on update. The
7015        // server accepts a present scope column whose value equals the
7016        // stored row and applies it as a no-op, so a decoded envelope
7017        // round-trips. The local row is the only value the client can prove
7018        // equality against; when the row is absent locally the client cannot
7019        // prove equality against the server's stored row and fails closed.
7020        // A primary key that is also a scope column needs no stored-row
7021        // read: the primary key in a sparse payload is by construction the
7022        // row id being patched (§6.1), so its value is proven equal already.
7023        for scope in &schema_table.scope_variables {
7024            if !partial.contains_key(&scope.column) || scope.column == schema_table.primary_key {
7025                continue;
7026            }
7027            let Some(column) = schema_table
7028                .columns
7029                .iter()
7030                .find(|column| column.name == scope.column)
7031            else {
7032                continue;
7033            };
7034            let stored = match staged {
7035                Some(row) => row.as_ref().and_then(|row| {
7036                    json_to_column_value(column, row.get(&scope.column))
7037                        .ok()
7038                        .map(|value| column_value_to_json(&value))
7039                }),
7040                None => self
7041                    .conn
7042                    .query_row(
7043                        &format!(
7044                            "SELECT {} FROM {} WHERE {}",
7045                            quote_ident(&scope.column),
7046                            visible_table(&schema_table.name),
7047                            row_id_predicate(schema_table)
7048                        ),
7049                        rusqlite::params![row_id],
7050                        |row| Ok(sql_ref_to_json(column, row.get_ref(0)?)),
7051                    )
7052                    .optional()
7053                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?,
7054            };
7055            // Decode the supplied value through the same column-type path the
7056            // rest of the patch encoding uses, so a value that only equals
7057            // the stored one in another number representation still compares
7058            // equal.
7059            let incoming = json_to_column_value(column, partial.get(&scope.column))
7060                .ok()
7061                .map(|value| column_value_to_json(&value));
7062            // A stored blob never equals a patch value, matching the server's
7063            // scope-column comparison (§3.4): bytes are unstorable as scope
7064            // values.
7065            let equal = stored.as_ref().is_some_and(|stored| {
7066                stored.get("$bytes").is_none() && incoming.as_ref() == Some(stored)
7067            });
7068            if !equal {
7069                return Err(invalid_authoring(
7070                    "patch cannot write a scope column (§3.4)",
7071                    json!({ "table": table, "column": scope.column }),
7072                ));
7073            }
7074        }
7075        let mut values = partial;
7076        // Presence-set semantics: a proven-equal scope column is dropped, so
7077        // the patch leaves the stored value untouched (§6.2).
7078        for scope in &schema_table.scope_variables {
7079            values.remove(&scope.column);
7080        }
7081        let pk_value = match schema_table.columns[schema_table.pk_index].ty {
7082            // §2.4: the rowId of an integer key is its canonical decimal form.
7083            ColumnType::Integer => match row_id.parse::<i64>() {
7084                Ok(v)
7085                    if v.to_string() == row_id
7086                        && (-ssp2::primitives::I64_SAFE_MAX..=ssp2::primitives::I64_SAFE_MAX)
7087                            .contains(&v) =>
7088                {
7089                    Value::from(v)
7090                }
7091                _ => {
7092                    return Err(format!(
7093                    "sync.invalid_request: table {table:?}: invalid integer primary key {row_id:?}"
7094                )
7095                    .into())
7096                }
7097            },
7098            ColumnType::Boolean => match row_id {
7099                "true" => Value::Bool(true),
7100                "false" => Value::Bool(false),
7101                _ => {
7102                    return Err(format!(
7103                    "sync.invalid_request: table {table:?}: invalid boolean primary key {row_id:?}"
7104                )
7105                    .into())
7106                }
7107            },
7108            _ => Value::from(row_id.to_owned()),
7109        };
7110        values.insert(schema_table.primary_key.clone(), pk_value);
7111        // §6.1: a patch cannot null a non-nullable column.
7112        if let Some(column) = schema_table
7113            .columns
7114            .iter()
7115            .find(|column| !column.nullable && values.get(&column.name) == Some(&Value::Null))
7116        {
7117            return Err(invalid_authoring(
7118                "a non-nullable column is null (§6.1)",
7119                json!({ "table": table, "column": column.name }),
7120            ));
7121        }
7122        // §5.11: structural validation only; an absent key-id selector is
7123        // resolved at the push seam from the stored local row, and a
7124        // key-selection or unknown-key failure becomes a durable
7125        // `client.encrypt_failed` rejection there (§10.3), never an
7126        // author-time error.
7127        self.validate_author_encode(schema_table, row_id, &values)?;
7128        Ok(OutboxOp {
7129            upsert: true,
7130            table: table.to_owned(),
7131            row_id: row_id.to_owned(),
7132            base_version,
7133            values: Some(values),
7134            insert: false,
7135        })
7136    }
7137
7138    /// §5.11 key-id fallback: the stored local row's selector value as a
7139    /// positional row (only the selector slot filled). Returns None when no
7140    /// selector is configured, the row is locally absent, or the stored
7141    /// value is not a usable key id. A failed storage read is an error.
7142    fn stored_key_fallback(
7143        &self,
7144        table: &TableSchema,
7145        row_id: &str,
7146    ) -> Result<Option<Row>, String> {
7147        let Some(selector) = self.encryption.key_id_columns.get(&table.name) else {
7148            return Ok(None);
7149        };
7150        let Some(index) = table
7151            .columns
7152            .iter()
7153            .position(|column| &column.name == selector)
7154        else {
7155            return Ok(None);
7156        };
7157        let sql = format!(
7158            "SELECT {} FROM {} WHERE {}",
7159            quote_ident(selector),
7160            visible_table(&table.name),
7161            row_id_predicate(table)
7162        );
7163        let key = self
7164            .conn
7165            .query_row(&sql, rusqlite::params![row_id], |row| {
7166                row.get::<_, Option<String>>(0)
7167            })
7168            .optional()
7169            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
7170            .flatten()
7171            .filter(|key| !key.is_empty());
7172        let Some(key) = key else {
7173            return Ok(None);
7174        };
7175        let mut fallback: Row = vec![None; table.columns.len()];
7176        fallback[index] = Some(ColumnValue::String(key));
7177        Ok(Some(fallback))
7178    }
7179
7180    /// §5.11/§10.3 author-time encode check: a structural failure (a
7181    /// non-nullable NULL, a value the codec rejects) is an author-time
7182    /// error; a key-selection or unknown-key failure is deferred to the push
7183    /// seam, where it becomes a durable `client.encrypt_failed` rejection.
7184    fn validate_author_encode(
7185        &self,
7186        table: &TableSchema,
7187        row_id: &str,
7188        values: &Map<String, Value>,
7189    ) -> Result<(), String> {
7190        match encode_sparse_row_json(table, row_id, values, &self.encryption, None) {
7191            Err(error) if error.starts_with(ENCRYPT_FAILED_CODE) => Ok(()),
7192            result => result.map(|_| ()),
7193        }
7194    }
7195
7196    /// §5.11/§10.3: drop every pending commit whose push encode fails with
7197    /// `client.encrypt_failed` (an unresolvable key id or an unknown key) and
7198    /// raise one durable rejection per commit. `sync()` never aborts for an
7199    /// encode failure. Mirrors §7.4.4's `drop_incompatible_outbox`, including
7200    /// undoing the dropped commit's purely-optimistic rows.
7201    /// §7.1/§7.4.4: drop pending commits whose values the current codec refuses
7202    /// (an envelope or a type an earlier version accepted). `with_encryption`
7203    /// additionally drops commits whose §5.11 encryption cannot resolve a key;
7204    /// the startup boundary leaves those to the send seam, where hosts configure
7205    /// keys after open.
7206    /// Recovery runs as one observation. An enclosing observation (the guarded
7207    /// schema reset) passes its `batch`, so the rejection, outcome, and table
7208    /// domains join that change event instead of publishing a second one.
7209    fn drop_unencodable_outbox(
7210        &mut self,
7211        with_encryption: bool,
7212        batch: Option<&mut ChangeAccumulator>,
7213    ) -> Result<bool, String> {
7214        let mut failures = Vec::new();
7215        for commit in self.outbox.iter() {
7216            for op in &commit.ops {
7217                let Some(table) = self.schema.table(&op.table).filter(|_| op.upsert) else {
7218                    continue;
7219                };
7220                // An insert lacking a non-nullable column is left to
7221                // `drop_incompatible_outbox` (§7.4.4).
7222                let Some(values) = op.presented_values(table) else {
7223                    continue;
7224                };
7225                let fallback = self.stored_key_fallback(table, &op.row_id)?;
7226                let failure = match encode_sparse_row_json(
7227                    table,
7228                    &op.row_id,
7229                    &values,
7230                    &self.encryption,
7231                    fallback.as_ref(),
7232                ) {
7233                    Err(error) if error.starts_with(ENCRYPT_FAILED_CODE) => {
7234                        with_encryption.then_some((error, ENCRYPT_FAILED_CODE))
7235                    }
7236                    // §7.1/§7.4.4: a value the current codec refuses was
7237                    // persisted by a version that accepted it; it leaves
7238                    // through the incompatible-outbox path, so the FIFO
7239                    // queue never wedges.
7240                    Err(error) if error.starts_with(INVALID_REQUEST_CODE) => Some((
7241                        LEGACY_VALUE_REFUSAL_MESSAGE.to_owned(),
7242                        OUTBOX_INCOMPATIBLE_CODE,
7243                    )),
7244                    _ => None,
7245                };
7246                if let Some((error, code)) = failure {
7247                    failures.push((commit.clone(), error, code));
7248                    break;
7249                }
7250            }
7251        }
7252        if failures.is_empty() {
7253            return Ok(false);
7254        }
7255        self.reject_outbox_commits(
7256            failures
7257                .into_iter()
7258                .map(|(commit, message, code)| {
7259                    let details = (code == OUTBOX_INCOMPATIBLE_CODE).then(|| RejectionDetails {
7260                        field_paths: None,
7261                        reason: Some(INVALID_STORED_VALUES_REASON.to_owned()),
7262                        required_action: None,
7263                        references: None,
7264                    });
7265                    (commit, message, code, details)
7266                })
7267                .collect(),
7268            batch,
7269        )?;
7270        Ok(true)
7271    }
7272
7273    /// §7.4.4 client-local terminal drop of pending commits, each journaled as a
7274    /// rejection with `code` and `details`. Every code except
7275    /// `sync.outbox_incompatible` keeps the retained intent.
7276    #[allow(clippy::type_complexity)]
7277    fn reject_outbox_commits(
7278        &mut self,
7279        failures: Vec<(
7280            Arc<OutboxCommit>,
7281            String,
7282            &'static str,
7283            Option<RejectionDetails>,
7284        )>,
7285        batch: Option<&mut ChangeAccumulator>,
7286    ) -> Result<(), String> {
7287        // §7.4.4: one observation covers the durable outcome writes, the outbox
7288        // removal, the in-memory drop, and the overlay rebuild, so a storage fault
7289        // leaves the replica and the client unchanged, a successful recovery
7290        // publishes one batch with the rejection, outcome, and table domains, and
7291        // an ordinary open with nothing to recover publishes nothing.
7292        let rollback = self.capture();
7293        let owns_observation = batch.is_none();
7294        let owns_transaction = self.conn.is_autocommit();
7295        let mut domains = ChangeAccumulator::default();
7296        if owns_observation {
7297            self.begin_observation("syncular_value_recovery")?;
7298        }
7299        let dropped = (|| -> Result<(), String> {
7300            for (commit, message, code, details) in failures {
7301                if self.retain_failed_commits && code != OUTBOX_INCOMPATIBLE_CODE {
7302                    self.retain_failed_commit(&commit.client_commit_id, &commit.ops)?;
7303                }
7304                let representable = commit.ops.iter().all(Self::outbox_op_is_journalable);
7305                let rejection = RejectionRecord {
7306                    client_commit_id: commit.client_commit_id.clone(),
7307                    op_index: 0,
7308                    code: code.to_owned(),
7309                    message,
7310                    retryable: false,
7311                    details,
7312                    operation: representable
7313                        .then(|| commit.ops.first())
7314                        .flatten()
7315                        .map(CommitOperation::from),
7316                };
7317                self.persist_commit_outcome(
7318                    &commit.client_commit_id,
7319                    CommitOutcomeStatus::Rejected,
7320                    &[CommitOperationOutcome::Error {
7321                        rejection: rejection.clone(),
7322                    }],
7323                    representable.then_some(commit.ops.as_slice()),
7324                )?;
7325                self.leave_through(&commit.client_commit_id);
7326                self.delete_outbox_persisted(&commit.client_commit_id)?;
7327                self.outbox
7328                    .retain(|candidate| candidate.client_commit_id != commit.client_commit_id);
7329                self.rejections.push(rejection);
7330                for operation in &commit.ops {
7331                    domains.table(operation.table.as_str());
7332                }
7333            }
7334            domains.status = true;
7335            domains.rejections = true;
7336            domains.outcomes = true;
7337            self.prune_commit_outcomes()?;
7338            // The visible projection is re-derived from the surviving base + outbox.
7339            self.overlay_dirty.set(true);
7340            self.rebuild_overlay()?;
7341            Ok(())
7342        })();
7343        let result = match batch {
7344            Some(batch) => {
7345                if dropped.is_ok() {
7346                    for table in domains.tables.keys() {
7347                        batch.table(table.as_str());
7348                    }
7349                    batch.status |= domains.status;
7350                    batch.rejections |= domains.rejections;
7351                    batch.outcomes |= domains.outcomes;
7352                }
7353                dropped
7354            }
7355            None => {
7356                dropped.and_then(|()| self.finish_observation("syncular_value_recovery", domains))
7357            }
7358        };
7359        if let Err(error) = result {
7360            if owns_observation {
7361                if owns_transaction {
7362                    if let Err(rollback) = self.conn.execute_batch("ROLLBACK") {
7363                        let mut failure = self.storage_failure.borrow_mut();
7364                        let failure =
7365                            failure.get_or_insert_with(|| QueryReadFailure::from(error.clone()));
7366                        failure.rollback_failure = Some(Box::new(QueryReadFailure::from(rollback)));
7367                    }
7368                } else {
7369                    self.rollback_observation("syncular_value_recovery");
7370                }
7371            }
7372            self.restore(rollback);
7373            return Err(error);
7374        }
7375        Ok(())
7376    }
7377
7378    pub fn pending_commit_ids(&self) -> Vec<String> {
7379        self.outbox
7380            .iter()
7381            .map(|c| c.client_commit_id.clone())
7382            .collect()
7383    }
7384
7385    /// §7.1: every pending commit in FIFO order, as the TypeScript client's
7386    /// `pendingCommits()` returns it.
7387    pub fn pending_commits(&self) -> Result<Vec<PendingCommit>, String> {
7388        let mut stmt = self
7389            .conn
7390            .prepare_cached(
7391                "SELECT seq, commit_id, created_at_ms, ops_json FROM _syncular_outbox ORDER BY seq",
7392            )
7393            .map_err(|error| error.to_string())?;
7394        let rows = stmt
7395            .query_map([], |row| {
7396                Ok((
7397                    row.get(0)?,
7398                    row.get(1)?,
7399                    row.get(2)?,
7400                    row.get::<_, String>(3)?,
7401                ))
7402            })
7403            .map_err(|error| error.to_string())?;
7404        rows.map(|row| {
7405            let (seq, client_commit_id, created_at_ms, raw) =
7406                row.map_err(|error| error.to_string())?;
7407            let operations = serde_json::from_str(&raw).map_err(|error| {
7408                format!("invalid persisted outbox {client_commit_id:?}: {error}")
7409            })?;
7410            Ok(PendingCommit {
7411                seq,
7412                client_commit_id,
7413                created_at_ms,
7414                operations,
7415            })
7416        })
7417        .collect()
7418    }
7419
7420    /// §6.1: the sparse push payload bytes of every pending upsert operation,
7421    /// FIFO — exactly what the next push round would put on the wire. Used by
7422    /// conformance B.21(h) to pin cross-core byte identity.
7423    pub fn pending_payloads(&self) -> Result<Vec<Vec<u8>>, String> {
7424        let mut payloads = Vec::new();
7425        for commit in self.outbox.iter() {
7426            for op in &commit.ops {
7427                let Some(table) = self.schema.table(&op.table).filter(|_| op.upsert) else {
7428                    continue;
7429                };
7430                let Some(values) = op.presented_values(table) else {
7431                    continue;
7432                };
7433                let fallback = self.stored_key_fallback(table, &op.row_id)?;
7434                if let Ok(payload) = encode_sparse_row_json(
7435                    table,
7436                    &op.row_id,
7437                    &values,
7438                    &self.encryption,
7439                    fallback.as_ref(),
7440                ) {
7441                    payloads.push(payload);
7442                }
7443            }
7444        }
7445        Ok(payloads)
7446    }
7447
7448    pub fn conflicts(&self) -> &[ConflictRecord] {
7449        &self.conflicts
7450    }
7451
7452    pub fn rejections(&self) -> &[RejectionRecord] {
7453        &self.rejections
7454    }
7455
7456    pub fn resolve_commit_outcome(
7457        &mut self,
7458        input: ResolveCommitOutcomeInput,
7459    ) -> Result<CommitOutcome, String> {
7460        let current = self
7461            .commit_outcome(&input.client_commit_id)?
7462            .ok_or_else(|| {
7463                format!(
7464                    "sync.outcome_not_found: no durable outcome exists for {:?}",
7465                    input.client_commit_id
7466                )
7467            })?;
7468        if current.resolution != CommitOutcomeResolution::Active {
7469            return Ok(current);
7470        }
7471        if current.replacement_client_commit_id.is_some() {
7472            return Err(REPLACEMENT_PENDING.to_owned());
7473        }
7474        if input.resolution == CommitOutcomeResolution::Active {
7475            return Err("sync.invalid_request: resolution must leave active state".to_owned());
7476        }
7477        match input.resolution {
7478            CommitOutcomeResolution::Superseded => {
7479                let replacement = input
7480                    .replacement_client_commit_id
7481                    .as_deref()
7482                    .filter(|value| !value.is_empty() && *value != input.client_commit_id)
7483                    .ok_or_else(|| {
7484                        "sync.invalid_request: superseded outcomes require a distinct replacementClientCommitId"
7485                            .to_owned()
7486                    })?;
7487                let _ = replacement;
7488            }
7489            _ if input.replacement_client_commit_id.is_some() => {
7490                return Err(
7491                    "sync.invalid_request: replacementClientCommitId is valid only for superseded outcomes"
7492                        .to_owned(),
7493                );
7494            }
7495            _ => {}
7496        }
7497        let allowed = match current.status {
7498            CommitOutcomeStatus::Conflict => matches!(
7499                input.resolution,
7500                CommitOutcomeResolution::ResolvedKeepServer | CommitOutcomeResolution::Superseded
7501            ),
7502            CommitOutcomeStatus::Rejected => {
7503                matches!(
7504                    input.resolution,
7505                    CommitOutcomeResolution::Superseded
7506                        | CommitOutcomeResolution::ResolvedKeepServer
7507                )
7508            }
7509            CommitOutcomeStatus::Applied | CommitOutcomeStatus::Cached => {
7510                input.resolution == CommitOutcomeResolution::Dismissed
7511            }
7512            CommitOutcomeStatus::Replaced => false,
7513        };
7514        if !allowed {
7515            return Err(format!(
7516                "sync.invalid_request: resolution {:?} is invalid for {:?} outcome",
7517                input.resolution, current.status
7518            ));
7519        }
7520
7521        let rollback = self.capture();
7522        self.begin_observation("syncular_outcome_resolution")?;
7523        let mut batch = ChangeAccumulator::default();
7524        let result = self
7525            .release_outcome(
7526                &current,
7527                input.resolution,
7528                input.replacement_client_commit_id.as_deref(),
7529                &mut batch,
7530            )
7531            .and_then(|()| self.rebuild_overlay_if_dirty())
7532            .and_then(|()| self.finish_observation("syncular_outcome_resolution", batch));
7533        if let Err(error) = result {
7534            self.rollback_observation("syncular_outcome_resolution");
7535            self.restore(rollback);
7536            return Err(error);
7537        }
7538        self.commit_outcome(&current.client_commit_id)?
7539            .ok_or_else(|| "sync.outcome_not_found: outcome disappeared".to_owned())
7540    }
7541
7542    /// §7.2.2: record a decision against an active conflict or rejection as a
7543    /// held replacement commit and return its client commit id. Without
7544    /// `replacement` the retained envelope is kept ("keep mine"); every
7545    /// operation on a retained row takes that row's base version.
7546    pub fn replace_commit_outcome(
7547        &mut self,
7548        client_commit_id: &str,
7549        sequence: i64,
7550        replacement: Option<Vec<Mutation>>,
7551    ) -> Result<String, ClientError> {
7552        let prior = self.storage_failure.borrow_mut().take();
7553        let outcome = (|| -> Result<String, ClientError> {
7554            let Some(current) = self.commit_outcome(client_commit_id)? else {
7555                return Err(ClientError {
7556                    code: "sync.outcome_not_found".to_owned(),
7557                    message: "no durable outcome exists for the commit".to_owned(),
7558                    details: Some(json!({ "clientCommitId": client_commit_id })),
7559                    retryable: false,
7560                });
7561            };
7562            if current.resolution == CommitOutcomeResolution::Active
7563                && current.replacement_client_commit_id.is_some()
7564            {
7565                return Err(ClientError {
7566                    code: "client.replacement_pending".to_owned(),
7567                    message: "the outcome has a pending replacement".to_owned(),
7568                    details: Some(json!({ "clientCommitId": client_commit_id })),
7569                    retryable: false,
7570                });
7571            }
7572            let (Some(envelope), Some(rows)) = (current.operations, current.retained_rows) else {
7573                return Err(invalid_authoring(
7574                    "the outcome cannot be replaced",
7575                    json!({ "clientCommitId": client_commit_id }),
7576                ));
7577            };
7578            if current.sequence != sequence
7579                || current.resolution != CommitOutcomeResolution::Active
7580                || !matches!(
7581                    current.status,
7582                    CommitOutcomeStatus::Conflict | CommitOutcomeStatus::Rejected
7583                )
7584                || rows.is_empty()
7585                || envelope.len() != rows.len()
7586            {
7587                return Err(invalid_authoring(
7588                    "the outcome cannot be replaced",
7589                    json!({ "clientCommitId": client_commit_id }),
7590                ));
7591            }
7592            let ops = match replacement {
7593                None => envelope
7594                    .into_iter()
7595                    .zip(&rows)
7596                    .map(|(operation, row)| OutboxOp {
7597                        base_version: Some(row.server_version.unwrap_or(0)),
7598                        ..OutboxOp::from(operation)
7599                    })
7600                    .collect(),
7601                Some(mutations) => {
7602                    let mut ops = self.prepare_mutations(mutations)?;
7603                    for op in &mut ops {
7604                        let Some(row) = rows
7605                            .iter()
7606                            .find(|row| row.table == op.table && row.row_id == op.row_id)
7607                        else {
7608                            continue;
7609                        };
7610                        if op.base_version.is_some() {
7611                            return Err(invalid_authoring(
7612                                "an operation on a retained row takes its base version",
7613                                json!({ "table": op.table }),
7614                            ));
7615                        }
7616                        op.base_version = Some(row.server_version.unwrap_or(0));
7617                    }
7618                    ops
7619                }
7620            };
7621            Ok(self.record_outbox_commit(ops, Some(client_commit_id))?)
7622        })();
7623        self.finish_authoring(prior, outcome)
7624    }
7625
7626    /// §7.2.3: replace the operations of the pending commit `client_commit_id`
7627    /// and return `replacement_client_commit_id`. An attempted commit is fenced
7628    /// first (§6.12) over `transport`; a never-attempted one needs none.
7629    pub fn replace_pending_commit(
7630        &mut self,
7631        transport: &mut dyn Transport,
7632        client_commit_id: &str,
7633        mutations: Vec<Mutation>,
7634        replacement_client_commit_id: &str,
7635    ) -> Result<String, ClientError> {
7636        match self.prepare_pending_commit_replacement(
7637            client_commit_id,
7638            mutations,
7639            replacement_client_commit_id,
7640        )? {
7641            None => Ok(replacement_client_commit_id.to_owned()),
7642            Some(prepared) => {
7643                let reply = prepared.exchange(transport);
7644                self.apply_fence_round(prepared, reply)
7645            }
7646        }
7647    }
7648
7649    /// The owner half of [`SyncClient::replace_pending_commit`]. `None` means
7650    /// the replacement is complete (or an earlier call with the same
7651    /// replacement id completed it); otherwise send the fence round and apply
7652    /// its reply with [`SyncClient::apply_fence_round`].
7653    pub fn prepare_pending_commit_replacement(
7654        &mut self,
7655        client_commit_id: &str,
7656        mutations: Vec<Mutation>,
7657        replacement_client_commit_id: &str,
7658    ) -> Result<Option<PreparedFenceRound>, ClientError> {
7659        let prior = self.storage_failure.borrow_mut().take();
7660        let outcome = (|| -> Result<Option<PreparedFenceRound>, ClientError> {
7661            let Some(original) = self
7662                .outbox
7663                .iter()
7664                .find(|commit| commit.client_commit_id == client_commit_id)
7665                .cloned()
7666            else {
7667                return match self.commit_outcome(client_commit_id)? {
7668                    Some(outcome)
7669                        if Self::is_replaced(&outcome)
7670                            && outcome.replacement_client_commit_id.as_deref()
7671                                == Some(replacement_client_commit_id) =>
7672                    {
7673                        Ok(None)
7674                    }
7675                    _ => Err(ClientError {
7676                        code: "sync.outcome_not_found".to_owned(),
7677                        message: "no pending commit exists for the id".to_owned(),
7678                        details: Some(json!({ "clientCommitId": client_commit_id })),
7679                        retryable: false,
7680                    }),
7681                };
7682            };
7683            if replacement_client_commit_id.is_empty()
7684                || self
7685                    .outbox
7686                    .iter()
7687                    .any(|commit| commit.client_commit_id == replacement_client_commit_id)
7688                || self.commit_outcome(replacement_client_commit_id)?.is_some()
7689            {
7690                return Err(invalid_authoring(
7691                    "the replacement client commit id must be unused",
7692                    json!({ "replacementClientCommitId": replacement_client_commit_id }),
7693                ));
7694            }
7695            // §7.2.2: a held replacement waits for its proof under its own id.
7696            let held: bool = self
7697                .conn
7698                .query_row(
7699                    "SELECT EXISTS(SELECT 1 FROM _syncular_commit_outcomes
7700                      WHERE resolution = 'active' AND replacement_client_commit_id = ?1)",
7701                    [client_commit_id],
7702                    |row| row.get(0),
7703                )
7704                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
7705            if held {
7706                return Err(REPLACEMENT_PENDING.to_owned().into());
7707            }
7708            let full_rows: Vec<bool> = mutations
7709                .iter()
7710                .map(|mutation| matches!(mutation, Mutation::Upsert { .. }))
7711                .collect();
7712            let mut operations = self.prepare_mutations(mutations)?;
7713            for (operation, full_row) in operations.iter_mut().zip(full_rows) {
7714                let touched: Vec<&OutboxOp> = original
7715                    .ops
7716                    .iter()
7717                    .filter(|op| op.table == operation.table && op.row_id == operation.row_id)
7718                    .collect();
7719                // §7.1: a full-row upsert of a row the original inserted keeps
7720                // the insert intent the original recorded.
7721                operation.insert |= full_row && touched.iter().any(|op| op.insert);
7722                if let Some(first) = touched.first() {
7723                    operation.base_version = first.base_version;
7724                }
7725            }
7726            let attempted: bool = self
7727                .conn
7728                .query_row(
7729                    "SELECT attempted FROM _syncular_outbox WHERE commit_id = ?1",
7730                    [client_commit_id],
7731                    |row| row.get(0),
7732                )
7733                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
7734            if !attempted {
7735                self.replace_outbox_commit(
7736                    client_commit_id,
7737                    operations,
7738                    replacement_client_commit_id,
7739                )?;
7740                return Ok(None);
7741            }
7742            if self.transport_closed() {
7743                return Err(ClientError {
7744                    code: "sync.offline".to_owned(),
7745                    message: "transport gate is closed".to_owned(),
7746                    details: None,
7747                    retryable: false,
7748                });
7749            }
7750            if self.active_round.is_some() || self.fence_round.is_some() {
7751                return Err(ClientError {
7752                    code: "client.round_in_progress".to_owned(),
7753                    message: "a sync round is already in flight".to_owned(),
7754                    details: None,
7755                    retryable: false,
7756                });
7757            }
7758            if self.realtime_policy == RealtimePolicy::Required
7759                && self.realtime_state != RealtimeState::Connected
7760            {
7761                return Err(ClientError {
7762                    code: REALTIME_UNAVAILABLE_CODE.to_owned(),
7763                    message: "the realtime socket is not connected".to_owned(),
7764                    details: None,
7765                    retryable: true,
7766                });
7767            }
7768            let header = Frame::ReqHeader {
7769                client_id: self.client_id.clone(),
7770                schema_version: self.schema.version,
7771                log_epoch: self.get_meta(LOG_EPOCH_KEY)?,
7772                outbox_id: self.get_meta(OUTBOX_ID_KEY)?,
7773            };
7774            let id = uuid::Uuid::new_v4();
7775            self.fence_round = Some(id);
7776            Ok(Some(PreparedFenceRound {
7777                id,
7778                client_commit_id: client_commit_id.to_owned(),
7779                replacement_client_commit_id: replacement_client_commit_id.to_owned(),
7780                operations,
7781                request: encode_message(&Message {
7782                    wire_version: WIRE_VERSION,
7783                    msg_kind: MsgKind::Request,
7784                    frames: vec![
7785                        header,
7786                        Frame::FenceCommit {
7787                            client_commit_id: client_commit_id.to_owned(),
7788                        },
7789                    ],
7790                }),
7791                realtime: self.realtime_state == RealtimeState::Connected,
7792            }))
7793        })();
7794        self.finish_authoring(prior, outcome)
7795    }
7796
7797    /// Apply the reply of a [`PreparedFenceRound`] on the owner (§6.12,
7798    /// §7.2.3) and return the replacement's id. No network I/O. A stored
7799    /// result settles the original through the push-result path and fails
7800    /// with `client.commit_settled`.
7801    pub fn apply_fence_round(
7802        &mut self,
7803        prepared: PreparedFenceRound,
7804        reply: Result<Vec<u8>, TransportError>,
7805    ) -> Result<String, ClientError> {
7806        if self.fence_round != Some(prepared.id) {
7807            return Err(ClientError {
7808                code: "client.round_cancelled".to_owned(),
7809                message: "fence round belongs to a released client context".to_owned(),
7810                details: None,
7811                retryable: false,
7812            });
7813        }
7814        self.fence_round = None;
7815        let prior = self.storage_failure.borrow_mut().take();
7816        let outcome = (|| -> Result<String, ClientError> {
7817            let id = prepared.client_commit_id.as_str();
7818            let invalid = || ClientError {
7819                code: "client.invalid_host_response".to_owned(),
7820                message: "the fence response does not answer the fenced commit".to_owned(),
7821                details: Some(json!({ "clientCommitId": id })),
7822                retryable: false,
7823            };
7824            let bytes = reply.map_err(|error| ClientError {
7825                retryable: error
7826                    .details
7827                    .as_ref()
7828                    .and_then(|details| details.get("retryable"))
7829                    == Some(&Value::Bool(true)),
7830                code: error.code,
7831                message: error.message,
7832                details: error.details,
7833            })?;
7834            let response = decode_message(&bytes).map_err(|_| invalid())?;
7835            if response.msg_kind != MsgKind::Response {
7836                return Err(invalid());
7837            }
7838            let mut frames = response
7839                .frames
7840                .into_iter()
7841                .filter(|frame| !matches!(frame, Frame::Keepalive));
7842            match frames.next() {
7843                // §1.6: a schema-floor response; the client stops syncing as
7844                // a sync round's floor stops it.
7845                Some(Frame::RespHeader {
7846                    required_schema_version: Some(required),
7847                    latest_schema_version,
7848                    ..
7849                }) => {
7850                    self.set_schema_floor(Some(SchemaFloor {
7851                        required_schema_version: Some(required),
7852                        latest_schema_version,
7853                    }))?;
7854                    return Err(ClientError {
7855                        code: "sync.schema_mismatch".to_owned(),
7856                        message: "the server requires a newer schema version".to_owned(),
7857                        details: Some(json!({ "requiredSchemaVersion": required })),
7858                        retryable: false,
7859                    });
7860                }
7861                Some(Frame::RespHeader {
7862                    reset_required: false,
7863                    ..
7864                }) => {}
7865                _ => return Err(invalid()),
7866            }
7867            let answer = frames.next();
7868            let rest: Vec<Frame> = frames.collect();
7869            match answer {
7870                // A server that predates the frame refuses the request.
7871                Some(Frame::Error {
7872                    code,
7873                    message,
7874                    retryable,
7875                    details,
7876                    ..
7877                }) => Err(ClientError {
7878                    code,
7879                    message,
7880                    details: details.and_then(|details| serde_json::from_str(&details.0).ok()),
7881                    retryable,
7882                }),
7883                Some(Frame::CommitFenced { client_commit_id })
7884                    if client_commit_id == id && rest.is_empty() =>
7885                {
7886                    self.replace_outbox_commit(
7887                        id,
7888                        prepared.operations,
7889                        &prepared.replacement_client_commit_id,
7890                    )?;
7891                    Ok(prepared.replacement_client_commit_id)
7892                }
7893                Some(Frame::PushResult {
7894                    client_commit_id,
7895                    status,
7896                    commit_seq,
7897                    results,
7898                }) if client_commit_id == id => {
7899                    let mut details = HashMap::new();
7900                    match rest.as_slice() {
7901                        [] => {}
7902                        [Frame::PushResultDetails {
7903                            client_commit_id: owner,
7904                            entries,
7905                        }] if owner == id => {
7906                            let parsed = entries
7907                                .iter()
7908                                .map(|entry| -> Result<_, String> {
7909                                    Ok((entry.op_index, RejectionDetails::parse(&entry.details.0)?))
7910                                })
7911                                .collect::<Result<BTreeMap<i32, RejectionDetails>, String>>()
7912                                .map_err(|_| invalid())?;
7913                            details.insert(id.to_owned(), parsed);
7914                        }
7915                        _ => return Err(invalid()),
7916                    }
7917                    let settled = if status == PushStatus::Rejected {
7918                        "rejected"
7919                    } else {
7920                        "applied"
7921                    };
7922                    let mut report = SyncReport::default();
7923                    self.handle_push_results(
7924                        &[Frame::PushResult {
7925                            client_commit_id,
7926                            status,
7927                            commit_seq,
7928                            results,
7929                        }],
7930                        &HashSet::from([id]),
7931                        &details,
7932                        &mut report,
7933                        Some(id),
7934                    )
7935                    .map_err(|_| ClientError {
7936                        code: "client.outcome_persistence_failed".to_owned(),
7937                        message: "local commit outcome could not be persisted".to_owned(),
7938                        details: None,
7939                        retryable: false,
7940                    })?;
7941                    // §6.3: a serving failure is no outcome; the commit stays.
7942                    if !report.retryable.is_empty() {
7943                        return Err(ClientError {
7944                            code: "sync.idempotency_cache_miss".to_owned(),
7945                            message: "the server could not serve the stored result".to_owned(),
7946                            details: Some(json!({ "clientCommitId": id })),
7947                            retryable: true,
7948                        });
7949                    }
7950                    Err(ClientError {
7951                        code: "client.commit_settled".to_owned(),
7952                        message: "the commit already has a server outcome".to_owned(),
7953                        details: Some(json!({ "clientCommitId": id, "status": settled })),
7954                        retryable: false,
7955                    })
7956                }
7957                _ => Err(invalid()),
7958            }
7959        })();
7960        self.finish_authoring(prior, outcome)
7961    }
7962
7963    /// §7.2.3: swap a pending commit's operations and id in place (same
7964    /// outbox sequence), re-derive the overlay of its rows and every later
7965    /// commit, and journal the original as `replaced`, in one transaction
7966    /// with one change batch.
7967    fn replace_outbox_commit(
7968        &mut self,
7969        client_commit_id: &str,
7970        ops: Vec<OutboxOp>,
7971        replacement: &str,
7972    ) -> Result<(), ClientError> {
7973        let Some(index) = self
7974            .outbox
7975            .iter()
7976            .position(|commit| commit.client_commit_id == client_commit_id)
7977        else {
7978            return Err(ClientError {
7979                code: "sync.outcome_not_found".to_owned(),
7980                message: "no pending commit exists for the id".to_owned(),
7981                details: Some(json!({ "clientCommitId": client_commit_id })),
7982                retryable: false,
7983            });
7984        };
7985        let original = self.outbox[index].clone();
7986        let commit = OutboxCommit {
7987            client_commit_id: replacement.to_owned(),
7988            ops,
7989        };
7990        let rollback = self.capture();
7991        self.begin_observation("syncular_pending_replacement")?;
7992        let mut batch = ChangeAccumulator::default();
7993        let replaced = (|| {
7994            let (seq, created_at_ms): (i64, i64) = self
7995                .conn
7996                .query_row(
7997                    "SELECT seq, created_at_ms FROM _syncular_outbox WHERE commit_id = ?1",
7998                    [client_commit_id],
7999                    |row| Ok((row.get(0)?, row.get(1)?)),
8000                )
8001                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8002            self.persist_outbox_insert(&commit)?;
8003            self.leave_through(client_commit_id);
8004            self.delete_outbox_persisted(client_commit_id)?;
8005            // §7.2.1: journaled as a purge journals its drops, decided.
8006            let results = (0..original.ops.len())
8007                .map(|op_index| CommitOperationOutcome::Error {
8008                    rejection: RejectionRecord {
8009                        client_commit_id: client_commit_id.to_owned(),
8010                        op_index: op_index as i32,
8011                        code: COMMIT_REPLACED_CODE.to_owned(),
8012                        message: "the commit was replaced before the server applied it".to_owned(),
8013                        retryable: false,
8014                        details: None,
8015                        operation: None,
8016                    },
8017                })
8018                .collect::<Vec<_>>();
8019            let results_json =
8020                serde_json::to_string(&results).map_err(|error| error.to_string())?;
8021            self.conn
8022                .execute(
8023                    "UPDATE _syncular_outbox SET seq = ?1, created_at_ms = ?2 WHERE commit_id = ?3",
8024                    rusqlite::params![seq, created_at_ms, replacement],
8025                )
8026                .and_then(|_| {
8027                    self.conn.execute(
8028                        "INSERT INTO _syncular_commit_outcomes (
8029                           client_commit_id, status, recorded_at_ms, results_json, resolution,
8030                           resolved_at_ms, replacement_client_commit_id
8031                         ) VALUES (?1, 'rejected', ?2, ?3, 'superseded', ?2, ?4)",
8032                        rusqlite::params![
8033                            client_commit_id,
8034                            self.clock_now_ms(),
8035                            results_json,
8036                            replacement
8037                        ],
8038                    )
8039                })
8040                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8041            self.prune_commit_outcomes()?;
8042            for op in original.ops.iter().chain(&commit.ops) {
8043                self.overlay_dirty.table(&op.table);
8044                batch.table(&op.table);
8045            }
8046            self.outbox[index] = Arc::new(commit);
8047            batch.status = true;
8048            batch.outcomes = true;
8049            self.rebuild_overlay_if_dirty()?;
8050            self.finish_observation("syncular_pending_replacement", batch)
8051        })();
8052        if let Err(error) = replaced {
8053            self.rollback_observation("syncular_pending_replacement");
8054            self.restore(rollback);
8055            return Err(error.into());
8056        }
8057        Ok(())
8058    }
8059
8060    /// Internal host step at the start of an idle drive (§7.2.2): capture
8061    /// every pending decision with the units and epochs of this drive.
8062    #[doc(hidden)]
8063    pub fn prepare_replacements(&self) -> Result<Vec<CurrentBasePreparation>, String> {
8064        let mut stmt = self
8065            .conn
8066            .prepare_cached(
8067                "SELECT client_commit_id, seq, replacement_client_commit_id
8068                   FROM _syncular_commit_outcomes
8069                  WHERE resolution = 'active' AND replacement_client_commit_id IS NOT NULL
8070                  ORDER BY seq ASC",
8071            )
8072            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8073        let decisions = stmt
8074            .query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
8075            .and_then(|rows| rows.collect::<Result<Vec<(String, i64, String)>, _>>())
8076            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8077        if decisions.is_empty() {
8078            return Ok(Vec::new());
8079        }
8080        let units = self.stored(load_units(&self.conn))?;
8081        Ok(decisions
8082            .into_iter()
8083            .map(
8084                |(client_commit_id, sequence, replacement)| CurrentBasePreparation {
8085                    client_commit_id,
8086                    sequence,
8087                    replacement: Some(replacement),
8088                    units: units.clone(),
8089                    transport_epoch: self.transport_epoch,
8090                    registration_epoch: self.registration_epoch,
8091                    security_epoch: self.security_epoch,
8092                },
8093            )
8094            .collect())
8095    }
8096
8097    /// Internal host step when an idle drive reaches idle (§7.2.2): write,
8098    /// refuse, or keep each decision captured at the drive's start. Returns
8099    /// whether a decision was written, so the drive runs another round.
8100    #[doc(hidden)]
8101    pub fn settle_replacements(
8102        &mut self,
8103        decisions: &[CurrentBasePreparation],
8104        drive: &SyncOutcome,
8105    ) -> Result<bool, String> {
8106        if self.transport_closed() {
8107            return Ok(false);
8108        }
8109        let mut written = false;
8110        for decision in decisions {
8111            // A registration change during the drive says nothing about the
8112            // base; the decision waits for the next drive.
8113            if decision.registration_epoch != self.registration_epoch {
8114                continue;
8115            }
8116            let Some(replacement) = decision.replacement.as_deref() else {
8117                continue;
8118            };
8119            let Some(current) =
8120                self.commit_outcome(&decision.client_commit_id)?
8121                    .filter(|current| {
8122                        current.resolution == CommitOutcomeResolution::Active
8123                            && current.replacement_client_commit_id.as_deref() == Some(replacement)
8124                    })
8125            else {
8126                continue;
8127            };
8128            let held = self
8129                .outbox
8130                .iter()
8131                .find(|commit| commit.client_commit_id == replacement)
8132                .cloned();
8133            let refused = match &held {
8134                // A revocation drop (§3.3) or a crash already ended the
8135                // replacement; its own journal entry records what happened.
8136                None => None,
8137                Some(commit) => match self.finish_current_base(decision.clone(), drive.clone()) {
8138                    CurrentBaseProof {
8139                        rows: Some(rows), ..
8140                    } => {
8141                        let proven = commit.ops.iter().all(|op| {
8142                            rows.iter()
8143                                .find(|row| row.table == op.table && row.row_id == op.row_id)
8144                                .is_none_or(|row| {
8145                                    op.base_version == Some(row.server_version.unwrap_or(0))
8146                                })
8147                        });
8148                        written |= proven;
8149                        (!proven).then(|| "base_moved".to_owned())
8150                    }
8151                    CurrentBaseProof {
8152                        reason:
8153                            Some(
8154                                reason @ (CurrentBaseProofReason::SchemaFloor
8155                                | CurrentBaseProofReason::MissingCoverage
8156                                | CurrentBaseProofReason::Revoked
8157                                | CurrentBaseProofReason::OutcomeUnavailable),
8158                            ),
8159                        ..
8160                    } => Some(
8161                        serde_json::to_value(reason)
8162                            .ok()
8163                            .and_then(|reason| reason.as_str().map(str::to_owned))
8164                            .ok_or("sync.local_corrupt")?,
8165                    ),
8166                    _ => continue,
8167                },
8168            };
8169            // One transaction: the original outcome is superseded first, so
8170            // the refused replacement retains its intent over the restored
8171            // server base.
8172            let rollback = self.capture();
8173            self.begin_observation("syncular_replacement")?;
8174            let mut batch = ChangeAccumulator::default();
8175            let result = self
8176                .release_outcome(
8177                    &current,
8178                    CommitOutcomeResolution::Superseded,
8179                    Some(replacement),
8180                    &mut batch,
8181                )
8182                .and_then(|()| self.rebuild_overlay_if_dirty())
8183                .and_then(|()| match (refused, held) {
8184                    (Some(reason), Some(commit)) => self.reject_outbox_commits(
8185                        vec![(
8186                            commit,
8187                            "the replacement could not be written on a proven base".to_owned(),
8188                            REPLACEMENT_REFUSED_CODE,
8189                            Some(RejectionDetails {
8190                                field_paths: None,
8191                                reason: Some(reason),
8192                                required_action: None,
8193                                references: None,
8194                            }),
8195                        )],
8196                        Some(&mut batch),
8197                    ),
8198                    _ => Ok(()),
8199                })
8200                .and_then(|()| self.finish_observation("syncular_replacement", batch));
8201            if let Err(error) = result {
8202                self.rollback_observation("syncular_replacement");
8203                self.restore(rollback);
8204                return Err(error);
8205            }
8206        }
8207        if written {
8208            self.set_sync_needed(true, true);
8209        }
8210        Ok(written)
8211    }
8212
8213    /// §7.2.1 explicit resolution inside the caller's observation: record the
8214    /// resolution, release the retained aggregate and mark its tables for the
8215    /// overlay rebuild, which restores the server base and replays what
8216    /// remains over it.
8217    fn release_outcome(
8218        &mut self,
8219        current: &CommitOutcome,
8220        resolution: CommitOutcomeResolution,
8221        replacement: Option<&str>,
8222        batch: &mut ChangeAccumulator,
8223    ) -> Result<(), String> {
8224        self.conn
8225            .execute(
8226                "UPDATE _syncular_commit_outcomes
8227                    SET resolution = ?1, resolved_at_ms = ?2,
8228                        replacement_client_commit_id = ?3
8229                  WHERE client_commit_id = ?4 AND resolution = 'active'",
8230                rusqlite::params![
8231                    Self::outcome_resolution_name(resolution),
8232                    self.clock_now_ms(),
8233                    replacement,
8234                    current.client_commit_id
8235                ],
8236            )
8237            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8238        self.conn
8239            .execute(
8240                "DELETE FROM _syncular_failed_commits WHERE client_commit_id = ?1",
8241                rusqlite::params![current.client_commit_id],
8242            )
8243            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8244        for (commit, _) in self.failed_commits.iter() {
8245            if commit.client_commit_id == current.client_commit_id {
8246                for operation in &commit.ops {
8247                    self.overlay_dirty.table(&operation.table);
8248                }
8249            }
8250        }
8251        self.failed_commits
8252            .retain(|(commit, _)| commit.client_commit_id != current.client_commit_id);
8253        self.prune_commit_outcomes()?;
8254        self.conflicts
8255            .retain(|record| record.client_commit_id != current.client_commit_id);
8256        self.rejections
8257            .retain(|record| record.client_commit_id != current.client_commit_id);
8258        batch.conflicts |= current.status == CommitOutcomeStatus::Conflict;
8259        batch.rejections |= current.status == CommitOutcomeStatus::Rejected;
8260        batch.outcomes = true;
8261        for operation in current.operations.iter().flatten() {
8262            batch.table(&operation.table);
8263        }
8264        Ok(())
8265    }
8266
8267    pub fn schema_floor(&self) -> Option<&SchemaFloor> {
8268        self.schema_floor.as_ref()
8269    }
8270
8271    /// §7.3.5: the client's opaque auth-lease state, if any.
8272    pub fn lease_state(&self) -> Option<&LeaseState> {
8273        self.lease_state.as_ref()
8274    }
8275
8276    /// §7.3.5: record a request-level lease error (stop-and-surface). Only
8277    /// the two lease codes set it; other errors leave leaseState untouched.
8278    fn record_lease_error(&mut self, code: &str) -> Result<(), String> {
8279        if code != "sync.auth_lease_required" && code != "sync.auth_lease_revoked" {
8280            return Ok(());
8281        }
8282        let mut next = self.lease_state.clone().unwrap_or_default();
8283        next.error_code = Some(code.to_owned());
8284        self.set_lease_state(Some(next))
8285    }
8286
8287    fn set_lease_state(&mut self, next: Option<LeaseState>) -> Result<(), String> {
8288        if self.lease_state == next {
8289            return Ok(());
8290        }
8291        self.begin_observation("syncular_lease")?;
8292        let rollback = self.capture();
8293        self.lease_state = next;
8294        let persisted = match &self.lease_state {
8295            Some(lease) => serde_json::to_string(lease)
8296                .map_err(|error| error.to_string())
8297                .and_then(|json| self.set_meta(LEASE_STATE_KEY, &json)),
8298            None => self.delete_meta(LEASE_STATE_KEY),
8299        };
8300        let batch = ChangeAccumulator {
8301            status: true,
8302            ..ChangeAccumulator::default()
8303        };
8304        if let Err(error) =
8305            persisted.and_then(|()| self.finish_observation("syncular_lease", batch))
8306        {
8307            self.rollback_observation("syncular_lease");
8308            self.restore(rollback);
8309            return Err(error);
8310        }
8311        Ok(())
8312    }
8313
8314    fn set_schema_floor(&mut self, next: Option<SchemaFloor>) -> Result<(), String> {
8315        if self.schema_floor == next {
8316            return Ok(());
8317        }
8318        self.begin_observation("syncular_schema_floor")?;
8319        let rollback = self.capture();
8320        self.stopped = next.is_some();
8321        self.schema_floor = next;
8322        let persisted = match &self.schema_floor {
8323            Some(floor) => serde_json::to_string(floor)
8324                .map_err(|error| error.to_string())
8325                .and_then(|json| self.set_meta(SCHEMA_FLOOR_KEY, &json)),
8326            None => self.delete_meta(SCHEMA_FLOOR_KEY),
8327        };
8328        let batch = ChangeAccumulator {
8329            status: true,
8330            ..ChangeAccumulator::default()
8331        };
8332        if let Err(error) =
8333            persisted.and_then(|()| self.finish_observation("syncular_schema_floor", batch))
8334        {
8335            self.rollback_observation("syncular_schema_floor");
8336            self.restore(rollback);
8337            return Err(error);
8338        }
8339        Ok(())
8340    }
8341
8342    fn set_upgrading(&mut self, value: bool) {
8343        if self.upgrading == value {
8344            return;
8345        }
8346        if self.begin_observation("syncular_upgrading").is_err() {
8347            return;
8348        }
8349        self.upgrading = value;
8350        self.upgrade_kept_tables &= value;
8351        let batch = ChangeAccumulator {
8352            status: true,
8353            ..ChangeAccumulator::default()
8354        };
8355        if self
8356            .finish_observation("syncular_upgrading", batch)
8357            .is_err()
8358        {
8359            self.rollback_observation("syncular_upgrading");
8360        }
8361    }
8362
8363    pub fn sync_needed(&self) -> bool {
8364        self.sync_needed
8365    }
8366
8367    pub fn read_rows(&self, table: &str) -> Result<Vec<RowState>, String> {
8368        let schema_table = self
8369            .schema
8370            .table(table)
8371            .ok_or_else(|| format!("unknown table {table:?}"))?;
8372        let sql = format!(
8373            "SELECT * FROM {} ORDER BY {} ASC",
8374            visible_table(table),
8375            quote_ident(&schema_table.primary_key)
8376        );
8377        let mut stmt = self
8378            .conn
8379            .prepare(&sql)
8380            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8381        let mut rows = stmt
8382            .query([])
8383            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8384        let mut out = Vec::new();
8385        while let Some(row) = rows
8386            .next()
8387            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
8388        {
8389            let mut values = Map::new();
8390            for (i, column) in schema_table.columns.iter().enumerate() {
8391                let value = row
8392                    .get_ref(i)
8393                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8394                values.insert(column.name.clone(), sql_ref_to_json(column, value));
8395            }
8396            let version: i64 = row
8397                .get(schema_table.columns.len())
8398                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8399            let row_id = match values.get(&schema_table.primary_key) {
8400                Some(Value::String(s)) => s.clone(),
8401                Some(Value::Number(n)) => n.to_string(),
8402                Some(Value::Bool(b)) => b.to_string(),
8403                other => format!("{}", other.cloned().unwrap_or(Value::Null)),
8404            };
8405            let sealed_key = if schema_table.has_encrypted_columns() {
8406                row.get(schema_table.columns.len() + 1)
8407                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
8408            } else {
8409                None
8410            };
8411            out.push(RowState {
8412                row_id,
8413                version,
8414                values,
8415                sealed_key,
8416            });
8417        }
8418        Ok(out)
8419    }
8420
8421    // -- §5.10.5 native CRDT (the `crdt-yjs` feature) --------------------------
8422    //
8423    // The Rust face of the §5.10.4 client model: a local crdt edit loads the
8424    // current stored (server-merged ⊕ pending-overlay) column bytes, applies
8425    // the op with `yrs`, re-encodes the whole doc state, and records a
8426    // baseVersion-less sparse upsert carrying only the primary key and the
8427    // crdt column (§5.10.3, §6.6). No local merge — merging is server-side;
8428    // the overlay re-materializes the edit immediately (optimistic apply,
8429    // §7.1) and the server-merged bytes arrive on the next pull, idempotently.
8430    // Byte-compatible with `@syncular/crdt-yjs`.
8431
8432    /// The current stored value of a `crdt` column for one row — the visible
8433    /// (optimistic) bytes, or `None` when the row is absent or the column is
8434    /// NULL (the empty document, §5.10.1). Errors if the column is not a
8435    /// `crdt` column (guards the app against a typo'd column name).
8436    #[cfg(feature = "crdt-yjs")]
8437    fn crdt_column_bytes(
8438        &self,
8439        table: &str,
8440        row_id: &str,
8441        column: &str,
8442    ) -> Result<Option<Vec<u8>>, String> {
8443        let schema_table = self
8444            .schema
8445            .table(table)
8446            .ok_or_else(|| format!("unknown table {table:?}"))?;
8447        let col = schema_table
8448            .columns
8449            .iter()
8450            .find(|c| c.name == column)
8451            .ok_or_else(|| format!("table {table:?} has no column {column:?}"))?;
8452        if col.ty != ColumnType::Crdt {
8453            return Err(format!("column {column:?} is not a crdt column (§5.10.1)"));
8454        }
8455        let sql = format!(
8456            "SELECT {} FROM {} WHERE {}",
8457            quote_ident(column),
8458            visible_table(table),
8459            row_id_predicate(schema_table)
8460        );
8461        let bytes: Option<Vec<u8>> = self
8462            .conn
8463            .prepare_cached(&sql)
8464            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
8465            .query_row(rusqlite::params![row_id], |row| {
8466                row.get::<_, Option<Vec<u8>>>(0)
8467            })
8468            .map_err(|e| match e {
8469                rusqlite::Error::QueryReturnedNoRows => "no such row".to_owned(),
8470                other => Self::sqlite_failure(&self.storage_failure, other),
8471            })?;
8472        Ok(bytes)
8473    }
8474
8475    /// §5.10.4 materialize: the collaborative text of a `crdt` column, decoded
8476    /// from the stored bytes with `yrs` — `YjsColumn.text(name).toString()`.
8477    /// An absent row / NULL column is the empty document (empty string).
8478    #[cfg(feature = "crdt-yjs")]
8479    pub fn crdt_text(
8480        &self,
8481        table: &str,
8482        row_id: &str,
8483        column: &str,
8484        name: &str,
8485    ) -> Result<String, String> {
8486        let bytes = self
8487            .crdt_column_bytes(table, row_id, column)?
8488            .unwrap_or_default();
8489        crate::crdt::text(&bytes, name)
8490    }
8491
8492    /// §5.10.4 push-an-update: apply a text insert to a `crdt` column and
8493    /// record the resulting crdt-only sparse operation. Returns the enqueued
8494    /// `clientCommitId`.
8495    #[cfg(feature = "crdt-yjs")]
8496    pub fn crdt_insert_text(
8497        &mut self,
8498        table: &str,
8499        row_id: &str,
8500        column: &str,
8501        name: &str,
8502        index: u32,
8503        value: &str,
8504    ) -> Result<String, ClientError> {
8505        let prior = self.storage_failure.borrow_mut().take();
8506        let outcome = (|| -> Result<String, ClientError> {
8507            let current = self
8508                .crdt_column_bytes(table, row_id, column)?
8509                .unwrap_or_default();
8510            let update = crate::crdt::insert_text(&current, name, index, value)?;
8511            self.perform_crdt_push_update(table, row_id, column, &update)
8512        })();
8513        self.finish_authoring(prior, outcome)
8514    }
8515
8516    /// §5.10.4 push-an-update: apply a text delete to a `crdt` column and
8517    /// record the resulting crdt-only sparse operation. Returns the enqueued
8518    /// `clientCommitId`.
8519    #[cfg(feature = "crdt-yjs")]
8520    pub fn crdt_delete_text(
8521        &mut self,
8522        table: &str,
8523        row_id: &str,
8524        column: &str,
8525        name: &str,
8526        index: u32,
8527        len: u32,
8528    ) -> Result<String, ClientError> {
8529        let prior = self.storage_failure.borrow_mut().take();
8530        let outcome = (|| -> Result<String, ClientError> {
8531            let current = self
8532                .crdt_column_bytes(table, row_id, column)?
8533                .unwrap_or_default();
8534            let update = crate::crdt::delete_text(&current, name, index, len)?;
8535            self.perform_crdt_push_update(table, row_id, column, &update)
8536        })();
8537        self.finish_authoring(prior, outcome)
8538    }
8539
8540    /// §5.10.4 generic escape hatch: apply an arbitrary Yjs update onto a
8541    /// `crdt` column's current state and record the resulting crdt-only sparse
8542    /// operation. The app authored the update with its own `yrs` model.
8543    /// Returns the enqueued `clientCommitId`.
8544    #[cfg(feature = "crdt-yjs")]
8545    pub fn crdt_apply_update(
8546        &mut self,
8547        table: &str,
8548        row_id: &str,
8549        column: &str,
8550        update: &[u8],
8551    ) -> Result<String, ClientError> {
8552        let prior = self.storage_failure.borrow_mut().take();
8553        let outcome = (|| -> Result<String, ClientError> {
8554            let current = self
8555                .crdt_column_bytes(table, row_id, column)?
8556                .unwrap_or_default();
8557            let next = crate::crdt::apply_update(&current, update)?;
8558            self.perform_crdt_push_update(table, row_id, column, &next)
8559        })();
8560        self.finish_authoring(prior, outcome)
8561    }
8562
8563    /// Shared tail of the crdt edit methods: record a §6.1 sparse crdt-only
8564    /// upsert — the primary key plus the crdt column, no `baseVersion` — and
8565    /// enqueue it. The server merges the crdt column and leaves every other
8566    /// column untouched (§5.10.3), so a baseVersion-less crdt edit cannot
8567    /// clobber a concurrent edit to another column. A locally absent row
8568    /// records the same partial operation; the server answers per §6.2.
8569    #[cfg(feature = "crdt-yjs")]
8570    fn perform_crdt_push_update(
8571        &mut self,
8572        table: &str,
8573        row_id: &str,
8574        column: &str,
8575        crdt_bytes: &[u8],
8576    ) -> Result<String, ClientError> {
8577        let mut bytes_obj = Map::new();
8578        bytes_obj.insert("$bytes".to_owned(), Value::from(bytes_to_hex(crdt_bytes)));
8579        let mut partial = Map::new();
8580        partial.insert(column.to_owned(), Value::Object(bytes_obj));
8581        self.perform_patch(table, row_id, partial, None)
8582    }
8583
8584    /// Run an arbitrary read-only SQL query against the local database and
8585    /// return each row as a `column-name → JSON value` map. This is the seam
8586    /// the React `useSyncQuery` live-query API needs (it takes app-authored
8587    /// SQL over the visible tables/views, not a fixed table read like
8588    /// [`read_rows`]).
8589    ///
8590    /// Bound `params` are the driver value forms: JSON strings/numbers/bools/
8591    /// null bind directly; a `{"$bytes": hex}` object binds as a BLOB — the
8592    /// same envelope the command surface uses everywhere else. Output BLOB
8593    /// columns come back as `{"$bytes": hex}` to round-trip cleanly.
8594    ///
8595    /// The result column typing is dynamic (SQLite's stored affinity), because
8596    /// arbitrary SQL can alias, join, and compute — there is no schema column
8597    /// to consult per output cell, unlike [`read_rows`].
8598    pub fn query(&self, sql: &str, params: &[QueryValue]) -> Result<Vec<QueryRow>, String> {
8599        query_connection(&self.conn, sql, params).map_err(|failure| failure.to_string())
8600    }
8601
8602    /// Repository benchmark and conformance access, present only with `bench-internals`.
8603    #[cfg(feature = "bench-internals")]
8604    #[doc(hidden)]
8605    pub fn benchmark_connection(&mut self) -> &mut Connection {
8606        &mut self.conn
8607    }
8608
8609    /// Private benchmark intervals; absent from ordinary builds and diagnostics.
8610    #[cfg(feature = "bench-internals")]
8611    #[doc(hidden)]
8612    pub fn benchmark_phases(
8613        &self,
8614        enabled: Option<bool>,
8615        reset: bool,
8616    ) -> Result<Option<Value>, String> {
8617        self.benchmark_phases.configure(enabled, reset)?;
8618        Ok(self.benchmark_phases.snapshot())
8619    }
8620
8621    /// §5.11 native ceiling: refuse a declared authority query whose authored
8622    /// statement reads a table or column outside `ceiling` (table to permitted
8623    /// columns) or performs an action other than SELECT, READ, or a
8624    /// deterministic core function. The refusal is
8625    /// `client.authority_read_forbidden` with `{ query, reason: "ceiling",
8626    /// table, column }`.
8627    pub fn check_authority_ceiling(
8628        &mut self,
8629        ceiling: &BTreeMap<String, Vec<String>>,
8630    ) -> Result<(), ClientError> {
8631        for query in &self.limits.authority_reads {
8632            for (table, columns) in authority_read_set(&mut self.conn, query)? {
8633                let Some(allowed) = ceiling.get(&table) else {
8634                    return Err(authority_refusal(
8635                        &query.name,
8636                        "ceiling",
8637                        Some(table.as_str()),
8638                        None,
8639                    ));
8640                };
8641                if let Some(column) = columns
8642                    .iter()
8643                    .find(|column| !column.is_empty() && !allowed.contains(column))
8644                {
8645                    return Err(authority_refusal(
8646                        &query.name,
8647                        "ceiling",
8648                        Some(table.as_str()),
8649                        Some(column.as_str()),
8650                    ));
8651                }
8652            }
8653        }
8654        Ok(())
8655    }
8656
8657    /// §5.11: run declared authority queries over the accepted base in one
8658    /// SQLite read transaction. Each request is a query name and its params
8659    /// keyed by param name; each result carries its rows, its coverage per
8660    /// table and unit, and whether every entry is complete.
8661    pub fn authority_read(
8662        &self,
8663        requests: &[(String, Map<String, Value>)],
8664    ) -> Result<AuthorityReadResult, ClientError> {
8665        if self.limits.authority_reads.is_empty() {
8666            return Err(authority_forbidden(None));
8667        }
8668        // Every request resolves and types its params before the read opens.
8669        let mut prepared = Vec::with_capacity(requests.len());
8670        for (name, params) in requests {
8671            let query = self
8672                .limits
8673                .authority_reads
8674                .iter()
8675                .find(|query| &query.name == name)
8676                .ok_or_else(|| ClientError {
8677                    code: "client.authority_query_unknown".to_owned(),
8678                    message: "authority query is not declared".to_owned(),
8679                    details: Some(json!({ "query": name })),
8680                    retryable: false,
8681                })?;
8682            let invalid = |param: &str| ClientError {
8683                code: "sync.invalid_request".to_owned(),
8684                message: "authority query parameter is missing, extra or mistyped".to_owned(),
8685                details: Some(json!({ "query": name, "param": param })),
8686                retryable: false,
8687            };
8688            if let Some(extra) = params
8689                .keys()
8690                .find(|key| !query.params.iter().any(|param| &param.name == *key))
8691            {
8692                return Err(invalid(extra.as_str()));
8693            }
8694            let mut bound = BTreeMap::new();
8695            for param in &query.params {
8696                let value = params
8697                    .get(&param.name)
8698                    .ok_or_else(|| invalid(param.name.as_str()))?;
8699                let sql = match (param.ty.as_str(), value) {
8700                    (_, Value::Null) if param.nullable => Value::Null,
8701                    ("string", Value::String(_)) | ("float", Value::Number(_)) => value.clone(),
8702                    ("integer", Value::Number(number))
8703                        if number
8704                            .as_i64()
8705                            .is_some_and(|n| n.unsigned_abs() <= MAX_JS_SAFE_INTEGER) =>
8706                    {
8707                        value.clone()
8708                    }
8709                    ("boolean", Value::Bool(flag)) => Value::from(i64::from(*flag)),
8710                    ("json", Value::String(text))
8711                        if serde_json::from_str::<Value>(text).is_ok() =>
8712                    {
8713                        value.clone()
8714                    }
8715                    _ => return Err(invalid(param.name.as_str())),
8716                };
8717                bound.insert(param.name.as_str(), sql);
8718            }
8719            // A coverage param names a unit value: a string or an integer.
8720            let scalar = |param: &str| match params.get(param) {
8721                Some(Value::String(text)) => Ok(text.clone()),
8722                Some(Value::Number(number))
8723                    if number
8724                        .as_i64()
8725                        .is_some_and(|n| n.unsigned_abs() <= MAX_JS_SAFE_INTEGER) =>
8726                {
8727                    Ok(number.to_string())
8728                }
8729                _ => Err(invalid(param)),
8730            };
8731            let mut coverage = Vec::new();
8732            for entry in &query.coverage {
8733                let base = WindowBase {
8734                    variable: entry.variable.clone(),
8735                    fixed_scopes: entry
8736                        .fixed_scopes
8737                        .iter()
8738                        .map(
8739                            |(variable, param)| -> Result<(String, String), ClientError> {
8740                                Ok((variable.clone(), scalar(param.as_str())?))
8741                            },
8742                        )
8743                        .collect::<Result<UnitScopes, ClientError>>()?,
8744                };
8745                for unit in &entry.units {
8746                    coverage.push((entry.table.as_str(), base.clone(), scalar(unit.as_str())?));
8747                }
8748            }
8749            prepared.push((query, bound, coverage));
8750        }
8751        self.conn
8752            .execute_batch("SAVEPOINT syncular_authority_read")
8753            .map_err(authority_stored)?;
8754        let result = (|| -> Result<AuthorityReadResult, ClientError> {
8755            let revision = meta_get(&self.conn, LOCAL_REVISION_KEY)
8756                .map_err(authority_stored)?
8757                .filter(|revision| {
8758                    revision
8759                        .parse::<u64>()
8760                        .is_ok_and(|parsed| &parsed.to_string() == revision)
8761                })
8762                .ok_or_else(authority_corrupt)?;
8763            let units = load_units(&self.conn).map_err(authority_stored)?;
8764            let mut results = Vec::with_capacity(prepared.len());
8765            for (query, bound, coverage) in &prepared {
8766                let (sql, mut params) = self.authority_statement(query)?;
8767                params.extend(query.bind.iter().map(|name| bound[name.as_str()].clone()));
8768                let rows =
8769                    query_connection(&self.conn, &sql, &params).map_err(ClientError::from)?;
8770                let coverage = coverage
8771                    .iter()
8772                    .map(|(table, base, unit)| {
8773                        let mut json_base = json!({ "variable": base.variable });
8774                        if !base.fixed_scopes.is_empty() {
8775                            json_base["fixedScopes"] = json!(base.fixed_scopes);
8776                        }
8777                        AuthorityCoverageState {
8778                            table: (*table).to_owned(),
8779                            base: json_base,
8780                            unit: unit.clone(),
8781                            state: entry_coverage(
8782                                &units,
8783                                table,
8784                                self.schema.table(table),
8785                                base,
8786                                unit,
8787                            )
8788                            .0,
8789                        }
8790                    })
8791                    .collect::<Vec<_>>();
8792                results.push(AuthorityQueryResult {
8793                    query: query.name.clone(),
8794                    rows,
8795                    complete: coverage.iter().all(|entry| entry.state == "complete"),
8796                    coverage,
8797                });
8798            }
8799            Ok(AuthorityReadResult { revision, results })
8800        })();
8801        match result {
8802            Ok(read) => {
8803                self.conn
8804                    .execute_batch("RELEASE syncular_authority_read")
8805                    .map_err(authority_stored)?;
8806                Ok(read)
8807            }
8808            Err(error) => {
8809                self.conn
8810                    .execute_batch(
8811                        "ROLLBACK TO syncular_authority_read; RELEASE syncular_authority_read",
8812                    )
8813                    .map_err(authority_stored)?;
8814                Err(error)
8815            }
8816        }
8817    }
8818
8819    /// §5.11: the statement `authority_read` runs for `query` and its shadow
8820    /// params, which precede the authored binds. Every read table with
8821    /// intent reads its accepted base through a common table expression of
8822    /// the same name; the text is identical in the TypeScript core. The Rust
8823    /// mirror keeps the accepted base in `_syncular_base_<table>`: retained,
8824    /// acknowledged and pending intent replay only onto the visible table, so
8825    /// the base row of an intent id is the earliest accepted state.
8826    fn authority_statement(
8827        &self,
8828        query: &AuthorityQuery,
8829    ) -> Result<(String, Vec<Value>), ClientError> {
8830        let mut shadows = Vec::new();
8831        let mut params = Vec::new();
8832        for (name, reads) in &query.reads {
8833            let table = self.schema.table(name).expect("validated authority table");
8834            let mut ids = Vec::new();
8835            let mut statement = self
8836                .conn
8837                .prepare_cached(
8838                    "SELECT DISTINCT id FROM (\
8839                     SELECT json_extract(value,'$.table') AS tbl,json_extract(value,'$.rowId') AS id \
8840                     FROM _syncular_outbox,json_each(ops_json) \
8841                     UNION ALL SELECT json_extract(value,'$.table'),json_extract(value,'$.rowId') \
8842                     FROM _syncular_failed_commits,json_each(operations_json) \
8843                     UNION ALL SELECT tbl,id FROM _syncular_acked_rows) WHERE tbl=?1",
8844                )
8845                .map_err(authority_stored)?;
8846            let mut rows = statement.query([name]).map_err(authority_stored)?;
8847            while let Some(row) = rows.next().map_err(authority_stored)? {
8848                ids.push(row.get::<_, String>(0).map_err(authority_stored)?);
8849            }
8850            if ids.is_empty() {
8851                continue;
8852            }
8853            ids.sort_by(|a, b| a.encode_utf16().cmp(b.encode_utf16()));
8854            let columns: Vec<&str> =
8855                std::iter::once(table.primary_key.as_str())
8856                    .chain(reads.iter().map(String::as_str).filter(|column| {
8857                        *column != table.primary_key && *column != "_sync_version"
8858                    }))
8859                    .chain(std::iter::once("_sync_version"))
8860                    .collect();
8861            let physical = columns
8862                .iter()
8863                .map(|column| {
8864                    if *column == "_sync_version" {
8865                        "_syncular_version".to_owned()
8866                    } else {
8867                        quote_ident(column)
8868                    }
8869                })
8870                .collect::<Vec<_>>()
8871                .join(",");
8872            let key = quote_ident(&table.primary_key);
8873            let mut statement = self
8874                .conn
8875                .prepare(&format!(
8876                    "SELECT CAST({key} AS TEXT),{physical} FROM {} \
8877                     WHERE CAST({key} AS TEXT) IN (SELECT value FROM json_each(?1))",
8878                    base_table(name),
8879                ))
8880                .map_err(authority_stored)?;
8881            let mut rows = statement
8882                .query([serde_json::to_string(&ids).expect("intent ids serialize")])
8883                .map_err(authority_stored)?;
8884            let mut bases = Vec::new();
8885            while let Some(row) = rows.next().map_err(authority_stored)? {
8886                let id = row.get::<_, String>(0).map_err(authority_stored)?;
8887                let mut values = Vec::with_capacity(columns.len());
8888                for index in 1..=columns.len() {
8889                    values.push(match row.get_ref(index).map_err(authority_stored)? {
8890                        ValueRef::Null => Value::Null,
8891                        ValueRef::Integer(integer) => Value::from(integer),
8892                        ValueRef::Real(real) => serde_json::Number::from_f64(real)
8893                            .map(Value::Number)
8894                            .ok_or_else(authority_corrupt)?,
8895                        ValueRef::Text(text) => {
8896                            Value::from(std::str::from_utf8(text).map_err(|_| authority_corrupt())?)
8897                        }
8898                        ValueRef::Blob(_) => return Err(authority_corrupt()),
8899                    });
8900                }
8901                let version = values
8902                    .last()
8903                    .and_then(Value::as_i64)
8904                    .ok_or_else(authority_corrupt)?;
8905                if version >= 0 {
8906                    bases.push((id, Value::Array(values)));
8907                }
8908            }
8909            bases.sort_by(|a, b| a.0.encode_utf16().cmp(b.0.encode_utf16()));
8910            let shadow = quote_ident(name);
8911            shadows.push(format!(
8912                "{shadow} AS (SELECT {} FROM main.{shadow} WHERE CAST({key} AS TEXT) NOT IN \
8913                 (SELECT value FROM json_each(?)) UNION ALL SELECT {} FROM json_each(?))",
8914                columns
8915                    .iter()
8916                    .map(|column| quote_ident(column))
8917                    .collect::<Vec<_>>()
8918                    .join(","),
8919                (0..columns.len())
8920                    .map(|index| format!("json_extract(value,'$[{index}]')"))
8921                    .collect::<Vec<_>>()
8922                    .join(","),
8923            ));
8924            params.push(Value::from(
8925                serde_json::to_string(&ids).expect("intent ids serialize"),
8926            ));
8927            params.push(Value::from(
8928                Value::from_iter(bases.into_iter().map(|(_, row)| row)).to_string(),
8929            ));
8930        }
8931        let sql = if shadows.is_empty() {
8932            query.sql.clone()
8933        } else {
8934            let keyword = |text: &str, word: &str| {
8935                text.get(..word.len())
8936                    .is_some_and(|head| head.eq_ignore_ascii_case(word))
8937                    && text[word.len()..].starts_with(char::is_whitespace)
8938            };
8939            let shadows = shadows.join(",");
8940            let authored = query.sql.trim_start();
8941            if keyword(authored, "WITH") {
8942                let rest = authored[4..].trim_start();
8943                if keyword(rest, "RECURSIVE") {
8944                    format!("WITH RECURSIVE {shadows}, {}", rest[9..].trim_start())
8945                } else {
8946                    format!("WITH {shadows}, {rest}")
8947                }
8948            } else {
8949                format!("WITH {shadows} {}", query.sql)
8950            }
8951        };
8952        Ok((sql, params))
8953    }
8954
8955    /// Rows, coverage, and local revision from one SQLite read snapshot.
8956    /// §7.5 atomic snapshot read. An `owner` records a failure in
8957    /// `diagnostics_snapshot().query_failures` until its next successful read.
8958    pub fn query_snapshot(
8959        &mut self,
8960        sql: &str,
8961        params: &[QueryValue],
8962        coverage: &[WindowCoverage],
8963        owner: Option<QueryOwner<'_>>,
8964    ) -> Result<QuerySnapshot, String> {
8965        let result = snapshot_connection(&self.conn, Some(&self.schema), sql, params, coverage);
8966        if let Some(owner) = owner {
8967            self.record_query_read(owner, result.as_ref().err());
8968        }
8969        result.map_err(|failure| failure.to_string())
8970    }
8971
8972    /// §7.6: record the outcome of one owned snapshot read, including reads a
8973    /// host ran on a separate connection. A success removes the owner's entry;
8974    /// an identical failure leaves it unchanged; a changed failure moves last.
8975    pub fn record_query_read(&mut self, owner: QueryOwner<'_>, failure: Option<&QueryReadFailure>) {
8976        let position = self
8977            .query_failures
8978            .iter()
8979            .position(|entry| entry.id == owner.id);
8980        let Some(failure) = failure else {
8981            if let Some(index) = position {
8982                self.query_failures.remove(index);
8983            }
8984            return;
8985        };
8986        let tables: Vec<String> = BTreeSet::from_iter(owner.tables.iter().copied())
8987            .into_iter()
8988            .map(str::to_owned)
8989            .collect();
8990        let code = failure.code.unwrap_or("client.query_failed").to_owned();
8991        if position.is_some_and(|index| {
8992            let entry = &self.query_failures[index];
8993            entry.tables == tables && entry.code == code && entry.sqlite_code == failure.sqlite_code
8994        }) {
8995            return;
8996        }
8997        if let Some(index) = position {
8998            self.query_failures.remove(index);
8999        }
9000        self.query_failures.push(DiagnosticQueryFailure {
9001            id: owner.id.to_owned(),
9002            tables,
9003            code,
9004            sqlite_code: failure.sqlite_code,
9005            at_ms: self.clock_now_ms(),
9006        });
9007        if self.query_failures.len() > MAX_DIAGNOSTIC_QUERY_FAILURES {
9008            self.query_failures.remove(0);
9009        }
9010    }
9011
9012    // -- request building ---------------------------------------------------------
9013
9014    fn build_request(&self, url_capable: bool) -> Result<(Message, RequestMeta), Box<SyncOutcome>> {
9015        #[cfg(feature = "bench-internals")]
9016        let _phase = self.benchmark_phases.start(Phase::RequestPrepare);
9017        let log_epoch = self.get_meta(LOG_EPOCH_KEY).map_err(|message| {
9018            Box::new(SyncOutcome::Failed {
9019                error_code: "storage.failed".into(),
9020                message,
9021                details: None,
9022                recommended_action: None,
9023            })
9024        })?;
9025        let max_commits = self.limits.max_push_commits_per_request;
9026        let max_ops = self
9027            .limits
9028            .max_push_operations_per_request
9029            .unwrap_or(PUSH_OPS_PER_REQUEST);
9030        let byte_cap = self.limits.max_push_request_bytes;
9031        // §4.2/§5.4: bit 3 is advertised iff the transport can fetch a
9032        // bare URL — capability negotiation, decided per transport.
9033        let accept = self.limits.accept.unwrap_or(if url_capable {
9034            DEFAULT_ACCEPT | ACCEPT_SIGNED_URLS
9035        } else {
9036            DEFAULT_ACCEPT
9037        });
9038        let storage_failed = |message: String| {
9039            Box::new(SyncOutcome::Failed {
9040                error_code: "storage.failed".into(),
9041                message,
9042                details: None,
9043                recommended_action: None,
9044            })
9045        };
9046        let header = Frame::ReqHeader {
9047            client_id: self.client_id.clone(),
9048            schema_version: self.schema.version,
9049            log_epoch: log_epoch.clone(),
9050            outbox_id: self.get_meta(OUTBOX_ID_KEY).map_err(storage_failed)?,
9051        };
9052        // §1.5: the lead frames are REQ_HEADER plus the optional ROUND_FAILURE,
9053        // which stays ahead of every push, pull, unit and progress frame; the
9054        // byte-capacity probes below measure this exact sequence.
9055        let mut lead = vec![header];
9056        lead.extend(
9057            self.round_failure
9058                .iter()
9059                .map(|code| Frame::RoundFailure { code: code.clone() }),
9060        );
9061        // §2.1: a replica without an epoch holds nothing bound to one.
9062        if log_epoch.is_none() {
9063            lead.push(Frame::AdoptEpoch);
9064        }
9065        let registered: Vec<UnitRecord> = self
9066            .stored(load_units(&self.conn))
9067            .map_err(storage_failed)?
9068            .into_iter()
9069            .filter(|unit| unit.status == UnitStatus::Active)
9070            .collect();
9071        let registration_digest = ssp2::registration::registration_digest(
9072            registered
9073                .iter()
9074                .map(|unit| scope_pairs(&unit.scopes))
9075                .collect::<Vec<_>>()
9076                .iter()
9077                .map(Vec::as_slice),
9078        );
9079        let echo_digest = self
9080            .get_meta(ECHO_DIGEST_KEY)
9081            .map_err(storage_failed)?
9082            .filter(|hex| !hex.is_empty())
9083            .map(|hex| {
9084                crate::values::hex_to_bytes(&hex)
9085                    .ok()
9086                    .and_then(|bytes| <[u8; 32]>::try_from(bytes).ok())
9087                    .ok_or_else(|| {
9088                        "sync.local_corrupt: persisted echo digest is invalid".to_owned()
9089                    })
9090            })
9091            .transpose()
9092            .map_err(storage_failed)?;
9093        let pull = Frame::PullHeader {
9094            limit_commits: self.limits.limit_commits.unwrap_or(0),
9095            limit_snapshot_rows: self.limits.limit_snapshot_rows.unwrap_or(0),
9096            max_snapshot_pages: self.limits.max_snapshot_pages.unwrap_or(0),
9097            accept,
9098            cursor: self
9099                .stored(replica_cursor(&self.conn))
9100                .map_err(storage_failed)?,
9101            registration_digest,
9102            echo_digest,
9103        };
9104        let registration_digest = bytes_to_hex(&registration_digest);
9105        // §4.1: the list travels when it changed since the server stored it,
9106        // after `unregistered` and after a reset (both clear the stored digest).
9107        let travels = self
9108            .get_meta(REGISTERED_DIGEST_KEY)
9109            .map_err(storage_failed)?
9110            .as_deref()
9111            != Some(registration_digest.as_str());
9112        let mut sub_frames: Vec<Frame> = Vec::new();
9113        if travels {
9114            sub_frames.extend(registered.iter().map(|unit| Frame::Unit {
9115                scopes: scope_pairs(&unit.scopes),
9116            }));
9117        }
9118        // §4.3: one PROGRESS per catching-up unit, in registration order, each
9119        // followed by its RESTRICT while the unit holds a restriction.
9120        for unit in &registered {
9121            let Some(cursor) = unit.cursor else {
9122                continue;
9123            };
9124            sub_frames.push(Frame::Progress {
9125                id: unit.id.clone(),
9126                cursor,
9127                bootstrap_state: unit.bootstrap_state.clone().map(RawJson),
9128            });
9129            sub_frames.extend(
9130                unit.restriction
9131                    .as_ref()
9132                    .map(|restriction| Frame::Restrict {
9133                        cursor: restriction.cursor,
9134                        tables: restriction.tables.clone(),
9135                    }),
9136            );
9137        }
9138        // The fixed frames (order-independent size) and the header+pull probe
9139        // both encode canonically, so the byte budget is the exact wire size.
9140        let fixed_bytes = match byte_cap {
9141            Some(_) => {
9142                let mut frames = lead.clone();
9143                frames.push(pull.clone());
9144                frames.extend(sub_frames.iter().cloned());
9145                encode_message(&Message {
9146                    wire_version: WIRE_VERSION,
9147                    msg_kind: MsgKind::Request,
9148                    frames,
9149                })
9150                .len()
9151            }
9152            None => 0,
9153        };
9154        if let Some(cap) = byte_cap {
9155            if fixed_bytes > cap {
9156                return Err(Self::push_capacity_outcome("bytes", cap, fixed_bytes, None));
9157            }
9158        }
9159        let base_bytes = match byte_cap {
9160            Some(_) => {
9161                let mut frames = lead.clone();
9162                frames.push(pull.clone());
9163                encode_message(&Message {
9164                    wire_version: WIRE_VERSION,
9165                    msg_kind: MsgKind::Request,
9166                    frames,
9167                })
9168                .len()
9169            }
9170            None => 0,
9171        };
9172        // §8.8: a `pull` round carries no commit and defers none; a `through`
9173        // round pushes and defers only its prefix.
9174        let pushable = self.pushable_commits();
9175        let total_outbox = if log_epoch.is_some() { pushable } else { 0 };
9176        let mut push_frames: Vec<Frame> = Vec::new();
9177        let mut pushed_ids = Vec::new();
9178        let mut ops_in_request = 0usize;
9179        let mut bytes_in_request = 0usize;
9180        // §2.1: an epoch-less request withholds the whole outbox until the
9181        // next, epoch-bound request.
9182        let mut deferred_commits = pushable - total_outbox;
9183        // §7.2.2: a pending replacement is held; the push stops before it
9184        // without deferring work.
9185        let held: HashSet<String> = self
9186            .prepare_replacements()
9187            .map_err(storage_failed)?
9188            .into_iter()
9189            .filter_map(|decision| decision.replacement)
9190            .collect();
9191        #[cfg(feature = "bench-internals")]
9192        let outbox_phase = self.benchmark_phases.start(Phase::OutboxEncode);
9193        for (index, commit) in self.outbox.iter().take(total_outbox).enumerate() {
9194            if held.contains(&commit.client_commit_id) {
9195                break;
9196            }
9197            // §6.1/§7.1: the commit-count and operation caps are hard. A
9198            // first commit over the operation cap is a typed capacity error
9199            // and stays queued; a later one defers with the complete suffix.
9200            if max_commits.is_some_and(|cap| push_frames.len() >= cap) {
9201                deferred_commits = total_outbox - index;
9202                break;
9203            }
9204            if ops_in_request + commit.ops.len() > max_ops {
9205                if push_frames.is_empty() {
9206                    return Err(Self::push_capacity_outcome(
9207                        "operations",
9208                        max_ops,
9209                        commit.ops.len(),
9210                        Some(commit.client_commit_id.as_str()),
9211                    ));
9212                }
9213                deferred_commits = total_outbox - index;
9214                break;
9215            }
9216            // §7.1 chained base: the commit waits for the change of the commit
9217            // it chains on, which supplies its rebased version.
9218            if self.outbox[..index]
9219                .iter()
9220                .flat_map(|earlier| &earlier.ops)
9221                .any(|earlier| commit.ops.iter().any(|op| chains_on(earlier, op)))
9222            {
9223                deferred_commits = total_outbox - index;
9224                break;
9225            }
9226            let operations = commit
9227                .ops
9228                .iter()
9229                .map(|op| {
9230                    let payload = match self
9231                        .schema
9232                        .table(&op.table)
9233                        .and_then(|table| Some((table, op.presented_values(table)?)))
9234                    {
9235                        Some((table, values)) => {
9236                            // §0: outbox entries encode at send time with the
9237                            // current codec (validated at mutate()). §6.1: the
9238                            // values map's keys are the sparse presence set; an
9239                            // insert-intent operation presents every column (§7.1).
9240                            // §5.11: encrypted columns are encrypted here, with
9241                            // an absent key-id selector read from the stored row.
9242                            // `sync_inner` runs `drop_unencodable_outbox` first,
9243                            // so an encrypt failure cannot reach this encode; the
9244                            // author seam validated every other failure.
9245                            let fallback =
9246                                self.stored_key_fallback(table, &op.row_id)
9247                                    .map_err(|message| {
9248                                        Box::new(SyncOutcome::Failed {
9249                                            error_code: "storage.failed".into(),
9250                                            message,
9251                                            details: None,
9252                                            recommended_action: None,
9253                                        })
9254                                    })?;
9255                            encode_sparse_row_json(
9256                                table,
9257                                &op.row_id,
9258                                &values,
9259                                &self.encryption,
9260                                fallback.as_ref(),
9261                            )
9262                            .ok()
9263                        }
9264                        None => None,
9265                    };
9266                    Ok(ssp2::model::Operation {
9267                        table: op.table.clone(),
9268                        row_id: op.row_id.clone(),
9269                        op: if op.upsert { Op::Upsert } else { Op::Delete },
9270                        base_version: op.base_version,
9271                        payload,
9272                    })
9273                })
9274                .collect::<Result<Vec<_>, Box<SyncOutcome>>>()?;
9275            // §6.3.2, §7.1: the commit's outbox sequence.
9276            let client_seq = self
9277                .conn
9278                .prepare_cached("SELECT seq FROM _syncular_outbox WHERE commit_id = ?1")
9279                .and_then(|mut statement| {
9280                    statement.query_row([&commit.client_commit_id], |row| row.get(0))
9281                })
9282                .map_err(|error| {
9283                    storage_failed(Self::sqlite_failure(&self.storage_failure, error))
9284                })?;
9285            let frame = Frame::PushCommit {
9286                client_commit_id: commit.client_commit_id.clone(),
9287                client_seq,
9288                operations,
9289            };
9290            let frame_bytes = match byte_cap {
9291                Some(_) => {
9292                    let mut frames = lead.clone();
9293                    frames.push(frame.clone());
9294                    frames.push(pull.clone());
9295                    encode_message(&Message {
9296                        wire_version: WIRE_VERSION,
9297                        msg_kind: MsgKind::Request,
9298                        frames,
9299                    })
9300                    .len()
9301                        - base_bytes
9302                }
9303                None => 0,
9304            };
9305            // The head is always encoded so the caller can report the full
9306            // projected request size; a later commit defers once it no longer
9307            // fits.
9308            if let Some(cap) = byte_cap {
9309                if !push_frames.is_empty() && fixed_bytes + bytes_in_request + frame_bytes > cap {
9310                    deferred_commits = total_outbox - index;
9311                    break;
9312                }
9313            }
9314            push_frames.push(frame);
9315            pushed_ids.push(commit.client_commit_id.clone());
9316            ops_in_request += commit.ops.len();
9317            bytes_in_request += frame_bytes;
9318        }
9319        #[cfg(feature = "bench-internals")]
9320        drop(outbox_phase);
9321        if let Some(cap) = byte_cap {
9322            if fixed_bytes + bytes_in_request > cap {
9323                // The head alone does not fit this budget; the commit stays
9324                // queued and no transport round is attempted.
9325                let blocked = if push_frames.is_empty() {
9326                    None
9327                } else {
9328                    self.outbox.first().map(|c| c.client_commit_id.as_str())
9329                };
9330                return Err(Self::push_capacity_outcome(
9331                    "bytes",
9332                    cap,
9333                    fixed_bytes + bytes_in_request,
9334                    blocked,
9335                ));
9336            }
9337        }
9338        let mut frames = lead;
9339        frames.extend(push_frames);
9340        frames.push(pull);
9341        frames.extend(sub_frames);
9342        let message = Message {
9343            wire_version: WIRE_VERSION,
9344            msg_kind: MsgKind::Request,
9345            frames,
9346        };
9347        Ok((
9348            message,
9349            RequestMeta {
9350                pushed_ids,
9351                registration_digest,
9352                accept,
9353                deferred_commits,
9354                applied: BTreeMap::new(),
9355                deferred: BTreeSet::new(),
9356            },
9357        ))
9358    }
9359
9360    /// §7.1: a configured push capacity limit cannot carry this request.
9361    fn push_capacity_outcome(
9362        kind: &str,
9363        limit: usize,
9364        size: usize,
9365        client_commit_id: Option<&str>,
9366    ) -> Box<SyncOutcome> {
9367        let mut details = Map::new();
9368        details.insert("kind".to_owned(), Value::from(kind));
9369        details.insert("limit".to_owned(), Value::from(limit as u64));
9370        details.insert("size".to_owned(), Value::from(size as u64));
9371        if let Some(id) = client_commit_id {
9372            details.insert("clientCommitId".to_owned(), Value::from(id));
9373        }
9374        Box::new(SyncOutcome::Failed {
9375            error_code: "client.push_request_too_large".into(),
9376            message: "the push request exceeds a configured capacity limit".into(),
9377            details: Some(Value::Object(details)),
9378            recommended_action: None,
9379        })
9380    }
9381
9382    // -- sync -------------------------------------------------------------------
9383
9384    /// Cloneable observation handle; no client lock is needed to read it.
9385    pub fn progress(&self) -> ProgressObserver {
9386        self.progress.clone()
9387    }
9388
9389    pub fn sync(&mut self, transport: &mut dyn Transport) -> SyncOutcome {
9390        self.sync_bounded(transport, None)
9391    }
9392
9393    /// One round; `idle_bound` is the idle drive's round bound (§7.8).
9394    fn sync_bounded(
9395        &mut self,
9396        transport: &mut dyn Transport,
9397        idle_bound: Option<(u64, u32)>,
9398    ) -> SyncOutcome {
9399        let mut prepared = match self.prepare_sync_round(transport.supports_url_fetch()) {
9400            Ok(prepared) => prepared,
9401            Err(outcome) => return *outcome,
9402        };
9403        prepared.idle_bound = idle_bound;
9404        // The round's network deadline rides `PreparedSyncRound` and is scoped
9405        // to each exchange, so uploads, continuations, the main request, and
9406        // every segment fetch share one monotonic anchor without leaving
9407        // deadline state on a reused transport.
9408        let mut next = prepared;
9409        loop {
9410            match self.apply_sync_round(next.exchange(transport)) {
9411                crate::AppliedSyncRound::Continue(prepared) => next = prepared,
9412                crate::AppliedSyncRound::Complete {
9413                    outcome, controls, ..
9414                } => {
9415                    if !self.transport_closed() {
9416                        for text in controls {
9417                            let _ = transport.realtime_send(&text);
9418                        }
9419                    } else {
9420                        self.disconnect_realtime(transport);
9421                    }
9422                    return outcome;
9423                }
9424            }
9425        }
9426    }
9427
9428    fn finish_sync_round(
9429        &mut self,
9430        started_at_ms: i64,
9431        attempt: u64,
9432        mut outcome: SyncOutcome,
9433    ) -> SyncOutcome {
9434        if let SyncOutcome::Failed {
9435            error_code,
9436            message,
9437            details,
9438            ..
9439        } = &mut outcome
9440        {
9441            if let Some((failure, code)) = self
9442                .storage_failure
9443                .borrow()
9444                .as_ref()
9445                .and_then(|failure| failure.code.map(|code| (failure, code)))
9446            {
9447                *error_code = code.to_owned();
9448                *message = match code {
9449                    "client.storage_busy" => "local SQLite storage is busy",
9450                    "client.storage_full" => "local SQLite storage is full",
9451                    "client.storage_io" => "local SQLite storage I/O failed",
9452                    "client.storage_corrupt" => "local SQLite storage is corrupt",
9453                    _ => unreachable!("unrecognized classified storage failure"),
9454                }
9455                .to_owned();
9456                *details = failure.details();
9457            }
9458        }
9459        let details = match &outcome {
9460            SyncOutcome::Failed { details, .. } => details.as_ref(),
9461            _ => None,
9462        };
9463        let cause_kind = details
9464            .and_then(|details| details.get("causeKind"))
9465            .and_then(Value::as_str)
9466            .and_then(|cause| match cause {
9467                "network" => Some(crate::TransportCauseKind::Network),
9468                "connect" => Some(crate::TransportCauseKind::Connect),
9469                "tls" => Some(crate::TransportCauseKind::Tls),
9470                "io" => Some(crate::TransportCauseKind::Io),
9471                "request" => Some(crate::TransportCauseKind::Request),
9472                "protocol" => Some(crate::TransportCauseKind::Protocol),
9473                "timeout" => Some(crate::TransportCauseKind::Timeout),
9474                "round_deadline" => Some(crate::TransportCauseKind::RoundDeadline),
9475                "aborted" => Some(crate::TransportCauseKind::Aborted),
9476                "body" => Some(crate::TransportCauseKind::Body),
9477                "status" => Some(crate::TransportCauseKind::Status),
9478                "redirect" => Some(crate::TransportCauseKind::Redirect),
9479                "unknown" => Some(crate::TransportCauseKind::Unknown),
9480                _ => None,
9481            });
9482        let http_status = if matches!(
9483            cause_kind,
9484            Some(
9485                crate::TransportCauseKind::Status
9486                    | crate::TransportCauseKind::Body
9487                    | crate::TransportCauseKind::Redirect
9488            )
9489        ) {
9490            details
9491                .and_then(|details| details.get("httpStatus"))
9492                .and_then(Value::as_f64)
9493                .filter(|status| status.fract() == 0.0 && (100.0..=599.0).contains(status))
9494                .map(|status| status as u16)
9495        } else {
9496            None
9497        };
9498        let retry_delay_ms = self.round_retry_delay_ms;
9499        self.progress.update(|p| match &outcome {
9500            SyncOutcome::Ok(report) | SyncOutcome::BudgetExhausted(report)
9501                if report.failed.is_empty() =>
9502            {
9503                p.state = ProgressState::Complete
9504            }
9505            SyncOutcome::Ok(_) | SyncOutcome::BudgetExhausted(_) => {
9506                p.state = ProgressState::Failed;
9507                p.error_code = Some("sync.scope_revoked".into());
9508            }
9509            SyncOutcome::Failed { error_code, .. } => {
9510                p.state = ProgressState::Failed;
9511                p.error_code = Some(Self::diagnostic_code(error_code));
9512                p.cause_kind = cause_kind;
9513                p.http_status = http_status;
9514                p.retry_delay_ms = retry_delay_ms;
9515            }
9516            SyncOutcome::RealtimeUnavailable { .. } => {
9517                p.state = ProgressState::Failed;
9518                p.error_code = Some(REALTIME_UNAVAILABLE_CODE.to_owned());
9519                p.retry_delay_ms = retry_delay_ms;
9520            }
9521        });
9522        let completed_at_ms = self.clock_now_ms();
9523        self.last_round = Some(match &outcome {
9524            SyncOutcome::Ok(report) | SyncOutcome::BudgetExhausted(report) => DiagnosticLastRound {
9525                epoch: self.epoch.clone(),
9526                attempt,
9527                status: "succeeded".to_owned(),
9528                started_at_ms,
9529                completed_at_ms,
9530                duration_ms: completed_at_ms.saturating_sub(started_at_ms).max(0),
9531                counters: Some(DiagnosticRoundCounters {
9532                    pushed: report.pushed,
9533                    applied: report.applied.len(),
9534                    rejected: report.rejected.len(),
9535                    retryable: report.retryable.len(),
9536                    conflicts: report.conflicts,
9537                    commits_applied: report.commits_applied,
9538                    segment_rows_applied: report.segment_rows_applied,
9539                    bootstrapping: report.bootstrapping.len(),
9540                    resets: report.resets.len(),
9541                    revoked: report.revoked.len(),
9542                    failed: report.failed.len(),
9543                    deferred_commits: report.deferred_commits,
9544                }),
9545                error_code: None,
9546                cause_kind: None,
9547                http_status: None,
9548            },
9549            SyncOutcome::Failed { error_code, .. } => DiagnosticLastRound {
9550                epoch: self.epoch.clone(),
9551                attempt,
9552                status: "failed".to_owned(),
9553                started_at_ms,
9554                completed_at_ms,
9555                duration_ms: completed_at_ms.saturating_sub(started_at_ms).max(0),
9556                counters: None,
9557                error_code: Some(Self::diagnostic_code(error_code)),
9558                cause_kind,
9559                http_status,
9560            },
9561            SyncOutcome::RealtimeUnavailable { .. } => DiagnosticLastRound {
9562                epoch: self.epoch.clone(),
9563                attempt,
9564                status: "failed".to_owned(),
9565                started_at_ms,
9566                completed_at_ms,
9567                duration_ms: completed_at_ms.saturating_sub(started_at_ms).max(0),
9568                counters: None,
9569                error_code: Some(REALTIME_UNAVAILABLE_CODE.to_owned()),
9570                cause_kind: None,
9571                http_status: None,
9572            },
9573        });
9574        outcome
9575    }
9576
9577    /// Capture one request on the client owner. Mutations made after this
9578    /// call remain in the outbox for a later round; no network I/O occurs here.
9579    pub fn prepare_sync_round(
9580        &mut self,
9581        url_capable: bool,
9582    ) -> Result<crate::PreparedSyncRound, Box<SyncOutcome>> {
9583        if self.transport_closed() {
9584            return Err(Box::new(SyncOutcome::Failed {
9585                error_code: "sync.offline".into(),
9586                message: "transport gate is closed".into(),
9587                details: None,
9588                recommended_action: None,
9589            }));
9590        }
9591        if self.active_round.is_some() || self.fence_round.is_some() {
9592            return Err(Box::new(SyncOutcome::Failed {
9593                error_code: "client.round_in_progress".into(),
9594                message: "a sync round is already in flight".into(),
9595                details: None,
9596                recommended_action: None,
9597            }));
9598        }
9599        self.storage_failure.borrow_mut().take();
9600        let attempt = self.progress.start(&self.epoch);
9601        self.round_retry_delay_ms = None;
9602        let started_at_ms = self.clock_now_ms();
9603        let prepared = (|| {
9604            if self.stopped {
9605                return Err(Box::new(SyncOutcome::Ok(SyncReport {
9606                    schema_floor: self.schema_floor.clone(),
9607                    ..SyncReport::default()
9608                })));
9609            }
9610            if self.security_preflight {
9611                return Err(Box::new(SyncOutcome::Failed {
9612                    error_code: SECURITY_PREFLIGHT_REQUIRED_CODE.into(),
9613                    message: "security preflight must complete before syncing".into(),
9614                    details: None,
9615                    recommended_action: None,
9616                }));
9617            }
9618            self.set_sync_needed(false, false);
9619            self.drain_pending_evictions()
9620                .and_then(|_| self.drop_incompatible_outbox())
9621                .and_then(|_| self.drop_unencodable_outbox(true, None))
9622                .map_err(|message| {
9623                    Box::new(SyncOutcome::Failed {
9624                        error_code: "storage.failed".into(),
9625                        message,
9626                        details: None,
9627                        recommended_action: None,
9628                    })
9629                })?;
9630            // §5.11: reveal rows sealed under a key the keyring gained since.
9631            self.reveal_sealed_rows().map_err(|error| {
9632                Box::new(SyncOutcome::Failed {
9633                    error_code: error.code,
9634                    message: error.message,
9635                    details: error.details,
9636                    recommended_action: None,
9637                })
9638            })?;
9639            let has_log_epoch = self.get_meta(LOG_EPOCH_KEY).map_err(|message| {
9640                Box::new(SyncOutcome::Failed {
9641                    error_code: "storage.failed".into(),
9642                    message,
9643                    details: None,
9644                    recommended_action: None,
9645                })
9646            })?;
9647            let mut uploads = if has_log_epoch.is_some()
9648                && matches!(
9649                    self.transport_gate,
9650                    crate::TransportGate::Open | crate::TransportGate::Through(_)
9651                )
9652                && self.schema_has_blobs()
9653            {
9654                self.pending_blob_uploads().map_err(|e| {
9655                    Box::new(SyncOutcome::Failed {
9656                        error_code: e.code,
9657                        message: e.message,
9658                        details: e.details,
9659                        recommended_action: None,
9660                    })
9661                })?
9662            } else {
9663                Vec::new()
9664            };
9665            // §8.8: a `through` round uploads only the blobs its prefix references.
9666            if matches!(self.transport_gate, crate::TransportGate::Through(_)) {
9667                let prefix = Value::Array(
9668                    self.outbox
9669                        .iter()
9670                        .take(self.pushable_commits())
9671                        .map(|commit| Value::String(commit.client_commit_id.clone()))
9672                        .collect(),
9673                );
9674                let referenced = self
9675                    .conn
9676                    .prepare(
9677                        "SELECT blob_id FROM _syncular_blob_commit_refs
9678                          WHERE commit_id IN (SELECT value FROM json_each(?1))",
9679                    )
9680                    .and_then(|mut statement| {
9681                        statement
9682                            .query_map([prefix.to_string()], |row| row.get::<_, String>(0))?
9683                            .collect::<Result<HashSet<_>, _>>()
9684                    })
9685                    .map_err(|error| {
9686                        Box::new(SyncOutcome::Failed {
9687                            error_code: "storage.failed".into(),
9688                            message: Self::sqlite_failure(&self.storage_failure, error),
9689                            details: None,
9690                            recommended_action: None,
9691                        })
9692                    })?;
9693                uploads.retain(|upload| referenced.contains(&upload.id));
9694            }
9695            if self.realtime_state != RealtimeState::Connected
9696                && self.realtime_policy == RealtimePolicy::Required
9697            {
9698                let retry_delay_ms = self.schedule_background_retry();
9699                self.realtime_retry_delay_ms = Some(retry_delay_ms);
9700                return Err(Box::new(SyncOutcome::RealtimeUnavailable {
9701                    state: self.realtime_state,
9702                    reason_code: self.realtime_reason_code.clone(),
9703                    retry_delay_ms,
9704                }));
9705            }
9706            let (message, mut meta) = self.build_request(url_capable)?;
9707            let units = self.stored(load_units(&self.conn)).map_err(|message| {
9708                Box::new(SyncOutcome::Failed {
9709                    error_code: "storage.failed".into(),
9710                    message,
9711                    details: None,
9712                    recommended_action: None,
9713                })
9714            })?;
9715            for unit in &units {
9716                let applied =
9717                    self.stored(applied_rows(&self.conn, &unit.id))
9718                        .map_err(|message| {
9719                            Box::new(SyncOutcome::Failed {
9720                                error_code: "storage.failed".into(),
9721                                message,
9722                                details: None,
9723                                recommended_action: None,
9724                            })
9725                        })?;
9726                if !applied.is_empty() {
9727                    meta.applied.insert(unit.id.clone(), applied);
9728                }
9729            }
9730            // §7.1: the send-attempt marker of every commit the request
9731            // carries commits before the round leaves the owner.
9732            let pushed: Vec<String> = message
9733                .frames
9734                .iter()
9735                .filter_map(|frame| match frame {
9736                    Frame::PushCommit { client_seq, .. } => Some(client_seq.to_string()),
9737                    _ => None,
9738                })
9739                .collect();
9740            if !pushed.is_empty() {
9741                self.conn
9742                    .execute(
9743                        &format!(
9744                            "UPDATE _syncular_outbox SET attempted = 1 WHERE seq IN ({})",
9745                            pushed.join(",")
9746                        ),
9747                        [],
9748                    )
9749                    .map_err(|error| {
9750                        Box::new(SyncOutcome::Failed {
9751                            error_code: "storage.failed".into(),
9752                            message: Self::sqlite_failure(&self.storage_failure, error),
9753                            details: None,
9754                            recommended_action: None,
9755                        })
9756                    })?;
9757            }
9758            let id = uuid::Uuid::new_v4();
9759            self.active_round = Some((id, started_at_ms, attempt));
9760            let phase = if uploads.is_empty() {
9761                crate::round::RoundPhase::Sync
9762            } else {
9763                crate::round::RoundPhase::UploadGrant
9764            };
9765            Ok(crate::PreparedSyncRound {
9766                id,
9767                started_at_ms,
9768                attempt,
9769                message,
9770                meta,
9771                uploads: uploads.into(),
9772                phase,
9773                encoded: None,
9774                continuation: None,
9775                completed: None,
9776                realtime: self.realtime_state == RealtimeState::Connected,
9777                // §5.5: the owning unit's scope map, each value a one-element list.
9778                scopes: units
9779                    .into_iter()
9780                    .map(|unit| {
9781                        (
9782                            unit.id,
9783                            canonical_scope_json(&unit_scope_lists(&unit.scopes)),
9784                        )
9785                    })
9786                    .collect(),
9787                #[cfg(feature = "bench-internals")]
9788                benchmark_phases: self.benchmark_phases.clone(),
9789                progress: self.progress.clone(),
9790                fixed_now: self
9791                    .now_ms
9792                    .as_ref()
9793                    .map(|clock| clock.load(std::sync::atomic::Ordering::Relaxed)),
9794                round_deadline_at: None,
9795                idle_bound: None,
9796                network_started_at: None,
9797            })
9798        })();
9799        prepared
9800            .map_err(|outcome| Box::new(self.finish_sync_round(started_at_ms, attempt, *outcome)))
9801    }
9802
9803    /// Discard the reply of an old authorization or registration context. Its
9804    /// submitted commits stay durable and can be retried with the same ids.
9805    /// §7.6: an abandoned in-flight round ends its attempt as failed.
9806    pub fn cancel_sync_round(&mut self) {
9807        self.fence_round = None;
9808        if let Some((_, started_at_ms, attempt)) = self.active_round.take() {
9809            // A storage failure recorded since the round started is not its cause.
9810            self.storage_failure.borrow_mut().take();
9811            self.finish_sync_round(
9812                started_at_ms,
9813                attempt,
9814                SyncOutcome::Failed {
9815                    error_code: "client.round_cancelled".into(),
9816                    message: "sync round belongs to a released client context".into(),
9817                    details: None,
9818                    recommended_action: None,
9819                },
9820            );
9821        }
9822    }
9823
9824    /// Apply captured network results on the owner, preserving all normal
9825    /// version, schema, content-address and cursor checks. No network I/O.
9826    pub fn apply_sync_round(
9827        &mut self,
9828        completed: crate::CompletedSyncRound,
9829    ) -> crate::AppliedSyncRound {
9830        let mut prepared = completed.prepared;
9831        if self.active_round.map(|(id, ..)| id) != Some(prepared.id) || self.security_preflight {
9832            return crate::AppliedSyncRound::Complete {
9833                outcome: SyncOutcome::Failed {
9834                    error_code: "client.round_cancelled".into(),
9835                    message: "sync round belongs to a released client context".into(),
9836                    details: None,
9837                    recommended_action: None,
9838                },
9839                controls: Vec::new(),
9840                more: false,
9841                bootstrap_advanced: false,
9842            };
9843        }
9844        self.storage_failure.borrow_mut().take();
9845        let (response, mut downloads, transport_failed) = match completed.exchange {
9846            crate::round::ExchangeResult::Upload { id, result } => {
9847                let result = match result {
9848                    // §5.9.7: a non-retryable server refusal (`blob.too_large`)
9849                    // is the body's final outcome. The commits naming it take
9850                    // the incompatible-commit path with the server's code and
9851                    // leave this round's request; the round continues.
9852                    Err(error)
9853                        if error
9854                            .details
9855                            .as_ref()
9856                            .and_then(|details| details.get("retryable"))
9857                            == Some(&Value::Bool(false)) =>
9858                    {
9859                        self.conn
9860                            .prepare(
9861                                "SELECT commit_id FROM _syncular_blob_commit_refs WHERE blob_id = ?",
9862                            )
9863                            .and_then(|mut statement| {
9864                                statement
9865                                    .query_map(rusqlite::params![id], |row| row.get::<_, String>(0))?
9866                                    .collect::<Result<HashSet<_>, _>>()
9867                            })
9868                            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
9869                            .and_then(|refused| {
9870                                let commits = self
9871                                    .outbox
9872                                    .iter()
9873                                    .filter(|commit| refused.contains(&commit.client_commit_id))
9874                                    .cloned()
9875                                    .collect::<Vec<_>>();
9876                                if !commits.is_empty() {
9877                                    self.drop_outbox_commits(&commits, &error.code, &error.message)?;
9878                                }
9879                                prepared.message.frames.retain(|frame| {
9880                                    !matches!(frame, Frame::PushCommit { client_commit_id, .. }
9881                                        if refused.contains(client_commit_id))
9882                                });
9883                                prepared.meta.pushed_ids.retain(|id| !refused.contains(id));
9884                                prepared.continuation = Some(crate::round::RoundPhase::UploadGrant);
9885                                Ok(())
9886                            })
9887                            .map_err(|message| TransportError::new("client.failed", message))
9888                    }
9889                    result => result,
9890                };
9891                let result = result.and_then(|()| {
9892                    self.conn
9893                        .execute(
9894                            "DELETE FROM _syncular_blob_uploads WHERE blob_id = ?",
9895                            rusqlite::params![id],
9896                        )
9897                        .map(|_| ())
9898                        .map_err(|error| {
9899                            TransportError::new(
9900                                "client.failed",
9901                                Self::sqlite_failure(&self.storage_failure, error),
9902                            )
9903                        })
9904                });
9905                match result {
9906                    Ok(()) => return crate::AppliedSyncRound::Continue(prepared),
9907                    Err(TransportError {
9908                        code,
9909                        message,
9910                        details,
9911                    }) => {
9912                        self.active_round = None;
9913                        if Self::unreachable_transport(&details) {
9914                            // The round's work is still owed; the host's
9915                            // connectivity resume runs it.
9916                            self.set_sync_needed(true, false);
9917                        } else if Self::retryable_failure_code(&code) {
9918                            self.schedule_background_retry();
9919                        }
9920                        let recommended_action = recommended_action_of(&details);
9921                        let outcome = self.finish_sync_round(
9922                            prepared.started_at_ms,
9923                            prepared.attempt,
9924                            SyncOutcome::Failed {
9925                                error_code: code,
9926                                message,
9927                                details,
9928                                recommended_action,
9929                            },
9930                        );
9931                        return crate::AppliedSyncRound::Complete {
9932                            outcome,
9933                            controls: Vec::new(),
9934                            more: false,
9935                            bootstrap_advanced: false,
9936                        };
9937                    }
9938                }
9939            }
9940            crate::round::ExchangeResult::Reply {
9941                response,
9942                downloads,
9943                transport_failed,
9944            } => (response, downloads, transport_failed),
9945        };
9946        self.active_round = None;
9947        let before = self.resume_tokens();
9948        let outcome = (|| {
9949            let response = match response {
9950                Ok(response) => {
9951                    // §1.5: a complete, decodable response ends the report, an
9952                    // in-band ERROR included (the server already recorded it).
9953                    self.round_failure = None;
9954                    response
9955                }
9956                Err(TransportError {
9957                    code,
9958                    message,
9959                    details,
9960                }) => {
9961                    // §1.5: the server cannot see a round whose transport
9962                    // failed or whose response never decoded, so its code rides
9963                    // the following requests. A code the frame grammar rejects
9964                    // is not reportable, and the previous code stays; the
9965                    // client-local drive timeout never goes on the wire (§7.8).
9966                    if code != "sync.idle_timeout" && ssp2::model::valid_round_failure_code(&code) {
9967                        self.round_failure = Some(code.clone());
9968                    }
9969                    // §8.8: a prefix sent without a receipt is an uncertain delivery.
9970                    if !prepared.meta.pushed_ids.is_empty()
9971                        && matches!(self.transport_gate, crate::TransportGate::Through(_))
9972                    {
9973                        self.move_transport_gate(crate::TransportGate::Pull);
9974                    }
9975                    if transport_failed {
9976                        if prepared.realtime {
9977                            self.set_realtime_state(RealtimeState::Lost, Some(&code));
9978                        }
9979                        if let Err(message) = self.record_lease_error(&code) {
9980                            return SyncOutcome::Failed {
9981                                error_code: "storage.failed".to_owned(),
9982                                message,
9983                                details: None,
9984                                recommended_action: None,
9985                            };
9986                        }
9987                    }
9988                    if Self::retryable_failure_code(&code) && !Self::unreachable_transport(&details)
9989                    {
9990                        let delay = self.schedule_background_retry();
9991                        if prepared.realtime && transport_failed {
9992                            self.realtime_retry_delay_ms = Some(delay);
9993                        }
9994                    }
9995                    let recommended_action = recommended_action_of(&details);
9996                    return SyncOutcome::Failed {
9997                        error_code: code,
9998                        message,
9999                        details,
10000                        recommended_action,
10001                    };
10002                }
10003            };
10004            let mut outcome = self.process_response(&mut downloads, response, &prepared.meta);
10005            if let SyncOutcome::Ok(report) = &mut outcome {
10006                report.deferred_commits = prepared.meta.deferred_commits;
10007            }
10008            match &outcome {
10009                SyncOutcome::Ok(_) => self.reset_background_retry(),
10010                SyncOutcome::Failed {
10011                    error_code,
10012                    details,
10013                    ..
10014                } if Self::retryable_failure_code(error_code)
10015                    && !Self::unreachable_transport(details) =>
10016                {
10017                    self.schedule_background_retry();
10018                }
10019                _ => {}
10020            }
10021            if prepared.meta.deferred_commits > 0 {
10022                self.set_sync_needed(true, true);
10023            }
10024            self.previous_version_lifetime_check();
10025            outcome
10026        })();
10027        match &outcome {
10028            // §7.1: a unit still catching up needs another round, also when the
10029            // drive that started it ends early.
10030            SyncOutcome::Ok(report) if !report.bootstrapping.is_empty() => {
10031                self.set_sync_needed(true, false)
10032            }
10033            // The round's work is still owed; the host's connectivity resume
10034            // runs it.
10035            SyncOutcome::Failed { details, .. } if Self::unreachable_transport(details) => {
10036                self.set_sync_needed(true, false)
10037            }
10038            _ => {}
10039        }
10040        let more = !self.transport_closed()
10041            && matches!(&outcome, SyncOutcome::Ok(report)
10042                if report.schema_floor.is_none()
10043                    && (!report.bootstrapping.is_empty()
10044                        || report.commits_applied > 0
10045                        || report.segment_rows_applied > 0
10046                        || !report.resets.is_empty()
10047                        || report.deferred_commits > 0
10048                        || self.sync_needed));
10049        let bootstrap_advanced = matches!(&outcome, SyncOutcome::Ok(report) if report.segment_rows_applied > 0 && !report.bootstrapping.is_empty())
10050            && before != self.resume_tokens();
10051        crate::AppliedSyncRound::Complete {
10052            outcome: self.finish_sync_round(prepared.started_at_ms, prepared.attempt, outcome),
10053            controls: if !self.transport_closed() {
10054                downloads.controls
10055            } else {
10056                Vec::new()
10057            },
10058            more,
10059            bootstrap_advanced,
10060        }
10061    }
10062
10063    /// Every unit's resume token and applied-segment record: a bootstrap
10064    /// that advanced changes one (§4.7), also when it applied images of a
10065    /// section it deferred (§5.3, §5.6).
10066    #[allow(clippy::type_complexity)]
10067    fn resume_tokens(&self) -> Option<Vec<(String, Option<String>, Option<String>)>> {
10068        self.conn
10069            .prepare_cached(
10070                "SELECT id, bootstrap_state, applied FROM _syncular_units ORDER BY rowid",
10071            )
10072            .and_then(|mut stmt| {
10073                stmt.query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))?
10074                    .collect()
10075            })
10076            .ok()
10077    }
10078
10079    /// §7.8: one idle drive's default total deadline, the TS client's value.
10080    pub const SYNC_IDLE_TIMEOUT_MS: u64 = 60_000;
10081
10082    pub fn sync_until_idle(
10083        &mut self,
10084        transport: &mut dyn Transport,
10085        max_rounds: Option<u32>,
10086    ) -> SyncOutcome {
10087        self.sync_until_idle_with_deadline(transport, max_rounds, Some(Self::SYNC_IDLE_TIMEOUT_MS))
10088    }
10089
10090    /// As [`SyncClient::sync_until_idle`], with an explicit total deadline in
10091    /// milliseconds (`None` disables it). The deadline is checked against the
10092    /// client clock between rounds: a drive past it after a completed round
10093    /// ends as `BudgetExhausted`. Each round is bounded by `timeout_ms` on its
10094    /// own, or the transport's tighter whole-round deadline (§1.8); a round
10095    /// that reaches the drive bound fails with `sync.idle_timeout`.
10096    pub fn sync_until_idle_with_deadline(
10097        &mut self,
10098        transport: &mut dyn Transport,
10099        max_rounds: Option<u32>,
10100        timeout_ms: Option<u64>,
10101    ) -> SyncOutcome {
10102        // §7.8: an explicit budget is a strict positive round count. Zero is a
10103        // caller error, not an exhaustion.
10104        if max_rounds == Some(0) {
10105            return SyncOutcome::Failed {
10106                details: None,
10107                error_code: "sync.invalid_request".into(),
10108                message: "maxRounds must be a positive integer".into(),
10109                recommended_action: None,
10110            };
10111        }
10112        if timeout_ms.is_some_and(|ms| ms == 0 || i64::try_from(ms).is_err()) {
10113            return SyncOutcome::Failed {
10114                details: None,
10115                error_code: "sync.invalid_request".into(),
10116                message: "timeoutMs must be a positive integer".into(),
10117                recommended_action: None,
10118            };
10119        }
10120        let started_at_ms = self.clock_now_ms();
10121        let rounds = max_rounds.unwrap_or(20);
10122        let mut aggregate = SyncReport::default();
10123        // §7.2.2: decisions pending at the drive's start are evaluated when it
10124        // reaches idle.
10125        let decisions = match self.prepare_replacements() {
10126            Ok(decisions) => decisions,
10127            Err(message) => {
10128                return SyncOutcome::Failed {
10129                    details: None,
10130                    error_code: "storage.failed".into(),
10131                    message,
10132                    recommended_action: None,
10133                }
10134            }
10135        };
10136        let mut spent = 0;
10137        let mut completed = false;
10138        while spent < rounds {
10139            // §7.8: a deadline that elapsed across completed rounds ends the
10140            // drive like an exhausted round budget; the next drive resumes.
10141            if completed
10142                && timeout_ms.is_some_and(|ms| {
10143                    self.clock_now_ms() >= started_at_ms.saturating_add(ms as i64)
10144                })
10145            {
10146                return SyncOutcome::BudgetExhausted(aggregate);
10147            }
10148            let idle_bound = timeout_ms.map(|ms| (ms, spent));
10149            spent += 1;
10150            let before = self.resume_tokens();
10151            match self.sync_bounded(transport, idle_bound) {
10152                SyncOutcome::Failed {
10153                    error_code,
10154                    message,
10155                    details,
10156                    recommended_action,
10157                } => {
10158                    return SyncOutcome::Failed {
10159                        details,
10160                        error_code,
10161                        message,
10162                        recommended_action,
10163                    };
10164                }
10165                outcome @ SyncOutcome::RealtimeUnavailable { .. } => return outcome,
10166                SyncOutcome::BudgetExhausted(_) => {
10167                    unreachable!("sync() never exhausts a round budget")
10168                }
10169                SyncOutcome::Ok(report) => {
10170                    completed = true;
10171                    if max_rounds.is_none()
10172                        && report.segment_rows_applied > 0
10173                        && !report.bootstrapping.is_empty()
10174                        && before != self.resume_tokens()
10175                    {
10176                        spent = 0;
10177                    }
10178                    // TS parity: a closed transport or a schema floor ends
10179                    // the loop. The latest round still merges first.
10180                    let stop = self.transport_closed() || report.schema_floor.is_some();
10181                    aggregate.merge(&report);
10182                    // §4.5: pull again whenever the response contained
10183                    // commits or segments; resets re-bootstrap; a pending
10184                    // resume token continues paging (§4.7); deferred outbox
10185                    // commits and a raised sync-needed signal push on the next
10186                    // round.
10187                    let more = !stop
10188                        && (!report.bootstrapping.is_empty()
10189                            || report.commits_applied > 0
10190                            || report.segment_rows_applied > 0
10191                            || !report.resets.is_empty()
10192                            || report.deferred_commits > 0
10193                            || self.sync_needed);
10194                    if more {
10195                        continue;
10196                    }
10197                    // §7.2.2: a written decision runs another round, which
10198                    // pushes it.
10199                    match self.settle_replacements(&decisions, &SyncOutcome::Ok(aggregate.clone()))
10200                    {
10201                        Ok(true) if !stop => {}
10202                        Ok(_) => return SyncOutcome::Ok(aggregate),
10203                        Err(message) => {
10204                            return SyncOutcome::Failed {
10205                                details: None,
10206                                error_code: "storage.failed".into(),
10207                                message,
10208                                recommended_action: None,
10209                            }
10210                        }
10211                    }
10212                }
10213            }
10214        }
10215        // §7.8: partial success. The aggregate report is retained and the run
10216        // is explicitly not idle.
10217        SyncOutcome::BudgetExhausted(aggregate)
10218    }
10219
10220    fn process_response(
10221        &mut self,
10222        transport: &mut dyn Transport,
10223        response: Message,
10224        meta: &RequestMeta,
10225    ) -> SyncOutcome {
10226        #[cfg(feature = "bench-internals")]
10227        let _phase = self.benchmark_phases.start(Phase::ResponseApply);
10228        let mut report = SyncReport {
10229            pushed: meta.pushed_ids.len() as u32,
10230            ..SyncReport::default()
10231        };
10232        let mut rejection_details_by_commit: HashMap<String, BTreeMap<i32, RejectionDetails>> =
10233            HashMap::new();
10234        let pushed_ids = meta
10235            .pushed_ids
10236            .iter()
10237            .map(String::as_str)
10238            .collect::<HashSet<_>>();
10239        let mut last_final_push_result_id: Option<String> = None;
10240        for frame in &response.frames {
10241            match frame {
10242                Frame::PushResultDetails {
10243                    client_commit_id,
10244                    entries,
10245                } => {
10246                    let details = rejection_details_by_commit
10247                        .entry(client_commit_id.clone())
10248                        .or_default();
10249                    for entry in entries {
10250                        let parsed = match RejectionDetails::parse(&entry.details.0) {
10251                            Ok(value) => value,
10252                            Err(message) => {
10253                                return SyncOutcome::Failed {
10254                                    details: None,
10255                                    error_code: "sync.invalid_request".to_owned(),
10256                                    message,
10257                                    recommended_action: None,
10258                                };
10259                            }
10260                        };
10261                        details.insert(entry.op_index, parsed);
10262                    }
10263                }
10264                Frame::PushResult {
10265                    client_commit_id,
10266                    status,
10267                    results,
10268                    ..
10269                } if pushed_ids.contains(client_commit_id.as_str())
10270                    && Self::push_result_is_final(*status, results) =>
10271                {
10272                    last_final_push_result_id = Some(client_commit_id.clone());
10273                }
10274                _ => {}
10275            }
10276        }
10277        let mut frames = response.frames.into_iter().peekable();
10278        match frames.next() {
10279            Some(Frame::RespHeader {
10280                required_schema_version,
10281                latest_schema_version,
10282                log_epoch,
10283                reset_required,
10284            }) => {
10285                if let Some(required) = required_schema_version {
10286                    // §1.6 schema-floor response: nothing else is processed;
10287                    // stop syncing and surface the upgrade requirement.
10288                    let floor = SchemaFloor {
10289                        required_schema_version: Some(required),
10290                        latest_schema_version,
10291                    };
10292                    if let Err(message) = self.set_schema_floor(Some(floor.clone())) {
10293                        return SyncOutcome::Failed {
10294                            details: None,
10295                            error_code: "storage.failed".to_owned(),
10296                            message,
10297                            recommended_action: None,
10298                        };
10299                    }
10300                    report.schema_floor = Some(floor);
10301                    return SyncOutcome::Ok(report);
10302                }
10303                if reset_required {
10304                    if frames.next().is_some() {
10305                        return SyncOutcome::Failed {
10306                            details: None,
10307                            error_code: "client.invalid_host_response".to_owned(),
10308                            message: "log-epoch reset response contains body frames".to_owned(),
10309                            recommended_action: None,
10310                        };
10311                    }
10312                    match self.run_log_epoch_reset(&log_epoch) {
10313                        Ok(resets) => {
10314                            report.resets = resets;
10315                            return SyncOutcome::Ok(report);
10316                        }
10317                        Err(message) => {
10318                            return SyncOutcome::Failed {
10319                                details: None,
10320                                error_code: "sync.local_corrupt".to_owned(),
10321                                message,
10322                                recommended_action: None,
10323                            };
10324                        }
10325                    }
10326                }
10327                let stored_epoch = match self.get_meta(LOG_EPOCH_KEY) {
10328                    Ok(stored) => stored,
10329                    Err(message) => {
10330                        return SyncOutcome::Failed {
10331                            details: None,
10332                            error_code: "storage.failed".to_owned(),
10333                            message,
10334                            recommended_action: None,
10335                        };
10336                    }
10337                };
10338                // §2.1 adoption: the epoch is stored before any section applies.
10339                if stored_epoch.is_none() {
10340                    if let Err(message) = self.set_meta(LOG_EPOCH_KEY, &log_epoch) {
10341                        return SyncOutcome::Failed {
10342                            details: None,
10343                            error_code: "storage.failed".to_owned(),
10344                            message,
10345                            recommended_action: None,
10346                        };
10347                    }
10348                } else if stored_epoch.as_deref() != Some(log_epoch.as_str()) {
10349                    return SyncOutcome::Failed {
10350                        details: None,
10351                        error_code: "client.invalid_host_response".to_owned(),
10352                        message: "server changed logEpoch without requiring a reset".to_owned(),
10353                        recommended_action: None,
10354                    };
10355                }
10356            }
10357            _ => {
10358                return SyncOutcome::Failed {
10359                    details: None,
10360                    error_code: "sync.invalid_request".to_owned(),
10361                    message: "response does not start with RESP_HEADER".to_owned(),
10362                    recommended_action: None,
10363                };
10364            }
10365        }
10366
10367        if let Err(message) = self.begin_coalesced_apply() {
10368            return SyncOutcome::Failed {
10369                details: None,
10370                error_code: "storage.failed".into(),
10371                message,
10372                recommended_action: None,
10373            };
10374        }
10375        let mut failure: Option<(String, String, Option<String>, Option<Value>)> = None;
10376        // §4.5 client application: the units whose persisted echo a live
10377        // change must match, fixed at LIVE_START after every SUB_END persisted.
10378        let mut live: Option<(LiveStatus, String, Vec<UnitRecord>)> = None;
10379        let mut live_ended = false;
10380        while let Some(frame) = frames.next() {
10381            match frame {
10382                frame @ Frame::PushResult { .. } => {
10383                    let successful = matches!(
10384                        &frame,
10385                        Frame::PushResult {
10386                            status: PushStatus::Applied | PushStatus::Cached,
10387                            ..
10388                        }
10389                    );
10390                    let mut results = vec![frame];
10391                    if successful {
10392                        while matches!(
10393                            frames.peek(),
10394                            Some(Frame::PushResult {
10395                                status: PushStatus::Applied | PushStatus::Cached,
10396                                ..
10397                            })
10398                        ) {
10399                            if let Some(next) = frames.next() {
10400                                results.push(next);
10401                            }
10402                        }
10403                    }
10404                    if self
10405                        .handle_push_results(
10406                            &results,
10407                            &pushed_ids,
10408                            &rejection_details_by_commit,
10409                            &mut report,
10410                            last_final_push_result_id.as_deref(),
10411                        )
10412                        .is_err()
10413                    {
10414                        failure = Some((
10415                            "client.outcome_persistence_failed".to_owned(),
10416                            "local commit outcome could not be persisted".to_owned(),
10417                            None,
10418                            None,
10419                        ));
10420                        break;
10421                    }
10422                }
10423                Frame::PushResultDetails { .. } => {}
10424                Frame::SubStart {
10425                    id,
10426                    status,
10427                    reason_code,
10428                    bootstrap,
10429                    fenced,
10430                } => {
10431                    // §1.4 rule 5: an ERROR closes the section; its body still
10432                    // applied, its SUB_END values are never persisted.
10433                    let mut body = Vec::new();
10434                    let mut sub_end: Option<(i64, Option<String>)> = None;
10435                    let mut error: Option<Frame> = None;
10436                    for inner in frames.by_ref() {
10437                        match inner {
10438                            Frame::SubEnd {
10439                                next_cursor,
10440                                bootstrap_state,
10441                            } => {
10442                                sub_end = Some((next_cursor, bootstrap_state.map(|r| r.0)));
10443                                break;
10444                            }
10445                            inner @ Frame::Error { .. } => {
10446                                error = Some(inner);
10447                                break;
10448                            }
10449                            Frame::Unknown { .. } => {}
10450                            other => body.push(other),
10451                        }
10452                    }
10453                    let ended = sub_end.is_some();
10454                    let section = SectionStart {
10455                        id,
10456                        status,
10457                        reason_code,
10458                        bootstrap,
10459                        fenced,
10460                    };
10461                    let completed = match self.process_section(
10462                        transport,
10463                        &section,
10464                        body,
10465                        sub_end,
10466                        meta,
10467                        &mut report,
10468                    ) {
10469                        Err(SectionError::Abort(code, message)) => {
10470                            failure = Some((code, message, None, None));
10471                            break;
10472                        }
10473                        Err(SectionError::Transport(error)) => {
10474                            failure = Some((error.code, error.message, None, error.details));
10475                            break;
10476                        }
10477                        Ok(completed) => completed,
10478                        Err(_) => false,
10479                    };
10480                    if ended {
10481                        // The counters stay: `complete` and `failed` report them.
10482                        // §7.7: a completed bootstrap ends with the unit total
10483                        // equal to the rows processed.
10484                        self.progress.update(|p| {
10485                            p.unit_id = None;
10486                            p.table = None;
10487                            p.segment_id = None;
10488                            if completed && p.unit_rows_total.is_some() {
10489                                p.unit_rows_total = p.unit_rows_processed;
10490                            }
10491                        });
10492                    }
10493                    match error {
10494                        Some(Frame::Error {
10495                            code,
10496                            message,
10497                            recommended_action,
10498                            details,
10499                            ..
10500                        }) => {
10501                            failure = Some(Self::error_frame_failure(
10502                                code,
10503                                message,
10504                                recommended_action,
10505                                details,
10506                            ));
10507                            break;
10508                        }
10509                        Some(_) => unreachable!("only an ERROR closes a section early"),
10510                        None if !ended => {
10511                            failure = Some((
10512                                "sync.invalid_request".to_owned(),
10513                                "unit section without SUB_END".to_owned(),
10514                                None,
10515                                None,
10516                            ));
10517                            break;
10518                        }
10519                        None => {}
10520                    }
10521                }
10522                Frame::LiveStart {
10523                    status,
10524                    reason_code,
10525                } => {
10526                    let receivers = match self.stored(load_units(&self.conn)) {
10527                        Ok(units) => units
10528                            .into_iter()
10529                            .filter(|unit| {
10530                                unit.status == UnitStatus::Active
10531                                    && unit.echo.is_some()
10532                                    && !unit.bootstrapping()
10533                            })
10534                            .collect(),
10535                        Err(message) => {
10536                            failure = Some(("storage.failed".to_owned(), message, None, None));
10537                            break;
10538                        }
10539                    };
10540                    live = Some((status, reason_code, receivers));
10541                }
10542                Frame::Commit {
10543                    commit_seq,
10544                    tables,
10545                    changes,
10546                    ..
10547                } => {
10548                    let Some((LiveStatus::Active, _, receivers)) = &live else {
10549                        continue;
10550                    };
10551                    let receivers = receivers.clone();
10552                    match self.apply_live_commit(
10553                        &receivers,
10554                        &tables,
10555                        changes,
10556                        commit_seq,
10557                        AppliedServerCommitSource::Pull,
10558                    ) {
10559                        Ok(applied) => report.commits_applied += u32::from(applied),
10560                        Err(error) => {
10561                            failure = Some((error.code, error.message, None, error.details));
10562                            break;
10563                        }
10564                    }
10565                }
10566                Frame::LiveEnd {
10567                    through_seq,
10568                    echo_digest,
10569                } => {
10570                    let Some((status, reason_code, _)) = live.take() else {
10571                        continue;
10572                    };
10573                    live_ended = true;
10574                    live = Some((status, String::new(), Vec::new()));
10575                    if let Err(message) = self.finish_live_section(
10576                        status,
10577                        &reason_code,
10578                        through_seq,
10579                        echo_digest,
10580                        &meta.registration_digest,
10581                        &mut report,
10582                    ) {
10583                        failure = Some(("storage.failed".to_owned(), message, None, None));
10584                        break;
10585                    }
10586                }
10587                Frame::Lease {
10588                    lease_id,
10589                    expires_at_ms,
10590                } => {
10591                    // §7.3.5: persist the opaque lease; a fresh lease clears
10592                    // any prior lease error (the outage/revocation is over).
10593                    if let Err(message) = self.set_lease_state(Some(LeaseState {
10594                        lease_id: Some(lease_id),
10595                        expires_at_ms: Some(expires_at_ms),
10596                        error_code: None,
10597                    })) {
10598                        failure = Some(("storage.failed".to_owned(), message, None, None));
10599                        break;
10600                    }
10601                }
10602                Frame::Error {
10603                    code,
10604                    message,
10605                    recommended_action,
10606                    details,
10607                    ..
10608                } => {
10609                    // §1.6: the whole request failed; already-completed
10610                    // units keep their applied data and cursors.
10611                    failure = Some(Self::error_frame_failure(
10612                        code,
10613                        message,
10614                        recommended_action,
10615                        details,
10616                    ));
10617                    break;
10618                }
10619                Frame::Unknown { .. } => {}
10620                // §1.6: a building server's keepalive carries nothing to apply.
10621                Frame::Keepalive => {}
10622                _ => {
10623                    failure = Some((
10624                        "sync.invalid_request".to_owned(),
10625                        "unexpected frame in response".to_owned(),
10626                        None,
10627                        None,
10628                    ));
10629                    break;
10630                }
10631            }
10632        }
10633
10634        let applied = match failure {
10635            Some(failure) => Err(failure),
10636            // Local apply boundaries already reconciled their affected overlay.
10637            // Refuse round success if any remaining dirty work fails to
10638            // reconcile. §4.8 E1: the push half may have drained commits that
10639            // pinned rows of a shrunk window unit, so retry deferred evictions.
10640            None => self
10641                .rebuild_overlay_if_dirty()
10642                .and_then(|()| self.drain_pending_evictions())
10643                .map_err(|message| ("storage.failed".to_owned(), message, None, None)),
10644        };
10645        // §1.4 rule 4: frames completed before a failure stay committed; a
10646        // failed COMMIT of the coalesced transaction fails the round.
10647        if let Err(message) = self.finish_coalesced_apply() {
10648            return SyncOutcome::Failed {
10649                details: None,
10650                error_code: "storage.failed".into(),
10651                message,
10652                recommended_action: None,
10653            };
10654        }
10655        if let Err((error_code, message, recommended_action, details)) = applied {
10656            return SyncOutcome::Failed {
10657                details,
10658                error_code,
10659                message,
10660                recommended_action,
10661            };
10662        }
10663        let catching_up = match self.stored(load_units(&self.conn)) {
10664            Ok(units) => units
10665                .into_iter()
10666                .filter(|unit| unit.status == UnitStatus::Active && unit.cursor.is_some())
10667                .map(|unit| unit.id)
10668                .collect::<Vec<_>>(),
10669            Err(message) => {
10670                return SyncOutcome::Failed {
10671                    details: None,
10672                    error_code: "storage.failed".into(),
10673                    message,
10674                    recommended_action: None,
10675                }
10676            }
10677        };
10678        // §7.1: a response without LIVE_END, one answered `unregistered` or
10679        // `reset`, or a unit still catching up leaves sync-needed raised;
10680        // after `unregistered` the next round starts at once.
10681        let status = live.map(|(status, _, _)| status);
10682        if !live_ended || status != Some(LiveStatus::Active) || !catching_up.is_empty() {
10683            self.set_sync_needed(true, status == Some(LiveStatus::Unregistered));
10684        }
10685        self.ack_after_pull(transport);
10686        // §7.4.5: the reset is over once the first post-reset pull round
10687        // leaves no unit catching up: the tables are rebuilt and current.
10688        if self.upgrading && catching_up.is_empty() {
10689            self.set_upgrading(false);
10690        }
10691        report.bootstrapping = catching_up;
10692        SyncOutcome::Ok(report)
10693    }
10694
10695    /// §1.6 / §10.1: the failure an in-band `ERROR` frame reports.
10696    fn error_frame_failure(
10697        code: String,
10698        message: String,
10699        recommended_action: String,
10700        details: Option<RawJson>,
10701    ) -> (String, String, Option<String>, Option<Value>) {
10702        let recommended_action = (!recommended_action.is_empty()).then_some(recommended_action);
10703        let details = details
10704            .and_then(|details| serde_json::from_str::<Value>(&details.0).ok())
10705            .filter(Value::is_object);
10706        (code, message, recommended_action, details)
10707    }
10708
10709    /// §4.5 at `LIVE_END` of a pull: join rule J for an `active` section, the
10710    /// §4.6 replica reset for `reset`, nothing for `unregistered`; then the
10711    /// replica cursor, the echo digest and the digest of the list the server
10712    /// now stores.
10713    fn finish_live_section(
10714        &mut self,
10715        status: LiveStatus,
10716        reason_code: &str,
10717        through_seq: i64,
10718        echo_digest: Option<[u8; 32]>,
10719        registration_digest: &str,
10720        report: &mut SyncReport,
10721    ) -> Result<(), String> {
10722        let rollback = self.capture();
10723        let resets = report.resets.len();
10724        self.begin_observation("syncular_live_end")?;
10725        let finished = (|| {
10726            let mut batch = ChangeAccumulator::default();
10727            let before = self.stored(replica_cursor(&self.conn))?;
10728            let mut cursor = if status == LiveStatus::Unregistered {
10729                before
10730            } else {
10731                -1
10732            };
10733            let joined = before.max(through_seq);
10734            for unit in self.stored(load_units(&self.conn))? {
10735                if unit.status != UnitStatus::Active || unit.bootstrapping() {
10736                    continue;
10737                }
10738                match status {
10739                    // §4.6 replica reset: every live unit bootstraps again;
10740                    // post-bootstrap units keep their cursors.
10741                    LiveStatus::Reset if unit.cursor.is_none() => {
10742                        self.record_unit_windows(&mut batch, &unit)?;
10743                        report.resets.push(unit.id.clone());
10744                        self.stored(save_unit(
10745                            &self.conn,
10746                            &UnitRecord {
10747                                reason_code: Some(reason_code.to_owned()),
10748                                cursor: Some(-1),
10749                                seeded: Vec::new(),
10750                                ..unit
10751                            },
10752                        ))?;
10753                    }
10754                    // §4.5 join rule J.
10755                    LiveStatus::Active => {
10756                        let next = unit.cursor.unwrap_or(joined).max(through_seq);
10757                        if next >= joined {
10758                            cursor = joined;
10759                        }
10760                        if unit.cursor.is_some() {
10761                            // A post-bootstrap unit that joins live transitions.
10762                            if next >= joined {
10763                                self.record_unit_windows(&mut batch, &unit)?;
10764                            }
10765                            self.stored(save_unit(
10766                                &self.conn,
10767                                &UnitRecord {
10768                                    cursor: (next < joined).then_some(next),
10769                                    ..unit
10770                                },
10771                            ))?;
10772                        }
10773                    }
10774                    _ => {}
10775                }
10776            }
10777            self.set_meta(REPLICA_CURSOR_KEY, &cursor.to_string())?;
10778            self.set_meta(
10779                ECHO_DIGEST_KEY,
10780                &echo_digest
10781                    .map(|digest| bytes_to_hex(&digest))
10782                    .unwrap_or_default(),
10783            )?;
10784            if status == LiveStatus::Unregistered {
10785                self.delete_meta(REGISTERED_DIGEST_KEY)?;
10786            } else {
10787                self.set_meta(REGISTERED_DIGEST_KEY, registration_digest)?;
10788            }
10789            self.finish_observation("syncular_live_end", batch)
10790        })();
10791        if finished.is_err() {
10792            self.rollback_observation("syncular_live_end");
10793            self.restore(rollback);
10794            report.resets.truncate(resets);
10795        }
10796        finished
10797    }
10798
10799    // -- push results (§6.3, §7.2) ------------------------------------------------
10800
10801    fn handle_push_results(
10802        &mut self,
10803        frames: &[Frame],
10804        pushed_ids: &HashSet<&str>,
10805        rejection_details_by_commit: &HashMap<String, BTreeMap<i32, RejectionDetails>>,
10806        report: &mut SyncReport,
10807        last_final_push_result_id: Option<&str>,
10808    ) -> Result<(), String> {
10809        self.begin_observation("syncular_push_results")?;
10810        let rollback = self.capture();
10811        let conflict_count = self.conflicts.len();
10812        let applied_count = report.applied.len();
10813        let rejected_count = report.rejected.len();
10814        let retryable_count = report.retryable.len();
10815        let mut drained = Vec::new();
10816        let mut batch = ChangeAccumulator::default();
10817        let persisted = (|| {
10818            for frame in frames {
10819                let Frame::PushResult {
10820                    client_commit_id,
10821                    status,
10822                    results,
10823                    commit_seq,
10824                } = frame
10825                else {
10826                    return Err("unexpected acknowledgement frame".to_owned());
10827                };
10828                if !pushed_ids.contains(client_commit_id.as_str()) {
10829                    continue;
10830                }
10831                let Some(index) = self
10832                    .outbox
10833                    .iter()
10834                    .position(|commit| commit.client_commit_id == *client_commit_id)
10835                else {
10836                    continue;
10837                };
10838                let status = *status;
10839                let rejection_details = rejection_details_by_commit.get(client_commit_id);
10840                let operations = self.outbox[index].ops.clone();
10841                match status {
10842                    PushStatus::Applied | PushStatus::Cached => {
10843                        // §7.2: a lost ack replays as `cached` — proceed as if the
10844                        // ack had arrived.
10845                        let sequence =
10846                            commit_seq.ok_or_else(|| "ACK lacks a commit sequence".to_owned())?;
10847                        let affected: HashSet<_> = operations
10848                            .iter()
10849                            .map(|op| (op.table.as_str(), op.row_id.as_str()))
10850                            .collect();
10851                        let prior = self.acknowledged_operations(Some(&affected), None)?;
10852                        for (op_index, operation) in operations.iter().enumerate() {
10853                            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))
10854                                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
10855                            if delivered {
10856                                continue;
10857                            }
10858                            let table = self
10859                                .schema
10860                                .table(&operation.table)
10861                                .ok_or_else(|| "sync.unknown_table".to_owned())?;
10862                            let mut intended: Map<String, Value> = self
10863                                .stored_row(table, &operation.row_id, true)?
10864                                .map(|(row, _)| {
10865                                    table
10866                                        .columns
10867                                        .iter()
10868                                        .zip(&row)
10869                                        .map(|(column, value)| {
10870                                            (column.name.clone(), column_value_to_json(value))
10871                                        })
10872                                        .collect()
10873                                })
10874                                .unwrap_or_default();
10875                            let mut scope_image = intended.clone();
10876                            for op in prior
10877                                .iter()
10878                                .chain(
10879                                    self.failed_commits
10880                                        .iter()
10881                                        .flat_map(|(commit, _)| &commit.ops),
10882                                )
10883                                .chain(
10884                                    self.outbox
10885                                        .iter()
10886                                        .take(index)
10887                                        .flat_map(|commit| &commit.ops),
10888                                )
10889                                .chain(operations.iter().take(op_index + 1))
10890                            {
10891                                if op.table != operation.table || op.row_id != operation.row_id {
10892                                    continue;
10893                                }
10894                                if let Some(values) = &op.values {
10895                                    intended.extend(values.clone());
10896                                } else {
10897                                    scope_image = intended.clone();
10898                                    intended.clear();
10899                                }
10900                            }
10901                            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)",
10902                                rusqlite::params![client_commit_id, op_index as i64, operation.table, operation.row_id, sequence,
10903                                    serde_json::to_string(&CommitOperation::from(operation)).map_err(|_| "sync.local_corrupt".to_owned())?,
10904                                    serde_json::to_string(if operation.upsert { &intended } else { &scope_image }).map_err(|_| "sync.local_corrupt".to_owned())?])
10905                                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
10906                        }
10907                        let journal_results = results
10908                            .iter()
10909                            .map(|result| {
10910                                let op_index = match result {
10911                                    OpResult::Applied { op_index }
10912                                    | OpResult::Conflict { op_index, .. }
10913                                    | OpResult::Error { op_index, .. } => *op_index,
10914                                };
10915                                CommitOperationOutcome::Applied { op_index }
10916                            })
10917                            .collect::<Vec<_>>();
10918                        let outcome_status = if status == PushStatus::Applied {
10919                            CommitOutcomeStatus::Applied
10920                        } else {
10921                            CommitOutcomeStatus::Cached
10922                        };
10923                        let persisted = self
10924                            .persist_commit_outcome(
10925                                client_commit_id,
10926                                outcome_status,
10927                                &journal_results,
10928                                None,
10929                            )
10930                            .and_then(|()| self.delete_outbox_persisted(client_commit_id));
10931                        persisted?;
10932                        self.sync_needed = true;
10933                        batch.status = true;
10934                        batch.outcomes = true;
10935                    }
10936                    PushStatus::Rejected => {
10937                        if results.iter().any(|result| {
10938                            matches!(
10939                                result,
10940                                OpResult::Error {
10941                                    code,
10942                                    retryable: true,
10943                                    ..
10944                                } if code == "sync.idempotency_cache_miss"
10945                            )
10946                        }) {
10947                            // §6.3/§7.2: a serving failure, not an outcome — keep the
10948                            // exact commit queued for an identical retry.
10949                            report.retryable.push(client_commit_id.to_owned());
10950                            continue;
10951                        }
10952
10953                        let mut journal_results = Vec::with_capacity(results.len());
10954                        let mut conflicts = Vec::new();
10955                        let mut rejections = Vec::new();
10956                        for result in results {
10957                            match result {
10958                                OpResult::Applied { op_index } => {
10959                                    journal_results.push(CommitOperationOutcome::Applied {
10960                                        op_index: *op_index,
10961                                    });
10962                                }
10963                                OpResult::Conflict {
10964                                    op_index,
10965                                    code,
10966                                    message,
10967                                    server_version,
10968                                    server_row,
10969                                    conflict_columns: conflict_columns_bitmap,
10970                                } => {
10971                                    let operation = operations
10972                                        .get(*op_index as usize)
10973                                        .map(CommitOperation::from);
10974                                    let (table, row_id) = operation
10975                                        .as_ref()
10976                                        .map(|op| (op.table.clone(), op.row_id.clone()))
10977                                        .unwrap_or_default();
10978                                    let server_row_json = self
10979                                        .schema
10980                                        .table(&table)
10981                                        .and_then(|t| {
10982                                            decode_row_bytes(t, server_row, &self.encryption)
10983                                                .ok()
10984                                                .map(|(row, _)| (t, row))
10985                                        })
10986                                        .map(|(t, row)| {
10987                                            let mut map = Map::new();
10988                                            for (i, column) in t.columns.iter().enumerate() {
10989                                                map.insert(
10990                                                    column.name.clone(),
10991                                                    column_value_to_json(
10992                                                        row.get(i).unwrap_or(&None),
10993                                                    ),
10994                                                );
10995                                            }
10996                                            map
10997                                        })
10998                                        .unwrap_or_default();
10999                                    // §6.3: decode the presence-layout bitmap
11000                                    // into the marked column names.
11001                                    let conflict_columns = self
11002                                        .schema
11003                                        .table(&table)
11004                                        .map(|t| {
11005                                            t.columns
11006                                                .iter()
11007                                                .enumerate()
11008                                                .filter(|(index, _)| {
11009                                                    conflict_columns_bitmap
11010                                                        .get(index / 8)
11011                                                        .is_some_and(|byte| {
11012                                                            byte & (1 << (index % 8)) != 0
11013                                                        })
11014                                                })
11015                                                .map(|(_, column)| column.name.clone())
11016                                                .collect::<Vec<_>>()
11017                                        })
11018                                        .unwrap_or_default();
11019                                    let conflict = ConflictRecord {
11020                                        client_commit_id: client_commit_id.to_owned(),
11021                                        op_index: *op_index,
11022                                        table,
11023                                        row_id,
11024                                        code: code.clone(),
11025                                        message: message.clone(),
11026                                        server_version: *server_version,
11027                                        server_row: server_row_json,
11028                                        conflict_columns,
11029                                        operation,
11030                                    };
11031                                    journal_results.push(CommitOperationOutcome::Conflict {
11032                                        conflict: conflict.clone(),
11033                                    });
11034                                    conflicts.push(conflict);
11035                                }
11036                                OpResult::Error {
11037                                    op_index,
11038                                    code,
11039                                    message,
11040                                    retryable,
11041                                } => {
11042                                    let rejection = RejectionRecord {
11043                                        client_commit_id: client_commit_id.to_owned(),
11044                                        op_index: *op_index,
11045                                        code: code.clone(),
11046                                        message: message.clone(),
11047                                        retryable: *retryable,
11048                                        details: rejection_details
11049                                            .and_then(|details| details.get(op_index))
11050                                            .cloned(),
11051                                        operation: operations
11052                                            .get(*op_index as usize)
11053                                            .map(CommitOperation::from),
11054                                    };
11055                                    journal_results.push(CommitOperationOutcome::Error {
11056                                        rejection: rejection.clone(),
11057                                    });
11058                                    rejections.push(rejection);
11059                                }
11060                            }
11061                        }
11062                        if self.retain_failed_commits {
11063                            self.retain_failed_commit(client_commit_id, &operations)?;
11064                        }
11065                        let outcome_status = if conflicts.is_empty() {
11066                            CommitOutcomeStatus::Rejected
11067                        } else {
11068                            CommitOutcomeStatus::Conflict
11069                        };
11070                        self.leave_through(client_commit_id);
11071                        let persisted = self
11072                            .persist_commit_outcome(
11073                                client_commit_id,
11074                                outcome_status,
11075                                &journal_results,
11076                                Some(&operations),
11077                            )
11078                            .and_then(|()| self.delete_outbox_persisted(client_commit_id));
11079                        persisted?;
11080                        batch.conflicts = !conflicts.is_empty();
11081                        batch.rejections = !rejections.is_empty();
11082                        batch.status = true;
11083                        batch.outcomes = true;
11084                        self.conflicts.extend(conflicts);
11085                        self.rejections.extend(rejections);
11086                    }
11087                }
11088                drained.push(self.outbox.remove(index));
11089                if batch.status {
11090                    for operation in &operations {
11091                        if !self.record_row_scopes(
11092                            &mut batch,
11093                            &operation.table,
11094                            &operation.row_id,
11095                            false,
11096                        ) {
11097                            batch.table(&operation.table);
11098                        }
11099                    }
11100                }
11101                match status {
11102                    PushStatus::Applied | PushStatus::Cached => {
11103                        report.applied.push(client_commit_id.to_owned())
11104                    }
11105                    PushStatus::Rejected => report.rejected.push(client_commit_id.to_owned()),
11106                }
11107            }
11108            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)) {
11109                self.prune_commit_outcomes()?;
11110            }
11111            self.reconcile_rows(&drained)?;
11112            self.rebuild_overlay_if_dirty()?;
11113            self.finish_observation("syncular_push_results", batch)
11114        })();
11115        if let Err(error) = persisted {
11116            self.rollback_observation("syncular_push_results");
11117            self.restore(rollback);
11118            report.applied.truncate(applied_count);
11119            report.rejected.truncate(rejected_count);
11120            report.retryable.truncate(retryable_count);
11121            return Err(error);
11122        }
11123        if !rollback.sync_needed && self.sync_needed {
11124            self.sync_intent_queue.push_back(SyncIntent::Interactive);
11125        }
11126        report.conflicts += (self.conflicts.len() - conflict_count) as u32;
11127        Ok(())
11128    }
11129
11130    fn push_result_is_final(status: PushStatus, results: &[OpResult]) -> bool {
11131        status != PushStatus::Rejected
11132            || !results.iter().any(|result| {
11133                matches!(
11134                    result,
11135                    OpResult::Error {
11136                        code,
11137                        retryable: true,
11138                        ..
11139                    } if code == "sync.idempotency_cache_miss"
11140                )
11141            })
11142    }
11143
11144    // -- unit sections and the live section ------------------------------------------
11145
11146    /// One unit section (§4.4): apply its segments, then persist its
11147    /// `SUB_END` (§4.6 reset, §3.3 revocation and purge, the echo, cursor and
11148    /// resume token). A section of a unit the app released while the round was
11149    /// in flight is skipped; a fail-closed first page fails the unit and skips
11150    /// the rest of its section (§5.6). Returns whether its `SUB_END` completed
11151    /// a bootstrap (§7.7).
11152    fn process_section(
11153        &mut self,
11154        transport: &mut dyn Transport,
11155        start: &SectionStart,
11156        body: Vec<Frame>,
11157        sub_end: Option<(i64, Option<String>)>,
11158        meta: &RequestMeta,
11159        report: &mut SyncReport,
11160    ) -> Result<bool, SectionError> {
11161        let storage = |message| SectionError::Abort("storage.failed".to_owned(), message);
11162        let unit = self
11163            .stored(get_unit(&self.conn, &start.id))
11164            .map_err(storage)?
11165            .filter(|unit| unit.status == UnitStatus::Active);
11166        // §7.7: a section boundary ends the previous payload; the section's
11167        // UNIT_EXTENT starts the unit counters in the same snapshot.
11168        let extent = match (&unit, body.first()) {
11169            (
11170                Some(_),
11171                Some(Frame::UnitExtent {
11172                    rows_total,
11173                    rows_done,
11174                }),
11175            ) => u64::try_from(*rows_total)
11176                .ok()
11177                .zip(u64::try_from(*rows_done).ok()),
11178            _ => None,
11179        };
11180        self.progress.update(|p| {
11181            p.phase = ProgressPhase::Import;
11182            p.unit_id = unit.as_ref().map(|unit| unit.id.clone());
11183            p.unit_rows_total = extent.map(|(total, _)| total);
11184            p.unit_rows_processed = extent.map(|(_, done)| done);
11185            p.table = None;
11186            p.segment_id = None;
11187            p.bytes_received = 0;
11188            p.bytes_total = None;
11189            p.rows_processed = 0;
11190            p.rows_total = None;
11191            p.import_write_ms = None;
11192            p.import_commit_ms = None;
11193            p.download_ms = None;
11194        });
11195        let Some(unit) = unit else {
11196            return Ok(false);
11197        };
11198        let echo: Vec<EchoRecord> = start
11199            .fenced
11200            .iter()
11201            .map(|record| EchoRecord {
11202                table: record.table.clone(),
11203                status: record.status.name().to_owned(),
11204                scopes: record.scopes.iter().cloned().collect(),
11205            })
11206            .collect();
11207        // §5.6: rows earlier attempts at this position applied.
11208        let applied_record = self
11209            .stored(applied_rows(&self.conn, &unit.id))
11210            .map_err(storage)?;
11211        // §5.6: a resumed bootstrap keeps the tables it already seeded.
11212        let mut seeded: BTreeSet<String> = if unit.bootstrap_state.is_none() {
11213            BTreeSet::new()
11214        } else {
11215            unit.seeded.iter().cloned().collect()
11216        };
11217        let applied = (|| {
11218            for frame in body {
11219                match frame {
11220                    Frame::SegmentInline { payload } => {
11221                        let segment = decode_rows_segment(&payload).map_err(|e| {
11222                            SectionError::Abort(e.code.as_str().to_owned(), e.detail)
11223                        })?;
11224                        self.progress.update(|p| {
11225                            p.phase = ProgressPhase::Import;
11226                            p.unit_id = Some(unit.id.clone());
11227                            p.table = Some(segment.table.clone());
11228                            p.segment_id = None;
11229                            p.bytes_received = payload.len() as u64;
11230                            p.bytes_total = Some(payload.len() as u64);
11231                            p.rows_processed = 0;
11232                            p.rows_total =
11233                                Some(segment.blocks.iter().map(|block| block.len() as u64).sum());
11234                            p.import_write_ms = None;
11235                            p.import_commit_ms = None;
11236                            p.download_ms = None;
11237                        });
11238                        let (pair, clear, effective) =
11239                            self.segment_pair(&unit, &echo, &seeded, &segment.table)?;
11240                        report.segment_rows_applied +=
11241                            self.apply_segment(&pair, &segment, clear, &effective, &unit.id)?;
11242                        seeded.insert(segment.table);
11243                    }
11244                    Frame::SegmentRef {
11245                        segment_id,
11246                        byte_length,
11247                        media_type,
11248                        table,
11249                        row_count,
11250                        as_of_commit_seq,
11251                        scope_digest,
11252                        row_cursor,
11253                        next_row_cursor,
11254                        url,
11255                        url_expires_at_ms,
11256                        ..
11257                    } => {
11258                        // §4.2: reject a descriptor whose mediaType was not
11259                        // advertised — never skip or guess.
11260                        let advertised = match media_type {
11261                            MediaType::Rows => {
11262                                meta.accept & ACCEPT_EXTERNAL_ROWS != 0
11263                                    || meta.accept & ACCEPT_INLINE_ROWS != 0
11264                            }
11265                            MediaType::Sqlite => meta.accept & ACCEPT_SQLITE != 0,
11266                        };
11267                        if !advertised {
11268                            return Err(SectionError::Abort(
11269                                "sync.invalid_request".to_owned(),
11270                                format!(
11271                                    "SEGMENT_REF mediaType {} was not advertised in accept (§4.2)",
11272                                    media_type.name()
11273                                ),
11274                            ));
11275                        }
11276                        // §5.6 applied-segment rule: a partly applied image
11277                        // already ran its table's first-page clear.
11278                        let resumed = applied_record.get(&segment_id).copied();
11279                        if resumed.is_some() {
11280                            seeded.insert(table.clone());
11281                        }
11282                        if resumed == Some(row_count) {
11283                            // §7.7: an earlier attempt imported this payload;
11284                            // its rows still count toward the unit.
11285                            self.progress.update(|p| {
11286                                p.phase = ProgressPhase::Import;
11287                                p.unit_id = Some(unit.id.clone());
11288                                p.table = Some(table.clone());
11289                                p.segment_id = Some(segment_id.clone());
11290                                p.bytes_received = 0;
11291                                p.bytes_total = None;
11292                                p.rows_processed = 0;
11293                                p.rows_total = u64::try_from(row_count).ok();
11294                                p.import_write_ms = None;
11295                                p.import_commit_ms = None;
11296                                p.download_ms = None;
11297                            });
11298                            self.progress.update(|p| {
11299                                p.rows_processed = u64::try_from(row_count).unwrap_or(0)
11300                            });
11301                            continue;
11302                        }
11303                        if meta
11304                            .deferred
11305                            .contains(&(unit.id.clone(), segment_id.clone()))
11306                        {
11307                            return Err(SectionError::Deferred);
11308                        }
11309                        self.progress.update(|p| {
11310                            p.phase = ProgressPhase::Download;
11311                            p.unit_id = Some(unit.id.clone());
11312                            p.table = Some(table.clone());
11313                            p.segment_id = Some(segment_id.clone());
11314                            p.bytes_received = 0;
11315                            p.bytes_total = u64::try_from(byte_length).ok();
11316                            p.rows_processed = 0;
11317                            p.rows_total = u64::try_from(row_count).ok();
11318                            p.import_write_ms = None;
11319                            p.import_commit_ms = None;
11320                            p.download_ms = None;
11321                        });
11322                        let observer = self.progress.clone();
11323                        let mut on_progress = |bytes| observer.update(|p| p.bytes_received = bytes);
11324                        // §7.7: from the request's start to its last body byte.
11325                        let requested = std::time::Instant::now();
11326                        let bytes = if let Some(url) = url {
11327                            // §5.4: a url-carrying descriptor MUST be fetched
11328                            // from that URL; failure invalidates the whole
11329                            // descriptor (no fall-through to §5.5 — re-pull
11330                            // recovers, §1.4 rule 5).
11331                            if meta.accept & ACCEPT_SIGNED_URLS == 0 {
11332                                return Err(SectionError::Abort(
11333                                    "sync.invalid_request".to_owned(),
11334                                    "SEGMENT_REF carries a url but accept bit 3 was not advertised (§5.4)"
11335                                        .to_owned(),
11336                                ));
11337                            }
11338                            // §5.4: MUST NOT start a fetch at/past expiry.
11339                            if url_expires_at_ms.is_some_and(|exp| {
11340                                exp <= transport
11341                                    .segment_fetch_started_at(&url)
11342                                    .unwrap_or_else(|| self.clock_now_ms())
11343                            }) {
11344                                return Err(SectionError::Abort(
11345                                    "sync.segment_expired".to_owned(),
11346                                    format!(
11347                                        "signed URL for segment {segment_id} expired before fetch — re-pull mints fresh descriptors (§5.4)"
11348                                    ),
11349                                ));
11350                            }
11351                            transport
11352                                .fetch_url(
11353                                    &url,
11354                                    u64::try_from(byte_length).unwrap_or(0),
11355                                    &mut on_progress,
11356                                )
11357                                .map_err(|e| self.segment_fetch_failed(e))?
11358                        } else {
11359                            // §5.5: the owning unit's scope map, each value a one-element list.
11360                            let requested_scopes_json =
11361                                canonical_scope_json(&unit_scope_lists(&unit.scopes));
11362                            transport
11363                                .download_segment(
11364                                    &SegmentRequest {
11365                                        segment_id: segment_id.clone(),
11366                                        table: table.clone(),
11367                                        requested_scopes_json,
11368                                        byte_length: u64::try_from(byte_length).unwrap_or(0),
11369                                    },
11370                                    &mut on_progress,
11371                                )
11372                                .map_err(|e| {
11373                                    // §5.5: access changed since the response;
11374                                    // the next round's SUB_START settles the unit.
11375                                    if e.code == "sync.forbidden" {
11376                                        SectionError::Refused
11377                                    } else {
11378                                        self.segment_fetch_failed(e)
11379                                    }
11380                                })?
11381                        };
11382                        let download_ms = u64::try_from(requested.elapsed().as_millis()).ok();
11383                        // §5.4: the descriptor's byteLength caps the body before
11384                        // §5.1 verifies the content address; the client discards
11385                        // the segment and re-pulls on either failure.
11386                        if bytes.len() as i64 > byte_length {
11387                            self.schedule_background_retry();
11388                            return Err(SectionError::Abort(
11389                                "sync.invalid_request".to_owned(),
11390                                "segment exceeds its byteLength".to_owned(),
11391                            ));
11392                        }
11393                        on_progress(bytes.len() as u64);
11394                        let digest = Sha256::digest(&bytes);
11395                        let expected = segment_id
11396                            .strip_prefix("sha256:")
11397                            .unwrap_or(segment_id.as_str());
11398                        if bytes_to_hex(&digest) != expected {
11399                            // §5.1: the client discards the segment and re-pulls.
11400                            self.schedule_background_retry();
11401                            return Err(SectionError::Abort(
11402                                "sync.invalid_request".to_owned(),
11403                                "segment bytes do not match the content address (§5.1)".to_owned(),
11404                            ));
11405                        }
11406                        self.progress.update(|p| {
11407                            p.phase = ProgressPhase::Import;
11408                            p.download_ms = download_ms;
11409                        });
11410                        if media_type == MediaType::Sqlite {
11411                            // §5.3: a range image keeps its position in the resume
11412                            // token; a descriptor row cursor is invalid.
11413                            if row_cursor.is_some() || next_row_cursor.is_some() {
11414                                return Err(SectionError::Abort(
11415                                    "sync.invalid_request".to_owned(),
11416                                    "sqlite segments are whole-table: rowCursor/nextRowCursor must be absent (§5.3)"
11417                                        .to_owned(),
11418                                ));
11419                            }
11420                            let (pair, clear, effective) =
11421                                self.segment_pair(&unit, &echo, &seeded, &table)?;
11422                            report.segment_rows_applied += self.apply_sqlite_segment(
11423                                &pair,
11424                                &bytes,
11425                                clear,
11426                                &effective,
11427                                &unit.id,
11428                                &segment_id,
11429                                resumed.unwrap_or(0),
11430                                row_count,
11431                                as_of_commit_seq,
11432                                &scope_digest,
11433                            )?;
11434                            seeded.insert(table);
11435                        } else {
11436                            let segment = decode_rows_segment(&bytes).map_err(|e| {
11437                                SectionError::Abort(e.code.as_str().to_owned(), e.detail)
11438                            })?;
11439                            let (pair, clear, effective) =
11440                                self.segment_pair(&unit, &echo, &seeded, &segment.table)?;
11441                            report.segment_rows_applied +=
11442                                self.apply_segment(&pair, &segment, clear, &effective, &unit.id)?;
11443                            seeded.insert(segment.table);
11444                            // An image records its rows with each chunk.
11445                            self.stored(record_applied_rows(
11446                                &self.conn,
11447                                &unit.id,
11448                                &segment_id,
11449                                row_count,
11450                            ))
11451                            .map_err(storage)?;
11452                        }
11453                    }
11454                    Frame::UnitExtent { .. } => {}
11455                    _ => {
11456                        return Err(SectionError::Abort(
11457                            "sync.invalid_request".to_owned(),
11458                            "unexpected frame inside a unit section".to_owned(),
11459                        ));
11460                    }
11461                }
11462            }
11463            Ok(())
11464        })();
11465        match applied {
11466            Ok(()) => {}
11467            // The unit keeps catching up with its cursor unpersisted.
11468            Err(SectionError::Refused | SectionError::Deferred) => return Ok(false),
11469            Err(SectionError::FailClosed) => {
11470                // §5.6: the failure is unit-local; the rest of the response
11471                // still applies and the failed unit leaves the list.
11472                self.begin_observation("syncular_section_failure")
11473                    .map_err(storage)?;
11474                let failed = (|| {
11475                    let mut batch = ChangeAccumulator::default();
11476                    self.record_unit_windows(&mut batch, &unit)?;
11477                    batch.status = true;
11478                    self.stored(save_unit(
11479                        &self.conn,
11480                        &UnitRecord {
11481                            status: UnitStatus::Failed,
11482                            reason_code: Some("sync.scope_revoked".to_owned()),
11483                            restriction: None,
11484                            ..unit.clone()
11485                        },
11486                    ))?;
11487                    self.finish_observation("syncular_section_failure", batch)
11488                })();
11489                if let Err(message) = failed {
11490                    self.rollback_observation("syncular_section_failure");
11491                    return Err(storage(message));
11492                }
11493                report.failed.push(unit.id);
11494                return Ok(false);
11495            }
11496            Err(error) => return Err(error),
11497        }
11498        let Some((next_cursor, bootstrap_state)) = sub_end else {
11499            return Ok(false);
11500        };
11501        let completes = start.bootstrap && bootstrap_state.is_none();
11502        let rollback = self.capture();
11503        let counts = (
11504            report.resets.len(),
11505            report.revoked.len(),
11506            report.failed.len(),
11507        );
11508        self.begin_observation("syncular_sub_end")
11509            .map_err(storage)?;
11510        let finished = self
11511            .finish_section(start, echo, next_cursor, bootstrap_state, seeded, report)
11512            .and_then(|batch| {
11513                self.rebuild_overlay_if_dirty()?;
11514                self.finish_observation("syncular_sub_end", batch)
11515            });
11516        if let Err(message) = finished {
11517            self.rollback_observation("syncular_sub_end");
11518            self.restore(rollback);
11519            report.resets.truncate(counts.0);
11520            report.revoked.truncate(counts.1);
11521            report.failed.truncate(counts.2);
11522            return Err(storage(message));
11523        }
11524        Ok(completes)
11525    }
11526
11527    /// §5.6: the table, first-page flag and effective scopes of one segment
11528    /// of `unit`'s section. A first page outside the unit's restriction ends it.
11529    #[allow(clippy::type_complexity)]
11530    fn segment_pair(
11531        &self,
11532        unit: &UnitRecord,
11533        echo: &[EchoRecord],
11534        seeded: &BTreeSet<String>,
11535        name: &str,
11536    ) -> Result<(TableSchema, bool, Vec<(String, Vec<String>)>), SectionError> {
11537        let table = self.schema.table(name).cloned().ok_or_else(|| {
11538            SectionError::Abort(
11539                "sync.schema_mismatch".to_owned(),
11540                format!("segment table {name:?} is not in the client schema"),
11541            )
11542        })?;
11543        let effective = covers(&table, &unit.scopes)
11544            .then(|| pair_scopes(&unit.scopes, name, Some(echo)))
11545            .flatten()
11546            .ok_or_else(|| {
11547                SectionError::Abort(
11548                    "sync.invalid_request".to_owned(),
11549                    "a segment names no active pair of its unit".to_owned(),
11550                )
11551            })?;
11552        let first_page = !seeded.contains(name);
11553        // §5.6: a first page of a table outside the restriction is a whole
11554        // bootstrap from a server that predates RESTRICT; the restriction ends
11555        // before the clear runs.
11556        if first_page
11557            && unit
11558                .restriction
11559                .as_ref()
11560                .is_some_and(|restriction| !restriction.tables.iter().any(|t| t == name))
11561        {
11562            self.conn
11563                .execute(
11564                    "UPDATE _syncular_units SET restriction=NULL WHERE id=?1",
11565                    [&unit.id],
11566                )
11567                .map_err(|error| {
11568                    SectionError::Abort(
11569                        "storage.failed".to_owned(),
11570                        Self::sqlite_failure(&self.storage_failure, error),
11571                    )
11572                })?;
11573        }
11574        Ok((table, first_page, effective))
11575    }
11576
11577    /// §4.4 `SUB_END` of an active, revoked or reset section, inside the
11578    /// caller's observation: a reset discards cursor, resume token and
11579    /// first-page record and keeps the echo; a revoked pair purges by its last
11580    /// echo (§3.3); otherwise the echo replaces the persisted one, a revoked
11581    /// fenced record that turns active again re-bootstraps the unit, and a
11582    /// bootstrap section persists its pin, resume token and seeded tables.
11583    fn finish_section(
11584        &mut self,
11585        start: &SectionStart,
11586        echo: Vec<EchoRecord>,
11587        next_cursor: i64,
11588        bootstrap_state: Option<String>,
11589        seeded: BTreeSet<String>,
11590        report: &mut SyncReport,
11591    ) -> Result<ChangeAccumulator, String> {
11592        #[cfg(feature = "bench-internals")]
11593        let _phase = self.benchmark_phases.start(Phase::CursorPersist);
11594        let mut batch = ChangeAccumulator::default();
11595        // §4.4: SUB_END writes only into a unit that is still registered.
11596        let Some(unit) = self
11597            .stored(get_unit(&self.conn, &start.id))?
11598            .filter(|unit| unit.status == UnitStatus::Active)
11599        else {
11600            return Ok(batch);
11601        };
11602        self.record_unit_windows(&mut batch, &unit)?;
11603        if start.status == SubStatus::Reset {
11604            // §4.6: staleness, never a purge; the rows stay until the
11605            // bootstrap replaces them.
11606            report.resets.push(unit.id.clone());
11607            self.stored(save_unit(
11608                &self.conn,
11609                &UnitRecord {
11610                    reason_code: Some(start.reason_code.clone()),
11611                    cursor: Some(-1),
11612                    bootstrap_state: None,
11613                    seeded: Vec::new(),
11614                    restriction: None,
11615                    ..unit
11616                },
11617            ))?;
11618            return Ok(batch);
11619        }
11620        let revoked = start.status == SubStatus::Revoked;
11621        let mut units = None;
11622        let mut failed = false;
11623        let mut rearmed = false;
11624        for table in self.schema.tables.clone() {
11625            if !covers(&table, &unit.scopes) {
11626                continue;
11627            }
11628            let last = unit
11629                .echo
11630                .as_deref()
11631                .and_then(|last| pair_scopes(&unit.scopes, &table.name, Some(last)));
11632            let next = (!revoked)
11633                .then(|| pair_scopes(&unit.scopes, &table.name, Some(&echo)))
11634                .flatten();
11635            // §3.3: a revoked fenced record that turns active again re-bootstraps.
11636            rearmed |= unit.echo.is_some() && last.is_none() && next.is_some();
11637            // §3.3: purge a pair the response revokes, keyed on the echo the
11638            // client persisted while the pair was active.
11639            if let (Some(last), None) = (&last, &next) {
11640                let units = match units {
11641                    Some(ref units) => units,
11642                    None => units.insert(self.stored(load_units(&self.conn))?),
11643                };
11644                let owners = unit_owners(units, &table, &unit.id);
11645                failed |= !self.purge_pair(&mut batch, &table, last, &owners)?;
11646            }
11647        }
11648        if revoked || failed {
11649            if revoked {
11650                report.revoked.push(unit.id.clone());
11651            }
11652            if failed {
11653                report.failed.push(unit.id.clone());
11654            }
11655            batch.status = true;
11656            self.stored(save_unit(
11657                &self.conn,
11658                &UnitRecord {
11659                    status: if failed {
11660                        UnitStatus::Failed
11661                    } else {
11662                        UnitStatus::Revoked
11663                    },
11664                    reason_code: Some(if failed {
11665                        "sync.scope_revoked".to_owned()
11666                    } else {
11667                        start.reason_code.clone()
11668                    }),
11669                    cursor: Some(-1),
11670                    bootstrap_state: None,
11671                    seeded: Vec::new(),
11672                    echo: None,
11673                    restriction: None,
11674                    ..unit
11675                },
11676            ))?;
11677            return Ok(batch);
11678        }
11679        // §3.3: the server accepted the unit, so a later refusal re-arms once.
11680        self.window_armed.remove(&unit.id);
11681        let completed = start.bootstrap && !rearmed && bootstrap_state.is_none();
11682        let (cursor, bootstrap_state, seeded) = if rearmed {
11683            (Some(-1), None, Vec::new())
11684        } else if start.bootstrap {
11685            let seeded = if bootstrap_state.is_none() {
11686                Vec::new()
11687            } else {
11688                seeded.into_iter().collect()
11689            };
11690            (Some(next_cursor), bootstrap_state, seeded)
11691        } else {
11692            (
11693                unit.cursor,
11694                unit.bootstrap_state.clone(),
11695                unit.seeded.clone(),
11696            )
11697        };
11698        self.stored(save_unit(
11699            &self.conn,
11700            &UnitRecord {
11701                reason_code: None,
11702                echo: Some(echo.clone()),
11703                cursor,
11704                bootstrap_state,
11705                seeded,
11706                // §7.4.3: the restriction ends when the unit re-bootstraps or
11707                // completes its bootstrap.
11708                restriction: unit.restriction.clone().filter(|_| !rearmed && !completed),
11709                ..unit.clone()
11710            },
11711        ))?;
11712        if !completed {
11713            return Ok(batch);
11714        }
11715        // §7.1: a completed bootstrap covers acknowledged intent of its pairs
11716        // at or below its pin. The intent or the bootstrapped row proves the
11717        // pair: a patch omits its scope columns, and the base row it merged
11718        // over may be gone (a §7.4.4 reset before the ACK).
11719        for table in self.schema.tables.clone() {
11720            let Some(effective) = covers(&table, &unit.scopes)
11721                .then(|| pair_scopes(&unit.scopes, &table.name, Some(&echo)))
11722                .flatten()
11723            else {
11724                continue;
11725            };
11726            let mut statement = self
11727                .conn
11728                .prepare("SELECT id,intent_json FROM _syncular_acked_rows WHERE tbl=?1 AND commit_seq<=?2")
11729                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11730            let rows = statement
11731                .query_map(rusqlite::params![table.name, next_cursor], |row| {
11732                    Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
11733                })
11734                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11735            let mut covered = HashSet::new();
11736            for row in rows {
11737                let (id, intent) =
11738                    row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11739                let values: Map<String, Value> =
11740                    serde_json::from_str(&intent).map_err(|_| "sync.local_corrupt".to_owned())?;
11741                let base = self.stored_row(&table, &id, true)?.map(|(row, _)| {
11742                    table
11743                        .columns
11744                        .iter()
11745                        .zip(&row)
11746                        .map(|(column, value)| (column.name.clone(), column_value_to_json(value)))
11747                        .collect()
11748                });
11749                if [Some(values), base]
11750                    .iter()
11751                    .flatten()
11752                    .any(|values| owns_local_row(&table, &effective, &[], values))
11753                {
11754                    covered.insert(id);
11755                }
11756            }
11757            drop(statement);
11758            for id in covered {
11759                self.conn
11760                    .execute(
11761                        "DELETE FROM _syncular_acked_rows WHERE tbl=?1 AND id=?2 AND commit_seq<=?3",
11762                        rusqlite::params![table.name, id, next_cursor],
11763                    )
11764                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11765                self.overlay_dirty.table(&table.name);
11766                batch.table(&table.name);
11767            }
11768        }
11769        Ok(batch)
11770    }
11771
11772    /// §3.3: purge one revoked pair inside the caller's observation: delete
11773    /// the rows matching its last effective scopes that no owner holds, drop
11774    /// the retained intent and every pending commit that provably writes into
11775    /// them, and delete now-unauthorized blob bodies. `Ok(false)` when the
11776    /// table has no local scope-column mapping (fail closed: nothing deleted).
11777    fn purge_pair(
11778        &mut self,
11779        batch: &mut ChangeAccumulator,
11780        table: &TableSchema,
11781        last: &[(String, Vec<String>)],
11782        owners: &[Vec<(String, Vec<String>)>],
11783    ) -> Result<bool, String> {
11784        if local_scope_predicate(table, last, owners).is_err() {
11785            return Ok(false);
11786        }
11787        for commit in self.drop_failed_commits(|name, values| {
11788            name == table.name && owns_local_row(table, last, owners, values)
11789        })? {
11790            batch.conflicts = true;
11791            batch.rejections = true;
11792            batch.outcomes = true;
11793            for operation in commit.ops {
11794                batch.table(&operation.table);
11795            }
11796        }
11797        if !self.purge_scope_rows(&table.name, last, owners)? {
11798            return Err("storage.failed: the revoked scope purge failed".to_owned());
11799        }
11800        self.record_scope_map(batch, &table.name, last);
11801        if self.drop_doomed_outbox(table, last, owners)? {
11802            batch.status = true;
11803            batch.rejections = true;
11804            batch.outcomes = true;
11805        }
11806        // §5.9.7 B2: revocation deletes now-unauthorized blob bodies.
11807        self.delete_unreferenced_cached_blobs()?;
11808        Ok(true)
11809    }
11810
11811    /// §4.5 client application: apply one live-section or delta `COMMIT`
11812    /// with only the changes that match the persisted echo of a receiving
11813    /// unit; every applied change then goes through the version guard.
11814    /// Returns whether any change of the frame applied.
11815    fn apply_live_commit(
11816        &mut self,
11817        receivers: &[UnitRecord],
11818        tables: &[String],
11819        changes: Vec<ssp2::model::Change>,
11820        commit_seq: i64,
11821        source: AppliedServerCommitSource,
11822    ) -> Result<bool, TransportError> {
11823        let changes: Vec<ssp2::model::Change> = changes
11824            .into_iter()
11825            .filter(|change| {
11826                // An unknown table fails loud in the apply below.
11827                let Some(table) = tables
11828                    .get(change.table_index as usize)
11829                    .and_then(|name| self.schema.table(name))
11830                else {
11831                    return true;
11832                };
11833                receivers.iter().any(|unit| {
11834                    covers(table, &unit.scopes)
11835                        && pair_scopes(&unit.scopes, &table.name, unit.echo.as_deref()).is_some_and(
11836                            |scopes| {
11837                                scopes.iter().all(|(variable, values)| {
11838                                    change
11839                                        .scopes
11840                                        .iter()
11841                                        .find(|(key, _)| key == variable)
11842                                        .is_some_and(|(_, value)| values.contains(value))
11843                                })
11844                            },
11845                        )
11846                })
11847            })
11848            .collect();
11849        if changes.is_empty() {
11850            return Ok(false);
11851        }
11852        let affected_tables = changes
11853            .iter()
11854            .filter_map(|change| tables.get(change.table_index as usize))
11855            .cloned()
11856            .collect::<BTreeSet<_>>();
11857        let previous_batches = self.change_queue.len();
11858        self.apply_commit_frame(tables, &changes, commit_seq)?;
11859        if self.change_queue.len() > previous_batches {
11860            if let Some(batch) = self.change_queue.back_mut() {
11861                batch
11862                    .applied_commits
11863                    .extend(
11864                        affected_tables
11865                            .into_iter()
11866                            .map(|table| AppliedServerCommit {
11867                                table,
11868                                commit_seq,
11869                                source,
11870                            }),
11871                    );
11872            }
11873        }
11874        Ok(true)
11875    }
11876
11877    // Both pull and realtime frames use the same durable observation boundary.
11878    fn apply_commit_frame(
11879        &mut self,
11880        tables: &[String],
11881        changes: &[ssp2::model::Change],
11882        sequence: i64,
11883    ) -> Result<(), TransportError> {
11884        #[cfg(feature = "bench-internals")]
11885        let _phase = self.benchmark_phases.start(Phase::CommitApply);
11886        let rollback = self.capture();
11887        self.coalesce_unit(changes.len())
11888            .and_then(|()| self.begin_observation("syncular_commit"))
11889            .map_err(|message| TransportError::new("storage.failed", message))?;
11890        let applied = (|| {
11891            let mut batch = ChangeAccumulator::default();
11892            self.record_commit_changes(&mut batch, tables, changes);
11893            // §7.1 chained base: a change names the version an acknowledged own
11894            // commit wrote; pending upserts chained on it move to that version.
11895            for change in changes {
11896                let Some(table) = tables.get(change.table_index as usize) else {
11897                    continue;
11898                };
11899                let acknowledged = self
11900                    .conn
11901                    .prepare_cached("SELECT op_json FROM _syncular_acked_rows WHERE tbl=?1 AND id=?2 AND commit_seq=?3")
11902                    .and_then(|mut statement| {
11903                        statement
11904                            .query_map(rusqlite::params![table, change.row_id, sequence], |row| row.get::<_, String>(0))?
11905                            .collect::<Result<Vec<_>, _>>()
11906                    })
11907                    .map_err(|error| TransportError::new("storage.failed", Self::sqlite_failure(&self.storage_failure, error)))?
11908                    .iter()
11909                    .map(|op| serde_json::from_str::<CommitOperation>(op).map(OutboxOp::from))
11910                    .collect::<Result<Vec<_>, _>>()
11911                    .map_err(|_| TransportError::new("storage.failed", "sync.local_corrupt: invalid acknowledged operation".to_owned()))?;
11912                for index in 0..self.outbox.len() {
11913                    if !self.outbox[index]
11914                        .ops
11915                        .iter()
11916                        .any(|op| acknowledged.iter().any(|earlier| chains_on(earlier, op)))
11917                    {
11918                        continue;
11919                    }
11920                    let commit = Arc::make_mut(&mut self.outbox[index]);
11921                    for op in &mut commit.ops {
11922                        if acknowledged.iter().any(|earlier| chains_on(earlier, op)) {
11923                            op.base_version = Some(change.row_version);
11924                        }
11925                    }
11926                    let ops = serde_json::to_string(
11927                        &commit
11928                            .ops
11929                            .iter()
11930                            .map(CommitOperation::from)
11931                            .collect::<Vec<_>>(),
11932                    )
11933                    .map_err(|_| {
11934                        TransportError::new(
11935                            "storage.failed",
11936                            "sync.local_corrupt: unencodable outbox".to_owned(),
11937                        )
11938                    })?;
11939                    let id = commit.client_commit_id.clone();
11940                    self.conn
11941                        .execute(
11942                            "UPDATE _syncular_outbox SET ops_json=?1 WHERE commit_id=?2",
11943                            rusqlite::params![ops, id],
11944                        )
11945                        .map_err(|error| {
11946                            TransportError::new(
11947                                "storage.failed",
11948                                Self::sqlite_failure(&self.storage_failure, error),
11949                            )
11950                        })?;
11951                }
11952            }
11953            {
11954                let storage_failed = |error| {
11955                    TransportError::new(
11956                        "storage.failed",
11957                        Self::sqlite_failure(&self.storage_failure, error),
11958                    )
11959                };
11960                let pinned: HashSet<(&str, &str)> = self
11961                    .outbox
11962                    .iter()
11963                    .flat_map(|commit| &commit.ops)
11964                    .map(|op| (op.table.as_str(), op.row_id.as_str()))
11965                    .collect();
11966                for change in changes {
11967                    let table = tables.get(change.table_index as usize).ok_or_else(|| {
11968                        TransportError::new(
11969                            "sync.invalid_request",
11970                            "change tableIndex out of range".to_owned(),
11971                        )
11972                    })?;
11973                    if pinned.contains(&(table.as_str(), change.row_id.as_str())) {
11974                        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)")
11975                            .and_then(|mut statement| statement.execute(rusqlite::params![table, change.row_id, sequence]))
11976                            .map_err(storage_failed)?;
11977                    }
11978                    self.conn.prepare_cached("DELETE FROM _syncular_acked_rows WHERE tbl=?1 AND id=?2 AND commit_seq<=?3")
11979                        .and_then(|mut statement| statement.execute(rusqlite::params![table, change.row_id, sequence]))
11980                        .map_err(storage_failed)?;
11981                }
11982            }
11983            self.apply_commit_changes(tables, changes)?;
11984            self.rebuild_overlay_if_dirty()
11985                .map_err(|message| TransportError::new("storage.failed", message))?;
11986            self.finish_observation("syncular_commit", batch)
11987                .map_err(|message| TransportError::new("storage.failed", message))
11988        })();
11989        if applied.is_err() {
11990            self.rollback_observation("syncular_commit");
11991            self.restore(rollback);
11992        }
11993        applied
11994    }
11995
11996    fn apply_commit_changes(
11997        &mut self,
11998        tables: &[String],
11999        changes: &[ssp2::model::Change],
12000    ) -> Result<(), TransportError> {
12001        // A clean overlay can reconcile changed primary keys independently
12002        // when their tables have no secondary unique constraints. Such a
12003        // constraint can change whether another row's write succeeds, so a
12004        // table with one and any local intent takes the table rebuild.
12005        let changed_tables: BTreeSet<&str> = changes
12006            .iter()
12007            .filter_map(|change| tables.get(change.table_index as usize))
12008            .map(String::as_str)
12009            .collect();
12010        let mut mirror_visible = !self.overlay_dirty.get();
12011        for name in &changed_tables {
12012            if mirror_visible
12013                && self
12014                    .schema
12015                    .table(name)
12016                    .is_some_and(|table| table.indexes.iter().any(|index| index.unique))
12017            {
12018                let (pending, protected) = self
12019                    .table_intent(name)
12020                    .map_err(|message| TransportError::new("storage.failed", message))?;
12021                mirror_visible = !pending && !protected;
12022            }
12023        }
12024        for change in changes {
12025            let table_name = tables.get(change.table_index as usize).ok_or_else(|| {
12026                TransportError::new(
12027                    "sync.invalid_request",
12028                    "change tableIndex out of range".to_owned(),
12029                )
12030            })?;
12031            let table = self.schema.table(table_name).ok_or_else(|| {
12032                TransportError::new(
12033                    "sync.schema_mismatch",
12034                    format!("change targets unknown table {table_name:?}"),
12035                )
12036            })?;
12037            let landed = match change.op {
12038                Op::Upsert => {
12039                    let payload = change.row.as_ref().ok_or_else(|| {
12040                        TransportError::new(
12041                            "sync.invalid_request",
12042                            "upsert change without row payload".to_owned(),
12043                        )
12044                    })?;
12045                    // §5.11: decrypt encrypted columns on apply, or seal the row.
12046                    let (row, sealed) = {
12047                        #[cfg(feature = "bench-internals")]
12048                        let _phase = self.benchmark_phases.start(Phase::RowDecode);
12049                        // §5.11: a decrypt failure keeps its own identity.
12050                        decode_row_bytes(table, payload, &self.encryption)?
12051                    };
12052                    let table_name = table.name.clone();
12053                    // §4.5 version guard: only a newer upsert lands.
12054                    let landed = self
12055                        .write_base_row(&table_name, &row, change.row_version, sealed.as_ref())
12056                        .map_err(|m| TransportError::new("sync.invalid_request", m))?;
12057                    if mirror_visible && landed {
12058                        self.write_row(
12059                            &visible_table(&table_name),
12060                            &table_name,
12061                            &row,
12062                            change.row_version,
12063                            sealed.as_ref(),
12064                        )
12065                        .map_err(|m| TransportError::new("sync.invalid_request", m))?;
12066                    }
12067                    landed
12068                }
12069                // §4.5 version guard: a delete at or below the local version
12070                // is skipped, a delete of an absent row is a no-op.
12071                Op::Delete => self
12072                    .delete_base_row(table_name, &change.row_id, change.row_version)
12073                    .map_err(|m| TransportError::new("sync.invalid_request", m))?,
12074            };
12075            // The change dropped the row's acknowledged intent either way
12076            // (§7.1), so the overlay of a skipped change rebuilds from the
12077            // unchanged base.
12078            self.overlay_dirty.table(table_name);
12079            if mirror_visible && !(landed && change.op == Op::Upsert) {
12080                let predicate = row_id_predicate(table);
12081                let visible = visible_table(table_name);
12082                let mut statements = vec![format!("DELETE FROM {visible} WHERE {predicate}")];
12083                if !landed {
12084                    statements.push(format!(
12085                        "INSERT INTO {visible} SELECT * FROM {} WHERE {predicate}",
12086                        base_table(table_name)
12087                    ));
12088                }
12089                for statement in &statements {
12090                    self.conn
12091                        .prepare_cached(statement)
12092                        .and_then(|mut statement| {
12093                            statement.execute(rusqlite::params![change.row_id])
12094                        })
12095                        .map_err(|error| {
12096                            TransportError::new("sync.invalid_request", error.to_string())
12097                        })?;
12098                }
12099            }
12100        }
12101        if mirror_visible {
12102            let changed_rows: HashSet<(&str, &str)> = changes
12103                .iter()
12104                .map(|change| {
12105                    (
12106                        tables[change.table_index as usize].as_str(),
12107                        change.row_id.as_str(),
12108                    )
12109                })
12110                .collect();
12111            self.replay_overlay(&changed_tables, Some(&changed_rows))
12112                .map_err(|message| TransportError::new("storage.failed", message))?;
12113            self.overlay_dirty.set(false);
12114        }
12115        Ok(())
12116    }
12117
12118    /// §5.6 segment application: validate against the generated schema,
12119    /// clear the pair's scope on the table's first page (fail closed
12120    /// without a mapping), then upsert each row with its segment-carried
12121    /// server version under the §4.5 version guard (§5.2).
12122    fn apply_segment(
12123        &mut self,
12124        table: &TableSchema,
12125        segment: &RowsSegment,
12126        first_page: bool,
12127        effective: &[(String, Vec<String>)],
12128        unit_id: &str,
12129    ) -> Result<u32, SectionError> {
12130        // §5.2: the column table validates against the generated schema —
12131        // order, names, types, nullability; mismatch is fatal. §5.11: the
12132        // server sends the WIRE types (bytes for an encrypted column), so
12133        // validate against wire_columns.
12134        let column = if segment.columns.len() != table.wire_columns.len() {
12135            Some(Value::from("count"))
12136        } else {
12137            segment
12138                .columns
12139                .iter()
12140                .zip(table.wire_columns.iter())
12141                .position(|(a, b)| a.name != b.name || a.ty != b.ty || a.nullable != b.nullable)
12142                .map(Value::from)
12143        };
12144        if segment.table != table.name
12145            || segment.schema_version != self.schema.version
12146            || column.is_some()
12147        {
12148            let mut details = Map::new();
12149            details.insert("table".to_owned(), Value::from(table.name.as_str()));
12150            if let Some(column) = column {
12151                details.insert("column".to_owned(), column);
12152            }
12153            return Err(SectionError::Transport(TransportError {
12154                code: "sync.schema_mismatch".to_owned(),
12155                message: "rows segment columns do not match the generated schema (§5.2)".to_owned(),
12156                details: Some(Value::Object(details)),
12157            }));
12158        }
12159        let mut applied = 0u32;
12160        let (mut write, mut commit) = (std::time::Duration::ZERO, std::time::Duration::ZERO);
12161        let empty = Vec::new();
12162        let blocks = if segment.blocks.is_empty() {
12163            std::slice::from_ref(&empty)
12164        } else {
12165            &segment.blocks
12166        };
12167        for (index, block) in blocks.iter().enumerate() {
12168            let clear = first_page && index == 0;
12169            if !clear && block.is_empty() {
12170                continue;
12171            }
12172            let rollback = self.capture();
12173            let (pending, protected) = self
12174                .table_intent(&table.name)
12175                .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12176            let reconcile_pending =
12177                !protected && pending && table.indexes.iter().any(|index| index.unique);
12178            let mirror_visible = !protected && !reconcile_pending;
12179            self.coalesce_unit(block.len())
12180                .and_then(|()| self.begin_observation("syncular_segment_block"))
12181                .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12182            let started = std::time::Instant::now();
12183            let outcome = (|| {
12184                self.rebuild_overlay_if_dirty()
12185                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12186                let mut changed_keys = Vec::new();
12187                let mut batch = ChangeAccumulator::default();
12188                if clear && self.clear_scope(table, effective, unit_id)? || !block.is_empty() {
12189                    batch.table(&table.name);
12190                }
12191                for (row_index, row) in block.iter().enumerate() {
12192                    let decrypted;
12193                    let mut sealed = None;
12194                    let values = if table.has_encrypted_columns() {
12195                        let mut values = row.values.clone();
12196                        sealed = crate::values::decrypt_segment_row(
12197                            table,
12198                            &mut values,
12199                            &self.encryption,
12200                        )
12201                        .map_err(SectionError::Transport)?;
12202                        decrypted = values;
12203                        &decrypted
12204                    } else {
12205                        &row.values
12206                    };
12207                    if !self
12208                        .write_base_row(&table.name, values, row.server_version, sealed.as_ref())
12209                        .map_err(|message| {
12210                            SectionError::Abort("sync.invalid_request".into(), message)
12211                        })?
12212                    {
12213                        continue;
12214                    }
12215                    if reconcile_pending {
12216                        changed_keys.push(
12217                            owned_sql_value(RowParam::Cell(&values[table.pk_index])).map_err(
12218                                |message| SectionError::Abort("storage.failed".into(), message),
12219                            )?,
12220                        );
12221                    }
12222                    if mirror_visible {
12223                        self.write_row(
12224                            &visible_table(&table.name),
12225                            &table.name,
12226                            values,
12227                            row.server_version,
12228                            sealed.as_ref(),
12229                        )
12230                        .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12231                    }
12232                    let processed = u64::from(applied) + row_index as u64 + 1;
12233                    if processed.is_multiple_of(1024) {
12234                        self.progress.update(|p| p.rows_processed = processed);
12235                    }
12236                }
12237                self.reconcile_import(table, &mut changed_keys, protected, reconcile_pending)
12238                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12239                let written = std::time::Instant::now();
12240                self.finish_observation("syncular_segment_block", batch)
12241                    .map(|()| written)
12242                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))
12243            })();
12244            let written = match outcome {
12245                Ok(written) => written,
12246                Err(error) => {
12247                    self.rollback_observation("syncular_segment_block");
12248                    self.restore(rollback);
12249                    return Err(error);
12250                }
12251            };
12252            // §7.7: a payload reports its import cost.
12253            write += written - started;
12254            commit += written.elapsed();
12255            applied += block.len() as u32;
12256            self.progress.update(|p| {
12257                p.rows_processed = u64::from(applied);
12258                p.import_write_ms = u64::try_from(write.as_millis()).ok();
12259                p.import_commit_ms = u64::try_from(commit.as_millis()).ok();
12260            });
12261            std::thread::yield_now();
12262        }
12263        self.progress
12264            .update(|p| p.rows_processed = u64::from(applied));
12265        Ok(applied)
12266    }
12267
12268    /// §5.3 sqlite-image application: validate the in-file metadata
12269    /// against the descriptor, validate column names/order against the
12270    /// generated schema, run the §5.6 first-page clear when fresh, then
12271    /// replace-or-upsert every image row with its `_syncular_version`.
12272    /// Mechanics: the image lands in a temp file read through a second
12273    /// rusqlite connection, equivalent to ATTACH + INSERT…SELECT.
12274    /// Each image chunk commits its writes and revision before readers continue.
12275    #[allow(clippy::too_many_arguments)]
12276    fn apply_sqlite_segment(
12277        &mut self,
12278        table: &TableSchema,
12279        bytes: &[u8],
12280        first_page: bool,
12281        effective: &[(String, Vec<String>)],
12282        unit_id: &str,
12283        segment_id: &str,
12284        resumed: i64,
12285        row_count: i64,
12286        as_of_commit_seq: i64,
12287        scope_digest: &str,
12288    ) -> Result<u32, SectionError> {
12289        let invalid = |detail: &str| {
12290            SectionError::Abort(
12291                "sync.invalid_request".to_owned(),
12292                format!("sqlite segment rejected: {detail} (§5.3)"),
12293            )
12294        };
12295        // §5.11: an image bypasses the decrypt seam, so a server cannot serve
12296        // one for a table with encrypted columns.
12297        if table.has_encrypted_columns() {
12298            return Err(invalid("table has encrypted columns"));
12299        }
12300
12301        // The image lands beside the replica so it shares the replica's
12302        // directory permissions and volume; an in-memory replica has no
12303        // directory and uses the system temp dir. The file is owner-only.
12304        let directory = self
12305            .previous_version_replica_path()
12306            .and_then(|replica| std::path::Path::new(&replica).parent().map(Into::into))
12307            .unwrap_or_else(std::env::temp_dir);
12308        let path = directory.join(format!(".syncular-image-{}.tmp", uuid::Uuid::new_v4()));
12309        let outcome = (|| {
12310            let mut options = std::fs::OpenOptions::new();
12311            options.write(true).create_new(true);
12312            #[cfg(unix)]
12313            std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
12314            std::io::Write::write_all(
12315                &mut options
12316                    .open(&path)
12317                    .map_err(|_| invalid("image temp file write failed"))?,
12318                bytes,
12319            )
12320            .map_err(|_| invalid("image temp file write failed"))?;
12321            let img = rusqlite::Connection::open_with_flags(
12322                &path,
12323                rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
12324            )
12325            .map_err(|_| invalid("bytes do not open as a SQLite database"))?;
12326            self.apply_sqlite_image(
12327                &img,
12328                table,
12329                first_page,
12330                effective,
12331                unit_id,
12332                segment_id,
12333                resumed,
12334                row_count,
12335                as_of_commit_seq,
12336                scope_digest,
12337            )
12338        })();
12339        let _ = std::fs::remove_file(&path);
12340        outcome
12341    }
12342
12343    #[allow(clippy::too_many_arguments)]
12344    fn apply_sqlite_image(
12345        &mut self,
12346        img: &rusqlite::Connection,
12347        table: &crate::schema::TableSchema,
12348        first_fresh_page: bool,
12349        effective: &[(String, Vec<String>)],
12350        unit_id: &str,
12351        segment_id: &str,
12352        resumed: i64,
12353        row_count: i64,
12354        as_of_commit_seq: i64,
12355        scope_digest: &str,
12356    ) -> Result<u32, SectionError> {
12357        let invalid = |detail: String| {
12358            SectionError::Abort(
12359                "sync.invalid_request".to_owned(),
12360                format!("sqlite segment rejected: {detail} (§5.3)"),
12361            )
12362        };
12363
12364        // 1. Metadata vs descriptor + client state (§5.3 rule 2; exactly
12365        //    one row).
12366        type MetaRow = (i64, String, i64, i64, String, i64, i64);
12367        let meta: MetaRow = img
12368            .query_row(
12369                "SELECT format, \"table\", \"schemaVersion\", \"asOfCommitSeq\",
12370                        \"scopeDigest\", \"rowCount\",
12371                        (SELECT count(*) FROM _syncular_segment)
12372                 FROM _syncular_segment",
12373                [],
12374                |row| {
12375                    Ok((
12376                        row.get(0)?,
12377                        row.get(1)?,
12378                        row.get(2)?,
12379                        row.get(3)?,
12380                        row.get(4)?,
12381                        row.get(5)?,
12382                        row.get(6)?,
12383                    ))
12384                },
12385            )
12386            .map_err(|_| invalid("missing or unreadable _syncular_segment metadata".to_owned()))?;
12387        let (format, meta_table, schema_version, pin, digest, meta_rows, meta_count) = meta;
12388        if meta_count != 1 {
12389            return Err(invalid(format!(
12390                "_syncular_segment must contain exactly one row, found {meta_count}"
12391            )));
12392        }
12393        if format != 1 {
12394            return Err(invalid(format!("format {format}")));
12395        }
12396        if meta_table != table.name {
12397            return Err(invalid(format!("image table {meta_table:?}")));
12398        }
12399        if schema_version != i64::from(self.schema.version) {
12400            return Err(invalid(format!("schemaVersion {schema_version}")));
12401        }
12402        if pin != as_of_commit_seq {
12403            return Err(invalid(format!("asOfCommitSeq {pin}")));
12404        }
12405        if digest != scope_digest {
12406            return Err(invalid("scopeDigest mismatch".to_owned()));
12407        }
12408        if meta_rows != row_count {
12409            return Err(invalid(format!("rowCount {meta_rows}")));
12410        }
12411
12412        // 2. Column names and order vs the generated schema (§5.3 rule 3).
12413        let mut names: Vec<String> = Vec::new();
12414        let mut primary_keys: Vec<String> = Vec::new();
12415        {
12416            let mut stmt = img
12417                .prepare(&format!("PRAGMA table_info({})", quote_ident(&table.name)))
12418                .map_err(|_| invalid("image data table missing".to_owned()))?;
12419            let mut rows = stmt
12420                .query([])
12421                .map_err(|_| invalid("image data table unreadable".to_owned()))?;
12422            while let Some(row) = rows
12423                .next()
12424                .map_err(|_| invalid("image data table unreadable".to_owned()))?
12425            {
12426                if row
12427                    .get::<_, i64>(5)
12428                    .map_err(|error| invalid(Self::sqlite_failure(&self.storage_failure, error)))?
12429                    > 0
12430                {
12431                    primary_keys.push(row.get(1).map_err(|error| {
12432                        invalid(Self::sqlite_failure(&self.storage_failure, error))
12433                    })?);
12434                }
12435                names.push(
12436                    row.get::<_, String>(1)
12437                        .map_err(|_| invalid("image data table unreadable".to_owned()))?,
12438                );
12439            }
12440        }
12441        let mut expected: Vec<&str> = table.columns.iter().map(|c| c.name.as_str()).collect();
12442        expected.push("_syncular_version");
12443        if names.len() != expected.len() || names.iter().zip(expected.iter()).any(|(a, b)| a != b) {
12444            return Err(SectionError::Transport(TransportError {
12445                code: "sync.schema_mismatch".to_owned(),
12446                message: "sqlite segment columns do not match the generated schema (§5.3)"
12447                    .to_owned(),
12448                details: Some(serde_json::json!({ "table": table.name })),
12449            }));
12450        }
12451
12452        if primary_keys != vec![table.primary_key.clone()] {
12453            return Err(invalid(
12454                "image primary key does not match generated schema".into(),
12455            ));
12456        }
12457        let actual_count: i64 = img
12458            .query_row(
12459                &format!("SELECT count(*) FROM {}", quote_ident(&table.name)),
12460                [],
12461                |row| row.get(0),
12462            )
12463            .map_err(|error| invalid(Self::sqlite_failure(&self.storage_failure, error)))?;
12464        if actual_count != row_count {
12465            return Err(invalid("image row count does not match descriptor".into()));
12466        }
12467        let insert = self.insert_row_sql(&base_table(&table.name), table);
12468        let visible_insert = self.insert_row_sql(&visible_table(&table.name), table);
12469        let column_list = names
12470            .iter()
12471            .map(|n| quote_ident(n))
12472            .collect::<Vec<_>>()
12473            .join(", ");
12474        // §5.6: an earlier attempt at this position committed the first
12475        // `resumed` rows in primary-key order; the content address pins them.
12476        let mut stmt = img
12477            .prepare(&format!(
12478                "SELECT {column_list} FROM {} ORDER BY {} LIMIT -1 OFFSET ?1",
12479                quote_ident(&table.name),
12480                quote_ident(&table.primary_key)
12481            ))
12482            .map_err(|error| invalid(Self::sqlite_failure(&self.storage_failure, error)))?;
12483        let mut rows = stmt
12484            .query([resumed])
12485            .map_err(|error| invalid(Self::sqlite_failure(&self.storage_failure, error)))?;
12486        let resumed = u32::try_from(resumed)
12487            .ok()
12488            .filter(|rows| i64::from(*rows) <= actual_count)
12489            .ok_or_else(|| invalid("applied-segment record exceeds the image".into()))?;
12490        let mut applied = resumed;
12491        let mut limit = if first_fresh_page {
12492            1024
12493        } else {
12494            self.image_chunk_rows
12495                .get(&table.name)
12496                .copied()
12497                .unwrap_or(1024)
12498        };
12499        let (mut write, mut commit) = (std::time::Duration::ZERO, std::time::Duration::ZERO);
12500        loop {
12501            let clear = applied == 0 && first_fresh_page;
12502            let rollback = self.capture();
12503            let (pending, protected) = self
12504                .table_intent(&table.name)
12505                .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12506            let reconcile_pending =
12507                !protected && pending && table.indexes.iter().any(|index| index.unique);
12508            let mirror_visible = !protected && !reconcile_pending;
12509            // §5.3: a table's first chunk holds 1,024 rows; a later range image
12510            // starts at the size its previous range reached. A later chunk holds at
12511            // least 1,024 rows, at most twice the rows of the one before, at
12512            // most 65,536, and at most the rows the one before applied per
12513            // 250 ms of its time before COMMIT; a chunk that replays local
12514            // writes holds at most 1,024.
12515            let chunk = if pending || protected {
12516                limit.min(1024)
12517            } else {
12518                limit
12519            };
12520            self.coalesce_unit(chunk as usize)
12521                .and_then(|()| self.begin_observation("syncular_image_chunk"))
12522                .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12523            let started = std::time::Instant::now();
12524            let result = (|| {
12525                self.rebuild_overlay_if_dirty()
12526                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12527                let mut changed_keys = Vec::new();
12528                let mut batch = ChangeAccumulator::default();
12529                if clear && self.clear_scope(table, effective, unit_id)? {
12530                    batch.table(&table.name);
12531                }
12532                let mut processed = 0u32;
12533                {
12534                    let mut ins = self.conn.prepare_cached(&insert).map_err(|error| {
12535                        invalid(Self::sqlite_failure(&self.storage_failure, error))
12536                    })?;
12537                    let mut mirror = if mirror_visible {
12538                        Some(self.conn.prepare_cached(&visible_insert).map_err(|error| {
12539                            invalid(Self::sqlite_failure(&self.storage_failure, error))
12540                        })?)
12541                    } else {
12542                        None
12543                    };
12544                    for _ in 0..chunk {
12545                        let Some(row) = rows.next().map_err(|error| {
12546                            invalid(Self::sqlite_failure(&self.storage_failure, error))
12547                        })?
12548                        else {
12549                            break;
12550                        };
12551                        for (i, column) in table.columns.iter().enumerate() {
12552                            let cell = row.get_ref(i).map_err(|error| {
12553                                invalid(Self::sqlite_failure(&self.storage_failure, error))
12554                            })?;
12555                            let param = image_cell_param(column, cell).map_err(invalid)?;
12556                            ins.raw_bind_parameter(i + 1, &param).map_err(|error| {
12557                                invalid(Self::sqlite_failure(&self.storage_failure, error))
12558                            })?;
12559                            if let Some(mirror) = &mut mirror {
12560                                mirror.raw_bind_parameter(i + 1, &param).map_err(|error| {
12561                                    invalid(Self::sqlite_failure(&self.storage_failure, error))
12562                                })?;
12563                            }
12564                        }
12565                        let version_index = table.columns.len();
12566                        let version: i64 = row.get(version_index).map_err(|error| {
12567                            invalid(Self::sqlite_failure(&self.storage_failure, error))
12568                        })?;
12569                        if version < 1 {
12570                            return Err(invalid("image row version must be positive".into()));
12571                        }
12572                        ins.raw_bind_parameter(version_index + 1, version)
12573                            .map_err(|error| {
12574                                invalid(Self::sqlite_failure(&self.storage_failure, error))
12575                            })?;
12576                        // §4.5 version guard: the base upsert decides.
12577                        let landed = ins.raw_execute().map_err(|error| {
12578                            invalid(Self::sqlite_failure(&self.storage_failure, error))
12579                        })? > 0;
12580                        processed += 1;
12581                        if processed.is_multiple_of(1024) && processed < chunk {
12582                            self.progress
12583                                .update(|p| p.rows_processed = u64::from(applied + processed));
12584                        }
12585                        if !landed {
12586                            continue;
12587                        }
12588                        if let Some(mirror) = &mut mirror {
12589                            mirror
12590                                .raw_bind_parameter(version_index + 1, version)
12591                                .map_err(|error| {
12592                                    invalid(Self::sqlite_failure(&self.storage_failure, error))
12593                                })?;
12594                            mirror.raw_execute().map_err(|error| {
12595                                invalid(Self::sqlite_failure(&self.storage_failure, error))
12596                            })?;
12597                        }
12598                        if reconcile_pending {
12599                            changed_keys.push(row.get::<_, SqlValue>(table.pk_index).map_err(
12600                                |error| invalid(Self::sqlite_failure(&self.storage_failure, error)),
12601                            )?);
12602                        }
12603                    }
12604                }
12605                if processed > 0 {
12606                    batch.table(&table.name);
12607                    self.overlay_dirty.table(&table.name);
12608                }
12609                self.stored(record_applied_rows(
12610                    &self.conn,
12611                    unit_id,
12612                    segment_id,
12613                    i64::from(applied + processed),
12614                ))
12615                .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12616                self.reconcile_import(table, &mut changed_keys, protected, reconcile_pending)
12617                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12618                let written = std::time::Instant::now();
12619                self.finish_observation("syncular_image_chunk", batch)
12620                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12621                Ok((processed, written))
12622            })();
12623            let (processed, written) = match result {
12624                Ok(done) => done,
12625                Err(error) => {
12626                    self.rollback_observation("syncular_image_chunk");
12627                    self.restore(rollback);
12628                    return Err(error);
12629                }
12630            };
12631            // The chunk commits before the yield, also inside a coalesced apply.
12632            let coalesced = self.coalesced.is_some();
12633            if coalesced {
12634                self.commit_coalesced_apply()
12635                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12636            }
12637            let spent = (written - started, written.elapsed());
12638            #[cfg(test)]
12639            let spent = self.image_chunk_ms.get().map_or(spent, |(write, commit)| {
12640                (
12641                    std::time::Duration::from_secs_f64(write / 1000.0),
12642                    std::time::Duration::from_secs_f64(commit / 1000.0),
12643                )
12644            });
12645            write += spent.0;
12646            commit += spent.1;
12647            applied += processed;
12648            let last = processed < chunk || i64::from(applied) == actual_count;
12649            // A file replica's WAL keeps its high-water size until truncated.
12650            if last && self.conn.is_autocommit() {
12651                self.conn
12652                    .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
12653                    .map_err(|error| invalid(Self::sqlite_failure(&self.storage_failure, error)))?;
12654            }
12655            if coalesced {
12656                self.begin_coalesced_apply()
12657                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12658            }
12659            self.progress.update(|p| {
12660                p.rows_processed = u64::from(applied);
12661                p.import_write_ms = u64::try_from(write.as_millis()).ok();
12662                p.import_commit_ms = u64::try_from(commit.as_millis()).ok();
12663            });
12664            let duration = spent.0.as_secs_f64() * 1000.0;
12665            std::thread::yield_now();
12666            if last {
12667                break;
12668            }
12669            // A zero duration saturates the cast and leaves the doubling.
12670            limit = (processed * 2)
12671                .min(65_536)
12672                .min((f64::from(processed) * 250.0 / duration) as u32)
12673                .max(1024);
12674            self.image_chunk_rows.insert(table.name.clone(), limit);
12675        }
12676        if i64::from(applied) != actual_count {
12677            return Err(invalid(format!(
12678                "image yielded {applied} rows, expected {actual_count}"
12679            )));
12680        }
12681        Ok(applied - resumed)
12682    }
12683
12684    /// §7.1 keyed reconciliation of the rows `drained` commits touch: restore
12685    /// them from the base and replay their remaining intent. A table with a
12686    /// secondary unique index restores and replays every row with intent,
12687    /// since one row's value can admit or defer another row's write.
12688    fn reconcile_rows(&self, drained: &[Arc<OutboxCommit>]) -> Result<(), String> {
12689        let names: BTreeSet<&str> = drained
12690            .iter()
12691            .flat_map(|commit| &commit.ops)
12692            .map(|op| op.table.as_str())
12693            .collect();
12694        for name in names {
12695            let Some(table) = self.schema.table(name) else {
12696                continue;
12697            };
12698            let ops = drained.iter().flat_map(|commit| &commit.ops);
12699            let tables = BTreeSet::from([name]);
12700            let rows: HashSet<_> = ops
12701                .clone()
12702                .map(|op| (op.table.as_str(), op.row_id.as_str()))
12703                .collect();
12704            let unique = table.indexes.iter().any(|index| index.unique);
12705            let acknowledged = if unique {
12706                self.acknowledged_operations(None, Some(&tables))?
12707            } else {
12708                Vec::new()
12709            };
12710            let peers = acknowledged
12711                .iter()
12712                .chain(
12713                    self.failed_commits
12714                        .iter()
12715                        .flat_map(|(commit, _)| &commit.ops),
12716                )
12717                .chain(self.outbox.iter().flat_map(|commit| &commit.ops))
12718                .filter(|_| unique);
12719            self.restore_base_rows(table, &mut Vec::new(), peers.chain(ops.clone()))?;
12720            self.replay_overlay(&tables, (!unique).then_some(&rows))?;
12721        }
12722        Ok(())
12723    }
12724
12725    /// Whether `table` has pending outbox intent, and whether it has protected
12726    /// (acknowledged or retained failed) intent.
12727    fn table_intent(&self, table: &str) -> Result<(bool, bool), String> {
12728        let touches = |op: &OutboxOp| op.table == table;
12729        Ok((
12730            self.outbox
12731                .iter()
12732                .flat_map(|commit| &commit.ops)
12733                .any(touches),
12734            self.failed_commits
12735                .iter()
12736                .flat_map(|(commit, _)| &commit.ops)
12737                .any(touches)
12738                || self
12739                    .conn
12740                    .query_row(
12741                        "SELECT EXISTS(SELECT 1 FROM _syncular_acked_rows WHERE tbl=?1)",
12742                        [table],
12743                        |row| row.get(0),
12744                    )
12745                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?,
12746        ))
12747    }
12748
12749    /// §7.1 reconciliation after an import block or chunk. Keyed replay covers
12750    /// only pending intent, so a table with protected intent rebuilds; a
12751    /// `restore` restores the imported `keys` and every pending row first.
12752    fn reconcile_import(
12753        &mut self,
12754        table: &TableSchema,
12755        keys: &mut Vec<SqlValue>,
12756        protected: bool,
12757        restore: bool,
12758    ) -> Result<(), String> {
12759        if protected {
12760            return self.rebuild_overlay_if_dirty();
12761        }
12762        let pending = self.outbox.iter().flat_map(|commit| &commit.ops);
12763        if restore {
12764            self.restore_base_rows(table, keys, pending.clone())?;
12765        }
12766        self.apply_outbox_ops(pending.filter(|op| op.table == table.name))?;
12767        self.overlay_dirty.set(false);
12768        Ok(())
12769    }
12770
12771    /// Restore the visible rows of `keys` and of the rows `ops` touch in
12772    /// `table` from the base before the caller replays their intent. The
12773    /// caller owns the transaction and publishes its revision after replay.
12774    fn restore_base_rows<'a>(
12775        &self,
12776        table: &TableSchema,
12777        keys: &mut Vec<SqlValue>,
12778        ops: impl IntoIterator<Item = &'a OutboxOp>,
12779    ) -> Result<(), String> {
12780        let visible = visible_table(&table.name);
12781        let base = base_table(&table.name);
12782        let pk = quote_ident(&table.primary_key);
12783        let predicate = row_id_predicate(table);
12784        let mut lookup = self.conn.prepare_cached(&format!(
12785            "SELECT {pk} FROM {base} WHERE {predicate} UNION SELECT {pk} FROM {visible} WHERE {predicate}"
12786        )).map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
12787        let mut deleted = HashSet::new();
12788        for op in ops.into_iter().filter(|op| op.table == table.name) {
12789            if op.upsert {
12790                if let Some(values) = &op.values {
12791                    let key = json_to_column_value(
12792                        &table.columns[table.pk_index],
12793                        values.get(&table.primary_key),
12794                    )?;
12795                    keys.push(owned_sql_value(RowParam::Cell(&key))?);
12796                }
12797            } else if deleted.insert(&op.row_id) {
12798                keys.extend(
12799                    lookup
12800                        .query_map([&op.row_id], |row| row.get::<_, SqlValue>(0))
12801                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
12802                        .collect::<Result<Vec<_>, _>>()
12803                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?,
12804                );
12805            }
12806        }
12807        // Delete the complete affected set before restoring any base value, so
12808        // old optimistic unique values cannot collide with the new server rows.
12809        for chunk in keys.chunks(400) {
12810            let holes = vec!["?"; chunk.len()].join(",");
12811            self.conn
12812                .prepare_cached(&format!("DELETE FROM {visible} WHERE {pk} IN ({holes})"))
12813                .and_then(|mut statement| statement.execute(rusqlite::params_from_iter(chunk)))
12814                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
12815        }
12816        let updates = table
12817            .columns
12818            .iter()
12819            .map(|column| column.name.as_str())
12820            .chain(std::iter::once("_syncular_version"))
12821            .chain(table.sealed_columns().iter().copied())
12822            .filter(|name| *name != table.primary_key)
12823            .map(|name| {
12824                let name = quote_ident(name);
12825                format!("{name}=excluded.{name}")
12826            })
12827            .collect::<Vec<_>>()
12828            .join(",");
12829        for chunk in keys.chunks(400) {
12830            let holes = vec!["?"; chunk.len()].join(",");
12831            self.conn.prepare_cached(&format!("INSERT INTO {visible} SELECT * FROM {base} WHERE {pk} IN ({holes}) ON CONFLICT ({pk}) DO UPDATE SET {updates}"))
12832                .and_then(|mut statement| statement.execute(rusqlite::params_from_iter(chunk)))
12833                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
12834        }
12835        Ok(())
12836    }
12837
12838    // -- application-authorized local purge ---------------------------------------
12839
12840    fn compile_local_data_purge(
12841        &self,
12842        input: &LocalDataPurgeInput,
12843    ) -> Result<CompiledLocalDataPurge, String> {
12844        let invalid = |message: String| format!("sync.invalid_request: {message}");
12845        if input.purge_id.is_empty()
12846            || input.purge_id.len() > 128
12847            || !is_local_operation_code_like(&input.purge_id)
12848        {
12849            return Err(invalid(
12850                "local purge purgeId must be a 1–128 character code-like identifier".to_owned(),
12851            ));
12852        }
12853        if input.targets.is_empty() || input.targets.len() > MAX_LOCAL_PURGE_TARGETS {
12854            return Err(invalid(format!(
12855                "local purge needs between 1 and {MAX_LOCAL_PURGE_TARGETS} targets"
12856            )));
12857        }
12858
12859        let mut deduplicated: BTreeMap<
12860            String,
12861            (CompiledLocalDataPurgeTarget, LocalDataPurgeTarget),
12862        > = BTreeMap::new();
12863        let mut projections = BTreeSet::new();
12864        for target in &input.targets {
12865            let (table_name, raw_selectors) = match target {
12866                LocalDataPurgeTarget::Table { table, selectors } => (table, selectors),
12867                LocalDataPurgeTarget::Projection { projection } => {
12868                    projections.insert(projection.clone());
12869                    continue;
12870                }
12871            };
12872            let table = self.schema.table(table_name).ok_or_else(|| {
12873                invalid(format!("local purge names unknown table {:?}", table_name))
12874            })?;
12875            if raw_selectors.is_empty() || raw_selectors.len() > MAX_LOCAL_PURGE_SELECTORS {
12876                return Err(invalid(format!(
12877                    "local purge target {:?} needs between 1 and {MAX_LOCAL_PURGE_SELECTORS} selectors",
12878                    table_name
12879                )));
12880            }
12881            let mut selectors = Vec::with_capacity(raw_selectors.len());
12882            let mut canonical_selectors = BTreeMap::new();
12883            for (column_name, raw_values) in raw_selectors {
12884                let Some((column_index, column)) = table
12885                    .columns
12886                    .iter()
12887                    .enumerate()
12888                    .find(|(_, column)| column.name == *column_name)
12889                else {
12890                    return Err(invalid(format!(
12891                        "local purge target {:?} names unknown column {:?}",
12892                        table_name, column_name
12893                    )));
12894                };
12895                let encrypted = table
12896                    .encrypted_columns
12897                    .iter()
12898                    .any(|candidate| candidate.index == column_index);
12899                if column.ty != ColumnType::String || encrypted {
12900                    return Err(invalid(format!(
12901                        "local purge selector {:?}.{:?} must be a plaintext string column",
12902                        table_name, column_name
12903                    )));
12904                }
12905                if raw_values.is_empty() || raw_values.len() > MAX_LOCAL_PURGE_VALUES {
12906                    return Err(invalid(format!(
12907                        "local purge selector {:?}.{:?} needs between 1 and {MAX_LOCAL_PURGE_VALUES} values",
12908                        table_name, column_name
12909                    )));
12910                }
12911                let mut values = raw_values.clone();
12912                values.sort();
12913                values.dedup();
12914                if values.iter().any(|value| {
12915                    value.is_empty()
12916                        || value.len() > MAX_LOCAL_PURGE_VALUE_LENGTH
12917                        || !is_local_operation_code_like(value)
12918                }) {
12919                    return Err(invalid(format!(
12920                        "local purge selector values must be 1–{MAX_LOCAL_PURGE_VALUE_LENGTH} character code-like identifiers"
12921                    )));
12922                }
12923                selectors.push((column_name.clone(), values.clone()));
12924                canonical_selectors.insert(column_name.clone(), values);
12925            }
12926            let canonical = LocalDataPurgeTarget::Table {
12927                table: table_name.clone(),
12928                selectors: canonical_selectors,
12929            };
12930            let key = serde_json::to_string(&canonical).map_err(|error| error.to_string())?;
12931            deduplicated.insert(
12932                key,
12933                (
12934                    CompiledLocalDataPurgeTarget {
12935                        table: table_name.clone(),
12936                        selectors,
12937                    },
12938                    canonical,
12939                ),
12940            );
12941        }
12942        let (targets, mut canonical): (Vec<_>, Vec<_>) = deduplicated.into_values().unzip();
12943        canonical.extend(
12944            projections
12945                .iter()
12946                .map(|name| LocalDataPurgeTarget::Projection {
12947                    projection: name.clone(),
12948                }),
12949        );
12950        let canonical_plan =
12951            serde_json::to_string(&canonical).map_err(|error| error.to_string())?;
12952        Ok(CompiledLocalDataPurge {
12953            targets,
12954            projections,
12955            canonical_plan,
12956        })
12957    }
12958
12959    fn local_purge_base_row_ids(
12960        &self,
12961        targets: &[CompiledLocalDataPurgeTarget],
12962    ) -> Result<BTreeMap<String, BTreeSet<String>>, String> {
12963        let mut by_table: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
12964        for target in targets {
12965            let table = self
12966                .schema
12967                .table(&target.table)
12968                .ok_or_else(|| format!("sync.invalid_request: unknown table {:?}", target.table))?;
12969            let mut clauses = Vec::with_capacity(target.selectors.len());
12970            let mut params = Vec::new();
12971            for (column, values) in &target.selectors {
12972                clauses.push(format!(
12973                    "{} IN ({})",
12974                    quote_ident(column),
12975                    values.iter().map(|_| "?").collect::<Vec<_>>().join(", ")
12976                ));
12977                params.extend(values.iter().cloned().map(SqlValue::Text));
12978            }
12979            let sql = format!(
12980                "SELECT CAST({} AS TEXT) FROM {} WHERE {}",
12981                quote_ident(&table.primary_key),
12982                base_table(&target.table),
12983                clauses.join(" AND ")
12984            );
12985            let mut statement = self
12986                .conn
12987                .prepare(&sql)
12988                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
12989            let rows = statement
12990                .query_map(rusqlite::params_from_iter(params), |row| {
12991                    let value = sql_ref_to_json(&table.columns[table.pk_index], row.get_ref(0)?);
12992                    render_row_id_json(Some(&value))
12993                        .map_err(|message| rusqlite::Error::ToSqlConversionFailure(message.into()))
12994                })
12995                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
12996            let ids = by_table.entry(target.table.clone()).or_default();
12997            for row in rows {
12998                ids.insert(
12999                    row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?,
13000                );
13001            }
13002        }
13003        Ok(by_table)
13004    }
13005
13006    fn local_purge_values_match(
13007        target: &CompiledLocalDataPurgeTarget,
13008        values: &Map<String, Value>,
13009    ) -> bool {
13010        target.selectors.iter().all(|(column, allowed)| {
13011            values
13012                .get(column)
13013                .and_then(Value::as_str)
13014                .is_some_and(|value| allowed.iter().any(|candidate| candidate == value))
13015        })
13016    }
13017
13018    /// Apply one host-authorized local security purge. The host MUST gate the
13019    /// corresponding subscriptions first; this primitive owns local SQLite
13020    /// cleanup and never grants/revokes server authority by itself.
13021    pub fn purge_local_data(
13022        &mut self,
13023        input: &LocalDataPurgeInput,
13024    ) -> Result<LocalDataPurgeResult, ClientError> {
13025        let CompiledLocalDataPurge {
13026            targets,
13027            projections,
13028            canonical_plan,
13029        } = self.compile_local_data_purge(input)?;
13030        for name in &projections {
13031            self.lookup_projection(name)?;
13032        }
13033        let meta_key = format!("localPurge:{}", input.purge_id);
13034        let applied_plan = self
13035            .conn
13036            .query_row(
13037                "SELECT value FROM _syncular_meta WHERE key = ?1",
13038                rusqlite::params![meta_key],
13039                |row| row.get::<_, String>(0),
13040            )
13041            .optional()
13042            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13043        if let Some(applied_plan) = applied_plan {
13044            if applied_plan != canonical_plan {
13045                return Err(format!(
13046                    "sync.invalid_request: local purge id {:?} was already used with a different plan",
13047                    input.purge_id
13048                ).into());
13049            }
13050            // A retry after a failed rewrite finishes it.
13051            self.erase_purged_pages()?;
13052            return Ok(LocalDataPurgeResult {
13053                already_applied: true,
13054                purged_rows: 0,
13055                dropped_commits: 0,
13056            });
13057        }
13058
13059        // RFC 0005 D7: the container file cannot be a purge target (its name is
13060        // not in the running schema), so purge drops it as a fixed step, before
13061        // any mirror row is touched and unconditionally.
13062        let _ = self.drop_previous_version();
13063
13064        let rollback = self.capture();
13065        self.begin_observation("syncular_local_purge")?;
13066        let applied = (|| -> Result<(ChangeAccumulator, LocalDataPurgeResult), String> {
13067            let mut batch = ChangeAccumulator::default();
13068            let mut purged_rows = 0;
13069            for name in &projections {
13070                purged_rows += self.clear_projection(name, None)?;
13071                batch.table(name);
13072            }
13073            if targets.is_empty() {
13074                self.set_meta(&meta_key, &canonical_plan)?;
13075                return Ok((batch, LocalDataPurgeResult { already_applied: false, purged_rows, dropped_commits: 0 }));
13076            }
13077            let row_ids = self.local_purge_base_row_ids(&targets)?;
13078            let retained_dropped = self.drop_failed_commits(|table, values| {
13079                targets.iter().any(|target| {
13080                    target.table == table && Self::local_purge_values_match(target, values)
13081                })
13082            })?;
13083            let doomed = self
13084                .outbox
13085                .iter()
13086                .filter(|commit| {
13087                    commit.ops.iter().any(|operation| {
13088                        let matching_targets = targets
13089                            .iter()
13090                            .filter(|target| target.table == operation.table)
13091                            .collect::<Vec<_>>();
13092                        if matching_targets.is_empty() {
13093                            return false;
13094                        }
13095                        if row_ids
13096                            .get(&operation.table)
13097                            .is_some_and(|ids| ids.contains(&operation.row_id))
13098                        {
13099                            return true;
13100                        }
13101                        operation.values.as_ref().is_some_and(|values| {
13102                            matching_targets
13103                                .iter()
13104                                .any(|target| Self::local_purge_values_match(target, values))
13105                        })
13106                    })
13107                })
13108                .cloned()
13109                .collect::<Vec<_>>();
13110            let doomed_ids = doomed
13111                .iter()
13112                .map(|commit| commit.client_commit_id.clone())
13113                .collect::<BTreeSet<_>>();
13114            for commit in &retained_dropped {
13115                batch.conflicts = true;
13116                batch.rejections = true;
13117                batch.outcomes = true;
13118                for operation in &commit.ops {
13119                    batch.table(&operation.table);
13120                }
13121            }
13122            let mut rejections = Vec::new();
13123            // §5.11 purge erasure: the journal keeps a dropped commit's identity and
13124            // codes, never its operations, so no purged value survives in it.
13125            for commit in &doomed {
13126                for operation in &commit.ops {
13127                    batch.table(&operation.table);
13128                    self.overlay_dirty.table(&operation.table);
13129                }
13130                let results = (0..commit.ops.len())
13131                    .map(|op_index| {
13132                        let rejection = RejectionRecord {
13133                            client_commit_id: commit.client_commit_id.clone(),
13134                            op_index: op_index as i32,
13135                            code: "client.local_data_purged".to_owned(),
13136                            message: "the commit was dropped by an application-authorized local data purge".to_owned(),
13137                            retryable: false,
13138                            details: None,
13139                            operation: None,
13140                        };
13141                        rejections.push(rejection.clone());
13142                        CommitOperationOutcome::Error { rejection }
13143                    })
13144                    .collect::<Vec<_>>();
13145                self.persist_commit_outcome(
13146                    &commit.client_commit_id,
13147                    CommitOutcomeStatus::Rejected,
13148                    &results,
13149                    None,
13150                )?;
13151                self.leave_through(&commit.client_commit_id);
13152                self.delete_outbox_persisted(&commit.client_commit_id)?;
13153            }
13154            if !doomed.is_empty() {
13155                self.outbox
13156                    .retain(|commit| !doomed_ids.contains(&commit.client_commit_id));
13157                self.rejections.extend(rejections);
13158                self.prune_commit_outcomes()?;
13159                batch.status = true;
13160                batch.rejections = true;
13161                batch.outcomes = true;
13162            }
13163
13164            for (table, ids) in &row_ids {
13165                if ids.is_empty() {
13166                    continue;
13167                }
13168                batch.table(table);
13169                self.overlay_dirty.table(table);
13170                for row_id in ids {
13171                    self.delete_base_row(table, row_id, i64::MAX)?;
13172                    purged_rows += 1;
13173                }
13174            }
13175            // §5.11 purge erasure: a journaled outcome with an operation or
13176            // conflict row the purge reaches keeps its identity, status, ids
13177            // and codes only.
13178            let touches = |table: &str, row_id: &str, values: Option<&Map<String, Value>>| {
13179                targets.iter().any(|target| {
13180                    target.table == table
13181                        && (row_ids.get(table).is_some_and(|ids| ids.contains(row_id))
13182                            || values.is_some_and(|values| {
13183                                Self::local_purge_values_match(target, values)
13184                            }))
13185                })
13186            };
13187            let entries = self
13188                .conn
13189                .prepare("SELECT client_commit_id, results_json, operations_json FROM _syncular_commit_outcomes")
13190                .and_then(|mut statement| {
13191                    statement
13192                        .query_map([], |row| {
13193                            Ok((
13194                                row.get::<_, String>(0)?,
13195                                row.get::<_, String>(1)?,
13196                                row.get::<_, Option<String>>(2)?,
13197                            ))
13198                        })?
13199                        .collect::<Result<Vec<_>, _>>()
13200                })
13201                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13202            for (client_commit_id, results_json, operations_json) in entries {
13203                let corrupt = |_| "sync.local_corrupt: persisted commit outcome is invalid".to_owned();
13204                let mut results: Vec<CommitOperationOutcome> =
13205                    serde_json::from_str(&results_json).map_err(corrupt)?;
13206                let operations: Vec<CommitOperation> = operations_json
13207                    .map(|json| serde_json::from_str(&json))
13208                    .transpose()
13209                    .map_err(corrupt)?
13210                    .unwrap_or_default();
13211                let named = operations
13212                    .iter()
13213                    .chain(results.iter().filter_map(|result| match result {
13214                        CommitOperationOutcome::Conflict { conflict } => conflict.operation.as_ref(),
13215                        CommitOperationOutcome::Error { rejection } => rejection.operation.as_ref(),
13216                        CommitOperationOutcome::Applied { .. } => None,
13217                    }))
13218                    .any(|operation| touches(&operation.table, &operation.row_id, operation.values.as_ref()))
13219                    || results.iter().any(|result| {
13220                        matches!(result, CommitOperationOutcome::Conflict { conflict }
13221                            if touches(&conflict.table, &conflict.row_id, Some(&conflict.server_row)))
13222                    });
13223                if !named {
13224                    continue;
13225                }
13226                for result in &mut results {
13227                    match result {
13228                        CommitOperationOutcome::Conflict { conflict } => {
13229                            conflict.server_row = Map::new();
13230                            conflict.conflict_columns.clear();
13231                            conflict.operation = None;
13232                        }
13233                        CommitOperationOutcome::Error { rejection } => {
13234                            rejection.details = None;
13235                            rejection.operation = None;
13236                        }
13237                        CommitOperationOutcome::Applied { .. } => {}
13238                    }
13239                }
13240                let results_json = serde_json::to_string(&results).map_err(|error| error.to_string())?;
13241                self.conn
13242                    .execute(
13243                        "UPDATE _syncular_commit_outcomes SET results_json = ?1, operations_json = NULL WHERE client_commit_id = ?2",
13244                        rusqlite::params![results_json, client_commit_id],
13245                    )
13246                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13247                batch.outcomes = true;
13248            }
13249            self.rebuild_overlay_if_dirty()?;
13250            self.delete_unreferenced_cached_blobs()?;
13251            self.conn
13252                .execute(
13253                    "INSERT INTO _syncular_meta(key, value) VALUES (?1, ?2)",
13254                    rusqlite::params![meta_key, canonical_plan],
13255                )
13256                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13257            Ok((
13258                batch,
13259                LocalDataPurgeResult {
13260                    already_applied: false,
13261                    purged_rows,
13262                    dropped_commits: doomed.len(),
13263                },
13264            ))
13265        })()
13266        .and_then(|(batch, result)| {
13267            self.finish_observation("syncular_local_purge", batch)
13268                .map(|()| result)
13269        });
13270        let result = match applied {
13271            Ok(result) => result,
13272            Err(error) => {
13273                self.rollback_observation("syncular_local_purge");
13274                self.restore(rollback);
13275                return Err(error.into());
13276            }
13277        };
13278        self.cancel_sync_round();
13279        self.erase_purged_pages()?;
13280        Ok(result)
13281    }
13282
13283    /// §5.11 purge erasure: SQLite leaves a deleted value in the freed pages of the
13284    /// database file, and the WAL keeps the frames written before the purge,
13285    /// until either is rewritten. VACUUM rebuilds the file from the remaining
13286    /// rows, and the checkpoint truncates the WAL.
13287    fn erase_purged_pages(&self) -> Result<(), String> {
13288        let erased = self.stored(
13289            self.conn
13290                .execute_batch("PRAGMA secure_delete = ON; VACUUM;")
13291                .and_then(|()| {
13292                    self.conn
13293                        .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| {
13294                            row.get::<_, bool>(0)
13295                        })
13296                }),
13297        );
13298        let reset = self.stored(self.conn.execute_batch("PRAGMA secure_delete = OFF"));
13299        if erased.and_then(|busy| reset.map(|()| busy))? {
13300            return Err("client.storage_busy: WAL checkpoint is busy".to_owned());
13301        }
13302        Ok(())
13303    }
13304
13305    /// Application-authorized recovery of the replicated projection. Unlike a
13306    /// local security purge, this retains the entire outbox, device identity,
13307    /// lease, outcomes, unit registrations, and protected bookkeeping.
13308    /// The projection reset, unit rewind, optimistic replay, and
13309    /// idempotency marker share one savepoint for interruption safety.
13310    pub fn rebootstrap_local_data(
13311        &mut self,
13312        input: &LocalDataRebootstrapInput,
13313    ) -> Result<LocalDataRebootstrapResult, String> {
13314        if input.rebootstrap_id.is_empty()
13315            || input.rebootstrap_id.len() > 128
13316            || !is_local_operation_code_like(&input.rebootstrap_id)
13317        {
13318            return Err(
13319                "sync.invalid_request: local rebootstrap rebootstrapId must be a 1–128 character code-like identifier"
13320                    .to_owned(),
13321            );
13322        }
13323        let meta_key = format!("localRebootstrap:{}", input.rebootstrap_id);
13324        if let Some(persisted) = meta_get(&self.conn, &meta_key).map_err(|_| {
13325            "sync.local_corrupt: persisted local rebootstrap receipt is unreadable".to_owned()
13326        })? {
13327            let (retained_commits, reset_subscriptions) =
13328                decode_local_rebootstrap_receipt(&persisted)?;
13329            return Ok(LocalDataRebootstrapResult {
13330                already_applied: true,
13331                retained_commits,
13332                reset_subscriptions,
13333            });
13334        }
13335        if self.stopped || self.schema_floor.is_some() {
13336            return Err(
13337                "sync.invalid_request: local rebootstrap cannot bypass an active schema-floor stop; update the application first"
13338                    .to_owned(),
13339            );
13340        }
13341
13342        let retained_commits = self.outbox.len();
13343        let reset_subscriptions = self.stored(load_units(&self.conn))?.len();
13344        let receipt = encode_local_rebootstrap_receipt(retained_commits, reset_subscriptions)?;
13345        let rollback = self.capture();
13346        self.begin_observation("syncular_local_rebootstrap")?;
13347        let mut batch = ChangeAccumulator::default();
13348        let applied = (|| -> Result<(), String> {
13349            self.run_schema_reset_observed(&mut batch, false)?;
13350            self.conn
13351                .execute(
13352                    "INSERT INTO _syncular_meta(key, value) VALUES (?1, ?2)",
13353                    rusqlite::params![meta_key, receipt],
13354                )
13355                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13356            self.sync_needed = true;
13357            self.sync_intent_queue.push_back(SyncIntent::Interactive);
13358            batch.status = true;
13359            Ok(())
13360        })()
13361        .and_then(|()| self.finish_observation("syncular_local_rebootstrap", batch));
13362        if let Err(error) = applied {
13363            self.rollback_observation("syncular_local_rebootstrap");
13364            self.restore(rollback);
13365            return Err(error);
13366        }
13367        self.cancel_sync_round();
13368
13369        Ok(LocalDataRebootstrapResult {
13370            already_applied: false,
13371            retained_commits,
13372            reset_subscriptions,
13373        })
13374    }
13375
13376    // -- scope purge + doomed outbox (§3.3) ----------------------------------------
13377
13378    /// Delete base and visible rows owned by the effective scopes
13379    /// ([`local_scope_predicate`]); `Ok(false)` = no local scope-column
13380    /// mapping for a key (the fail-closed case). A SQLite failure is an error.
13381    fn purge_scope_rows(
13382        &mut self,
13383        table_name: &str,
13384        effective: &[(String, Vec<String>)],
13385        owners: &[Vec<(String, Vec<String>)>],
13386    ) -> Result<bool, String> {
13387        let Some(table) = self.schema.table(table_name) else {
13388            return Ok(false);
13389        };
13390        let Ok(predicate) = local_scope_predicate(table, effective, owners) else {
13391            return Ok(false);
13392        };
13393        let Some((predicate, params)) = predicate else {
13394            return Ok(true);
13395        };
13396        self.overlay_dirty.table(table_name);
13397        for source in [base_table(table_name), visible_table(table_name)] {
13398            self.conn
13399                .execute(
13400                    &format!("DELETE FROM {source} WHERE {predicate}"),
13401                    rusqlite::params_from_iter(&params),
13402                )
13403                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13404        }
13405        Ok(true)
13406    }
13407
13408    /// §3.3: drop pending commits whose upserts provably land in the
13409    /// revoked effective scopes and no other owner covers (row ownership)
13410    /// — whole-commit, never per-operation.
13411    fn drop_doomed_outbox(
13412        &mut self,
13413        table: &TableSchema,
13414        effective: &[(String, Vec<String>)],
13415        owners: &[Vec<(String, Vec<String>)>],
13416    ) -> Result<bool, String> {
13417        let doomed: Vec<_> =
13418            self.outbox
13419                .iter()
13420                .filter(|commit| {
13421                    commit.ops.iter().any(|op| {
13422                        op.upsert
13423                            && op.table == table.name
13424                            && op.values.as_ref().is_some_and(|values| {
13425                                owns_local_row(table, effective, owners, values)
13426                            })
13427                    })
13428                })
13429                .cloned()
13430                .collect();
13431        if doomed.is_empty() {
13432            return Ok(false);
13433        }
13434        let mut rejections = Vec::new();
13435        for commit in &doomed {
13436            let results = commit
13437                .ops
13438                .iter()
13439                .enumerate()
13440                .map(|(op_index, operation)| {
13441                    self.overlay_dirty.table(&operation.table);
13442                    let rejection = RejectionRecord {
13443                        client_commit_id: commit.client_commit_id.clone(),
13444                        op_index: op_index as i32,
13445                        code: "sync.scope_revoked".to_owned(),
13446                        message: "the commit was dropped because its effective scope was revoked"
13447                            .to_owned(),
13448                        retryable: false,
13449                        details: None,
13450                        operation: Some(CommitOperation::from(operation)),
13451                    };
13452                    rejections.push(rejection.clone());
13453                    CommitOperationOutcome::Error { rejection }
13454                })
13455                .collect::<Vec<_>>();
13456            self.persist_commit_outcome(
13457                &commit.client_commit_id,
13458                CommitOutcomeStatus::Rejected,
13459                &results,
13460                Some(&commit.ops),
13461            )?;
13462            self.leave_through(&commit.client_commit_id);
13463            self.delete_outbox_persisted(&commit.client_commit_id)?;
13464        }
13465        self.prune_commit_outcomes()?;
13466        let doomed_ids = doomed
13467            .iter()
13468            .map(|commit| commit.client_commit_id.as_str())
13469            .collect::<BTreeSet<_>>();
13470        self.outbox
13471            .retain(|commit| !doomed_ids.contains(commit.client_commit_id.as_str()));
13472        self.rejections.extend(rejections);
13473        Ok(true)
13474    }
13475
13476    // -- blobs (§5.9) ----------------------------------------------------------------
13477
13478    /// §5.9.7: hash bytes into the content address, cache them, queue the
13479    /// upload (flushed before the next push, B4). Returns the canonical
13480    /// BlobRef JSON `{blobId, byteLength, mediaType?}` for a `blob_ref`
13481    /// column value.
13482    pub fn upload_blob(
13483        &mut self,
13484        bytes: &[u8],
13485        media_type: Option<String>,
13486        name: Option<String>,
13487    ) -> Result<Value, String> {
13488        let blob_id = blob_id_for(bytes);
13489        let now = self.clock_now_ms();
13490        let tx = self
13491            .conn
13492            .transaction()
13493            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13494        tx.execute(
13495            "INSERT INTO _syncular_blobs(blob_id, bytes, byte_length, media_type, created_at_ms) VALUES (?,?,?,?,?)
13496             ON CONFLICT(blob_id) DO NOTHING",
13497            rusqlite::params![blob_id, bytes, bytes.len() as i64, media_type, now],
13498        )
13499        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13500        tx.execute(
13501            "INSERT OR IGNORE INTO _syncular_blob_uploads(blob_id, media_type, created_at_ms) VALUES (?,?,?)",
13502            rusqlite::params![blob_id, media_type, now],
13503        )
13504        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13505        tx.commit()
13506            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13507        self.enforce_blob_cache_cap();
13508        let mut obj = Map::new();
13509        obj.insert("blobId".to_owned(), Value::from(blob_id));
13510        obj.insert("byteLength".to_owned(), Value::from(bytes.len() as i64));
13511        if let Some(mt) = media_type {
13512            obj.insert("mediaType".to_owned(), Value::from(mt));
13513        }
13514        if let Some(n) = name {
13515            obj.insert("name".to_owned(), Value::from(n));
13516        }
13517        Ok(Value::Object(obj))
13518    }
13519
13520    /// §5.9.7: resolve an owned blob body without driver encoding. A
13521    /// content-addressed cache hit serves with no fetch (B1); a miss downloads
13522    /// (§5.9.5), verifies the address, caches the bytes, and returns them.
13523    pub fn fetch_blob_bytes(
13524        &mut self,
13525        transport: &mut dyn Transport,
13526        blob_id_or_ref: &str,
13527    ) -> Result<FetchedBlob, (String, String)> {
13528        let simple = |m: String| ("client.failed".to_owned(), m);
13529        // A BlobRef declares the size that caps the download (§5.9.5); a bare
13530        // blobId declares none.
13531        let (blob_id, byte_length) = if blob_id_or_ref.starts_with("sha256:") {
13532            (blob_id_or_ref.to_owned(), None)
13533        } else {
13534            let value: Value = serde_json::from_str(blob_id_or_ref)
13535                .map_err(|_| simple("blob ref is not JSON".to_owned()))?;
13536            (
13537                value
13538                    .get("blobId")
13539                    .and_then(Value::as_str)
13540                    .ok_or_else(|| simple("blob ref has no blobId".to_owned()))?
13541                    .to_owned(),
13542                value.get("byteLength").and_then(Value::as_u64),
13543            )
13544        };
13545        if let Some(cached) = self.get_cached_blob_bytes(&blob_id).map_err(simple)? {
13546            return Ok(cached);
13547        }
13548        if self.transport_closed() {
13549            return Err(("sync.offline".into(), "transport gate is closed".into()));
13550        }
13551        // §5.9.5: propagate the server's blob.* code (blob.forbidden /
13552        // blob.not_found) verbatim so the harness can assert on it. The
13553        // authorized endpoint serves bytes inline OR (always-issue, presign
13554        // configured) a signed url the client fetches directly — no host auth,
13555        // no fall-through: failure => re-request (the caller's next fetch_blob_bytes).
13556        #[cfg(feature = "bench-internals")]
13557        let download_phase = self.benchmark_phases.start(Phase::BlobDownload);
13558        let bytes = match transport
13559            .blob_download(&blob_id, byte_length)
13560            .map_err(|e| (e.code, e.message))?
13561        {
13562            BlobDownload::Bytes(bytes) => bytes,
13563            BlobDownload::Url {
13564                url,
13565                url_expires_at_ms,
13566            } => {
13567                // §5.9.5: MUST NOT start a fetch at/past expiry.
13568                if url_expires_at_ms.is_some_and(|exp| exp <= self.clock_now_ms()) {
13569                    return Err((
13570                        "sync.segment_expired".to_owned(),
13571                        format!(
13572                            "blob url for {blob_id} expired before fetch — re-request mints a fresh url (§5.9.5)"
13573                        ),
13574                    ));
13575                }
13576                transport
13577                    .fetch_blob_url(&url, byte_length)
13578                    .map_err(|e| (e.code, e.message))?
13579            }
13580        };
13581        #[cfg(feature = "bench-internals")]
13582        drop(download_phase);
13583        #[cfg(feature = "bench-internals")]
13584        let validate_phase = self.benchmark_phases.start(Phase::BlobValidate);
13585        // §5.9.5 inherits §5.1: the declared size caps the body before the
13586        // content address is verified.
13587        if byte_length.is_some_and(|cap| bytes.len() as u64 > cap) {
13588            return Err((
13589                "sync.invalid_request".to_owned(),
13590                "blob exceeds its byteLength".to_owned(),
13591            ));
13592        }
13593        if blob_id_for(&bytes) != blob_id {
13594            return Err(simple(format!(
13595                "blob content address mismatch for {blob_id}"
13596            )));
13597        }
13598        #[cfg(feature = "bench-internals")]
13599        drop(validate_phase);
13600        #[cfg(feature = "bench-internals")]
13601        let insert_phase = self.benchmark_phases.start(Phase::BlobCacheInsert);
13602        let now = self.clock_now_ms();
13603        self.conn
13604            .execute(
13605                "INSERT OR IGNORE INTO _syncular_blobs(blob_id, bytes, byte_length, media_type, created_at_ms) VALUES (?,?,?,NULL,?)",
13606                rusqlite::params![blob_id, bytes, bytes.len() as i64, now],
13607            )
13608            .map_err(|e| simple(e.to_string()))?;
13609        self.conn
13610            .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
13611            .map_err(|e| simple(e.to_string()))?;
13612        self.enforce_blob_cache_cap();
13613        #[cfg(feature = "bench-internals")]
13614        drop(insert_phase);
13615        self.get_cached_blob_bytes(&blob_id)
13616            .map_err(simple)?
13617            .ok_or_else(|| simple("blob cache write failed".to_owned()))
13618    }
13619
13620    fn get_cached_blob_bytes(&self, blob_id: &str) -> Result<Option<FetchedBlob>, String> {
13621        #[cfg(feature = "bench-internals")]
13622        let _phase = self.benchmark_phases.start(Phase::BlobCacheRead);
13623        let mut stmt = self
13624            .conn
13625            .prepare("SELECT bytes, byte_length, media_type FROM _syncular_blobs WHERE blob_id = ?")
13626            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13627        let mut rows = stmt
13628            .query(rusqlite::params![blob_id])
13629            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13630        if let Some(row) = rows
13631            .next()
13632            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
13633        {
13634            let bytes: Vec<u8> = row
13635                .get(0)
13636                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13637            let byte_length: i64 = row
13638                .get(1)
13639                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13640            let media_type: Option<String> = row
13641                .get(2)
13642                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13643            return Ok(Some(FetchedBlob {
13644                blob_id: blob_id.to_owned(),
13645                byte_length,
13646                bytes,
13647                media_type,
13648            }));
13649        }
13650        Ok(None)
13651    }
13652
13653    /// §5.9.7 B4: upload every queued blob before push.
13654    fn pending_blob_uploads(&self) -> Result<Vec<crate::round::PendingUpload>, TransportError> {
13655        let pending: Vec<(String, Option<String>)> = {
13656            let mut stmt = self
13657                .conn
13658                .prepare(
13659                    "SELECT blob_id, media_type FROM (
13660                      SELECT blob_id, media_type, created_at_ms FROM _syncular_blob_uploads
13661                      UNION ALL
13662                      SELECT DISTINCT r.blob_id, b.media_type, 9223372036854775807 AS created_at_ms
13663                      FROM _syncular_blob_commit_refs r LEFT JOIN _syncular_blobs b ON b.blob_id = r.blob_id
13664                      WHERE NOT EXISTS (SELECT 1 FROM _syncular_blob_uploads u WHERE u.blob_id = r.blob_id)
13665                    ) ORDER BY created_at_ms, blob_id",
13666                )
13667                .map_err(|e| TransportError::new("client.failed", e.to_string()))?;
13668            let rows = stmt
13669                .query_map([], |row| {
13670                    Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?))
13671                })
13672                .map_err(|e| TransportError::new("client.failed", e.to_string()))?;
13673            rows.collect::<Result<_, _>>()
13674                .map_err(|error| match error {
13675                    rusqlite::Error::InvalidColumnType(..)
13676                    | rusqlite::Error::FromSqlConversionFailure(..) => TransportError::new(
13677                        "sync.local_corrupt",
13678                        "Pending blob upload metadata is invalid",
13679                    ),
13680                    _ => TransportError::new("client.failed", error.to_string()),
13681                })?
13682        };
13683        let mut uploads = Vec::new();
13684        for (blob_id, media_type) in pending {
13685            let bytes = (|| {
13686                let stored: Option<(SqlValue, SqlValue)> = self
13687                    .conn
13688                    .query_row(
13689                        "SELECT bytes, byte_length FROM _syncular_blobs WHERE blob_id = ?",
13690                        rusqlite::params![blob_id],
13691                        |row| Ok((row.get(0)?, row.get(1)?)),
13692                    )
13693                    .optional()
13694                    .map_err(|e| TransportError::new("client.failed", e.to_string()))?;
13695                let Some((SqlValue::Blob(bytes), SqlValue::Integer(byte_length))) = stored else {
13696                    return Err(TransportError::new(
13697                        "sync.local_corrupt",
13698                        "Pending blob upload body is missing or corrupt",
13699                    ));
13700                };
13701                if byte_length != bytes.len() as i64 || blob_id_for(&bytes) != blob_id {
13702                    return Err(TransportError::new(
13703                        "sync.local_corrupt",
13704                        "Pending blob upload body is missing or corrupt",
13705                    ));
13706                }
13707                Ok(bytes)
13708            })();
13709            let failed = bytes.is_err();
13710            uploads.push(crate::round::PendingUpload {
13711                id: blob_id,
13712                bytes,
13713                media_type,
13714            });
13715            if failed {
13716                break;
13717            }
13718        }
13719        Ok(uploads)
13720    }
13721
13722    fn visible_blob_ids_sql(&self) -> String {
13723        let mut selects = Vec::new();
13724        for table in &self.schema.tables {
13725            for column in table
13726                .columns
13727                .iter()
13728                .filter(|column| column.ty == ColumnType::BlobRef)
13729            {
13730                let identifier = quote_ident(&column.name);
13731                selects.push(format!(
13732                    "SELECT json_extract({identifier}, '$.blobId') AS blob_id FROM {} \
13733                     WHERE typeof({identifier}) = 'text' AND json_valid({identifier}) \
13734                     AND json_type({identifier}, '$.blobId') = 'text'",
13735                    quote_ident(&table.name),
13736                ));
13737            }
13738        }
13739        if selects.is_empty() {
13740            "SELECT NULL AS blob_id WHERE 0".to_owned()
13741        } else {
13742            selects.join(" UNION ")
13743        }
13744    }
13745
13746    /// §5.9.7 B1 size cap. Visible rows, pending commits, and
13747    /// staged uploads pin bodies directly; no derived refcount is stored.
13748    fn enforce_blob_cache_cap(&self) {
13749        let Some(max_bytes) = self.limits.blob_cache_max_bytes else {
13750            return;
13751        };
13752        let mut total: i64 = self
13753            .conn
13754            .query_row(
13755                "SELECT COALESCE(SUM(byte_length), 0) FROM _syncular_blobs",
13756                [],
13757                |row| row.get(0),
13758            )
13759            .unwrap_or(0);
13760        if total <= max_bytes {
13761            return;
13762        }
13763        let query = format!(
13764            "SELECT blob_id, byte_length FROM _syncular_blobs
13765             WHERE blob_id NOT IN (SELECT blob_id FROM _syncular_blob_uploads)
13766               AND blob_id NOT IN (SELECT blob_id FROM _syncular_blob_commit_refs)
13767               AND blob_id NOT IN ({})
13768             ORDER BY created_at_ms ASC, blob_id ASC",
13769            self.visible_blob_ids_sql(),
13770        );
13771        let candidates: Vec<(String, i64)> = {
13772            let Ok(mut stmt) = self.conn.prepare(&query) else {
13773                return;
13774            };
13775            let Ok(rows) = stmt.query_map([], |row| {
13776                Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
13777            }) else {
13778                return;
13779            };
13780            rows.filter_map(Result::ok).collect()
13781        };
13782        for (blob_id, byte_length) in candidates {
13783            if total <= max_bytes {
13784                break;
13785            }
13786            let _ = self.conn.execute(
13787                "DELETE FROM _syncular_blobs WHERE blob_id = ?",
13788                rusqlite::params![blob_id],
13789            );
13790            total -= byte_length;
13791        }
13792    }
13793
13794    fn delete_unreferenced_cached_blobs(&mut self) -> Result<(), String> {
13795        #[cfg(feature = "bench-internals")]
13796        let _phase = self.benchmark_phases.start(Phase::BlobRetention);
13797        if !self.schema_has_blobs() {
13798            return Ok(());
13799        }
13800        self.rebuild_overlay_if_dirty()?;
13801        self.conn
13802            .execute(
13803                &format!(
13804                    "DELETE FROM _syncular_blobs
13805                 WHERE blob_id NOT IN (SELECT blob_id FROM _syncular_blob_uploads)
13806                   AND blob_id NOT IN (SELECT blob_id FROM _syncular_blob_commit_refs)
13807                   AND blob_id NOT IN ({})",
13808                    self.visible_blob_ids_sql(),
13809                ),
13810                [],
13811            )
13812            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13813        Ok(())
13814    }
13815
13816    // -- local row storage ----------------------------------------------------------
13817
13818    /// The cached per-table primary-key upsert SQL for `full_table` (see
13819    /// the `insert_sql` field: built once, reused per row).
13820    fn insert_row_sql(&self, full_table: &str, table: &crate::schema::TableSchema) -> String {
13821        if let Some(sql) = self.insert_sql.borrow().get(full_table) {
13822            return sql.clone();
13823        }
13824        let mut columns: Vec<String> = table.columns.iter().map(|c| quote_ident(&c.name)).collect();
13825        columns.push(quote_ident("_syncular_version"));
13826        columns.extend(table.sealed_columns().iter().map(|name| quote_ident(name)));
13827        let placeholders: Vec<&str> = columns.iter().map(|_| "?").collect();
13828        let primary_key = quote_ident(&table.primary_key);
13829        let updates = columns
13830            .iter()
13831            .filter(|column| **column != primary_key)
13832            .map(|column| format!("{column}=excluded.{column}"))
13833            .collect::<Vec<_>>()
13834            .join(", ");
13835        // §4.5 version guard: server state lands in the base table only above
13836        // the stored version; the visible overlay takes every write.
13837        let guard = if full_table == base_table(&table.name) {
13838            format!(" WHERE excluded._syncular_version > {full_table}._syncular_version")
13839        } else {
13840            String::new()
13841        };
13842        let sql = format!(
13843            "INSERT INTO {full_table} ({}) VALUES ({}) ON CONFLICT ({primary_key}) DO UPDATE SET {updates}{guard}",
13844            columns.join(", "),
13845            placeholders.join(", ")
13846        );
13847        self.insert_sql
13848            .borrow_mut()
13849            .insert(full_table.to_owned(), sql.clone());
13850        sql
13851    }
13852
13853    /// §4.5: write a server row under the version guard; returns whether it
13854    /// landed. `sealed` is its §5.11 sealed state, `None` for an unsealed row.
13855    fn write_base_row(
13856        &self,
13857        table_name: &str,
13858        row: &Row,
13859        version: i64,
13860        sealed: Option<&SealedRow>,
13861    ) -> Result<bool, String> {
13862        let landed = self.write_row(&base_table(table_name), table_name, row, version, sealed)?;
13863        if landed {
13864            self.overlay_dirty.table(table_name);
13865        }
13866        Ok(landed)
13867    }
13868
13869    fn write_row(
13870        &self,
13871        full_table: &str,
13872        table_name: &str,
13873        row: &Row,
13874        version: i64,
13875        sealed: Option<&SealedRow>,
13876    ) -> Result<bool, String> {
13877        #[cfg(feature = "bench-internals")]
13878        let _phase = self.benchmark_phases.start(Phase::RowWrite);
13879        let table = self
13880            .schema
13881            .table(table_name)
13882            .ok_or_else(|| format!("unknown table {table_name:?}"))?;
13883        let sql = self.insert_row_sql(full_table, table);
13884        let mut stmt = self
13885            .conn
13886            .prepare_cached(&sql)
13887            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13888        let params = row
13889            .iter()
13890            .map(RowParam::Cell)
13891            .chain(std::iter::once(RowParam::Version(version)))
13892            .chain(
13893                [
13894                    sealed.map(|sealed| sealed.key_id.as_str()),
13895                    sealed.map(|sealed| sealed.envelopes.as_str()),
13896                ]
13897                .into_iter()
13898                .take(table.sealed_columns().len())
13899                .map(RowParam::Text),
13900            );
13901        stmt.execute(rusqlite::params_from_iter(params))
13902            .map(|changed| changed > 0)
13903            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
13904    }
13905
13906    /// §4.5: delete a server row whose stored version lies below `version`;
13907    /// returns whether a row left.
13908    fn delete_base_row(
13909        &self,
13910        table_name: &str,
13911        row_id: &str,
13912        version: i64,
13913    ) -> Result<bool, String> {
13914        let table = self
13915            .schema
13916            .table(table_name)
13917            .ok_or_else(|| format!("unknown table {table_name:?}"))?;
13918        let sql = format!(
13919            "DELETE FROM {} WHERE {} AND _syncular_version < ?2",
13920            base_table(table_name),
13921            row_id_predicate(table)
13922        );
13923        let mut stmt = self
13924            .conn
13925            .prepare_cached(&sql)
13926            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13927        let landed = stmt
13928            .execute(rusqlite::params![row_id, version])
13929            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
13930            > 0;
13931        if landed {
13932            self.overlay_dirty.table(table_name);
13933        }
13934        Ok(landed)
13935    }
13936
13937    fn has_acknowledged_rows(&self) -> Result<bool, String> {
13938        self.conn
13939            .query_row(
13940                "SELECT EXISTS(SELECT 1 FROM _syncular_acked_rows)",
13941                [],
13942                |row| row.get(0),
13943            )
13944            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
13945    }
13946
13947    fn acknowledged_operations(
13948        &self,
13949        rows: Option<&HashSet<(&str, &str)>>,
13950        tables: Option<&BTreeSet<&str>>,
13951    ) -> Result<Vec<OutboxOp>, String> {
13952        let keys = rows.map(|rows| serde_json::to_string(&rows).expect("row keys"));
13953        let mut statement = self
13954            .conn
13955            .prepare_cached(if keys.is_some() {
13956                ACKED_ROWS_BY_ROW
13957            } else {
13958                "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"
13959            })
13960            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13961        let rows = statement
13962            .query_map(
13963                rusqlite::params![
13964                    keys,
13965                    tables.map(|tables| serde_json::to_string(tables).expect("table keys"))
13966                ],
13967                |row| {
13968                    #[cfg(test)]
13969                    self.acknowledged_replay_count
13970                        .set(self.acknowledged_replay_count.get() + 1);
13971                    Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
13972                },
13973            )
13974            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13975        rows.map(|row| {
13976            let (op, intent) =
13977                row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13978            let op: CommitOperation =
13979                serde_json::from_str(&op).map_err(|_| "sync.local_corrupt".to_owned())?;
13980            let table = self
13981                .schema
13982                .table(&op.table)
13983                .ok_or_else(|| "sync.unknown_table".to_owned())?;
13984            let values = if op.op == "upsert" && self.visible_row(table, &op.row_id)?.is_none() {
13985                Some(serde_json::from_str(&intent).map_err(|_| "sync.local_corrupt".to_owned())?)
13986            } else {
13987                op.values.clone()
13988            };
13989            Ok(OutboxOp {
13990                values,
13991                ..op.into()
13992            })
13993        })
13994        .collect()
13995    }
13996
13997    fn drop_acknowledged_rows(
13998        &self,
13999        matches: impl Fn(&str, &Map<String, Value>) -> bool,
14000    ) -> Result<Vec<OutboxCommit>, String> {
14001        let mut statement = self
14002            .conn
14003            .prepare("SELECT commit_id,tbl,intent_json,id FROM _syncular_acked_rows")
14004            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14005        let rows = statement
14006            .query_map([], |row| {
14007                Ok((
14008                    row.get::<_, String>(0)?,
14009                    row.get::<_, String>(1)?,
14010                    row.get::<_, String>(2)?,
14011                    row.get::<_, String>(3)?,
14012                ))
14013            })
14014            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14015        let mut doomed = HashSet::new();
14016        for row in rows {
14017            let (id, table, intent, row_id) =
14018                row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14019            let values =
14020                serde_json::from_str(&intent).map_err(|_| "sync.local_corrupt".to_owned())?;
14021            let base_matches = self
14022                .schema
14023                .table(&table)
14024                .map(|schema| self.stored_row(schema, &row_id, true))
14025                .transpose()?
14026                .flatten()
14027                .is_some_and(|(base, _)| {
14028                    let schema = self.schema.table(&table).expect("acknowledged table");
14029                    let values = schema
14030                        .columns
14031                        .iter()
14032                        .zip(base.iter())
14033                        .map(|(column, value)| (column.name.clone(), column_value_to_json(value)))
14034                        .collect();
14035                    matches(&table, &values)
14036                });
14037            if matches(&table, &values) || base_matches {
14038                doomed.insert(id);
14039            }
14040        }
14041        let mut dropped = Vec::new();
14042        for id in doomed {
14043            let mut statement = self
14044                .conn
14045                .prepare("SELECT op_json FROM _syncular_acked_rows WHERE commit_id=?1 ORDER BY idx")
14046                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14047            let operations = statement
14048                .query_map([&id], |row| row.get::<_, String>(0))
14049                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14050            let mut ops = Vec::new();
14051            for operation in operations {
14052                let json = operation
14053                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14054                let op: CommitOperation =
14055                    serde_json::from_str(&json).map_err(|_| "sync.local_corrupt".to_owned())?;
14056                self.overlay_dirty.table(&op.table);
14057                ops.push(OutboxOp {
14058                    table: op.table,
14059                    row_id: op.row_id,
14060                    upsert: op.op == "upsert",
14061                    base_version: op.base_version,
14062                    values: op.values,
14063                    insert: op.insert,
14064                });
14065            }
14066            dropped.push(OutboxCommit {
14067                client_commit_id: id.clone(),
14068                ops,
14069            });
14070            self.conn
14071                .execute("DELETE FROM _syncular_acked_rows WHERE commit_id=?1", [id])
14072                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14073        }
14074        Ok(dropped)
14075    }
14076
14077    /// [`Self::rebuild_overlay`], skipped when neither the base tables nor
14078    /// the outbox changed since the last rebuild (the no-op sync round).
14079    fn rebuild_overlay_if_dirty(&mut self) -> Result<(), String> {
14080        if self.overlay_dirty.get() {
14081            self.rebuild_overlay()?;
14082        }
14083        Ok(())
14084    }
14085
14086    /// §7.1: local reads see outbox state applied optimistically — rebuild
14087    /// every visible table as (base server state) + (pending outbox replay
14088    /// on top). Optimistic rows carry version `-1`.
14089    fn rebuild_overlay(&mut self) -> Result<(), String> {
14090        #[cfg(feature = "bench-internals")]
14091        let _phase = self.benchmark_phases.start(Phase::OverlayRebuild);
14092        #[cfg(test)]
14093        self.overlay_rebuild_count
14094            .set(self.overlay_rebuild_count.get() + 1);
14095        let dirty = self.overlay_dirty.snapshot();
14096        let tables: Vec<_> = self
14097            .schema
14098            .tables
14099            .iter()
14100            .filter(|table| {
14101                dirty
14102                    .as_ref()
14103                    .is_none_or(|names| names.is_empty() || names.contains(&table.name))
14104            })
14105            .cloned()
14106            .collect();
14107        let names: BTreeSet<_> = tables.iter().map(|table| table.name.as_str()).collect();
14108        // A built-in projection is refilled from the rebuilt rows once
14109        // instead of per row by its source triggers.
14110        let built_in: Vec<_> = tables
14111            .iter()
14112            .flat_map(|table| {
14113                table
14114                    .local_projections
14115                    .iter()
14116                    .filter(|spec| spec.built_in())
14117                    .map(move |spec| (spec, table))
14118            })
14119            .collect();
14120        self.begin_observation("syncular_overlay")?;
14121        let rebuilt = (|| {
14122            for (spec, _) in &built_in {
14123                for suffix in ["bi", "bu", "ai", "ad", "au"] {
14124                    self.stored(self.conn.execute(
14125                        &format!(
14126                            "DROP TRIGGER IF EXISTS {}",
14127                            quote_ident(&format!("_syncular_project_{}_{suffix}", spec.name))
14128                        ),
14129                        [],
14130                    ))?;
14131                }
14132            }
14133            for table in &tables {
14134                let visible = visible_table(&table.name);
14135                let base = base_table(&table.name);
14136                self.conn
14137                    .execute_batch(&format!(
14138                        "DELETE FROM {visible}; INSERT INTO {visible} SELECT * FROM {base}"
14139                    ))
14140                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14141            }
14142            self.replay_overlay(&names, None)?;
14143            for (spec, table) in &built_in {
14144                self.fill_built_in(spec, table)?;
14145                self.create_projection_triggers(spec, table)?;
14146            }
14147            self.conn
14148                .execute_batch("RELEASE syncular_overlay")
14149                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14150            Ok(())
14151        })();
14152        if rebuilt.is_err() {
14153            self.conn
14154                .execute_batch("ROLLBACK TO syncular_overlay; RELEASE syncular_overlay")
14155                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14156        } else {
14157            self.overlay_dirty.set(false);
14158        }
14159        rebuilt
14160    }
14161
14162    /// §7.1 replay of acknowledged, retained failed and pending intent, in
14163    /// that order, for the operations of `tables` on `rows` (every row for
14164    /// `None`) over their current visible state.
14165    fn replay_overlay(
14166        &self,
14167        tables: &BTreeSet<&str>,
14168        rows: Option<&HashSet<(&str, &str)>>,
14169    ) -> Result<(), String> {
14170        let replays = |op: &&OutboxOp| {
14171            tables.contains(op.table.as_str())
14172                && rows.is_none_or(|rows| rows.contains(&(op.table.as_str(), op.row_id.as_str())))
14173        };
14174        self.apply_outbox_ops(&self.acknowledged_operations(rows, Some(tables))?)?;
14175        for (commit, initial) in self.failed_commits.iter() {
14176            for operation in commit.ops.iter().filter(replays) {
14177                let Some(table) = self.schema.table(&operation.table) else {
14178                    continue;
14179                };
14180                if operation.upsert
14181                    && self.visible_row(table, &operation.row_id)?.is_none()
14182                    && operation.presented_values(table).is_some_and(|values| {
14183                        table
14184                            .columns
14185                            .iter()
14186                            .all(|column| values.contains_key(&column.name))
14187                    })
14188                {
14189                    let key = serde_json::to_string(&(&operation.table, &operation.row_id))
14190                        .expect("row key serialization");
14191                    if let Some(Value::Object(values)) = initial.get(&key) {
14192                        self.apply_outbox_ops(&[OutboxOp {
14193                            values: Some(values.clone()),
14194                            ..operation.clone()
14195                        }])?;
14196                    }
14197                }
14198            }
14199            self.apply_outbox_ops(commit.ops.iter().filter(replays))?;
14200        }
14201        self.apply_outbox_ops(
14202            self.outbox
14203                .iter()
14204                .flat_map(|commit| &commit.ops)
14205                .filter(replays),
14206        )
14207    }
14208
14209    /// §7.1 replay: every operation is applied over the current visible
14210    /// state. An operation that no longer applies (a server row now holds its
14211    /// unique value) stays pending and invisible until a later replay admits
14212    /// it or the server answers its push.
14213    fn apply_outbox_ops<'a>(
14214        &self,
14215        ops: impl IntoIterator<Item = &'a OutboxOp>,
14216    ) -> Result<(), String> {
14217        #[cfg(feature = "bench-internals")]
14218        let mut phase = self.benchmark_phases.start(Phase::PendingReplay);
14219        for op in ops {
14220            #[cfg(feature = "bench-internals")]
14221            if let Some(phase) = &mut phase {
14222                phase.unit();
14223            }
14224            if op.upsert {
14225                if let Some((table, values)) = self
14226                    .schema
14227                    .table(&op.table)
14228                    .filter(|table| table.indexes.iter().any(|index| index.unique))
14229                    .and_then(|table| Some((table, op.presented_values(table)?)))
14230                {
14231                    let mut intended: Map<String, Value> = self
14232                        .visible_row(table, &op.row_id)?
14233                        .map(|(row, _)| {
14234                            table
14235                                .columns
14236                                .iter()
14237                                .zip(&row)
14238                                .map(|(column, value)| {
14239                                    (column.name.clone(), column_value_to_json(value))
14240                                })
14241                                .collect()
14242                        })
14243                        .unwrap_or_default();
14244                    intended.extend(values.into_owned());
14245                    if !self.unique_conflicts(table, &intended, false)?.is_empty() {
14246                        continue;
14247                    }
14248                }
14249            }
14250            self.apply_outbox_op(op)?;
14251        }
14252        Ok(())
14253    }
14254
14255    fn apply_outbox_op(&self, op: &OutboxOp) -> Result<(), String> {
14256        let Some(table) = self.schema.table(&op.table) else {
14257            return Ok(());
14258        };
14259        let visible = visible_table(&table.name);
14260        if !op.upsert {
14261            let sql = format!("DELETE FROM {visible} WHERE {}", row_id_predicate(table));
14262            self.conn
14263                .prepare_cached(&sql)
14264                .and_then(|mut statement| statement.execute(rusqlite::params![op.row_id]))
14265                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14266            return Ok(());
14267        }
14268        // §7.1: an insert-intent operation that lacks a non-nullable column
14269        // cannot encode; it stays invisible until the send-time prepass drops
14270        // it as sync.outbox_incompatible (§7.4.4).
14271        let Some(values) = op.presented_values(table) else {
14272            return Ok(());
14273        };
14274        // §7.1: the overlay applies the operation's PRESENT columns
14275        // over the current local row. A partial operation over an
14276        // absent local row leaves it absent — the server answers it
14277        // with sync.row_deleted or sync.row_missing (§6.2). An
14278        // insert-intent operation presents every column.
14279        let full = table
14280            .columns
14281            .iter()
14282            .all(|column| values.contains_key(&column.name));
14283        let local = self.visible_row(table, &op.row_id)?;
14284        if local.is_none() && !full {
14285            return Ok(());
14286        }
14287        let mut row: Row = Vec::with_capacity(table.columns.len());
14288        for (index, column) in table.columns.iter().enumerate() {
14289            let incoming = match values.get(&column.name) {
14290                Some(raw) => json_to_column_value(
14291                    if raw.get("$bytes").is_some()
14292                        && table
14293                            .encrypted_columns
14294                            .iter()
14295                            .any(|encrypted| encrypted.index == index)
14296                    {
14297                        &table.wire_columns[index]
14298                    } else {
14299                        column
14300                    },
14301                    Some(raw),
14302                ),
14303                None => Ok(local
14304                    .as_ref()
14305                    .and_then(|(values, _)| values.get(index).cloned())
14306                    .flatten()),
14307            };
14308            row.push(incoming.map_err(|_| {
14309                "sync.local_corrupt: persisted optimistic row value is invalid".to_owned()
14310            })?);
14311        }
14312        let version = local.as_ref().map_or(-1, |(_, version)| *version);
14313        self.write_row(&visible, &table.name, &row, version, None)
14314            .map(|_| ())
14315            .map_err(|error| {
14316                if error.starts_with("UNIQUE constraint failed:") {
14317                    "sync.constraint_violation: local write violates a unique constraint".to_owned()
14318                } else {
14319                    error
14320                }
14321            })
14322    }
14323
14324    /// Whether the row is present in the overlay. Existence reads only the
14325    /// key: locked encrypted values stay opaque, and decoding the complete row
14326    /// would reject a valid plain write.
14327    fn visible_row_exists(&self, table: &TableSchema, row_id: &str) -> Result<bool, String> {
14328        self.conn
14329            .query_row(
14330                &format!(
14331                    "SELECT EXISTS(SELECT 1 FROM {} WHERE {})",
14332                    visible_table(&table.name),
14333                    row_id_predicate(table)
14334                ),
14335                rusqlite::params![row_id],
14336                |row| row.get(0),
14337            )
14338            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
14339    }
14340
14341    /// §5.11: a sealed row is read-only; a write could otherwise send NULL
14342    /// over ciphertext this device cannot see.
14343    fn refuse_sealed_row(&self, table: &TableSchema, row_id: &str) -> Result<(), ClientError> {
14344        if !table.has_encrypted_columns() {
14345            return Ok(());
14346        }
14347        let key_id: Option<String> = self
14348            .conn
14349            .query_row(
14350                &format!(
14351                    "SELECT \"_sync_sealed_key\" FROM {} WHERE {}",
14352                    visible_table(&table.name),
14353                    row_id_predicate(table)
14354                ),
14355                rusqlite::params![row_id],
14356                |row| row.get(0),
14357            )
14358            .optional()
14359            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
14360            .flatten();
14361        match key_id {
14362            None => Ok(()),
14363            Some(key_id) => Err(ClientError {
14364                code: "client.encryption_key_missing".to_owned(),
14365                message: "the row is sealed under a key this device does not hold".to_owned(),
14366                details: Some(json!({ "table": table.name, "keyId": key_id })),
14367                retryable: false,
14368            }),
14369        }
14370    }
14371
14372    /// §5.11 reveal: decrypt every sealed base row whose envelope keys the
14373    /// keyring now holds into its columns and clear both reserved columns,
14374    /// one change batch per table. `client.decrypt_failed` fails the caller.
14375    fn reveal_sealed_rows(&mut self) -> Result<(), TransportError> {
14376        let storage = |message: String| TransportError::new("storage.failed", message);
14377        let tables: Vec<TableSchema> = self
14378            .schema
14379            .tables
14380            .iter()
14381            .filter(|table| table.has_encrypted_columns())
14382            .cloned()
14383            .collect();
14384        for table in &tables {
14385            let base = base_table(&table.name);
14386            let pk = quote_ident(&table.primary_key);
14387            let sealed: Vec<(SqlValue, i64, String)> = self
14388                .conn
14389                .prepare_cached(&format!(
14390                    "SELECT {pk}, \"_syncular_version\", \"_sync_sealed\" FROM {base} WHERE \"_sync_sealed_key\" IS NOT NULL"
14391                ))
14392                .and_then(|mut statement| {
14393                    statement
14394                        .query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))?
14395                        .collect()
14396                })
14397                .map_err(|error| storage(Self::sqlite_failure(&self.storage_failure, error)))?;
14398            let mut revealed = Vec::new();
14399            for (key, version, envelopes) in sealed {
14400                if let Some(row) =
14401                    crate::values::reveal_sealed_row(table, &envelopes, &self.encryption)?
14402                {
14403                    revealed.push((key, version, row));
14404                }
14405            }
14406            if revealed.is_empty() {
14407                continue;
14408            }
14409            self.begin_observation("syncular_reveal").map_err(storage)?;
14410            let outcome = (|| {
14411                let assignments = table
14412                    .encrypted_columns
14413                    .iter()
14414                    .map(|enc| format!("{}=?", quote_ident(&table.columns[enc.index].name)))
14415                    .collect::<Vec<_>>()
14416                    .join(",");
14417                let mut statement = self
14418                    .conn
14419                    .prepare_cached(&format!(
14420                        "UPDATE {base} SET {assignments},\"_sync_sealed_key\"=NULL,\"_sync_sealed\"=NULL WHERE {pk}=? AND \"_syncular_version\"=?"
14421                    ))
14422                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14423                for (key, version, row) in &revealed {
14424                    let mut params = table
14425                        .encrypted_columns
14426                        .iter()
14427                        .map(|enc| owned_sql_value(RowParam::Cell(&row[enc.index])))
14428                        .collect::<Result<Vec<_>, _>>()?;
14429                    params.push(key.clone());
14430                    params.push(SqlValue::Integer(*version));
14431                    statement
14432                        .execute(rusqlite::params_from_iter(params))
14433                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14434                }
14435                drop(statement);
14436                self.overlay_dirty.table(&table.name);
14437                self.rebuild_overlay()?;
14438                let mut batch = ChangeAccumulator::default();
14439                batch.table(&table.name);
14440                self.finish_observation("syncular_reveal", batch)
14441            })();
14442            if outcome.is_err() {
14443                self.rollback_observation("syncular_reveal");
14444            }
14445            outcome.map_err(storage)?;
14446        }
14447        Ok(())
14448    }
14449
14450    /// The visible (optimistic) row's values plus version, or `None` when the
14451    /// row is absent from the overlay.
14452    fn visible_row(&self, table: &TableSchema, row_id: &str) -> Result<Option<(Row, i64)>, String> {
14453        self.stored_row(table, row_id, false)
14454    }
14455
14456    fn stored_row(
14457        &self,
14458        table: &TableSchema,
14459        row_id: &str,
14460        base: bool,
14461    ) -> Result<Option<(Row, i64)>, String> {
14462        let sql = format!(
14463            "SELECT * FROM {} WHERE {}",
14464            if base {
14465                base_table(&table.name)
14466            } else {
14467                visible_table(&table.name)
14468            },
14469            row_id_predicate(table)
14470        );
14471        let mut stmt = self
14472            .conn
14473            .prepare_cached(&sql)
14474            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14475        let mut rows = stmt
14476            .query(rusqlite::params![row_id])
14477            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14478        let Some(row) = rows
14479            .next()
14480            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
14481        else {
14482            return Ok(None);
14483        };
14484        let mut values = Vec::with_capacity(table.columns.len());
14485        for (index, column) in table.columns.iter().enumerate() {
14486            let raw = row
14487                .get_ref(index)
14488                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14489            if let rusqlite::types::ValueRef::Blob(bytes) = raw {
14490                if table
14491                    .encrypted_columns
14492                    .iter()
14493                    .any(|encrypted| encrypted.index == index)
14494                {
14495                    values.push(Some(ColumnValue::Bytes(bytes.to_vec())));
14496                    continue;
14497                }
14498            }
14499            let json = sql_ref_to_json(column, raw);
14500            values.push(json_to_column_value(column, Some(&json)).map_err(|_| {
14501                "sync.local_corrupt: persisted local row value is invalid".to_owned()
14502            })?);
14503        }
14504        let version: i64 = row
14505            .get(table.columns.len())
14506            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14507        Ok(Some((values, version)))
14508    }
14509
14510    // -- realtime (§8) ---------------------------------------------------------------
14511
14512    /// §8.8: the configured realtime policy.
14513    #[must_use]
14514    pub fn realtime_policy(&self) -> RealtimePolicy {
14515        self.realtime_policy
14516    }
14517
14518    /// §8.8: the explicit realtime availability state.
14519    #[must_use]
14520    pub fn realtime_state(&self) -> RealtimeState {
14521        self.realtime_state
14522    }
14523
14524    /// §8.8: set the realtime policy. Refused while the socket is connected:
14525    /// a policy change never silently re-routes an ownership state.
14526    pub fn set_realtime_policy(&mut self, policy: RealtimePolicy) -> Result<(), String> {
14527        if self.realtime_state == RealtimeState::Connected && policy != self.realtime_policy {
14528            return Err(
14529                "sync.invalid_request: disconnect realtime before changing the realtime policy"
14530                    .to_owned(),
14531            );
14532        }
14533        self.realtime_policy = policy;
14534        match policy {
14535            RealtimePolicy::Off => self.set_realtime_state(RealtimeState::Disabled, None),
14536            RealtimePolicy::Required | RealtimePolicy::Optional
14537                if self.realtime_state == RealtimeState::Disabled =>
14538            {
14539                self.set_realtime_state(RealtimeState::Disconnected, None);
14540            }
14541            RealtimePolicy::Required | RealtimePolicy::Optional => {}
14542        }
14543        Ok(())
14544    }
14545
14546    /// Record an availability transition, keeping the reason code bounded and
14547    /// code-like (§7.6) and clearing it where it cannot apply.
14548    fn set_realtime_state(&mut self, state: RealtimeState, reason_code: Option<&str>) {
14549        self.realtime_state = state;
14550        self.realtime_reason_code = reason_code.map(Self::diagnostic_code);
14551        if matches!(state, RealtimeState::Connected | RealtimeState::Disabled) {
14552            self.realtime_reason_code = None;
14553            self.realtime_retry_delay_ms = None;
14554        }
14555    }
14556
14557    #[must_use]
14558    fn realtime_connected(&self) -> bool {
14559        self.realtime_state == RealtimeState::Connected
14560    }
14561
14562    pub fn connect_realtime(&mut self, transport: &mut dyn Transport) -> Result<(), String> {
14563        if self.transport_closed() {
14564            return Err("sync.offline: transport gate is closed".into());
14565        }
14566        if self.realtime_policy == RealtimePolicy::Off {
14567            return Err(
14568                "sync.invalid_request: realtime is off; realtime connect is refused".to_owned(),
14569            );
14570        }
14571        if self.realtime_connected() {
14572            return Ok(());
14573        }
14574        self.realtime_state = RealtimeState::Connecting;
14575        match transport.realtime_connect(&self.client_id) {
14576            Ok(()) => {
14577                self.set_realtime_state(RealtimeState::Connected, None);
14578                Ok(())
14579            }
14580            Err(error) => {
14581                self.set_realtime_state(RealtimeState::Refused, Some(&error.code));
14582                Err(format!("{}: {}", error.code, error.message))
14583            }
14584        }
14585    }
14586
14587    pub fn disconnect_realtime(&mut self, transport: &mut dyn Transport) {
14588        self.cancel_sync_round();
14589        // A deliberately disconnected or policy-disabled client has nothing
14590        // to release; a `lost` socket still does (the host owns the handle).
14591        if self.realtime_state == RealtimeState::Disconnected
14592            || self.realtime_state == RealtimeState::Disabled
14593        {
14594            return;
14595        }
14596        let _ = transport.realtime_close();
14597        self.set_realtime_state(
14598            if self.realtime_policy == RealtimePolicy::Off {
14599                RealtimeState::Disabled
14600            } else {
14601                RealtimeState::Disconnected
14602            },
14603            None,
14604        );
14605        self.presence.clear(); // §8.6.1: presence is per-connection
14606    }
14607
14608    /// §8.8: the host observed the socket end without disconnecting it (a
14609    /// peer close, an I/O error, a failed send; the native transport reports
14610    /// these as `Inbound::Disconnected`). Releases the transport, moves a
14611    /// `Connected` state to `Lost` with the transport's code as the reason, and schedules
14612    /// one background retry intent so the host reconnects and catches up.
14613    pub fn realtime_lost(&mut self, transport: &mut dyn Transport, error: &TransportError) {
14614        if self.realtime_state != RealtimeState::Connected {
14615            return;
14616        }
14617        self.cancel_sync_round();
14618        let _ = transport.realtime_close();
14619        self.set_realtime_state(RealtimeState::Lost, Some(&error.code));
14620        self.realtime_retry_delay_ms = Some(self.schedule_background_retry());
14621        self.presence.clear();
14622    }
14623
14624    /// §8.6.2: publish (or clear, `doc: None`) this client's presence
14625    /// document for `scope_key`. Requires a live socket; the document is
14626    /// ephemeral (lost on disconnect). Authorization is the connection's
14627    /// registration (§8.6.3) — an unheld key is rejected loudly by the
14628    /// server with `presence.forbidden`.
14629    pub fn set_presence(
14630        &mut self,
14631        transport: &mut dyn Transport,
14632        scope_key: &str,
14633        doc: Option<&Value>,
14634    ) -> Result<(), String> {
14635        if self.transport_closed() {
14636            return Err("sync.offline: transport gate is closed".into());
14637        }
14638        if !self.realtime_connected() {
14639            return Err("setPresence requires a connected realtime socket (§8.6)".to_string());
14640        }
14641        let text = encode_presence_publish(scope_key, doc);
14642        transport
14643            .realtime_send(&text)
14644            .map_err(|e| format!("{}: {}", e.code, e.message))
14645    }
14646
14647    /// §8.6: the peers currently present on a scope key (ephemeral).
14648    pub fn presence(&self, scope_key: &str) -> Vec<PresencePeer> {
14649        self.presence
14650            .get(scope_key)
14651            .map(|peers| peers.values().cloned().collect())
14652            .unwrap_or_default()
14653    }
14654
14655    /// §8.6 apply an inbound presence fanout to the local map.
14656    fn apply_presence(
14657        &mut self,
14658        scope_key: String,
14659        kind: Option<PresenceKind>,
14660        actor_id: Option<String>,
14661        client_id: Option<String>,
14662        doc: Option<Value>,
14663        error: Option<String>,
14664    ) {
14665        // A refused publish (§8.6.2) changes no peer; the native host surfaces
14666        // it as a `presence` event carrying the server's `error` code.
14667        if error.is_some() {
14668            return;
14669        }
14670        let (Some(kind), Some(actor_id), Some(client_id)) = (kind, actor_id, client_id) else {
14671            return;
14672        };
14673        let peer_key = format!("{actor_id} {client_id}");
14674        match kind {
14675            PresenceKind::Leave => {
14676                if let Some(peers) = self.presence.get_mut(&scope_key) {
14677                    peers.remove(&peer_key);
14678                    if peers.is_empty() {
14679                        self.presence.remove(&scope_key);
14680                    }
14681                }
14682            }
14683            _ => {
14684                let doc = match doc {
14685                    Some(Value::Object(_)) => doc.unwrap(),
14686                    _ => return,
14687                };
14688                self.presence.entry(scope_key).or_default().insert(
14689                    peer_key,
14690                    PresencePeer {
14691                        actor_id,
14692                        client_id,
14693                        doc,
14694                    },
14695                );
14696            }
14697        }
14698    }
14699
14700    /// Inbound JSON control message (§8.1). Unknown events are tolerated.
14701    pub fn on_realtime_text(&mut self, text: &str) {
14702        if self.stopped || self.transport_closed() || self.security_preflight {
14703            return;
14704        }
14705        match parse_control(text) {
14706            Ok(ControlMessage::Hello { requires_sync, .. }) => {
14707                if requires_sync {
14708                    // §8.1: pull before trusting the socket for continuity.
14709                    self.set_sync_needed(true, true);
14710                }
14711            }
14712            Ok(ControlMessage::Presence {
14713                scope_key,
14714                kind,
14715                actor_id,
14716                client_id,
14717                doc,
14718                error,
14719                ..
14720            }) => {
14721                self.apply_presence(scope_key, kind, actor_id, client_id, doc, error);
14722            }
14723            Ok(ControlMessage::Wake { .. }) => {
14724                // §8.3: any wake-up means "run a pull soon", never data.
14725                self.set_sync_needed(true, true);
14726            }
14727            Ok(ControlMessage::Scopes { .. }) => {
14728                // §3.3/§8.7: the grants changed, so the next `set_window`
14729                // re-arms every revoked value it names. No sync-needed, no round.
14730                self.window_armed.clear();
14731                self.scopes_changed += 1;
14732            }
14733            _ => {}
14734        }
14735    }
14736
14737    /// Inbound binary delta: a complete SSP2 response (§8.2), applied like
14738    /// a pull response per section; an unapplied delta is a wake-up.
14739    /// Mailbox hosts send durable acknowledgements on their I/O executor.
14740    pub fn on_realtime_binary_queued(&mut self, bytes: &[u8]) -> Vec<String> {
14741        let mut transport = crate::round::DownloadResults::default();
14742        self.on_realtime_binary(&mut transport, bytes);
14743        transport.controls
14744    }
14745
14746    /// §8.2: a delta applies exactly like a live section and sets the replica
14747    /// cursor to its `throughSeq`; one at or below the replica cursor is a
14748    /// duplicate. A delta the client does not apply (no live unit, a status
14749    /// other than `active`, a decode or apply failure) is a drop and raises
14750    /// sync-needed.
14751    pub fn on_realtime_binary(&mut self, transport: &mut dyn Transport, bytes: &[u8]) {
14752        if self.stopped || self.transport_closed() || self.security_preflight {
14753            return;
14754        }
14755        #[cfg(feature = "bench-internals")]
14756        let decode_phase = self.benchmark_phases.start(Phase::ResponseDecode);
14757        let message = match decode_message(bytes) {
14758            Ok(m) if m.msg_kind == MsgKind::Response => m,
14759            _ => {
14760                self.set_sync_needed(true, true);
14761                return;
14762            }
14763        };
14764        #[cfg(feature = "bench-internals")]
14765        drop(decode_phase);
14766        // §8.2: a delta's header means what a pull response's header means. A
14767        // schema floor (§1.6) is recorded, stops syncing and applies nothing.
14768        if let Some(Frame::RespHeader {
14769            required_schema_version: Some(required),
14770            latest_schema_version,
14771            ..
14772        }) = message.frames.first()
14773        {
14774            let floor = SchemaFloor {
14775                required_schema_version: Some(*required),
14776                latest_schema_version: *latest_schema_version,
14777            };
14778            if self.set_schema_floor(Some(floor)).is_err() {
14779                self.set_sync_needed(true, true);
14780            }
14781            return;
14782        }
14783        let through = message.frames.iter().find_map(|frame| match frame {
14784            Frame::LiveEnd { through_seq, .. } => Some(*through_seq),
14785            _ => None,
14786        });
14787        let epoch = self.get_meta(LOG_EPOCH_KEY).ok().flatten();
14788        let mut dropped = !matches!(message.frames.first(), Some(Frame::RespHeader {
14789                reset_required: false,
14790                log_epoch,
14791                ..
14792            }) if Some(log_epoch) == epoch.as_ref());
14793        let mut applied: Option<i64> = None;
14794        dropped |= self.begin_coalesced_apply().is_err();
14795        let mut receivers: Option<Vec<UnitRecord>> = None;
14796        for frame in message.frames {
14797            if dropped {
14798                break;
14799            }
14800            match frame {
14801                Frame::LiveStart { status, .. } => {
14802                    let Ok(cursor) = self.stored(replica_cursor(&self.conn)) else {
14803                        dropped = true;
14804                        break;
14805                    };
14806                    if status != LiveStatus::Active || cursor < 0 {
14807                        dropped = true;
14808                    } else if !through.is_some_and(|through| through <= cursor) {
14809                        // A catching-up unit receives no delta (§8.2).
14810                        receivers = self.stored(load_units(&self.conn)).ok().map(|units| {
14811                            units
14812                                .into_iter()
14813                                .filter(|unit| {
14814                                    unit.status == UnitStatus::Active
14815                                        && unit.echo.is_some()
14816                                        && unit.cursor.is_none()
14817                                })
14818                                .collect()
14819                        });
14820                        dropped = receivers.is_none();
14821                    }
14822                }
14823                Frame::Commit {
14824                    commit_seq,
14825                    tables,
14826                    changes,
14827                    ..
14828                } => {
14829                    let Some(receivers) = receivers.clone() else {
14830                        continue;
14831                    };
14832                    dropped = self
14833                        .apply_live_commit(
14834                            &receivers,
14835                            &tables,
14836                            changes,
14837                            commit_seq,
14838                            AppliedServerCommitSource::Delta,
14839                        )
14840                        .is_err();
14841                }
14842                Frame::LiveEnd { through_seq, .. } if receivers.is_some() => {
14843                    dropped = self
14844                        .set_meta(REPLICA_CURSOR_KEY, &through_seq.to_string())
14845                        .is_err();
14846                    applied = Some(through_seq);
14847                }
14848                Frame::Error { .. } => dropped = true,
14849                _ => {}
14850            }
14851        }
14852        // §1.4 rule 4: the ack follows the COMMIT. A failed COMMIT restored
14853        // the replica cursor, so the delta counts as a drop.
14854        if self.finish_coalesced_apply().is_err() || dropped {
14855            applied = None;
14856            dropped = true;
14857        }
14858        if let Some(cursor) = applied {
14859            // §8.2 ack point: the delta's throughSeq.
14860            let ack = format!("{{\"type\":\"ack\",\"cursor\":{cursor}}}");
14861            let _ = transport.realtime_send(&ack);
14862        }
14863        if dropped {
14864            self.set_sync_needed(true, true);
14865        }
14866    }
14867
14868    /// §8.2 ack point after a pull round on a live connection: the replica
14869    /// cursor while it is at least `0`.
14870    fn ack_after_pull(&mut self, transport: &mut dyn Transport) {
14871        if !self.realtime_connected() {
14872            return;
14873        }
14874        if let Ok(cursor @ 0..) = self.stored(replica_cursor(&self.conn)) {
14875            let ack = format!("{{\"type\":\"ack\",\"cursor\":{cursor}}}");
14876            let _ = transport.realtime_send(&ack);
14877        }
14878    }
14879}
14880
14881#[cfg(test)]
14882mod previous_version_wiring_tests;
14883
14884#[cfg(test)]
14885mod identity_tests;
14886
14887#[cfg(test)]
14888mod insert_intent_tests;
14889
14890#[cfg(test)]
14891mod robustness_tests;
14892
14893#[cfg(test)]
14894mod range_image_tests;