| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "bytes" |
| 6 | "context" |
| 7 | "encoding/json" |
| 8 | "fmt" |
| 9 | "io" |
| 10 | "os" |
| 11 | "os/exec" |
| 12 | "path/filepath" |
| 13 | "strconv" |
| 14 | "strings" |
| 15 | "sync" |
| 16 | "testing" |
| 17 | "time" |
| 18 | |
| 19 | "the-valley/change" |
| 20 | "the-valley/rebase" |
| 21 | ) |
| 22 | |
| 23 | // hooked is a fixture whose origin runs the fixture host's rendered hook, |
| 24 | // which grants restack to the principal restacker and request to |
| 25 | // requester. Without the hook, the test is skipped. |
| 26 | func hooked(t *testing.T) *fixture { |
| 27 | t.Helper() |
| 28 | hook := os.Getenv(hookEnv) |
| 29 | if hook == "" { |
| 30 | t.Skip(hookEnv + " names no rendered hook; restack-unit supplies one") |
| 31 | } |
| 32 | withoutIdentity(t) |
| 33 | return newFixture(t, hook) |
| 34 | } |
| 35 | |
| 36 | // pass runs one write pass, as `valley-restacker once`, under a cue that |
| 37 | // composes every policy to the cap given, pushing as the restacker's |
| 38 | // principal. It returns what the pass printed with --json. |
| 39 | func (r *restacker) pass(cap int) *Plan { |
| 40 | r.t.Helper() |
| 41 | schema, floor := fakePolicyCap(r.t, cap) |
| 42 | r.t.Setenv("VALLEY_PRINCIPAL", r.c.principal) |
| 43 | var out, errOut bytes.Buffer |
| 44 | if err := once(context.Background(), append(writeArgs(r.c, schema, floor), "--json"), &out, &errOut); err != nil { |
| 45 | r.t.Fatalf("once: %v\n%s", err, errOut.String()) |
| 46 | } |
| 47 | var p Plan |
| 48 | if err := json.Unmarshal(out.Bytes(), &p); err != nil { |
| 49 | r.t.Fatalf("the pass does not read: %v\n%s", err, out.String()) |
| 50 | } |
| 51 | return &p |
| 52 | } |
| 53 | |
| 54 | // writeArgs is the arguments of a write pass with c's configuration. |
| 55 | func writeArgs(c config, schema, floor string) []string { |
| 56 | return []string{"--repo", c.repo, "--state", c.state, "--principal", c.principal, |
| 57 | "--commit-name", c.commitName, "--commit-email", c.commitEmail, "--schema", schema, "--instance", floor} |
| 58 | } |
| 59 | |
| 60 | // pushAs pushes to origin as a principal, through the hook. |
| 61 | func (f *fixture) pushAs(principal string, args ...string) error { |
| 62 | g := f.as(principal) |
| 63 | cmd := exec.Command("git", append([]string{"push", "--quiet", "origin"}, args...)...) |
| 64 | cmd.Dir, cmd.Env = g.Dir, g.Env |
| 65 | if out, err := cmd.CombinedOutput(); err != nil { |
| 66 | return fmt.Errorf("%v: %s", err, out) |
| 67 | } |
| 68 | return nil |
| 69 | } |
| 70 | |
| 71 | // judge writes an outcome record on origin's side, as the integrator does: |
| 72 | // no push may write one. |
| 73 | func (f *fixture) judge(name, head, decision string) { |
| 74 | f.t.Helper() |
| 75 | line := fmt.Sprintf("%s %s %s %s\n", head, f.at("refs/heads/main"), change.EvidenceFingerprint(nil), decision) |
| 76 | path := filepath.Join(f.t.TempDir(), "outcome") |
| 77 | if err := os.WriteFile(path, []byte(line), 0o644); err != nil { |
| 78 | f.t.Fatal(err) |
| 79 | } |
| 80 | blob := f.onOrigin("hash-object", "-w", path) |
| 81 | f.onOrigin("update-ref", rebase.OutcomePrefix+name, blob) |
| 82 | } |
| 83 | |
| 84 | // recordOf is the change's record on origin. |
| 85 | func (f *fixture) recordOf(id string) *change.Record { |
| 86 | f.t.Helper() |
| 87 | data := f.onOrigin("cat-file", "blob", change.Ref(rebase.Target, id)+":record.json") |
| 88 | r, err := change.Parse([]byte(data + "\n")) |
| 89 | if err != nil { |
| 90 | f.t.Fatal(err) |
| 91 | } |
| 92 | return r |
| 93 | } |
| 94 | |
| 95 | // reportAt is the report a report commit on origin holds. |
| 96 | func (f *fixture) reportAt(commit string) *change.RestackReport { |
| 97 | f.t.Helper() |
| 98 | data := f.onOrigin("cat-file", "blob", commit+":report.json") |
| 99 | r, err := change.ParseRestackReport([]byte(data + "\n")) |
| 100 | if err != nil { |
| 101 | f.t.Fatal(err) |
| 102 | } |
| 103 | return r |
| 104 | } |
| 105 | |
| 106 | // reportOf is the change's latest report on origin, or nil for none. |
| 107 | func (f *fixture) reportOf(id string) *change.RestackReport { |
| 108 | f.t.Helper() |
| 109 | commit := f.at(rebase.RestackPrefix + id) |
| 110 | if commit == "" { |
| 111 | return nil |
| 112 | } |
| 113 | return f.reportAt(commit) |
| 114 | } |
| 115 | |
| 116 | // restackedTo holds that the change's record gained exactly one version, |
| 117 | // v2, uploaded by the restacker at head, keeping the owner, the title and |
| 118 | // the branch, and that its latest report says complete with that version. |
| 119 | func (f *fixture) restackedTo(id, owner, title, branch, head string) { |
| 120 | f.t.Helper() |
| 121 | r := f.recordOf(id) |
| 122 | v := r.ActiveVersion() |
| 123 | if r.State != change.Ready || r.Seq != 2 || len(r.Versions) != 2 || v.N != 2 || rebase.HeadOf(v) != head || |
| 124 | v.Uploader != "restacker" || v.Title != title || v.Branch != branch || r.Owner != owner { |
| 125 | f.t.Errorf("%s's record is not restacked to %s once: %+v", id[:4], short(head), r) |
| 126 | } |
| 127 | rep := f.reportOf(id) |
| 128 | if rep == nil || rep.Result != change.RestackComplete { |
| 129 | f.t.Fatalf("%s's report is %+v", id[:4], rep) |
| 130 | } |
| 131 | for _, l := range rep.Layers { |
| 132 | if l.ChangeID == id && (l.Published == nil || l.Published.Version == nil || *l.Published.Version != 2 || |
| 133 | l.Published.Head != change.HeadPrefix+head) { |
| 134 | f.t.Errorf("%s's report does not say v2 was published at %s: %+v", id[:4], short(head), l.Published) |
| 135 | } |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | // settledState holds that the pass left no journal and kept no object for |
| 140 | // one. |
| 141 | func (r *restacker) settledState() { |
| 142 | r.t.Helper() |
| 143 | if _, err := os.Stat(filepath.Join(r.c.state, journalFile)); err == nil { |
| 144 | r.t.Error("the pass left a journal") |
| 145 | } |
| 146 | if kept := gitOutT(r.t, r.g, "for-each-ref", retainPrefix, "refs/valley-rebase/"); kept != "" { |
| 147 | r.t.Errorf("the pass kept objects:\n%s", kept) |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | // count is how many of the pass's actions are of the write given. |
| 152 | func count(p *Plan, write string) int { |
| 153 | n := 0 |
| 154 | for _, a := range p.Actions { |
| 155 | if a.Write == write { |
| 156 | n++ |
| 157 | } |
| 158 | } |
| 159 | return n |
| 160 | } |
| 161 | |
| 162 | // After a landing, one write pass rebases every ready change onto main |
| 163 | // through the rendered hook, as the restacker's principal: a stack of two |
| 164 | // owners' changes is one family, and each layer descends from the new |
| 165 | // layer below it, with only its own file changed. Each change gains one |
| 166 | // version, uploaded by the restacker, under its owner and title, and a |
| 167 | // report that says complete. A change that conflicts with the landing |
| 168 | // moves nothing and gets a report that says conflict, naming the path, |
| 169 | // and a draft is left alone. The pass lets go of its journal. A second |
| 170 | // pass pushes nothing: the restacked stack is current, and the conflict |
| 171 | // is not tried again while nothing it observed has moved. |
| 172 | func TestAPassRestacksReadyChangesAfterALanding(t *testing.T) { |
| 173 | f := hooked(t) |
| 174 | f.readyAs(idA, "alice", "a", "main", "A's title") |
| 175 | f.readyAs(idB, "bob", "b", "a", "B's title") |
| 176 | f.git("checkout", "--quiet", "-B", "c", "main") |
| 177 | conflicted := f.commit("c's line", "shared.txt") |
| 178 | f.git("push", "--quiet", "origin", "c") |
| 179 | f.writeRecord(idC, &change.Record{ |
| 180 | Schema: change.Schema, ChangeID: idC, Target: rebase.Target, Owner: "carol", State: change.Ready, Seq: 1, Active: 1, |
| 181 | Versions: []change.Version{{N: 1, Head: change.HeadPrefix + conflicted, Title: "C's title", Branch: "c", Uploader: "carol"}}, |
| 182 | }, "", conflicted) |
| 183 | draft := f.readyAs(idE, "alice", "e", "main", "E's title") |
| 184 | f.setState(idE, change.Draft) |
| 185 | f.git("checkout", "--quiet", "main") |
| 186 | f.commit("main's line", "shared.txt") |
| 187 | f.git("push", "--quiet", "origin", "main") |
| 188 | tip := f.at("refs/heads/main") |
| 189 | cRecord := f.at(change.Ref(rebase.Target, idC)) |
| 190 | |
| 191 | r := newRestacker(t, f) |
| 192 | p := r.pass(64) |
| 193 | a, b := f.at("refs/heads/a"), f.at("refs/heads/b") |
| 194 | if parent := f.onOrigin("rev-parse", a+"^"); parent != tip { |
| 195 | t.Errorf("a is on %s, not main's tip %s", short(parent), short(tip)) |
| 196 | } |
| 197 | if parent := f.onOrigin("rev-parse", b+"^"); parent != a { |
| 198 | t.Errorf("b is on %s, not a's new head %s", short(parent), short(a)) |
| 199 | } |
| 200 | for _, d := range [][3]string{{tip, a, "a.txt"}, {a, b, "b.txt"}} { |
| 201 | if changed := f.onOrigin("diff", "--name-only", d[0], d[1]); changed != d[2] { |
| 202 | t.Errorf("%s changes %q, not %s alone", short(d[1]), changed, d[2]) |
| 203 | } |
| 204 | } |
| 205 | f.restackedTo(idA, "alice", "A's title", "a", a) |
| 206 | f.restackedTo(idB, "bob", "B's title", "b", b) |
| 207 | |
| 208 | if f.at("refs/heads/c") != conflicted || f.at(change.Ref(rebase.Target, idC)) != cRecord { |
| 209 | t.Error("the conflicting change moved") |
| 210 | } |
| 211 | if rep := f.reportOf(idC); rep == nil || rep.Result != change.RestackConflict || rep.Failing == nil || *rep.Failing != idC || |
| 212 | len(rep.Conflicts) != 1 || rep.Conflicts[0] != "shared.txt" { |
| 213 | t.Errorf("c's report is %+v", rep) |
| 214 | } |
| 215 | if f.at("refs/heads/e") != draft || f.recordOf(idE).Seq != 2 || f.reportOf(idE) != nil { |
| 216 | t.Error("the draft was touched") |
| 217 | } |
| 218 | if count(p, "branches") != 1 || count(p, "version") != 2 || count(p, "report") != 3 { |
| 219 | t.Errorf("the pass pushed %+v", p.Actions) |
| 220 | } |
| 221 | r.settledState() |
| 222 | |
| 223 | before := f.refs() |
| 224 | p = r.pass(64) |
| 225 | if len(p.Actions) != 0 || f.refs() != before { |
| 226 | t.Errorf("a second pass pushed %+v", p.Actions) |
| 227 | } |
| 228 | for _, fp := range p.Families { |
| 229 | if fp.Layers[0].ID == idC && fp.Writes != nil && len(fp.Writes.Reports) == 1 && !fp.Writes.Reports[0].Unchanged { |
| 230 | t.Errorf("the second pass rebased the conflict again: %+v", fp.Writes) |
| 231 | } |
| 232 | } |
| 233 | r.settledState() |
| 234 | } |
| 235 | |
| 236 | // A related request that might still land holds its family: the pass |
| 237 | // moves no branch and adds no version, and its report says blocked, |
| 238 | // naming the request. Once the integrator's outcome for the request is a |
| 239 | // current stale, the next pass restacks the change and leaves the |
| 240 | // request as it was. |
| 241 | func TestARequestHoldsItsFamilyUntilACurrentStaleReleasesIt(t *testing.T) { |
| 242 | f := hooked(t) |
| 243 | head := f.readyAs(idA, "alice", "a", "main", "A's title") |
| 244 | request := rebase.RequestPrefix + change.RequestName(idA) |
| 245 | if err := f.pushAs("requester", head+":"+request); err != nil { |
| 246 | t.Fatal(err) |
| 247 | } |
| 248 | f.moveMain() |
| 249 | record := f.at(change.Ref(rebase.Target, idA)) |
| 250 | |
| 251 | r := newRestacker(t, f) |
| 252 | r.pass(64) |
| 253 | if f.at("refs/heads/a") != head || f.at(change.Ref(rebase.Target, idA)) != record { |
| 254 | t.Fatal("the pass moved a change a request holds") |
| 255 | } |
| 256 | rep := f.reportOf(idA) |
| 257 | if rep == nil || rep.Result != change.RestackBlocked || len(rep.Requests) != 1 || rep.Requests[0].Ref != request || |
| 258 | rep.Refusal == nil || !strings.Contains(*rep.Refusal, "might still land") { |
| 259 | t.Fatalf("a's report is %+v", rep) |
| 260 | } |
| 261 | |
| 262 | f.judge(change.RequestName(idA), head, "stale") |
| 263 | r.pass(64) |
| 264 | f.restackedTo(idA, "alice", "A's title", "a", f.at("refs/heads/a")) |
| 265 | if f.at(request) != head { |
| 266 | t.Error("the restacker moved the request") |
| 267 | } |
| 268 | r.settledState() |
| 269 | } |
| 270 | |
| 271 | // A pass that ended after any step of its journal is finished by the |
| 272 | // next: each write already on origin is not pushed again, each change has |
| 273 | // exactly one new version, every report says complete, and the journal |
| 274 | // is let go. |
| 275 | func TestAPassFinishesAJournalLeftAtAnyStep(t *testing.T) { |
| 276 | steps := []string{"kept", "branches pushed", "lower version added", "both versions added", "one report pushed"} |
| 277 | for n, step := range steps { |
| 278 | t.Run(step, func(t *testing.T) { |
| 279 | f := hooked(t) |
| 280 | f.readyAs(idA, "alice", "a", "main", "A's title") |
| 281 | f.readyAs(idB, "bob", "b", "a", "B's title") |
| 282 | f.moveMain() |
| 283 | t.Setenv("VALLEY_PRINCIPAL", "restacker") |
| 284 | r := newRestacker(t, f) |
| 285 | fam := of(t, r.journal(), idA) |
| 286 | ctx := context.Background() |
| 287 | made := []func() bool{ |
| 288 | func() bool { push, _ := fam.Branches.Push(ctx, r.g); return push == rebase.Pushed }, |
| 289 | func() bool { return fam.Versions[0].Push(ctx, r.g).Err == nil }, |
| 290 | func() bool { return fam.Versions[1].Push(ctx, r.g).Err == nil }, |
| 291 | func() bool { return fam.Reports[0].Pending.Push(ctx, r.g).Push == rebase.Pushed }, |
| 292 | } |
| 293 | for i := 0; i < n; i++ { |
| 294 | if !made[i]() { |
| 295 | t.Fatalf("step %d of the journal was not pushed", i+1) |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | p := r.pass(64) |
| 300 | f.restackedTo(idA, "alice", "A's title", "a", fam.Branches.Updates[0].New) |
| 301 | f.restackedTo(idB, "bob", "B's title", "b", fam.Branches.Updates[1].New) |
| 302 | if want := min(n, 1); count(p, "branches") != 1-want { |
| 303 | t.Errorf("the pass pushed the branches %d times, after %s", count(p, "branches"), step) |
| 304 | } |
| 305 | if want := 2 - min(max(n-1, 0), 2); count(p, "version") != want { |
| 306 | t.Errorf("the pass added %d versions, after %s, where %d were left", count(p, "version"), step, want) |
| 307 | } |
| 308 | if p.Recovery == nil || p.Pending != nil { |
| 309 | t.Errorf("the journal was not found, or is still open: %+v", p.Pending) |
| 310 | } |
| 311 | r.settledState() |
| 312 | }) |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | // An owner who pushes to a branch the restacker has moved stops that |
| 317 | // change's version for good: the pass adds the version below it, adds |
| 318 | // none to the moved change, and reports partial for both, with each |
| 319 | // version origin holds. The moved change's record stays as its owner left |
| 320 | // it, and the plan that follows in the same pass holds it, since its |
| 321 | // branch is not at its version's head. |
| 322 | func TestAnOwnerWhoMovesARestackedBranchStopsItsVersion(t *testing.T) { |
| 323 | f := hooked(t) |
| 324 | f.readyAs(idA, "alice", "a", "main", "A's title") |
| 325 | f.readyAs(idB, "bob", "b", "a", "B's title") |
| 326 | f.moveMain() |
| 327 | t.Setenv("VALLEY_PRINCIPAL", "restacker") |
| 328 | r := newRestacker(t, f) |
| 329 | fam := of(t, r.journal(), idA) |
| 330 | if push, _ := fam.Branches.Push(context.Background(), r.g); push != rebase.Pushed { |
| 331 | t.Fatal("the branches were not pushed") |
| 332 | } |
| 333 | f.ownerPushes("b") |
| 334 | bRecord := f.at(change.Ref(rebase.Target, idB)) |
| 335 | |
| 336 | p := r.pass(64) |
| 337 | for _, fp := range p.Families { |
| 338 | if fp.Layers[0].ID == idB && fp.Action != hold { |
| 339 | t.Errorf("once the journal is let go, the plan does not hold b, whose branch is not at its version's head: %+v", fp) |
| 340 | } |
| 341 | } |
| 342 | if got := f.recordOf(idA); got.Seq != 2 || rebase.HeadOf(got.ActiveVersion()) != fam.Branches.Updates[0].New { |
| 343 | t.Errorf("a's version was not added: %+v", got) |
| 344 | } |
| 345 | if f.at(change.Ref(rebase.Target, idB)) != bRecord { |
| 346 | t.Error("a version was added to the change its owner moved") |
| 347 | } |
| 348 | // The latest report or one before it, since a later plan in the same |
| 349 | // pass may report on b again, says partial. |
| 350 | partial := false |
| 351 | for commit := f.at(rebase.RestackPrefix + idB); commit != ""; commit = f.parentOf(commit) { |
| 352 | rep := f.reportAt(commit) |
| 353 | if rep.Result != change.RestackPartial { |
| 354 | continue |
| 355 | } |
| 356 | partial = true |
| 357 | for _, l := range rep.Layers { |
| 358 | switch { |
| 359 | case l.ChangeID == idA && (l.Published == nil || l.Published.Version == nil || *l.Published.Version != 2): |
| 360 | t.Errorf("the partial report does not say a's v2 was added: %+v", l.Published) |
| 361 | case l.ChangeID == idB && (l.Published == nil || l.Published.Version != nil): |
| 362 | t.Errorf("the partial report says b's version was added: %+v", l.Published) |
| 363 | } |
| 364 | } |
| 365 | if rep.Refusal == nil || !strings.Contains(*rep.Refusal, "its author moved it") { |
| 366 | t.Errorf("the partial report does not say why: %v", rep.Refusal) |
| 367 | } |
| 368 | } |
| 369 | if !partial { |
| 370 | t.Error("no report of b says partial") |
| 371 | } |
| 372 | r.settledState() |
| 373 | } |
| 374 | |
| 375 | // parentOf is a commit's first parent on origin, or "" for none. |
| 376 | func (f *fixture) parentOf(commit string) string { |
| 377 | cmd := exec.Command("git", "rev-parse", "--verify", "--quiet", commit+"^") |
| 378 | cmd.Dir, cmd.Env = f.origin, f.env |
| 379 | out, _ := cmd.Output() |
| 380 | return strings.TrimSpace(string(out)) |
| 381 | } |
| 382 | |
| 383 | // A request filed between a family's branch push and its versions pauses |
| 384 | // the versions: the pass reports partial, adds none, and keeps the |
| 385 | // journal open, so it starts no new operation. Once the request's outcome |
| 386 | // is a current stale, the next pass adds the version, reports complete, |
| 387 | // and lets go of the journal. |
| 388 | func TestARequestBetweenPhasesPausesTheVersions(t *testing.T) { |
| 389 | f := hooked(t) |
| 390 | old := f.readyAs(idA, "alice", "a", "main", "A's title") |
| 391 | f.moveMain() |
| 392 | t.Setenv("VALLEY_PRINCIPAL", "restacker") |
| 393 | r := newRestacker(t, f) |
| 394 | fam := of(t, r.journal(), idA) |
| 395 | if push, _ := fam.Branches.Push(context.Background(), r.g); push != rebase.Pushed { |
| 396 | t.Fatal("the branches were not pushed") |
| 397 | } |
| 398 | if err := f.pushAs("requester", old+":"+rebase.RequestPrefix+"zz-old"); err != nil { |
| 399 | t.Fatal(err) |
| 400 | } |
| 401 | record := f.at(change.Ref(rebase.Target, idA)) |
| 402 | |
| 403 | p := r.pass(64) |
| 404 | if f.at(change.Ref(rebase.Target, idA)) != record || p.Pending == nil { |
| 405 | t.Fatalf("the paused version was added, or the journal let go: %+v", p.Pending) |
| 406 | } |
| 407 | if _, err := os.Stat(filepath.Join(r.c.state, journalFile)); err != nil { |
| 408 | t.Errorf("the open journal is gone: %v", err) |
| 409 | } |
| 410 | rep := f.reportOf(idA) |
| 411 | if rep == nil || rep.Result != change.RestackPartial || rep.Refusal == nil || !strings.Contains(*rep.Refusal, "zz-old might still land") { |
| 412 | t.Fatalf("a's report is %+v", rep) |
| 413 | } |
| 414 | if p = r.pass(64); len(p.Actions) != 0 || p.Pending == nil { |
| 415 | t.Errorf("a pass with the request still open pushed %+v", p.Actions) |
| 416 | } |
| 417 | |
| 418 | f.judge("zz-old", old, "stale") |
| 419 | p = r.pass(64) |
| 420 | if p.Pending != nil { |
| 421 | t.Errorf("the journal is still open: %+v", p.Pending) |
| 422 | } |
| 423 | f.restackedTo(idA, "alice", "A's title", "a", fam.Branches.Updates[0].New) |
| 424 | r.settledState() |
| 425 | } |
| 426 | |
| 427 | // A report of what did happen is kept in the journal before it is pushed, |
| 428 | // and stays there until a read of origin shows it. Here an owner moves a |
| 429 | // restacked branch, so the version above stops and the family's reports |
| 430 | // say partial. When origin refuses the push of one of them, the pass |
| 431 | // leaves the journal open with that report in it, and the next pass |
| 432 | // pushes it. When origin takes the push and its answer is lost, the next |
| 433 | // read finds it there, and it is not pushed again. |
| 434 | func TestAReportOfWhatHappenedOutlivesAFailedPush(t *testing.T) { |
| 435 | for _, failure := range []string{"refused", "answer lost"} { |
| 436 | t.Run(failure, func(t *testing.T) { |
| 437 | f := hooked(t) |
| 438 | f.readyAs(idA, "alice", "a", "main", "A's title") |
| 439 | f.readyAs(idB, "bob", "b", "a", "B's title") |
| 440 | f.moveMain() |
| 441 | t.Setenv("VALLEY_PRINCIPAL", "restacker") |
| 442 | r := newRestacker(t, f) |
| 443 | fam := of(t, r.journal(), idA) |
| 444 | if push, _ := fam.Branches.Push(context.Background(), r.g); push != rebase.Pushed { |
| 445 | t.Fatal("the branches were not pushed") |
| 446 | } |
| 447 | f.ownerPushes("b") |
| 448 | ref := rebase.RestackPrefix + idB |
| 449 | lift := func() {} |
| 450 | if failure == "refused" { |
| 451 | lift = f.refuseOnOrigin(ref) |
| 452 | } else { |
| 453 | r.loseAnswers(ref) |
| 454 | } |
| 455 | |
| 456 | p := r.pass(64) |
| 457 | var pushes []string |
| 458 | for _, a := range p.Actions { |
| 459 | if a.Write == "replacement" && a.ID == idB { |
| 460 | pushes = append(pushes, a.Result) |
| 461 | } |
| 462 | } |
| 463 | if failure == "answer lost" { |
| 464 | if strings.Join(pushes, " ") != "unknown" { |
| 465 | t.Errorf("b's report of what happened was pushed as %v, where once, its answer lost, is expected", pushes) |
| 466 | } |
| 467 | if !partialOf(f, idB) { |
| 468 | t.Error("no report of b on origin says partial") |
| 469 | } |
| 470 | r.settledState() |
| 471 | return |
| 472 | } |
| 473 | if len(pushes) == 0 || strings.Trim(strings.Join(pushes, " "), "refused ") != "" { |
| 474 | t.Errorf("b's report of what happened was pushed as %v", pushes) |
| 475 | } |
| 476 | if f.reportOf(idB) != nil { |
| 477 | t.Fatal("origin holds a report of b it refused") |
| 478 | } |
| 479 | j, err := loadJournal(r.c.state, r.c.binding()) |
| 480 | if err != nil || j == nil || p.Pending == nil { |
| 481 | t.Fatalf("the pass let go of the journal that holds b's report: %v", err) |
| 482 | } |
| 483 | kept := false |
| 484 | for _, rep := range of(t, j, idA).Replacements { |
| 485 | kept = kept || rep.Pending.ID == idB && rep.Pending.Report.Result == change.RestackPartial |
| 486 | } |
| 487 | if !kept { |
| 488 | t.Fatalf("the journal does not hold b's report of what happened: %+v", of(t, j, idA).Replacements) |
| 489 | } |
| 490 | |
| 491 | lift() |
| 492 | r.pass(64) |
| 493 | if !partialOf(f, idB) { |
| 494 | t.Error("no report of b on origin says partial once origin takes it") |
| 495 | } |
| 496 | r.settledState() |
| 497 | }) |
| 498 | } |
| 499 | } |
| 500 | |
| 501 | // partialOf reports whether the change's latest report on origin, or one |
| 502 | // before it, says partial: a's version added, the change's own not, since |
| 503 | // its author moved it. A later plan in the same pass may report on the |
| 504 | // change again. |
| 505 | func partialOf(f *fixture, id string) bool { |
| 506 | f.t.Helper() |
| 507 | for commit := f.at(rebase.RestackPrefix + id); commit != ""; commit = f.parentOf(commit) { |
| 508 | rep := f.reportAt(commit) |
| 509 | if rep.Result != change.RestackPartial || rep.Refusal == nil || !strings.Contains(*rep.Refusal, "its author moved it") { |
| 510 | continue |
| 511 | } |
| 512 | for _, l := range rep.Layers { |
| 513 | if l.Published == nil || (l.ChangeID == idA) != (l.Published.Version != nil) { |
| 514 | f.t.Errorf("the partial report of %s does not say what was published: %+v", id[:4], l) |
| 515 | } |
| 516 | } |
| 517 | return true |
| 518 | } |
| 519 | return false |
| 520 | } |
| 521 | |
| 522 | // refuseOnOrigin has origin refuse every push that moves the ref, ahead |
| 523 | // of its own hook, until the function it returns is called. |
| 524 | func (f *fixture) refuseOnOrigin(ref string) (lift func()) { |
| 525 | f.t.Helper() |
| 526 | hook := filepath.Join(f.origin, "hooks", "pre-receive") |
| 527 | own := hook + ".own" |
| 528 | if err := os.Rename(hook, own); err != nil { |
| 529 | f.t.Fatal(err) |
| 530 | } |
| 531 | script := fmt.Sprintf("#!/bin/sh\nlines=$(cat)\n"+ |
| 532 | "if printf '%%s\\n' \"$lines\" | grep -q ' %s$'; then echo 'origin refuses %s for the test' >&2; exit 1; fi\n"+ |
| 533 | "printf '%%s\\n' \"$lines\" | exec '%s'\n", ref, ref, own) |
| 534 | if err := os.WriteFile(hook, []byte(script), 0o755); err != nil { |
| 535 | f.t.Fatal(err) |
| 536 | } |
| 537 | return func() { |
| 538 | if err := os.Rename(own, hook); err != nil { |
| 539 | f.t.Fatal(err) |
| 540 | } |
| 541 | } |
| 542 | } |
| 543 | |
| 544 | // dropEnv names the ref whose pushes lossyReceivePack loses the answer to. |
| 545 | const dropEnv = "RESTACK_TEST_DROP" |
| 546 | |
| 547 | // loseAnswers has origin's answer lost to every push of the restacker's |
| 548 | // that moves the ref: origin takes the push, and the pass hears nothing. |
| 549 | func (r *restacker) loseAnswers(ref string) { |
| 550 | r.t.Helper() |
| 551 | self, err := os.Executable() |
| 552 | if err != nil { |
| 553 | r.t.Fatal(err) |
| 554 | } |
| 555 | path := filepath.Join(r.t.TempDir(), "lossy-receive-pack") |
| 556 | script := fmt.Sprintf("#!/bin/sh\n%s=drop-acks %s='%s' exec '%s' \"$@\"\n", roleEnv, dropEnv, ref, self) |
| 557 | if err := os.WriteFile(path, []byte(script), 0o755); err != nil { |
| 558 | r.t.Fatal(err) |
| 559 | } |
| 560 | gitOutT(r.t, r.g, "config", "remote.origin.receivepack", path) |
| 561 | } |
| 562 | |
| 563 | // lossyReceivePack is git receive-pack less its answer to a push that |
| 564 | // moves the ref named. It runs the real receive-pack, which takes the |
| 565 | // push, and passes its report on without the status of any ref when one |
| 566 | // of them is that ref, as when origin's answer is lost. The side-band |
| 567 | // capabilities are taken out of its advertisement, so the report comes as |
| 568 | // plain pkt-lines. The rebase engine's tests drop every answer the same |
| 569 | // way. |
| 570 | func lossyReceivePack(ref string, args []string) int { |
| 571 | cmd := exec.Command("git", append([]string{"receive-pack"}, args...)...) |
| 572 | cmd.Stdin, cmd.Stderr = os.Stdin, os.Stderr |
| 573 | out, err := cmd.StdoutPipe() |
| 574 | if err != nil || cmd.Start() != nil { |
| 575 | return 1 |
| 576 | } |
| 577 | r := bufio.NewReader(out) |
| 578 | advertised := false |
| 579 | var status [][]byte |
| 580 | for { |
| 581 | p, err := readPkt(r) |
| 582 | if err != nil { |
| 583 | break |
| 584 | } |
| 585 | switch { |
| 586 | case !advertised && p == nil: |
| 587 | advertised = true |
| 588 | case !advertised: |
| 589 | if refs, caps, ok := bytes.Cut(p, []byte{0}); ok { |
| 590 | var kept []string |
| 591 | for _, c := range strings.Fields(string(caps)) { |
| 592 | if !strings.HasPrefix(c, "side-band") { |
| 593 | kept = append(kept, c) |
| 594 | } |
| 595 | } |
| 596 | p = []byte(string(refs) + "\x00" + strings.Join(kept, " ") + "\n") |
| 597 | } |
| 598 | case bytes.HasPrefix(p, []byte("ok ")) || bytes.HasPrefix(p, []byte("ng ")) || bytes.HasPrefix(p, []byte("option ")): |
| 599 | status = append(status, p) |
| 600 | continue |
| 601 | case p == nil: |
| 602 | lost := false |
| 603 | for _, line := range status { |
| 604 | if fields := strings.Fields(string(line)); len(fields) > 1 && fields[1] == ref { |
| 605 | lost = true |
| 606 | } |
| 607 | } |
| 608 | for _, line := range status { |
| 609 | if !lost { |
| 610 | writePkt(line) |
| 611 | } |
| 612 | } |
| 613 | status = nil |
| 614 | } |
| 615 | writePkt(p) |
| 616 | } |
| 617 | if cmd.Wait() != nil { |
| 618 | return 1 |
| 619 | } |
| 620 | return 0 |
| 621 | } |
| 622 | |
| 623 | // readPkt reads one pkt-line, nil for a flush. |
| 624 | func readPkt(r *bufio.Reader) ([]byte, error) { |
| 625 | var size [4]byte |
| 626 | if _, err := io.ReadFull(r, size[:]); err != nil { |
| 627 | return nil, err |
| 628 | } |
| 629 | n, err := strconv.ParseUint(string(size[:]), 16, 16) |
| 630 | if err != nil || n < 4 { |
| 631 | return nil, err |
| 632 | } |
| 633 | p := make([]byte, n-4) |
| 634 | _, err = io.ReadFull(r, p) |
| 635 | return p, err |
| 636 | } |
| 637 | |
| 638 | // writePkt writes one pkt-line to stdout, nil as a flush. |
| 639 | func writePkt(p []byte) { |
| 640 | if p == nil { |
| 641 | io.WriteString(os.Stdout, "0000") |
| 642 | return |
| 643 | } |
| 644 | fmt.Fprintf(os.Stdout, "%04x%s", len(p)+4, p) |
| 645 | } |
| 646 | |
| 647 | // The project's cap on automatic versions holds: with a cap of 1, the |
| 648 | // first landing's restack adds the change's one automatic version, and |
| 649 | // after a second landing the pass holds the change and reports blocked, |
| 650 | // saying the cap is why. |
| 651 | func TestAPassHonoursTheCap(t *testing.T) { |
| 652 | f := hooked(t) |
| 653 | f.readyAs(idA, "alice", "a", "main", "A's title") |
| 654 | f.moveMain() |
| 655 | r := newRestacker(t, f) |
| 656 | r.pass(1) |
| 657 | f.restackedTo(idA, "alice", "A's title", "a", f.at("refs/heads/a")) |
| 658 | head, record := f.at("refs/heads/a"), f.at(change.Ref(rebase.Target, idA)) |
| 659 | |
| 660 | f.git("checkout", "--quiet", "main") |
| 661 | f.commit("main moves again", "again.txt") |
| 662 | f.git("push", "--quiet", "origin", "main") |
| 663 | r.pass(1) |
| 664 | if f.at("refs/heads/a") != head || f.at(change.Ref(rebase.Target, idA)) != record { |
| 665 | t.Fatal("the pass restacked a change over the cap") |
| 666 | } |
| 667 | if rep := f.reportOf(idA); rep == nil || rep.Result != change.RestackBlocked || rep.Refusal == nil || |
| 668 | !strings.Contains(*rep.Refusal, "over the cap of 1") { |
| 669 | t.Errorf("a's report is %+v", rep) |
| 670 | } |
| 671 | r.settledState() |
| 672 | } |
| 673 | |
| 674 | // run reconciles at once and then on its interval, without being told |
| 675 | // anything has moved: after a landing it restacks a ready change, and a |
| 676 | // change readied later, off an older main, is restacked with no landing |
| 677 | // between. Stopped, it returns. |
| 678 | func TestRunConverges(t *testing.T) { |
| 679 | f := hooked(t) |
| 680 | base := f.at("refs/heads/main") |
| 681 | f.readyAs(idA, "alice", "a", "main", "A's title") |
| 682 | f.moveMain() |
| 683 | r := newRestacker(t, f) |
| 684 | schema, floor := fakePolicyCap(t, 64) |
| 685 | t.Setenv("VALLEY_PRINCIPAL", r.c.principal) |
| 686 | ctx, cancel := context.WithCancel(context.Background()) |
| 687 | done := make(chan error, 1) |
| 688 | var out, errOut syncBuffer |
| 689 | go func() { |
| 690 | done <- loop(ctx, append(writeArgs(r.c, schema, floor), "--interval", "200ms"), &out, &errOut) |
| 691 | }() |
| 692 | // A pass prints what it pushed once it ends. |
| 693 | restacked := func(id string) { |
| 694 | t.Helper() |
| 695 | for deadline := time.Now().Add(60 * time.Second); time.Now().Before(deadline); time.Sleep(100 * time.Millisecond) { |
| 696 | if strings.Contains(out.String(), "report "+id+": pushed") { |
| 697 | return |
| 698 | } |
| 699 | } |
| 700 | cancel() |
| 701 | t.Fatalf("run did not restack %s:\n%s\n%s", id[:4], out.String(), errOut.String()) |
| 702 | } |
| 703 | restacked(idA) |
| 704 | f.readyAs(idB, "bob", "b", base, "B's title") |
| 705 | restacked(idB) |
| 706 | cancel() |
| 707 | select { |
| 708 | case err := <-done: |
| 709 | if err != nil { |
| 710 | t.Errorf("run ended with %v", err) |
| 711 | } |
| 712 | case <-time.After(30 * time.Second): |
| 713 | t.Fatal("run did not end once stopped") |
| 714 | } |
| 715 | f.restackedTo(idA, "alice", "A's title", "a", f.at("refs/heads/a")) |
| 716 | f.restackedTo(idB, "bob", "B's title", "b", f.at("refs/heads/b")) |
| 717 | } |
| 718 | |
| 719 | // A pass's wait after failures doubles from the interval, up to the |
| 720 | // bound. |
| 721 | func TestBackoffIsBounded(t *testing.T) { |
| 722 | for failures, want := range []time.Duration{15 * time.Second, 30 * time.Second, time.Minute, 2 * time.Minute, 4 * time.Minute, maxBackoff, maxBackoff} { |
| 723 | if got := backoff(15*time.Second, failures); got != want { |
| 724 | t.Errorf("after %d failures, run waits %v, not %v", failures, got, want) |
| 725 | } |
| 726 | } |
| 727 | } |
| 728 | |
| 729 | // syncBuffer is a buffer one goroutine writes while another reads it. |
| 730 | type syncBuffer struct { |
| 731 | mu sync.Mutex |
| 732 | buf bytes.Buffer |
| 733 | } |
| 734 | |
| 735 | func (b *syncBuffer) Write(p []byte) (int, error) { |
| 736 | b.mu.Lock() |
| 737 | defer b.mu.Unlock() |
| 738 | return b.buf.Write(p) |
| 739 | } |
| 740 | |
| 741 | func (b *syncBuffer) String() string { |
| 742 | b.mu.Lock() |
| 743 | defer b.mu.Unlock() |
| 744 | return b.buf.String() |
| 745 | } |