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: the first-open repair's erasure record (`<key>:erased`).
119const PURGE_REPAIR_KEY: &str = "localPurgeRepair";
120/// §5.11 client-local code: an encode at the push seam resolved no usable key
121/// id or named an unknown key. Never a wire code (§10.3).
122const ENCRYPT_FAILED_CODE: &str = "client.encrypt_failed";
123const INVALID_REQUEST_CODE: &str = "sync.invalid_request:";
124/// §7.4.4: static text for a persisted commit the current codec refuses.
125const LEGACY_VALUE_REFUSAL_MESSAGE: &str =
126    "the persisted commit carries values the current codec refuses";
127/// §7.4.4: bounded reason on every intrinsic value drop.
128const INVALID_STORED_VALUES_REASON: &str = "invalid_stored_values";
129/// §7.2.2: an outcome with a pending decision accepts no other resolution.
130const REPLACEMENT_PENDING: &str =
131    "client.replacement_pending: the outcome has a pending replacement";
132/// §7.2.2 client-local code: a pending replacement was not written.
133const REPLACEMENT_REFUSED_CODE: &str = "sync.replacement_refused";
134/// §7.2.1/§7.2.3 client-local journal result of a replaced commit's operations.
135const COMMIT_REPLACED_CODE: &str = "client.commit_replaced";
136
137#[derive(Debug, Serialize, Deserialize)]
138#[serde(rename_all = "camelCase", deny_unknown_fields)]
139struct PersistedLocalDataRebootstrapReceipt {
140    version: u8,
141    retained_commits: u64,
142    reset_subscriptions: u64,
143}
144
145fn invalid_local_rebootstrap_receipt() -> String {
146    "sync.local_corrupt: persisted local rebootstrap receipt is invalid".to_owned()
147}
148
149fn encode_local_rebootstrap_receipt(
150    retained_commits: usize,
151    reset_subscriptions: usize,
152) -> Result<String, String> {
153    let retained_commits =
154        u64::try_from(retained_commits).map_err(|_| invalid_local_rebootstrap_receipt())?;
155    let reset_subscriptions =
156        u64::try_from(reset_subscriptions).map_err(|_| invalid_local_rebootstrap_receipt())?;
157    if retained_commits > MAX_JS_SAFE_INTEGER || reset_subscriptions > MAX_JS_SAFE_INTEGER {
158        return Err(invalid_local_rebootstrap_receipt());
159    }
160    serde_json::to_string(&PersistedLocalDataRebootstrapReceipt {
161        version: LOCAL_REBOOTSTRAP_RECEIPT_VERSION,
162        retained_commits,
163        reset_subscriptions,
164    })
165    .map_err(|_| invalid_local_rebootstrap_receipt())
166}
167
168fn decode_local_rebootstrap_receipt(value: &str) -> Result<(usize, usize), String> {
169    // Pre-0.15.36 markers proved application but did not retain the receipt.
170    if value == "v1" {
171        return Ok((0, 0));
172    }
173    let receipt: PersistedLocalDataRebootstrapReceipt =
174        serde_json::from_str(value).map_err(|_| invalid_local_rebootstrap_receipt())?;
175    if receipt.version != LOCAL_REBOOTSTRAP_RECEIPT_VERSION
176        || receipt.retained_commits > MAX_JS_SAFE_INTEGER
177        || receipt.reset_subscriptions > MAX_JS_SAFE_INTEGER
178    {
179        return Err(invalid_local_rebootstrap_receipt());
180    }
181    Ok((
182        usize::try_from(receipt.retained_commits)
183            .map_err(|_| invalid_local_rebootstrap_receipt())?,
184        usize::try_from(receipt.reset_subscriptions)
185            .map_err(|_| invalid_local_rebootstrap_receipt())?,
186    ))
187}
188
189#[cfg(test)]
190mod observation_tests;
191
192/// Internal state for hosts that perform network I/O outside the client owner.
193#[doc(hidden)]
194#[derive(Clone)]
195pub struct CurrentBasePreparation {
196    client_commit_id: String,
197    sequence: i64,
198    /// §7.2.2: the pending replacement a drive evaluates; `None` for
199    /// `proveCurrentBase`.
200    replacement: Option<String>,
201    units: Vec<UnitRecord>,
202    transport_epoch: u64,
203    registration_epoch: u64,
204    security_epoch: u64,
205}
206
207#[cfg(test)]
208mod units_tests;
209
210#[cfg(test)]
211mod replace_outcome_tests;
212
213#[cfg(test)]
214mod pending_replacement_tests;
215
216/// A §6.12 fence round that [`SyncClient::prepare_pending_commit_replacement`]
217/// prepared on the owner. Send [`PreparedFenceRound::request_bytes`] as a sync
218/// request (over the realtime socket when [`PreparedFenceRound::realtime`] is
219/// set) and hand the reply to [`SyncClient::apply_fence_round`]; a host with a
220/// blocking [`Transport`] calls [`PreparedFenceRound::exchange`].
221pub struct PreparedFenceRound {
222    id: uuid::Uuid,
223    client_commit_id: String,
224    replacement_client_commit_id: String,
225    operations: Vec<OutboxOp>,
226    request: Vec<u8>,
227    realtime: bool,
228}
229
230impl PreparedFenceRound {
231    pub fn request_bytes(&self) -> &[u8] {
232        &self.request
233    }
234
235    pub fn realtime(&self) -> bool {
236        self.realtime
237    }
238
239    /// Send the request without accessing client state.
240    pub fn exchange(&self, transport: &mut dyn Transport) -> Result<Vec<u8>, TransportError> {
241        if self.realtime {
242            transport.realtime_sync(&self.request)
243        } else {
244            transport.sync(&self.request)
245        }
246    }
247}
248
249#[derive(Debug, Clone)]
250struct OutboxOp {
251    upsert: bool,
252    table: String,
253    row_id: String,
254    base_version: Option<i64>,
255    /// Schema-agnostic local form (§0): driver JSON values, encoded with
256    /// the current codec at send time. A key's presence IS the §6.1 sparse
257    /// presence set — both the overlay and the wire payload derive from it.
258    values: Option<Map<String, Value>>,
259    /// §7.1 insert intent: `mutate` recorded this upsert while the row was
260    /// absent from the visible replica. Replay and send-time encoding present
261    /// every current-schema column; a column `values` lacks is NULL.
262    insert: bool,
263}
264
265impl OutboxOp {
266    /// The values this upsert presents under the current `table` (§7.1). An
267    /// insert-intent operation presents every column, a missing one as NULL;
268    /// `None` when a missing column is non-nullable, which leaves the commit
269    /// unencodable (§7.4.4), or when the operation carries no values.
270    fn presented_values(&self, table: &TableSchema) -> Option<Cow<'_, Map<String, Value>>> {
271        let values = self.values.as_ref()?;
272        if !self.insert || table.columns.iter().all(|c| values.contains_key(&c.name)) {
273            return Some(Cow::Borrowed(values));
274        }
275        full_row_values(table, values.clone()).ok().map(Cow::Owned)
276    }
277}
278
279impl From<CommitOperation> for OutboxOp {
280    fn from(operation: CommitOperation) -> Self {
281        Self {
282            upsert: operation.op == "upsert",
283            table: operation.table,
284            row_id: operation.row_id,
285            base_version: operation.base_version,
286            values: operation.values,
287            insert: operation.insert,
288        }
289    }
290}
291
292/// §7.5 static authoring refusal; the table and column travel in details.
293fn invalid_authoring(message: &str, details: Value) -> ClientError {
294    ClientError {
295        code: "sync.invalid_request".to_owned(),
296        message: message.to_owned(),
297        details: Some(details),
298        retryable: false,
299    }
300}
301
302/// §7.1 chained base: `later` repeats `earlier`'s positive base on the same
303/// row and presents only columns `earlier` presents.
304fn chains_on(earlier: &OutboxOp, later: &OutboxOp) -> bool {
305    // Only an upsert carries values, and it always carries its primary key.
306    earlier.row_id == later.row_id
307        && earlier.table == later.table
308        && later.base_version.is_some_and(|base| base > 0)
309        && earlier.base_version == later.base_version
310        && later.values.as_ref().is_some_and(|values| {
311            values.keys().all(|column| {
312                earlier
313                    .values
314                    .as_ref()
315                    .is_some_and(|earlier| earlier.contains_key(column))
316            })
317        })
318}
319
320impl From<&OutboxOp> for CommitOperation {
321    fn from(operation: &OutboxOp) -> Self {
322        Self {
323            table: operation.table.clone(),
324            row_id: operation.row_id.clone(),
325            op: if operation.upsert { "upsert" } else { "delete" }.to_owned(),
326            base_version: operation.base_version,
327            values: operation.values.clone(),
328            insert: operation.insert,
329        }
330    }
331}
332
333#[derive(Debug, Clone)]
334struct OutboxCommit {
335    client_commit_id: String,
336    ops: Vec<OutboxOp>,
337}
338
339/// One commit's `(table, value keys, insert intent)` per upsert operation — the classification
340/// shape the §7.4.4 send-time drop and the RFC 0005 D6 audit share, so the two
341/// can never disagree about which commits cannot re-encode.
342fn commit_audit_operations(commit: &OutboxCommit) -> Vec<(&str, Vec<&str>, bool)> {
343    commit
344        .ops
345        .iter()
346        .filter(|operation| operation.upsert)
347        .map(|operation| {
348            (
349                operation.table.as_str(),
350                operation
351                    .values
352                    .as_ref()
353                    .map(|values| values.keys().map(String::as_str).collect())
354                    .unwrap_or_default(),
355                operation.insert,
356            )
357        })
358        .collect()
359}
360
361type FailedCommit = (OutboxCommit, Map<String, Value>);
362
363#[derive(Debug, Clone)]
364struct CompiledLocalDataPurgeTarget {
365    table: String,
366    selectors: Vec<(String, Vec<String>)>,
367}
368
369struct CompiledLocalDataPurge {
370    targets: Vec<CompiledLocalDataPurgeTarget>,
371    projections: BTreeSet<String>,
372    canonical_plan: String,
373}
374
375struct StoredCommitOutcomeRow {
376    sequence: i64,
377    client_commit_id: String,
378    status: String,
379    recorded_at_ms: i64,
380    results_json: String,
381    operations_json: Option<String>,
382    resolution: String,
383    resolved_at_ms: Option<i64>,
384    replacement_client_commit_id: Option<String>,
385}
386
387impl StoredCommitOutcomeRow {
388    fn from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Self> {
389        Ok(Self {
390            sequence: row.get(0)?,
391            client_commit_id: row.get(1)?,
392            status: row.get(2)?,
393            recorded_at_ms: row.get(3)?,
394            results_json: row.get(4)?,
395            operations_json: row.get(5)?,
396            resolution: row.get(6)?,
397            resolved_at_ms: row.get(7)?,
398            replacement_client_commit_id: row.get(8)?,
399        })
400    }
401}
402
403/// Section outcome distinguishing the §5.6 unit-local fail-closed
404/// path from a round-aborting failure (§1.4 rule 5).
405/// §4.4 a unit section's `SUB_START`.
406struct SectionStart {
407    id: String,
408    status: SubStatus,
409    reason_code: String,
410    bootstrap: bool,
411    fenced: Vec<FencedRecord>,
412}
413
414enum SectionError {
415    FailClosed,
416    /// §5.5: the server refused a segment with `sync.forbidden`.
417    Refused,
418    /// §5.3 client memory: the round deferred this image's body to a later
419    /// pull of the same resume token.
420    Deferred,
421    Abort(String, String),
422    Transport(TransportError),
423}
424
425#[derive(Debug)]
426pub(crate) struct RequestMeta {
427    pushed_ids: Vec<String>,
428    /// Hex of the registration digest this pull carried; the server stores
429    /// that list once the round completes (§4.1).
430    registration_digest: String,
431    pub(crate) accept: u8,
432    /// §6.1 splitBatch: outbox commits held back from THIS request because
433    /// the running operation count reached the push cap — the next round
434    /// pushes them (`sync_needed` stays set while any remain).
435    deferred_commits: usize,
436    /// §5.6 applied-segment record per unit: segment id → rows applied at
437    /// the unit's current cursor and token.
438    pub(crate) applied: BTreeMap<String, BTreeMap<String, i64>>,
439    /// §5.3 client memory: (unit, segment id) of the first image whose body
440    /// the round did not fetch because the batch already holds two images.
441    /// That unit's section stops there without persisting `SUB_END`.
442    pub(crate) deferred: BTreeSet<(String, String)>,
443}
444
445#[derive(Default)]
446struct ChangeAccumulator {
447    /// None means table-wide; Some is the exact scoped domain.
448    tables: BTreeMap<String, Option<BTreeSet<String>>>,
449    windows: BTreeMap<String, BTreeSet<String>>,
450    status: bool,
451    conflicts: bool,
452    rejections: bool,
453    outcomes: bool,
454}
455
456impl ChangeAccumulator {
457    fn table(&mut self, table: &str) {
458        self.tables.insert(table.to_owned(), None);
459    }
460
461    fn scope(&mut self, table: &str, key: String) {
462        match self.tables.get_mut(table) {
463            Some(None) => {}
464            Some(Some(keys)) => {
465                keys.insert(key);
466            }
467            None => {
468                self.tables
469                    .insert(table.to_owned(), Some(BTreeSet::from([key])));
470            }
471        }
472    }
473
474    fn window(&mut self, base_key: &str, value: &str) {
475        self.windows
476            .entry(base_key.to_owned())
477            .or_default()
478            .insert(value.to_owned());
479    }
480
481    fn touched(&self) -> bool {
482        !self.tables.is_empty()
483            || !self.windows.is_empty()
484            || self.status
485            || self.conflicts
486            || self.rejections
487            || self.outcomes
488    }
489}
490
491/// §6.1: the server caps total operations per request (reference default
492/// 500) and rejects the whole batch with `sync.too_many_operations`; the
493/// client "splits and retries". Splitting happens at build time: commits are
494/// included IN ORDER until the operation budget is spent, the rest wait for
495/// the next round.
496const PUSH_OPS_PER_REQUEST: usize = 500;
497const MAX_LOCAL_PURGE_TARGETS: usize = 64;
498const MAX_LOCAL_PURGE_SELECTORS: usize = 8;
499const MAX_LOCAL_PURGE_VALUES: usize = 128;
500const MAX_LOCAL_PURGE_VALUE_LENGTH: usize = 256;
501pub const SECURITY_PREFLIGHT_REQUIRED_CODE: &str = "client.security_preflight_required";
502
503/// Dirty visible tables; `None` means a whole-replica recovery/reset.
504struct OverlayDirty(RefCell<Option<BTreeSet<String>>>);
505
506impl OverlayDirty {
507    fn clean() -> Self {
508        Self(RefCell::new(Some(BTreeSet::new())))
509    }
510    fn get(&self) -> bool {
511        self.0
512            .borrow()
513            .as_ref()
514            .is_none_or(|tables| !tables.is_empty())
515    }
516    fn set(&self, dirty: bool) {
517        *self.0.borrow_mut() = if dirty { None } else { Some(BTreeSet::new()) };
518    }
519    fn table(&self, table: &str) {
520        if let Some(tables) = self.0.borrow_mut().as_mut() {
521            tables.insert(table.to_owned());
522        }
523    }
524    fn snapshot(&self) -> Option<BTreeSet<String>> {
525        self.0.borrow().clone()
526    }
527    fn restore(&self, tables: Option<BTreeSet<String>>) {
528        *self.0.borrow_mut() = tables;
529    }
530}
531
532/// A copy-on-write in-memory mirror: a [`Rollback`] shares it, and the first
533/// write after a capture copies it once.
534#[derive(Debug, Clone, Default)]
535struct Shared<T>(Arc<T>);
536
537impl<T> std::ops::Deref for Shared<T> {
538    type Target = T;
539    fn deref(&self) -> &T {
540        &self.0
541    }
542}
543
544impl<T: Clone> std::ops::DerefMut for Shared<T> {
545    fn deref_mut(&mut self) -> &mut T {
546        Arc::make_mut(&mut self.0)
547    }
548}
549
550impl<T> From<T> for Shared<T> {
551    fn from(value: T) -> Self {
552        Self(Arc::new(value))
553    }
554}
555
556/// The in-memory mirrors of durable state, captured before a local
557/// transaction and restored when it rolls back. Queues only grow inside a
558/// transaction, so their lengths suffice.
559#[derive(Debug, Clone)]
560struct Rollback {
561    outbox: Shared<Vec<Arc<OutboxCommit>>>,
562    failed_commits: Shared<Vec<FailedCommit>>,
563    conflicts: Shared<Vec<ConflictRecord>>,
564    rejections: Shared<Vec<RejectionRecord>>,
565    schema_floor: Option<SchemaFloor>,
566    lease_state: Option<LeaseState>,
567    stopped: bool,
568    upgrading: bool,
569    upgrade_kept_tables: bool,
570    sync_needed: bool,
571    active_round: Option<(uuid::Uuid, i64, u64)>,
572    overlay_dirty: Option<BTreeSet<String>>,
573    transport_gate: crate::TransportGate,
574    transport_epoch: u64,
575    change_queue: usize,
576    projection_pending_queue: usize,
577    sync_intent_queue: usize,
578    last_change: Option<DiagnosticLastChange>,
579}
580
581pub struct SyncClient {
582    #[cfg(feature = "bench-internals")]
583    benchmark_phases: Recorder,
584    conn: Connection,
585    schema: ClientSchema,
586    client_id: String,
587    limits: ClientLimits,
588    outbox: Shared<Vec<Arc<OutboxCommit>>>,
589    failed_commits: Shared<Vec<FailedCommit>>,
590    retain_failed_commits: bool,
591    conflicts: Shared<Vec<ConflictRecord>>,
592    rejections: Shared<Vec<RejectionRecord>>,
593    schema_floor: Option<SchemaFloor>,
594    /// §7.3.5: the opaque auth-lease state (from LEASE frames + lease errors).
595    lease_state: Option<LeaseState>,
596    /// §1.6: the schema-floor response stops syncing until an upgrade.
597    stopped: bool,
598    /// §7.4.5: true while a schema-bump reset + first re-bootstrap is in flight.
599    upgrading: bool,
600    /// §7.4.5: the running reset kept at least one table.
601    upgrade_kept_tables: bool,
602    /// §8.4 coalesced sync-needed signal.
603    sync_needed: bool,
604    /// §8.8: how sync rounds treat the realtime binding, and its exact
605    /// availability state with the evidence behind a lost or refused one.
606    realtime_policy: RealtimePolicy,
607    realtime_state: RealtimeState,
608    realtime_reason_code: Option<String>,
609    realtime_retry_delay_ms: Option<u64>,
610    /// §8.6 presence: scopeKey → (`actorId clientId` peer key → peer).
611    presence: HashMap<String, HashMap<String, PresencePeer>>,
612    /// Client clock (epoch ms) for the §5.4 `urlExpiresAtMs` check and the
613    /// §7.8 drive deadline; the host may pin it and move the pinned value
614    /// (conformance runs on a virtual clock).
615    now_ms: Option<std::sync::Arc<std::sync::atomic::AtomicI64>>,
616    /// §5.11 client-side encryption keys (`keyId → key bytes`). Empty ⇒ E2EE
617    /// off. The encrypt/decrypt seam (`values.rs`) is compiled only under the
618    /// `e2ee` feature; without it, a schema with encrypted columns fails loud.
619    encryption: crate::values::EncryptionConfig,
620    /// Fail-closed host bootstrap gate. While set, command hosts permit only
621    /// status/lifecycle inspection and an exact authorized local purge.
622    security_preflight: bool,
623    security_epoch: u64,
624    transport_gate: crate::TransportGate,
625    transport_epoch: u64,
626    /// Raised by every registration change; a current-base proof spanning
627    /// one reports missing coverage.
628    registration_epoch: u64,
629    /// RFC 0005 D2/D8: the previous-version capture config. `None` (default)
630    /// means the feature is off; the descriptor write and the container orphan
631    /// sweep still happen.
632    previous_version: Option<PreviousVersionContextConfig>,
633    /// Per-table primary-key upsert SQL, built once per (full table name) —
634    /// the row write path runs per row during bootstrap (§5.6), so the SQL
635    /// string (and, via `prepare_cached`, its compiled statement) is reused
636    /// instead of being rebuilt and re-prepared per row. Cleared on a §7.4.3
637    /// schema reset (the column lists may have changed).
638    insert_sql: RefCell<HashMap<String, String>>,
639    /// §7.1: reconcile only tables whose base/outbox changed. Whole-replica
640    /// reset and restart explicitly invalidate every table.
641    overlay_dirty: OverlayDirty,
642    // First SQLite failure of the current operation, before savepoint cleanup.
643    storage_failure: RefCell<Option<QueryReadFailure>>,
644    /// Test-only structural performance signal: response processing must not
645    /// turn a batch of acknowledgements into one full overlay rebuild each.
646    #[cfg(test)]
647    overlay_rebuild_count: Cell<usize>,
648    #[cfg(test)]
649    acknowledged_replay_count: Cell<usize>,
650    /// Test-only structural performance signal: outcome retention is enforced
651    /// once per response rather than once per acknowledgement.
652    #[cfg(test)]
653    outcome_prune_count: Cell<usize>,
654    /// Test-only pinned time of every §5.3 image chunk, in ms: fixed write
655    /// time, write time per row, and commit time.
656    #[cfg(test)]
657    image_chunk_ms: Cell<Option<(f64, f64, f64)>>,
658    /// Exact observer-transaction output drained by command/FFI hosts.
659    progress: ProgressObserver,
660    /// §7.6: random per core instance, never persisted or sent.
661    epoch: String,
662    change_queue: VecDeque<ClientChangeBatch>,
663    projection_pending_queue: VecDeque<String>,
664    opening_replica: bool,
665    sync_intent_queue: VecDeque<SyncIntent>,
666    /// §8.7 `scopes` events received since the last drain.
667    scopes_changed: usize,
668    /// §3.3: units `set_window` registered or re-armed and no round accepted since.
669    window_armed: HashSet<String>,
670    /// Explicit exponential retry policy for transient transport failures.
671    retry_delay_ms: u64,
672    /// §7.7: the background retry the current round scheduled, if any.
673    round_retry_delay_ms: Option<u64>,
674    /// §5.3: a table's next image chunk size, carried from one range image
675    /// of the table to the next.
676    image_chunk_rows: HashMap<String, u32>,
677    /// A round whose response never completed (§1.5): the client keeps its
678    /// code and reports it on every following request until a round receives a
679    /// complete, decodable response. The server already recorded the round, so
680    /// nothing else can tell it the round failed on this side.
681    round_failure: Option<String>,
682    /// The in-flight round: its id, `started_at_ms` and progress attempt.
683    active_round: Option<(uuid::Uuid, i64, u64)>,
684    /// The in-flight §6.12 fence round, serialized with sync rounds.
685    fence_round: Option<uuid::Uuid>,
686    last_round: Option<DiagnosticLastRound>,
687    last_change: Option<DiagnosticLastChange>,
688    /// §7.6: latest failed owned snapshot read per owner id, oldest first.
689    query_failures: Vec<DiagnosticQueryFailure>,
690    /// SPEC §1.4 rule 4: the open coalesced apply transaction of a response.
691    coalesced: Option<CoalescedApply>,
692    /// A coalesced apply transaction of the current response failed; every
693    /// later observation of that response fails until it ends.
694    coalesced_failure: Option<String>,
695}
696
697/// SPEC §1.4 rule 4: the frames and blocks of one response share one local
698/// write transaction of at most `COALESCED_APPLY_ROWS` rows. The in-memory
699/// state captured at its `BEGIN` is restored when its `COMMIT` fails.
700struct CoalescedApply {
701    rows: usize,
702    rollback: Rollback,
703}
704
705const COALESCED_APPLY_ROWS: usize = 1024;
706
707pub(crate) fn quote_ident(name: &str) -> String {
708    format!("\"{}\"", name.replace('"', "\"\""))
709}
710/// §7.4.1 `_syncular_meta` helpers. Free functions so RFC 0005's
711/// previous-version module reads and writes the SAME records as the client
712/// instead of growing a parallel meta layer.
713pub(crate) fn meta_get(conn: &Connection, key: &str) -> rusqlite::Result<Option<String>> {
714    conn.query_row(
715        "SELECT value FROM _syncular_meta WHERE key = ?1",
716        rusqlite::params![key],
717        |row| row.get::<_, String>(0),
718    )
719    .optional()
720}
721
722pub(crate) fn meta_set(conn: &Connection, key: &str, value: &str) -> rusqlite::Result<()> {
723    conn.execute(
724        "INSERT OR REPLACE INTO _syncular_meta (key, value) VALUES (?1, ?2)",
725        rusqlite::params![key, value],
726    )
727    .map(|_| ())
728}
729
730pub(crate) fn meta_delete(conn: &Connection, key: &str) -> rusqlite::Result<()> {
731    conn.execute(
732        "DELETE FROM _syncular_meta WHERE key = ?1",
733        rusqlite::params![key],
734    )
735    .map(|_| ())
736}
737
738/// Seek by the existing key while retaining the exact legacy text match.
739fn row_id_predicate(table: &TableSchema) -> String {
740    let key = quote_ident(&table.primary_key);
741    let text_match = format!("CAST({key} AS TEXT) = ?1");
742    match table.columns[table.pk_index].ty {
743        ColumnType::String | ColumnType::Json => {
744            format!("{key} = ?1 AND {text_match}")
745        }
746        // Native columns have no declared SQLite affinity. Match the stored
747        // integer bind type explicitly. Unary + removes expression affinity so
748        // SQLite can seek the typeless key; the text check preserves exact IDs.
749        ColumnType::Integer | ColumnType::Boolean => {
750            format!("{key} = +CAST(?1 AS INTEGER) AND {text_match}")
751        }
752        // REAL-to-text conversion can round distinct values to the same text.
753        // Narrowing those matches by numeric equality would change behavior.
754        _ => text_match,
755    }
756}
757
758/// §3.3/§4.8/§5.6 row ownership: rows whose local scope columns match
759/// `effective` and that no entry of `owners` matches. `owners` holds the
760/// pair scopes of every owner of the table (§3.3 row ownership); a scoped delete never removes a row one of them still covers.
761/// Scope values bind by the column's declared type, as `row_id_predicate`
762/// does. `Ok(None)` matches nothing (an empty map or value list); `Err(())`
763/// is a missing local scope-column mapping (the fail-closed case).
764fn local_scope_predicate(
765    table: &TableSchema,
766    effective: &[(String, Vec<String>)],
767    owners: &[Vec<(String, Vec<String>)>],
768) -> Result<Option<(String, Vec<SqlValue>)>, ()> {
769    if effective.is_empty() || effective.iter().any(|(_, values)| values.is_empty()) {
770        return Ok(None);
771    }
772    let column = |variable: &str| {
773        let name = table.scope_column(variable).ok_or(())?;
774        let column = table
775            .columns
776            .iter()
777            .find(|column| column.name == name)
778            .ok_or(())?;
779        Ok((quote_ident(name), column.ty == ColumnType::Integer))
780    };
781    let mut clauses = Vec::new();
782    let mut params = Vec::new();
783    for (variable, values) in effective {
784        let (key, integer) = column(variable)?;
785        let holes = vec!["?"; values.len()].join(", ");
786        clauses.push(if integer {
787            params.extend(values.iter().cloned().map(SqlValue::Text));
788            let seek = vec!["+CAST(? AS INTEGER)"; values.len()].join(", ");
789            format!("{key} IN ({seek}) AND CAST({key} AS TEXT) IN ({holes})")
790        } else {
791            format!("{key} IN ({holes})")
792        });
793        params.extend(values.iter().cloned().map(SqlValue::Text));
794    }
795    // Owners bind as one JSON parameter per variable set, so the statement
796    // keeps its size at any owner count; owners of one variable bind the
797    // union of their values. An owner holding other values of a variable
798    // `effective` names owns none of its rows and drops out. Values compare
799    // as text, the exact semantics of the effective clauses.
800    let mut groups: BTreeMap<Vec<&str>, Vec<Vec<&[String]>>> = BTreeMap::new();
801    for owner in owners {
802        if owner.is_empty()
803            || owner.iter().any(|(variable, values)| {
804                values.is_empty()
805                    || effective.iter().any(|(name, wanted)| {
806                        name == variable && wanted.iter().all(|value| !values.contains(value))
807                    })
808            })
809        {
810            continue;
811        }
812        let mut owner: Vec<_> = owner.iter().collect();
813        owner.sort_by(|a, b| a.0.cmp(&b.0));
814        groups
815            .entry(
816                owner
817                    .iter()
818                    .map(|(variable, _)| variable.as_str())
819                    .collect(),
820            )
821            .or_default()
822            .push(owner.iter().map(|(_, values)| values.as_slice()).collect());
823    }
824    let within = |variable: &str, list: &str| {
825        let (key, integer) = column(variable)?;
826        let key = if integer {
827            format!("CAST({key} AS TEXT)")
828        } else {
829            key
830        };
831        Ok(format!("{key} IN (SELECT value FROM json_each({list}))"))
832    };
833    for (variables, tuples) in groups {
834        if let [variable] = variables[..] {
835            let values: BTreeSet<&String> = tuples.iter().flatten().copied().flatten().collect();
836            params.push(SqlValue::Text(
837                Value::from_iter(values.into_iter().cloned()).to_string(),
838            ));
839            clauses.push(format!("NOT {}", within(variable, "?")?));
840        } else {
841            params.push(SqlValue::Text(
842                serde_json::to_string(&tuples).expect("owner tuples serialize"),
843            ));
844            let matches = variables
845                .iter()
846                .enumerate()
847                .map(|(index, variable)| within(variable, &format!("o.value,'$[{index}]'")))
848                .collect::<Result<Vec<_>, ()>>()?;
849            clauses.push(format!(
850                "NOT EXISTS (SELECT 1 FROM json_each(?) o WHERE {})",
851                matches.join(" AND ")
852            ));
853        }
854    }
855    Ok(Some((clauses.join(" AND "), params)))
856}
857
858/// [`local_scope_predicate`] over decoded row values (retained rows).
859fn owns_local_row(
860    table: &TableSchema,
861    effective: &[(String, Vec<String>)],
862    owners: &[Vec<(String, Vec<String>)>],
863    values: &Map<String, Value>,
864) -> bool {
865    let matches = |scopes: &[(String, Vec<String>)]| {
866        !scopes.is_empty()
867            && scopes.iter().all(|(variable, allowed)| {
868                table
869                    .scope_column(variable)
870                    .and_then(|column| values.get(column))
871                    .filter(|value| !value.is_null())
872                    .is_some_and(|value| {
873                        allowed.contains(
874                            &value
875                                .as_str()
876                                .map_or_else(|| value.to_string(), str::to_owned),
877                        )
878                    })
879            })
880    };
881    matches(effective) && !owners.iter().any(|owner| matches(owner))
882}
883
884fn is_local_operation_code_like(value: &str) -> bool {
885    let bytes = value.as_bytes();
886    bytes.first().is_some_and(u8::is_ascii_alphanumeric)
887        && bytes
888            .iter()
889            .all(|byte| byte.is_ascii_alphanumeric() || matches!(*byte, b'.' | b'_' | b':' | b'-'))
890}
891
892fn base_table(name: &str) -> String {
893    quote_ident(&format!("_syncular_base_{name}"))
894}
895
896/// §4.8 deferred eviction record: (unit id, table, effective scope map).
897type PendingEvict = (String, String, Vec<(String, Vec<String>)>);
898
899/// §4.8: a stable key for a window base: variable + canonical fixed scopes.
900fn window_base_key(base: &WindowBase) -> String {
901    format!(
902        "{}\0{}",
903        base.variable,
904        ssp2::registration::canonical_unit_json(&scope_pairs(&base.fixed_scopes))
905    )
906}
907
908/// The unit of one window value: the fixed scopes plus the value.
909fn window_unit_scopes(base: &WindowBase, value: &str) -> UnitScopes {
910    let mut scopes = base.fixed_scopes.clone();
911    scopes.insert(base.variable.clone(), value.to_owned());
912    scopes
913}
914
915/// A unit's scope map as the codec and the digests take it.
916fn scope_pairs(scopes: &UnitScopes) -> Vec<(String, String)> {
917    let mut pairs: Vec<(String, String)> = scopes
918        .iter()
919        .map(|(variable, value)| (variable.clone(), value.clone()))
920        .collect();
921    pairs.sort_by(|a, b| a.0.encode_utf16().cmp(b.0.encode_utf16()));
922    pairs
923}
924
925/// §4.1: the unit covers every table declaring all of its variables.
926fn covers(table: &TableSchema, scopes: &UnitScopes) -> bool {
927    scopes
928        .keys()
929        .all(|variable| table.scope_column(variable).is_some())
930}
931
932/// §4.4: the effective scopes of the (unit, table) pair under `echo`: the
933/// scope map as one-element lists plus the fenced lists. `None` when the
934/// fence revoked the pair.
935fn pair_scopes(
936    scopes: &UnitScopes,
937    table: &str,
938    echo: Option<&[EchoRecord]>,
939) -> Option<Vec<(String, Vec<String>)>> {
940    let fenced = echo.and_then(|echo| echo.iter().find(|record| record.table == table));
941    if fenced.is_some_and(|record| record.status == "revoked") {
942        return None;
943    }
944    let mut effective: BTreeMap<String, Vec<String>> = fenced
945        .map(|record| record.scopes.clone())
946        .unwrap_or_default();
947    for (variable, value) in scopes {
948        effective.insert(variable.clone(), vec![value.clone()]);
949    }
950    Some(effective.into_iter().collect())
951}
952
953/// §7.5 subset rule for one coverage value of `table`: its authority state
954/// (`complete`, `pending`, `missing` or `revoked`) and whether a candidate is
955/// `revoked`. A candidate is a persisted unit whose variables are a subset of
956/// the entry's and whose values equal the entry's on them. `declared` also
957/// requires that the table declares every variable of the unit; the read
958/// sidecar holds no schema, and there the subset of the entry's variables,
959/// which the table declares, implies it.
960fn entry_coverage(
961    units: &[UnitRecord],
962    table: &str,
963    declared: Option<&TableSchema>,
964    base: &WindowBase,
965    value: &str,
966) -> (&'static str, bool) {
967    let entry = window_unit_scopes(base, value);
968    let candidates: Vec<&UnitRecord> = units
969        .iter()
970        .filter(|unit| {
971            declared.is_none_or(|schema| covers(schema, &unit.scopes))
972                && unit
973                    .scopes
974                    .iter()
975                    .all(|(variable, held)| entry.get(variable) == Some(held))
976        })
977        .collect();
978    let complete = candidates.iter().any(|unit| {
979        unit.status == UnitStatus::Active
980            && !unit.bootstrapping()
981            && unit.echo.is_some()
982            && pair_scopes(&unit.scopes, table, unit.echo.as_deref()).is_some_and(|effective| {
983                entry
984                    .keys()
985                    .filter(|variable| !unit.scopes.contains_key(*variable))
986                    .all(|variable| {
987                        effective
988                            .iter()
989                            .find(|(name, _)| name == variable)
990                            .is_none_or(|(_, values)| values.iter().any(|held| held == "*"))
991                    })
992            })
993    });
994    let revoked = candidates
995        .iter()
996        .any(|unit| unit.status == UnitStatus::Revoked);
997    let state = if complete {
998        "complete"
999    } else if candidates.is_empty() {
1000        "missing"
1001    } else if candidates
1002        .iter()
1003        .any(|unit| matches!(unit.status, UnitStatus::Revoked | UnitStatus::Failed))
1004    {
1005        "revoked"
1006    } else {
1007        "pending"
1008    };
1009    (state, revoked)
1010}
1011
1012/// §3.3 row ownership: the pair scopes of every owner of `table` except
1013/// `except_id`. An owner is active with a persisted echo and live or
1014/// post-bootstrap, or bootstrapping with a segment of the table in its
1015/// current bootstrap, or holding a restriction that excludes the table.
1016fn unit_owners(
1017    units: &[UnitRecord],
1018    table: &TableSchema,
1019    except_id: &str,
1020) -> Vec<Vec<(String, Vec<String>)>> {
1021    units
1022        .iter()
1023        .filter(|unit| {
1024            unit.id != except_id
1025                && unit.status == UnitStatus::Active
1026                && unit.echo.is_some()
1027                && (!unit.bootstrapping()
1028                    || unit.seeded.contains(&table.name)
1029                    || unit
1030                        .restriction
1031                        .as_ref()
1032                        .is_some_and(|restriction| !restriction.tables.contains(&table.name)))
1033                && covers(table, &unit.scopes)
1034        })
1035        .filter_map(|unit| pair_scopes(&unit.scopes, &table.name, unit.echo.as_deref()))
1036        .collect()
1037}
1038
1039/// §5.5 / §5.6: the unit's scope map, each value a one-element list.
1040fn unit_scope_lists(scopes: &UnitScopes) -> Vec<(String, Vec<String>)> {
1041    scopes
1042        .iter()
1043        .map(|(variable, value)| (variable.clone(), vec![value.clone()]))
1044        .collect()
1045}
1046
1047/// §7.1 acknowledged intent of the rows `?1` names (`[[table, id], ...]`).
1048/// It joins through the (tbl, id) index: a scan per acknowledgement would
1049/// make draining a batch quadratic.
1050const 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";
1051
1052const UNIT_COLUMNS: &str =
1053    "id, scopes, explicit, status, reason_code, cursor, bootstrap_state, seeded, echo, restriction";
1054
1055/// A unit row; a field that does not parse is a conversion failure, which
1056/// both read paths classify as `sync.local_corrupt`.
1057fn unit_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<UnitRecord> {
1058    fn json<T: serde::de::DeserializeOwned>(index: usize, raw: &str) -> rusqlite::Result<T> {
1059        serde_json::from_str(raw).map_err(|error| {
1060            rusqlite::Error::FromSqlConversionFailure(
1061                index,
1062                rusqlite::types::Type::Text,
1063                Box::new(error),
1064            )
1065        })
1066    }
1067    Ok(UnitRecord {
1068        id: row.get(0)?,
1069        scopes: json(1, &row.get::<_, String>(1)?)?,
1070        explicit: row.get::<_, i64>(2)? == 1,
1071        status: json(
1072            3,
1073            &serde_json::to_string(&row.get::<_, String>(3)?).expect("text"),
1074        )?,
1075        reason_code: row.get(4)?,
1076        cursor: row.get(5)?,
1077        bootstrap_state: row.get(6)?,
1078        seeded: json(7, &row.get::<_, String>(7)?)?,
1079        echo: row
1080            .get::<_, Option<String>>(8)?
1081            .map(|echo| json::<Vec<EchoRecord>>(8, &echo))
1082            .transpose()?
1083            .map(|echo| {
1084                if echo
1085                    .iter()
1086                    .all(|record| record.status == "active" || record.status == "revoked")
1087                {
1088                    Ok(echo)
1089                } else {
1090                    Err(rusqlite::Error::FromSqlConversionFailure(
1091                        8,
1092                        rusqlite::types::Type::Text,
1093                        "echo status is neither active nor revoked".into(),
1094                    ))
1095                }
1096            })
1097            .transpose()?,
1098        restriction: row
1099            .get::<_, Option<String>>(9)?
1100            .map(|raw| json::<UnitRestriction>(9, &raw))
1101            .transpose()?,
1102    })
1103}
1104
1105/// Every unit in registration order (§4.1).
1106fn load_units(conn: &Connection) -> rusqlite::Result<Vec<UnitRecord>> {
1107    conn.prepare_cached(&format!(
1108        "SELECT {UNIT_COLUMNS} FROM _syncular_units ORDER BY rowid"
1109    ))?
1110    .query_map([], unit_from_row)?
1111    .collect()
1112}
1113
1114fn get_unit(conn: &Connection, id: &str) -> rusqlite::Result<Option<UnitRecord>> {
1115    conn.query_row(
1116        &format!("SELECT {UNIT_COLUMNS} FROM _syncular_units WHERE id = ?1"),
1117        [id],
1118        unit_from_row,
1119    )
1120    .optional()
1121}
1122
1123/// Insert or update in place: an update keeps the registration order. The
1124/// §5.6 applied-segment record ends when the cursor or the token changes.
1125fn save_unit(conn: &Connection, unit: &UnitRecord) -> rusqlite::Result<()> {
1126    conn.prepare_cached(&format!(
1127        "INSERT INTO _syncular_units({UNIT_COLUMNS}) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10)
1128         ON CONFLICT(id) DO UPDATE SET explicit=excluded.explicit, status=excluded.status,
1129           reason_code=excluded.reason_code, cursor=excluded.cursor,
1130           bootstrap_state=excluded.bootstrap_state, seeded=excluded.seeded, echo=excluded.echo,
1131           restriction=excluded.restriction,
1132           applied=CASE WHEN cursor IS excluded.cursor
1133             AND bootstrap_state IS excluded.bootstrap_state THEN applied END"
1134    ))?
1135    .execute(rusqlite::params![
1136        unit.id,
1137        serde_json::to_string(&unit.scopes).expect("scope map serializes"),
1138        i64::from(unit.explicit),
1139        unit.status.name(),
1140        unit.reason_code,
1141        unit.cursor,
1142        unit.bootstrap_state,
1143        serde_json::to_string(&unit.seeded).expect("table list serializes"),
1144        unit.echo
1145            .as_ref()
1146            .map(|echo| serde_json::to_string(echo).expect("echo serializes")),
1147        unit.restriction
1148            .as_ref()
1149            .map(|restriction| serde_json::to_string(restriction).expect("restriction serializes")),
1150    ])
1151    .map(|_| ())
1152}
1153
1154/// §5.6 applied-segment record of unit `id`: segment id → rows applied at
1155/// its current cursor and token.
1156fn applied_rows(conn: &Connection, id: &str) -> rusqlite::Result<BTreeMap<String, i64>> {
1157    conn.query_row(
1158        "SELECT applied FROM _syncular_units WHERE id = ?1",
1159        [id],
1160        |row| row.get::<_, Option<String>>(0),
1161    )
1162    .optional()?
1163    .flatten()
1164    .map_or(Ok(BTreeMap::new()), |raw| {
1165        serde_json::from_str(&raw).map_err(|error| {
1166            rusqlite::Error::FromSqlConversionFailure(
1167                0,
1168                rusqlite::types::Type::Text,
1169                Box::new(error),
1170            )
1171        })
1172    })
1173}
1174
1175/// §5.6: `rows` rows of `segment_id` applied at unit `id`'s position. Runs
1176/// in the transaction that commits them.
1177fn record_applied_rows(
1178    conn: &Connection,
1179    id: &str,
1180    segment_id: &str,
1181    rows: i64,
1182) -> rusqlite::Result<()> {
1183    conn.prepare_cached(
1184        "UPDATE _syncular_units SET applied=json_patch(coalesce(applied,'{}'),?1) WHERE id=?2",
1185    )?
1186    .execute(rusqlite::params![
1187        serde_json::json!({ segment_id: rows }).to_string(),
1188        id
1189    ])
1190    .map(|_| ())
1191}
1192
1193/// §4.1 references: every window registry entry `(base, value)` holding a unit.
1194fn window_refs(conn: &Connection, unit_id: &str) -> rusqlite::Result<Vec<(String, String)>> {
1195    conn.prepare_cached("SELECT base, unit FROM _syncular_windows WHERE sub_id = ?1")?
1196        .query_map([unit_id], |row| Ok((row.get(0)?, row.get(1)?)))?
1197        .collect()
1198}
1199
1200/// §7.4.3 reset, §2.1 log reset and local rebootstrap: keep the unit
1201/// registrations and discard the synced state of every unit outside `keep`,
1202/// so the next round sends the list and bootstraps those units. A schema bump
1203/// passes `restrictions`: every reset unit keeps its echo and takes its
1204/// restriction from the map, if any (§7.4.3); the other resets discard both.
1205/// The replica cursor survives only while a kept unit is live. The caller
1206/// owns the transaction.
1207fn reset_units(
1208    conn: &Connection,
1209    keep: &BTreeSet<String>,
1210    restrictions: Option<&BTreeMap<String, UnitRestriction>>,
1211) -> rusqlite::Result<()> {
1212    conn.execute(
1213        "UPDATE _syncular_units SET status='active', reason_code=NULL, cursor=-1,
1214           bootstrap_state=NULL, seeded='[]', applied=NULL,
1215           echo=CASE WHEN ?2 IS NULL THEN NULL ELSE echo END,
1216           restriction=(SELECT value FROM json_each(?2) WHERE key=_syncular_units.id)
1217         WHERE id NOT IN (SELECT value FROM json_each(?1))",
1218        rusqlite::params![
1219            serde_json::to_string(keep).expect("unit ids serialize"),
1220            restrictions.map(|map| serde_json::to_string(map).expect("restrictions serialize")),
1221        ],
1222    )?;
1223    conn.execute_batch(
1224        "DELETE FROM _syncular_meta WHERE key IN ('echoDigest','registrationDigest');
1225         DELETE FROM _syncular_meta WHERE key='replicaCursor'
1226           AND NOT EXISTS (SELECT 1 FROM _syncular_units WHERE cursor IS NULL);",
1227    )
1228}
1229
1230/// §4.5: the replica cursor, `-1` while no unit is live.
1231fn replica_cursor(conn: &Connection) -> rusqlite::Result<i64> {
1232    meta_get(conn, REPLICA_CURSOR_KEY)?.map_or(Ok(-1), |raw| {
1233        raw.parse().map_err(|error| {
1234            rusqlite::Error::FromSqlConversionFailure(
1235                0,
1236                rusqlite::types::Type::Text,
1237                Box::new(error),
1238            )
1239        })
1240    })
1241}
1242
1243fn visible_table(name: &str) -> String {
1244    quote_ident(name)
1245}
1246
1247const FTS_SOURCE_ID_COLUMN: &str = "_syncular_source_id";
1248
1249/// §7.4.3: is a `sqlite_master` table name a synced table (visible or base),
1250/// i.e. NOT one of the durable bookkeeping tables the reset preserves?
1251fn is_synced_table_name(name: &str) -> bool {
1252    if name.starts_with("sqlite_") {
1253        return false;
1254    }
1255    if name.starts_with("_syncular_base_") {
1256        return true; // the base half of a synced table pair
1257    }
1258    // Bookkeeping: outbox, units, meta, blob cache/uploads.
1259    !name.starts_with("_syncular_")
1260}
1261
1262/// `"sha256:" + hex` of the bytes — the content address (§5.9.1).
1263fn blob_id_for(bytes: &[u8]) -> String {
1264    let digest = Sha256::digest(bytes);
1265    format!("sha256:{}", bytes_to_hex(&digest))
1266}
1267
1268/// One [`SyncClient::write_row`] bind parameter, borrowing the row-codec
1269/// value it wraps — strings/JSON/bytes bind as borrowed TEXT/BLOB (no copy
1270/// per row on the §5.6 bootstrap path), scalars bind owned.
1271enum RowParam<'a> {
1272    Cell(&'a Option<ColumnValue>),
1273    Version(i64),
1274    Text(Option<&'a str>),
1275}
1276
1277impl rusqlite::ToSql for RowParam<'_> {
1278    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
1279        Ok(match self {
1280            RowParam::Version(v) => ToSqlOutput::Owned(SqlValue::Integer(*v)),
1281            RowParam::Text(text) => match text {
1282                Some(text) => ToSqlOutput::Borrowed(ValueRef::Text(text.as_bytes())),
1283                None => ToSqlOutput::Owned(SqlValue::Null),
1284            },
1285            RowParam::Cell(cell) => match cell {
1286                None => ToSqlOutput::Owned(SqlValue::Null),
1287                Some(ColumnValue::String(s)) => ToSqlOutput::Borrowed(ValueRef::Text(s.as_bytes())),
1288                Some(ColumnValue::Integer(i)) => ToSqlOutput::Owned(SqlValue::Integer(*i)),
1289                Some(ColumnValue::Float(f)) => ToSqlOutput::Owned(SqlValue::Real(*f)),
1290                Some(ColumnValue::Boolean(b)) => {
1291                    ToSqlOutput::Owned(SqlValue::Integer(i64::from(*b)))
1292                }
1293                Some(ColumnValue::Json(raw)) | Some(ColumnValue::BlobRef(raw)) => {
1294                    ToSqlOutput::Borrowed(ValueRef::Text(raw.0.as_bytes()))
1295                }
1296                // §5.10: crdt bytes store as BLOB, like bytes.
1297                Some(ColumnValue::Bytes(b)) | Some(ColumnValue::Crdt(b)) => {
1298                    ToSqlOutput::Borrowed(ValueRef::Blob(b))
1299                }
1300            },
1301        })
1302    }
1303}
1304
1305// Retain a typed primary key across the current import chunk without copying row payloads.
1306fn owned_sql_value(param: impl rusqlite::ToSql) -> Result<SqlValue, String> {
1307    match param.to_sql().map_err(|error| error.to_string())? {
1308        ToSqlOutput::Owned(value) => Ok(value),
1309        ToSqlOutput::Borrowed(value) => {
1310            SqlValue::try_from(value).map_err(|error| error.to_string())
1311        }
1312        _ => Err("sync.invalid_request: unsupported SQLite key parameter".into()),
1313    }
1314}
1315
1316/// §5.3 image cell → bind parameter, strict per the declared column type
1317/// (`boolean` from INTEGER 0/1, `json` from its raw TEXT, NULL only when
1318/// nullable). Mismatches are image-producer violations. Returns the cell
1319/// borrowed when the stored representation already matches what the row
1320/// codec would write, or the normalized scalar (boolean → 0/1, float from
1321/// INTEGER → REAL) otherwise — the local write is byte-identical to the
1322/// old convert-then-insert path without allocating per cell.
1323fn image_cell_param<'a>(column: &Column, value: ValueRef<'a>) -> Result<ToSqlOutput<'a>, String> {
1324    use ssp2::segment::ColumnType;
1325    let mismatch = || {
1326        Err(format!(
1327            "image column {:?} holds a value of the wrong type",
1328            column.name
1329        ))
1330    };
1331    match value {
1332        ValueRef::Null => {
1333            if !column.nullable {
1334                return Err(format!(
1335                    "image column {:?} is NULL but not nullable",
1336                    column.name
1337                ));
1338            }
1339            Ok(ToSqlOutput::Owned(SqlValue::Null))
1340        }
1341        ValueRef::Integer(i) => match column.ty {
1342            ColumnType::Integer => Ok(ToSqlOutput::Borrowed(value)),
1343            ColumnType::Boolean => Ok(ToSqlOutput::Owned(SqlValue::Integer(i64::from(i != 0)))),
1344            ColumnType::Float => Ok(ToSqlOutput::Owned(SqlValue::Real(i as f64))),
1345            _ => mismatch(),
1346        },
1347        ValueRef::Real(_) => match column.ty {
1348            ColumnType::Float => Ok(ToSqlOutput::Borrowed(value)),
1349            _ => mismatch(),
1350        },
1351        ValueRef::Text(t) => {
1352            std::str::from_utf8(t)
1353                .map_err(|_| format!("image column {:?} is not UTF-8", column.name))?;
1354            match column.ty {
1355                ColumnType::String | ColumnType::Json | ColumnType::BlobRef => {
1356                    Ok(ToSqlOutput::Borrowed(value))
1357                }
1358                _ => mismatch(),
1359            }
1360        }
1361        ValueRef::Blob(_) => match column.ty {
1362            // §5.10: a crdt column stores its opaque bytes as BLOB, like bytes.
1363            ColumnType::Bytes | ColumnType::Crdt => Ok(ToSqlOutput::Borrowed(value)),
1364            _ => mismatch(),
1365        },
1366    }
1367}
1368
1369pub(crate) fn sql_ref_to_json(column: &Column, value: rusqlite::types::ValueRef<'_>) -> Value {
1370    use rusqlite::types::ValueRef;
1371    match value {
1372        ValueRef::Null => Value::Null,
1373        ValueRef::Integer(i) => match column.ty {
1374            ssp2::segment::ColumnType::Boolean => Value::Bool(i != 0),
1375            ssp2::segment::ColumnType::Float => {
1376                serde_json::Number::from_f64(i as f64).map_or(Value::Null, Value::Number)
1377            }
1378            _ => Value::from(i),
1379        },
1380        ValueRef::Real(f) => serde_json::Number::from_f64(f).map_or(Value::Null, Value::Number),
1381        ValueRef::Text(t) => Value::from(String::from_utf8_lossy(t).into_owned()),
1382        ValueRef::Blob(b) => {
1383            let mut map = Map::new();
1384            map.insert("$bytes".to_owned(), Value::from(bytes_to_hex(b)));
1385            Value::Object(map)
1386        }
1387    }
1388}
1389
1390/// Bind a driver JSON value form as a rusqlite parameter for [`SyncClient::query`].
1391/// Objects are accepted in lossless `{"$bytes": hex}` and
1392/// `{"$bigint": decimal}` envelope forms.
1393fn json_param_to_sql(value: &Value) -> Result<SqlValue, String> {
1394    Ok(match value {
1395        Value::Null => SqlValue::Null,
1396        Value::Bool(b) => SqlValue::Integer(i64::from(*b)),
1397        Value::Number(n) => {
1398            if let Some(i) = n.as_i64() {
1399                SqlValue::Integer(i)
1400            } else if let Some(f) = n.as_f64() {
1401                SqlValue::Real(f)
1402            } else {
1403                return Err(format!("query param number {n} is out of range"));
1404            }
1405        }
1406        Value::String(s) => SqlValue::Text(s.clone()),
1407        Value::Object(_) => {
1408            if let Some(hex) = value.get("$bytes").and_then(Value::as_str) {
1409                SqlValue::Blob(crate::values::hex_to_bytes(hex)?)
1410            } else if let Some(decimal) = value.get("$bigint").and_then(Value::as_str) {
1411                SqlValue::Integer(decimal.parse::<i64>().map_err(|_| {
1412                    format!("query bigint param {decimal:?} is outside SQLite's i64 range")
1413                })?)
1414            } else {
1415                return Err(
1416                    "query object param must be a {$bytes: hex} or {$bigint: decimal} value"
1417                        .to_owned(),
1418                );
1419            }
1420        }
1421        Value::Array(_) => return Err("query array params are not supported".to_owned()),
1422    })
1423}
1424
1425/// Map a rusqlite value with no schema column to consult (arbitrary query
1426/// output): integers/reals/text pass through by stored affinity, blobs ride
1427/// as `{"$bytes": hex}`. Distinct from [`sql_ref_to_json`], which uses the
1428/// schema column type to recover booleans/floats/json.
1429fn sql_ref_to_json_dynamic(value: rusqlite::types::ValueRef<'_>) -> Value {
1430    use rusqlite::types::ValueRef;
1431    match value {
1432        ValueRef::Null => Value::Null,
1433        ValueRef::Integer(i) => {
1434            // JSON/Tauri IPC cannot represent every SQLite i64 exactly. Keep
1435            // ordinary UI-sized integers ergonomic and envelope only values
1436            // beyond JavaScript's safe range.
1437            const MAX_SAFE_INTEGER: i64 = 9_007_199_254_740_991;
1438            if (-MAX_SAFE_INTEGER..=MAX_SAFE_INTEGER).contains(&i) {
1439                Value::from(i)
1440            } else {
1441                let mut map = Map::new();
1442                map.insert("$bigint".to_owned(), Value::from(i.to_string()));
1443                Value::Object(map)
1444            }
1445        }
1446        ValueRef::Real(f) => serde_json::Number::from_f64(f).map_or(Value::Null, Value::Number),
1447        ValueRef::Text(t) => Value::from(String::from_utf8_lossy(t).into_owned()),
1448        ValueRef::Blob(b) => {
1449            let mut map = Map::new();
1450            map.insert("$bytes".to_owned(), Value::from(bytes_to_hex(b)));
1451            Value::Object(map)
1452        }
1453    }
1454}
1455
1456/// §7.5: SQLite failures classify by result code into [`QueryReadFailure`].
1457fn query_connection(
1458    conn: &Connection,
1459    sql: &str,
1460    params: &[QueryValue],
1461) -> Result<Vec<QueryRow>, QueryReadFailure> {
1462    let lowered_sql = crate::query_guard::lower_public_query_sql(sql);
1463    let mut stmt = crate::query_guard::prepare_read_only(conn, &lowered_sql)?;
1464    let bound: Vec<SqlValue> = params
1465        .iter()
1466        .map(json_param_to_sql)
1467        .collect::<Result<_, _>>()?;
1468    // §2.4: an unaliased physical version column stays engine-internal, so a
1469    // `SELECT *` row feeds straight back into mutation values. An explicit
1470    // alias (`_sync_version AS v`) returns it as ordinary query data. The
1471    // §5.11 sealed columns follow the same rule.
1472    let columns: Vec<(usize, String)> = stmt
1473        .column_names()
1474        .enumerate()
1475        .filter(|(_, name)| {
1476            !matches!(
1477                *name,
1478                "_syncular_version" | "_sync_sealed_key" | "_sync_sealed"
1479            )
1480        })
1481        .map(|(i, name)| (i, name.to_owned()))
1482        .collect();
1483    let bound_refs: Vec<&dyn rusqlite::ToSql> =
1484        bound.iter().map(|v| v as &dyn rusqlite::ToSql).collect();
1485    let mut sql_rows = stmt.query(bound_refs.as_slice())?;
1486    let mut out = Vec::new();
1487    while let Some(row) = sql_rows.next()? {
1488        let mut record = Map::new();
1489        for (i, name) in &columns {
1490            let value = row.get_ref(*i)?;
1491            record.insert(name.clone(), sql_ref_to_json_dynamic(value));
1492        }
1493        out.push(record);
1494    }
1495    Ok(out)
1496}
1497
1498fn persisted_window_state(
1499    conn: &Connection,
1500    base: &WindowBase,
1501) -> Result<WindowState, QueryReadFailure> {
1502    let mut stmt = conn.prepare(
1503        "SELECT windows.unit, units.status, units.cursor, units.bootstrap_state
1504           FROM _syncular_windows AS windows
1505           LEFT JOIN _syncular_units AS units ON units.id = windows.sub_id
1506          WHERE windows.base = ?1
1507          ORDER BY windows.unit ASC",
1508    )?;
1509    let rows = stmt.query_map(rusqlite::params![window_base_key(base)], |row| {
1510        Ok((
1511            row.get::<_, String>(0)?,
1512            row.get::<_, Option<String>>(1)?,
1513            row.get::<_, Option<i64>>(2)?,
1514            row.get::<_, Option<String>>(3)?,
1515        ))
1516    })?;
1517    let mut units = Vec::new();
1518    let mut pending = Vec::new();
1519    let mut revoked = Vec::new();
1520    for row in rows {
1521        let (unit, status, cursor, bootstrap_state) = row?;
1522        if status.as_deref() == Some("revoked") {
1523            revoked.push(unit.clone());
1524        }
1525        // §4.8: complete iff registered, active and not bootstrapping.
1526        if status.as_deref() != Some("active")
1527            || cursor.is_some_and(|cursor| cursor < 0 || bootstrap_state.is_some())
1528        {
1529            pending.push(unit.clone());
1530        }
1531        units.push(unit);
1532    }
1533    Ok(WindowState {
1534        units,
1535        pending,
1536        revoked,
1537    })
1538}
1539
1540/// One read-only statement in a §7.5 snapshot read.
1541#[derive(Debug, Clone, Copy)]
1542pub struct SnapshotStatement<'a> {
1543    pub sql: &'a str,
1544    pub params: &'a [Value],
1545}
1546
1547/// A §7.5 atomic read request: read-only statements, window coverage, unit
1548/// catch-up states, and commit deliveries, all resolved from one SQLite read
1549/// transaction and one revision.
1550#[derive(Debug, Clone, Default)]
1551pub struct SnapshotReadRequest<'a> {
1552    pub statements: Vec<SnapshotStatement<'a>>,
1553    pub coverage: &'a [WindowCoverage],
1554    pub units: Vec<String>,
1555    pub commit_ids: Vec<String>,
1556}
1557
1558#[cfg(test)]
1559thread_local! {
1560    /// Test-only rendezvous that runs between the statements of one snapshot
1561    /// read. A test uses it to commit on another connection mid-read and prove
1562    /// the read transaction's snapshot and revision stay stable.
1563    static SNAPSHOT_READ_HOOK: std::cell::RefCell<Option<Box<dyn FnOnce()>>> =
1564        std::cell::RefCell::new(None);
1565}
1566
1567#[cfg(test)]
1568fn run_snapshot_read_hook() {
1569    SNAPSHOT_READ_HOOK.with(|slot| {
1570        if let Some(hook) = slot.borrow_mut().take() {
1571            hook();
1572        }
1573    });
1574}
1575
1576/// §7.5: resolve a request over one SQLite read transaction. The revision,
1577/// every statement's rows, coverage, catch-up states, and deliveries are
1578/// captured under one `SAVEPOINT`; any statement's failure rolls the whole
1579/// read back and releases the connection.
1580fn snapshot_read_connection(
1581    conn: &Connection,
1582    schema: Option<&ClientSchema>,
1583    request: &SnapshotReadRequest<'_>,
1584) -> Result<SnapshotRead, QueryReadFailure> {
1585    conn.execute_batch("SAVEPOINT syncular_snapshot_read")?;
1586    let corrupt = |message: &str| QueryReadFailure {
1587        code: Some("sync.local_corrupt"),
1588        sqlite_code: None,
1589        sqlite_message: None,
1590        rollback_failure: None,
1591        message: message.to_owned(),
1592    };
1593    let stored_failure = |error: rusqlite::Error, message: &str| match error {
1594        rusqlite::Error::Utf8Error(..)
1595        | rusqlite::Error::InvalidColumnType(..)
1596        | rusqlite::Error::FromSqlConversionFailure(..)
1597        | rusqlite::Error::IntegralValueOutOfRange(..) => corrupt(message),
1598        _ => QueryReadFailure::from(error),
1599    };
1600    let result: Result<SnapshotRead, QueryReadFailure> = (|| {
1601        // The durable revision as a canonical decimal `u64`; a missing marker
1602        // is the legacy zero, and any other non-canonical value is corrupt.
1603        let revision: Option<String> = conn
1604            .query_row(
1605                "SELECT value FROM _syncular_meta WHERE key = ?1",
1606                rusqlite::params![LOCAL_REVISION_KEY],
1607                |row| row.get(0),
1608            )
1609            .optional()
1610            .map_err(|error| stored_failure(error, "persisted local revision is invalid"))?;
1611        let revision = match revision {
1612            None => "0".to_owned(),
1613            Some(value)
1614                if value == "0"
1615                    || (matches!(value.as_bytes().first(), Some(b'1'..=b'9'))
1616                        && value.bytes().all(|b| b.is_ascii_digit())
1617                        && value.parse::<u64>().is_ok()) =>
1618            {
1619                value
1620            }
1621            Some(_) => return Err(corrupt("persisted local revision is invalid")),
1622        };
1623        let mut queries = Vec::with_capacity(request.statements.len());
1624        for statement in &request.statements {
1625            queries.push(query_connection(conn, statement.sql, statement.params)?);
1626            #[cfg(test)]
1627            run_snapshot_read_hook();
1628        }
1629        let mut pending = Vec::new();
1630        let mut missing = Vec::new();
1631        let mut revoked = Vec::new();
1632        let persisted = if request.coverage.is_empty() {
1633            Vec::new()
1634        } else {
1635            load_units(conn)
1636                .map_err(|error| stored_failure(error, "persisted unit state is invalid"))?
1637        };
1638        for requested in request.coverage {
1639            let declared = match schema {
1640                Some(schema) => {
1641                    Some(
1642                        schema
1643                            .table(&requested.table)
1644                            .ok_or_else(|| QueryReadFailure {
1645                                code: Some("sync.invalid_request"),
1646                                sqlite_code: None,
1647                                sqlite_message: None,
1648                                rollback_failure: None,
1649                                message: "unknown coverage table".to_owned(),
1650                            })?,
1651                    )
1652                }
1653                None => None,
1654            };
1655            let base_key = window_base_key(&requested.base);
1656            for unit in BTreeSet::from_iter(requested.units.iter().cloned()) {
1657                let (state, revoked_candidate) = entry_coverage(
1658                    &persisted,
1659                    &requested.table,
1660                    declared,
1661                    &requested.base,
1662                    &unit,
1663                );
1664                let reference = WindowUnitRef {
1665                    base_key: base_key.clone(),
1666                    unit,
1667                };
1668                // Refs dedupe across entries of several tables on one base.
1669                let add = |list: &mut Vec<WindowUnitRef>, reference: &WindowUnitRef| {
1670                    if !list.iter().any(|held| {
1671                        held.base_key == reference.base_key && held.unit == reference.unit
1672                    }) {
1673                        list.push(reference.clone());
1674                    }
1675                };
1676                match state {
1677                    "complete" => continue,
1678                    "missing" => add(&mut missing, &reference),
1679                    _ => add(&mut pending, &reference),
1680                }
1681                if revoked_candidate {
1682                    add(&mut revoked, &reference);
1683                }
1684            }
1685        }
1686        let mut units = Vec::with_capacity(request.units.len());
1687        for id in &request.units {
1688            let exists: bool = conn.query_row(
1689                "SELECT EXISTS(SELECT 1 FROM _syncular_units WHERE id = ?1)",
1690                [id],
1691                |row| row.get(0),
1692            )?;
1693            if !exists {
1694                units.push(UnitCatchup::Unknown { id: id.clone() });
1695                continue;
1696            }
1697            // Every persisted field is required to be well typed; a corrupt
1698            // record fails typed instead of inventing a state.
1699            let unit = get_unit(conn, id)
1700                .map_err(|error| stored_failure(error, "persisted unit state is invalid"))?
1701                .ok_or_else(|| corrupt("persisted unit state is invalid"))?;
1702            let cursor = match unit.cursor {
1703                Some(cursor) => cursor,
1704                None => replica_cursor(conn)
1705                    .map_err(|error| stored_failure(error, "persisted unit state is invalid"))?,
1706            };
1707            if cursor.unsigned_abs() > MAX_JS_SAFE_INTEGER {
1708                return Err(corrupt("persisted unit state is invalid"));
1709            }
1710            let active = unit.status == UnitStatus::Active;
1711            let pending = unit.bootstrapping();
1712            units.push(UnitCatchup::Known {
1713                id: id.clone(),
1714                status: unit.status,
1715                live: unit.cursor.is_none(),
1716                cursor,
1717                has_resume_token: unit.bootstrap_state.is_some(),
1718                bootstrap_complete: active && !pending,
1719                known_pending_pages: active && pending,
1720                reason_code: unit.reason_code,
1721            });
1722        }
1723        let mut deliveries = Vec::with_capacity(request.commit_ids.len());
1724        for id in &request.commit_ids {
1725            let pending: bool = conn.query_row(
1726                "SELECT EXISTS(SELECT 1 FROM _syncular_outbox WHERE commit_id = ?1)",
1727                rusqlite::params![id],
1728                |row| row.get(0),
1729            )?;
1730            if pending {
1731                deliveries.push(CommitDelivery::Pending {
1732                    client_commit_id: id.clone(),
1733                });
1734                continue;
1735            }
1736            let row = conn
1737                .query_row(
1738                    "SELECT seq, client_commit_id, status, recorded_at_ms, results_json, operations_json,
1739                            resolution, resolved_at_ms, replacement_client_commit_id
1740                       FROM _syncular_commit_outcomes WHERE client_commit_id = ?1",
1741                    rusqlite::params![id],
1742                    StoredCommitOutcomeRow::from_row,
1743                )
1744                .optional()
1745                .map_err(|error| stored_failure(error, "persisted commit outcome is invalid"))?;
1746            deliveries.push(match row {
1747                Some(row) => CommitDelivery::Known {
1748                    client_commit_id: id.clone(),
1749                    outcome: SyncClient::outcome_from_row(row)
1750                        .map(SyncClient::reported_outcome)
1751                        .map_err(|_| corrupt("persisted commit outcome is invalid"))?,
1752                },
1753                None => CommitDelivery::Unknown {
1754                    client_commit_id: id.clone(),
1755                },
1756            });
1757        }
1758        Ok(SnapshotRead {
1759            revision,
1760            queries,
1761            coverage: CoverageSnapshot {
1762                complete: pending.is_empty() && missing.is_empty(),
1763                pending,
1764                missing,
1765                revoked,
1766            },
1767            units,
1768            deliveries,
1769        })
1770    })();
1771    match result {
1772        Ok(read) => {
1773            conn.execute_batch("RELEASE syncular_snapshot_read")?;
1774            Ok(read)
1775        }
1776        Err(mut error) => {
1777            if let Err(rollback) = conn
1778                .execute_batch("ROLLBACK TO syncular_snapshot_read; RELEASE syncular_snapshot_read")
1779            {
1780                error.rollback_failure = Some(Box::new(QueryReadFailure::from(rollback)));
1781            }
1782            Err(error)
1783        }
1784    }
1785}
1786
1787fn snapshot_connection(
1788    conn: &Connection,
1789    schema: Option<&ClientSchema>,
1790    sql: &str,
1791    params: &[Value],
1792    coverage: &[WindowCoverage],
1793) -> Result<QuerySnapshot, QueryReadFailure> {
1794    let read = snapshot_read_connection(
1795        conn,
1796        schema,
1797        &SnapshotReadRequest {
1798            statements: vec![SnapshotStatement { sql, params }],
1799            coverage,
1800            units: Vec::new(),
1801            commit_ids: Vec::new(),
1802        },
1803    )?;
1804    Ok(QuerySnapshot {
1805        revision: read.revision,
1806        rows: read
1807            .queries
1808            .into_iter()
1809            .next()
1810            .expect("single-query snapshot returns one result"),
1811        coverage: read.coverage,
1812    })
1813}
1814
1815/// A long-lived read-only SQLite sidecar for latency-critical native views.
1816/// Network rounds stay serialized on the mutable core owner, while atomic
1817/// query snapshots use this independent connection and therefore never queue
1818/// behind HTTP/WebSocket latency.
1819pub struct FileQuerySnapshotReader {
1820    path: String,
1821    conn: Option<Connection>,
1822}
1823
1824impl FileQuerySnapshotReader {
1825    #[must_use]
1826    pub fn new(path: impl Into<String>) -> Self {
1827        Self {
1828            path: path.into(),
1829            conn: None,
1830        }
1831    }
1832
1833    fn connection(&mut self) -> Result<&Connection, QueryReadFailure> {
1834        if self.conn.is_none() {
1835            let conn = Connection::open_with_flags(
1836                &self.path,
1837                OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
1838            )
1839            .map_err(QueryReadFailure::from)?;
1840            conn.busy_timeout(std::time::Duration::from_millis(250))
1841                .map_err(QueryReadFailure::from)?;
1842            self.conn = Some(conn);
1843        }
1844        self.conn
1845            .as_ref()
1846            .ok_or_else(|| QueryReadFailure::from("read sidecar connection missing".to_owned()))
1847    }
1848
1849    /// One atomic read over the shared primitive: every statement, coverage,
1850    /// catch-up, and delivery under one `SAVEPOINT` and one revision.
1851    pub fn snapshot_read(
1852        &mut self,
1853        request: &SnapshotReadRequest<'_>,
1854    ) -> Result<SnapshotRead, QueryReadFailure> {
1855        snapshot_read_connection(self.connection()?, None, request)
1856    }
1857
1858    /// The current durable local revision. A host can skip a read when it is
1859    /// unchanged; a corrupt or unreadable marker fails typed.
1860    pub fn local_revision(&mut self) -> Result<String, QueryReadFailure> {
1861        Ok(self
1862            .snapshot_read(&SnapshotReadRequest::default())?
1863            .revision)
1864    }
1865
1866    /// One unit's persisted catch-up state (see the §7.5 contract).
1867    pub fn unit_catchup(&mut self, id: &str) -> Result<UnitCatchup, QueryReadFailure> {
1868        let read = self.snapshot_read(&SnapshotReadRequest {
1869            units: vec![id.to_owned()],
1870            ..Default::default()
1871        })?;
1872        Ok(read
1873            .units
1874            .into_iter()
1875            .next()
1876            .expect("one requested catch-up"))
1877    }
1878
1879    /// One client commit's delivery status: pending, its retained outcome, or
1880    /// an explicit unknown (never held, or pruned by retention).
1881    pub fn commit_delivery(&mut self, id: &str) -> Result<CommitDelivery, QueryReadFailure> {
1882        let read = self.snapshot_read(&SnapshotReadRequest {
1883            commit_ids: vec![id.to_owned()],
1884            ..Default::default()
1885        })?;
1886        Ok(read
1887            .deliveries
1888            .into_iter()
1889            .next()
1890            .expect("one requested delivery"))
1891    }
1892
1893    /// Hosts report an owned failure, and the first success after it, to the
1894    /// owning core through [`SyncClient::record_query_read`] (§7.6).
1895    pub fn query_snapshot(
1896        &mut self,
1897        sql: &str,
1898        params: &[Value],
1899        coverage: &[WindowCoverage],
1900    ) -> Result<QuerySnapshot, QueryReadFailure> {
1901        snapshot_connection(self.connection()?, None, sql, params, coverage)
1902    }
1903}
1904
1905/// `client.authority_read_forbidden` with static text; `details` carries the
1906/// query, the reason and, where one applies, the table and column (§5.11).
1907fn authority_forbidden(details: Option<Value>) -> ClientError {
1908    ClientError {
1909        code: "client.authority_read_forbidden".to_owned(),
1910        message: "authority read denied".to_owned(),
1911        details,
1912        retryable: false,
1913    }
1914}
1915
1916/// `sync.local_corrupt` for missing or invalid authority read evidence.
1917fn authority_corrupt() -> ClientError {
1918    ClientError {
1919        code: "sync.local_corrupt".to_owned(),
1920        message: "authority revision or base evidence is missing or invalid".to_owned(),
1921        details: None,
1922        retryable: false,
1923    }
1924}
1925
1926/// A storage failure of an authority read: a value that does not convert is
1927/// corrupt evidence; every other failure keeps its storage classification.
1928fn authority_stored(error: rusqlite::Error) -> ClientError {
1929    match error {
1930        rusqlite::Error::Utf8Error(..)
1931        | rusqlite::Error::InvalidColumnType(..)
1932        | rusqlite::Error::FromSqlConversionFailure(..)
1933        | rusqlite::Error::IntegralValueOutOfRange(..) => authority_corrupt(),
1934        other => ClientError::from(QueryReadFailure::from(other)),
1935    }
1936}
1937
1938fn authority_refusal(
1939    query: &str,
1940    reason: &str,
1941    table: Option<&str>,
1942    column: Option<&str>,
1943) -> ClientError {
1944    let mut details = json!({ "query": query, "reason": reason });
1945    if let Some(table) = table {
1946        details["table"] = Value::from(table);
1947    }
1948    if let Some(column) = column {
1949        details["column"] = Value::from(column);
1950    }
1951    authority_forbidden(Some(details))
1952}
1953
1954/// §5.11 creation check of every declared authority query against `schema`.
1955/// A refusal is `client.authority_read_forbidden` with the details
1956/// `{ query, reason, table?, column? }`.
1957pub fn validate_authority_reads(
1958    schema: &ClientSchema,
1959    queries: &[AuthorityQuery],
1960) -> Result<(), ClientError> {
1961    let mut names = BTreeSet::new();
1962    for query in queries {
1963        let refuse = |reason: &str, table: Option<&str>, column: Option<&str>| {
1964            authority_refusal(&query.name, reason, table, column)
1965        };
1966        let declared = |param: &String| query.params.iter().any(|held| &held.name == param);
1967        if !names.insert(query.name.as_str()) {
1968            return Err(refuse("shape", None, None));
1969        }
1970        if !query.params.iter().all(|param| {
1971            matches!(
1972                param.ty.as_str(),
1973                "string" | "integer" | "float" | "boolean" | "json"
1974            )
1975        }) {
1976            return Err(refuse("param", None, None));
1977        }
1978        let mut quoted = false;
1979        let holes = query
1980            .sql
1981            .chars()
1982            .filter(|c| {
1983                if *c == '\'' {
1984                    quoted = !quoted;
1985                }
1986                !quoted && *c == '?'
1987            })
1988            .count();
1989        if !query.bind.iter().all(declared) || holes != query.bind.len() {
1990            return Err(refuse("shape", None, None));
1991        }
1992        for entry in &query.coverage {
1993            let well_formed = schema.table(&entry.table).is_some_and(|table| {
1994                table.scope_column(&entry.variable).is_some()
1995                    && entry.fixed_scopes.iter().all(|(variable, param)| {
1996                        table.scope_column(variable).is_some() && declared(param)
1997                    })
1998                    && entry.units.iter().all(declared)
1999            });
2000            if !well_formed {
2001                return Err(refuse("shape", Some(entry.table.as_str()), None));
2002            }
2003        }
2004        for (name, columns) in &query.reads {
2005            let table = schema
2006                .table(name)
2007                .filter(|_| !name.starts_with("_syncular_"))
2008                .ok_or_else(|| refuse("column", Some(name.as_str()), None))?;
2009            for column in columns {
2010                if column == "_sync_version" {
2011                    continue;
2012                }
2013                let plain = !column.starts_with("_sync")
2014                    && table.columns.iter().enumerate().any(|(index, held)| {
2015                        &held.name == column
2016                            && !table.encrypted_columns.iter().any(|e| e.index == index)
2017                            && matches!(
2018                                held.ty,
2019                                ColumnType::String
2020                                    | ColumnType::Integer
2021                                    | ColumnType::Float
2022                                    | ColumnType::Boolean
2023                                    | ColumnType::Json
2024                            )
2025                    });
2026                if !plain {
2027                    return Err(refuse("column", Some(name.as_str()), Some(column.as_str())));
2028                }
2029            }
2030        }
2031    }
2032    Ok(())
2033}
2034
2035/// §5.11 native ceiling: prepare the authored statement of `query` on `conn`
2036/// under the SQLite authorizer and return its read set, table to columns. An
2037/// empty column is a read of the table without a column (`count(*)`). Any
2038/// action other than SELECT, READ, or a deterministic core function refuses
2039/// with reason `ceiling`; a statement that does not prepare refuses with
2040/// reason `shape`. The authorizer sees the authored statement only, never
2041/// the accepted-base shadows `authority_read` adds.
2042pub fn authority_read_set(
2043    conn: &mut Connection,
2044    query: &AuthorityQuery,
2045) -> Result<BTreeMap<String, BTreeSet<String>>, ClientError> {
2046    const DETERMINISTIC: &[&str] = &[
2047        "abs",
2048        "avg",
2049        "char",
2050        "coalesce",
2051        "concat",
2052        "concat_ws",
2053        "count",
2054        "format",
2055        "glob",
2056        "group_concat",
2057        "hex",
2058        "if",
2059        "ifnull",
2060        "iif",
2061        "instr",
2062        "json",
2063        "json_array",
2064        "json_array_length",
2065        "json_extract",
2066        "json_group_array",
2067        "json_group_object",
2068        "json_object",
2069        "json_quote",
2070        "json_type",
2071        "json_valid",
2072        "length",
2073        "like",
2074        "likelihood",
2075        "likely",
2076        "lower",
2077        "ltrim",
2078        "max",
2079        "min",
2080        "nullif",
2081        "octet_length",
2082        "printf",
2083        "quote",
2084        "replace",
2085        "round",
2086        "rtrim",
2087        "sign",
2088        "string_agg",
2089        "substr",
2090        "substring",
2091        "sum",
2092        "total",
2093        "trim",
2094        "typeof",
2095        "unhex",
2096        "unicode",
2097        "unlikely",
2098        "upper",
2099        "->",
2100        "->>",
2101    ];
2102    let reads = Arc::new(std::sync::Mutex::new(
2103        BTreeMap::<String, BTreeSet<String>>::new(),
2104    ));
2105    let refused = Arc::new(std::sync::atomic::AtomicBool::new(false));
2106    let (seen, denied) = (Arc::clone(&reads), Arc::clone(&refused));
2107    let sqlite = |error: rusqlite::Error| ClientError::from(QueryReadFailure::from(error));
2108    conn.authorizer(Some(
2109        move |context: rusqlite::hooks::AuthContext<'_>| match context.action {
2110            rusqlite::hooks::AuthAction::Select => rusqlite::hooks::Authorization::Allow,
2111            rusqlite::hooks::AuthAction::Read {
2112                table_name,
2113                column_name,
2114            } => {
2115                // The Rust mirror stores the public `_sync_version` as
2116                // `_syncular_version` (query_guard lowers it).
2117                let column = if column_name == "_syncular_version" {
2118                    "_sync_version"
2119                } else {
2120                    column_name
2121                };
2122                seen.lock()
2123                    .expect("authority read set lock")
2124                    .entry(table_name.to_owned())
2125                    .or_default()
2126                    .insert(column.to_owned());
2127                rusqlite::hooks::Authorization::Allow
2128            }
2129            rusqlite::hooks::AuthAction::Function { function_name }
2130                if DETERMINISTIC
2131                    .iter()
2132                    .any(|name| name.eq_ignore_ascii_case(function_name)) =>
2133            {
2134                rusqlite::hooks::Authorization::Allow
2135            }
2136            _ => {
2137                denied.store(true, std::sync::atomic::Ordering::Relaxed);
2138                rusqlite::hooks::Authorization::Deny
2139            }
2140        },
2141    ))
2142    .map_err(sqlite)?;
2143    let prepared = crate::query_guard::prepare_read_only(
2144        conn,
2145        &crate::query_guard::lower_public_query_sql(&query.sql),
2146    )
2147    .map(drop);
2148    conn.authorizer(None::<fn(rusqlite::hooks::AuthContext<'_>) -> rusqlite::hooks::Authorization>)
2149        .map_err(sqlite)?;
2150    if refused.load(std::sync::atomic::Ordering::Relaxed) {
2151        return Err(authority_refusal(&query.name, "ceiling", None, None));
2152    }
2153    if prepared.is_err() {
2154        return Err(authority_refusal(&query.name, "shape", None, None));
2155    }
2156    let mut set = reads.lock().expect("authority read set lock");
2157    Ok(std::mem::take(&mut *set))
2158}
2159
2160// §7.4.2: every open and recreation checks before any persistent writes.
2161/// A marker read that hit a recognized SQLite storage failure keeps that
2162/// classification (BUSY/LOCKED stay retryable); only an unclassified read
2163/// failure is the invalid-marker `sync.local_corrupt`.
2164fn schema_marker_read_failure(error: rusqlite::Error) -> String {
2165    let failure = QueryReadFailure::from(error);
2166    if failure.code.is_some() {
2167        failure.to_string()
2168    } else {
2169        "sync.local_corrupt: persisted local schema marker is unreadable or invalid".to_owned()
2170    }
2171}
2172
2173/// §7.1: reject an invalid configured client limit before any storage is
2174/// opened or written. Zero would wedge the push queue and an out-of-range
2175/// value would differ per target; the TS core enforces the same bounds.
2176fn validate_client_limits(limits: &crate::api::ClientLimits) -> Result<(), String> {
2177    if limits.outcome_retention_max_entries == Some(0) {
2178        return Err("sync.invalid_request: outcomeRetentionMaxEntries must be positive".to_owned());
2179    }
2180    if [
2181        limits.max_push_commits_per_request,
2182        limits.max_push_operations_per_request,
2183        limits.max_push_request_bytes,
2184    ]
2185    .into_iter()
2186    .flatten()
2187    .any(|value| value == 0 || value > u32::MAX as usize)
2188    {
2189        return Err(
2190            "sync.invalid_request: push limit must be an integer in 1..=4294967295".to_owned(),
2191        );
2192    }
2193    Ok(())
2194}
2195
2196fn read_local_schema_version(
2197    conn: &Connection,
2198    requested: i32,
2199) -> Result<Option<i32>, ClientError> {
2200    let corrupt =
2201        || "sync.local_corrupt: persisted local schema marker is unreadable or invalid".to_owned();
2202    let table_type: Option<String> = conn
2203        .query_row(
2204            "SELECT type FROM sqlite_master WHERE name = '_syncular_meta'",
2205            [],
2206            |row| row.get(0),
2207        )
2208        .optional()
2209        .map_err(schema_marker_read_failure)?;
2210    let Some(table_type) = table_type else {
2211        return Ok(None);
2212    };
2213    if table_type != "table" {
2214        return Err(corrupt().into());
2215    }
2216    // §7.4.2: a duplicated marker cannot be resolved. `query_row` would take
2217    // whichever row SQLite returns first, and an older one would drive a
2218    // destructive reset over a newer replica.
2219    let mut statement = conn
2220        .prepare("SELECT value FROM _syncular_meta WHERE key = ?1")
2221        .map_err(schema_marker_read_failure)?;
2222    let mut rows = statement
2223        .query([LOCAL_SCHEMA_VERSION_KEY])
2224        .map_err(schema_marker_read_failure)?;
2225    let value: Option<String> = rows
2226        .next()
2227        .map_err(schema_marker_read_failure)?
2228        .map(|row| row.get(0))
2229        .transpose()
2230        .map_err(schema_marker_read_failure)?;
2231    if rows.next().map_err(schema_marker_read_failure)?.is_some() {
2232        return Err(corrupt().into());
2233    }
2234    let Some(value) = value else {
2235        let has_descriptor = conn
2236            .query_row(
2237                "SELECT 1 FROM _syncular_meta WHERE key = ?1 LIMIT 1",
2238                [crate::previous_version::LOCAL_SCHEMA_DESCRIPTOR_KEY],
2239                |_| Ok(()),
2240            )
2241            .optional()
2242            .map_err(schema_marker_read_failure)?
2243            .is_some();
2244        if has_descriptor {
2245            return Err(corrupt().into());
2246        }
2247        return Ok(None);
2248    };
2249    if !matches!(value.as_bytes().first(), Some(b'1'..=b'9'))
2250        || !value.bytes().all(|b| b.is_ascii_digit())
2251    {
2252        return Err(corrupt().into());
2253    }
2254    let version = value.parse::<i32>().map_err(|_| corrupt())?;
2255    if version > requested {
2256        return Err(ClientError {
2257            code: "client.schema_downgrade".to_owned(),
2258            message: "persisted local schema is newer than the requested schema".to_owned(),
2259            details: Some(json!({ "persistedVersion": version, "requestedVersion": requested })),
2260            retryable: false,
2261        });
2262    }
2263    Ok(Some(version))
2264}
2265
2266/// The open and recreate constructors' error: a converted core error keeps
2267/// `retryable` for `client.storage_busy` exactly as the String boundary did.
2268fn open_failure(mut error: ClientError) -> ClientError {
2269    error.retryable = error.code == "client.storage_busy";
2270    error
2271}
2272
2273/// Open a replica file. On a browser worker the file must recover a hot
2274/// journal before any statement reads it: `wasm_vfs` replaces the installed
2275/// OPFS VFS's reserved lock callback before the connection opens its file. A
2276/// new browser replica uses 64 KiB pages (§5.3), because every OPFS call costs
2277/// the same whatever its size; a database with tables keeps its page size. Its
2278/// page cache holds 64 MiB, because SQLite's 2,000 KiB default is 31 such pages
2279/// and every cache miss is an OPFS call.
2280fn open_replica(path: &str) -> Result<Connection, String> {
2281    let browser = cfg!(all(target_arch = "wasm32", target_os = "unknown"))
2282        && !path.is_empty()
2283        && path != ":memory:";
2284    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
2285    if browser {
2286        crate::wasm_vfs::disable_foreign_lock_check()?;
2287    }
2288    let conn = Connection::open(path).map_err(|e| format!("open db {path:?}: {e}"))?;
2289    if browser {
2290        conn.execute_batch("PRAGMA page_size = 65536; PRAGMA cache_size = -65536")
2291            .map_err(|e| format!("open db {path:?}: {e}"))?;
2292    }
2293    Ok(conn)
2294}
2295
2296impl SyncClient {
2297    pub fn new_with_identity(
2298        client_id: Option<String>,
2299        schema_json: &Value,
2300        limits: ClientLimits,
2301    ) -> Result<Self, String> {
2302        let resolved = client_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
2303        let conn = Connection::open_in_memory().map_err(|e| e.to_string())?;
2304        Self::with_connection(resolved, schema_json, limits, conn)
2305    }
2306
2307    pub fn new(
2308        client_id: String,
2309        schema_json: &Value,
2310        limits: ClientLimits,
2311    ) -> Result<Self, String> {
2312        let conn = Connection::open_in_memory().map_err(|e| e.to_string())?;
2313        Self::with_connection(client_id, schema_json, limits, conn)
2314    }
2315
2316    /// Build a client backed by an on-disk SQLite database at `path` — the
2317    /// seam a native host (Tauri plugin, FFI file-DB variant) uses to persist
2318    /// across process restarts. `create_tables` runs `IF NOT EXISTS`, so
2319    /// re-opening the same file reuses the persisted rows. Keeps rusqlite out
2320    /// of the command router's dependency set (the router only holds a path).
2321    pub fn open_path(
2322        client_id: String,
2323        schema_json: &Value,
2324        limits: ClientLimits,
2325        path: &str,
2326    ) -> Result<Self, ClientError> {
2327        (|| {
2328            validate_client_limits(&limits)?;
2329            parse_schema_json(schema_json)?;
2330            let conn = open_replica(path)?;
2331            Self::with_connection_identity(Some(client_id), schema_json, limits, conn)
2332        })()
2333        .map_err(open_failure)
2334    }
2335
2336    /// Open a file replica and resolve its client id. Native targets require
2337    /// WAL for the independent snapshot reader; `wasm32-unknown-unknown`
2338    /// accepts the sqlite-wasm worker journal instead. `":memory:"` and `""`
2339    /// name no file: they open an in-memory replica, which has no WAL and no
2340    /// snapshot reader.
2341    pub fn open_path_with_identity(
2342        client_id: Option<String>,
2343        schema_json: &Value,
2344        limits: ClientLimits,
2345        path: &str,
2346    ) -> Result<Self, ClientError> {
2347        Self::open_path_with_identity_journal(
2348            client_id,
2349            schema_json,
2350            limits,
2351            path,
2352            !cfg!(all(target_arch = "wasm32", target_os = "unknown"))
2353                && !path.is_empty()
2354                && path != ":memory:",
2355        )
2356        .map_err(open_failure)
2357    }
2358
2359    fn open_path_with_identity_journal(
2360        client_id: Option<String>,
2361        schema_json: &Value,
2362        limits: ClientLimits,
2363        path: &str,
2364        require_wal: bool,
2365    ) -> Result<Self, ClientError> {
2366        validate_client_limits(&limits)?;
2367        // §7.4.2: an invalid requested version is refused before the replica is
2368        // even created, so a rejected constructor leaves no file behind.
2369        parse_schema_json(schema_json)?;
2370        let conn = open_replica(path)?;
2371        // A file-backed native client uses an independent read connection for
2372        // latency-critical snapshots. WAL is SQLite's intended reader/writer
2373        // concurrency mode: a view read never holds a rollback-journal lock
2374        // that delays the client's next commit. The busy timeout must precede
2375        // this replica's own startup transaction; WAL is applied only after
2376        // startup succeeded, because a refused open must leave the replica's
2377        // journal mode and contents untouched (§7.4.2).
2378        conn.busy_timeout(std::time::Duration::from_millis(250))
2379            .map_err(|error| format!("configure db {path:?} busy timeout: {error}"))?;
2380        // Durability is the caller's contract here, not the VFS default: a
2381        // rollback-journal commit needs FULL before it writes the database
2382        // pages, or a killed worker can leave a half-written image behind.
2383        // WAL below inherits the same setting.
2384        conn.pragma_update(None, "synchronous", "FULL")
2385            .map_err(|error| format!("configure db {path:?} synchronous: {error}"))?;
2386        let client = Self::with_connection_identity(client_id, schema_json, limits, conn)?;
2387        // A browser worker's sqlite-wasm VFS has no WAL mode, and the wasm
2388        // host has no independent snapshot reader. The WAL requirement exists
2389        // for native file replicas, where it is the reader/writer boundary.
2390        if require_wal {
2391            let journal_mode: String = client
2392                .conn
2393                .pragma_update_and_check(None, "journal_mode", "WAL", |row| row.get(0))
2394                .map_err(|error| Self::sqlite_failure(&client.storage_failure, error))?;
2395            if journal_mode != "wal" {
2396                return Err(
2397                    "sync.invalid_request: file-backed client requires WAL journal mode"
2398                        .to_owned()
2399                        .into(),
2400                );
2401            }
2402        }
2403        Ok(client)
2404    }
2405
2406    /// Delete a file replica at `path`, including its `-journal`, `-wal`, and
2407    /// `-shm` sidecars, through the VFS that owns it. Use this after
2408    /// `client.storage_corrupt`: an OPFS SAH pool stores those files under
2409    /// opaque names, so deleting the pool directory behind SQLite bypasses the
2410    /// pool's slot accounting.
2411    ///
2412    /// Close the client and every [`FileQuerySnapshotReader`] on `path` first;
2413    /// a VFS cannot delete a file another handle still owns. A file that does
2414    /// not exist counts as deleted, so a cleanly closed replica without
2415    /// sidecars resets. The next open
2416    /// creates a fresh replica (new client id) and re-bootstraps from the
2417    /// server. A memory replica has nothing to delete and fails with
2418    /// `sync.invalid_request`.
2419    pub fn reset_replica(path: &str) -> Result<(), String> {
2420        if path.is_empty() || path == ":memory:" {
2421            return Err("sync.invalid_request: a memory replica has nothing to reset".to_owned());
2422        }
2423        // SAFETY: a null VFS name asks SQLite for its process-wide default VFS,
2424        // the same one `Connection::open(path)` above selects. `xDelete` is
2425        // that VFS's own function pointer, and `c_name` outlives the call.
2426        let vfs = unsafe { rusqlite::ffi::sqlite3_vfs_find(std::ptr::null()) };
2427        if vfs.is_null() {
2428            return Err("client.storage_io: no SQLite VFS is registered".to_owned());
2429        }
2430        let delete = unsafe { (*vfs).xDelete }
2431            .ok_or_else(|| "client.storage_io: the SQLite VFS cannot delete files".to_owned())?;
2432        for suffix in ["-wal", "-shm", "-journal", ""] {
2433            let file_name = format!("{path}{suffix}");
2434            let c_name = std::ffi::CString::new(file_name.as_str()).map_err(|_| {
2435                format!("sync.invalid_request: replica path {file_name:?} contains a NUL byte")
2436            })?;
2437            // SAFETY: `vfs` and its `xDelete` pointer come from the live
2438            // SQLite library; `c_name` is a valid NUL-terminated path.
2439            let code = unsafe { delete(vfs, c_name.as_ptr(), 1) };
2440            // A cleanly closed WAL replica has no sidecars; a missing file is
2441            // already deleted.
2442            if code != rusqlite::ffi::SQLITE_OK && code != rusqlite::ffi::SQLITE_IOERR_DELETE_NOENT
2443            {
2444                return Err(format!(
2445                    "client.storage_io: deleting replica file {file_name:?} failed with SQLite code {code}"
2446                ));
2447            }
2448        }
2449        Ok(())
2450    }
2451
2452    #[must_use]
2453    pub fn client_id(&self) -> &str {
2454        &self.client_id
2455    }
2456
2457    /// Rotate the caller's client id (§1.5) and return the new one. Use it
2458    /// after a `sync.invalid_client_id` refusal (`recommendedAction:
2459    /// resetClientId`): the next round carries the new id. A live realtime
2460    /// socket is closed so the next connection registers with the new id.
2461    /// The replica and its outbox stay in place; wipe them yourself when the
2462    /// stored data belongs to the account that signed out.
2463    pub fn reset_client_id(&mut self, transport: &mut dyn Transport) -> Result<String, String> {
2464        self.disconnect_realtime(transport);
2465        let client_id = uuid::Uuid::new_v4().to_string();
2466        self.set_meta(CLIENT_ID_KEY, &client_id)?;
2467        self.client_id.clone_from(&client_id);
2468        self.round_failure = None;
2469        Ok(client_id)
2470    }
2471
2472    /// Build a client over a caller-supplied rusqlite connection — the seam a
2473    /// native host (Tauri plugin, FFI file-DB variant) uses to back the core
2474    /// with an on-disk database (`Connection::open(path)`) rather than the
2475    /// default `:memory:`. The connection MUST be fresh (no pre-existing
2476    /// syncular tables); `create_tables` runs `IF NOT EXISTS`, so re-opening
2477    /// the same file across process restarts reuses the persisted rows.
2478    pub fn with_connection(
2479        client_id: String,
2480        schema_json: &Value,
2481        limits: ClientLimits,
2482        conn: Connection,
2483    ) -> Result<Self, String> {
2484        Self::with_connection_identity(Some(client_id), schema_json, limits, conn).map_err(
2485            |error| match error.details.as_ref().and_then(|d| d.get("legacyCause")) {
2486                Some(Value::String(cause)) => cause.clone(),
2487                _ => error.to_string(),
2488            },
2489        )
2490    }
2491
2492    /// [`Self::with_connection`] for `open_path_with_identity`: no requested id
2493    /// means a durable replica's persisted `clientId` wins over a fresh one.
2494    fn with_connection_identity(
2495        client_id: Option<String>,
2496        schema_json: &Value,
2497        limits: ClientLimits,
2498        conn: Connection,
2499    ) -> Result<Self, ClientError> {
2500        validate_client_limits(&limits)?;
2501        let schema = parse_schema_json(schema_json)?;
2502        validate_authority_reads(&schema, &limits.authority_reads)
2503            .map_err(|error| error.to_string())?;
2504        // RFC 0005 D8: resolve the previous-version config before the opening
2505        // reset runs — the capture happens inside it. Bad bounds fail loud.
2506        let previous_version = match limits.previous_version_context {
2507            Some(config) => {
2508                config.validate()?;
2509                Some(config)
2510            }
2511            None => None,
2512        };
2513        let mut client = SyncClient {
2514            #[cfg(feature = "bench-internals")]
2515            benchmark_phases: Recorder::default(),
2516            conn,
2517            schema,
2518            client_id: client_id
2519                .clone()
2520                .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()),
2521            limits,
2522            outbox: Shared::default(),
2523            failed_commits: Shared::default(),
2524            retain_failed_commits: false,
2525            conflicts: Shared::default(),
2526            rejections: Shared::default(),
2527            schema_floor: None,
2528            lease_state: None,
2529            stopped: false,
2530            upgrading: false,
2531            upgrade_kept_tables: false,
2532            sync_needed: false,
2533            realtime_policy: RealtimePolicy::Optional,
2534            realtime_state: RealtimeState::Disconnected,
2535            realtime_reason_code: None,
2536            realtime_retry_delay_ms: None,
2537            presence: HashMap::new(),
2538            now_ms: None,
2539            encryption: crate::values::EncryptionConfig::default(),
2540            security_preflight: false,
2541            security_epoch: 0,
2542            transport_gate: crate::TransportGate::Open,
2543            transport_epoch: 0,
2544            registration_epoch: 0,
2545            previous_version,
2546            insert_sql: RefCell::new(HashMap::new()),
2547            overlay_dirty: OverlayDirty::clean(),
2548            storage_failure: RefCell::new(None),
2549            #[cfg(test)]
2550            overlay_rebuild_count: Cell::new(0),
2551            #[cfg(test)]
2552            acknowledged_replay_count: Cell::new(0),
2553            #[cfg(test)]
2554            outcome_prune_count: Cell::new(0),
2555            #[cfg(test)]
2556            image_chunk_ms: Cell::new(None),
2557            progress: ProgressObserver::default(),
2558            epoch: uuid::Uuid::new_v4().to_string(),
2559            change_queue: VecDeque::new(),
2560            projection_pending_queue: VecDeque::new(),
2561            opening_replica: true,
2562            sync_intent_queue: VecDeque::new(),
2563            scopes_changed: 0,
2564            window_armed: HashSet::new(),
2565            retry_delay_ms: 250,
2566            round_retry_delay_ms: None,
2567            image_chunk_rows: HashMap::new(),
2568            round_failure: None,
2569            active_round: None,
2570            fence_round: None,
2571            last_round: None,
2572            last_change: None,
2573            query_failures: Vec::new(),
2574            coalesced: None,
2575            coalesced_failure: None,
2576        };
2577        // The row write path leans on the prepared-statement cache (two
2578        // insert statements per synced table, plus the bookkeeping
2579        // statements); size it so a multi-table schema never thrashes.
2580        client
2581            .conn
2582            .set_prepared_statement_cache_capacity(64.max(client.schema.tables.len() * 4));
2583        // §7.4.2: one write transaction (SQLite `BEGIN IMMEDIATE`, a reserved
2584        // writer) covers the marker read, the identity check, and every
2585        // bookkeeping/schema write, so a concurrent open that upgraded the
2586        // replica cannot interleave between the guard and the writes, and a
2587        // refusal leaves the replica unchanged.
2588        client
2589            .conn
2590            .execute_batch("BEGIN IMMEDIATE")
2591            .map_err(|error| Self::sqlite_failure(&client.storage_failure, error))?;
2592        let startup = (|| -> Result<(), ClientError> {
2593            // The marker guard runs inside the write transaction, so the version
2594            // it validates is the version every write below commits under.
2595            let marker = read_local_schema_version(&client.conn, client.schema.version)?;
2596            // New app indexes may reference columns that only exist after a
2597            // version-bump reset.
2598            client.create_bookkeeping_tables()?;
2599            match client.get_meta(CLIENT_ID_KEY)? {
2600                Some(existing) => match client_id {
2601                    Some(requested) if existing != requested => {
2602                        return Err(format!(
2603                            "client.identity_mismatch: this database belongs to {existing:?}; refusing to rebind it to {requested:?}"
2604                        )
2605                        .into())
2606                    }
2607                    _ => client.client_id = existing,
2608                },
2609                None => client.set_meta(CLIENT_ID_KEY, &client.client_id)?,
2610            }
2611            client.restore_persisted_state()?;
2612            client.failed_commits = client.load_failed_commits()?.into();
2613            match marker {
2614                None => {
2615                    client.detach_projections(None)?;
2616                    client.create_synced_tables()?;
2617                    client.persist_schema_version()?;
2618                    client.save_unit_scope_schema()?;
2619                }
2620                Some(version) if version == client.schema.version => {
2621                    client.detach_projections(None)?;
2622                    client.create_synced_tables()?;
2623                    // RFC 0005 D1: the same-version open backfills the descriptor
2624                    // for a database first opened by an unaware binary, so the
2625                    // NEXT bump can capture without needing a schema bump first.
2626                    set_local_schema_descriptor(&client.conn, &client.schema)
2627                        .map_err(|error| Self::sqlite_failure(&client.storage_failure, error))?;
2628                    client.save_unit_scope_schema()?;
2629                }
2630                Some(_) => client.run_schema_reset()?,
2631            }
2632            // RFC 0005 D9: the reset sweep cannot see a container whose capture
2633            // committed in its OWN file while the replica's savepoint never
2634            // released — a crash at that seam leaves a container beside a matching
2635            // OLD marker, and the next open at that version runs no reset. Discard
2636            // it before anything can read it. No-op when no container exists.
2637            client.reconcile_previous_version_at_boot()?;
2638            client.clear_satisfied_persisted_schema_floor()?;
2639            client.prune_unknown_units(false)?;
2640            // §7.1/§7.4.4: recover intrinsically codec-invalid persisted values at
2641            // the full startup/reset reconciliation boundary, inside this open
2642            // transaction and after the schema and identity guards, so a commit
2643            // an earlier version accepted is dropped with durable rejection
2644            // evidence before any replay. A table the current schema removed
2645            // keeps the §7.4.4 send-time classification, and an unresolved
2646            // encryption key stays with the send seam because hosts configure
2647            // keys after open.
2648            client.drop_unencodable_outbox(false, None)?;
2649            if marker == Some(client.schema.version)
2650                && (!client.outbox.is_empty()
2651                    || !client.failed_commits.is_empty()
2652                    || client.has_acknowledged_rows()?)
2653            {
2654                // Reconstruct the visible optimistic overlay from the durable
2655                // base plus outbox instead of trusting a process-interrupted
2656                // mirror.
2657                client.overlay_dirty.set(true);
2658                client.rebuild_overlay()?;
2659            }
2660            // Every persisted active unit needs one catch-up pull on
2661            // open: realtime only covers changes after connection, while an
2662            // idempotent setWindow correctly creates no fresh command effect.
2663            // Pending outbox work has the same restart requirement. The core
2664            // owns this intent so native hosts never poll or require an
2665            // application-issued sync().
2666            client.enqueue_startup_sync_if_needed()?;
2667            client
2668                .projection_pending_queue
2669                .extend(client.collect_projection_pending()?);
2670            Ok(())
2671        })();
2672        match startup {
2673            Ok(()) => match client.conn.execute_batch("COMMIT") {
2674                // §4.8: an eviction a crash interrupted finishes before any
2675                // read, with or without a transport; a replica reopened in
2676                // preflight finishes it at activation.
2677                Ok(()) => {
2678                    client.opening_replica = false;
2679                    // §5.11: a purge before 0.105.5 left its words in the
2680                    // full-text index; the first open of a replica that
2681                    // applied one erases it before any read. The record
2682                    // follows the erasure, so an interrupted repair runs
2683                    // again at the next open.
2684                    let purged = client.stored(
2685                        client
2686                            .conn
2687                            .query_row(
2688                                "SELECT 1 FROM _syncular_meta WHERE key LIKE 'localPurge:%' LIMIT 1",
2689                                [],
2690                                |_| Ok(()),
2691                            )
2692                            .optional(),
2693                    )?;
2694                    let repaired = format!("{PURGE_REPAIR_KEY}:erased");
2695                    if purged.is_some() {
2696                        client.erase_purged_pages(PURGE_REPAIR_KEY)?;
2697                    } else if client.get_meta(&repaired)?.is_none() {
2698                        client.set_meta(&repaired, "1")?;
2699                    }
2700                    // §7.3.4: a purge before 0.105.13 left the units over its
2701                    // rows at their cursors. The rows are gone, so once, every
2702                    // unit that covers a recorded target's table catches up
2703                    // from -1, unless a selector on a scope column names none
2704                    // of the unit's effective values.
2705                    let refill = format!("{PURGE_REPAIR_KEY}:refill");
2706                    if client.get_meta(&refill)?.is_none() {
2707                        let rows = client.stored(
2708                            client
2709                                .conn
2710                                .prepare(
2711                                    "SELECT m.key||' '||t.key, json_extract(t.value,'$.table'), s.key, v.value FROM _syncular_meta m, json_each(m.value) t, json_each(t.value,'$.selectors') s, json_each(s.value) v WHERE m.key LIKE 'localPurge:%' AND json_valid(m.value) AND json_type(m.value)='array' AND json_type(t.value)='object'",
2712                                )
2713                                .and_then(|mut statement| {
2714                                    statement
2715                                        .query_map([], |row| {
2716                                            Ok((
2717                                                row.get::<_, String>(0)?,
2718                                                row.get::<_, String>(1)?,
2719                                                row.get::<_, String>(2)?,
2720                                                row.get::<_, String>(3)?,
2721                                            ))
2722                                        })?
2723                                        .collect::<rusqlite::Result<Vec<_>>>()
2724                                }),
2725                        )?;
2726                        let mut targets: BTreeMap<String, (String, BTreeMap<String, Vec<String>>)> =
2727                            BTreeMap::new();
2728                        for (target, table, column, value) in rows {
2729                            targets
2730                                .entry(target)
2731                                .or_insert_with(|| (table, BTreeMap::new()))
2732                                .1
2733                                .entry(column)
2734                                .or_default()
2735                                .push(value);
2736                        }
2737                        for unit in client.stored(load_units(&client.conn))? {
2738                            if unit.status == UnitStatus::Active
2739                                && (unit.cursor != Some(-1) || unit.bootstrap_state.is_some())
2740                                && targets.values().any(|(name, selectors)| {
2741                                    let Some(table) = client.schema.table(name) else {
2742                                        return false;
2743                                    };
2744                                    let Some(effective) = covers(table, &unit.scopes)
2745                                        .then(|| {
2746                                            pair_scopes(&unit.scopes, name, unit.echo.as_deref())
2747                                        })
2748                                        .flatten()
2749                                    else {
2750                                        return false;
2751                                    };
2752                                    table.scope_variables.iter().all(|scope| {
2753                                        let held = effective
2754                                            .iter()
2755                                            .find(|(variable, _)| *variable == scope.variable);
2756                                        match (selectors.get(&scope.column), held) {
2757                                            (Some(values), Some((_, held))) => {
2758                                                held.iter().any(|value| {
2759                                                    value == "*" || values.contains(value)
2760                                                })
2761                                            }
2762                                            _ => true,
2763                                        }
2764                                    })
2765                                })
2766                            {
2767                                client.stored(save_unit(
2768                                    &client.conn,
2769                                    &UnitRecord {
2770                                        cursor: Some(-1),
2771                                        bootstrap_state: None,
2772                                        seeded: Vec::new(),
2773                                        restriction: None,
2774                                        ..unit
2775                                    },
2776                                ))?;
2777                            }
2778                        }
2779                        client.set_meta(&refill, "1")?;
2780                    }
2781                    if !client.security_preflight {
2782                        client.drain_pending_evictions()?;
2783                    }
2784                    Ok(client)
2785                }
2786                Err(error) => {
2787                    let failure = Self::sqlite_failure(&client.storage_failure, error);
2788                    if let Err(rollback) = client.conn.execute_batch("ROLLBACK") {
2789                        // Keep a failed rollback's typed storage classification.
2790                        let _ = Self::sqlite_failure(&client.storage_failure, rollback);
2791                    }
2792                    Err(failure.into())
2793                }
2794            },
2795            Err(error) => {
2796                if let Err(rollback) = client.conn.execute_batch("ROLLBACK") {
2797                    // Keep a failed rollback's typed storage classification.
2798                    let _ = Self::sqlite_failure(&client.storage_failure, rollback);
2799                }
2800                Err(error)
2801            }
2802        }
2803    }
2804
2805    /// Pin the client clock (epoch ms) — the §5.4 expiry check runs
2806    /// against this instead of system time (conformance virtual clock).
2807    pub fn set_now_ms(&mut self, now_ms: i64) {
2808        self.now_ms = Some(std::sync::Arc::new(now_ms.into()));
2809    }
2810
2811    /// The pinned clock, shared: a host that stores into it moves the client
2812    /// clock while a call runs (a virtual clock that advances per request).
2813    pub fn pinned_clock(&self) -> Option<std::sync::Arc<std::sync::atomic::AtomicI64>> {
2814        self.now_ms.clone()
2815    }
2816
2817    /// §5.11: install the client-side encryption keys (`keyId → key bytes`).
2818    /// The command router parses these from the `create` command's
2819    /// `encryption` config (keys as `{$bytes: hex}`).
2820    pub fn set_encryption(&mut self, encryption: crate::values::EncryptionConfig) {
2821        self.encryption = encryption;
2822    }
2823
2824    #[must_use]
2825    pub fn security_lifecycle(&self) -> &'static str {
2826        if self.security_preflight {
2827            "preflight"
2828        } else {
2829            "active"
2830        }
2831    }
2832
2833    #[must_use]
2834    pub fn security_preflight(&self) -> bool {
2835        self.security_preflight
2836    }
2837
2838    /// Host-owned, non-persisted network gate (§8.8). Local operations remain
2839    /// available. `Through` names a pending commit; any other id fails with
2840    /// `sync.outcome_not_found` and leaves the gate unchanged.
2841    pub fn set_transport_gate(
2842        &mut self,
2843        transport: &mut dyn Transport,
2844        state: crate::TransportGate,
2845    ) -> Result<(), ClientError> {
2846        if let crate::TransportGate::Through(id) = &state {
2847            if !self
2848                .outbox
2849                .iter()
2850                .any(|commit| commit.client_commit_id == *id)
2851            {
2852                return Err(ClientError {
2853                    code: "sync.outcome_not_found".to_owned(),
2854                    message: "the commit is not pending".to_owned(),
2855                    details: Some(json!({ "clientCommitId": id })),
2856                    retryable: false,
2857                });
2858            }
2859        }
2860        let closed = state == crate::TransportGate::Closed;
2861        if self.transport_gate != state {
2862            self.sync_intent_queue.clear();
2863            self.move_transport_gate(state);
2864        }
2865        // A captured reply keeps its normal apply/revocation semantics.
2866        if closed && self.active_round.is_none() {
2867            self.disconnect_realtime(transport);
2868        }
2869        Ok(())
2870    }
2871
2872    /// §8.8: a gate change, set by the host or by a `through` fallback. A
2873    /// change batch that rolls back restores the gate and epoch it captured.
2874    fn move_transport_gate(&mut self, state: crate::TransportGate) {
2875        use crate::TransportGate::{Closed, Open, Through};
2876        let wake = state != Closed
2877            && (self.transport_gate == Closed || matches!(state, Open | Through(_)))
2878            && !self.security_preflight;
2879        self.transport_gate = state;
2880        self.transport_epoch = self.transport_epoch.wrapping_add(1);
2881        self.sync_intent_queue.push_back(if wake {
2882            SyncIntent::Interactive
2883        } else {
2884            SyncIntent::None
2885        });
2886    }
2887
2888    /// §8.8: how many outbox commits, from the front, a round may push.
2889    fn pushable_commits(&self) -> usize {
2890        match &self.transport_gate {
2891            crate::TransportGate::Open => self.outbox.len(),
2892            crate::TransportGate::Through(boundary) => self
2893                .outbox
2894                .iter()
2895                .position(|commit| commit.client_commit_id == *boundary)
2896                .map_or(0, |index| index + 1),
2897            crate::TransportGate::Closed | crate::TransportGate::Pull => 0,
2898        }
2899    }
2900
2901    /// §8.8 through fallback: a commit of the prefix leaves the outbox other
2902    /// than by its acknowledgement. Called before the in-memory removal.
2903    fn leave_through(&mut self, client_commit_id: &str) {
2904        if matches!(self.transport_gate, crate::TransportGate::Through(_))
2905            && self
2906                .outbox
2907                .iter()
2908                .take(self.pushable_commits())
2909                .any(|commit| commit.client_commit_id == client_commit_id)
2910        {
2911            self.move_transport_gate(crate::TransportGate::Pull);
2912        }
2913    }
2914
2915    pub fn transport_gate(&self) -> crate::TransportGate {
2916        self.transport_gate.clone()
2917    }
2918
2919    fn transport_closed(&self) -> bool {
2920        self.transport_gate == crate::TransportGate::Closed
2921    }
2922
2923    /// Quarantine this replica: enter the fail-closed gate, release all
2924    /// core-owned key material, and record the gate in the database so
2925    /// reopening re-enters preflight until `activate_security` clears it.
2926    ///
2927    /// Use [`SyncClient::seal_security_on_teardown`] for the shutdown barrier,
2928    /// which must NOT leave that durable mark.
2929    pub fn begin_security_preflight(&mut self) -> Result<(), String> {
2930        let entering = !self.security_preflight;
2931        self.seal_security_on_teardown();
2932        // Persist the quarantine so it survives handle teardown and restart:
2933        // reopening this replica re-enters preflight until activation clears it.
2934        self.set_meta(SECURITY_PREFLIGHT_PENDING_KEY, "1")?;
2935        if entering {
2936            self.emit_status_batch()?;
2937        }
2938        Ok(())
2939    }
2940
2941    /// One change batch carrying the status snapshot (§5.11 lifecycle).
2942    fn emit_status_batch(&mut self) -> Result<(), String> {
2943        self.begin_observation("syncular_status")?;
2944        let batch = ChangeAccumulator {
2945            status: true,
2946            ..ChangeAccumulator::default()
2947        };
2948        self.finish_observation("syncular_status", batch)
2949            .inspect_err(|_| self.rollback_observation("syncular_status"))
2950    }
2951
2952    /// Release core-owned key material as a host tears the client down,
2953    /// WITHOUT recording a quarantine.
2954    ///
2955    /// Shutting an activated client down is not a quarantine event. Persisting
2956    /// the gate here marks every cleanly closed replica as pending, and the
2957    /// next plain `create` is then refused permanently: the reopen path
2958    /// restores the flag from the marker and the create guard rejects it. The
2959    /// in-memory flag still closes the gate for anything still holding this
2960    /// instance, which is all a teardown barrier needs.
2961    pub fn seal_security_on_teardown(&mut self) {
2962        self.cancel_sync_round();
2963        self.security_preflight = true;
2964        self.security_epoch = self.security_epoch.wrapping_add(1);
2965        self.encryption = crate::values::EncryptionConfig::default();
2966        self.sync_intent_queue.clear();
2967    }
2968
2969    /// Install the post-authentication keyring and release the host loop.
2970    pub fn activate_security(
2971        &mut self,
2972        encryption: crate::values::EncryptionConfig,
2973    ) -> Result<(), String> {
2974        if !self.security_preflight {
2975            return Err(
2976                "sync.invalid_request: activateSecurity requires security preflight".to_owned(),
2977            );
2978        }
2979        // §4.8: an interrupted eviction finishes before protected reads open.
2980        self.drain_pending_evictions()?;
2981        self.enqueue_startup_sync_if_needed()?;
2982        self.delete_meta(SECURITY_PREFLIGHT_PENDING_KEY)?;
2983        self.encryption = encryption;
2984        self.security_preflight = false;
2985        // §5.11: rows sealed under a key this keyring now holds open at once.
2986        self.reveal_sealed_rows()
2987            .map_err(|error| format!("{}: {}", error.code, error.message))?;
2988        self.emit_status_batch()
2989    }
2990
2991    /// §5.11: extend the installed keyring while active. The whole input is
2992    /// validated in key-id order before anything changes, so a refusal names
2993    /// the first bad key id in that order; lifecycle, realtime, and the round
2994    /// are untouched, and rows sealed under the new keys reveal at once.
2995    pub fn add_encryption_keys(
2996        &mut self,
2997        mut keys: std::collections::BTreeMap<String, Vec<u8>>,
2998    ) -> Result<(), ClientError> {
2999        let refusal = if self.security_preflight {
3000            Some(ClientError {
3001                code: SECURITY_PREFLIGHT_REQUIRED_CODE.to_owned(),
3002                message: "the local replica is in security preflight; complete quarantine checks and call activateSecurity before accessing protected data".to_owned(),
3003                details: None,
3004                retryable: false,
3005            })
3006        } else {
3007            keys.iter().find_map(|(key_id, bytes)| {
3008                if bytes.len() != 32 {
3009                    Some(invalid_authoring(
3010                        "encryption key must be 32 bytes (AES-256)",
3011                        json!({ "keyId": key_id }),
3012                    ))
3013                } else if self
3014                    .encryption
3015                    .keys
3016                    .get(key_id)
3017                    .is_some_and(|held| held != bytes)
3018                {
3019                    Some(invalid_authoring(
3020                        "encryption key id is already held with different key bytes",
3021                        json!({ "keyId": key_id }),
3022                    ))
3023                } else {
3024                    None
3025                }
3026            })
3027        };
3028        // Native key hygiene: every buffer that is not installed is zeroed
3029        // before drop.
3030        if let Some(error) = refusal {
3031            for bytes in keys.values_mut() {
3032                bytes.fill(0);
3033            }
3034            return Err(error);
3035        }
3036        for (key_id, mut bytes) in keys {
3037            match self.encryption.keys.entry(key_id) {
3038                std::collections::hash_map::Entry::Occupied(_) => bytes.fill(0),
3039                std::collections::hash_map::Entry::Vacant(slot) => {
3040                    slot.insert(bytes);
3041                }
3042            }
3043        }
3044        self.reveal_sealed_rows().map_err(|error| ClientError {
3045            code: error.code,
3046            message: error.message,
3047            details: error.details,
3048            retryable: false,
3049        })
3050    }
3051
3052    fn clock_now_ms(&self) -> i64 {
3053        self.now_ms
3054            .as_ref()
3055            .map_or_else(crate::wall_clock_ms, |clock| {
3056                clock.load(std::sync::atomic::Ordering::Relaxed)
3057            })
3058    }
3059
3060    fn create_bookkeeping_tables(&self) -> Result<(), String> {
3061        let exists = |name: &str| {
3062            self.conn
3063                .query_row(
3064                    "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?1)",
3065                    [name],
3066                    |row| row.get::<_, bool>(0),
3067                )
3068                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
3069        };
3070        let outbox_existed = exists("_syncular_outbox")?;
3071        // Durable client bookkeeping (outbox + units + meta). §7.1: a commit
3072        // queued before the send-attempt marker existed counts as attempted.
3073        self.conn
3074            .execute_batch(
3075                "CREATE TABLE IF NOT EXISTS _syncular_outbox (
3076                   seq INTEGER PRIMARY KEY AUTOINCREMENT,
3077                   commit_id TEXT NOT NULL UNIQUE, ops_json TEXT NOT NULL,
3078                   created_at_ms INTEGER NOT NULL DEFAULT 0,
3079                   attempted INTEGER NOT NULL DEFAULT 1);
3080                 CREATE TABLE IF NOT EXISTS _syncular_row_deliveries (
3081                   tbl TEXT NOT NULL, id TEXT NOT NULL, commit_seq INTEGER NOT NULL, PRIMARY KEY(tbl,id));
3082                 CREATE TABLE IF NOT EXISTS _syncular_acked_rows (
3083                   commit_id TEXT NOT NULL, idx INTEGER NOT NULL, tbl TEXT NOT NULL, id TEXT NOT NULL,
3084                   commit_seq INTEGER NOT NULL, op_json TEXT NOT NULL, intent_json TEXT,
3085                   PRIMARY KEY(commit_id, idx));
3086                 CREATE INDEX IF NOT EXISTS _syncular_acked_rows_row
3087                   ON _syncular_acked_rows(tbl, id);
3088                 CREATE TABLE IF NOT EXISTS _syncular_failed_commits (
3089                   seq INTEGER PRIMARY KEY AUTOINCREMENT, client_commit_id TEXT NOT NULL UNIQUE,
3090                   operations_json TEXT NOT NULL, initial_json TEXT NOT NULL);
3091                 CREATE TABLE IF NOT EXISTS _syncular_commit_outcomes (
3092                   seq INTEGER PRIMARY KEY AUTOINCREMENT,
3093                   client_commit_id TEXT NOT NULL UNIQUE,
3094                   status TEXT NOT NULL CHECK(status IN ('applied', 'cached', 'conflict', 'rejected')),
3095                   recorded_at_ms INTEGER NOT NULL,
3096                   results_json TEXT NOT NULL,
3097                   operations_json TEXT,
3098                   resolution TEXT NOT NULL DEFAULT 'active'
3099                     CHECK(resolution IN ('active', 'resolved_keep_server', 'superseded', 'dismissed')),
3100                   resolved_at_ms INTEGER,
3101                   replacement_client_commit_id TEXT);
3102                 CREATE INDEX IF NOT EXISTS _syncular_commit_outcomes_resolution_seq
3103                   ON _syncular_commit_outcomes(resolution, seq);
3104                 CREATE TABLE IF NOT EXISTS _syncular_units (
3105                   id TEXT PRIMARY KEY, scopes TEXT NOT NULL,
3106                   explicit INTEGER NOT NULL DEFAULT 0,
3107                   status TEXT NOT NULL DEFAULT 'active', reason_code TEXT,
3108                   cursor INTEGER DEFAULT -1, bootstrap_state TEXT,
3109                   seeded TEXT NOT NULL DEFAULT '[]', echo TEXT, applied TEXT, restriction TEXT);
3110                 CREATE TABLE IF NOT EXISTS _syncular_meta (
3111                   key TEXT PRIMARY KEY, value TEXT NOT NULL);
3112                 CREATE TABLE IF NOT EXISTS _syncular_windows (
3113                   base TEXT NOT NULL, unit TEXT NOT NULL, sub_id TEXT NOT NULL,
3114                   PRIMARY KEY (base, unit));
3115                 CREATE INDEX IF NOT EXISTS _syncular_windows_unit ON _syncular_windows(sub_id);
3116                 CREATE TABLE IF NOT EXISTS _syncular_pending_evictions (
3117                   unit_id TEXT NOT NULL, tbl TEXT NOT NULL,
3118                   effective_scopes TEXT NOT NULL, PRIMARY KEY (unit_id, tbl));
3119                 CREATE TABLE IF NOT EXISTS _syncular_blob_commit_refs(
3120                   commit_id TEXT NOT NULL, blob_id TEXT NOT NULL,
3121                   PRIMARY KEY(commit_id, blob_id));
3122                 CREATE INDEX IF NOT EXISTS _syncular_blob_commit_refs_body
3123                   ON _syncular_blob_commit_refs(blob_id);",
3124            )
3125            .map_err(|e| e.to_string())?;
3126        // The §5.6 applied-segment record and the §7.4.3 restriction, added
3127        // after the units table shipped.
3128        for column in ["applied", "restriction"] {
3129            if !self
3130                .conn
3131                .prepare("SELECT 1 FROM pragma_table_info('_syncular_units') WHERE name = ?1")
3132                .and_then(|mut stmt| stmt.exists([column]))
3133                .map_err(|e| e.to_string())?
3134            {
3135                self.conn
3136                    .execute_batch(&format!(
3137                        "ALTER TABLE _syncular_units ADD COLUMN {column} TEXT"
3138                    ))
3139                    .map_err(|e| e.to_string())?;
3140            }
3141        }
3142        // An outbox created before `pendingCommits` carried creation times.
3143        let _ = self.conn.execute_batch(
3144            "ALTER TABLE _syncular_outbox ADD COLUMN created_at_ms INTEGER NOT NULL DEFAULT 0",
3145        );
3146        // Migrate an outcome journal created before failed aggregate
3147        // envelopes were retained. Historical rows intentionally stay NULL.
3148        let _ = self
3149            .conn
3150            .execute_batch("ALTER TABLE _syncular_commit_outcomes ADD COLUMN operations_json TEXT");
3151        // §7.1: an outbox created before the send-attempt marker; every commit
3152        // it holds counts as attempted.
3153        if !self
3154            .conn
3155            .prepare("SELECT 1 FROM pragma_table_info('_syncular_outbox') WHERE name = 'attempted'")
3156            .and_then(|mut stmt| stmt.exists([]))
3157            .map_err(|e| e.to_string())?
3158        {
3159            self.conn
3160                .execute_batch(
3161                    "ALTER TABLE _syncular_outbox ADD COLUMN attempted INTEGER NOT NULL DEFAULT 1",
3162                )
3163                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
3164        }
3165        if self.get_meta(LOCAL_REVISION_KEY)?.is_none() {
3166            self.set_meta(LOCAL_REVISION_KEY, "0")?;
3167        }
3168        // §7.1: `outboxId` names the outbox sequence. A new outbox table starts
3169        // a new sequence, so it replaces the id in the same transaction.
3170        if !outbox_existed || self.get_meta(OUTBOX_ID_KEY)?.is_none() {
3171            self.set_meta(OUTBOX_ID_KEY, &uuid::Uuid::new_v4().to_string())?;
3172        }
3173        // §9: a replica written under wire version 3 keeps its outbox, journal,
3174        // rows and pending evictions and registers its units fresh. Its
3175        // subscriptions, cursors, echoes, resume tokens and window entries go;
3176        // units left from an earlier version 4 life restart.
3177        if exists("_syncular_window_pending_evict")? {
3178            let invalid: bool = self
3179                .conn
3180                .query_row(
3181                    "SELECT EXISTS(SELECT 1 FROM _syncular_window_pending_evict
3182                       WHERE NOT json_valid(effective_scopes)
3183                          OR json_type(effective_scopes) <> 'object'
3184                          OR EXISTS(SELECT 1 FROM json_each(effective_scopes)
3185                               WHERE type <> 'array'
3186                                  OR EXISTS(SELECT 1 FROM json_each(value) AS v
3187                                       WHERE v.type <> 'text')))",
3188                    [],
3189                    |row| row.get(0),
3190                )
3191                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
3192            if invalid {
3193                return Err(
3194                    "sync.local_corrupt: a version 3 pending eviction cannot be upgraded"
3195                        .to_owned(),
3196                );
3197            }
3198            self.conn
3199                .execute_batch(
3200                    "INSERT OR REPLACE INTO _syncular_pending_evictions
3201                       SELECT sub_id, tbl, effective_scopes FROM _syncular_window_pending_evict;
3202                     DROP TABLE _syncular_window_pending_evict;
3203                     DROP TABLE IF EXISTS _syncular_subscriptions;
3204                     DELETE FROM _syncular_windows;",
3205                )
3206                .and_then(|()| reset_units(&self.conn, &BTreeSet::new(), None))
3207                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
3208        }
3209        // §5.9.7 blob cache. Mutable upload state stays off the body row so
3210        // completing a large upload does not rewrite its BLOB record.
3211        if self.schema_has_blobs() {
3212            if exists("_syncular_blobs")? {
3213                let mut statement = self
3214                    .conn
3215                    .prepare("PRAGMA table_info(_syncular_blobs)")
3216                    .map_err(|e| e.to_string())?;
3217                let mut columns = statement
3218                    .query_map([], |row| row.get::<_, String>(1))
3219                    .map_err(|e| e.to_string())?
3220                    .collect::<Result<Vec<_>, _>>()
3221                    .map_err(|e| e.to_string())?;
3222                columns.sort();
3223                let mut expected = vec![
3224                    "blob_id",
3225                    "byte_length",
3226                    "bytes",
3227                    "created_at_ms",
3228                    "media_type",
3229                ];
3230                expected.sort_unstable();
3231                if columns != expected {
3232                    return Err(
3233                        "sync.schema_mismatch: Local blob schema is incompatible".to_owned()
3234                    );
3235                }
3236            } else {
3237                self.conn
3238                    .execute_batch(
3239                        "CREATE TABLE _syncular_blobs(
3240                           blob_id TEXT PRIMARY KEY,
3241                           bytes BLOB NOT NULL,
3242                           byte_length INTEGER NOT NULL,
3243                           media_type TEXT,
3244                           created_at_ms INTEGER NOT NULL);",
3245                    )
3246                    .map_err(|e| e.to_string())?;
3247            }
3248            self.conn
3249                .execute_batch(
3250                    "CREATE TABLE IF NOT EXISTS _syncular_blob_uploads(
3251                       blob_id TEXT PRIMARY KEY,
3252                       media_type TEXT,
3253                       created_at_ms INTEGER NOT NULL);",
3254                )
3255                .map_err(|e| e.to_string())?;
3256        }
3257        Ok(())
3258    }
3259
3260    /// True iff any synced table declares a `blob_ref` column (§5.9).
3261    fn schema_has_blobs(&self) -> bool {
3262        self.schema
3263            .tables
3264            .iter()
3265            .any(|t| t.columns.iter().any(|c| c.ty == ColumnType::BlobRef))
3266    }
3267
3268    // -- meta (§7.4.1 marker, bookkeeping) ------------------------------------
3269
3270    fn get_meta(&self, key: &str) -> Result<Option<String>, String> {
3271        meta_get(&self.conn, key)
3272            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
3273    }
3274
3275    // The caller holds the startup/reset transaction. Either both schema
3276    // records persist or the enclosing operation fails and rolls back.
3277    fn persist_schema_version(&self) -> Result<(), String> {
3278        self.conn
3279            .execute(
3280                "INSERT OR REPLACE INTO _syncular_meta(key,value) VALUES (?1,?2)",
3281                rusqlite::params![LOCAL_SCHEMA_VERSION_KEY, self.schema.version.to_string()],
3282            )
3283            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
3284        set_local_schema_descriptor(&self.conn, &self.schema)
3285            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
3286    }
3287
3288    pub(crate) fn set_meta(&self, key: &str, value: &str) -> Result<(), String> {
3289        meta_set(&self.conn, key, value)
3290            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
3291    }
3292
3293    fn delete_meta(&self, key: &str) -> Result<(), String> {
3294        meta_delete(&self.conn, key)
3295            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
3296    }
3297
3298    /// §7.1: the durable outbox in FIFO order, in schema-agnostic local form.
3299    fn load_outbox(&self) -> Result<Vec<Arc<OutboxCommit>>, String> {
3300        let mut stmt = self
3301            .conn
3302            .prepare("SELECT commit_id, ops_json FROM _syncular_outbox ORDER BY seq ASC")
3303            .map_err(|error| error.to_string())?;
3304        let rows = stmt
3305            .query_map([], |row| {
3306                Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
3307            })
3308            .map_err(|error| error.to_string())?;
3309        let mut commits = Vec::new();
3310        for row in rows {
3311            let (client_commit_id, raw) = row.map_err(|error| error.to_string())?;
3312            let entries: Vec<Value> = serde_json::from_str(&raw).map_err(|error| {
3313                format!("invalid persisted outbox {client_commit_id:?}: {error}")
3314            })?;
3315            let mut ops = Vec::with_capacity(entries.len());
3316            for entry in entries {
3317                let op = entry.get("op").and_then(Value::as_str).unwrap_or("delete");
3318                ops.push(OutboxOp {
3319                    upsert: op == "upsert",
3320                    table: entry
3321                        .get("table")
3322                        .and_then(Value::as_str)
3323                        .ok_or_else(|| "persisted outbox operation missing table".to_owned())?
3324                        .to_owned(),
3325                    row_id: entry
3326                        .get("rowId")
3327                        .and_then(Value::as_str)
3328                        .ok_or_else(|| "persisted outbox operation missing rowId".to_owned())?
3329                        .to_owned(),
3330                    base_version: entry.get("baseVersion").and_then(Value::as_i64),
3331                    // A legacy entry's `changedFields` key is ignored:
3332                    // the values map is the presence set (§6.1).
3333                    values: entry.get("values").and_then(Value::as_object).cloned(),
3334                    insert: entry.get("insert") == Some(&Value::Bool(true)),
3335                });
3336            }
3337            commits.push(Arc::new(OutboxCommit {
3338                client_commit_id,
3339                ops,
3340            }));
3341        }
3342        Ok(commits)
3343    }
3344
3345    fn restore_persisted_state(&mut self) -> Result<(), String> {
3346        self.outbox = self.load_outbox()?.into();
3347
3348        self.prune_commit_outcomes()?;
3349        let active = self.commit_outcomes(CommitOutcomeQuery {
3350            active_only: true,
3351            ..CommitOutcomeQuery::default()
3352        })?;
3353        self.conflicts = active
3354            .iter()
3355            .flat_map(|outcome| outcome.results.iter())
3356            .filter_map(|result| match result {
3357                CommitOperationOutcome::Conflict { conflict } => Some(conflict.clone()),
3358                _ => None,
3359            })
3360            .collect::<Vec<_>>()
3361            .into();
3362        self.rejections = active
3363            .iter()
3364            .flat_map(|outcome| outcome.results.iter())
3365            .filter_map(|result| match result {
3366                CommitOperationOutcome::Error { rejection } => Some(rejection.clone()),
3367                _ => None,
3368            })
3369            .collect::<Vec<_>>()
3370            .into();
3371
3372        self.lease_state = self
3373            .get_meta(LEASE_STATE_KEY)?
3374            .map(|raw| serde_json::from_str(&raw))
3375            .transpose()
3376            .map_err(|error| format!("invalid persisted lease state: {error}"))?;
3377        self.schema_floor = self
3378            .get_meta(SCHEMA_FLOOR_KEY)?
3379            .map(|raw| serde_json::from_str(&raw))
3380            .transpose()
3381            .map_err(|error| format!("invalid persisted schema floor: {error}"))?;
3382        self.stopped = self.schema_floor.is_some();
3383        // A replica left in unactivated preflight reopens gated: the quarantine
3384        // decision persists with the data across handle teardown and restart.
3385        if self.get_meta(SECURITY_PREFLIGHT_PENDING_KEY)?.as_deref() == Some("1") {
3386            self.security_preflight = true;
3387        }
3388        Ok(())
3389    }
3390
3391    fn save_unit_scope_schema(&self) -> Result<(), String> {
3392        let declarations: BTreeMap<_, BTreeMap<_, _>> = self
3393            .schema
3394            .tables
3395            .iter()
3396            .map(|table| {
3397                (
3398                    table.name.clone(),
3399                    table
3400                        .scope_variables
3401                        .iter()
3402                        .map(|scope| {
3403                            (
3404                                scope.variable.clone(),
3405                                [scope.prefix.clone(), scope.column.clone()],
3406                            )
3407                        })
3408                        .collect(),
3409                )
3410            })
3411            .collect();
3412        self.set_meta(
3413            "subscriptionScopeSchema",
3414            &serde_json::to_string(&declarations).expect("scope schema serialization"),
3415        )?;
3416        let generations: BTreeMap<_, _> = self
3417            .schema
3418            .tables
3419            .iter()
3420            .filter_map(|table| Some((&table.name, table.generation.as_ref()?)))
3421            .collect();
3422        self.set_meta(
3423            TABLE_GENERATIONS_KEY,
3424            &serde_json::to_string(&generations).expect("generations serialize"),
3425        )
3426    }
3427
3428    /// Drop units that cover no table of the running schema, with their window
3429    /// registry rows and pending evictions; never translate scopes. At a bump
3430    /// (§7.4.3) a unit also needs every variable unchanged in prefix and column
3431    /// on every table it covered before.
3432    fn prune_unknown_units(&mut self, bump: bool) -> Result<(), String> {
3433        let previous: Option<BTreeMap<String, BTreeMap<String, [String; 2]>>> = if bump {
3434            self.get_meta("subscriptionScopeSchema")?
3435                .map(|raw| serde_json::from_str(&raw))
3436                .transpose()
3437                .map_err(|_| "sync.local_corrupt: invalid persisted scope schema".to_owned())?
3438        } else {
3439            None
3440        };
3441        // A table keeps the variables' meaning when each has the same prefix
3442        // and column as before. An old binary stored no declaration evidence;
3443        // matching names cannot prove unchanged meaning, so the app registers
3444        // again.
3445        let unchanged = |name: &str, variables: &[&String]| {
3446            let (Some(old), Some(table)) = (
3447                previous.as_ref().and_then(|previous| previous.get(name)),
3448                self.schema.table(name),
3449            ) else {
3450                return false;
3451            };
3452            variables.iter().all(|variable| {
3453                table
3454                    .scope_variables
3455                    .iter()
3456                    .find(|scope| &scope.variable == *variable)
3457                    .is_some_and(|scope| {
3458                        old.get(*variable) == Some(&[scope.prefix.clone(), scope.column.clone()])
3459                    })
3460            })
3461        };
3462        let compatible = |scopes: &UnitScopes| {
3463            if !self.schema.tables.iter().any(|table| covers(table, scopes)) {
3464                return false;
3465            }
3466            if !bump {
3467                return true;
3468            }
3469            let Some(previous) = &previous else {
3470                return false;
3471            };
3472            previous.iter().all(|(name, old)| {
3473                !scopes.keys().all(|variable| old.contains_key(variable))
3474                    || unchanged(name, &scopes.keys().collect::<Vec<_>>())
3475            })
3476        };
3477        let mut stale: BTreeSet<String> = self
3478            .stored(load_units(&self.conn))?
3479            .into_iter()
3480            .filter(|unit| !compatible(&unit.scopes))
3481            .map(|unit| unit.id)
3482            .collect();
3483        // A shrunk window's deferred eviction outlives its unit row and keeps
3484        // its per-table scopes. A table the schema no longer has cannot be
3485        // evicted, and at a bump a table whose scope declarations changed must
3486        // not be evicted by the outdated rule.
3487        for (id, table, effective) in self.load_pending_evictions()? {
3488            if self.schema.table(&table).is_none()
3489                || (bump
3490                    && !unchanged(
3491                        &table,
3492                        &effective
3493                            .iter()
3494                            .map(|(variable, _)| variable)
3495                            .collect::<Vec<_>>(),
3496                    ))
3497            {
3498                stale.insert(id);
3499            }
3500        }
3501        for id in &stale {
3502            for sql in [
3503                "DELETE FROM _syncular_windows WHERE sub_id = ?1",
3504                "DELETE FROM _syncular_pending_evictions WHERE unit_id = ?1",
3505                "DELETE FROM _syncular_units WHERE id = ?1",
3506            ] {
3507                self.conn
3508                    .execute(sql, rusqlite::params![id])
3509                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
3510            }
3511        }
3512        Ok(())
3513    }
3514
3515    pub fn local_revision(&self) -> Result<u64, String> {
3516        Ok(self
3517            .get_meta(LOCAL_REVISION_KEY)?
3518            .and_then(|value| value.parse().ok())
3519            .unwrap_or(0))
3520    }
3521
3522    /// §7.5: resolve a snapshot read on the mutable owner connection through
3523    /// the same primitive the read-only sidecar uses, so the command surface
3524    /// and the file sidecar return one revision, rows, coverage, catch-up, and
3525    /// delivery shape. The structured [`QueryReadFailure`] is preserved; an
3526    /// `owner` records its failure (and its next success) in diagnostics.
3527    pub fn snapshot_read(
3528        &mut self,
3529        request: &SnapshotReadRequest<'_>,
3530        owner: Option<QueryOwner<'_>>,
3531    ) -> Result<SnapshotRead, QueryReadFailure> {
3532        let result = snapshot_read_connection(&self.conn, Some(&self.schema), request).and_then(
3533            |mut read| {
3534                for delivery in &mut read.deliveries {
3535                    if let CommitDelivery::Known { outcome, .. } = delivery {
3536                        *outcome = self
3537                            .attach_retained_rows(outcome.clone())
3538                            .map_err(QueryReadFailure::from)?;
3539                    }
3540                }
3541                Ok(read)
3542            },
3543        );
3544        if let Some(owner) = owner {
3545            self.record_query_read(owner, result.as_ref().err());
3546        }
3547        result
3548    }
3549
3550    /// §7.5: one client commit's delivery status with the owner's retained
3551    /// rows: pending, its journal outcome, or an explicit unknown.
3552    pub fn commit_delivery(&mut self, id: &str) -> Result<CommitDelivery, QueryReadFailure> {
3553        let read = self.snapshot_read(
3554            &SnapshotReadRequest {
3555                commit_ids: vec![id.to_owned()],
3556                ..Default::default()
3557            },
3558            None,
3559        )?;
3560        Ok(read
3561            .deliveries
3562            .into_iter()
3563            .next()
3564            .expect("one requested delivery"))
3565    }
3566
3567    #[must_use]
3568    pub fn status_snapshot(&self) -> SyncStatusSnapshot {
3569        SyncStatusSnapshot {
3570            current_schema_version: self.schema.version,
3571            outbox: self.outbox.len(),
3572            upgrading: self.upgrading,
3573            upgrade_kept_tables: self.upgrade_kept_tables,
3574            lease_state: self.lease_state.clone(),
3575            schema_floor: self.schema_floor.clone(),
3576            sync_needed: self.sync_needed,
3577            previous_version_context: self.previous_version_status(),
3578            security_lifecycle: self.security_lifecycle(),
3579        }
3580    }
3581
3582    /// RFC 0005 A2: container presence for a host that must act on it (Diego's
3583    /// rollback precondition), read without creating the file.
3584    fn previous_version_status(&self) -> PreviousVersionStatus {
3585        let Some(replica_path) = self.previous_version_replica_path() else {
3586            return PreviousVersionStatus {
3587                present: false,
3588                created_at_ms: None,
3589            };
3590        };
3591        match crate::previous_version::read_previous_version_record(&replica_path) {
3592            Ok(Some(record)) => PreviousVersionStatus {
3593                present: true,
3594                created_at_ms: Some(record.created_at_ms),
3595            },
3596            _ => PreviousVersionStatus {
3597                present: std::path::Path::new(
3598                    &crate::previous_version::previous_version_container_path(&replica_path),
3599                )
3600                .exists(),
3601                created_at_ms: None,
3602            },
3603        }
3604    }
3605
3606    /// RFC 0005 D7: read captured rows from the previous local schema. `state`
3607    /// is always `previousVersion`; the container never makes
3608    /// `query_snapshot()` coverage complete. Lease stop/expiry, scope
3609    /// revocation, coverage completion and the TTL DISCARD the container and
3610    /// close the read with their own reason.
3611    pub fn previous_version_snapshot(
3612        &self,
3613        spec: &PreviousVersionReadSpec,
3614    ) -> Result<PreviousVersionSnapshot, String> {
3615        let now_ms = self.clock_now_ms();
3616        crate::previous_version::previous_version_snapshot(
3617            &self.conn,
3618            self.previous_version_replica_path().as_deref(),
3619            self.previous_version.as_ref(),
3620            PreviousVersionLifecycle {
3621                lease_inactive: self.previous_version_lease_inactive(now_ms),
3622                scope_revoked: self
3623                    .stored(load_units(&self.conn))?
3624                    .iter()
3625                    .any(|unit| unit.status == UnitStatus::Revoked),
3626                coverage_complete: self.previous_version_coverage_complete()?,
3627            },
3628            now_ms,
3629            self.schema.version,
3630            spec,
3631        )
3632    }
3633
3634    /// RFC 0005 D6: the advisory pre-reset compatibility audit.
3635    pub fn previous_version_audit(
3636        &self,
3637    ) -> Result<Option<crate::previous_version::PreviousVersionAudit>, String> {
3638        crate::previous_version::stored_previous_version_audit(&self.conn)
3639            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
3640    }
3641
3642    /// RFC 0005 A2/D9: the executable downgrade step. Drop the container file
3643    /// and both metadata records, and report whether anything was present.
3644    /// Idempotent: absence is a successful no-op.
3645    pub fn previous_version_discard(
3646        &self,
3647    ) -> Result<crate::previous_version::PreviousVersionDiscardOutcome, String> {
3648        self.drop_previous_version()
3649    }
3650
3651    fn drop_previous_version(
3652        &self,
3653    ) -> Result<crate::previous_version::PreviousVersionDiscardOutcome, String> {
3654        let Some(replica_path) = self.previous_version_replica_path() else {
3655            return Ok(crate::previous_version::PreviousVersionDiscardOutcome {
3656                present: false,
3657                discarded: false,
3658            });
3659        };
3660        crate::previous_version::discard_previous_version(&self.conn, &replica_path)
3661    }
3662
3663    /// RFC 0005 D7: `leaseState.errorCode` or an expired lease.
3664    fn previous_version_lease_inactive(&self, now_ms: i64) -> bool {
3665        let Some(lease) = &self.lease_state else {
3666            return false;
3667        };
3668        if lease.error_code.is_some() {
3669            return true;
3670        }
3671        lease.expires_at_ms.is_some_and(|expires| expires <= now_ms)
3672    }
3673
3674    /// RFC 0005 D7: §7.4.5 replacement coverage — no active unit is
3675    /// bootstrapping. An empty active set is not completion (mirrors the TS
3676    /// predicate exactly).
3677    fn previous_version_coverage_complete(&self) -> Result<bool, String> {
3678        let units = self.stored(load_units(&self.conn))?;
3679        let mut active = units
3680            .iter()
3681            .filter(|unit| unit.status == UnitStatus::Active)
3682            .peekable();
3683        Ok(active.peek().is_some() && !active.any(UnitRecord::bootstrapping))
3684    }
3685
3686    /// RFC 0005 D7: lifetime triggers evaluated once per sync round, after the
3687    /// apply. A container that no longer has a reason to exist is discarded so
3688    /// the rows do not outlive the window they were kept for.
3689    fn previous_version_lifetime_check(&self) {
3690        let Some(config) = self.previous_version.filter(|config| config.enabled) else {
3691            return;
3692        };
3693        let now_ms = self.clock_now_ms();
3694        if self.previous_version_lease_inactive(now_ms) {
3695            let _ = self.drop_previous_version();
3696            return;
3697        }
3698        let Some(replica_path) = self.previous_version_replica_path() else {
3699            return;
3700        };
3701        let Ok(Some(record)) = crate::previous_version::read_previous_version_record(&replica_path)
3702        else {
3703            return;
3704        };
3705        let Ok(units) = load_units(&self.conn) else {
3706            return;
3707        };
3708        if units.iter().any(|unit| unit.status == UnitStatus::Revoked) {
3709            let _ = self.drop_previous_version();
3710            return;
3711        }
3712        if now_ms - record.created_at_ms > config.max_age_ms {
3713            let _ = self.drop_previous_version();
3714            return;
3715        }
3716        if self.previous_version_coverage_complete() == Ok(true) {
3717            let _ = self.drop_previous_version();
3718        }
3719    }
3720
3721    pub fn diagnostics_snapshot(&self) -> Result<ClientDiagnosticsSnapshot, String> {
3722        let registered = self.stored(load_units(&self.conn))?;
3723        // Both meta values in one statement: the FFI host recomputes
3724        // diagnostics after every command.
3725        let (local_revision, replica_cursor): (Option<String>, Option<String>) = self.stored(
3726            self.conn
3727                .prepare_cached(
3728                    "SELECT (SELECT value FROM _syncular_meta WHERE key = ?1),
3729                            (SELECT value FROM _syncular_meta WHERE key = ?2)",
3730                )
3731                .and_then(|mut statement| {
3732                    statement.query_row([LOCAL_REVISION_KEY, REPLICA_CURSOR_KEY], |row| {
3733                        Ok((row.get(0)?, row.get(1)?))
3734                    })
3735                }),
3736        )?;
3737        let mut units = DiagnosticUnits::default();
3738        for unit in &registered {
3739            *match unit.status {
3740                UnitStatus::Revoked => &mut units.revoked,
3741                UnitStatus::Failed => &mut units.failed,
3742                UnitStatus::Active if !unit.bootstrapping() => &mut units.complete,
3743                UnitStatus::Active
3744                    if unit.reason_code.as_deref() == Some("sync.cursor_expired") =>
3745                {
3746                    &mut units.reset
3747                }
3748                UnitStatus::Active => &mut units.bootstrapping,
3749            } += 1;
3750        }
3751        units.reason_codes = registered
3752            .iter()
3753            .filter_map(|unit| unit.reason_code.as_deref().map(Self::diagnostic_code))
3754            .collect::<BTreeSet<_>>()
3755            .into_iter()
3756            .collect();
3757        let captured_at_ms = self.clock_now_ms();
3758        let lease = if let Some(error_code) = self
3759            .lease_state
3760            .as_ref()
3761            .and_then(|state| state.error_code.clone())
3762        {
3763            ClientDiagnosticsLease {
3764                state: "stopped".to_owned(),
3765                expires_at_ms: self
3766                    .lease_state
3767                    .as_ref()
3768                    .and_then(|state| state.expires_at_ms),
3769                error_code: Some(Self::diagnostic_code(&error_code)),
3770            }
3771        } else if let Some(expires_at_ms) = self
3772            .lease_state
3773            .as_ref()
3774            .and_then(|state| state.expires_at_ms)
3775        {
3776            ClientDiagnosticsLease {
3777                state: if expires_at_ms <= captured_at_ms {
3778                    "expired".to_owned()
3779                } else {
3780                    "active".to_owned()
3781                },
3782                expires_at_ms: Some(expires_at_ms),
3783                error_code: None,
3784            }
3785        } else {
3786            ClientDiagnosticsLease {
3787                state: "none".to_owned(),
3788                expires_at_ms: None,
3789                error_code: None,
3790            }
3791        };
3792        let connectivity = match self.last_round.as_ref() {
3793            _ if self.transport_closed() && self.active_round.is_none() => "offline",
3794            Some(round) if round.status == "succeeded" => "online",
3795            Some(round)
3796                if round.status == "failed"
3797                    && matches!(
3798                        round.cause_kind,
3799                        Some(
3800                            crate::TransportCauseKind::Network | crate::TransportCauseKind::Connect
3801                        )
3802                    ) =>
3803            {
3804                "offline"
3805            }
3806            Some(round) if round.status == "failed" && round.http_status.is_some() => "online",
3807            _ => "unknown",
3808        };
3809        Ok(ClientDiagnosticsSnapshot {
3810            version: CLIENT_DIAGNOSTICS_VERSION,
3811            captured_at_ms,
3812            host: ClientDiagnosticsHost {
3813                kind: "direct".to_owned(),
3814                role: "single".to_owned(),
3815                connectivity: connectivity.to_owned(),
3816                realtime: self.realtime_state,
3817                realtime_policy: self.realtime_policy,
3818                realtime_reason_code: self.realtime_reason_code.clone(),
3819                realtime_retry_delay_ms: self.realtime_retry_delay_ms,
3820            },
3821            security_lifecycle: self.security_lifecycle().to_owned(),
3822            schema: ClientDiagnosticsSchema {
3823                current_version: self.schema.version,
3824                upgrading: self.upgrading,
3825                required_version: self
3826                    .schema_floor
3827                    .as_ref()
3828                    .and_then(|floor| floor.required_schema_version),
3829                latest_version: self
3830                    .schema_floor
3831                    .as_ref()
3832                    .and_then(|floor| floor.latest_schema_version),
3833            },
3834            replica: ClientDiagnosticsReplica {
3835                local_revision: local_revision
3836                    .and_then(|value| value.parse::<u64>().ok())
3837                    .unwrap_or(0)
3838                    .to_string(),
3839                sync_needed: self.sync_needed,
3840                pending_outbox: self.outbox.len(),
3841            },
3842            lease,
3843            active_units: registered
3844                .iter()
3845                .filter(|unit| unit.status == UnitStatus::Active)
3846                .count(),
3847            units,
3848            replica_cursor: replica_cursor.map_or(Ok(-1), |raw| {
3849                raw.parse()
3850                    .map_err(|_| "sync.local_corrupt: persisted unit state is invalid".to_owned())
3851            })?,
3852            last_round: self.last_round.clone(),
3853            last_change: self.last_change.clone(),
3854            storage: self.diagnostics_storage(),
3855            query_failures: self.query_failures.clone(),
3856        })
3857    }
3858
3859    fn diagnostics_storage(&self) -> ClientDiagnosticsStorage {
3860        let read = || -> Result<ClientDiagnosticsStorage, rusqlite::Error> {
3861            let page_count: i64 = self
3862                .conn
3863                .query_row("PRAGMA page_count", [], |row| row.get(0))?;
3864            let page_size: i64 = self
3865                .conn
3866                .query_row("PRAGMA page_size", [], |row| row.get(0))?;
3867            // One cached aggregate, since the FFI host recomputes diagnostics
3868            // after every command; every invocation still reads current storage.
3869            let (outbox_bytes, outcome_entries, outcome_bytes): (i64, i64, i64) = self
3870                .conn
3871                .prepare_cached(
3872                    "SELECT (SELECT COALESCE(SUM(LENGTH(ops_json)), 0) FROM _syncular_outbox),
3873                            COUNT(*), COALESCE(SUM(LENGTH(results_json) + COALESCE(LENGTH(operations_json), 0)), 0)
3874                       FROM _syncular_commit_outcomes",
3875                )?
3876                .query_row([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))?;
3877            let blob_bytes = if self.schema_has_blobs() {
3878                self.conn
3879                    .prepare_cached("SELECT COALESCE(SUM(byte_length), 0) FROM _syncular_blobs")?
3880                    .query_row([], |row| row.get(0))?
3881            } else {
3882                0
3883            };
3884            let pressure = self
3885                .limits
3886                .blob_cache_max_bytes
3887                .is_some_and(|limit| blob_bytes > limit);
3888            Ok(ClientDiagnosticsStorage {
3889                status: if pressure { "pressure" } else { "healthy" }.to_owned(),
3890                database_bytes_approx: Some(page_count.saturating_mul(page_size).max(0)),
3891                pending_outbox_bytes_approx: Some(outbox_bytes.max(0)),
3892                retained_outcome_bytes_approx: Some(outcome_bytes.max(0)),
3893                retained_outcome_entries: Some(outcome_entries.max(0)),
3894                blob_cache_bytes_approx: Some(blob_bytes.max(0)),
3895                pressure_reason_code: pressure.then(|| "client.blob_cache_over_limit".to_owned()),
3896            })
3897        };
3898        read().unwrap_or_else(|_| ClientDiagnosticsStorage {
3899            status: "unreadable".to_owned(),
3900            database_bytes_approx: None,
3901            pending_outbox_bytes_approx: None,
3902            retained_outcome_bytes_approx: None,
3903            retained_outcome_entries: None,
3904            blob_cache_bytes_approx: None,
3905            pressure_reason_code: None,
3906        })
3907    }
3908
3909    pub fn drain_change_batches(&mut self) -> Vec<ClientChangeBatch> {
3910        self.change_queue.drain(..).collect()
3911    }
3912
3913    pub fn drain_sync_intents(&mut self) -> Vec<SyncIntent> {
3914        let intents = self.sync_intent_queue.drain(..).collect();
3915        if !self.transport_closed() {
3916            intents
3917        } else {
3918            vec![SyncIntent::None]
3919        }
3920    }
3921
3922    /// §8.7 host announcement: the number of `scopes` events received since
3923    /// the last drain. The event changes no sync state; the host surfaces each
3924    /// one to the app, whose discovery registers the newly readable units.
3925    pub fn drain_scopes_changed(&mut self) -> usize {
3926        std::mem::take(&mut self.scopes_changed)
3927    }
3928
3929    fn schedule_background_retry(&mut self) -> u64 {
3930        let delay_ms = self.retry_delay_ms;
3931        self.sync_intent_queue
3932            .push_back(SyncIntent::Background { delay_ms });
3933        self.retry_delay_ms = (self.retry_delay_ms * 2).min(30_000);
3934        self.round_retry_delay_ms = Some(delay_ms);
3935        delay_ms
3936    }
3937
3938    fn reset_background_retry(&mut self) {
3939        self.retry_delay_ms = 250;
3940    }
3941
3942    fn retryable_transport_code(code: &str) -> bool {
3943        code == "transport.failed"
3944            || code == "transport.timeout"
3945            || code == "transport.unavailable"
3946            || code == "sync.transport_failed"
3947    }
3948
3949    /// §1.8: the transport reported a refused or unreachable endpoint. The
3950    /// native transport says `connect` (DNS failure, connection refused,
3951    /// reset, or aborted); a browser fetch transport says `network`. Repeating
3952    /// the request on a backoff repairs neither, so no retry is scheduled.
3953    fn unreachable_transport(details: &Option<serde_json::Value>) -> bool {
3954        matches!(
3955            details
3956                .as_ref()
3957                .and_then(|details| details.get("causeKind"))
3958                .and_then(serde_json::Value::as_str),
3959            Some("connect" | "network")
3960        )
3961    }
3962
3963    /// §1.5: a segment fetch that fails inside an otherwise complete round is
3964    /// invisible to the server (the round response arrived whole), so its code
3965    /// rides the following requests like a socket-round failure. A code the
3966    /// frame grammar rejects is not reportable and the previous code stays.
3967    fn segment_fetch_failed(&mut self, error: TransportError) -> SectionError {
3968        if ssp2::model::valid_round_failure_code(&error.code) {
3969            self.round_failure = Some(error.code.clone());
3970        }
3971        SectionError::Transport(error)
3972    }
3973
3974    /// A failed round worth a background retry: a transport failure, or a
3975    /// §10.2 code the catalog marks retryable (clients may hardcode the
3976    /// catalog metadata, §10.1). Matches the TypeScript core, which retries
3977    /// on the server's `retryable` flag.
3978    fn retryable_failure_code(code: &str) -> bool {
3979        Self::retryable_transport_code(code)
3980            || matches!(
3981                code,
3982                "sync.auth_required"
3983                    | "sync.auth_lease_required"
3984                    | "sync.auth_lease_revoked"
3985                    | "sync.internal_error"
3986                    | "sync.idempotency_cache_miss"
3987                    | "sync.schema_not_ready"
3988                    | "sync.segment_build_timeout"
3989                    | "sync.segment_store_unavailable"
3990                    | "sync.segment_expired"
3991                    | "sync.rate_limited"
3992                    | "sync.websocket_connection_limit"
3993                    | "sync.idle_timeout"
3994            )
3995    }
3996
3997    fn diagnostic_code(code: &str) -> String {
3998        let valid = !code.is_empty()
3999            && code.len() <= 96
4000            && code.contains('.')
4001            && code
4002                .bytes()
4003                .next()
4004                .is_some_and(|byte| byte.is_ascii_lowercase())
4005            && code.bytes().all(|byte| {
4006                byte.is_ascii_lowercase()
4007                    || byte.is_ascii_digit()
4008                    || matches!(byte, b'.' | b'_' | b'-')
4009            });
4010        if valid {
4011            code.to_owned()
4012        } else {
4013            "client.unknown_failure".to_owned()
4014        }
4015    }
4016
4017    fn set_sync_needed(&mut self, value: bool, interactive: bool) {
4018        if self.sync_needed != value {
4019            if self.begin_observation("syncular_status").is_ok() {
4020                self.sync_needed = value;
4021                let batch = ChangeAccumulator {
4022                    status: true,
4023                    ..ChangeAccumulator::default()
4024                };
4025                if self.finish_observation("syncular_status", batch).is_err() {
4026                    self.rollback_observation("syncular_status");
4027                }
4028            } else {
4029                self.sync_needed = value;
4030            }
4031        }
4032        if value && interactive {
4033            self.sync_intent_queue.push_back(SyncIntent::Interactive);
4034        }
4035    }
4036
4037    /// A unit-store result: a row that does not parse is `sync.local_corrupt`;
4038    /// every other SQLite error keeps its storage classification.
4039    fn stored<T>(&self, result: rusqlite::Result<T>) -> Result<T, String> {
4040        result.map_err(|error| match error {
4041            rusqlite::Error::FromSqlConversionFailure(..) => {
4042                "sync.local_corrupt: persisted unit state is invalid".to_owned()
4043            }
4044            error => Self::sqlite_failure(&self.storage_failure, error),
4045        })
4046    }
4047
4048    fn sqlite_failure(
4049        storage_failure: &RefCell<Option<QueryReadFailure>>,
4050        error: rusqlite::Error,
4051    ) -> String {
4052        let message = error.to_string();
4053        let failure = QueryReadFailure::from(error);
4054        let code = failure.code;
4055        if code.is_some() && storage_failure.borrow().is_none() {
4056            *storage_failure.borrow_mut() = Some(failure);
4057        }
4058        match code {
4059            Some(code) => format!("{code}: {message}"),
4060            None => message,
4061        }
4062    }
4063
4064    fn begin_observation(&self, name: &str) -> Result<(), String> {
4065        if let Some(failure) = &self.coalesced_failure {
4066            return Err(failure.clone());
4067        }
4068        // SQLite rolls a whole transaction back on some I/O and capacity
4069        // errors; later frames must not commit on their own after that.
4070        if self.coalesced.is_some() && self.conn.is_autocommit() {
4071            return Err("the coalesced apply transaction was rolled back".to_owned());
4072        }
4073        self.conn
4074            .execute_batch(&format!("SAVEPOINT {name}"))
4075            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
4076    }
4077
4078    /// SPEC §1.4 rule 4: open a coalesced apply transaction unless a caller
4079    /// already owns one.
4080    fn begin_coalesced_apply(&mut self) -> Result<(), String> {
4081        if self.coalesced.is_some() || !self.conn.is_autocommit() {
4082            return Ok(());
4083        }
4084        self.conn
4085            .execute_batch("BEGIN")
4086            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4087        self.coalesced = Some(CoalescedApply {
4088            rows: 0,
4089            rollback: self.capture(),
4090        });
4091        Ok(())
4092    }
4093
4094    fn capture(&self) -> Rollback {
4095        Rollback {
4096            outbox: self.outbox.clone(),
4097            failed_commits: self.failed_commits.clone(),
4098            conflicts: self.conflicts.clone(),
4099            rejections: self.rejections.clone(),
4100            schema_floor: self.schema_floor.clone(),
4101            lease_state: self.lease_state.clone(),
4102            stopped: self.stopped,
4103            upgrading: self.upgrading,
4104            upgrade_kept_tables: self.upgrade_kept_tables,
4105            sync_needed: self.sync_needed,
4106            active_round: self.active_round,
4107            overlay_dirty: self.overlay_dirty.snapshot(),
4108            transport_gate: self.transport_gate.clone(),
4109            transport_epoch: self.transport_epoch,
4110            change_queue: self.change_queue.len(),
4111            projection_pending_queue: self.projection_pending_queue.len(),
4112            sync_intent_queue: self.sync_intent_queue.len(),
4113            last_change: self.last_change.clone(),
4114        }
4115    }
4116
4117    fn restore(&mut self, rollback: Rollback) {
4118        self.outbox = rollback.outbox;
4119        self.failed_commits = rollback.failed_commits;
4120        self.conflicts = rollback.conflicts;
4121        self.rejections = rollback.rejections;
4122        self.schema_floor = rollback.schema_floor;
4123        self.lease_state = rollback.lease_state;
4124        self.stopped = rollback.stopped;
4125        self.upgrading = rollback.upgrading;
4126        self.upgrade_kept_tables = rollback.upgrade_kept_tables;
4127        self.sync_needed = rollback.sync_needed;
4128        self.active_round = rollback.active_round;
4129        self.transport_gate = rollback.transport_gate;
4130        self.transport_epoch = rollback.transport_epoch;
4131        self.overlay_dirty.restore(rollback.overlay_dirty);
4132        self.change_queue.truncate(rollback.change_queue);
4133        self.projection_pending_queue
4134            .truncate(rollback.projection_pending_queue);
4135        self.sync_intent_queue.truncate(rollback.sync_intent_queue);
4136        self.last_change = rollback.last_change;
4137    }
4138
4139    /// Account the rows of the next frame or block. A unit that would take the
4140    /// coalesced transaction past the bound commits the earlier units first.
4141    fn coalesce_unit(&mut self, rows: usize) -> Result<(), String> {
4142        let Some(open) = &self.coalesced else {
4143            return Ok(());
4144        };
4145        if open.rows > 0 && open.rows + rows > COALESCED_APPLY_ROWS {
4146            self.commit_coalesced_apply()?;
4147            self.begin_coalesced_apply()?;
4148        }
4149        if let Some(open) = &mut self.coalesced {
4150            open.rows += rows;
4151        }
4152        Ok(())
4153    }
4154
4155    /// COMMIT the coalesced transaction. A failed COMMIT rolls every coalesced
4156    /// frame back, restores the in-memory state of its `BEGIN`, drops the
4157    /// change batches and sync intents queued since, and fails the rest of the
4158    /// response.
4159    fn commit_coalesced_apply(&mut self) -> Result<(), String> {
4160        let Some(open) = self.coalesced.take() else {
4161            return Ok(());
4162        };
4163        let committed = if self.conn.is_autocommit() {
4164            Err("the coalesced apply transaction was rolled back".to_owned())
4165        } else {
4166            self.collect_projection_pending().and_then(|pending| {
4167                self.stored(self.conn.execute_batch("COMMIT"))?;
4168                self.projection_pending_queue.extend(pending);
4169                Ok(())
4170            })
4171        };
4172        let Err(error) = committed else {
4173            return Ok(());
4174        };
4175        if !self.conn.is_autocommit() {
4176            if let Err(rollback) = self.conn.execute_batch("ROLLBACK") {
4177                let _ = Self::sqlite_failure(&self.storage_failure, rollback);
4178            }
4179        }
4180        self.restore(open.rollback);
4181        self.coalesced_failure = Some(error.clone());
4182        Err(error)
4183    }
4184
4185    /// End the response's coalescing: COMMIT what is open and clear a failure.
4186    fn finish_coalesced_apply(&mut self) -> Result<(), String> {
4187        let committed = self.commit_coalesced_apply();
4188        match self.coalesced_failure.take() {
4189            Some(failure) => Err(failure),
4190            None => committed,
4191        }
4192    }
4193
4194    fn rollback_observation(&self, name: &str) {
4195        if let Err(error) = self
4196            .conn
4197            .execute_batch(&format!("ROLLBACK TO {name}; RELEASE {name}"))
4198        {
4199            if let Some(failure) = self.storage_failure.borrow_mut().as_mut() {
4200                if failure.rollback_failure.is_none() {
4201                    failure.rollback_failure = Some(Box::new(QueryReadFailure::from(error)));
4202                }
4203            }
4204        }
4205    }
4206
4207    fn finish_observation(
4208        &mut self,
4209        name: &str,
4210        mut batch: ChangeAccumulator,
4211    ) -> Result<(), String> {
4212        #[cfg(feature = "bench-internals")]
4213        let _phase = self.benchmark_phases.start(Phase::ObservationCommit);
4214        // §8.8: an acknowledged boundary ends a `through` gate.
4215        if matches!(self.transport_gate, crate::TransportGate::Through(_))
4216            && self.pushable_commits() == 0
4217        {
4218            self.move_transport_gate(crate::TransportGate::Pull);
4219        }
4220        for table in &self.schema.tables {
4221            for projection in &table.local_projections {
4222                if batch.tables.contains_key(&table.name)
4223                    || projection
4224                        .dependencies
4225                        .iter()
4226                        .any(|dep| batch.tables.contains_key(&dep.table))
4227                {
4228                    batch.table(&projection.name);
4229                }
4230            }
4231        }
4232        if self.failed_commits.iter().any(|(commit, _)| {
4233            commit
4234                .ops
4235                .iter()
4236                .any(|operation| batch.tables.contains_key(&operation.table))
4237        }) {
4238            batch.outcomes = true;
4239        }
4240        let projection_pending = if self.coalesced.is_none() && !self.opening_replica {
4241            self.collect_projection_pending()?
4242        } else {
4243            Vec::new()
4244        };
4245        if !batch.touched() {
4246            self.conn
4247                .execute_batch(&format!("RELEASE {name}"))
4248                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4249            self.projection_pending_queue.extend(projection_pending);
4250            return Ok(());
4251        }
4252        let revision = self
4253            .local_revision()?
4254            .checked_add(1)
4255            .ok_or_else(|| "local revision exhausted u64".to_owned())?;
4256        self.conn
4257            .execute(
4258                "INSERT OR REPLACE INTO _syncular_meta(key, value) VALUES (?1, ?2)",
4259                rusqlite::params![LOCAL_REVISION_KEY, revision.to_string()],
4260            )
4261            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4262        let status = batch.status.then(|| self.status_snapshot());
4263        let event = ClientChangeBatch {
4264            revision: revision.to_string(),
4265            tables: batch
4266                .tables
4267                .into_iter()
4268                .map(|(table, scope_keys)| TableChange {
4269                    table,
4270                    scope_keys: scope_keys.map(|keys| keys.into_iter().collect()),
4271                })
4272                .collect(),
4273            windows: batch
4274                .windows
4275                .into_iter()
4276                .map(|(base_key, units)| WindowChange {
4277                    base_key,
4278                    units: units.into_iter().collect(),
4279                })
4280                .collect(),
4281            status,
4282            conflicts_changed: batch.conflicts,
4283            rejections_changed: batch.rejections,
4284            outcomes_changed: batch.outcomes,
4285            applied_commits: Vec::new(),
4286        };
4287        self.conn
4288            .execute_batch(&format!("RELEASE {name}"))
4289            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4290        let mut diagnostic_tables = event
4291            .tables
4292            .iter()
4293            .map(|entry| entry.table.clone())
4294            .collect::<BTreeSet<_>>()
4295            .into_iter()
4296            .collect::<Vec<_>>();
4297        // §7.6: the selected variables of the changed window bases.
4298        let mut diagnostic_windows = event
4299            .windows
4300            .iter()
4301            .map(|entry| {
4302                entry
4303                    .base_key
4304                    .split('\0')
4305                    .next()
4306                    .unwrap_or_default()
4307                    .to_owned()
4308            })
4309            .collect::<BTreeSet<_>>()
4310            .into_iter()
4311            .collect::<Vec<_>>();
4312        let domains_truncated = diagnostic_tables.len() > MAX_DIAGNOSTIC_DOMAINS
4313            || diagnostic_windows.len() > MAX_DIAGNOSTIC_DOMAINS;
4314        diagnostic_tables.truncate(MAX_DIAGNOSTIC_DOMAINS);
4315        diagnostic_windows.truncate(MAX_DIAGNOSTIC_DOMAINS);
4316        self.last_change = Some(DiagnosticLastChange {
4317            revision: event.revision.clone(),
4318            recorded_at_ms: self.clock_now_ms(),
4319            tables: diagnostic_tables,
4320            windows: diagnostic_windows,
4321            domains_truncated,
4322            status_changed: event.status.is_some(),
4323            conflicts_changed: event.conflicts_changed,
4324            rejections_changed: event.rejections_changed,
4325            outcomes_changed: event.outcomes_changed,
4326        });
4327        self.change_queue.push_back(event);
4328        self.projection_pending_queue.extend(projection_pending);
4329        Ok(())
4330    }
4331
4332    fn record_scope_map(
4333        &self,
4334        batch: &mut ChangeAccumulator,
4335        table_name: &str,
4336        scopes: &[(String, Vec<String>)],
4337    ) {
4338        let Some(table) = self.schema.table(table_name) else {
4339            return;
4340        };
4341        // A bulk scoped delete whose map leaves a declared variable unnamed
4342        // cannot list the deleted rows' keys for it: the change is table-wide.
4343        if table.scope_variables.iter().any(|scope| {
4344            !scopes
4345                .iter()
4346                .any(|(variable, _)| *variable == scope.variable)
4347        }) {
4348            batch.table(table_name);
4349            return;
4350        }
4351        for (variable, values) in scopes {
4352            let Some(scope) = table
4353                .scope_variables
4354                .iter()
4355                .find(|scope| &scope.variable == variable)
4356            else {
4357                continue;
4358            };
4359            for value in values {
4360                batch.scope(table_name, format!("{}:{value}", scope.prefix));
4361            }
4362        }
4363    }
4364
4365    /// Record a row's current scope keys from the base or visible table.
4366    fn record_row_scopes(
4367        &self,
4368        batch: &mut ChangeAccumulator,
4369        table_name: &str,
4370        row_id: &str,
4371        base: bool,
4372    ) -> bool {
4373        let Some(table) = self.schema.table(table_name) else {
4374            return false;
4375        };
4376        if table.scope_variables.is_empty() {
4377            return false;
4378        }
4379        let columns = table
4380            .scope_variables
4381            .iter()
4382            .map(|scope| quote_ident(&scope.column))
4383            .collect::<Vec<_>>()
4384            .join(", ");
4385        let full_table = if base {
4386            base_table(table_name)
4387        } else {
4388            visible_table(table_name)
4389        };
4390        let sql = format!(
4391            "SELECT {columns} FROM {full_table} WHERE {} LIMIT 1",
4392            row_id_predicate(table)
4393        );
4394        let Ok(mut stmt) = self.conn.prepare_cached(&sql) else {
4395            return false;
4396        };
4397        let values = stmt.query_row(rusqlite::params![row_id], |row| {
4398            let mut values = Vec::with_capacity(table.scope_variables.len());
4399            for index in 0..table.scope_variables.len() {
4400                values.push(row.get::<_, Option<String>>(index)?);
4401            }
4402            Ok(values)
4403        });
4404        let Ok(values) = values else {
4405            return false;
4406        };
4407        let mut recorded = false;
4408        for (scope, value) in table.scope_variables.iter().zip(values) {
4409            if let Some(value) = value {
4410                batch.scope(table_name, format!("{}:{value}", scope.prefix));
4411                recorded = true;
4412            }
4413        }
4414        recorded
4415    }
4416
4417    fn record_commit_changes(
4418        &self,
4419        batch: &mut ChangeAccumulator,
4420        tables: &[String],
4421        changes: &[ssp2::model::Change],
4422    ) {
4423        #[cfg(feature = "bench-internals")]
4424        let _phase = self.benchmark_phases.start(Phase::ObservationPrepare);
4425        for change in changes {
4426            let Some(table_name) = tables.get(change.table_index as usize) else {
4427                continue;
4428            };
4429            let mut precise = self.record_row_scopes(batch, table_name, &change.row_id, true);
4430            if let Some(table) = self.schema.table(table_name) {
4431                for (variable, value) in &change.scopes {
4432                    if let Some(scope) = table
4433                        .scope_variables
4434                        .iter()
4435                        .find(|scope| &scope.variable == variable)
4436                    {
4437                        batch.scope(table_name, format!("{}:{value}", scope.prefix));
4438                        precise = true;
4439                    }
4440                }
4441            }
4442            if !precise {
4443                batch.table(table_name);
4444            }
4445        }
4446    }
4447
4448    /// Whether a base or visible row matches the scope predicate; `false`
4449    /// without a local scope-column mapping. A SQLite failure is an error.
4450    fn scoped_rows_exist(
4451        &self,
4452        table_name: &str,
4453        effective: &[(String, Vec<String>)],
4454        owners: &[Vec<(String, Vec<String>)>],
4455    ) -> Result<bool, String> {
4456        let Some(table) = self.schema.table(table_name) else {
4457            return Ok(false);
4458        };
4459        let Ok(Some((predicate, params))) = local_scope_predicate(table, effective, owners) else {
4460            return Ok(false);
4461        };
4462        for source in [base_table(table_name), visible_table(table_name)] {
4463            if self
4464                .conn
4465                .query_row(
4466                    &format!("SELECT EXISTS(SELECT 1 FROM {source} WHERE {predicate})"),
4467                    rusqlite::params_from_iter(&params),
4468                    |row| row.get::<_, bool>(0),
4469                )
4470                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
4471            {
4472                return Ok(true);
4473            }
4474        }
4475        Ok(false)
4476    }
4477
4478    /// §5.6 first-page clear of `unit_id`'s pair: delete its rows except
4479    /// those another owner covers (§3.3), failing closed without a local
4480    /// scope-column mapping. Owners are read only when a row matches, inside
4481    /// the caller's transaction. Returns whether rows matched.
4482    fn clear_scope(
4483        &mut self,
4484        table: &TableSchema,
4485        effective: &[(String, Vec<String>)],
4486        unit_id: &str,
4487    ) -> Result<bool, SectionError> {
4488        let storage = |message| SectionError::Abort("storage.failed".to_owned(), message);
4489        let matched = self
4490            .scoped_rows_exist(&table.name, effective, &[])
4491            .map_err(storage)?;
4492        let owners = if matched {
4493            unit_owners(
4494                &self.stored(load_units(&self.conn)).map_err(storage)?,
4495                table,
4496                unit_id,
4497            )
4498        } else {
4499            Vec::new()
4500        };
4501        let changed = matched
4502            && (owners.is_empty()
4503                || self
4504                    .scoped_rows_exist(&table.name, effective, &owners)
4505                    .map_err(storage)?);
4506        if !self
4507            .purge_scope_rows(&table.name, effective, &owners)
4508            .map_err(storage)?
4509        {
4510            return Err(SectionError::FailClosed);
4511        }
4512        Ok(changed)
4513    }
4514
4515    /// §7.4.5: true while a schema-bump reset + first re-bootstrap runs.
4516    pub fn upgrading(&self) -> bool {
4517        self.upgrading
4518    }
4519
4520    /// §7.4.2 "app ships new code": swap to a NEW generated schema while
4521    /// keeping this client's local database (identity, outbox, tables). The
4522    /// §7.4.1 marker check then fires the wipe/re-bootstrap flow when the
4523    /// version increases. Recreation runs the same marker guard as opening
4524    /// a durable replica, holds the guard and every write it authorizes under
4525    /// one write transaction, and preserves the current client (compiled
4526    /// schema, outbox, tables) on refusal.
4527    pub fn recreate_with_schema(&mut self, schema_json: &Value) -> Result<(), ClientError> {
4528        (|| -> Result<(), ClientError> {
4529            let new_schema = parse_schema_json(schema_json)?;
4530            validate_authority_reads(&new_schema, &self.limits.authority_reads)
4531                .map_err(|error| error.to_string())?;
4532            // §3.3: a reopened client remembers no re-armed window unit.
4533            self.window_armed.clear();
4534            self.conn
4535                .execute_batch("BEGIN IMMEDIATE")
4536                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4537            self.opening_replica = true;
4538            let prior_schema = std::mem::replace(&mut self.schema, new_schema);
4539            // §7.4.3/§7.4.4: a reset inside this transaction mutates in-memory
4540            // state (dropped outbox commits, rejections, upgrade and floor flags,
4541            // overlay dirtiness) and appends change/intent batches. A COMMIT that
4542            // fails after the reset succeeded rolls the database back, so every
4543            // one of those fields is captured here and restored with it.
4544            let rollback = self.capture();
4545            let guarded = (|| -> Result<(), ClientError> {
4546                // §7.4.2: the marker is re-read under the write lock the caller
4547                // holds, so a replica another process upgraded meanwhile refuses
4548                // this recreation instead of having its marker and tables
4549                // downgraded.
4550                let marker = read_local_schema_version(&self.conn, self.schema.version)?;
4551                self.create_bookkeeping_tables()?;
4552                match marker {
4553                    Some(version) if version < self.schema.version => self.run_schema_reset()?,
4554                    None => {
4555                        self.detach_projections(None)?;
4556                        self.create_synced_tables()?;
4557                        self.persist_schema_version()?;
4558                    }
4559                    Some(_) => {
4560                        self.detach_projections(None)?;
4561                        self.create_synced_tables()?;
4562                    }
4563                }
4564                // §7.4.2: recreation IS the boot for the in-memory core, so reload the
4565                // durable outbox the same-version path is about to replay. Only the
4566                // outbox is reloaded: the recovery below reads it, and the caller's
4567                // rollback snapshot already covers this field.
4568                self.outbox = self.load_outbox()?.into();
4569                // §7.1/§7.4.4: recover intrinsically codec-invalid persisted values at
4570                // this guarded boundary once the schema and marker agree. A bump went
4571                // through `run_schema_reset`, which performs the same recovery after
4572                // it creates the new physical tables and before its final replay.
4573                self.drop_unencodable_outbox(false, None)?;
4574                if marker == Some(self.schema.version)
4575                    && (!self.outbox.is_empty()
4576                        || !self.failed_commits.is_empty()
4577                        || self.has_acknowledged_rows()?)
4578                {
4579                    self.overlay_dirty.set(true);
4580                    self.rebuild_overlay()?;
4581                }
4582                self.prune_unknown_units(false)?;
4583                self.save_unit_scope_schema()?;
4584                // The conformance recreate is the in-memory equivalent of reopening
4585                // a durable client. Apply the same startup catch-up contract even
4586                // when the schema itself did not change.
4587                self.enqueue_startup_sync_if_needed()?;
4588                self.projection_pending_queue
4589                    .extend(self.collect_projection_pending()?);
4590                Ok(())
4591            })();
4592            self.opening_replica = false;
4593            let outcome = match guarded {
4594                Ok(()) => self
4595                    .conn
4596                    .execute_batch("COMMIT")
4597                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error).into()),
4598                Err(error) => Err(error),
4599            };
4600            if let Err(error) = outcome {
4601                if let Err(rollback) = self.conn.execute_batch("ROLLBACK") {
4602                    // Keep a failed rollback's typed storage classification.
4603                    let _ = Self::sqlite_failure(&self.storage_failure, rollback);
4604                }
4605                self.schema = prior_schema;
4606                self.restore(rollback);
4607                // Prepared insert statements were derived from the reverted schema.
4608                self.insert_sql.borrow_mut().clear();
4609                return Err(error);
4610            }
4611            if !self.security_preflight {
4612                self.drain_pending_evictions()?;
4613            }
4614            Ok(())
4615        })()
4616        .map_err(open_failure)
4617    }
4618
4619    fn enqueue_startup_sync_if_needed(&mut self) -> Result<(), String> {
4620        let startup_work = !self.stopped
4621            && (!self.outbox.is_empty()
4622                || self.has_acknowledged_rows()?
4623                || !self.load_pending_evictions()?.is_empty()
4624                || self
4625                    .stored(load_units(&self.conn))?
4626                    .iter()
4627                    .any(|unit| unit.status == UnitStatus::Active));
4628        if startup_work {
4629            self.sync_needed = true;
4630            self.sync_intent_queue.push_back(SyncIntent::Interactive);
4631        }
4632        Ok(())
4633    }
4634
4635    /// A native client persists schema-floor stops across process restarts.
4636    /// Once the running app already satisfies that floor, the persisted stop
4637    /// is only stale evidence from an older server round (for example, the
4638    /// server was restarted after catching up to an app that was ahead).
4639    /// Clear it and let the normal startup pull re-negotiate. If the server is
4640    /// still incompatible it will return the floor again in that first round.
4641    fn clear_satisfied_persisted_schema_floor(&mut self) -> Result<(), String> {
4642        let satisfied = self
4643            .schema_floor
4644            .as_ref()
4645            .and_then(|floor| floor.required_schema_version)
4646            .is_some_and(|required| self.schema.version >= required);
4647        if !satisfied {
4648            return Ok(());
4649        }
4650        self.delete_meta(SCHEMA_FLOOR_KEY)?;
4651        self.schema_floor = None;
4652        self.stopped = false;
4653        Ok(())
4654    }
4655
4656    /// RFC 0005 D1: discard an orphan or stale container at boot. The reset
4657    /// path already swept it; this covers a same-version or fresh-install open,
4658    /// which runs no reset and therefore no sweep — plus the D7 TTL, which only
4659    /// an aware binary can apply.
4660    fn reconcile_previous_version_at_boot(&self) -> Result<(), String> {
4661        let Some(replica_path) = self.previous_version_replica_path() else {
4662            return Ok(());
4663        };
4664        let max_age_ms = self
4665            .previous_version
4666            .filter(|config| config.enabled)
4667            .map(|config| config.max_age_ms);
4668        reconcile_previous_version_at_boot(
4669            &self.conn,
4670            &replica_path,
4671            self.schema.version,
4672            max_age_ms,
4673            self.clock_now_ms(),
4674        )
4675    }
4676
4677    /// RFC 0005 D3: the sibling container path, or `None` when the replica has
4678    /// no file — an in-memory replica returns an empty path, and a `file:` URI
4679    /// has no plain sibling path — so the feature resolves as off there.
4680    fn previous_version_replica_path(&self) -> Option<String> {
4681        let path = self.conn.path()?;
4682        if path.is_empty() || path.starts_with("file:") {
4683            return None;
4684        }
4685        Some(path.to_owned())
4686    }
4687
4688    /// §7.4.3 reset: whole-database local reset EXCEPT the outbox, clientId,
4689    /// and leaseState. Drops/recreates every synced table from the new
4690    /// schema, resets unit sync state (keeping registrations), clears
4691    /// the schema-floor stop state, rewrites the marker, drops outbox commits
4692    /// that cannot re-encode (§7.4.4), and replays the survivors on top.
4693    fn run_schema_reset(&mut self) -> Result<(), String> {
4694        self.begin_observation("syncular_schema_reset")?;
4695        let rollback = self.capture();
4696        let mut batch = ChangeAccumulator::default();
4697        let result = self
4698            .run_schema_reset_observed(&mut batch, true)
4699            .and_then(|()| self.finish_observation("syncular_schema_reset", batch));
4700        if let Err(error) = result {
4701            self.rollback_observation("syncular_schema_reset");
4702            self.restore(rollback);
4703            return Err(error);
4704        }
4705        // After the commit: a rolled-back reset keeps the in-flight round.
4706        self.cancel_sync_round();
4707        Ok(())
4708    }
4709
4710    fn run_log_epoch_reset(&mut self, log_epoch: &str) -> Result<Vec<String>, String> {
4711        if self.get_meta(LOG_EPOCH_KEY)?.is_none() {
4712            self.begin_observation("syncular_epoch_acquisition")?;
4713            let rollback = self.capture();
4714            if let Err(error) = self.conn.execute(
4715                "INSERT OR REPLACE INTO _syncular_meta(key,value) VALUES (?1,?2)",
4716                rusqlite::params![LOG_EPOCH_KEY, log_epoch],
4717            ) {
4718                self.rollback_observation("syncular_epoch_acquisition");
4719                return Err(Self::sqlite_failure(&self.storage_failure, error));
4720            }
4721            self.sync_needed = true;
4722            let batch = ChangeAccumulator {
4723                status: true,
4724                ..ChangeAccumulator::default()
4725            };
4726            if let Err(error) = self.finish_observation("syncular_epoch_acquisition", batch) {
4727                self.rollback_observation("syncular_epoch_acquisition");
4728                self.restore(rollback);
4729                return Err(error);
4730            }
4731            self.sync_intent_queue.push_back(SyncIntent::Interactive);
4732            return Ok(Vec::new());
4733        }
4734        let resets = self
4735            .stored(load_units(&self.conn))?
4736            .into_iter()
4737            .map(|unit| unit.id)
4738            .collect();
4739        self.begin_observation("syncular_log_epoch_reset")?;
4740        let rollback = self.capture();
4741        let mut batch = ChangeAccumulator::default();
4742        let result = self
4743            .run_schema_reset_observed(&mut batch, false)
4744            .and_then(|()| {
4745                self.conn
4746                    .execute(
4747                        "INSERT OR REPLACE INTO _syncular_meta(key,value) VALUES (?1,?2)",
4748                        rusqlite::params![LOG_EPOCH_KEY, log_epoch],
4749                    )
4750                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4751                self.sync_needed = true;
4752                batch.status = true;
4753                self.finish_observation("syncular_log_epoch_reset", batch)
4754            });
4755        if let Err(error) = result {
4756            self.rollback_observation("syncular_log_epoch_reset");
4757            self.restore(rollback);
4758            return Err(error);
4759        }
4760        self.cancel_sync_round();
4761        self.sync_intent_queue.push_back(SyncIntent::Interactive);
4762        Ok(resets)
4763    }
4764
4765    fn run_schema_reset_observed(
4766        &mut self,
4767        batch: &mut ChangeAccumulator,
4768        capture: bool,
4769    ) -> Result<(), String> {
4770        // §7.4.2: the reset is the only path that wipes local tables for a
4771        // version bump, and it rewrites the marker last. Re-read the marker
4772        // under this reset's transaction: a replica another process upgraded
4773        // meanwhile refuses here instead of being reset to this client's
4774        // older schema.
4775        read_local_schema_version(&self.conn, self.schema.version)
4776            .map_err(|error| error.to_string())?;
4777        // §7.4.3: a schema bump keeps every table whose generation or one of
4778        // its equivalent generations equals the persisted one; the log-epoch
4779        // reset keeps nothing. The previous
4780        // declaration evidence decides which units cover only kept tables.
4781        let mut kept = BTreeSet::new();
4782        let mut previous_declarations: Option<BTreeMap<String, BTreeMap<String, Value>>> = None;
4783        if capture {
4784            let persisted: BTreeMap<String, String> = self
4785                .get_meta(TABLE_GENERATIONS_KEY)?
4786                .map(|raw| serde_json::from_str(&raw))
4787                .transpose()
4788                .map_err(|_| "sync.local_corrupt: invalid persisted table generations".to_owned())?
4789                .unwrap_or_default();
4790            kept = self
4791                .schema
4792                .tables
4793                .iter()
4794                .filter(|table| {
4795                    table.generation.is_some()
4796                        && persisted.get(&table.name).is_some_and(|stored| {
4797                            table.generation.as_ref() == Some(stored)
4798                                || table.equivalent_generations.contains(stored)
4799                        })
4800                })
4801                .map(|table| table.name.clone())
4802                .collect();
4803            previous_declarations = self
4804                .get_meta("subscriptionScopeSchema")?
4805                .map(|raw| serde_json::from_str(&raw))
4806                .transpose()
4807                .map_err(|_| "sync.local_corrupt: invalid persisted scope schema".to_owned())?;
4808        }
4809        // Kept tables keep both halves and their row-level bookkeeping; the
4810        // projections of kept tables keep their storage.
4811        let mut kept_objects = BTreeSet::new();
4812        for table in self
4813            .schema
4814            .tables
4815            .iter()
4816            .filter(|table| kept.contains(&table.name))
4817        {
4818            kept_objects.insert(table.name.clone());
4819            kept_objects.insert(format!("_syncular_base_{}", table.name));
4820        }
4821        kept_objects.extend(self.detach_projections(Some(&kept))?);
4822        let kept_json = serde_json::to_string(&kept).expect("table names serialize");
4823        for sql in [
4824            "DELETE FROM _syncular_acked_rows WHERE tbl NOT IN (SELECT value FROM json_each(?1))",
4825            "DELETE FROM _syncular_row_deliveries WHERE tbl NOT IN (SELECT value FROM json_each(?1))",
4826        ] {
4827            self.conn
4828                .execute(sql, [&kept_json])
4829                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4830        }
4831        self.upgrading = true;
4832        self.upgrade_kept_tables = !kept.is_empty();
4833        batch.status = true;
4834        // RFC 0005 D6: classify the pending outbox against the NEW compiled
4835        // schema BEFORE the wipe, and record the advisory audit. This pass
4836        // drops nothing, so the audit sees the original pending intent; the
4837        // §7.4.4 send-time drop and the intrinsic value recovery later in this
4838        // reset are the paths that remove a commit. The classification is
4839        // shared with the send-time drop so the two cannot disagree about what
4840        // is incompatible.
4841        if self.previous_version.is_some_and(|config| config.enabled) {
4842            let previous_version = self
4843                .get_meta(LOCAL_SCHEMA_VERSION_KEY)?
4844                .and_then(|value| value.parse::<i32>().ok())
4845                .unwrap_or(self.schema.version);
4846            let pending = self
4847                .outbox
4848                .iter()
4849                .map(|commit| PendingCommitAudit {
4850                    commit_id: &commit.client_commit_id,
4851                    operations: commit_audit_operations(commit),
4852                })
4853                .collect::<Vec<_>>();
4854            crate::previous_version::write_previous_version_audit(
4855                &self.conn,
4856                &crate::previous_version::build_previous_version_audit(
4857                    &self.schema,
4858                    &pending,
4859                    previous_version,
4860                    self.schema.version,
4861                    self.clock_now_ms(),
4862                ),
4863            )?;
4864        }
4865        // RFC 0005 D5: the container lives in its own FILE, so the reset can
4866        // never reach it. Sweep first (unconditional — also on the log-epoch
4867        // reset, which captures nothing), then capture BEFORE the wipe drops
4868        // any row. A refused capture records its reason and leaves no file.
4869        if let Some(replica_path) = self.previous_version_replica_path() {
4870            sweep_previous_version_container(&self.conn, &replica_path)?;
4871            if capture {
4872                if let Some(config) = self.previous_version.filter(|config| config.enabled) {
4873                    let previous_version = self
4874                        .get_meta(LOCAL_SCHEMA_VERSION_KEY)?
4875                        .and_then(|value| value.parse::<i32>().ok())
4876                        .unwrap_or(self.schema.version);
4877                    capture_previous_version_from_replica(
4878                        &self.conn,
4879                        &replica_path,
4880                        previous_version,
4881                        self.schema.version,
4882                        &config,
4883                        self.clock_now_ms(),
4884                    )?;
4885                }
4886            }
4887        }
4888        for table in self
4889            .schema
4890            .tables
4891            .iter()
4892            .filter(|table| !kept.contains(&table.name))
4893        {
4894            batch.table(&table.name);
4895        }
4896        for unit in self.stored(load_units(&self.conn))? {
4897            self.record_unit_windows(batch, &unit)?;
4898        }
4899        if capture {
4900            self.prune_unknown_units(true)?;
4901        }
4902        // The per-table insert SQL is derived from the OLD column lists.
4903        self.insert_sql.borrow_mut().clear();
4904        self.overlay_dirty.set(true);
4905        // Drop every synced table (base + visible) that currently exists —
4906        // discovered from sqlite_master so a bump that adds/removes tables is
4907        // handled. Bookkeeping tables (`_syncular_outbox/_units/_meta`
4908        // and the blob cache) are preserved; base tables are `_syncular_base_*`
4909        // so they are matched explicitly, not by the bookkeeping filter.
4910        // Drop virtual tables first so SQLite removes every FTS shadow table
4911        // atomically instead of the generic discovery tearing it apart.
4912        let virtual_tables: Vec<String> = {
4913            let mut stmt = self
4914                .conn
4915                .prepare(
4916                    "SELECT name FROM sqlite_master WHERE type = 'table' AND sql LIKE 'CREATE VIRTUAL TABLE%'",
4917                )
4918                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4919            let rows = stmt
4920                .query_map([], |row| row.get::<_, String>(0))
4921                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4922            rows.filter_map(Result::ok)
4923                .filter(|name| is_synced_table_name(name) && !kept_objects.contains(name))
4924                .collect()
4925        };
4926        for name in virtual_tables {
4927            self.conn
4928                .execute_batch(&format!(
4929                    "DROP TABLE IF EXISTS {}",
4930                    quote_ident(&format!("_syncular_fts_{name}"))
4931                ))
4932                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4933            self.conn
4934                .execute(&format!("DROP TABLE IF EXISTS {}", quote_ident(&name)), [])
4935                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4936        }
4937        let existing: Vec<String> = {
4938            let mut stmt = self
4939                .conn
4940                .prepare("SELECT name FROM sqlite_master WHERE type = 'table'")
4941                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4942            let rows = stmt
4943                .query_map([], |row| row.get::<_, String>(0))
4944                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4945            rows.filter_map(Result::ok)
4946                .filter(|name| is_synced_table_name(name) && !kept_objects.contains(name))
4947                .collect()
4948        };
4949        for name in &existing {
4950            if let Some(table) = name.strip_prefix("_syncular_base_") {
4951                batch.table(table);
4952            } else if !name.starts_with("_syncular_") {
4953                batch.table(name);
4954            }
4955        }
4956        for name in existing {
4957            self.conn
4958                .execute(&format!("DROP TABLE IF EXISTS {}", quote_ident(&name)), [])
4959                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
4960        }
4961        // Recreate the synced tables from the NEW schema.
4962        self.create_synced_tables()?;
4963        // Reset the sync state of every unit that covers a table the reset
4964        // did not keep, under the previous declarations or the new schema,
4965        // keeping the registration.
4966        let keep_units = match &previous_declarations {
4967            Some(previous) if !kept.is_empty() => self
4968                .stored(load_units(&self.conn))?
4969                .into_iter()
4970                .filter(|unit| {
4971                    previous.iter().all(|(name, old)| {
4972                        kept.contains(name) || !unit.scopes.keys().all(|v| old.contains_key(v))
4973                    }) && self
4974                        .schema
4975                        .tables
4976                        .iter()
4977                        .all(|table| kept.contains(&table.name) || !covers(table, &unit.scopes))
4978                })
4979                .map(|unit| unit.id)
4980                .collect(),
4981            _ => BTreeSet::new(),
4982        };
4983        // §7.4.3 restriction: an active unit that is not kept and whose rows
4984        // of a kept table are complete through a cursor C (its restriction's,
4985        // its post-bootstrap P, or the replica cursor it is live under)
4986        // bootstraps only its other covered tables and joins at C.
4987        let restrictions = if capture {
4988            let replica = self.stored(replica_cursor(&self.conn))?;
4989            let mut restrictions = BTreeMap::new();
4990            for unit in self.stored(load_units(&self.conn))? {
4991                if keep_units.contains(&unit.id) || unit.status != UnitStatus::Active {
4992                    continue;
4993                }
4994                let cursor = match (&unit.restriction, unit.cursor) {
4995                    (Some(restriction), _) => restriction.cursor,
4996                    (None, Some(cursor)) if cursor >= 0 && unit.bootstrap_state.is_none() => cursor,
4997                    (None, None) if replica >= 0 => replica,
4998                    _ => continue,
4999                };
5000                let covered: Vec<&String> = self
5001                    .schema
5002                    .tables
5003                    .iter()
5004                    .filter(|table| covers(table, &unit.scopes))
5005                    .map(|table| &table.name)
5006                    .collect();
5007                let mut tables: Vec<String> = covered
5008                    .iter()
5009                    .filter(|name| {
5010                        !kept.contains(**name)
5011                            || unit
5012                                .restriction
5013                                .as_ref()
5014                                .is_some_and(|restriction| restriction.tables.contains(name))
5015                    })
5016                    .map(|name| (*name).clone())
5017                    .collect();
5018                if tables.is_empty() || tables.len() == covered.len() {
5019                    continue;
5020                }
5021                tables.sort_by(|a, b| a.encode_utf16().cmp(b.encode_utf16()));
5022                restrictions.insert(unit.id, UnitRestriction { cursor, tables });
5023            }
5024            Some(restrictions)
5025        } else {
5026            None
5027        };
5028        reset_units(&self.conn, &keep_units, restrictions.as_ref())
5029            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5030        // The stop state is over: this client now ships a servable schema.
5031        self.stopped = false;
5032        self.schema_floor = None;
5033        self.delete_meta(SCHEMA_FLOOR_KEY)?;
5034        // Rewrite the marker LAST so a crash mid-reset re-runs the reset.
5035        self.persist_schema_version()?;
5036        self.save_unit_scope_schema()?;
5037        // §7.1/§7.4.4: the previous-version capture and audit above saw the
5038        // original pending intent; the synced tables now carry the new schema, so
5039        // recover intrinsically codec-invalid persisted values here, before the
5040        // final replay. A pending upsert that names a column the new schema
5041        // removed stays pending for the send-time `drop_incompatible_outbox`
5042        // prepass. The reset wrapper snapshots and restores the outbox,
5043        // rejections, and change queues, so a failed commit rolls this recovery
5044        // back with the rest of the reset.
5045        // §7.4.4: the enclosing reset observation owns the publication, so the
5046        // recovery contributes its rejection, outcome, and table domains to it.
5047        self.drop_unencodable_outbox(false, Some(batch))?;
5048        // Re-apply the surviving outbox optimistically over the empty tables.
5049        self.rebuild_overlay()?;
5050        Ok(())
5051    }
5052
5053    /// §7.4.4 send-time prepass: a persisted upsert whose values reference a
5054    /// column the current schema lacks (or a removed table) cannot be encoded
5055    /// (`commit_audit_operations` inspects upserts, so a value-free delete stays
5056    /// encodable and is validated by the server), nor can an insert-intent
5057    /// upsert that lacks a non-nullable column (§7.1, the audit's
5058    /// `missing-required-column`). Drop the commit, undo
5059    /// its optimistic projection, and raise a client-local
5060    /// `sync.outbox_incompatible` rejection.
5061    fn drop_incompatible_outbox(&mut self) -> Result<bool, String> {
5062        // §8.8: only the commits this round pushes; a held commit waits.
5063        let incompatible = self
5064            .outbox
5065            .iter()
5066            .take(self.pushable_commits())
5067            .filter(|commit| {
5068                first_incompatibility(&self.schema, &commit_audit_operations(commit)).is_some()
5069            })
5070            .cloned()
5071            .collect::<Vec<_>>();
5072        if incompatible.is_empty() {
5073            return Ok(false);
5074        }
5075        self.drop_outbox_commits(
5076            &incompatible,
5077            OUTBOX_INCOMPATIBLE_CODE,
5078            "the persisted commit cannot encode under the current schema",
5079        )?;
5080        Ok(true)
5081    }
5082
5083    /// §7.4.4 incompatible-commit path, also taken by a refused blob upload
5084    /// (§5.9.7) with the server's code: reject every operation of `commits`,
5085    /// remove them from the outbox, and undo their optimistic rows.
5086    fn drop_outbox_commits(
5087        &mut self,
5088        incompatible: &[Arc<OutboxCommit>],
5089        code: &str,
5090        message: &str,
5091    ) -> Result<(), String> {
5092        // §7.4.4: one observation covers the durable outcome writes, the outbox
5093        // removal, the in-memory drop, and the overlay rebuild, so a storage
5094        // fault leaves the replica and the client unchanged and publishes no
5095        // change; a successful drop publishes exactly one batch carrying the
5096        // rejections, outcomes, status, and the tables whose projection changed.
5097        let rollback = self.capture();
5098        let owns_transaction = self.conn.is_autocommit();
5099        self.begin_observation("syncular_outbox_drop")?;
5100        let mut batch = ChangeAccumulator::default();
5101        let dropped = (|| -> Result<(), String> {
5102            let mut rejections = Vec::new();
5103            for commit in incompatible {
5104                let results = commit
5105                    .ops
5106                    .iter()
5107                    .enumerate()
5108                    .map(|(op_index, operation)| {
5109                        let rejection = RejectionRecord {
5110                            client_commit_id: commit.client_commit_id.clone(),
5111                            op_index: op_index as i32,
5112                            code: code.to_owned(),
5113                            message: message.to_owned(),
5114                            retryable: false,
5115                            details: None,
5116                            operation: Some(CommitOperation::from(operation)),
5117                        };
5118                        rejections.push(rejection.clone());
5119                        CommitOperationOutcome::Error { rejection }
5120                    })
5121                    .collect::<Vec<_>>();
5122                self.persist_commit_outcome(
5123                    &commit.client_commit_id,
5124                    CommitOutcomeStatus::Rejected,
5125                    &results,
5126                    Some(&commit.ops),
5127                )?;
5128                self.leave_through(&commit.client_commit_id);
5129                self.delete_outbox_persisted(&commit.client_commit_id)?;
5130                // A removed table has no local projection to invalidate; every
5131                // surviving table the dropped commit touched does.
5132                for operation in &commit.ops {
5133                    if self.schema.table(&operation.table).is_some() {
5134                        batch.table(&operation.table);
5135                    }
5136                }
5137            }
5138            self.prune_commit_outcomes()?;
5139            let incompatible_ids = incompatible
5140                .iter()
5141                .map(|commit| commit.client_commit_id.as_str())
5142                .collect::<BTreeSet<_>>();
5143            self.outbox
5144                .retain(|commit| !incompatible_ids.contains(commit.client_commit_id.as_str()));
5145            self.rejections.extend(rejections);
5146            // The dropped commits' purely-optimistic rows are undone: the
5147            // visible projection is re-derived from the surviving base + outbox.
5148            self.overlay_dirty.set(true);
5149            self.rebuild_overlay()?;
5150            batch.status = true;
5151            batch.rejections = true;
5152            batch.outcomes = true;
5153            Ok(())
5154        })();
5155        let result = dropped.and_then(|()| self.finish_observation("syncular_outbox_drop", batch));
5156        if let Err(error) = result {
5157            // An outer RELEASE is the COMMIT. Roll back that transaction
5158            // directly: retrying RELEASE after ROLLBACK TO still needs the
5159            // reader's lock. A nested observation only rolls back its savepoint.
5160            if owns_transaction {
5161                if let Err(rollback) = self.conn.execute_batch("ROLLBACK") {
5162                    let mut failure = self.storage_failure.borrow_mut();
5163                    let failure =
5164                        failure.get_or_insert_with(|| QueryReadFailure::from(error.clone()));
5165                    failure.rollback_failure = Some(Box::new(QueryReadFailure::from(rollback)));
5166                }
5167            } else {
5168                self.rollback_observation("syncular_outbox_drop");
5169            }
5170            self.restore(rollback);
5171            return Err(error);
5172        }
5173        Ok(())
5174    }
5175
5176    /// §7.4.3: (re)create the base + visible table pair for every synced
5177    /// table in the CURRENT schema (idempotent — `IF NOT EXISTS`).
5178    fn create_synced_tables(&self) -> Result<(), String> {
5179        for table in &self.schema.tables {
5180            // The base half + the visible half form the synced-table pair. An
5181            // index name is global in SQLite, so the base half's indexes are
5182            // name-prefixed (`_syncular_base_<index>`) to stay distinct.
5183            for (full, index_prefix) in [
5184                (base_table(&table.name), "_syncular_base_"),
5185                (visible_table(&table.name), ""),
5186            ] {
5187                let mut cols: Vec<String> =
5188                    table.columns.iter().map(|c| quote_ident(&c.name)).collect();
5189                cols.push("\"_syncular_version\" INTEGER NOT NULL".to_owned());
5190                cols.extend(
5191                    table
5192                        .sealed_columns()
5193                        .iter()
5194                        .map(|name| format!("{} TEXT", quote_ident(name))),
5195                );
5196                let sql = format!(
5197                    "CREATE TABLE IF NOT EXISTS {full} ({} , PRIMARY KEY ({}))",
5198                    cols.join(", "),
5199                    quote_ident(&table.primary_key)
5200                );
5201                self.conn
5202                    .execute(&sql, [])
5203                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5204                // §5.11: a replica created before sealed apply gains the
5205                // reserved columns in place, on both halves in the same order,
5206                // so data, indexes and the FTS projection stay.
5207                for name in table.sealed_columns() {
5208                    let present: bool = self
5209                        .conn
5210                        .query_row(
5211                            "SELECT EXISTS(SELECT 1 FROM pragma_table_info(?1) WHERE name = ?2)",
5212                            rusqlite::params![format!("{index_prefix}{}", table.name), name],
5213                            |row| row.get(0),
5214                        )
5215                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5216                    if !present {
5217                        self.conn
5218                            .execute(
5219                                &format!(
5220                                    "ALTER TABLE {full} ADD COLUMN {} TEXT",
5221                                    quote_ident(name)
5222                                ),
5223                                [],
5224                            )
5225                            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5226                    }
5227                }
5228                // The reveal at every round start reads the sealed rows of the
5229                // base half through this partial index.
5230                if table.has_encrypted_columns() && !index_prefix.is_empty() {
5231                    self.conn
5232                        .execute(
5233                            &format!(
5234                                "CREATE INDEX IF NOT EXISTS {} ON {full} (\"_sync_sealed_key\") WHERE \"_sync_sealed_key\" IS NOT NULL",
5235                                quote_ident(&format!("_syncular_sealed_{}", table.name))
5236                            ),
5237                            [],
5238                        )
5239                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5240                }
5241            }
5242        }
5243        // §7.4.3 declared indexes: reconciled in place on both halves (the
5244        // base half's names carry the `_syncular_base_` prefix) at every open
5245        // and at the end of every reset. `localIndexes` records the declared
5246        // names Syncular created; only those are ever dropped.
5247        let recorded: BTreeMap<String, BTreeSet<String>> = match self.get_meta("localIndexes")? {
5248            Some(raw) => serde_json::from_str(&raw)
5249                .map_err(|_| "sync.local_corrupt: invalid persisted local indexes".to_owned())?,
5250            // A replica without the record: every declared index that exists
5251            // counts as created by Syncular, so nothing is stale.
5252            None => BTreeMap::new(),
5253        };
5254        let declared: BTreeMap<String, BTreeSet<String>> = self
5255            .schema
5256            .tables
5257            .iter()
5258            .filter(|table| !table.indexes.is_empty())
5259            .map(|table| {
5260                let names = table.indexes.iter().map(|index| index.name.clone());
5261                (table.name.clone(), names.collect())
5262            })
5263            .collect();
5264        for (table, names) in &recorded {
5265            for name in names.iter().filter(|name| {
5266                !declared
5267                    .get(table)
5268                    .is_some_and(|declared| declared.contains(*name))
5269            }) {
5270                self.stored(self.conn.execute_batch(&format!(
5271                    "DROP INDEX IF EXISTS {}; DROP INDEX IF EXISTS {}",
5272                    quote_ident(name),
5273                    quote_ident(&format!("_syncular_base_{name}"))
5274                )))?;
5275            }
5276        }
5277        for table in &self.schema.tables {
5278            for index in &table.indexes {
5279                for (owner, name) in [
5280                    (
5281                        format!("_syncular_base_{}", table.name),
5282                        format!("_syncular_base_{}", index.name),
5283                    ),
5284                    (table.name.clone(), index.name.clone()),
5285                ] {
5286                    let current: Option<(String, bool, bool)> = self.stored(
5287                        self.conn
5288                            .query_row(
5289                                "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",
5290                                [&name],
5291                                |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
5292                            )
5293                            .optional(),
5294                    )?;
5295                    if let Some((current_owner, unique, partial)) = current {
5296                        let mut stmt = self
5297                            .stored(self.conn.prepare(
5298                                "SELECT name FROM pragma_index_info(?1) ORDER BY seqno",
5299                            ))?;
5300                        let columns = self.stored(
5301                            self.stored(
5302                                stmt.query_map([&name], |row| row.get::<_, Option<String>>(0)),
5303                            )?
5304                            .collect::<Result<Vec<_>, _>>(),
5305                        )?;
5306                        if current_owner == owner
5307                            && unique == index.unique
5308                            && !partial
5309                            && columns
5310                                .iter()
5311                                .map(Option::as_deref)
5312                                .eq(index.columns.iter().map(|column| Some(column.as_str())))
5313                        {
5314                            continue;
5315                        }
5316                        self.stored(
5317                            self.conn
5318                                .execute(&format!("DROP INDEX {}", quote_ident(&name)), []),
5319                        )?;
5320                    }
5321                    self.stored(self.conn.execute(
5322                        &format!(
5323                            "CREATE {}INDEX {} ON {} ({})",
5324                            if index.unique { "UNIQUE " } else { "" },
5325                            quote_ident(&name),
5326                            quote_ident(&owner),
5327                            index
5328                                .columns
5329                                .iter()
5330                                .map(|column| quote_ident(column))
5331                                .collect::<Vec<_>>()
5332                                .join(", ")
5333                        ),
5334                        [],
5335                    ))?;
5336                }
5337            }
5338        }
5339        self.set_meta(
5340            "localIndexes",
5341            &serde_json::to_string(&declared).expect("index names serialize"),
5342        )?;
5343        self.open_projections()
5344    }
5345
5346    fn create_fts_storage(
5347        &self,
5348        name: &str,
5349        columns: &str,
5350        tokenize: &str,
5351        options: &str,
5352    ) -> Result<(), String> {
5353        let tokenizer = tokenize.replace('\'', "''");
5354        let sql = format!(
5355            "CREATE VIRTUAL TABLE IF NOT EXISTS {} USING fts5({} UNINDEXED, {columns}, tokenize='{tokenizer}'{options})",
5356            quote_ident(name),
5357            quote_ident(FTS_SOURCE_ID_COLUMN),
5358        );
5359        self.conn
5360            .execute(&sql, [])
5361            .map_err(|error| format!("cannot create local FTS5 projection {name:?}: {error}"))?;
5362        let mapping = quote_ident(&format!("_syncular_fts_{name}"));
5363        self.stored(self.conn.execute_batch(&format!("CREATE TABLE IF NOT EXISTS {mapping}(id INTEGER PRIMARY KEY, source_id TEXT NOT NULL UNIQUE)")))
5364    }
5365
5366    // -- persistence write-through --------------------------------------------
5367
5368    fn persist_outbox_insert(&self, commit: &OutboxCommit) -> Result<(), String> {
5369        let ops: Vec<Value> = commit
5370            .ops
5371            .iter()
5372            .map(|op| {
5373                let mut entry = serde_json::json!({
5374                    "op": if op.upsert { "upsert" } else { "delete" },
5375                    "table": op.table,
5376                    "rowId": op.row_id,
5377                    "baseVersion": op.base_version,
5378                    "values": op.values.clone().map(Value::Object),
5379                });
5380                if op.insert {
5381                    entry["insert"] = Value::Bool(true);
5382                }
5383                entry
5384            })
5385            .collect();
5386        self.conn
5387            .execute(
5388                "INSERT OR REPLACE INTO _syncular_outbox (commit_id, ops_json, created_at_ms, attempted) VALUES (?1, ?2, ?3, 0)",
5389                rusqlite::params![
5390                    commit.client_commit_id,
5391                    Value::Array(ops).to_string(),
5392                    self.clock_now_ms()
5393                ],
5394            )
5395            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5396        for operation in &commit.ops {
5397            let Some(values) = &operation.values else {
5398                continue;
5399            };
5400            let Some(table) = self.schema.table(&operation.table) else {
5401                continue;
5402            };
5403            for column in table
5404                .columns
5405                .iter()
5406                .filter(|column| column.ty == ColumnType::BlobRef)
5407            {
5408                let Some(Value::String(raw)) = values.get(&column.name) else {
5409                    continue;
5410                };
5411                let Ok(blob_ref) = serde_json::from_str::<Value>(raw) else {
5412                    continue;
5413                };
5414                let Some(blob_id) = blob_ref.get("blobId").and_then(Value::as_str) else {
5415                    continue;
5416                };
5417                self.conn
5418                    .execute(
5419                        "INSERT OR IGNORE INTO _syncular_blob_commit_refs(commit_id, blob_id)
5420                         SELECT ?1, ?2 WHERE EXISTS (SELECT 1 FROM _syncular_blobs WHERE blob_id = ?2)",
5421                        rusqlite::params![commit.client_commit_id, blob_id],
5422                    )
5423                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5424            }
5425        }
5426        Ok(())
5427    }
5428
5429    fn delete_outbox_persisted(&self, client_commit_id: &str) -> Result<(), String> {
5430        self.conn
5431            .execute(
5432                "DELETE FROM _syncular_blob_commit_refs WHERE commit_id = ?1",
5433                rusqlite::params![client_commit_id],
5434            )
5435            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5436        self.conn
5437            .execute(
5438                "DELETE FROM _syncular_outbox WHERE commit_id = ?1",
5439                rusqlite::params![client_commit_id],
5440            )
5441            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5442        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)", [])
5443            .map(|_| ())
5444            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
5445    }
5446
5447    fn outcome_status_name(status: CommitOutcomeStatus) -> &'static str {
5448        match status {
5449            CommitOutcomeStatus::Applied => "applied",
5450            CommitOutcomeStatus::Cached => "cached",
5451            CommitOutcomeStatus::Conflict => "conflict",
5452            // §7.2.1: a replaced commit is stored as a decided rejection.
5453            CommitOutcomeStatus::Rejected | CommitOutcomeStatus::Replaced => "rejected",
5454        }
5455    }
5456
5457    fn outcome_resolution_name(resolution: CommitOutcomeResolution) -> &'static str {
5458        match resolution {
5459            CommitOutcomeResolution::Active => "active",
5460            CommitOutcomeResolution::ResolvedKeepServer => "resolved_keep_server",
5461            CommitOutcomeResolution::Superseded => "superseded",
5462            CommitOutcomeResolution::Dismissed => "dismissed",
5463        }
5464    }
5465
5466    fn parse_outcome_status(value: &str) -> Result<CommitOutcomeStatus, String> {
5467        match value {
5468            "applied" => Ok(CommitOutcomeStatus::Applied),
5469            "cached" => Ok(CommitOutcomeStatus::Cached),
5470            "conflict" => Ok(CommitOutcomeStatus::Conflict),
5471            "rejected" => Ok(CommitOutcomeStatus::Rejected),
5472            _ => Err(format!("invalid persisted commit outcome status {value:?}")),
5473        }
5474    }
5475
5476    fn parse_outcome_resolution(value: &str) -> Result<CommitOutcomeResolution, String> {
5477        match value {
5478            "active" => Ok(CommitOutcomeResolution::Active),
5479            "resolved_keep_server" => Ok(CommitOutcomeResolution::ResolvedKeepServer),
5480            "superseded" => Ok(CommitOutcomeResolution::Superseded),
5481            "dismissed" => Ok(CommitOutcomeResolution::Dismissed),
5482            _ => Err(format!(
5483                "invalid persisted commit outcome resolution {value:?}"
5484            )),
5485        }
5486    }
5487
5488    fn persist_commit_outcome(
5489        &self,
5490        client_commit_id: &str,
5491        status: CommitOutcomeStatus,
5492        results: &[CommitOperationOutcome],
5493        operations: Option<&[OutboxOp]>,
5494    ) -> Result<(), String> {
5495        let results_json = serde_json::to_string(results).map_err(|error| error.to_string())?;
5496        let operations_json = operations
5497            .map(|items| {
5498                serde_json::to_string(&items.iter().map(CommitOperation::from).collect::<Vec<_>>())
5499            })
5500            .transpose()
5501            .map_err(|error| error.to_string())?;
5502        self.conn
5503            .execute(
5504                "INSERT INTO _syncular_commit_outcomes (
5505                   client_commit_id, status, recorded_at_ms, results_json,
5506                   operations_json, resolution
5507                 ) VALUES (?1, ?2, ?3, ?4, ?5, 'active')",
5508                rusqlite::params![
5509                    client_commit_id,
5510                    Self::outcome_status_name(status),
5511                    self.clock_now_ms(),
5512                    results_json,
5513                    operations_json
5514                ],
5515            )
5516            .map(|_| ())
5517            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
5518    }
5519
5520    /// §7.2: the journal holds a stored cell only in its canonical shape. A cell
5521    /// the byte-envelope rule refuses cannot be journaled verbatim.
5522    fn stored_cell_is_representable(cell: &Value) -> bool {
5523        cell.is_null()
5524            || cell.is_string()
5525            || cell.is_boolean()
5526            || cell.is_number()
5527            || is_canonical_bytes_envelope(cell)
5528    }
5529
5530    fn stored_row_is_representable(value: &Value) -> bool {
5531        value
5532            .as_object()
5533            .is_some_and(|row| row.values().all(Self::stored_cell_is_representable))
5534    }
5535
5536    fn stored_operation_is_representable(value: &Value) -> bool {
5537        value.get("table").is_some_and(Value::is_string)
5538            && value.get("rowId").is_some_and(Value::is_string)
5539            && value.get("baseVersion").is_none_or(|v| {
5540                v.as_i64()
5541                    .is_some_and(|n| n.unsigned_abs() <= MAX_JS_SAFE_INTEGER)
5542            })
5543            && match value.get("op").and_then(Value::as_str) {
5544                Some("upsert") => {
5545                    value
5546                        .get("values")
5547                        .is_some_and(Self::stored_row_is_representable)
5548                        && value
5549                            .get("insert")
5550                            .is_none_or(|insert| *insert == Value::Bool(true))
5551                }
5552                Some("delete") => value.get("values").is_none() && value.get("insert").is_none(),
5553                _ => false,
5554            }
5555    }
5556
5557    /// §7.2/§7.4.4: a dropped commit keeps its operation envelope in the journal
5558    /// only when the journal reader accepts the serialized operation, which is the
5559    /// rule `outcome_from_row` applies to this same row later.
5560    fn outbox_op_is_journalable(operation: &OutboxOp) -> bool {
5561        serde_json::to_value(CommitOperation::from(operation))
5562            .is_ok_and(|value| Self::stored_operation_is_representable(&value))
5563    }
5564
5565    /// §7.2.1: the one predicate for a replaced commit: a rejection whose
5566    /// every result is `client.commit_replaced` and that names its replacement.
5567    fn is_replaced(outcome: &CommitOutcome) -> bool {
5568        outcome.status == CommitOutcomeStatus::Rejected
5569            && outcome.replacement_client_commit_id.is_some()
5570            && !outcome.results.is_empty()
5571            && outcome.results.iter().all(|result| {
5572                matches!(result, CommitOperationOutcome::Error { rejection }
5573                    if rejection.code == COMMIT_REPLACED_CODE)
5574            })
5575    }
5576
5577    /// §7.2.1: `commitOutcomes` and `commitDelivery` report a replaced
5578    /// commit as `replaced`; every other journal surface reads the rejection.
5579    fn reported_outcome(mut outcome: CommitOutcome) -> CommitOutcome {
5580        if Self::is_replaced(&outcome) {
5581            outcome.status = CommitOutcomeStatus::Replaced;
5582        }
5583        outcome
5584    }
5585
5586    fn outcome_from_row(row: StoredCommitOutcomeRow) -> Result<CommitOutcome, String> {
5587        let StoredCommitOutcomeRow {
5588            sequence,
5589            client_commit_id,
5590            status,
5591            recorded_at_ms,
5592            results_json,
5593            operations_json,
5594            resolution,
5595            resolved_at_ms,
5596            replacement_client_commit_id,
5597        } = row;
5598        if sequence.unsigned_abs() > MAX_JS_SAFE_INTEGER
5599            || recorded_at_ms.unsigned_abs() > MAX_JS_SAFE_INTEGER
5600            || resolved_at_ms.is_some_and(|value| value.unsigned_abs() > MAX_JS_SAFE_INTEGER)
5601        {
5602            return Err("sync.local_corrupt: persisted commit outcome is invalid".to_owned());
5603        }
5604        let invalid = || "sync.local_corrupt: persisted commit outcome is invalid".to_owned();
5605        let stored: Vec<Value> = serde_json::from_str(&results_json).map_err(|_| invalid())?;
5606        for result in &stored {
5607            let nested = match result.get("status").and_then(Value::as_str) {
5608                Some("conflict") => result.get("conflict"),
5609                Some("error") => result.get("rejection"),
5610                _ => None,
5611            };
5612            if nested
5613                .and_then(|record| record.get("operation"))
5614                .is_some_and(|op| !Self::stored_operation_is_representable(op))
5615                || (result.get("status").and_then(Value::as_str) == Some("conflict")
5616                    && nested
5617                        .and_then(|record| record.get("serverRow"))
5618                        .is_some_and(|row| !Self::stored_row_is_representable(row)))
5619            {
5620                return Err(invalid());
5621            }
5622        }
5623        let results: Vec<CommitOperationOutcome> =
5624            serde_json::from_value(Value::Array(stored)).map_err(|_| invalid())?;
5625        let has_conflict = results
5626            .iter()
5627            .any(|result| matches!(result, CommitOperationOutcome::Conflict { .. }));
5628        let has_error = results
5629            .iter()
5630            .any(|result| matches!(result, CommitOperationOutcome::Error { .. }));
5631        let status = Self::parse_outcome_status(&status).map_err(|_| invalid())?;
5632        let redacted = results.is_empty() && operations_json.is_none();
5633        if match status {
5634            CommitOutcomeStatus::Applied | CommitOutcomeStatus::Cached => has_conflict || has_error,
5635            CommitOutcomeStatus::Replaced => true,
5636            CommitOutcomeStatus::Conflict => !(has_conflict || redacted),
5637            CommitOutcomeStatus::Rejected => has_conflict || !(has_error || redacted),
5638        } {
5639            return Err(invalid());
5640        }
5641        let operations: Option<Vec<CommitOperation>> = operations_json
5642            .map(|raw| {
5643                let stored: Vec<Value> = serde_json::from_str(&raw).map_err(|_| invalid())?;
5644                if !stored.iter().all(Self::stored_operation_is_representable) {
5645                    return Err(invalid());
5646                }
5647                serde_json::from_value(Value::Array(stored)).map_err(|_| invalid())
5648            })
5649            .transpose()?;
5650        for result in &results {
5651            match result {
5652                CommitOperationOutcome::Conflict { conflict }
5653                    if conflict.server_version.unsigned_abs() > MAX_JS_SAFE_INTEGER =>
5654                {
5655                    return Err("sync.local_corrupt: persisted commit outcome is invalid".to_owned())
5656                }
5657                CommitOperationOutcome::Error { rejection } => {
5658                    if let Some(details) = &rejection.details {
5659                        let encoded = serde_json::to_string(details).map_err(|_| {
5660                            "sync.local_corrupt: persisted commit outcome is invalid".to_owned()
5661                        })?;
5662                        RejectionDetails::parse(&encoded).map_err(|_| {
5663                            "sync.local_corrupt: persisted commit outcome is invalid".to_owned()
5664                        })?;
5665                    }
5666                }
5667                _ => {}
5668            }
5669        }
5670        Ok(CommitOutcome {
5671            sequence,
5672            client_commit_id,
5673            status,
5674            recorded_at_ms,
5675            results,
5676            operations,
5677            retained_rows: None,
5678            resolution: Self::parse_outcome_resolution(&resolution)?,
5679            resolved_at_ms,
5680            replacement_client_commit_id,
5681        })
5682    }
5683
5684    /// Resolve declared unique keys through SQLite, including affinity and NULL semantics.
5685    fn unique_conflicts(
5686        &self,
5687        table: &TableSchema,
5688        values: &Map<String, Value>,
5689        base: bool,
5690    ) -> Result<Vec<RetainedUniqueConflict>, String> {
5691        let source = if base {
5692            base_table(&table.name)
5693        } else {
5694            visible_table(&table.name)
5695        };
5696        let mut conflicts = Vec::new();
5697        for index in table.indexes.iter().filter(|index| index.unique) {
5698            let mut params = vec![json_param_to_sql(
5699                values.get(&table.primary_key).ok_or("sync.local_corrupt")?,
5700            )?];
5701            for name in &index.columns {
5702                let column = table
5703                    .columns
5704                    .iter()
5705                    .find(|column| column.name == *name)
5706                    .ok_or("sync.local_corrupt")?;
5707                let cell = json_to_column_value(column, values.get(name))?;
5708                params.push(owned_sql_value(RowParam::Cell(&cell))?);
5709            }
5710            let sql = format!(
5711                "SELECT * FROM {source} WHERE {} != ? AND {}",
5712                quote_ident(&table.primary_key),
5713                index
5714                    .columns
5715                    .iter()
5716                    .map(|column| format!("{} = ?", quote_ident(column)))
5717                    .collect::<Vec<_>>()
5718                    .join(" AND ")
5719            );
5720            let mut statement = self
5721                .conn
5722                .prepare_cached(&sql)
5723                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5724            let records = statement
5725                .query_map(rusqlite::params_from_iter(params), |record| {
5726                    let values = table
5727                        .columns
5728                        .iter()
5729                        .enumerate()
5730                        .map(|(index, column)| {
5731                            let value = sql_ref_to_json(column, record.get_ref(index)?);
5732                            json_to_column_value(column, Some(&value)).map_err(|message| {
5733                                rusqlite::Error::ToSqlConversionFailure(message.into())
5734                            })
5735                        })
5736                        .collect::<Result<Row, _>>()?;
5737                    Ok((values, record.get::<_, i64>(table.columns.len())?))
5738                })
5739                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5740            for record in records {
5741                let (row, version) =
5742                    record.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5743                let row_id = render_row_id_json(Some(&column_value_to_json(&row[table.pk_index])))?;
5744                conflicts.push(RetainedUniqueConflict {
5745                    index: index.name.clone(),
5746                    columns: index.columns.clone(),
5747                    row_id,
5748                    server_row: table
5749                        .columns
5750                        .iter()
5751                        .zip(&row)
5752                        .map(|(column, value)| (column.name.clone(), column_value_to_json(value)))
5753                        .collect(),
5754                    server_version: version,
5755                });
5756            }
5757        }
5758        Ok(conflicts)
5759    }
5760
5761    fn attach_retained_rows(&self, mut outcome: CommitOutcome) -> Result<CommitOutcome, String> {
5762        if let Some((commit, initial)) = self
5763            .failed_commits
5764            .iter()
5765            .find(|(commit, _)| commit.client_commit_id == outcome.client_commit_id)
5766        {
5767            let mut rows = Vec::new();
5768            for operation in &commit.ops {
5769                // A table the current schema removed has no rows to retain.
5770                let Some(table) = self.schema.table(&operation.table) else {
5771                    continue;
5772                };
5773                let key =
5774                    serde_json::to_string(&(operation.table.clone(), operation.row_id.clone()))
5775                        .map_err(|_| "sync.local_corrupt".to_owned())?;
5776                let base = self.stored_row(table, &operation.row_id, true)?;
5777                rows.push(RetainedCommitRow {
5778                    table: operation.table.clone(),
5779                    row_id: operation.row_id.clone(),
5780                    unique_conflicts: if operation.upsert {
5781                        self.unique_conflicts(
5782                            table,
5783                            initial
5784                                .get(&key)
5785                                .and_then(Value::as_object)
5786                                .or(operation.values.as_ref())
5787                                .ok_or("sync.local_corrupt")?,
5788                            true,
5789                        )?
5790                    } else {
5791                        Vec::new()
5792                    },
5793                    local_row: if operation.upsert {
5794                        initial
5795                            .get(&key)
5796                            .and_then(Value::as_object)
5797                            .cloned()
5798                            .or_else(|| operation.values.clone())
5799                    } else {
5800                        None
5801                    },
5802                    server_row: base.as_ref().map(|(values, _)| {
5803                        table
5804                            .columns
5805                            .iter()
5806                            .zip(values)
5807                            .map(|(column, value)| {
5808                                (column.name.clone(), column_value_to_json(value))
5809                            })
5810                            .collect()
5811                    }),
5812                    server_version: base.map(|(_, version)| version),
5813                });
5814            }
5815            outcome.retained_rows = Some(rows);
5816        }
5817        Ok(outcome)
5818    }
5819
5820    fn commit_outcome(&self, client_commit_id: &str) -> Result<Option<CommitOutcome>, String> {
5821        let row = self
5822            .conn
5823            .query_row(
5824                "SELECT seq, client_commit_id, status, recorded_at_ms, results_json, operations_json,
5825                        resolution, resolved_at_ms, replacement_client_commit_id
5826                   FROM _syncular_commit_outcomes WHERE client_commit_id = ?1",
5827                rusqlite::params![client_commit_id],
5828                |row| {
5829                    Ok(StoredCommitOutcomeRow {
5830                        sequence: row.get(0)?,
5831                        client_commit_id: row.get(1)?,
5832                        status: row.get(2)?,
5833                        recorded_at_ms: row.get(3)?,
5834                        results_json: row.get(4)?,
5835                        operations_json: row.get(5)?,
5836                        resolution: row.get(6)?,
5837                        resolved_at_ms: row.get(7)?,
5838                        replacement_client_commit_id: row.get(8)?,
5839                    })
5840                },
5841            )
5842            .optional()
5843            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
5844        row.map(|row| self.attach_retained_rows(Self::outcome_from_row(row)?))
5845            .transpose()
5846    }
5847
5848    /// Internal host step. The host must run its idle drive before finishing.
5849    #[doc(hidden)]
5850    pub fn prepare_current_base(
5851        &self,
5852        client_commit_id: &str,
5853        sequence: i64,
5854    ) -> Result<CurrentBasePreparation, CurrentBaseProof> {
5855        let outcome = self
5856            .commit_outcome(client_commit_id)
5857            .map_err(|_| CurrentBaseProof::failure(CurrentBaseProofReason::SnapshotFailed))?;
5858        let valid = outcome.as_ref().is_some_and(|outcome| {
5859            outcome.sequence == sequence
5860                && outcome.resolution == CommitOutcomeResolution::Active
5861                && matches!(
5862                    outcome.status,
5863                    CommitOutcomeStatus::Conflict | CommitOutcomeStatus::Rejected
5864                )
5865                && outcome
5866                    .operations
5867                    .as_ref()
5868                    .zip(outcome.retained_rows.as_ref())
5869                    .is_some_and(|(operations, rows)| {
5870                        !rows.is_empty() && operations.len() == rows.len()
5871                    })
5872        });
5873        if !valid {
5874            return Err(CurrentBaseProof::failure(
5875                CurrentBaseProofReason::OutcomeUnavailable,
5876            ));
5877        }
5878        if self.transport_closed() {
5879            return Err(CurrentBaseProof::failure(CurrentBaseProofReason::Offline));
5880        }
5881        Ok(CurrentBasePreparation {
5882            client_commit_id: client_commit_id.to_owned(),
5883            sequence,
5884            replacement: None,
5885            units: load_units(&self.conn)
5886                .map_err(|_| CurrentBaseProof::failure(CurrentBaseProofReason::SnapshotFailed))?,
5887            transport_epoch: self.transport_epoch,
5888            registration_epoch: self.registration_epoch,
5889            security_epoch: self.security_epoch,
5890        })
5891    }
5892
5893    /// Internal host step after the completed post-rejection idle drive.
5894    #[doc(hidden)]
5895    pub fn finish_current_base(
5896        &mut self,
5897        prepared: CurrentBasePreparation,
5898        drive: SyncOutcome,
5899    ) -> CurrentBaseProof {
5900        if self.transport_closed() || self.transport_epoch != prepared.transport_epoch {
5901            return CurrentBaseProof::failure(CurrentBaseProofReason::Offline);
5902        }
5903        if self.registration_epoch != prepared.registration_epoch {
5904            return CurrentBaseProof::failure(CurrentBaseProofReason::MissingCoverage);
5905        }
5906        if self.security_preflight || self.security_epoch != prepared.security_epoch {
5907            return CurrentBaseProof::failure(CurrentBaseProofReason::SyncFailed);
5908        }
5909        let report = match drive {
5910            SyncOutcome::Ok(report) => report,
5911            SyncOutcome::BudgetExhausted(_) => {
5912                return CurrentBaseProof::failure(CurrentBaseProofReason::BudgetExhausted)
5913            }
5914            _ => return CurrentBaseProof::failure(CurrentBaseProofReason::SyncFailed),
5915        };
5916        if report.schema_floor.is_some() {
5917            return CurrentBaseProof::failure(CurrentBaseProofReason::SchemaFloor);
5918        }
5919        if self
5920            .conn
5921            .execute_batch("SAVEPOINT syncular_base_proof")
5922            .is_err()
5923        {
5924            return CurrentBaseProof::failure(CurrentBaseProofReason::SnapshotFailed);
5925        }
5926        let proof = (|| {
5927            let snapshot = snapshot_read_connection(
5928                &self.conn,
5929                Some(&self.schema),
5930                &SnapshotReadRequest {
5931                    units: prepared.units.iter().map(|unit| unit.id.clone()).collect(),
5932                    commit_ids: vec![prepared.client_commit_id.clone()],
5933                    ..Default::default()
5934                },
5935            )
5936            .map_err(|_| CurrentBaseProofReason::SnapshotFailed)?;
5937            let current = self
5938                .commit_outcome(&prepared.client_commit_id)
5939                .map_err(|_| CurrentBaseProofReason::SnapshotFailed)?;
5940            let unavailable = if report.revoked.is_empty() {
5941                CurrentBaseProofReason::OutcomeUnavailable
5942            } else {
5943                CurrentBaseProofReason::Revoked
5944            };
5945            let Some(outcome) = current else {
5946                return Err(unavailable);
5947            };
5948            if !matches!(
5949                snapshot.deliveries.first(),
5950                Some(CommitDelivery::Known { .. })
5951            ) || outcome.sequence != prepared.sequence
5952                || outcome.resolution != CommitOutcomeResolution::Active
5953                || !matches!(
5954                    outcome.status,
5955                    CommitOutcomeStatus::Conflict | CommitOutcomeStatus::Rejected
5956                )
5957            {
5958                return Err(unavailable);
5959            }
5960            let (Some(operations), Some(rows)) = (outcome.operations, outcome.retained_rows) else {
5961                return Err(unavailable);
5962            };
5963            if rows.is_empty() || operations.len() != rows.len() {
5964                return Err(unavailable);
5965            }
5966            let after =
5967                load_units(&self.conn).map_err(|_| CurrentBaseProofReason::SnapshotFailed)?;
5968            let complete: HashSet<&str> = snapshot
5969                .units
5970                .iter()
5971                .filter_map(|unit| match unit {
5972                    UnitCatchup::Known {
5973                        id,
5974                        bootstrap_complete: true,
5975                        ..
5976                    } => Some(id.as_str()),
5977                    _ => None,
5978                })
5979                .collect();
5980            // A unit id names one scope map (§4.1), so the same id before and
5981            // after the drive is the same registration.
5982            let candidates: Vec<&UnitRecord> = after
5983                .iter()
5984                .filter(|unit| {
5985                    complete.contains(unit.id.as_str())
5986                        && prepared.units.iter().any(|before| before.id == unit.id)
5987                })
5988                .collect();
5989            let covered = |table_name: &str, row: &Map<String, Value>| {
5990                let Some(table) = self.schema.table(table_name) else {
5991                    return false;
5992                };
5993                candidates.iter().any(|unit| {
5994                    covers(table, &unit.scopes)
5995                        && pair_scopes(&unit.scopes, table_name, unit.echo.as_deref()).is_some_and(
5996                            |scopes| {
5997                                scopes.iter().all(|(variable, allowed)| {
5998                                    table
5999                                        .scope_column(variable)
6000                                        .and_then(|column| match row.get(column) {
6001                                            Some(Value::String(value)) => Some(value.clone()),
6002                                            Some(Value::Bool(value)) => Some(value.to_string()),
6003                                            Some(Value::Number(value)) => {
6004                                                value.as_f64().map(|number| {
6005                                                    ryu_js::Buffer::new()
6006                                                        .format_finite(number)
6007                                                        .to_owned()
6008                                                })
6009                                            }
6010                                            _ => None,
6011                                        })
6012                                        .is_some_and(|value| {
6013                                            !value.is_empty() && allowed.contains(&value)
6014                                        })
6015                                })
6016                            },
6017                        )
6018                })
6019            };
6020            for row in &rows {
6021                let Some(base) = row.server_row.as_ref().or(row.local_row.as_ref()) else {
6022                    return Err(if report.revoked.is_empty() {
6023                        CurrentBaseProofReason::MissingCoverage
6024                    } else {
6025                        CurrentBaseProofReason::Revoked
6026                    });
6027                };
6028                if !covered(&row.table, base)
6029                    || row
6030                        .unique_conflicts
6031                        .iter()
6032                        .any(|conflict| !covered(&row.table, &conflict.server_row))
6033                {
6034                    return Err(if report.revoked.is_empty() {
6035                        CurrentBaseProofReason::MissingCoverage
6036                    } else {
6037                        CurrentBaseProofReason::Revoked
6038                    });
6039                }
6040            }
6041            Ok(rows)
6042        })();
6043        if self
6044            .conn
6045            .execute_batch("RELEASE syncular_base_proof")
6046            .is_err()
6047        {
6048            return CurrentBaseProof::failure(CurrentBaseProofReason::SnapshotFailed);
6049        }
6050        match proof {
6051            Ok(rows) => CurrentBaseProof {
6052                proven: true,
6053                rows: Some(rows),
6054                reason: None,
6055            },
6056            Err(reason) => CurrentBaseProof::failure(reason),
6057        }
6058    }
6059
6060    pub fn prove_current_base(
6061        &mut self,
6062        transport: &mut dyn Transport,
6063        client_commit_id: &str,
6064        sequence: i64,
6065        max_rounds: Option<u32>,
6066    ) -> CurrentBaseProof {
6067        let prepared = match self.prepare_current_base(client_commit_id, sequence) {
6068            Ok(prepared) => prepared,
6069            Err(proof) => return proof,
6070        };
6071        let drive = self.sync_until_idle(transport, max_rounds);
6072        self.finish_current_base(prepared, drive)
6073    }
6074
6075    pub fn commit_outcomes(&self, query: CommitOutcomeQuery) -> Result<Vec<CommitOutcome>, String> {
6076        if query.limit == Some(0) {
6077            return Err("sync.invalid_request: commit outcome limit must be positive".to_owned());
6078        }
6079        let mut sql = String::from(
6080            "SELECT seq, client_commit_id, status, recorded_at_ms, results_json, operations_json,
6081                    resolution, resolved_at_ms, replacement_client_commit_id
6082               FROM _syncular_commit_outcomes",
6083        );
6084        if query.active_only {
6085            sql.push_str(" WHERE resolution = 'active' AND status IN ('conflict', 'rejected')");
6086        }
6087        sql.push_str(" ORDER BY seq DESC");
6088        if let Some(limit) = query.limit {
6089            sql.push_str(&format!(" LIMIT {limit}"));
6090        }
6091        let mut stmt = self
6092            .conn
6093            .prepare(&sql)
6094            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6095        let rows = stmt
6096            .query_map([], |row| {
6097                Ok(StoredCommitOutcomeRow {
6098                    sequence: row.get(0)?,
6099                    client_commit_id: row.get(1)?,
6100                    status: row.get(2)?,
6101                    recorded_at_ms: row.get(3)?,
6102                    results_json: row.get(4)?,
6103                    operations_json: row.get(5)?,
6104                    resolution: row.get(6)?,
6105                    resolved_at_ms: row.get(7)?,
6106                    replacement_client_commit_id: row.get(8)?,
6107                })
6108            })
6109            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6110        let mut outcomes = Vec::new();
6111        for row in rows {
6112            let row = row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6113            outcomes.push(Self::reported_outcome(
6114                self.attach_retained_rows(Self::outcome_from_row(row)?)?,
6115            ));
6116        }
6117        Ok(outcomes)
6118    }
6119
6120    fn prune_commit_outcomes(&self) -> Result<(), String> {
6121        #[cfg(test)]
6122        self.outcome_prune_count
6123            .set(self.outcome_prune_count.get() + 1);
6124        let max_entries = self.limits.outcome_retention_max_entries.unwrap_or(1_000);
6125        let count = self
6126            .conn
6127            .query_row(
6128                "SELECT COUNT(*) FROM _syncular_commit_outcomes",
6129                [],
6130                |row| row.get::<_, i64>(0),
6131            )
6132            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
6133            as usize;
6134        let excess = count.saturating_sub(max_entries);
6135        if excess == 0 {
6136            return Ok(());
6137        }
6138        let mut stmt = self
6139            .conn
6140            .prepare(
6141                "SELECT seq FROM _syncular_commit_outcomes
6142                  WHERE status IN ('applied', 'cached') OR resolution != 'active'
6143                  ORDER BY seq ASC LIMIT ?1",
6144            )
6145            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6146        let rows = stmt
6147            .query_map(rusqlite::params![excess as i64], |row| row.get::<_, i64>(0))
6148            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6149        let sequences = rows
6150            .collect::<Result<Vec<_>, _>>()
6151            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6152        drop(stmt);
6153        for sequence in sequences {
6154            self.conn
6155                .execute(
6156                    "DELETE FROM _syncular_commit_outcomes WHERE seq = ?1",
6157                    rusqlite::params![sequence],
6158                )
6159                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6160        }
6161        Ok(())
6162    }
6163
6164    // -- units (§4.1) ------------------------------------------------------------
6165
6166    /// Every registered unit in registration order (§4.1).
6167    pub fn units(&self) -> Result<Vec<UnitRecord>, String> {
6168        self.stored(load_units(&self.conn))
6169    }
6170
6171    pub fn unit(&self, id: &str) -> Result<Option<UnitRecord>, String> {
6172        self.stored(get_unit(&self.conn, id))
6173    }
6174
6175    /// Register one unit (§4.1) and return its id.
6176    pub fn subscribe(&mut self, scopes: UnitScopes) -> Result<String, String> {
6177        Ok(self.subscribe_many(vec![scopes])?.remove(0))
6178    }
6179
6180    /// Register several units in one local transaction and return their ids:
6181    /// one commit for all of them (on OPFS a commit costs milliseconds, so a
6182    /// cold start with hundreds of units pays it once). An error rolls back
6183    /// every registration of the call. Registering an active unit again
6184    /// changes nothing; a revoked unit re-arms (§3.3). A call that registers or
6185    /// re-arms a unit raises sync-needed with an interactive intent.
6186    pub fn subscribe_many(&mut self, units: Vec<UnitScopes>) -> Result<Vec<String>, String> {
6187        let rollback = self.capture();
6188        self.begin_observation("syncular_subscribe")?;
6189        let mut changed = false;
6190        let registered = (|| {
6191            let mut ids = Vec::with_capacity(units.len());
6192            let mut batch = ChangeAccumulator::default();
6193            for scopes in units {
6194                let (id, held) = self.hold_unit(scopes, true)?;
6195                if held {
6196                    if let Some(unit) = self.stored(get_unit(&self.conn, &id))? {
6197                        self.record_unit_windows(&mut batch, &unit)?;
6198                    }
6199                }
6200                changed |= held;
6201                ids.push(id);
6202            }
6203            self.finish_observation("syncular_subscribe", batch)?;
6204            Ok(ids)
6205        })();
6206        let ids = match registered {
6207            Ok(ids) => ids,
6208            Err(error) => {
6209                self.rollback_observation("syncular_subscribe");
6210                self.restore(rollback);
6211                return Err(error);
6212            }
6213        };
6214        if changed {
6215            self.registration_epoch = self.registration_epoch.wrapping_add(1);
6216            self.set_sync_needed(true, true);
6217        }
6218        Ok(ids)
6219    }
6220
6221    /// Release the explicit reference to a unit. The unit leaves the
6222    /// registration list when no window base holds it (§4.1); its rows stay.
6223    pub fn unsubscribe(&mut self, id: &str) -> Result<(), String> {
6224        let Some(unit) = self.stored(get_unit(&self.conn, id))? else {
6225            return Ok(());
6226        };
6227        if !unit.explicit {
6228            return Ok(());
6229        }
6230        if !self.stored(window_refs(&self.conn, id))?.is_empty() {
6231            return self.stored(save_unit(
6232                &self.conn,
6233                &UnitRecord {
6234                    explicit: false,
6235                    ..unit
6236                },
6237            ));
6238        }
6239        let rollback = self.capture();
6240        self.begin_observation("syncular_unsubscribe")?;
6241        let removed = (|| {
6242            self.conn
6243                .execute("DELETE FROM _syncular_units WHERE id = ?1", [id])
6244                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6245            let mut batch = ChangeAccumulator::default();
6246            self.record_unit_windows(&mut batch, &unit)?;
6247            self.finish_observation("syncular_unsubscribe", batch)
6248        })();
6249        if let Err(error) = removed {
6250            self.rollback_observation("syncular_unsubscribe");
6251            self.restore(rollback);
6252            return Err(error);
6253        }
6254        self.registration_epoch = self.registration_epoch.wrapping_add(1);
6255        if unit.status == UnitStatus::Active {
6256            self.set_sync_needed(true, true);
6257        }
6258        Ok(())
6259    }
6260
6261    /// Take one reference on a unit (§4.1): validate the scope map, register a
6262    /// new unit catching up with cursor `-1`, re-arm a revoked one (§3.3).
6263    /// Returns the id and whether the registration list changed.
6264    fn hold_unit(&mut self, scopes: UnitScopes, explicit: bool) -> Result<(String, bool), String> {
6265        if scopes.is_empty()
6266            || scopes.values().any(|value| value == "*")
6267            || !self
6268                .schema
6269                .tables
6270                .iter()
6271                .any(|table| covers(table, &scopes))
6272        {
6273            return Err("sync.invalid_subscription: a unit names one non-wildcard value per variable and covers a table".to_owned());
6274        }
6275        let id = ssp2::registration::unit_id(&scope_pairs(&scopes));
6276        let existing = self.stored(get_unit(&self.conn, &id))?;
6277        if let Some(existing) = existing
6278            .as_ref()
6279            .filter(|unit| unit.status != UnitStatus::Revoked)
6280        {
6281            if explicit && !existing.explicit {
6282                self.stored(save_unit(
6283                    &self.conn,
6284                    &UnitRecord {
6285                        explicit,
6286                        ..existing.clone()
6287                    },
6288                ))?;
6289            }
6290            return Ok((id, false));
6291        }
6292        self.delete_pending_evict(&id)?;
6293        self.stored(save_unit(
6294            &self.conn,
6295            &UnitRecord {
6296                id: id.clone(),
6297                scopes,
6298                explicit: explicit || existing.is_some_and(|unit| unit.explicit),
6299                status: UnitStatus::Active,
6300                reason_code: None,
6301                cursor: Some(-1),
6302                bootstrap_state: None,
6303                seeded: Vec::new(),
6304                echo: None,
6305                restriction: None,
6306            },
6307        ))?;
6308        Ok((id, true))
6309    }
6310
6311    // -- windows (§4.8) -----------------------------------------------------------
6312
6313    /// §4.8: set the windowed-in values of a base, one unit per value. Added
6314    /// values take a reference on their unit (a new unit bootstraps on the
6315    /// next sync); removed values release theirs, and a unit no reference
6316    /// holds leaves the registration list fused with its first eviction chunk
6317    /// (E1–E4). Idempotent; re-entry cancels a deferred eviction.
6318    pub fn set_window(
6319        &mut self,
6320        base: &WindowBase,
6321        units: &[String],
6322    ) -> Result<CommandEffects, String> {
6323        let base_key = window_base_key(base);
6324        let live = self.load_window_units(&base_key)?;
6325        let mut changed = false;
6326        // §7.8: the added values register in one transaction. §3.3: a held
6327        // value whose unit is revoked re-arms once per open core.
6328        let mut added: Vec<&String> = Vec::new();
6329        for value in units {
6330            let held = live.iter().find(|(held, _)| held == value);
6331            let rearm = match held {
6332                None => true,
6333                Some((_, id)) => {
6334                    !self.window_armed.contains(id)
6335                        && self
6336                            .stored(get_unit(&self.conn, id))?
6337                            .is_some_and(|unit| unit.status == UnitStatus::Revoked)
6338                }
6339            };
6340            if rearm {
6341                added.push(value);
6342            }
6343        }
6344        if !added.is_empty() {
6345            let rollback = self.capture();
6346            self.begin_observation("syncular_window")?;
6347            let widened = (|| {
6348                let mut batch = ChangeAccumulator::default();
6349                for value in &added {
6350                    let (id, registered) =
6351                        self.hold_unit(window_unit_scopes(base, value), false)?;
6352                    self.sync_needed |= registered;
6353                    if registered {
6354                        self.window_armed.insert(id.clone());
6355                    }
6356                    self.conn
6357                        .execute(
6358                            "INSERT OR REPLACE INTO _syncular_windows(base, unit, sub_id) VALUES (?1, ?2, ?3)",
6359                            rusqlite::params![base_key, value, id],
6360                        )
6361                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6362                    batch.window(&base_key, value);
6363                    // A registered or re-armed unit is a transition for every
6364                    // window value that references it.
6365                    if registered {
6366                        if let Some(unit) = self.stored(get_unit(&self.conn, &id))? {
6367                            self.record_unit_windows(&mut batch, &unit)?;
6368                        }
6369                    }
6370                }
6371                batch.status = true;
6372                self.finish_observation("syncular_window", batch)
6373            })();
6374            if let Err(error) = widened {
6375                self.rollback_observation("syncular_window");
6376                self.restore(rollback);
6377                return Err(error);
6378            }
6379            changed = true;
6380            self.registration_epoch = self.registration_epoch.wrapping_add(1);
6381        }
6382        for (value, id) in live {
6383            if units.contains(&value) {
6384                continue;
6385            }
6386            self.rebuild_overlay_if_dirty()?;
6387            let rollback = self.capture();
6388            self.begin_observation("syncular_window")?;
6389            let remaining = self.release_window_unit(&base_key, &value, &id);
6390            let remaining = match remaining {
6391                Ok(remaining) => remaining,
6392                Err(error) => {
6393                    self.rollback_observation("syncular_window");
6394                    self.restore(rollback);
6395                    return Err(error);
6396                }
6397            };
6398            changed = true;
6399            self.registration_epoch = self.registration_epoch.wrapping_add(1);
6400            if remaining {
6401                self.drain_pending_evictions()?;
6402            }
6403        }
6404        Ok(if changed && !self.transport_closed() {
6405            CommandEffects::interactive()
6406        } else {
6407            CommandEffects::none()
6408        })
6409    }
6410
6411    /// §4.8 completeness oracle: the windowed-in values of a base and those
6412    /// whose unit is not complete. A value is complete once its unit is active
6413    /// and no longer bootstrapping; registration alone is not completeness.
6414    pub fn window_state(&self, base: &WindowBase) -> Result<WindowState, String> {
6415        persisted_window_state(&self.conn, base).map_err(|failure| failure.message)
6416    }
6417
6418    /// Registry rows for a base, ordered by value: (value, unit id).
6419    fn load_window_units(&self, base_key: &str) -> Result<Vec<(String, String)>, String> {
6420        let mut statement = self
6421            .conn
6422            .prepare_cached(
6423                "SELECT unit, sub_id FROM _syncular_windows WHERE base = ?1 ORDER BY unit ASC",
6424            )
6425            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6426        let rows = statement
6427            .query_map([base_key], |row| Ok((row.get(0)?, row.get(1)?)))
6428            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6429        rows.collect::<Result<_, _>>()
6430            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
6431    }
6432
6433    /// §4.8: the window-domain changes of one unit transition, the one path
6434    /// every transition site takes: one per window value that references the
6435    /// unit or, when none does, one for the base derived from its scope map
6436    /// (the variable first in code-unit order and its value; the other
6437    /// variables its fixed scopes). A transition adds no table change.
6438    fn record_unit_windows(
6439        &self,
6440        batch: &mut ChangeAccumulator,
6441        unit: &UnitRecord,
6442    ) -> Result<(), String> {
6443        let refs = self.stored(window_refs(&self.conn, &unit.id))?;
6444        if refs.is_empty() {
6445            let mut pairs = scope_pairs(&unit.scopes).into_iter();
6446            if let Some((variable, value)) = pairs.next() {
6447                let base = WindowBase {
6448                    variable,
6449                    fixed_scopes: pairs.collect(),
6450                };
6451                batch.window(&window_base_key(&base), &value);
6452            }
6453        }
6454        for (base_key, value) in refs {
6455            batch.window(&base_key, &value);
6456        }
6457        Ok(())
6458    }
6459
6460    /// §4.8: release a window value's reference inside the caller's
6461    /// observation. When no reference holds the unit, unregister it fused with
6462    /// its first eviction chunk (E3): delete the rows of every covered table
6463    /// matching the persisted echo, except rows pinned by the outbox (E1) or
6464    /// owned by another unit (§3.3), and park the per-table scopes of what
6465    /// remains in the pending-eviction registry. Fails closed without a local
6466    /// scope-column mapping. Returns whether unpinned rows remain.
6467    fn release_window_unit(
6468        &mut self,
6469        base_key: &str,
6470        value: &str,
6471        id: &str,
6472    ) -> Result<bool, String> {
6473        self.conn
6474            .execute(
6475                "DELETE FROM _syncular_windows WHERE base = ?1 AND unit = ?2",
6476                rusqlite::params![base_key, value],
6477            )
6478            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6479        self.window_armed.remove(id);
6480        let mut batch = ChangeAccumulator::default();
6481        batch.window(base_key, value);
6482        batch.status = true;
6483        let unit = self.stored(get_unit(&self.conn, id))?;
6484        let mut remaining = false;
6485        if let Some(unit) = unit.filter(|unit| !unit.explicit) {
6486            if self.stored(window_refs(&self.conn, id))?.is_empty() {
6487                let units = self.stored(load_units(&self.conn))?;
6488                self.conn
6489                    .execute("DELETE FROM _syncular_units WHERE id = ?1", [id])
6490                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6491                self.sync_needed = true;
6492                for table in self.schema.tables.clone() {
6493                    let Some(effective) = unit
6494                        .echo
6495                        .as_deref()
6496                        .filter(|_| covers(&table, &unit.scopes))
6497                        .and_then(|echo| pair_scopes(&unit.scopes, &table.name, Some(echo)))
6498                    else {
6499                        continue;
6500                    };
6501                    let pinned = self.pinned_row_ids(&table.name);
6502                    let owners = unit_owners(&units, &table, id);
6503                    let (more, deferred) =
6504                        self.evict_scope_rows(&table.name, &effective, &owners, &pinned)?;
6505                    remaining |= more;
6506                    if deferred {
6507                        self.save_pending_evict(id, &table.name, &effective)?;
6508                    }
6509                    self.record_scope_map(&mut batch, &table.name, &effective);
6510                }
6511            }
6512        }
6513        self.finish_observation("syncular_window", batch)?;
6514        Ok(remaining)
6515    }
6516
6517    /// §4.8 E1: delete base rows owned by the effective scopes
6518    /// ([`local_scope_predicate`]) EXCEPT pinned primary keys. Returns (more
6519    /// unpinned work, any scoped rows remain). A missing scope-column mapping
6520    /// fails without deleting rows.
6521    fn evict_scope_rows(
6522        &self,
6523        table_name: &str,
6524        effective: &[(String, Vec<String>)],
6525        owners: &[Vec<(String, Vec<String>)>],
6526        pinned: &std::collections::HashSet<String>,
6527    ) -> Result<(bool, bool), String> {
6528        let table = self.schema.table(table_name).ok_or("sync.unknown_table")?;
6529        let Some((scope, mut params)) = local_scope_predicate(table, effective, owners)
6530            .map_err(|()| "sync.scope_revoked".to_owned())?
6531        else {
6532            return Ok((false, false));
6533        };
6534        let scope_params = params.len();
6535        let pk = quote_ident(&table.primary_key);
6536        // Pinned ids are rowId text; the text form matches every key type.
6537        let predicate = if pinned.is_empty() {
6538            scope.clone()
6539        } else {
6540            params.extend(pinned.iter().cloned().map(SqlValue::Text));
6541            let holes = vec!["?"; pinned.len()].join(", ");
6542            format!("{scope} AND CAST({pk} AS TEXT) NOT IN ({holes})")
6543        };
6544        let base = base_table(table_name);
6545        let visible = visible_table(table_name);
6546        let mut ids: Vec<SqlValue> = Vec::new();
6547        for source in [&base, &visible] {
6548            let mut stmt = self
6549                .conn
6550                .prepare_cached(&format!(
6551                    "SELECT {pk} FROM {source} WHERE {predicate} LIMIT 1024"
6552                ))
6553                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6554            ids = stmt
6555                .query_map(rusqlite::params_from_iter(&params), |row| row.get(0))
6556                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
6557                .collect::<Result<_, _>>()
6558                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6559            if !ids.is_empty() {
6560                break;
6561            }
6562        }
6563        if !ids.is_empty() {
6564            for id in &ids {
6565                self.conn
6566                    .execute(
6567                        "DELETE FROM _syncular_acked_rows WHERE tbl=?1 AND id=?2",
6568                        rusqlite::params![table_name, id],
6569                    )
6570                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6571            }
6572            let holes = vec!["?"; ids.len()].join(", ");
6573            for source in [&base, &visible] {
6574                self.conn
6575                    .execute(
6576                        &format!("DELETE FROM {source} WHERE {pk} IN ({holes})"),
6577                        rusqlite::params_from_iter(&ids),
6578                    )
6579                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6580            }
6581        }
6582        let mut remaining = false;
6583        let mut deferred = false;
6584        for source in [&base, &visible] {
6585            remaining |= self
6586                .conn
6587                .query_row(
6588                    &format!("SELECT EXISTS(SELECT 1 FROM {source} WHERE {predicate})"),
6589                    rusqlite::params_from_iter(&params),
6590                    |row| row.get::<_, bool>(0),
6591                )
6592                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6593            deferred |= self
6594                .conn
6595                .query_row(
6596                    &format!("SELECT EXISTS(SELECT 1 FROM {source} WHERE {scope})"),
6597                    rusqlite::params_from_iter(&params[..scope_params]),
6598                    |row| row.get::<_, bool>(0),
6599                )
6600                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6601        }
6602        Ok((remaining, deferred))
6603    }
6604
6605    /// §4.8 E1: continue deferred evictions after the outbox drains or between
6606    /// chunks, retaining outbox pins and their durable marker. A unit that
6607    /// re-entered the window has no pending entry left.
6608    fn drain_pending_evictions(&mut self) -> Result<(), String> {
6609        let pending = self.load_pending_evictions()?;
6610        if pending.is_empty() {
6611            return Ok(());
6612        }
6613        self.rebuild_overlay_if_dirty()?;
6614        for (unit_id, table_name, effective) in pending {
6615            let Some(table) = self.schema.table(&table_name).cloned() else {
6616                self.delete_pending_evict_table(&unit_id, &table_name)?;
6617                continue;
6618            };
6619            loop {
6620                std::thread::yield_now();
6621                self.begin_observation("syncular_evict")?;
6622                let chunk = (|| {
6623                    let pinned = self.pinned_row_ids(&table_name);
6624                    let owners =
6625                        unit_owners(&self.stored(load_units(&self.conn))?, &table, &unit_id);
6626                    let (remaining, deferred) =
6627                        self.evict_scope_rows(&table_name, &effective, &owners, &pinned)?;
6628                    if !deferred {
6629                        self.delete_pending_evict_table(&unit_id, &table_name)?;
6630                    }
6631                    let mut batch = ChangeAccumulator::default();
6632                    self.record_scope_map(&mut batch, &table_name, &effective);
6633                    self.finish_observation("syncular_evict", batch)?;
6634                    Ok(remaining)
6635                })();
6636                match chunk {
6637                    Ok(true) => {}
6638                    Ok(false) => break,
6639                    Err(error) => {
6640                        self.rollback_observation("syncular_evict");
6641                        return Err(error);
6642                    }
6643                }
6644            }
6645        }
6646        Ok(())
6647    }
6648
6649    /// §4.8 E1: primary keys of `table` referenced by a pending outbox
6650    /// commit — rows that MUST NOT be evicted until the commit drains.
6651    fn pinned_row_ids(&self, table: &str) -> std::collections::HashSet<String> {
6652        let mut pinned = std::collections::HashSet::new();
6653        for commit in self
6654            .outbox
6655            .iter()
6656            .map(|commit| &**commit)
6657            .chain(self.failed_commits.iter().map(|(commit, _)| commit))
6658        {
6659            for op in &commit.ops {
6660                if op.table == table {
6661                    pinned.insert(op.row_id.clone());
6662                }
6663            }
6664        }
6665        pinned
6666    }
6667
6668    fn save_pending_evict(
6669        &self,
6670        unit_id: &str,
6671        table: &str,
6672        effective: &[(String, Vec<String>)],
6673    ) -> Result<(), String> {
6674        self.conn.execute(
6675            "INSERT OR REPLACE INTO _syncular_pending_evictions(unit_id, tbl, effective_scopes) VALUES (?1, ?2, ?3)",
6676            rusqlite::params![unit_id, table, scope_map_to_json(effective).to_string()],
6677        ).map(|_| ()).map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
6678    }
6679
6680    /// Re-entry cancels every pending eviction of the unit.
6681    fn delete_pending_evict(&self, unit_id: &str) -> Result<(), String> {
6682        self.conn
6683            .execute(
6684                "DELETE FROM _syncular_pending_evictions WHERE unit_id = ?1",
6685                [unit_id],
6686            )
6687            .map(|_| ())
6688            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
6689    }
6690
6691    fn delete_pending_evict_table(&self, unit_id: &str, table: &str) -> Result<(), String> {
6692        self.conn
6693            .execute(
6694                "DELETE FROM _syncular_pending_evictions WHERE unit_id = ?1 AND tbl = ?2",
6695                [unit_id, table],
6696            )
6697            .map(|_| ())
6698            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
6699    }
6700
6701    fn load_pending_evictions(&self) -> Result<Vec<PendingEvict>, String> {
6702        let mut stmt = self
6703            .conn
6704            .prepare("SELECT unit_id, tbl, effective_scopes FROM _syncular_pending_evictions")
6705            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6706        let rows = stmt
6707            .query_map([], |row| {
6708                Ok((
6709                    row.get::<_, String>(0)?,
6710                    row.get::<_, String>(1)?,
6711                    row.get::<_, String>(2)?,
6712                ))
6713            })
6714            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6715        rows.map(|row| {
6716            let (unit_id, table, json) =
6717                row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6718            let value: Value = serde_json::from_str(&json)
6719                .map_err(|_| "sync.local_corrupt: invalid pending eviction scopes".to_owned())?;
6720            let effective = json_to_scope_map(&value)
6721                .map_err(|_| "sync.local_corrupt: invalid pending eviction scopes".to_owned())?;
6722            Ok((unit_id, table, effective))
6723        })
6724        .collect()
6725    }
6726
6727    /// Select failed-intent retention; reload durable retained aggregates.
6728    pub fn set_retain_failed_commits(&mut self, enabled: bool) -> Result<(), String> {
6729        self.retain_failed_commits = enabled;
6730        for (commit, _) in self.failed_commits.iter() {
6731            for operation in &commit.ops {
6732                self.overlay_dirty.table(&operation.table);
6733            }
6734        }
6735        self.failed_commits = self.load_failed_commits()?.into();
6736        for (commit, _) in self.failed_commits.iter() {
6737            for operation in &commit.ops {
6738                self.overlay_dirty.table(&operation.table);
6739            }
6740        }
6741        Ok(())
6742    }
6743
6744    fn load_failed_commits(&self) -> Result<Vec<FailedCommit>, String> {
6745        let mut statement = self.conn.prepare("SELECT client_commit_id, operations_json, initial_json FROM _syncular_failed_commits ORDER BY seq")
6746            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6747        let rows = statement
6748            .query_map([], |row| {
6749                Ok((
6750                    row.get::<_, String>(0)?,
6751                    row.get::<_, String>(1)?,
6752                    row.get::<_, String>(2)?,
6753                ))
6754            })
6755            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6756        rows.map(|row| {
6757            let (id, operations, initial) =
6758                row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6759            let operations: Vec<CommitOperation> =
6760                serde_json::from_str(&operations).map_err(|_| "sync.local_corrupt".to_owned())?;
6761            let initial =
6762                serde_json::from_str(&initial).map_err(|_| "sync.local_corrupt".to_owned())?;
6763            Ok((
6764                OutboxCommit {
6765                    client_commit_id: id,
6766                    ops: operations
6767                        .into_iter()
6768                        .map(|op| OutboxOp {
6769                            upsert: op.op == "upsert",
6770                            table: op.table,
6771                            row_id: op.row_id,
6772                            base_version: op.base_version,
6773                            values: op.values,
6774                            insert: op.insert,
6775                        })
6776                        .collect(),
6777                },
6778                initial,
6779            ))
6780        })
6781        .collect()
6782    }
6783
6784    fn retain_failed_commit(&mut self, id: &str, operations: &[OutboxOp]) -> Result<(), String> {
6785        let mut initial = Map::new();
6786        for operation in operations {
6787            // A table the current schema removed has no rows to retain.
6788            let Some(table) = self.schema.table(&operation.table) else {
6789                continue;
6790            };
6791            let initial_row = match self.stored_row(table, &operation.row_id, true)? {
6792                Some(row) => Some(row),
6793                None => self.visible_row(table, &operation.row_id)?,
6794            };
6795            if let Some((values, _)) = initial_row {
6796                let mut intended: Map<String, Value> = table
6797                    .columns
6798                    .iter()
6799                    .zip(values.iter())
6800                    .map(|(column, value)| (column.name.clone(), column_value_to_json(value)))
6801                    .collect();
6802                if let Some(patch) = &operation.values {
6803                    intended.extend(patch.clone());
6804                }
6805                initial.insert(
6806                    serde_json::to_string(&(operation.table.clone(), operation.row_id.clone()))
6807                        .map_err(|_| "sync.local_corrupt".to_owned())?,
6808                    Value::Object(intended),
6809                );
6810            }
6811        }
6812        self.conn.execute("INSERT INTO _syncular_failed_commits(client_commit_id, operations_json, initial_json) VALUES (?1, ?2, ?3)", rusqlite::params![id,
6813            serde_json::to_string(&operations.iter().map(CommitOperation::from).collect::<Vec<_>>()).map_err(|_| "sync.local_corrupt".to_owned())?,
6814            serde_json::to_string(&initial).map_err(|_| "sync.local_corrupt".to_owned())?])
6815            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6816        self.failed_commits.push((
6817            OutboxCommit {
6818                client_commit_id: id.to_owned(),
6819                ops: operations.to_vec(),
6820            },
6821            initial,
6822        ));
6823        Ok(())
6824    }
6825
6826    fn drop_failed_commits(
6827        &mut self,
6828        matches: impl Fn(&str, &Map<String, Value>) -> bool,
6829    ) -> Result<Vec<OutboxCommit>, String> {
6830        let mut doomed = self.drop_acknowledged_rows(&matches)?;
6831        for (commit, initial) in self.failed_commits.iter() {
6832            for operation in &commit.ops {
6833                let key =
6834                    serde_json::to_string(&(operation.table.clone(), operation.row_id.clone()))
6835                        .map_err(|_| "sync.local_corrupt".to_owned())?;
6836                if initial
6837                    .get(&key)
6838                    .and_then(Value::as_object)
6839                    .is_some_and(|values| matches(&operation.table, values))
6840                {
6841                    doomed.push(commit.clone());
6842                    break;
6843                }
6844            }
6845        }
6846        for commit in &doomed {
6847            self.conn
6848                .execute(
6849                    "DELETE FROM _syncular_failed_commits WHERE client_commit_id = ?1",
6850                    rusqlite::params![commit.client_commit_id],
6851                )
6852                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
6853        }
6854        for commit in &doomed {
6855            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))?;
6856        }
6857        self.conflicts.retain(|record| {
6858            !doomed
6859                .iter()
6860                .any(|commit| commit.client_commit_id == record.client_commit_id)
6861        });
6862        self.rejections.retain(|record| {
6863            !doomed
6864                .iter()
6865                .any(|commit| commit.client_commit_id == record.client_commit_id)
6866        });
6867        self.failed_commits.retain(|(commit, _)| {
6868            !doomed
6869                .iter()
6870                .any(|dropped| dropped.client_commit_id == commit.client_commit_id)
6871        });
6872        for commit in &doomed {
6873            for operation in &commit.ops {
6874                self.overlay_dirty.table(&operation.table);
6875            }
6876        }
6877        Ok(doomed)
6878    }
6879
6880    /// Record one commit of local mutations. The returned commit ID is the
6881    /// §2.3 idempotency key. Failures are structured so callers read
6882    /// `code`/`message`/`details` instead of parsing a string prefix.
6883    pub fn mutate(&mut self, mutations: Vec<Mutation>) -> Result<String, ClientError> {
6884        let prior = self.storage_failure.borrow_mut().take();
6885        let outcome = self
6886            .prepare_mutations(mutations)
6887            .and_then(|ops| Ok(self.record_outbox_commit(ops, None)?));
6888        self.finish_authoring(prior, outcome)
6889    }
6890
6891    /// §7.1: validate one commit's mutations into outbox operations.
6892    fn prepare_mutations(&self, mutations: Vec<Mutation>) -> Result<Vec<OutboxOp>, ClientError> {
6893        {
6894            if mutations.is_empty() {
6895                return Err(
6896                    "sync.invalid_request: a commit must contain at least one operation (§6.1)"
6897                        .to_owned()
6898                        .into(),
6899                );
6900            }
6901            let mut ops = Vec::with_capacity(mutations.len());
6902            // §7.1: a patch reads the row as the commit's earlier operations
6903            // leave it: the values an earlier upsert wrote, or None after an
6904            // earlier delete. A patch changes neither presence nor a scope
6905            // column, so it records nothing.
6906            let mut staged: HashMap<(String, String), Option<Map<String, Value>>> = HashMap::new();
6907            for mutation in mutations {
6908                match mutation {
6909                    Mutation::Patch {
6910                        table,
6911                        values,
6912                        base_version,
6913                    } => {
6914                        let schema_table = self
6915                            .schema
6916                            .table(&table)
6917                            .ok_or_else(|| "sync.unknown_table".to_owned())?;
6918                        let values = normalize_values_casing(schema_table, values)?;
6919                        let row_id = render_row_id_json(values.get(&schema_table.primary_key))?;
6920                        let base = staged.get(&(table.clone(), row_id.clone()));
6921                        ops.push(self.prepare_patch(
6922                            &table,
6923                            &row_id,
6924                            values,
6925                            base_version,
6926                            base,
6927                        )?);
6928                    }
6929                    Mutation::Upsert {
6930                        table,
6931                        values,
6932                        base_version,
6933                    } => {
6934                        let schema_table = self.schema.table(&table).ok_or_else(|| {
6935                            format!("sync.unknown_table: unknown table {table:?}")
6936                        })?;
6937                        // §5: value keys are accepted in snake_case AND the
6938                        // generated row types' camelCase; normalize to SQL truth
6939                        // before the pk lookup / codec see them.
6940                        let values = normalize_values_casing(schema_table, values)?;
6941                        let row_id = render_row_id_json(values.get(&schema_table.primary_key))?;
6942                        // §6.7 `mutate` marks every column present: fill missing
6943                        // nullable columns with NULL before the payload is built.
6944                        let values = full_row_values(schema_table, values)?;
6945                        self.refuse_sealed_row(schema_table, &row_id)?;
6946                        // §5.11: validate the payload encodes with the current
6947                        // codec. A key-selection or unknown-key failure is a
6948                        // durable rejection at the push seam (§10.3), never an
6949                        // author-time error. Full-row `mutate` presents every
6950                        // column, so no stored fallback is needed.
6951                        self.validate_author_encode(schema_table, &row_id, &values)?;
6952                        // §7.1 insert intent: the row is absent from the
6953                        // visible replica at call time, before this batch
6954                        // applies anything.
6955                        let insert = !self.visible_row_exists(schema_table, &row_id)?;
6956                        staged.insert((table.clone(), row_id.clone()), Some(values.clone()));
6957                        ops.push(OutboxOp {
6958                            upsert: true,
6959                            table,
6960                            row_id,
6961                            base_version,
6962                            values: Some(values),
6963                            insert,
6964                        });
6965                    }
6966                    Mutation::Delete {
6967                        table,
6968                        row_id,
6969                        base_version,
6970                    } => {
6971                        let schema_table = self.schema.table(&table).ok_or_else(|| {
6972                            format!("sync.unknown_table: unknown table {table:?}")
6973                        })?;
6974                        self.refuse_sealed_row(schema_table, &row_id)?;
6975                        // §2.4: the server rejects a rowId holding U+0000.
6976                        if row_id.contains('\0') {
6977                            return Err("sync.invalid_request: rowId holds U+0000 (§2.4)"
6978                                .to_owned()
6979                                .into());
6980                        }
6981                        staged.insert((table.clone(), row_id.clone()), None);
6982                        ops.push(OutboxOp {
6983                            upsert: false,
6984                            table,
6985                            row_id,
6986                            base_version,
6987                            values: None,
6988                            insert: false,
6989                        });
6990                    }
6991                }
6992            }
6993            Ok(ops)
6994        }
6995    }
6996
6997    /// Scope the retained `storage_failure` diagnostic to this call so an
6998    /// earlier operation's failure cannot classify a new one, and surface the
6999    /// call's own classified failure with its details. A fresh classified
7000    /// failure replaces the retained diagnostic; otherwise the earlier one is
7001    /// kept for the next sync.
7002    fn finish_authoring<T>(
7003        &self,
7004        prior: Option<QueryReadFailure>,
7005        outcome: Result<T, ClientError>,
7006    ) -> Result<T, ClientError> {
7007        let fresh = self.storage_failure.borrow_mut().take();
7008        *self.storage_failure.borrow_mut() = fresh.clone().or(prior);
7009        outcome.map_err(|error| fresh.map(ClientError::from).unwrap_or(error))
7010    }
7011
7012    /// `decides` names the active outcome this commit replaces (§7.2.2); the
7013    /// outcome records it as its pending decision in the same transaction.
7014    fn record_outbox_commit(
7015        &mut self,
7016        ops: Vec<OutboxOp>,
7017        decides: Option<&str>,
7018    ) -> Result<String, String> {
7019        let commit = OutboxCommit {
7020            client_commit_id: uuid::Uuid::new_v4().to_string(),
7021            ops,
7022        };
7023        self.begin_observation("syncular_mutation")?;
7024        let mut batch = ChangeAccumulator::default();
7025        for op in &commit.ops {
7026            let mut precise = self.record_row_scopes(&mut batch, &op.table, &op.row_id, false);
7027            if let Some(values) = &op.values {
7028                if let Some(table) = self.schema.table(&op.table) {
7029                    for scope in &table.scope_variables {
7030                        if let Some(Value::String(value)) = values.get(&scope.column) {
7031                            batch.scope(&op.table, format!("{}:{value}", scope.prefix));
7032                            precise = true;
7033                        }
7034                    }
7035                }
7036            }
7037            if !precise {
7038                batch.table(&op.table);
7039            }
7040        }
7041        let persisted = self.persist_outbox_insert(&commit).and_then(|()| {
7042            let Some(outcome) = decides else {
7043                return Ok(());
7044            };
7045            batch.outcomes = true;
7046            let updated = self
7047                .conn
7048                .execute(
7049                    "UPDATE _syncular_commit_outcomes SET replacement_client_commit_id = ?1
7050                      WHERE client_commit_id = ?2 AND resolution = 'active'
7051                        AND replacement_client_commit_id IS NULL",
7052                    rusqlite::params![commit.client_commit_id, outcome],
7053                )
7054                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
7055            if updated == 1 {
7056                Ok(())
7057            } else {
7058                Err(REPLACEMENT_PENDING.to_owned())
7059            }
7060        });
7061        if let Err(error) = persisted {
7062            self.rollback_observation("syncular_mutation");
7063            return Err(error);
7064        }
7065        // A clean overlay contains the FIFO fold of every previous commit, so
7066        // the new commit applies over it. §7.1: an operation that does not
7067        // apply (a secondary unique collision) fails the whole commit; the
7068        // savepoint rollback removes the outbox entry and every visible write.
7069        // The append undoes itself: a rollback capture would copy the outbox.
7070        let was_dirty = self.overlay_dirty.snapshot();
7071        let id = commit.client_commit_id.clone();
7072        let appended = self.rebuild_overlay_if_dirty().and_then(|()| {
7073            commit
7074                .ops
7075                .iter()
7076                .try_for_each(|op| self.apply_outbox_op(op))?;
7077            self.outbox.push(Arc::new(commit));
7078            batch.status = true;
7079            self.finish_observation("syncular_mutation", batch)
7080                .inspect_err(|_| drop(self.outbox.pop()))
7081        });
7082        if let Err(error) = appended {
7083            self.rollback_observation("syncular_mutation");
7084            self.overlay_dirty.restore(was_dirty);
7085            return Err(error);
7086        }
7087        Ok(id)
7088    }
7089
7090    /// Record one §6.1 sparse upsert: the primary key plus the supplied
7091    /// non-scope columns are present; every other column is absent and stays
7092    /// untouched on the server and in the local overlay. An absent local base
7093    /// refuses the whole batch with sync.row_missing before enqueueing (§7.1).
7094    /// Failures are structured so callers read `code`/`message`/`details`.
7095    pub fn patch(
7096        &mut self,
7097        table: &str,
7098        row_id: &str,
7099        partial: Map<String, Value>,
7100        base_version: Option<i64>,
7101    ) -> Result<String, ClientError> {
7102        let prior = self.storage_failure.borrow_mut().take();
7103        let outcome = self.perform_patch(table, row_id, partial, base_version);
7104        self.finish_authoring(prior, outcome)
7105    }
7106
7107    /// The unscoped patch body. Public authoring entry points scope
7108    /// `storage_failure` around the whole operation, including any pre-read.
7109    fn perform_patch(
7110        &mut self,
7111        table: &str,
7112        row_id: &str,
7113        partial: Map<String, Value>,
7114        base_version: Option<i64>,
7115    ) -> Result<String, ClientError> {
7116        let operation = self.prepare_patch(table, row_id, partial, base_version, None)?;
7117        Ok(self.record_outbox_commit(vec![operation], None)?)
7118    }
7119
7120    /// `staged` is the row as the batch's earlier operations leave it
7121    /// (`Some(None)` after a delete); `None` reads the visible replica.
7122    fn prepare_patch(
7123        &self,
7124        table: &str,
7125        row_id: &str,
7126        partial: Map<String, Value>,
7127        base_version: Option<i64>,
7128        staged: Option<&Option<Map<String, Value>>>,
7129    ) -> Result<OutboxOp, ClientError> {
7130        let schema_table = self
7131            .schema
7132            .table(table)
7133            .ok_or_else(|| format!("sync.unknown_table: unknown table {table:?}"))?;
7134        let partial = normalize_values_casing(schema_table, partial)?;
7135        if let Some(pk) = partial.get(&schema_table.primary_key) {
7136            if render_row_id_json(Some(pk)).ok().as_deref() != Some(row_id) {
7137                return Err(invalid_authoring(
7138                    "patch cannot change the primary key",
7139                    json!({ "table": table }),
7140                ));
7141            }
7142        }
7143        let exists = match staged {
7144            Some(row) => row.is_some(),
7145            None => self.visible_row_exists(schema_table, row_id)?,
7146        };
7147        if !exists {
7148            return Err("sync.row_missing: a sparse patch requires a local row"
7149                .to_owned()
7150                .into());
7151        }
7152        self.refuse_sealed_row(schema_table, row_id)?;
7153        // §3.4 rule 5 / §6.2: scope columns are immutable on update. The
7154        // server accepts a present scope column whose value equals the
7155        // stored row and applies it as a no-op, so a decoded envelope
7156        // round-trips. The local row is the only value the client can prove
7157        // equality against; when the row is absent locally the client cannot
7158        // prove equality against the server's stored row and fails closed.
7159        // A primary key that is also a scope column needs no stored-row
7160        // read: the primary key in a sparse payload is by construction the
7161        // row id being patched (§6.1), so its value is proven equal already.
7162        for scope in &schema_table.scope_variables {
7163            if !partial.contains_key(&scope.column) || scope.column == schema_table.primary_key {
7164                continue;
7165            }
7166            let Some(column) = schema_table
7167                .columns
7168                .iter()
7169                .find(|column| column.name == scope.column)
7170            else {
7171                continue;
7172            };
7173            let stored = match staged {
7174                Some(row) => row.as_ref().and_then(|row| {
7175                    json_to_column_value(column, row.get(&scope.column))
7176                        .ok()
7177                        .map(|value| column_value_to_json(&value))
7178                }),
7179                None => self
7180                    .conn
7181                    .query_row(
7182                        &format!(
7183                            "SELECT {} FROM {} WHERE {}",
7184                            quote_ident(&scope.column),
7185                            visible_table(&schema_table.name),
7186                            row_id_predicate(schema_table)
7187                        ),
7188                        rusqlite::params![row_id],
7189                        |row| Ok(sql_ref_to_json(column, row.get_ref(0)?)),
7190                    )
7191                    .optional()
7192                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?,
7193            };
7194            // Decode the supplied value through the same column-type path the
7195            // rest of the patch encoding uses, so a value that only equals
7196            // the stored one in another number representation still compares
7197            // equal.
7198            let incoming = json_to_column_value(column, partial.get(&scope.column))
7199                .ok()
7200                .map(|value| column_value_to_json(&value));
7201            // A stored blob never equals a patch value, matching the server's
7202            // scope-column comparison (§3.4): bytes are unstorable as scope
7203            // values.
7204            let equal = stored.as_ref().is_some_and(|stored| {
7205                stored.get("$bytes").is_none() && incoming.as_ref() == Some(stored)
7206            });
7207            if !equal {
7208                return Err(invalid_authoring(
7209                    "patch cannot write a scope column (§3.4)",
7210                    json!({ "table": table, "column": scope.column }),
7211                ));
7212            }
7213        }
7214        let mut values = partial;
7215        // Presence-set semantics: a proven-equal scope column is dropped, so
7216        // the patch leaves the stored value untouched (§6.2).
7217        for scope in &schema_table.scope_variables {
7218            values.remove(&scope.column);
7219        }
7220        let pk_value = match schema_table.columns[schema_table.pk_index].ty {
7221            // §2.4: the rowId of an integer key is its canonical decimal form.
7222            ColumnType::Integer => match row_id.parse::<i64>() {
7223                Ok(v)
7224                    if v.to_string() == row_id
7225                        && (-ssp2::primitives::I64_SAFE_MAX..=ssp2::primitives::I64_SAFE_MAX)
7226                            .contains(&v) =>
7227                {
7228                    Value::from(v)
7229                }
7230                _ => {
7231                    return Err(format!(
7232                    "sync.invalid_request: table {table:?}: invalid integer primary key {row_id:?}"
7233                )
7234                    .into())
7235                }
7236            },
7237            ColumnType::Boolean => match row_id {
7238                "true" => Value::Bool(true),
7239                "false" => Value::Bool(false),
7240                _ => {
7241                    return Err(format!(
7242                    "sync.invalid_request: table {table:?}: invalid boolean primary key {row_id:?}"
7243                )
7244                    .into())
7245                }
7246            },
7247            _ => Value::from(row_id.to_owned()),
7248        };
7249        values.insert(schema_table.primary_key.clone(), pk_value);
7250        // §6.1: a patch cannot null a non-nullable column.
7251        if let Some(column) = schema_table
7252            .columns
7253            .iter()
7254            .find(|column| !column.nullable && values.get(&column.name) == Some(&Value::Null))
7255        {
7256            return Err(invalid_authoring(
7257                "a non-nullable column is null (§6.1)",
7258                json!({ "table": table, "column": column.name }),
7259            ));
7260        }
7261        // §5.11: structural validation only; an absent key-id selector is
7262        // resolved at the push seam from the stored local row, and a
7263        // key-selection or unknown-key failure becomes a durable
7264        // `client.encrypt_failed` rejection there (§10.3), never an
7265        // author-time error.
7266        self.validate_author_encode(schema_table, row_id, &values)?;
7267        Ok(OutboxOp {
7268            upsert: true,
7269            table: table.to_owned(),
7270            row_id: row_id.to_owned(),
7271            base_version,
7272            values: Some(values),
7273            insert: false,
7274        })
7275    }
7276
7277    /// §5.11 key-id fallback: the stored local row's selector value as a
7278    /// positional row (only the selector slot filled). Returns None when no
7279    /// selector is configured, the row is locally absent, or the stored
7280    /// value is not a usable key id. A failed storage read is an error.
7281    fn stored_key_fallback(
7282        &self,
7283        table: &TableSchema,
7284        row_id: &str,
7285    ) -> Result<Option<Row>, String> {
7286        let Some(selector) = self.encryption.key_id_columns.get(&table.name) else {
7287            return Ok(None);
7288        };
7289        let Some(index) = table
7290            .columns
7291            .iter()
7292            .position(|column| &column.name == selector)
7293        else {
7294            return Ok(None);
7295        };
7296        let sql = format!(
7297            "SELECT {} FROM {} WHERE {}",
7298            quote_ident(selector),
7299            visible_table(&table.name),
7300            row_id_predicate(table)
7301        );
7302        let key = self
7303            .conn
7304            .query_row(&sql, rusqlite::params![row_id], |row| {
7305                row.get::<_, Option<String>>(0)
7306            })
7307            .optional()
7308            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
7309            .flatten()
7310            .filter(|key| !key.is_empty());
7311        let Some(key) = key else {
7312            return Ok(None);
7313        };
7314        let mut fallback: Row = vec![None; table.columns.len()];
7315        fallback[index] = Some(ColumnValue::String(key));
7316        Ok(Some(fallback))
7317    }
7318
7319    /// §5.11/§10.3 author-time encode check: a structural failure (a
7320    /// non-nullable NULL, a value the codec rejects) is an author-time
7321    /// error; a key-selection or unknown-key failure is deferred to the push
7322    /// seam, where it becomes a durable `client.encrypt_failed` rejection.
7323    fn validate_author_encode(
7324        &self,
7325        table: &TableSchema,
7326        row_id: &str,
7327        values: &Map<String, Value>,
7328    ) -> Result<(), String> {
7329        match encode_sparse_row_json(table, row_id, values, &self.encryption, None) {
7330            Err(error) if error.starts_with(ENCRYPT_FAILED_CODE) => Ok(()),
7331            result => result.map(|_| ()),
7332        }
7333    }
7334
7335    /// §5.11/§10.3: drop every pending commit whose push encode fails with
7336    /// `client.encrypt_failed` (an unresolvable key id or an unknown key) and
7337    /// raise one durable rejection per commit. `sync()` never aborts for an
7338    /// encode failure. Mirrors §7.4.4's `drop_incompatible_outbox`, including
7339    /// undoing the dropped commit's purely-optimistic rows.
7340    /// §7.1/§7.4.4: drop pending commits whose values the current codec refuses
7341    /// (an envelope or a type an earlier version accepted). `with_encryption`
7342    /// additionally drops commits whose §5.11 encryption cannot resolve a key;
7343    /// the startup boundary leaves those to the send seam, where hosts configure
7344    /// keys after open. The send path checks only the commits this round pushes
7345    /// (§8.8): a held commit is never encoded or dropped before it is due.
7346    /// Recovery runs as one observation. An enclosing observation (the guarded
7347    /// schema reset) passes its `batch`, so the rejection, outcome, and table
7348    /// domains join that change event instead of publishing a second one.
7349    fn drop_unencodable_outbox(
7350        &mut self,
7351        with_encryption: bool,
7352        batch: Option<&mut ChangeAccumulator>,
7353    ) -> Result<bool, String> {
7354        let mut failures = Vec::new();
7355        let due = if with_encryption {
7356            self.pushable_commits()
7357        } else {
7358            self.outbox.len()
7359        };
7360        for commit in self.outbox.iter().take(due) {
7361            for op in &commit.ops {
7362                let Some(table) = self.schema.table(&op.table).filter(|_| op.upsert) else {
7363                    continue;
7364                };
7365                // An insert lacking a non-nullable column is left to
7366                // `drop_incompatible_outbox` (§7.4.4).
7367                let Some(values) = op.presented_values(table) else {
7368                    continue;
7369                };
7370                let fallback = self.stored_key_fallback(table, &op.row_id)?;
7371                let failure = match encode_sparse_row_json(
7372                    table,
7373                    &op.row_id,
7374                    &values,
7375                    &self.encryption,
7376                    fallback.as_ref(),
7377                ) {
7378                    Err(error) if error.starts_with(ENCRYPT_FAILED_CODE) => {
7379                        with_encryption.then_some((error, ENCRYPT_FAILED_CODE))
7380                    }
7381                    // §7.1/§7.4.4: a value the current codec refuses was
7382                    // persisted by a version that accepted it; it leaves
7383                    // through the incompatible-outbox path, so the FIFO
7384                    // queue never wedges.
7385                    Err(error) if error.starts_with(INVALID_REQUEST_CODE) => Some((
7386                        LEGACY_VALUE_REFUSAL_MESSAGE.to_owned(),
7387                        OUTBOX_INCOMPATIBLE_CODE,
7388                    )),
7389                    _ => None,
7390                };
7391                if let Some((error, code)) = failure {
7392                    failures.push((commit.clone(), error, code));
7393                    break;
7394                }
7395            }
7396        }
7397        if failures.is_empty() {
7398            return Ok(false);
7399        }
7400        self.reject_outbox_commits(
7401            failures
7402                .into_iter()
7403                .map(|(commit, message, code)| {
7404                    let details = (code == OUTBOX_INCOMPATIBLE_CODE).then(|| RejectionDetails {
7405                        field_paths: None,
7406                        reason: Some(INVALID_STORED_VALUES_REASON.to_owned()),
7407                        required_action: None,
7408                        references: None,
7409                    });
7410                    (commit, message, code, details)
7411                })
7412                .collect(),
7413            batch,
7414        )?;
7415        Ok(true)
7416    }
7417
7418    /// §7.4.4 client-local terminal drop of pending commits, each journaled as a
7419    /// rejection with `code` and `details`. Every code except
7420    /// `sync.outbox_incompatible` keeps the retained intent.
7421    #[allow(clippy::type_complexity)]
7422    fn reject_outbox_commits(
7423        &mut self,
7424        failures: Vec<(
7425            Arc<OutboxCommit>,
7426            String,
7427            &'static str,
7428            Option<RejectionDetails>,
7429        )>,
7430        batch: Option<&mut ChangeAccumulator>,
7431    ) -> Result<(), String> {
7432        // §7.4.4: one observation covers the durable outcome writes, the outbox
7433        // removal, the in-memory drop, and the overlay rebuild, so a storage fault
7434        // leaves the replica and the client unchanged, a successful recovery
7435        // publishes one batch with the rejection, outcome, and table domains, and
7436        // an ordinary open with nothing to recover publishes nothing.
7437        let rollback = self.capture();
7438        let owns_observation = batch.is_none();
7439        let owns_transaction = self.conn.is_autocommit();
7440        let mut domains = ChangeAccumulator::default();
7441        if owns_observation {
7442            self.begin_observation("syncular_value_recovery")?;
7443        }
7444        let dropped = (|| -> Result<(), String> {
7445            for (commit, message, code, details) in failures {
7446                if self.retain_failed_commits && code != OUTBOX_INCOMPATIBLE_CODE {
7447                    self.retain_failed_commit(&commit.client_commit_id, &commit.ops)?;
7448                }
7449                let representable = commit.ops.iter().all(Self::outbox_op_is_journalable);
7450                let rejection = RejectionRecord {
7451                    client_commit_id: commit.client_commit_id.clone(),
7452                    op_index: 0,
7453                    code: code.to_owned(),
7454                    message,
7455                    retryable: false,
7456                    details,
7457                    operation: representable
7458                        .then(|| commit.ops.first())
7459                        .flatten()
7460                        .map(CommitOperation::from),
7461                };
7462                self.persist_commit_outcome(
7463                    &commit.client_commit_id,
7464                    CommitOutcomeStatus::Rejected,
7465                    &[CommitOperationOutcome::Error {
7466                        rejection: rejection.clone(),
7467                    }],
7468                    representable.then_some(commit.ops.as_slice()),
7469                )?;
7470                self.leave_through(&commit.client_commit_id);
7471                self.delete_outbox_persisted(&commit.client_commit_id)?;
7472                self.outbox
7473                    .retain(|candidate| candidate.client_commit_id != commit.client_commit_id);
7474                self.rejections.push(rejection);
7475                for operation in &commit.ops {
7476                    domains.table(operation.table.as_str());
7477                }
7478            }
7479            domains.status = true;
7480            domains.rejections = true;
7481            domains.outcomes = true;
7482            self.prune_commit_outcomes()?;
7483            // The visible projection is re-derived from the surviving base + outbox.
7484            self.overlay_dirty.set(true);
7485            self.rebuild_overlay()?;
7486            Ok(())
7487        })();
7488        let result = match batch {
7489            Some(batch) => {
7490                if dropped.is_ok() {
7491                    for table in domains.tables.keys() {
7492                        batch.table(table.as_str());
7493                    }
7494                    batch.status |= domains.status;
7495                    batch.rejections |= domains.rejections;
7496                    batch.outcomes |= domains.outcomes;
7497                }
7498                dropped
7499            }
7500            None => {
7501                dropped.and_then(|()| self.finish_observation("syncular_value_recovery", domains))
7502            }
7503        };
7504        if let Err(error) = result {
7505            if owns_observation {
7506                if owns_transaction {
7507                    if let Err(rollback) = self.conn.execute_batch("ROLLBACK") {
7508                        let mut failure = self.storage_failure.borrow_mut();
7509                        let failure =
7510                            failure.get_or_insert_with(|| QueryReadFailure::from(error.clone()));
7511                        failure.rollback_failure = Some(Box::new(QueryReadFailure::from(rollback)));
7512                    }
7513                } else {
7514                    self.rollback_observation("syncular_value_recovery");
7515                }
7516            }
7517            self.restore(rollback);
7518            return Err(error);
7519        }
7520        Ok(())
7521    }
7522
7523    pub fn pending_commit_ids(&self) -> Vec<String> {
7524        self.outbox
7525            .iter()
7526            .map(|c| c.client_commit_id.clone())
7527            .collect()
7528    }
7529
7530    /// §7.1: every pending commit in FIFO order, as the TypeScript client's
7531    /// `pendingCommits()` returns it.
7532    pub fn pending_commits(&self) -> Result<Vec<PendingCommit>, String> {
7533        let mut stmt = self
7534            .conn
7535            .prepare_cached(
7536                "SELECT seq, commit_id, created_at_ms, ops_json FROM _syncular_outbox ORDER BY seq",
7537            )
7538            .map_err(|error| error.to_string())?;
7539        let rows = stmt
7540            .query_map([], |row| {
7541                Ok((
7542                    row.get(0)?,
7543                    row.get(1)?,
7544                    row.get(2)?,
7545                    row.get::<_, String>(3)?,
7546                ))
7547            })
7548            .map_err(|error| error.to_string())?;
7549        rows.map(|row| {
7550            let (seq, client_commit_id, created_at_ms, raw) =
7551                row.map_err(|error| error.to_string())?;
7552            let operations = serde_json::from_str(&raw).map_err(|error| {
7553                format!("invalid persisted outbox {client_commit_id:?}: {error}")
7554            })?;
7555            Ok(PendingCommit {
7556                seq,
7557                client_commit_id,
7558                created_at_ms,
7559                operations,
7560            })
7561        })
7562        .collect()
7563    }
7564
7565    /// §6.1: the sparse push payload bytes of every pending upsert operation,
7566    /// FIFO — exactly what the next push round would put on the wire. Used by
7567    /// conformance B.21(h) to pin cross-core byte identity.
7568    pub fn pending_payloads(&self) -> Result<Vec<Vec<u8>>, String> {
7569        let mut payloads = Vec::new();
7570        for commit in self.outbox.iter() {
7571            for op in &commit.ops {
7572                let Some(table) = self.schema.table(&op.table).filter(|_| op.upsert) else {
7573                    continue;
7574                };
7575                let Some(values) = op.presented_values(table) else {
7576                    continue;
7577                };
7578                let fallback = self.stored_key_fallback(table, &op.row_id)?;
7579                if let Ok(payload) = encode_sparse_row_json(
7580                    table,
7581                    &op.row_id,
7582                    &values,
7583                    &self.encryption,
7584                    fallback.as_ref(),
7585                ) {
7586                    payloads.push(payload);
7587                }
7588            }
7589        }
7590        Ok(payloads)
7591    }
7592
7593    pub fn conflicts(&self) -> &[ConflictRecord] {
7594        &self.conflicts
7595    }
7596
7597    pub fn rejections(&self) -> &[RejectionRecord] {
7598        &self.rejections
7599    }
7600
7601    pub fn resolve_commit_outcome(
7602        &mut self,
7603        input: ResolveCommitOutcomeInput,
7604    ) -> Result<CommitOutcome, String> {
7605        let current = self
7606            .commit_outcome(&input.client_commit_id)?
7607            .ok_or_else(|| {
7608                format!(
7609                    "sync.outcome_not_found: no durable outcome exists for {:?}",
7610                    input.client_commit_id
7611                )
7612            })?;
7613        if current.resolution != CommitOutcomeResolution::Active {
7614            return Ok(current);
7615        }
7616        if current.replacement_client_commit_id.is_some() {
7617            return Err(REPLACEMENT_PENDING.to_owned());
7618        }
7619        if input.resolution == CommitOutcomeResolution::Active {
7620            return Err("sync.invalid_request: resolution must leave active state".to_owned());
7621        }
7622        match input.resolution {
7623            CommitOutcomeResolution::Superseded => {
7624                let replacement = input
7625                    .replacement_client_commit_id
7626                    .as_deref()
7627                    .filter(|value| !value.is_empty() && *value != input.client_commit_id)
7628                    .ok_or_else(|| {
7629                        "sync.invalid_request: superseded outcomes require a distinct replacementClientCommitId"
7630                            .to_owned()
7631                    })?;
7632                let _ = replacement;
7633            }
7634            _ if input.replacement_client_commit_id.is_some() => {
7635                return Err(
7636                    "sync.invalid_request: replacementClientCommitId is valid only for superseded outcomes"
7637                        .to_owned(),
7638                );
7639            }
7640            _ => {}
7641        }
7642        let allowed = match current.status {
7643            CommitOutcomeStatus::Conflict => matches!(
7644                input.resolution,
7645                CommitOutcomeResolution::ResolvedKeepServer | CommitOutcomeResolution::Superseded
7646            ),
7647            CommitOutcomeStatus::Rejected => {
7648                matches!(
7649                    input.resolution,
7650                    CommitOutcomeResolution::Superseded
7651                        | CommitOutcomeResolution::ResolvedKeepServer
7652                )
7653            }
7654            CommitOutcomeStatus::Applied | CommitOutcomeStatus::Cached => {
7655                input.resolution == CommitOutcomeResolution::Dismissed
7656            }
7657            CommitOutcomeStatus::Replaced => false,
7658        };
7659        if !allowed {
7660            return Err(format!(
7661                "sync.invalid_request: resolution {:?} is invalid for {:?} outcome",
7662                input.resolution, current.status
7663            ));
7664        }
7665
7666        let rollback = self.capture();
7667        self.begin_observation("syncular_outcome_resolution")?;
7668        let mut batch = ChangeAccumulator::default();
7669        let result = self
7670            .release_outcome(
7671                &current,
7672                input.resolution,
7673                input.replacement_client_commit_id.as_deref(),
7674                &mut batch,
7675            )
7676            .and_then(|()| self.rebuild_overlay_if_dirty())
7677            .and_then(|()| self.finish_observation("syncular_outcome_resolution", batch));
7678        if let Err(error) = result {
7679            self.rollback_observation("syncular_outcome_resolution");
7680            self.restore(rollback);
7681            return Err(error);
7682        }
7683        self.commit_outcome(&current.client_commit_id)?
7684            .ok_or_else(|| "sync.outcome_not_found: outcome disappeared".to_owned())
7685    }
7686
7687    /// §7.2.2: record a decision against an active conflict or rejection as a
7688    /// held replacement commit and return its client commit id. Without
7689    /// `replacement` the retained envelope is kept ("keep mine"); every
7690    /// operation on a retained row takes that row's base version.
7691    pub fn replace_commit_outcome(
7692        &mut self,
7693        client_commit_id: &str,
7694        sequence: i64,
7695        replacement: Option<Vec<Mutation>>,
7696    ) -> Result<String, ClientError> {
7697        let prior = self.storage_failure.borrow_mut().take();
7698        let outcome = (|| -> Result<String, ClientError> {
7699            let Some(current) = self.commit_outcome(client_commit_id)? else {
7700                return Err(ClientError {
7701                    code: "sync.outcome_not_found".to_owned(),
7702                    message: "no durable outcome exists for the commit".to_owned(),
7703                    details: Some(json!({ "clientCommitId": client_commit_id })),
7704                    retryable: false,
7705                });
7706            };
7707            if current.resolution == CommitOutcomeResolution::Active
7708                && current.replacement_client_commit_id.is_some()
7709            {
7710                return Err(ClientError {
7711                    code: "client.replacement_pending".to_owned(),
7712                    message: "the outcome has a pending replacement".to_owned(),
7713                    details: Some(json!({ "clientCommitId": client_commit_id })),
7714                    retryable: false,
7715                });
7716            }
7717            let (Some(envelope), Some(rows)) = (current.operations, current.retained_rows) else {
7718                return Err(invalid_authoring(
7719                    "the outcome cannot be replaced",
7720                    json!({ "clientCommitId": client_commit_id }),
7721                ));
7722            };
7723            if current.sequence != sequence
7724                || current.resolution != CommitOutcomeResolution::Active
7725                || !matches!(
7726                    current.status,
7727                    CommitOutcomeStatus::Conflict | CommitOutcomeStatus::Rejected
7728                )
7729                || rows.is_empty()
7730                || envelope.len() != rows.len()
7731            {
7732                return Err(invalid_authoring(
7733                    "the outcome cannot be replaced",
7734                    json!({ "clientCommitId": client_commit_id }),
7735                ));
7736            }
7737            let ops = match replacement {
7738                None => envelope
7739                    .into_iter()
7740                    .zip(&rows)
7741                    .map(|(operation, row)| OutboxOp {
7742                        base_version: Some(row.server_version.unwrap_or(0)),
7743                        ..OutboxOp::from(operation)
7744                    })
7745                    .collect(),
7746                Some(mutations) => {
7747                    let mut ops = self.prepare_mutations(mutations)?;
7748                    for op in &mut ops {
7749                        let Some(row) = rows
7750                            .iter()
7751                            .find(|row| row.table == op.table && row.row_id == op.row_id)
7752                        else {
7753                            continue;
7754                        };
7755                        if op.base_version.is_some() {
7756                            return Err(invalid_authoring(
7757                                "an operation on a retained row takes its base version",
7758                                json!({ "table": op.table }),
7759                            ));
7760                        }
7761                        op.base_version = Some(row.server_version.unwrap_or(0));
7762                    }
7763                    ops
7764                }
7765            };
7766            Ok(self.record_outbox_commit(ops, Some(client_commit_id))?)
7767        })();
7768        self.finish_authoring(prior, outcome)
7769    }
7770
7771    /// §7.2.3: replace the operations of the pending commit `client_commit_id`
7772    /// and return `replacement_client_commit_id`. An attempted commit is fenced
7773    /// first (§6.12) over `transport`; a never-attempted one needs none.
7774    pub fn replace_pending_commit(
7775        &mut self,
7776        transport: &mut dyn Transport,
7777        client_commit_id: &str,
7778        mutations: Vec<Mutation>,
7779        replacement_client_commit_id: &str,
7780    ) -> Result<String, ClientError> {
7781        match self.prepare_pending_commit_replacement(
7782            client_commit_id,
7783            mutations,
7784            replacement_client_commit_id,
7785        )? {
7786            None => Ok(replacement_client_commit_id.to_owned()),
7787            Some(prepared) => {
7788                let reply = prepared.exchange(transport);
7789                self.apply_fence_round(prepared, reply)
7790            }
7791        }
7792    }
7793
7794    /// The owner half of [`SyncClient::replace_pending_commit`]. `None` means
7795    /// the replacement is complete (or an earlier call with the same
7796    /// replacement id completed it); otherwise send the fence round and apply
7797    /// its reply with [`SyncClient::apply_fence_round`].
7798    pub fn prepare_pending_commit_replacement(
7799        &mut self,
7800        client_commit_id: &str,
7801        mutations: Vec<Mutation>,
7802        replacement_client_commit_id: &str,
7803    ) -> Result<Option<PreparedFenceRound>, ClientError> {
7804        let prior = self.storage_failure.borrow_mut().take();
7805        let outcome = (|| -> Result<Option<PreparedFenceRound>, ClientError> {
7806            let Some(original) = self
7807                .outbox
7808                .iter()
7809                .find(|commit| commit.client_commit_id == client_commit_id)
7810                .cloned()
7811            else {
7812                return match self.commit_outcome(client_commit_id)? {
7813                    Some(outcome)
7814                        if Self::is_replaced(&outcome)
7815                            && outcome.replacement_client_commit_id.as_deref()
7816                                == Some(replacement_client_commit_id) =>
7817                    {
7818                        Ok(None)
7819                    }
7820                    _ => Err(ClientError {
7821                        code: "sync.outcome_not_found".to_owned(),
7822                        message: "no pending commit exists for the id".to_owned(),
7823                        details: Some(json!({ "clientCommitId": client_commit_id })),
7824                        retryable: false,
7825                    }),
7826                };
7827            };
7828            if replacement_client_commit_id.is_empty()
7829                || self
7830                    .outbox
7831                    .iter()
7832                    .any(|commit| commit.client_commit_id == replacement_client_commit_id)
7833                || self.commit_outcome(replacement_client_commit_id)?.is_some()
7834            {
7835                return Err(invalid_authoring(
7836                    "the replacement client commit id must be unused",
7837                    json!({ "replacementClientCommitId": replacement_client_commit_id }),
7838                ));
7839            }
7840            // §7.2.2: a held replacement waits for its proof under its own id.
7841            let held: bool = self
7842                .conn
7843                .query_row(
7844                    "SELECT EXISTS(SELECT 1 FROM _syncular_commit_outcomes
7845                      WHERE resolution = 'active' AND replacement_client_commit_id = ?1)",
7846                    [client_commit_id],
7847                    |row| row.get(0),
7848                )
7849                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
7850            if held {
7851                return Err(REPLACEMENT_PENDING.to_owned().into());
7852            }
7853            let full_rows: Vec<bool> = mutations
7854                .iter()
7855                .map(|mutation| matches!(mutation, Mutation::Upsert { .. }))
7856                .collect();
7857            let mut operations = self.prepare_mutations(mutations)?;
7858            for (operation, full_row) in operations.iter_mut().zip(full_rows) {
7859                let touched: Vec<&OutboxOp> = original
7860                    .ops
7861                    .iter()
7862                    .filter(|op| op.table == operation.table && op.row_id == operation.row_id)
7863                    .collect();
7864                // §7.1: a full-row upsert of a row the original inserted keeps
7865                // the insert intent the original recorded.
7866                operation.insert |= full_row && touched.iter().any(|op| op.insert);
7867                if let Some(first) = touched.first() {
7868                    operation.base_version = first.base_version;
7869                }
7870            }
7871            let attempted: bool = self
7872                .conn
7873                .query_row(
7874                    "SELECT attempted FROM _syncular_outbox WHERE commit_id = ?1",
7875                    [client_commit_id],
7876                    |row| row.get(0),
7877                )
7878                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
7879            if !attempted {
7880                self.replace_outbox_commit(
7881                    client_commit_id,
7882                    operations,
7883                    replacement_client_commit_id,
7884                )?;
7885                return Ok(None);
7886            }
7887            if self.transport_closed() {
7888                return Err(ClientError {
7889                    code: "sync.offline".to_owned(),
7890                    message: "transport gate is closed".to_owned(),
7891                    details: None,
7892                    retryable: false,
7893                });
7894            }
7895            if self.active_round.is_some() || self.fence_round.is_some() {
7896                return Err(ClientError {
7897                    code: "client.round_in_progress".to_owned(),
7898                    message: "a sync round is already in flight".to_owned(),
7899                    details: None,
7900                    retryable: false,
7901                });
7902            }
7903            if self.realtime_policy == RealtimePolicy::Required
7904                && self.realtime_state != RealtimeState::Connected
7905            {
7906                return Err(ClientError {
7907                    code: REALTIME_UNAVAILABLE_CODE.to_owned(),
7908                    message: "the realtime socket is not connected".to_owned(),
7909                    details: None,
7910                    retryable: true,
7911                });
7912            }
7913            let header = Frame::ReqHeader {
7914                client_id: self.client_id.clone(),
7915                schema_version: self.schema.version,
7916                log_epoch: self.get_meta(LOG_EPOCH_KEY)?,
7917                outbox_id: self.get_meta(OUTBOX_ID_KEY)?,
7918            };
7919            let id = uuid::Uuid::new_v4();
7920            self.fence_round = Some(id);
7921            Ok(Some(PreparedFenceRound {
7922                id,
7923                client_commit_id: client_commit_id.to_owned(),
7924                replacement_client_commit_id: replacement_client_commit_id.to_owned(),
7925                operations,
7926                request: encode_message(&Message {
7927                    wire_version: WIRE_VERSION,
7928                    msg_kind: MsgKind::Request,
7929                    frames: vec![
7930                        header,
7931                        Frame::FenceCommit {
7932                            client_commit_id: client_commit_id.to_owned(),
7933                        },
7934                    ],
7935                }),
7936                realtime: self.realtime_state == RealtimeState::Connected,
7937            }))
7938        })();
7939        self.finish_authoring(prior, outcome)
7940    }
7941
7942    /// Apply the reply of a [`PreparedFenceRound`] on the owner (§6.12,
7943    /// §7.2.3) and return the replacement's id. No network I/O. A stored
7944    /// result settles the original through the push-result path and fails
7945    /// with `client.commit_settled`.
7946    pub fn apply_fence_round(
7947        &mut self,
7948        prepared: PreparedFenceRound,
7949        reply: Result<Vec<u8>, TransportError>,
7950    ) -> Result<String, ClientError> {
7951        if self.fence_round != Some(prepared.id) {
7952            return Err(ClientError {
7953                code: "client.round_cancelled".to_owned(),
7954                message: "fence round belongs to a released client context".to_owned(),
7955                details: None,
7956                retryable: false,
7957            });
7958        }
7959        self.fence_round = None;
7960        let prior = self.storage_failure.borrow_mut().take();
7961        let outcome = (|| -> Result<String, ClientError> {
7962            let id = prepared.client_commit_id.as_str();
7963            let invalid = || ClientError {
7964                code: "client.invalid_host_response".to_owned(),
7965                message: "the fence response does not answer the fenced commit".to_owned(),
7966                details: Some(json!({ "clientCommitId": id })),
7967                retryable: false,
7968            };
7969            let bytes = reply.map_err(|error| ClientError {
7970                retryable: error
7971                    .details
7972                    .as_ref()
7973                    .and_then(|details| details.get("retryable"))
7974                    == Some(&Value::Bool(true)),
7975                code: error.code,
7976                message: error.message,
7977                details: error.details,
7978            })?;
7979            let response = decode_message(&bytes).map_err(|_| invalid())?;
7980            if response.msg_kind != MsgKind::Response {
7981                return Err(invalid());
7982            }
7983            let mut frames = response
7984                .frames
7985                .into_iter()
7986                .filter(|frame| !matches!(frame, Frame::Keepalive));
7987            match frames.next() {
7988                // §1.6: a schema-floor response; the client stops syncing as
7989                // a sync round's floor stops it.
7990                Some(Frame::RespHeader {
7991                    required_schema_version: Some(required),
7992                    latest_schema_version,
7993                    ..
7994                }) => {
7995                    self.set_schema_floor(Some(SchemaFloor {
7996                        required_schema_version: Some(required),
7997                        latest_schema_version,
7998                    }))?;
7999                    return Err(ClientError {
8000                        code: "sync.schema_mismatch".to_owned(),
8001                        message: "the server requires a newer schema version".to_owned(),
8002                        details: Some(json!({ "requiredSchemaVersion": required })),
8003                        retryable: false,
8004                    });
8005                }
8006                Some(Frame::RespHeader {
8007                    reset_required: false,
8008                    ..
8009                }) => {}
8010                _ => return Err(invalid()),
8011            }
8012            let answer = frames.next();
8013            let rest: Vec<Frame> = frames.collect();
8014            match answer {
8015                // A server that predates the frame refuses the request.
8016                Some(Frame::Error {
8017                    code,
8018                    message,
8019                    retryable,
8020                    details,
8021                    ..
8022                }) => Err(ClientError {
8023                    code,
8024                    message,
8025                    details: details.and_then(|details| serde_json::from_str(&details.0).ok()),
8026                    retryable,
8027                }),
8028                Some(Frame::CommitFenced { client_commit_id })
8029                    if client_commit_id == id && rest.is_empty() =>
8030                {
8031                    self.replace_outbox_commit(
8032                        id,
8033                        prepared.operations,
8034                        &prepared.replacement_client_commit_id,
8035                    )?;
8036                    Ok(prepared.replacement_client_commit_id)
8037                }
8038                Some(Frame::PushResult {
8039                    client_commit_id,
8040                    status,
8041                    commit_seq,
8042                    results,
8043                }) if client_commit_id == id => {
8044                    let mut details = HashMap::new();
8045                    match rest.as_slice() {
8046                        [] => {}
8047                        [Frame::PushResultDetails {
8048                            client_commit_id: owner,
8049                            entries,
8050                        }] if owner == id => {
8051                            let parsed = entries
8052                                .iter()
8053                                .map(|entry| -> Result<_, String> {
8054                                    Ok((entry.op_index, RejectionDetails::parse(&entry.details.0)?))
8055                                })
8056                                .collect::<Result<BTreeMap<i32, RejectionDetails>, String>>()
8057                                .map_err(|_| invalid())?;
8058                            details.insert(id.to_owned(), parsed);
8059                        }
8060                        _ => return Err(invalid()),
8061                    }
8062                    let settled = if status == PushStatus::Rejected {
8063                        "rejected"
8064                    } else {
8065                        "applied"
8066                    };
8067                    let mut report = SyncReport::default();
8068                    self.handle_push_results(
8069                        &[Frame::PushResult {
8070                            client_commit_id,
8071                            status,
8072                            commit_seq,
8073                            results,
8074                        }],
8075                        &HashSet::from([id]),
8076                        &details,
8077                        &mut report,
8078                        Some(id),
8079                    )
8080                    .map_err(|_| ClientError {
8081                        code: "client.outcome_persistence_failed".to_owned(),
8082                        message: "local commit outcome could not be persisted".to_owned(),
8083                        details: None,
8084                        retryable: false,
8085                    })?;
8086                    // §6.3: a serving failure is no outcome; the commit stays.
8087                    if !report.retryable.is_empty() {
8088                        return Err(ClientError {
8089                            code: "sync.idempotency_cache_miss".to_owned(),
8090                            message: "the server could not serve the stored result".to_owned(),
8091                            details: Some(json!({ "clientCommitId": id })),
8092                            retryable: true,
8093                        });
8094                    }
8095                    Err(ClientError {
8096                        code: "client.commit_settled".to_owned(),
8097                        message: "the commit already has a server outcome".to_owned(),
8098                        details: Some(json!({ "clientCommitId": id, "status": settled })),
8099                        retryable: false,
8100                    })
8101                }
8102                _ => Err(invalid()),
8103            }
8104        })();
8105        self.finish_authoring(prior, outcome)
8106    }
8107
8108    /// §7.2.3: swap a pending commit's operations and id in place (same
8109    /// outbox sequence), re-derive the overlay of its rows and every later
8110    /// commit, and journal the original as `replaced`, in one transaction
8111    /// with one change batch.
8112    fn replace_outbox_commit(
8113        &mut self,
8114        client_commit_id: &str,
8115        ops: Vec<OutboxOp>,
8116        replacement: &str,
8117    ) -> Result<(), ClientError> {
8118        let Some(index) = self
8119            .outbox
8120            .iter()
8121            .position(|commit| commit.client_commit_id == client_commit_id)
8122        else {
8123            return Err(ClientError {
8124                code: "sync.outcome_not_found".to_owned(),
8125                message: "no pending commit exists for the id".to_owned(),
8126                details: Some(json!({ "clientCommitId": client_commit_id })),
8127                retryable: false,
8128            });
8129        };
8130        let original = self.outbox[index].clone();
8131        let commit = OutboxCommit {
8132            client_commit_id: replacement.to_owned(),
8133            ops,
8134        };
8135        let rollback = self.capture();
8136        self.begin_observation("syncular_pending_replacement")?;
8137        let mut batch = ChangeAccumulator::default();
8138        let replaced = (|| {
8139            let (seq, created_at_ms): (i64, i64) = self
8140                .conn
8141                .query_row(
8142                    "SELECT seq, created_at_ms FROM _syncular_outbox WHERE commit_id = ?1",
8143                    [client_commit_id],
8144                    |row| Ok((row.get(0)?, row.get(1)?)),
8145                )
8146                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8147            self.persist_outbox_insert(&commit)?;
8148            self.leave_through(client_commit_id);
8149            self.delete_outbox_persisted(client_commit_id)?;
8150            // §7.2.1: journaled as a purge journals its drops, decided.
8151            let results = (0..original.ops.len())
8152                .map(|op_index| CommitOperationOutcome::Error {
8153                    rejection: RejectionRecord {
8154                        client_commit_id: client_commit_id.to_owned(),
8155                        op_index: op_index as i32,
8156                        code: COMMIT_REPLACED_CODE.to_owned(),
8157                        message: "the commit was replaced before the server applied it".to_owned(),
8158                        retryable: false,
8159                        details: None,
8160                        operation: None,
8161                    },
8162                })
8163                .collect::<Vec<_>>();
8164            let results_json =
8165                serde_json::to_string(&results).map_err(|error| error.to_string())?;
8166            self.conn
8167                .execute(
8168                    "UPDATE _syncular_outbox SET seq = ?1, created_at_ms = ?2 WHERE commit_id = ?3",
8169                    rusqlite::params![seq, created_at_ms, replacement],
8170                )
8171                .and_then(|_| {
8172                    self.conn.execute(
8173                        "INSERT INTO _syncular_commit_outcomes (
8174                           client_commit_id, status, recorded_at_ms, results_json, resolution,
8175                           resolved_at_ms, replacement_client_commit_id
8176                         ) VALUES (?1, 'rejected', ?2, ?3, 'superseded', ?2, ?4)",
8177                        rusqlite::params![
8178                            client_commit_id,
8179                            self.clock_now_ms(),
8180                            results_json,
8181                            replacement
8182                        ],
8183                    )
8184                })
8185                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8186            self.prune_commit_outcomes()?;
8187            for op in original.ops.iter().chain(&commit.ops) {
8188                self.overlay_dirty.table(&op.table);
8189                batch.table(&op.table);
8190            }
8191            self.outbox[index] = Arc::new(commit);
8192            batch.status = true;
8193            batch.outcomes = true;
8194            self.rebuild_overlay_if_dirty()?;
8195            self.finish_observation("syncular_pending_replacement", batch)
8196        })();
8197        if let Err(error) = replaced {
8198            self.rollback_observation("syncular_pending_replacement");
8199            self.restore(rollback);
8200            return Err(error.into());
8201        }
8202        Ok(())
8203    }
8204
8205    /// Internal host step at the start of an idle drive (§7.2.2): capture
8206    /// every pending decision with the units and epochs of this drive.
8207    #[doc(hidden)]
8208    pub fn prepare_replacements(&self) -> Result<Vec<CurrentBasePreparation>, String> {
8209        let mut stmt = self
8210            .conn
8211            .prepare_cached(
8212                "SELECT client_commit_id, seq, replacement_client_commit_id
8213                   FROM _syncular_commit_outcomes
8214                  WHERE resolution = 'active' AND replacement_client_commit_id IS NOT NULL
8215                  ORDER BY seq ASC",
8216            )
8217            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8218        let decisions = stmt
8219            .query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
8220            .and_then(|rows| rows.collect::<Result<Vec<(String, i64, String)>, _>>())
8221            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8222        if decisions.is_empty() {
8223            return Ok(Vec::new());
8224        }
8225        let units = self.stored(load_units(&self.conn))?;
8226        Ok(decisions
8227            .into_iter()
8228            .map(
8229                |(client_commit_id, sequence, replacement)| CurrentBasePreparation {
8230                    client_commit_id,
8231                    sequence,
8232                    replacement: Some(replacement),
8233                    units: units.clone(),
8234                    transport_epoch: self.transport_epoch,
8235                    registration_epoch: self.registration_epoch,
8236                    security_epoch: self.security_epoch,
8237                },
8238            )
8239            .collect())
8240    }
8241
8242    /// Internal host step when an idle drive reaches idle (§7.2.2): write,
8243    /// refuse, or keep each decision captured at the drive's start. Returns
8244    /// whether a decision was written, so the drive runs another round.
8245    #[doc(hidden)]
8246    pub fn settle_replacements(
8247        &mut self,
8248        decisions: &[CurrentBasePreparation],
8249        drive: &SyncOutcome,
8250    ) -> Result<bool, String> {
8251        if self.transport_closed() {
8252            return Ok(false);
8253        }
8254        let mut written = false;
8255        for decision in decisions {
8256            // A registration change during the drive says nothing about the
8257            // base; the decision waits for the next drive.
8258            if decision.registration_epoch != self.registration_epoch {
8259                continue;
8260            }
8261            let Some(replacement) = decision.replacement.as_deref() else {
8262                continue;
8263            };
8264            let Some(current) =
8265                self.commit_outcome(&decision.client_commit_id)?
8266                    .filter(|current| {
8267                        current.resolution == CommitOutcomeResolution::Active
8268                            && current.replacement_client_commit_id.as_deref() == Some(replacement)
8269                    })
8270            else {
8271                continue;
8272            };
8273            let held = self
8274                .outbox
8275                .iter()
8276                .find(|commit| commit.client_commit_id == replacement)
8277                .cloned();
8278            let refused = match &held {
8279                // A revocation drop (§3.3) or a crash already ended the
8280                // replacement; its own journal entry records what happened.
8281                None => None,
8282                Some(commit) => match self.finish_current_base(decision.clone(), drive.clone()) {
8283                    CurrentBaseProof {
8284                        rows: Some(rows), ..
8285                    } => {
8286                        let proven = commit.ops.iter().all(|op| {
8287                            rows.iter()
8288                                .find(|row| row.table == op.table && row.row_id == op.row_id)
8289                                .is_none_or(|row| {
8290                                    op.base_version == Some(row.server_version.unwrap_or(0))
8291                                })
8292                        });
8293                        written |= proven;
8294                        (!proven).then(|| "base_moved".to_owned())
8295                    }
8296                    CurrentBaseProof {
8297                        reason:
8298                            Some(
8299                                reason @ (CurrentBaseProofReason::SchemaFloor
8300                                | CurrentBaseProofReason::MissingCoverage
8301                                | CurrentBaseProofReason::Revoked
8302                                | CurrentBaseProofReason::OutcomeUnavailable),
8303                            ),
8304                        ..
8305                    } => Some(
8306                        serde_json::to_value(reason)
8307                            .ok()
8308                            .and_then(|reason| reason.as_str().map(str::to_owned))
8309                            .ok_or("sync.local_corrupt")?,
8310                    ),
8311                    _ => continue,
8312                },
8313            };
8314            // One transaction: the original outcome is superseded first, so
8315            // the refused replacement retains its intent over the restored
8316            // server base.
8317            let rollback = self.capture();
8318            self.begin_observation("syncular_replacement")?;
8319            let mut batch = ChangeAccumulator::default();
8320            let result = self
8321                .release_outcome(
8322                    &current,
8323                    CommitOutcomeResolution::Superseded,
8324                    Some(replacement),
8325                    &mut batch,
8326                )
8327                .and_then(|()| self.rebuild_overlay_if_dirty())
8328                .and_then(|()| match (refused, held) {
8329                    (Some(reason), Some(commit)) => self.reject_outbox_commits(
8330                        vec![(
8331                            commit,
8332                            "the replacement could not be written on a proven base".to_owned(),
8333                            REPLACEMENT_REFUSED_CODE,
8334                            Some(RejectionDetails {
8335                                field_paths: None,
8336                                reason: Some(reason),
8337                                required_action: None,
8338                                references: None,
8339                            }),
8340                        )],
8341                        Some(&mut batch),
8342                    ),
8343                    _ => Ok(()),
8344                })
8345                .and_then(|()| self.finish_observation("syncular_replacement", batch));
8346            if let Err(error) = result {
8347                self.rollback_observation("syncular_replacement");
8348                self.restore(rollback);
8349                return Err(error);
8350            }
8351        }
8352        if written {
8353            self.set_sync_needed(true, true);
8354        }
8355        Ok(written)
8356    }
8357
8358    /// §7.2.1 explicit resolution inside the caller's observation: record the
8359    /// resolution, release the retained aggregate and mark its tables for the
8360    /// overlay rebuild, which restores the server base and replays what
8361    /// remains over it.
8362    fn release_outcome(
8363        &mut self,
8364        current: &CommitOutcome,
8365        resolution: CommitOutcomeResolution,
8366        replacement: Option<&str>,
8367        batch: &mut ChangeAccumulator,
8368    ) -> Result<(), String> {
8369        self.conn
8370            .execute(
8371                "UPDATE _syncular_commit_outcomes
8372                    SET resolution = ?1, resolved_at_ms = ?2,
8373                        replacement_client_commit_id = ?3
8374                  WHERE client_commit_id = ?4 AND resolution = 'active'",
8375                rusqlite::params![
8376                    Self::outcome_resolution_name(resolution),
8377                    self.clock_now_ms(),
8378                    replacement,
8379                    current.client_commit_id
8380                ],
8381            )
8382            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8383        self.conn
8384            .execute(
8385                "DELETE FROM _syncular_failed_commits WHERE client_commit_id = ?1",
8386                rusqlite::params![current.client_commit_id],
8387            )
8388            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8389        for (commit, _) in self.failed_commits.iter() {
8390            if commit.client_commit_id == current.client_commit_id {
8391                for operation in &commit.ops {
8392                    self.overlay_dirty.table(&operation.table);
8393                }
8394            }
8395        }
8396        self.failed_commits
8397            .retain(|(commit, _)| commit.client_commit_id != current.client_commit_id);
8398        self.prune_commit_outcomes()?;
8399        self.conflicts
8400            .retain(|record| record.client_commit_id != current.client_commit_id);
8401        self.rejections
8402            .retain(|record| record.client_commit_id != current.client_commit_id);
8403        batch.conflicts |= current.status == CommitOutcomeStatus::Conflict;
8404        batch.rejections |= current.status == CommitOutcomeStatus::Rejected;
8405        batch.outcomes = true;
8406        for operation in current.operations.iter().flatten() {
8407            batch.table(&operation.table);
8408        }
8409        Ok(())
8410    }
8411
8412    pub fn schema_floor(&self) -> Option<&SchemaFloor> {
8413        self.schema_floor.as_ref()
8414    }
8415
8416    /// §7.3.5: the client's opaque auth-lease state, if any.
8417    pub fn lease_state(&self) -> Option<&LeaseState> {
8418        self.lease_state.as_ref()
8419    }
8420
8421    /// §7.3.5: record a request-level lease error (stop-and-surface). Only
8422    /// the two lease codes set it; other errors leave leaseState untouched.
8423    fn record_lease_error(&mut self, code: &str) -> Result<(), String> {
8424        if code != "sync.auth_lease_required" && code != "sync.auth_lease_revoked" {
8425            return Ok(());
8426        }
8427        let mut next = self.lease_state.clone().unwrap_or_default();
8428        next.error_code = Some(code.to_owned());
8429        self.set_lease_state(Some(next))
8430    }
8431
8432    fn set_lease_state(&mut self, next: Option<LeaseState>) -> Result<(), String> {
8433        if self.lease_state == next {
8434            return Ok(());
8435        }
8436        self.begin_observation("syncular_lease")?;
8437        let rollback = self.capture();
8438        self.lease_state = next;
8439        let persisted = match &self.lease_state {
8440            Some(lease) => serde_json::to_string(lease)
8441                .map_err(|error| error.to_string())
8442                .and_then(|json| self.set_meta(LEASE_STATE_KEY, &json)),
8443            None => self.delete_meta(LEASE_STATE_KEY),
8444        };
8445        let batch = ChangeAccumulator {
8446            status: true,
8447            ..ChangeAccumulator::default()
8448        };
8449        if let Err(error) =
8450            persisted.and_then(|()| self.finish_observation("syncular_lease", batch))
8451        {
8452            self.rollback_observation("syncular_lease");
8453            self.restore(rollback);
8454            return Err(error);
8455        }
8456        Ok(())
8457    }
8458
8459    fn set_schema_floor(&mut self, next: Option<SchemaFloor>) -> Result<(), String> {
8460        if self.schema_floor == next {
8461            return Ok(());
8462        }
8463        self.begin_observation("syncular_schema_floor")?;
8464        let rollback = self.capture();
8465        self.stopped = next.is_some();
8466        self.schema_floor = next;
8467        let persisted = match &self.schema_floor {
8468            Some(floor) => serde_json::to_string(floor)
8469                .map_err(|error| error.to_string())
8470                .and_then(|json| self.set_meta(SCHEMA_FLOOR_KEY, &json)),
8471            None => self.delete_meta(SCHEMA_FLOOR_KEY),
8472        };
8473        let batch = ChangeAccumulator {
8474            status: true,
8475            ..ChangeAccumulator::default()
8476        };
8477        if let Err(error) =
8478            persisted.and_then(|()| self.finish_observation("syncular_schema_floor", batch))
8479        {
8480            self.rollback_observation("syncular_schema_floor");
8481            self.restore(rollback);
8482            return Err(error);
8483        }
8484        Ok(())
8485    }
8486
8487    fn set_upgrading(&mut self, value: bool) {
8488        if self.upgrading == value {
8489            return;
8490        }
8491        if self.begin_observation("syncular_upgrading").is_err() {
8492            return;
8493        }
8494        self.upgrading = value;
8495        self.upgrade_kept_tables &= value;
8496        let batch = ChangeAccumulator {
8497            status: true,
8498            ..ChangeAccumulator::default()
8499        };
8500        if self
8501            .finish_observation("syncular_upgrading", batch)
8502            .is_err()
8503        {
8504            self.rollback_observation("syncular_upgrading");
8505        }
8506    }
8507
8508    pub fn sync_needed(&self) -> bool {
8509        self.sync_needed
8510    }
8511
8512    pub fn read_rows(&self, table: &str) -> Result<Vec<RowState>, String> {
8513        let schema_table = self
8514            .schema
8515            .table(table)
8516            .ok_or_else(|| format!("unknown table {table:?}"))?;
8517        let sql = format!(
8518            "SELECT * FROM {} ORDER BY {} ASC",
8519            visible_table(table),
8520            quote_ident(&schema_table.primary_key)
8521        );
8522        let mut stmt = self
8523            .conn
8524            .prepare(&sql)
8525            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8526        let mut rows = stmt
8527            .query([])
8528            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8529        let mut out = Vec::new();
8530        while let Some(row) = rows
8531            .next()
8532            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
8533        {
8534            let mut values = Map::new();
8535            for (i, column) in schema_table.columns.iter().enumerate() {
8536                let value = row
8537                    .get_ref(i)
8538                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8539                values.insert(column.name.clone(), sql_ref_to_json(column, value));
8540            }
8541            let version: i64 = row
8542                .get(schema_table.columns.len())
8543                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
8544            let row_id = match values.get(&schema_table.primary_key) {
8545                Some(Value::String(s)) => s.clone(),
8546                Some(Value::Number(n)) => n.to_string(),
8547                Some(Value::Bool(b)) => b.to_string(),
8548                other => format!("{}", other.cloned().unwrap_or(Value::Null)),
8549            };
8550            let sealed_key = if schema_table.has_encrypted_columns() {
8551                row.get(schema_table.columns.len() + 1)
8552                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
8553            } else {
8554                None
8555            };
8556            out.push(RowState {
8557                row_id,
8558                version,
8559                values,
8560                sealed_key,
8561            });
8562        }
8563        Ok(out)
8564    }
8565
8566    // -- §5.10.5 native CRDT (the `crdt-yjs` feature) --------------------------
8567    //
8568    // The Rust face of the §5.10.4 client model: a local crdt edit loads the
8569    // current stored (server-merged ⊕ pending-overlay) column bytes, applies
8570    // the op with `yrs`, re-encodes the whole doc state, and records a
8571    // baseVersion-less sparse upsert carrying only the primary key and the
8572    // crdt column (§5.10.3, §6.6). No local merge — merging is server-side;
8573    // the overlay re-materializes the edit immediately (optimistic apply,
8574    // §7.1) and the server-merged bytes arrive on the next pull, idempotently.
8575    // Byte-compatible with `@syncular/crdt-yjs`.
8576
8577    /// The current stored value of a `crdt` column for one row — the visible
8578    /// (optimistic) bytes, or `None` when the row is absent or the column is
8579    /// NULL (the empty document, §5.10.1). Errors if the column is not a
8580    /// `crdt` column (guards the app against a typo'd column name).
8581    #[cfg(feature = "crdt-yjs")]
8582    fn crdt_column_bytes(
8583        &self,
8584        table: &str,
8585        row_id: &str,
8586        column: &str,
8587    ) -> Result<Option<Vec<u8>>, String> {
8588        let schema_table = self
8589            .schema
8590            .table(table)
8591            .ok_or_else(|| format!("unknown table {table:?}"))?;
8592        let col = schema_table
8593            .columns
8594            .iter()
8595            .find(|c| c.name == column)
8596            .ok_or_else(|| format!("table {table:?} has no column {column:?}"))?;
8597        if col.ty != ColumnType::Crdt {
8598            return Err(format!("column {column:?} is not a crdt column (§5.10.1)"));
8599        }
8600        let sql = format!(
8601            "SELECT {} FROM {} WHERE {}",
8602            quote_ident(column),
8603            visible_table(table),
8604            row_id_predicate(schema_table)
8605        );
8606        let bytes: Option<Vec<u8>> = self
8607            .conn
8608            .prepare_cached(&sql)
8609            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
8610            .query_row(rusqlite::params![row_id], |row| {
8611                row.get::<_, Option<Vec<u8>>>(0)
8612            })
8613            .map_err(|e| match e {
8614                rusqlite::Error::QueryReturnedNoRows => "no such row".to_owned(),
8615                other => Self::sqlite_failure(&self.storage_failure, other),
8616            })?;
8617        Ok(bytes)
8618    }
8619
8620    /// §5.10.4 materialize: the collaborative text of a `crdt` column, decoded
8621    /// from the stored bytes with `yrs` — `YjsColumn.text(name).toString()`.
8622    /// An absent row / NULL column is the empty document (empty string).
8623    #[cfg(feature = "crdt-yjs")]
8624    pub fn crdt_text(
8625        &self,
8626        table: &str,
8627        row_id: &str,
8628        column: &str,
8629        name: &str,
8630    ) -> Result<String, String> {
8631        let bytes = self
8632            .crdt_column_bytes(table, row_id, column)?
8633            .unwrap_or_default();
8634        crate::crdt::text(&bytes, name)
8635    }
8636
8637    /// §5.10.4 push-an-update: apply a text insert to a `crdt` column and
8638    /// record the resulting crdt-only sparse operation. Returns the enqueued
8639    /// `clientCommitId`.
8640    #[cfg(feature = "crdt-yjs")]
8641    pub fn crdt_insert_text(
8642        &mut self,
8643        table: &str,
8644        row_id: &str,
8645        column: &str,
8646        name: &str,
8647        index: u32,
8648        value: &str,
8649    ) -> Result<String, ClientError> {
8650        let prior = self.storage_failure.borrow_mut().take();
8651        let outcome = (|| -> Result<String, ClientError> {
8652            let current = self
8653                .crdt_column_bytes(table, row_id, column)?
8654                .unwrap_or_default();
8655            let update = crate::crdt::insert_text(&current, name, index, value)?;
8656            self.perform_crdt_push_update(table, row_id, column, &update)
8657        })();
8658        self.finish_authoring(prior, outcome)
8659    }
8660
8661    /// §5.10.4 push-an-update: apply a text delete to a `crdt` column and
8662    /// record the resulting crdt-only sparse operation. Returns the enqueued
8663    /// `clientCommitId`.
8664    #[cfg(feature = "crdt-yjs")]
8665    pub fn crdt_delete_text(
8666        &mut self,
8667        table: &str,
8668        row_id: &str,
8669        column: &str,
8670        name: &str,
8671        index: u32,
8672        len: u32,
8673    ) -> Result<String, ClientError> {
8674        let prior = self.storage_failure.borrow_mut().take();
8675        let outcome = (|| -> Result<String, ClientError> {
8676            let current = self
8677                .crdt_column_bytes(table, row_id, column)?
8678                .unwrap_or_default();
8679            let update = crate::crdt::delete_text(&current, name, index, len)?;
8680            self.perform_crdt_push_update(table, row_id, column, &update)
8681        })();
8682        self.finish_authoring(prior, outcome)
8683    }
8684
8685    /// §5.10.4 generic escape hatch: apply an arbitrary Yjs update onto a
8686    /// `crdt` column's current state and record the resulting crdt-only sparse
8687    /// operation. The app authored the update with its own `yrs` model.
8688    /// Returns the enqueued `clientCommitId`.
8689    #[cfg(feature = "crdt-yjs")]
8690    pub fn crdt_apply_update(
8691        &mut self,
8692        table: &str,
8693        row_id: &str,
8694        column: &str,
8695        update: &[u8],
8696    ) -> Result<String, ClientError> {
8697        let prior = self.storage_failure.borrow_mut().take();
8698        let outcome = (|| -> Result<String, ClientError> {
8699            let current = self
8700                .crdt_column_bytes(table, row_id, column)?
8701                .unwrap_or_default();
8702            let next = crate::crdt::apply_update(&current, update)?;
8703            self.perform_crdt_push_update(table, row_id, column, &next)
8704        })();
8705        self.finish_authoring(prior, outcome)
8706    }
8707
8708    /// Shared tail of the crdt edit methods: record a §6.1 sparse crdt-only
8709    /// upsert — the primary key plus the crdt column, no `baseVersion` — and
8710    /// enqueue it. The server merges the crdt column and leaves every other
8711    /// column untouched (§5.10.3), so a baseVersion-less crdt edit cannot
8712    /// clobber a concurrent edit to another column. A locally absent row
8713    /// records the same partial operation; the server answers per §6.2.
8714    #[cfg(feature = "crdt-yjs")]
8715    fn perform_crdt_push_update(
8716        &mut self,
8717        table: &str,
8718        row_id: &str,
8719        column: &str,
8720        crdt_bytes: &[u8],
8721    ) -> Result<String, ClientError> {
8722        let mut bytes_obj = Map::new();
8723        bytes_obj.insert("$bytes".to_owned(), Value::from(bytes_to_hex(crdt_bytes)));
8724        let mut partial = Map::new();
8725        partial.insert(column.to_owned(), Value::Object(bytes_obj));
8726        self.perform_patch(table, row_id, partial, None)
8727    }
8728
8729    /// Run an arbitrary read-only SQL query against the local database and
8730    /// return each row as a `column-name → JSON value` map. This is the seam
8731    /// the React `useSyncQuery` live-query API needs (it takes app-authored
8732    /// SQL over the visible tables/views, not a fixed table read like
8733    /// [`read_rows`]).
8734    ///
8735    /// Bound `params` are the driver value forms: JSON strings/numbers/bools/
8736    /// null bind directly; a `{"$bytes": hex}` object binds as a BLOB — the
8737    /// same envelope the command surface uses everywhere else. Output BLOB
8738    /// columns come back as `{"$bytes": hex}` to round-trip cleanly.
8739    ///
8740    /// The result column typing is dynamic (SQLite's stored affinity), because
8741    /// arbitrary SQL can alias, join, and compute — there is no schema column
8742    /// to consult per output cell, unlike [`read_rows`].
8743    pub fn query(&self, sql: &str, params: &[QueryValue]) -> Result<Vec<QueryRow>, String> {
8744        query_connection(&self.conn, sql, params).map_err(|failure| failure.to_string())
8745    }
8746
8747    /// Repository benchmark and conformance access, present only with `bench-internals`.
8748    #[cfg(feature = "bench-internals")]
8749    #[doc(hidden)]
8750    pub fn benchmark_connection(&mut self) -> &mut Connection {
8751        &mut self.conn
8752    }
8753
8754    /// Private benchmark intervals; absent from ordinary builds and diagnostics.
8755    #[cfg(feature = "bench-internals")]
8756    #[doc(hidden)]
8757    pub fn benchmark_phases(
8758        &self,
8759        enabled: Option<bool>,
8760        reset: bool,
8761    ) -> Result<Option<Value>, String> {
8762        self.benchmark_phases.configure(enabled, reset)?;
8763        Ok(self.benchmark_phases.snapshot())
8764    }
8765
8766    /// §5.11 native ceiling: refuse a declared authority query whose authored
8767    /// statement reads a table or column outside `ceiling` (table to permitted
8768    /// columns) or performs an action other than SELECT, READ, or a
8769    /// deterministic core function. The refusal is
8770    /// `client.authority_read_forbidden` with `{ query, reason: "ceiling",
8771    /// table, column }`.
8772    pub fn check_authority_ceiling(
8773        &mut self,
8774        ceiling: &BTreeMap<String, Vec<String>>,
8775    ) -> Result<(), ClientError> {
8776        for query in &self.limits.authority_reads {
8777            for (table, columns) in authority_read_set(&mut self.conn, query)? {
8778                let Some(allowed) = ceiling.get(&table) else {
8779                    return Err(authority_refusal(
8780                        &query.name,
8781                        "ceiling",
8782                        Some(table.as_str()),
8783                        None,
8784                    ));
8785                };
8786                if let Some(column) = columns
8787                    .iter()
8788                    .find(|column| !column.is_empty() && !allowed.contains(column))
8789                {
8790                    return Err(authority_refusal(
8791                        &query.name,
8792                        "ceiling",
8793                        Some(table.as_str()),
8794                        Some(column.as_str()),
8795                    ));
8796                }
8797            }
8798        }
8799        Ok(())
8800    }
8801
8802    /// §5.11: run declared authority queries over the accepted base in one
8803    /// SQLite read transaction. Each request is a query name and its params
8804    /// keyed by param name; each result carries its rows, its coverage per
8805    /// table and unit, and whether every entry is complete.
8806    pub fn authority_read(
8807        &self,
8808        requests: &[(String, Map<String, Value>)],
8809    ) -> Result<AuthorityReadResult, ClientError> {
8810        if self.limits.authority_reads.is_empty() {
8811            return Err(authority_forbidden(None));
8812        }
8813        // Every request resolves and types its params before the read opens.
8814        let mut prepared = Vec::with_capacity(requests.len());
8815        for (name, params) in requests {
8816            let query = self
8817                .limits
8818                .authority_reads
8819                .iter()
8820                .find(|query| &query.name == name)
8821                .ok_or_else(|| ClientError {
8822                    code: "client.authority_query_unknown".to_owned(),
8823                    message: "authority query is not declared".to_owned(),
8824                    details: Some(json!({ "query": name })),
8825                    retryable: false,
8826                })?;
8827            let invalid = |param: &str| ClientError {
8828                code: "sync.invalid_request".to_owned(),
8829                message: "authority query parameter is missing, extra or mistyped".to_owned(),
8830                details: Some(json!({ "query": name, "param": param })),
8831                retryable: false,
8832            };
8833            if let Some(extra) = params
8834                .keys()
8835                .find(|key| !query.params.iter().any(|param| &param.name == *key))
8836            {
8837                return Err(invalid(extra.as_str()));
8838            }
8839            let mut bound = BTreeMap::new();
8840            for param in &query.params {
8841                let value = params
8842                    .get(&param.name)
8843                    .ok_or_else(|| invalid(param.name.as_str()))?;
8844                let sql = match (param.ty.as_str(), value) {
8845                    (_, Value::Null) if param.nullable => Value::Null,
8846                    ("string", Value::String(_)) | ("float", Value::Number(_)) => value.clone(),
8847                    ("integer", Value::Number(number))
8848                        if number
8849                            .as_i64()
8850                            .is_some_and(|n| n.unsigned_abs() <= MAX_JS_SAFE_INTEGER) =>
8851                    {
8852                        value.clone()
8853                    }
8854                    ("boolean", Value::Bool(flag)) => Value::from(i64::from(*flag)),
8855                    ("json", Value::String(text))
8856                        if serde_json::from_str::<Value>(text).is_ok() =>
8857                    {
8858                        value.clone()
8859                    }
8860                    _ => return Err(invalid(param.name.as_str())),
8861                };
8862                bound.insert(param.name.as_str(), sql);
8863            }
8864            // A coverage param names a unit value: a string or an integer.
8865            let scalar = |param: &str| match params.get(param) {
8866                Some(Value::String(text)) => Ok(text.clone()),
8867                Some(Value::Number(number))
8868                    if number
8869                        .as_i64()
8870                        .is_some_and(|n| n.unsigned_abs() <= MAX_JS_SAFE_INTEGER) =>
8871                {
8872                    Ok(number.to_string())
8873                }
8874                _ => Err(invalid(param)),
8875            };
8876            let mut coverage = Vec::new();
8877            for entry in &query.coverage {
8878                let base = WindowBase {
8879                    variable: entry.variable.clone(),
8880                    fixed_scopes: entry
8881                        .fixed_scopes
8882                        .iter()
8883                        .map(
8884                            |(variable, param)| -> Result<(String, String), ClientError> {
8885                                Ok((variable.clone(), scalar(param.as_str())?))
8886                            },
8887                        )
8888                        .collect::<Result<UnitScopes, ClientError>>()?,
8889                };
8890                for unit in &entry.units {
8891                    coverage.push((entry.table.as_str(), base.clone(), scalar(unit.as_str())?));
8892                }
8893            }
8894            prepared.push((query, bound, coverage));
8895        }
8896        self.conn
8897            .execute_batch("SAVEPOINT syncular_authority_read")
8898            .map_err(authority_stored)?;
8899        let result = (|| -> Result<AuthorityReadResult, ClientError> {
8900            let revision = meta_get(&self.conn, LOCAL_REVISION_KEY)
8901                .map_err(authority_stored)?
8902                .filter(|revision| {
8903                    revision
8904                        .parse::<u64>()
8905                        .is_ok_and(|parsed| &parsed.to_string() == revision)
8906                })
8907                .ok_or_else(authority_corrupt)?;
8908            let units = load_units(&self.conn).map_err(authority_stored)?;
8909            let mut results = Vec::with_capacity(prepared.len());
8910            for (query, bound, coverage) in &prepared {
8911                let (sql, mut params) = self.authority_statement(query)?;
8912                params.extend(query.bind.iter().map(|name| bound[name.as_str()].clone()));
8913                let rows =
8914                    query_connection(&self.conn, &sql, &params).map_err(ClientError::from)?;
8915                let coverage = coverage
8916                    .iter()
8917                    .map(|(table, base, unit)| {
8918                        let mut json_base = json!({ "variable": base.variable });
8919                        if !base.fixed_scopes.is_empty() {
8920                            json_base["fixedScopes"] = json!(base.fixed_scopes);
8921                        }
8922                        AuthorityCoverageState {
8923                            table: (*table).to_owned(),
8924                            base: json_base,
8925                            unit: unit.clone(),
8926                            state: entry_coverage(
8927                                &units,
8928                                table,
8929                                self.schema.table(table),
8930                                base,
8931                                unit,
8932                            )
8933                            .0,
8934                        }
8935                    })
8936                    .collect::<Vec<_>>();
8937                results.push(AuthorityQueryResult {
8938                    query: query.name.clone(),
8939                    rows,
8940                    complete: coverage.iter().all(|entry| entry.state == "complete"),
8941                    coverage,
8942                });
8943            }
8944            Ok(AuthorityReadResult { revision, results })
8945        })();
8946        match result {
8947            Ok(read) => {
8948                self.conn
8949                    .execute_batch("RELEASE syncular_authority_read")
8950                    .map_err(authority_stored)?;
8951                Ok(read)
8952            }
8953            Err(error) => {
8954                self.conn
8955                    .execute_batch(
8956                        "ROLLBACK TO syncular_authority_read; RELEASE syncular_authority_read",
8957                    )
8958                    .map_err(authority_stored)?;
8959                Err(error)
8960            }
8961        }
8962    }
8963
8964    /// §5.11: the statement `authority_read` runs for `query` and its shadow
8965    /// params, which precede the authored binds. Every read table with
8966    /// intent reads its accepted base through a common table expression of
8967    /// the same name; the text is identical in the TypeScript core. The Rust
8968    /// mirror keeps the accepted base in `_syncular_base_<table>`: retained,
8969    /// acknowledged and pending intent replay only onto the visible table, so
8970    /// the base row of an intent id is the earliest accepted state.
8971    fn authority_statement(
8972        &self,
8973        query: &AuthorityQuery,
8974    ) -> Result<(String, Vec<Value>), ClientError> {
8975        let mut shadows = Vec::new();
8976        let mut params = Vec::new();
8977        for (name, reads) in &query.reads {
8978            let table = self.schema.table(name).expect("validated authority table");
8979            let mut ids = Vec::new();
8980            let mut statement = self
8981                .conn
8982                .prepare_cached(
8983                    "SELECT DISTINCT id FROM (\
8984                     SELECT json_extract(value,'$.table') AS tbl,json_extract(value,'$.rowId') AS id \
8985                     FROM _syncular_outbox,json_each(ops_json) \
8986                     UNION ALL SELECT json_extract(value,'$.table'),json_extract(value,'$.rowId') \
8987                     FROM _syncular_failed_commits,json_each(operations_json) \
8988                     UNION ALL SELECT tbl,id FROM _syncular_acked_rows) WHERE tbl=?1",
8989                )
8990                .map_err(authority_stored)?;
8991            let mut rows = statement.query([name]).map_err(authority_stored)?;
8992            while let Some(row) = rows.next().map_err(authority_stored)? {
8993                ids.push(row.get::<_, String>(0).map_err(authority_stored)?);
8994            }
8995            if ids.is_empty() {
8996                continue;
8997            }
8998            ids.sort_by(|a, b| a.encode_utf16().cmp(b.encode_utf16()));
8999            let columns: Vec<&str> =
9000                std::iter::once(table.primary_key.as_str())
9001                    .chain(reads.iter().map(String::as_str).filter(|column| {
9002                        *column != table.primary_key && *column != "_sync_version"
9003                    }))
9004                    .chain(std::iter::once("_sync_version"))
9005                    .collect();
9006            let physical = columns
9007                .iter()
9008                .map(|column| {
9009                    if *column == "_sync_version" {
9010                        "_syncular_version".to_owned()
9011                    } else {
9012                        quote_ident(column)
9013                    }
9014                })
9015                .collect::<Vec<_>>()
9016                .join(",");
9017            let key = quote_ident(&table.primary_key);
9018            let mut statement = self
9019                .conn
9020                .prepare(&format!(
9021                    "SELECT CAST({key} AS TEXT),{physical} FROM {} \
9022                     WHERE CAST({key} AS TEXT) IN (SELECT value FROM json_each(?1))",
9023                    base_table(name),
9024                ))
9025                .map_err(authority_stored)?;
9026            let mut rows = statement
9027                .query([serde_json::to_string(&ids).expect("intent ids serialize")])
9028                .map_err(authority_stored)?;
9029            let mut bases = Vec::new();
9030            while let Some(row) = rows.next().map_err(authority_stored)? {
9031                let id = row.get::<_, String>(0).map_err(authority_stored)?;
9032                let mut values = Vec::with_capacity(columns.len());
9033                for index in 1..=columns.len() {
9034                    values.push(match row.get_ref(index).map_err(authority_stored)? {
9035                        ValueRef::Null => Value::Null,
9036                        ValueRef::Integer(integer) => Value::from(integer),
9037                        ValueRef::Real(real) => serde_json::Number::from_f64(real)
9038                            .map(Value::Number)
9039                            .ok_or_else(authority_corrupt)?,
9040                        ValueRef::Text(text) => {
9041                            Value::from(std::str::from_utf8(text).map_err(|_| authority_corrupt())?)
9042                        }
9043                        ValueRef::Blob(_) => return Err(authority_corrupt()),
9044                    });
9045                }
9046                let version = values
9047                    .last()
9048                    .and_then(Value::as_i64)
9049                    .ok_or_else(authority_corrupt)?;
9050                if version >= 0 {
9051                    bases.push((id, Value::Array(values)));
9052                }
9053            }
9054            bases.sort_by(|a, b| a.0.encode_utf16().cmp(b.0.encode_utf16()));
9055            let shadow = quote_ident(name);
9056            shadows.push(format!(
9057                "{shadow} AS (SELECT {} FROM main.{shadow} WHERE CAST({key} AS TEXT) NOT IN \
9058                 (SELECT value FROM json_each(?)) UNION ALL SELECT {} FROM json_each(?))",
9059                columns
9060                    .iter()
9061                    .map(|column| quote_ident(column))
9062                    .collect::<Vec<_>>()
9063                    .join(","),
9064                (0..columns.len())
9065                    .map(|index| format!("json_extract(value,'$[{index}]')"))
9066                    .collect::<Vec<_>>()
9067                    .join(","),
9068            ));
9069            params.push(Value::from(
9070                serde_json::to_string(&ids).expect("intent ids serialize"),
9071            ));
9072            params.push(Value::from(
9073                Value::from_iter(bases.into_iter().map(|(_, row)| row)).to_string(),
9074            ));
9075        }
9076        let sql = if shadows.is_empty() {
9077            query.sql.clone()
9078        } else {
9079            let keyword = |text: &str, word: &str| {
9080                text.get(..word.len())
9081                    .is_some_and(|head| head.eq_ignore_ascii_case(word))
9082                    && text[word.len()..].starts_with(char::is_whitespace)
9083            };
9084            let shadows = shadows.join(",");
9085            let authored = query.sql.trim_start();
9086            if keyword(authored, "WITH") {
9087                let rest = authored[4..].trim_start();
9088                if keyword(rest, "RECURSIVE") {
9089                    format!("WITH RECURSIVE {shadows}, {}", rest[9..].trim_start())
9090                } else {
9091                    format!("WITH {shadows}, {rest}")
9092                }
9093            } else {
9094                format!("WITH {shadows} {}", query.sql)
9095            }
9096        };
9097        Ok((sql, params))
9098    }
9099
9100    /// Rows, coverage, and local revision from one SQLite read snapshot.
9101    /// §7.5 atomic snapshot read. An `owner` records a failure in
9102    /// `diagnostics_snapshot().query_failures` until its next successful read.
9103    pub fn query_snapshot(
9104        &mut self,
9105        sql: &str,
9106        params: &[QueryValue],
9107        coverage: &[WindowCoverage],
9108        owner: Option<QueryOwner<'_>>,
9109    ) -> Result<QuerySnapshot, String> {
9110        let result = snapshot_connection(&self.conn, Some(&self.schema), sql, params, coverage);
9111        if let Some(owner) = owner {
9112            self.record_query_read(owner, result.as_ref().err());
9113        }
9114        result.map_err(|failure| failure.to_string())
9115    }
9116
9117    /// §7.6: record the outcome of one owned snapshot read, including reads a
9118    /// host ran on a separate connection. A success removes the owner's entry;
9119    /// an identical failure leaves it unchanged; a changed failure moves last.
9120    pub fn record_query_read(&mut self, owner: QueryOwner<'_>, failure: Option<&QueryReadFailure>) {
9121        let position = self
9122            .query_failures
9123            .iter()
9124            .position(|entry| entry.id == owner.id);
9125        let Some(failure) = failure else {
9126            if let Some(index) = position {
9127                self.query_failures.remove(index);
9128            }
9129            return;
9130        };
9131        let tables: Vec<String> = BTreeSet::from_iter(owner.tables.iter().copied())
9132            .into_iter()
9133            .map(str::to_owned)
9134            .collect();
9135        let code = failure.code.unwrap_or("client.query_failed").to_owned();
9136        if position.is_some_and(|index| {
9137            let entry = &self.query_failures[index];
9138            entry.tables == tables && entry.code == code && entry.sqlite_code == failure.sqlite_code
9139        }) {
9140            return;
9141        }
9142        if let Some(index) = position {
9143            self.query_failures.remove(index);
9144        }
9145        self.query_failures.push(DiagnosticQueryFailure {
9146            id: owner.id.to_owned(),
9147            tables,
9148            code,
9149            sqlite_code: failure.sqlite_code,
9150            at_ms: self.clock_now_ms(),
9151        });
9152        if self.query_failures.len() > MAX_DIAGNOSTIC_QUERY_FAILURES {
9153            self.query_failures.remove(0);
9154        }
9155    }
9156
9157    // -- request building ---------------------------------------------------------
9158
9159    fn build_request(&self, url_capable: bool) -> Result<(Message, RequestMeta), Box<SyncOutcome>> {
9160        #[cfg(feature = "bench-internals")]
9161        let _phase = self.benchmark_phases.start(Phase::RequestPrepare);
9162        let log_epoch = self.get_meta(LOG_EPOCH_KEY).map_err(|message| {
9163            Box::new(SyncOutcome::Failed {
9164                error_code: "storage.failed".into(),
9165                message,
9166                details: None,
9167                recommended_action: None,
9168            })
9169        })?;
9170        let max_commits = self.limits.max_push_commits_per_request;
9171        let max_ops = self
9172            .limits
9173            .max_push_operations_per_request
9174            .unwrap_or(PUSH_OPS_PER_REQUEST);
9175        let byte_cap = self.limits.max_push_request_bytes;
9176        // §4.2/§5.4: bit 3 is advertised iff the transport can fetch a
9177        // bare URL — capability negotiation, decided per transport.
9178        let accept = self.limits.accept.unwrap_or(if url_capable {
9179            DEFAULT_ACCEPT | ACCEPT_SIGNED_URLS
9180        } else {
9181            DEFAULT_ACCEPT
9182        });
9183        let storage_failed = |message: String| {
9184            Box::new(SyncOutcome::Failed {
9185                error_code: "storage.failed".into(),
9186                message,
9187                details: None,
9188                recommended_action: None,
9189            })
9190        };
9191        let header = Frame::ReqHeader {
9192            client_id: self.client_id.clone(),
9193            schema_version: self.schema.version,
9194            log_epoch: log_epoch.clone(),
9195            outbox_id: self.get_meta(OUTBOX_ID_KEY).map_err(storage_failed)?,
9196        };
9197        // §1.5: the lead frames are REQ_HEADER plus the optional ROUND_FAILURE,
9198        // which stays ahead of every push, pull, unit and progress frame; the
9199        // byte-capacity probes below measure this exact sequence.
9200        let mut lead = vec![header];
9201        lead.extend(
9202            self.round_failure
9203                .iter()
9204                .map(|code| Frame::RoundFailure { code: code.clone() }),
9205        );
9206        // §2.1: a replica without an epoch holds nothing bound to one.
9207        if log_epoch.is_none() {
9208            lead.push(Frame::AdoptEpoch);
9209        }
9210        let registered: Vec<UnitRecord> = self
9211            .stored(load_units(&self.conn))
9212            .map_err(storage_failed)?
9213            .into_iter()
9214            .filter(|unit| unit.status == UnitStatus::Active)
9215            .collect();
9216        let registration_digest = ssp2::registration::registration_digest(
9217            registered
9218                .iter()
9219                .map(|unit| scope_pairs(&unit.scopes))
9220                .collect::<Vec<_>>()
9221                .iter()
9222                .map(Vec::as_slice),
9223        );
9224        let echo_digest = self
9225            .get_meta(ECHO_DIGEST_KEY)
9226            .map_err(storage_failed)?
9227            .filter(|hex| !hex.is_empty())
9228            .map(|hex| {
9229                crate::values::hex_to_bytes(&hex)
9230                    .ok()
9231                    .and_then(|bytes| <[u8; 32]>::try_from(bytes).ok())
9232                    .ok_or_else(|| {
9233                        "sync.local_corrupt: persisted echo digest is invalid".to_owned()
9234                    })
9235            })
9236            .transpose()
9237            .map_err(storage_failed)?;
9238        let pull = Frame::PullHeader {
9239            limit_commits: self.limits.limit_commits.unwrap_or(0),
9240            limit_snapshot_rows: self.limits.limit_snapshot_rows.unwrap_or(0),
9241            max_snapshot_pages: self.limits.max_snapshot_pages.unwrap_or(0),
9242            accept,
9243            cursor: self
9244                .stored(replica_cursor(&self.conn))
9245                .map_err(storage_failed)?,
9246            registration_digest,
9247            echo_digest,
9248        };
9249        let registration_digest = bytes_to_hex(&registration_digest);
9250        // §4.1: the list travels when it changed since the server stored it,
9251        // after `unregistered` and after a reset (both clear the stored digest).
9252        let travels = self
9253            .get_meta(REGISTERED_DIGEST_KEY)
9254            .map_err(storage_failed)?
9255            .as_deref()
9256            != Some(registration_digest.as_str());
9257        let mut sub_frames: Vec<Frame> = Vec::new();
9258        if travels {
9259            sub_frames.extend(registered.iter().map(|unit| Frame::Unit {
9260                scopes: scope_pairs(&unit.scopes),
9261            }));
9262        }
9263        // §4.3: one PROGRESS per catching-up unit, in registration order, each
9264        // followed by its RESTRICT while the unit holds a restriction.
9265        for unit in &registered {
9266            let Some(cursor) = unit.cursor else {
9267                continue;
9268            };
9269            sub_frames.push(Frame::Progress {
9270                id: unit.id.clone(),
9271                cursor,
9272                bootstrap_state: unit.bootstrap_state.clone().map(RawJson),
9273            });
9274            sub_frames.extend(
9275                unit.restriction
9276                    .as_ref()
9277                    .map(|restriction| Frame::Restrict {
9278                        cursor: restriction.cursor,
9279                        tables: restriction.tables.clone(),
9280                    }),
9281            );
9282        }
9283        // The fixed frames (order-independent size) and the header+pull probe
9284        // both encode canonically, so the byte budget is the exact wire size.
9285        let fixed_bytes = match byte_cap {
9286            Some(_) => {
9287                let mut frames = lead.clone();
9288                frames.push(pull.clone());
9289                frames.extend(sub_frames.iter().cloned());
9290                encode_message(&Message {
9291                    wire_version: WIRE_VERSION,
9292                    msg_kind: MsgKind::Request,
9293                    frames,
9294                })
9295                .len()
9296            }
9297            None => 0,
9298        };
9299        if let Some(cap) = byte_cap {
9300            if fixed_bytes > cap {
9301                return Err(Self::push_capacity_outcome("bytes", cap, fixed_bytes, None));
9302            }
9303        }
9304        let base_bytes = match byte_cap {
9305            Some(_) => {
9306                let mut frames = lead.clone();
9307                frames.push(pull.clone());
9308                encode_message(&Message {
9309                    wire_version: WIRE_VERSION,
9310                    msg_kind: MsgKind::Request,
9311                    frames,
9312                })
9313                .len()
9314            }
9315            None => 0,
9316        };
9317        // §8.8: a `pull` round carries no commit and defers none; a `through`
9318        // round pushes and defers only its prefix.
9319        let pushable = self.pushable_commits();
9320        let total_outbox = if log_epoch.is_some() { pushable } else { 0 };
9321        let mut push_frames: Vec<Frame> = Vec::new();
9322        let mut pushed_ids = Vec::new();
9323        let mut ops_in_request = 0usize;
9324        let mut bytes_in_request = 0usize;
9325        // §2.1: an epoch-less request withholds the whole outbox until the
9326        // next, epoch-bound request.
9327        let mut deferred_commits = pushable - total_outbox;
9328        // §7.2.2: a pending replacement is held; the push stops before it
9329        // without deferring work.
9330        let held: HashSet<String> = self
9331            .prepare_replacements()
9332            .map_err(storage_failed)?
9333            .into_iter()
9334            .filter_map(|decision| decision.replacement)
9335            .collect();
9336        #[cfg(feature = "bench-internals")]
9337        let outbox_phase = self.benchmark_phases.start(Phase::OutboxEncode);
9338        for (index, commit) in self.outbox.iter().take(total_outbox).enumerate() {
9339            if held.contains(&commit.client_commit_id) {
9340                break;
9341            }
9342            // §6.1/§7.1: the commit-count and operation caps are hard. A
9343            // first commit over the operation cap is a typed capacity error
9344            // and stays queued; a later one defers with the complete suffix.
9345            if max_commits.is_some_and(|cap| push_frames.len() >= cap) {
9346                deferred_commits = total_outbox - index;
9347                break;
9348            }
9349            if ops_in_request + commit.ops.len() > max_ops {
9350                if push_frames.is_empty() {
9351                    return Err(Self::push_capacity_outcome(
9352                        "operations",
9353                        max_ops,
9354                        commit.ops.len(),
9355                        Some(commit.client_commit_id.as_str()),
9356                    ));
9357                }
9358                deferred_commits = total_outbox - index;
9359                break;
9360            }
9361            // §7.1 chained base: the commit waits for the change of the commit
9362            // it chains on, which supplies its rebased version.
9363            if self.outbox[..index]
9364                .iter()
9365                .flat_map(|earlier| &earlier.ops)
9366                .any(|earlier| commit.ops.iter().any(|op| chains_on(earlier, op)))
9367            {
9368                deferred_commits = total_outbox - index;
9369                break;
9370            }
9371            let operations = commit
9372                .ops
9373                .iter()
9374                .map(|op| {
9375                    let payload = match self
9376                        .schema
9377                        .table(&op.table)
9378                        .and_then(|table| Some((table, op.presented_values(table)?)))
9379                    {
9380                        Some((table, values)) => {
9381                            // §0: outbox entries encode at send time with the
9382                            // current codec (validated at mutate()). §6.1: the
9383                            // values map's keys are the sparse presence set; an
9384                            // insert-intent operation presents every column (§7.1).
9385                            // §5.11: encrypted columns are encrypted here, with
9386                            // an absent key-id selector read from the stored row.
9387                            // `sync_inner` runs `drop_unencodable_outbox` first,
9388                            // so an encrypt failure cannot reach this encode; the
9389                            // author seam validated every other failure.
9390                            let fallback =
9391                                self.stored_key_fallback(table, &op.row_id)
9392                                    .map_err(|message| {
9393                                        Box::new(SyncOutcome::Failed {
9394                                            error_code: "storage.failed".into(),
9395                                            message,
9396                                            details: None,
9397                                            recommended_action: None,
9398                                        })
9399                                    })?;
9400                            encode_sparse_row_json(
9401                                table,
9402                                &op.row_id,
9403                                &values,
9404                                &self.encryption,
9405                                fallback.as_ref(),
9406                            )
9407                            .ok()
9408                        }
9409                        None => None,
9410                    };
9411                    Ok(ssp2::model::Operation {
9412                        table: op.table.clone(),
9413                        row_id: op.row_id.clone(),
9414                        op: if op.upsert { Op::Upsert } else { Op::Delete },
9415                        base_version: op.base_version,
9416                        payload,
9417                    })
9418                })
9419                .collect::<Result<Vec<_>, Box<SyncOutcome>>>()?;
9420            // §6.3.2, §7.1: the commit's outbox sequence.
9421            let client_seq = self
9422                .conn
9423                .prepare_cached("SELECT seq FROM _syncular_outbox WHERE commit_id = ?1")
9424                .and_then(|mut statement| {
9425                    statement.query_row([&commit.client_commit_id], |row| row.get(0))
9426                })
9427                .map_err(|error| {
9428                    storage_failed(Self::sqlite_failure(&self.storage_failure, error))
9429                })?;
9430            let frame = Frame::PushCommit {
9431                client_commit_id: commit.client_commit_id.clone(),
9432                client_seq,
9433                operations,
9434            };
9435            let frame_bytes = match byte_cap {
9436                Some(_) => {
9437                    let mut frames = lead.clone();
9438                    frames.push(frame.clone());
9439                    frames.push(pull.clone());
9440                    encode_message(&Message {
9441                        wire_version: WIRE_VERSION,
9442                        msg_kind: MsgKind::Request,
9443                        frames,
9444                    })
9445                    .len()
9446                        - base_bytes
9447                }
9448                None => 0,
9449            };
9450            // The head is always encoded so the caller can report the full
9451            // projected request size; a later commit defers once it no longer
9452            // fits.
9453            if let Some(cap) = byte_cap {
9454                if !push_frames.is_empty() && fixed_bytes + bytes_in_request + frame_bytes > cap {
9455                    deferred_commits = total_outbox - index;
9456                    break;
9457                }
9458            }
9459            push_frames.push(frame);
9460            pushed_ids.push(commit.client_commit_id.clone());
9461            ops_in_request += commit.ops.len();
9462            bytes_in_request += frame_bytes;
9463        }
9464        #[cfg(feature = "bench-internals")]
9465        drop(outbox_phase);
9466        if let Some(cap) = byte_cap {
9467            if fixed_bytes + bytes_in_request > cap {
9468                // The head alone does not fit this budget; the commit stays
9469                // queued and no transport round is attempted.
9470                let blocked = if push_frames.is_empty() {
9471                    None
9472                } else {
9473                    self.outbox.first().map(|c| c.client_commit_id.as_str())
9474                };
9475                return Err(Self::push_capacity_outcome(
9476                    "bytes",
9477                    cap,
9478                    fixed_bytes + bytes_in_request,
9479                    blocked,
9480                ));
9481            }
9482        }
9483        let mut frames = lead;
9484        frames.extend(push_frames);
9485        frames.push(pull);
9486        frames.extend(sub_frames);
9487        let message = Message {
9488            wire_version: WIRE_VERSION,
9489            msg_kind: MsgKind::Request,
9490            frames,
9491        };
9492        Ok((
9493            message,
9494            RequestMeta {
9495                pushed_ids,
9496                registration_digest,
9497                accept,
9498                deferred_commits,
9499                applied: BTreeMap::new(),
9500                deferred: BTreeSet::new(),
9501            },
9502        ))
9503    }
9504
9505    /// §7.1: a configured push capacity limit cannot carry this request.
9506    fn push_capacity_outcome(
9507        kind: &str,
9508        limit: usize,
9509        size: usize,
9510        client_commit_id: Option<&str>,
9511    ) -> Box<SyncOutcome> {
9512        let mut details = Map::new();
9513        details.insert("kind".to_owned(), Value::from(kind));
9514        details.insert("limit".to_owned(), Value::from(limit as u64));
9515        details.insert("size".to_owned(), Value::from(size as u64));
9516        if let Some(id) = client_commit_id {
9517            details.insert("clientCommitId".to_owned(), Value::from(id));
9518        }
9519        Box::new(SyncOutcome::Failed {
9520            error_code: "client.push_request_too_large".into(),
9521            message: "the push request exceeds a configured capacity limit".into(),
9522            details: Some(Value::Object(details)),
9523            recommended_action: None,
9524        })
9525    }
9526
9527    // -- sync -------------------------------------------------------------------
9528
9529    /// Cloneable observation handle; no client lock is needed to read it.
9530    pub fn progress(&self) -> ProgressObserver {
9531        self.progress.clone()
9532    }
9533
9534    pub fn sync(&mut self, transport: &mut dyn Transport) -> SyncOutcome {
9535        self.sync_bounded(transport, None)
9536    }
9537
9538    /// One round; `idle_bound` is the idle drive's round bound (§7.8).
9539    fn sync_bounded(
9540        &mut self,
9541        transport: &mut dyn Transport,
9542        idle_bound: Option<(u64, u32)>,
9543    ) -> SyncOutcome {
9544        let mut prepared = match self.prepare_sync_round(transport.supports_url_fetch()) {
9545            Ok(prepared) => prepared,
9546            Err(outcome) => return *outcome,
9547        };
9548        prepared.idle_bound = idle_bound;
9549        // The round's network deadline rides `PreparedSyncRound` and is scoped
9550        // to each exchange, so uploads, continuations, the main request, and
9551        // every segment fetch share one monotonic anchor without leaving
9552        // deadline state on a reused transport.
9553        let mut next = prepared;
9554        loop {
9555            match self.apply_sync_round(next.exchange(transport)) {
9556                crate::AppliedSyncRound::Continue(prepared) => next = prepared,
9557                crate::AppliedSyncRound::Complete {
9558                    outcome, controls, ..
9559                } => {
9560                    if !self.transport_closed() {
9561                        for text in controls {
9562                            let _ = transport.realtime_send(&text);
9563                        }
9564                    } else {
9565                        self.disconnect_realtime(transport);
9566                    }
9567                    return outcome;
9568                }
9569            }
9570        }
9571    }
9572
9573    fn finish_sync_round(
9574        &mut self,
9575        started_at_ms: i64,
9576        attempt: u64,
9577        mut outcome: SyncOutcome,
9578    ) -> SyncOutcome {
9579        if let SyncOutcome::Failed {
9580            error_code,
9581            message,
9582            details,
9583            ..
9584        } = &mut outcome
9585        {
9586            if let Some((failure, code)) = self
9587                .storage_failure
9588                .borrow()
9589                .as_ref()
9590                .and_then(|failure| failure.code.map(|code| (failure, code)))
9591            {
9592                *error_code = code.to_owned();
9593                *message = match code {
9594                    "client.storage_busy" => "local SQLite storage is busy",
9595                    "client.storage_full" => "local SQLite storage is full",
9596                    "client.storage_io" => "local SQLite storage I/O failed",
9597                    "client.storage_corrupt" => "local SQLite storage is corrupt",
9598                    _ => unreachable!("unrecognized classified storage failure"),
9599                }
9600                .to_owned();
9601                *details = failure.details();
9602            }
9603        }
9604        let details = match &outcome {
9605            SyncOutcome::Failed { details, .. } => details.as_ref(),
9606            _ => None,
9607        };
9608        let cause_kind = details
9609            .and_then(|details| details.get("causeKind"))
9610            .and_then(Value::as_str)
9611            .and_then(|cause| match cause {
9612                "network" => Some(crate::TransportCauseKind::Network),
9613                "connect" => Some(crate::TransportCauseKind::Connect),
9614                "tls" => Some(crate::TransportCauseKind::Tls),
9615                "io" => Some(crate::TransportCauseKind::Io),
9616                "request" => Some(crate::TransportCauseKind::Request),
9617                "protocol" => Some(crate::TransportCauseKind::Protocol),
9618                "timeout" => Some(crate::TransportCauseKind::Timeout),
9619                "round_deadline" => Some(crate::TransportCauseKind::RoundDeadline),
9620                "aborted" => Some(crate::TransportCauseKind::Aborted),
9621                "body" => Some(crate::TransportCauseKind::Body),
9622                "status" => Some(crate::TransportCauseKind::Status),
9623                "redirect" => Some(crate::TransportCauseKind::Redirect),
9624                "unknown" => Some(crate::TransportCauseKind::Unknown),
9625                _ => None,
9626            });
9627        let http_status = if matches!(
9628            cause_kind,
9629            Some(
9630                crate::TransportCauseKind::Status
9631                    | crate::TransportCauseKind::Body
9632                    | crate::TransportCauseKind::Redirect
9633            )
9634        ) {
9635            details
9636                .and_then(|details| details.get("httpStatus"))
9637                .and_then(Value::as_f64)
9638                .filter(|status| status.fract() == 0.0 && (100.0..=599.0).contains(status))
9639                .map(|status| status as u16)
9640        } else {
9641            None
9642        };
9643        let retry_delay_ms = self.round_retry_delay_ms;
9644        self.progress.update(|p| match &outcome {
9645            SyncOutcome::Ok(report) | SyncOutcome::BudgetExhausted(report)
9646                if report.failed.is_empty() =>
9647            {
9648                p.state = ProgressState::Complete
9649            }
9650            SyncOutcome::Ok(_) | SyncOutcome::BudgetExhausted(_) => {
9651                p.state = ProgressState::Failed;
9652                p.error_code = Some("sync.scope_revoked".into());
9653            }
9654            SyncOutcome::Failed { error_code, .. } => {
9655                p.state = ProgressState::Failed;
9656                p.error_code = Some(Self::diagnostic_code(error_code));
9657                p.cause_kind = cause_kind;
9658                p.http_status = http_status;
9659                p.retry_delay_ms = retry_delay_ms;
9660            }
9661            SyncOutcome::RealtimeUnavailable { .. } => {
9662                p.state = ProgressState::Failed;
9663                p.error_code = Some(REALTIME_UNAVAILABLE_CODE.to_owned());
9664                p.retry_delay_ms = retry_delay_ms;
9665            }
9666        });
9667        let completed_at_ms = self.clock_now_ms();
9668        self.last_round = Some(match &outcome {
9669            SyncOutcome::Ok(report) | SyncOutcome::BudgetExhausted(report) => DiagnosticLastRound {
9670                epoch: self.epoch.clone(),
9671                attempt,
9672                status: "succeeded".to_owned(),
9673                started_at_ms,
9674                completed_at_ms,
9675                duration_ms: completed_at_ms.saturating_sub(started_at_ms).max(0),
9676                counters: Some(DiagnosticRoundCounters {
9677                    pushed: report.pushed,
9678                    applied: report.applied.len(),
9679                    rejected: report.rejected.len(),
9680                    retryable: report.retryable.len(),
9681                    conflicts: report.conflicts,
9682                    commits_applied: report.commits_applied,
9683                    segment_rows_applied: report.segment_rows_applied,
9684                    bootstrapping: report.bootstrapping.len(),
9685                    resets: report.resets.len(),
9686                    revoked: report.revoked.len(),
9687                    failed: report.failed.len(),
9688                    deferred_commits: report.deferred_commits,
9689                }),
9690                error_code: None,
9691                cause_kind: None,
9692                http_status: None,
9693            },
9694            SyncOutcome::Failed { error_code, .. } => DiagnosticLastRound {
9695                epoch: self.epoch.clone(),
9696                attempt,
9697                status: "failed".to_owned(),
9698                started_at_ms,
9699                completed_at_ms,
9700                duration_ms: completed_at_ms.saturating_sub(started_at_ms).max(0),
9701                counters: None,
9702                error_code: Some(Self::diagnostic_code(error_code)),
9703                cause_kind,
9704                http_status,
9705            },
9706            SyncOutcome::RealtimeUnavailable { .. } => DiagnosticLastRound {
9707                epoch: self.epoch.clone(),
9708                attempt,
9709                status: "failed".to_owned(),
9710                started_at_ms,
9711                completed_at_ms,
9712                duration_ms: completed_at_ms.saturating_sub(started_at_ms).max(0),
9713                counters: None,
9714                error_code: Some(REALTIME_UNAVAILABLE_CODE.to_owned()),
9715                cause_kind: None,
9716                http_status: None,
9717            },
9718        });
9719        outcome
9720    }
9721
9722    /// Capture one request on the client owner. Mutations made after this
9723    /// call remain in the outbox for a later round; no network I/O occurs here.
9724    pub fn prepare_sync_round(
9725        &mut self,
9726        url_capable: bool,
9727    ) -> Result<crate::PreparedSyncRound, Box<SyncOutcome>> {
9728        if self.transport_closed() {
9729            return Err(Box::new(SyncOutcome::Failed {
9730                error_code: "sync.offline".into(),
9731                message: "transport gate is closed".into(),
9732                details: None,
9733                recommended_action: None,
9734            }));
9735        }
9736        if self.active_round.is_some() || self.fence_round.is_some() {
9737            return Err(Box::new(SyncOutcome::Failed {
9738                error_code: "client.round_in_progress".into(),
9739                message: "a sync round is already in flight".into(),
9740                details: None,
9741                recommended_action: None,
9742            }));
9743        }
9744        self.storage_failure.borrow_mut().take();
9745        let attempt = self.progress.start(&self.epoch);
9746        self.round_retry_delay_ms = None;
9747        let started_at_ms = self.clock_now_ms();
9748        let prepared = (|| {
9749            if self.stopped {
9750                return Err(Box::new(SyncOutcome::Ok(SyncReport {
9751                    schema_floor: self.schema_floor.clone(),
9752                    ..SyncReport::default()
9753                })));
9754            }
9755            if self.security_preflight {
9756                return Err(Box::new(SyncOutcome::Failed {
9757                    error_code: SECURITY_PREFLIGHT_REQUIRED_CODE.into(),
9758                    message: "security preflight must complete before syncing".into(),
9759                    details: None,
9760                    recommended_action: None,
9761                }));
9762            }
9763            self.set_sync_needed(false, false);
9764            self.drain_pending_evictions()
9765                .and_then(|_| self.drop_incompatible_outbox())
9766                .and_then(|_| self.drop_unencodable_outbox(true, None))
9767                .map_err(|message| {
9768                    Box::new(SyncOutcome::Failed {
9769                        error_code: "storage.failed".into(),
9770                        message,
9771                        details: None,
9772                        recommended_action: None,
9773                    })
9774                })?;
9775            // §5.11: reveal rows sealed under a key the keyring gained since.
9776            self.reveal_sealed_rows().map_err(|error| {
9777                Box::new(SyncOutcome::Failed {
9778                    error_code: error.code,
9779                    message: error.message,
9780                    details: error.details,
9781                    recommended_action: None,
9782                })
9783            })?;
9784            let has_log_epoch = self.get_meta(LOG_EPOCH_KEY).map_err(|message| {
9785                Box::new(SyncOutcome::Failed {
9786                    error_code: "storage.failed".into(),
9787                    message,
9788                    details: None,
9789                    recommended_action: None,
9790                })
9791            })?;
9792            let mut uploads = if has_log_epoch.is_some()
9793                && matches!(
9794                    self.transport_gate,
9795                    crate::TransportGate::Open | crate::TransportGate::Through(_)
9796                )
9797                && self.schema_has_blobs()
9798            {
9799                self.pending_blob_uploads().map_err(|e| {
9800                    Box::new(SyncOutcome::Failed {
9801                        error_code: e.code,
9802                        message: e.message,
9803                        details: e.details,
9804                        recommended_action: None,
9805                    })
9806                })?
9807            } else {
9808                Vec::new()
9809            };
9810            // §8.8: a `through` round uploads only the blobs its prefix references.
9811            if matches!(self.transport_gate, crate::TransportGate::Through(_)) {
9812                let prefix = Value::Array(
9813                    self.outbox
9814                        .iter()
9815                        .take(self.pushable_commits())
9816                        .map(|commit| Value::String(commit.client_commit_id.clone()))
9817                        .collect(),
9818                );
9819                let referenced = self
9820                    .conn
9821                    .prepare(
9822                        "SELECT blob_id FROM _syncular_blob_commit_refs
9823                          WHERE commit_id IN (SELECT value FROM json_each(?1))",
9824                    )
9825                    .and_then(|mut statement| {
9826                        statement
9827                            .query_map([prefix.to_string()], |row| row.get::<_, String>(0))?
9828                            .collect::<Result<HashSet<_>, _>>()
9829                    })
9830                    .map_err(|error| {
9831                        Box::new(SyncOutcome::Failed {
9832                            error_code: "storage.failed".into(),
9833                            message: Self::sqlite_failure(&self.storage_failure, error),
9834                            details: None,
9835                            recommended_action: None,
9836                        })
9837                    })?;
9838                uploads.retain(|upload| referenced.contains(&upload.id));
9839            }
9840            if self.realtime_state != RealtimeState::Connected
9841                && self.realtime_policy == RealtimePolicy::Required
9842            {
9843                let retry_delay_ms = self.schedule_background_retry();
9844                self.realtime_retry_delay_ms = Some(retry_delay_ms);
9845                return Err(Box::new(SyncOutcome::RealtimeUnavailable {
9846                    state: self.realtime_state,
9847                    reason_code: self.realtime_reason_code.clone(),
9848                    retry_delay_ms,
9849                }));
9850            }
9851            let (message, mut meta) = self.build_request(url_capable)?;
9852            let units = self.stored(load_units(&self.conn)).map_err(|message| {
9853                Box::new(SyncOutcome::Failed {
9854                    error_code: "storage.failed".into(),
9855                    message,
9856                    details: None,
9857                    recommended_action: None,
9858                })
9859            })?;
9860            for unit in &units {
9861                let applied =
9862                    self.stored(applied_rows(&self.conn, &unit.id))
9863                        .map_err(|message| {
9864                            Box::new(SyncOutcome::Failed {
9865                                error_code: "storage.failed".into(),
9866                                message,
9867                                details: None,
9868                                recommended_action: None,
9869                            })
9870                        })?;
9871                if !applied.is_empty() {
9872                    meta.applied.insert(unit.id.clone(), applied);
9873                }
9874            }
9875            // §7.1: the send-attempt marker of every commit the request
9876            // carries commits before the round leaves the owner.
9877            let pushed: Vec<String> = message
9878                .frames
9879                .iter()
9880                .filter_map(|frame| match frame {
9881                    Frame::PushCommit { client_seq, .. } => Some(client_seq.to_string()),
9882                    _ => None,
9883                })
9884                .collect();
9885            if !pushed.is_empty() {
9886                self.conn
9887                    .execute(
9888                        &format!(
9889                            "UPDATE _syncular_outbox SET attempted = 1 WHERE seq IN ({})",
9890                            pushed.join(",")
9891                        ),
9892                        [],
9893                    )
9894                    .map_err(|error| {
9895                        Box::new(SyncOutcome::Failed {
9896                            error_code: "storage.failed".into(),
9897                            message: Self::sqlite_failure(&self.storage_failure, error),
9898                            details: None,
9899                            recommended_action: None,
9900                        })
9901                    })?;
9902            }
9903            let id = uuid::Uuid::new_v4();
9904            self.active_round = Some((id, started_at_ms, attempt));
9905            let phase = if uploads.is_empty() {
9906                crate::round::RoundPhase::Sync
9907            } else {
9908                crate::round::RoundPhase::UploadGrant
9909            };
9910            Ok(crate::PreparedSyncRound {
9911                id,
9912                started_at_ms,
9913                attempt,
9914                message,
9915                meta,
9916                uploads: uploads.into(),
9917                phase,
9918                encoded: None,
9919                continuation: None,
9920                completed: None,
9921                realtime: self.realtime_state == RealtimeState::Connected,
9922                // §5.5: the owning unit's scope map, each value a one-element list.
9923                scopes: units
9924                    .into_iter()
9925                    .map(|unit| {
9926                        (
9927                            unit.id,
9928                            canonical_scope_json(&unit_scope_lists(&unit.scopes)),
9929                        )
9930                    })
9931                    .collect(),
9932                #[cfg(feature = "bench-internals")]
9933                benchmark_phases: self.benchmark_phases.clone(),
9934                progress: self.progress.clone(),
9935                fixed_now: self
9936                    .now_ms
9937                    .as_ref()
9938                    .map(|clock| clock.load(std::sync::atomic::Ordering::Relaxed)),
9939                round_deadline_at: None,
9940                idle_bound: None,
9941                network_started_at: None,
9942            })
9943        })();
9944        prepared
9945            .map_err(|outcome| Box::new(self.finish_sync_round(started_at_ms, attempt, *outcome)))
9946    }
9947
9948    /// Discard the reply of an old authorization or registration context. Its
9949    /// submitted commits stay durable and can be retried with the same ids.
9950    /// §7.6: an abandoned in-flight round ends its attempt as failed.
9951    pub fn cancel_sync_round(&mut self) {
9952        self.fence_round = None;
9953        if let Some((_, started_at_ms, attempt)) = self.active_round.take() {
9954            // A storage failure recorded since the round started is not its cause.
9955            self.storage_failure.borrow_mut().take();
9956            self.finish_sync_round(
9957                started_at_ms,
9958                attempt,
9959                SyncOutcome::Failed {
9960                    error_code: "client.round_cancelled".into(),
9961                    message: "sync round belongs to a released client context".into(),
9962                    details: None,
9963                    recommended_action: None,
9964                },
9965            );
9966        }
9967    }
9968
9969    /// Apply captured network results on the owner, preserving all normal
9970    /// version, schema, content-address and cursor checks. No network I/O.
9971    pub fn apply_sync_round(
9972        &mut self,
9973        completed: crate::CompletedSyncRound,
9974    ) -> crate::AppliedSyncRound {
9975        let mut prepared = completed.prepared;
9976        if self.active_round.map(|(id, ..)| id) != Some(prepared.id) || self.security_preflight {
9977            return crate::AppliedSyncRound::Complete {
9978                outcome: SyncOutcome::Failed {
9979                    error_code: "client.round_cancelled".into(),
9980                    message: "sync round belongs to a released client context".into(),
9981                    details: None,
9982                    recommended_action: None,
9983                },
9984                controls: Vec::new(),
9985                more: false,
9986                bootstrap_advanced: false,
9987            };
9988        }
9989        self.storage_failure.borrow_mut().take();
9990        let (response, mut downloads, transport_failed) = match completed.exchange {
9991            crate::round::ExchangeResult::Upload { id, result } => {
9992                let result = match result {
9993                    // §5.9.7: a non-retryable server refusal (`blob.too_large`)
9994                    // is the body's final outcome. The commits naming it take
9995                    // the incompatible-commit path with the server's code and
9996                    // leave this round's request; the round continues.
9997                    Err(error)
9998                        if error
9999                            .details
10000                            .as_ref()
10001                            .and_then(|details| details.get("retryable"))
10002                            == Some(&Value::Bool(false)) =>
10003                    {
10004                        self.conn
10005                            .prepare(
10006                                "SELECT commit_id FROM _syncular_blob_commit_refs WHERE blob_id = ?",
10007                            )
10008                            .and_then(|mut statement| {
10009                                statement
10010                                    .query_map(rusqlite::params![id], |row| row.get::<_, String>(0))?
10011                                    .collect::<Result<HashSet<_>, _>>()
10012                            })
10013                            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
10014                            .and_then(|refused| {
10015                                // §8.8: only a commit the gate lets this round
10016                                // push takes the refusal. A held commit keeps
10017                                // the body queued and meets the refusal when a
10018                                // round pushes it.
10019                                let commits = self
10020                                    .outbox
10021                                    .iter()
10022                                    .take(self.pushable_commits())
10023                                    .filter(|commit| refused.contains(&commit.client_commit_id))
10024                                    .cloned()
10025                                    .collect::<Vec<_>>();
10026                                if !commits.is_empty() {
10027                                    self.drop_outbox_commits(&commits, &error.code, &error.message)?;
10028                                }
10029                                prepared.message.frames.retain(|frame| {
10030                                    !matches!(frame, Frame::PushCommit { client_commit_id, .. }
10031                                        if refused.contains(client_commit_id))
10032                                });
10033                                prepared.meta.pushed_ids.retain(|id| !refused.contains(id));
10034                                prepared.continuation = Some(crate::round::RoundPhase::UploadGrant);
10035                                Ok(true)
10036                            })
10037                            .map_err(|message| TransportError::new("client.failed", message))
10038                    }
10039                    result => result.map(|()| false),
10040                };
10041                // A refused body stays queued while a held commit names it.
10042                let result = result.and_then(|refused| {
10043                    self.conn
10044                        .execute(
10045                            if refused {
10046                                "DELETE FROM _syncular_blob_uploads WHERE blob_id = ?1
10047                                   AND NOT EXISTS (SELECT 1 FROM _syncular_blob_commit_refs
10048                                                    WHERE blob_id = ?1)"
10049                            } else {
10050                                "DELETE FROM _syncular_blob_uploads WHERE blob_id = ?1"
10051                            },
10052                            rusqlite::params![id],
10053                        )
10054                        .map(|_| ())
10055                        .map_err(|error| {
10056                            TransportError::new(
10057                                "client.failed",
10058                                Self::sqlite_failure(&self.storage_failure, error),
10059                            )
10060                        })
10061                });
10062                match result {
10063                    Ok(()) => return crate::AppliedSyncRound::Continue(prepared),
10064                    Err(TransportError {
10065                        code,
10066                        message,
10067                        details,
10068                    }) => {
10069                        self.active_round = None;
10070                        if Self::unreachable_transport(&details) {
10071                            // The round's work is still owed; the host's
10072                            // connectivity resume runs it.
10073                            self.set_sync_needed(true, false);
10074                        } else if Self::retryable_failure_code(&code) {
10075                            self.schedule_background_retry();
10076                        }
10077                        let recommended_action = recommended_action_of(&details);
10078                        let outcome = self.finish_sync_round(
10079                            prepared.started_at_ms,
10080                            prepared.attempt,
10081                            SyncOutcome::Failed {
10082                                error_code: code,
10083                                message,
10084                                details,
10085                                recommended_action,
10086                            },
10087                        );
10088                        return crate::AppliedSyncRound::Complete {
10089                            outcome,
10090                            controls: Vec::new(),
10091                            more: false,
10092                            bootstrap_advanced: false,
10093                        };
10094                    }
10095                }
10096            }
10097            crate::round::ExchangeResult::Reply {
10098                response,
10099                downloads,
10100                transport_failed,
10101            } => (response, downloads, transport_failed),
10102        };
10103        self.active_round = None;
10104        let before = self.resume_tokens();
10105        let outcome = (|| {
10106            let response = match response {
10107                Ok(response) => {
10108                    // §1.5: a complete, decodable response ends the report, an
10109                    // in-band ERROR included (the server already recorded it).
10110                    self.round_failure = None;
10111                    response
10112                }
10113                Err(TransportError {
10114                    code,
10115                    message,
10116                    details,
10117                }) => {
10118                    // §1.5: the server cannot see a round whose transport
10119                    // failed or whose response never decoded, so its code rides
10120                    // the following requests. A code the frame grammar rejects
10121                    // is not reportable, and the previous code stays; the
10122                    // client-local drive timeout never goes on the wire (§7.8).
10123                    if code != "sync.idle_timeout" && ssp2::model::valid_round_failure_code(&code) {
10124                        self.round_failure = Some(code.clone());
10125                    }
10126                    // §8.8: a prefix sent without a receipt is an uncertain delivery.
10127                    if !prepared.meta.pushed_ids.is_empty()
10128                        && matches!(self.transport_gate, crate::TransportGate::Through(_))
10129                    {
10130                        self.move_transport_gate(crate::TransportGate::Pull);
10131                    }
10132                    if transport_failed {
10133                        if prepared.realtime {
10134                            self.set_realtime_state(RealtimeState::Lost, Some(&code));
10135                        }
10136                        if let Err(message) = self.record_lease_error(&code) {
10137                            return SyncOutcome::Failed {
10138                                error_code: "storage.failed".to_owned(),
10139                                message,
10140                                details: None,
10141                                recommended_action: None,
10142                            };
10143                        }
10144                    }
10145                    if Self::retryable_failure_code(&code) && !Self::unreachable_transport(&details)
10146                    {
10147                        let delay = self.schedule_background_retry();
10148                        if prepared.realtime && transport_failed {
10149                            self.realtime_retry_delay_ms = Some(delay);
10150                        }
10151                    }
10152                    let recommended_action = recommended_action_of(&details);
10153                    return SyncOutcome::Failed {
10154                        error_code: code,
10155                        message,
10156                        details,
10157                        recommended_action,
10158                    };
10159                }
10160            };
10161            let mut outcome = self.process_response(&mut downloads, response, &prepared.meta);
10162            if let SyncOutcome::Ok(report) = &mut outcome {
10163                report.deferred_commits = prepared.meta.deferred_commits;
10164            }
10165            match &outcome {
10166                SyncOutcome::Ok(_) => self.reset_background_retry(),
10167                SyncOutcome::Failed {
10168                    error_code,
10169                    details,
10170                    ..
10171                } if Self::retryable_failure_code(error_code)
10172                    && !Self::unreachable_transport(details) =>
10173                {
10174                    self.schedule_background_retry();
10175                }
10176                _ => {}
10177            }
10178            if prepared.meta.deferred_commits > 0 {
10179                self.set_sync_needed(true, true);
10180            }
10181            self.previous_version_lifetime_check();
10182            outcome
10183        })();
10184        match &outcome {
10185            // §7.1: a unit still catching up needs another round, also when the
10186            // drive that started it ends early.
10187            SyncOutcome::Ok(report) if !report.bootstrapping.is_empty() => {
10188                self.set_sync_needed(true, false)
10189            }
10190            // The round's work is still owed; the host's connectivity resume
10191            // runs it.
10192            SyncOutcome::Failed { details, .. } if Self::unreachable_transport(details) => {
10193                self.set_sync_needed(true, false)
10194            }
10195            _ => {}
10196        }
10197        let more = !self.transport_closed()
10198            && matches!(&outcome, SyncOutcome::Ok(report)
10199                if report.schema_floor.is_none()
10200                    && (!report.bootstrapping.is_empty()
10201                        || report.commits_applied > 0
10202                        || report.segment_rows_applied > 0
10203                        || !report.resets.is_empty()
10204                        || report.deferred_commits > 0
10205                        || self.sync_needed));
10206        let bootstrap_advanced = matches!(&outcome, SyncOutcome::Ok(report) if report.segment_rows_applied > 0 && !report.bootstrapping.is_empty())
10207            && before != self.resume_tokens();
10208        crate::AppliedSyncRound::Complete {
10209            outcome: self.finish_sync_round(prepared.started_at_ms, prepared.attempt, outcome),
10210            controls: if !self.transport_closed() {
10211                downloads.controls
10212            } else {
10213                Vec::new()
10214            },
10215            more,
10216            bootstrap_advanced,
10217        }
10218    }
10219
10220    /// Every unit's resume token and applied-segment record: a bootstrap
10221    /// that advanced changes one (§4.7), also when it applied images of a
10222    /// section it deferred (§5.3, §5.6).
10223    #[allow(clippy::type_complexity)]
10224    fn resume_tokens(&self) -> Option<Vec<(String, Option<String>, Option<String>)>> {
10225        self.conn
10226            .prepare_cached(
10227                "SELECT id, bootstrap_state, applied FROM _syncular_units ORDER BY rowid",
10228            )
10229            .and_then(|mut stmt| {
10230                stmt.query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))?
10231                    .collect()
10232            })
10233            .ok()
10234    }
10235
10236    /// §7.8: one idle drive's default total deadline, the TS client's value.
10237    pub const SYNC_IDLE_TIMEOUT_MS: u64 = 60_000;
10238
10239    pub fn sync_until_idle(
10240        &mut self,
10241        transport: &mut dyn Transport,
10242        max_rounds: Option<u32>,
10243    ) -> SyncOutcome {
10244        self.sync_until_idle_with_deadline(transport, max_rounds, Some(Self::SYNC_IDLE_TIMEOUT_MS))
10245    }
10246
10247    /// As [`SyncClient::sync_until_idle`], with an explicit total deadline in
10248    /// milliseconds (`None` disables it). The deadline is checked against the
10249    /// client clock between rounds: a drive past it after a completed round
10250    /// ends as `BudgetExhausted`. Each round is bounded by `timeout_ms` on its
10251    /// own, or the transport's tighter whole-round deadline (§1.8); a round
10252    /// that reaches the drive bound fails with `sync.idle_timeout`.
10253    pub fn sync_until_idle_with_deadline(
10254        &mut self,
10255        transport: &mut dyn Transport,
10256        max_rounds: Option<u32>,
10257        timeout_ms: Option<u64>,
10258    ) -> SyncOutcome {
10259        // §7.8: an explicit budget is a strict positive round count. Zero is a
10260        // caller error, not an exhaustion.
10261        if max_rounds == Some(0) {
10262            return SyncOutcome::Failed {
10263                details: None,
10264                error_code: "sync.invalid_request".into(),
10265                message: "maxRounds must be a positive integer".into(),
10266                recommended_action: None,
10267            };
10268        }
10269        if timeout_ms.is_some_and(|ms| ms == 0 || i64::try_from(ms).is_err()) {
10270            return SyncOutcome::Failed {
10271                details: None,
10272                error_code: "sync.invalid_request".into(),
10273                message: "timeoutMs must be a positive integer".into(),
10274                recommended_action: None,
10275            };
10276        }
10277        let started_at_ms = self.clock_now_ms();
10278        let rounds = max_rounds.unwrap_or(20);
10279        let mut aggregate = SyncReport::default();
10280        // §7.2.2: decisions pending at the drive's start are evaluated when it
10281        // reaches idle.
10282        let decisions = match self.prepare_replacements() {
10283            Ok(decisions) => decisions,
10284            Err(message) => {
10285                return SyncOutcome::Failed {
10286                    details: None,
10287                    error_code: "storage.failed".into(),
10288                    message,
10289                    recommended_action: None,
10290                }
10291            }
10292        };
10293        let mut spent = 0;
10294        let mut completed = false;
10295        while spent < rounds {
10296            // §7.8: a deadline that elapsed across completed rounds ends the
10297            // drive like an exhausted round budget; the next drive resumes.
10298            if completed
10299                && timeout_ms.is_some_and(|ms| {
10300                    self.clock_now_ms() >= started_at_ms.saturating_add(ms as i64)
10301                })
10302            {
10303                return SyncOutcome::BudgetExhausted(aggregate);
10304            }
10305            let idle_bound = timeout_ms.map(|ms| (ms, spent));
10306            spent += 1;
10307            let before = self.resume_tokens();
10308            match self.sync_bounded(transport, idle_bound) {
10309                SyncOutcome::Failed {
10310                    error_code,
10311                    message,
10312                    details,
10313                    recommended_action,
10314                } => {
10315                    return SyncOutcome::Failed {
10316                        details,
10317                        error_code,
10318                        message,
10319                        recommended_action,
10320                    };
10321                }
10322                outcome @ SyncOutcome::RealtimeUnavailable { .. } => return outcome,
10323                SyncOutcome::BudgetExhausted(_) => {
10324                    unreachable!("sync() never exhausts a round budget")
10325                }
10326                SyncOutcome::Ok(report) => {
10327                    completed = true;
10328                    if max_rounds.is_none()
10329                        && report.segment_rows_applied > 0
10330                        && !report.bootstrapping.is_empty()
10331                        && before != self.resume_tokens()
10332                    {
10333                        spent = 0;
10334                    }
10335                    // TS parity: a closed transport or a schema floor ends
10336                    // the loop. The latest round still merges first.
10337                    let stop = self.transport_closed() || report.schema_floor.is_some();
10338                    aggregate.merge(&report);
10339                    // §4.5: pull again whenever the response contained
10340                    // commits or segments; resets re-bootstrap; a pending
10341                    // resume token continues paging (§4.7); deferred outbox
10342                    // commits and a raised sync-needed signal push on the next
10343                    // round.
10344                    let more = !stop
10345                        && (!report.bootstrapping.is_empty()
10346                            || report.commits_applied > 0
10347                            || report.segment_rows_applied > 0
10348                            || !report.resets.is_empty()
10349                            || report.deferred_commits > 0
10350                            || self.sync_needed);
10351                    if more {
10352                        continue;
10353                    }
10354                    // §7.2.2: a written decision runs another round, which
10355                    // pushes it.
10356                    match self.settle_replacements(&decisions, &SyncOutcome::Ok(aggregate.clone()))
10357                    {
10358                        Ok(true) if !stop => {}
10359                        Ok(_) => return SyncOutcome::Ok(aggregate),
10360                        Err(message) => {
10361                            return SyncOutcome::Failed {
10362                                details: None,
10363                                error_code: "storage.failed".into(),
10364                                message,
10365                                recommended_action: None,
10366                            }
10367                        }
10368                    }
10369                }
10370            }
10371        }
10372        // §7.8: partial success. The aggregate report is retained and the run
10373        // is explicitly not idle.
10374        SyncOutcome::BudgetExhausted(aggregate)
10375    }
10376
10377    fn process_response(
10378        &mut self,
10379        transport: &mut dyn Transport,
10380        response: Message,
10381        meta: &RequestMeta,
10382    ) -> SyncOutcome {
10383        #[cfg(feature = "bench-internals")]
10384        let _phase = self.benchmark_phases.start(Phase::ResponseApply);
10385        let mut report = SyncReport {
10386            pushed: meta.pushed_ids.len() as u32,
10387            ..SyncReport::default()
10388        };
10389        let mut rejection_details_by_commit: HashMap<String, BTreeMap<i32, RejectionDetails>> =
10390            HashMap::new();
10391        let pushed_ids = meta
10392            .pushed_ids
10393            .iter()
10394            .map(String::as_str)
10395            .collect::<HashSet<_>>();
10396        let mut last_final_push_result_id: Option<String> = None;
10397        for frame in &response.frames {
10398            match frame {
10399                Frame::PushResultDetails {
10400                    client_commit_id,
10401                    entries,
10402                } => {
10403                    let details = rejection_details_by_commit
10404                        .entry(client_commit_id.clone())
10405                        .or_default();
10406                    for entry in entries {
10407                        let parsed = match RejectionDetails::parse(&entry.details.0) {
10408                            Ok(value) => value,
10409                            Err(message) => {
10410                                return SyncOutcome::Failed {
10411                                    details: None,
10412                                    error_code: "sync.invalid_request".to_owned(),
10413                                    message,
10414                                    recommended_action: None,
10415                                };
10416                            }
10417                        };
10418                        details.insert(entry.op_index, parsed);
10419                    }
10420                }
10421                Frame::PushResult {
10422                    client_commit_id,
10423                    status,
10424                    results,
10425                    ..
10426                } if pushed_ids.contains(client_commit_id.as_str())
10427                    && Self::push_result_is_final(*status, results) =>
10428                {
10429                    last_final_push_result_id = Some(client_commit_id.clone());
10430                }
10431                _ => {}
10432            }
10433        }
10434        let mut frames = response.frames.into_iter().peekable();
10435        match frames.next() {
10436            Some(Frame::RespHeader {
10437                required_schema_version,
10438                latest_schema_version,
10439                log_epoch,
10440                reset_required,
10441            }) => {
10442                if let Some(required) = required_schema_version {
10443                    // §1.6 schema-floor response: nothing else is processed;
10444                    // stop syncing and surface the upgrade requirement.
10445                    let floor = SchemaFloor {
10446                        required_schema_version: Some(required),
10447                        latest_schema_version,
10448                    };
10449                    if let Err(message) = self.set_schema_floor(Some(floor.clone())) {
10450                        return SyncOutcome::Failed {
10451                            details: None,
10452                            error_code: "storage.failed".to_owned(),
10453                            message,
10454                            recommended_action: None,
10455                        };
10456                    }
10457                    report.schema_floor = Some(floor);
10458                    return SyncOutcome::Ok(report);
10459                }
10460                if reset_required {
10461                    if frames.next().is_some() {
10462                        return SyncOutcome::Failed {
10463                            details: None,
10464                            error_code: "client.invalid_host_response".to_owned(),
10465                            message: "log-epoch reset response contains body frames".to_owned(),
10466                            recommended_action: None,
10467                        };
10468                    }
10469                    match self.run_log_epoch_reset(&log_epoch) {
10470                        Ok(resets) => {
10471                            report.resets = resets;
10472                            return SyncOutcome::Ok(report);
10473                        }
10474                        Err(message) => {
10475                            return SyncOutcome::Failed {
10476                                details: None,
10477                                error_code: "sync.local_corrupt".to_owned(),
10478                                message,
10479                                recommended_action: None,
10480                            };
10481                        }
10482                    }
10483                }
10484                let stored_epoch = match self.get_meta(LOG_EPOCH_KEY) {
10485                    Ok(stored) => stored,
10486                    Err(message) => {
10487                        return SyncOutcome::Failed {
10488                            details: None,
10489                            error_code: "storage.failed".to_owned(),
10490                            message,
10491                            recommended_action: None,
10492                        };
10493                    }
10494                };
10495                // §2.1 adoption: the epoch is stored before any section applies.
10496                if stored_epoch.is_none() {
10497                    if let Err(message) = self.set_meta(LOG_EPOCH_KEY, &log_epoch) {
10498                        return SyncOutcome::Failed {
10499                            details: None,
10500                            error_code: "storage.failed".to_owned(),
10501                            message,
10502                            recommended_action: None,
10503                        };
10504                    }
10505                } else if stored_epoch.as_deref() != Some(log_epoch.as_str()) {
10506                    return SyncOutcome::Failed {
10507                        details: None,
10508                        error_code: "client.invalid_host_response".to_owned(),
10509                        message: "server changed logEpoch without requiring a reset".to_owned(),
10510                        recommended_action: None,
10511                    };
10512                }
10513            }
10514            _ => {
10515                return SyncOutcome::Failed {
10516                    details: None,
10517                    error_code: "sync.invalid_request".to_owned(),
10518                    message: "response does not start with RESP_HEADER".to_owned(),
10519                    recommended_action: None,
10520                };
10521            }
10522        }
10523
10524        if let Err(message) = self.begin_coalesced_apply() {
10525            return SyncOutcome::Failed {
10526                details: None,
10527                error_code: "storage.failed".into(),
10528                message,
10529                recommended_action: None,
10530            };
10531        }
10532        let mut failure: Option<(String, String, Option<String>, Option<Value>)> = None;
10533        // §4.5 client application: the units whose persisted echo a live
10534        // change must match, fixed at LIVE_START after every SUB_END persisted.
10535        let mut live: Option<(LiveStatus, String, Vec<UnitRecord>)> = None;
10536        let mut live_ended = false;
10537        while let Some(frame) = frames.next() {
10538            match frame {
10539                frame @ Frame::PushResult { .. } => {
10540                    let successful = matches!(
10541                        &frame,
10542                        Frame::PushResult {
10543                            status: PushStatus::Applied | PushStatus::Cached,
10544                            ..
10545                        }
10546                    );
10547                    let mut results = vec![frame];
10548                    if successful {
10549                        while matches!(
10550                            frames.peek(),
10551                            Some(Frame::PushResult {
10552                                status: PushStatus::Applied | PushStatus::Cached,
10553                                ..
10554                            })
10555                        ) {
10556                            if let Some(next) = frames.next() {
10557                                results.push(next);
10558                            }
10559                        }
10560                    }
10561                    if self
10562                        .handle_push_results(
10563                            &results,
10564                            &pushed_ids,
10565                            &rejection_details_by_commit,
10566                            &mut report,
10567                            last_final_push_result_id.as_deref(),
10568                        )
10569                        .is_err()
10570                    {
10571                        failure = Some((
10572                            "client.outcome_persistence_failed".to_owned(),
10573                            "local commit outcome could not be persisted".to_owned(),
10574                            None,
10575                            None,
10576                        ));
10577                        break;
10578                    }
10579                }
10580                Frame::PushResultDetails { .. } => {}
10581                Frame::SubStart {
10582                    id,
10583                    status,
10584                    reason_code,
10585                    bootstrap,
10586                    fenced,
10587                } => {
10588                    // §1.4 rule 5: an ERROR closes the section; its body still
10589                    // applied, its SUB_END values are never persisted.
10590                    let mut body = Vec::new();
10591                    let mut sub_end: Option<(i64, Option<String>)> = None;
10592                    let mut error: Option<Frame> = None;
10593                    for inner in frames.by_ref() {
10594                        match inner {
10595                            Frame::SubEnd {
10596                                next_cursor,
10597                                bootstrap_state,
10598                            } => {
10599                                sub_end = Some((next_cursor, bootstrap_state.map(|r| r.0)));
10600                                break;
10601                            }
10602                            inner @ Frame::Error { .. } => {
10603                                error = Some(inner);
10604                                break;
10605                            }
10606                            Frame::Unknown { .. } => {}
10607                            other => body.push(other),
10608                        }
10609                    }
10610                    let ended = sub_end.is_some();
10611                    let section = SectionStart {
10612                        id,
10613                        status,
10614                        reason_code,
10615                        bootstrap,
10616                        fenced,
10617                    };
10618                    let completed = match self.process_section(
10619                        transport,
10620                        &section,
10621                        body,
10622                        sub_end,
10623                        meta,
10624                        &mut report,
10625                    ) {
10626                        Err(SectionError::Abort(code, message)) => {
10627                            failure = Some((code, message, None, None));
10628                            break;
10629                        }
10630                        Err(SectionError::Transport(error)) => {
10631                            failure = Some((error.code, error.message, None, error.details));
10632                            break;
10633                        }
10634                        Ok(completed) => completed,
10635                        Err(_) => false,
10636                    };
10637                    if ended {
10638                        // The counters stay: `complete` and `failed` report them.
10639                        // §7.7: a completed bootstrap ends with the unit total
10640                        // equal to the rows processed.
10641                        self.progress.update(|p| {
10642                            p.unit_id = None;
10643                            p.table = None;
10644                            p.segment_id = None;
10645                            if completed && p.unit_rows_total.is_some() {
10646                                p.unit_rows_total = p.unit_rows_processed;
10647                            }
10648                        });
10649                    }
10650                    match error {
10651                        Some(Frame::Error {
10652                            code,
10653                            message,
10654                            recommended_action,
10655                            details,
10656                            ..
10657                        }) => {
10658                            failure = Some(Self::error_frame_failure(
10659                                code,
10660                                message,
10661                                recommended_action,
10662                                details,
10663                            ));
10664                            break;
10665                        }
10666                        Some(_) => unreachable!("only an ERROR closes a section early"),
10667                        None if !ended => {
10668                            failure = Some((
10669                                "sync.invalid_request".to_owned(),
10670                                "unit section without SUB_END".to_owned(),
10671                                None,
10672                                None,
10673                            ));
10674                            break;
10675                        }
10676                        None => {}
10677                    }
10678                }
10679                Frame::LiveStart {
10680                    status,
10681                    reason_code,
10682                } => {
10683                    let receivers = match self.stored(load_units(&self.conn)) {
10684                        Ok(units) => units
10685                            .into_iter()
10686                            .filter(|unit| {
10687                                unit.status == UnitStatus::Active
10688                                    && unit.echo.is_some()
10689                                    && !unit.bootstrapping()
10690                            })
10691                            .collect(),
10692                        Err(message) => {
10693                            failure = Some(("storage.failed".to_owned(), message, None, None));
10694                            break;
10695                        }
10696                    };
10697                    live = Some((status, reason_code, receivers));
10698                }
10699                Frame::Commit {
10700                    commit_seq,
10701                    tables,
10702                    changes,
10703                    ..
10704                } => {
10705                    let Some((LiveStatus::Active, _, receivers)) = &live else {
10706                        continue;
10707                    };
10708                    let receivers = receivers.clone();
10709                    match self.apply_live_commit(
10710                        &receivers,
10711                        &tables,
10712                        changes,
10713                        commit_seq,
10714                        AppliedServerCommitSource::Pull,
10715                    ) {
10716                        Ok(applied) => report.commits_applied += u32::from(applied),
10717                        Err(error) => {
10718                            failure = Some((error.code, error.message, None, error.details));
10719                            break;
10720                        }
10721                    }
10722                }
10723                Frame::LiveEnd {
10724                    through_seq,
10725                    echo_digest,
10726                } => {
10727                    let Some((status, reason_code, _)) = live.take() else {
10728                        continue;
10729                    };
10730                    live_ended = true;
10731                    live = Some((status, String::new(), Vec::new()));
10732                    if let Err(message) = self.finish_live_section(
10733                        status,
10734                        &reason_code,
10735                        through_seq,
10736                        echo_digest,
10737                        &meta.registration_digest,
10738                        &mut report,
10739                    ) {
10740                        failure = Some(("storage.failed".to_owned(), message, None, None));
10741                        break;
10742                    }
10743                }
10744                Frame::Lease {
10745                    lease_id,
10746                    expires_at_ms,
10747                } => {
10748                    // §7.3.5: persist the opaque lease; a fresh lease clears
10749                    // any prior lease error (the outage/revocation is over).
10750                    if let Err(message) = self.set_lease_state(Some(LeaseState {
10751                        lease_id: Some(lease_id),
10752                        expires_at_ms: Some(expires_at_ms),
10753                        error_code: None,
10754                    })) {
10755                        failure = Some(("storage.failed".to_owned(), message, None, None));
10756                        break;
10757                    }
10758                }
10759                Frame::Error {
10760                    code,
10761                    message,
10762                    recommended_action,
10763                    details,
10764                    ..
10765                } => {
10766                    // §1.6: the whole request failed; already-completed
10767                    // units keep their applied data and cursors.
10768                    failure = Some(Self::error_frame_failure(
10769                        code,
10770                        message,
10771                        recommended_action,
10772                        details,
10773                    ));
10774                    break;
10775                }
10776                Frame::Unknown { .. } => {}
10777                // §1.6: a building server's keepalive carries nothing to apply.
10778                Frame::Keepalive => {}
10779                _ => {
10780                    failure = Some((
10781                        "sync.invalid_request".to_owned(),
10782                        "unexpected frame in response".to_owned(),
10783                        None,
10784                        None,
10785                    ));
10786                    break;
10787                }
10788            }
10789        }
10790
10791        let applied = match failure {
10792            Some(failure) => Err(failure),
10793            // Local apply boundaries already reconciled their affected overlay.
10794            // Refuse round success if any remaining dirty work fails to
10795            // reconcile. §4.8 E1: the push half may have drained commits that
10796            // pinned rows of a shrunk window unit, so retry deferred evictions.
10797            None => self
10798                .rebuild_overlay_if_dirty()
10799                .and_then(|()| self.drain_pending_evictions())
10800                .map_err(|message| ("storage.failed".to_owned(), message, None, None)),
10801        };
10802        // §1.4 rule 4: frames completed before a failure stay committed; a
10803        // failed COMMIT of the coalesced transaction fails the round.
10804        if let Err(message) = self.finish_coalesced_apply() {
10805            return SyncOutcome::Failed {
10806                details: None,
10807                error_code: "storage.failed".into(),
10808                message,
10809                recommended_action: None,
10810            };
10811        }
10812        if let Err((error_code, message, recommended_action, details)) = applied {
10813            return SyncOutcome::Failed {
10814                details,
10815                error_code,
10816                message,
10817                recommended_action,
10818            };
10819        }
10820        let catching_up = match self.stored(load_units(&self.conn)) {
10821            Ok(units) => units
10822                .into_iter()
10823                .filter(|unit| unit.status == UnitStatus::Active && unit.cursor.is_some())
10824                .map(|unit| unit.id)
10825                .collect::<Vec<_>>(),
10826            Err(message) => {
10827                return SyncOutcome::Failed {
10828                    details: None,
10829                    error_code: "storage.failed".into(),
10830                    message,
10831                    recommended_action: None,
10832                }
10833            }
10834        };
10835        // §7.1: a response without LIVE_END, one answered `unregistered` or
10836        // `reset`, or a unit still catching up leaves sync-needed raised;
10837        // after `unregistered` the next round starts at once.
10838        let status = live.map(|(status, _, _)| status);
10839        if !live_ended || status != Some(LiveStatus::Active) || !catching_up.is_empty() {
10840            self.set_sync_needed(true, status == Some(LiveStatus::Unregistered));
10841        }
10842        self.ack_after_pull(transport);
10843        // §7.4.5: the reset is over once the first post-reset pull round
10844        // leaves no unit catching up: the tables are rebuilt and current.
10845        if self.upgrading && catching_up.is_empty() {
10846            self.set_upgrading(false);
10847        }
10848        report.bootstrapping = catching_up;
10849        SyncOutcome::Ok(report)
10850    }
10851
10852    /// §1.6 / §10.1: the failure an in-band `ERROR` frame reports.
10853    fn error_frame_failure(
10854        code: String,
10855        message: String,
10856        recommended_action: String,
10857        details: Option<RawJson>,
10858    ) -> (String, String, Option<String>, Option<Value>) {
10859        let recommended_action = (!recommended_action.is_empty()).then_some(recommended_action);
10860        let details = details
10861            .and_then(|details| serde_json::from_str::<Value>(&details.0).ok())
10862            .filter(Value::is_object);
10863        (code, message, recommended_action, details)
10864    }
10865
10866    /// §4.5 at `LIVE_END` of a pull: join rule J for an `active` section, the
10867    /// §4.6 replica reset for `reset`, nothing for `unregistered`; then the
10868    /// replica cursor, the echo digest and the digest of the list the server
10869    /// now stores.
10870    fn finish_live_section(
10871        &mut self,
10872        status: LiveStatus,
10873        reason_code: &str,
10874        through_seq: i64,
10875        echo_digest: Option<[u8; 32]>,
10876        registration_digest: &str,
10877        report: &mut SyncReport,
10878    ) -> Result<(), String> {
10879        let rollback = self.capture();
10880        let resets = report.resets.len();
10881        self.begin_observation("syncular_live_end")?;
10882        let finished = (|| {
10883            let mut batch = ChangeAccumulator::default();
10884            let before = self.stored(replica_cursor(&self.conn))?;
10885            let mut cursor = if status == LiveStatus::Unregistered {
10886                before
10887            } else {
10888                -1
10889            };
10890            let joined = before.max(through_seq);
10891            for unit in self.stored(load_units(&self.conn))? {
10892                if unit.status != UnitStatus::Active || unit.bootstrapping() {
10893                    continue;
10894                }
10895                match status {
10896                    // §4.6 replica reset: every live unit bootstraps again;
10897                    // post-bootstrap units keep their cursors.
10898                    LiveStatus::Reset if unit.cursor.is_none() => {
10899                        self.record_unit_windows(&mut batch, &unit)?;
10900                        report.resets.push(unit.id.clone());
10901                        self.stored(save_unit(
10902                            &self.conn,
10903                            &UnitRecord {
10904                                reason_code: Some(reason_code.to_owned()),
10905                                cursor: Some(-1),
10906                                seeded: Vec::new(),
10907                                ..unit
10908                            },
10909                        ))?;
10910                    }
10911                    // §4.5 join rule J.
10912                    LiveStatus::Active => {
10913                        let next = unit.cursor.unwrap_or(joined).max(through_seq);
10914                        if next >= joined {
10915                            cursor = joined;
10916                        }
10917                        if unit.cursor.is_some() {
10918                            // A post-bootstrap unit that joins live transitions.
10919                            if next >= joined {
10920                                self.record_unit_windows(&mut batch, &unit)?;
10921                            }
10922                            self.stored(save_unit(
10923                                &self.conn,
10924                                &UnitRecord {
10925                                    cursor: (next < joined).then_some(next),
10926                                    ..unit
10927                                },
10928                            ))?;
10929                        }
10930                    }
10931                    _ => {}
10932                }
10933            }
10934            self.set_meta(REPLICA_CURSOR_KEY, &cursor.to_string())?;
10935            self.set_meta(
10936                ECHO_DIGEST_KEY,
10937                &echo_digest
10938                    .map(|digest| bytes_to_hex(&digest))
10939                    .unwrap_or_default(),
10940            )?;
10941            if status == LiveStatus::Unregistered {
10942                self.delete_meta(REGISTERED_DIGEST_KEY)?;
10943            } else {
10944                self.set_meta(REGISTERED_DIGEST_KEY, registration_digest)?;
10945            }
10946            self.finish_observation("syncular_live_end", batch)
10947        })();
10948        if finished.is_err() {
10949            self.rollback_observation("syncular_live_end");
10950            self.restore(rollback);
10951            report.resets.truncate(resets);
10952        }
10953        finished
10954    }
10955
10956    // -- push results (§6.3, §7.2) ------------------------------------------------
10957
10958    fn handle_push_results(
10959        &mut self,
10960        frames: &[Frame],
10961        pushed_ids: &HashSet<&str>,
10962        rejection_details_by_commit: &HashMap<String, BTreeMap<i32, RejectionDetails>>,
10963        report: &mut SyncReport,
10964        last_final_push_result_id: Option<&str>,
10965    ) -> Result<(), String> {
10966        self.begin_observation("syncular_push_results")?;
10967        let rollback = self.capture();
10968        let conflict_count = self.conflicts.len();
10969        let applied_count = report.applied.len();
10970        let rejected_count = report.rejected.len();
10971        let retryable_count = report.retryable.len();
10972        let mut drained = Vec::new();
10973        let mut batch = ChangeAccumulator::default();
10974        let persisted = (|| {
10975            for frame in frames {
10976                let Frame::PushResult {
10977                    client_commit_id,
10978                    status,
10979                    results,
10980                    commit_seq,
10981                } = frame
10982                else {
10983                    return Err("unexpected acknowledgement frame".to_owned());
10984                };
10985                if !pushed_ids.contains(client_commit_id.as_str()) {
10986                    continue;
10987                }
10988                let Some(index) = self
10989                    .outbox
10990                    .iter()
10991                    .position(|commit| commit.client_commit_id == *client_commit_id)
10992                else {
10993                    continue;
10994                };
10995                let status = *status;
10996                let rejection_details = rejection_details_by_commit.get(client_commit_id);
10997                let operations = self.outbox[index].ops.clone();
10998                match status {
10999                    PushStatus::Applied | PushStatus::Cached => {
11000                        // §7.2: a lost ack replays as `cached` — proceed as if the
11001                        // ack had arrived.
11002                        let sequence =
11003                            commit_seq.ok_or_else(|| "ACK lacks a commit sequence".to_owned())?;
11004                        let affected: HashSet<_> = operations
11005                            .iter()
11006                            .map(|op| (op.table.as_str(), op.row_id.as_str()))
11007                            .collect();
11008                        let prior = self.acknowledged_operations(Some(&affected), None)?;
11009                        for (op_index, operation) in operations.iter().enumerate() {
11010                            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))
11011                                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11012                            if delivered {
11013                                continue;
11014                            }
11015                            let table = self
11016                                .schema
11017                                .table(&operation.table)
11018                                .ok_or_else(|| "sync.unknown_table".to_owned())?;
11019                            let mut intended: Map<String, Value> = self
11020                                .stored_row(table, &operation.row_id, true)?
11021                                .map(|(row, _)| {
11022                                    table
11023                                        .columns
11024                                        .iter()
11025                                        .zip(&row)
11026                                        .map(|(column, value)| {
11027                                            (column.name.clone(), column_value_to_json(value))
11028                                        })
11029                                        .collect()
11030                                })
11031                                .unwrap_or_default();
11032                            let mut scope_image = intended.clone();
11033                            for op in prior
11034                                .iter()
11035                                .chain(
11036                                    self.failed_commits
11037                                        .iter()
11038                                        .flat_map(|(commit, _)| &commit.ops),
11039                                )
11040                                .chain(
11041                                    self.outbox
11042                                        .iter()
11043                                        .take(index)
11044                                        .flat_map(|commit| &commit.ops),
11045                                )
11046                                .chain(operations.iter().take(op_index + 1))
11047                            {
11048                                if op.table != operation.table || op.row_id != operation.row_id {
11049                                    continue;
11050                                }
11051                                if let Some(values) = &op.values {
11052                                    intended.extend(values.clone());
11053                                } else {
11054                                    scope_image = intended.clone();
11055                                    intended.clear();
11056                                }
11057                            }
11058                            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)",
11059                                rusqlite::params![client_commit_id, op_index as i64, operation.table, operation.row_id, sequence,
11060                                    serde_json::to_string(&CommitOperation::from(operation)).map_err(|_| "sync.local_corrupt".to_owned())?,
11061                                    serde_json::to_string(if operation.upsert { &intended } else { &scope_image }).map_err(|_| "sync.local_corrupt".to_owned())?])
11062                                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11063                        }
11064                        let journal_results = results
11065                            .iter()
11066                            .map(|result| {
11067                                let op_index = match result {
11068                                    OpResult::Applied { op_index }
11069                                    | OpResult::Conflict { op_index, .. }
11070                                    | OpResult::Error { op_index, .. } => *op_index,
11071                                };
11072                                CommitOperationOutcome::Applied { op_index }
11073                            })
11074                            .collect::<Vec<_>>();
11075                        let outcome_status = if status == PushStatus::Applied {
11076                            CommitOutcomeStatus::Applied
11077                        } else {
11078                            CommitOutcomeStatus::Cached
11079                        };
11080                        let persisted = self
11081                            .persist_commit_outcome(
11082                                client_commit_id,
11083                                outcome_status,
11084                                &journal_results,
11085                                None,
11086                            )
11087                            .and_then(|()| self.delete_outbox_persisted(client_commit_id));
11088                        persisted?;
11089                        self.sync_needed = true;
11090                        batch.status = true;
11091                        batch.outcomes = true;
11092                    }
11093                    PushStatus::Rejected => {
11094                        if results.iter().any(|result| {
11095                            matches!(
11096                                result,
11097                                OpResult::Error {
11098                                    code,
11099                                    retryable: true,
11100                                    ..
11101                                } if code == "sync.idempotency_cache_miss"
11102                            )
11103                        }) {
11104                            // §6.3/§7.2: a serving failure, not an outcome — keep the
11105                            // exact commit queued for an identical retry.
11106                            report.retryable.push(client_commit_id.to_owned());
11107                            continue;
11108                        }
11109
11110                        let mut journal_results = Vec::with_capacity(results.len());
11111                        let mut conflicts = Vec::new();
11112                        let mut rejections = Vec::new();
11113                        for result in results {
11114                            match result {
11115                                OpResult::Applied { op_index } => {
11116                                    journal_results.push(CommitOperationOutcome::Applied {
11117                                        op_index: *op_index,
11118                                    });
11119                                }
11120                                OpResult::Conflict {
11121                                    op_index,
11122                                    code,
11123                                    message,
11124                                    server_version,
11125                                    server_row,
11126                                    conflict_columns: conflict_columns_bitmap,
11127                                } => {
11128                                    let operation = operations
11129                                        .get(*op_index as usize)
11130                                        .map(CommitOperation::from);
11131                                    let (table, row_id) = operation
11132                                        .as_ref()
11133                                        .map(|op| (op.table.clone(), op.row_id.clone()))
11134                                        .unwrap_or_default();
11135                                    let server_row_json = self
11136                                        .schema
11137                                        .table(&table)
11138                                        .and_then(|t| {
11139                                            decode_row_bytes(t, server_row, &self.encryption)
11140                                                .ok()
11141                                                .map(|(row, _)| (t, row))
11142                                        })
11143                                        .map(|(t, row)| {
11144                                            let mut map = Map::new();
11145                                            for (i, column) in t.columns.iter().enumerate() {
11146                                                map.insert(
11147                                                    column.name.clone(),
11148                                                    column_value_to_json(
11149                                                        row.get(i).unwrap_or(&None),
11150                                                    ),
11151                                                );
11152                                            }
11153                                            map
11154                                        })
11155                                        .unwrap_or_default();
11156                                    // §6.3: decode the presence-layout bitmap
11157                                    // into the marked column names.
11158                                    let conflict_columns = self
11159                                        .schema
11160                                        .table(&table)
11161                                        .map(|t| {
11162                                            t.columns
11163                                                .iter()
11164                                                .enumerate()
11165                                                .filter(|(index, _)| {
11166                                                    conflict_columns_bitmap
11167                                                        .get(index / 8)
11168                                                        .is_some_and(|byte| {
11169                                                            byte & (1 << (index % 8)) != 0
11170                                                        })
11171                                                })
11172                                                .map(|(_, column)| column.name.clone())
11173                                                .collect::<Vec<_>>()
11174                                        })
11175                                        .unwrap_or_default();
11176                                    let conflict = ConflictRecord {
11177                                        client_commit_id: client_commit_id.to_owned(),
11178                                        op_index: *op_index,
11179                                        table,
11180                                        row_id,
11181                                        code: code.clone(),
11182                                        message: message.clone(),
11183                                        server_version: *server_version,
11184                                        server_row: server_row_json,
11185                                        conflict_columns,
11186                                        operation,
11187                                    };
11188                                    journal_results.push(CommitOperationOutcome::Conflict {
11189                                        conflict: conflict.clone(),
11190                                    });
11191                                    conflicts.push(conflict);
11192                                }
11193                                OpResult::Error {
11194                                    op_index,
11195                                    code,
11196                                    message,
11197                                    retryable,
11198                                } => {
11199                                    let rejection = RejectionRecord {
11200                                        client_commit_id: client_commit_id.to_owned(),
11201                                        op_index: *op_index,
11202                                        code: code.clone(),
11203                                        message: message.clone(),
11204                                        retryable: *retryable,
11205                                        details: rejection_details
11206                                            .and_then(|details| details.get(op_index))
11207                                            .cloned(),
11208                                        operation: operations
11209                                            .get(*op_index as usize)
11210                                            .map(CommitOperation::from),
11211                                    };
11212                                    journal_results.push(CommitOperationOutcome::Error {
11213                                        rejection: rejection.clone(),
11214                                    });
11215                                    rejections.push(rejection);
11216                                }
11217                            }
11218                        }
11219                        if self.retain_failed_commits {
11220                            self.retain_failed_commit(client_commit_id, &operations)?;
11221                        }
11222                        let outcome_status = if conflicts.is_empty() {
11223                            CommitOutcomeStatus::Rejected
11224                        } else {
11225                            CommitOutcomeStatus::Conflict
11226                        };
11227                        self.leave_through(client_commit_id);
11228                        let persisted = self
11229                            .persist_commit_outcome(
11230                                client_commit_id,
11231                                outcome_status,
11232                                &journal_results,
11233                                Some(&operations),
11234                            )
11235                            .and_then(|()| self.delete_outbox_persisted(client_commit_id));
11236                        persisted?;
11237                        batch.conflicts = !conflicts.is_empty();
11238                        batch.rejections = !rejections.is_empty();
11239                        batch.status = true;
11240                        batch.outcomes = true;
11241                        self.conflicts.extend(conflicts);
11242                        self.rejections.extend(rejections);
11243                    }
11244                }
11245                drained.push(self.outbox.remove(index));
11246                if batch.status {
11247                    for operation in &operations {
11248                        if !self.record_row_scopes(
11249                            &mut batch,
11250                            &operation.table,
11251                            &operation.row_id,
11252                            false,
11253                        ) {
11254                            batch.table(&operation.table);
11255                        }
11256                    }
11257                }
11258                match status {
11259                    PushStatus::Applied | PushStatus::Cached => {
11260                        report.applied.push(client_commit_id.to_owned())
11261                    }
11262                    PushStatus::Rejected => report.rejected.push(client_commit_id.to_owned()),
11263                }
11264            }
11265            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)) {
11266                self.prune_commit_outcomes()?;
11267            }
11268            self.reconcile_rows(&drained)?;
11269            self.rebuild_overlay_if_dirty()?;
11270            self.finish_observation("syncular_push_results", batch)
11271        })();
11272        if let Err(error) = persisted {
11273            self.rollback_observation("syncular_push_results");
11274            self.restore(rollback);
11275            report.applied.truncate(applied_count);
11276            report.rejected.truncate(rejected_count);
11277            report.retryable.truncate(retryable_count);
11278            return Err(error);
11279        }
11280        if !rollback.sync_needed && self.sync_needed {
11281            self.sync_intent_queue.push_back(SyncIntent::Interactive);
11282        }
11283        report.conflicts += (self.conflicts.len() - conflict_count) as u32;
11284        Ok(())
11285    }
11286
11287    fn push_result_is_final(status: PushStatus, results: &[OpResult]) -> bool {
11288        status != PushStatus::Rejected
11289            || !results.iter().any(|result| {
11290                matches!(
11291                    result,
11292                    OpResult::Error {
11293                        code,
11294                        retryable: true,
11295                        ..
11296                    } if code == "sync.idempotency_cache_miss"
11297                )
11298            })
11299    }
11300
11301    // -- unit sections and the live section ------------------------------------------
11302
11303    /// One unit section (§4.4): apply its segments, then persist its
11304    /// `SUB_END` (§4.6 reset, §3.3 revocation and purge, the echo, cursor and
11305    /// resume token). A section of a unit the app released while the round was
11306    /// in flight is skipped; a fail-closed first page fails the unit and skips
11307    /// the rest of its section (§5.6). Returns whether its `SUB_END` completed
11308    /// a bootstrap (§7.7).
11309    fn process_section(
11310        &mut self,
11311        transport: &mut dyn Transport,
11312        start: &SectionStart,
11313        body: Vec<Frame>,
11314        sub_end: Option<(i64, Option<String>)>,
11315        meta: &RequestMeta,
11316        report: &mut SyncReport,
11317    ) -> Result<bool, SectionError> {
11318        let storage = |message| SectionError::Abort("storage.failed".to_owned(), message);
11319        let unit = self
11320            .stored(get_unit(&self.conn, &start.id))
11321            .map_err(storage)?
11322            .filter(|unit| unit.status == UnitStatus::Active);
11323        // §7.7: a section boundary ends the previous payload; the section's
11324        // UNIT_EXTENT starts the unit counters in the same snapshot.
11325        let extent = match (&unit, body.first()) {
11326            (
11327                Some(_),
11328                Some(Frame::UnitExtent {
11329                    rows_total,
11330                    rows_done,
11331                }),
11332            ) => u64::try_from(*rows_total)
11333                .ok()
11334                .zip(u64::try_from(*rows_done).ok()),
11335            _ => None,
11336        };
11337        self.progress.update(|p| {
11338            p.phase = ProgressPhase::Import;
11339            p.unit_id = unit.as_ref().map(|unit| unit.id.clone());
11340            p.unit_rows_total = extent.map(|(total, _)| total);
11341            p.unit_rows_processed = extent.map(|(_, done)| done);
11342            p.table = None;
11343            p.segment_id = None;
11344            p.bytes_received = 0;
11345            p.bytes_total = None;
11346            p.rows_processed = 0;
11347            p.rows_total = None;
11348            p.import_write_ms = None;
11349            p.import_commit_ms = None;
11350            p.download_ms = None;
11351        });
11352        let Some(unit) = unit else {
11353            return Ok(false);
11354        };
11355        let echo: Vec<EchoRecord> = start
11356            .fenced
11357            .iter()
11358            .map(|record| EchoRecord {
11359                table: record.table.clone(),
11360                status: record.status.name().to_owned(),
11361                scopes: record.scopes.iter().cloned().collect(),
11362            })
11363            .collect();
11364        // §5.6: rows earlier attempts at this position applied.
11365        let applied_record = self
11366            .stored(applied_rows(&self.conn, &unit.id))
11367            .map_err(storage)?;
11368        // §5.6: a resumed bootstrap keeps the tables it already seeded.
11369        let mut seeded: BTreeSet<String> = if unit.bootstrap_state.is_none() {
11370            BTreeSet::new()
11371        } else {
11372            unit.seeded.iter().cloned().collect()
11373        };
11374        let applied = (|| {
11375            for frame in body {
11376                match frame {
11377                    Frame::SegmentInline { payload } => {
11378                        let segment = decode_rows_segment(&payload).map_err(|e| {
11379                            SectionError::Abort(e.code.as_str().to_owned(), e.detail)
11380                        })?;
11381                        self.progress.update(|p| {
11382                            p.phase = ProgressPhase::Import;
11383                            p.unit_id = Some(unit.id.clone());
11384                            p.table = Some(segment.table.clone());
11385                            p.segment_id = None;
11386                            p.bytes_received = payload.len() as u64;
11387                            p.bytes_total = Some(payload.len() as u64);
11388                            p.rows_processed = 0;
11389                            p.rows_total =
11390                                Some(segment.blocks.iter().map(|block| block.len() as u64).sum());
11391                            p.import_write_ms = None;
11392                            p.import_commit_ms = None;
11393                            p.download_ms = None;
11394                        });
11395                        let (pair, clear, effective) =
11396                            self.segment_pair(&unit, &echo, &seeded, &segment.table)?;
11397                        report.segment_rows_applied +=
11398                            self.apply_segment(&pair, &segment, clear, &effective, &unit.id)?;
11399                        seeded.insert(segment.table);
11400                    }
11401                    Frame::SegmentRef {
11402                        segment_id,
11403                        byte_length,
11404                        media_type,
11405                        table,
11406                        row_count,
11407                        as_of_commit_seq,
11408                        scope_digest,
11409                        row_cursor,
11410                        next_row_cursor,
11411                        url,
11412                        url_expires_at_ms,
11413                        ..
11414                    } => {
11415                        // §4.2: reject a descriptor whose mediaType was not
11416                        // advertised — never skip or guess.
11417                        let advertised = match media_type {
11418                            MediaType::Rows => {
11419                                meta.accept & ACCEPT_EXTERNAL_ROWS != 0
11420                                    || meta.accept & ACCEPT_INLINE_ROWS != 0
11421                            }
11422                            MediaType::Sqlite => meta.accept & ACCEPT_SQLITE != 0,
11423                        };
11424                        if !advertised {
11425                            return Err(SectionError::Abort(
11426                                "sync.invalid_request".to_owned(),
11427                                format!(
11428                                    "SEGMENT_REF mediaType {} was not advertised in accept (§4.2)",
11429                                    media_type.name()
11430                                ),
11431                            ));
11432                        }
11433                        // §5.6 applied-segment rule: a partly applied image
11434                        // already ran its table's first-page clear.
11435                        let resumed = applied_record.get(&segment_id).copied();
11436                        if resumed.is_some() {
11437                            seeded.insert(table.clone());
11438                        }
11439                        if resumed == Some(row_count) {
11440                            // §7.7: an earlier attempt imported this payload;
11441                            // its rows still count toward the unit.
11442                            self.progress.update(|p| {
11443                                p.phase = ProgressPhase::Import;
11444                                p.unit_id = Some(unit.id.clone());
11445                                p.table = Some(table.clone());
11446                                p.segment_id = Some(segment_id.clone());
11447                                p.bytes_received = 0;
11448                                p.bytes_total = None;
11449                                p.rows_processed = 0;
11450                                p.rows_total = u64::try_from(row_count).ok();
11451                                p.import_write_ms = None;
11452                                p.import_commit_ms = None;
11453                                p.download_ms = None;
11454                            });
11455                            self.progress.update(|p| {
11456                                p.rows_processed = u64::try_from(row_count).unwrap_or(0)
11457                            });
11458                            continue;
11459                        }
11460                        if meta
11461                            .deferred
11462                            .contains(&(unit.id.clone(), segment_id.clone()))
11463                        {
11464                            return Err(SectionError::Deferred);
11465                        }
11466                        self.progress.update(|p| {
11467                            p.phase = ProgressPhase::Download;
11468                            p.unit_id = Some(unit.id.clone());
11469                            p.table = Some(table.clone());
11470                            p.segment_id = Some(segment_id.clone());
11471                            p.bytes_received = 0;
11472                            p.bytes_total = u64::try_from(byte_length).ok();
11473                            p.rows_processed = 0;
11474                            p.rows_total = u64::try_from(row_count).ok();
11475                            p.import_write_ms = None;
11476                            p.import_commit_ms = None;
11477                            p.download_ms = None;
11478                        });
11479                        let observer = self.progress.clone();
11480                        let mut on_progress = |bytes| observer.update(|p| p.bytes_received = bytes);
11481                        // §7.7: from the request's start to its last body byte.
11482                        let requested = std::time::Instant::now();
11483                        let bytes = if let Some(url) = url {
11484                            // §5.4: a url-carrying descriptor MUST be fetched
11485                            // from that URL; failure invalidates the whole
11486                            // descriptor (no fall-through to §5.5 — re-pull
11487                            // recovers, §1.4 rule 5).
11488                            if meta.accept & ACCEPT_SIGNED_URLS == 0 {
11489                                return Err(SectionError::Abort(
11490                                    "sync.invalid_request".to_owned(),
11491                                    "SEGMENT_REF carries a url but accept bit 3 was not advertised (§5.4)"
11492                                        .to_owned(),
11493                                ));
11494                            }
11495                            // §5.4: MUST NOT start a fetch at/past expiry.
11496                            if url_expires_at_ms.is_some_and(|exp| {
11497                                exp <= transport
11498                                    .segment_fetch_started_at(&url)
11499                                    .unwrap_or_else(|| self.clock_now_ms())
11500                            }) {
11501                                return Err(SectionError::Abort(
11502                                    "sync.segment_expired".to_owned(),
11503                                    format!(
11504                                        "signed URL for segment {segment_id} expired before fetch — re-pull mints fresh descriptors (§5.4)"
11505                                    ),
11506                                ));
11507                            }
11508                            transport
11509                                .fetch_url(
11510                                    &url,
11511                                    u64::try_from(byte_length).unwrap_or(0),
11512                                    &mut on_progress,
11513                                )
11514                                .map_err(|e| self.segment_fetch_failed(e))?
11515                        } else {
11516                            // §5.5: the owning unit's scope map, each value a one-element list.
11517                            let requested_scopes_json =
11518                                canonical_scope_json(&unit_scope_lists(&unit.scopes));
11519                            transport
11520                                .download_segment(
11521                                    &SegmentRequest {
11522                                        segment_id: segment_id.clone(),
11523                                        table: table.clone(),
11524                                        requested_scopes_json,
11525                                        byte_length: u64::try_from(byte_length).unwrap_or(0),
11526                                    },
11527                                    &mut on_progress,
11528                                )
11529                                .map_err(|e| {
11530                                    // §5.5: access changed since the response;
11531                                    // the next round's SUB_START settles the unit.
11532                                    if e.code == "sync.forbidden" {
11533                                        SectionError::Refused
11534                                    } else {
11535                                        self.segment_fetch_failed(e)
11536                                    }
11537                                })?
11538                        };
11539                        let download_ms = u64::try_from(requested.elapsed().as_millis()).ok();
11540                        // §5.4: the descriptor's byteLength caps the body before
11541                        // §5.1 verifies the content address; the client discards
11542                        // the segment and re-pulls on either failure.
11543                        if bytes.len() as i64 > byte_length {
11544                            self.schedule_background_retry();
11545                            return Err(SectionError::Abort(
11546                                "sync.invalid_request".to_owned(),
11547                                "segment exceeds its byteLength".to_owned(),
11548                            ));
11549                        }
11550                        on_progress(bytes.len() as u64);
11551                        let digest = Sha256::digest(&bytes);
11552                        let expected = segment_id
11553                            .strip_prefix("sha256:")
11554                            .unwrap_or(segment_id.as_str());
11555                        if bytes_to_hex(&digest) != expected {
11556                            // §5.1: the client discards the segment and re-pulls.
11557                            self.schedule_background_retry();
11558                            return Err(SectionError::Abort(
11559                                "sync.invalid_request".to_owned(),
11560                                "segment bytes do not match the content address (§5.1)".to_owned(),
11561                            ));
11562                        }
11563                        self.progress.update(|p| {
11564                            p.phase = ProgressPhase::Import;
11565                            p.download_ms = download_ms;
11566                        });
11567                        if media_type == MediaType::Sqlite {
11568                            // §5.3: a range image keeps its position in the resume
11569                            // token; a descriptor row cursor is invalid.
11570                            if row_cursor.is_some() || next_row_cursor.is_some() {
11571                                return Err(SectionError::Abort(
11572                                    "sync.invalid_request".to_owned(),
11573                                    "sqlite segments are whole-table: rowCursor/nextRowCursor must be absent (§5.3)"
11574                                        .to_owned(),
11575                                ));
11576                            }
11577                            let (pair, clear, effective) =
11578                                self.segment_pair(&unit, &echo, &seeded, &table)?;
11579                            report.segment_rows_applied += self.apply_sqlite_segment(
11580                                &pair,
11581                                &bytes,
11582                                clear,
11583                                &effective,
11584                                &unit.id,
11585                                &segment_id,
11586                                resumed.unwrap_or(0),
11587                                row_count,
11588                                as_of_commit_seq,
11589                                &scope_digest,
11590                            )?;
11591                            seeded.insert(table);
11592                        } else {
11593                            let segment = decode_rows_segment(&bytes).map_err(|e| {
11594                                SectionError::Abort(e.code.as_str().to_owned(), e.detail)
11595                            })?;
11596                            let (pair, clear, effective) =
11597                                self.segment_pair(&unit, &echo, &seeded, &segment.table)?;
11598                            report.segment_rows_applied +=
11599                                self.apply_segment(&pair, &segment, clear, &effective, &unit.id)?;
11600                            seeded.insert(segment.table);
11601                            // An image records its rows with each chunk.
11602                            self.stored(record_applied_rows(
11603                                &self.conn,
11604                                &unit.id,
11605                                &segment_id,
11606                                row_count,
11607                            ))
11608                            .map_err(storage)?;
11609                        }
11610                    }
11611                    Frame::UnitExtent { .. } => {}
11612                    _ => {
11613                        return Err(SectionError::Abort(
11614                            "sync.invalid_request".to_owned(),
11615                            "unexpected frame inside a unit section".to_owned(),
11616                        ));
11617                    }
11618                }
11619            }
11620            Ok(())
11621        })();
11622        match applied {
11623            Ok(()) => {}
11624            // The unit keeps catching up with its cursor unpersisted.
11625            Err(SectionError::Refused | SectionError::Deferred) => return Ok(false),
11626            Err(SectionError::FailClosed) => {
11627                // §5.6: the failure is unit-local; the rest of the response
11628                // still applies and the failed unit leaves the list.
11629                self.begin_observation("syncular_section_failure")
11630                    .map_err(storage)?;
11631                let failed = (|| {
11632                    let mut batch = ChangeAccumulator::default();
11633                    self.record_unit_windows(&mut batch, &unit)?;
11634                    batch.status = true;
11635                    self.stored(save_unit(
11636                        &self.conn,
11637                        &UnitRecord {
11638                            status: UnitStatus::Failed,
11639                            reason_code: Some("sync.scope_revoked".to_owned()),
11640                            restriction: None,
11641                            ..unit.clone()
11642                        },
11643                    ))?;
11644                    self.finish_observation("syncular_section_failure", batch)
11645                })();
11646                if let Err(message) = failed {
11647                    self.rollback_observation("syncular_section_failure");
11648                    return Err(storage(message));
11649                }
11650                report.failed.push(unit.id);
11651                return Ok(false);
11652            }
11653            Err(error) => return Err(error),
11654        }
11655        let Some((next_cursor, bootstrap_state)) = sub_end else {
11656            return Ok(false);
11657        };
11658        let completes = start.bootstrap && bootstrap_state.is_none();
11659        let rollback = self.capture();
11660        let counts = (
11661            report.resets.len(),
11662            report.revoked.len(),
11663            report.failed.len(),
11664        );
11665        self.begin_observation("syncular_sub_end")
11666            .map_err(storage)?;
11667        let finished = self
11668            .finish_section(start, echo, next_cursor, bootstrap_state, seeded, report)
11669            .and_then(|batch| {
11670                self.rebuild_overlay_if_dirty()?;
11671                self.finish_observation("syncular_sub_end", batch)
11672            });
11673        if let Err(message) = finished {
11674            self.rollback_observation("syncular_sub_end");
11675            self.restore(rollback);
11676            report.resets.truncate(counts.0);
11677            report.revoked.truncate(counts.1);
11678            report.failed.truncate(counts.2);
11679            return Err(storage(message));
11680        }
11681        Ok(completes)
11682    }
11683
11684    /// §5.6: the table, first-page flag and effective scopes of one segment
11685    /// of `unit`'s section. A first page outside the unit's restriction ends it.
11686    #[allow(clippy::type_complexity)]
11687    fn segment_pair(
11688        &self,
11689        unit: &UnitRecord,
11690        echo: &[EchoRecord],
11691        seeded: &BTreeSet<String>,
11692        name: &str,
11693    ) -> Result<(TableSchema, bool, Vec<(String, Vec<String>)>), SectionError> {
11694        let table = self.schema.table(name).cloned().ok_or_else(|| {
11695            SectionError::Abort(
11696                "sync.schema_mismatch".to_owned(),
11697                format!("segment table {name:?} is not in the client schema"),
11698            )
11699        })?;
11700        let effective = covers(&table, &unit.scopes)
11701            .then(|| pair_scopes(&unit.scopes, name, Some(echo)))
11702            .flatten()
11703            .ok_or_else(|| {
11704                SectionError::Abort(
11705                    "sync.invalid_request".to_owned(),
11706                    "a segment names no active pair of its unit".to_owned(),
11707                )
11708            })?;
11709        let first_page = !seeded.contains(name);
11710        // §5.6: a first page of a table outside the restriction is a whole
11711        // bootstrap from a server that predates RESTRICT; the restriction ends
11712        // before the clear runs.
11713        if first_page
11714            && unit
11715                .restriction
11716                .as_ref()
11717                .is_some_and(|restriction| !restriction.tables.iter().any(|t| t == name))
11718        {
11719            self.conn
11720                .execute(
11721                    "UPDATE _syncular_units SET restriction=NULL WHERE id=?1",
11722                    [&unit.id],
11723                )
11724                .map_err(|error| {
11725                    SectionError::Abort(
11726                        "storage.failed".to_owned(),
11727                        Self::sqlite_failure(&self.storage_failure, error),
11728                    )
11729                })?;
11730        }
11731        Ok((table, first_page, effective))
11732    }
11733
11734    /// §4.4 `SUB_END` of an active, revoked or reset section, inside the
11735    /// caller's observation: a reset discards cursor, resume token and
11736    /// first-page record and keeps the echo; a revoked pair purges by its last
11737    /// echo (§3.3); otherwise the echo replaces the persisted one, a revoked
11738    /// fenced record that turns active again re-bootstraps the unit, and a
11739    /// bootstrap section persists its pin, resume token and seeded tables.
11740    fn finish_section(
11741        &mut self,
11742        start: &SectionStart,
11743        echo: Vec<EchoRecord>,
11744        next_cursor: i64,
11745        bootstrap_state: Option<String>,
11746        seeded: BTreeSet<String>,
11747        report: &mut SyncReport,
11748    ) -> Result<ChangeAccumulator, String> {
11749        #[cfg(feature = "bench-internals")]
11750        let _phase = self.benchmark_phases.start(Phase::CursorPersist);
11751        let mut batch = ChangeAccumulator::default();
11752        // §4.4: SUB_END writes only into a unit that is still registered.
11753        let Some(unit) = self
11754            .stored(get_unit(&self.conn, &start.id))?
11755            .filter(|unit| unit.status == UnitStatus::Active)
11756        else {
11757            return Ok(batch);
11758        };
11759        self.record_unit_windows(&mut batch, &unit)?;
11760        if start.status == SubStatus::Reset {
11761            // §4.6: staleness, never a purge; the rows stay until the
11762            // bootstrap replaces them.
11763            report.resets.push(unit.id.clone());
11764            self.stored(save_unit(
11765                &self.conn,
11766                &UnitRecord {
11767                    reason_code: Some(start.reason_code.clone()),
11768                    cursor: Some(-1),
11769                    bootstrap_state: None,
11770                    seeded: Vec::new(),
11771                    restriction: None,
11772                    ..unit
11773                },
11774            ))?;
11775            return Ok(batch);
11776        }
11777        let revoked = start.status == SubStatus::Revoked;
11778        let mut units = None;
11779        let mut failed = false;
11780        let mut rearmed = false;
11781        for table in self.schema.tables.clone() {
11782            if !covers(&table, &unit.scopes) {
11783                continue;
11784            }
11785            let last = unit
11786                .echo
11787                .as_deref()
11788                .and_then(|last| pair_scopes(&unit.scopes, &table.name, Some(last)));
11789            let next = (!revoked)
11790                .then(|| pair_scopes(&unit.scopes, &table.name, Some(&echo)))
11791                .flatten();
11792            // §3.3: a revoked fenced record that turns active again re-bootstraps.
11793            rearmed |= unit.echo.is_some() && last.is_none() && next.is_some();
11794            // §3.3: purge a pair the response revokes, keyed on the echo the
11795            // client persisted while the pair was active.
11796            if let (Some(last), None) = (&last, &next) {
11797                let units = match units {
11798                    Some(ref units) => units,
11799                    None => units.insert(self.stored(load_units(&self.conn))?),
11800                };
11801                let owners = unit_owners(units, &table, &unit.id);
11802                failed |= !self.purge_pair(&mut batch, &table, last, &owners)?;
11803            }
11804        }
11805        if revoked || failed {
11806            if revoked {
11807                report.revoked.push(unit.id.clone());
11808            }
11809            if failed {
11810                report.failed.push(unit.id.clone());
11811            }
11812            batch.status = true;
11813            self.stored(save_unit(
11814                &self.conn,
11815                &UnitRecord {
11816                    status: if failed {
11817                        UnitStatus::Failed
11818                    } else {
11819                        UnitStatus::Revoked
11820                    },
11821                    reason_code: Some(if failed {
11822                        "sync.scope_revoked".to_owned()
11823                    } else {
11824                        start.reason_code.clone()
11825                    }),
11826                    cursor: Some(-1),
11827                    bootstrap_state: None,
11828                    seeded: Vec::new(),
11829                    echo: None,
11830                    restriction: None,
11831                    ..unit
11832                },
11833            ))?;
11834            return Ok(batch);
11835        }
11836        // §3.3: the server accepted the unit, so a later refusal re-arms once.
11837        self.window_armed.remove(&unit.id);
11838        let completed = start.bootstrap && !rearmed && bootstrap_state.is_none();
11839        let (cursor, bootstrap_state, seeded) = if rearmed {
11840            (Some(-1), None, Vec::new())
11841        } else if start.bootstrap {
11842            let seeded = if bootstrap_state.is_none() {
11843                Vec::new()
11844            } else {
11845                seeded.into_iter().collect()
11846            };
11847            (Some(next_cursor), bootstrap_state, seeded)
11848        } else {
11849            (
11850                unit.cursor,
11851                unit.bootstrap_state.clone(),
11852                unit.seeded.clone(),
11853            )
11854        };
11855        self.stored(save_unit(
11856            &self.conn,
11857            &UnitRecord {
11858                reason_code: None,
11859                echo: Some(echo.clone()),
11860                cursor,
11861                bootstrap_state,
11862                seeded,
11863                // §7.4.3: the restriction ends when the unit re-bootstraps or
11864                // completes its bootstrap.
11865                restriction: unit.restriction.clone().filter(|_| !rearmed && !completed),
11866                ..unit.clone()
11867            },
11868        ))?;
11869        if !completed {
11870            return Ok(batch);
11871        }
11872        // §7.1: a completed bootstrap covers acknowledged intent of its pairs
11873        // at or below its pin. The intent or the bootstrapped row proves the
11874        // pair: a patch omits its scope columns, and the base row it merged
11875        // over may be gone (a §7.4.4 reset before the ACK).
11876        for table in self.schema.tables.clone() {
11877            let Some(effective) = covers(&table, &unit.scopes)
11878                .then(|| pair_scopes(&unit.scopes, &table.name, Some(&echo)))
11879                .flatten()
11880            else {
11881                continue;
11882            };
11883            let mut statement = self
11884                .conn
11885                .prepare("SELECT id,intent_json FROM _syncular_acked_rows WHERE tbl=?1 AND commit_seq<=?2")
11886                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11887            let rows = statement
11888                .query_map(rusqlite::params![table.name, next_cursor], |row| {
11889                    Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
11890                })
11891                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11892            let mut covered = HashSet::new();
11893            for row in rows {
11894                let (id, intent) =
11895                    row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11896                let values: Map<String, Value> =
11897                    serde_json::from_str(&intent).map_err(|_| "sync.local_corrupt".to_owned())?;
11898                let base = self.stored_row(&table, &id, true)?.map(|(row, _)| {
11899                    table
11900                        .columns
11901                        .iter()
11902                        .zip(&row)
11903                        .map(|(column, value)| (column.name.clone(), column_value_to_json(value)))
11904                        .collect()
11905                });
11906                if [Some(values), base]
11907                    .iter()
11908                    .flatten()
11909                    .any(|values| owns_local_row(&table, &effective, &[], values))
11910                {
11911                    covered.insert(id);
11912                }
11913            }
11914            drop(statement);
11915            for id in covered {
11916                self.conn
11917                    .execute(
11918                        "DELETE FROM _syncular_acked_rows WHERE tbl=?1 AND id=?2 AND commit_seq<=?3",
11919                        rusqlite::params![table.name, id, next_cursor],
11920                    )
11921                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
11922                self.overlay_dirty.table(&table.name);
11923                batch.table(&table.name);
11924            }
11925        }
11926        Ok(batch)
11927    }
11928
11929    /// §3.3: purge one revoked pair inside the caller's observation: delete
11930    /// the rows matching its last effective scopes that no owner holds, drop
11931    /// the retained intent and every pending commit that provably writes into
11932    /// them, and delete now-unauthorized blob bodies. `Ok(false)` when the
11933    /// table has no local scope-column mapping (fail closed: nothing deleted).
11934    fn purge_pair(
11935        &mut self,
11936        batch: &mut ChangeAccumulator,
11937        table: &TableSchema,
11938        last: &[(String, Vec<String>)],
11939        owners: &[Vec<(String, Vec<String>)>],
11940    ) -> Result<bool, String> {
11941        if local_scope_predicate(table, last, owners).is_err() {
11942            return Ok(false);
11943        }
11944        for commit in self.drop_failed_commits(|name, values| {
11945            name == table.name && owns_local_row(table, last, owners, values)
11946        })? {
11947            batch.conflicts = true;
11948            batch.rejections = true;
11949            batch.outcomes = true;
11950            for operation in commit.ops {
11951                batch.table(&operation.table);
11952            }
11953        }
11954        if !self.purge_scope_rows(&table.name, last, owners)? {
11955            return Err("storage.failed: the revoked scope purge failed".to_owned());
11956        }
11957        self.record_scope_map(batch, &table.name, last);
11958        if self.drop_doomed_outbox(table, last, owners)? {
11959            batch.status = true;
11960            batch.rejections = true;
11961            batch.outcomes = true;
11962        }
11963        // §5.9.7 B2: revocation deletes now-unauthorized blob bodies.
11964        self.delete_unreferenced_cached_blobs()?;
11965        Ok(true)
11966    }
11967
11968    /// §4.5 client application: apply one live-section or delta `COMMIT`
11969    /// with only the changes that match the persisted echo of a receiving
11970    /// unit; every applied change then goes through the version guard.
11971    /// Returns whether any change of the frame applied.
11972    fn apply_live_commit(
11973        &mut self,
11974        receivers: &[UnitRecord],
11975        tables: &[String],
11976        changes: Vec<ssp2::model::Change>,
11977        commit_seq: i64,
11978        source: AppliedServerCommitSource,
11979    ) -> Result<bool, TransportError> {
11980        let changes: Vec<ssp2::model::Change> = changes
11981            .into_iter()
11982            .filter(|change| {
11983                // An unknown table fails loud in the apply below.
11984                let Some(table) = tables
11985                    .get(change.table_index as usize)
11986                    .and_then(|name| self.schema.table(name))
11987                else {
11988                    return true;
11989                };
11990                receivers.iter().any(|unit| {
11991                    covers(table, &unit.scopes)
11992                        && pair_scopes(&unit.scopes, &table.name, unit.echo.as_deref()).is_some_and(
11993                            |scopes| {
11994                                scopes.iter().all(|(variable, values)| {
11995                                    change
11996                                        .scopes
11997                                        .iter()
11998                                        .find(|(key, _)| key == variable)
11999                                        .is_some_and(|(_, value)| values.contains(value))
12000                                })
12001                            },
12002                        )
12003                })
12004            })
12005            .collect();
12006        if changes.is_empty() {
12007            return Ok(false);
12008        }
12009        let affected_tables = changes
12010            .iter()
12011            .filter_map(|change| tables.get(change.table_index as usize))
12012            .cloned()
12013            .collect::<BTreeSet<_>>();
12014        let previous_batches = self.change_queue.len();
12015        self.apply_commit_frame(tables, &changes, commit_seq)?;
12016        if self.change_queue.len() > previous_batches {
12017            if let Some(batch) = self.change_queue.back_mut() {
12018                batch
12019                    .applied_commits
12020                    .extend(
12021                        affected_tables
12022                            .into_iter()
12023                            .map(|table| AppliedServerCommit {
12024                                table,
12025                                commit_seq,
12026                                source,
12027                            }),
12028                    );
12029            }
12030        }
12031        Ok(true)
12032    }
12033
12034    // Both pull and realtime frames use the same durable observation boundary.
12035    fn apply_commit_frame(
12036        &mut self,
12037        tables: &[String],
12038        changes: &[ssp2::model::Change],
12039        sequence: i64,
12040    ) -> Result<(), TransportError> {
12041        #[cfg(feature = "bench-internals")]
12042        let _phase = self.benchmark_phases.start(Phase::CommitApply);
12043        let rollback = self.capture();
12044        self.coalesce_unit(changes.len())
12045            .and_then(|()| self.begin_observation("syncular_commit"))
12046            .map_err(|message| TransportError::new("storage.failed", message))?;
12047        let applied = (|| {
12048            let mut batch = ChangeAccumulator::default();
12049            self.record_commit_changes(&mut batch, tables, changes);
12050            // §7.1 chained base: a change names the version an acknowledged own
12051            // commit wrote; pending upserts chained on it move to that version.
12052            for change in changes {
12053                let Some(table) = tables.get(change.table_index as usize) else {
12054                    continue;
12055                };
12056                let acknowledged = self
12057                    .conn
12058                    .prepare_cached("SELECT op_json FROM _syncular_acked_rows WHERE tbl=?1 AND id=?2 AND commit_seq=?3")
12059                    .and_then(|mut statement| {
12060                        statement
12061                            .query_map(rusqlite::params![table, change.row_id, sequence], |row| row.get::<_, String>(0))?
12062                            .collect::<Result<Vec<_>, _>>()
12063                    })
12064                    .map_err(|error| TransportError::new("storage.failed", Self::sqlite_failure(&self.storage_failure, error)))?
12065                    .iter()
12066                    .map(|op| serde_json::from_str::<CommitOperation>(op).map(OutboxOp::from))
12067                    .collect::<Result<Vec<_>, _>>()
12068                    .map_err(|_| TransportError::new("storage.failed", "sync.local_corrupt: invalid acknowledged operation".to_owned()))?;
12069                for index in 0..self.outbox.len() {
12070                    if !self.outbox[index]
12071                        .ops
12072                        .iter()
12073                        .any(|op| acknowledged.iter().any(|earlier| chains_on(earlier, op)))
12074                    {
12075                        continue;
12076                    }
12077                    let commit = Arc::make_mut(&mut self.outbox[index]);
12078                    for op in &mut commit.ops {
12079                        if acknowledged.iter().any(|earlier| chains_on(earlier, op)) {
12080                            op.base_version = Some(change.row_version);
12081                        }
12082                    }
12083                    let ops = serde_json::to_string(
12084                        &commit
12085                            .ops
12086                            .iter()
12087                            .map(CommitOperation::from)
12088                            .collect::<Vec<_>>(),
12089                    )
12090                    .map_err(|_| {
12091                        TransportError::new(
12092                            "storage.failed",
12093                            "sync.local_corrupt: unencodable outbox".to_owned(),
12094                        )
12095                    })?;
12096                    let id = commit.client_commit_id.clone();
12097                    self.conn
12098                        .execute(
12099                            "UPDATE _syncular_outbox SET ops_json=?1 WHERE commit_id=?2",
12100                            rusqlite::params![ops, id],
12101                        )
12102                        .map_err(|error| {
12103                            TransportError::new(
12104                                "storage.failed",
12105                                Self::sqlite_failure(&self.storage_failure, error),
12106                            )
12107                        })?;
12108                }
12109            }
12110            {
12111                let storage_failed = |error| {
12112                    TransportError::new(
12113                        "storage.failed",
12114                        Self::sqlite_failure(&self.storage_failure, error),
12115                    )
12116                };
12117                let pinned: HashSet<(&str, &str)> = self
12118                    .outbox
12119                    .iter()
12120                    .flat_map(|commit| &commit.ops)
12121                    .map(|op| (op.table.as_str(), op.row_id.as_str()))
12122                    .collect();
12123                for change in changes {
12124                    let table = tables.get(change.table_index as usize).ok_or_else(|| {
12125                        TransportError::new(
12126                            "sync.invalid_request",
12127                            "change tableIndex out of range".to_owned(),
12128                        )
12129                    })?;
12130                    if pinned.contains(&(table.as_str(), change.row_id.as_str())) {
12131                        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)")
12132                            .and_then(|mut statement| statement.execute(rusqlite::params![table, change.row_id, sequence]))
12133                            .map_err(storage_failed)?;
12134                    }
12135                    self.conn.prepare_cached("DELETE FROM _syncular_acked_rows WHERE tbl=?1 AND id=?2 AND commit_seq<=?3")
12136                        .and_then(|mut statement| statement.execute(rusqlite::params![table, change.row_id, sequence]))
12137                        .map_err(storage_failed)?;
12138                }
12139            }
12140            self.apply_commit_changes(tables, changes)?;
12141            self.rebuild_overlay_if_dirty()
12142                .map_err(|message| TransportError::new("storage.failed", message))?;
12143            self.finish_observation("syncular_commit", batch)
12144                .map_err(|message| TransportError::new("storage.failed", message))
12145        })();
12146        if applied.is_err() {
12147            self.rollback_observation("syncular_commit");
12148            self.restore(rollback);
12149        }
12150        applied
12151    }
12152
12153    fn apply_commit_changes(
12154        &mut self,
12155        tables: &[String],
12156        changes: &[ssp2::model::Change],
12157    ) -> Result<(), TransportError> {
12158        // A clean overlay can reconcile changed primary keys independently
12159        // when their tables have no secondary unique constraints. Such a
12160        // constraint can change whether another row's write succeeds, so a
12161        // table with one and any local intent takes the table rebuild.
12162        let changed_tables: BTreeSet<&str> = changes
12163            .iter()
12164            .filter_map(|change| tables.get(change.table_index as usize))
12165            .map(String::as_str)
12166            .collect();
12167        let mut mirror_visible = !self.overlay_dirty.get();
12168        for name in &changed_tables {
12169            if mirror_visible
12170                && self
12171                    .schema
12172                    .table(name)
12173                    .is_some_and(|table| table.indexes.iter().any(|index| index.unique))
12174            {
12175                let (pending, protected) = self
12176                    .table_intent(name)
12177                    .map_err(|message| TransportError::new("storage.failed", message))?;
12178                mirror_visible = !pending && !protected;
12179            }
12180        }
12181        for change in changes {
12182            let table_name = tables.get(change.table_index as usize).ok_or_else(|| {
12183                TransportError::new(
12184                    "sync.invalid_request",
12185                    "change tableIndex out of range".to_owned(),
12186                )
12187            })?;
12188            let table = self.schema.table(table_name).ok_or_else(|| {
12189                TransportError::new(
12190                    "sync.schema_mismatch",
12191                    format!("change targets unknown table {table_name:?}"),
12192                )
12193            })?;
12194            let landed = match change.op {
12195                Op::Upsert => {
12196                    let payload = change.row.as_ref().ok_or_else(|| {
12197                        TransportError::new(
12198                            "sync.invalid_request",
12199                            "upsert change without row payload".to_owned(),
12200                        )
12201                    })?;
12202                    // §5.11: decrypt encrypted columns on apply, or seal the row.
12203                    let (row, sealed) = {
12204                        #[cfg(feature = "bench-internals")]
12205                        let _phase = self.benchmark_phases.start(Phase::RowDecode);
12206                        // §5.11: a decrypt failure keeps its own identity.
12207                        decode_row_bytes(table, payload, &self.encryption)?
12208                    };
12209                    let table_name = table.name.clone();
12210                    // §4.5 version guard: only a newer upsert lands.
12211                    let landed = self
12212                        .write_base_row(&table_name, &row, change.row_version, sealed.as_ref())
12213                        .map_err(|m| TransportError::new("sync.invalid_request", m))?;
12214                    if mirror_visible && landed {
12215                        self.write_row(
12216                            &visible_table(&table_name),
12217                            &table_name,
12218                            &row,
12219                            change.row_version,
12220                            sealed.as_ref(),
12221                        )
12222                        .map_err(|m| TransportError::new("sync.invalid_request", m))?;
12223                    }
12224                    landed
12225                }
12226                // §4.5 version guard: a delete at or below the local version
12227                // is skipped, a delete of an absent row is a no-op.
12228                Op::Delete => self
12229                    .delete_base_row(table_name, &change.row_id, change.row_version)
12230                    .map_err(|m| TransportError::new("sync.invalid_request", m))?,
12231            };
12232            // The change dropped the row's acknowledged intent either way
12233            // (§7.1), so the overlay of a skipped change rebuilds from the
12234            // unchanged base.
12235            self.overlay_dirty.table(table_name);
12236            if mirror_visible && !(landed && change.op == Op::Upsert) {
12237                let predicate = row_id_predicate(table);
12238                let visible = visible_table(table_name);
12239                let mut statements = vec![format!("DELETE FROM {visible} WHERE {predicate}")];
12240                if !landed {
12241                    statements.push(format!(
12242                        "INSERT INTO {visible} SELECT * FROM {} WHERE {predicate}",
12243                        base_table(table_name)
12244                    ));
12245                }
12246                for statement in &statements {
12247                    self.conn
12248                        .prepare_cached(statement)
12249                        .and_then(|mut statement| {
12250                            statement.execute(rusqlite::params![change.row_id])
12251                        })
12252                        .map_err(|error| {
12253                            TransportError::new("sync.invalid_request", error.to_string())
12254                        })?;
12255                }
12256            }
12257        }
12258        if mirror_visible {
12259            let changed_rows: HashSet<(&str, &str)> = changes
12260                .iter()
12261                .map(|change| {
12262                    (
12263                        tables[change.table_index as usize].as_str(),
12264                        change.row_id.as_str(),
12265                    )
12266                })
12267                .collect();
12268            self.replay_overlay(&changed_tables, Some(&changed_rows))
12269                .map_err(|message| TransportError::new("storage.failed", message))?;
12270            self.overlay_dirty.set(false);
12271        }
12272        Ok(())
12273    }
12274
12275    /// §5.6 segment application: validate against the generated schema,
12276    /// clear the pair's scope on the table's first page (fail closed
12277    /// without a mapping), then upsert each row with its segment-carried
12278    /// server version under the §4.5 version guard (§5.2).
12279    fn apply_segment(
12280        &mut self,
12281        table: &TableSchema,
12282        segment: &RowsSegment,
12283        first_page: bool,
12284        effective: &[(String, Vec<String>)],
12285        unit_id: &str,
12286    ) -> Result<u32, SectionError> {
12287        // §5.2: the column table validates against the generated schema —
12288        // order, names, types, nullability; mismatch is fatal. §5.11: the
12289        // server sends the WIRE types (bytes for an encrypted column), so
12290        // validate against wire_columns.
12291        let column = if segment.columns.len() != table.wire_columns.len() {
12292            Some(Value::from("count"))
12293        } else {
12294            segment
12295                .columns
12296                .iter()
12297                .zip(table.wire_columns.iter())
12298                .position(|(a, b)| a.name != b.name || a.ty != b.ty || a.nullable != b.nullable)
12299                .map(Value::from)
12300        };
12301        if segment.table != table.name
12302            || segment.schema_version != self.schema.version
12303            || column.is_some()
12304        {
12305            let mut details = Map::new();
12306            details.insert("table".to_owned(), Value::from(table.name.as_str()));
12307            if let Some(column) = column {
12308                details.insert("column".to_owned(), column);
12309            }
12310            return Err(SectionError::Transport(TransportError {
12311                code: "sync.schema_mismatch".to_owned(),
12312                message: "rows segment columns do not match the generated schema (§5.2)".to_owned(),
12313                details: Some(Value::Object(details)),
12314            }));
12315        }
12316        let mut applied = 0u32;
12317        let (mut write, mut commit) = (std::time::Duration::ZERO, std::time::Duration::ZERO);
12318        let empty = Vec::new();
12319        let blocks = if segment.blocks.is_empty() {
12320            std::slice::from_ref(&empty)
12321        } else {
12322            &segment.blocks
12323        };
12324        for (index, block) in blocks.iter().enumerate() {
12325            let clear = first_page && index == 0;
12326            if !clear && block.is_empty() {
12327                continue;
12328            }
12329            let rollback = self.capture();
12330            let (pending, protected) = self
12331                .table_intent(&table.name)
12332                .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12333            let reconcile_pending =
12334                !protected && pending && table.indexes.iter().any(|index| index.unique);
12335            let mirror_visible = !protected && !reconcile_pending;
12336            self.coalesce_unit(block.len())
12337                .and_then(|()| self.begin_observation("syncular_segment_block"))
12338                .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12339            let started = std::time::Instant::now();
12340            let outcome = (|| {
12341                self.rebuild_overlay_if_dirty()
12342                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12343                let mut changed_keys = Vec::new();
12344                let mut batch = ChangeAccumulator::default();
12345                if clear && self.clear_scope(table, effective, unit_id)? || !block.is_empty() {
12346                    batch.table(&table.name);
12347                }
12348                for (row_index, row) in block.iter().enumerate() {
12349                    let decrypted;
12350                    let mut sealed = None;
12351                    let values = if table.has_encrypted_columns() {
12352                        let mut values = row.values.clone();
12353                        sealed = crate::values::decrypt_segment_row(
12354                            table,
12355                            &mut values,
12356                            &self.encryption,
12357                        )
12358                        .map_err(SectionError::Transport)?;
12359                        decrypted = values;
12360                        &decrypted
12361                    } else {
12362                        &row.values
12363                    };
12364                    if !self
12365                        .write_base_row(&table.name, values, row.server_version, sealed.as_ref())
12366                        .map_err(|message| {
12367                            SectionError::Abort("sync.invalid_request".into(), message)
12368                        })?
12369                    {
12370                        continue;
12371                    }
12372                    if reconcile_pending {
12373                        changed_keys.push(
12374                            owned_sql_value(RowParam::Cell(&values[table.pk_index])).map_err(
12375                                |message| SectionError::Abort("storage.failed".into(), message),
12376                            )?,
12377                        );
12378                    }
12379                    if mirror_visible {
12380                        self.write_row(
12381                            &visible_table(&table.name),
12382                            &table.name,
12383                            values,
12384                            row.server_version,
12385                            sealed.as_ref(),
12386                        )
12387                        .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12388                    }
12389                    let processed = u64::from(applied) + row_index as u64 + 1;
12390                    if processed.is_multiple_of(1024) {
12391                        self.progress.update(|p| p.rows_processed = processed);
12392                    }
12393                }
12394                self.reconcile_import(table, &mut changed_keys, protected, reconcile_pending)
12395                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12396                let written = std::time::Instant::now();
12397                self.finish_observation("syncular_segment_block", batch)
12398                    .map(|()| written)
12399                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))
12400            })();
12401            let written = match outcome {
12402                Ok(written) => written,
12403                Err(error) => {
12404                    self.rollback_observation("syncular_segment_block");
12405                    self.restore(rollback);
12406                    return Err(error);
12407                }
12408            };
12409            // §7.7: a payload reports its import cost.
12410            write += written - started;
12411            commit += written.elapsed();
12412            applied += block.len() as u32;
12413            self.progress.update(|p| {
12414                p.rows_processed = u64::from(applied);
12415                p.import_write_ms = u64::try_from(write.as_millis()).ok();
12416                p.import_commit_ms = u64::try_from(commit.as_millis()).ok();
12417            });
12418            std::thread::yield_now();
12419        }
12420        self.progress
12421            .update(|p| p.rows_processed = u64::from(applied));
12422        Ok(applied)
12423    }
12424
12425    /// §5.3 sqlite-image application: validate the in-file metadata
12426    /// against the descriptor, validate column names/order against the
12427    /// generated schema, run the §5.6 first-page clear when fresh, then
12428    /// replace-or-upsert every image row with its `_syncular_version`.
12429    /// Mechanics: the image lands in a temp file read through a second
12430    /// rusqlite connection, equivalent to ATTACH + INSERT…SELECT.
12431    /// Each image chunk commits its writes and revision before readers continue.
12432    #[allow(clippy::too_many_arguments)]
12433    fn apply_sqlite_segment(
12434        &mut self,
12435        table: &TableSchema,
12436        bytes: &[u8],
12437        first_page: bool,
12438        effective: &[(String, Vec<String>)],
12439        unit_id: &str,
12440        segment_id: &str,
12441        resumed: i64,
12442        row_count: i64,
12443        as_of_commit_seq: i64,
12444        scope_digest: &str,
12445    ) -> Result<u32, SectionError> {
12446        let invalid = |detail: &str| {
12447            SectionError::Abort(
12448                "sync.invalid_request".to_owned(),
12449                format!("sqlite segment rejected: {detail} (§5.3)"),
12450            )
12451        };
12452        // §5.11: an image bypasses the decrypt seam, so a server cannot serve
12453        // one for a table with encrypted columns.
12454        if table.has_encrypted_columns() {
12455            return Err(invalid("table has encrypted columns"));
12456        }
12457
12458        // The image lands beside the replica so it shares the replica's
12459        // directory permissions and volume; an in-memory replica has no
12460        // directory and uses the system temp dir. The file is owner-only.
12461        let directory = self
12462            .previous_version_replica_path()
12463            .and_then(|replica| std::path::Path::new(&replica).parent().map(Into::into))
12464            .unwrap_or_else(std::env::temp_dir);
12465        let path = directory.join(format!(".syncular-image-{}.tmp", uuid::Uuid::new_v4()));
12466        let outcome = (|| {
12467            let mut options = std::fs::OpenOptions::new();
12468            options.write(true).create_new(true);
12469            #[cfg(unix)]
12470            std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
12471            std::io::Write::write_all(
12472                &mut options
12473                    .open(&path)
12474                    .map_err(|_| invalid("image temp file write failed"))?,
12475                bytes,
12476            )
12477            .map_err(|_| invalid("image temp file write failed"))?;
12478            let img = rusqlite::Connection::open_with_flags(
12479                &path,
12480                rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
12481            )
12482            .map_err(|_| invalid("bytes do not open as a SQLite database"))?;
12483            self.apply_sqlite_image(
12484                &img,
12485                table,
12486                first_page,
12487                effective,
12488                unit_id,
12489                segment_id,
12490                resumed,
12491                row_count,
12492                as_of_commit_seq,
12493                scope_digest,
12494            )
12495        })();
12496        let _ = std::fs::remove_file(&path);
12497        outcome
12498    }
12499
12500    #[allow(clippy::too_many_arguments)]
12501    fn apply_sqlite_image(
12502        &mut self,
12503        img: &rusqlite::Connection,
12504        table: &crate::schema::TableSchema,
12505        first_fresh_page: bool,
12506        effective: &[(String, Vec<String>)],
12507        unit_id: &str,
12508        segment_id: &str,
12509        resumed: i64,
12510        row_count: i64,
12511        as_of_commit_seq: i64,
12512        scope_digest: &str,
12513    ) -> Result<u32, SectionError> {
12514        let invalid = |detail: String| {
12515            SectionError::Abort(
12516                "sync.invalid_request".to_owned(),
12517                format!("sqlite segment rejected: {detail} (§5.3)"),
12518            )
12519        };
12520
12521        // 1. Metadata vs descriptor + client state (§5.3 rule 2; exactly
12522        //    one row).
12523        type MetaRow = (i64, String, i64, i64, String, i64, i64);
12524        let meta: MetaRow = img
12525            .query_row(
12526                "SELECT format, \"table\", \"schemaVersion\", \"asOfCommitSeq\",
12527                        \"scopeDigest\", \"rowCount\",
12528                        (SELECT count(*) FROM _syncular_segment)
12529                 FROM _syncular_segment",
12530                [],
12531                |row| {
12532                    Ok((
12533                        row.get(0)?,
12534                        row.get(1)?,
12535                        row.get(2)?,
12536                        row.get(3)?,
12537                        row.get(4)?,
12538                        row.get(5)?,
12539                        row.get(6)?,
12540                    ))
12541                },
12542            )
12543            .map_err(|_| invalid("missing or unreadable _syncular_segment metadata".to_owned()))?;
12544        let (format, meta_table, schema_version, pin, digest, meta_rows, meta_count) = meta;
12545        if meta_count != 1 {
12546            return Err(invalid(format!(
12547                "_syncular_segment must contain exactly one row, found {meta_count}"
12548            )));
12549        }
12550        if format != 1 {
12551            return Err(invalid(format!("format {format}")));
12552        }
12553        if meta_table != table.name {
12554            return Err(invalid(format!("image table {meta_table:?}")));
12555        }
12556        if schema_version != i64::from(self.schema.version) {
12557            return Err(invalid(format!("schemaVersion {schema_version}")));
12558        }
12559        if pin != as_of_commit_seq {
12560            return Err(invalid(format!("asOfCommitSeq {pin}")));
12561        }
12562        if digest != scope_digest {
12563            return Err(invalid("scopeDigest mismatch".to_owned()));
12564        }
12565        if meta_rows != row_count {
12566            return Err(invalid(format!("rowCount {meta_rows}")));
12567        }
12568
12569        // 2. Column names and order vs the generated schema (§5.3 rule 3).
12570        let mut names: Vec<String> = Vec::new();
12571        let mut primary_keys: Vec<String> = Vec::new();
12572        {
12573            let mut stmt = img
12574                .prepare(&format!("PRAGMA table_info({})", quote_ident(&table.name)))
12575                .map_err(|_| invalid("image data table missing".to_owned()))?;
12576            let mut rows = stmt
12577                .query([])
12578                .map_err(|_| invalid("image data table unreadable".to_owned()))?;
12579            while let Some(row) = rows
12580                .next()
12581                .map_err(|_| invalid("image data table unreadable".to_owned()))?
12582            {
12583                if row
12584                    .get::<_, i64>(5)
12585                    .map_err(|error| invalid(Self::sqlite_failure(&self.storage_failure, error)))?
12586                    > 0
12587                {
12588                    primary_keys.push(row.get(1).map_err(|error| {
12589                        invalid(Self::sqlite_failure(&self.storage_failure, error))
12590                    })?);
12591                }
12592                names.push(
12593                    row.get::<_, String>(1)
12594                        .map_err(|_| invalid("image data table unreadable".to_owned()))?,
12595                );
12596            }
12597        }
12598        let mut expected: Vec<&str> = table.columns.iter().map(|c| c.name.as_str()).collect();
12599        expected.push("_syncular_version");
12600        if names.len() != expected.len() || names.iter().zip(expected.iter()).any(|(a, b)| a != b) {
12601            return Err(SectionError::Transport(TransportError {
12602                code: "sync.schema_mismatch".to_owned(),
12603                message: "sqlite segment columns do not match the generated schema (§5.3)"
12604                    .to_owned(),
12605                details: Some(serde_json::json!({ "table": table.name })),
12606            }));
12607        }
12608
12609        if primary_keys != vec![table.primary_key.clone()] {
12610            return Err(invalid(
12611                "image primary key does not match generated schema".into(),
12612            ));
12613        }
12614        let actual_count: i64 = img
12615            .query_row(
12616                &format!("SELECT count(*) FROM {}", quote_ident(&table.name)),
12617                [],
12618                |row| row.get(0),
12619            )
12620            .map_err(|error| invalid(Self::sqlite_failure(&self.storage_failure, error)))?;
12621        if actual_count != row_count {
12622            return Err(invalid("image row count does not match descriptor".into()));
12623        }
12624        let insert = self.insert_row_sql(&base_table(&table.name), table);
12625        let visible_insert = self.insert_row_sql(&visible_table(&table.name), table);
12626        let column_list = names
12627            .iter()
12628            .map(|n| quote_ident(n))
12629            .collect::<Vec<_>>()
12630            .join(", ");
12631        // §5.6: an earlier attempt at this position committed the first
12632        // `resumed` rows in primary-key order; the content address pins them.
12633        let mut stmt = img
12634            .prepare(&format!(
12635                "SELECT {column_list} FROM {} ORDER BY {} LIMIT -1 OFFSET ?1",
12636                quote_ident(&table.name),
12637                quote_ident(&table.primary_key)
12638            ))
12639            .map_err(|error| invalid(Self::sqlite_failure(&self.storage_failure, error)))?;
12640        let mut rows = stmt
12641            .query([resumed])
12642            .map_err(|error| invalid(Self::sqlite_failure(&self.storage_failure, error)))?;
12643        let resumed = u32::try_from(resumed)
12644            .ok()
12645            .filter(|rows| i64::from(*rows) <= actual_count)
12646            .ok_or_else(|| invalid("applied-segment record exceeds the image".into()))?;
12647        let mut applied = resumed;
12648        let mut limit = if first_fresh_page {
12649            1024
12650        } else {
12651            self.image_chunk_rows
12652                .get(&table.name)
12653                .copied()
12654                .unwrap_or(1024)
12655        };
12656        let (mut write, mut commit) = (std::time::Duration::ZERO, std::time::Duration::ZERO);
12657        // Rows, write ms and per-row write ms of the chunk before.
12658        let mut model: Option<(u32, f64, Option<f64>)> = None;
12659        loop {
12660            let clear = applied == 0 && first_fresh_page;
12661            let rollback = self.capture();
12662            let (pending, protected) = self
12663                .table_intent(&table.name)
12664                .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12665            let reconcile_pending =
12666                !protected && pending && table.indexes.iter().any(|index| index.unique);
12667            let mirror_visible = !protected && !reconcile_pending;
12668            // §5.3: a table's first chunk holds 1,024 rows; a later range image
12669            // starts at the size its previous range reached. A later chunk holds at
12670            // least 1,024 rows, at most twice the rows of the one before and at
12671            // most 65,536. The second chunk of an image holds twice the rows of
12672            // the first. The two latest chunks whose row counts differ by at
12673            // least half the smaller split write time into a per-row and a
12674            // fixed part; while sizes repeat, the last split's per-row time
12675            // holds. A later chunk then holds the rows whose per-row time fills
12676            // the larger of 250 ms, the time from the end of the writes of the
12677            // chunk before through its COMMIT, and the fixed part. A chunk that
12678            // replays local writes holds at most 1,024.
12679            let chunk = if pending || protected {
12680                limit.min(1024)
12681            } else {
12682                limit
12683            };
12684            self.coalesce_unit(chunk as usize)
12685                .and_then(|()| self.begin_observation("syncular_image_chunk"))
12686                .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12687            let started = std::time::Instant::now();
12688            let result = (|| {
12689                self.rebuild_overlay_if_dirty()
12690                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12691                let mut changed_keys = Vec::new();
12692                let mut batch = ChangeAccumulator::default();
12693                if clear && self.clear_scope(table, effective, unit_id)? {
12694                    batch.table(&table.name);
12695                }
12696                let mut processed = 0u32;
12697                {
12698                    let mut ins = self.conn.prepare_cached(&insert).map_err(|error| {
12699                        invalid(Self::sqlite_failure(&self.storage_failure, error))
12700                    })?;
12701                    let mut mirror = if mirror_visible {
12702                        Some(self.conn.prepare_cached(&visible_insert).map_err(|error| {
12703                            invalid(Self::sqlite_failure(&self.storage_failure, error))
12704                        })?)
12705                    } else {
12706                        None
12707                    };
12708                    for _ in 0..chunk {
12709                        let Some(row) = rows.next().map_err(|error| {
12710                            invalid(Self::sqlite_failure(&self.storage_failure, error))
12711                        })?
12712                        else {
12713                            break;
12714                        };
12715                        for (i, column) in table.columns.iter().enumerate() {
12716                            let cell = row.get_ref(i).map_err(|error| {
12717                                invalid(Self::sqlite_failure(&self.storage_failure, error))
12718                            })?;
12719                            let param = image_cell_param(column, cell).map_err(invalid)?;
12720                            ins.raw_bind_parameter(i + 1, &param).map_err(|error| {
12721                                invalid(Self::sqlite_failure(&self.storage_failure, error))
12722                            })?;
12723                            if let Some(mirror) = &mut mirror {
12724                                mirror.raw_bind_parameter(i + 1, &param).map_err(|error| {
12725                                    invalid(Self::sqlite_failure(&self.storage_failure, error))
12726                                })?;
12727                            }
12728                        }
12729                        let version_index = table.columns.len();
12730                        let version: i64 = row.get(version_index).map_err(|error| {
12731                            invalid(Self::sqlite_failure(&self.storage_failure, error))
12732                        })?;
12733                        if version < 1 {
12734                            return Err(invalid("image row version must be positive".into()));
12735                        }
12736                        ins.raw_bind_parameter(version_index + 1, version)
12737                            .map_err(|error| {
12738                                invalid(Self::sqlite_failure(&self.storage_failure, error))
12739                            })?;
12740                        // §4.5 version guard: the base upsert decides.
12741                        let landed = ins.raw_execute().map_err(|error| {
12742                            invalid(Self::sqlite_failure(&self.storage_failure, error))
12743                        })? > 0;
12744                        processed += 1;
12745                        if processed.is_multiple_of(1024) && processed < chunk {
12746                            self.progress
12747                                .update(|p| p.rows_processed = u64::from(applied + processed));
12748                        }
12749                        if !landed {
12750                            continue;
12751                        }
12752                        if let Some(mirror) = &mut mirror {
12753                            mirror
12754                                .raw_bind_parameter(version_index + 1, version)
12755                                .map_err(|error| {
12756                                    invalid(Self::sqlite_failure(&self.storage_failure, error))
12757                                })?;
12758                            mirror.raw_execute().map_err(|error| {
12759                                invalid(Self::sqlite_failure(&self.storage_failure, error))
12760                            })?;
12761                        }
12762                        if reconcile_pending {
12763                            changed_keys.push(row.get::<_, SqlValue>(table.pk_index).map_err(
12764                                |error| invalid(Self::sqlite_failure(&self.storage_failure, error)),
12765                            )?);
12766                        }
12767                    }
12768                }
12769                if processed > 0 {
12770                    batch.table(&table.name);
12771                    self.overlay_dirty.table(&table.name);
12772                }
12773                self.stored(record_applied_rows(
12774                    &self.conn,
12775                    unit_id,
12776                    segment_id,
12777                    i64::from(applied + processed),
12778                ))
12779                .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12780                self.reconcile_import(table, &mut changed_keys, protected, reconcile_pending)
12781                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12782                let written = std::time::Instant::now();
12783                self.finish_observation("syncular_image_chunk", batch)
12784                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12785                Ok((processed, written))
12786            })();
12787            let (processed, written) = match result {
12788                Ok(done) => done,
12789                Err(error) => {
12790                    self.rollback_observation("syncular_image_chunk");
12791                    self.restore(rollback);
12792                    return Err(error);
12793                }
12794            };
12795            // The chunk commits before the yield, also inside a coalesced apply.
12796            let coalesced = self.coalesced.is_some();
12797            if coalesced {
12798                self.commit_coalesced_apply()
12799                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12800            }
12801            let spent = (written - started, written.elapsed());
12802            #[cfg(test)]
12803            let spent = self
12804                .image_chunk_ms
12805                .get()
12806                .map_or(spent, |(fixed, row, commit)| {
12807                    (
12808                        std::time::Duration::from_secs_f64(
12809                            (fixed + row * f64::from(processed)) / 1000.0,
12810                        ),
12811                        std::time::Duration::from_secs_f64(commit / 1000.0),
12812                    )
12813                });
12814            write += spent.0;
12815            commit += spent.1;
12816            applied += processed;
12817            let last = processed < chunk || i64::from(applied) == actual_count;
12818            // A file replica's WAL keeps its high-water size until truncated.
12819            if last && self.conn.is_autocommit() {
12820                self.conn
12821                    .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
12822                    .map_err(|error| invalid(Self::sqlite_failure(&self.storage_failure, error)))?;
12823            }
12824            if coalesced {
12825                self.begin_coalesced_apply()
12826                    .map_err(|message| SectionError::Abort("storage.failed".into(), message))?;
12827            }
12828            self.progress.update(|p| {
12829                p.rows_processed = u64::from(applied);
12830                p.import_write_ms = u64::try_from(write.as_millis()).ok();
12831                p.import_commit_ms = u64::try_from(commit.as_millis()).ok();
12832            });
12833            let write_ms = spent.0.as_secs_f64() * 1000.0;
12834            let per_row = match model {
12835                Some((rows, before, _)) if 2 * processed.abs_diff(rows) >= processed.min(rows) => {
12836                    Some((write_ms - before) / (f64::from(processed) - f64::from(rows)))
12837                }
12838                Some((_, _, per_row)) => per_row,
12839                None => None,
12840            };
12841            model = Some((processed, write_ms, per_row));
12842            let fixed = (write_ms - per_row.unwrap_or(0.0) * f64::from(processed)).max(0.0);
12843            let budget = (spent.1.as_secs_f64() * 1000.0).max(250.0).max(fixed);
12844            std::thread::yield_now();
12845            if last {
12846                break;
12847            }
12848            // Without a positive per-row time the chunk doubles.
12849            limit = (processed * 2)
12850                .min(65_536)
12851                .min(match per_row {
12852                    Some(per_row) if per_row > 0.0 => (budget / per_row) as u32,
12853                    _ => u32::MAX,
12854                })
12855                .max(1024);
12856            self.image_chunk_rows.insert(table.name.clone(), limit);
12857        }
12858        if i64::from(applied) != actual_count {
12859            return Err(invalid(format!(
12860                "image yielded {applied} rows, expected {actual_count}"
12861            )));
12862        }
12863        Ok(applied - resumed)
12864    }
12865
12866    /// §7.1 keyed reconciliation of the rows `drained` commits touch: restore
12867    /// them from the base and replay their remaining intent. A table with a
12868    /// secondary unique index restores and replays every row with intent,
12869    /// since one row's value can admit or defer another row's write.
12870    fn reconcile_rows(&self, drained: &[Arc<OutboxCommit>]) -> Result<(), String> {
12871        let names: BTreeSet<&str> = drained
12872            .iter()
12873            .flat_map(|commit| &commit.ops)
12874            .map(|op| op.table.as_str())
12875            .collect();
12876        for name in names {
12877            let Some(table) = self.schema.table(name) else {
12878                continue;
12879            };
12880            let ops = drained.iter().flat_map(|commit| &commit.ops);
12881            let tables = BTreeSet::from([name]);
12882            let rows: HashSet<_> = ops
12883                .clone()
12884                .map(|op| (op.table.as_str(), op.row_id.as_str()))
12885                .collect();
12886            let unique = table.indexes.iter().any(|index| index.unique);
12887            let acknowledged = if unique {
12888                self.acknowledged_operations(None, Some(&tables))?
12889            } else {
12890                Vec::new()
12891            };
12892            let peers = acknowledged
12893                .iter()
12894                .chain(
12895                    self.failed_commits
12896                        .iter()
12897                        .flat_map(|(commit, _)| &commit.ops),
12898                )
12899                .chain(self.outbox.iter().flat_map(|commit| &commit.ops))
12900                .filter(|_| unique);
12901            self.restore_base_rows(table, &mut Vec::new(), peers.chain(ops.clone()))?;
12902            self.replay_overlay(&tables, (!unique).then_some(&rows))?;
12903        }
12904        Ok(())
12905    }
12906
12907    /// Whether `table` has pending outbox intent, and whether it has protected
12908    /// (acknowledged or retained failed) intent.
12909    fn table_intent(&self, table: &str) -> Result<(bool, bool), String> {
12910        let touches = |op: &OutboxOp| op.table == table;
12911        Ok((
12912            self.outbox
12913                .iter()
12914                .flat_map(|commit| &commit.ops)
12915                .any(touches),
12916            self.failed_commits
12917                .iter()
12918                .flat_map(|(commit, _)| &commit.ops)
12919                .any(touches)
12920                || self
12921                    .conn
12922                    .query_row(
12923                        "SELECT EXISTS(SELECT 1 FROM _syncular_acked_rows WHERE tbl=?1)",
12924                        [table],
12925                        |row| row.get(0),
12926                    )
12927                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?,
12928        ))
12929    }
12930
12931    /// §7.1 reconciliation after an import block or chunk. Keyed replay covers
12932    /// only pending intent, so a table with protected intent rebuilds; a
12933    /// `restore` restores the imported `keys` and every pending row first.
12934    fn reconcile_import(
12935        &mut self,
12936        table: &TableSchema,
12937        keys: &mut Vec<SqlValue>,
12938        protected: bool,
12939        restore: bool,
12940    ) -> Result<(), String> {
12941        if protected {
12942            return self.rebuild_overlay_if_dirty();
12943        }
12944        let pending = self.outbox.iter().flat_map(|commit| &commit.ops);
12945        if restore {
12946            self.restore_base_rows(table, keys, pending.clone())?;
12947        }
12948        self.apply_outbox_ops(pending.filter(|op| op.table == table.name))?;
12949        self.overlay_dirty.set(false);
12950        Ok(())
12951    }
12952
12953    /// Restore the visible rows of `keys` and of the rows `ops` touch in
12954    /// `table` from the base before the caller replays their intent. The
12955    /// caller owns the transaction and publishes its revision after replay.
12956    fn restore_base_rows<'a>(
12957        &self,
12958        table: &TableSchema,
12959        keys: &mut Vec<SqlValue>,
12960        ops: impl IntoIterator<Item = &'a OutboxOp>,
12961    ) -> Result<(), String> {
12962        let visible = visible_table(&table.name);
12963        let base = base_table(&table.name);
12964        let pk = quote_ident(&table.primary_key);
12965        let predicate = row_id_predicate(table);
12966        let mut lookup = self.conn.prepare_cached(&format!(
12967            "SELECT {pk} FROM {base} WHERE {predicate} UNION SELECT {pk} FROM {visible} WHERE {predicate}"
12968        )).map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
12969        let mut deleted = HashSet::new();
12970        for op in ops.into_iter().filter(|op| op.table == table.name) {
12971            if op.upsert {
12972                if let Some(values) = &op.values {
12973                    let key = json_to_column_value(
12974                        &table.columns[table.pk_index],
12975                        values.get(&table.primary_key),
12976                    )?;
12977                    keys.push(owned_sql_value(RowParam::Cell(&key))?);
12978                }
12979            } else if deleted.insert(&op.row_id) {
12980                keys.extend(
12981                    lookup
12982                        .query_map([&op.row_id], |row| row.get::<_, SqlValue>(0))
12983                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
12984                        .collect::<Result<Vec<_>, _>>()
12985                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?,
12986                );
12987            }
12988        }
12989        // Delete the complete affected set before restoring any base value, so
12990        // old optimistic unique values cannot collide with the new server rows.
12991        for chunk in keys.chunks(400) {
12992            let holes = vec!["?"; chunk.len()].join(",");
12993            self.conn
12994                .prepare_cached(&format!("DELETE FROM {visible} WHERE {pk} IN ({holes})"))
12995                .and_then(|mut statement| statement.execute(rusqlite::params_from_iter(chunk)))
12996                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
12997        }
12998        let updates = table
12999            .columns
13000            .iter()
13001            .map(|column| column.name.as_str())
13002            .chain(std::iter::once("_syncular_version"))
13003            .chain(table.sealed_columns().iter().copied())
13004            .filter(|name| *name != table.primary_key)
13005            .map(|name| {
13006                let name = quote_ident(name);
13007                format!("{name}=excluded.{name}")
13008            })
13009            .collect::<Vec<_>>()
13010            .join(",");
13011        for chunk in keys.chunks(400) {
13012            let holes = vec!["?"; chunk.len()].join(",");
13013            self.conn.prepare_cached(&format!("INSERT INTO {visible} SELECT * FROM {base} WHERE {pk} IN ({holes}) ON CONFLICT ({pk}) DO UPDATE SET {updates}"))
13014                .and_then(|mut statement| statement.execute(rusqlite::params_from_iter(chunk)))
13015                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13016        }
13017        Ok(())
13018    }
13019
13020    // -- application-authorized local purge ---------------------------------------
13021
13022    fn compile_local_data_purge(
13023        &self,
13024        input: &LocalDataPurgeInput,
13025    ) -> Result<CompiledLocalDataPurge, String> {
13026        let invalid = |message: String| format!("sync.invalid_request: {message}");
13027        if input.purge_id.is_empty()
13028            || input.purge_id.len() > 128
13029            || !is_local_operation_code_like(&input.purge_id)
13030        {
13031            return Err(invalid(
13032                "local purge purgeId must be a 1–128 character code-like identifier".to_owned(),
13033            ));
13034        }
13035        if input.targets.is_empty() || input.targets.len() > MAX_LOCAL_PURGE_TARGETS {
13036            return Err(invalid(format!(
13037                "local purge needs between 1 and {MAX_LOCAL_PURGE_TARGETS} targets"
13038            )));
13039        }
13040
13041        let mut deduplicated: BTreeMap<
13042            String,
13043            (CompiledLocalDataPurgeTarget, LocalDataPurgeTarget),
13044        > = BTreeMap::new();
13045        let mut projections = BTreeSet::new();
13046        for target in &input.targets {
13047            let (table_name, raw_selectors) = match target {
13048                LocalDataPurgeTarget::Table { table, selectors } => (table, selectors),
13049                LocalDataPurgeTarget::Projection { projection } => {
13050                    projections.insert(projection.clone());
13051                    continue;
13052                }
13053            };
13054            let table = self.schema.table(table_name).ok_or_else(|| {
13055                invalid(format!("local purge names unknown table {:?}", table_name))
13056            })?;
13057            if raw_selectors.is_empty() || raw_selectors.len() > MAX_LOCAL_PURGE_SELECTORS {
13058                return Err(invalid(format!(
13059                    "local purge target {:?} needs between 1 and {MAX_LOCAL_PURGE_SELECTORS} selectors",
13060                    table_name
13061                )));
13062            }
13063            let mut selectors = Vec::with_capacity(raw_selectors.len());
13064            let mut canonical_selectors = BTreeMap::new();
13065            for (column_name, raw_values) in raw_selectors {
13066                let Some((column_index, column)) = table
13067                    .columns
13068                    .iter()
13069                    .enumerate()
13070                    .find(|(_, column)| column.name == *column_name)
13071                else {
13072                    return Err(invalid(format!(
13073                        "local purge target {:?} names unknown column {:?}",
13074                        table_name, column_name
13075                    )));
13076                };
13077                let encrypted = table
13078                    .encrypted_columns
13079                    .iter()
13080                    .any(|candidate| candidate.index == column_index);
13081                if column.ty != ColumnType::String || encrypted {
13082                    return Err(invalid(format!(
13083                        "local purge selector {:?}.{:?} must be a plaintext string column",
13084                        table_name, column_name
13085                    )));
13086                }
13087                if raw_values.is_empty() || raw_values.len() > MAX_LOCAL_PURGE_VALUES {
13088                    return Err(invalid(format!(
13089                        "local purge selector {:?}.{:?} needs between 1 and {MAX_LOCAL_PURGE_VALUES} values",
13090                        table_name, column_name
13091                    )));
13092                }
13093                let mut values = raw_values.clone();
13094                values.sort();
13095                values.dedup();
13096                if values.iter().any(|value| {
13097                    value.is_empty()
13098                        || value.len() > MAX_LOCAL_PURGE_VALUE_LENGTH
13099                        || !is_local_operation_code_like(value)
13100                }) {
13101                    return Err(invalid(format!(
13102                        "local purge selector values must be 1–{MAX_LOCAL_PURGE_VALUE_LENGTH} character code-like identifiers"
13103                    )));
13104                }
13105                selectors.push((column_name.clone(), values.clone()));
13106                canonical_selectors.insert(column_name.clone(), values);
13107            }
13108            let canonical = LocalDataPurgeTarget::Table {
13109                table: table_name.clone(),
13110                selectors: canonical_selectors,
13111            };
13112            let key = serde_json::to_string(&canonical).map_err(|error| error.to_string())?;
13113            deduplicated.insert(
13114                key,
13115                (
13116                    CompiledLocalDataPurgeTarget {
13117                        table: table_name.clone(),
13118                        selectors,
13119                    },
13120                    canonical,
13121                ),
13122            );
13123        }
13124        let (targets, mut canonical): (Vec<_>, Vec<_>) = deduplicated.into_values().unzip();
13125        canonical.extend(
13126            projections
13127                .iter()
13128                .map(|name| LocalDataPurgeTarget::Projection {
13129                    projection: name.clone(),
13130                }),
13131        );
13132        let canonical_plan =
13133            serde_json::to_string(&canonical).map_err(|error| error.to_string())?;
13134        Ok(CompiledLocalDataPurge {
13135            targets,
13136            projections,
13137            canonical_plan,
13138        })
13139    }
13140
13141    fn local_purge_base_row_ids(
13142        &self,
13143        targets: &[CompiledLocalDataPurgeTarget],
13144    ) -> Result<BTreeMap<String, BTreeSet<String>>, String> {
13145        let mut by_table: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
13146        for target in targets {
13147            let table = self
13148                .schema
13149                .table(&target.table)
13150                .ok_or_else(|| format!("sync.invalid_request: unknown table {:?}", target.table))?;
13151            let mut clauses = Vec::with_capacity(target.selectors.len());
13152            let mut params = Vec::new();
13153            for (column, values) in &target.selectors {
13154                clauses.push(format!(
13155                    "{} IN ({})",
13156                    quote_ident(column),
13157                    values.iter().map(|_| "?").collect::<Vec<_>>().join(", ")
13158                ));
13159                params.extend(values.iter().cloned().map(SqlValue::Text));
13160            }
13161            let sql = format!(
13162                "SELECT CAST({} AS TEXT) FROM {} WHERE {}",
13163                quote_ident(&table.primary_key),
13164                base_table(&target.table),
13165                clauses.join(" AND ")
13166            );
13167            let mut statement = self
13168                .conn
13169                .prepare(&sql)
13170                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13171            let rows = statement
13172                .query_map(rusqlite::params_from_iter(params), |row| {
13173                    let value = sql_ref_to_json(&table.columns[table.pk_index], row.get_ref(0)?);
13174                    render_row_id_json(Some(&value))
13175                        .map_err(|message| rusqlite::Error::ToSqlConversionFailure(message.into()))
13176                })
13177                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13178            let ids = by_table.entry(target.table.clone()).or_default();
13179            for row in rows {
13180                ids.insert(
13181                    row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?,
13182                );
13183            }
13184        }
13185        Ok(by_table)
13186    }
13187
13188    fn local_purge_values_match(
13189        target: &CompiledLocalDataPurgeTarget,
13190        values: &Map<String, Value>,
13191    ) -> bool {
13192        target.selectors.iter().all(|(column, allowed)| {
13193            values
13194                .get(column)
13195                .and_then(Value::as_str)
13196                .is_some_and(|value| allowed.iter().any(|candidate| candidate == value))
13197        })
13198    }
13199
13200    /// Apply one host-authorized local security purge. The host MUST gate the
13201    /// corresponding subscriptions first; this primitive owns local SQLite
13202    /// cleanup and never grants/revokes server authority by itself.
13203    pub fn purge_local_data(
13204        &mut self,
13205        input: &LocalDataPurgeInput,
13206    ) -> Result<LocalDataPurgeResult, ClientError> {
13207        let CompiledLocalDataPurge {
13208            targets,
13209            projections,
13210            canonical_plan,
13211        } = self.compile_local_data_purge(input)?;
13212        for name in &projections {
13213            self.lookup_projection(name)?;
13214        }
13215        let meta_key = format!("localPurge:{}", input.purge_id);
13216        let applied_plan = self
13217            .conn
13218            .query_row(
13219                "SELECT value FROM _syncular_meta WHERE key = ?1",
13220                rusqlite::params![meta_key],
13221                |row| row.get::<_, String>(0),
13222            )
13223            .optional()
13224            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13225        if let Some(applied_plan) = applied_plan {
13226            if applied_plan != canonical_plan {
13227                return Err(format!(
13228                    "sync.invalid_request: local purge id {:?} was already used with a different plan",
13229                    input.purge_id
13230                ).into());
13231            }
13232            // A retry after an unfinished rewrite finishes it.
13233            self.require_previous_version_gone()?;
13234            self.erase_purged_pages(&meta_key)?;
13235            return Ok(LocalDataPurgeResult {
13236                already_applied: true,
13237                purged_rows: 0,
13238                dropped_commits: 0,
13239            });
13240        }
13241
13242        // RFC 0005 D7: the container file cannot be a purge target (its name is
13243        // not in the running schema), so purge drops it as a fixed step, before
13244        // any mirror row is touched and unconditionally.
13245        let _ = self.drop_previous_version();
13246
13247        let rollback = self.capture();
13248        self.begin_observation("syncular_local_purge")?;
13249        let applied = (|| -> Result<(ChangeAccumulator, LocalDataPurgeResult), String> {
13250            let mut batch = ChangeAccumulator::default();
13251            let mut purged_rows = 0;
13252            for name in &projections {
13253                purged_rows += self.clear_projection(name, None)?;
13254                batch.table(name);
13255            }
13256            if targets.is_empty() {
13257                self.set_meta(&meta_key, &canonical_plan)?;
13258                return Ok((batch, LocalDataPurgeResult { already_applied: false, purged_rows, dropped_commits: 0 }));
13259            }
13260            let row_ids = self.local_purge_base_row_ids(&targets)?;
13261            let retained_dropped = self.drop_failed_commits(|table, values| {
13262                targets.iter().any(|target| {
13263                    target.table == table && Self::local_purge_values_match(target, values)
13264                })
13265            })?;
13266            let doomed = self
13267                .outbox
13268                .iter()
13269                .filter(|commit| {
13270                    commit.ops.iter().any(|operation| {
13271                        let matching_targets = targets
13272                            .iter()
13273                            .filter(|target| target.table == operation.table)
13274                            .collect::<Vec<_>>();
13275                        if matching_targets.is_empty() {
13276                            return false;
13277                        }
13278                        if row_ids
13279                            .get(&operation.table)
13280                            .is_some_and(|ids| ids.contains(&operation.row_id))
13281                        {
13282                            return true;
13283                        }
13284                        operation.values.as_ref().is_some_and(|values| {
13285                            matching_targets
13286                                .iter()
13287                                .any(|target| Self::local_purge_values_match(target, values))
13288                        })
13289                    })
13290                })
13291                .cloned()
13292                .collect::<Vec<_>>();
13293            let doomed_ids = doomed
13294                .iter()
13295                .map(|commit| commit.client_commit_id.clone())
13296                .collect::<BTreeSet<_>>();
13297            for commit in &retained_dropped {
13298                batch.conflicts = true;
13299                batch.rejections = true;
13300                batch.outcomes = true;
13301                for operation in &commit.ops {
13302                    batch.table(&operation.table);
13303                }
13304            }
13305            let mut rejections = Vec::new();
13306            // §5.11 purge erasure: the journal keeps a dropped commit's identity and
13307            // codes, never its operations, so no purged value survives in it.
13308            for commit in &doomed {
13309                for operation in &commit.ops {
13310                    batch.table(&operation.table);
13311                    self.overlay_dirty.table(&operation.table);
13312                }
13313                let results = (0..commit.ops.len())
13314                    .map(|op_index| {
13315                        let rejection = RejectionRecord {
13316                            client_commit_id: commit.client_commit_id.clone(),
13317                            op_index: op_index as i32,
13318                            code: "client.local_data_purged".to_owned(),
13319                            message: "the commit was dropped by an application-authorized local data purge".to_owned(),
13320                            retryable: false,
13321                            details: None,
13322                            operation: None,
13323                        };
13324                        rejections.push(rejection.clone());
13325                        CommitOperationOutcome::Error { rejection }
13326                    })
13327                    .collect::<Vec<_>>();
13328                self.persist_commit_outcome(
13329                    &commit.client_commit_id,
13330                    CommitOutcomeStatus::Rejected,
13331                    &results,
13332                    None,
13333                )?;
13334                self.leave_through(&commit.client_commit_id);
13335                self.delete_outbox_persisted(&commit.client_commit_id)?;
13336            }
13337            if !doomed.is_empty() {
13338                self.outbox
13339                    .retain(|commit| !doomed_ids.contains(&commit.client_commit_id));
13340                self.rejections.extend(rejections);
13341                self.prune_commit_outcomes()?;
13342                batch.status = true;
13343                batch.rejections = true;
13344                batch.outcomes = true;
13345            }
13346
13347            // §7.3.4: a unit whose cursor claims a purged row catches up from
13348            // -1, the §3.3 rule for rows a purge removed (§4.5 C1).
13349            for unit in self.stored(load_units(&self.conn))? {
13350                if unit.status != UnitStatus::Active
13351                    || (unit.cursor == Some(-1) && unit.bootstrap_state.is_none())
13352                {
13353                    continue;
13354                }
13355                let mut holds = false;
13356                for target in &targets {
13357                    let Some(table) = self.schema.table(&target.table) else {
13358                        continue;
13359                    };
13360                    let Some((scope, scope_params)) = covers(table, &unit.scopes)
13361                        .then(|| pair_scopes(&unit.scopes, &table.name, unit.echo.as_deref()))
13362                        .flatten()
13363                        .and_then(|effective| local_scope_predicate(table, &effective, &[]).ok().flatten())
13364                    else {
13365                        continue;
13366                    };
13367                    let clauses = target
13368                        .selectors
13369                        .iter()
13370                        .map(|(column, values)| {
13371                            format!("{} IN ({})", quote_ident(column), vec!["?"; values.len()].join(", "))
13372                        })
13373                        .collect::<Vec<_>>()
13374                        .join(" AND ");
13375                    let params = target
13376                        .selectors
13377                        .iter()
13378                        .flat_map(|(_, values)| values.iter().cloned().map(SqlValue::Text))
13379                        .chain(scope_params);
13380                    holds = self
13381                        .conn
13382                        .query_row(
13383                            &format!(
13384                                "SELECT 1 FROM {} WHERE {clauses} AND {scope} LIMIT 1",
13385                                base_table(&target.table)
13386                            ),
13387                            rusqlite::params_from_iter(params),
13388                            |_| Ok(()),
13389                        )
13390                        .optional()
13391                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
13392                        .is_some();
13393                    if holds {
13394                        break;
13395                    }
13396                }
13397                if holds {
13398                    self.record_unit_windows(&mut batch, &unit)?;
13399                    batch.status = true;
13400                    self.stored(save_unit(
13401                        &self.conn,
13402                        &UnitRecord {
13403                            cursor: Some(-1),
13404                            bootstrap_state: None,
13405                            seeded: Vec::new(),
13406                            restriction: None,
13407                            ..unit
13408                        },
13409                    ))?;
13410                }
13411            }
13412
13413            for (table, ids) in &row_ids {
13414                if ids.is_empty() {
13415                    continue;
13416                }
13417                batch.table(table);
13418                self.overlay_dirty.table(table);
13419                for row_id in ids {
13420                    self.delete_base_row(table, row_id, i64::MAX)?;
13421                    purged_rows += 1;
13422                }
13423            }
13424            // §5.11 purge erasure: a journaled outcome with an operation or
13425            // conflict row the purge reaches keeps its identity, status, ids
13426            // and codes only.
13427            let touches = |table: &str, row_id: &str, values: Option<&Map<String, Value>>| {
13428                targets.iter().any(|target| {
13429                    target.table == table
13430                        && (row_ids.get(table).is_some_and(|ids| ids.contains(row_id))
13431                            || values.is_some_and(|values| {
13432                                Self::local_purge_values_match(target, values)
13433                            }))
13434                })
13435            };
13436            let entries = self
13437                .conn
13438                .prepare("SELECT client_commit_id, results_json, operations_json FROM _syncular_commit_outcomes")
13439                .and_then(|mut statement| {
13440                    statement
13441                        .query_map([], |row| {
13442                            Ok((
13443                                row.get::<_, String>(0)?,
13444                                row.get::<_, String>(1)?,
13445                                row.get::<_, Option<String>>(2)?,
13446                            ))
13447                        })?
13448                        .collect::<Result<Vec<_>, _>>()
13449                })
13450                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13451            for (client_commit_id, results_json, operations_json) in entries {
13452                let corrupt = |_| "sync.local_corrupt: persisted commit outcome is invalid".to_owned();
13453                let mut results: Vec<CommitOperationOutcome> =
13454                    serde_json::from_str(&results_json).map_err(corrupt)?;
13455                let operations: Vec<CommitOperation> = operations_json
13456                    .map(|json| serde_json::from_str(&json))
13457                    .transpose()
13458                    .map_err(corrupt)?
13459                    .unwrap_or_default();
13460                let named = operations
13461                    .iter()
13462                    .chain(results.iter().filter_map(|result| match result {
13463                        CommitOperationOutcome::Conflict { conflict } => conflict.operation.as_ref(),
13464                        CommitOperationOutcome::Error { rejection } => rejection.operation.as_ref(),
13465                        CommitOperationOutcome::Applied { .. } => None,
13466                    }))
13467                    .any(|operation| touches(&operation.table, &operation.row_id, operation.values.as_ref()))
13468                    || results.iter().any(|result| {
13469                        matches!(result, CommitOperationOutcome::Conflict { conflict }
13470                            if touches(&conflict.table, &conflict.row_id, Some(&conflict.server_row)))
13471                    });
13472                if !named {
13473                    continue;
13474                }
13475                for result in &mut results {
13476                    match result {
13477                        CommitOperationOutcome::Conflict { conflict } => {
13478                            conflict.server_row = Map::new();
13479                            conflict.conflict_columns.clear();
13480                            conflict.operation = None;
13481                        }
13482                        CommitOperationOutcome::Error { rejection } => {
13483                            rejection.details = None;
13484                            rejection.operation = None;
13485                        }
13486                        CommitOperationOutcome::Applied { .. } => {}
13487                    }
13488                }
13489                let results_json = serde_json::to_string(&results).map_err(|error| error.to_string())?;
13490                self.conn
13491                    .execute(
13492                        "UPDATE _syncular_commit_outcomes SET results_json = ?1, operations_json = NULL WHERE client_commit_id = ?2",
13493                        rusqlite::params![results_json, client_commit_id],
13494                    )
13495                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13496                batch.outcomes = true;
13497            }
13498            self.rebuild_overlay_if_dirty()?;
13499            self.delete_unreferenced_cached_blobs()?;
13500            self.conn
13501                .execute(
13502                    "INSERT INTO _syncular_meta(key, value) VALUES (?1, ?2)",
13503                    rusqlite::params![meta_key, canonical_plan],
13504                )
13505                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13506            Ok((
13507                batch,
13508                LocalDataPurgeResult {
13509                    already_applied: false,
13510                    purged_rows,
13511                    dropped_commits: doomed.len(),
13512                },
13513            ))
13514        })()
13515        .and_then(|(batch, result)| {
13516            self.finish_observation("syncular_local_purge", batch)
13517                .map(|()| result)
13518        });
13519        let result = match applied {
13520            Ok(result) => result,
13521            Err(error) => {
13522                self.rollback_observation("syncular_local_purge");
13523                self.restore(rollback);
13524                return Err(error.into());
13525            }
13526        };
13527        self.cancel_sync_round();
13528        self.require_previous_version_gone()?;
13529        self.erase_purged_pages(&meta_key)?;
13530        Ok(result)
13531    }
13532
13533    /// §5.11: the previous-version container is a copy of earlier rows; its
13534    /// removal is best-effort elsewhere, so a container that survived the
13535    /// purge fails it before the erasure is recorded.
13536    fn require_previous_version_gone(&self) -> Result<(), String> {
13537        let Some(replica_path) = self.previous_version_replica_path() else {
13538            return Ok(());
13539        };
13540        let container = crate::previous_version::previous_version_container_path(&replica_path);
13541        if std::path::Path::new(&container).exists() {
13542            self.drop_previous_version()?;
13543        }
13544        if std::path::Path::new(&container).exists() {
13545            return Err(
13546                "client.storage_failure: the previous-version container survived the purge"
13547                    .to_owned(),
13548            );
13549        }
13550        Ok(())
13551    }
13552
13553    /// §5.11 purge erasure: SQLite leaves a deleted value in the freed pages of the
13554    /// database file, FTS5 keeps a deleted document's tokens in its index
13555    /// segments, and the WAL keeps the frames written before the purge, until
13556    /// each is rewritten. The FTS5 merge drops the deleted tokens, VACUUM
13557    /// rebuilds the file from the remaining rows, and the checkpoint truncates
13558    /// the WAL. The plan's completion marker follows the checkpoint, so only a
13559    /// finished rewrite lets a retry skip it.
13560    fn erase_purged_pages(&self, meta_key: &str) -> Result<(), String> {
13561        let marker = format!("{meta_key}:erased");
13562        let done = self.stored(
13563            self.conn
13564                .query_row(
13565                    "SELECT 1 FROM _syncular_meta WHERE key = ?1",
13566                    [&marker],
13567                    |_| Ok(()),
13568                )
13569                .optional(),
13570        )?;
13571        if done.is_some() {
13572            return Ok(());
13573        }
13574        let indexes: Vec<String> = self.stored(
13575            self.conn
13576                .prepare(
13577                    "SELECT name FROM sqlite_master WHERE type = 'table' AND sql LIKE 'CREATE VIRTUAL TABLE%USING fts5%'",
13578                )
13579                .and_then(|mut statement| {
13580                    statement
13581                        .query_map([], |row| row.get(0))?
13582                        .collect::<Result<Vec<String>, _>>()
13583                }),
13584        )?;
13585        let erased = self.stored(
13586            self.conn
13587                .execute_batch("PRAGMA secure_delete = ON;")
13588                .and_then(|()| {
13589                    for index in &indexes {
13590                        let name = quote_ident(index);
13591                        self.conn.execute_batch(&format!(
13592                            "INSERT INTO {name}({name}) VALUES('optimize');"
13593                        ))?;
13594                    }
13595                    self.conn.execute_batch("VACUUM;")
13596                })
13597                .and_then(|()| {
13598                    self.conn
13599                        .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| {
13600                            row.get::<_, bool>(0)
13601                        })
13602                }),
13603        );
13604        let reset = self.stored(self.conn.execute_batch("PRAGMA secure_delete = OFF"));
13605        if erased.and_then(|busy| reset.map(|()| busy))? {
13606            return Err("client.storage_busy: WAL checkpoint is busy".to_owned());
13607        }
13608        self.set_meta(&marker, "1")
13609    }
13610
13611    /// Application-authorized recovery of the replicated projection. Unlike a
13612    /// local security purge, this retains the entire outbox, device identity,
13613    /// lease, outcomes, unit registrations, and protected bookkeeping.
13614    /// The projection reset, unit rewind, optimistic replay, and
13615    /// idempotency marker share one savepoint for interruption safety.
13616    pub fn rebootstrap_local_data(
13617        &mut self,
13618        input: &LocalDataRebootstrapInput,
13619    ) -> Result<LocalDataRebootstrapResult, String> {
13620        if input.rebootstrap_id.is_empty()
13621            || input.rebootstrap_id.len() > 128
13622            || !is_local_operation_code_like(&input.rebootstrap_id)
13623        {
13624            return Err(
13625                "sync.invalid_request: local rebootstrap rebootstrapId must be a 1–128 character code-like identifier"
13626                    .to_owned(),
13627            );
13628        }
13629        let meta_key = format!("localRebootstrap:{}", input.rebootstrap_id);
13630        if let Some(persisted) = meta_get(&self.conn, &meta_key).map_err(|_| {
13631            "sync.local_corrupt: persisted local rebootstrap receipt is unreadable".to_owned()
13632        })? {
13633            let (retained_commits, reset_subscriptions) =
13634                decode_local_rebootstrap_receipt(&persisted)?;
13635            return Ok(LocalDataRebootstrapResult {
13636                already_applied: true,
13637                retained_commits,
13638                reset_subscriptions,
13639            });
13640        }
13641        if self.stopped || self.schema_floor.is_some() {
13642            return Err(
13643                "sync.invalid_request: local rebootstrap cannot bypass an active schema-floor stop; update the application first"
13644                    .to_owned(),
13645            );
13646        }
13647
13648        let retained_commits = self.outbox.len();
13649        let reset_subscriptions = self.stored(load_units(&self.conn))?.len();
13650        let receipt = encode_local_rebootstrap_receipt(retained_commits, reset_subscriptions)?;
13651        let rollback = self.capture();
13652        self.begin_observation("syncular_local_rebootstrap")?;
13653        let mut batch = ChangeAccumulator::default();
13654        let applied = (|| -> Result<(), String> {
13655            self.run_schema_reset_observed(&mut batch, false)?;
13656            self.conn
13657                .execute(
13658                    "INSERT INTO _syncular_meta(key, value) VALUES (?1, ?2)",
13659                    rusqlite::params![meta_key, receipt],
13660                )
13661                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13662            self.sync_needed = true;
13663            self.sync_intent_queue.push_back(SyncIntent::Interactive);
13664            batch.status = true;
13665            Ok(())
13666        })()
13667        .and_then(|()| self.finish_observation("syncular_local_rebootstrap", batch));
13668        if let Err(error) = applied {
13669            self.rollback_observation("syncular_local_rebootstrap");
13670            self.restore(rollback);
13671            return Err(error);
13672        }
13673        self.cancel_sync_round();
13674
13675        Ok(LocalDataRebootstrapResult {
13676            already_applied: false,
13677            retained_commits,
13678            reset_subscriptions,
13679        })
13680    }
13681
13682    // -- scope purge + doomed outbox (§3.3) ----------------------------------------
13683
13684    /// Delete base and visible rows owned by the effective scopes
13685    /// ([`local_scope_predicate`]); `Ok(false)` = no local scope-column
13686    /// mapping for a key (the fail-closed case). A SQLite failure is an error.
13687    fn purge_scope_rows(
13688        &mut self,
13689        table_name: &str,
13690        effective: &[(String, Vec<String>)],
13691        owners: &[Vec<(String, Vec<String>)>],
13692    ) -> Result<bool, String> {
13693        let Some(table) = self.schema.table(table_name) else {
13694            return Ok(false);
13695        };
13696        let Ok(predicate) = local_scope_predicate(table, effective, owners) else {
13697            return Ok(false);
13698        };
13699        let Some((predicate, params)) = predicate else {
13700            return Ok(true);
13701        };
13702        self.overlay_dirty.table(table_name);
13703        for source in [base_table(table_name), visible_table(table_name)] {
13704            self.conn
13705                .execute(
13706                    &format!("DELETE FROM {source} WHERE {predicate}"),
13707                    rusqlite::params_from_iter(&params),
13708                )
13709                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13710        }
13711        Ok(true)
13712    }
13713
13714    /// §3.3: drop pending commits whose upserts provably land in the
13715    /// revoked effective scopes and no other owner covers (row ownership)
13716    /// — whole-commit, never per-operation.
13717    fn drop_doomed_outbox(
13718        &mut self,
13719        table: &TableSchema,
13720        effective: &[(String, Vec<String>)],
13721        owners: &[Vec<(String, Vec<String>)>],
13722    ) -> Result<bool, String> {
13723        let doomed: Vec<_> =
13724            self.outbox
13725                .iter()
13726                .filter(|commit| {
13727                    commit.ops.iter().any(|op| {
13728                        op.upsert
13729                            && op.table == table.name
13730                            && op.values.as_ref().is_some_and(|values| {
13731                                owns_local_row(table, effective, owners, values)
13732                            })
13733                    })
13734                })
13735                .cloned()
13736                .collect();
13737        if doomed.is_empty() {
13738            return Ok(false);
13739        }
13740        let mut rejections = Vec::new();
13741        for commit in &doomed {
13742            let results = commit
13743                .ops
13744                .iter()
13745                .enumerate()
13746                .map(|(op_index, operation)| {
13747                    self.overlay_dirty.table(&operation.table);
13748                    let rejection = RejectionRecord {
13749                        client_commit_id: commit.client_commit_id.clone(),
13750                        op_index: op_index as i32,
13751                        code: "sync.scope_revoked".to_owned(),
13752                        message: "the commit was dropped because its effective scope was revoked"
13753                            .to_owned(),
13754                        retryable: false,
13755                        details: None,
13756                        operation: Some(CommitOperation::from(operation)),
13757                    };
13758                    rejections.push(rejection.clone());
13759                    CommitOperationOutcome::Error { rejection }
13760                })
13761                .collect::<Vec<_>>();
13762            self.persist_commit_outcome(
13763                &commit.client_commit_id,
13764                CommitOutcomeStatus::Rejected,
13765                &results,
13766                Some(&commit.ops),
13767            )?;
13768            self.leave_through(&commit.client_commit_id);
13769            self.delete_outbox_persisted(&commit.client_commit_id)?;
13770        }
13771        self.prune_commit_outcomes()?;
13772        let doomed_ids = doomed
13773            .iter()
13774            .map(|commit| commit.client_commit_id.as_str())
13775            .collect::<BTreeSet<_>>();
13776        self.outbox
13777            .retain(|commit| !doomed_ids.contains(commit.client_commit_id.as_str()));
13778        self.rejections.extend(rejections);
13779        Ok(true)
13780    }
13781
13782    // -- blobs (§5.9) ----------------------------------------------------------------
13783
13784    /// §5.9.7: hash bytes into the content address, cache them, queue the
13785    /// upload (flushed before the next push, B4). Returns the canonical
13786    /// BlobRef JSON `{blobId, byteLength, mediaType?}` for a `blob_ref`
13787    /// column value.
13788    pub fn upload_blob(
13789        &mut self,
13790        bytes: &[u8],
13791        media_type: Option<String>,
13792        name: Option<String>,
13793    ) -> Result<Value, String> {
13794        let blob_id = blob_id_for(bytes);
13795        let now = self.clock_now_ms();
13796        let tx = self
13797            .conn
13798            .transaction()
13799            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13800        tx.execute(
13801            "INSERT INTO _syncular_blobs(blob_id, bytes, byte_length, media_type, created_at_ms) VALUES (?,?,?,?,?)
13802             ON CONFLICT(blob_id) DO NOTHING",
13803            rusqlite::params![blob_id, bytes, bytes.len() as i64, media_type, now],
13804        )
13805        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13806        tx.execute(
13807            "INSERT OR IGNORE INTO _syncular_blob_uploads(blob_id, media_type, created_at_ms) VALUES (?,?,?)",
13808            rusqlite::params![blob_id, media_type, now],
13809        )
13810        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13811        tx.commit()
13812            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13813        self.enforce_blob_cache_cap();
13814        let mut obj = Map::new();
13815        obj.insert("blobId".to_owned(), Value::from(blob_id));
13816        obj.insert("byteLength".to_owned(), Value::from(bytes.len() as i64));
13817        if let Some(mt) = media_type {
13818            obj.insert("mediaType".to_owned(), Value::from(mt));
13819        }
13820        if let Some(n) = name {
13821            obj.insert("name".to_owned(), Value::from(n));
13822        }
13823        Ok(Value::Object(obj))
13824    }
13825
13826    /// §5.9.7: resolve an owned blob body without driver encoding. A
13827    /// content-addressed cache hit serves with no fetch (B1); a miss downloads
13828    /// (§5.9.5), verifies the address, caches the bytes, and returns them.
13829    pub fn fetch_blob_bytes(
13830        &mut self,
13831        transport: &mut dyn Transport,
13832        blob_id_or_ref: &str,
13833    ) -> Result<FetchedBlob, (String, String)> {
13834        let simple = |m: String| ("client.failed".to_owned(), m);
13835        // A BlobRef declares the size that caps the download (§5.9.5); a bare
13836        // blobId declares none.
13837        let (blob_id, byte_length) = if blob_id_or_ref.starts_with("sha256:") {
13838            (blob_id_or_ref.to_owned(), None)
13839        } else {
13840            let value: Value = serde_json::from_str(blob_id_or_ref)
13841                .map_err(|_| simple("blob ref is not JSON".to_owned()))?;
13842            (
13843                value
13844                    .get("blobId")
13845                    .and_then(Value::as_str)
13846                    .ok_or_else(|| simple("blob ref has no blobId".to_owned()))?
13847                    .to_owned(),
13848                value.get("byteLength").and_then(Value::as_u64),
13849            )
13850        };
13851        if let Some(cached) = self.get_cached_blob_bytes(&blob_id).map_err(simple)? {
13852            return Ok(cached);
13853        }
13854        if self.transport_closed() {
13855            return Err(("sync.offline".into(), "transport gate is closed".into()));
13856        }
13857        // §5.9.5: propagate the server's blob.* code (blob.forbidden /
13858        // blob.not_found) verbatim so the harness can assert on it. The
13859        // authorized endpoint serves bytes inline OR (always-issue, presign
13860        // configured) a signed url the client fetches directly — no host auth,
13861        // no fall-through: failure => re-request (the caller's next fetch_blob_bytes).
13862        #[cfg(feature = "bench-internals")]
13863        let download_phase = self.benchmark_phases.start(Phase::BlobDownload);
13864        let bytes = match transport
13865            .blob_download(&blob_id, byte_length)
13866            .map_err(|e| (e.code, e.message))?
13867        {
13868            BlobDownload::Bytes(bytes) => bytes,
13869            BlobDownload::Url {
13870                url,
13871                url_expires_at_ms,
13872            } => {
13873                // §5.9.5: MUST NOT start a fetch at/past expiry.
13874                if url_expires_at_ms.is_some_and(|exp| exp <= self.clock_now_ms()) {
13875                    return Err((
13876                        "sync.segment_expired".to_owned(),
13877                        format!(
13878                            "blob url for {blob_id} expired before fetch — re-request mints a fresh url (§5.9.5)"
13879                        ),
13880                    ));
13881                }
13882                transport
13883                    .fetch_blob_url(&url, byte_length)
13884                    .map_err(|e| (e.code, e.message))?
13885            }
13886        };
13887        #[cfg(feature = "bench-internals")]
13888        drop(download_phase);
13889        #[cfg(feature = "bench-internals")]
13890        let validate_phase = self.benchmark_phases.start(Phase::BlobValidate);
13891        // §5.9.5 inherits §5.1: the declared size caps the body before the
13892        // content address is verified.
13893        if byte_length.is_some_and(|cap| bytes.len() as u64 > cap) {
13894            return Err((
13895                "sync.invalid_request".to_owned(),
13896                "blob exceeds its byteLength".to_owned(),
13897            ));
13898        }
13899        if blob_id_for(&bytes) != blob_id {
13900            return Err(simple(format!(
13901                "blob content address mismatch for {blob_id}"
13902            )));
13903        }
13904        #[cfg(feature = "bench-internals")]
13905        drop(validate_phase);
13906        #[cfg(feature = "bench-internals")]
13907        let insert_phase = self.benchmark_phases.start(Phase::BlobCacheInsert);
13908        let now = self.clock_now_ms();
13909        self.conn
13910            .execute(
13911                "INSERT OR IGNORE INTO _syncular_blobs(blob_id, bytes, byte_length, media_type, created_at_ms) VALUES (?,?,?,NULL,?)",
13912                rusqlite::params![blob_id, bytes, bytes.len() as i64, now],
13913            )
13914            .map_err(|e| simple(e.to_string()))?;
13915        self.conn
13916            .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
13917            .map_err(|e| simple(e.to_string()))?;
13918        self.enforce_blob_cache_cap();
13919        #[cfg(feature = "bench-internals")]
13920        drop(insert_phase);
13921        self.get_cached_blob_bytes(&blob_id)
13922            .map_err(simple)?
13923            .ok_or_else(|| simple("blob cache write failed".to_owned()))
13924    }
13925
13926    fn get_cached_blob_bytes(&self, blob_id: &str) -> Result<Option<FetchedBlob>, String> {
13927        #[cfg(feature = "bench-internals")]
13928        let _phase = self.benchmark_phases.start(Phase::BlobCacheRead);
13929        let mut stmt = self
13930            .conn
13931            .prepare("SELECT bytes, byte_length, media_type FROM _syncular_blobs WHERE blob_id = ?")
13932            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13933        let mut rows = stmt
13934            .query(rusqlite::params![blob_id])
13935            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13936        if let Some(row) = rows
13937            .next()
13938            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
13939        {
13940            let bytes: Vec<u8> = row
13941                .get(0)
13942                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13943            let byte_length: i64 = row
13944                .get(1)
13945                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13946            let media_type: Option<String> = row
13947                .get(2)
13948                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
13949            return Ok(Some(FetchedBlob {
13950                blob_id: blob_id.to_owned(),
13951                byte_length,
13952                bytes,
13953                media_type,
13954            }));
13955        }
13956        Ok(None)
13957    }
13958
13959    /// §5.9.7 B4: upload every queued blob before push.
13960    fn pending_blob_uploads(&self) -> Result<Vec<crate::round::PendingUpload>, TransportError> {
13961        let pending: Vec<(String, Option<String>)> = {
13962            let mut stmt = self
13963                .conn
13964                .prepare(
13965                    "SELECT blob_id, media_type FROM (
13966                      SELECT blob_id, media_type, created_at_ms FROM _syncular_blob_uploads
13967                      UNION ALL
13968                      SELECT DISTINCT r.blob_id, b.media_type, 9223372036854775807 AS created_at_ms
13969                      FROM _syncular_blob_commit_refs r LEFT JOIN _syncular_blobs b ON b.blob_id = r.blob_id
13970                      WHERE NOT EXISTS (SELECT 1 FROM _syncular_blob_uploads u WHERE u.blob_id = r.blob_id)
13971                    ) ORDER BY created_at_ms, blob_id",
13972                )
13973                .map_err(|e| TransportError::new("client.failed", e.to_string()))?;
13974            let rows = stmt
13975                .query_map([], |row| {
13976                    Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?))
13977                })
13978                .map_err(|e| TransportError::new("client.failed", e.to_string()))?;
13979            rows.collect::<Result<_, _>>()
13980                .map_err(|error| match error {
13981                    rusqlite::Error::InvalidColumnType(..)
13982                    | rusqlite::Error::FromSqlConversionFailure(..) => TransportError::new(
13983                        "sync.local_corrupt",
13984                        "Pending blob upload metadata is invalid",
13985                    ),
13986                    _ => TransportError::new("client.failed", error.to_string()),
13987                })?
13988        };
13989        let mut uploads = Vec::new();
13990        for (blob_id, media_type) in pending {
13991            let bytes = (|| {
13992                let stored: Option<(SqlValue, SqlValue)> = self
13993                    .conn
13994                    .query_row(
13995                        "SELECT bytes, byte_length FROM _syncular_blobs WHERE blob_id = ?",
13996                        rusqlite::params![blob_id],
13997                        |row| Ok((row.get(0)?, row.get(1)?)),
13998                    )
13999                    .optional()
14000                    .map_err(|e| TransportError::new("client.failed", e.to_string()))?;
14001                let Some((SqlValue::Blob(bytes), SqlValue::Integer(byte_length))) = stored else {
14002                    return Err(TransportError::new(
14003                        "sync.local_corrupt",
14004                        "Pending blob upload body is missing or corrupt",
14005                    ));
14006                };
14007                if byte_length != bytes.len() as i64 || blob_id_for(&bytes) != blob_id {
14008                    return Err(TransportError::new(
14009                        "sync.local_corrupt",
14010                        "Pending blob upload body is missing or corrupt",
14011                    ));
14012                }
14013                Ok(bytes)
14014            })();
14015            let failed = bytes.is_err();
14016            uploads.push(crate::round::PendingUpload {
14017                id: blob_id,
14018                bytes,
14019                media_type,
14020            });
14021            if failed {
14022                break;
14023            }
14024        }
14025        Ok(uploads)
14026    }
14027
14028    fn visible_blob_ids_sql(&self) -> String {
14029        let mut selects = Vec::new();
14030        for table in &self.schema.tables {
14031            for column in table
14032                .columns
14033                .iter()
14034                .filter(|column| column.ty == ColumnType::BlobRef)
14035            {
14036                let identifier = quote_ident(&column.name);
14037                selects.push(format!(
14038                    "SELECT json_extract({identifier}, '$.blobId') AS blob_id FROM {} \
14039                     WHERE typeof({identifier}) = 'text' AND json_valid({identifier}) \
14040                     AND json_type({identifier}, '$.blobId') = 'text'",
14041                    quote_ident(&table.name),
14042                ));
14043            }
14044        }
14045        if selects.is_empty() {
14046            "SELECT NULL AS blob_id WHERE 0".to_owned()
14047        } else {
14048            selects.join(" UNION ")
14049        }
14050    }
14051
14052    /// §5.9.7 B1 size cap. Visible rows, pending commits, and
14053    /// staged uploads pin bodies directly; no derived refcount is stored.
14054    fn enforce_blob_cache_cap(&self) {
14055        let Some(max_bytes) = self.limits.blob_cache_max_bytes else {
14056            return;
14057        };
14058        let mut total: i64 = self
14059            .conn
14060            .query_row(
14061                "SELECT COALESCE(SUM(byte_length), 0) FROM _syncular_blobs",
14062                [],
14063                |row| row.get(0),
14064            )
14065            .unwrap_or(0);
14066        if total <= max_bytes {
14067            return;
14068        }
14069        let query = format!(
14070            "SELECT blob_id, byte_length FROM _syncular_blobs
14071             WHERE blob_id NOT IN (SELECT blob_id FROM _syncular_blob_uploads)
14072               AND blob_id NOT IN (SELECT blob_id FROM _syncular_blob_commit_refs)
14073               AND blob_id NOT IN ({})
14074             ORDER BY created_at_ms ASC, blob_id ASC",
14075            self.visible_blob_ids_sql(),
14076        );
14077        let candidates: Vec<(String, i64)> = {
14078            let Ok(mut stmt) = self.conn.prepare(&query) else {
14079                return;
14080            };
14081            let Ok(rows) = stmt.query_map([], |row| {
14082                Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
14083            }) else {
14084                return;
14085            };
14086            rows.filter_map(Result::ok).collect()
14087        };
14088        for (blob_id, byte_length) in candidates {
14089            if total <= max_bytes {
14090                break;
14091            }
14092            let _ = self.conn.execute(
14093                "DELETE FROM _syncular_blobs WHERE blob_id = ?",
14094                rusqlite::params![blob_id],
14095            );
14096            total -= byte_length;
14097        }
14098    }
14099
14100    fn delete_unreferenced_cached_blobs(&mut self) -> Result<(), String> {
14101        #[cfg(feature = "bench-internals")]
14102        let _phase = self.benchmark_phases.start(Phase::BlobRetention);
14103        if !self.schema_has_blobs() {
14104            return Ok(());
14105        }
14106        self.rebuild_overlay_if_dirty()?;
14107        self.conn
14108            .execute(
14109                &format!(
14110                    "DELETE FROM _syncular_blobs
14111                 WHERE blob_id NOT IN (SELECT blob_id FROM _syncular_blob_uploads)
14112                   AND blob_id NOT IN (SELECT blob_id FROM _syncular_blob_commit_refs)
14113                   AND blob_id NOT IN ({})",
14114                    self.visible_blob_ids_sql(),
14115                ),
14116                [],
14117            )
14118            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14119        Ok(())
14120    }
14121
14122    // -- local row storage ----------------------------------------------------------
14123
14124    /// The cached per-table primary-key upsert SQL for `full_table` (see
14125    /// the `insert_sql` field: built once, reused per row).
14126    fn insert_row_sql(&self, full_table: &str, table: &crate::schema::TableSchema) -> String {
14127        if let Some(sql) = self.insert_sql.borrow().get(full_table) {
14128            return sql.clone();
14129        }
14130        let mut columns: Vec<String> = table.columns.iter().map(|c| quote_ident(&c.name)).collect();
14131        columns.push(quote_ident("_syncular_version"));
14132        columns.extend(table.sealed_columns().iter().map(|name| quote_ident(name)));
14133        let placeholders: Vec<&str> = columns.iter().map(|_| "?").collect();
14134        let primary_key = quote_ident(&table.primary_key);
14135        let updates = columns
14136            .iter()
14137            .filter(|column| **column != primary_key)
14138            .map(|column| format!("{column}=excluded.{column}"))
14139            .collect::<Vec<_>>()
14140            .join(", ");
14141        // §4.5 version guard: server state lands in the base table only above
14142        // the stored version; the visible overlay takes every write.
14143        let guard = if full_table == base_table(&table.name) {
14144            format!(" WHERE excluded._syncular_version > {full_table}._syncular_version")
14145        } else {
14146            String::new()
14147        };
14148        let sql = format!(
14149            "INSERT INTO {full_table} ({}) VALUES ({}) ON CONFLICT ({primary_key}) DO UPDATE SET {updates}{guard}",
14150            columns.join(", "),
14151            placeholders.join(", ")
14152        );
14153        self.insert_sql
14154            .borrow_mut()
14155            .insert(full_table.to_owned(), sql.clone());
14156        sql
14157    }
14158
14159    /// §4.5: write a server row under the version guard; returns whether it
14160    /// landed. `sealed` is its §5.11 sealed state, `None` for an unsealed row.
14161    fn write_base_row(
14162        &self,
14163        table_name: &str,
14164        row: &Row,
14165        version: i64,
14166        sealed: Option<&SealedRow>,
14167    ) -> Result<bool, String> {
14168        let landed = self.write_row(&base_table(table_name), table_name, row, version, sealed)?;
14169        if landed {
14170            self.overlay_dirty.table(table_name);
14171        }
14172        Ok(landed)
14173    }
14174
14175    fn write_row(
14176        &self,
14177        full_table: &str,
14178        table_name: &str,
14179        row: &Row,
14180        version: i64,
14181        sealed: Option<&SealedRow>,
14182    ) -> Result<bool, String> {
14183        #[cfg(feature = "bench-internals")]
14184        let _phase = self.benchmark_phases.start(Phase::RowWrite);
14185        let table = self
14186            .schema
14187            .table(table_name)
14188            .ok_or_else(|| format!("unknown table {table_name:?}"))?;
14189        let sql = self.insert_row_sql(full_table, table);
14190        let mut stmt = self
14191            .conn
14192            .prepare_cached(&sql)
14193            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14194        let params = row
14195            .iter()
14196            .map(RowParam::Cell)
14197            .chain(std::iter::once(RowParam::Version(version)))
14198            .chain(
14199                [
14200                    sealed.map(|sealed| sealed.key_id.as_str()),
14201                    sealed.map(|sealed| sealed.envelopes.as_str()),
14202                ]
14203                .into_iter()
14204                .take(table.sealed_columns().len())
14205                .map(RowParam::Text),
14206            );
14207        stmt.execute(rusqlite::params_from_iter(params))
14208            .map(|changed| changed > 0)
14209            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
14210    }
14211
14212    /// §4.5: delete a server row whose stored version lies below `version`;
14213    /// returns whether a row left.
14214    fn delete_base_row(
14215        &self,
14216        table_name: &str,
14217        row_id: &str,
14218        version: i64,
14219    ) -> Result<bool, String> {
14220        let table = self
14221            .schema
14222            .table(table_name)
14223            .ok_or_else(|| format!("unknown table {table_name:?}"))?;
14224        let sql = format!(
14225            "DELETE FROM {} WHERE {} AND _syncular_version < ?2",
14226            base_table(table_name),
14227            row_id_predicate(table)
14228        );
14229        let mut stmt = self
14230            .conn
14231            .prepare_cached(&sql)
14232            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14233        let landed = stmt
14234            .execute(rusqlite::params![row_id, version])
14235            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
14236            > 0;
14237        if landed {
14238            self.overlay_dirty.table(table_name);
14239        }
14240        Ok(landed)
14241    }
14242
14243    fn has_acknowledged_rows(&self) -> Result<bool, String> {
14244        self.conn
14245            .query_row(
14246                "SELECT EXISTS(SELECT 1 FROM _syncular_acked_rows)",
14247                [],
14248                |row| row.get(0),
14249            )
14250            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
14251    }
14252
14253    fn acknowledged_operations(
14254        &self,
14255        rows: Option<&HashSet<(&str, &str)>>,
14256        tables: Option<&BTreeSet<&str>>,
14257    ) -> Result<Vec<OutboxOp>, String> {
14258        let keys = rows.map(|rows| serde_json::to_string(&rows).expect("row keys"));
14259        let mut statement = self
14260            .conn
14261            .prepare_cached(if keys.is_some() {
14262                ACKED_ROWS_BY_ROW
14263            } else {
14264                "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"
14265            })
14266            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14267        let rows = statement
14268            .query_map(
14269                rusqlite::params![
14270                    keys,
14271                    tables.map(|tables| serde_json::to_string(tables).expect("table keys"))
14272                ],
14273                |row| {
14274                    #[cfg(test)]
14275                    self.acknowledged_replay_count
14276                        .set(self.acknowledged_replay_count.get() + 1);
14277                    Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
14278                },
14279            )
14280            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14281        rows.map(|row| {
14282            let (op, intent) =
14283                row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14284            let op: CommitOperation =
14285                serde_json::from_str(&op).map_err(|_| "sync.local_corrupt".to_owned())?;
14286            let table = self
14287                .schema
14288                .table(&op.table)
14289                .ok_or_else(|| "sync.unknown_table".to_owned())?;
14290            let values = if op.op == "upsert" && self.visible_row(table, &op.row_id)?.is_none() {
14291                Some(serde_json::from_str(&intent).map_err(|_| "sync.local_corrupt".to_owned())?)
14292            } else {
14293                op.values.clone()
14294            };
14295            Ok(OutboxOp {
14296                values,
14297                ..op.into()
14298            })
14299        })
14300        .collect()
14301    }
14302
14303    fn drop_acknowledged_rows(
14304        &self,
14305        matches: impl Fn(&str, &Map<String, Value>) -> bool,
14306    ) -> Result<Vec<OutboxCommit>, String> {
14307        let mut statement = self
14308            .conn
14309            .prepare("SELECT commit_id,tbl,intent_json,id FROM _syncular_acked_rows")
14310            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14311        let rows = statement
14312            .query_map([], |row| {
14313                Ok((
14314                    row.get::<_, String>(0)?,
14315                    row.get::<_, String>(1)?,
14316                    row.get::<_, String>(2)?,
14317                    row.get::<_, String>(3)?,
14318                ))
14319            })
14320            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14321        let mut doomed = HashSet::new();
14322        for row in rows {
14323            let (id, table, intent, row_id) =
14324                row.map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14325            let values =
14326                serde_json::from_str(&intent).map_err(|_| "sync.local_corrupt".to_owned())?;
14327            let base_matches = self
14328                .schema
14329                .table(&table)
14330                .map(|schema| self.stored_row(schema, &row_id, true))
14331                .transpose()?
14332                .flatten()
14333                .is_some_and(|(base, _)| {
14334                    let schema = self.schema.table(&table).expect("acknowledged table");
14335                    let values = schema
14336                        .columns
14337                        .iter()
14338                        .zip(base.iter())
14339                        .map(|(column, value)| (column.name.clone(), column_value_to_json(value)))
14340                        .collect();
14341                    matches(&table, &values)
14342                });
14343            if matches(&table, &values) || base_matches {
14344                doomed.insert(id);
14345            }
14346        }
14347        let mut dropped = Vec::new();
14348        for id in doomed {
14349            let mut statement = self
14350                .conn
14351                .prepare("SELECT op_json FROM _syncular_acked_rows WHERE commit_id=?1 ORDER BY idx")
14352                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14353            let operations = statement
14354                .query_map([&id], |row| row.get::<_, String>(0))
14355                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14356            let mut ops = Vec::new();
14357            for operation in operations {
14358                let json = operation
14359                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14360                let op: CommitOperation =
14361                    serde_json::from_str(&json).map_err(|_| "sync.local_corrupt".to_owned())?;
14362                self.overlay_dirty.table(&op.table);
14363                ops.push(OutboxOp {
14364                    table: op.table,
14365                    row_id: op.row_id,
14366                    upsert: op.op == "upsert",
14367                    base_version: op.base_version,
14368                    values: op.values,
14369                    insert: op.insert,
14370                });
14371            }
14372            dropped.push(OutboxCommit {
14373                client_commit_id: id.clone(),
14374                ops,
14375            });
14376            self.conn
14377                .execute("DELETE FROM _syncular_acked_rows WHERE commit_id=?1", [id])
14378                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14379        }
14380        Ok(dropped)
14381    }
14382
14383    /// [`Self::rebuild_overlay`], skipped when neither the base tables nor
14384    /// the outbox changed since the last rebuild (the no-op sync round).
14385    fn rebuild_overlay_if_dirty(&mut self) -> Result<(), String> {
14386        if self.overlay_dirty.get() {
14387            self.rebuild_overlay()?;
14388        }
14389        Ok(())
14390    }
14391
14392    /// §7.1: local reads see outbox state applied optimistically — rebuild
14393    /// every visible table as (base server state) + (pending outbox replay
14394    /// on top). Optimistic rows carry version `-1`.
14395    fn rebuild_overlay(&mut self) -> Result<(), String> {
14396        #[cfg(feature = "bench-internals")]
14397        let _phase = self.benchmark_phases.start(Phase::OverlayRebuild);
14398        #[cfg(test)]
14399        self.overlay_rebuild_count
14400            .set(self.overlay_rebuild_count.get() + 1);
14401        let dirty = self.overlay_dirty.snapshot();
14402        let tables: Vec<_> = self
14403            .schema
14404            .tables
14405            .iter()
14406            .filter(|table| {
14407                dirty
14408                    .as_ref()
14409                    .is_none_or(|names| names.is_empty() || names.contains(&table.name))
14410            })
14411            .cloned()
14412            .collect();
14413        let names: BTreeSet<_> = tables.iter().map(|table| table.name.as_str()).collect();
14414        // A built-in projection is refilled from the rebuilt rows once
14415        // instead of per row by its source triggers.
14416        let built_in: Vec<_> = tables
14417            .iter()
14418            .flat_map(|table| {
14419                table
14420                    .local_projections
14421                    .iter()
14422                    .filter(|spec| spec.built_in())
14423                    .map(move |spec| (spec, table))
14424            })
14425            .collect();
14426        self.begin_observation("syncular_overlay")?;
14427        let rebuilt = (|| {
14428            for (spec, _) in &built_in {
14429                for suffix in ["bi", "bu", "ai", "ad", "au"] {
14430                    self.stored(self.conn.execute(
14431                        &format!(
14432                            "DROP TRIGGER IF EXISTS {}",
14433                            quote_ident(&format!("_syncular_project_{}_{suffix}", spec.name))
14434                        ),
14435                        [],
14436                    ))?;
14437                }
14438            }
14439            for table in &tables {
14440                let visible = visible_table(&table.name);
14441                let base = base_table(&table.name);
14442                self.conn
14443                    .execute_batch(&format!(
14444                        "DELETE FROM {visible}; INSERT INTO {visible} SELECT * FROM {base}"
14445                    ))
14446                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14447            }
14448            self.replay_overlay(&names, None)?;
14449            for (spec, table) in &built_in {
14450                self.fill_built_in(spec, table)?;
14451                self.create_projection_triggers(spec, table)?;
14452            }
14453            self.conn
14454                .execute_batch("RELEASE syncular_overlay")
14455                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14456            Ok(())
14457        })();
14458        if rebuilt.is_err() {
14459            self.conn
14460                .execute_batch("ROLLBACK TO syncular_overlay; RELEASE syncular_overlay")
14461                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14462        } else {
14463            self.overlay_dirty.set(false);
14464        }
14465        rebuilt
14466    }
14467
14468    /// §7.1 replay of acknowledged, retained failed and pending intent, in
14469    /// that order, for the operations of `tables` on `rows` (every row for
14470    /// `None`) over their current visible state.
14471    fn replay_overlay(
14472        &self,
14473        tables: &BTreeSet<&str>,
14474        rows: Option<&HashSet<(&str, &str)>>,
14475    ) -> Result<(), String> {
14476        let replays = |op: &&OutboxOp| {
14477            tables.contains(op.table.as_str())
14478                && rows.is_none_or(|rows| rows.contains(&(op.table.as_str(), op.row_id.as_str())))
14479        };
14480        self.apply_outbox_ops(&self.acknowledged_operations(rows, Some(tables))?)?;
14481        for (commit, initial) in self.failed_commits.iter() {
14482            for operation in commit.ops.iter().filter(replays) {
14483                let Some(table) = self.schema.table(&operation.table) else {
14484                    continue;
14485                };
14486                if operation.upsert
14487                    && self.visible_row(table, &operation.row_id)?.is_none()
14488                    && operation.presented_values(table).is_some_and(|values| {
14489                        table
14490                            .columns
14491                            .iter()
14492                            .all(|column| values.contains_key(&column.name))
14493                    })
14494                {
14495                    let key = serde_json::to_string(&(&operation.table, &operation.row_id))
14496                        .expect("row key serialization");
14497                    if let Some(Value::Object(values)) = initial.get(&key) {
14498                        self.apply_outbox_ops(&[OutboxOp {
14499                            values: Some(values.clone()),
14500                            ..operation.clone()
14501                        }])?;
14502                    }
14503                }
14504            }
14505            self.apply_outbox_ops(commit.ops.iter().filter(replays))?;
14506        }
14507        self.apply_outbox_ops(
14508            self.outbox
14509                .iter()
14510                .flat_map(|commit| &commit.ops)
14511                .filter(replays),
14512        )
14513    }
14514
14515    /// §7.1 replay: every operation is applied over the current visible
14516    /// state. An operation that no longer applies (a server row now holds its
14517    /// unique value) stays pending and invisible until a later replay admits
14518    /// it or the server answers its push.
14519    fn apply_outbox_ops<'a>(
14520        &self,
14521        ops: impl IntoIterator<Item = &'a OutboxOp>,
14522    ) -> Result<(), String> {
14523        #[cfg(feature = "bench-internals")]
14524        let mut phase = self.benchmark_phases.start(Phase::PendingReplay);
14525        for op in ops {
14526            #[cfg(feature = "bench-internals")]
14527            if let Some(phase) = &mut phase {
14528                phase.unit();
14529            }
14530            if op.upsert {
14531                if let Some((table, values)) = self
14532                    .schema
14533                    .table(&op.table)
14534                    .filter(|table| table.indexes.iter().any(|index| index.unique))
14535                    .and_then(|table| Some((table, op.presented_values(table)?)))
14536                {
14537                    let mut intended: Map<String, Value> = self
14538                        .visible_row(table, &op.row_id)?
14539                        .map(|(row, _)| {
14540                            table
14541                                .columns
14542                                .iter()
14543                                .zip(&row)
14544                                .map(|(column, value)| {
14545                                    (column.name.clone(), column_value_to_json(value))
14546                                })
14547                                .collect()
14548                        })
14549                        .unwrap_or_default();
14550                    intended.extend(values.into_owned());
14551                    if !self.unique_conflicts(table, &intended, false)?.is_empty() {
14552                        continue;
14553                    }
14554                }
14555            }
14556            self.apply_outbox_op(op)?;
14557        }
14558        Ok(())
14559    }
14560
14561    fn apply_outbox_op(&self, op: &OutboxOp) -> Result<(), String> {
14562        let Some(table) = self.schema.table(&op.table) else {
14563            return Ok(());
14564        };
14565        let visible = visible_table(&table.name);
14566        if !op.upsert {
14567            let sql = format!("DELETE FROM {visible} WHERE {}", row_id_predicate(table));
14568            self.conn
14569                .prepare_cached(&sql)
14570                .and_then(|mut statement| statement.execute(rusqlite::params![op.row_id]))
14571                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14572            return Ok(());
14573        }
14574        // §7.1: an insert-intent operation that lacks a non-nullable column
14575        // cannot encode; it stays invisible until the send-time prepass drops
14576        // it as sync.outbox_incompatible (§7.4.4).
14577        let Some(values) = op.presented_values(table) else {
14578            return Ok(());
14579        };
14580        // §7.1: the overlay applies the operation's PRESENT columns
14581        // over the current local row. A partial operation over an
14582        // absent local row leaves it absent — the server answers it
14583        // with sync.row_deleted or sync.row_missing (§6.2). An
14584        // insert-intent operation presents every column.
14585        let full = table
14586            .columns
14587            .iter()
14588            .all(|column| values.contains_key(&column.name));
14589        let local = self.visible_row(table, &op.row_id)?;
14590        if local.is_none() && !full {
14591            return Ok(());
14592        }
14593        let mut row: Row = Vec::with_capacity(table.columns.len());
14594        for (index, column) in table.columns.iter().enumerate() {
14595            let incoming = match values.get(&column.name) {
14596                Some(raw) => json_to_column_value(
14597                    if raw.get("$bytes").is_some()
14598                        && table
14599                            .encrypted_columns
14600                            .iter()
14601                            .any(|encrypted| encrypted.index == index)
14602                    {
14603                        &table.wire_columns[index]
14604                    } else {
14605                        column
14606                    },
14607                    Some(raw),
14608                ),
14609                None => Ok(local
14610                    .as_ref()
14611                    .and_then(|(values, _)| values.get(index).cloned())
14612                    .flatten()),
14613            };
14614            row.push(incoming.map_err(|_| {
14615                "sync.local_corrupt: persisted optimistic row value is invalid".to_owned()
14616            })?);
14617        }
14618        let version = local.as_ref().map_or(-1, |(_, version)| *version);
14619        self.write_row(&visible, &table.name, &row, version, None)
14620            .map(|_| ())
14621            .map_err(|error| {
14622                if error.starts_with("UNIQUE constraint failed:") {
14623                    "sync.constraint_violation: local write violates a unique constraint".to_owned()
14624                } else {
14625                    error
14626                }
14627            })
14628    }
14629
14630    /// Whether the row is present in the overlay. Existence reads only the
14631    /// key: locked encrypted values stay opaque, and decoding the complete row
14632    /// would reject a valid plain write.
14633    fn visible_row_exists(&self, table: &TableSchema, row_id: &str) -> Result<bool, String> {
14634        self.conn
14635            .query_row(
14636                &format!(
14637                    "SELECT EXISTS(SELECT 1 FROM {} WHERE {})",
14638                    visible_table(&table.name),
14639                    row_id_predicate(table)
14640                ),
14641                rusqlite::params![row_id],
14642                |row| row.get(0),
14643            )
14644            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))
14645    }
14646
14647    /// §5.11: a sealed row is read-only; a write could otherwise send NULL
14648    /// over ciphertext this device cannot see.
14649    fn refuse_sealed_row(&self, table: &TableSchema, row_id: &str) -> Result<(), ClientError> {
14650        if !table.has_encrypted_columns() {
14651            return Ok(());
14652        }
14653        let key_id: Option<String> = self
14654            .conn
14655            .query_row(
14656                &format!(
14657                    "SELECT \"_sync_sealed_key\" FROM {} WHERE {}",
14658                    visible_table(&table.name),
14659                    row_id_predicate(table)
14660                ),
14661                rusqlite::params![row_id],
14662                |row| row.get(0),
14663            )
14664            .optional()
14665            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
14666            .flatten();
14667        match key_id {
14668            None => Ok(()),
14669            Some(key_id) => Err(ClientError {
14670                code: "client.encryption_key_missing".to_owned(),
14671                message: "the row is sealed under a key this device does not hold".to_owned(),
14672                details: Some(json!({ "table": table.name, "keyId": key_id })),
14673                retryable: false,
14674            }),
14675        }
14676    }
14677
14678    /// §5.11 reveal: decrypt every sealed base row whose envelope keys the
14679    /// keyring now holds into its columns and clear both reserved columns,
14680    /// one change batch per table. `client.decrypt_failed` fails the caller.
14681    fn reveal_sealed_rows(&mut self) -> Result<(), TransportError> {
14682        let storage = |message: String| TransportError::new("storage.failed", message);
14683        let tables: Vec<TableSchema> = self
14684            .schema
14685            .tables
14686            .iter()
14687            .filter(|table| table.has_encrypted_columns())
14688            .cloned()
14689            .collect();
14690        for table in &tables {
14691            let base = base_table(&table.name);
14692            let pk = quote_ident(&table.primary_key);
14693            let sealed: Vec<(SqlValue, i64, String)> = self
14694                .conn
14695                .prepare_cached(&format!(
14696                    "SELECT {pk}, \"_syncular_version\", \"_sync_sealed\" FROM {base} WHERE \"_sync_sealed_key\" IS NOT NULL"
14697                ))
14698                .and_then(|mut statement| {
14699                    statement
14700                        .query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))?
14701                        .collect()
14702                })
14703                .map_err(|error| storage(Self::sqlite_failure(&self.storage_failure, error)))?;
14704            let mut revealed = Vec::new();
14705            for (key, version, envelopes) in sealed {
14706                if let Some(row) =
14707                    crate::values::reveal_sealed_row(table, &envelopes, &self.encryption)?
14708                {
14709                    revealed.push((key, version, row));
14710                }
14711            }
14712            if revealed.is_empty() {
14713                continue;
14714            }
14715            self.begin_observation("syncular_reveal").map_err(storage)?;
14716            let outcome = (|| {
14717                let assignments = table
14718                    .encrypted_columns
14719                    .iter()
14720                    .map(|enc| format!("{}=?", quote_ident(&table.columns[enc.index].name)))
14721                    .collect::<Vec<_>>()
14722                    .join(",");
14723                let mut statement = self
14724                    .conn
14725                    .prepare_cached(&format!(
14726                        "UPDATE {base} SET {assignments},\"_sync_sealed_key\"=NULL,\"_sync_sealed\"=NULL WHERE {pk}=? AND \"_syncular_version\"=?"
14727                    ))
14728                    .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14729                for (key, version, row) in &revealed {
14730                    let mut params = table
14731                        .encrypted_columns
14732                        .iter()
14733                        .map(|enc| owned_sql_value(RowParam::Cell(&row[enc.index])))
14734                        .collect::<Result<Vec<_>, _>>()?;
14735                    params.push(key.clone());
14736                    params.push(SqlValue::Integer(*version));
14737                    statement
14738                        .execute(rusqlite::params_from_iter(params))
14739                        .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14740                }
14741                drop(statement);
14742                self.overlay_dirty.table(&table.name);
14743                self.rebuild_overlay()?;
14744                let mut batch = ChangeAccumulator::default();
14745                batch.table(&table.name);
14746                self.finish_observation("syncular_reveal", batch)
14747            })();
14748            if outcome.is_err() {
14749                self.rollback_observation("syncular_reveal");
14750            }
14751            outcome.map_err(storage)?;
14752        }
14753        Ok(())
14754    }
14755
14756    /// The visible (optimistic) row's values plus version, or `None` when the
14757    /// row is absent from the overlay.
14758    fn visible_row(&self, table: &TableSchema, row_id: &str) -> Result<Option<(Row, i64)>, String> {
14759        self.stored_row(table, row_id, false)
14760    }
14761
14762    fn stored_row(
14763        &self,
14764        table: &TableSchema,
14765        row_id: &str,
14766        base: bool,
14767    ) -> Result<Option<(Row, i64)>, String> {
14768        let sql = format!(
14769            "SELECT * FROM {} WHERE {}",
14770            if base {
14771                base_table(&table.name)
14772            } else {
14773                visible_table(&table.name)
14774            },
14775            row_id_predicate(table)
14776        );
14777        let mut stmt = self
14778            .conn
14779            .prepare_cached(&sql)
14780            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14781        let mut rows = stmt
14782            .query(rusqlite::params![row_id])
14783            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14784        let Some(row) = rows
14785            .next()
14786            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?
14787        else {
14788            return Ok(None);
14789        };
14790        let mut values = Vec::with_capacity(table.columns.len());
14791        for (index, column) in table.columns.iter().enumerate() {
14792            let raw = row
14793                .get_ref(index)
14794                .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14795            if let rusqlite::types::ValueRef::Blob(bytes) = raw {
14796                if table
14797                    .encrypted_columns
14798                    .iter()
14799                    .any(|encrypted| encrypted.index == index)
14800                {
14801                    values.push(Some(ColumnValue::Bytes(bytes.to_vec())));
14802                    continue;
14803                }
14804            }
14805            let json = sql_ref_to_json(column, raw);
14806            values.push(json_to_column_value(column, Some(&json)).map_err(|_| {
14807                "sync.local_corrupt: persisted local row value is invalid".to_owned()
14808            })?);
14809        }
14810        let version: i64 = row
14811            .get(table.columns.len())
14812            .map_err(|error| Self::sqlite_failure(&self.storage_failure, error))?;
14813        Ok(Some((values, version)))
14814    }
14815
14816    // -- realtime (§8) ---------------------------------------------------------------
14817
14818    /// §8.8: the configured realtime policy.
14819    #[must_use]
14820    pub fn realtime_policy(&self) -> RealtimePolicy {
14821        self.realtime_policy
14822    }
14823
14824    /// §8.8: the explicit realtime availability state.
14825    #[must_use]
14826    pub fn realtime_state(&self) -> RealtimeState {
14827        self.realtime_state
14828    }
14829
14830    /// §8.8: set the realtime policy. Refused while the socket is connected:
14831    /// a policy change never silently re-routes an ownership state.
14832    pub fn set_realtime_policy(&mut self, policy: RealtimePolicy) -> Result<(), String> {
14833        if self.realtime_state == RealtimeState::Connected && policy != self.realtime_policy {
14834            return Err(
14835                "sync.invalid_request: disconnect realtime before changing the realtime policy"
14836                    .to_owned(),
14837            );
14838        }
14839        self.realtime_policy = policy;
14840        match policy {
14841            RealtimePolicy::Off => self.set_realtime_state(RealtimeState::Disabled, None),
14842            RealtimePolicy::Required | RealtimePolicy::Optional
14843                if self.realtime_state == RealtimeState::Disabled =>
14844            {
14845                self.set_realtime_state(RealtimeState::Disconnected, None);
14846            }
14847            RealtimePolicy::Required | RealtimePolicy::Optional => {}
14848        }
14849        Ok(())
14850    }
14851
14852    /// Record an availability transition, keeping the reason code bounded and
14853    /// code-like (§7.6) and clearing it where it cannot apply.
14854    fn set_realtime_state(&mut self, state: RealtimeState, reason_code: Option<&str>) {
14855        self.realtime_state = state;
14856        self.realtime_reason_code = reason_code.map(Self::diagnostic_code);
14857        if matches!(state, RealtimeState::Connected | RealtimeState::Disabled) {
14858            self.realtime_reason_code = None;
14859            self.realtime_retry_delay_ms = None;
14860        }
14861    }
14862
14863    #[must_use]
14864    fn realtime_connected(&self) -> bool {
14865        self.realtime_state == RealtimeState::Connected
14866    }
14867
14868    pub fn connect_realtime(&mut self, transport: &mut dyn Transport) -> Result<(), String> {
14869        if self.transport_closed() {
14870            return Err("sync.offline: transport gate is closed".into());
14871        }
14872        if self.realtime_policy == RealtimePolicy::Off {
14873            return Err(
14874                "sync.invalid_request: realtime is off; realtime connect is refused".to_owned(),
14875            );
14876        }
14877        if self.realtime_connected() {
14878            return Ok(());
14879        }
14880        self.realtime_state = RealtimeState::Connecting;
14881        match transport.realtime_connect(&self.client_id) {
14882            Ok(()) => {
14883                self.set_realtime_state(RealtimeState::Connected, None);
14884                Ok(())
14885            }
14886            Err(error) => {
14887                self.set_realtime_state(RealtimeState::Refused, Some(&error.code));
14888                Err(format!("{}: {}", error.code, error.message))
14889            }
14890        }
14891    }
14892
14893    pub fn disconnect_realtime(&mut self, transport: &mut dyn Transport) {
14894        self.cancel_sync_round();
14895        // A deliberately disconnected or policy-disabled client has nothing
14896        // to release; a `lost` socket still does (the host owns the handle).
14897        if self.realtime_state == RealtimeState::Disconnected
14898            || self.realtime_state == RealtimeState::Disabled
14899        {
14900            return;
14901        }
14902        let _ = transport.realtime_close();
14903        self.set_realtime_state(
14904            if self.realtime_policy == RealtimePolicy::Off {
14905                RealtimeState::Disabled
14906            } else {
14907                RealtimeState::Disconnected
14908            },
14909            None,
14910        );
14911        self.presence.clear(); // §8.6.1: presence is per-connection
14912    }
14913
14914    /// §8.8: the host observed the socket end without disconnecting it (a
14915    /// peer close, an I/O error, a failed send; the native transport reports
14916    /// these as `Inbound::Disconnected`). Releases the transport, moves a
14917    /// `Connected` state to `Lost` with the transport's code as the reason, and schedules
14918    /// one background retry intent so the host reconnects and catches up.
14919    pub fn realtime_lost(&mut self, transport: &mut dyn Transport, error: &TransportError) {
14920        if self.realtime_state != RealtimeState::Connected {
14921            return;
14922        }
14923        self.cancel_sync_round();
14924        let _ = transport.realtime_close();
14925        self.set_realtime_state(RealtimeState::Lost, Some(&error.code));
14926        self.realtime_retry_delay_ms = Some(self.schedule_background_retry());
14927        self.presence.clear();
14928    }
14929
14930    /// §8.6.2: publish (or clear, `doc: None`) this client's presence
14931    /// document for `scope_key`. Requires a live socket; the document is
14932    /// ephemeral (lost on disconnect). Authorization is the connection's
14933    /// registration (§8.6.3) — an unheld key is rejected loudly by the
14934    /// server with `presence.forbidden`.
14935    pub fn set_presence(
14936        &mut self,
14937        transport: &mut dyn Transport,
14938        scope_key: &str,
14939        doc: Option<&Value>,
14940    ) -> Result<(), String> {
14941        if self.transport_closed() {
14942            return Err("sync.offline: transport gate is closed".into());
14943        }
14944        if !self.realtime_connected() {
14945            return Err("setPresence requires a connected realtime socket (§8.6)".to_string());
14946        }
14947        let text = encode_presence_publish(scope_key, doc);
14948        transport
14949            .realtime_send(&text)
14950            .map_err(|e| format!("{}: {}", e.code, e.message))
14951    }
14952
14953    /// §8.6: the peers currently present on a scope key (ephemeral).
14954    pub fn presence(&self, scope_key: &str) -> Vec<PresencePeer> {
14955        self.presence
14956            .get(scope_key)
14957            .map(|peers| peers.values().cloned().collect())
14958            .unwrap_or_default()
14959    }
14960
14961    /// §8.6 apply an inbound presence fanout to the local map.
14962    fn apply_presence(
14963        &mut self,
14964        scope_key: String,
14965        kind: Option<PresenceKind>,
14966        actor_id: Option<String>,
14967        client_id: Option<String>,
14968        doc: Option<Value>,
14969        error: Option<String>,
14970    ) {
14971        // A refused publish (§8.6.2) changes no peer; the native host surfaces
14972        // it as a `presence` event carrying the server's `error` code.
14973        if error.is_some() {
14974            return;
14975        }
14976        let (Some(kind), Some(actor_id), Some(client_id)) = (kind, actor_id, client_id) else {
14977            return;
14978        };
14979        let peer_key = format!("{actor_id} {client_id}");
14980        match kind {
14981            PresenceKind::Leave => {
14982                if let Some(peers) = self.presence.get_mut(&scope_key) {
14983                    peers.remove(&peer_key);
14984                    if peers.is_empty() {
14985                        self.presence.remove(&scope_key);
14986                    }
14987                }
14988            }
14989            _ => {
14990                let doc = match doc {
14991                    Some(Value::Object(_)) => doc.unwrap(),
14992                    _ => return,
14993                };
14994                self.presence.entry(scope_key).or_default().insert(
14995                    peer_key,
14996                    PresencePeer {
14997                        actor_id,
14998                        client_id,
14999                        doc,
15000                    },
15001                );
15002            }
15003        }
15004    }
15005
15006    /// Inbound JSON control message (§8.1). Unknown events are tolerated.
15007    pub fn on_realtime_text(&mut self, text: &str) {
15008        if self.stopped || self.transport_closed() || self.security_preflight {
15009            return;
15010        }
15011        match parse_control(text) {
15012            Ok(ControlMessage::Hello { requires_sync, .. }) => {
15013                if requires_sync {
15014                    // §8.1: pull before trusting the socket for continuity.
15015                    self.set_sync_needed(true, true);
15016                }
15017            }
15018            Ok(ControlMessage::Presence {
15019                scope_key,
15020                kind,
15021                actor_id,
15022                client_id,
15023                doc,
15024                error,
15025                ..
15026            }) => {
15027                self.apply_presence(scope_key, kind, actor_id, client_id, doc, error);
15028            }
15029            Ok(ControlMessage::Wake { .. }) => {
15030                // §8.3: any wake-up means "run a pull soon", never data.
15031                self.set_sync_needed(true, true);
15032            }
15033            Ok(ControlMessage::Scopes { .. }) => {
15034                // §3.3/§8.7: the grants changed, so the next `set_window`
15035                // re-arms every revoked value it names. No sync-needed, no round.
15036                self.window_armed.clear();
15037                self.scopes_changed += 1;
15038            }
15039            _ => {}
15040        }
15041    }
15042
15043    /// Inbound binary delta: a complete SSP2 response (§8.2), applied like
15044    /// a pull response per section; an unapplied delta is a wake-up.
15045    /// Mailbox hosts send durable acknowledgements on their I/O executor.
15046    pub fn on_realtime_binary_queued(&mut self, bytes: &[u8]) -> Vec<String> {
15047        let mut transport = crate::round::DownloadResults::default();
15048        self.on_realtime_binary(&mut transport, bytes);
15049        transport.controls
15050    }
15051
15052    /// §8.2: a delta applies exactly like a live section and sets the replica
15053    /// cursor to its `throughSeq`; one at or below the replica cursor is a
15054    /// duplicate. A delta the client does not apply (no live unit, a status
15055    /// other than `active`, a decode or apply failure) is a drop and raises
15056    /// sync-needed.
15057    pub fn on_realtime_binary(&mut self, transport: &mut dyn Transport, bytes: &[u8]) {
15058        if self.stopped || self.transport_closed() || self.security_preflight {
15059            return;
15060        }
15061        #[cfg(feature = "bench-internals")]
15062        let decode_phase = self.benchmark_phases.start(Phase::ResponseDecode);
15063        let message = match decode_message(bytes) {
15064            Ok(m) if m.msg_kind == MsgKind::Response => m,
15065            _ => {
15066                self.set_sync_needed(true, true);
15067                return;
15068            }
15069        };
15070        #[cfg(feature = "bench-internals")]
15071        drop(decode_phase);
15072        // §8.2: a delta's header means what a pull response's header means. A
15073        // schema floor (§1.6) is recorded, stops syncing and applies nothing.
15074        if let Some(Frame::RespHeader {
15075            required_schema_version: Some(required),
15076            latest_schema_version,
15077            ..
15078        }) = message.frames.first()
15079        {
15080            let floor = SchemaFloor {
15081                required_schema_version: Some(*required),
15082                latest_schema_version: *latest_schema_version,
15083            };
15084            if self.set_schema_floor(Some(floor)).is_err() {
15085                self.set_sync_needed(true, true);
15086            }
15087            return;
15088        }
15089        let through = message.frames.iter().find_map(|frame| match frame {
15090            Frame::LiveEnd { through_seq, .. } => Some(*through_seq),
15091            _ => None,
15092        });
15093        let epoch = self.get_meta(LOG_EPOCH_KEY).ok().flatten();
15094        let mut dropped = !matches!(message.frames.first(), Some(Frame::RespHeader {
15095                reset_required: false,
15096                log_epoch,
15097                ..
15098            }) if Some(log_epoch) == epoch.as_ref());
15099        let mut applied: Option<i64> = None;
15100        dropped |= self.begin_coalesced_apply().is_err();
15101        let mut receivers: Option<Vec<UnitRecord>> = None;
15102        for frame in message.frames {
15103            if dropped {
15104                break;
15105            }
15106            match frame {
15107                Frame::LiveStart { status, .. } => {
15108                    let Ok(cursor) = self.stored(replica_cursor(&self.conn)) else {
15109                        dropped = true;
15110                        break;
15111                    };
15112                    if status != LiveStatus::Active || cursor < 0 {
15113                        dropped = true;
15114                    } else if !through.is_some_and(|through| through <= cursor) {
15115                        // A catching-up unit receives no delta (§8.2).
15116                        receivers = self.stored(load_units(&self.conn)).ok().map(|units| {
15117                            units
15118                                .into_iter()
15119                                .filter(|unit| {
15120                                    unit.status == UnitStatus::Active
15121                                        && unit.echo.is_some()
15122                                        && unit.cursor.is_none()
15123                                })
15124                                .collect()
15125                        });
15126                        dropped = receivers.is_none();
15127                    }
15128                }
15129                Frame::Commit {
15130                    commit_seq,
15131                    tables,
15132                    changes,
15133                    ..
15134                } => {
15135                    let Some(receivers) = receivers.clone() else {
15136                        continue;
15137                    };
15138                    dropped = self
15139                        .apply_live_commit(
15140                            &receivers,
15141                            &tables,
15142                            changes,
15143                            commit_seq,
15144                            AppliedServerCommitSource::Delta,
15145                        )
15146                        .is_err();
15147                }
15148                Frame::LiveEnd { through_seq, .. } if receivers.is_some() => {
15149                    dropped = self
15150                        .set_meta(REPLICA_CURSOR_KEY, &through_seq.to_string())
15151                        .is_err();
15152                    applied = Some(through_seq);
15153                }
15154                Frame::Error { .. } => dropped = true,
15155                _ => {}
15156            }
15157        }
15158        // §1.4 rule 4: the ack follows the COMMIT. A failed COMMIT restored
15159        // the replica cursor, so the delta counts as a drop.
15160        if self.finish_coalesced_apply().is_err() || dropped {
15161            applied = None;
15162            dropped = true;
15163        }
15164        if let Some(cursor) = applied {
15165            // §8.2 ack point: the delta's throughSeq.
15166            let ack = format!("{{\"type\":\"ack\",\"cursor\":{cursor}}}");
15167            let _ = transport.realtime_send(&ack);
15168        }
15169        if dropped {
15170            self.set_sync_needed(true, true);
15171        }
15172    }
15173
15174    /// §8.2 ack point after a pull round on a live connection: the replica
15175    /// cursor while it is at least `0`.
15176    fn ack_after_pull(&mut self, transport: &mut dyn Transport) {
15177        if !self.realtime_connected() {
15178            return;
15179        }
15180        if let Ok(cursor @ 0..) = self.stored(replica_cursor(&self.conn)) {
15181            let ack = format!("{{\"type\":\"ack\",\"cursor\":{cursor}}}");
15182            let _ = transport.realtime_send(&ack);
15183        }
15184    }
15185}
15186
15187#[cfg(test)]
15188mod previous_version_wiring_tests;
15189
15190#[cfg(test)]
15191mod identity_tests;
15192
15193#[cfg(test)]
15194mod insert_intent_tests;
15195
15196#[cfg(test)]
15197mod robustness_tests;
15198
15199#[cfg(test)]
15200mod range_image_tests;