gunk-dev/the-valley

inventory.go

source09393407add1main's published tip history
18.0 KiB
1// Every change a repository holds a record of, and how far each version
2// has landed.
3//
4// changes and pending read one snapshot of origin for each repository
5// they list: every branch, every record, every integration request and
6// outcome, and every attestation ref. From it they decide, for each
7// version of each change, the landing evidence it has. The first rule
8// that applies is the 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 main
37
38import (
39 "bytes"
40 "errors"
41 "fmt"
42 "os"
43 "os/exec"
44 "sort"
45 "strings"
46
47 "the-valley/change"
48)
49
50// The landing evidence a version can have.
51const (
52 landed = "landed"
53 landedRecorded = "landed-recorded"
54 uncertain = "uncertain"
55 notLanded = "not-landed"
56)
57
58const (
59 transferNote = "transfer.note"
60 predicateTransfer = "the-valley/integration/transfer/v1"
61)
62
63// inventoryPatterns are the ls-remote patterns of every ref a snapshot
64// reads.
65var inventoryPatterns = []string{
66 "refs/heads/*",
67 change.RefPrefix + recordTarget + "/*",
68 requestPrefix + "*",
69 outcomePrefix + "*",
70 attestationRefs + "*",
71}
72
73// verifier is what a transfer statement is checked with: the verifier
74// keys of the identity registry's known-signers file, the name the
75// integrator signs under, and the attest helper that checks a note.
76// VALLEY_KNOWN_SIGNERS and VALLEY_INTEGRATOR_SIGNER name the first two.
77// Without both, no transfer statement is believed, and a version that
78// only one could show landed reads as uncertain or not-landed.
79type verifier struct {
80 keys, signer, attest string
81}
82
83// verifierHint says what a transfer statement is verified with, for a
84// command that could not verify one.
85const verifierHint = "Set VALLEY_KNOWN_SIGNERS to the known-signers file and VALLEY_INTEGRATOR_SIGNER to the integrator's signing name, with attest on PATH"
86
87func verifierFromEnv() verifier {
88 return verifier{
89 keys: os.Getenv("VALLEY_KNOWN_SIGNERS"),
90 signer: os.Getenv("VALLEY_INTEGRATOR_SIGNER"),
91 attest: "attest",
92 }
93}
94
95// transferStatement is one transfer statement found under an attestation
96// ref, with the values a landing is matched on, read before it is
97// verified.
98type transferStatement struct {
99 note []byte
100 change string // predicate.change: the request's change name
101 base string // predicate.base.valley-tree-v1: the tree the evidence was over
102 landed string // subject.digest.git-sha1: the commit that landed
103}
104
105// snapshot is one read of a repository's origin.
106type snapshot struct {
107 g git
108 o origin
109 tip string // main on origin; "" when origin has none
110 all []recorded
111 verify verifier
112
113 outcomes map[string]memo // outcome ref → the record it holds
114 landings map[string][2]string // "<change ID> <n>" → landing and commit
115 firstParent map[string]bool // main's first-parent history, down to its first merge; nil until read
116 reachesOf map[string]bool
117 reachOf map[string]map[string]bool
118 digestOf map[string]string
119 transfers []transferStatement
120 read bool // whether transfers has been read
121
122 // unverified is set when a transfer statement named a version and
123 // could not be checked, so its landing may be stronger than shown.
124 unverified bool
125}
126
127// readSnapshot lists origin once and fetches every object the snapshot
128// reads: main, every branch tip, every record commit and every outcome
129// record. A record commit has its version heads as parents, so they come
130// with it.
131func readSnapshot(g git, v verifier) (*snapshot, error) {
132 o, err := listOrigin(g, inventoryPatterns...)
133 if err != nil {
134 return nil, err
135 }
136 var want []string
137 for ref, oid := range o.refs {
138 if strings.HasPrefix(ref, "refs/heads/") || strings.HasPrefix(ref, outcomePrefix) {
139 want = append(want, oid)
140 }
141 }
142 if err := fetch(g, want...); err != nil {
143 return nil, err
144 }
145 all, err := readAll(g, o)
146 if err != nil {
147 return nil, err
148 }
149 return newSnapshot(g, o, all, v), 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(g git, o origin, all []recorded, v verifier) *snapshot {
155 s := &snapshot{
156 g: g, o: o, tip: o.refs["refs/heads/"+recordTarget], all: all, verify: v,
157 outcomes: map[string]memo{}, landings: map[string][2]string{},
158 reachesOf: map[string]bool{}, reachOf: map[string]map[string]bool{}, digestOf: map[string]string{},
159 }
160 for ref, oid := range o.refs {
161 if strings.HasPrefix(ref, outcomePrefix) {
162 data, err := g.output(true, "cat-file", "blob", oid)
163 if err != nil {
164 data = ""
165 }
166 s.outcomes[ref] = parseMemo(data)
167 }
168 }
169 return s
170}
171
172// headOf is a version's head as an object ID.
173func headOf(v change.Version) string {
174 return strings.TrimPrefix(v.Head, change.HeadPrefix)
175}
176
177// onMain reports whether a commit is on main's first-parent history (main
178// itself, its first parent, that commit's first parent, and so on) with no
179// merge between it and main's tip: whether
180// `git rev-list --first-parent --merges <oid>..main` would list nothing.
181// This is where a landing puts a change. The history is read down to its
182// first merge, which is itself the last commit counted, since no merge is
183// above it.
184func (s *snapshot) onMain(oid string) bool {
185 if s.tip == "" || oid == "" {
186 return false
187 }
188 if s.firstParent == nil {
189 s.firstParent = map[string]bool{}
190 if out, err := s.g.output(true, "rev-list", "--first-parent", "--parents", s.tip); err == nil {
191 for _, line := range strings.Split(out, "\n") {
192 fields := strings.Fields(line)
193 if len(fields) == 0 {
194 continue
195 }
196 s.firstParent[fields[0]] = true
197 if len(fields) > 2 {
198 break
199 }
200 }
201 }
202 }
203 return s.firstParent[oid]
204}
205
206// reaches reports whether main reaches a commit by any path: whether the
207// commit is an ancestor of main, or main itself. That is ancestry, which
208// is not landing (onMain).
209func (s *snapshot) reaches(oid string) bool {
210 if s.tip == "" || oid == "" {
211 return false
212 }
213 r, seen := s.reachesOf[oid]
214 if !seen {
215 r = s.g.succeeds(true, "merge-base", "--is-ancestor", oid, s.tip)
216 s.reachesOf[oid] = r
217 }
218 return r
219}
220
221// requestNames are the names a request for a version is filed under: its
222// branch, the way approve names one, and c-<change ID>.
223func requestNames(id string, v change.Version) []string {
224 var names []string
225 if v.Branch != "" {
226 names = append(names, changeName(v.Branch))
227 }
228 return append(names, "c-"+id)
229}
230
231// request is the integration request origin holds for a version: one
232// filed under either of its names, at its head.
233func (s *snapshot) request(id string, v change.Version) *jsonRequest {
234 for _, name := range requestNames(id, v) {
235 if ref := requestPrefix + name; s.o.refs[ref] == headOf(v) {
236 return &jsonRequest{Ref: ref, Commit: headOf(v)}
237 }
238 }
239 return nil
240}
241
242// outcome is the integrator's last decision about a version: the outcome
243// record under either of its names whose head is the version's head.
244func (s *snapshot) outcome(id string, v change.Version) (name string, m memo, found bool) {
245 for _, name := range requestNames(id, v) {
246 if m, ok := s.outcomes[outcomePrefix+name]; ok && m.head == headOf(v) {
247 return name, m, true
248 }
249 }
250 return "", memo{}, false
251}
252
253// landing is the landing evidence a version has, and the commit on main it
254// landed as, when it has. Each version is decided once per snapshot.
255func (s *snapshot) landing(id string, v change.Version) (kind, commit string) {
256 key := fmt.Sprintf("%s %d", id, v.N)
257 if l, ok := s.landings[key]; ok {
258 return l[0], l[1]
259 }
260 kind, commit = s.decideLanding(id, v)
261 s.landings[key] = [2]string{kind, commit}
262 return kind, commit
263}
264
265func (s *snapshot) decideLanding(id string, v change.Version) (kind, commit string) {
266 head := headOf(v)
267 if s.onMain(head) {
268 return landed, head
269 }
270 if commit, ok := s.recordedLanding(id, v); ok {
271 return landedRecorded, commit
272 }
273 if name, m, ok := s.outcome(id, v); ok {
274 consumed := m.decision == "land" && s.o.refs[requestPrefix+name] != head
275 if consumed || m.decision == "failed" {
276 return uncertain, ""
277 }
278 }
279 return notLanded, ""
280}
281
282// isLanded reports whether a version has landed by the first two rules.
283func (s *snapshot) isLanded(id string, v change.Version) bool {
284 kind, _ := s.landing(id, v)
285 return kind == landed || kind == landedRecorded
286}
287
288// recordedLanding looks for a transfer statement that records the version
289// landing as a commit on main, and verifies the first that matches.
290func (s *snapshot) recordedLanding(id string, v change.Version) (string, bool) {
291 names := map[string]bool{}
292 for _, n := range requestNames(id, v) {
293 names[n] = true
294 }
295 head := headOf(v)
296 for _, t := range s.transferStatements() {
297 if !names[t.change] || !isObjectID(t.landed) || !s.onMain(t.landed) || !s.singleParent(t.landed) {
298 continue
299 }
300 if m, ok := s.outcomes[outcomePrefix+t.change]; !ok || m.decision != "land" || m.head != head {
301 continue
302 }
303 digest, ok := s.digest(headOf(v))
304 if !ok {
305 s.unverified = true
306 continue
307 }
308 if t.base != digest || !s.mergesTo(headOf(v), t.landed) {
309 continue
310 }
311 if s.verified(t) {
312 return t.landed, true
313 }
314 }
315 return "", false
316}
317
318// singleParent reports whether a commit has exactly one parent, as every
319// commit the integrator lands as does.
320func (s *snapshot) singleParent(oid string) bool {
321 out, err := s.g.output(true, "rev-list", "--parents", "-n", "1", oid)
322 return err == nil && len(strings.Fields(out)) == 2
323}
324
325// mergesTo reports whether the integrator's merge of head onto landed's
326// parent gives landed's tree. It is the merge integrator/git.go's
327// mergeDelta makes: merge-tree onto the tip, with the merge base of the
328// tip and the head as the base. A head that merges to another tree, or
329// not at all, is not what landed.
330func (s *snapshot) mergesTo(head, landed string) bool {
331 tip, err := s.g.output(true, "rev-parse", "--verify", "--quiet", landed+"^1^{commit}")
332 if err != nil {
333 return false
334 }
335 want, err := s.g.output(true, "rev-parse", "--verify", "--quiet", landed+"^{tree}")
336 if err != nil {
337 return false
338 }
339 base, err := s.g.output(true, "merge-base", tip, head)
340 if err != nil {
341 return false
342 }
343 out, err := s.g.output(true, "merge-tree", "--write-tree", "--merge-base="+base, tip, head)
344 if err != nil {
345 return false
346 }
347 tree, _, _ := strings.Cut(out, "\n")
348 return strings.TrimSpace(tree) == want
349}
350
351// transferStatements reads every transfer statement under origin's
352// attestation refs, once. A transfer statement is the transfer.note at
353// the top of an attestation ref's tree. Anything unreadable is skipped:
354// what is not read is not believed.
355func (s *snapshot) transferStatements() []transferStatement {
356 if s.read {
357 return s.transfers
358 }
359 s.read = true
360 var trees []string
361 for ref, oid := range s.o.refs {
362 if strings.HasPrefix(ref, attestationRefs) {
363 trees = append(trees, oid)
364 }
365 }
366 if len(trees) == 0 {
367 return nil
368 }
369 sort.Strings(trees)
370 if err := fetch(s.g, trees...); err != nil {
371 s.unverified = true
372 return nil
373 }
374 var query bytes.Buffer
375 for _, tree := range trees {
376 fmt.Fprintf(&query, "%s:%s\n", tree, transferNote)
377 }
378 out, err := s.g.input(true, &query, "cat-file", "--batch-check=%(objectname) %(objecttype)")
379 if err != nil {
380 s.unverified = true
381 return nil
382 }
383 for _, line := range strings.Split(out, "\n") {
384 oid, kind, _ := strings.Cut(line, " ")
385 if kind != "blob" {
386 continue
387 }
388 note, err := s.g.output(true, "cat-file", "blob", oid)
389 if err != nil {
390 continue
391 }
392 note += "\n"
393 text, ok := noteText(note)
394 if !ok || statementValue(text, "predicateType") != predicateTransfer {
395 continue
396 }
397 s.transfers = append(s.transfers, transferStatement{
398 note: []byte(note),
399 change: statementValue(text, "predicate.change"),
400 base: statementValue(text, "predicate.base.valley-tree-v1"),
401 landed: statementValue(text, "subject.digest.git-sha1"),
402 })
403 }
404 return s.transfers
405}
406
407// noteText is the statement text of a note: everything before the last
408// blank line, which separates the text from its signatures.
409func noteText(note string) (string, bool) {
410 split := strings.LastIndex(note, "\n\n")
411 if split < 0 {
412 return "", false
413 }
414 return note[:split+1], true
415}
416
417// statementValue reads one key's value from statement text, where each
418// line is a key, one space and a value. It is a lookup, and it decides
419// nothing: what is read here only chooses which statement to verify.
420func statementValue(text, key string) string {
421 for _, line := range strings.Split(text, "\n") {
422 if k, v, ok := strings.Cut(line, " "); ok && k == key {
423 return v
424 }
425 }
426 return ""
427}
428
429// repoDir is the directory attest is pointed at.
430func (s *snapshot) repoDir() string {
431 if s.g.dir == "" {
432 return "."
433 }
434 return s.g.dir
435}
436
437// digest is the valley-tree-v1 digest of a commit's tree, from attest,
438// which defines the scheme.
439func (s *snapshot) digest(oid string) (string, bool) {
440 if d, ok := s.digestOf[oid]; ok {
441 return d, d != ""
442 }
443 cmd := exec.Command(s.verify.attest, "digest", "--repo", s.repoDir(), "--rev", oid)
444 cmd.Env = s.g.env
445 out, err := cmd.Output()
446 d := ""
447 if scheme, value, ok := strings.Cut(strings.TrimSpace(string(out)), ":"); err == nil && ok && scheme == "valley-tree-v1" {
448 d = value
449 }
450 s.digestOf[oid] = d
451 return d, d != ""
452}
453
454// verified runs attest verify over a transfer statement: its signature
455// must be the integrator's, by a key the known-signers file holds, and
456// its subject must be the tree of the commit it says landed.
457func (s *snapshot) verified(t transferStatement) bool {
458 if s.verify.keys == "" || s.verify.signer == "" {
459 s.unverified = true
460 return false
461 }
462 file, err := os.CreateTemp("", "valley-transfer-*.note")
463 if err != nil {
464 s.unverified = true
465 return false
466 }
467 defer os.Remove(file.Name())
468 _, err = file.Write(t.note)
469 if cerr := file.Close(); err != nil || cerr != nil {
470 s.unverified = true
471 return false
472 }
473 cmd := exec.Command(s.verify.attest, "verify", "--note", file.Name(),
474 "--known-keys", s.verify.keys, "--signer", s.verify.signer,
475 "--repo", s.repoDir(), "--rev", t.landed)
476 cmd.Env = s.g.env
477 if err := cmd.Run(); err != nil {
478 // attest refusing the note is an answer. Failing to run it is not.
479 var exit *exec.ExitError
480 if !errors.As(err, &exit) {
481 s.unverified = true
482 }
483 return false
484 }
485 return true
486}
487
488// reach is every commit reachable from oid that main does not reach.
489func (s *snapshot) reach(oid string) map[string]bool {
490 if r, ok := s.reachOf[oid]; ok {
491 return r
492 }
493 args := []string{"rev-list", oid}
494 if s.tip != "" {
495 args = append(args, "^"+s.tip)
496 }
497 r := map[string]bool{}
498 if out, err := s.g.output(true, args...); err == nil {
499 for _, c := range strings.Fields(out) {
500 r[c] = true
501 }
502 }
503 s.reachOf[oid] = r
504 return r
505}
506
507// strictAncestor reports whether a is an ancestor of b, and not b itself.
508// A commit main does not reach is an ancestor of b exactly when it is in
509// reach(b), so git is asked only about a commit main reaches.
510func (s *snapshot) strictAncestor(a, b string) bool {
511 switch {
512 case a == b:
513 return false
514 case s.reach(b)[a]:
515 return true
516 case s.reaches(a):
517 return s.g.succeeds(true, "merge-base", "--is-ancestor", a, b)
518 }
519 return false
520}
521
522// includes is the change IDs among candidates whose active head is a
523// strict ancestor of n's active head, nearest only: one that is itself an
524// ancestor of another such change's head is left out. It is ancestry
525// alone, so a change that includes another lands the other's content too.
526func (s *snapshot) includes(n recorded, candidates []recorded) []string {
527 head := headOf(n.record.ActiveVersion())
528 var below []recorded
529 for _, c := range candidates {
530 if c.id != n.id && s.strictAncestor(headOf(c.record.ActiveVersion()), head) {
531 below = append(below, c)
532 }
533 }
534 ids := []string{}
535 for _, c := range below {
536 nearest := true
537 for _, d := range below {
538 if s.strictAncestor(headOf(c.record.ActiveVersion()), headOf(d.record.ActiveVersion())) {
539 nearest = false
540 break
541 }
542 }
543 if nearest {
544 ids = append(ids, c.id)
545 }
546 }
547 sort.Strings(ids)
548 return ids
549}
550
551// unrecorded is every branch on origin, other than main, whose tip main
552// does not reach and that is not the head of any change's active version,
553// in the order of their names.
554func (s *snapshot) unrecorded() []jsonBranch {
555 active := map[string]bool{}
556 for _, n := range s.all {
557 active[headOf(n.record.ActiveVersion())] = true
558 }
559 branches := []jsonBranch{}
560 for ref, oid := range s.o.refs {
561 name, ok := strings.CutPrefix(ref, "refs/heads/")
562 if !ok || name == recordTarget || active[oid] || s.reaches(oid) {
563 continue
564 }
565 branches = append(branches, jsonBranch{Branch: name, Head: oid})
566 }
567 sort.Slice(branches, func(i, j int) bool { return branches[i].Branch < branches[j].Branch })
568 return branches
569}