gunk-dev/the-valley

snapshot.go

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