package thin import ( "context" "fmt" "strings" "testing" "amadan.net/oficina/equipo/internal/runner/forge" "amadan.net/oficina/equipo/internal/wire" ) // fakeCI is the hub's hosted CI: whether it is on, then each status read // in turn (the last one repeats); failed answers the logs=failed read. type fakeCI struct { on bool onErr error statuses []forge.CIStatus failed *forge.CIStatus calls []string } func (f *fakeCI) CIHosted(_ context.Context, repo string) (bool, error) { f.calls = append(f.calls, "hosted "+repo) return f.on, f.onErr } func (f *fakeCI) CIStatus(ctx context.Context, repo, branch, logs string) (forge.CIStatus, error) { f.calls = append(f.calls, "status "+repo+" "+branch+" "+logs) if ctx.Err() != nil { return forge.CIStatus{}, ctx.Err() } if logs == forge.CILogsFailed && f.failed != nil { return *f.failed, nil } if len(f.statuses) == 0 { return forge.CIStatus{}, forge.ErrCIRead } st := f.statuses[0] if len(f.statuses) > 1 { f.statuses = f.statuses[1:] } return st, nil } // hostedRig is a checks attempt on the hub rig's candidate, accepted in // the runner's state as the instance dispatched it (with the offer). func hostedRig(t *testing.T, ci *fakeCI) (*Engineer, stepRow, string) { t.Helper() e, f, r, cand := hubRig(t) e.CI = ci r.Specialist, r.StepID, r.HostedChecks = wire.SpecialistChecks, "c1", true r.BaseSHA = gitOut(t, f.dir, "rev-parse", "main") if err := e.O.State.AcceptDispatch(context.Background(), "d1", r.DispatchCommand); err != nil { t.Fatal(err) } return e, heldStep(t, e), cand } // heldStep is the checks attempt as the engine would run it next. func heldStep(t *testing.T, e *Engineer) stepRow { t.Helper() if _, err := e.O.State.db.Exec("UPDATE steps SET not_before=''"); err != nil { t.Fatal(err) } r, ok, err := e.O.State.nextStep(context.Background()) if err != nil || !ok { t.Fatalf("no attempt held: %v %v", ok, err) } return r } func ciAt(sha, state string) forge.CIStatus { return forge.CIStatus{NS: "oficina", Repo: "sample", Branch: "equipo/tk1-fix-typo", SHA: sha, State: state, UpdatedAt: 1794402264} } // Offered hosted success and old resumed hosted phases cannot substitute for // unavailable base-run evidence. func TestHostedChecksPass(t *testing.T) { for _, phase := range []string{"", phaseHosted} { ci := &fakeCI{on: true} e, r, cand := hostedRig(t, ci) r.Phase = phase ci.statuses = []forge.CIStatus{ciAt(cand, "success")} rep := e.Exec(context.Background(), r, func(wire.StepReport) {}) if rep.Checks != wire.ChecksPassed || rep.Hosted == nil || rep.BaseChecksSHA != "" || len(ci.calls) == 0 { t.Fatalf("candidate hosted gate supplied authority: %+v calls=%v", rep, ci.calls) } } } // TestHostedChecksFailure: a failure names its failing units first, from // the one snapshot, with the failing logs only from a second read of the // same run; if that read is of another run, the logs are left out. func TestHostedChecksFailure(t *testing.T) { for _, sameRun := range []bool{true, false} { ci := &fakeCI{on: true} e, r, cand := hostedRig(t, ci) st := ciAt(cand, "failure") st.Summary = `step "compile" failed` st.Steps = []forge.CIStep{{Name: "compile", State: "failure"}, {Name: "check", State: "failure", Shards: []forge.CIShard{{Name: "shard 4 of 23", State: "success"}, {Name: "shard 5 of 23", State: "failure"}}}, {Name: "perf", State: "success"}} full := st full.Steps = []forge.CIStep{{Name: "compile", State: "failure", Log: "rastrillo: budget size: 1 problem(s)"}, {Name: "check", State: "failure", Shards: []forge.CIShard{{Name: "shard 5 of 23", State: "failure", Log: "--- FAIL: TestHeadless/2_project"}}}} if !sameRun { full.UpdatedAt++ } ci.statuses, ci.failed = []forge.CIStatus{st}, &full rep, _ := e.hostedVerdict(context.Background(), r, judgeReport(r), st) if rep.State != wire.StepDone || rep.Checks != wire.ChecksFailed || rep.Gate != wire.GateHosted || rep.ExitCode == nil || *rep.ExitCode == 0 { t.Fatalf("report %+v", rep) } if rep.Hosted == nil || strings.Join(rep.Hosted.Failed, "|") != "compile|check shard 5 of 23" || rep.Hosted.State != "failure" { t.Fatalf("binding %+v", rep.Hosted) } head := "Hosted CI on oficina/sample at " + cand[:7] + ": failed.\nFailed: compile; check shard 5 of 23\nstep \"compile\" failed\n" if !strings.HasPrefix(rep.Output, head) { t.Fatalf("output %q", rep.Output) } hasLogs := strings.Contains(rep.Output, "budget size: 1 problem") && strings.Contains(rep.Output, wire.CIUnitHeader("check shard 5 of 23")+"\n--- FAIL: TestHeadless/2_project") if hasLogs != sameRun { t.Fatalf("same run %v, logs %v: %q", sameRun, hasLogs, rep.Output) } } } // TestHostedFailedUnitsBounded: however many units fail, and however long // their names, the binding stays within its bounds. func TestHostedFailedUnitsBounded(t *testing.T) { var steps []forge.CIStep for i := 0; i < 40; i++ { steps = append(steps, forge.CIStep{Name: strings.Repeat("é", 200) + string(rune('a'+i%26)), State: "failure"}) } names := failedUnits(steps) if len(names) != wire.MaxHostedFailed { t.Fatalf("%d names", len(names)) } for _, n := range names { if len(n) > wire.MaxHostedName || !strings.HasPrefix(n, "é") || strings.ContainsRune(n, '�') { t.Fatalf("name %q (%d bytes)", n, len(n)) } } } func TestHostedDiagnosticWaitsWithoutCertifying(t *testing.T) { ci := &fakeCI{on: true} e, r, cand := hostedRig(t, ci) ci.statuses = []forge.CIStatus{ciAt(cand, "running")} first := e.Exec(context.Background(), r, func(wire.StepReport) {}) if first.State != stepDeferred || first.BaseChecksSHA != "" { t.Fatalf("pending diagnostic lost: %+v", first) } r.Phase = phaseHosted ci.statuses = []forge.CIStatus{ciAt(cand, wire.HostedFailure)} final := e.Exec(context.Background(), r, func(wire.StepReport) {}) if final.Checks != wire.ChecksFailed || final.BaseChecksSHA != "" || final.Hosted == nil { t.Fatalf("hosted failure lost or certified: %+v", final) } } // shardLog is a failing shard's long log: a test failure with its // message early on, then noise, then its own last lines. func shardLog(n, size int) string { var b strings.Builder fmt.Fprintf(&b, "=== RUN TestShard%d\n--- FAIL: TestShard%d (0.01s)\n shard_test.go:%d: shard %d broke\n", n, n, n, n) for b.Len() < size { fmt.Fprintf(&b, "noise line %d of shard %d, nothing to see here\n", b.Len(), n) } fmt.Fprintf(&b, "FAIL\tamadan.net/shard%d\t1.0s\n", n) return b.String() } // TestFailedLogsEveryShard (stopped-jobs audit, fix 4): with three // failing shards of 40 KB each, every shard is named in the output and // keeps its failing test and message, within the checks output bound. // Before, only the tail of all of them joined was kept: the fix round saw // the last shard only. func TestFailedLogsEveryShard(t *testing.T) { ci := &fakeCI{on: true} e, r, cand := hostedRig(t, ci) st := ciAt(cand, "failure") full := st check := forge.CIStep{Name: "check", State: "failure"} for n := 1; n <= 3; n++ { check.Shards = append(check.Shards, forge.CIShard{Name: fmt.Sprintf("shard %d of 23", n*5), State: "failure", Log: shardLog(n, 40<<10)}) } st.Steps = []forge.CIStep{{Name: "check", State: "failure", Shards: []forge.CIShard{{Name: "shard 5 of 23", State: "failure"}, {Name: "shard 10 of 23", State: "failure"}, {Name: "shard 15 of 23", State: "failure"}}}} full.Steps = []forge.CIStep{check} ci.statuses, ci.failed = []forge.CIStatus{st}, &full rep, _ := e.hostedVerdict(context.Background(), r, judgeReport(r), st) if len(rep.Output) > wire.MaxChecksOutput { t.Fatalf("output %d bytes, over %d", len(rep.Output), wire.MaxChecksOutput) } for n := 1; n <= 3; n++ { for _, want := range []string{wire.CIUnitHeader(fmt.Sprintf("check shard %d of 23", n*5)) + "\n", fmt.Sprintf("--- FAIL: TestShard%d (0.01s)\n shard_test.go:%d: shard %d broke\n", n, n, n), fmt.Sprintf("FAIL\tamadan.net/shard%d\t1.0s", n)} { if !strings.Contains(rep.Output, want) { t.Errorf("output lacks %q", want) } } } } // Each unit gets an equal share; what a short one leaves goes to the // others, and a unit within its share is kept whole. func TestCIUnitsShare(t *testing.T) { short := wire.CIUnit{Name: "lint", Log: "--- FAIL: lint\n"} long := wire.CIUnit{Name: "test", Log: shardLog(1, 20<<10)} out := wire.JoinCIUnits([]wire.CIUnit{short, long}, 8<<10) if len(out) > 8<<10 || len(out) < 7<<10 || !strings.Contains(out, wire.CIUnitHeader("lint")+"\n--- FAIL: lint\n") || !strings.Contains(out, "shard 1 broke") { t.Fatalf("%d bytes:\n%s", len(out), out) } head, units := wire.SplitCIUnits("Hosted CI failed.\n" + out) if head != "Hosted CI failed.\n" || len(units) != 2 || units[0].Name != "lint" || units[1].Name != "test" || !strings.Contains(units[1].Log, "shard 1 broke") { t.Fatalf("split %q %+v", head, units) } } // However many units fail, and however long their names, every unit is // named before any log takes its share, within the bound. func TestCIUnitsEveryNameFirst(t *testing.T) { var units []wire.CIUnit for i := 0; i < wire.MaxHostedFailed; i++ { units = append(units, wire.CIUnit{Name: fmt.Sprintf("%02d ", i) + strings.Repeat("n", wire.MaxHostedName-3), Log: shardLog(i, 4<<10)}) } for _, limit := range []int{1500, 2600, 4500, 32 << 10} { out := wire.JoinCIUnits(units, limit) if len(out) > limit { t.Fatalf("limit %d: %d bytes", limit, len(out)) } named := 0 for _, u := range units { if strings.Contains(out, wire.CIUnitHeader(u.Name)+"\n") { named++ } } if want := min(len(units), limit/(len(wire.CIUnitHeader(units[0].Name))+1)); named != want { t.Fatalf("limit %d: %d units named, want %d", limit, named, want) } } } // With more failing units than the binding names (wire.MaxHostedFailed), // every unit's log is still its own part: the instance finds each by its // header, not by the binding's capped list. func TestFailedLogsBeyondTheNamedUnits(t *testing.T) { ci := &fakeCI{on: true} e, r, cand := hostedRig(t, ci) st := ciAt(cand, "failure") snap, logs := forge.CIStep{Name: "check", State: "failure"}, forge.CIStep{Name: "check", State: "failure"} total := wire.MaxHostedFailed + 3 for n := 1; n <= total; n++ { name := fmt.Sprintf("shard %d of 23", n) snap.Shards = append(snap.Shards, forge.CIShard{Name: name, State: "failure"}) logs.Shards = append(logs.Shards, forge.CIShard{Name: name, State: "failure", Log: shardLog(n, 4<<10)}) } st.Steps = []forge.CIStep{snap} full := st full.Steps = []forge.CIStep{logs} ci.statuses, ci.failed = []forge.CIStatus{st}, &full rep, _ := e.hostedVerdict(context.Background(), r, judgeReport(r), st) _, units := wire.SplitCIUnits(rep.Output) if len(rep.Hosted.Failed) != wire.MaxHostedFailed || len(units) != total || len(rep.Output) > wire.MaxChecksOutput { t.Fatalf("%d named, %d units found, %d bytes", len(rep.Hosted.Failed), len(units), len(rep.Output)) } for n, u := range units { if u.Name != fmt.Sprintf("check shard %d of 23", n+1) || !strings.Contains(u.Log, fmt.Sprintf("--- FAIL: TestShard%d ", n+1)) || strings.Contains(u.Log, "=== CI unit") { t.Fatalf("unit %d %q: %q", n, u.Name, u.Log) } } } // A compiler's diagnostic early in a long log is kept when the log is // cut, at the runner's share and at the fix round's. func TestCIUnitsKeepDiagnostics(t *testing.T) { log := "# amadan.net/oficina/equipo/internal/x\ninternal/x/x.go:12:3: undefined: bar\nbuild error: exit status 1\n" + shardLog(1, 30<<10) for _, limit := range []int{1500, 8 << 10} { out := wire.JoinCIUnits([]wire.CIUnit{{Name: "build", Log: log}}, limit) if !strings.Contains(out, "internal/x/x.go:12:3: undefined: bar\n") || !strings.Contains(out, "build error: exit status 1\n") || len(out) > limit { t.Fatalf("limit %d: %q", limit, out) } } } // A local gate's full-sized output never pushes hosted CI's units out // of the combined diagnostic: the whole stays within the bound the // instance keeps, and every unit is in it. func TestCombinedOutputKeepsHostedUnits(t *testing.T) { local := strings.Repeat(strings.Repeat("l", 163)+"\n", 200) var units []wire.CIUnit for n := 1; n <= 3; n++ { units = append(units, wire.CIUnit{Name: fmt.Sprintf("check shard %d of 23", n), Log: shardLog(n, 12<<10)}) } out := combinedOutput(local, "Hosted CI failed.\n"+wire.JoinCIUnits(units, wire.MaxChecksOutput)) if len(out) > wire.MaxChecksOutput { t.Fatalf("%d bytes", len(out)) } if _, got := wire.SplitCIUnits(out); len(got) != 3 || !strings.Contains(out, "--- FAIL: TestShard1 ") || !strings.HasSuffix(strings.TrimSpace(strings.Split(out, "\nHosted CI diagnostic:")[0]), "l") { t.Fatalf("units %d:\n%s", len(got), out[:200]) } }