gunk-dev/the-valley

snapshot.go

sourcef703cb5df113main's published tip history
19.8 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 out, err := s.g.tool(s.ctx, s.verify.Attest, "digest", "--repo", s.repoDir(), "--rev", oid).Output()
434 d := ""
435 if scheme, value, ok := strings.Cut(strings.TrimSpace(string(out)), ":"); finished(err) == nil && ok && scheme == "valley-tree-v1" {
436 d = value
437 }
438 s.digestOf[oid] = d
439 return d, d != ""
440}
441
442// verified runs attest verify over a transfer statement: its signature
443// must be the integrator's, by a key the known-signers file holds, and
444// its subject must be the tree of the commit it says landed.
445func (s *Snapshot) verified(t transferStatement) bool {
446 if s.verify.Keys == "" || s.verify.Signer == "" {
447 s.unverified = true
448 return false
449 }
450 file, err := os.CreateTemp("", "valley-transfer-*.note")
451 if err != nil {
452 s.unverified = true
453 return false
454 }
455 defer os.Remove(file.Name())
456 _, err = file.Write(t.note)
457 if cerr := file.Close(); err != nil || cerr != nil {
458 s.unverified = true
459 return false
460 }
461 cmd := s.g.tool(s.ctx, s.verify.Attest, "verify", "--note", file.Name(),
462 "--known-keys", s.verify.Keys, "--signer", s.verify.Signer,
463 "--repo", s.repoDir(), "--rev", t.landed)
464 if err := finished(cmd.Run()); err != nil {
465 // attest refusing the note is an answer. Failing to run it is not.
466 var exit *exec.ExitError
467 if !errors.As(err, &exit) {
468 s.unverified = true
469 }
470 return false
471 }
472 return true
473}
474
475// Reach is every commit reachable from oid that main does not reach.
476func (s *Snapshot) Reach(oid string) map[string]bool {
477 if r, ok := s.reachOf[oid]; ok {
478 return r
479 }
480 args := []string{"rev-list", oid}
481 if s.Tip != "" {
482 args = append(args, "^"+s.Tip)
483 }
484 r := map[string]bool{}
485 if out, err := s.g.output(s.ctx, true, args...); err == nil {
486 for _, c := range strings.Fields(out) {
487 r[c] = true
488 }
489 }
490 s.reachOf[oid] = r
491 return r
492}
493
494// StrictAncestor reports whether a is an ancestor of b, and not b itself.
495// A commit main does not reach is an ancestor of b exactly when it is in
496// Reach(b), so git is asked only about a commit main reaches.
497func (s *Snapshot) StrictAncestor(a, b string) bool {
498 switch {
499 case a == b:
500 return false
501 case s.Reach(b)[a]:
502 return true
503 case s.Reaches(a):
504 return s.g.succeeds(s.ctx, true, "merge-base", "--is-ancestor", a, b)
505 }
506 return false
507}
508
509// BranchHead is a branch on origin and the commit at its tip.
510type BranchHead struct {
511 Branch, Head string
512}
513
514// Unrecorded is every branch on origin, other than main, whose tip main
515// does not reach and that is not the head of any change's active version,
516// in the order of their names.
517func (s *Snapshot) Unrecorded() []BranchHead {
518 active := map[string]bool{}
519 for _, n := range s.Changes {
520 active[HeadOf(n.Record.ActiveVersion())] = true
521 }
522 var branches []BranchHead
523 for ref, oid := range s.Refs {
524 name, ok := strings.CutPrefix(ref, "refs/heads/")
525 if !ok || name == Target || active[oid] || s.Reaches(oid) {
526 continue
527 }
528 branches = append(branches, BranchHead{Branch: name, Head: oid})
529 }
530 sort.Slice(branches, func(i, j int) bool { return branches[i].Branch < branches[j].Branch })
531 return branches
532}
533
534// Node is one head among those Nest stacks: a change's active head or a
535// branch's tip, with the commit time it is ordered by and the name ties
536// are broken by.
537type Node struct {
538 Name string
539 Head string
540 When int64
541}
542
543// Nesting is how a set of nodes stack, by ancestry alone. Each slice is
544// indexed as the nodes were given.
545type Nesting struct {
546 // Parent is the node each is nested under: the nearest node whose head
547 // strictly contains its own, or -1 for none. Where two are equally
548 // near, the one with the later commit is taken.
549 Parent []int
550 // Base is the nearest node whose head its own head strictly contains,
551 // or -1 for main. Where two are equally near, the one nested under it
552 // is taken, and otherwise the one with the later commit.
553 Base []int
554 // Inside is every node whose head strictly contains its own, in the
555 // order given.
556 Inside [][]int
557}
558
559// Nest stacks the nodes: valley pending nests its entries this way, and
560// a stack's layers each sit on their base.
561func (s *Snapshot) Nest(nodes []Node) Nesting {
562 n := len(nodes)
563 in := make([][]bool, n) // in[i][j]: node i's head strictly contains node j's
564 nest := Nesting{Parent: make([]int, n), Base: make([]int, n), Inside: make([][]int, n)}
565 for i := range nodes {
566 in[i] = make([]bool, n)
567 for j := range nodes {
568 in[i][j] = i != j && s.StrictAncestor(nodes[j].Head, nodes[i].Head)
569 if in[i][j] {
570 nest.Inside[j] = append(nest.Inside[j], i)
571 }
572 }
573 }
574 // nearest is the nodes i contains, or that contain i, with none
575 // between, the latest commit first.
576 nearest := func(i int, above bool) []int {
577 var near []int
578 for j := range nodes {
579 outer, inner := j, i
580 if !above {
581 outer, inner = i, j
582 }
583 if !in[outer][inner] {
584 continue
585 }
586 between := false
587 for k := range nodes {
588 between = between || in[outer][k] && in[k][inner]
589 }
590 if !between {
591 near = append(near, j)
592 }
593 }
594 sort.SliceStable(near, func(a, b int) bool {
595 x, y := nodes[near[a]], nodes[near[b]]
596 if x.When != y.When {
597 return x.When > y.When
598 }
599 return x.Name < y.Name
600 })
601 return near
602 }
603 for i := range nodes {
604 nest.Parent[i] = -1
605 if above := nearest(i, true); len(above) > 0 {
606 nest.Parent[i] = above[0]
607 }
608 }
609 for i := range nodes {
610 nest.Base[i] = -1
611 below := nearest(i, false)
612 for _, d := range below {
613 if nest.Parent[d] == i {
614 nest.Base[i] = d
615 break
616 }
617 }
618 if nest.Base[i] == -1 && len(below) > 0 {
619 nest.Base[i] = below[0]
620 }
621 }
622 return nest
623}