gunk-dev/the-valley

inventory.go

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