syncular-client 0.30.9

Syncular v2 Rust client core on rusqlite, implemented from SPEC.md alone (language-neutrality POC, stage 2)
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
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
//! Driver-facing API shapes (JSON-able), mirroring the conformance
//! `ClientInstance` contract: sync reports, conflicts, rejections, row
//! states, subscription states. Serialized as camelCase to cross the shim
//! boundary unchanged.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

use crate::previous_version::PreviousVersionContextConfig;
/// Stable dynamic value boundary used by generated named queries.
pub type QueryValue = Value;
/// One dynamic query result row, keyed by QueryIR runtime projection name.
pub type QueryRow = Map<String, QueryValue>;

/// An owned blob body returned by the Rust client without driver encoding.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FetchedBlob {
    pub blob_id: String,
    pub byte_length: i64,
    pub bytes: Vec<u8>,
    pub media_type: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TimeBucketUnit {
    Month,
}

const MAX_TIME_BUCKET_MS: i64 = 253_402_300_799_999;

fn utc_year_month(timestamp_ms: i64) -> Result<(i64, i64), String> {
    if !(0..=MAX_TIME_BUCKET_MS).contains(&timestamp_ms) {
        return Err(
            "sync.invalid_request: time bucket timestamps must fall from 1970 through 9999"
                .to_owned(),
        );
    }
    let z = timestamp_ms / 86_400_000 + 719_468;
    let era = z.div_euclid(146_097);
    let day_of_era = z - era * 146_097;
    let year_of_era =
        (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
    let mut year = year_of_era + era * 400;
    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
    let month_prime = (5 * day_of_year + 2) / 153;
    let month = month_prime + if month_prime < 10 { 3 } else { -9 };
    if month <= 2 {
        year += 1;
    }
    Ok((year, month))
}

/// Derive the immutable UTC scope value stored when a row is created.
pub fn creation_time_bucket(created_at_ms: i64, unit: TimeBucketUnit) -> Result<String, String> {
    match unit {
        TimeBucketUnit::Month => {
            let (year, month) = utc_year_month(created_at_ms)?;
            Ok(format!("{year:04}-{month:02}"))
        }
    }
}

/// Return a rolling UTC month window ordered from oldest to newest.
pub fn last(count: usize, unit: TimeBucketUnit, now_ms: i64) -> Result<Vec<String>, String> {
    if !(1..=1_200).contains(&count) {
        return Err(
            "sync.invalid_request: time bucket count must be from 1 through 1200".to_owned(),
        );
    }
    match unit {
        TimeBucketUnit::Month => {
            let (year, month) = utc_year_month(now_ms)?;
            let current = year * 12 + month - 1;
            if current - (count as i64 - 1) < 1970 * 12 {
                return Err(
                    "sync.invalid_request: every returned UTC month must fall from 1970 through 9999"
                        .to_owned(),
                );
            }
            Ok((0..count)
                .rev()
                .map(|offset| {
                    let value = current - offset as i64;
                    format!(
                        "{:04}-{:02}",
                        value.div_euclid(12),
                        value.rem_euclid(12) + 1
                    )
                })
                .collect())
        }
    }
}

/// §4.8 window base: one table, the scope variable whose values are the
/// window units, any fixed scopes shared by every unit, and host-opaque
/// `params` carried onto each unit's subscription.
#[derive(Debug, Clone)]
pub struct WindowBase {
    pub table: String,
    pub variable: String,
    /// Scopes shared by every unit (other variables), if any.
    pub fixed_scopes: Vec<(String, Vec<String>)>,
    pub params: Option<String>,
}

/// §4.8 completeness oracle (I3): the windowed-in units for a base, plus
/// the subset whose bootstrap has not yet completed. Registration alone is
/// not completeness — a `pending` unit's local replica may be empty or
/// partial (its subscription still has `cursor: -1` or holds a resume
/// token), and MUST NOT be rendered as complete. A unit with zero server
/// rows still completes once its bootstrap round finishes.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct WindowState {
    /// Windowed-in units for this base, ordered by value.
    pub units: Vec<String>,
    /// Registered units whose bootstrap has not yet completed.
    pub pending: Vec<String>,
}

#[cfg(test)]
mod time_bucket_tests {
    use super::{creation_time_bucket, last, TimeBucketUnit};

    #[test]
    fn utc_month_buckets_cross_year_boundaries() {
        let now = 1_770_508_800_000; // 2026-02-08T00:00:00Z
        assert_eq!(
            creation_time_bucket(now, TimeBucketUnit::Month).unwrap(),
            "2026-02"
        );
        assert_eq!(
            last(3, TimeBucketUnit::Month, now).unwrap(),
            vec!["2025-12", "2026-01", "2026-02"]
        );
    }

    #[test]
    fn utc_month_buckets_reject_unbounded_input() {
        assert!(last(0, TimeBucketUnit::Month, 0).is_err());
        assert!(last(1_201, TimeBucketUnit::Month, 0).is_err());
        assert!(last(2, TimeBucketUnit::Month, 0).is_err());
        assert!(creation_time_bucket(-1, TimeBucketUnit::Month).is_err());
    }
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TableChange {
    pub table: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scope_keys: Option<Vec<String>>,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WindowChange {
    pub base_key: String,
    pub table: String,
    pub units: Vec<String>,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SyncStatusSnapshot {
    pub current_schema_version: i32,
    pub outbox: usize,
    pub upgrading: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lease_state: Option<LeaseState>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub schema_floor: Option<SchemaFloor>,
    pub sync_needed: bool,
    /// RFC 0005 A2: container presence, so a host can enforce the downgrade
    /// precondition (`previousVersionDiscard`) instead of documenting it.
    pub previous_version_context: PreviousVersionStatus,
}

/// RFC 0005 A2: presence of the previous-version container file.
#[derive(Debug, Clone, Copy, Default, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct PreviousVersionStatus {
    pub present: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at_ms: Option<i64>,
}

pub const CLIENT_DIAGNOSTICS_VERSION: u8 = 1;
pub const MAX_DIAGNOSTIC_EXPECTED_SUBSCRIPTIONS: usize = 256;
pub const MAX_DIAGNOSTIC_QUERY_FAILURES: usize = 256;

/// §8.8 client-local code: the `required` policy refused a sync round because
/// the realtime socket is not connected. Never a wire code (§10.3).
pub const REALTIME_UNAVAILABLE_CODE: &str = "sync.realtime_unavailable";
/// §8.8 client-local code: a connected socket ended without a deliberate
/// disconnect and the round reported no transport code. Never a wire code.
pub const REALTIME_LOST_CODE: &str = "client.realtime_lost";

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ExpectedDiagnosticSubscription {
    pub id: String,
    pub table: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ClientDiagnosticsRequest {
    #[serde(default)]
    pub expected_subscriptions: Vec<ExpectedDiagnosticSubscription>,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ClientDiagnosticsHost {
    pub kind: String,
    pub role: String,
    pub connectivity: String,
    pub realtime: RealtimeState,
    pub realtime_policy: RealtimePolicy,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub realtime_reason_code: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub realtime_retry_delay_ms: Option<u64>,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct DiagnosticSubscription {
    pub id: String,
    pub table: String,
    pub state: String,
    pub complete: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cursor: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason_code: Option<String>,
}

#[derive(Debug, Clone, Serialize, Default, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct DiagnosticRoundCounters {
    pub pushed: u32,
    pub applied: usize,
    pub rejected: usize,
    pub retryable: usize,
    pub conflicts: u32,
    pub commits_applied: u32,
    pub segment_rows_applied: u32,
    pub bootstrapping: usize,
    pub resets: usize,
    pub revoked: usize,
    pub failed: usize,
    pub deferred_commits: usize,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct DiagnosticLastRound {
    pub status: String,
    pub started_at_ms: i64,
    pub completed_at_ms: i64,
    pub duration_ms: i64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub counters: Option<DiagnosticRoundCounters>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_code: Option<String>,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct DiagnosticLastChange {
    pub revision: String,
    pub recorded_at_ms: i64,
    pub tables: Vec<String>,
    pub windows: Vec<String>,
    pub domains_truncated: bool,
    pub status_changed: bool,
    pub conflicts_changed: bool,
    pub rejections_changed: bool,
    pub outcomes_changed: bool,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ClientDiagnosticsStorage {
    pub status: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub database_bytes_approx: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pending_outbox_bytes_approx: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retained_outcome_bytes_approx: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retained_outcome_entries: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub blob_cache_bytes_approx: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pressure_reason_code: Option<String>,
}

/// §7.6: the latest owned snapshot read of one query id failed.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct DiagnosticQueryFailure {
    pub id: String,
    /// Distinct generated table names, ascending.
    pub tables: Vec<String>,
    /// `client.storage_corrupt`, `client.storage_io`, or `client.query_failed`.
    pub code: String,
    /// SQLite extended result code, when the driver exposed one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sqlite_code: Option<i32>,
    /// First failure since this id's last successful read.
    pub at_ms: i64,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ClientDiagnosticsSnapshot {
    pub version: u8,
    pub captured_at_ms: i64,
    pub host: ClientDiagnosticsHost,
    pub security_lifecycle: String,
    pub schema: ClientDiagnosticsSchema,
    pub replica: ClientDiagnosticsReplica,
    pub lease: ClientDiagnosticsLease,
    pub subscriptions: Vec<DiagnosticSubscription>,
    pub subscriptions_truncated: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_round: Option<DiagnosticLastRound>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_change: Option<DiagnosticLastChange>,
    pub storage: ClientDiagnosticsStorage,
    pub query_failures: Vec<DiagnosticQueryFailure>,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ClientDiagnosticsSchema {
    pub current_version: i32,
    pub upgrading: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub required_version: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub latest_version: Option<i32>,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ClientDiagnosticsReplica {
    pub local_revision: String,
    pub sync_needed: bool,
    pub pending_outbox: usize,
}

/// §8.8: how this client treats the realtime binding for sync rounds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum RealtimePolicy {
    Required,
    #[default]
    Optional,
    Off,
}

impl RealtimePolicy {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            RealtimePolicy::Required => "required",
            RealtimePolicy::Optional => "optional",
            RealtimePolicy::Off => "off",
        }
    }
}

/// §8.8: the explicit availability state of the realtime binding. The
/// TypeScript host adds `unsupported` (no connector configured) and `unknown`
/// (a wrapper without evidence); the Rust core reaches neither because a
/// transport always carries a connect path.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum RealtimeState {
    Connected,
    Connecting,
    #[default]
    Disconnected,
    Lost,
    Refused,
    Disabled,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ClientDiagnosticsLease {
    pub state: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at_ms: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_code: Option<String>,
}

/// JSON bindings carry the u64 revision as a decimal string (§7.5).
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientChangeBatch {
    pub revision: String,
    pub tables: Vec<TableChange>,
    pub windows: Vec<WindowChange>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<SyncStatusSnapshot>,
    pub conflicts_changed: bool,
    pub rejections_changed: bool,
    pub outcomes_changed: bool,
}

#[derive(Debug, Clone, Serialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum SyncIntent {
    None,
    Interactive,
    Background {
        #[serde(rename = "delayMs")]
        delay_ms: u64,
    },
}

#[derive(Debug, Clone, Serialize)]
pub struct CommandEffects {
    pub sync: SyncIntent,
}

impl CommandEffects {
    #[must_use]
    pub fn none() -> Self {
        Self {
            sync: SyncIntent::None,
        }
    }

    #[must_use]
    pub fn interactive() -> Self {
        Self {
            sync: SyncIntent::Interactive,
        }
    }
}

#[derive(Debug, Clone)]
pub struct WindowCoverage {
    pub base: WindowBase,
    pub units: Vec<String>,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WindowUnitRef {
    pub base_key: String,
    pub unit: String,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CoverageSnapshot {
    pub complete: bool,
    pub pending: Vec<WindowUnitRef>,
    pub missing: Vec<WindowUnitRef>,
}

/// §7.5: the query that owns a snapshot read. The id is application-owned,
/// stable, and PHI-free; generated named queries pass their `ID` and `TABLES`.
#[derive(Debug, Clone, Copy)]
pub struct QueryOwner<'a> {
    pub id: &'a str,
    pub tables: &'a [&'a str],
}

/// §7.5: a failed snapshot read. `code` is `client.storage_corrupt` or
/// `client.storage_io` when SQLite reported corruption or I/O failure, and
/// `None` for every other failure, which keeps its existing message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct QueryReadFailure {
    pub code: Option<&'static str>,
    pub sqlite_code: Option<i32>,
    pub sqlite_message: Option<String>,
    pub rollback_failure: Option<Box<QueryReadFailure>>,
    pub message: String,
}

impl std::fmt::Display for QueryReadFailure {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.code {
            Some(code) => write!(f, "{code}: {}", self.message),
            None => f.write_str(&self.message),
        }
    }
}

impl From<String> for QueryReadFailure {
    fn from(message: String) -> Self {
        Self {
            code: None,
            sqlite_code: None,
            sqlite_message: None,
            rollback_failure: None,
            message,
        }
    }
}

impl From<rusqlite::Error> for QueryReadFailure {
    /// Classify by SQLite's primary result code, never by message text.
    fn from(error: rusqlite::Error) -> Self {
        let sqlite_code = match &error {
            rusqlite::Error::SqliteFailure(failure, _) => Some(failure.extended_code),
            _ => None,
        };
        match sqlite_code.map(|code| code & 0xff) {
            Some(11 | 26) => Self {
                code: Some("client.storage_corrupt"),
                sqlite_code,
                sqlite_message: Some(error.to_string()),
                rollback_failure: None,
                message: "local SQLite storage is corrupt".to_owned(),
            },
            Some(13) => Self {
                code: Some("client.storage_full"),
                sqlite_code,
                sqlite_message: Some(error.to_string()),
                rollback_failure: None,
                message: "local SQLite storage is full".to_owned(),
            },
            Some(10) => Self {
                code: Some("client.storage_io"),
                sqlite_code,
                sqlite_message: Some(error.to_string()),
                rollback_failure: None,
                message: "local SQLite storage I/O failed".to_owned(),
            },
            _ => Self {
                code: None,
                sqlite_code,
                sqlite_message: Some(error.to_string()),
                rollback_failure: None,
                message: error.to_string(),
            },
        }
    }
}

impl QueryReadFailure {
    pub fn details(&self) -> Option<Value> {
        self.sqlite_code.map(|code| {
            let mut details =
                serde_json::json!({ "sqliteCode": code, "sqliteMessage": self.sqlite_message });
            if let Some(rollback) = &self.rollback_failure {
                details["rollbackFailure"] = serde_json::json!({
                    "sqliteCode": rollback.sqlite_code, "message": rollback.sqlite_message
                });
            }
            details
        })
    }
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct QuerySnapshot {
    pub revision: String,
    pub rows: Vec<QueryRow>,
    pub coverage: CoverageSnapshot,
}

impl WindowState {
    /// The per-unit verdict: registered AND bootstrap-complete.
    #[must_use]
    pub fn complete(&self, unit: &str) -> bool {
        self.units.iter().any(|u| u == unit) && !self.pending.iter().any(|u| u == unit)
    }
}

/// One local mutation (§6.1 shapes, schema-agnostic local form per §0).
#[derive(Debug, Clone)]
pub enum Mutation {
    Patch {
        table: String,
        values: Map<String, Value>,
        base_version: Option<i64>,
    },
    Upsert {
        table: String,
        values: Map<String, Value>,
        base_version: Option<i64>,
    },
    Delete {
        table: String,
        row_id: String,
        base_version: Option<i64>,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct SchemaFloor {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub required_schema_version: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub latest_schema_version: Option<i32>,
}

/// §7.3.5: the client's opaque auth-lease state — `leaseId`/`expiresAtMs`
/// from the last `LEASE` frame, and `errorCode` once a round was rejected
/// with a request-level lease code (stop-and-surface; no data purge).
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct LeaseState {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lease_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at_ms: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_code: Option<String>,
}

/// §8.6 a peer's ephemeral presence document on a scope key.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PresencePeer {
    pub actor_id: String,
    pub client_id: String,
    pub doc: serde_json::Value,
}

#[derive(Debug, Clone, Serialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct SyncReport {
    pub pushed: u32,
    pub applied: Vec<String>,
    pub rejected: Vec<String>,
    pub retryable: Vec<String>,
    pub conflicts: u32,
    pub commits_applied: u32,
    pub segment_rows_applied: u32,
    pub bootstrapping: Vec<String>,
    pub resets: Vec<String>,
    pub revoked: Vec<String>,
    pub failed: Vec<String>,
    pub deferred_commits: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub schema_floor: Option<SchemaFloor>,
}

/// `sync()` never panics or errors out-of-band: transport and protocol
/// failures come back as `Failed` (the driver's `{ ok: false }`).
#[derive(Debug, Clone)]
pub enum SyncOutcome {
    Ok(SyncReport),
    Failed {
        error_code: String,
        message: String,
        details: Option<Value>,
    },
    /// §8.8: the `required` policy refused a round because the socket is not
    /// connected. `reason_code` is present for `lost` and `refused` states,
    /// and `retry_delay_ms` is the delay of the background retry intent this
    /// outcome scheduled.
    RealtimeUnavailable {
        state: RealtimeState,
        reason_code: Option<String>,
        retry_delay_ms: u64,
    },
}

impl SyncOutcome {
    pub fn to_json(&self) -> Value {
        match self {
            SyncOutcome::Ok(report) => {
                let mut map = Map::new();
                map.insert("ok".to_owned(), Value::Bool(true));
                map.insert(
                    "report".to_owned(),
                    serde_json::to_value(report).expect("report serializes"),
                );
                Value::Object(map)
            }
            SyncOutcome::Failed {
                error_code,
                message,
                details,
            } => {
                let mut map = Map::new();
                map.insert("ok".to_owned(), Value::Bool(false));
                map.insert("errorCode".to_owned(), Value::from(error_code.clone()));
                map.insert("message".to_owned(), Value::from(message.clone()));
                if let Some(details) = details {
                    map.insert("details".to_owned(), details.clone());
                }
                Value::Object(map)
            }
            SyncOutcome::RealtimeUnavailable {
                state,
                reason_code,
                retry_delay_ms,
            } => {
                let mut map = Map::new();
                map.insert("ok".to_owned(), Value::Bool(false));
                map.insert(
                    "errorCode".to_owned(),
                    Value::from(REALTIME_UNAVAILABLE_CODE),
                );
                map.insert(
                    "message".to_owned(),
                    Value::from("realtime is required and the realtime socket is not connected"),
                );
                map.insert(
                    "realtimeState".to_owned(),
                    serde_json::to_value(state).expect("state serializes"),
                );
                if let Some(reason_code) = reason_code {
                    map.insert(
                        "realtimeReasonCode".to_owned(),
                        Value::from(reason_code.clone()),
                    );
                }
                map.insert("retryDelayMs".to_owned(), Value::from(*retry_delay_ms));
                Value::Object(map)
            }
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ConflictRecord {
    pub client_commit_id: String,
    pub op_index: i32,
    pub table: String,
    pub row_id: String,
    pub code: String,
    pub message: String,
    pub server_version: i64,
    /// Driver row (bytes as `{"$bytes": hex}`), decoded from the conflict
    /// record's `serverRow` (§6.3).
    pub server_row: Map<String, Value>,
    /// §6.3 `conflictColumns`: the present columns whose `column_version`
    /// exceeded `baseVersion`, decoded from the bitmap into column names in
    /// declaration order. Absent on a legacy journal entry, which reads as an
    /// empty list.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub conflict_columns: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub operation: Option<CommitOperation>,
}

/// Bounded code-like metadata explicitly declared safe for authorized client
/// recovery UI. Diagnostic prose remains in `RejectionRecord.message`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RejectionDetails {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub field_paths: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub required_action: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub references: Option<BTreeMap<String, String>>,
}

impl RejectionDetails {
    pub(crate) fn parse(raw: &str) -> Result<Self, String> {
        if raw.len() > 4_096 {
            return Err("rejection details exceed 4096 encoded bytes".to_owned());
        }
        let details: Self = serde_json::from_str(raw)
            .map_err(|error| format!("invalid rejection details: {error}"))?;
        details.validate()?;
        Ok(details)
    }

    fn validate(&self) -> Result<(), String> {
        let mut members = 0;
        if let Some(paths) = &self.field_paths {
            members += 1;
            if paths.is_empty() || paths.len() > 32 {
                return Err("fieldPaths must contain 1-32 paths".to_owned());
            }
            let mut seen = std::collections::BTreeSet::new();
            for path in paths {
                if path.len() > 160 || !path.split('.').all(valid_identifier) || !seen.insert(path)
                {
                    return Err("fieldPaths contains an invalid or duplicate path".to_owned());
                }
            }
        }
        if let Some(reason) = &self.reason {
            members += 1;
            if !valid_token(reason, 96) {
                return Err("reason must be a lowercase stable token".to_owned());
            }
        }
        if let Some(action) = &self.required_action {
            members += 1;
            if !valid_token(action, 96) {
                return Err("requiredAction must be a lowercase stable token".to_owned());
            }
        }
        if let Some(references) = &self.references {
            members += 1;
            if references.is_empty() || references.len() > 16 {
                return Err("references must contain 1-16 entries".to_owned());
            }
            for (key, value) in references {
                if !valid_token(key, 64)
                    || value.is_empty()
                    || value.len() > 256
                    || value.trim() != value
                    || value.chars().any(char::is_control)
                {
                    return Err("references contains an invalid key or value".to_owned());
                }
            }
        }
        if members == 0 {
            return Err("rejection details must not be empty".to_owned());
        }
        Ok(())
    }
}

fn valid_identifier(segment: &str) -> bool {
    let mut chars = segment.chars();
    matches!(chars.next(), Some(first) if first == '_' || first.is_ascii_alphabetic())
        && chars.all(|character| character == '_' || character.is_ascii_alphanumeric())
}

fn valid_token(token: &str, max: usize) -> bool {
    if token.is_empty() || token.len() > max || !token.starts_with(|c: char| c.is_ascii_lowercase())
    {
        return false;
    }
    let mut previous_separator = false;
    for character in token.chars() {
        if character.is_ascii_lowercase() || character.is_ascii_digit() {
            previous_separator = false;
        } else if matches!(character, '.' | '_' | '-') && !previous_separator {
            previous_separator = true;
        } else {
            return false;
        }
    }
    !previous_separator
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct RejectionRecord {
    pub client_commit_id: String,
    pub op_index: i32,
    pub code: String,
    pub message: String,
    pub retryable: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<RejectionDetails>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub operation: Option<CommitOperation>,
}

/// Schema-agnostic local operation retained with a failed final outcome.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CommitOperation {
    pub table: String,
    pub row_id: String,
    pub op: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub base_version: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub values: Option<Map<String, Value>>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum CommitOutcomeStatus {
    Applied,
    Cached,
    Conflict,
    Rejected,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum CommitOutcomeResolution {
    Active,
    ResolvedKeepServer,
    Superseded,
    Dismissed,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum CommitOperationOutcome {
    Applied {
        #[serde(rename = "opIndex")]
        op_index: i32,
    },
    Conflict {
        conflict: ConflictRecord,
    },
    Error {
        rejection: RejectionRecord,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct RetainedCommitRow {
    pub table: String,
    pub row_id: String,
    pub local_row: Option<Map<String, Value>>,
    pub server_row: Option<Map<String, Value>>,
    pub server_version: Option<i64>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CommitOutcome {
    pub sequence: i64,
    pub client_commit_id: String,
    pub status: CommitOutcomeStatus,
    pub recorded_at_ms: i64,
    pub results: Vec<CommitOperationOutcome>,
    /// Complete local failed-commit envelope retained after outbox drain.
    /// Absent for successful and historical outcomes; never sent over wire.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub operations: Option<Vec<CommitOperation>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retained_rows: Option<Vec<RetainedCommitRow>>,
    pub resolution: CommitOutcomeResolution,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resolved_at_ms: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub replacement_client_commit_id: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct CommitOutcomeQuery {
    pub limit: Option<usize>,
    #[serde(default)]
    pub active_only: bool,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ResolveCommitOutcomeInput {
    pub client_commit_id: String,
    pub resolution: CommitOutcomeResolution,
    pub replacement_client_commit_id: Option<String>,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RowState {
    pub row_id: String,
    /// Local synced version: `-1` = optimistic, else the server version
    /// (from a `COMMIT` change or a segment row record, §5.2/§5.6).
    pub version: i64,
    pub values: Map<String, Value>,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SubscriptionStateView {
    pub id: String,
    pub table: String,
    /// `active` | `revoked` | `failed`.
    pub status: String,
    pub cursor: i64,
    pub has_resume_token: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub effective_scopes: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason_code: Option<String>,
}

/// One AND-combined application-authorized local purge target. Targets in
/// one input are OR-combined. Selector columns must compile to plaintext
/// strings; values are bounded code-like routing identifiers.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct LocalDataPurgeTarget {
    pub table: String,
    pub selectors: BTreeMap<String, Vec<String>>,
}

/// Durable local idempotency key plus exact routing targets. The host owns
/// directive authenticity and subscription gating; the client owns SQLite.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct LocalDataPurgeInput {
    pub purge_id: String,
    pub targets: Vec<LocalDataPurgeTarget>,
}

/// Privacy-safe local purge acknowledgement; row ids never cross the bridge.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct LocalDataPurgeResult {
    pub already_applied: bool,
    pub purged_rows: usize,
    pub dropped_commits: usize,
}

/// Durable application repair id. Reusing the id is an exact no-op.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct LocalDataRebootstrapInput {
    pub rebootstrap_id: String,
}

/// Privacy-safe acknowledgement for a replicated-projection recovery.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct LocalDataRebootstrapResult {
    pub already_applied: bool,
    pub retained_commits: usize,
    pub reset_subscriptions: usize,
}

/// Client limits (§4.2 request knobs).
#[derive(Debug, Clone, Default)]
pub struct ClientLimits {
    pub limit_commits: Option<i32>,
    pub limit_snapshot_rows: Option<i32>,
    pub max_snapshot_pages: Option<i32>,
    /// §4.2 accept bitmask; this client defaults to `0b0111` (rows
    /// baseline + sqlite images, §5.3 — rusqlite can always import).
    pub accept: Option<u8>,
    /// §5.9.7 B1 blob-cache size cap (bytes). When set and the sum of cached
    /// body sizes exceeds it, unreferenced bodies without pending work are
    /// evicted by creation timestamp after each cache write. `None` retains bodies
    /// until storage pressure (default).
    pub blob_cache_max_bytes: Option<i64>,
    /// Maximum durable final outcomes. Active conflicts/rejections are never
    /// pruned to satisfy the cap. Defaults to 1,000.
    pub outcome_retention_max_entries: Option<usize>,
    /// RFC 0005 D8: the previous-version capture config. Absent or
    /// `enabled: false` runs the feature off (default); the descriptor write
    /// and the container orphan sweep still happen.
    pub previous_version_context: Option<PreviousVersionContextConfig>,
}