gunk-dev/the-valley

snapshot.go

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