gunk-dev/the-valley

snapshot.go

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