kovlet 0.1.0

Kovlet's portable sync client core: sign-in, sync, merge, outbox and files for Rust, Tauri, Swift and Kotlin apps
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
//! Protocol 2 on the merge target (ADR 0021 §5.3, PROTOCOL.md §17):
//! subscriptions, their resume cursors, and which rows the store holds.
//!
//! - **Whole space** (`"*"`, sub [`WHOLE_SPACE_SUB`]): a full replica with
//!   protocol 1 semantics. A full result is a snapshot (it replaces the
//!   state), a resumed one merges what changed, and `changes` carry every op.
//! - **Query subscriptions** (a partial replica): the store holds the union
//!   of the rows its subscriptions hold, plus rows with a pending local write
//!   or an acked write the subscriptions haven't judged yet. A row nothing
//!   holds any more leaves the app's store as a [`Change::Purge`]; a row that
//!   another subscription still holds stays.
//!
//! Each subscription's state (query, resume cursor, `through_seq`, held rows)
//! is written in the same transaction as the data it describes (`meta` of a
//! [`StateWrite`]), so a crash re-delivers from the older cursor and merges
//! the same way. Subscriptions persist until the app unsubscribes, so an app
//! started offline still knows which rows its queries hold.

use serde::{Deserialize, Serialize};

use super::*;
use crate::protocol::{Changes, ResultFrame, QUERY_ALL};

/// The subscription id of a full replica over protocol 2.
pub const WHOLE_SPACE_SUB: &str = "space";
/// The subscription id of a schema declaration (no subscription stays open).
pub const DECLARE_SUB: &str = "declare";

fn index_key(space: &str) -> String {
    format!("v2subs:{space}")
}

fn sub_key(space: &str, sub: &str) -> String {
    format!("v2sub:{space}:{sub}")
}

/// What is stored per subscription.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
struct StoredSub {
    query: Value,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    params: Option<JsonMap>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    cursor: Option<String>,
    #[serde(default)]
    through: i64,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    keys: Vec<RowRef>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    more: BTreeMap<String, bool>,
}

/// One subscription's state.
#[derive(Debug, Clone, Default)]
pub(crate) struct Sub {
    pub query: Value,
    pub params: Option<JsonMap>,
    pub cursor: Option<String>,
    pub through: i64,
    pub keys: BTreeSet<RowRef>,
    pub more: BTreeMap<String, bool>,
    /// A complete result arrived on this connection.
    pub complete: bool,
    pub error: Option<Error>,
}

impl Sub {
    fn stored(&self) -> String {
        serde_json::to_string(&StoredSub {
            query: self.query.clone(),
            params: self.params.clone(),
            cursor: self.cursor.clone(),
            through: self.through,
            keys: self.keys.iter().cloned().collect(),
            more: self.more.clone(),
        })
        .expect("subscriptions serialize")
    }
}

/// A subscription as the app sees it ([`crate::Space::subscriptions`]).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SubscriptionStatus {
    /// The subscription id (stable per space, query and params).
    pub sub: String,
    pub query: Value,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub params: Option<JsonMap>,
    /// A complete result arrived on the current connection.
    pub complete: bool,
    /// Rows the subscription holds.
    pub rows: usize,
    /// Top-level keys with rows beyond their `limit`.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub more: BTreeMap<String, bool>,
    /// Why the server ended it (`invalid_query`, `forbidden`, …); it is not
    /// sent again until the app subscribes again.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<Error>,
}

/// A query result's pages, until the complete one.
#[derive(Default)]
struct Pages {
    rows: Vec<RecordState>,
    files: Vec<FileState>,
    tables: BTreeMap<String, TableSchema>,
    ids: Option<BTreeMap<String, Vec<String>>>,
}

/// The target's protocol 2 state.
#[derive(Default)]
pub(crate) struct SubsState {
    /// Query mode: the store holds only what subscriptions hold.
    pub partial: bool,
    pub subs: BTreeMap<String, Sub>,
    /// row → subscriptions holding it.
    holders: BTreeMap<RowRef, BTreeSet<String>>,
    /// row → seq of an acked write of this client the subscriptions haven't judged yet.
    unconfirmed: BTreeMap<RowRef, i64>,
    pages: BTreeMap<String, Pages>,
}

impl SubsState {
    /// Restores the stored subscriptions of a space.
    pub fn load(sync: &dyn SyncStore, space: &str) -> Result<SubsState> {
        let mut st = SubsState::default();
        let ids: Vec<String> = match sync.meta_get(&index_key(space))? {
            Some(v) if !v.is_empty() => serde_json::from_str(&v).unwrap_or_default(),
            _ => Vec::new(),
        };
        for id in ids {
            let Some(raw) = sync.meta_get(&sub_key(space, &id))?.filter(|v| !v.is_empty()) else { continue };
            let Ok(s) = serde_json::from_str::<StoredSub>(&raw) else { continue };
            let sub = Sub {
                query: s.query,
                params: s.params,
                cursor: s.cursor,
                through: s.through,
                keys: s.keys.into_iter().collect(),
                more: s.more,
                complete: false,
                error: None,
            };
            for k in &sub.keys {
                st.holders.entry(k.clone()).or_default().insert(id.clone());
            }
            st.subs.insert(id, sub);
        }
        Ok(st)
    }

    fn index(&self) -> String {
        serde_json::to_string(&self.subs.keys().collect::<Vec<_>>()).expect("ids serialize")
    }

    fn held(&self, k: &RowRef) -> bool {
        self.holders.get(k).is_some_and(|h| !h.is_empty())
    }

    /// The smallest `through` over complete, healthy subscriptions (0 while one is incomplete).
    fn judged_through(&self, sub: &str, through: i64) -> i64 {
        let mut min = i64::MAX;
        for (id, s) in &self.subs {
            // A "*" subscription left from a full-replica run never judges queries.
            if s.error.is_some() || id == WHOLE_SPACE_SUB {
                continue;
            }
            let t = if id == sub {
                through
            } else if s.complete {
                s.through
            } else {
                0
            };
            min = min.min(t);
        }
        min
    }
}

/// Clears a space's stored subscriptions (with [`SyncStore::forget_space`]).
pub(crate) fn forget(sync: &dyn SyncStore, space: &str) -> Result<()> {
    if let Some(v) = sync.meta_get(&index_key(space))?.filter(|v| !v.is_empty()) {
        for id in serde_json::from_str::<Vec<String>>(&v).unwrap_or_default() {
            sync.meta_set(&sub_key(space, &id), "")?;
        }
    }
    sync.meta_set(&index_key(space), "")
}

/// What one protocol 2 frame does to the store.
#[derive(Default)]
struct Update<'a> {
    ops: Vec<&'a Op>,
    only_known: bool,
    states: Vec<&'a RecordState>,
    files: Vec<FileState>,
    /// Schemas to merge in (`replace`: they are the whole set).
    tables: Option<&'a BTreeMap<String, TableSchema>>,
    replace_tables: bool,
    purge: BTreeSet<RowRef>,
    cursor: Option<i64>,
    meta: Vec<(String, String)>,
}

impl Target {
    /// Query mode: the store holds only what subscriptions hold.
    pub(crate) fn set_partial(&self, partial: bool) {
        self.state.lock().unwrap().v2.partial = partial;
    }

    pub(crate) fn partial(&self) -> bool {
        self.state.lock().unwrap().v2.partial
    }

    /// Registers a subscription (kept across restarts until unsubscribed).
    /// Returns false when it already exists; its error, if any, is cleared.
    pub(crate) fn add_subscription(&self, sub: &str, query: Value, params: Option<JsonMap>) -> Result<bool> {
        let _g = self.lock.lock().unwrap();
        let (index, stored) = {
            let mut s = self.state.lock().unwrap();
            if let Some(cur) = s.v2.subs.get_mut(sub) {
                cur.error = None;
                return Ok(false);
            }
            let new = Sub { query, params, ..Default::default() };
            let stored = new.stored();
            s.v2.subs.insert(sub.to_string(), new);
            (s.v2.index(), stored)
        };
        self.sync().meta_set(&sub_key(&self.space_id, sub), &stored)?;
        self.sync().meta_set(&index_key(&self.space_id), &index)?;
        Ok(true)
    }

    /// Ends a subscription: rows only it held leave the store.
    pub(crate) fn remove_subscription(&self, sub: &str) -> Result<bool> {
        let _g = self.lock.lock().unwrap();
        self.live()?;
        let (lost, purge) = {
            let s = self.state.lock().unwrap();
            let Some(cur) = s.v2.subs.get(sub) else { return Ok(false) };
            let lost: Vec<RowRef> = cur.keys.iter().cloned().collect();
            let purge = self.evictable(&s, &cur.keys, Some(sub), &BTreeSet::new(), &BTreeSet::new());
            (lost, purge)
        };
        let index = {
            let s = self.state.lock().unwrap();
            let mut copy = s.v2.subs.clone();
            copy.remove(sub);
            serde_json::to_string(&copy.keys().collect::<Vec<_>>()).expect("ids serialize")
        };
        let u = Update {
            purge,
            meta: vec![(sub_key(&self.space_id, sub), String::new()), (index_key(&self.space_id), index)],
            ..Default::default()
        };
        self.exec_update(u)?;
        let mut s = self.state.lock().unwrap();
        s.v2.subs.remove(sub);
        s.v2.pages.remove(sub);
        for k in lost {
            if let Some(h) = s.v2.holders.get_mut(&k) {
                h.remove(sub);
                if h.is_empty() {
                    s.v2.holders.remove(&k);
                }
            }
        }
        Ok(true)
    }

    /// Every subscription, for the app.
    pub(crate) fn subscriptions(&self) -> Vec<SubscriptionStatus> {
        let s = self.state.lock().unwrap();
        s.v2.subs
            .iter()
            .map(|(id, x)| SubscriptionStatus {
                sub: id.clone(),
                query: x.query.clone(),
                params: x.params.clone(),
                complete: x.complete,
                rows: x.keys.len(),
                more: x.more.clone(),
                error: x.error.clone(),
            })
            .collect()
    }

    /// The `subscribe` frames to send on a new connection: `(sub, query,
    /// params, resume)`. Failed subscriptions are not sent again.
    pub(crate) fn subscribe_specs(&self) -> Vec<(String, Value, Option<JsonMap>, Option<String>)> {
        let mut s = self.state.lock().unwrap();
        let synced = s.synced;
        s.v2.pages.clear();
        s.v2.subs
            .iter_mut()
            .filter(|(_, x)| x.error.is_none())
            .map(|(id, x)| {
                x.complete = false;
                // A whole-space resume needs the replica it resumes.
                let resume = if id == WHOLE_SPACE_SUB && !synced { None } else { x.cursor.clone() };
                (id.clone(), x.query.clone(), x.params.clone(), resume)
            })
            .collect()
    }

    /// One subscription's `subscribe` frame: `(query, params, resume)`.
    pub(crate) fn subscribe_specs_for(&self, sub: &str) -> Option<(Value, Option<JsonMap>, Option<String>)> {
        let mut s = self.state.lock().unwrap();
        s.v2.pages.remove(sub);
        let x = s.v2.subs.get_mut(sub).filter(|x| x.error.is_none())?;
        x.complete = false;
        Some((x.query.clone(), x.params.clone(), x.cursor.clone()))
    }

    /// The server ended a subscription (`error` with `sub`).
    pub(crate) fn subscription_failed(&self, sub: &str, error: Error) {
        let mut s = self.state.lock().unwrap();
        s.v2.pages.remove(sub);
        if let Some(x) = s.v2.subs.get_mut(sub) {
            x.error = Some(error);
            x.complete = true;
        }
    }

    /// Whether a subscription holds this row (the server confirmed it matches).
    pub(crate) fn held(&self, table: &str, id: &str) -> bool {
        self.state.lock().unwrap().v2.held(&rref(table, id))
    }

    /// Forgets the whole-space resume cursor: the next `"*"` subscribe gets a full result.
    pub(crate) fn reset_whole_space(&self) {
        if let Some(x) = self.state.lock().unwrap().v2.subs.get_mut(WHOLE_SPACE_SUB) {
            x.cursor = None;
        }
    }

    /// Feeds one `result` page. True once the complete page is applied.
    pub(crate) fn apply_result(&self, page: ResultFrame) -> Result<bool> {
        if page.sub == WHOLE_SPACE_SUB {
            return self.whole_space_result(page);
        }
        if page.sub == DECLARE_SUB {
            // A schema declaration's answer: the space's tables, no subscription.
            if let Some(t) = page.tables.as_ref().filter(|t| !t.is_empty()) {
                let _g = self.lock.lock().unwrap();
                self.live()?;
                self.exec_update(Update { tables: Some(t), ..Default::default() })?;
            }
            return Ok(page.complete);
        }
        {
            let mut s = self.state.lock().unwrap();
            if !s.v2.subs.contains_key(&page.sub) {
                return Ok(page.complete); // unsubscribed meanwhile
            }
            let acc = s.v2.pages.entry(page.sub.clone()).or_default();
            acc.rows.extend(page.rows.iter().cloned());
            acc.files.extend(page.files.iter().cloned());
            if let Some(t) = &page.tables {
                acc.tables.extend(t.clone());
            }
            if page.ids.is_some() {
                acc.ids = page.ids.clone();
            }
            if !page.complete {
                return Ok(false);
            }
        }
        self.query_result(page)?;
        Ok(true)
    }

    fn whole_space_meta(&self, cursor: &str, through: i64) -> (Sub, Vec<(String, String)>) {
        let s = self.state.lock().unwrap();
        let mut sub =
            s.v2.subs
                .get(WHOLE_SPACE_SUB)
                .cloned()
                .unwrap_or_else(|| Sub { query: Value::String(QUERY_ALL.into()), ..Default::default() });
        sub.cursor = Some(cursor.to_string());
        sub.through = sub.through.max(through);
        let mut copy = s.v2.subs.clone();
        copy.insert(WHOLE_SPACE_SUB.into(), sub.clone());
        let index = serde_json::to_string(&copy.keys().collect::<Vec<_>>()).expect("ids serialize");
        let meta = vec![(sub_key(&self.space_id, WHOLE_SPACE_SUB), sub.stored()), (index_key(&self.space_id), index)];
        (sub, meta)
    }

    fn whole_space_result(&self, page: ResultFrame) -> Result<bool> {
        let (mut sub, meta) = self.whole_space_meta(&page.cursor, page.through_seq);
        let meta = if page.complete { meta } else { Vec::new() };
        let done = if !page.resumed {
            // A full result replaces the state, like a protocol 1 snapshot.
            let snap = Snapshot {
                space_id: page.space_id.clone(),
                head_seq: page.through_seq,
                tables: page.tables.clone(),
                records: page.rows,
                files: page.files,
                complete: page.complete,
                usage: None,
            };
            self.apply_snapshot_with(&snap, meta)?
        } else {
            let _g = self.lock.lock().unwrap();
            self.live()?;
            let u = Update {
                states: page.rows.iter().collect(),
                files: page.files.clone(),
                tables: page.tables.as_ref(),
                replace_tables: true,
                cursor: page.complete.then_some(page.through_seq),
                meta,
                ..Default::default()
            };
            self.exec_update(u)?;
            page.complete
        };
        if done {
            sub.complete = true;
            let mut s = self.state.lock().unwrap();
            s.synced = true;
            s.v2.subs.insert(WHOLE_SPACE_SUB.into(), sub);
        }
        Ok(done)
    }

    /// Which of `cands` leave the store: query mode only, and only rows no
    /// other subscription holds (`next` is what `sub` holds afterwards), with
    /// no pending local write, and no acked write still awaiting judgement
    /// (`unconfirmed`, minus `confirmed`).
    fn evictable(
        &self,
        s: &State,
        cands: &BTreeSet<RowRef>,
        sub: Option<&str>,
        next: &BTreeSet<RowRef>,
        confirmed: &BTreeSet<RowRef>,
    ) -> BTreeSet<RowRef> {
        let mut out = BTreeSet::new();
        if !s.v2.partial {
            return out;
        }
        let pending: HashSet<String> = s.outbox.iter().map(|p| p.mutation.entity_key()).collect();
        for k in cands {
            if next.contains(k) {
                continue;
            }
            if let Some(h) = s.v2.holders.get(k) {
                if h.iter().any(|x| Some(x.as_str()) != sub) {
                    continue;
                }
            }
            if pending.contains(&format!("record\u{0}{}\u{0}{}", k.table, k.id)) {
                continue;
            }
            if s.v2.unconfirmed.contains_key(k) && !confirmed.contains(k) {
                continue;
            }
            out.insert(k.clone());
        }
        out
    }

    /// Plans a subscription's new membership: `next` is what it holds
    /// afterwards, `extra` rows it saw but doesn't keep. Returns the rows it
    /// lost, the rows that leave the store, and the acked writes now judged.
    fn plan_membership(
        &self,
        s: &State,
        sub: &str,
        old: &BTreeSet<RowRef>,
        next: &BTreeSet<RowRef>,
        extra: Vec<RowRef>,
        through: i64,
    ) -> (Vec<RowRef>, BTreeSet<RowRef>, BTreeSet<RowRef>) {
        let mut lost = Vec::new();
        let mut cands = BTreeSet::new();
        for k in old {
            if !next.contains(k) {
                lost.push(k.clone());
                cands.insert(k.clone());
            }
        }
        cands.extend(extra);
        let judged = s.v2.judged_through(sub, through);
        let mut confirmed = BTreeSet::new();
        for (k, seq) in &s.v2.unconfirmed {
            if *seq <= judged {
                confirmed.insert(k.clone());
                if !s.v2.held(k) {
                    cands.insert(k.clone());
                }
            }
        }
        let purge = self.evictable(s, &cands, Some(sub), next, &confirmed);
        (lost, purge, confirmed)
    }

    /// Records a planned membership after its write succeeded.
    fn commit_membership(&self, sub: String, lost: &[RowRef], updated: Sub, confirmed: &BTreeSet<RowRef>) {
        let mut s = self.state.lock().unwrap();
        for k in lost {
            if let Some(h) = s.v2.holders.get_mut(k) {
                h.remove(&sub);
                if h.is_empty() {
                    s.v2.holders.remove(k);
                }
            }
        }
        for k in &updated.keys {
            s.v2.holders.entry(k.clone()).or_default().insert(sub.clone());
        }
        for k in confirmed {
            s.v2.unconfirmed.remove(k);
        }
        s.v2.subs.insert(sub, updated);
    }

    /// A query subscription's complete result: merge its rows, then make its
    /// membership exactly the rows sent (or `ids`, for a resumed result).
    fn query_result(&self, page: ResultFrame) -> Result<()> {
        let _g = self.lock.lock().unwrap();
        self.live()?;
        let sub = page.sub.clone();
        let (acc, lost, purge, confirmed, updated) = {
            let mut s = self.state.lock().unwrap();
            let acc = s.v2.pages.remove(&sub).unwrap_or_default();
            let Some(cur) = s.v2.subs.get(&sub).cloned() else { return Ok(()) };
            let mut next = BTreeSet::new();
            let mut extra = Vec::new();
            match &acc.ids {
                Some(ids) => {
                    for (t, ids) in ids {
                        for id in ids {
                            next.insert(rref(t, id));
                        }
                    }
                }
                None => {
                    for r in &acc.rows {
                        if !r.deleted {
                            next.insert(rref(&r.table, &r.id));
                        }
                    }
                }
            }
            for r in &acc.rows {
                // Rows sent but not kept (trashed rows of a full result) are candidates too.
                let k = rref(&r.table, &r.id);
                if !next.contains(&k) {
                    extra.push(k);
                }
            }
            let through = cur.through.max(page.through_seq);
            let (lost, purge, confirmed) = self.plan_membership(&s, &sub, &cur.keys, &next, extra, through);
            let updated = Sub {
                keys: next,
                cursor: Some(page.cursor.clone()),
                through,
                more: page.more.clone().unwrap_or_default(),
                complete: true,
                error: None,
                ..cur
            };
            (acc, lost, purge, confirmed, updated)
        };
        let mut states = Vec::new();
        for r in &acc.rows {
            if !purge.contains(&rref(&r.table, &r.id)) {
                states.push(r);
            }
        }
        let u = Update {
            states,
            files: acc.files.clone(),
            tables: (!acc.tables.is_empty()).then_some(&acc.tables),
            purge,
            meta: vec![(sub_key(&self.space_id, &sub), updated.stored())],
            ..Default::default()
        };
        self.exec_update(u)?;
        self.commit_membership(sub, &lost, updated, &confirmed);
        Ok(())
    }

    /// Applies a `changes` frame. True when a schema op of a whole-space
    /// subscription dropped columns or a table (fetch the space again).
    pub(crate) fn apply_changes(&self, ch: &Changes) -> Result<bool> {
        if ch.sub == WHOLE_SPACE_SUB {
            // Every op in the space, like a protocol 1 broadcast. LWW makes a
            // replayed op harmless, so nothing is skipped by seq.
            let (sub, meta) = self.whole_space_meta(&ch.cursor, ch.through_seq);
            let resnapshot = self.apply_ops_with(&ch.ops, false, false, meta)?;
            let mut s = self.state.lock().unwrap();
            s.cursor = s.cursor.max(ch.through_seq);
            s.v2.subs.insert(WHOLE_SPACE_SUB.into(), Sub { complete: true, ..sub });
            return Ok(resnapshot);
        }
        let _g = self.lock.lock().unwrap();
        self.live()?;
        let sub = ch.sub.clone();
        let (lost, purge, confirmed, updated) = {
            let s = self.state.lock().unwrap();
            let Some(cur) = s.v2.subs.get(&sub).cloned() else { return Ok(false) };
            let mut next = cur.keys.clone();
            for r in &ch.removed {
                next.remove(&rref(&r.table, &r.id));
            }
            for r in &ch.added {
                next.insert(rref(&r.table, &r.id));
            }
            let through = cur.through.max(ch.through_seq);
            let (lost, purge, confirmed) = self.plan_membership(&s, &sub, &cur.keys, &next, Vec::new(), through);
            let mut more = cur.more.clone();
            more.extend(ch.more.clone().unwrap_or_default());
            let updated = Sub { keys: next, cursor: Some(ch.cursor.clone()), through, more, ..cur };
            (lost, purge, confirmed, updated)
        };
        let u = Update {
            ops: ch.ops.iter().collect(),
            only_known: true,
            states: ch.added.iter().collect(),
            purge,
            meta: vec![(sub_key(&self.space_id, &sub), updated.stored())],
            ..Default::default()
        };
        let resnapshot = self.exec_update(u)?;
        self.commit_membership(sub, &lost, updated, &confirmed);
        Ok(resnapshot)
    }

    /// The rows these queued writes created (their `_local` stamp is the
    /// write's), as outbox entity keys: later writes to them depend on them.
    pub(crate) fn created_by(&self, entries: &[PendingMutation]) -> Result<BTreeSet<String>> {
        let mut out = BTreeSet::new();
        for p in entries {
            let m = &p.mutation;
            let (Some(table), "record", "upsert") = (&m.table, m.kind.as_str(), m.op.as_str()) else { continue };
            let clocks = self.sync().clocks(&self.space_id, table, std::slice::from_ref(&m.id))?;
            if clocks.get(&m.id).and_then(|rc| rc.fields.get(LOCAL)) == Some(&m.hlc) {
                out.insert(m.entity_key());
            }
        }
        Ok(out)
    }

    /// Query mode: marks rows of acked writes as "not judged yet", so they
    /// stay until every subscription has seen `seq` (PROTOCOL.md §17.3).
    pub(crate) fn mark_unconfirmed(&self, rows: &[RowRef], seq: i64) {
        let mut s = self.state.lock().unwrap();
        if !s.v2.partial {
            return;
        }
        for k in rows {
            let e = s.v2.unconfirmed.entry(k.clone()).or_insert(seq);
            *e = (*e).max(seq);
        }
    }

    /// Query mode: drops these rows from the store when nothing holds them
    /// (after a rollback re-read them from the server).
    pub(crate) fn evict_unheld(&self, rows: &[RowRef]) -> Result<()> {
        let _g = self.lock.lock().unwrap();
        self.live()?;
        let purge = {
            let s = self.state.lock().unwrap();
            let cands: BTreeSet<RowRef> = rows.iter().cloned().collect();
            self.evictable(&s, &cands, None, &BTreeSet::new(), &BTreeSet::new())
        };
        if purge.is_empty() {
            return Ok(());
        }
        self.exec_update(Update { purge, ..Default::default() })?;
        Ok(())
    }

    /// Forgets everything synced for the signed-in identity: every row the
    /// core knows leaves the app's store (`Change::Purge`), and the clocks,
    /// outbox, write queue, cursor and subscriptions go, in one transaction.
    /// Used when an end user signs out or another one signs in.
    pub(crate) fn wipe(&self) -> Result<()> {
        let _g = self.lock.lock().unwrap();
        self.live()?;
        let (outbox, subs) = {
            let s = self.state.lock().unwrap();
            (
                s.outbox.iter().map(|p| p.mutation.mutation_id.clone()).collect::<Vec<_>>(),
                s.v2.subs.keys().cloned().collect::<Vec<_>>(),
            )
        };
        let space_id = self.space_id.clone();
        let mut build = |_: &ClockMap, rows: Option<&[RowRef]>| -> Result<Plan> {
            let rows = rows.unwrap_or_default();
            let mut meta: Vec<(String, String)> =
                subs.iter().map(|id| (sub_key(&space_id, id), String::new())).collect();
            meta.push((index_key(&space_id), String::new()));
            let write = StateWrite {
                purge: rows.to_vec(),
                outbox_remove: outbox.clone(),
                cursor: Some(0),
                meta,
                ..Default::default()
            };
            let changes: Vec<Change> =
                rows.iter().map(|r| Change::Purge { table: r.table.clone(), id: r.id.clone() }).collect();
            let batch = (!changes.is_empty()).then(|| ChangeBatch {
                space_id: space_id.clone(),
                origin: Origin::Remote,
                changes,
                complete: false,
            });
            Ok(Plan { batch, write, revert: None })
        };
        let p = self.exec(&Needs::new(), false, true, &mut build)?;
        let queued: Vec<String> =
            self.sync().queued(&self.space_id, usize::MAX)?.into_iter().map(|m| m.mutation_id).collect();
        if !queued.is_empty() {
            self.sync().queue_remove(&self.space_id, &queued)?;
        }
        {
            let mut s = self.state.lock().unwrap();
            let partial = s.v2.partial;
            s.cursor = 0;
            s.synced = false;
            s.outbox.clear();
            s.snapshot = None;
            s.seed.clear();
            s.v2 = SubsState { partial, ..Default::default() };
        }
        self.notify(&p.batch, true);
        Ok(())
    }

    /// Writes one protocol 2 update: ops, full row states, files, schemas,
    /// purges, the cursor and subscription state, in one plan (one
    /// transaction for a combined store). The caller holds the merge lock.
    fn exec_update(&self, u: Update<'_>) -> Result<bool> {
        let schemas0 = self.state.lock().unwrap().schemas.clone();
        let mut needs = Needs::new();
        for op in &u.ops {
            if let (Some(t), Some(id), "record") = (&op.table, &op.id, op.kind.as_str()) {
                need(&mut needs, t, id);
            }
        }
        for r in &u.states {
            need(&mut needs, &r.table, &r.id);
        }
        let space_id = self.space_id.clone();
        let mut resnapshot = false;
        let mut max_hlc: Option<String> = None;
        let mut build = |clocks: &ClockMap, _: Option<&[RowRef]>| -> Result<Plan> {
            let mut dirty: BTreeMap<RowRef, RowClocks> = BTreeMap::new();
            let mut changes = Vec::new();
            let mut schemas: Option<BTreeMap<String, TableSchema>> = None;
            let (_, rs) = merge_ops(&u.ops, clocks, u.only_known, &schemas0, &mut dirty, &mut changes, &mut schemas);
            resnapshot = rs;
            for r in &u.states {
                for h in r.hlcs.values() {
                    if newer(h, max_hlc.as_deref()) {
                        max_hlc = Some(h.clone());
                    }
                }
                let k = rref(&r.table, &r.id);
                let cur = dirty.get(&k).or_else(|| clocks.get(&k)).cloned();
                if let Some(rc) = merge_state(r, cur.as_ref(), &mut changes) {
                    dirty.insert(k, rc);
                }
            }
            for f in &u.files {
                changes.push(Change::File { file: f.clone() });
            }
            if let Some(tables) = u.tables {
                let sc = schemas.get_or_insert_with(|| schemas0.clone());
                if u.replace_tables {
                    for t in schemas0.keys().filter(|t| !tables.contains_key(*t)) {
                        sc.remove(t);
                        changes.push(Change::Schema { table: t.clone(), schema: None });
                    }
                }
                for (t, ts) in tables {
                    if sc.get(t) != Some(ts) {
                        sc.insert(t.clone(), ts.clone());
                        changes.push(Change::Schema { table: t.clone(), schema: Some(ts.clone()) });
                    }
                }
            }
            let mut write = StateWrite { schemas, cursor: u.cursor, meta: u.meta.clone(), ..Default::default() };
            for k in &u.purge {
                dirty.remove(k);
                changes.push(Change::Purge { table: k.table.clone(), id: k.id.clone() });
                write.purge.push(k.clone());
            }
            write.clocks = dirty.into_iter().collect();
            let batch = (!changes.is_empty()).then(|| ChangeBatch {
                space_id: space_id.clone(),
                origin: Origin::Remote,
                changes,
                complete: false,
            });
            Ok(Plan { batch, write, revert: None })
        };
        let p = self.exec(&needs, false, false, &mut build)?;
        {
            let mut s = self.state.lock().unwrap();
            if let Some(c) = p.write.cursor {
                s.cursor = s.cursor.max(c);
            }
            if let Some(sc) = &p.write.schemas {
                s.schemas = sc.clone();
            }
            if let Some(h) = max_hlc {
                if newer(&h, s.max_hlc.as_deref()) {
                    s.max_hlc = Some(h);
                }
            }
        }
        self.notify(&p.batch, false);
        Ok(resnapshot)
    }
}