gunk-dev/the-valley

snapshot.go

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