Skip to main content

tauri_plugin_syncular/
lib.rs

1//! # tauri-plugin-syncular — a native syncular instance inside the Tauri process
2//!
3//! A NATIVE syncular client (the Rust `syncular-client` core, consumed
4//! DIRECTLY — no FFI) runs in the Tauri host process and is exposed to the
5//! webview as Tauri commands + events. The JS bridge (`@syncular/tauri`)
6//! implements the same `SyncClientLike` interface the React package
7//! normalizes, so the hooks work unchanged — the fourth host of one interface
8//! after direct / worker-leader / follower.
9//!
10//! The webview does not run JS syncular. Webview OPFS is eviction-prone and inconsistent across
11//! WKWebView/webkitgtk; the Rust core gives a real file DB and native perf.
12//!
13//! ## The surface (mirrors the FFI / conformance shim)
14//!
15//! - `syncular_command(command_json)` — the WHOLE command surface in one
16//!   command (`{"method","params"}`), dispatched through the shared
17//!   `syncular-command` router (the plugin is its THIRD consumer, so the
18//!   surface stays conformance-locked).
19//! - `syncular_query(sql, params)` — the React live-query fast path (arbitrary
20//!   read-only SQL); routed through the same `query` command.
21//! - `syncular_query_snapshot(sql, params, coverage)` — atomic reactive reads
22//!   on an independent read-only SQLite connection for file-backed clients.
23//! - the `events` IPC channel the creating webview passes in `create` — exact
24//!   revisioned `change` batches plus ephemeral
25//!   `presence` and `scopes-changed` (§8.7); command/realtime sync intents stay inside the event-driven
26//!   owner loop.
27//!
28//! ## Thread-safety, honestly
29//!
30//! [`core::SyncularCore`] owns a rusqlite connection and is NOT `Sync`. One
31//! owning thread holds the mutable client; every command arrives over a mailbox
32//! (mpsc). The background host loop (§8.4 wake-driven `syncUntilIdle` with
33//! deadlines) runs on that thread. File-backed clients add one read owner with
34//! an independent read-only SQLite connection for snapshots, so network work
35//! cannot block local views while the mutable client remains single-owned.
36
37use std::collections::BTreeSet;
38use std::str::FromStr;
39use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender};
40use std::sync::{Arc, Condvar, Mutex};
41use std::time::{Duration, Instant};
42
43use serde_json::{json, Value};
44use tauri::ipc::{Channel, JavaScriptChannelId};
45use tauri::plugin::{Builder, TauriPlugin};
46use tauri::{Manager, RunEvent, Runtime};
47
48pub mod core;
49pub mod transport;
50
51use core::SyncularCore;
52use syncular_client::{
53    FileQuerySnapshotReader, QueryReadFailure, WindowCoverage, MAX_DIAGNOSTIC_QUERY_FAILURES,
54};
55
56/// Plugin configuration. Passed to [`init`]; every field is optional except a
57/// caller almost always wants a `base_url` (for real network sync) and a
58/// `database_dir` or `db_path` (for persistence — defaults to an in-memory core
59/// if both are absent).
60#[derive(Debug, Clone)]
61pub struct SyncularConfig {
62    /// Server base URL for the native HTTP+WS transport (needs the
63    /// `native-transport` feature). Absent → client-local only.
64    pub base_url: Option<String>,
65    /// Path of the SPEC §12 local authority's own SQLite file, never the
66    /// replica's `db_path`. With it set, sync rounds run against the in-process
67    /// authority until `attachLocalAuthority` completes, then against
68    /// `base_url`. Absent → no local authority.
69    pub local_authority_path: Option<String>,
70    /// Optional realtime WS URL; derived from `base_url` when absent.
71    pub ws_url: Option<String>,
72    /// Extra request headers (auth, actor/project ids) as (name, value).
73    pub headers: Vec<(String, String)>,
74    /// Per-request network deadline in milliseconds. `None` (the default)
75    /// leaves requests unbounded, matching the reference HTTP binding.
76    pub request_timeout_ms: Option<u64>,
77    /// One monotonic deadline for a whole sync round (uploads, continuations,
78    /// main request, and every segment fetch) in milliseconds. `None` (the
79    /// default) leaves the round unbounded.
80    pub round_deadline_ms: Option<u64>,
81    /// Largest request body the transport will send, in bytes. `None` (the
82    /// default) is unbounded.
83    pub max_request_bytes: Option<u64>,
84    /// Largest decoded (post-decompression) response body, in bytes. `None`
85    /// (the default) is unbounded.
86    pub max_response_bytes: Option<u64>,
87    /// Redirect handling: `"deny"` (the default) refuses every redirect so
88    /// configured credentials, URL userinfo, and signed capabilities never
89    /// replay to another origin; `"follow"` follows a redirect only for a
90    /// request with none of those, and still refuses a credential-bearing
91    /// request.
92    pub redirects: Option<String>,
93    /// Interval the server sends realtime heartbeats at, in milliseconds.
94    /// `None` (the default) means 30000. Twice this interval of silence after
95    /// the first heartbeat closes the socket as lost.
96    pub realtime_heartbeat_ms: Option<u64>,
97    /// On-disk SQLite path a `create` opens when it names no database. Absent →
98    /// in-memory (nothing survives a restart). Apps usually set this to a file
99    /// under the app-data dir; see [`init`].
100    pub db_path: Option<String>,
101    /// Directory of the named databases. A `create` that carries `database`
102    /// (for example one replica per signed-in actor) opens
103    /// `<database_dir>/<database>.db`; the plugin creates the directory. The
104    /// webview names a database and never supplies a path.
105    pub database_dir: Option<String>,
106    /// Run the background host loop (§8.4). Default true.
107    pub auto_sync: bool,
108    /// Native app-approved table/column ceiling. Webview create selects scopes
109    /// and a subset; raw IPC cannot expand this policy.
110    pub authority_columns: std::collections::BTreeMap<String, Vec<String>>,
111}
112
113impl Default for SyncularConfig {
114    fn default() -> Self {
115        Self {
116            base_url: None,
117            local_authority_path: None,
118            ws_url: None,
119            headers: Vec::new(),
120            request_timeout_ms: None,
121            round_deadline_ms: None,
122            max_request_bytes: None,
123            max_response_bytes: None,
124            redirects: None,
125            realtime_heartbeat_ms: None,
126            db_path: None,
127            database_dir: None,
128            auto_sync: true,
129            authority_columns: std::collections::BTreeMap::new(),
130        }
131    }
132}
133
134impl SyncularConfig {
135    /// Build the JSON config the core's transport reads.
136    fn to_transport_json(&self) -> Value {
137        let mut map = serde_json::Map::new();
138        if let Some(base) = &self.base_url {
139            map.insert("baseUrl".to_owned(), Value::from(base.clone()));
140        }
141        if let Some(path) = &self.local_authority_path {
142            map.insert("localAuthorityPath".to_owned(), Value::from(path.clone()));
143        }
144        if let Some(ws) = &self.ws_url {
145            map.insert("wsUrl".to_owned(), Value::from(ws.clone()));
146        }
147        if !self.headers.is_empty() {
148            let headers: serde_json::Map<String, Value> = self
149                .headers
150                .iter()
151                .map(|(k, v)| (k.clone(), Value::from(v.clone())))
152                .collect();
153            map.insert("headers".to_owned(), Value::Object(headers));
154        }
155        if let Some(ms) = self.request_timeout_ms {
156            map.insert("requestTimeoutMs".to_owned(), Value::from(ms));
157        }
158        if let Some(ms) = self.round_deadline_ms {
159            map.insert("roundDeadlineMs".to_owned(), Value::from(ms));
160        }
161        if let Some(bytes) = self.max_request_bytes {
162            map.insert("maxRequestBytes".to_owned(), Value::from(bytes));
163        }
164        if let Some(bytes) = self.max_response_bytes {
165            map.insert("maxResponseBytes".to_owned(), Value::from(bytes));
166        }
167        if let Some(redirects) = &self.redirects {
168            map.insert("redirects".to_owned(), Value::from(redirects.clone()));
169        }
170        if let Some(ms) = self.realtime_heartbeat_ms {
171            map.insert("realtimeHeartbeatMs".to_owned(), Value::from(ms));
172        }
173        Value::Object(map)
174    }
175}
176
177/// A request posted to the owning thread's mailbox. Each carries a one-shot
178/// reply channel; the Tauri command blocks on it (`spawn_blocking`-friendly).
179enum Request {
180    Command {
181        command: Value,
182        reply: Sender<Value>,
183    },
184    Query {
185        sql: String,
186        params: Value,
187        reply: Sender<Value>,
188    },
189    /// Replace the transport's request headers. Header state
190    /// lives on the core-owned transport, so mutation rides the same mailbox
191    /// as every other access — the one-owning-thread invariant holds.
192    SetHeaders {
193        headers: Vec<(String, String)>,
194        reply: Sender<Value>,
195    },
196    /// Native realtime reader wake; contains no data (the transport buffer does).
197    TransportWake,
198    RoundFinished(
199        Box<(
200            syncular_client::CompletedSyncRound,
201            crate::transport::HostTransport,
202        )>,
203    ),
204    /// §7.6: an owned read-sidecar failure, or the first success after one.
205    QueryRead {
206        id: String,
207        tables: Vec<String>,
208        failure: Option<QueryReadFailure>,
209    },
210    #[cfg(test)]
211    Block {
212        duration: Duration,
213        entered: Sender<()>,
214    },
215    Shutdown,
216}
217
218/// Latency-critical reads use a second, read-only SQLite connection. This
219/// mailbox is deliberately independent from [`Request`]: a network round on
220/// the mutable owner must never head-of-line-block a local UI snapshot.
221enum ReadRequest {
222    QuerySnapshot {
223        sql: String,
224        params: Vec<Value>,
225        coverage: Vec<WindowCoverage>,
226        owner: Option<(String, Vec<String>)>,
227        reply: Sender<Value>,
228    },
229    /// §7.5: one atomic read over the shared primitive, carrying every
230    /// requested statement, catch-up state, and delivery.
231    SnapshotRead {
232        statements: Vec<(String, Vec<Value>)>,
233        coverage: Vec<WindowCoverage>,
234        units: Vec<String>,
235        commit_ids: Vec<String>,
236        owner: Option<(String, Vec<String>)>,
237        reply: Sender<Value>,
238    },
239    /// Stop the reader thread.
240    Shutdown,
241}
242
243/// The `{error: {code, message, details?, retryable?}}` envelope the read
244/// sidecar returns. `retryable` mirrors the §7.5 write-failure classification
245/// so a `SQLITE_BUSY` read keeps `client.storage_busy` retryability.
246fn read_failure_json(failure: syncular_client::QueryReadFailure) -> Value {
247    json!({
248        "error": {
249            "code": failure.code.unwrap_or("client.failed"),
250            "message": failure.message,
251            "details": failure.details(),
252            "retryable": failure.retryable(),
253        }
254    })
255}
256
257/// The plugin's managed state: the mailbox sender the commands post to. Wrapped
258/// in a `Mutex` only to be `Sync` for Tauri state (the `Sender` is `Send`).
259struct SyncularState {
260    sender: Mutex<Sender<Request>>,
261    /// The snapshot reader of the file database the last successful `create`
262    /// opened; `None` before it, after `shutdown`, and for an in-memory client.
263    /// `create` and `shutdown` hold this lock until their reply, so the reader
264    /// always reads the database the owner has open.
265    reader: Mutex<Option<Sender<ReadRequest>>>,
266    config: SyncularConfig,
267    security_gate: SecurityGate,
268    /// The IPC channel of the webview whose `create` opened the client. Only
269    /// that webview receives the client's events.
270    events: Arc<Mutex<Option<Channel<Value>>>>,
271    /// The label of the webview whose `create` succeeded last. The app has one
272    /// client, so every other command from another webview is refused.
273    owner: Mutex<Option<String>>,
274}
275
276struct SecurityGateState {
277    preflight: bool,
278    active_reads: usize,
279}
280
281struct SecurityGate {
282    state: Mutex<SecurityGateState>,
283    idle: Condvar,
284}
285
286struct SecurityReadGuard<'a> {
287    gate: &'a SecurityGate,
288}
289
290impl SecurityGate {
291    fn new_preflight() -> Self {
292        Self {
293            state: Mutex::new(SecurityGateState {
294                preflight: true,
295                active_reads: 0,
296            }),
297            idle: Condvar::new(),
298        }
299    }
300
301    fn begin_preflight(&self) -> Result<(), String> {
302        let mut state = self
303            .state
304            .lock()
305            .map_err(|_| "syncular security gate poisoned".to_owned())?;
306        state.preflight = true;
307        while state.active_reads > 0 {
308            state = self
309                .idle
310                .wait(state)
311                .map_err(|_| "syncular security gate poisoned".to_owned())?;
312        }
313        Ok(())
314    }
315
316    fn activate(&self) -> Result<(), String> {
317        let mut state = self
318            .state
319            .lock()
320            .map_err(|_| "syncular security gate poisoned".to_owned())?;
321        state.preflight = false;
322        Ok(())
323    }
324
325    fn enter_read(&self) -> Result<SecurityReadGuard<'_>, Value> {
326        let mut state = self
327            .state
328            .lock()
329            .map_err(|_| client_error("syncular security gate poisoned"))?;
330        if state.preflight {
331            return Err(security_preflight_error());
332        }
333        state.active_reads += 1;
334        Ok(SecurityReadGuard { gate: self })
335    }
336}
337
338impl Drop for SecurityReadGuard<'_> {
339    fn drop(&mut self) {
340        let Ok(mut state) = self.gate.state.lock() else {
341            return;
342        };
343        state.active_reads = state.active_reads.saturating_sub(1);
344        if state.active_reads == 0 {
345            self.gate.idle.notify_all();
346        }
347    }
348}
349
350impl SyncularState {
351    /// `Err` is the structured reply for a webview that does not own the
352    /// client. Before the first `create` nobody owns it, and the router
353    /// answers with its own no-client error.
354    fn require_owner(&self, label: &str) -> Result<(), Value> {
355        let owner = self
356            .owner
357            .lock()
358            .map_err(|_| client_error("syncular owner poisoned"))?;
359        match owner.as_deref() {
360            Some(owner) if owner != label => Err(json!({ "error": {
361                "code": "sync.client_owned_by_another_webview",
362                "message": "the native client belongs to another webview"
363            } })),
364            _ => Ok(()),
365        }
366    }
367
368    fn send(&self, request: Request) -> Result<(), String> {
369        self.sender
370            .lock()
371            .map_err(|_| "syncular mailbox poisoned".to_owned())?
372            .send(request)
373            .map_err(|_| "the syncular core thread has stopped".to_owned())
374    }
375
376    fn reader(&self) -> Result<Option<Sender<ReadRequest>>, String> {
377        Ok(self
378            .reader
379            .lock()
380            .map_err(|_| "syncular read mailbox poisoned".to_owned())?
381            .clone())
382    }
383}
384
385fn spawn_reader(path: String, owner_tx: Sender<Request>) -> Result<Sender<ReadRequest>, String> {
386    let (reader_tx, reader_rx) = std::sync::mpsc::channel::<ReadRequest>();
387    std::thread::Builder::new()
388        .name("syncular-read".to_owned())
389        .spawn(move || run_reader_thread(path, reader_rx, owner_tx))
390        .map_err(|e| format!("failed to spawn syncular read thread: {e}"))?;
391    Ok(reader_tx)
392}
393
394/// One owner the read sidecar has reported a failure for, carrying exactly the
395/// fields the owning core journals it under (`record_query_read` compares
396/// tables, code, and sqlite code before re-ordering an entry).
397struct ReportedQueryFailure {
398    id: String,
399    tables: Vec<String>,
400    code: &'static str,
401    sqlite_code: Option<i32>,
402}
403
404/// §7.6: report an owned read to the owner mailbox only on a failure
405/// transition: every failure, plus the first success that clears one, so a
406/// clean success loop enqueues nothing and the reader never waits for the owner
407/// to catch up on an earlier message. The mirror follows the core journal's
408/// retention: the tables are normalized the same way, an unchanged failure
409/// signature keeps its position, and passing `MAX_DIAGNOSTIC_QUERY_FAILURES`
410/// evicts the oldest id, so no owner id is kept without a bound.
411fn report_owned_read(
412    reported: &mut Vec<ReportedQueryFailure>,
413    owner_tx: &Sender<Request>,
414    id: String,
415    tables: Vec<String>,
416    failure: Option<QueryReadFailure>,
417) {
418    let position = reported.iter().position(|entry| entry.id == id);
419    let Some(failure) = failure else {
420        // Only the success that clears an outstanding failure is a transition.
421        let Some(index) = position else {
422            return;
423        };
424        reported.remove(index);
425        let _ = owner_tx.send(Request::QueryRead {
426            id,
427            tables,
428            failure: None,
429        });
430        return;
431    };
432    let code = failure.code.unwrap_or("client.query_failed");
433    let sqlite_code = failure.sqlite_code;
434    let signature: Vec<String> = BTreeSet::from_iter(tables.iter().cloned())
435        .into_iter()
436        .collect();
437    let unchanged = position.is_some_and(|index| {
438        let entry = &reported[index];
439        entry.tables == signature && entry.code == code && entry.sqlite_code == sqlite_code
440    });
441    if !unchanged {
442        if let Some(index) = position {
443            reported.remove(index);
444        }
445        reported.push(ReportedQueryFailure {
446            id: id.clone(),
447            tables: signature,
448            code,
449            sqlite_code,
450        });
451        if reported.len() > MAX_DIAGNOSTIC_QUERY_FAILURES {
452            reported.remove(0);
453        }
454    }
455    let _ = owner_tx.send(Request::QueryRead {
456        id,
457        tables,
458        failure: Some(failure),
459    });
460}
461
462fn run_reader_thread(path: String, rx: Receiver<ReadRequest>, owner_tx: Sender<Request>) {
463    let mut reader = FileQuerySnapshotReader::new(path);
464    // The read sidecar's own reports, bounded like the core journal.
465    let mut reported: Vec<ReportedQueryFailure> = Vec::new();
466    while let Ok(request) = rx.recv() {
467        match request {
468            ReadRequest::QuerySnapshot {
469                sql,
470                params,
471                coverage,
472                owner,
473                reply,
474            } => {
475                let result = reader.query_snapshot(&sql, &params, &coverage);
476                let value = match &result {
477                    Ok(snapshot) => json!({ "result": snapshot }),
478                    Err(failure) => read_failure_json(failure.clone()),
479                };
480                if let Some((id, tables)) = owner {
481                    report_owned_read(&mut reported, &owner_tx, id, tables, result.err());
482                }
483                let _ = reply.send(value);
484            }
485            ReadRequest::SnapshotRead {
486                statements,
487                coverage,
488                units,
489                commit_ids,
490                owner,
491                reply,
492            } => {
493                let request = syncular_client::SnapshotReadRequest {
494                    statements: statements
495                        .iter()
496                        .map(|(sql, params)| syncular_client::SnapshotStatement { sql, params })
497                        .collect(),
498                    coverage: &coverage,
499                    units,
500                    commit_ids,
501                };
502                let result = reader.snapshot_read(&request);
503                let value = match &result {
504                    Ok(read) => json!({ "result": read }),
505                    Err(failure) => read_failure_json(failure.clone()),
506                };
507                // §7.6: the same owner-failure bookkeeping the QuerySnapshot
508                // read uses, so a named owner gets one diagnostic path.
509                if let Some((id, tables)) = owner {
510                    report_owned_read(&mut reported, &owner_tx, id, tables, result.err());
511                }
512                let _ = reply.send(value);
513            }
514            ReadRequest::Shutdown => return,
515        }
516    }
517}
518
519/// The owning thread: builds the core, then loops over the mailbox and the
520/// background host policy. `emit` pushes drained events onto the Tauri channel.
521/// One serialized I/O executor per owner. It never owns a SQLite connection.
522enum NetworkWork {
523    Round(
524        Box<syncular_client::PreparedSyncRound>,
525        crate::transport::HostTransport,
526    ),
527    Controls(Vec<String>, crate::transport::HostTransport),
528}
529
530struct RoundRun {
531    reply: Option<Sender<Value>>,
532    until_idle: bool,
533    max_rounds: Option<u32>,
534    /// §7.8 drive bound of an until-idle run: total deadline and per-round bound.
535    timeout_ms: u64,
536    started_at: Instant,
537    spent: u32,
538    aggregate: syncular_client::SyncReport,
539    proof: Option<syncular_client::CurrentBasePreparation>,
540    /// §7.2.2: the decisions pending when this until-idle drive started.
541    decisions: Option<Vec<syncular_client::CurrentBasePreparation>>,
542}
543
544fn run_owner_thread<F>(config: SyncularConfig, tx: Sender<Request>, rx: Receiver<Request>, emit: F)
545where
546    F: Fn(&Value) + Send + Sync + 'static,
547{
548    let emit = std::sync::Arc::new(emit);
549    let wake_tx = tx.clone();
550    let notify: std::sync::Arc<dyn Fn() + Send + Sync> = std::sync::Arc::new(move || {
551        let _ = wake_tx.send(Request::TransportWake);
552    });
553    let mut core = match SyncularCore::new_with_notify(&config.to_transport_json(), Some(notify)) {
554        Ok(core) => core,
555        Err(message) => {
556            // The webview learns of a startup failure as the structured reply
557            // to its `create` (and to every later call), keeping the core's code.
558            let error = syncular_client::ClientError::from(message);
559            let reply = json!({ "error": {
560                "code": error.code,
561                "message": error.message,
562                "details": error.details,
563            } });
564            while let Ok(request) = rx.recv() {
565                match request {
566                    Request::Command { reply: tx, .. }
567                    | Request::Query { reply: tx, .. }
568                    | Request::SetHeaders { reply: tx, .. } => {
569                        let _ = tx.send(reply.clone());
570                    }
571                    Request::Shutdown => return,
572                    _ => {}
573                }
574            }
575            return;
576        }
577    };
578    let progress_emit = emit.clone();
579    core.progress_listener = Some(std::sync::Arc::new(move |progress| {
580        progress_emit(&json!({ "type": "progress", "progress": progress }));
581    }));
582    let (network_tx, network_rx) = std::sync::mpsc::channel();
583    let completed_tx = tx.clone();
584    let network = std::thread::spawn(move || {
585        use syncular_client::Transport;
586        while let Ok(work) = network_rx.recv() {
587            match work {
588                NetworkWork::Round(prepared, mut transport) => {
589                    let completed = (*prepared).exchange(&mut transport);
590                    if completed_tx
591                        .send(Request::RoundFinished(Box::new((completed, transport))))
592                        .is_err()
593                    {
594                        return;
595                    }
596                }
597                NetworkWork::Controls(controls, mut transport) => {
598                    for text in controls {
599                        let _ = transport.realtime_send(&text);
600                    }
601                }
602            }
603        }
604    });
605    let mut active: Option<RoundRun> = None;
606    let mut queued = std::collections::VecDeque::new();
607    let mut background_deadline: Option<Instant> = None;
608    loop {
609        if !core.transport_enabled() {
610            background_deadline = None;
611        }
612        if let Some((controls, transport)) = core.take_controls() {
613            if network_tx
614                .send(NetworkWork::Controls(controls, transport))
615                .is_err()
616            {
617                break;
618            }
619        }
620        // Consume sync intent only while idle. Mutations arriving mid-round
621        // retain their coalesced intent and enter the next captured request.
622        if active.is_none() {
623            if let Some(run) = queued.pop_front() {
624                active = Some(run);
625            } else if config.auto_sync {
626                match core.take_sync_intent() {
627                    syncular_client::SyncIntent::Interactive => {
628                        background_deadline = None;
629                        active = Some(RoundRun {
630                            reply: None,
631                            until_idle: true,
632                            max_rounds: None,
633                            timeout_ms: syncular_client::SyncClient::SYNC_IDLE_TIMEOUT_MS,
634                            started_at: Instant::now(),
635                            spent: 0,
636                            aggregate: Default::default(),
637                            proof: None,
638                            decisions: None,
639                        });
640                    }
641                    syncular_client::SyncIntent::Background { delay_ms } => {
642                        let candidate = Instant::now()
643                            .checked_add(Duration::from_millis(delay_ms))
644                            .unwrap_or_else(Instant::now);
645                        background_deadline = Some(
646                            background_deadline.map_or(candidate, |current| current.min(candidate)),
647                        );
648                    }
649                    syncular_client::SyncIntent::None => {}
650                }
651            }
652            if active
653                .as_ref()
654                .is_some_and(|run| run.until_idle && run.decisions.is_none())
655            {
656                match core.prepare_replacements() {
657                    Ok(decisions) => {
658                        active.as_mut().expect("active run").decisions = Some(decisions)
659                    }
660                    Err(message) => {
661                        if let Some(reply) = active.take().and_then(|run| run.reply) {
662                            let _ = reply.send(
663                                json!({ "result": syncular_client::SyncOutcome::Failed {
664                                details: None,
665                                error_code: "storage.failed".into(),
666                                message,
667                                recommended_action: None,
668                            }.to_json() }),
669                            );
670                        }
671                        continue;
672                    }
673                }
674            }
675            if active.is_some() {
676                match core.prepare_round() {
677                    Ok((mut prepared, transport)) => {
678                        let run = active.as_mut().expect("active run");
679                        if run.until_idle {
680                            prepared.set_idle_deadline(run.timeout_ms, run.spent);
681                        }
682                        run.spent += 1;
683                        if network_tx
684                            .send(NetworkWork::Round(Box::new(prepared), transport))
685                            .is_err()
686                        {
687                            break;
688                        }
689                    }
690                    Err(outcome) => {
691                        if let Some(mut run) = active.take() {
692                            let result = match run.proof.take() {
693                                Some(proof) => json!(core.finish_current_base(proof, *outcome)),
694                                None => outcome.to_json(),
695                            };
696                            if let Some(reply) = run.reply {
697                                let _ = reply.send(json!({ "result": result }));
698                            }
699                        }
700                    }
701                }
702                pump_events(&mut core, &*emit);
703                if active.is_none() {
704                    continue;
705                }
706            }
707        }
708        let request = if active.is_none() {
709            if let Some(deadline) = background_deadline {
710                match rx.recv_timeout(deadline.saturating_duration_since(Instant::now())) {
711                    Ok(request) => request,
712                    Err(RecvTimeoutError::Timeout) => {
713                        background_deadline = None;
714                        queued.push_back(RoundRun {
715                            reply: None,
716                            until_idle: true,
717                            max_rounds: None,
718                            timeout_ms: syncular_client::SyncClient::SYNC_IDLE_TIMEOUT_MS,
719                            started_at: Instant::now(),
720                            spent: 0,
721                            aggregate: Default::default(),
722                            proof: None,
723                            decisions: None,
724                        });
725                        continue;
726                    }
727                    Err(RecvTimeoutError::Disconnected) => break,
728                }
729            } else {
730                match rx.recv() {
731                    Ok(request) => request,
732                    Err(_) => break,
733                }
734            }
735        } else {
736            match rx.recv() {
737                Ok(request) => request,
738                Err(_) => break,
739            }
740        };
741        match request {
742            Request::RoundFinished(completed) => {
743                let (completed, transport) = *completed;
744                let applied = core.apply_round(completed);
745                let (mut outcome, more, bootstrap_advanced) = match applied {
746                    syncular_client::AppliedSyncRound::Continue(prepared) => {
747                        if network_tx
748                            .send(NetworkWork::Round(Box::new(prepared), transport))
749                            .is_err()
750                        {
751                            break;
752                        }
753                        pump_events(&mut core, &*emit);
754                        continue;
755                    }
756                    syncular_client::AppliedSyncRound::Complete {
757                        outcome,
758                        more,
759                        bootstrap_advanced,
760                        ..
761                    } => (outcome, more, bootstrap_advanced),
762                };
763                let Some(mut run) = active.take() else {
764                    continue;
765                };
766                let mut keep_running = false;
767                if run.until_idle {
768                    if let syncular_client::SyncOutcome::Ok(report) = &outcome {
769                        run.aggregate.merge(report);
770                        if bootstrap_advanced && run.max_rounds.is_none() {
771                            run.spent = 0;
772                        }
773                        keep_running = more && core.transport_enabled();
774                        // §7.8: an elapsed round budget or drive deadline
775                        // ends the drive with the aggregate report.
776                        if keep_running
777                            && (run.spent >= run.max_rounds.unwrap_or(20)
778                                || run.started_at.elapsed()
779                                    >= Duration::from_millis(run.timeout_ms))
780                        {
781                            keep_running = false;
782                            outcome = syncular_client::SyncOutcome::BudgetExhausted(
783                                run.aggregate.clone(),
784                            );
785                        } else if !keep_running {
786                            outcome = syncular_client::SyncOutcome::Ok(run.aggregate.clone());
787                            // §7.2.2: a written decision runs another round,
788                            // which pushes it.
789                            match core.settle_replacements(
790                                run.decisions.as_deref().unwrap_or_default(),
791                                &outcome,
792                            ) {
793                                Ok(true) if run.spent >= run.max_rounds.unwrap_or(20) => {
794                                    outcome = syncular_client::SyncOutcome::BudgetExhausted(
795                                        run.aggregate.clone(),
796                                    );
797                                }
798                                Ok(written) => keep_running = written,
799                                Err(message) => {
800                                    outcome = syncular_client::SyncOutcome::Failed {
801                                        details: None,
802                                        error_code: "storage.failed".into(),
803                                        message,
804                                        recommended_action: None,
805                                    };
806                                }
807                            }
808                        }
809                    }
810                }
811                if keep_running {
812                    queued.push_front(run);
813                } else if let Some(reply) = run.reply {
814                    let result = match run.proof.take() {
815                        Some(proof) => json!(core.finish_current_base(proof, outcome)),
816                        None => outcome.to_json(),
817                    };
818                    let _ = reply.send(json!({ "result": result }));
819                } else if matches!(outcome, syncular_client::SyncOutcome::BudgetExhausted(_)) {
820                    // §7.8: an exhausted host drive queues the next drive at once.
821                    queued.push_back(RoundRun {
822                        started_at: Instant::now(),
823                        spent: 0,
824                        aggregate: Default::default(),
825                        decisions: None,
826                        ..run
827                    });
828                }
829                pump_events(&mut core, &*emit);
830            }
831            Request::Command { command, reply } => {
832                let method = command.get("method").and_then(Value::as_str);
833                if matches!(method, Some("sync" | "syncUntilIdle" | "proveCurrentBase"))
834                    && core.transport_enabled()
835                {
836                    let until_idle = method != Some("sync");
837                    let proof = if method == Some("proveCurrentBase") {
838                        let outcome = command.pointer("/params/outcome");
839                        let id = outcome
840                            .and_then(|v| v.get("clientCommitId"))
841                            .and_then(Value::as_str);
842                        let sequence = outcome
843                            .and_then(|v| v.get("sequence"))
844                            .and_then(Value::as_i64);
845                        let (Some(id), Some(sequence)) = (id, sequence) else {
846                            let _ = reply.send(json!({ "error": { "code": "sync.invalid_request", "message": "proveCurrentBase requires an outcome identity", "retryable": false } }));
847                            continue;
848                        };
849                        match core.prepare_current_base(id, sequence) {
850                            Ok(proof) => Some(proof),
851                            Err(proof) => {
852                                let _ = reply.send(json!({ "result": proof }));
853                                continue;
854                            }
855                        }
856                    } else {
857                        None
858                    };
859                    // The shared router ignores `maxRounds` for `sync`; only
860                    // `syncUntilIdle` carries a round budget.
861                    let max_rounds = if until_idle {
862                        match command.pointer("/params/maxRounds") {
863                            None | Some(Value::Null) => None,
864                            Some(value) => match value
865                                .as_u64()
866                                .and_then(|n| u32::try_from(n).ok())
867                                .filter(|n| *n >= 1)
868                            {
869                                Some(n) => Some(n),
870                                None => {
871                                    let _ = reply.send(json!({
872                                        "error": {
873                                            "code": "sync.invalid_request",
874                                            "message": "maxRounds must be a positive integer",
875                                            "retryable": false
876                                        }
877                                    }));
878                                    continue;
879                                }
880                            },
881                        }
882                    } else {
883                        None
884                    };
885                    // `sync` carries no drive bound either.
886                    let timeout_ms = match command.pointer("/params/timeoutMs") {
887                        Some(value) if until_idle && !value.is_null() => match value
888                            .as_u64()
889                            .filter(|ms| *ms >= 1 && i64::try_from(*ms).is_ok())
890                        {
891                            Some(ms) => ms,
892                            None => {
893                                let _ = reply.send(json!({
894                                    "error": {
895                                        "code": "sync.invalid_request",
896                                        "message": "timeoutMs must be a positive integer",
897                                        "retryable": false
898                                    }
899                                }));
900                                continue;
901                            }
902                        },
903                        _ => syncular_client::SyncClient::SYNC_IDLE_TIMEOUT_MS,
904                    };
905                    queued.push_back(RoundRun {
906                        reply: Some(reply),
907                        until_idle,
908                        max_rounds,
909                        timeout_ms,
910                        started_at: Instant::now(),
911                        spent: 0,
912                        aggregate: Default::default(),
913                        proof,
914                        decisions: None,
915                    });
916                    continue;
917                }
918                let result = core.command(&command);
919                let _ = reply.send(result);
920                pump_events(&mut core, &*emit);
921            }
922            Request::Query { sql, params, reply } => {
923                let _ = reply.send(core.query(&sql, params));
924                pump_events(&mut core, &*emit);
925            }
926            Request::SetHeaders { headers, reply } => {
927                core.set_headers(headers);
928                let _ = reply.send(json!({ "result": null }));
929            }
930            Request::TransportWake => {
931                core.poll_transport();
932                pump_events(&mut core, &*emit);
933            }
934            Request::QueryRead {
935                id,
936                tables,
937                failure,
938            } => {
939                core.record_query_read(&id, &tables, failure.as_ref());
940                pump_events(&mut core, &*emit);
941            }
942            #[cfg(test)]
943            Request::Block { duration, entered } => {
944                let _ = entered.send(());
945                std::thread::sleep(duration);
946            }
947            Request::Shutdown => break,
948        }
949    }
950    core.shutdown();
951    drop(network_tx);
952    // Transport shutdown releases a pending socket round. An HTTP request
953    // finishes on its own bounded transport timeout, outside the owner.
954    let _ = network.join();
955    for run in active.into_iter().chain(queued) {
956        if let Some(reply) = run.reply {
957            let _ = reply.send(json!({ "error": { "code": "client.closed", "message": "client owner has closed" } }));
958        }
959    }
960}
961
962/// The database file a `create` opens: `<database_dir>/<database>.db` for a
963/// named database, otherwise the configured `db_path` (`None` → in-memory; a
964/// configuration with only `database_dir` requires the name). A
965/// database name is one file name of ASCII letters, digits, `-`, `_` and `.`,
966/// starting with a letter or digit, so it cannot leave the directory. The
967/// webview never supplies a path itself.
968fn resolve_database(config: &SyncularConfig, params: &Value) -> Result<Option<String>, Value> {
969    if params.get("dbPath").is_some() {
970        return Err(invalid_request(
971            "sync.invalid_request: create.dbPath is host configuration; name a database with create.database",
972        ));
973    }
974    let Some(database) = params.get("database") else {
975        if config.db_path.is_none() && config.database_dir.is_some() {
976            return Err(invalid_request(
977                "sync.invalid_request: create.database is required when SyncularConfig sets database_dir without db_path",
978            ));
979        }
980        return Ok(config.db_path.clone());
981    };
982    let Some(name) = database.as_str().filter(|name| {
983        (1..=128).contains(&name.len())
984            && name.starts_with(|c: char| c.is_ascii_alphanumeric())
985            && !name.contains("..")
986            && name
987                .chars()
988                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
989    }) else {
990        return Err(invalid_request(
991            "sync.invalid_request: create.database must be 1 to 128 ASCII letters, digits, '-', '_' or '.', start with a letter or digit, and contain no '..'",
992        ));
993    };
994    let Some(dir) = &config.database_dir else {
995        return Err(invalid_request(
996            "sync.invalid_request: create.database needs SyncularConfig.database_dir",
997        ));
998    };
999    std::fs::create_dir_all(dir)
1000        .map_err(|error| client_error(format!("cannot create the database directory: {error}")))?;
1001    Ok(Some(
1002        std::path::Path::new(dir)
1003            .join(format!("{name}.db"))
1004            .to_string_lossy()
1005            .into_owned(),
1006    ))
1007}
1008
1009fn invalid_request(message: &str) -> Value {
1010    json!({ "error": { "code": "sync.invalid_request", "message": message } })
1011}
1012
1013fn client_error(message: impl Into<String>) -> Value {
1014    json!({ "error": { "code": "client.failed", "message": message.into() } })
1015}
1016
1017fn security_preflight_error() -> Value {
1018    json!({
1019        "error": {
1020            "code": syncular_client::SECURITY_PREFLIGHT_REQUIRED_CODE,
1021            "message": "the local replica is in security preflight; complete quarantine checks and call activateSecurity before accessing protected data"
1022        }
1023    })
1024}
1025
1026fn pump_events<F: Fn(&Value)>(core: &mut SyncularCore, emit: &F) {
1027    for event in core.drain_events() {
1028        emit(&event.json);
1029    }
1030}
1031
1032// -- Tauri commands (the thin shell) -----------------------------------------
1033
1034#[tauri::command]
1035async fn syncular_command<R: Runtime>(
1036    app: tauri::AppHandle<R>,
1037    webview: tauri::Webview<R>,
1038    mut command: Value,
1039) -> Result<Value, String> {
1040    let method = command
1041        .get("method")
1042        .and_then(Value::as_str)
1043        .unwrap_or("")
1044        .to_owned();
1045    if method != "create" {
1046        if let Err(reply) = app.state::<SyncularState>().require_owner(webview.label()) {
1047            return Ok(reply);
1048        }
1049    }
1050    let label = webview.label().to_owned();
1051    // §7.6: the generic command entry delegates both owned snapshot reads to
1052    // the dedicated Tauri read commands, so one existing read path produces the
1053    // owner-failure bookkeeping the sidecar's transition mirror tracks. It runs
1054    // before any state borrow, because those commands take the app handle.
1055    // In-memory replicas keep their own owner fallback inside those commands,
1056    // and only the required fields below keep the router's error text; every
1057    // other malformed shape gets the dedicated command's validation.
1058    if matches!(method.as_str(), "querySnapshot" | "snapshotRead") {
1059        let params = command.get("params").unwrap_or(&Value::Null);
1060        if method == "querySnapshot" {
1061            let Some(sql) = params.get("sql").and_then(Value::as_str) else {
1062                return Ok(client_error("querySnapshot missing sql"));
1063            };
1064            return syncular_query_snapshot(
1065                app,
1066                webview,
1067                sql.to_owned(),
1068                params.get("params").cloned(),
1069                params.get("coverage").cloned(),
1070                params.get("owner").cloned(),
1071            )
1072            .await;
1073        }
1074        let statements = params.get("statements").cloned().unwrap_or(Value::Null);
1075        if !statements.is_array() {
1076            return Ok(invalid_request(
1077                "sync.invalid_request: snapshotRead statements must be a list",
1078            ));
1079        }
1080        return syncular_snapshot_read(
1081            app,
1082            statements,
1083            params.get("coverage").cloned(),
1084            params.get("units").cloned(),
1085            params.get("commitIds").cloned(),
1086            params.get("owner").cloned(),
1087        )
1088        .await;
1089    }
1090    let state = app.state::<SyncularState>();
1091    if method == "create" || method == "beginSecurityPreflight" || method == "shutdown" {
1092        // Gate fast reads and wait for already-started sidecar snapshots before
1093        // the owner-thread barrier is enqueued.
1094        state.security_gate.begin_preflight()?;
1095    }
1096    // Taken after the gate drained, so no admitted read still waits for it.
1097    let mut reader = if method == "create" || method == "shutdown" {
1098        Some(
1099            state
1100                .reader
1101                .lock()
1102                .map_err(|_| "syncular read mailbox poisoned".to_owned())?,
1103        )
1104    } else {
1105        None
1106    };
1107    let mut database = None;
1108    let mut events = None;
1109    if method == "create" {
1110        // An app-wide emit reaches every webview allowed to `listen`, so the
1111        // events travel on the creating webview's own IPC channel.
1112        let channel = command
1113            .get_mut("params")
1114            .and_then(Value::as_object_mut)
1115            .and_then(|params| params.remove("events"));
1116        match channel
1117            .as_ref()
1118            .and_then(Value::as_str)
1119            .map(JavaScriptChannelId::from_str)
1120        {
1121            Some(Ok(id)) => events = Some(id.channel_on(webview)),
1122            _ => {
1123                return Ok(invalid_request(
1124                    "sync.invalid_request: create requires an events channel",
1125                ))
1126            }
1127        }
1128        if let Some(reads) = command.pointer("/params/authorityReads") {
1129            let declarations: Vec<syncular_client::AuthorityReadDeclaration> =
1130                match serde_json::from_value(reads.clone()) {
1131                    Ok(value) => value,
1132                    Err(_) => {
1133                        return Ok(
1134                            json!({"error": {"code": "client.authority_read_forbidden", "message": "invalid authority declaration"}}),
1135                        )
1136                    }
1137                };
1138            if !declarations.iter().all(|read| {
1139                state
1140                    .config
1141                    .authority_columns
1142                    .get(&read.table)
1143                    .is_some_and(|columns| read.columns.iter().all(|c| columns.contains(c)))
1144            }) {
1145                return Ok(
1146                    json!({"error": {"code": "client.authority_read_forbidden", "message": "authority declaration exceeds the native app policy"}}),
1147                );
1148            }
1149        }
1150        database =
1151            match resolve_database(&state.config, command.get("params").unwrap_or(&Value::Null)) {
1152                Ok(path) => path,
1153                Err(reply) => return Ok(reply),
1154            };
1155        if let Some(path) = &database {
1156            match command.get_mut("params").and_then(Value::as_object_mut) {
1157                Some(params) => {
1158                    params.insert("dbPath".to_owned(), Value::from(path.clone()));
1159                }
1160                None => {
1161                    if let Some(object) = command.as_object_mut() {
1162                        object.insert("params".to_owned(), json!({ "dbPath": path }));
1163                    }
1164                }
1165            }
1166        }
1167    }
1168    let create_preflight = method == "create"
1169        && command
1170            .pointer("/params/securityPreflight")
1171            .and_then(Value::as_bool)
1172            .unwrap_or(false);
1173    // Installed before the create runs, so its first events reach the channel.
1174    let previous_events = match events {
1175        Some(channel) => Some(
1176            state
1177                .events
1178                .lock()
1179                .map_err(|_| "syncular event channel poisoned".to_owned())?
1180                .replace(channel),
1181        ),
1182        None => None,
1183    };
1184    let (reply_tx, reply_rx) = std::sync::mpsc::channel();
1185    state.send(Request::Command {
1186        command,
1187        reply: reply_tx,
1188    })?;
1189    let reply = reply_rx
1190        .recv()
1191        .map_err(|_| "the syncular core dropped the reply".to_owned())?;
1192    let succeeded = reply.get("error").is_none();
1193    // A refused create leaves the previous client, and its webview, in place.
1194    if let (false, Some(previous)) = (succeeded, previous_events) {
1195        *state
1196            .events
1197            .lock()
1198            .map_err(|_| "syncular event channel poisoned".to_owned())? = previous;
1199    }
1200    if succeeded && method == "create" {
1201        *state
1202            .owner
1203            .lock()
1204            .map_err(|_| "syncular owner poisoned".to_owned())? = Some(label);
1205    }
1206    if let (true, Some(slot)) = (succeeded, reader.as_mut()) {
1207        let next = match database.filter(|path| path.as_str() != ":memory:") {
1208            Some(path) => Some(spawn_reader(
1209                path,
1210                state
1211                    .sender
1212                    .lock()
1213                    .map_err(|_| "syncular mailbox poisoned".to_owned())?
1214                    .clone(),
1215            )?),
1216            None => None,
1217        };
1218        if let Some(previous) = std::mem::replace(&mut **slot, next) {
1219            let _ = previous.send(ReadRequest::Shutdown);
1220        }
1221    }
1222    drop(reader);
1223    if succeeded && method == "create" {
1224        if !create_preflight {
1225            state.security_gate.activate()?;
1226        }
1227    } else if succeeded && method == "activateSecurity" {
1228        state.security_gate.activate()?;
1229    }
1230    Ok(reply)
1231}
1232
1233/// Replace the native transport's request headers at runtime — the auth
1234/// Header rotation path: a fresh JWT reaches the transport without
1235/// re-registering the plugin. HTTP requests use the new set from the next
1236/// call; the realtime socket applies it on its next (re)connect.
1237#[tauri::command]
1238async fn syncular_set_headers<R: Runtime>(
1239    app: tauri::AppHandle<R>,
1240    webview: tauri::Webview<R>,
1241    headers: std::collections::BTreeMap<String, String>,
1242) -> Result<Value, String> {
1243    let state = app.state::<SyncularState>();
1244    if let Err(reply) = state.require_owner(webview.label()) {
1245        return Ok(reply);
1246    }
1247    // Runtime bearer replacement is an active-session operation. Hold the
1248    // same gate as fast reads so beginSecurityPreflight both rejects new
1249    // replacements and waits for an already-started mailbox update.
1250    let _active_guard = match state.security_gate.enter_read() {
1251        Ok(guard) => guard,
1252        Err(reply) => return Ok(reply),
1253    };
1254    let (reply_tx, reply_rx) = std::sync::mpsc::channel();
1255    state.send(Request::SetHeaders {
1256        headers: headers.into_iter().collect(),
1257        reply: reply_tx,
1258    })?;
1259    reply_rx
1260        .recv()
1261        .map_err(|_| "the syncular core dropped the reply".to_owned())
1262}
1263
1264#[tauri::command]
1265async fn syncular_query<R: Runtime>(
1266    app: tauri::AppHandle<R>,
1267    webview: tauri::Webview<R>,
1268    sql: String,
1269    params: Option<Value>,
1270) -> Result<Value, String> {
1271    let state = app.state::<SyncularState>();
1272    if let Err(reply) = state.require_owner(webview.label()) {
1273        return Ok(reply);
1274    }
1275    let _read_guard = match state.security_gate.enter_read() {
1276        Ok(guard) => guard,
1277        Err(reply) => return Ok(reply),
1278    };
1279    let (reply_tx, reply_rx) = std::sync::mpsc::channel();
1280    state.send(Request::Query {
1281        sql,
1282        params: params.unwrap_or(Value::Null),
1283        reply: reply_tx,
1284    })?;
1285    reply_rx
1286        .recv()
1287        .map_err(|_| "the syncular core dropped the reply".to_owned())
1288}
1289
1290/// Atomic rows + revision + window coverage on the independent read-only
1291/// connection. In-memory configurations fall back to the core owner because
1292/// SQLite cannot share an anonymous database across connections.
1293#[tauri::command]
1294async fn syncular_query_snapshot<R: Runtime>(
1295    app: tauri::AppHandle<R>,
1296    webview: tauri::Webview<R>,
1297    sql: String,
1298    params: Option<Value>,
1299    coverage: Option<Value>,
1300    owner: Option<Value>,
1301) -> Result<Value, String> {
1302    let state = app.state::<SyncularState>();
1303    if let Err(reply) = state.require_owner(webview.label()) {
1304        return Ok(reply);
1305    }
1306    let _read_guard = match state.security_gate.enter_read() {
1307        Ok(guard) => guard,
1308        Err(reply) => return Ok(reply),
1309    };
1310    let params_value = params.unwrap_or_else(|| Value::Array(Vec::new()));
1311    let coverage_value = coverage.unwrap_or_else(|| Value::Array(Vec::new()));
1312
1313    if let Some(reader) = state.reader()? {
1314        let bind = match params_value.as_array() {
1315            Some(values) => values.clone(),
1316            None => return Ok(client_error("querySnapshot params must be a list")),
1317        };
1318        let parsed_coverage = match syncular_command::parse_window_coverage(Some(&coverage_value)) {
1319            Ok(value) => value,
1320            Err(message) => return Ok(invalid_request(&message)),
1321        };
1322        // §7.5 owner: the same `{id, tables}` contract the command router parses.
1323        let parsed_owner =
1324            match syncular_command::parse_query_owner(owner.as_ref(), "querySnapshot") {
1325                Ok(value) => value.map(|(id, tables)| {
1326                    (
1327                        id.to_owned(),
1328                        tables.into_iter().map(str::to_owned).collect(),
1329                    )
1330                }),
1331                Err(error) => return Ok(syncular_command::reply(Err(error))),
1332            };
1333        let (reply_tx, reply_rx) = std::sync::mpsc::channel();
1334        reader
1335            .send(ReadRequest::QuerySnapshot {
1336                sql,
1337                params: bind,
1338                coverage: parsed_coverage,
1339                owner: parsed_owner,
1340                reply: reply_tx,
1341            })
1342            .map_err(|_| "the syncular read thread has stopped".to_owned())?;
1343        return reply_rx
1344            .recv()
1345            .map_err(|_| "the syncular read thread dropped the reply".to_owned());
1346    }
1347
1348    let (reply_tx, reply_rx) = std::sync::mpsc::channel();
1349    state.send(Request::Command {
1350        command: json!({
1351            "method": "querySnapshot",
1352            "params": {
1353                "sql": sql,
1354                "params": params_value,
1355                "coverage": coverage_value,
1356                "owner": owner.unwrap_or(Value::Null),
1357            }
1358        }),
1359        reply: reply_tx,
1360    })?;
1361    reply_rx
1362        .recv()
1363        .map_err(|_| "the syncular core dropped the reply".to_owned())
1364}
1365
1366/// §7.5: one atomic read over the file-backed sidecar, or the owner command
1367/// for an in-memory replica (SQLite cannot share an anonymous database across
1368/// connections). `statements` is a list of `{sql, params?}`; `units` and
1369/// `commitIds` name the catch-up and delivery reads. All results share one
1370/// revision and one read transaction. The webview reaches it as the
1371/// `snapshotRead` method of `syncular_command`.
1372async fn syncular_snapshot_read<R: Runtime>(
1373    app: tauri::AppHandle<R>,
1374    statements: Value,
1375    coverage: Option<Value>,
1376    units: Option<Value>,
1377    commit_ids: Option<Value>,
1378    owner: Option<Value>,
1379) -> Result<Value, String> {
1380    let state = app.state::<SyncularState>();
1381    let _read_guard = match state.security_gate.enter_read() {
1382        Ok(guard) => guard,
1383        Err(reply) => return Ok(reply),
1384    };
1385    let params = json!({
1386        "statements": statements,
1387        "coverage": coverage,
1388        "units": units,
1389        "commitIds": commit_ids,
1390        "owner": owner,
1391    });
1392    let parsed = match syncular_command::parse_snapshot_read(&params) {
1393        Ok(parsed) => parsed,
1394        Err(error) => return Ok(syncular_command::reply(Err(error))),
1395    };
1396
1397    if let Some(reader) = state.reader()? {
1398        let (reply_tx, reply_rx) = std::sync::mpsc::channel();
1399        reader
1400            .send(ReadRequest::SnapshotRead {
1401                statements: parsed.statements,
1402                coverage: parsed.coverage,
1403                units: parsed.units,
1404                commit_ids: parsed.commit_ids,
1405                owner: parsed.owner,
1406                reply: reply_tx,
1407            })
1408            .map_err(|_| "the syncular read thread has stopped".to_owned())?;
1409        return reply_rx
1410            .recv()
1411            .map_err(|_| "the syncular read thread dropped the reply".to_owned());
1412    }
1413
1414    let (reply_tx, reply_rx) = std::sync::mpsc::channel();
1415    state.send(Request::Command {
1416        command: json!({ "method": "snapshotRead", "params": params }),
1417        reply: reply_tx,
1418    })?;
1419    reply_rx
1420        .recv()
1421        .map_err(|_| "the syncular core dropped the reply".to_owned())
1422}
1423
1424/// Initialize the plugin with a config. Register with
1425/// `tauri::Builder::default().plugin(tauri_plugin_syncular::init(config))`.
1426///
1427/// The owning thread is spawned in `setup`; it builds the core (native
1428/// transport if `base_url` + the `native-transport` feature), pumps events onto
1429/// the creating webview's `events` channel, and runs the §8.4 host loop. The
1430/// mailbox `Sender` is managed as plugin state and torn down on `RunEvent::Exit`.
1431pub fn init<R: Runtime>(config: SyncularConfig) -> TauriPlugin<R> {
1432    Builder::<R>::new("syncular")
1433        .invoke_handler(tauri::generate_handler![
1434            syncular_command,
1435            syncular_query,
1436            syncular_query_snapshot,
1437            syncular_set_headers
1438        ])
1439        .setup(move |app, _api| {
1440            let (tx, rx) = std::sync::mpsc::channel::<Request>();
1441            let events = Arc::new(Mutex::new(None::<Channel<Value>>));
1442            let emit_events = Arc::clone(&events);
1443            app.manage(SyncularState {
1444                sender: Mutex::new(tx.clone()),
1445                reader: Mutex::new(None),
1446                config: config.clone(),
1447                // Fail closed until the first successful `create` declares
1448                // whether this process starts active or in preflight.
1449                security_gate: SecurityGate::new_preflight(),
1450                events,
1451                owner: Mutex::new(None),
1452            });
1453            let emit = move |value: &Value| {
1454                // Best-effort: a webview that has gone away must not crash the
1455                // owning thread.
1456                if let Some(channel) = emit_events.lock().ok().and_then(|slot| slot.clone()) {
1457                    let _ = channel.send(value.clone());
1458                }
1459            };
1460            std::thread::Builder::new()
1461                .name("syncular-core".to_owned())
1462                .spawn(move || run_owner_thread(config, tx, rx, emit))
1463                .map_err(|e| format!("failed to spawn syncular core thread: {e}"))?;
1464            Ok(())
1465        })
1466        .on_event(|app, event| {
1467            if let RunEvent::Exit = event {
1468                if let Some(state) = app.try_state::<SyncularState>() {
1469                    let _ = state.send(Request::Shutdown);
1470                    if let Ok(Some(reader)) = state.reader() {
1471                        let _ = reader.send(ReadRequest::Shutdown);
1472                    }
1473                }
1474            }
1475        })
1476        .build()
1477}
1478
1479#[cfg(test)]
1480mod tests {
1481    use super::*;
1482
1483    /// The mock webview with this label, created on first use.
1484    fn webview(
1485        app: &tauri::AppHandle<tauri::test::MockRuntime>,
1486        label: &str,
1487    ) -> tauri::Webview<tauri::test::MockRuntime> {
1488        let window = match app.get_webview_window(label) {
1489            Some(window) => window,
1490            None => tauri::WebviewWindowBuilder::new(app, label, Default::default())
1491                .build()
1492                .expect("mock webview"),
1493        };
1494        window.as_ref().clone()
1495    }
1496
1497    /// Run one `syncular_command` from the mock webview `label`. A `create`
1498    /// carries that webview's events channel unless the test sets `events`.
1499    fn run_command_from(
1500        app: &tauri::AppHandle<tauri::test::MockRuntime>,
1501        label: &str,
1502        mut command: Value,
1503    ) -> Result<Value, String> {
1504        if command["method"] == "create" {
1505            if let Some(params) = command.get_mut("params").and_then(Value::as_object_mut) {
1506                params
1507                    .entry("events")
1508                    .or_insert_with(|| json!("__CHANNEL__:1"));
1509            }
1510        }
1511        tauri::async_runtime::block_on(syncular_command(app.clone(), webview(app, label), command))
1512    }
1513
1514    /// Run one `syncular_command` from the mock `main` webview.
1515    fn run_command(
1516        app: &tauri::AppHandle<tauri::test::MockRuntime>,
1517        command: Value,
1518    ) -> Result<Value, String> {
1519        run_command_from(app, "main", command)
1520    }
1521
1522    #[test]
1523    fn config_to_transport_json_shapes_fields() {
1524        let config = SyncularConfig {
1525            base_url: Some("https://api.example.com".to_owned()),
1526            local_authority_path: Some("/data/authority.db".to_owned()),
1527            headers: vec![("authorization".to_owned(), "Bearer x".to_owned())],
1528            request_timeout_ms: Some(1000),
1529            round_deadline_ms: Some(2000),
1530            max_request_bytes: Some(1024),
1531            max_response_bytes: Some(2048),
1532            redirects: Some("deny".to_owned()),
1533            realtime_heartbeat_ms: Some(15000),
1534            ..Default::default()
1535        };
1536        let json = config.to_transport_json();
1537        assert_eq!(json["baseUrl"], "https://api.example.com");
1538        assert_eq!(json["localAuthorityPath"], "/data/authority.db");
1539        assert_eq!(json["headers"]["authorization"], "Bearer x");
1540        assert_eq!(json["requestTimeoutMs"], 1000);
1541        assert_eq!(json["roundDeadlineMs"], 2000);
1542        assert_eq!(json["maxRequestBytes"], 1024);
1543        assert_eq!(json["maxResponseBytes"], 2048);
1544        assert_eq!(json["redirects"], "deny");
1545        assert_eq!(json["realtimeHeartbeatMs"], 15000);
1546    }
1547
1548    #[test]
1549    fn a_startup_failure_is_the_structured_reply_to_create() {
1550        use tauri::test::{mock_builder, mock_context, noop_assets};
1551
1552        let app = mock_builder()
1553            .plugin(init(SyncularConfig {
1554                realtime_heartbeat_ms: Some(0),
1555                auto_sync: false,
1556                ..Default::default()
1557            }))
1558            .build(mock_context(noop_assets()))
1559            .expect("build mock app");
1560        let created = run_command(
1561            app.handle(),
1562            json!({ "method": "create", "params": { "schema": { "version": 1, "tables": [] } } }),
1563        )
1564        .expect("a structured create reply, not an IPC rejection");
1565        assert_eq!(
1566            created["error"]["code"], "sync.invalid_request",
1567            "{created}"
1568        );
1569        assert_eq!(
1570            created["error"]["details"]["legacyCause"],
1571            "sync.invalid_request: transport config realtimeHeartbeatMs must be a positive integer"
1572        );
1573    }
1574
1575    #[test]
1576    fn transport_policy_config_is_validated_at_the_core_boundary() {
1577        // A headerless core still validates the policy it is handed.
1578        let core = SyncularCore::new(&serde_json::json!({"requestTimeoutMs": 1000}));
1579        assert!(core.is_ok());
1580        let error = SyncularCore::new(&serde_json::json!({"requestTimeoutMs": 0}))
1581            .err()
1582            .unwrap();
1583        assert_eq!(
1584            error,
1585            "sync.invalid_request: transport config requestTimeoutMs must be a positive integer"
1586        );
1587        let error = SyncularCore::new(&serde_json::json!({"redirects": "sometimes"}))
1588            .err()
1589            .unwrap();
1590        assert_eq!(
1591            error,
1592            "sync.invalid_request: transport config redirects must be \"deny\" or \"follow\""
1593        );
1594        let mut core = SyncularCore::new(&serde_json::json!({})).unwrap();
1595        assert_eq!(
1596            core.set_transport_policy(crate::transport::HostTransportPolicy {
1597                max_response_bytes: Some(0),
1598                ..Default::default()
1599            })
1600            .unwrap_err(),
1601            "sync.invalid_request: transport config maxResponseBytes must be a positive integer"
1602        );
1603    }
1604
1605    #[test]
1606    fn security_gate_blocks_new_operations_and_waits_for_in_flight_work() {
1607        let gate = std::sync::Arc::new(SecurityGate::new_preflight());
1608        gate.activate().expect("activate test gate");
1609        let read = gate.enter_read().expect("active read");
1610        let gate_for_barrier = std::sync::Arc::clone(&gate);
1611        let (done_tx, done_rx) = std::sync::mpsc::channel();
1612        let barrier = std::thread::spawn(move || {
1613            gate_for_barrier.begin_preflight().expect("enter preflight");
1614            done_tx.send(()).expect("barrier reply");
1615        });
1616
1617        assert!(done_rx.recv_timeout(Duration::from_millis(20)).is_err());
1618        drop(read);
1619        done_rx
1620            .recv_timeout(Duration::from_secs(1))
1621            .expect("barrier drains after the read");
1622        barrier.join().expect("barrier thread");
1623        assert!(gate.enter_read().is_err());
1624    }
1625
1626    #[test]
1627    fn direct_set_headers_command_respects_the_native_preflight_gate() {
1628        use std::collections::BTreeMap;
1629        use tauri::test::{mock_builder, mock_context, noop_assets};
1630
1631        let app = mock_builder()
1632            .plugin(init(SyncularConfig {
1633                auto_sync: false,
1634                ..Default::default()
1635            }))
1636            .build(mock_context(noop_assets()))
1637            .expect("build mock app");
1638
1639        let blocked = tauri::async_runtime::block_on(syncular_set_headers(
1640            app.handle().clone(),
1641            webview(app.handle(), "main"),
1642            BTreeMap::from([("authorization".to_owned(), "Bearer blocked".to_owned())]),
1643        ))
1644        .expect("preflight reply");
1645        assert_eq!(
1646            blocked["error"]["code"],
1647            Value::from("client.security_preflight_required")
1648        );
1649
1650        let created = run_command(
1651            app.handle(),
1652            json!({
1653                "method": "create",
1654                "params": {
1655                    "clientId": "native-header-gate",
1656                    "schema": { "version": 1, "tables": [] }
1657                }
1658            }),
1659        )
1660        .expect("create reply");
1661        assert!(created.get("error").is_none(), "{created}");
1662
1663        let active = tauri::async_runtime::block_on(syncular_set_headers(
1664            app.handle().clone(),
1665            webview(app.handle(), "main"),
1666            BTreeMap::from([("authorization".to_owned(), "Bearer active".to_owned())]),
1667        ))
1668        .expect("active reply");
1669        assert_eq!(active["result"], Value::Null);
1670    }
1671
1672    #[test]
1673    fn local_authority_commands_route_through_the_plugin_without_a_configured_authority() {
1674        use tauri::test::{mock_builder, mock_context, noop_assets};
1675
1676        let app = mock_builder()
1677            .plugin(init(SyncularConfig {
1678                auto_sync: false,
1679                ..Default::default()
1680            }))
1681            .build(mock_context(noop_assets()))
1682            .expect("build mock app");
1683        let command = |method: &str| {
1684            run_command(app.handle(), json!({ "method": method, "params": {} }))
1685                .expect("command reply")
1686        };
1687
1688        let created = run_command(
1689            app.handle(),
1690            json!({
1691                "method": "create",
1692                "params": {
1693                    "clientId": "native-no-authority",
1694                    "schema": { "version": 1, "tables": [] }
1695                }
1696            }),
1697        )
1698        .expect("create reply");
1699        assert!(created.get("error").is_none(), "{created}");
1700
1701        let state = command("localAuthorityState");
1702        assert_eq!(state["result"]["state"], Value::Null, "{state}");
1703        for method in ["attachLocalAuthority", "abandonLocalAuthorityAttach"] {
1704            let reply = command(method);
1705            assert_eq!(
1706                reply["error"]["code"], "client.local_authority_unconfigured",
1707                "{method}: {reply}"
1708            );
1709        }
1710    }
1711
1712    #[test]
1713    fn preflight_refuses_plain_replacement_creates_through_the_plugin() {
1714        use tauri::test::{mock_builder, mock_context, noop_assets};
1715
1716        let app = mock_builder()
1717            .plugin(init(SyncularConfig {
1718                auto_sync: false,
1719                ..Default::default()
1720            }))
1721            .build(mock_context(noop_assets()))
1722            .expect("build mock app");
1723        let command = |value: Value| run_command(app.handle(), value).expect("command reply");
1724
1725        let created = command(json!({
1726            "method": "create",
1727            "params": {
1728                "clientId": "native-preflight-escape",
1729                "schema": { "version": 1, "tables": [] },
1730                "securityPreflight": true
1731            }
1732        }));
1733        assert!(created.get("error").is_none(), "{created}");
1734
1735        // The escape attempt: a plain re-create must be refused by the shared
1736        // router, and the plugin's fast-read gate must stay engaged.
1737        let escape = command(json!({
1738            "method": "create",
1739            "params": {
1740                "clientId": "native-preflight-escape",
1741                "schema": { "version": 1, "tables": [] }
1742            }
1743        }));
1744        assert_eq!(
1745            escape["error"]["code"],
1746            Value::from("client.security_preflight_required"),
1747            "{escape}"
1748        );
1749        let read = tauri::async_runtime::block_on(syncular_query(
1750            app.handle().clone(),
1751            webview(app.handle(), "main"),
1752            "SELECT 1".to_owned(),
1753            None,
1754        ))
1755        .expect("query reply");
1756        assert_eq!(
1757            read["error"]["code"],
1758            Value::from("client.security_preflight_required")
1759        );
1760
1761        // Activation (with a fresh header set) releases both gates.
1762        let activated = command(json!({
1763            "method": "activateSecurity",
1764            "params": { "headers": { "authorization": "Bearer fresh" } }
1765        }));
1766        assert!(activated.get("error").is_none(), "{activated}");
1767        let read = tauri::async_runtime::block_on(syncular_query(
1768            app.handle().clone(),
1769            webview(app.handle(), "main"),
1770            "SELECT 1 AS value".to_owned(),
1771            None,
1772        ))
1773        .expect("query reply");
1774        assert_eq!(read["result"]["rows"][0]["value"], 1);
1775        let recreated = command(json!({
1776            "method": "create",
1777            "params": {
1778                "clientId": "native-preflight-escape",
1779                "schema": { "version": 1, "tables": [] }
1780            }
1781        }));
1782        assert!(recreated.get("error").is_none(), "{recreated}");
1783    }
1784
1785    #[test]
1786    fn authority_snapshot_raw_ipc_obeys_native_columns_and_never_opens_protected_reads() {
1787        use tauri::test::{mock_builder, mock_context, noop_assets};
1788        let path =
1789            std::env::temp_dir().join(format!("syncular-authority-ipc-{}.db", std::process::id()));
1790        let app = mock_builder()
1791            .plugin(init(SyncularConfig {
1792                auto_sync: false,
1793                db_path: Some(path.to_string_lossy().into_owned()),
1794                authority_columns: [(
1795                    "authority".into(),
1796                    vec!["id".into(), "actor_id".into(), "role".into()],
1797                )]
1798                .into(),
1799                ..Default::default()
1800            }))
1801            .build(mock_context(noop_assets()))
1802            .expect("mock app");
1803        let handle = app.handle().clone();
1804        let command = |value: Value| run_command(&handle, value).expect("IPC reply");
1805        let schema = json!({"version": 1, "tables": [{"name": "authority", "primaryKey": "id", "scopes": [{"pattern": "actor:{actor_id}"}], "columns": [
1806            {"name": "id", "type": "string", "nullable": false}, {"name": "actor_id", "type": "string", "nullable": false}, {"name": "role", "type": "string", "nullable": false}, {"name": "secret", "type": "bytes", "encrypted": true, "declaredType": "string", "nullable": true}
1807        ]}]});
1808        let policy = json!([{"table": "authority", "columns": ["id", "actor_id", "role"], "scopes": {"actor_id": ["a", "b"]}}]);
1809        let create = |reads: Value| json!({"method": "create", "params": {"schema": schema, "securityPreflight": true, "transportEnabled": false, "authorityReads": reads}});
1810        let created = command(create(policy.clone()));
1811        assert!(created.get("error").is_none(), "{created}");
1812        let conn = rusqlite::Connection::open(&path).expect("fixture db");
1813        conn.execute_batch("INSERT INTO _syncular_base_authority(id,actor_id,role,secret,_syncular_version)VALUES('one','a','accepted','clinical plaintext',7); INSERT INTO authority SELECT * FROM _syncular_base_authority;").expect("fixture base");
1814        for actor in ["a", "b"] {
1815            let echo = json!([{"table": "authority", "status": "active", "scopes": {"actor_id": [actor]}}]);
1816            conn.execute(
1817                "INSERT INTO _syncular_units(id,scopes,explicit,cursor,echo)VALUES(?1,?2,1,NULL,?3)",
1818                rusqlite::params![actor, json!({"actor_id": actor}).to_string(), echo.to_string()],
1819            )
1820            .expect("fixture unit");
1821        }
1822        let snapshot = command(json!({"method": "authoritySnapshot", "params": {}}));
1823        assert_eq!(snapshot["result"]["complete"], true, "{snapshot}");
1824        assert_eq!(
1825            snapshot["result"]["tables"][0]["rows"][0]["values"],
1826            json!({"id": "one", "actor_id": "a", "role": "accepted"})
1827        );
1828        assert!(!snapshot.to_string().contains("clinical plaintext"));
1829        assert_eq!(
1830            command(json!({"method": "securityLifecycle", "params": {}}))["result"]["state"],
1831            "preflight"
1832        );
1833        for params in [
1834            json!({"sql": "SELECT secret FROM authority"}),
1835            json!({"columns": ["secret"]}),
1836            json!({"table": "_syncular_meta"}),
1837            json!({"scopes": {"actor_id": ["outside"]}}),
1838            json!({"authorityReads": policy}),
1839        ] {
1840            assert_eq!(
1841                command(json!({"method": "authoritySnapshot", "params": params}))["error"]["code"],
1842                "client.authority_read_forbidden"
1843            );
1844        }
1845        for columns in [
1846            json!(["id", "actor_id", "secret"]),
1847            json!([
1848                "id",
1849                "actor_id",
1850                "role FROM authority; DELETE FROM authority"
1851            ]),
1852        ] {
1853            assert_eq!(
1854                command(create(
1855                    json!([{"table": "authority", "columns": columns, "scopes": {"actor_id": ["a"]}}])
1856                ))["error"]["code"],
1857                "client.authority_read_forbidden"
1858            );
1859        }
1860        for method in [
1861            "query",
1862            "querySnapshot",
1863            "mutate",
1864            "setHeaders",
1865            "subscribe",
1866            "sync",
1867        ] {
1868            assert_eq!(
1869                command(json!({"method": method, "params": {"sql": "SELECT id FROM authority"}}))
1870                    ["error"]["code"],
1871                "client.security_preflight_required"
1872            );
1873        }
1874        assert_eq!(
1875            tauri::async_runtime::block_on(syncular_query(
1876                app.handle().clone(),
1877                webview(app.handle(), "main"),
1878                "SELECT id FROM authority".into(),
1879                None
1880            ))
1881            .unwrap()["error"]["code"],
1882            "client.security_preflight_required"
1883        );
1884        assert_eq!(
1885            tauri::async_runtime::block_on(syncular_query_snapshot(
1886                app.handle().clone(),
1887                webview(app.handle(), "main"),
1888                "SELECT id FROM authority".into(),
1889                None,
1890                None,
1891                None
1892            ))
1893            .unwrap()["error"]["code"],
1894            "client.security_preflight_required"
1895        );
1896        let before = snapshot["result"]["revision"].clone();
1897        assert_eq!(
1898            command(json!({"method": "authoritySnapshot", "params": {}}))["result"]["revision"],
1899            before
1900        );
1901        conn.execute("UPDATE _syncular_units SET cursor=7, bootstrap_state='credential-do-not-expose' WHERE id='b'", []).unwrap();
1902        let partial = command(json!({"method": "authoritySnapshot", "params": {}}));
1903        assert_eq!(partial["result"]["complete"], false);
1904        assert!(!partial.to_string().contains("credential-do-not-expose"));
1905        conn.execute(
1906            "UPDATE _syncular_units SET echo='credential-do-not-expose' WHERE id='b'",
1907            [],
1908        )
1909        .unwrap();
1910        let corrupt = command(json!({"method": "authoritySnapshot", "params": {}}));
1911        assert_eq!(corrupt["error"]["code"], "sync.local_corrupt");
1912        assert!(!corrupt.to_string().contains("credential-do-not-expose"));
1913        conn.execute("DELETE FROM _syncular_units WHERE id='b'", [])
1914            .unwrap();
1915        command(json!({"method": "beginSecurityPreflight", "params": {}}));
1916        // Entering preflight emits one status batch (§5.11), which advances the
1917        // revision; a second lock does not.
1918        let locked = command(json!({"method": "authoritySnapshot", "params": {}}));
1919        assert!(locked.get("error").is_none());
1920        let before = locked["result"]["revision"].clone();
1921        // The owner's mailbox serializes a lock/read race without admitting SQL.
1922        let barrier = std::sync::Barrier::new(2);
1923        std::thread::scope(|scope| {
1924            let locking = scope.spawn(|| {
1925                barrier.wait();
1926                command(json!({"method": "beginSecurityPreflight", "params": {}}))
1927            });
1928            barrier.wait();
1929            let reading = command(json!({"method": "authoritySnapshot", "params": {}}));
1930            assert_eq!(reading["result"]["revision"], before);
1931            assert!(locking.join().unwrap().get("error").is_none());
1932        });
1933        // A racing close either follows the entire snapshot or rejects it.
1934        let barrier = std::sync::Barrier::new(2);
1935        std::thread::scope(|scope| {
1936            let closing = scope.spawn(|| {
1937                barrier.wait();
1938                command(json!({"method": "shutdown", "params": {}}))
1939            });
1940            barrier.wait();
1941            let reading = command(json!({"method": "authoritySnapshot", "params": {}}));
1942            assert!(
1943                reading["result"]["revision"] == before
1944                    || reading["error"]["code"] == "client.closed",
1945                "{reading}"
1946            );
1947            assert!(closing.join().unwrap().get("error").is_none());
1948        });
1949        assert_eq!(
1950            command(json!({"method": "authoritySnapshot", "params": {}}))["error"]["code"],
1951            "client.closed"
1952        );
1953        drop(conn);
1954        let _ = std::fs::remove_file(path);
1955    }
1956
1957    #[test]
1958    fn resolve_database_names_a_file_inside_the_configured_directory() {
1959        let dir =
1960            std::env::temp_dir().join(format!("syncular-tauri-resolve-{}", std::process::id()));
1961        let config = SyncularConfig {
1962            db_path: Some("/tmp/default.db".to_owned()),
1963            database_dir: Some(dir.to_string_lossy().into_owned()),
1964            ..Default::default()
1965        };
1966        // No name → the configured default path.
1967        assert_eq!(
1968            resolve_database(&config, &json!({ "clientId": "c1" })),
1969            Ok(Some("/tmp/default.db".to_owned()))
1970        );
1971        // A name → `<database_dir>/<name>.db`, directory created.
1972        assert_eq!(
1973            resolve_database(&config, &json!({ "database": "app-actor-0f.v2" })),
1974            Ok(Some(
1975                dir.join("app-actor-0f.v2.db")
1976                    .to_string_lossy()
1977                    .into_owned()
1978            ))
1979        );
1980        assert!(dir.is_dir());
1981        // A webview-supplied path and every name that could leave the
1982        // directory are refused.
1983        for params in [
1984            json!({ "dbPath": "/etc/other.db" }),
1985            json!({ "database": "../escape" }),
1986            json!({ "database": "a/b" }),
1987            json!({ "database": "a\\b" }),
1988            json!({ "database": "/abs" }),
1989            json!({ "database": ".hidden" }),
1990            json!({ "database": "a..b" }),
1991            json!({ "database": "" }),
1992            json!({ "database": "x".repeat(129) }),
1993            json!({ "database": 7 }),
1994        ] {
1995            let refused = resolve_database(&config, &params).expect_err("refused");
1996            assert_eq!(refused["error"]["code"], "sync.invalid_request", "{params}");
1997        }
1998        // A configuration with only a directory never opens an unnamed
1999        // create in memory.
2000        let refused = resolve_database(
2001            &SyncularConfig {
2002                database_dir: Some(dir.to_string_lossy().into_owned()),
2003                ..Default::default()
2004            },
2005            &json!({ "clientId": "c1" }),
2006        )
2007        .expect_err("name required");
2008        assert_eq!(refused["error"]["code"], "sync.invalid_request");
2009        // A name without a configured directory is refused, never placed
2010        // somewhere else.
2011        let refused = resolve_database(&SyncularConfig::default(), &json!({ "database": "actor" }))
2012            .expect_err("no directory");
2013        assert_eq!(refused["error"]["code"], "sync.invalid_request");
2014        std::fs::remove_dir_all(dir).expect("remove temp directory");
2015    }
2016
2017    /// One replica per actor: each `create` opens its named database, keeps
2018    /// its own client id, and the snapshot reader follows the open database.
2019    #[test]
2020    fn named_databases_keep_one_replica_and_client_id_per_actor() {
2021        use tauri::test::{mock_builder, mock_context, noop_assets};
2022
2023        let dir =
2024            std::env::temp_dir().join(format!("syncular-tauri-actors-{}", std::process::id()));
2025        let _ = std::fs::remove_dir_all(&dir);
2026        let app = mock_builder()
2027            .plugin(init(SyncularConfig {
2028                database_dir: Some(dir.to_string_lossy().into_owned()),
2029                auto_sync: false,
2030                ..Default::default()
2031            }))
2032            .build(mock_context(noop_assets()))
2033            .expect("build mock app");
2034        let command = |value: Value| run_command(app.handle(), value).expect("command reply");
2035        let snapshot = |sql: &str| {
2036            tauri::async_runtime::block_on(syncular_query_snapshot(
2037                app.handle().clone(),
2038                webview(app.handle(), "main"),
2039                sql.to_owned(),
2040                None,
2041                None,
2042                None,
2043            ))
2044            .expect("snapshot reply")
2045        };
2046        let schema = json!({
2047            "version": 1,
2048            "tables": [{
2049                "name": "todo", "primaryKey": "id",
2050                "columns": [
2051                    { "name": "id", "type": "string", "nullable": false },
2052                    { "name": "title", "type": "string", "nullable": false }
2053                ],
2054                "scopes": []
2055            }]
2056        });
2057        let create = |database: &str, client_id: &str| {
2058            command(json!({ "method": "create", "params": {
2059                "database": database, "clientId": client_id, "schema": schema
2060            } }))
2061        };
2062
2063        assert_eq!(create("actor-a", "client-a")["result"], json!({}));
2064        command(json!({ "method": "mutate", "params": { "mutations": [{
2065            "op": "upsert", "table": "todo", "values": { "id": "t1", "title": "a" }
2066        }] } }));
2067        assert_eq!(
2068            snapshot("SELECT title FROM todo")["result"]["rows"][0]["title"],
2069            "a"
2070        );
2071        assert_eq!(
2072            command(json!({ "method": "shutdown" }))["result"],
2073            json!({})
2074        );
2075
2076        assert_eq!(create("actor-b", "client-b")["result"], json!({}));
2077        assert_eq!(
2078            snapshot("SELECT title FROM todo")["result"]["rows"],
2079            json!([]),
2080            "the reader follows the second actor's database"
2081        );
2082        assert!(dir.join("actor-a.db").is_file());
2083        assert!(dir.join("actor-b.db").is_file());
2084        assert_eq!(
2085            command(json!({ "method": "shutdown" }))["result"],
2086            json!({})
2087        );
2088
2089        // Each replica keeps the client id it was created with.
2090        assert_eq!(
2091            create("actor-a", "client-b")["error"]["code"],
2092            "client.identity_mismatch"
2093        );
2094        assert_eq!(create("actor-a", "client-a")["result"], json!({}));
2095        assert_eq!(
2096            snapshot("SELECT title FROM todo")["result"]["rows"][0]["title"],
2097            "a"
2098        );
2099        assert_eq!(
2100            create("../actor-a", "client-a")["error"]["code"],
2101            "sync.invalid_request"
2102        );
2103        command(json!({ "method": "shutdown" }));
2104        std::fs::remove_dir_all(dir).expect("remove temp directory");
2105    }
2106
2107    /// Sync events reach only the webview that created the client. An app-wide
2108    /// emit reaches every webview's default `listen`, including windows the
2109    /// app never granted `syncular:default`.
2110    #[test]
2111    fn events_never_broadcast_app_wide() {
2112        use std::sync::atomic::{AtomicUsize, Ordering};
2113        use std::sync::Arc;
2114        use tauri::Listener;
2115
2116        let app = tauri::test::mock_builder()
2117            .plugin(init(SyncularConfig {
2118                auto_sync: false,
2119                ..Default::default()
2120            }))
2121            .build(tauri::test::mock_context(tauri::test::noop_assets()))
2122            .unwrap();
2123        let broadcast = Arc::new(AtomicUsize::new(0));
2124        let seen = Arc::clone(&broadcast);
2125        app.listen_any("syncular://event", move |_| {
2126            seen.fetch_add(1, Ordering::SeqCst);
2127        });
2128        let call = |command: Value| run_command(app.handle(), command).unwrap();
2129        let schema = json!({ "version": 1, "tables": [{
2130            "name": "todo", "primaryKey": "id",
2131            "columns": [{ "name": "id", "type": "string", "nullable": false }],
2132            "scopes": []
2133        }] });
2134        let refused = call(json!({ "method": "create", "params": {
2135            "schema": schema, "events": null
2136        } }));
2137        assert_eq!(
2138            refused["error"]["code"], "sync.invalid_request",
2139            "{refused}"
2140        );
2141        let created = call(json!({ "method": "create", "params": { "schema": schema } }));
2142        assert!(created.get("error").is_none(), "{created}");
2143        call(json!({ "method": "mutate", "params": { "mutations": [{
2144            "op": "upsert", "table": "todo", "values": { "id": "t1" }
2145        }] } }));
2146        // The owner pumps a command's events before it serves the next one.
2147        call(json!({ "method": "localRevision", "params": {} }));
2148        assert_eq!(broadcast.load(Ordering::SeqCst), 0);
2149    }
2150
2151    /// The app has one client, owned by the webview whose `create` succeeded
2152    /// last. Every other command from another webview is refused with a
2153    /// static code and never reaches the client.
2154    #[test]
2155    fn only_the_owning_webview_reaches_the_client() {
2156        let app = tauri::test::mock_builder()
2157            .plugin(init(SyncularConfig {
2158                auto_sync: false,
2159                ..Default::default()
2160            }))
2161            .build(tauri::test::mock_context(tauri::test::noop_assets()))
2162            .unwrap();
2163        let schema = json!({ "version": 1, "tables": [{
2164            "name": "todo", "primaryKey": "id",
2165            "columns": [{ "name": "id", "type": "string", "nullable": false }],
2166            "scopes": []
2167        }] });
2168        let from =
2169            |label: &str, command: Value| run_command_from(app.handle(), label, command).unwrap();
2170        let count = |label: &str| {
2171            tauri::async_runtime::block_on(syncular_query(
2172                app.handle().clone(),
2173                webview(app.handle(), label),
2174                "SELECT count(*) AS n FROM todo".to_owned(),
2175                None,
2176            ))
2177            .unwrap()
2178        };
2179        let refusal = json!({ "error": {
2180            "code": "sync.client_owned_by_another_webview",
2181            "message": "the native client belongs to another webview"
2182        } });
2183        let mutate = json!({ "method": "mutate", "params": { "mutations": [{
2184            "op": "upsert", "table": "todo", "values": { "id": "t1" }
2185        }] } });
2186
2187        // Before any create nobody owns the client; the router answers.
2188        assert_ne!(
2189            from("second", json!({ "method": "localRevision", "params": {} })),
2190            refusal
2191        );
2192
2193        let created = from(
2194            "main",
2195            json!({ "method": "create", "params": { "schema": schema } }),
2196        );
2197        assert!(created.get("error").is_none(), "{created}");
2198        assert_eq!(from("second", mutate.clone()), refusal);
2199        assert_eq!(
2200            from(
2201                "second",
2202                json!({ "method": "querySnapshot", "params": { "sql": "SELECT 1" } })
2203            ),
2204            refusal
2205        );
2206        assert_eq!(
2207            from(
2208                "second",
2209                json!({ "method": "snapshotRead", "params": { "statements": [] } })
2210            ),
2211            refusal
2212        );
2213        assert_eq!(count("second"), refusal);
2214        assert_eq!(
2215            tauri::async_runtime::block_on(syncular_set_headers(
2216                app.handle().clone(),
2217                webview(app.handle(), "second"),
2218                std::collections::BTreeMap::new(),
2219            ))
2220            .unwrap(),
2221            refusal
2222        );
2223        assert_eq!(
2224            count("main")["result"]["rows"][0]["n"],
2225            0,
2226            "the refused mutate reached the client"
2227        );
2228        let owned = from("main", mutate.clone());
2229        assert!(owned.get("error").is_none(), "{owned}");
2230        assert_eq!(count("main")["result"]["rows"][0]["n"], 1);
2231
2232        // A second webview's create takes over; the first is then refused.
2233        let taken = from(
2234            "second",
2235            json!({ "method": "create", "params": { "schema": schema } }),
2236        );
2237        assert!(taken.get("error").is_none(), "{taken}");
2238        assert_eq!(from("main", mutate.clone()), refusal);
2239        assert_eq!(count("main"), refusal);
2240        assert_eq!(count("second")["result"]["rows"][0]["n"], 0);
2241
2242        // A refused create leaves the owner in place.
2243        let refused = from(
2244            "main",
2245            json!({ "method": "create", "params": { "schema": schema, "events": null } }),
2246        );
2247        assert_eq!(
2248            refused["error"]["code"], "sync.invalid_request",
2249            "{refused}"
2250        );
2251        assert_eq!(from("main", mutate), refusal);
2252        assert!(
2253            from("second", json!({ "method": "localRevision", "params": {} }))
2254                .get("error")
2255                .is_none()
2256        );
2257    }
2258
2259    /// The owner-thread mailbox loop end-to-end, without any Tauri window: post
2260    /// commands, collect emitted events. This is the real host path — the Tauri
2261    /// commands are a two-line channel forward over exactly this.
2262    #[test]
2263    fn owner_thread_round_trips_over_mailbox() {
2264        use std::sync::mpsc::channel;
2265        use std::sync::{Arc, Mutex as StdMutex};
2266
2267        let (tx, rx) = channel::<Request>();
2268        let events: Arc<StdMutex<Vec<Value>>> = Arc::new(StdMutex::new(Vec::new()));
2269        let events_for_thread = Arc::clone(&events);
2270        let config = SyncularConfig {
2271            auto_sync: false,
2272            ..Default::default()
2273        };
2274        let owner_tx = tx.clone();
2275        let handle = std::thread::spawn(move || {
2276            run_owner_thread(config, owner_tx, rx, move |v| {
2277                events_for_thread.lock().unwrap().push(v.clone());
2278            });
2279        });
2280
2281        let call = |command: Value| -> Value {
2282            let (rtx, rrx) = channel();
2283            tx.send(Request::Command {
2284                command,
2285                reply: rtx,
2286            })
2287            .unwrap();
2288            rrx.recv().unwrap()
2289        };
2290
2291        let schema = json!({
2292            "version": 1,
2293            "tables": [{
2294                "name": "todo", "primaryKey": "id",
2295                "columns": [
2296                    { "name": "id", "type": "string", "nullable": false },
2297                    { "name": "title", "type": "string", "nullable": false }
2298                ],
2299                "scopes": []
2300            }]
2301        });
2302        assert_eq!(
2303            call(json!({ "method": "create", "params": { "clientId": "c1", "schema": schema } }))
2304                ["result"],
2305            json!({})
2306        );
2307        call(json!({ "method": "mutate", "params": { "mutations": [{
2308            "op": "upsert", "table": "todo", "values": { "id": "t1", "title": "hi" }
2309        }] } }));
2310
2311        // A query over the mailbox.
2312        let (qtx, qrx) = channel();
2313        tx.send(Request::Query {
2314            sql: "SELECT title FROM todo".to_owned(),
2315            params: Value::Null,
2316            reply: qtx,
2317        })
2318        .unwrap();
2319        let rows = qrx.recv().unwrap();
2320        assert_eq!(rows["result"]["rows"][0]["title"], "hi");
2321
2322        // Header rotation rides the same mailbox; a
2323        // client-local (Null-transport) core accepts and ignores the set.
2324        let (htx, hrx) = channel();
2325        tx.send(Request::SetHeaders {
2326            headers: vec![("authorization".to_owned(), "Bearer fresh".to_owned())],
2327            reply: htx,
2328        })
2329        .unwrap();
2330        assert_eq!(hrx.recv().unwrap()["result"], Value::Null);
2331
2332        tx.send(Request::Shutdown).unwrap();
2333        handle.join().unwrap();
2334
2335        let seen = events.lock().unwrap();
2336        let kinds: Vec<String> = seen
2337            .iter()
2338            .filter_map(|e| e.get("type").and_then(Value::as_str).map(str::to_owned))
2339            .collect();
2340        // The local mutate emits the exact revisioned batch onto the channel.
2341        assert!(kinds.iter().any(|k| k == "change"), "kinds: {kinds:?}");
2342    }
2343
2344    /// The scripted server's sections for one non-reset round (SPEC §4.3):
2345    /// an empty bootstrap pinned at 0 answering the `{id: "one"}` unit's
2346    /// `PROGRESS`, then the live section with `commits` through `through_seq`.
2347    #[cfg(feature = "native-transport")]
2348    fn scripted_sections(
2349        request: &ssp2::model::Message,
2350        through_seq: i64,
2351        commits: Vec<ssp2::model::Frame>,
2352    ) -> Vec<ssp2::model::Frame> {
2353        use ssp2::model::{Frame, LiveStatus, SubStatus};
2354        use ssp2::segment::{Column, ColumnType, RowsSegment};
2355        let unit = ssp2::registration::unit_id(&[("id".into(), "one".into())]);
2356        let mut frames = Vec::new();
2357        if request
2358            .frames
2359            .iter()
2360            .any(|frame| matches!(frame, Frame::Progress { id, .. } if *id == unit))
2361        {
2362            frames.push(Frame::SubStart {
2363                id: unit,
2364                status: SubStatus::Active,
2365                reason_code: String::new(),
2366                bootstrap: true,
2367                fenced: vec![],
2368            });
2369            frames.push(Frame::SegmentInline {
2370                payload: ssp2::segment::encode_rows_segment(&RowsSegment {
2371                    table: "todo".into(),
2372                    schema_version: 1,
2373                    columns: ["id", "title"]
2374                        .map(|name| Column {
2375                            name: name.into(),
2376                            ty: ColumnType::String,
2377                            nullable: false,
2378                        })
2379                        .into(),
2380                    blocks: vec![],
2381                }),
2382            });
2383            frames.push(Frame::SubEnd {
2384                next_cursor: 0,
2385                bootstrap_state: None,
2386            });
2387        }
2388        frames.push(Frame::LiveStart {
2389            status: LiveStatus::Active,
2390            reason_code: String::new(),
2391        });
2392        frames.extend(commits);
2393        frames.push(Frame::LiveEnd {
2394            through_seq,
2395            echo_digest: Some([7; 32]),
2396        });
2397        frames
2398    }
2399
2400    #[cfg(feature = "native-transport")]
2401    #[test]
2402    fn pending_network_round_keeps_local_mutations_and_queries_responsive() {
2403        use ssp2::model::{Change, Frame, Message, MsgKind, Op, OpResult, PushStatus};
2404        use ssp2::segment::{encode_row, Column, ColumnType, ColumnValue};
2405        use std::io::{Read, Write};
2406        use std::net::TcpListener;
2407        use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
2408        use std::sync::mpsc::channel;
2409        use std::sync::Arc;
2410
2411        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2412        let address = listener.local_addr().unwrap();
2413        let (entered_tx, entered_rx) = channel();
2414        let (release_tx, release_rx) = channel();
2415        let (delivered_tx, delivered_rx) = channel();
2416        let (ack_tx, ack_rx) = channel();
2417        let image_sent = Arc::new(AtomicBool::new(false));
2418        let server_image_sent = image_sent.clone();
2419        let requests = Arc::new(AtomicUsize::new(0));
2420        let server_requests = requests.clone();
2421        let server = std::thread::spawn(move || {
2422            let mut pushed = Vec::new();
2423            loop {
2424                let (mut socket, _) = listener.accept().unwrap();
2425                server_requests.fetch_add(1, Ordering::SeqCst);
2426                let mut header = Vec::new();
2427                while !header.ends_with(b"\r\n\r\n") {
2428                    let mut byte = [0];
2429                    socket.read_exact(&mut byte).unwrap();
2430                    header.push(byte[0]);
2431                }
2432                let header = String::from_utf8(header).unwrap();
2433                assert!(header
2434                    .to_ascii_lowercase()
2435                    .contains("authorization: bearer fresh"));
2436                let length: usize = header
2437                    .lines()
2438                    .find_map(|line| {
2439                        let (name, value) = line.split_once(':')?;
2440                        name.eq_ignore_ascii_case("content-length")
2441                            .then(|| value.trim().parse().unwrap())
2442                    })
2443                    .unwrap();
2444                let mut bytes = vec![0; length];
2445                socket.read_exact(&mut bytes).unwrap();
2446                let request = ssp2::decode_message(&bytes).unwrap();
2447                let reset = matches!(
2448                    &request.frames[0],
2449                    Frame::ReqHeader {
2450                        log_epoch: None,
2451                        ..
2452                    }
2453                );
2454                let deliver = !reset && pushed.len() == 3;
2455                let mut frames = vec![Frame::RespHeader {
2456                    required_schema_version: None,
2457                    latest_schema_version: None,
2458                    log_epoch: "epoch".into(),
2459                    reset_required: reset,
2460                }];
2461                if !reset {
2462                    let commits: Vec<_> = request
2463                        .frames
2464                        .iter()
2465                        .filter_map(|frame| {
2466                            if let Frame::PushCommit {
2467                                client_commit_id,
2468                                operations,
2469                                ..
2470                            } = frame
2471                            {
2472                                Some((client_commit_id.clone(), operations.len()))
2473                            } else {
2474                                None
2475                            }
2476                        })
2477                        .collect();
2478                    if !commits.is_empty() && pushed.is_empty() {
2479                        entered_tx.send(()).unwrap();
2480                        release_rx.recv().unwrap();
2481                    }
2482                    for (id, count) in commits {
2483                        pushed.push(id.clone());
2484                        frames.push(Frame::PushResult {
2485                            client_commit_id: id,
2486                            status: PushStatus::Applied,
2487                            commit_seq: Some(pushed.len() as i64),
2488                            results: (0..count)
2489                                .map(|i| OpResult::Applied { op_index: i as i32 })
2490                                .collect(),
2491                        });
2492                    }
2493                }
2494                if !reset {
2495                    let mut commits = Vec::new();
2496                    if deliver {
2497                        assert!(request
2498                            .frames
2499                            .iter()
2500                            .any(|frame| matches!(frame, Frame::PullHeader { .. })));
2501                        assert!(!request
2502                            .frames
2503                            .iter()
2504                            .any(|frame| matches!(frame, Frame::PushCommit { .. })));
2505                        let columns = ["id", "title"].map(|name| Column {
2506                            name: name.into(),
2507                            ty: ColumnType::String,
2508                            nullable: false,
2509                        });
2510                        let mut row = ssp2::primitives::Writer::new();
2511                        encode_row(
2512                            &mut row,
2513                            &columns,
2514                            &vec![
2515                                Some(ColumnValue::String("one".into())),
2516                                Some(ColumnValue::String("300/v3".into())),
2517                            ],
2518                        );
2519                        commits.push(Frame::Commit {
2520                            commit_seq: 3,
2521                            created_at_ms: 0,
2522                            actor_id: "actor".into(),
2523                            tables: vec!["todo".into()],
2524                            changes: vec![Change {
2525                                table_index: 0,
2526                                row_id: "one".into(),
2527                                op: Op::Upsert,
2528                                row_version: 3,
2529                                scopes: vec![("id".into(), "one".into())],
2530                                row: Some(row.into_bytes()),
2531                            }],
2532                        });
2533                        server_image_sent.store(true, Ordering::SeqCst);
2534                    }
2535                    frames.extend(scripted_sections(
2536                        &request,
2537                        if deliver { 3 } else { 0 },
2538                        commits,
2539                    ));
2540                }
2541                let response = ssp2::encode_message(&Message {
2542                    wire_version: ssp2::decode::WIRE_VERSION,
2543                    msg_kind: MsgKind::Response,
2544                    frames,
2545                });
2546                write!(
2547                    socket,
2548                    "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
2549                    response.len()
2550                )
2551                .unwrap();
2552                socket.write_all(&response).unwrap();
2553                if deliver {
2554                    break;
2555                }
2556            }
2557            pushed
2558        });
2559        let (tx, rx) = channel();
2560        let owner_tx = tx.clone();
2561        let owner = std::thread::spawn(move || {
2562            run_owner_thread(
2563                SyncularConfig {
2564                    base_url: Some(format!("http://{address}")),
2565                    auto_sync: true,
2566                    ..Default::default()
2567                },
2568                owner_tx,
2569                rx,
2570                move |event| {
2571                    if event["type"] == "change" && event["batch"]["outcomesChanged"] == true {
2572                        let _ = ack_tx.send(());
2573                    }
2574                    if image_sent.load(Ordering::SeqCst) && event["type"] == "change" {
2575                        let _ = delivered_tx.send(());
2576                    }
2577                },
2578            )
2579        });
2580        let call = |command: Value| {
2581            let (reply, result) = channel();
2582            tx.send(Request::Command { command, reply }).unwrap();
2583            result
2584        };
2585        let created = call(json!({ "method": "create", "params": {
2586            "clientId": "pending-round", "transportEnabled": false, "securityPreflight": true, "schema": { "version": 1, "tables": [{
2587                "name": "todo", "primaryKey": "id", "columns": [
2588                    { "name": "id", "type": "string", "nullable": false },
2589                    { "name": "title", "type": "string", "nullable": false }
2590                ], "scopes": [{ "pattern": "todo:{id}" }]
2591            }] }
2592        } }));
2593        assert!(created.recv().unwrap().get("error").is_none());
2594        assert!(call(json!({ "method": "activateSecurity", "params": {} }))
2595            .recv()
2596            .unwrap()
2597            .get("error")
2598            .is_none());
2599        assert!(
2600            call(json!({ "method": "subscribe", "params": { "scopes": { "id": "one" } } }))
2601                .recv()
2602                .unwrap()
2603                .get("error")
2604                .is_none()
2605        );
2606        let first = call(json!({ "method": "mutate", "params": { "mutations": [{
2607            "op": "upsert", "table": "todo", "values": { "id": "one", "title": "100/v1" }
2608        }] } }))
2609        .recv()
2610        .unwrap();
2611        let queued_second = call(json!({ "method": "mutate", "params": { "mutations": [{
2612            "op": "patch", "table": "todo", "values": { "id": "one", "title": "200/v2" }
2613        }] } }))
2614        .recv()
2615        .unwrap();
2616        assert_eq!(
2617            call(json!({ "method": "sync" })).recv().unwrap()["result"]["errorCode"],
2618            "sync.offline"
2619        );
2620        assert_eq!(
2621            call(json!({ "method": "connectRealtime" })).recv().unwrap()["error"]["code"],
2622            "sync.offline"
2623        );
2624        assert_eq!(requests.load(Ordering::SeqCst), 0);
2625        let (reply, result) = channel();
2626        tx.send(Request::SetHeaders {
2627            headers: vec![("authorization".into(), "Bearer fresh".into())],
2628            reply,
2629        })
2630        .unwrap();
2631        assert_eq!(result.recv().unwrap()["result"], Value::Null);
2632        assert!(
2633            call(json!({ "method": "setTransportEnabled", "params": { "enabled": true } }))
2634                .recv()
2635                .unwrap()
2636                .get("error")
2637                .is_none()
2638        );
2639        entered_rx.recv_timeout(Duration::from_secs(10)).unwrap();
2640        assert!(
2641            call(json!({ "method": "setTransportEnabled", "params": { "enabled": false } }))
2642                .recv()
2643                .unwrap()
2644                .get("error")
2645                .is_none()
2646        );
2647        let started = Instant::now();
2648        let second = call(json!({ "method": "mutate", "params": { "mutations": [{
2649            "op": "patch", "table": "todo", "values": { "id": "one", "title": "300/v3" }
2650        }] } }));
2651        let local_reply = second.recv_timeout(Duration::from_millis(100));
2652        let elapsed = started.elapsed();
2653        let (query_tx, query_rx) = channel();
2654        tx.send(Request::Query {
2655            sql: "SELECT title FROM todo ORDER BY id".into(),
2656            params: Value::Null,
2657            reply: query_tx,
2658        })
2659        .unwrap();
2660        let local_rows = query_rx.recv_timeout(Duration::from_millis(100));
2661        // Release even on the old blocking implementation, so a failing test
2662        // joins its transport and owner rather than leaving network threads.
2663        release_tx.send(()).unwrap();
2664        let second_reply = local_reply
2665            .clone()
2666            .unwrap_or_else(|_| second.recv().unwrap());
2667        let rows = local_rows
2668            .clone()
2669            .unwrap_or_else(|_| query_rx.recv().unwrap());
2670        // Local mutation emits an outcome batch too; wait for both captured commits' applied outcomes.
2671        loop {
2672            ack_rx.recv_timeout(Duration::from_secs(10)).unwrap();
2673            let outcomes = call(json!({ "method": "commitOutcomes" })).recv().unwrap();
2674            if outcomes["result"]["outcomes"]
2675                .as_array()
2676                .unwrap()
2677                .iter()
2678                .filter(|o| o["status"] == "applied")
2679                .count()
2680                == 2
2681            {
2682                break;
2683            }
2684        }
2685        let paused_count = requests.load(Ordering::SeqCst);
2686        assert_eq!(
2687            call(json!({ "method": "sync" })).recv().unwrap()["result"]["errorCode"],
2688            "sync.offline"
2689        );
2690        assert_eq!(requests.load(Ordering::SeqCst), paused_count);
2691        assert!(
2692            call(json!({ "method": "setTransportEnabled", "params": { "enabled": true } }))
2693                .recv()
2694                .unwrap()
2695                .get("error")
2696                .is_none()
2697        );
2698        delivered_rx
2699            .recv_timeout(Duration::from_secs(10))
2700            .expect("ACK schedules the own-image pull without realtime or a manual round");
2701        let (query_tx, query_rx) = channel();
2702        tx.send(Request::Query {
2703            sql: "SELECT title,_sync_version AS version FROM todo WHERE id='one'".into(),
2704            params: Value::Null,
2705            reply: query_tx,
2706        })
2707        .unwrap();
2708        let delivered = query_rx.recv().unwrap();
2709        assert_eq!(delivered["result"]["rows"][0]["title"], "300/v3");
2710        assert_eq!(delivered["result"]["rows"][0]["version"], 3);
2711        let pushed = server.join().unwrap();
2712        tx.send(Request::Shutdown).unwrap();
2713        owner.join().unwrap();
2714        assert!(
2715            local_reply.is_ok(),
2716            "local mutation waited for network reply"
2717        );
2718        assert!(local_rows.is_ok(), "local query waited for network reply");
2719        eprintln!("second local mutation while network pending: {elapsed:?}");
2720        assert_eq!(rows["result"]["rows"].as_array().unwrap().len(), 1);
2721        assert_eq!(
2722            pushed,
2723            vec![
2724                first["result"]["clientCommitId"].as_str().unwrap(),
2725                queued_second["result"]["clientCommitId"].as_str().unwrap(),
2726                second_reply["result"]["clientCommitId"].as_str().unwrap()
2727            ]
2728        );
2729    }
2730
2731    #[cfg(feature = "native-transport")]
2732    #[test]
2733    fn owner_thread_publishes_refused_connection_evidence() {
2734        use std::net::TcpListener;
2735        use std::sync::{mpsc::channel, Arc, Mutex};
2736
2737        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2738        let address = listener.local_addr().unwrap();
2739        drop(listener);
2740        let events = Arc::new(Mutex::new(Vec::<Value>::new()));
2741        let emitted = Arc::clone(&events);
2742        let (tx, rx) = channel::<Request>();
2743        let owner_tx = tx.clone();
2744        let owner = std::thread::spawn(move || {
2745            run_owner_thread(
2746                SyncularConfig {
2747                    base_url: Some(format!("http://{address}")),
2748                    auto_sync: false,
2749                    ..Default::default()
2750                },
2751                owner_tx,
2752                rx,
2753                move |event| emitted.lock().unwrap().push(event.clone()),
2754            )
2755        });
2756        let call = |command: Value| -> Value {
2757            let (reply, result) = channel();
2758            tx.send(Request::Command { command, reply }).unwrap();
2759            result.recv().unwrap()
2760        };
2761        let created = call(json!({ "method": "create", "params": {
2762            "clientId": "diagnostics-tauri-connect", "transportEnabled": true,
2763            "schema": { "version": 1, "tables": [] }
2764        } }));
2765        assert!(created.get("error").is_none(), "{created}");
2766        call(json!({ "method": "enableDiagnostics", "params": {} }));
2767        let failed = call(json!({ "method": "sync", "params": {} }));
2768        assert_eq!(failed["result"]["details"]["causeKind"], "connect");
2769        let snapshot = call(json!({ "method": "diagnosticsSnapshot", "params": {} }));
2770        assert_eq!(snapshot["result"]["lastRound"]["causeKind"], "connect");
2771        assert_eq!(snapshot["result"]["host"]["connectivity"], "offline");
2772        {
2773            let events = events.lock().unwrap();
2774            assert!(events
2775                .iter()
2776                .any(|event| event["type"] == "progress"
2777                    && event["progress"]["causeKind"] == "connect"));
2778            assert!(events.iter().any(|event| event["type"] == "diagnostics"
2779                && event["snapshot"]["lastRound"]["causeKind"] == "connect"));
2780            let progress = events
2781                .iter()
2782                .rfind(|event| event["type"] == "progress")
2783                .unwrap();
2784            assert!(progress["progress"]["epoch"].is_string());
2785            assert_eq!(
2786                snapshot["result"]["lastRound"]["epoch"],
2787                progress["progress"]["epoch"]
2788            );
2789            assert_eq!(
2790                snapshot["result"]["lastRound"]["attempt"],
2791                progress["progress"]["attempt"]
2792            );
2793        }
2794        tx.send(Request::Shutdown).unwrap();
2795        owner.join().unwrap();
2796    }
2797
2798    #[cfg(feature = "native-transport")]
2799    #[test]
2800    fn owner_thread_publishes_transport_status_and_clears_it_on_recovery() {
2801        use ssp2::model::{Frame, Message, MsgKind};
2802        use std::io::{Read, Write};
2803        use std::net::TcpListener;
2804        use std::sync::{mpsc::channel, Arc, Mutex};
2805
2806        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2807        let address = listener.local_addr().unwrap();
2808        let server = std::thread::spawn(move || {
2809            for round in 0..2 {
2810                let (mut socket, _) = listener.accept().unwrap();
2811                let mut header = Vec::new();
2812                while !header.ends_with(b"\r\n\r\n") {
2813                    let mut byte = [0];
2814                    socket.read_exact(&mut byte).unwrap();
2815                    header.push(byte[0]);
2816                }
2817                let header = String::from_utf8(header).unwrap();
2818                let length: usize = header
2819                    .lines()
2820                    .find_map(|line| {
2821                        let (name, value) = line.split_once(':')?;
2822                        name.eq_ignore_ascii_case("content-length")
2823                            .then(|| value.trim().parse().unwrap())
2824                    })
2825                    .unwrap();
2826                let mut request = vec![0; length];
2827                socket.read_exact(&mut request).unwrap();
2828                if round == 0 {
2829                    let body = b"private-response-secret";
2830                    write!(socket, "HTTP/1.1 500 Internal Server Error\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()).unwrap();
2831                    socket.write_all(body).unwrap();
2832                } else {
2833                    let response = ssp2::encode_message(&Message {
2834                        wire_version: ssp2::decode::WIRE_VERSION,
2835                        msg_kind: MsgKind::Response,
2836                        frames: vec![Frame::RespHeader {
2837                            required_schema_version: None,
2838                            latest_schema_version: None,
2839                            log_epoch: "epoch-1".into(),
2840                            reset_required: true,
2841                        }],
2842                    });
2843                    write!(
2844                        socket,
2845                        "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
2846                        response.len()
2847                    )
2848                    .unwrap();
2849                    socket.write_all(&response).unwrap();
2850                }
2851            }
2852        });
2853        let events = Arc::new(Mutex::new(Vec::<Value>::new()));
2854        let emitted = Arc::clone(&events);
2855        let (tx, rx) = channel::<Request>();
2856        let owner_tx = tx.clone();
2857        let owner = std::thread::spawn(move || {
2858            run_owner_thread(
2859                SyncularConfig {
2860                    base_url: Some(format!("http://{address}")),
2861                    auto_sync: false,
2862                    ..Default::default()
2863                },
2864                owner_tx,
2865                rx,
2866                move |event| emitted.lock().unwrap().push(event.clone()),
2867            )
2868        });
2869        let call = |command: Value| -> Value {
2870            let (reply, result) = channel();
2871            tx.send(Request::Command { command, reply }).unwrap();
2872            result.recv().unwrap()
2873        };
2874        let created = call(json!({ "method": "create", "params": {
2875            "clientId": "diagnostics-tauri", "transportEnabled": true,
2876            "schema": { "version": 1, "tables": [] }
2877        } }));
2878        assert!(created.get("error").is_none(), "{created}");
2879        call(json!({ "method": "enableDiagnostics", "params": {} }));
2880        let failed = call(json!({ "method": "sync", "params": {} }));
2881        assert_eq!(failed["result"]["details"]["causeKind"], "status");
2882        assert_eq!(failed["result"]["details"]["httpStatus"], 500);
2883        let snapshot = call(json!({ "method": "diagnosticsSnapshot", "params": {} }));
2884        assert_eq!(snapshot["result"]["lastRound"]["causeKind"], "status");
2885        assert_eq!(snapshot["result"]["lastRound"]["httpStatus"], 500);
2886        assert_eq!(snapshot["result"]["host"]["connectivity"], "online");
2887        {
2888            let events = events.lock().unwrap();
2889            assert!(events.iter().any(|event| event["type"] == "progress"
2890                && event["progress"]["causeKind"] == "status"
2891                && event["progress"]["httpStatus"] == 500));
2892            assert!(events.iter().any(|event| event["type"] == "diagnostics"
2893                && event["snapshot"]["lastRound"]["httpStatus"] == 500));
2894            assert!(!format!("{events:?}").contains("private-response-secret"));
2895        }
2896        let recovered = call(json!({ "method": "sync", "params": {} }));
2897        assert_eq!(recovered["result"]["ok"], true);
2898        let snapshot = call(json!({ "method": "diagnosticsSnapshot", "params": {} }));
2899        assert_eq!(snapshot["result"]["lastRound"]["status"], "succeeded");
2900        assert!(snapshot["result"]["lastRound"].get("causeKind").is_none());
2901        assert!(snapshot["result"]["lastRound"].get("httpStatus").is_none());
2902        tx.send(Request::Shutdown).unwrap();
2903        owner.join().unwrap();
2904        server.join().unwrap();
2905    }
2906
2907    /// A server that answers every pull with one new commit, so an until-idle
2908    /// drive never idles. It reports each request number on `rounds`.
2909    #[cfg(feature = "native-transport")]
2910    fn endless_commit_server() -> (
2911        std::net::SocketAddr,
2912        std::sync::Arc<std::sync::atomic::AtomicUsize>,
2913        std::sync::Arc<std::sync::atomic::AtomicBool>,
2914        std::thread::JoinHandle<()>,
2915        std::sync::mpsc::Receiver<usize>,
2916    ) {
2917        use ssp2::model::{Change, Frame, Message, MsgKind, Op, OpResult, PushStatus};
2918        use ssp2::segment::{encode_row, Column, ColumnType, ColumnValue};
2919        use std::io::{ErrorKind, Read, Write};
2920        use std::net::TcpListener;
2921        use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
2922        use std::sync::Arc;
2923
2924        let (rounds_tx, rounds) = std::sync::mpsc::channel();
2925        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2926        listener.set_nonblocking(true).unwrap();
2927        let address = listener.local_addr().unwrap();
2928        let requests = Arc::new(AtomicUsize::new(0));
2929        let stop = Arc::new(AtomicBool::new(false));
2930        let server_requests = Arc::clone(&requests);
2931        let server_stop = Arc::clone(&stop);
2932        let server = std::thread::spawn(move || {
2933            let columns = ["id", "title"].map(|name| Column {
2934                name: name.into(),
2935                ty: ColumnType::String,
2936                nullable: false,
2937            });
2938            while !server_stop.load(Ordering::SeqCst) {
2939                let (mut socket, _) = match listener.accept() {
2940                    Ok(accepted) => accepted,
2941                    Err(error) if error.kind() == ErrorKind::WouldBlock => {
2942                        std::thread::yield_now();
2943                        continue;
2944                    }
2945                    Err(error) => panic!("accept: {error}"),
2946                };
2947                socket.set_nonblocking(false).unwrap();
2948                let round = server_requests.fetch_add(1, Ordering::SeqCst) + 1;
2949                let mut header = Vec::new();
2950                while !header.ends_with(b"\r\n\r\n") {
2951                    let mut byte = [0];
2952                    socket.read_exact(&mut byte).unwrap();
2953                    header.push(byte[0]);
2954                }
2955                let header = String::from_utf8(header).unwrap();
2956                let length: usize = header
2957                    .lines()
2958                    .find_map(|line| {
2959                        let (name, value) = line.split_once(':')?;
2960                        name.eq_ignore_ascii_case("content-length")
2961                            .then(|| value.trim().parse().unwrap())
2962                    })
2963                    .unwrap();
2964                let mut bytes = vec![0; length];
2965                socket.read_exact(&mut bytes).unwrap();
2966                let request = ssp2::decode_message(&bytes).unwrap();
2967                let reset = matches!(
2968                    &request.frames[0],
2969                    Frame::ReqHeader {
2970                        log_epoch: None,
2971                        ..
2972                    }
2973                );
2974                let mut frames = vec![Frame::RespHeader {
2975                    required_schema_version: None,
2976                    latest_schema_version: None,
2977                    log_epoch: "epoch".into(),
2978                    reset_required: reset,
2979                }];
2980                if !reset {
2981                    for frame in &request.frames {
2982                        if let Frame::PushCommit {
2983                            client_commit_id, ..
2984                        } = frame
2985                        {
2986                            frames.push(Frame::PushResult {
2987                                client_commit_id: client_commit_id.clone(),
2988                                status: PushStatus::Rejected,
2989                                commit_seq: None,
2990                                results: vec![OpResult::Error {
2991                                    op_index: 0,
2992                                    code: "app.rejected".into(),
2993                                    message: "rejected".into(),
2994                                    retryable: false,
2995                                }],
2996                            });
2997                        }
2998                    }
2999                }
3000                if !reset {
3001                    let mut row = ssp2::primitives::Writer::new();
3002                    encode_row(
3003                        &mut row,
3004                        &columns,
3005                        &vec![
3006                            Some(ColumnValue::String("one".into())),
3007                            Some(ColumnValue::String(format!("v{round}"))),
3008                        ],
3009                    );
3010                    let commit = Frame::Commit {
3011                        commit_seq: round as i64,
3012                        created_at_ms: 0,
3013                        actor_id: "actor".into(),
3014                        tables: vec!["todo".into()],
3015                        changes: vec![Change {
3016                            table_index: 0,
3017                            row_id: "one".into(),
3018                            op: Op::Upsert,
3019                            row_version: round as i64,
3020                            scopes: vec![("id".into(), "one".into())],
3021                            row: Some(row.into_bytes()),
3022                        }],
3023                    };
3024                    frames.extend(scripted_sections(&request, round as i64, vec![commit]));
3025                }
3026                let response = ssp2::encode_message(&Message {
3027                    wire_version: ssp2::decode::WIRE_VERSION,
3028                    msg_kind: MsgKind::Response,
3029                    frames,
3030                });
3031                write!(
3032                    socket,
3033                    "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
3034                    response.len()
3035                )
3036                .unwrap();
3037                socket.write_all(&response).unwrap();
3038                let _ = rounds_tx.send(round);
3039            }
3040        });
3041        (address, requests, stop, server, rounds)
3042    }
3043
3044    #[cfg(feature = "native-transport")]
3045    #[test]
3046    fn owner_thread_sync_until_idle_reports_budget_exhaustion_with_the_report() {
3047        use std::sync::atomic::Ordering;
3048        use std::sync::mpsc::channel;
3049
3050        let (address, requests, stop, server, _rounds) = endless_commit_server();
3051
3052        let (tx, rx) = channel::<Request>();
3053        let owner_tx = tx.clone();
3054        let owner = std::thread::spawn(move || {
3055            run_owner_thread(
3056                SyncularConfig {
3057                    base_url: Some(format!("http://{address}")),
3058                    auto_sync: false,
3059                    ..Default::default()
3060                },
3061                owner_tx,
3062                rx,
3063                |_| {},
3064            )
3065        });
3066        let call = |command: Value| -> Value {
3067            let (reply, result) = channel();
3068            tx.send(Request::Command { command, reply }).unwrap();
3069            result.recv().unwrap()
3070        };
3071
3072        let created = call(json!({ "method": "create", "params": {
3073            "clientId": "budget-tauri", "transportEnabled": true, "retainFailedCommits": true, "schema": { "version": 1, "tables": [{
3074                "name": "todo", "primaryKey": "id",
3075                "columns": [
3076                    { "name": "id", "type": "string", "nullable": false },
3077                    { "name": "title", "type": "string", "nullable": false }
3078                ],
3079                "scopes": [{ "pattern": "todo:{id}" }]
3080            }] }
3081        } }));
3082        assert!(created.get("error").is_none(), "{created}");
3083        assert!(
3084            call(json!({ "method": "subscribe", "params": { "scopes": { "id": "one" } } }))
3085                .get("error")
3086                .is_none()
3087        );
3088
3089        // An invalid budget is refused before any network round.
3090        let before = requests.load(Ordering::SeqCst);
3091        let invalid = call(json!({ "method": "syncUntilIdle", "params": { "maxRounds": 0 } }));
3092        assert_eq!(
3093            invalid["error"]["code"], "sync.invalid_request",
3094            "{invalid}"
3095        );
3096        assert_eq!(
3097            requests.load(Ordering::SeqCst),
3098            before,
3099            "an invalid budget performs no round"
3100        );
3101        for timeout in [json!(0), json!(-1), json!(1.5), json!("60000")] {
3102            let invalid =
3103                call(json!({ "method": "syncUntilIdle", "params": { "timeoutMs": timeout } }));
3104            assert_eq!(
3105                invalid["error"]["code"], "sync.invalid_request",
3106                "{invalid}"
3107            );
3108            assert_eq!(
3109                invalid["error"]["message"], "timeoutMs must be a positive integer",
3110                "{invalid}"
3111            );
3112        }
3113        assert_eq!(
3114            requests.load(Ordering::SeqCst),
3115            before,
3116            "an invalid timeoutMs performs no round"
3117        );
3118
3119        // `sync` ignores an irrelevant maxRounds (0 would be invalid for the
3120        // capped command) and performs one round.
3121        let single = call(json!({ "method": "sync", "params": { "maxRounds": 0 } }));
3122        assert!(single["result"].get("errorCode").is_none(), "{single}");
3123
3124        let before_capped = requests.load(Ordering::SeqCst);
3125        let exhausted = call(json!({ "method": "syncUntilIdle", "params": { "maxRounds": 2 } }));
3126        assert!(
3127            exhausted["result"].get("errorCode").is_none(),
3128            "{exhausted}"
3129        );
3130        assert_eq!(exhausted["result"]["ok"], json!(true), "{exhausted}");
3131        assert_eq!(
3132            exhausted["result"]["budgetExhausted"],
3133            json!(true),
3134            "{exhausted}"
3135        );
3136        assert_eq!(
3137            requests.load(Ordering::SeqCst) - before_capped,
3138            2,
3139            "the capped run made exactly two rounds: {exhausted}"
3140        );
3141        assert_eq!(
3142            exhausted["result"]["report"]["commitsApplied"],
3143            json!(2),
3144            "the aggregate retains every round's work: {exhausted}"
3145        );
3146
3147        let mutated = call(json!({ "method": "mutate", "params": { "mutations": [{
3148            "op": "upsert", "table": "todo", "values": { "id": "one", "title": "mine" }
3149        }] } }));
3150        let id = mutated["result"]["clientCommitId"].as_str().unwrap();
3151        call(json!({ "method": "sync", "params": {} }));
3152        let outcome =
3153            call(json!({ "method": "commitOutcome", "params": { "clientCommitId": id } }));
3154        let before_proof = requests.load(Ordering::SeqCst);
3155        let proof = call(
3156            json!({ "method": "proveCurrentBase", "params": { "outcome": outcome["result"]["outcome"], "maxRounds": 1 } }),
3157        );
3158        assert_eq!(
3159            proof["result"],
3160            json!({ "proven": false, "reason": "budget_exhausted" }),
3161            "{proof}"
3162        );
3163        assert_eq!(requests.load(Ordering::SeqCst) - before_proof, 1);
3164
3165        tx.send(Request::Shutdown).unwrap();
3166        owner.join().unwrap();
3167        stop.store(true, Ordering::SeqCst);
3168        server.join().unwrap();
3169    }
3170
3171    #[cfg(feature = "native-transport")]
3172    #[test]
3173    fn owner_thread_queues_the_next_host_drive_after_budget_exhaustion() {
3174        use std::sync::atomic::Ordering;
3175        use std::sync::mpsc::channel;
3176
3177        let (address, _requests, stop, server, rounds) = endless_commit_server();
3178        let (tx, rx) = channel::<Request>();
3179        let owner_tx = tx.clone();
3180        let owner = std::thread::spawn(move || {
3181            run_owner_thread(
3182                SyncularConfig {
3183                    base_url: Some(format!("http://{address}")),
3184                    auto_sync: true,
3185                    ..Default::default()
3186                },
3187                owner_tx,
3188                rx,
3189                |_| {},
3190            )
3191        });
3192        let call = |command: Value| -> Value {
3193            let (reply, result) = channel();
3194            tx.send(Request::Command { command, reply }).unwrap();
3195            result.recv().unwrap()
3196        };
3197        let created = call(json!({ "method": "create", "params": {
3198            "clientId": "host-budget-tauri", "transportEnabled": true, "schema": { "version": 1, "tables": [{
3199                "name": "todo", "primaryKey": "id",
3200                "columns": [
3201                    { "name": "id", "type": "string", "nullable": false },
3202                    { "name": "title", "type": "string", "nullable": false }
3203                ],
3204                "scopes": [{ "pattern": "todo:{id}" }]
3205            }] }
3206        } }));
3207        assert!(created.get("error").is_none(), "{created}");
3208        // `create` starts the first host drive; the subscription arriving
3209        // during it leaves one coalesced intent for a second. The server
3210        // never idles, so each drive exhausts its 20-round budget, and round
3211        // 41 belongs to a drive no intent started.
3212        call(json!({ "method": "subscribe", "params": { "scopes": { "id": "one" } } }));
3213        for _ in 0..41 {
3214            rounds
3215                .recv_timeout(Duration::from_secs(10))
3216                .expect("the host drive continues after budget exhaustion");
3217        }
3218
3219        tx.send(Request::Shutdown).unwrap();
3220        owner.join().unwrap();
3221        stop.store(true, Ordering::SeqCst);
3222        server.join().unwrap();
3223    }
3224
3225    #[test]
3226    fn snapshot_reader_is_not_blocked_by_the_network_owner_mailbox() {
3227        use std::sync::mpsc::channel;
3228
3229        let path =
3230            std::env::temp_dir().join(format!("syncular-tauri-sidecar-{}.db", std::process::id()));
3231        let config = SyncularConfig {
3232            db_path: Some(path.to_string_lossy().into_owned()),
3233            auto_sync: false,
3234            ..Default::default()
3235        };
3236        let (tx, rx) = channel::<Request>();
3237        let owner_tx = tx.clone();
3238        let owner = std::thread::spawn(move || run_owner_thread(config, owner_tx, rx, |_| {}));
3239
3240        let (create_tx, create_rx) = channel();
3241        tx.send(Request::Command {
3242            command: json!({
3243                "method": "create",
3244                "params": {
3245                    "clientId": "sidecar-client",
3246                    "schema": { "version": 1, "tables": [] },
3247                    "dbPath": path.to_string_lossy()
3248                }
3249            }),
3250            reply: create_tx,
3251        })
3252        .expect("post create");
3253        assert_eq!(create_rx.recv().expect("create reply")["result"], json!({}));
3254
3255        let (read_tx, read_rx) = channel::<ReadRequest>();
3256        let read_path = path.to_string_lossy().into_owned();
3257        let owner_tx = tx.clone();
3258        let reader = std::thread::spawn(move || run_reader_thread(read_path, read_rx, owner_tx));
3259
3260        // Model a slow HTTP/WS round on the mutable owner. The dedicated read
3261        // mailbox must still return the durable local snapshot immediately.
3262        let (entered_tx, entered_rx) = channel();
3263        tx.send(Request::Block {
3264            duration: Duration::from_millis(200),
3265            entered: entered_tx,
3266        })
3267        .expect("block owner");
3268        entered_rx.recv().expect("owner entered blocking round");
3269        let (snapshot_tx, snapshot_rx) = channel();
3270        read_tx
3271            .send(ReadRequest::QuerySnapshot {
3272                sql: "SELECT 1 AS value".to_owned(),
3273                params: Vec::new(),
3274                coverage: Vec::new(),
3275                owner: None,
3276                reply: snapshot_tx,
3277            })
3278            .expect("post snapshot");
3279        let snapshot = snapshot_rx
3280            .recv_timeout(Duration::from_millis(50))
3281            .expect("local snapshot must not wait for the owner");
3282        assert_eq!(snapshot["result"]["rows"][0]["value"], 1);
3283
3284        let (failed_tx, failed_rx) = channel();
3285        read_tx
3286            .send(ReadRequest::QuerySnapshot {
3287                sql: "SELECT private_value FROM missing_private_table".to_owned(),
3288                params: Vec::new(),
3289                coverage: Vec::new(),
3290                owner: Some(("queries:missing".to_owned(), vec!["tasks".to_owned()])),
3291                reply: failed_tx,
3292            })
3293            .expect("post failed snapshot");
3294        assert_eq!(
3295            failed_rx.recv().expect("failed snapshot reply")["error"]["code"],
3296            "client.failed"
3297        );
3298        let (diagnostics_tx, diagnostics_rx) = channel();
3299        tx.send(Request::Command {
3300            command: json!({ "method": "diagnosticsSnapshot", "params": {} }),
3301            reply: diagnostics_tx,
3302        })
3303        .expect("post diagnostics");
3304        assert_eq!(
3305            diagnostics_rx.recv().expect("diagnostics reply")["result"]["queryFailures"][0]["id"],
3306            "queries:missing"
3307        );
3308
3309        let (recovered_tx, recovered_rx) = channel();
3310        read_tx
3311            .send(ReadRequest::QuerySnapshot {
3312                sql: "SELECT 1 AS value".to_owned(),
3313                params: Vec::new(),
3314                coverage: Vec::new(),
3315                owner: Some(("queries:missing".to_owned(), vec!["tasks".to_owned()])),
3316                reply: recovered_tx,
3317            })
3318            .expect("post recovered snapshot");
3319        assert!(recovered_rx.recv().expect("recovered snapshot reply")["result"].is_object());
3320        let (cleared_tx, cleared_rx) = channel();
3321        tx.send(Request::Command {
3322            command: json!({ "method": "diagnosticsSnapshot", "params": {} }),
3323            reply: cleared_tx,
3324        })
3325        .expect("post cleared diagnostics");
3326        assert_eq!(
3327            cleared_rx.recv().expect("cleared diagnostics reply")["result"]["queryFailures"],
3328            json!([])
3329        );
3330
3331        // More distinct failed owners than the diagnostic cap cannot leave
3332        // extra process-lifetime bookkeeping in the sidecar.
3333        for index in 0..300 {
3334            let (reply, result) = channel();
3335            read_tx
3336                .send(ReadRequest::QuerySnapshot {
3337                    sql: "SELECT value FROM absent_owner_table".to_owned(),
3338                    params: Vec::new(),
3339                    coverage: Vec::new(),
3340                    owner: Some((format!("owner-{index}"), vec!["tasks".to_owned()])),
3341                    reply,
3342                })
3343                .expect("post owner failure");
3344            assert!(result.recv().expect("failure reply")["error"].is_object());
3345        }
3346        let (reply, result) = channel();
3347        tx.send(Request::Command {
3348            command: json!({ "method": "diagnosticsSnapshot", "params": {} }),
3349            reply,
3350        })
3351        .expect("post bounded diagnostics");
3352        let value = result.recv().expect("bounded diagnostics");
3353        let failures = value["result"]["queryFailures"].as_array().unwrap();
3354        assert_eq!(failures.len(), 256);
3355        assert_eq!(failures.last().unwrap()["id"], "owner-299");
3356
3357        read_tx.send(ReadRequest::Shutdown).expect("stop reader");
3358        reader.join().expect("join reader");
3359        tx.send(Request::Shutdown).expect("stop owner");
3360        owner.join().expect("join owner");
3361        std::fs::remove_file(path).expect("remove temp database");
3362    }
3363    #[test]
3364    fn read_failure_json_preserves_retryability_and_storage_details() {
3365        let busy = QueryReadFailure {
3366            code: Some("client.storage_busy"),
3367            sqlite_code: Some(5),
3368            sqlite_message: Some("database is locked".to_owned()),
3369            rollback_failure: Some(Box::new(QueryReadFailure {
3370                code: Some("client.storage_busy"),
3371                sqlite_code: Some(6),
3372                sqlite_message: Some("rollback could not lock".to_owned()),
3373                rollback_failure: None,
3374                message: "local SQLite storage is busy".to_owned(),
3375            })),
3376            message: "local SQLite storage is busy".to_owned(),
3377        };
3378        let value = read_failure_json(busy);
3379        assert_eq!(value["error"]["code"], "client.storage_busy");
3380        assert_eq!(value["error"]["retryable"], true);
3381        assert_eq!(value["error"]["details"]["sqliteCode"], 5);
3382        assert_eq!(
3383            value["error"]["details"]["sqliteMessage"],
3384            "database is locked"
3385        );
3386        assert_eq!(
3387            value["error"]["details"]["rollbackFailure"]["sqliteCode"],
3388            6
3389        );
3390        let corrupt = read_failure_json(QueryReadFailure {
3391            code: Some("sync.local_corrupt"),
3392            sqlite_code: None,
3393            sqlite_message: None,
3394            rollback_failure: None,
3395            message: "persisted local revision is invalid".to_owned(),
3396        });
3397        assert_eq!(corrupt["error"]["code"], "sync.local_corrupt");
3398        assert_eq!(corrupt["error"]["retryable"], false);
3399        assert!(corrupt["error"]["details"].is_null());
3400    }
3401
3402    #[test]
3403    fn snapshot_read_command_is_strict_and_dispatches_by_storage_mode() {
3404        use tauri::test::{mock_builder, mock_context, noop_assets};
3405
3406        let path =
3407            std::env::temp_dir().join(format!("syncular-tauri-snapshot-{}.db", std::process::id()));
3408        let _ = std::fs::remove_file(&path);
3409        let file_app = mock_builder()
3410            .plugin(init(SyncularConfig {
3411                db_path: Some(path.to_string_lossy().into_owned()),
3412                auto_sync: false,
3413                ..Default::default()
3414            }))
3415            .build(mock_context(noop_assets()))
3416            .expect("build file app");
3417        let command = |value: Value| run_command(file_app.handle(), value).expect("command reply");
3418        let read = |statements: Value, owner: Option<Value>| {
3419            tauri::async_runtime::block_on(syncular_snapshot_read(
3420                file_app.handle().clone(),
3421                statements,
3422                None,
3423                None,
3424                None,
3425                owner,
3426            ))
3427            .expect("read reply")
3428        };
3429        let schema = json!({
3430            "version": 1,
3431            "tables": [{
3432                "name": "todo", "primaryKey": "id",
3433                "columns": [
3434                    { "name": "id", "type": "string", "nullable": false },
3435                    { "name": "n", "type": "integer", "nullable": true }
3436                ],
3437                "scopes": []
3438            }]
3439        });
3440        assert_eq!(
3441            command(json!({ "method": "create", "params": {
3442                "clientId": "c1", "schema": schema.clone()
3443            } }))["result"],
3444            json!({})
3445        );
3446        // §2.4: authored row integers are bounded to the JavaScript safe range
3447        // (±(2^53−1)); the boundary value must queue a commit.
3448        let mutation = command(json!({ "method": "mutate", "params": { "mutations": [{
3449            "op": "upsert", "table": "todo",
3450            "values": { "id": "r1", "n": 9_007_199_254_740_991u64 }
3451        }] } }));
3452        assert!(
3453            mutation["result"]["clientCommitId"].as_str().is_some(),
3454            "safe authoring must queue a commit: {mutation}"
3455        );
3456
3457        // File-backed: one sidecar read returns the revision and every row.
3458        // The literal keeps the driver's full-width i64 `$bigint` envelope
3459        // covered through the same multi-statement read, because the
3460        // synchronized-row contract cannot carry that value through authoring.
3461        let ok = read(
3462            json!([
3463                { "sql": "SELECT id, n FROM todo" },
3464                { "sql": "SELECT CAST('9007199254740993' AS INTEGER) AS n FROM todo" }
3465            ]),
3466            None,
3467        );
3468        assert!(
3469            ok["result"]["revision"].as_str().is_some(),
3470            "expected a decimal revision: {ok}"
3471        );
3472        assert_eq!(ok["result"]["queries"][0][0]["id"], "r1");
3473        assert_eq!(
3474            ok["result"]["queries"][0][0]["n"],
3475            json!(9_007_199_254_740_991u64)
3476        );
3477        assert_eq!(
3478            ok["result"]["queries"][1][0]["n"]["$bigint"],
3479            "9007199254740993"
3480        );
3481
3482        // A malformed statement `params` and a non-array `statements` are
3483        // stable invalid requests, never silently defaulted.
3484        let malformed = read(json!([{ "sql": "SELECT ?", "params": "oops" }]), None);
3485        assert_eq!(
3486            malformed["error"]["code"], "sync.invalid_request",
3487            "{malformed}"
3488        );
3489        let nonarray = read(json!("oops"), None);
3490        assert_eq!(
3491            nonarray["error"]["code"], "sync.invalid_request",
3492            "{nonarray}"
3493        );
3494
3495        // §7.6: an owned sidecar failure reaches diagnostics.
3496        let failed = read(
3497            json!([{ "sql": "SELECT * FROM does_not_exist" }]),
3498            Some(json!({ "id": "queries:snapshot", "tables": ["todo"] })),
3499        );
3500        assert!(failed["error"].is_object(), "{failed}");
3501        let diagnostics = command(json!({ "method": "diagnosticsSnapshot", "params": {} }));
3502        assert_eq!(
3503            diagnostics["result"]["queryFailures"][0]["id"], "queries:snapshot",
3504            "{diagnostics}"
3505        );
3506        // An owned success on the file route clears the recorded failure.
3507        let recovered = read(
3508            json!([{ "sql": "SELECT 1 AS n" }]),
3509            Some(json!({ "id": "queries:snapshot", "tables": ["todo"] })),
3510        );
3511        assert!(recovered["result"].is_object(), "{recovered}");
3512        let cleared = command(json!({ "method": "diagnosticsSnapshot", "params": {} }));
3513        assert_eq!(
3514            cleared["result"]["queryFailures"],
3515            json!([]),
3516            "a successful owned file read clears the failure: {cleared}"
3517        );
3518
3519        command(json!({ "method": "shutdown" }));
3520
3521        // In-memory: the same command falls back to the owner connection.
3522        let memory_app = mock_builder()
3523            .plugin(init(SyncularConfig {
3524                auto_sync: false,
3525                ..Default::default()
3526            }))
3527            .build(mock_context(noop_assets()))
3528            .expect("build memory app");
3529        let memory_command =
3530            |value: Value| run_command(memory_app.handle(), value).expect("command reply");
3531        let memory_read = |statements: Value| {
3532            tauri::async_runtime::block_on(syncular_snapshot_read(
3533                memory_app.handle().clone(),
3534                statements,
3535                None,
3536                None,
3537                None,
3538                None,
3539            ))
3540            .expect("read reply")
3541        };
3542        assert_eq!(
3543            memory_command(json!({ "method": "create", "params": {
3544                "clientId": "c2", "schema": schema
3545            } }))["result"],
3546            json!({})
3547        );
3548        let memory_ok = memory_read(json!([{ "sql": "SELECT 7 AS n" }]));
3549        assert_eq!(memory_ok["result"]["queries"][0][0]["n"], 7, "{memory_ok}");
3550
3551        // The in-memory route uses the owner connection with the same owner
3552        // contract: failure is recorded and a later success clears it.
3553        let memory_failed = tauri::async_runtime::block_on(syncular_snapshot_read(
3554            memory_app.handle().clone(),
3555            json!([{ "sql": "SELECT * FROM does_not_exist" }]),
3556            None,
3557            None,
3558            None,
3559            Some(json!({ "id": "queries:memory", "tables": ["todo"] })),
3560        ))
3561        .expect("read reply");
3562        assert!(memory_failed["error"].is_object(), "{memory_failed}");
3563        let memory_diagnostics =
3564            memory_command(json!({ "method": "diagnosticsSnapshot", "params": {} }));
3565        assert_eq!(
3566            memory_diagnostics["result"]["queryFailures"][0]["id"], "queries:memory",
3567            "{memory_diagnostics}"
3568        );
3569        let memory_recovered = tauri::async_runtime::block_on(syncular_snapshot_read(
3570            memory_app.handle().clone(),
3571            json!([{ "sql": "SELECT 1 AS n" }]),
3572            None,
3573            None,
3574            None,
3575            Some(json!({ "id": "queries:memory", "tables": ["todo"] })),
3576        ))
3577        .expect("read reply");
3578        assert!(memory_recovered["result"].is_object(), "{memory_recovered}");
3579        let memory_cleared =
3580            memory_command(json!({ "method": "diagnosticsSnapshot", "params": {} }));
3581        assert_eq!(
3582            memory_cleared["result"]["queryFailures"],
3583            json!([]),
3584            "a successful owned in-memory read clears the failure: {memory_cleared}"
3585        );
3586
3587        let _ = std::fs::remove_file(&path);
3588    }
3589
3590    #[test]
3591    fn a_file_backed_owned_read_serves_the_same_reply_on_both_public_routes() {
3592        use tauri::test::{mock_builder, mock_context, noop_assets};
3593
3594        let path = std::env::temp_dir().join(format!(
3595            "syncular-tauri-read-routes-{}.db",
3596            std::process::id()
3597        ));
3598        let _ = std::fs::remove_file(&path);
3599        let app = mock_builder()
3600            .plugin(init(SyncularConfig {
3601                db_path: Some(path.to_string_lossy().into_owned()),
3602                auto_sync: false,
3603                ..Default::default()
3604            }))
3605            .build(mock_context(noop_assets()))
3606            .expect("build file app");
3607        let command = |value: Value| run_command(app.handle(), value).expect("command reply");
3608        let dedicated_snapshot = |sql: &str, owner: Option<Value>| {
3609            tauri::async_runtime::block_on(syncular_query_snapshot(
3610                app.handle().clone(),
3611                webview(app.handle(), "main"),
3612                sql.to_owned(),
3613                None,
3614                None,
3615                owner,
3616            ))
3617            .expect("dedicated snapshot reply")
3618        };
3619        let dedicated_read = |statements: Value, owner: Option<Value>| {
3620            tauri::async_runtime::block_on(syncular_snapshot_read(
3621                app.handle().clone(),
3622                statements,
3623                None,
3624                None,
3625                None,
3626                owner,
3627            ))
3628            .expect("dedicated read reply")
3629        };
3630        let ids = || -> Vec<String> {
3631            command(json!({ "method": "diagnosticsSnapshot", "params": {} }))["result"]
3632                ["queryFailures"]
3633                .as_array()
3634                .expect("query failures array")
3635                .iter()
3636                .map(|failure| failure["id"].as_str().expect("failure id").to_owned())
3637                .collect()
3638        };
3639        assert_eq!(
3640            command(json!({ "method": "create", "params": {
3641                "clientId": "read-routes",
3642                "schema": { "version": 1, "tables": [] },
3643            } }))["result"],
3644            json!({})
3645        );
3646        let owner = json!({ "id": "queries:routes", "tables": ["tasks"] });
3647
3648        // A successful owned read has one reply shape on both public routes,
3649        // because the generic entry is normalized onto the file sidecar.
3650        assert_eq!(
3651            command(json!({ "method": "querySnapshot", "params": {
3652                "sql": "SELECT 1 AS value",
3653                "owner": owner,
3654            } })),
3655            dedicated_snapshot("SELECT 1 AS value", Some(owner.clone())),
3656            "querySnapshot serves one reply on both routes"
3657        );
3658        assert_eq!(
3659            command(json!({ "method": "snapshotRead", "params": {
3660                "statements": [{ "sql": "SELECT 1 AS value" }],
3661                "owner": owner,
3662            } })),
3663            dedicated_read(json!([{ "sql": "SELECT 1 AS value" }]), Some(owner.clone()),),
3664            "snapshotRead serves one reply on both routes"
3665        );
3666        assert_eq!(ids(), Vec::<String>::new(), "clean reads record nothing");
3667
3668        // A failure on either route is cleared by a success on the other.
3669        assert!(command(json!({ "method": "querySnapshot", "params": {
3670            "sql": "SELECT value FROM absent_owner_table",
3671            "owner": owner,
3672        } }))["error"]
3673            .is_object());
3674        assert_eq!(ids(), ["queries:routes"]);
3675        assert!(
3676            dedicated_read(json!([{ "sql": "SELECT 1 AS value" }]), Some(owner.clone()),)["result"]
3677                .is_object()
3678        );
3679        assert_eq!(
3680            ids(),
3681            Vec::<String>::new(),
3682            "the dedicated route cleared the generic route's failure"
3683        );
3684        assert!(
3685            dedicated_snapshot("SELECT value FROM absent_owner_table", Some(owner.clone()))
3686                ["error"]
3687                .is_object()
3688        );
3689        assert_eq!(ids(), ["queries:routes"]);
3690        assert!(command(json!({ "method": "snapshotRead", "params": {
3691            "statements": [{ "sql": "SELECT 1 AS value" }],
3692            "owner": owner,
3693        } }))["result"]
3694            .is_object());
3695        assert_eq!(
3696            ids(),
3697            Vec::<String>::new(),
3698            "the generic route cleared the dedicated route's failure"
3699        );
3700
3701        // Required fields and malformed shapes keep the errors they had before
3702        // the delegation, so nothing about invalid requests changes.
3703        let missing_sql = command(json!({ "method": "querySnapshot", "params": {} }));
3704        assert_eq!(missing_sql["error"]["code"], "client.failed");
3705        assert_eq!(missing_sql["error"]["message"], "querySnapshot missing sql");
3706        let malformed = command(json!({ "method": "querySnapshot", "params": {
3707            "sql": "SELECT 1",
3708            "params": "oops",
3709            "owner": owner,
3710        } }));
3711        assert_eq!(malformed["error"]["code"], "client.failed");
3712        assert_eq!(
3713            malformed["error"]["message"],
3714            "querySnapshot params must be a list"
3715        );
3716        let malformed = command(json!({ "method": "snapshotRead", "params": {
3717            "statements": "oops",
3718            "owner": owner,
3719        } }));
3720        assert_eq!(malformed["error"]["code"], "sync.invalid_request");
3721        assert_eq!(
3722            malformed["error"]["message"],
3723            "sync.invalid_request: snapshotRead statements must be a list"
3724        );
3725
3726        let _ = std::fs::remove_file(&path);
3727    }
3728
3729    #[test]
3730    fn a_delayed_owner_receives_only_reader_failure_transitions() {
3731        use std::sync::mpsc::channel;
3732
3733        let path = std::env::temp_dir().join(format!(
3734            "syncular-tauri-read-transitions-{}.db",
3735            std::process::id()
3736        ));
3737        let _ = std::fs::remove_file(&path);
3738        // A real replica: the sidecar's snapshot read needs the bookkeeping
3739        // tables the client creates on open, and the absent table drives the
3740        // owned failures.
3741        drop(
3742            syncular_client::SyncClient::open_path(
3743                "read-transitions".to_owned(),
3744                &json!({ "version": 1, "tables": [] }),
3745                syncular_client::ClientLimits::default(),
3746                &path.to_string_lossy(),
3747            )
3748            .expect("create replica"),
3749        );
3750
3751        let (owner_tx, owner_rx) = channel::<Request>();
3752        let (read_tx, read_rx) = channel::<ReadRequest>();
3753        let read_path = path.to_string_lossy().into_owned();
3754        // The owning thread is deliberately absent: it neither records nor
3755        // publishes anything, so the reader has to decide every transition on
3756        // its own and must never wait for the owner to drain an earlier message.
3757        let reader = std::thread::spawn(move || run_reader_thread(read_path, read_rx, owner_tx));
3758
3759        let clean = "SELECT 1 AS value";
3760        let failing = "SELECT value FROM absent_owner_table";
3761        let owner = |id: &str, tables: &[&str]| {
3762            Some((
3763                id.to_owned(),
3764                tables.iter().map(|table| (*table).to_owned()).collect(),
3765            ))
3766        };
3767        let query_snapshot = |sql: &str, owner: Option<(String, Vec<String>)>| {
3768            let (reply, result) = channel();
3769            read_tx
3770                .send(ReadRequest::QuerySnapshot {
3771                    sql: sql.to_owned(),
3772                    params: Vec::new(),
3773                    coverage: Vec::new(),
3774                    owner,
3775                    reply,
3776                })
3777                .expect("post snapshot read");
3778            result.recv().expect("snapshot reply")
3779        };
3780        let snapshot_read = |sql: &str, owner: Option<(String, Vec<String>)>| {
3781            let (reply, result) = channel();
3782            read_tx
3783                .send(ReadRequest::SnapshotRead {
3784                    statements: vec![(sql.to_owned(), Vec::<syncular_client::QueryValue>::new())],
3785                    coverage: Vec::new(),
3786                    units: Vec::new(),
3787                    commit_ids: Vec::new(),
3788                    owner,
3789                    reply,
3790                })
3791                .expect("post multi-statement read");
3792            result.recv().expect("multi-statement read reply")
3793        };
3794        /// Drain the queued owner messages without processing them: the count
3795        /// and each outcome are the assertion.
3796        fn drain(owner_rx: &Receiver<Request>) -> Vec<Option<QueryReadFailure>> {
3797            let mut messages = Vec::new();
3798            while let Ok(Request::QueryRead { failure, .. }) = owner_rx.try_recv() {
3799                messages.push(failure);
3800            }
3801            messages
3802        }
3803
3804        // Failure, then success, then many successes, with the owner never
3805        // draining: exactly the failure and the one clearing success are sent.
3806        assert!(
3807            query_snapshot(failing, owner("queries:transition", &["tasks"]))["error"].is_object()
3808        );
3809        assert!(
3810            query_snapshot(clean, owner("queries:transition", &["tasks"]))["result"].is_object()
3811        );
3812        for round in 0..8 {
3813            assert!(
3814                query_snapshot(clean, owner("queries:transition", &["tasks"]))["result"]
3815                    .is_object(),
3816                "{round}"
3817            );
3818        }
3819        let transitions = drain(&owner_rx);
3820        assert_eq!(
3821            transitions.len(),
3822            2,
3823            "a delayed owner sees the failure and one clear, not one message per read"
3824        );
3825        assert!(transitions[0].is_some(), "the failure is reported");
3826        assert!(transitions[1].is_none(), "the clearing success is reported");
3827
3828        // The same transitions hold on the SnapshotRead route.
3829        assert!(
3830            snapshot_read(failing, owner("queries:transition", &["tasks"]))["error"].is_object()
3831        );
3832        assert!(
3833            snapshot_read(clean, owner("queries:transition", &["tasks"]))["result"].is_object()
3834        );
3835        for round in 0..8 {
3836            assert!(
3837                snapshot_read(clean, owner("queries:transition", &["tasks"]))["result"].is_object(),
3838                "{round}"
3839            );
3840        }
3841        let transitions = drain(&owner_rx);
3842        assert_eq!(transitions.len(), 2);
3843        assert!(transitions[0].is_some());
3844        assert!(transitions[1].is_none());
3845
3846        // A recovered owner reports nothing further while it stays clean.
3847        for round in 0..16 {
3848            assert!(
3849                query_snapshot(clean, owner("queries:transition", &["tasks"]))["result"]
3850                    .is_object(),
3851                "{round}"
3852            );
3853            assert!(
3854                snapshot_read(clean, owner("queries:transition", &["tasks"]))["result"].is_object(),
3855                "{round}"
3856            );
3857        }
3858        assert!(
3859            drain(&owner_rx).is_empty(),
3860            "a clean success loop enqueues nothing"
3861        );
3862
3863        // A changed failure signature still clears on the next success.
3864        assert!(
3865            query_snapshot(failing, owner("queries:signature", &["tasks"]))["error"].is_object()
3866        );
3867        assert!(
3868            query_snapshot(failing, owner("queries:signature", &["docs"]))["error"].is_object()
3869        );
3870        assert!(!drain(&owner_rx).is_empty(), "both failures are reported");
3871        assert!(query_snapshot(clean, owner("queries:signature", &["docs"]))["result"].is_object());
3872        let transitions = drain(&owner_rx);
3873        assert_eq!(transitions.len(), 1);
3874        assert!(
3875            transitions[0].is_none(),
3876            "a changed signature keeps the recovery report"
3877        );
3878        assert!(query_snapshot(clean, owner("queries:signature", &["docs"]))["result"].is_object());
3879        assert!(drain(&owner_rx).is_empty());
3880
3881        // A fresh failure re-arms the transition even for the same owner.
3882        assert!(
3883            query_snapshot(failing, owner("queries:signature", &["docs"]))["error"].is_object()
3884        );
3885        assert!(query_snapshot(clean, owner("queries:signature", &["docs"]))["result"].is_object());
3886        let transitions = drain(&owner_rx);
3887        assert_eq!(transitions.len(), 2);
3888        assert!(transitions[0].is_some());
3889        assert!(transitions[1].is_none());
3890
3891        // Keep the same bounded retention order as the owner, even while its
3892        // mailbox is paused. An unchanged repeat must not rescue the oldest id.
3893        for index in 0..MAX_DIAGNOSTIC_QUERY_FAILURES {
3894            assert!(
3895                query_snapshot(failing, owner(&format!("bounded-{index}"), &["tasks"]))["error"]
3896                    .is_object()
3897            );
3898        }
3899        assert!(query_snapshot(failing, owner("bounded-0", &["tasks"]))["error"].is_object());
3900        assert!(query_snapshot(failing, owner("bounded-1", &["changed"]))["error"].is_object());
3901        assert!(query_snapshot(failing, owner("bounded-new", &["tasks"]))["error"].is_object());
3902        assert_eq!(drain(&owner_rx).len(), MAX_DIAGNOSTIC_QUERY_FAILURES + 3);
3903        assert!(query_snapshot(clean, owner("bounded-0", &["tasks"]))["result"].is_object());
3904        assert!(
3905            drain(&owner_rx).is_empty(),
3906            "the evicted oldest id has no retained failure to clear"
3907        );
3908        assert!(snapshot_read(clean, owner("bounded-1", &["changed"]))["result"].is_object());
3909        let retained = drain(&owner_rx);
3910        assert_eq!(retained.len(), 1);
3911        assert!(
3912            retained[0].is_none(),
3913            "the changed, retained signature still clears"
3914        );
3915
3916        read_tx.send(ReadRequest::Shutdown).expect("stop reader");
3917        reader.join().expect("join reader");
3918        std::fs::remove_file(path).expect("remove replica file");
3919    }
3920
3921    #[test]
3922    fn owned_read_failures_clear_from_either_route_and_keep_journal_order() {
3923        use tauri::test::{mock_builder, mock_context, noop_assets};
3924
3925        let path = std::env::temp_dir().join(format!(
3926            "syncular-tauri-read-order-{}.db",
3927            std::process::id()
3928        ));
3929        let _ = std::fs::remove_file(&path);
3930        let app = mock_builder()
3931            .plugin(init(SyncularConfig {
3932                db_path: Some(path.to_string_lossy().into_owned()),
3933                auto_sync: false,
3934                ..Default::default()
3935            }))
3936            .build(mock_context(noop_assets()))
3937            .expect("build file app");
3938        let command = |value: Value| run_command(app.handle(), value).expect("command reply");
3939        let read = |statements: Value, owner: Value| {
3940            tauri::async_runtime::block_on(syncular_snapshot_read(
3941                app.handle().clone(),
3942                statements,
3943                None,
3944                None,
3945                None,
3946                Some(owner),
3947            ))
3948            .expect("read reply")
3949        };
3950        let failures = || {
3951            command(json!({ "method": "diagnosticsSnapshot", "params": {} }))["result"]
3952                ["queryFailures"]
3953                .clone()
3954        };
3955        let ids = || -> Vec<String> {
3956            failures()
3957                .as_array()
3958                .expect("query failures array")
3959                .iter()
3960                .map(|failure| failure["id"].as_str().expect("failure id").to_owned())
3961                .collect()
3962        };
3963        let owner = |id: &str, tables: Value| json!({ "id": id, "tables": tables });
3964        // The generic command entry, carrying an owner. In file-backed mode it
3965        // is normalized onto the same sidecar as the dedicated commands, so one
3966        // producer owns the transition bookkeeping.
3967        let owned_command = |id: &str, tables: Value, sql: &str| {
3968            command(json!({ "method": "snapshotRead", "params": {
3969                "statements": [{ "sql": sql, "params": [] }],
3970                "owner": owner(id, tables),
3971            } }))
3972        };
3973        assert_eq!(
3974            command(json!({ "method": "create", "params": {
3975                "clientId": "read-routes",
3976                "schema": { "version": 1, "tables": [] },
3977            } }))["result"],
3978            json!({}),
3979            "the config db_path opens the replica the sidecar reads"
3980        );
3981
3982        // Journal retention: an unchanged failure signature keeps its position,
3983        // a changed one moves last.
3984        for (id, tables) in [
3985            ("owner-x", json!(["tasks"])),
3986            ("owner-y", json!(["docs"])),
3987            ("owner-x", json!(["tasks"])),
3988        ] {
3989            assert!(
3990                owned_command(id, tables, "SELECT value FROM absent_owner_table")["error"]
3991                    .is_object()
3992            );
3993        }
3994        assert_eq!(
3995            ids(),
3996            ["owner-x", "owner-y"],
3997            "an unchanged failure keeps its journal position"
3998        );
3999        assert!(owned_command(
4000            "owner-x",
4001            json!(["other"]),
4002            "SELECT value FROM absent_owner_table"
4003        )["error"]
4004            .is_object());
4005        assert_eq!(
4006            ids(),
4007            ["owner-y", "owner-x"],
4008            "a changed failure signature moves the entry last"
4009        );
4010
4011        // A success on one read route clears the failure the other route had
4012        // the sidecar report, and the journal keeps rejection order.
4013        assert!(read(
4014            json!([{ "sql": "SELECT 1 AS value" }]),
4015            owner("owner-x", json!(["tasks"]))
4016        )["result"]
4017            .is_object());
4018        assert_eq!(ids(), ["owner-y"], "the sidecar success cleared owner-x");
4019        assert!(read(
4020            json!([{ "sql": "SELECT 1 AS value" }]),
4021            owner("owner-y", json!(["docs"]))
4022        )["result"]
4023            .is_object());
4024        assert_eq!(ids(), Vec::<String>::new());
4025
4026        assert!(owned_command(
4027            "owner-z",
4028            json!(["tasks"]),
4029            "SELECT value FROM absent_owner_table"
4030        )["error"]
4031            .is_object());
4032        assert_eq!(ids(), ["owner-z"]);
4033        assert!(read(
4034            json!([{ "sql": "SELECT 1 AS value" }]),
4035            owner("owner-z", json!(["tasks"]))
4036        )["result"]
4037            .is_object());
4038        assert_eq!(
4039            ids(),
4040            Vec::<String>::new(),
4041            "a success on one route clears the other route's failure"
4042        );
4043
4044        assert!(read(
4045            json!([{ "sql": "SELECT value FROM absent_owner_table" }]),
4046            owner("owner-w", json!(["tasks"]))
4047        )["error"]
4048            .is_object());
4049        assert_eq!(ids(), ["owner-w"]);
4050        assert!(
4051            owned_command("owner-w", json!(["tasks"]), "SELECT 1 AS value")["result"].is_object()
4052        );
4053        assert_eq!(
4054            ids(),
4055            Vec::<String>::new(),
4056            "the generic route's success clears the sidecar failure"
4057        );
4058
4059        // Clean sidecar reads never enter the journal.
4060        for round in 0..8 {
4061            assert!(
4062                read(
4063                    json!([{ "sql": "SELECT 1 AS value" }]),
4064                    owner("owner-clean", json!(["tasks"]))
4065                )["result"]
4066                    .is_object(),
4067                "{round}"
4068            );
4069        }
4070        assert_eq!(ids(), Vec::<String>::new());
4071
4072        let _ = std::fs::remove_file(&path);
4073    }
4074}