gunk-dev/the-valley

snapshot.go

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