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
//! Note storage capability — temporal-referential record CRUD.
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use uuid::Uuid;
use crate::types::{
BatchWriteSummary, BoundedCount, DeleteMode, Page, PageRequest, SeekCursor, SeekPage, SqlValue,
StorageResult,
};
/// A storage-level note record. Flat, SQL-friendly representation.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Note {
pub id: Uuid,
pub namespace: String,
pub kind: String,
pub status: String,
pub name: Option<String>,
pub content: String,
pub salience: Option<f64>,
pub decay_factor: Option<f64>,
pub expires_at: Option<i64>,
pub properties: Option<Value>,
pub created_at: i64,
pub updated_at: i64,
pub deleted_at: Option<i64>,
/// Immutable caller-chosen identity, unique among live notes of the same namespace and kind.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key: Option<String>,
/// Persisted revision, assigned by storage and advanced on every matched update.
#[serde(default = "initial_note_version")]
pub version: i64,
}
const fn initial_note_version() -> i64 {
1
}
impl Note {
/// Create a new note with a generated UUID and current timestamp.
pub fn new(
namespace: impl Into<String>,
kind: impl Into<String>,
content: impl Into<String>,
) -> Self {
let now = chrono::Utc::now().timestamp_micros();
Self {
id: Uuid::new_v4(),
namespace: namespace.into(),
kind: kind.into(),
status: "active".to_string(),
name: None,
content: content.into(),
salience: None,
decay_factor: None,
expires_at: None,
properties: None,
created_at: now,
updated_at: now,
deleted_at: None,
key: None,
version: 1,
}
}
/// Set the note display name.
pub fn with_name(mut self, n: impl Into<String>) -> Self {
self.name = Some(n.into());
self
}
/// Set salience (infallible). Rejects non-finite values by returning `self`
/// unchanged; clamps finite values to `[0.0, 1.0]`. Prefer
/// [`try_with_salience`](Self::try_with_salience) at public boundaries.
pub fn with_salience(mut self, s: f64) -> Self {
if !s.is_finite() {
return self;
}
self.salience = Some(s.clamp(0.0, 1.0));
self
}
/// Set decay factor (infallible). Rejects non-finite values by returning
/// `self` unchanged; floors finite values at `0.0`. Prefer
/// [`try_with_decay`](Self::try_with_decay) at public boundaries.
pub fn with_decay(mut self, d: f64) -> Self {
if !d.is_finite() {
return self;
}
self.decay_factor = Some(d.max(0.0));
self
}
/// Set salience with validation. Returns an error for non-finite or
/// out-of-range `[0.0, 1.0]` values.
pub fn try_with_salience(mut self, s: f64) -> Result<Self, String> {
if !s.is_finite() {
return Err(format!("salience must be finite, got {s}"));
}
if !(0.0..=1.0).contains(&s) {
return Err(format!("salience must be in [0.0, 1.0], got {s}"));
}
self.salience = Some(s);
Ok(self)
}
/// Set decay factor with validation. Returns an error for non-finite or
/// negative values.
pub fn try_with_decay(mut self, d: f64) -> Result<Self, String> {
if !d.is_finite() {
return Err(format!("decay_factor must be finite, got {d}"));
}
if d < 0.0 {
return Err(format!("decay_factor must be >= 0.0, got {d}"));
}
self.decay_factor = Some(d);
Ok(self)
}
/// Set the note properties JSON blob.
pub fn with_properties(mut self, p: Value) -> Self {
self.properties = Some(p);
self
}
}
#[cfg(test)]
mod tests {
use super::*;
fn base_note() -> Note {
Note::new("ns:test", "memory", "hello world")
}
#[test]
fn note_key_is_optional_and_unkeyed_wire_shape_is_unchanged() {
let note = base_note();
assert_eq!(note.key, None);
let legacy = serde_json::to_value(¬e).unwrap();
assert!(legacy.get("key").is_none());
assert_eq!(serde_json::from_value::<Note>(legacy).unwrap(), note);
let mut keyed = note;
keyed.key = Some("operation-1".to_string());
let encoded = serde_json::to_value(&keyed).unwrap();
assert_eq!(encoded["key"], "operation-1");
assert_eq!(serde_json::from_value::<Note>(encoded).unwrap(), keyed);
}
// -- with_salience --
#[test]
fn with_salience_clamps_to_range() {
let n = base_note().with_salience(1.5);
assert_eq!(n.salience, Some(1.0));
let n = base_note().with_salience(-0.1);
assert_eq!(n.salience, Some(0.0));
let n = base_note().with_salience(0.7);
assert_eq!(n.salience, Some(0.7));
}
#[test]
fn with_salience_ignores_nan() {
let n = base_note().with_salience(f64::NAN);
assert_eq!(n.salience, None, "NaN must not set salience");
}
#[test]
fn with_salience_ignores_inf() {
let n = base_note().with_salience(f64::INFINITY);
assert_eq!(n.salience, None, "+Inf must not set salience");
let n = base_note().with_salience(f64::NEG_INFINITY);
assert_eq!(n.salience, None, "-Inf must not set salience");
}
// -- with_decay --
#[test]
fn with_decay_floors_at_zero() {
let n = base_note().with_decay(-1.0);
assert_eq!(n.decay_factor, Some(0.0));
let n = base_note().with_decay(0.5);
assert_eq!(n.decay_factor, Some(0.5));
}
#[test]
fn with_decay_ignores_nan() {
let n = base_note().with_decay(f64::NAN);
assert_eq!(n.decay_factor, None, "NaN must not set decay_factor");
}
#[test]
fn with_decay_ignores_inf() {
let n = base_note().with_decay(f64::INFINITY);
assert_eq!(n.decay_factor, None, "+Inf must not set decay_factor");
}
// -- try_with_salience --
#[test]
fn try_with_salience_accepts_valid_range() {
let n = base_note().try_with_salience(0.0).unwrap();
assert_eq!(n.salience, Some(0.0));
let n = base_note().try_with_salience(1.0).unwrap();
assert_eq!(n.salience, Some(1.0));
let n = base_note().try_with_salience(0.85).unwrap();
assert_eq!(n.salience, Some(0.85));
}
#[test]
fn try_with_salience_rejects_nan() {
let err = base_note().try_with_salience(f64::NAN).unwrap_err();
assert!(err.contains("finite"), "error must mention finite: {err}");
}
#[test]
fn try_with_salience_rejects_out_of_range() {
let err = base_note().try_with_salience(1.1).unwrap_err();
assert!(err.contains("1.0"), "error must mention bound: {err}");
let err = base_note().try_with_salience(-0.01).unwrap_err();
assert!(err.contains("0.0"), "error must mention bound: {err}");
}
// -- try_with_decay --
#[test]
fn try_with_decay_accepts_valid_values() {
let n = base_note().try_with_decay(0.0).unwrap();
assert_eq!(n.decay_factor, Some(0.0));
let n = base_note().try_with_decay(2.5).unwrap();
assert_eq!(n.decay_factor, Some(2.5));
}
#[test]
fn try_with_decay_rejects_nan() {
let err = base_note().try_with_decay(f64::NAN).unwrap_err();
assert!(err.contains("finite"), "error must mention finite: {err}");
}
#[test]
fn try_with_decay_rejects_negative() {
let err = base_note().try_with_decay(-0.1).unwrap_err();
assert!(err.contains("0.0"), "error must mention bound: {err}");
}
#[derive(Default)]
struct DefaultOnlyNoteStore {
query_calls: std::sync::atomic::AtomicUsize,
}
impl DefaultOnlyNoteStore {
fn query_call_count(&self) -> usize {
self.query_calls.load(std::sync::atomic::Ordering::SeqCst)
}
}
fn unsupported<T>(operation: &'static str) -> StorageResult<T> {
Err(crate::StorageError::Unsupported {
capability: crate::StorageCapability::Notes,
operation: operation.into(),
message: "test double does not implement this operation".into(),
})
}
#[async_trait]
impl NoteStore for DefaultOnlyNoteStore {
async fn upsert_note(&self, _note: Note) -> StorageResult<()> {
unsupported("upsert_note")
}
async fn upsert_notes(&self, _notes: Vec<Note>) -> StorageResult<BatchWriteSummary> {
unsupported("upsert_notes")
}
async fn get_note(&self, _id: Uuid) -> StorageResult<Option<Note>> {
unsupported("get_note")
}
async fn get_note_including_deleted(&self, _id: Uuid) -> StorageResult<Option<Note>> {
unsupported("get_note_including_deleted")
}
async fn delete_note(&self, _id: Uuid, _mode: DeleteMode) -> StorageResult<bool> {
unsupported("delete_note")
}
async fn update_note_properties(
&self,
_id: Uuid,
_properties: Option<Value>,
_updated_at: i64,
) -> StorageResult<bool> {
unsupported("update_note_properties")
}
async fn set_note_property(
&self,
_id: Uuid,
_key: &str,
_value: Value,
_updated_at: i64,
) -> StorageResult<bool> {
unsupported("set_note_property")
}
async fn try_patch_note_property(
&self,
_id: Uuid,
_namespace: &str,
_filter: &NoteFilter,
_json_path: &str,
_value: Value,
_updated_at: i64,
) -> StorageResult<bool> {
unsupported("try_patch_note_property")
}
async fn query_notes(
&self,
_namespace: &str,
_kind: Option<&str>,
_page: PageRequest,
) -> StorageResult<Page<Note>> {
self.query_calls
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Ok(Page {
items: Vec::new(),
total: Some(0),
})
}
async fn query_notes_filtered(
&self,
_namespace: &str,
_filter: &NoteFilter,
_page: PageRequest,
) -> StorageResult<Page<Note>> {
self.query_calls
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Ok(Page {
items: Vec::new(),
total: Some(0),
})
}
async fn query_notes_filtered_bounded(
&self,
_namespace: &str,
_filter: &NoteFilter,
_max_rows: u32,
) -> StorageResult<Vec<Note>> {
unsupported("query_notes_filtered_bounded")
}
async fn count_notes(&self, _namespace: &str, _kind: Option<&str>) -> StorageResult<u64> {
unsupported("count_notes")
}
async fn try_insert_note(&self, _note: Note) -> StorageResult<bool> {
unsupported("try_insert_note")
}
}
#[tokio::test]
async fn default_snapshot_count_is_fail_closed_without_query_fallback() {
let store = DefaultOnlyNoteStore::default();
let result = store
.count_notes_filtered_in_snapshot(
"ns:test",
&[NoteFilter::default(), NoteFilter::default()],
)
.await;
assert!(
matches!(
result,
Err(crate::StorageError::Unsupported { ref operation, .. })
if operation == "count_notes_filtered_in_snapshot"
),
"inherited snapshot count must fail closed, got {result:?}"
);
assert_eq!(
store.query_call_count(),
0,
"inherited snapshot count must not fall back to independent queries"
);
}
#[tokio::test]
async fn count_free_page_default_is_fail_closed_without_exact_query_fallback() {
let store = DefaultOnlyNoteStore::default();
let result = store
.query_notes_filtered_count_free(
"ns:test",
&NoteFilter::default(),
PageRequest::default(),
)
.await;
assert!(
matches!(
result,
Err(crate::StorageError::Unsupported { ref operation, .. })
if operation == "query_notes_filtered_count_free"
),
"inherited count-free query must fail closed, got {result:?}"
);
assert_eq!(
store.query_call_count(),
0,
"count-free default must not invoke the exact-count page"
);
}
#[tokio::test]
async fn unfiltered_count_free_page_default_is_fail_closed_without_exact_query_fallback() {
let store = DefaultOnlyNoteStore::default();
let result = store
.query_notes_count_free("ns:test", Some("message"), PageRequest::default())
.await;
assert!(
matches!(
result,
Err(crate::StorageError::Unsupported { ref operation, .. })
if operation == "query_notes_count_free"
),
"inherited count-free query must fail closed, got {result:?}"
);
assert_eq!(
store.query_call_count(),
0,
"count-free default must not invoke the exact-count page"
);
}
#[tokio::test]
async fn bounded_snapshot_count_default_is_fail_closed_without_query_fallback() {
let store = DefaultOnlyNoteStore::default();
let result = store
.count_notes_filtered_bounded_in_snapshot(
"ns:test",
&[NoteFilter::default(), NoteFilter::default()],
1_000,
)
.await;
assert!(
matches!(
result,
Err(crate::StorageError::Unsupported { ref operation, .. })
if operation == "count_notes_filtered_bounded_in_snapshot"
),
"inherited bounded snapshot count must fail closed, got {result:?}"
);
assert_eq!(
store.query_call_count(),
0,
"bounded snapshot count must not compose independent page queries"
);
}
}
/// Sort direction for filtered note queries.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SortDir {
Asc,
Desc,
}
/// Comparison operator for a [`PropertyFilter`] on a JSON path.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FilterOp {
Eq,
/// Matches rows where the JSON field equals the value OR the field is absent/NULL.
/// Used for properties that may be missing in legacy rows (e.g. `$.read`).
EqOrMissing,
/// Matches the supplied value using the indexable
/// `ifnull(json_extract(...), '')` expression. The value may be any
/// [`SqlValue`] accepted by the SQL adapter; in particular, `Text("")`
/// matches both missing values and present-but-empty values.
EqOrMissingIndexed,
/// Matches rows where the JSON field is absent or SQL-NULL.
JsonTypeMissing,
/// Matches rows where the JSON field is absent or explicitly JSON `null`,
/// while constraining its index key to the empty recipient key. This is
/// the index-friendly legacy-recipient partition used with
/// [`FilterOp::EqOrMissingIndexed`].
JsonTypeMissingOrNullIndexed,
/// Combines the exact-value and legacy-recipient partitions
/// (`EqOrMissingIndexed` + `JsonTypeMissingOrNullIndexed`) into one
/// predicate over the same indexable `ifnull(json_extract(...), '')`
/// expression, so a single index seek serves both partitions instead of
/// two separate bounded queries. Matches rows where the field equals the
/// value, OR the field is absent/JSON-`null`. A present-but-empty JSON
/// string value does NOT match through the legacy branch — the same
/// `json_type` guard `JsonTypeMissingOrNullIndexed` uses excludes it —
/// so this reproduces `EqOrMissing` exactly, given a non-empty compared
/// value.
EqOrLegacyIndexed,
/// Matches rows where a JSON text field equals the value, while treating
/// every missing or non-text value as that same value. The SQL adapter
/// emits `CASE WHEN json_type(...) = 'text' THEN json_extract(...) ELSE
/// value END = value`, mirroring callers whose read model assigns one
/// textual default to absent, JSON-null, and malformed legacy values.
TextEqOrNonText,
/// Matches a JSON text field against the supplied set, or any missing or
/// non-text value. The non-text branch still matches when the set is empty.
/// `PropertyFilter.value` is unused; the set lives in this variant.
TextInOrNonText(Vec<SqlValue>),
Ne,
Lt,
Lte,
Gt,
Gte,
/// Matches rows where `json_type(properties, path) = value`.
/// Value must be a SQLite json_type string literal: 'true', 'false', 'integer',
/// 'real', 'text', 'array', 'object', or 'null'.
JsonTypeEq,
/// Matches rows where the json_type is absent (NULL) OR differs from value.
/// Equivalent to `json_type IS NULL OR json_type != value`.
/// Value must be a SQLite json_type string literal: 'true', 'false',
/// 'integer', 'real', 'text', 'array', 'object', or 'null'. Used for
/// unread filter: matches any `$.read` that is NOT the JSON boolean true.
JsonTypeNeMissing,
/// Matches rows where `json_extract(properties, path)` equals any value in
/// the set. A row with a missing/NULL property does not match — use
/// `TextInOrNonText` when a textual read model includes missing/non-text
/// legacy values. `PropertyFilter.value` is unused for this op; the set
/// lives in the variant itself.
In(Vec<SqlValue>),
/// Matches rows where the property is missing/NULL OR its value is not in
/// the set. Used to exclude a closed set while treating an unset property
/// as included (e.g. comm inbox excludes `outbound`). `PropertyFilter.value` is
/// unused for this op; the set lives in the variant itself.
NotInOrMissing(Vec<SqlValue>),
/// Matches rows whose JSON text field starts with the supplied prefix.
/// Rendered as an index-seekable half-open range over the plain
/// `json_extract` expression (`expr >= prefix AND expr < next(prefix)`,
/// where `next` increments the prefix's last code point), so an index
/// keyed on that expression serves the seek instead of a scan. SQLite
/// sorts non-text values outside the text range, so a missing, null or
/// numeric field never matches. `PropertyFilter.value` is the prefix and
/// must be `SqlValue::Text`; an empty prefix matches every text value.
TextStartsWithIndexed,
/// Keep only RFC 3339 text values that parse as UTC instants.
Rfc3339Valid,
/// Compare parsed UTC instants, including subsecond precision and offsets.
/// The value is a `Timestamp` or RFC 3339 `Text`.
Rfc3339Gte,
Rfc3339Lte,
}
/// A single `json_extract(properties, '$.field') op value` predicate.
///
/// Callers import this as `khive_storage::note::PropertyFilter` to avoid
/// collision with the vector-metadata `PropertyFilter` in `khive_storage::types`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PropertyFilter {
pub json_path: String,
pub op: FilterOp,
pub value: SqlValue,
}
/// Keyset pagination boundary over the notes store's default total order
/// (`created_at DESC, id ASC` — see `note_filter_page_order_clause`).
///
/// Only meaningful when [`NoteFilter::order_by`] is `None`: the boundary is
/// expressed in terms of that default order, and combining it with a custom
/// sort field has no defined meaning, so callers must not set both.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct NoteSeekAfter {
pub created_at: i64,
pub id: Uuid,
}
/// Boundary in an ascending RFC 3339 property order. Equal instants sort by
/// their stored text and then note ID, so this cursor identifies one row even
/// when distinct offsets encode the same instant.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct NoteInstantSeekAfter {
pub value: String,
pub id: Uuid,
}
#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum NoteTagMode {
#[default]
Any,
All,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct NoteKeyCursor {
pub updated_at: i64,
pub key: String,
pub id: Uuid,
}
impl From<&Note> for NoteKeyCursor {
fn from(note: &Note) -> Self {
Self {
updated_at: note.updated_at,
key: note.key.clone().expect("keyed row"),
id: note.id,
}
}
}
/// Filter + sort options for [`NoteStore::query_notes_filtered`].
///
/// Designed for general property-based filtering on any JSON field, not
/// schedule-specific, so D9 and future packs can reuse the same API.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct NoteFilter {
pub kind: Option<String>,
#[serde(default)]
pub property_filters: Vec<PropertyFilter>,
/// `(json_path, direction)` — `None` defaults to `created_at DESC`.
pub order_by: Option<(String, SortDir)>,
/// Interpret `order_by`'s text property as an RFC 3339 UTC instant before
/// sorting. Only ascending order is currently supported.
#[serde(default)]
pub order_by_instant: bool,
/// When true, omit the SQL ordering clause from count-free pages. The
/// caller is responsible for ordering the bounded result set.
#[serde(default)]
pub unordered: bool,
/// When non-empty, restricts results to any of these namespaces using
/// `namespace IN (...)`. Takes precedence over the `namespace` string
/// parameter passed to `query_notes_filtered`. When empty the
/// caller-supplied `namespace` parameter is used (backward-compatible).
#[serde(default)]
pub namespaces: Vec<String>,
/// Restrict to notes where `created_at >= min_created_at` (microseconds epoch).
/// `None` applies no lower-bound constraint.
pub min_created_at: Option<i64>,
#[serde(default)]
pub min_updated_at: Option<i64>,
#[serde(default)]
pub tags: Vec<String>,
#[serde(default)]
pub tag_mode: NoteTagMode,
/// Restrict results to rows strictly after this boundary in the default
/// `created_at DESC, id ASC` order, for keyset (seek) pagination that
/// avoids re-walking earlier pages the way `PageRequest.offset` does.
/// Requires `order_by` to be `None`.
///
/// Honoured only by [`NoteStore::query_notes_filtered_count_free`], which
/// seeks directly to the boundary and returns `total: None`.
/// [`NoteStore::query_notes_filtered`] rejects a non-`None` value with
/// `StorageError::InvalidInput`: it computes an exact `COUNT(*)` total
/// over the whole matching set, which has no defined meaning paired with
/// a seek boundary.
#[serde(default)]
pub after: Option<NoteSeekAfter>,
/// Seek after a row in the `order_by_instant` total order. Honoured only
/// by `query_notes_filtered_count_free` with `offset: 0`.
#[serde(default)]
pub after_instant: Option<NoteInstantSeekAfter>,
}
/// Temporal-referential note CRUD over the notes substrate table.
#[async_trait]
pub trait NoteStore: Send + Sync + 'static {
async fn get_live_notes_by_key(
&self,
_namespace: &str,
_key: &str,
_kind: Option<&str>,
) -> StorageResult<Vec<Note>> {
Err(crate::StorageError::Unsupported {
capability: crate::StorageCapability::Notes,
operation: "get_live_notes_by_key".into(),
message: "backend has no keyed note lookup".into(),
})
}
async fn query_keyed_notes(
&self,
_namespace: &str,
_filter: &NoteFilter,
_prefix: &str,
_after: Option<&NoteKeyCursor>,
_page: PageRequest,
) -> StorageResult<(Vec<Note>, Option<NoteKeyCursor>)> {
Err(crate::StorageError::Unsupported {
capability: crate::StorageCapability::Notes,
operation: "query_keyed_notes".into(),
message: "backend has no keyed note pagination".into(),
})
}
/// Insert or update a single note. Updates preserve the stored immutable key.
async fn upsert_note(&self, note: Note) -> StorageResult<()>;
/// Replace a note only when the persisted row still matches the caller's
/// read snapshot.
///
/// `expected_updated_at` is the snapshot revision and
/// `expected_deleted_at` closes the soft-delete race (legacy soft-delete
/// paths may change `deleted_at` without changing `updated_at`). The
/// replacement note's `updated_at` must be strictly greater than that
/// persisted revision. Returns `false` when the row disappeared, changed,
/// or was supplied a non-advancing replacement revision. This is the
/// full-note compare-and-swap seam used when a pack hook derives coupled
/// fields from that snapshot before persistence. The default returns
/// `Unsupported` rather than falling back to an unguarded upsert and
/// reintroducing the stale-snapshot race.
async fn replace_note_if_unchanged(
&self,
_note: Note,
_expected_updated_at: i64,
_expected_deleted_at: Option<i64>,
) -> StorageResult<bool> {
Err(crate::StorageError::Unsupported {
capability: crate::StorageCapability::Notes,
operation: "replace_note_if_unchanged".into(),
message: "this backend does not implement guarded note replacement".into(),
})
}
/// Insert a note only if no row already holds its id, reporting whether
/// this call is the one that inserted it.
///
/// This closes the other half of the read-modify-write race that
/// [`NoteStore::replace_note_if_unchanged`] closes. That one protects a
/// caller who read an existing row; this one protects a caller who read
/// *no* row. Where the id is derived rather than freshly generated — a
/// deterministic per-subject id — two callers can both read absence and
/// both write, and an upsert resolves that by overwriting, so the first
/// caller's write is lost with no error on either side. Returns `false`
/// when a row already existed, which the caller maps to a conflict rather
/// than to success.
///
/// The pre-existing row is left exactly as it is: this must not be
/// implemented as an upsert, since overwriting is the behaviour being
/// avoided. The default returns `Unsupported` for that reason, rather
/// than falling back to `upsert_note` and silently reintroducing the
/// race under a name that promises otherwise.
async fn insert_note_if_absent(&self, _note: Note) -> StorageResult<bool> {
Err(crate::StorageError::Unsupported {
capability: crate::StorageCapability::Notes,
operation: "insert_note_if_absent".into(),
message: "this backend does not implement guarded note insertion".into(),
})
}
/// Insert or update a batch of notes. Updates preserve each stored immutable key.
async fn upsert_notes(&self, notes: Vec<Note>) -> StorageResult<BatchWriteSummary>;
/// Fetch a note by UUID, returning `None` if absent.
async fn get_note(&self, id: Uuid) -> StorageResult<Option<Note>>;
/// Fetch a note by UUID regardless of soft-deletion state.
///
/// Returns the note row even when `deleted_at` is set. Callers use this
/// to distinguish "soft-deleted" from "never existed".
async fn get_note_including_deleted(&self, id: Uuid) -> StorageResult<Option<Note>>;
/// Delete a note by UUID using the specified delete mode.
async fn delete_note(&self, id: Uuid, mode: DeleteMode) -> StorageResult<bool>;
/// Patch `properties`/`updated_at` on an existing note in place via a real
/// `UPDATE`, leaving every other column (including the row's `rowid`)
/// untouched.
///
/// Unlike `upsert_note`, which writes the complete note shape, this leaves
/// every non-property column untouched. It also never churns the row's
/// implicit `rowid`, which is required by callers relying on stable row
/// identity (#780).
/// Returns `true` when a live (non-soft-deleted) row with this `id` was
/// found and updated, `false` otherwise.
async fn update_note_properties(
&self,
id: Uuid,
properties: Option<Value>,
updated_at: i64,
) -> StorageResult<bool>;
/// Atomically set one top-level key in a note's JSON `properties` object.
///
/// The backend must perform the read/modify/write as one storage operation
/// so concurrent writes to different keys cannot overwrite each other.
/// `value` keeps its JSON type, including explicit JSON `null`. A SQL-NULL
/// property document is initialized as an empty object. A live row whose
/// stored document is a non-object is not modified and returns `false`, as
/// do missing and soft-deleted rows. Keys containing U+0000 must be
/// rejected: SQLite JSON-path labels cannot address them without risking
/// mutation of a shorter sibling key.
async fn set_note_property(
&self,
id: Uuid,
key: &str,
value: Value,
updated_at: i64,
) -> StorageResult<bool>;
/// Atomically patch a single `properties` JSON key on a note, but only
/// when the row's *current* state (re-evaluated inside this same
/// statement, not a snapshot the caller fetched earlier) still satisfies
/// `filter`'s namespace/kind/property_filters.
///
/// Unlike `set_note_property` (which patches unconditionally once the row
/// is live) or `update_note_properties` (which replaces the whole
/// `properties` column with a value the caller already computed — safe
/// only when nothing else can have written to the row since the caller's
/// read), this also rechecks `filter` against the row's live state before
/// writing, so a target that stopped matching an eligibility predicate
/// between validation and this call is not mutated. Any other property
/// written concurrently between the caller's read and this call survives
/// untouched either way. A live row whose stored `properties` document is
/// a non-object (scalar, array, or otherwise) is not modified and returns
/// `false`, mirroring `set_note_property`. Returns `Ok(false)` — not an
/// error — when no live row currently matches `filter` (id not found,
/// soft-deleted, an eligibility property changed since the caller last
/// validated it, or the stored document is not a JSON object); the
/// caller degrades that the same way as `update_note_properties`'s
/// `Ok(false)`.
async fn try_patch_note_property(
&self,
id: Uuid,
namespace: &str,
filter: &NoteFilter,
json_path: &str,
value: Value,
updated_at: i64,
) -> StorageResult<bool>;
/// Atomically patch one JSON property on every supplied note.
///
/// Each target is rechecked against `namespace` and `filter` inside the
/// same transaction. The operation commits only when every distinct id
/// matches exactly one live object-valued row; a missing, soft-deleted, or
/// no-longer-eligible target rolls the entire unit back. Other property
/// keys are preserved by the same storage-side `json_set` operation as
/// [`Self::try_patch_note_property`]. Backends without a transactional
/// multi-note implementation retain the default `Unsupported` result.
async fn patch_note_property_atomic(
&self,
_ids: Vec<Uuid>,
_namespace: &str,
_filter: &NoteFilter,
_json_path: &str,
_value: Value,
_updated_at: i64,
) -> StorageResult<()> {
Err(crate::StorageError::Unsupported {
capability: crate::StorageCapability::Notes,
operation: "patch_note_property_atomic".into(),
message: "this backend does not implement atomic multi-note property patches".into(),
})
}
/// Query notes by namespace and optional kind with pagination.
/// The returned total and page items must come from one consistent
/// backend snapshot.
async fn query_notes(
&self,
namespace: &str,
kind: Option<&str>,
page: PageRequest,
) -> StorageResult<Page<Note>>;
/// Query notes by namespace and optional kind without computing an exact total.
///
/// Implementations must return `total: None`. Backends that cannot
/// guarantee a count-free projection must fail closed rather than invoke
/// [`Self::query_notes`], whose exact total remains available to callers
/// that expose a snapshot-consistent count.
async fn query_notes_count_free(
&self,
_namespace: &str,
_kind: Option<&str>,
_page: PageRequest,
) -> StorageResult<Page<Note>> {
Err(crate::StorageError::Unsupported {
capability: crate::StorageCapability::Notes,
operation: "query_notes_count_free".into(),
message: "this backend does not implement count-free note paging".into(),
})
}
/// Query notes with property-based filtering and custom sort.
/// The returned total and page items must come from one consistent
/// backend snapshot.
async fn query_notes_filtered(
&self,
namespace: &str,
filter: &NoteFilter,
page: PageRequest,
) -> StorageResult<Page<Note>>;
/// Query a filtered note page without computing an exact total.
///
/// Implementations must return `total: None`; callers that need a
/// `has_more` bit should request one lookahead row. Backends that cannot
/// guarantee a count-free projection must fail closed rather than invoke
/// [`Self::query_notes_filtered`], whose exact total is intentionally
/// backlog-proportional.
async fn query_notes_filtered_count_free(
&self,
_namespace: &str,
_filter: &NoteFilter,
_page: PageRequest,
) -> StorageResult<Page<Note>> {
Err(crate::StorageError::Unsupported {
capability: crate::StorageCapability::Notes,
operation: "query_notes_filtered_count_free".into(),
message: "this backend does not implement count-free filtered note paging".into(),
})
}
/// Count several filtered note populations in one consistent backend
/// snapshot. Backends that cannot provide that guarantee must return
/// [`crate::StorageError::Unsupported`] rather than composing independent
/// queries or treating an absent page total as zero. SQL backends should
/// override this operation so callers can retain separate index-friendly
/// predicates without racing between their counts.
async fn count_notes_filtered_in_snapshot(
&self,
_namespace: &str,
_filters: &[NoteFilter],
) -> StorageResult<Vec<u64>> {
Err(crate::StorageError::Unsupported {
capability: crate::StorageCapability::Notes,
operation: "count_notes_filtered_in_snapshot".into(),
message: "this backend does not implement snapshot-consistent filtered note counts"
.into(),
})
}
/// Count several filtered note populations in one backend snapshot, with
/// each count bounded by `cap`.
///
/// A saturated entry reports `count == cap` and `saturated == true`; an
/// unsaturated entry is exact. SQL implementations should count over a
/// limited `SELECT 1` subquery so work is proportional to `cap` and the
/// caller's own matching population, never an unrelated backlog. That
/// bound holds only when every `property_filter` in the given
/// `NoteFilter` is servable as an index key column (equality on a bound
/// parameter or a plan-time-provable partial-index predicate) all the way
/// down to the filter that actually narrows the population — a residual
/// filter evaluated after the index seek (a bound parameter the index
/// cannot use to skip rows) degrades the bound to work proportional to
/// the rows *scanned* before `cap` matches are found, not the rows that
/// match. Callers building filters against this bound must ensure the
/// full predicate set is indexed, not just the predicate that narrows the
/// population most. Backends that cannot preserve the shared snapshot or
/// work bound must fail closed.
async fn count_notes_filtered_bounded_in_snapshot(
&self,
_namespace: &str,
_filters: &[NoteFilter],
_cap: u32,
) -> StorageResult<Vec<BoundedCount>> {
Err(crate::StorageError::Unsupported {
capability: crate::StorageCapability::Notes,
operation: "count_notes_filtered_bounded_in_snapshot".into(),
message: "this backend does not implement snapshot-consistent bounded note counts"
.into(),
})
}
/// Resolve a note id to its immutable insertion sequence.
async fn note_sequence(&self, _id: Uuid) -> StorageResult<Option<i64>> {
Err(crate::StorageError::Unsupported {
capability: crate::StorageCapability::Notes,
operation: "note_sequence".into(),
message: "this backend does not implement note insertion sequences".into(),
})
}
/// Query an immutable insertion-sequence keyset page with the same
/// predicates as [`Self::query_notes_filtered`].
async fn query_notes_filtered_after(
&self,
_namespace: &str,
_filter: &NoteFilter,
_after: Option<SeekCursor>,
_limit: u32,
) -> StorageResult<SeekPage<Note>> {
Err(crate::StorageError::Unsupported {
capability: crate::StorageCapability::Notes,
operation: "query_notes_filtered_after".into(),
message: "this backend does not implement note seek pagination".into(),
})
}
/// Fetch up to `max_rows + 1` notes matching `filter` in a single
/// deterministically-ordered SQL statement, with no separate `COUNT(*)`
/// and no pagination loop.
///
/// A single statement observes one consistent snapshot for its entire
/// execution, so the result cannot be split across a concurrent insert
/// the way a `COUNT(*)` followed by independent `LIMIT`/`OFFSET` pages
/// can. Callers detect the over-bound case by checking whether the
/// returned `Vec` has more than `max_rows` items — that means at least
/// `max_rows + 1` rows matched and the caller must reject the query
/// rather than silently return a truncated, possibly priority-incomplete
/// set.
async fn query_notes_filtered_bounded(
&self,
namespace: &str,
filter: &NoteFilter,
max_rows: u32,
) -> StorageResult<Vec<Note>>;
/// Count notes in a namespace, optionally filtered by kind.
async fn count_notes(&self, namespace: &str, kind: Option<&str>) -> StorageResult<u64>;
/// Count notes across the given namespaces, optionally filtered by kind.
/// The default preserves compatibility by summing the existing
/// single-namespace operation; SQL backends should override this with one
/// `IN` aggregate.
async fn count_notes_in_namespaces(
&self,
namespaces: &[String],
kind: Option<&str>,
) -> StorageResult<u64> {
let mut total = 0;
for namespace in namespaces {
total += self.count_notes(namespace, kind).await?;
}
Ok(total)
}
/// Attempt to insert a note without overwriting an existing row.
///
/// Returns `true` when the row was newly written. Returns `false` only
/// when a live note with the same non-empty `external_id` already exists in
/// the same namespace and kind (confirmed dedup hit). Any other constraint
/// violation (e.g. a primary key collision) is surfaced as a `StorageError`
/// so that callers do not misinterpret unexpected failures as deduplication.
async fn try_insert_note(&self, note: Note) -> StorageResult<bool>;
/// Fetch multiple notes by UUID in a single call.
async fn get_notes_batch(&self, ids: &[Uuid]) -> StorageResult<Vec<Note>> {
let mut out = Vec::with_capacity(ids.len());
for &id in ids {
if let Some(n) = self.get_note(id).await? {
out.push(n);
}
}
Ok(out)
}
}