| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/sha256" |
| 7 | "encoding/base64" |
| 8 | "encoding/hex" |
| 9 | "encoding/json" |
| 10 | "fmt" |
| 11 | "os" |
| 12 | "path/filepath" |
| 13 | "reflect" |
| 14 | "regexp" |
| 15 | "sort" |
| 16 | "strings" |
| 17 | "testing" |
| 18 | "time" |
| 19 | |
| 20 | "the-valley/change" |
| 21 | "the-valley/rebase" |
| 22 | ) |
| 23 | |
| 24 | // id is the nth of a run of change IDs, 32 letters from k to z. |
| 25 | func id(n int) string { |
| 26 | var b strings.Builder |
| 27 | for i := 0; i < 32; i++ { |
| 28 | b.WriteByte(byte('k' + (n>>(i%8*2))%16)) |
| 29 | } |
| 30 | return b.String() |
| 31 | } |
| 32 | |
| 33 | // oversized is an observation of a conflicted family that holds more than |
| 34 | // a report may in every way: 70 recorded changes, 150 conflict paths with |
| 35 | // unusual names among them, 70 blocking requests, one of whose refs is |
| 36 | // too long and one of whose names is no branch name, and a refusal longer |
| 37 | // than a report holds, with control characters in it. |
| 38 | func oversized() Observation { |
| 39 | o := Observation{Action: restack, Result: change.RestackConflict, Conflicts: []string{}, Requests: []RequestPlan{}} |
| 40 | for i := 0; i < 70; i++ { |
| 41 | o.Layers = append(o.Layers, ObservedLayer{ |
| 42 | Name: id(i)[:6], ID: id(i), Branch: fmt.Sprintf("stack/%02d", i), BranchTip: strings.Repeat("1", 40), |
| 43 | Record: strings.Repeat("2", 40), Version: 1, Head: strings.Repeat("1", 40), State: "ready", |
| 44 | }) |
| 45 | } |
| 46 | o.Failing = id(40) |
| 47 | o.Conflicts = append(o.Conflicts, "line\nbreak.txt", "bell\x07.txt", "latin1-\xe9.txt", strings.Repeat("long/", 220)+"x") |
| 48 | for i := len(o.Conflicts); i < 150; i++ { |
| 49 | o.Conflicts = append(o.Conflicts, fmt.Sprintf("src/file-%03d.go", i)) |
| 50 | } |
| 51 | o.Requests = append(o.Requests, |
| 52 | RequestPlan{Name: strings.Repeat("r", 300), Head: strings.Repeat("3", 40)}, |
| 53 | RequestPlan{Name: "no..branch", Head: strings.Repeat("3", 40)}) |
| 54 | for i := 0; i < 68; i++ { |
| 55 | o.Requests = append(o.Requests, RequestPlan{Name: fmt.Sprintf("request-%02d", i), Head: strings.Repeat("3", 40)}) |
| 56 | } |
| 57 | o.Refusal = strings.Repeat("the layer conflicts\nwith main\t", 150) |
| 58 | return o |
| 59 | } |
| 60 | |
| 61 | // A report of an observation that holds more than the format allows is a |
| 62 | // fallback that the format takes: the change's own layer and the failing |
| 63 | // one, the conflict paths and requests that fit, up to the format's |
| 64 | // count, and a refusal cut to fit, free of control characters, ending |
| 65 | // with what it leaves out and the file that keeps the whole observation, |
| 66 | // named by its digest. |
| 67 | func TestAReportFallsBackWithinEveryBound(t *testing.T) { |
| 68 | o := oversized() |
| 69 | self := id(3) |
| 70 | r, omitted, err := bound(fullReport("op-1", strings.Repeat("4", 40), self, o, nil), o.Digest()) |
| 71 | if err != nil { |
| 72 | t.Fatal(err) |
| 73 | } |
| 74 | data, err := change.EncodeRestackReport(r) |
| 75 | if err != nil { |
| 76 | t.Fatal(err) |
| 77 | } |
| 78 | if _, err := change.ParseRestackReport(data); err != nil || len(data) > change.MaxReportBlob { |
| 79 | t.Fatalf("the fallback is %d bytes and reads as %v", len(data), err) |
| 80 | } |
| 81 | if len(r.Layers) != 2 || r.Layers[0].ChangeID != self || r.Layers[1].ChangeID != o.Failing { |
| 82 | t.Errorf("the fallback keeps the layers %+v", r.Layers) |
| 83 | } |
| 84 | if len(r.Conflicts) != change.MaxConflictPaths || r.Conflicts[0] != "src/file-004.go" { |
| 85 | t.Errorf("the fallback keeps %d conflict paths, first %q", len(r.Conflicts), r.Conflicts[0]) |
| 86 | } |
| 87 | if len(r.Requests) != 64 || r.Requests[0].Ref != rebase.RequestPrefix+"request-00" { |
| 88 | t.Errorf("the fallback keeps %d requests, first %+v", len(r.Requests), r.Requests[0]) |
| 89 | } |
| 90 | if r.Refusal == nil || len(*r.Refusal) > change.MaxRefusal || !strings.Contains(*r.Refusal, "observations/"+o.Digest()+".json") || |
| 91 | !strings.HasPrefix(*r.Refusal, "the layer conflicts with main the layer") { |
| 92 | t.Errorf("the fallback's refusal is %q", *r.Refusal) |
| 93 | } |
| 94 | for _, want := range []string{"68 of the family's 70 recorded changes", "50 of its 150 conflict paths", "6 of its 70 blocking requests", "the end of its refusal"} { |
| 95 | if !strings.Contains(strings.Join(omitted, "; "), want) { |
| 96 | t.Errorf("the fallback does not say it leaves out %s: %v", want, omitted) |
| 97 | } |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | // A report whose every field fits on its own, and that holds more than 64 |
| 102 | // KiB in all, sheds its conflict paths, then its requests, then the |
| 103 | // layers it does not need, until it fits. |
| 104 | func TestAReportTooLargeInAllSheds(t *testing.T) { |
| 105 | o := Observation{Action: restack, Result: change.RestackConflict, Requests: []RequestPlan{}} |
| 106 | for i := 0; i < 64; i++ { |
| 107 | o.Layers = append(o.Layers, ObservedLayer{ |
| 108 | Name: id(i)[:6], ID: id(i), Branch: fmt.Sprintf("%02d/", i) + strings.Repeat("b", 900), BranchTip: strings.Repeat("1", 40), |
| 109 | Record: strings.Repeat("2", 40), Version: 1, Head: strings.Repeat("1", 40), State: "ready", |
| 110 | }) |
| 111 | } |
| 112 | o.Failing = id(0) |
| 113 | for i := 0; i < 100; i++ { |
| 114 | o.Conflicts = append(o.Conflicts, fmt.Sprintf("%03d/", i)+strings.Repeat("c", 1000)) |
| 115 | } |
| 116 | full := fullReport("op-1", strings.Repeat("4", 40), id(9), o, nil) |
| 117 | if err := full.Check(); err != nil { |
| 118 | t.Fatalf("each field should fit on its own: %v", err) |
| 119 | } |
| 120 | r, omitted, err := bound(full, o.Digest()) |
| 121 | if err != nil { |
| 122 | t.Fatal(err) |
| 123 | } |
| 124 | data, err := change.EncodeRestackReport(r) |
| 125 | if err != nil || len(data) > change.MaxReportBlob { |
| 126 | t.Fatalf("the fallback is %d bytes: %v", len(data), err) |
| 127 | } |
| 128 | if len(r.Conflicts) != 0 || len(r.Layers) != 2 || !strings.Contains(strings.Join(omitted, "; "), "the 100 conflict paths left") { |
| 129 | t.Errorf("the fallback keeps %d paths and %d layers, leaving out %v", len(r.Conflicts), len(r.Layers), omitted) |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | // Two reports are the same when their observations and result are, |
| 134 | // whatever operation wrote each. Two fallbacks that show the same are told |
| 135 | // apart by the digest of what they leave out. |
| 136 | func TestReportsAreTheSameByWhatTheySay(t *testing.T) { |
| 137 | o := oversized() |
| 138 | tip := strings.Repeat("4", 40) |
| 139 | a, _, err := bound(fullReport("op-1", tip, id(3), o, nil), o.Digest()) |
| 140 | if err != nil { |
| 141 | t.Fatal(err) |
| 142 | } |
| 143 | b, _, _ := bound(fullReport("op-2", tip, id(3), o, nil), o.Digest()) |
| 144 | if !sameReport(a, b) { |
| 145 | t.Error("the same observation written by two operations is not the same report") |
| 146 | } |
| 147 | o.Conflicts[149] = "src/another.go" |
| 148 | c, _, _ := bound(fullReport("op-2", tip, id(3), o, nil), o.Digest()) |
| 149 | if sameReport(a, c) { |
| 150 | t.Error("two fallbacks of different observations are the same report") |
| 151 | } |
| 152 | if strings.Join(a.Conflicts, " ") != strings.Join(c.Conflicts, " ") { |
| 153 | t.Fatal("the test's fallbacks should show the same conflict paths") |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | // conflictOnManyPaths readies a change that conflicts with main on 122 |
| 158 | // paths, more than a report holds, two of them with control characters |
| 159 | // in their names. It returns the paths. |
| 160 | func (f *fixture) conflictOnManyPaths() []string { |
| 161 | f.t.Helper() |
| 162 | f.git("checkout", "--quiet", "-b", "a", "main") |
| 163 | names := []string{"line\nbreak.txt", "bell\x07.txt"} |
| 164 | for i := 0; i < 120; i++ { |
| 165 | names = append(names, fmt.Sprintf("many/file-%03d.txt", i)) |
| 166 | } |
| 167 | write := func(content string) { |
| 168 | for _, n := range names { |
| 169 | path := filepath.Join(f.work, n) |
| 170 | if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { |
| 171 | f.t.Fatal(err) |
| 172 | } |
| 173 | if err := os.WriteFile(path, []byte(content), 0o644); err != nil { |
| 174 | f.t.Fatal(err) |
| 175 | } |
| 176 | } |
| 177 | f.git("add", "-A") |
| 178 | } |
| 179 | write("a\n") |
| 180 | f.git("commit", "--quiet", "-m", "layer a") |
| 181 | f.git("push", "--quiet", "origin", "a") |
| 182 | head := f.git("rev-parse", "HEAD") |
| 183 | f.writeRecord(idA, &change.Record{ |
| 184 | Schema: change.Schema, ChangeID: idA, Target: rebase.Target, Owner: "alice", State: change.Ready, Seq: 1, Active: 1, |
| 185 | Versions: []change.Version{{N: 1, Head: change.HeadPrefix + head, Title: "A", Branch: "a", Uploader: "alice"}}, |
| 186 | }, "", head) |
| 187 | f.git("checkout", "--quiet", "main") |
| 188 | write("main\n") |
| 189 | f.git("commit", "--quiet", "-m", "main has its own") |
| 190 | f.git("push", "--quiet", "origin", "main") |
| 191 | return names |
| 192 | } |
| 193 | |
| 194 | // A conflict over more paths than a report holds keeps them all in the |
| 195 | // journal, and its report, which the format takes, names what fits and |
| 196 | // says what it leaves out. |
| 197 | func TestAConflictKeepsEveryPathInTheJournal(t *testing.T) { |
| 198 | f := newFixture(t, "") |
| 199 | names := f.conflictOnManyPaths() |
| 200 | r := newRestacker(t, f) |
| 201 | j := r.journal() |
| 202 | a := of(t, j, idA) |
| 203 | if a.Observed.Result != change.RestackConflict || len(a.Observed.Conflicts) != len(names) || a.Branches != nil { |
| 204 | t.Fatalf("the journal keeps %d conflict paths, of %d, as %s", len(a.Observed.Conflicts), len(names), a.Observed.Result) |
| 205 | } |
| 206 | rep := a.Reports[0] |
| 207 | if len(rep.Pending.Report.Conflicts) != change.MaxConflictPaths || *rep.Pending.Report.Failing != idA || |
| 208 | !strings.Contains(strings.Join(rep.Omitted, " "), "22 of its 122 conflict paths") { |
| 209 | t.Errorf("the report names %d paths and leaves out %v", len(rep.Pending.Report.Conflicts), rep.Omitted) |
| 210 | } |
| 211 | if !strings.Contains(*rep.Pending.Report.Refusal, a.Observed.Digest()) { |
| 212 | t.Errorf("the report's refusal names no digest: %q", *rep.Pending.Report.Refusal) |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | // A report that leaves part of its observation out names the file that |
| 217 | // keeps the whole of it, and that file outlives the journal. A write pass |
| 218 | // reports a conflict on 122 paths and lets go of its journal. The file |
| 219 | // the report names is in the state directory, holds every path, and |
| 220 | // reads as the observation whose digest names it. A second pass does not |
| 221 | // rebase the conflict again, and the file is still there. |
| 222 | func TestATruncatedReportNamesTheObservationItLeavesOut(t *testing.T) { |
| 223 | f := newFixture(t, "") |
| 224 | names := f.conflictOnManyPaths() |
| 225 | r := newRestacker(t, f) |
| 226 | r.pass(64) |
| 227 | r.settledState() |
| 228 | rep := f.reportOf(idA) |
| 229 | if rep == nil || rep.Result != change.RestackConflict || rep.Refusal == nil { |
| 230 | t.Fatalf("a's report is %+v", rep) |
| 231 | } |
| 232 | m := regexp.MustCompile(`as (observations/([0-9a-f]{16})\.json)\.$`).FindStringSubmatch(*rep.Refusal) |
| 233 | if m == nil { |
| 234 | t.Fatalf("the report names no file of the whole observation: %q", *rep.Refusal) |
| 235 | } |
| 236 | check := func() { |
| 237 | t.Helper() |
| 238 | data, err := os.ReadFile(filepath.Join(r.c.state, m[1])) |
| 239 | if err != nil { |
| 240 | t.Fatalf("the observation the report names is not kept: %v", err) |
| 241 | } |
| 242 | var o Observation |
| 243 | if err := json.Unmarshal(data, &o); err != nil { |
| 244 | t.Fatal(err) |
| 245 | } |
| 246 | sum := sha256.Sum256(data) |
| 247 | kept := append([]string{}, o.Conflicts...) |
| 248 | sort.Strings(kept) |
| 249 | sort.Strings(names) |
| 250 | if o.Digest() != m[2] || !strings.HasPrefix(hex.EncodeToString(sum[:]), m[2]) || !reflect.DeepEqual(kept, names) { |
| 251 | t.Errorf("%s holds %d conflict paths, digest %s", m[1], len(o.Conflicts), o.Digest()) |
| 252 | } |
| 253 | } |
| 254 | check() |
| 255 | |
| 256 | before := f.refs() |
| 257 | if p := r.pass(64); len(p.Actions) != 0 || f.refs() != before { |
| 258 | t.Errorf("a second pass pushed %+v", p.Actions) |
| 259 | } |
| 260 | check() |
| 261 | } |
| 262 | |
| 263 | // A conflict on a file whose name is not UTF-8 keeps the name in the |
| 264 | // journal byte for byte, in base64, and the journal reads back as kept, |
| 265 | // so recovery decides it. The report, which holds only UTF-8, leaves the |
| 266 | // name out and says so. |
| 267 | func TestAConflictOnAFileNameNotInUTF8KeepsItByteForByte(t *testing.T) { |
| 268 | f := newFixture(t, "") |
| 269 | latin1 := "caf\xe9.txt" |
| 270 | names := []string{latin1, "plain.txt"} |
| 271 | write := func(content string) { |
| 272 | for _, n := range names { |
| 273 | if err := os.WriteFile(filepath.Join(f.work, n), []byte(content), 0o644); err != nil { |
| 274 | t.Fatal(err) |
| 275 | } |
| 276 | } |
| 277 | f.git("add", "-A") |
| 278 | } |
| 279 | f.git("checkout", "--quiet", "-b", "a", "main") |
| 280 | write("a\n") |
| 281 | f.git("commit", "--quiet", "-m", "layer a") |
| 282 | f.git("push", "--quiet", "origin", "a") |
| 283 | head := f.git("rev-parse", "HEAD") |
| 284 | f.writeRecord(idA, &change.Record{ |
| 285 | Schema: change.Schema, ChangeID: idA, Target: rebase.Target, Owner: "alice", State: change.Ready, Seq: 1, Active: 1, |
| 286 | Versions: []change.Version{{N: 1, Head: change.HeadPrefix + head, Title: "A", Branch: "a", Uploader: "alice"}}, |
| 287 | }, "", head) |
| 288 | f.git("checkout", "--quiet", "main") |
| 289 | write("main\n") |
| 290 | f.git("commit", "--quiet", "-m", "main has its own") |
| 291 | f.git("push", "--quiet", "origin", "main") |
| 292 | |
| 293 | r := newRestacker(t, f) |
| 294 | j := r.journal() |
| 295 | a := of(t, j, idA) |
| 296 | if a.Observed.Result != change.RestackConflict || !reflect.DeepEqual([]string(a.Observed.Conflicts), names) { |
| 297 | t.Fatalf("the journal keeps the conflict paths %q, as %s", a.Observed.Conflicts, a.Observed.Result) |
| 298 | } |
| 299 | kept, err := loadJournal(r.c.state, r.c.binding()) |
| 300 | if err != nil { |
| 301 | t.Fatalf("the restacker refuses its own journal: %v", err) |
| 302 | } |
| 303 | if !reflect.DeepEqual(kept, j) || of(t, kept, idA).Observed.Conflicts[0] != latin1 { |
| 304 | t.Errorf("the journal reads back with the conflict paths %q", of(t, kept, idA).Observed.Conflicts) |
| 305 | } |
| 306 | data, err := os.ReadFile(filepath.Join(r.c.state, journalFile)) |
| 307 | if err != nil { |
| 308 | t.Fatal(err) |
| 309 | } |
| 310 | if !bytes.Contains(data, []byte(base64.StdEncoding.EncodeToString([]byte(latin1)))) { |
| 311 | t.Error("the journal does not keep the name in base64") |
| 312 | } |
| 313 | rep := a.Reports[0] |
| 314 | if !reflect.DeepEqual(rep.Pending.Report.Conflicts, []string{"plain.txt"}) || |
| 315 | !strings.Contains(strings.Join(rep.Omitted, " "), "1 of its 2 conflict paths") { |
| 316 | t.Errorf("the report names %q and leaves out %v", rep.Pending.Report.Conflicts, rep.Omitted) |
| 317 | } |
| 318 | r.recovery() |
| 319 | } |
| 320 | |
| 321 | // A report that says what the change's current report on origin says is |
| 322 | // not built again, under a new operation: a held family whose report has |
| 323 | // been pushed has nothing left to write. |
| 324 | func TestAnUnchangedReportIsNotBuiltAgain(t *testing.T) { |
| 325 | f := newFixture(t, "") |
| 326 | f.readyAs(idE, "alice", "e", "main", "E's title") |
| 327 | f.plainBranch("e-plain", "e") |
| 328 | f.moveMain() |
| 329 | r := newRestacker(t, f) |
| 330 | j := r.journal() |
| 331 | if w := of(t, j, idE).Reports[0].Pending.Push(context.Background(), r.g); w.Push != rebase.Pushed { |
| 332 | t.Fatalf("e's report: %+v", w) |
| 333 | } |
| 334 | // The pass that pushed it lets go of its journal, which would |
| 335 | // otherwise have the family wait. |
| 336 | if err := forget(context.Background(), r.g, r.c.state); err != nil { |
| 337 | t.Fatal(err) |
| 338 | } |
| 339 | |
| 340 | p, s := r.plan() |
| 341 | out, err := build(context.Background(), r.g, s, p, r.c.binding(), newOperation(time.Now().Add(time.Hour))) |
| 342 | if err != nil { |
| 343 | t.Fatal(err) |
| 344 | } |
| 345 | if len(out.journal.Families) != 0 { |
| 346 | t.Errorf("an unchanged report was built again: %+v", out.journal.Families) |
| 347 | } |
| 348 | if w := p.Families[0].Writes; w == nil || len(w.Reports) != 1 || !w.Reports[0].Unchanged { |
| 349 | t.Errorf("the plan's writes are %+v", w) |
| 350 | } |
| 351 | } |
| 352 | |
| 353 | // One snapshot gives the same reports however often it is planned. A |
| 354 | // family that several requests hold is planned again and again from the |
| 355 | // same snapshot, and each time its observation, and so its report, holds |
| 356 | // those requests and the reasons they give in one order. |
| 357 | func TestOneSnapshotGivesTheSameReports(t *testing.T) { |
| 358 | f := newFixture(t, "") |
| 359 | head := f.readyAs(idA, "alice", "a", "main", "A's title") |
| 360 | f.moveMain() |
| 361 | for _, name := range []string{"q-delta", "q-alpha", "q-echo", "q-charlie", "q-bravo", "q-foxtrot"} { |
| 362 | f.onOrigin("update-ref", rebase.RequestPrefix+name, head) |
| 363 | } |
| 364 | r := newRestacker(t, f) |
| 365 | ctx := context.Background() |
| 366 | s, err := rebase.ReadSnapshot(ctx, r.g, r.c.verify) |
| 367 | if err != nil { |
| 368 | t.Fatal(err) |
| 369 | } |
| 370 | var first []byte |
| 371 | for i := 0; i < 20; i++ { |
| 372 | p, err := plan(ctx, r.g, r.c, s, 64) |
| 373 | if err != nil { |
| 374 | t.Fatal(err) |
| 375 | } |
| 376 | out, err := build(ctx, r.g, s, p, r.c.binding(), "20261021T000000Z-00000000") |
| 377 | if err != nil { |
| 378 | t.Fatal(err) |
| 379 | } |
| 380 | a := of(t, out.journal, idA) |
| 381 | if len(a.Reports) != 1 || a.Observed.Result != change.RestackBlocked { |
| 382 | t.Fatalf("the held family's writes are %+v", a) |
| 383 | } |
| 384 | report, err := change.EncodeRestackReport(a.Reports[0].Pending.Report) |
| 385 | if err != nil { |
| 386 | t.Fatal(err) |
| 387 | } |
| 388 | observed, err := json.Marshal(a.Observed) |
| 389 | if err != nil { |
| 390 | t.Fatal(err) |
| 391 | } |
| 392 | now := append(report, observed...) |
| 393 | if first == nil { |
| 394 | first = now |
| 395 | if !strings.Contains(*a.Reports[0].Pending.Report.Refusal, "request q-alpha might still land") { |
| 396 | t.Fatalf("the report does not say what holds the family: %q", *a.Reports[0].Pending.Report.Refusal) |
| 397 | } |
| 398 | continue |
| 399 | } |
| 400 | if !bytes.Equal(now, first) { |
| 401 | t.Fatalf("plan %d of the same snapshot gives another report or observation:\n%s\nwhere the first gave:\n%s", i, now, first) |
| 402 | } |
| 403 | } |
| 404 | } |