gunk-dev/the-valley

snapshot.go

sourced5649addb600main's published tip history
19.4 KiB
1// Every change a repository holds a record of, and how far each version
2// has landed.
3//
4// A snapshot is one read of origin: every branch, every record, every
5// integration request and outcome, and every attestation ref. From it, for
6// each version of each change, it decides the landing evidence the
7// version has. The first rule that applies is the answer:
8//
9// 1. landed: the version's head is on main's first-parent history, and
10// no commit on that history between the head and main's tip is a
11// merge. The integrator never writes a merge, and a fast-forward puts
12// every commit of a change on that history. A merge above the head
13// could have dropped the head's content, whichever parent the head is
14// reached through, so it leaves the head not landed by this rule.
15// 2. landed-recorded: a commit L on main's first-parent history, with one
16// parent, carries a transfer statement, signed by the integrator,
17// whose change is a request name of the version and whose base is
18// the valley-tree-v1 digest of the version's tree. The integrator
19// writes one when it lands a change (integrator/transfer.go). The
20// integrator's outcome record for that request name says land, at
21// this version's head: only the integrator writes outcome records,
22// and the record names the exact head it landed, which a statement
23// about trees does not. And the integrator's own merge of the head
24// onto L's parent gives L's tree.
25// 3. uncertain: a request for the version was consumed, or the outcome
26// record says the integrator failed on it, and neither of the above
27// holds. The integrator moves main before it stores its evidence
28// (integrator/refs.go), so a landing can exist without its evidence.
29// 4. not-landed: otherwise.
30//
31// The outcome record alone is never proof of a landing, because a later
32// pass can overwrite it. A record a later pass overwrote leaves a landing
33// uncertain, never landed-recorded.
34
35package rebase
36
37import (
38 "bytes"
39 "context"
40 "errors"
41 "fmt"
42 "os"
43 "os/exec"
44 "sort"
45 "strings"
46
47 "the-valley/change"
48)
49
50// The landing evidence a version can have.
51const (
52 Landed = "landed"
53 LandedRecorded = "landed-recorded"
54 LandingUncertain = "uncertain"
55 NotLanded = "not-landed"
56)
57
58const (
59 transferNote = "transfer.note"
60 predicateTransfer = "the-valley/integration/transfer/v1"
61)
62
63// Verifier is what a transfer statement is checked with: the verifier
64// keys of the identity registry's known-signers file, the name the
65// integrator signs under, and the attest helper that checks a note.
66// Without the first two, no transfer statement is believed, and a version
67// that only one could show landed reads as uncertain or not-landed.
68type Verifier struct {
69 Keys, Signer, Attest string
70}
71
72// transferStatement is one transfer statement found under an attestation
73// ref, with the values a landing is matched on, read before it is
74// verified.
75type transferStatement struct {
76 note []byte
77 change string // predicate.change: the request's change name
78 base string // predicate.base.valley-tree-v1: the tree the evidence was over
79 landed string // subject.digest.git-sha1: the commit that landed
80}
81
82// Snapshot is one read of a repository's origin. Its landing decisions,
83// and the ancestry it reads, are read from git when first asked for, under
84// the context the snapshot was made with, and kept.
85type Snapshot struct {
86 Origin
87 Tip string // main on origin; "" when origin has none
88 Changes []Recorded // every record that reads, in the order of their IDs
89 Unread []UnreadRecord // each record that does not read, which no reader shows
90
91 ctx context.Context
92 g Git
93 verify Verifier
94
95 outcomes map[string]Outcome // outcome ref → the record it holds
96 landings map[string][2]string // "<change ID> <n>" → landing and commit
97 firstParent map[string]bool // main's first-parent history, down to its first merge; nil until read
98 reachesOf map[string]bool
99 reachOf map[string]map[string]bool
100 digestOf map[string]string
101 transfers []transferStatement
102 read bool // whether transfers has been read
103
104 // unverified is set when a transfer statement named a version and
105 // could not be checked, so its landing may be stronger than shown.
106 unverified bool
107}
108
109// ReadSnapshot lists origin once and fetches every object the snapshot
110// reads: main, every branch tip, every record commit and every outcome
111// record. A record commit has its version heads as parents, so they come
112// with it.
113func ReadSnapshot(ctx context.Context, g Git, v Verifier) (*Snapshot, error) {
114 o, err := ListOrigin(ctx, g, InventoryPatterns...)
115 if err != nil {
116 return nil, err
117 }
118 var want []string
119 for ref, oid := range o.Refs {
120 if strings.HasPrefix(ref, "refs/heads/") || strings.HasPrefix(ref, OutcomePrefix) {
121 want = append(want, oid)
122 }
123 }
124 if err := Fetch(ctx, g, want...); err != nil {
125 return nil, err
126 }
127 all, unread, err := ReadAll(ctx, g, o)
128 if err != nil {
129 return nil, err
130 }
131 s := NewSnapshot(ctx, g, o, all, v)
132 s.Unread = unread
133 return s, nil
134}
135
136// NewSnapshot is a snapshot of what o lists, with every record in all
137// already read and every object it names already fetched.
138func NewSnapshot(ctx context.Context, g Git, o Origin, all []Recorded, v Verifier) *Snapshot {
139 s := &Snapshot{
140 Origin: o, Tip: o.Refs["refs/heads/"+Target], Changes: all,
141 ctx: ctx, g: g, verify: v,
142 outcomes: map[string]Outcome{}, landings: map[string][2]string{},
143 reachesOf: map[string]bool{}, reachOf: map[string]map[string]bool{}, digestOf: map[string]string{},
144 }
145 for ref, oid := range o.Refs {
146 if strings.HasPrefix(ref, OutcomePrefix) {
147 data, err := g.output(ctx, true, "cat-file", "blob", oid)
148 if err != nil {
149 data = ""
150 }
151 s.outcomes[ref] = ParseOutcome(data)
152 }
153 }
154 return s
155}
156
157// Unverified reports whether a transfer statement named a version and
158// could not be checked, so that version's landing may be stronger than
159// the snapshot says.
160func (s *Snapshot) Unverified() bool { return s.unverified }
161
162// OnMain reports whether a commit is on main's first-parent history (main
163// itself, its first parent, that commit's first parent, and so on) with no
164// merge between it and main's tip: whether
165// `git rev-list --first-parent --merges <oid>..main` would list nothing.
166// This is where a landing puts a change. The history is read down to its
167// first merge, which is itself the last commit counted, since no merge is
168// above it.
169func (s *Snapshot) OnMain(oid string) bool {
170 if s.Tip == "" || oid == "" {
171 return false
172 }
173 if s.firstParent == nil {
174 s.firstParent = map[string]bool{}
175 if out, err := s.g.output(s.ctx, true, "rev-list", "--first-parent", "--parents", s.Tip); err == nil {
176 for _, line := range strings.Split(out, "\n") {
177 fields := strings.Fields(line)
178 if len(fields) == 0 {
179 continue
180 }
181 s.firstParent[fields[0]] = true
182 if len(fields) > 2 {
183 break
184 }
185 }
186 }
187 }
188 return s.firstParent[oid]
189}
190
191// Reaches reports whether main reaches a commit by any path: whether the
192// commit is an ancestor of main, or main itself. That is ancestry, which
193// is not landing (OnMain).
194func (s *Snapshot) Reaches(oid string) bool {
195 if s.Tip == "" || oid == "" {
196 return false
197 }
198 r, seen := s.reachesOf[oid]
199 if !seen {
200 r = s.g.succeeds(s.ctx, true, "merge-base", "--is-ancestor", oid, s.Tip)
201 s.reachesOf[oid] = r
202 }
203 return r
204}
205
206// Request is the ref of the integration request origin holds for a
207// version: one filed under either of its names, at its head.
208func (s *Snapshot) Request(id string, v change.Version) (ref string, ok bool) {
209 for _, name := range RequestNames(id, v) {
210 if ref := RequestPrefix + name; s.Refs[ref] == HeadOf(v) {
211 return ref, true
212 }
213 }
214 return "", false
215}
216
217// Outcome is the integrator's last decision about a version: the outcome
218// record under either of its names whose head is the version's head.
219func (s *Snapshot) Outcome(id string, v change.Version) (name string, m Outcome, found bool) {
220 for _, name := range RequestNames(id, v) {
221 if m, ok := s.outcomes[OutcomePrefix+name]; ok && m.Head == HeadOf(v) {
222 return name, m, true
223 }
224 }
225 return "", Outcome{}, false
226}
227
228// Landing is the landing evidence a version has, and the commit on main it
229// landed as, when it has. Each version is decided once per snapshot.
230func (s *Snapshot) Landing(id string, v change.Version) (kind, commit string) {
231 key := fmt.Sprintf("%s %d", id, v.N)
232 if l, ok := s.landings[key]; ok {
233 return l[0], l[1]
234 }
235 kind, commit = s.decideLanding(id, v)
236 s.landings[key] = [2]string{kind, commit}
237 return kind, commit
238}
239
240func (s *Snapshot) decideLanding(id string, v change.Version) (kind, commit string) {
241 head := HeadOf(v)
242 if s.OnMain(head) {
243 return Landed, head
244 }
245 if commit, ok := s.recordedLanding(id, v); ok {
246 return LandedRecorded, commit
247 }
248 if name, m, ok := s.Outcome(id, v); ok {
249 consumed := m.Decision == "land" && s.Refs[RequestPrefix+name] != head
250 if consumed || m.Decision == "failed" {
251 return LandingUncertain, ""
252 }
253 }
254 return NotLanded, ""
255}
256
257// IsLanded reports whether a version has landed by the first two rules.
258func (s *Snapshot) IsLanded(id string, v change.Version) bool {
259 kind, _ := s.Landing(id, v)
260 return kind == Landed || kind == LandedRecorded
261}
262
263// Unlanded reports whether a change, in any state, has an active version
264// that has not landed: the changes a stack's layers are among.
265func (s *Snapshot) Unlanded(n Recorded) bool {
266 return !s.IsLanded(n.ID, n.Record.ActiveVersion())
267}
268
269// recordedLanding looks for a transfer statement that records the version
270// landing as a commit on main, and verifies the first that matches.
271func (s *Snapshot) recordedLanding(id string, v change.Version) (string, bool) {
272 names := map[string]bool{}
273 for _, n := range RequestNames(id, v) {
274 names[n] = true
275 }
276 head := HeadOf(v)
277 for _, t := range s.transferStatements() {
278 if !names[t.change] || !IsObjectID(t.landed) || !s.OnMain(t.landed) || !s.singleParent(t.landed) {
279 continue
280 }
281 if m, ok := s.outcomes[OutcomePrefix+t.change]; !ok || m.Decision != "land" || m.Head != head {
282 continue
283 }
284 digest, ok := s.digest(head)
285 if !ok {
286 s.unverified = true
287 continue
288 }
289 if t.base != digest || !s.mergesTo(head, t.landed) {
290 continue
291 }
292 if s.verified(t) {
293 return t.landed, true
294 }
295 }
296 return "", false
297}
298
299// singleParent reports whether a commit has exactly one parent, as every
300// commit the integrator lands as does.
301func (s *Snapshot) singleParent(oid string) bool {
302 out, err := s.g.output(s.ctx, true, "rev-list", "--parents", "-n", "1", oid)
303 return err == nil && len(strings.Fields(out)) == 2
304}
305
306// mergesTo reports whether the integrator's merge of head onto landed's
307// parent gives landed's tree. It is the merge integrator/git.go's
308// mergeDelta makes: merge-tree onto the tip, with the merge base of the
309// tip and the head as the base. A head that merges to another tree, or
310// not at all, is not what landed.
311func (s *Snapshot) mergesTo(head, landed string) bool {
312 tip, err := s.g.output(s.ctx, true, "rev-parse", "--verify", "--quiet", landed+"^1^{commit}")
313 if err != nil {
314 return false
315 }
316 want, err := s.g.output(s.ctx, true, "rev-parse", "--verify", "--quiet", landed+"^{tree}")
317 if err != nil {
318 return false
319 }
320 base, err := s.g.output(s.ctx, true, "merge-base", tip, head)
321 if err != nil {
322 return false
323 }
324 out, err := s.g.output(s.ctx, true, "merge-tree", "--write-tree", "--merge-base="+base, tip, head)
325 if err != nil {
326 return false
327 }
328 tree, _, _ := strings.Cut(out, "\n")
329 return strings.TrimSpace(tree) == want
330}
331
332// transferStatements reads every transfer statement under origin's
333// attestation refs, once. A transfer statement is the transfer.note at
334// the top of an attestation ref's tree. Anything unreadable is skipped:
335// what is not read is not believed.
336func (s *Snapshot) transferStatements() []transferStatement {
337 if s.read {
338 return s.transfers
339 }
340 s.read = true
341 var trees []string
342 for ref, oid := range s.Refs {
343 if strings.HasPrefix(ref, AttestationRefs) {
344 trees = append(trees, oid)
345 }
346 }
347 if len(trees) == 0 {
348 return nil
349 }
350 sort.Strings(trees)
351 if err := Fetch(s.ctx, s.g, trees...); err != nil {
352 s.unverified = true
353 return nil
354 }
355 var query bytes.Buffer
356 for _, tree := range trees {
357 fmt.Fprintf(&query, "%s:%s\n", tree, transferNote)
358 }
359 out, err := s.g.input(s.ctx, true, &query, "cat-file", "--batch-check=%(objectname) %(objecttype)")
360 if err != nil {
361 s.unverified = true
362 return nil
363 }
364 for _, line := range strings.Split(out, "\n") {
365 oid, kind, _ := strings.Cut(line, " ")
366 if kind != "blob" {
367 continue
368 }
369 note, err := s.g.output(s.ctx, true, "cat-file", "blob", oid)
370 if err != nil {
371 continue
372 }
373 note += "\n"
374 text, ok := noteText(note)
375 if !ok || statementValue(text, "predicateType") != predicateTransfer {
376 continue
377 }
378 s.transfers = append(s.transfers, transferStatement{
379 note: []byte(note),
380 change: statementValue(text, "predicate.change"),
381 base: statementValue(text, "predicate.base.valley-tree-v1"),
382 landed: statementValue(text, "subject.digest.git-sha1"),
383 })
384 }
385 return s.transfers
386}
387
388// noteText is the statement text of a note: everything before the last
389// blank line, which separates the text from its signatures.
390func noteText(note string) (string, bool) {
391 split := strings.LastIndex(note, "\n\n")
392 if split < 0 {
393 return "", false
394 }
395 return note[:split+1], true
396}
397
398// statementValue reads one key's value from statement text, where each
399// line is a key, one space and a value. It is a lookup, and it decides
400// nothing: what is read here only chooses which statement to verify.
401func statementValue(text, key string) string {
402 for _, line := range strings.Split(text, "\n") {
403 if k, v, ok := strings.Cut(line, " "); ok && k == key {
404 return v
405 }
406 }
407 return ""
408}
409
410// repoDir is the directory attest is pointed at.
411func (s *Snapshot) repoDir() string {
412 if s.g.Dir == "" {
413 return "."
414 }
415 return s.g.Dir
416}
417
418// digest is the valley-tree-v1 digest of a commit's tree, from attest,
419// which defines the scheme.
420func (s *Snapshot) digest(oid string) (string, bool) {
421 if d, ok := s.digestOf[oid]; ok {
422 return d, d != ""
423 }
424 cmd := exec.CommandContext(s.ctx, s.verify.Attest, "digest", "--repo", s.repoDir(), "--rev", oid)
425 cmd.Env = s.g.Env
426 out, err := cmd.Output()
427 d := ""
428 if scheme, value, ok := strings.Cut(strings.TrimSpace(string(out)), ":"); err == nil && ok && scheme == "valley-tree-v1" {
429 d = value
430 }
431 s.digestOf[oid] = d
432 return d, d != ""
433}
434
435// verified runs attest verify over a transfer statement: its signature
436// must be the integrator's, by a key the known-signers file holds, and
437// its subject must be the tree of the commit it says landed.
438func (s *Snapshot) verified(t transferStatement) bool {
439 if s.verify.Keys == "" || s.verify.Signer == "" {
440 s.unverified = true
441 return false
442 }
443 file, err := os.CreateTemp("", "valley-transfer-*.note")
444 if err != nil {
445 s.unverified = true
446 return false
447 }
448 defer os.Remove(file.Name())
449 _, err = file.Write(t.note)
450 if cerr := file.Close(); err != nil || cerr != nil {
451 s.unverified = true
452 return false
453 }
454 cmd := exec.CommandContext(s.ctx, s.verify.Attest, "verify", "--note", file.Name(),
455 "--known-keys", s.verify.Keys, "--signer", s.verify.Signer,
456 "--repo", s.repoDir(), "--rev", t.landed)
457 cmd.Env = s.g.Env
458 if err := cmd.Run(); err != nil {
459 // attest refusing the note is an answer. Failing to run it is not.
460 var exit *exec.ExitError
461 if !errors.As(err, &exit) {
462 s.unverified = true
463 }
464 return false
465 }
466 return true
467}
468
469// Reach is every commit reachable from oid that main does not reach.
470func (s *Snapshot) Reach(oid string) map[string]bool {
471 if r, ok := s.reachOf[oid]; ok {
472 return r
473 }
474 args := []string{"rev-list", oid}
475 if s.Tip != "" {
476 args = append(args, "^"+s.Tip)
477 }
478 r := map[string]bool{}
479 if out, err := s.g.output(s.ctx, true, args...); err == nil {
480 for _, c := range strings.Fields(out) {
481 r[c] = true
482 }
483 }
484 s.reachOf[oid] = r
485 return r
486}
487
488// StrictAncestor reports whether a is an ancestor of b, and not b itself.
489// A commit main does not reach is an ancestor of b exactly when it is in
490// Reach(b), so git is asked only about a commit main reaches.
491func (s *Snapshot) StrictAncestor(a, b string) bool {
492 switch {
493 case a == b:
494 return false
495 case s.Reach(b)[a]:
496 return true
497 case s.Reaches(a):
498 return s.g.succeeds(s.ctx, true, "merge-base", "--is-ancestor", a, b)
499 }
500 return false
501}
502
503// BranchHead is a branch on origin and the commit at its tip.
504type BranchHead struct {
505 Branch, Head string
506}
507
508// Unrecorded is every branch on origin, other than main, whose tip main
509// does not reach and that is not the head of any change's active version,
510// in the order of their names.
511func (s *Snapshot) Unrecorded() []BranchHead {
512 active := map[string]bool{}
513 for _, n := range s.Changes {
514 active[HeadOf(n.Record.ActiveVersion())] = true
515 }
516 var branches []BranchHead
517 for ref, oid := range s.Refs {
518 name, ok := strings.CutPrefix(ref, "refs/heads/")
519 if !ok || name == Target || active[oid] || s.Reaches(oid) {
520 continue
521 }
522 branches = append(branches, BranchHead{Branch: name, Head: oid})
523 }
524 sort.Slice(branches, func(i, j int) bool { return branches[i].Branch < branches[j].Branch })
525 return branches
526}
527
528// Node is one head among those Nest stacks: a change's active head or a
529// branch's tip, with the commit time it is ordered by and the name ties
530// are broken by.
531type Node struct {
532 Name string
533 Head string
534 When int64
535}
536
537// Nesting is how a set of nodes stack, by ancestry alone. Each slice is
538// indexed as the nodes were given.
539type Nesting struct {
540 // Parent is the node each is nested under: the nearest node whose head
541 // strictly contains its own, or -1 for none. Where two are equally
542 // near, the one with the later commit is taken.
543 Parent []int
544 // Base is the nearest node whose head its own head strictly contains,
545 // or -1 for main. Where two are equally near, the one nested under it
546 // is taken, and otherwise the one with the later commit.
547 Base []int
548 // Inside is every node whose head strictly contains its own, in the
549 // order given.
550 Inside [][]int
551}
552
553// Nest stacks the nodes: valley pending nests its entries this way, and
554// a stack's layers each sit on their base.
555func (s *Snapshot) Nest(nodes []Node) Nesting {
556 n := len(nodes)
557 in := make([][]bool, n) // in[i][j]: node i's head strictly contains node j's
558 nest := Nesting{Parent: make([]int, n), Base: make([]int, n), Inside: make([][]int, n)}
559 for i := range nodes {
560 in[i] = make([]bool, n)
561 for j := range nodes {
562 in[i][j] = i != j && s.StrictAncestor(nodes[j].Head, nodes[i].Head)
563 if in[i][j] {
564 nest.Inside[j] = append(nest.Inside[j], i)
565 }
566 }
567 }
568 // nearest is the nodes i contains, or that contain i, with none
569 // between, the latest commit first.
570 nearest := func(i int, above bool) []int {
571 var near []int
572 for j := range nodes {
573 outer, inner := j, i
574 if !above {
575 outer, inner = i, j
576 }
577 if !in[outer][inner] {
578 continue
579 }
580 between := false
581 for k := range nodes {
582 between = between || in[outer][k] && in[k][inner]
583 }
584 if !between {
585 near = append(near, j)
586 }
587 }
588 sort.SliceStable(near, func(a, b int) bool {
589 x, y := nodes[near[a]], nodes[near[b]]
590 if x.When != y.When {
591 return x.When > y.When
592 }
593 return x.Name < y.Name
594 })
595 return near
596 }
597 for i := range nodes {
598 nest.Parent[i] = -1
599 if above := nearest(i, true); len(above) > 0 {
600 nest.Parent[i] = above[0]
601 }
602 }
603 for i := range nodes {
604 nest.Base[i] = -1
605 below := nearest(i, false)
606 for _, d := range below {
607 if nest.Parent[d] == i {
608 nest.Base[i] = d
609 break
610 }
611 }
612 if nest.Base[i] == -1 && len(below) > 0 {
613 nest.Base[i] = below[0]
614 }
615 }
616 return nest
617}