gunk-dev/the-valley

snapshot.go

source8043b5e912d0main's published tip history
30.9 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, outcome record and landing record, every
6// attestation ref, and every restack report. From it, for each version of
7// each change, it decides the landing evidence the version has. The first
8// rule 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 it never puts a
13// change's own commits on that history. This rule matches a head
14// written to main directly, or landed directly by an earlier
15// integrator. A merge above the head
16// could have dropped the head's content, whichever parent the head is
17// reached through, so it leaves the head not landed by this rule.
18// 2. landed-recorded: a commit L on main's first-parent history, with one
19// parent, carries a transfer statement, signed by the integrator,
20// whose change is a request name of the version and whose base is
21// the valley-tree-v1 digest of the version's tree. The integrator
22// writes one when it lands a change (integrator/transfer.go). The
23// integrator recorded landing this version's head as L under that
24// request name: a statement about trees does not name the exact head,
25// and the integrator's records do. Only the integrator writes them.
26// The landing record for the head (change/landing.go) says so when
27// origin holds one. A landing made before the integrator wrote
28// landing records has none, and then the outcome record for the
29// request name must say land at this version's head. And the
30// integrator's own merge of the head onto L's parent gives L's tree.
31// 3. uncertain: a request for the version was consumed, or the outcome
32// record says the integrator failed on it, or a landing record names
33// its head, and neither of the above holds. The integrator records a
34// landing in the transaction that moves main (integrator/refs.go), so
35// only a landing made before it did, or one cut short inside git's
36// commit of that transaction, exists without its evidence.
37// 4. not-landed: otherwise.
38//
39// An outcome record or a landing record alone is never proof of a
40// landing. An outcome record is kept per request name, so a later pass
41// can overwrite it: a landing that only its outcome record bound to its
42// head, and whose record a later pass overwrote, reads uncertain, never
43// landed-recorded. A landing record is kept per head, so a later landing
44// under the same request name leaves it in place.
45
46package rebase
47
48import (
49 "bytes"
50 "context"
51 "errors"
52 "fmt"
53 "os"
54 "os/exec"
55 "sort"
56 "strings"
57
58 "the-valley/change"
59)
60
61// The landing evidence a version can have.
62const (
63 Landed = "landed"
64 LandedRecorded = "landed-recorded"
65 LandingUncertain = "uncertain"
66 NotLanded = "not-landed"
67)
68
69const predicateTransfer = "the-valley/integration/transfer/v1"
70
71// Verifier is what a transfer statement is checked with: the verifier
72// keys of the identity registry's known-signers file, the name the
73// integrator signs under, and the attest helper that checks a note.
74// Without the first two, no transfer statement is believed, and a version
75// that only one could show landed reads as uncertain or not-landed.
76//
77// SignerProjects is the signer projects file the host's controllers
78// read (note/signerprojects.go): each signer it names, and the projects
79// that signer's check evidence counts in. A signer it names, a worker or
80// another controller, is never this host's integrator, so while it names
81// Signer no transfer statement is believed, in any project.
82//
83// Resolve, when set, finds the keys, the name and the signer projects
84// file when they are first needed: a snapshot calls it once, before it
85// verifies its first statement, and checks with what it returns in place
86// of Keys, Signer and SignerProjects. A snapshot that verifies no
87// statement never calls it.
88type Verifier struct {
89 Keys, Signer, Attest string
90 SignerProjects map[string]map[string]bool
91 Resolve func() (keys, signer string, signerProjects map[string]map[string]bool)
92}
93
94// transferStatement is one transfer statement found under an attestation
95// ref, with the values a landing is matched on, read before it is
96// verified.
97type transferStatement struct {
98 note []byte
99 change string // predicate.change: the request's change name
100 base string // predicate.base.valley-tree-v1: the tree the evidence was over
101 landed string // subject.digest.git-sha1: the commit that landed
102}
103
104// Snapshot is one read of a repository's origin. Its landing decisions,
105// and the ancestry it reads, are read from git when first asked for, under
106// the context the snapshot was made with, and kept.
107type Snapshot struct {
108 Origin
109 Tip string // main on origin; "" when origin has none
110 Changes []Recorded // every record that reads, in the order of their IDs
111 Unread []UnreadRecord // each record that does not read, which no reader shows
112
113 ctx context.Context
114 g Git
115 verify Verifier
116
117 outcomes map[string]Outcome // outcome ref → the record it holds
118 landed map[string]landingAt // head → its landing record, once read
119 reports map[string]Report // change ID → its restack report, once read
120 landings map[string][2]string // "<change ID> <n>" → landing and commit
121 firstParent map[string]int // main's first-parent history, down to its first merge, and each commit's number of parents; nil until read
122 reachesOf map[string]bool
123 reachOf map[string]reached
124 ancestorOf map[[2]string]bool // "is a an ancestor of b", as git answered it
125 history *history // every commit main reaches; nil until read, or when it does not read
126 historyRead bool
127 digestOf map[string]string
128 transfers []transferStatement
129 read bool // whether transfers has been read
130
131 // unverified is set when a transfer statement named a version and
132 // could not be checked, so its landing may be stronger than shown.
133 unverified bool
134}
135
136// snapshotTries is how many times ReadSnapshot lists origin and fetches
137// what the listing names before it gives up.
138const snapshotTries = 3
139
140// ReadSnapshot lists origin once and fetches every object the snapshot
141// reads: main, every branch tip, every record commit, every outcome and
142// landing record, and every restack report. A record commit has its
143// version heads as parents, so they come with it.
144//
145// A ref can move between the listing and the fetch. Origin may then no
146// longer hold the object the listing named, as when main was rewritten and
147// its old tip pruned, and the fetch fails. The read is then made again
148// from a new listing, up to snapshotTries times in all, and a fetch that
149// still fails is the snapshot's error.
150func ReadSnapshot(ctx context.Context, g Git, v Verifier) (*Snapshot, error) {
151 for try := 1; ; try++ {
152 end := g.phase("fetch")
153 o, err := ListOrigin(ctx, g, InventoryPatterns...)
154 end()
155 if err != nil {
156 return nil, err
157 }
158 s, err := fetchSnapshot(ctx, g, o, v)
159 if err == nil || try == snapshotTries || ctx.Err() != nil {
160 return s, err
161 }
162 }
163}
164
165// fetchSnapshot fetches every object a snapshot of the listing reads, and
166// reads every record it names.
167func fetchSnapshot(ctx context.Context, g Git, o Origin, v Verifier) (*Snapshot, error) {
168 var want []string
169 for ref, oid := range o.Refs {
170 if strings.HasPrefix(ref, "refs/heads/") || strings.HasPrefix(ref, OutcomePrefix) ||
171 strings.HasPrefix(ref, LandingPrefix) || strings.HasPrefix(ref, RestackPrefix) {
172 want = append(want, oid)
173 }
174 }
175 end := g.phase("fetch")
176 err := Fetch(ctx, g, want...)
177 end()
178 if err != nil {
179 return nil, err
180 }
181 defer g.phase("records")()
182 all, unread, err := ReadAll(ctx, g, o)
183 if err != nil {
184 return nil, err
185 }
186 s := NewSnapshot(ctx, g, o, all, v)
187 s.Unread = unread
188 return s, nil
189}
190
191// NewSnapshot is a snapshot of what o lists, with every record in all
192// already read and every object it names already fetched.
193func NewSnapshot(ctx context.Context, g Git, o Origin, all []Recorded, v Verifier) *Snapshot {
194 s := &Snapshot{
195 Origin: o, Tip: o.Refs["refs/heads/"+Target], Changes: all,
196 ctx: ctx, g: g, verify: v,
197 outcomes: map[string]Outcome{}, landed: map[string]landingAt{}, reports: map[string]Report{}, landings: map[string][2]string{},
198 reachesOf: map[string]bool{}, reachOf: map[string]reached{}, ancestorOf: map[[2]string]bool{}, digestOf: map[string]string{},
199 }
200 var records []string
201 for ref, oid := range o.Refs {
202 if strings.HasPrefix(ref, OutcomePrefix) {
203 records = append(records, oid)
204 }
205 }
206 read := g.blobs(ctx, records)
207 for ref, oid := range o.Refs {
208 if strings.HasPrefix(ref, OutcomePrefix) {
209 data, ok := read[oid]
210 if !ok {
211 var err error
212 if data, err = g.output(ctx, true, "cat-file", "blob", oid); err != nil {
213 data = ""
214 }
215 }
216 s.outcomes[ref] = ParseOutcome(data)
217 }
218 }
219 return s
220}
221
222// Unverified reports whether a transfer statement named a version and
223// could not be checked, so that version's landing may be stronger than
224// the snapshot says.
225func (s *Snapshot) Unverified() bool { return s.unverified }
226
227// OnMain reports whether a commit is on main's first-parent history (main
228// itself, its first parent, that commit's first parent, and so on) with no
229// merge between it and main's tip: whether
230// `git rev-list --first-parent --merges <oid>..main` would list nothing.
231// This is where a landing puts a change. The history is read down to its
232// first merge, which is itself the last commit counted, since no merge is
233// above it.
234func (s *Snapshot) OnMain(oid string) bool {
235 if s.Tip == "" || oid == "" {
236 return false
237 }
238 if s.firstParent == nil {
239 s.firstParent = map[string]int{}
240 if out, err := s.g.output(s.ctx, true, "rev-list", "--first-parent", "--parents", s.Tip); err == nil {
241 for _, line := range strings.Split(out, "\n") {
242 fields := strings.Fields(line)
243 if len(fields) == 0 {
244 continue
245 }
246 s.firstParent[fields[0]] = len(fields) - 1
247 if len(fields) > 2 {
248 break
249 }
250 }
251 }
252 }
253 _, on := s.firstParent[oid]
254 return on
255}
256
257// Reaches reports whether main reaches a commit by any path: whether the
258// commit is an ancestor of main, or main itself. That is ancestry, which
259// is not landing (OnMain).
260//
261// Main's history answers, once read. A commit outside it that Reach lists
262// is one main does not reach. Anything else, such as a name that is not a
263// commit's ID, git answers, once.
264func (s *Snapshot) Reaches(oid string) bool {
265 if s.Tip == "" || oid == "" {
266 return false
267 }
268 if h := s.mainHistory(); h != nil {
269 if h.has(oid) {
270 return true
271 }
272 if s.Reach(oid)[oid] {
273 return false
274 }
275 }
276 r, seen := s.reachesOf[oid]
277 if !seen {
278 r = s.g.succeeds(s.ctx, true, "merge-base", "--is-ancestor", oid, s.Tip)
279 s.reachesOf[oid] = r
280 }
281 return r
282}
283
284// Request is the ref of the integration request origin holds for a
285// version: one filed under either of its names, at its head.
286func (s *Snapshot) Request(id string, v change.Version) (ref string, ok bool) {
287 for _, name := range RequestNames(id, v) {
288 if ref := RequestPrefix + name; s.Refs[ref] == HeadOf(v) {
289 return ref, true
290 }
291 }
292 return "", false
293}
294
295// OutcomeOf is the outcome record origin holds under a request name, as
296// ParseOutcome reads it, and whether origin holds one.
297func (s *Snapshot) OutcomeOf(name string) (Outcome, bool) {
298 m, ok := s.outcomes[OutcomePrefix+name]
299 return m, ok
300}
301
302// Outcome is the integrator's last decision about a version: the outcome
303// record under either of its names whose head is the version's head.
304func (s *Snapshot) Outcome(id string, v change.Version) (name string, m Outcome, found bool) {
305 for _, name := range RequestNames(id, v) {
306 if m, ok := s.outcomes[OutcomePrefix+name]; ok && m.Head == HeadOf(v) {
307 return name, m, true
308 }
309 }
310 return "", Outcome{}, false
311}
312
313// Landing is the landing evidence a version has, and the commit on main it
314// landed as, when it has. Each version is decided once per snapshot.
315func (s *Snapshot) Landing(id string, v change.Version) (kind, commit string) {
316 key := fmt.Sprintf("%s %d", id, v.N)
317 if l, ok := s.landings[key]; ok {
318 return l[0], l[1]
319 }
320 kind, commit = s.decideLanding(id, v)
321 s.landings[key] = [2]string{kind, commit}
322 return kind, commit
323}
324
325func (s *Snapshot) decideLanding(id string, v change.Version) (kind, commit string) {
326 head := HeadOf(v)
327 if s.OnMain(head) {
328 return Landed, head
329 }
330 if commit, ok := s.recordedLanding(id, v); ok {
331 return LandedRecorded, commit
332 }
333 if name, m, ok := s.Outcome(id, v); ok {
334 consumed := m.Decision == "land" && s.Refs[RequestPrefix+name] != head
335 if consumed || m.Decision == "failed" {
336 return LandingUncertain, ""
337 }
338 }
339 if s.Refs[LandingPrefix+head] != "" {
340 return LandingUncertain, ""
341 }
342 return NotLanded, ""
343}
344
345// IsLanded reports whether a version has landed by the first two rules.
346func (s *Snapshot) IsLanded(id string, v change.Version) bool {
347 kind, _ := s.Landing(id, v)
348 return kind == Landed || kind == LandedRecorded
349}
350
351// LandedAs is the version a change landed as, and whether it has: the
352// newest of its versions that landed by the first two rules. A change
353// counts as landed once any of its versions has, so a version restacked
354// while an earlier one was approved, and still active when that one
355// landed, is no work left to land. An active version whose head reaches
356// that landing was made on a main that holds it, and is the change's next
357// round: the change reads unlanded until that version lands.
358func (s *Snapshot) LandedAs(n Recorded) (change.Version, bool) {
359 active := n.Record.ActiveVersion()
360 for i := len(n.Record.Versions) - 1; i >= 0; i-- {
361 v := n.Record.Versions[i]
362 kind, commit := s.Landing(n.ID, v)
363 if kind != Landed && kind != LandedRecorded {
364 continue
365 }
366 if v.N != active.N && s.StrictAncestor(commit, HeadOf(active)) {
367 return change.Version{}, false
368 }
369 return v, true
370 }
371 return change.Version{}, false
372}
373
374// Unlanded reports whether a change, in any state, has not landed as any
375// of its versions (LandedAs): the changes a stack's layers are among.
376func (s *Snapshot) Unlanded(n Recorded) bool {
377 _, landed := s.LandedAs(n)
378 return !landed
379}
380
381// recordedLanding looks for a transfer statement that records the version
382// landing as a commit on main, and verifies the first that matches.
383func (s *Snapshot) recordedLanding(id string, v change.Version) (string, bool) {
384 names := map[string]bool{}
385 for _, n := range RequestNames(id, v) {
386 names[n] = true
387 }
388 head := HeadOf(v)
389 for _, t := range s.transferStatements() {
390 if !names[t.change] || !IsObjectID(t.landed) || !s.OnMain(t.landed) || !s.singleParent(t.landed) {
391 continue
392 }
393 if !s.boundTo(t, head) {
394 continue
395 }
396 digest, ok := s.digest(head)
397 if !ok {
398 s.unverified = true
399 continue
400 }
401 if t.base != digest || !s.mergesTo(head, t.landed) {
402 continue
403 }
404 if s.verified(t) {
405 return t.landed, true
406 }
407 }
408 return "", false
409}
410
411// boundTo reports whether the integrator recorded landing head as the
412// statement's commit, under the statement's request name. When origin
413// holds a landing record for the head, that record alone answers. A
414// landing made before landing records were written has none, and its
415// outcome record answers instead.
416func (s *Snapshot) boundTo(t transferStatement, head string) bool {
417 if at, found := s.landingRecord(head); found {
418 return at.read && at.Landed == t.landed && at.Request == t.change && at.Head == head
419 }
420 m, ok := s.outcomes[OutcomePrefix+t.change]
421 return ok && m.Decision == "land" && m.Head == head
422}
423
424// landingAt is a landing record as a snapshot read it, and whether it
425// read.
426type landingAt struct {
427 change.Landing
428 read bool
429}
430
431// landingRecord reads the landing record origin holds for head, once.
432// found is false when origin holds none. A record that does not read is
433// found, and says nothing.
434func (s *Snapshot) landingRecord(head string) (landingAt, bool) {
435 oid := s.Refs[LandingPrefix+head]
436 if oid == "" {
437 return landingAt{}, false
438 }
439 if at, ok := s.landed[head]; ok {
440 return at, true
441 }
442 var at landingAt
443 if err := Fetch(s.ctx, s.g, oid); err != nil {
444 s.unverified = true
445 } else if data, err := s.g.output(s.ctx, true, "cat-file", "blob", oid+":"+change.LandingFile); err == nil {
446 if l, err := change.ParseLanding([]byte(data + "\n")); err == nil {
447 at = landingAt{Landing: l, read: true}
448 }
449 }
450 s.landed[head] = at
451 return at, true
452}
453
454// singleParent reports whether a commit has exactly one parent, as every
455// commit the integrator lands as does. For a commit on main (OnMain), the
456// read of main's first-parent history has its parents.
457func (s *Snapshot) singleParent(oid string) bool {
458 if n, on := s.firstParent[oid]; on {
459 return n == 1
460 }
461 out, err := s.g.output(s.ctx, true, "rev-list", "--parents", "-n", "1", oid)
462 return err == nil && len(strings.Fields(out)) == 2
463}
464
465// mergesTo reports whether the integrator's merge of head onto landed's
466// parent gives landed's tree. It is the merge integrator/git.go's
467// mergeDelta makes: merge-tree onto the tip, with the merge base of the
468// tip and the head as the base. A head that merges to another tree, or
469// not at all, is not what landed.
470func (s *Snapshot) mergesTo(head, landed string) bool {
471 tip, err := s.g.output(s.ctx, true, "rev-parse", "--verify", "--quiet", landed+"^1^{commit}")
472 if err != nil {
473 return false
474 }
475 want, err := s.g.output(s.ctx, true, "rev-parse", "--verify", "--quiet", landed+"^{tree}")
476 if err != nil {
477 return false
478 }
479 base, err := s.g.output(s.ctx, true, "merge-base", tip, head)
480 if err != nil {
481 return false
482 }
483 out, err := s.g.output(s.ctx, true, "merge-tree", "--write-tree", "--merge-base="+base, tip, head)
484 if err != nil {
485 return false
486 }
487 tree, _, _ := strings.Cut(out, "\n")
488 return strings.TrimSpace(tree) == want
489}
490
491// transferStatements reads every transfer statement under origin's
492// attestation refs, once. A transfer statement is a note at
493// change.TransferPath of a landed commit, under the transfer.d directory
494// at the top of an attestation ref's tree, or a single transfer.note at
495// the top of the tree, as a ref written before statements were kept per
496// landing holds it. Anything unreadable is skipped: what is not read is
497// not believed.
498func (s *Snapshot) transferStatements() []transferStatement {
499 if s.read {
500 return s.transfers
501 }
502 s.read = true
503 var trees []string
504 for ref, oid := range s.Refs {
505 if strings.HasPrefix(ref, AttestationRefs) {
506 trees = append(trees, oid)
507 }
508 }
509 if len(trees) == 0 {
510 return nil
511 }
512 sort.Strings(trees)
513 if err := Fetch(s.ctx, s.g, trees...); err != nil {
514 s.unverified = true
515 return nil
516 }
517 var query bytes.Buffer
518 for _, tree := range trees {
519 fmt.Fprintf(&query, "%s:%s\n%s:%s\n", tree, change.TransferNote, tree, change.TransferDir)
520 }
521 out, err := s.g.input(s.ctx, true, &query, "cat-file", "--batch-check=%(objectname) %(objecttype)")
522 if err != nil {
523 s.unverified = true
524 return nil
525 }
526 var blobs []string
527 for _, line := range strings.Split(out, "\n") {
528 oid, kind, _ := strings.Cut(line, " ")
529 switch kind {
530 case "blob":
531 blobs = append(blobs, oid)
532 case "tree":
533 listing, err := s.g.output(s.ctx, true, "ls-tree", "-r", "-z", oid)
534 if err != nil {
535 s.unverified = true
536 continue
537 }
538 for _, entry := range strings.Split(listing, "\x00") {
539 meta, path, ok := strings.Cut(entry, "\t")
540 if fields := strings.Fields(meta); ok && len(fields) == 3 && fields[1] == "blob" && isTransferPath(path) {
541 blobs = append(blobs, fields[2])
542 }
543 }
544 }
545 }
546 read := s.g.blobs(s.ctx, blobs)
547 for _, oid := range blobs {
548 note, ok := read[oid]
549 if !ok {
550 var err error
551 if note, err = s.g.output(s.ctx, true, "cat-file", "blob", oid); err != nil {
552 continue
553 }
554 }
555 note += "\n"
556 text, ok := noteText(note)
557 if !ok || statementValue(text, "predicateType") != predicateTransfer {
558 continue
559 }
560 s.transfers = append(s.transfers, transferStatement{
561 note: []byte(note),
562 change: statementValue(text, "predicate.change"),
563 base: statementValue(text, "predicate.base.valley-tree-v1"),
564 landed: statementValue(text, "subject.digest.git-sha1"),
565 })
566 }
567 return s.transfers
568}
569
570// isTransferPath reports whether a path within the transfer.d directory is
571// where change.TransferPath puts the statement for some commit:
572// <2 hex>/<2 hex>/<rest>.note, the three parts a full object ID.
573func isTransferPath(path string) bool {
574 parts := strings.Split(strings.TrimSuffix(path, ".note"), "/")
575 if len(parts) != 3 || len(parts[0]) != 2 || len(parts[1]) != 2 || !strings.HasSuffix(path, ".note") {
576 return false
577 }
578 return IsObjectID(parts[0] + parts[1] + parts[2])
579}
580
581// noteText is the statement text of a note: everything before the last
582// blank line, which separates the text from its signatures.
583func noteText(note string) (string, bool) {
584 split := strings.LastIndex(note, "\n\n")
585 if split < 0 {
586 return "", false
587 }
588 return note[:split+1], true
589}
590
591// statementValue reads one key's value from statement text, where each
592// line is a key, one space and a value. It is a lookup, and it decides
593// nothing: what is read here only chooses which statement to verify.
594func statementValue(text, key string) string {
595 for _, line := range strings.Split(text, "\n") {
596 if k, v, ok := strings.Cut(line, " "); ok && k == key {
597 return v
598 }
599 }
600 return ""
601}
602
603// repoDir is the directory attest is pointed at.
604func (s *Snapshot) repoDir() string {
605 if s.g.Dir == "" {
606 return "."
607 }
608 return s.g.Dir
609}
610
611// digest is the valley-tree-v1 digest of a commit's tree, from attest,
612// which defines the scheme.
613func (s *Snapshot) digest(oid string) (string, bool) {
614 defer s.g.phase("transfers")()
615 if d, ok := s.digestOf[oid]; ok {
616 return d, d != ""
617 }
618 out, err := s.g.tool(s.ctx, s.verify.Attest, "digest", "--repo", s.repoDir(), "--rev", oid).Output()
619 d := ""
620 if scheme, value, ok := strings.Cut(strings.TrimSpace(string(out)), ":"); finished(err) == nil && ok && scheme == "valley-tree-v1" {
621 d = value
622 }
623 s.digestOf[oid] = d
624 return d, d != ""
625}
626
627// verified runs attest verify over a transfer statement: its signature
628// must be the integrator's, by a key the known-signers file holds, and
629// its subject must be the tree of the commit it says landed. A name the
630// signer projects file restricts is not the integrator's, so nothing
631// signed under it is verified.
632func (s *Snapshot) verified(t transferStatement) bool {
633 defer s.g.phase("transfers")()
634 if s.verify.Resolve != nil {
635 s.verify.Keys, s.verify.Signer, s.verify.SignerProjects = s.verify.Resolve()
636 s.verify.Resolve = nil
637 }
638 if _, worker := s.verify.SignerProjects[s.verify.Signer]; worker || s.verify.Keys == "" || s.verify.Signer == "" {
639 s.unverified = true
640 return false
641 }
642 file, err := os.CreateTemp("", "valley-transfer-*.note")
643 if err != nil {
644 s.unverified = true
645 return false
646 }
647 defer os.Remove(file.Name())
648 _, err = file.Write(t.note)
649 if cerr := file.Close(); err != nil || cerr != nil {
650 s.unverified = true
651 return false
652 }
653 cmd := s.g.tool(s.ctx, s.verify.Attest, "verify", "--note", file.Name(),
654 "--known-keys", s.verify.Keys, "--signer", s.verify.Signer,
655 "--repo", s.repoDir(), "--rev", t.landed)
656 if err := finished(cmd.Run()); err != nil {
657 // attest refusing the note is an answer. Failing to run it is not.
658 var exit *exec.ExitError
659 if !errors.As(err, &exit) {
660 s.unverified = true
661 }
662 return false
663 }
664 return true
665}
666
667// reached is what a commit reaches, as one rev-list read it.
668type reached struct {
669 commits map[string]bool // every commit it reaches that main does not
670 // below is each commit main reaches that is a parent of one in
671 // commits: where its own history meets main's.
672 below []string
673}
674
675// Reach is every commit reachable from oid that main does not reach.
676func (s *Snapshot) Reach(oid string) map[string]bool {
677 return s.reached(oid).commits
678}
679
680// reached reads what oid reaches, once.
681func (s *Snapshot) reached(oid string) reached {
682 if r, ok := s.reachOf[oid]; ok {
683 return r
684 }
685 args := []string{"rev-list", "--parents", oid}
686 if s.Tip != "" {
687 args = append(args, "^"+s.Tip)
688 }
689 r := reached{commits: map[string]bool{}}
690 if out, err := s.g.output(s.ctx, true, args...); err == nil {
691 var parents []string
692 for _, line := range strings.Split(out, "\n") {
693 if fields := strings.Fields(line); len(fields) > 0 {
694 r.commits[fields[0]] = true
695 parents = append(parents, fields[1:]...)
696 }
697 }
698 seen := map[string]bool{}
699 for _, p := range parents {
700 if !r.commits[p] && !seen[p] {
701 seen[p] = true
702 r.below = append(r.below, p)
703 }
704 }
705 }
706 s.reachOf[oid] = r
707 return r
708}
709
710// StrictAncestor reports whether a is an ancestor of b, and not b itself.
711// A commit main does not reach is an ancestor of b exactly when it is in
712// Reach(b). A commit main reaches is one exactly when b is a commit main
713// reaches and has it in its history, or when a commit where b's own
714// history meets main's has it. Main's history answers that. git is asked
715// only when the snapshot cannot tell, and each pair once.
716func (s *Snapshot) StrictAncestor(a, b string) bool {
717 switch {
718 case a == b:
719 return false
720 case s.Reach(b)[a]:
721 return true
722 case !s.Reaches(a):
723 return false
724 }
725 if r, known := s.mainAncestor(a, b); known {
726 return r
727 }
728 key := [2]string{a, b}
729 r, seen := s.ancestorOf[key]
730 if !seen {
731 r = s.g.succeeds(s.ctx, true, "merge-base", "--is-ancestor", a, b)
732 s.ancestorOf[key] = r
733 }
734 return r
735}
736
737// mainAncestor answers, from main's history, whether a, a commit main
738// reaches, is an ancestor of b. known is false when it cannot tell: when
739// main's history did not read, or b is not a commit Reach(b) or main's
740// history lists.
741func (s *Snapshot) mainAncestor(a, b string) (r, known bool) {
742 h := s.mainHistory()
743 if h == nil || !h.has(a) {
744 return false, false
745 }
746 if h.has(b) {
747 return h.reaches(b, a), true
748 }
749 at := s.reached(b)
750 if !at.commits[b] {
751 return false, false
752 }
753 for _, c := range at.below {
754 if !h.has(c) {
755 return false, false
756 }
757 }
758 for _, c := range at.below {
759 if h.reaches(c, a) {
760 return true, true
761 }
762 }
763 return false, true
764}
765
766// mainHistory is every commit main reaches, read once. It is nil when
767// origin has no main, or its history does not read.
768func (s *Snapshot) mainHistory() *history {
769 if !s.historyRead && s.Tip != "" {
770 s.historyRead = true
771 s.history, _ = readHistory(s.ctx, s.g, s.Tip)
772 }
773 return s.history
774}
775
776// BranchHead is a branch on origin and the commit at its tip.
777type BranchHead struct {
778 Branch, Head string
779}
780
781// Unrecorded is every branch on origin, other than main, whose tip main
782// does not reach, that is not the head of any change's active version, and
783// that no landed version's head reaches, in the order of their names.
784//
785// A version lands as one new commit on main, so main does not reach the
786// version's own commits, nor a branch below them. Their content is on
787// main, so such a branch is no work waiting to land: it is left out, as
788// the rebase engine cuts a landed version's commits from a family
789// (LandedUnder).
790func (s *Snapshot) Unrecorded() []BranchHead {
791 active := map[string]bool{}
792 for _, n := range s.Changes {
793 active[HeadOf(n.Record.ActiveVersion())] = true
794 }
795 var branches []BranchHead
796 for ref, oid := range s.Refs {
797 name, ok := strings.CutPrefix(ref, "refs/heads/")
798 if !ok || name == Target || active[oid] || s.Reaches(oid) || s.underLanded(oid) {
799 continue
800 }
801 branches = append(branches, BranchHead{Branch: name, Head: oid})
802 }
803 sort.Slice(branches, func(i, j int) bool { return branches[i].Branch < branches[j].Branch })
804 return branches
805}
806
807// underLanded reports whether a landed version's head is oid or reaches
808// it. Each version's landing is decided once per snapshot, before
809// anything is walked, and only a landed version's head has its reach
810// read, once per snapshot.
811func (s *Snapshot) underLanded(oid string) bool {
812 for _, n := range s.Changes {
813 for _, v := range n.Record.Versions {
814 if h := HeadOf(v); s.IsLanded(n.ID, v) && (h == oid || s.Reach(h)[oid]) {
815 return true
816 }
817 }
818 }
819 return false
820}
821
822// LandedUnder is the head of every version that has landed, by the first
823// two rules, and that head reaches while main does not, head itself
824// included: work a landing took onto main as one new commit, which main
825// does not reach. They are in the order of the changes' IDs and their
826// versions. Each version's landing is decided first, and head's reach is
827// read only once some version has landed.
828func (s *Snapshot) LandedUnder(head string) []string {
829 var reach map[string]bool
830 var heads []string
831 for _, n := range s.Changes {
832 for _, v := range n.Record.Versions {
833 if !s.IsLanded(n.ID, v) {
834 continue
835 }
836 if reach == nil {
837 reach = s.Reach(head)
838 }
839 if h := HeadOf(v); reach[h] {
840 heads = append(heads, h)
841 }
842 }
843 }
844 return heads
845}
846
847// Node is one head among those Nest stacks: a change's active head or a
848// branch's tip, with the commit time it is ordered by and the name ties
849// are broken by.
850type Node struct {
851 Name string
852 Head string
853 When int64
854}
855
856// Nesting is how a set of nodes stack, by ancestry alone. Each slice is
857// indexed as the nodes were given.
858type Nesting struct {
859 // Parent is the node each is nested under: the nearest node whose head
860 // strictly contains its own, or -1 for none. Where two are equally
861 // near, the one with the later commit is taken.
862 Parent []int
863 // Base is the nearest node whose head its own head strictly contains,
864 // or -1 for main. Where two are equally near, the one nested under it
865 // is taken, and otherwise the one with the later commit.
866 Base []int
867 // Inside is every node whose head strictly contains its own, in the
868 // order given.
869 Inside [][]int
870}
871
872// Nest stacks the nodes: valley pending nests its entries this way, and
873// a stack's layers each sit on their base.
874func (s *Snapshot) Nest(nodes []Node) Nesting {
875 n := len(nodes)
876 in := make([][]bool, n) // in[i][j]: node i's head strictly contains node j's
877 nest := Nesting{Parent: make([]int, n), Base: make([]int, n), Inside: make([][]int, n)}
878 for i := range nodes {
879 in[i] = make([]bool, n)
880 for j := range nodes {
881 in[i][j] = i != j && s.StrictAncestor(nodes[j].Head, nodes[i].Head)
882 if in[i][j] {
883 nest.Inside[j] = append(nest.Inside[j], i)
884 }
885 }
886 }
887 // nearest is the nodes i contains, or that contain i, with none
888 // between, the latest commit first.
889 nearest := func(i int, above bool) []int {
890 var near []int
891 for j := range nodes {
892 outer, inner := j, i
893 if !above {
894 outer, inner = i, j
895 }
896 if !in[outer][inner] {
897 continue
898 }
899 between := false
900 for k := range nodes {
901 between = between || in[outer][k] && in[k][inner]
902 }
903 if !between {
904 near = append(near, j)
905 }
906 }
907 sort.SliceStable(near, func(a, b int) bool {
908 x, y := nodes[near[a]], nodes[near[b]]
909 if x.When != y.When {
910 return x.When > y.When
911 }
912 return x.Name < y.Name
913 })
914 return near
915 }
916 for i := range nodes {
917 nest.Parent[i] = -1
918 if above := nearest(i, true); len(above) > 0 {
919 nest.Parent[i] = above[0]
920 }
921 }
922 for i := range nodes {
923 nest.Base[i] = -1
924 below := nearest(i, false)
925 for _, d := range below {
926 if nest.Parent[d] == i {
927 nest.Base[i] = d
928 break
929 }
930 }
931 if nest.Base[i] == -1 && len(below) > 0 {
932 nest.Base[i] = below[0]
933 }
934 }
935 return nest
936}