gunk-dev/the-valley

inventory.go

sourcee77dde317001main's published tip history
17.7 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
83func verifierFromEnv() verifier {
84 return verifier{
85 keys: os.Getenv("VALLEY_KNOWN_SIGNERS"),
86 signer: os.Getenv("VALLEY_INTEGRATOR_SIGNER"),
87 attest: "attest",
88 }
89}
90
91// transferStatement is one transfer statement found under an attestation
92// ref, with the values a landing is matched on, read before it is
93// verified.
94type transferStatement struct {
95 note []byte
96 change string // predicate.change: the request's change name
97 base string // predicate.base.valley-tree-v1: the tree the evidence was over
98 landed string // subject.digest.git-sha1: the commit that landed
99}
100
101// snapshot is one read of a repository's origin.
102type snapshot struct {
103 g git
104 o origin
105 tip string // main on origin; "" when origin has none
106 all []recorded
107 verify verifier
108
109 outcomes map[string]memo // outcome ref → the record it holds
110 landings map[string][2]string // "<change ID> <n>" → landing and commit
111 firstParent map[string]bool // main's first-parent history, down to its first merge; nil until read
112 reachesOf map[string]bool
113 reachOf map[string]map[string]bool
114 digestOf map[string]string
115 transfers []transferStatement
116 read bool // whether transfers has been read
117
118 // unverified is set when a transfer statement named a version and
119 // could not be checked, so its landing may be stronger than shown.
120 unverified bool
121}
122
123// readSnapshot lists origin once and fetches every object the snapshot
124// reads: main, every branch tip, every record commit and every outcome
125// record. A record commit has its version heads as parents, so they come
126// with it.
127func readSnapshot(g git, v verifier) (*snapshot, error) {
128 o, err := listOrigin(g, inventoryPatterns...)
129 if err != nil {
130 return nil, err
131 }
132 var want []string
133 for ref, oid := range o.refs {
134 if strings.HasPrefix(ref, "refs/heads/") || strings.HasPrefix(ref, outcomePrefix) {
135 want = append(want, oid)
136 }
137 }
138 if err := fetch(g, want...); err != nil {
139 return nil, err
140 }
141 all, err := readAll(g, o)
142 if err != nil {
143 return nil, err
144 }
145 return newSnapshot(g, o, all, v), nil
146}
147
148// newSnapshot is a snapshot of what o lists, with every record in all
149// already read and every object it names already fetched.
150func newSnapshot(g git, o origin, all []recorded, v verifier) *snapshot {
151 s := &snapshot{
152 g: g, o: o, tip: o.refs["refs/heads/"+recordTarget], all: all, verify: v,
153 outcomes: map[string]memo{}, landings: map[string][2]string{},
154 reachesOf: map[string]bool{}, reachOf: map[string]map[string]bool{}, digestOf: map[string]string{},
155 }
156 for ref, oid := range o.refs {
157 if strings.HasPrefix(ref, outcomePrefix) {
158 data, err := g.output(true, "cat-file", "blob", oid)
159 if err != nil {
160 data = ""
161 }
162 s.outcomes[ref] = parseMemo(data)
163 }
164 }
165 return s
166}
167
168// headOf is a version's head as an object ID.
169func headOf(v change.Version) string {
170 return strings.TrimPrefix(v.Head, change.HeadPrefix)
171}
172
173// onMain reports whether a commit is on main's first-parent history (main
174// itself, its first parent, that commit's first parent, and so on) with no
175// merge between it and main's tip: whether
176// `git rev-list --first-parent --merges <oid>..main` would list nothing.
177// This is where a landing puts a change. The history is read down to its
178// first merge, which is itself the last commit counted, since no merge is
179// above it.
180func (s *snapshot) onMain(oid string) bool {
181 if s.tip == "" || oid == "" {
182 return false
183 }
184 if s.firstParent == nil {
185 s.firstParent = map[string]bool{}
186 if out, err := s.g.output(true, "rev-list", "--first-parent", "--parents", s.tip); err == nil {
187 for _, line := range strings.Split(out, "\n") {
188 fields := strings.Fields(line)
189 if len(fields) == 0 {
190 continue
191 }
192 s.firstParent[fields[0]] = true
193 if len(fields) > 2 {
194 break
195 }
196 }
197 }
198 }
199 return s.firstParent[oid]
200}
201
202// reaches reports whether main reaches a commit by any path: whether the
203// commit is an ancestor of main, or main itself. That is ancestry, which
204// is not landing (onMain).
205func (s *snapshot) reaches(oid string) bool {
206 if s.tip == "" || oid == "" {
207 return false
208 }
209 r, seen := s.reachesOf[oid]
210 if !seen {
211 r = s.g.succeeds(true, "merge-base", "--is-ancestor", oid, s.tip)
212 s.reachesOf[oid] = r
213 }
214 return r
215}
216
217// requestNames are the names a request for a version is filed under: its
218// branch, the way approve names one, and c-<change ID>.
219func requestNames(id string, v change.Version) []string {
220 var names []string
221 if v.Branch != "" {
222 names = append(names, changeName(v.Branch))
223 }
224 return append(names, "c-"+id)
225}
226
227// request is the integration request origin holds for a version: one
228// filed under either of its names, at its head.
229func (s *snapshot) request(id string, v change.Version) *jsonRequest {
230 for _, name := range requestNames(id, v) {
231 if ref := requestPrefix + name; s.o.refs[ref] == headOf(v) {
232 return &jsonRequest{Ref: ref, Commit: headOf(v)}
233 }
234 }
235 return nil
236}
237
238// outcome is the integrator's last decision about a version: the outcome
239// record under either of its names whose head is the version's head.
240func (s *snapshot) outcome(id string, v change.Version) (name string, m memo, found bool) {
241 for _, name := range requestNames(id, v) {
242 if m, ok := s.outcomes[outcomePrefix+name]; ok && m.head == headOf(v) {
243 return name, m, true
244 }
245 }
246 return "", memo{}, false
247}
248
249// landing is the landing evidence a version has, and the commit on main it
250// landed as, when it has. Each version is decided once per snapshot.
251func (s *snapshot) landing(id string, v change.Version) (kind, commit string) {
252 key := fmt.Sprintf("%s %d", id, v.N)
253 if l, ok := s.landings[key]; ok {
254 return l[0], l[1]
255 }
256 kind, commit = s.decideLanding(id, v)
257 s.landings[key] = [2]string{kind, commit}
258 return kind, commit
259}
260
261func (s *snapshot) decideLanding(id string, v change.Version) (kind, commit string) {
262 head := headOf(v)
263 if s.onMain(head) {
264 return landed, head
265 }
266 if commit, ok := s.recordedLanding(id, v); ok {
267 return landedRecorded, commit
268 }
269 if name, m, ok := s.outcome(id, v); ok {
270 consumed := m.decision == "land" && s.o.refs[requestPrefix+name] != head
271 if consumed || m.decision == "failed" {
272 return uncertain, ""
273 }
274 }
275 return notLanded, ""
276}
277
278// isLanded reports whether a version has landed by the first two rules.
279func (s *snapshot) isLanded(id string, v change.Version) bool {
280 kind, _ := s.landing(id, v)
281 return kind == landed || kind == landedRecorded
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(headOf(v))
300 if !ok {
301 s.unverified = true
302 continue
303 }
304 if t.base != digest || !s.mergesTo(headOf(v), 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(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(true, "rev-parse", "--verify", "--quiet", landed+"^1^{commit}")
328 if err != nil {
329 return false
330 }
331 want, err := s.g.output(true, "rev-parse", "--verify", "--quiet", landed+"^{tree}")
332 if err != nil {
333 return false
334 }
335 base, err := s.g.output(true, "merge-base", tip, head)
336 if err != nil {
337 return false
338 }
339 out, err := s.g.output(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.o.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.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(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(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 cmd := exec.Command(s.verify.attest, "digest", "--repo", s.repoDir(), "--rev", oid)
440 cmd.Env = s.g.env
441 out, err := cmd.Output()
442 d := ""
443 if scheme, value, ok := strings.Cut(strings.TrimSpace(string(out)), ":"); err == nil && ok && scheme == "valley-tree-v1" {
444 d = value
445 }
446 s.digestOf[oid] = d
447 return d, d != ""
448}
449
450// verified runs attest verify over a transfer statement: its signature
451// must be the integrator's, by a key the known-signers file holds, and
452// its subject must be the tree of the commit it says landed.
453func (s *snapshot) verified(t transferStatement) bool {
454 if s.verify.keys == "" || s.verify.signer == "" {
455 s.unverified = true
456 return false
457 }
458 file, err := os.CreateTemp("", "valley-transfer-*.note")
459 if err != nil {
460 s.unverified = true
461 return false
462 }
463 defer os.Remove(file.Name())
464 _, err = file.Write(t.note)
465 if cerr := file.Close(); err != nil || cerr != nil {
466 s.unverified = true
467 return false
468 }
469 cmd := exec.Command(s.verify.attest, "verify", "--note", file.Name(),
470 "--known-keys", s.verify.keys, "--signer", s.verify.signer,
471 "--repo", s.repoDir(), "--rev", t.landed)
472 cmd.Env = s.g.env
473 if err := cmd.Run(); err != nil {
474 // attest refusing the note is an answer. Failing to run it is not.
475 var exit *exec.ExitError
476 if !errors.As(err, &exit) {
477 s.unverified = true
478 }
479 return false
480 }
481 return true
482}
483
484// reach is every commit reachable from oid that main does not reach.
485func (s *snapshot) reach(oid string) map[string]bool {
486 if r, ok := s.reachOf[oid]; ok {
487 return r
488 }
489 args := []string{"rev-list", oid}
490 if s.tip != "" {
491 args = append(args, "^"+s.tip)
492 }
493 r := map[string]bool{}
494 if out, err := s.g.output(true, args...); err == nil {
495 for _, c := range strings.Fields(out) {
496 r[c] = true
497 }
498 }
499 s.reachOf[oid] = r
500 return r
501}
502
503// strictAncestor reports whether a is an ancestor of b, and not b itself.
504// A commit main does not reach is an ancestor of b exactly when it is in
505// reach(b), so git is asked only about a commit main reaches.
506func (s *snapshot) strictAncestor(a, b string) bool {
507 switch {
508 case a == b:
509 return false
510 case s.reach(b)[a]:
511 return true
512 case s.reaches(a):
513 return s.g.succeeds(true, "merge-base", "--is-ancestor", a, b)
514 }
515 return false
516}
517
518// includes is the change IDs among candidates whose active head is a
519// strict ancestor of n's active head, nearest only: one that is itself an
520// ancestor of another such change's head is left out. It is ancestry
521// alone, so a change that includes another lands the other's content too.
522func (s *snapshot) includes(n recorded, candidates []recorded) []string {
523 head := headOf(n.record.ActiveVersion())
524 var below []recorded
525 for _, c := range candidates {
526 if c.id != n.id && s.strictAncestor(headOf(c.record.ActiveVersion()), head) {
527 below = append(below, c)
528 }
529 }
530 ids := []string{}
531 for _, c := range below {
532 nearest := true
533 for _, d := range below {
534 if s.strictAncestor(headOf(c.record.ActiveVersion()), headOf(d.record.ActiveVersion())) {
535 nearest = false
536 break
537 }
538 }
539 if nearest {
540 ids = append(ids, c.id)
541 }
542 }
543 sort.Strings(ids)
544 return ids
545}
546
547// unrecorded is every branch on origin, other than main, whose tip main
548// does not reach and that is not the head of any change's active version,
549// in the order of their names.
550func (s *snapshot) unrecorded() []jsonBranch {
551 active := map[string]bool{}
552 for _, n := range s.all {
553 active[headOf(n.record.ActiveVersion())] = true
554 }
555 branches := []jsonBranch{}
556 for ref, oid := range s.o.refs {
557 name, ok := strings.CutPrefix(ref, "refs/heads/")
558 if !ok || name == recordTarget || active[oid] || s.reaches(oid) {
559 continue
560 }
561 branches = append(branches, jsonBranch{Branch: name, Head: oid})
562 }
563 sort.Slice(branches, func(i, j int) bool { return branches[i].Branch < branches[j].Branch })
564 return branches
565}