gunk-dev/the-valley

snapshot.go

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