gunk-dev/the-valley

snapshot.go

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