ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
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
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
use std::{collections::HashSet, path::PathBuf};

use super::{
  KeySegments, LocalFsBlob, LocalFsBlobError, LocalFsBlobRecord, LocalFsStore, MAX_PATH_LEN,
  MAX_SEGMENT_LEN, RESERVED, Segments, blob_address, is_verbatim, render_segment,
};
use crate::{
  AsyncBlobEngine, AsyncLocate, BlobRecord, Connected, Identifiable, Transformer, TypedId,
};

/// Drive a ready future without a runtime — the fs work is synchronous, so one poll suffices and an
/// async runtime would be a dev-dependency these tests do not spend.
fn block_on<F: Future>(future: F) -> F::Output {
  use core::{
    pin::pin,
    task::{Context, Poll, Waker},
  };
  let mut future = pin!(future);
  let mut cx = Context::from_waker(Waker::noop());
  loop {
    if let Poll::Ready(value) = future.as_mut().poll(&mut cx) {
      return value;
    }
  }
}

const SLOT: &str = "thumbnail";

// A two-level key: a text parent and an integer leaf — the compound shape a lineage key has.
struct ThumbKey {
  media: String,
  frame: i64,
}

impl ThumbKey {
  fn new(media: &str, frame: i64) -> Self {
    Self {
      media: media.to_owned(),
      frame,
    }
  }
}

impl KeySegments for ThumbKey {
  fn segments(&self, out: &mut Segments) {
    out.push(&self.media);
    out.push(&self.frame);
  }
}

struct Thumbnail {
  key: ThumbKey,
  bytes: Vec<u8>,
}

// The ancestor half of that key: the text parent, with the leaf left off.
struct ThumbLineage {
  #[expect(
    dead_code,
    reason = "the address binding names the type; no blob seam projects the lineage half"
  )]
  media: String,
}

impl Identifiable for Thumbnail {
  type Id = i64;

  fn id_ref(&self) -> &i64 {
    &self.key.frame
  }
}

impl Transformer for Thumbnail {
  type Key = ThumbKey;
  type Lineage = ThumbLineage;
  type Record = Self;
  // A blob is reached by its address and by nothing else — no wire face declares a filter, and no
  // table holds a column an order could name, so it binds no order on any `Record<B>` either.
  type Graphql = ();

  fn key(&self) -> ThumbKey {
    ThumbKey::new(&self.key.media, self.key.frame)
  }
}

impl BlobRecord for Thumbnail {
  type Bytes = Vec<u8>;

  fn bytes(&self) -> &Vec<u8> {
    &self.bytes
  }

  fn extension() -> Option<&'static str> {
    Some("png")
  }
}

// The SAME key with its leaf wrapped in a typed id — everything else, the parent segment and the
// extension included, held fixed, so a difference in the resolved path could only be the wrapper's.
struct TypedThumbKey {
  media: String,
  frame: TypedId<i64, TypedThumb>,
}

impl TypedThumbKey {
  fn new(media: &str, frame: i64) -> Self {
    Self {
      media: media.to_owned(),
      frame: TypedId::new(frame),
    }
  }
}

impl KeySegments for TypedThumbKey {
  fn segments(&self, out: &mut Segments) {
    out.push(&self.media);
    out.push(&self.frame);
  }
}

struct TypedThumb {
  key: TypedThumbKey,
}

impl Identifiable for TypedThumb {
  type Id = TypedId<i64, TypedThumb>;

  fn id_ref(&self) -> &Self::Id {
    &self.key.frame
  }
}

impl Transformer for TypedThumb {
  type Key = TypedThumbKey;
  type Lineage = ThumbLineage;
  type Record = Self;
  type Graphql = ();

  fn key(&self) -> TypedThumbKey {
    TypedThumbKey::new(&self.key.media, self.key.frame.id())
  }
}

impl BlobRecord for TypedThumb {
  type Bytes = Vec<u8>;

  fn bytes(&self) -> &Vec<u8> {
    unreachable!("the typed twin is only addressed, never written")
  }

  fn extension() -> Option<&'static str> {
    Some("png")
  }
}

// The same key with NO extension — the second half of the address pin.
struct Waveform;

impl Identifiable for Waveform {
  type Id = i64;

  // The leaf of the fixed key below — a record with no fields still answers the address it is
  // reached by.
  fn id_ref(&self) -> &i64 {
    &12
  }
}

impl Transformer for Waveform {
  type Key = ThumbKey;
  type Lineage = ThumbLineage;
  type Record = Self;
  type Graphql = ();

  fn key(&self) -> ThumbKey {
    ThumbKey::new("clip_42", 12)
  }
}

impl BlobRecord for Waveform {
  type Bytes = Vec<u8>;

  fn bytes(&self) -> &Vec<u8> {
    unreachable!("the extensionless record is only addressed, never written")
  }
}

// A key whose LEAF is TEXT, which the integer-leafed key above cannot be: the leaf is the one
// component whose written name is not its rendering — the record's extension goes on it — so it is
// the subject the per-component ceiling needs.
struct SlugKey {
  media: String,
  slug: String,
}

impl SlugKey {
  fn new(media: &str, slug: &str) -> Self {
    Self {
      media: media.to_owned(),
      slug: slug.to_owned(),
    }
  }
}

impl KeySegments for SlugKey {
  fn segments(&self, out: &mut Segments) {
    out.push(&self.media);
    out.push(&self.slug);
  }
}

struct Slugged {
  key: SlugKey,
}

impl Identifiable for Slugged {
  type Id = String;

  fn id_ref(&self) -> &String {
    &self.key.slug
  }
}

impl Transformer for Slugged {
  type Key = SlugKey;
  type Lineage = ThumbLineage;
  type Record = Self;
  type Graphql = ();

  fn key(&self) -> SlugKey {
    SlugKey::new(&self.key.media, &self.key.slug)
  }
}

impl BlobRecord for Slugged {
  type Bytes = Vec<u8>;

  fn bytes(&self) -> &Vec<u8> {
    unreachable!("the text-leafed record is only addressed, never written")
  }

  fn extension() -> Option<&'static str> {
    Some("png")
  }
}

// A key of ARBITRARY DEPTH, which is what the aggregate ceiling needs a subject for: a lineage whose
// every segment is comfortably under the per-component ceiling and whose whole address is not.
struct DeepKey(Vec<String>);

impl KeySegments for DeepKey {
  fn segments(&self, out: &mut Segments) {
    for level in &self.0 {
      out.push(level);
    }
  }
}

struct Deep;

// A key assembled at runtime has no statically-last field, so the id is the empty product — the
// `Nothing` fixture's reasoning, at a key with many columns rather than none.
impl Identifiable for Deep {
  type Id = ();

  fn id_ref(&self) -> &() {
    &()
  }
}

impl Transformer for Deep {
  type Key = DeepKey;
  type Lineage = ThumbLineage;
  type Record = Self;
  type Graphql = ();

  fn key(&self) -> DeepKey {
    DeepKey(Vec::new())
  }
}

impl BlobRecord for Deep {
  type Bytes = Vec<u8>;

  fn bytes(&self) -> &Vec<u8> {
    unreachable!("the deep record is only addressed, never written")
  }
}

fn open_store() -> (tempfile::TempDir, LocalFsStore) {
  let dir = tempfile::tempdir().expect("a temp dir");
  let store = LocalFsStore::open(dir.path()).expect("the store opens");
  (dir, store)
}

fn try_locate<R>(
  store: &LocalFsStore,
  slot: &str,
  key: &R::Key,
) -> Result<PathBuf, LocalFsBlobError>
where
  R: LocalFsBlobRecord,
  R::Bytes: AsRef<[u8]>,
{
  AsyncLocate::<R>::locate(
    &LocalFsBlob::new(slot),
    Connected::new(store, ()),
    key,
    R::extension(),
  )
}

fn locate<R>(store: &LocalFsStore, key: &R::Key) -> PathBuf
where
  R: LocalFsBlobRecord,
  R::Bytes: AsRef<[u8]>,
{
  try_locate::<R>(store, SLOT, key).expect("the address renders")
}

/// The names directly under the slot, sorted — what a browser of the tree would see.
fn slot_entries(dir: &tempfile::TempDir) -> Vec<String> {
  let mut names: Vec<_> = std::fs::read_dir(dir.path().join(SLOT))
    .expect("the slot directory")
    .map(|entry| {
      entry
        .expect("an entry")
        .file_name()
        .into_string()
        .expect("a utf-8 name")
    })
    .collect();
  names.sort();
  names
}

/// The address rendering, byte-exact, for a two-level key WITH an extension and WITHOUT one. This is
/// the scheme the user confirmed and it is a contract rather than an implementation detail: the slot
/// is the first segment, the key's fields are directory levels in walk order, and the leaf carries
/// the record's extension.
#[test]
fn a_two_level_key_renders_its_address_byte_exactly() {
  let (dir, store) = open_store();
  let key = ThumbKey::new("clip_42", 12);

  assert_eq!(
    locate::<Thumbnail>(&store, &key),
    dir.path().join("thumbnail/clip_42/12.png")
  );
  assert_eq!(
    locate::<Waveform>(&store, &key),
    dir.path().join("thumbnail/clip_42/12")
  );
}

/// A negative integer id: the sign is inside the verbatim charset, so it renders decimal and takes
/// no escape — which is what keeps an id-ordered directory browsable.
#[test]
fn a_negative_integer_renders_verbatim_with_its_sign() {
  let (dir, store) = open_store();

  assert_eq!(
    locate::<Thumbnail>(&store, &ThumbKey::new("clip", -7)),
    dir.path().join("thumbnail/clip/-7.png")
  );
  assert!(is_verbatim("-7"));
}

/// A text id outside the verbatim range takes the escape: a bare `=` plus lowercase base32 of the
/// UTF-8 bytes. Pinned byte-exactly, because it IS the address a reader reconstructs.
#[test]
fn a_text_id_that_escapes_renders_its_base32() {
  let (dir, store) = open_store();

  // RFC 4648 base32 of "a/b" (0x61 0x2f 0x62) is "MEXWE" once lowercased and unpadded.
  assert_eq!(
    locate::<Thumbnail>(&store, &ThumbKey::new("a/b", 1)),
    dir.path().join("thumbnail/=mexwe/1.png")
  );
}

/// Two text ids differing ONLY by case cannot collide — the property the single-case verbatim range
/// exists for, on a filesystem that compares names case-insensitively.
#[test]
fn text_ids_differing_only_by_case_never_collide() {
  let (dir, store) = open_store();
  let leaf = |media: &str| locate::<Thumbnail>(&store, &ThumbKey::new(media, 1));

  // One verbatim, one escaped: the ranges cannot meet.
  let lower = leaf("alice");
  let upper = leaf("Alice");
  assert_eq!(lower, dir.path().join("thumbnail/alice/1.png"));
  assert_ne!(lower, upper);
  assert_ne!(
    lower.to_str().expect("utf-8").to_lowercase(),
    upper.to_str().expect("utf-8").to_lowercase()
  );

  // And the both-escape case, where the verbatim range gives no help at all and only the
  // single-case alphabet does.
  let a = leaf("Bob Smith");
  let b = leaf("bob smith");
  assert_ne!(a, b);
  assert_ne!(
    a.to_str().expect("utf-8").to_lowercase(),
    b.to_str().expect("utf-8").to_lowercase()
  );
}

/// THE CASE PAIR, on a real filesystem rather than at the rendering: `"Abc"` and `"abc"` are two
/// ids that differ only by case, and they are TWO FILES THAT COEXIST — each reads back its own bytes
/// and both are on disk at once.
///
/// This is the property the single-case verbatim range exists for, and the one a render-level
/// assertion cannot reach: the product's own filesystem compares names case-insensitively, so a
/// two-case scheme would pass every rendering test in this file and still let the second `put`
/// silently overwrite the first. Pinned live, forever — any future widening of the verbatim charset
/// that admits a second case reds HERE.
#[test]
fn a_case_pair_writes_two_files_that_coexist() {
  let (dir, store) = open_store();
  let handle = LocalFsBlob::new(SLOT);
  let put = |media: &str, byte: u8| {
    block_on(handle.put(
      Connected::new(&store, ()),
      &Thumbnail {
        key: ThumbKey::new(media, 1),
        bytes: vec![byte],
      },
    ))
    .expect("the put")
  };
  let get = |media: &str| {
    block_on(AsyncBlobEngine::<Thumbnail>::get(
      &handle,
      Connected::new(&store, ()),
      &ThumbKey::new(media, 1),
    ))
    .expect("the read")
  };

  put("abc", 1);
  put("Abc", 2);

  // Each key reads back ITS OWN bytes: the second write did not land on the first file.
  assert_eq!(get("abc"), vec![1]);
  assert_eq!(get("Abc"), vec![2]);

  // And both exist at once, at two paths that are distinct under a case-INSENSITIVE comparison too.
  let lower = locate::<Thumbnail>(&store, &ThumbKey::new("abc", 1));
  let upper = locate::<Thumbnail>(&store, &ThumbKey::new("Abc", 1));
  assert!(lower.exists() && upper.exists());
  assert_ne!(
    lower.to_str().expect("utf-8").to_lowercase(),
    upper.to_str().expect("utf-8").to_lowercase()
  );

  // Two directories under the slot and no more — the lowercase one verbatim, the mixed-case one
  // escaped, which is the split that keeps them apart.
  assert_eq!(slot_entries(&dir), ["=ifrgg", "abc"]);
}

/// An adversarial set of text ids: EVERY one renders, none errors, and all render distinctly — even
/// after case folding, which is the comparison the target filesystem actually makes.
///
/// This is the totality claim stated as a test. A text id carries no restriction of any kind, so the
/// empty string, the two directory names, the device names, separators, unicode and a long value are
/// all legal ids and all must address a file.
#[test]
fn every_text_id_renders_and_none_collides() {
  let long = "x".repeat(300);
  let adversarial = [
    "",
    ".",
    "..",
    "...",
    ".hidden",
    "a.b",
    "a.",
    ".a",
    "1.2.3.4",
    "1.2.3.5",
    "255.255.255.255",
    "CON",
    "con",
    "NUL",
    "nul",
    "com1",
    "lpt9",
    "aux",
    "prn",
    "a/b",
    "a\\b",
    "a:b",
    "a\0b",
    "=already",
    "=",
    " ",
    "  ",
    "\n",
    "Ünïcødé",
    "日本語",
    "🎬",
    "Alice",
    "alice",
    "ALICE",
    "a-b_c",
    "-",
    "_",
    "0",
    &long,
  ];

  let mut folded = HashSet::new();
  for id in adversarial {
    let mut rendered = String::new();
    render_segment(id, &mut rendered);

    // It rendered — there is no error path to check, and that absence is the point.
    assert!(
      !rendered.is_empty(),
      "the id {id:?} rendered to an empty segment"
    );
    // Distinct under the filesystem's own comparison.
    assert!(
      folded.insert(rendered.to_lowercase()),
      "the id {id:?} collided at {rendered:?}"
    );
    // And every rendered segment is itself a safe single component.
    assert!(!rendered.contains('/'), "{id:?} rendered a separator");
    assert!(!rendered.contains('\\'), "{id:?} rendered a separator");
    assert!(!rendered.contains('\0'), "{id:?} rendered a NUL");
    assert!(rendered != "." && rendered != "..", "{id:?} rendered a dot");
  }
}

/// The pure-dot carve, which the `.` charset widening made necessary: `.` and `..` are now INSIDE
/// the verbatim charset and name the current and parent directory on every host, so they are carved
/// into the escaped set — escaped, never refused, because a text id of `..` is a legal id.
///
/// The neighbours are NOT carved: a dot anywhere else is an ordinary character, which is the whole
/// point of widening the charset.
#[test]
fn the_pure_dot_segments_escape_and_their_neighbours_do_not() {
  for dots in [".", ".."] {
    assert!(!is_verbatim(dots), "{dots:?} must not render verbatim");
    let mut rendered = String::new();
    render_segment(dots, &mut rendered);
    assert!(rendered.starts_with('='), "{dots:?} did not escape");
  }

  assert!(is_verbatim("..."));
  assert!(is_verbatim(".hidden"));
  assert!(is_verbatim("a.b"));
  assert!(is_verbatim("1.2.3.4"));
  assert!(is_verbatim("a."));
}

/// A text id that LOOKS like an address renders verbatim and is simply the text it is — there is no
/// tagging and none is needed, because a key field has ONE type and two members never share a
/// position.
#[test]
fn a_text_id_shaped_like_an_address_is_just_text() {
  let mut text = Segments::new();
  text.push(&"1.2.3.4".to_owned());
  let mut ip = Segments::new();
  ip.push(&core::net::Ipv4Addr::new(1, 2, 3, 4));

  // Identical renderings from different TYPES, which is legal precisely because a key position is
  // typed — and is why neither needs a discriminating prefix.
  assert_eq!(text.as_slice(), ip.as_slice());
  assert_eq!(text.as_slice(), ["1.2.3.4"]);
}

/// The network family's renderings, byte-exact, one per type — the examples the module doc carries.
#[test]
fn the_network_family_renders_verbatim() {
  use core::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};

  let v6 = Ipv6Addr::new(0x2001, 0x0db8, 0, 0, 0, 0, 0, 1);
  let mut segments = Segments::new();
  segments.push(&Ipv4Addr::new(1, 2, 3, 4));
  segments.push(&v6);
  segments.push(&IpAddr::V4(Ipv4Addr::new(255, 255, 255, 255)));
  segments.push(&IpAddr::V6(v6));
  segments.push(&SocketAddrV4::new(Ipv4Addr::new(1, 2, 3, 4), 8080));
  segments.push(&SocketAddrV6::new(v6, 8080, 0, 0));
  segments.push(&SocketAddrV6::new(v6, 8080, 7, 9));
  segments.push(&SocketAddr::V4(SocketAddrV4::new(
    Ipv4Addr::new(1, 2, 3, 4),
    80,
  )));

  assert_eq!(
    segments.as_slice(),
    [
      "1.2.3.4",
      // Fixed 32 lowercase hex — never `2001:db8::1`, whose colons are path-hostile and whose `::`
      // compression gives one address several spellings.
      "20010db8000000000000000000000001",
      "255.255.255.255",
      "20010db8000000000000000000000001",
      "1.2.3.4_8080",
      // `flowinfo` and `scope_id` render even at zero: both participate in `Eq`, so leaving them
      // out would let two unequal ids share a file.
      "20010db8000000000000000000000001_8080_0_0",
      "20010db8000000000000000000000001_8080_7_9",
      "1.2.3.4_80",
    ]
  );
  for rendered in segments.as_slice() {
    assert!(is_verbatim(rendered), "{rendered:?} should be verbatim");
  }
}

/// The two `SocketAddrV6` fields beyond the obvious pair are part of the ADDRESS, because they are
/// part of the identity: std calls these three values unequal, so they must not share a file.
#[test]
fn a_socket_v6_addresses_its_flowinfo_and_scope_id() {
  use core::net::{Ipv6Addr, SocketAddrV6};

  let ip = Ipv6Addr::LOCALHOST;
  let base = SocketAddrV6::new(ip, 80, 0, 0);
  let flow = SocketAddrV6::new(ip, 80, 1, 0);
  let scope = SocketAddrV6::new(ip, 80, 0, 1);

  // The premise, asserted rather than assumed: std says these are three distinct values.
  assert_ne!(base, flow);
  assert_ne!(base, scope);
  assert_ne!(flow, scope);

  let render = |addr: &SocketAddrV6| {
    let mut out = Segments::new();
    out.push(addr);
    out.as_slice()[0].clone()
  };
  let (b, f, s) = (render(&base), render(&flow), render(&scope));
  assert_ne!(b, f);
  assert_ne!(b, s);
  assert_ne!(f, s);
}

/// Pointer delegation means the SAME ADDRESS — the `NonZero` law extended. Pinned over one member of
/// each shape, because the law has to hold for the pointee's KIND and not merely for integers.
#[test]
fn a_pointer_addresses_what_its_pointee_does() {
  fn one<I: super::Segment>(id: &I) -> String {
    let mut out = Segments::new();
    out.push(id);
    out.as_slice()[0].clone()
  }

  // An integer, through all three pointer kinds.
  let bare = one(&9u64);
  assert_eq!(one(&std::sync::Arc::new(9u64)), bare);
  assert_eq!(one(&std::rc::Rc::new(9u64)), bare);
  assert_eq!(one(&Box::new(9u64)), bare);

  // A uuid.
  let uuid = uuid::Uuid::parse_str("67e55044-10b1-426f-9247-bb680e5fe0c8").expect("a uuid");
  assert_eq!(one(&std::sync::Arc::new(uuid)), one(&uuid));

  // Text — where the escape runs, so this also proves a pointer does not double-escape.
  let text = "Ünïcødé".to_owned();
  assert_eq!(one(&std::sync::Arc::new(text.clone())), one(&text));

  // And nested, since the inner pointer is itself a member.
  assert_eq!(one(&std::sync::Arc::new(Box::new(9u64))), bare);
}

/// A typed id addresses the file its BARE id does — the pointer-delegation law applied to the
/// wrapper that discriminates targets. What `TypedId` adds is a type-level fact, so it has to reach
/// no byte of a path: the whole address is compared, not merely the one segment that changed.
#[test]
fn a_typed_id_addresses_what_its_bare_id_does() {
  let (dir, store) = open_store();

  let bare = locate::<Thumbnail>(&store, &ThumbKey::new("clip_42", 12));
  let typed = locate::<TypedThumb>(&store, &TypedThumbKey::new("clip_42", 12));

  assert_eq!(typed, bare);
  assert_eq!(typed, dir.path().join("thumbnail/clip_42/12.png"));
}

/// And at the segment, over the member whose rendering is not the identity: a wrapped text id takes
/// the escape ONCE, so the delegation neither double-escapes nor lets the marker into the encoding.
#[test]
fn a_typed_text_id_escapes_exactly_as_its_bare_id_does() {
  struct Slug {
    id: TypedId<String, Slug>,
  }

  impl Identifiable for Slug {
    type Id = TypedId<String, Slug>;

    fn id_ref(&self) -> &Self::Id {
      &self.id
    }
  }

  fn one<I: super::Segment>(id: &I) -> String {
    let mut out = Segments::new();
    out.push(id);
    out.as_slice()[0].clone()
  }

  let text = "Ünïcødé".to_owned();
  assert_eq!(one(&TypedId::<String, Slug>::new(text.clone())), one(&text));
  assert!(one(&TypedId::<String, Slug>::new(text)).starts_with('='));
}

/// The reserved-device rule, measured rather than assumed: the UPPERCASE spellings escape because
/// they are outside the lowercase verbatim range, and the LOWERCASE ones escape because of the
/// carve. Both halves matter — without the carve, `con` would render verbatim and name a device.
#[test]
fn every_reserved_device_name_escapes_in_either_case() {
  for name in RESERVED {
    for spelling in [name.to_owned(), name.to_uppercase()] {
      assert!(
        !is_verbatim(&spelling),
        "{spelling:?} is a reserved device name and must not render verbatim"
      );
      let mut rendered = String::new();
      render_segment(&spelling, &mut rendered);
      assert!(rendered.starts_with('='), "{spelling:?} did not escape");
    }
  }
  // The neighbours are NOT carved — the rule names devices, not a prefix.
  assert!(is_verbatim("console"));
  assert!(is_verbatim("com10"));
  assert!(is_verbatim("com0"));
  assert!(is_verbatim("nullable"));
}

/// A RESERVED name on a real filesystem: `"con"` is a legal text id, it lands as a FILE, and it
/// coexists with the ordinary neighbour it is a prefix of. The carve exists so that no id is ever
/// refused, and this is that promise kept end to end rather than at the rendering — the id goes in,
/// the bytes come back, and on Windows the escaped name is a file where `con` would have been a
/// device in any directory.
#[test]
fn a_reserved_name_is_a_file_beside_an_ordinary_one() {
  let (dir, store) = open_store();
  let handle = LocalFsBlob::new(SLOT);
  let put = |media: &str, byte: u8| {
    block_on(handle.put(
      Connected::new(&store, ()),
      &Thumbnail {
        key: ThumbKey::new(media, 1),
        bytes: vec![byte],
      },
    ))
    .expect("the put")
  };
  let get = |media: &str| {
    block_on(AsyncBlobEngine::<Thumbnail>::get(
      &handle,
      Connected::new(&store, ()),
      &ThumbKey::new(media, 1),
    ))
    .expect("the read")
  };

  put("con", 1);
  put("console", 2);

  assert_eq!(get("con"), vec![1]);
  assert_eq!(get("console"), vec![2]);

  // The device name escaped and its non-device neighbour did not — the carve names devices, not a
  // prefix, and both are on disk at once.
  assert_eq!(slot_entries(&dir), ["=mnxw4", "console"]);
}

/// A stored blob reads back, and a second `put` at the same key REPLACES it — the keyed
/// last-write-wins the rename-over implements.
#[test]
fn a_put_reads_back_and_a_second_put_replaces_it() {
  let (_dir, store) = open_store();
  let handle = LocalFsBlob::new(SLOT);
  let read = || {
    block_on(AsyncBlobEngine::<Thumbnail>::get(
      &handle,
      Connected::new(&store, ()),
      &ThumbKey::new("clip", 3),
    ))
    .expect("the read")
  };

  block_on(handle.put(
    Connected::new(&store, ()),
    &Thumbnail {
      key: ThumbKey::new("clip", 3),
      bytes: vec![1, 2, 3],
    },
  ))
  .expect("the first put");
  assert_eq!(read(), vec![1, 2, 3]);

  block_on(handle.put(
    Connected::new(&store, ()),
    &Thumbnail {
      key: ThumbKey::new("clip", 3),
      bytes: vec![9],
    },
  ))
  .expect("the second put");
  assert_eq!(read(), vec![9]);
}

/// A publish leaves no staging residue: the key's directory holds the published file and nothing
/// else.
#[test]
fn a_publish_leaves_no_tmp_behind() {
  let (dir, store) = open_store();
  block_on(LocalFsBlob::new(SLOT).put(
    Connected::new(&store, ()),
    &Thumbnail {
      key: ThumbKey::new("clip", 1),
      bytes: vec![7],
    },
  ))
  .expect("the put");

  let entries: Vec<_> = std::fs::read_dir(dir.path().join("thumbnail/clip"))
    .expect("the key directory")
    .map(|entry| entry.expect("an entry").file_name())
    .collect();
  assert_eq!(entries, vec![std::ffi::OsString::from("1.png")]);
}

/// A text id that escapes round-trips through a real write and read, so the escape is the address on
/// disk and not only a rendering.
#[test]
fn an_escaped_text_id_round_trips_through_the_filesystem() {
  let (dir, store) = open_store();
  let handle = LocalFsBlob::new(SLOT);
  block_on(handle.put(
    Connected::new(&store, ()),
    &Thumbnail {
      key: ThumbKey::new("Ünïcødé", 1),
      bytes: vec![4, 2],
    },
  ))
  .expect("the put");

  assert_eq!(
    block_on(AsyncBlobEngine::<Thumbnail>::get(
      &handle,
      Connected::new(&store, ()),
      &ThumbKey::new("Ünïcødé", 1),
    ))
    .expect("the read"),
    vec![4, 2]
  );
  assert!(
    locate::<Thumbnail>(&store, &ThumbKey::new("Ünïcødé", 1))
      .strip_prefix(dir.path())
      .expect("under the root")
      .to_str()
      .expect("utf-8")
      .starts_with("thumbnail/=")
  );
}

/// A read of a key nothing was written at is a typed miss naming the resolved path, not an IO error
/// a caller has to interpret.
#[test]
fn a_missing_blob_is_a_typed_miss() {
  let (dir, store) = open_store();
  let err = block_on(AsyncBlobEngine::<Thumbnail>::get(
    &LocalFsBlob::new(SLOT),
    Connected::new(&store, ()),
    &ThumbKey::new("absent", 1),
  ))
  .expect_err("the miss");

  assert!(
    matches!(&err, LocalFsBlobError::Missing(path) if path == &dir.path().join("thumbnail/absent/1.png"))
  );
  assert!(err.to_string().starts_with("no blob stored at "));
}

/// The slot is the ONE refusal left on this path, and it is not an id: a slot names a directory this
/// backend owns, so it answers to the crate's identifier rule. The id in the same call is a text
/// value that escapes — legal, and not what fails.
#[test]
fn a_malformed_slot_is_refused_where_an_id_never_is() {
  let (_dir, store) = open_store();
  let err = AsyncLocate::<Thumbnail>::locate(
    &LocalFsBlob::new("../etc"),
    Connected::new(&store, ()),
    &ThumbKey::new("a/b", 1),
    Thumbnail::extension(),
  )
  .expect_err("the slot is refused");

  assert!(matches!(err, LocalFsBlobError::InvalidSlot(_)));
  assert!(err.to_string().contains("is not a valid slot"));
}

/// A key with NO fields addresses nothing — the one structural refusal left, and it is about the
/// key's SHAPE rather than about any value.
#[test]
fn a_key_with_no_fields_is_refused() {
  struct Empty;
  impl KeySegments for Empty {
    fn segments(&self, _out: &mut Segments) {}
  }

  struct Nothing;
  // A key with no columns has no last column either, so the id is the empty product too.
  impl Identifiable for Nothing {
    type Id = ();
    fn id_ref(&self) -> &() {
      &()
    }
  }
  // A key with no columns has neither half to name: nothing minted, no path — and nothing to filter
  // by either.
  impl Transformer for Nothing {
    type Key = Empty;
    type Lineage = ();
    type Record = Self;
    type Graphql = ();
    fn key(&self) -> Empty {
      Empty
    }
  }
  impl BlobRecord for Nothing {
    type Bytes = Vec<u8>;
    fn bytes(&self) -> &Vec<u8> {
      unreachable!("no address, so no write")
    }
  }

  let (_dir, store) = open_store();
  let err = AsyncLocate::<Nothing>::locate(
    &LocalFsBlob::new(SLOT),
    Connected::new(&store, ()),
    &Empty,
    None,
  )
  .expect_err("an empty key is refused");

  assert!(matches!(err, LocalFsBlobError::EmptyKey));
}

/// A rendered segment one byte past the per-component ceiling is refused BY NAME, carrying which
/// component, what it rendered to and what the ceiling is — never by the operating system, whose
/// `ENAMETOOLONG` names no key field and arrives only once a write has been attempted.
///
/// The boundary is pinned on both sides: a segment AT the ceiling addresses a file.
#[test]
fn a_segment_past_the_ceiling_is_refused_by_name() {
  let (_dir, store) = open_store();
  // Verbatim, so the rendered length IS the id's byte length and the boundary is unambiguous.
  let at = "a".repeat(MAX_SEGMENT_LEN);
  let over = "a".repeat(MAX_SEGMENT_LEN + 1);

  // The key's first segment is component 1: the slot this backend mints is component 0.
  let err = try_locate::<Thumbnail>(&store, SLOT, &ThumbKey::new(&over, 1)).expect_err("refused");
  let LocalFsBlobError::SegmentTooLong(refusal) = &err else {
    panic!("expected a SegmentTooLong, got {err:?}");
  };
  assert_eq!(refusal.position(), 1);
  assert_eq!(refusal.got(), MAX_SEGMENT_LEN + 1);
  assert_eq!(refusal.limit(), MAX_SEGMENT_LEN);
  assert!(
    err
      .to_string()
      .starts_with("component 1 of the blob address renders to 256 bytes")
  );

  // And one byte less resolves, so the refusal is the ceiling and not the length class.
  assert!(try_locate::<Thumbnail>(&store, SLOT, &ThumbKey::new(&at, 1)).is_ok());
}

/// The LEAF is measured with the record's extension on it, because the extension is part of the name
/// the filesystem holds: an id that fits ALONE and does not fit as a FILE is refused. The one case
/// where the rendered segment and the written component are different lengths.
#[test]
fn a_leaf_is_measured_with_its_extension() {
  let (_dir, store) = open_store();
  // `Slugged` writes `.png`, so a leaf costs four more bytes than it renders.
  let extension = ".png".len();
  let at = "b".repeat(MAX_SEGMENT_LEN - extension);
  let over = "b".repeat(MAX_SEGMENT_LEN - extension + 1);

  // The id itself is under the ceiling — it is the FILE NAME that is not.
  assert!(over.len() <= MAX_SEGMENT_LEN);
  let err = try_locate::<Slugged>(&store, SLOT, &SlugKey::new("clip", &over)).expect_err("refused");
  let LocalFsBlobError::SegmentTooLong(refusal) = &err else {
    panic!("expected a SegmentTooLong, got {err:?}");
  };
  assert_eq!(refusal.position(), 2);
  assert_eq!(refusal.got(), MAX_SEGMENT_LEN + 1);
  assert_eq!(refusal.limit(), MAX_SEGMENT_LEN);

  // The exact fit still addresses a file, extension included.
  let path = try_locate::<Slugged>(&store, SLOT, &SlugKey::new("clip", &at)).expect("resolves");
  assert_eq!(
    path
      .file_name()
      .expect("a file name")
      .to_str()
      .expect("utf-8")
      .len(),
    MAX_SEGMENT_LEN
  );
}

/// The SLOT is component 0 and answers to the same ceiling: it is a directory name this backend
/// mints, and its identifier rule is a CHARSET that says nothing about length.
#[test]
fn an_over_long_slot_is_the_zeroth_component() {
  let (_dir, store) = open_store();
  let slot = "s".repeat(MAX_SEGMENT_LEN + 1);

  // It passes the charset — this is a legal identifier, refused on length alone.
  assert!(crate::slot::is_identifier(slot.as_bytes()));
  let err = try_locate::<Thumbnail>(&store, &slot, &ThumbKey::new("clip", 1)).expect_err("refused");
  let LocalFsBlobError::SegmentTooLong(refusal) = &err else {
    panic!("expected a SegmentTooLong, got {err:?}");
  };
  assert_eq!(refusal.position(), 0);
}

/// The AGGREGATE ceiling, which only the WALK can see: every segment is comfortably under the
/// per-component ceiling and the whole address is over the path one. Refused by name, carrying the
/// address itself so a reader can see which of the root, the slot and the lineage is the long part.
#[test]
fn a_path_past_the_ceiling_is_refused_by_name() {
  let (_dir, store) = open_store();
  let level = "c".repeat(200);
  let deep = DeepKey(core::iter::repeat_n(level.clone(), 6).collect());

  // The premise: no single component is anywhere near its own ceiling.
  assert!(level.len() < MAX_SEGMENT_LEN);

  let err = try_locate::<Deep>(&store, SLOT, &deep).expect_err("refused");
  let LocalFsBlobError::PathTooLong(refusal) = &err else {
    panic!("expected a PathTooLong, got {err:?}");
  };
  assert_eq!(refusal.got(), refusal.path().as_os_str().len());
  assert!(refusal.got() > MAX_PATH_LEN);
  assert_eq!(refusal.limit(), MAX_PATH_LEN);
  assert!(err.to_string().ends_with("a portable path may take"));

  // A shallower lineage of the same segments resolves, so the refusal is the aggregate and nothing
  // about the segments themselves.
  assert!(try_locate::<Deep>(&store, SLOT, &DeepKey(vec![level; 2])).is_ok());
}

/// A refused address writes NOTHING: the length guards sit in the resolve, ahead of every filesystem
/// call, so a `put` that cannot address a file has not made half a directory tree either.
#[test]
fn a_length_refusal_reaches_the_put_before_any_io() {
  let (dir, store) = open_store();
  let err = block_on(LocalFsBlob::new(SLOT).put(
    Connected::new(&store, ()),
    &Thumbnail {
      key: ThumbKey::new(&"a".repeat(MAX_SEGMENT_LEN + 1), 1),
      bytes: vec![7],
    },
  ))
  .expect_err("refused");

  assert!(matches!(err, LocalFsBlobError::SegmentTooLong(_)));
  assert!(!dir.path().join(SLOT).exists());
}

/// Every non-text member of the vocabulary lands VERBATIM, which is what keeps the tree browsable
/// for the ids a product actually uses. Asserted through the sink, so the rendering under test is
/// the one an address goes through.
#[test]
fn every_non_text_member_renders_verbatim() {
  let uuid = uuid::Uuid::parse_str("67E55044-10B1-426F-9247-BB680E5FE0C8").expect("a uuid");
  let mut segments = Segments::new();
  segments.push(&7i64);
  segments.push(&-7i64);
  segments.push(&u64::MAX);
  segments.push(&core::num::NonZeroU64::new(9).expect("nonzero"));
  segments.push(&uuid);
  segments.push(&[0xde_u8, 0xad, 0xbe, 0xef]);

  assert_eq!(
    segments.as_slice(),
    [
      "7",
      "-7",
      "18446744073709551615",
      "9",
      // Canonical LOWERCASE, whatever case it was parsed from — the verbatim range is single-case.
      "67e55044-10b1-426f-9247-bb680e5fe0c8",
      "deadbeef",
    ]
  );
  for rendered in segments.as_slice() {
    assert!(is_verbatim(rendered), "{rendered:?} should be verbatim");
  }
}

/// A `NonZero` addresses the same file its integer member does — the transparency the vocabulary
/// promises, which for a STORED key has to mean an identical address.
#[test]
fn a_nonzero_addresses_what_its_integer_does() {
  let mut wrapped = Segments::new();
  wrapped.push(&core::num::NonZeroI32::new(-42).expect("nonzero"));
  let mut bare = Segments::new();
  bare.push(&-42i32);

  assert_eq!(wrapped.as_slice(), bare.as_slice());
}

/// A resolved path renders to its ADDRESS.
#[test]
fn a_resolved_path_renders_to_its_address() {
  let (dir, store) = open_store();
  let path = locate::<Thumbnail>(&store, &ThumbKey::new("clip", 1));

  assert_eq!(
    blob_address(&path).expect("a utf-8 address"),
    dir
      .path()
      .join("thumbnail/clip/1.png")
      .to_str()
      .expect("a utf-8 temp dir")
  );
}

/// The store's own LOCATION is the shipped citizen carrying that address — and it carries NEITHER
/// optional member, which is the zero-I/O pin read off the value rather than off a sentence.
#[test]
fn the_filesystem_location_is_the_address_and_nothing_it_would_have_to_stat_for() {
  let (dir, store) = open_store();
  let handle = LocalFsBlob::new("thumbnail");
  let path = locate::<Thumbnail>(&store, &ThumbKey::new("clip", 1));
  let location =
    AsyncLocate::<Thumbnail>::location(&handle, path).expect("the address renders to a location");

  assert_eq!(
    location.address(),
    dir
      .path()
      .join("thumbnail/clip/1.png")
      .to_str()
      .expect("a utf-8 temp dir")
  );
  assert_eq!(location.content_type(), None);
  assert_eq!(location.size(), None);
}

/// `locate` is a PURE render: it resolves an address for a key nothing was written at, and touches
/// the filesystem not at all.
#[test]
fn locate_resolves_without_an_existence_check() {
  let (dir, store) = open_store();

  assert_eq!(
    locate::<Thumbnail>(&store, &ThumbKey::new("never_written", 99)),
    dir.path().join("thumbnail/never_written/99.png")
  );
  assert!(!dir.path().join("thumbnail").exists());
}