armdb 0.11.2

sharded bitcask key-value storage optimized for NVMe
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
//! T10 Task 1: the row, the owner and the namespace collection.
//!
//! Nothing writes to a unique namespace yet — a later T10 task adds claim
//! projection and transactional enforcement. This binary only exercises the
//! collection shape: it opens empty, reads are typed, the row/owner formats
//! are pinned, and owner decode is length- and collection-checked.
//!
//! `UserId` is scaffolding for later T10 tasks that extend this same file
//! (reservation/claim tests) — unused by Task 1's own tests, hence the
//! module-wide allow, mirroring `armdb/src/counter_tests.rs`'s shared T9
//! fixture.
#![allow(dead_code)]

use std::sync::Arc;

use armdb::armour::Db;
use armdb::{FixedConfig, UniqueIndex, UniqueOwner, unique_index};
use armour_core::Fuid;

armour_core::const_hasher_or!(user_id, "USR", "dev-key-user_id", brand = "user");
type UserId = Fuid<user_id::Hasher>;

#[derive(
    Clone,
    Copy,
    Debug,
    PartialEq,
    Eq,
    Hash,
    zerocopy::FromBytes,
    zerocopy::IntoBytes,
    zerocopy::Immutable,
    zerocopy::KnownLayout,
)]
#[repr(C)]
pub struct UsernameKey([u8; 24]);
armdb::impl_key_zerocopy!(
    UsernameKey,
    armour_core::KeyScheme::Typed(&[armour_core::KeyType::Array(24)])
);

impl UsernameKey {
    fn new(s: &str) -> Self {
        let mut b = [0u8; 24];
        b[..s.len()].copy_from_slice(s.as_bytes());
        Self(b)
    }
}

unique_index!(Usernames, key = UsernameKey, name = "usernames");

#[test]
fn namespace_opens_empty_and_reads_are_typed() {
    let dir = tempfile::tempdir().unwrap();
    let db = Arc::new(Db::open_test(dir.path()).unwrap());
    let ns = db
        .open_unique_index::<Usernames>(FixedConfig::test())
        .unwrap();

    assert_eq!(ns.name(), "usernames");
    assert!(ns.owner_of(&UsernameKey::new("rail")).is_none());
    assert!(!ns.contains(&UsernameKey::new("rail")));
}

#[test]
fn row_and_owner_are_format_stable() {
    assert_eq!(size_of::<armdb::UniqueRow>(), 80);
    // 56 bytes of owner key = seven 8-byte components, one more than the
    // widest key in the consumer (48 bytes).
    assert_eq!(armdb::UNIQUE_OWNER_KEY_CAP, 56);
}

// Trivial `CollectionMeta` impls used only to prove `belongs_to` rejects on
// each of its two independent branches — neither is ever opened as a real
// collection here. `belongs_to` first compares the collection tag (derived
// from `NAME`) and only then, if that matches, compares `key_len` against
// `size_of::<T::SelfId>()`. To pin each branch on its own, without one
// assertion that could pass for either reason, `UserOfEightBytes` gets two
// foils: one with a different `NAME` (isolates the tag branch) and one with
// the *same* `NAME` but a different key width (isolates the length branch).
#[derive(Clone, Debug, PartialEq, armour_core::GetType)]
struct UserOfEightBytes;

impl armdb::CollectionMeta for UserOfEightBytes {
    type SelfId = [u8; 8];
    const NAME: &'static str = "user_of_eight_bytes";
}

/// Different `NAME` (and hence a different tag) than `UserOfEightBytes` —
/// used to pin the tag-comparison branch of `belongs_to`.
#[derive(Clone, Debug, PartialEq, armour_core::GetType)]
struct OtherCollectionWithSixteenByteKey;

impl armdb::CollectionMeta for OtherCollectionWithSixteenByteKey {
    type SelfId = [u8; 16];
    const NAME: &'static str = "other_collection_with_sixteen_byte_key";
}

/// The *same* `NAME` as `UserOfEightBytes` (so the same tag) but a 16-byte
/// `SelfId` — used to pin the length-comparison branch of `belongs_to` in
/// isolation from the tag branch: with a matching tag, the only way
/// `belongs_to` can still reject is the `key_len` check, which is the one
/// thing standing between a corrupt or foreign row and `Key::from_bytes`'s
/// unsafe `ptr::read` in release builds (`Key::from_bytes` only
/// `debug_assert`s the length; see `armdb/src/key.rs`).
#[derive(Clone, Debug, PartialEq, armour_core::GetType)]
struct UserOfEightBytesWithASixteenByteKey;

impl armdb::CollectionMeta for UserOfEightBytesWithASixteenByteKey {
    type SelfId = [u8; 16];
    const NAME: &'static str = "user_of_eight_bytes";
}

#[test]
fn owner_decode_succeeds_for_its_own_collection() {
    let owner: UniqueOwner = armdb::testing::unique_owner_for::<UserOfEightBytes>(&[1u8; 8]);
    assert!(owner.belongs_to::<UserOfEightBytes>().is_some());
}

#[test]
fn owner_decode_rejects_a_foreign_collection_tag() {
    // Different `NAME`: rejected on the tag comparison, before `key_len` is
    // ever compared — `OtherCollectionWithSixteenByteKey`'s key width is
    // irrelevant here.
    let owner = armdb::testing::unique_owner_for::<UserOfEightBytes>(&[1u8; 8]);
    assert!(
        owner
            .belongs_to::<OtherCollectionWithSixteenByteKey>()
            .is_none()
    );
}

// -- Task 2: claim targets, sink and the private write seam -----------------

#[derive(
    Clone,
    Copy,
    Debug,
    PartialEq,
    Eq,
    Hash,
    zerocopy::FromBytes,
    zerocopy::IntoBytes,
    zerocopy::Immutable,
    zerocopy::KnownLayout,
)]
#[repr(C)]
pub struct EmailKey([u8; 32]);
armdb::impl_key_zerocopy!(
    EmailKey,
    armour_core::KeyScheme::Typed(&[armour_core::KeyType::Array(32)])
);

impl EmailKey {
    fn new(s: &str) -> Self {
        let mut b = [0u8; 32];
        b[..s.len()].copy_from_slice(s.as_bytes());
        Self(b)
    }
}

unique_index!(Emails, key = EmailKey, name = "emails");

/// Two open namespaces sharing one `Db` — `usernames` (declared as a claim
/// target below) and `emails` (deliberately left undeclared). Returns the
/// backing `TempDir` (T10 Task 5 review, F8-style cleanup: mirrors
/// `open_namespace` below rather than leaking it for the process lifetime).
fn open_two_namespaces() -> (
    tempfile::TempDir,
    Arc<Db>,
    Arc<UniqueIndex<Usernames>>,
    Arc<UniqueIndex<Emails>>,
) {
    let dir = tempfile::tempdir().unwrap();
    let db = Arc::new(Db::open_test(dir.path()).unwrap());
    let usernames = db
        .open_unique_index::<Usernames>(FixedConfig::test())
        .unwrap();
    let emails = db.open_unique_index::<Emails>(FixedConfig::test()).unwrap();
    (dir, db, usernames, emails)
}

#[test]
fn sink_rejects_an_undeclared_namespace_and_honours_the_budget() {
    let (_dir, _db, usernames, emails) = open_two_namespaces();

    let targets = armdb::UniqueTargets::new().with(&usernames);
    let mut sink =
        armdb::testing::claim_sink(&targets, /*max_rows*/ 2, /*max_bytes*/ 1024);

    // declared → ok
    sink.claim(&usernames, UsernameKey::new("a")).unwrap();
    // undeclared → error naming the namespace
    let err = sink.claim(&emails, EmailKey::new("b")).unwrap_err();
    assert!(matches!(
        err,
        armdb::DbError::UndeclaredUniqueTarget {
            namespace: "emails"
        }
    ));

    // budget: the third claim exceeds max_rows = 2
    sink.claim(&usernames, UsernameKey::new("c")).unwrap();
    let err = sink.claim(&usernames, UsernameKey::new("d")).unwrap_err();
    assert!(matches!(
        err,
        armdb::DbError::ProjectionBudgetExceeded { .. }
    ));
}

#[test]
fn owner_decode_rejects_a_key_length_mismatch() {
    // Same `NAME` (tag matches `UserOfEightBytes`'s own tag) but a wider
    // `SelfId`: a row whose owner key is 8 bytes must not decode as a
    // 16-byte key type, even when the collection tag matches.
    let owner = armdb::testing::unique_owner_for::<UserOfEightBytes>(&[1u8; 8]);
    assert!(
        owner
            .belongs_to::<UserOfEightBytesWithASixteenByteKey>()
            .is_none()
    );
}

// -- Task 3: the carrier's third half and the registry declaration ---------
//
// `SchemaRegistry`, `unique_index`, `and_unique`/`and_counters` composition —
// all gated behind `feature = "schema"` (a default feature; Tasks 1-2's tests
// above need only `typed-tree`, so this section is gated per-item rather than
// gating the whole file).

#[cfg(feature = "schema")]
use armdb::schema::{CollectionKind, SchemaRegistry};
#[cfg(feature = "schema")]
use armdb::{Config, CounterTargets, OnMissingTarget, RapiraCodec, TtlPolicy, Upsert};
#[cfg(feature = "schema")]
use armour_core::{GetRefs, GetType};
#[cfg(feature = "schema")]
use rapira::Rapira;

#[cfg(feature = "schema")]
#[derive(Clone, Debug, PartialEq, GetType, GetRefs, Rapira)]
struct User {
    username: Option<String>,
}
#[cfg(feature = "schema")]
impl armdb::CollectionMeta for User {
    type SelfId = UserId;
    const NAME: &'static str = "task3_users";
}

/// The T8 half's target — a real secondary index fed by `User` (review fix
/// F3: an opened-but-unwired `idx` proved nothing; the index target set must
/// genuinely be non-empty and the projection must genuinely emit a row).
/// Keyed by `UserId` itself, so the projection needs no byte conversion.
#[cfg(feature = "schema")]
#[derive(
    Clone,
    Copy,
    Debug,
    Default,
    PartialEq,
    GetType,
    GetRefs,
    zerocopy::FromBytes,
    zerocopy::IntoBytes,
    zerocopy::Immutable,
    zerocopy::KnownLayout,
)]
#[repr(C)]
struct UserTagMarker(pub u8);
#[cfg(feature = "schema")]
impl armdb::CollectionMeta for UserTagMarker {
    type SelfId = UserId;
    const NAME: &'static str = "task3_user_tags";
}

/// The T9 half's target.
#[cfg(feature = "schema")]
#[derive(Clone, Debug, PartialEq, GetType, GetRefs, Rapira)]
struct UserStats {
    active_count: u64,
}
#[cfg(feature = "schema")]
impl armdb::CollectionMeta for UserStats {
    type SelfId = [u8; 8];
    const NAME: &'static str = "task3_user_stats";
}
#[cfg(feature = "schema")]
type UserStatsMap = armdb::typed_map!(UserStats, RapiraCodec);

/// Review fix F7: the previous version leaked its `TempDir` (`mem::forget`)
/// once per call — four call sites, four leaked directories per test run.
/// Returning it keeps the directory alive for exactly as long as the caller
/// needs it and lets it clean up on drop like every other test in this file.
#[cfg(feature = "schema")]
fn open_namespace() -> (tempfile::TempDir, Arc<Db>, Arc<UniqueIndex<Usernames>>) {
    let dir = tempfile::tempdir().unwrap();
    let db = Arc::new(Db::open_test(dir.path()).unwrap());
    let usernames = db
        .open_unique_index::<Usernames>(FixedConfig::test())
        .unwrap();
    (dir, db, usernames)
}

#[cfg(feature = "schema")]
fn open_ordinary_index(db: &Arc<Db>) -> Arc<armdb::zero_tree!(UserTagMarker)> {
    db.open_zero_tree::<UserTagMarker, { size_of::<UserTagMarker>() }, _>(
        Config::test(),
        armdb::NoHook,
        &[],
    )
    .unwrap()
}

#[cfg(feature = "schema")]
fn open_counter_target(db: &Arc<Db>) -> Arc<UserStatsMap> {
    db.open_typed_map::<UserStats, RapiraCodec, _>(Config::test(), armdb::NoHook, &[])
        .unwrap()
}

#[cfg(feature = "schema")]
fn counter_targets(counters: &Arc<UserStatsMap>) -> CounterTargets {
    CounterTargets::new().with_counter(
        counters,
        "active_count",
        OnMissingTarget::Skip,
        |v: &UserStats| v.active_count,
        |cur: Option<&UserStats>, n: u64| match cur {
            Some(_) => Upsert::Put(UserStats { active_count: n }),
            None => Upsert::Keep,
        },
    )
}

/// Review fix F1/F2/F3: proves the **carrier itself** carries all three
/// halves (`hook.targets()`/`counter_targets()`/`claim_targets()`), not just
/// that `reg.decls` grew three entries — and does it with a genuinely
/// composed carrier built through `secondary_index` → `counted_on` →
/// `unique_index_on` (F2's composing forms), so the registry's `Decl`
/// closures and the carrier's actual write-path closures are the *same*
/// closures, not independently written ones nothing forces to agree.
#[cfg(feature = "schema")]
#[test]
fn a_source_declares_claims_and_the_carrier_carries_all_three_halves() {
    let (_dir, db, usernames) = open_namespace();
    let idx = open_ordinary_index(&db); // T8 half
    let counters = open_counter_target(&db); // T9 half

    let mut reg = SchemaRegistry::new();
    reg.register(&idx, CollectionKind::SecondaryIndex);
    // `UniqueIndex` deliberately implements no `SchemaCollection`/`Access`
    // seam — Tasks 5-9 validate a namespace by walking `ClaimTarget::scan_rows`
    // directly, not through this seam — so it registers as a graph-only
    // external node rather than through `reg.register`.
    reg.register_external(usernames.name(), CollectionKind::UniqueIndex);

    // T8: a *real* secondary-index declaration — non-empty `IndexTargets`,
    // and the projection genuinely emits a row into `idx`.
    let carrier = reg.secondary_index::<User, _>(
        armdb::IndexTargets::new().with_index(&idx),
        move |k: &UserId, _v: &User, sink| sink.row(&idx, *k, UserTagMarker(1)),
    );

    // T9: compose the counter half onto the *same* carrier. `counted_on`
    // records the `Decl::Counter` and attaches to `carrier` in one call, so
    // the registry and the write path can never disagree about which
    // closure runs (see F2's doc comment on `SchemaRegistry::counted_on`).
    let carrier = reg.counted_on(carrier, counter_targets(&counters), |_k, _v, _sink| Ok(()));

    // T10: compose the claim half onto the same carrier, the same way.
    let hook = reg.unique_index_on(
        carrier,
        armdb::UniqueTargets::new().with(&usernames),
        move |_k, v: &User, sink| {
            if let Some(u) = &v.username {
                sink.claim(&usernames, UsernameKey::new(u))?;
            }
            Ok(())
        },
    );

    // The carrier itself carries all three halves — not just the registry.
    assert_eq!(
        hook.targets().len(),
        1,
        "the index half is genuinely non-empty"
    );
    assert!(
        hook.counter_targets().is_some(),
        "the counter half survived composition onto the carrier"
    );
    assert!(
        hook.claim_targets().is_some(),
        "the claim half survived composition onto the carrier"
    );

    let users = db
        .open_typed_map::<User, RapiraCodec, _>(Config::test(), hook, &[])
        .unwrap();
    reg.register_entity(&users);

    // All three declarations survive composition in the registry too.
    let built = reg.finish().unwrap();
    assert_eq!(built.unique_decl_sources().len(), 1);
    assert_eq!(built.counted_decl_sources().len(), 1);
}

// -- Task 3: the three declaration-time rejections --------------------------
//
// `reject_unique_decl` mirrors `reject_index_decl`/`reject_counter_decl`
// (already covered by `secondary_index_rejects_*` /
// `schema_counted_declaration_rejects_a_cascade` in `schema/tests.rs`) almost
// verbatim; these pin the same three guards for `unique_index` specifically,
// plus that `register_owner_tag` does not spuriously reject the *same*
// source declaring into the *same* namespace twice (its actual collision
// behaviour is unit-tested directly against the private method in
// `armdb/src/schema/registry.rs`'s own `owner_tag_tests`, since a genuine
// FNV-1a collision between two collection names isn't constructible here).

#[cfg(feature = "schema")]
#[test]
#[should_panic(expected = "unique_index: UniqueTargets must declare at least one target")]
fn unique_index_rejects_empty_targets() {
    let mut reg = SchemaRegistry::new();
    let _ = reg.unique_index::<User, _>(armdb::UniqueTargets::new(), |_k, _v: &User, _sink| Ok(()));
}

/// T10 Task 5 review (F2): a claiming source must not declare a TTL — a
/// sweep runs outside any transaction, so an expiring row could vanish
/// without releasing its claim, permanently locking the name with no owner.
/// Same shape as T9's "a counter target with TTL is unsupported".
#[cfg(feature = "schema")]
#[derive(Clone, Debug, PartialEq, GetType, GetRefs, Rapira)]
struct UserWithTtl {
    username: Option<String>,
    expires_at_ms: u64,
}
#[cfg(feature = "schema")]
impl armdb::CollectionMeta for UserWithTtl {
    type SelfId = UserId;
    const NAME: &'static str = "task5_users_with_ttl";
    const TTL: Option<TtlPolicy<Self>> = Some(TtlPolicy {
        revision: 1,
        deadline: |row, _| (row.expires_at_ms > 0).then_some(row.expires_at_ms),
    });
}

#[cfg(feature = "schema")]
#[test]
#[should_panic(
    expected = "unique_index: a claiming source must not declare a TTL — a sweep runs outside any transaction, so an expiring row could not release its claim atomically"
)]
fn unique_index_rejects_a_ttl_carrying_source() {
    let (_dir, _db, usernames) = open_namespace();
    let mut reg = SchemaRegistry::new();
    let _ = reg.unique_index::<UserWithTtl, _>(
        armdb::UniqueTargets::new().with(&usernames),
        move |_k, v: &UserWithTtl, sink| {
            if let Some(u) = &v.username {
                sink.claim(&usernames, UsernameKey::new(u))?;
            }
            Ok(())
        },
    );
}

/// C1 (whole-branch review): `unique_index_on`'s `SV::TTL.is_none()` assert
/// is only *one* of two reachable declaration paths — `Projected::and_unique`,
/// `UniqueTargets` and `Db::open_unique_index` are all `pub`, so a carrier
/// assembled by hand (never touching `SchemaRegistry`) meets no assert at
/// all. This pins the second, independent guard: a managed open rejects a
/// claim-carrying hook on a TTL-declaring collection even when it was never
/// built through the registry.
#[cfg(feature = "schema")]
#[test]
fn open_managed_rejects_a_hand_assembled_ttl_carrying_claim_carrier() {
    let (_dir, db, usernames) = open_namespace();

    // Bypasses `SchemaRegistry::unique_index`/`unique_index_on` entirely —
    // exactly the shape those methods build internally, but constructed by
    // hand so the registry's `SV::TTL.is_none()` assert never runs.
    let hook = armdb::Projected::new(armdb::IndexTargets::new(), |_, _, _| Ok(())).and_unique(
        armdb::UniqueTargets::new().with(&usernames),
        move |_k, v: &UserWithTtl, sink| {
            if let Some(u) = &v.username {
                sink.claim(&usernames, UsernameKey::new(u))?;
            }
            Ok(())
        },
    );

    let result = db.open_typed_map::<UserWithTtl, RapiraCodec, _>(Config::test(), hook, &[]);
    let Err(err) = result else {
        panic!("a claim carrier on a TTL-declaring collection must be rejected at open");
    };
    assert!(
        matches!(
            err,
            armdb::DbError::ClaimingSourceHasTtl { collection } if collection == "task5_users_with_ttl"
        ),
        "expected ClaimingSourceHasTtl, got {err:?}"
    );
}

/// I6 (whole-branch review): a claim-carrying hook opened directly
/// (`TypedMap::open_hooked`, bypassing `Db::open_*`) is never
/// `bind_tx_arc`'d, so it can never join `db.tx()` — every claim-changing
/// write on it would be refused forever by `UniqueIndexRequiresTx`. Mirrors
/// `counter_carrier_rejects_a_direct_open` (`counter_tests.rs`) for the claim
/// half's own `ClaimsRequireManagedOpen` guard.
#[cfg(feature = "schema")]
#[test]
fn claim_carrier_rejects_a_direct_open() {
    let (_dir, _db, usernames) = open_namespace();
    let src_dir = tempfile::tempdir().unwrap();

    let hook = armdb::Projected::new(armdb::IndexTargets::new(), |_, _, _| Ok(())).and_unique(
        armdb::UniqueTargets::new().with(&usernames),
        move |_k, v: &User, sink| {
            if let Some(u) = &v.username {
                sink.claim(&usernames, UsernameKey::new(u))?;
            }
            Ok(())
        },
    );

    let err = armdb::TypedMap::<UserId, User, RapiraCodec, _>::open_hooked(
        src_dir.path(),
        Config::test(),
        RapiraCodec,
        hook,
    )
    .err()
    .expect("a claim carrier has nowhere to join db.tx() from a direct open");
    assert!(matches!(err, armdb::DbError::ClaimsRequireManagedOpen));
}

/// `Usernames` (the namespace type itself) also implements `CollectionMeta`
/// (via the `unique_index!` macro), so it can be named as a claim *source* —
/// declaring it as its own namespace must be rejected before anything opens.
#[cfg(feature = "schema")]
#[test]
#[should_panic(expected = "unique_index: namespace `usernames` must not equal source `usernames`")]
fn unique_index_rejects_a_source_as_its_own_namespace() {
    let (_dir, _db, usernames) = open_namespace();
    let mut reg = SchemaRegistry::new();
    let _ = reg.unique_index::<Usernames, _>(
        armdb::UniqueTargets::new().with(&usernames),
        |_k, _v: &Usernames, _sink| Ok(()),
    );
}

#[cfg(feature = "schema")]
#[test]
#[should_panic(
    expected = "unique_index: namespace `usernames` is already a projecting source (cascade forbidden)"
)]
fn unique_index_rejects_a_namespace_that_is_already_a_projecting_source() {
    let (_dir, db, usernames) = open_namespace();
    let idx = open_ordinary_index(&db);
    let mut reg = SchemaRegistry::new();
    // Make "usernames" a projecting source of an unrelated index first — no
    // open `Usernames`-keyed collection is needed to *declare* this, only the
    // static type.
    let _ = reg.secondary_index::<Usernames, _>(
        armdb::IndexTargets::new().with_index(&idx),
        |_k, _v: &Usernames, _sink| Ok(()),
    );
    let _ = reg.unique_index::<User, _>(
        armdb::UniqueTargets::new().with(&usernames),
        |_k, _v: &User, _sink| Ok(()),
    );
}

/// The owner-tag map is keyed by `(namespace, tag)`; declaring the *same*
/// source into the *same* namespace a second time is not a collision (see
/// `register_owner_tag`'s doc comment) — only a *different* source name
/// hashing to the same tag would panic, which is not constructible from a
/// test without an actual FNV-1a collision (see `owner_tag_tests` in
/// `armdb/src/schema/registry.rs` for that behaviour, tested directly).
#[cfg(feature = "schema")]
#[test]
fn unique_index_allows_the_same_source_into_the_same_namespace_twice() {
    let (_dir, _db, usernames) = open_namespace();
    let mut reg = SchemaRegistry::new();
    let _h1 = reg.unique_index::<User, _>(
        armdb::UniqueTargets::new().with(&usernames),
        |_k, _v: &User, _sink| Ok(()),
    );
    let _h2 = reg.unique_index::<User, _>(
        armdb::UniqueTargets::new().with(&usernames),
        |_k, _v: &User, _sink| Ok(()),
    );
}

/// M1 (whole-branch review): `Projected::and_unique` called twice on the
/// *same* carrier used to silently keep only the second closure while the
/// first namespace it named was left with no source that would ever release
/// it — `unique_index_allows_the_same_source_into_the_same_namespace_twice`
/// above is the *legal* twin (two independent, freshly built carriers, same
/// namespace); this is the illegal one (one carrier, two namespaces).
#[cfg(feature = "schema")]
#[test]
#[should_panic(expected = "and_unique: a claim half is already attached to this carrier")]
fn and_unique_panics_when_called_twice_on_one_carrier() {
    let (_dir, _db, usernames, emails) = open_two_namespaces();
    let _ = armdb::Projected::<UserId, User>::new(armdb::IndexTargets::new(), |_, _, _| Ok(()))
        .and_unique(
            armdb::UniqueTargets::new().with(&usernames),
            |_k, _v: &User, _sink| Ok(()),
        )
        .and_unique(
            armdb::UniqueTargets::new().with(&emails),
            |_k, _v: &User, _sink| Ok(()),
        );
}

/// Same bug, reached through the registry's composing form instead of the
/// carrier directly: `unique_index` then `unique_index_on` on one source
/// threads the *same* carrier through `and_unique` twice, so `finish()` would
/// otherwise carry two live `Decl::Unique` entries while only the second
/// call's closure ever runs on the write path — the second namespace's
/// `repair` would happily write claims nothing releases.
#[cfg(feature = "schema")]
#[test]
#[should_panic(expected = "and_unique: a claim half is already attached to this carrier")]
fn unique_index_on_rejects_a_second_claim_declaration_for_one_source() {
    let (_dir, _db, usernames, emails) = open_two_namespaces();
    let mut reg = SchemaRegistry::new();
    let hook = reg.unique_index::<User, _>(
        armdb::UniqueTargets::new().with(&usernames),
        |_k, _v: &User, _sink| Ok(()),
    );
    let _ = reg.unique_index_on(
        hook,
        armdb::UniqueTargets::new().with(&emails),
        |_k, _v: &User, _sink| Ok(()),
    );
}