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
//! Lineage identity and its lifecycle (§15.2, §15.4).
//!
//! The read half of branching shipped first, at 0.14.2 through 0.14.6: the
//! ledger tables carry a `branch_id`, [`crate::graph::TraversalBuilder::on_branch`]
//! resolves along the ancestry, and 0.14.6 bounded that resolution by the fork
//! point ([D-223]). Nothing in that half could *create* a lineage — only raw
//! SQL could, which is why 0.14.6 could repair the read's semantics without
//! breaking anyone. This module is the other half: the name, and the one write
//! that registers it.
//!
//! # Why the read shipped first, and why that ordering is not an accident
//!
//! A write that creates something unreadable is the worse order. Had `fork()`
//! landed at 0.14.2, every branch created between then and 0.14.6 would have
//! been readable only through a query that silently absorbed its parent's later
//! writes — and the repair would have been a semantic break on stored data
//! rather than a correction to an unreachable path. That is [D-160] → [D-174]'s
//! ordering, applied a third time and recorded in [D-223].
//!
//! [D-160]: ../../docs/architecture/s13-decision-register.md#d-160
//! [D-174]: ../../docs/architecture/s13-decision-register.md#d-174
//! [D-223]: ../../docs/architecture/s13-decision-register.md#d-223
use crate;
use crateddl;
/// Longest accepted lineage name.
///
/// A sanity bound rather than a schema limit — `branches.branch_id` is `TEXT`
/// and SQLite would take a megabyte. It is set well above every identifier
/// shape the motivating use case generates (a ULID is 26 characters, a
/// hyphenated UUID 36, a path-like `turn/17/alt/3` shorter still) and well
/// below anything that would make a `branches` listing unreadable.
pub const MAX_BRANCH_ID: usize = 128;
/// A validated lineage name.
///
/// # This is not [`ModelName`](crate::vector::ModelName)'s reason, and the rule
/// is deliberately different
///
/// `ModelName` exists because a model name is spliced into a table identifier
/// and SQLite cannot bind an identifier as a parameter, so the validation is
/// what makes the splice safe. **None of that applies here.** A `branch_id`
/// reaches SQL as a bound value at every one of its call sites; there is no
/// splice to protect. Copying `ModelName`'s `[a-z][a-z0-9_]*` rule would be
/// borrowing a justification that does not hold, and it would reject the two
/// name shapes the use case in §15.5 actually produces — a hyphenated UUID and
/// a path-like turn id.
///
/// What this type is for is narrower and has nothing to do with SQL:
///
/// * `branch_id` is a primary key that four ledger tables hold a foreign key
/// into, and `branches` is append-only under two unconditional triggers
/// ([`CREATE_BRANCHES_GUARD_UPDATE`](crate::schema::ddl::CREATE_BRANCHES_GUARD_UPDATE)).
/// A name is therefore written **once** and can never be corrected — not by
/// the crate, not by raw SQL. Validation has one chance, and this is it.
/// * A name that differs from the caller's intent by a trailing space is not a
/// typo, it is a **second lineage that reads as the first**. Every subsequent
/// `on_branch("release ")` resolves to a different ancestry than
/// `on_branch("release")`, both succeed, and neither reports anything. That
/// is the failure shape this wave keeps finding, and it is cheapest to refuse
/// at [D-034]'s boundary.
///
/// So the rule is: non-empty, at most [`MAX_BRANCH_ID`] bytes, no ASCII control
/// characters, and no leading or trailing whitespace. Refused rather than
/// trimmed, on §4.1's principle — a silent repair here becomes two lineages
/// sharing one intent later.
///
/// # `main` is constructible and not forkable
///
/// [`Database::branches`](crate::Database::branches) returns the trunk and
/// every read may name it, so `BranchId::new("main")` must succeed. What is
/// refused is *creating* it a second time, and that refusal belongs to
/// [`Database::fork`](crate::Database::fork) rather than to this type: the
/// trunk is a lineage like any other to a reader, and only a writer has cause
/// to care that it already exists.
///
/// [D-034]: ../../docs/architecture/s13-decision-register.md#d-034
;
/// So a `BranchId` can be handed straight to the 0.14.4 read surface.
///
/// [`TraversalBuilder::on_branch`](crate::graph::TraversalBuilder::on_branch)
/// and [`query_as_of_edges_on`](crate::temporal::query_as_of_edges_on) take
/// `impl Into<String>`, and they shipped two releases before this type existed.
/// This impl is what makes `on_branch(id)` compile rather than
/// `on_branch(id.as_str())` — additive, and cheaper than widening four
/// signatures that are already public.
/// One row of `branches`: a lineage, its parent, and where it was cut.
///
/// # `#[non_exhaustive]` costs nothing here, and that is a fact about direction
///
/// [`EdgeBelief`](crate::temporal::EdgeBelief) needed a constructor to go with
/// the attribute, because `save_snapshot` is public and *takes* one — without
/// `EdgeBelief::new` the attribute would not have made the next field additive,
/// it would have made a public function uncallable (0.14.5). This type only
/// ever travels outward: [`Database::branches`](crate::Database::branches)
/// returns it and nothing public accepts it. So the attribute buys the additive
/// field and takes nothing back, and no constructor is owed. §15.4's
/// abandonment arm is the field it is being kept open for.
/// One lineage's handle on the ledger (§15.4, 0.14.9, [D-226]).
///
/// A `Database` plus a [`BranchId`], so a caller who forked writes and reads
/// through the fork instead of naming it at every call. Every operation here
/// exists on [`Database`](crate::Database) already and takes a lineage there —
/// **this type buys ergonomics and no capability**, which is what makes it the
/// last piece of §15.4's first bullet rather than a fifth release of it.
///
/// ```no_run
/// # use std::sync::Arc;
/// # use macrame::graph::EdgeAssertion;
/// # use macrame::{Database, BranchId};
/// # async fn f(db: Arc<Database>) -> macrame::Result<()> {
/// let alt = db.fork(BranchId::new("turn/17/alt/1")?, BranchId::main()).await?;
/// let view = db.view(alt.id);
///
/// view.assert_edge(EdgeAssertion::new("a", "b", "CITES").valid_from(ts())).await?;
/// let seen = view.traversal("a").execute_ids(view.read_conn(), ts()).await?;
/// # Ok(())
/// # }
/// # fn ts() -> &'static str { "2020-01-01T00:00:00.000000Z" }
/// ```
///
/// # It holds an `Arc<Database>` and cannot close it
///
/// [`Database::close`](crate::Database::close) takes `self` by value, and an
/// `Arc` cannot give that up while any clone survives. So the borrow is
/// structural rather than a documented request: a caller who forks a view,
/// reads it and drops it is not one call away from stopping the actor everyone
/// else is using. That is why the view is a **separate type** over an
/// `Arc<Database>` and not a `Database` with a field added, and it is the same
/// argument [D-203] made when `Database: Clone` was declined — a handle that can
/// be cloned freely must not carry the right to end the thing it handles.
///
/// `Clone` is therefore free of that concern and is derived: the view owns no
/// lifecycle, so cloning it is cloning an `Arc` and a short string.
///
/// # What it does with an assertion that names a lineage
///
/// It stamps its own on one that names none, and **refuses** one that names a
/// different lineage with [`DbError::BranchMismatch`].
/// Stamping over is the shape a caller building through the view produces and
/// costs nothing; relabelling a write that already named somewhere else would
/// discard a belief rather than contradict it. See that variant for the failure
/// it catches.
///
/// [D-203]: ../../docs/architecture/s13-decision-register.md#d-203
/// [D-226]: ../../docs/architecture/s13-decision-register.md#d-226
/// Hand-written because [`Database`](crate::Database) is not `Debug` — it owns
/// a connection, a channel and a clock, none of which prints usefully. What a
/// reader of this type wants is which lineage against which file, so that is
/// what it prints.
/// Register a lineage, refusing the three things a `CHECK` cannot (§15.2).
///
/// Runs inside the write actor, so the three reads and the insert are one turn
/// against one connection and nothing can register a colliding name between the
/// check and the write.
///
/// # What the schema already refuses, and what is left over
///
/// `branches` carries a foreign key on `parent_id`, a primary key on
/// `branch_id`, and two row-local `CHECK`s. So a missing parent and a duplicate
/// name would both fail at the engine anyway — they are checked here to be
/// *named*, because `classify` would otherwise surface a duplicate fork as a
/// constraint violation naming a column, and the caller's question was about a
/// branch.
///
/// # The third refusal, and the invariant that turned out not to be checkable
///
/// [`CREATE_BRANCHES_TABLE`]'s comment left this to `fork()`: *"the fork point
/// is at or after the parent's creation" is not [row-local], and a `CHECK`
/// cannot see another row. The cross-row half is `fork()`'s to enforce at
/// D-034's boundary.* Enforcing it as written **refuses every fork on every
/// injected-clock database in the crate**, and the reason is not the clock the
/// test chose. `seed_root_branch` stamps `main.created_at` from
/// `SystemTime::now()` inside `migrations::run`, which runs *before* the
/// database's clock is resolved — the floor that clock is raised against is
/// read from tables the migration has to create first, so the order cannot
/// simply be swapped. **`branches.created_at` is therefore not on the ledger's
/// timeline**, and on a [`FakeClock`](crate::util::FakeClock) database it sits
/// years in the future of every row.
///
/// What *is* comparable is `forked_at`: every one of them is issued by this
/// function from the same clock as every `recorded_at`. So the check is against
/// the parent's fork point, and the trunk — whose `forked_at` is `NULL` because
/// it was cut from nothing — constrains nothing, which is right: as far as any
/// ledger row is concerned the trunk has always existed.
///
/// The narrower rule is also the one worth having. It makes fork points
/// **non-decreasing down any root path**, which is precisely the property
/// [`ancestry_cte`](crate::graph::lineage) clamps for defensively. The clamp
/// stays — `branches` accepts raw-SQL rows this function never saw — but for
/// rows the crate wrote it is now a belt beside braces rather than the only
/// thing holding the shape.
///
/// What it refuses is a fork point earlier than its parent's. That branch would
/// inherit **nothing whatever from the parent it names** — every row the parent
/// wrote is after the parent's own fork point, so all of them fall past the
/// child's cutoff — leaving a lineage whose `parent_id` says one thing and
/// whose visible history says another. A sibling wearing a child's parent
/// pointer, and silent about it.
///
/// [`CREATE_BRANCHES_TABLE`]: crate::schema::ddl::CREATE_BRANCHES_TABLE
pub async
/// One belief `a` holds that `b` does not (§15.4, 0.14.11, [D-228]).
///
/// Returned by [`Database::diff`](crate::Database::diff), one per edge key on
/// which the two lineages disagree, ordered by that key. The fields describe
/// **`a`'s** side; `b`'s side is `diff(b, a)`, which is the same question asked
/// the other way round.
///
/// # `branch_id` is the interesting field
///
/// It is the lineage on `a`'s ancestry that actually holds this row, and it is
/// what separates *what this exploration concluded* from *what it still holds
/// while the trunk moved on*. When it equals `a`, the divergence is `a`'s own
/// assertion. When it does not, `a` is retaining an ancestor's belief that `b`
/// no longer shares — which happens whenever `b` churned the key after `a`
/// forked, and is exactly the case that makes "the divergence is the set of
/// rows carrying the branch's own id" false. See [D-228] for the two shapes
/// that break it.
///
/// # No constructor, and no `Eq`
///
/// `#[non_exhaustive]` with nothing owed, for [`Branch`]'s reason: this type
/// only ever travels outward and nothing public accepts one, so the attribute
/// buys the additive field and takes nothing back.
///
/// `weight` is an `f64`, so `Eq`, `Ord` and `Hash` are not derivable. That is
/// a real difference from [`EdgeBelief`](crate::temporal::EdgeBelief), which
/// carries no weight and is compared as a canonical form by the snapshot
/// suite. Ordering here comes from the query instead, on the edge key, so two
/// diffs of the same pair are still directly comparable.
///
/// [D-228]: ../../docs/architecture/s13-decision-register.md#d-228
/// The beliefs `a` holds that `b` does not (§15.4, 0.14.11, [D-228]).
///
/// # What the plan expected, and the two shapes that break it
///
/// §15.4 says divergence "is exactly the set of rows carrying the branch's own
/// id", and that is true only when `b` is `a`'s parent **and has not churned
/// since the fork**. Two counterexamples, both ordinary:
///
/// * `b` retires or reweights an inherited edge after `a` forked. `a` still
/// sees the pre-fork version — that is the whole of
/// [D-223](../../docs/architecture/s13-decision-register.md#d-223) — so `a`
/// believes something `b` does not, and the row carries **`b`'s** id, or the
/// trunk's, never `a`'s.
/// * `a` and `b` are siblings and `b` shadow-retires an edge both inherited.
/// `a` believes it and `b` does not, and the row belongs to their common
/// ancestor.
///
/// A row-provenance answer misses both, and it also *adds* one it should not:
/// `a` re-asserting an inherited edge at the value it already had writes a row
/// on `a` and changes no belief. So the answer is a difference of the two
/// resolved views, which is what the reader already computes for one lineage
/// at a time, and the cheap characterisation is a special case rather than the
/// definition.
///
/// # Cost, and the narrowing that is recorded rather than built
///
/// This is O(ledger): `a`'s visible set is the whole ledger from `a`'s point of
/// view, so the join has to see all of it. The narrowing is real and known —
/// keys that both lineages resolve to the *same* lineage are identical by
/// construction and cannot differ, so only keys held on the symmetric
/// difference of the two ancestries can — but it is not built here, per F-33:
/// the shape is understood, the trigger is a branched workload large enough to
/// notice, and there is no measurement yet that says it is worth the second
/// query shape.
///
/// [D-228]: ../../docs/architecture/s13-decision-register.md#d-228
pub async
/// Every lineage the ledger knows about, trunk first, then by creation.
///
/// Read through the read connection rather than the actor: `branches` is
/// append-only, so a listing cannot be torn by a concurrent write in any way a
/// caller could act on — the worst a racing `fork` can do is not appear yet.
///
/// Ordered rather than left to the engine, and ordered by `created_at` rather
/// than by name, because the useful reading of this list is the shape of the
/// tree over time. The trunk is pinned first because it is the one row that is
/// always there and is nobody's child.
pub async