package thin import ( "bytes" "context" "crypto/rand" "encoding/json" "errors" "os" "path/filepath" "runtime" "strconv" "strings" "sync/atomic" "testing" "time" "amadan.net/oficina/equipo/internal/wire" ) // Astra 4b round 1, finding 1: an answering session's git output is // bounded while it is read; a huge patch never lands in runner memory, // and git is stopped and reaped once the bound is reached. func TestAnswerGitOutputBoundedWhileRead(t *testing.T) { if testing.Short() { t.Skip("writes 16 MiB") } root := t.TempDir() work := filepath.Join(root, "work") gitT(t, root, "init", "-q", "-b", "main", work) os.WriteFile(filepath.Join(work, "a.txt"), []byte("a\n"), 0644) gitT(t, work, "add", "-A") gitT(t, work, "commit", "-qm", "base") base := gitT(t, work, "rev-parse", "HEAD") var big bytes.Buffer raw := make([]byte, 48<<17) rand.Read(raw) for i := 0; i < len(raw); i += 48 { big.WriteString(strconv.Quote(string(raw[i:i+48])) + "\n") } os.WriteFile(filepath.Join(work, "big.txt"), big.Bytes(), 0644) big.Reset() raw = nil gitT(t, work, "add", "-A") gitT(t, work, "commit", "-qm", "big") cand := gitT(t, work, "rev-parse", "HEAD") gitDir := filepath.Join(work, ".git") for _, c := range []struct{ name, args string }{{"git_diff", `{}`}, {"git_show", `{"commit":"` + cand + `"}`}} { runtime.GC() var a, b runtime.MemStats runtime.ReadMemStats(&a) out, bad := answerGit(context.Background(), "/usr/bin/git", gitDir, base, cand, c.name, json.RawMessage(c.args)) runtime.ReadMemStats(&b) if bad || len(out) > wire.MaxDiffBytes+200 || !strings.Contains(out, "[cut;") { t.Fatalf("%s: %d bytes, error %v", c.name, len(out), bad) } if grew := b.TotalAlloc - a.TotalAlloc; grew > 4<<20 { t.Fatalf("%s allocated %d MiB reading git's output", c.name, grew>>20) } } } // Astra 4b round 1, minor: git_show takes only commits git_log shows, // base..candidate: not the base, nor anything before it. func TestAnswerGitShowKeepsToTheChange(t *testing.T) { root := t.TempDir() work := filepath.Join(root, "work") gitT(t, root, "init", "-q", "-b", "main", work) os.WriteFile(filepath.Join(work, "a.txt"), []byte("first\n"), 0644) gitT(t, work, "add", "-A") gitT(t, work, "commit", "-qm", "older history") older := gitT(t, work, "rev-parse", "HEAD") os.WriteFile(filepath.Join(work, "a.txt"), []byte("second\n"), 0644) gitT(t, work, "commit", "-qam", "the base") base := gitT(t, work, "rev-parse", "HEAD") os.WriteFile(filepath.Join(work, "a.txt"), []byte("third\n"), 0644) gitT(t, work, "commit", "-qam", "the change") cand := gitT(t, work, "rev-parse", "HEAD") gd := filepath.Join(work, ".git") if out, bad := answerGit(context.Background(), "/usr/bin/git", gd, base, cand, "git_show", json.RawMessage(`{"commit":"`+cand+`"}`)); bad || !strings.Contains(out, "the change") { t.Fatalf("the change itself: %q", out) } for _, c := range []string{base, older} { if out, bad := answerGit(context.Background(), "/usr/bin/git", gd, base, cand, "git_show", json.RawMessage(`{"commit":"`+c+`"}`)); !bad { t.Fatalf("git_show answered outside base..candidate: %q", out) } } } func outboxAnswers(t *testing.T, s *State) map[string]wire.AnswerReport { t.Helper() frames, _, err := s.Unacked(context.Background(), 0) if err != nil { t.Fatal(err) } out := map[string]wire.AnswerReport{} for _, f := range frames { if f.Type == wire.FrameAnswer { var r wire.AnswerReport json.Unmarshal(f.Data, &r) if wire.QuestionTerminal(r.State) { out[r.QuestionID] = r } } } return out } // runAsk runs the engine until the question leaves the running state. func runAsk(t *testing.T, s *State, e *StepEngine, q string) { t.Helper() ctx, cancel := context.WithCancel(context.Background()) if err := e.Start(ctx); err != nil { t.Fatal(err) } if err := s.AcceptAsk(context.Background(), "c-"+q, wire.AskCommand{Person: "owner@example.com", TaskID: "tk1", QuestionID: q, Attempt: 1}); err != nil { t.Fatal(err) } e.Wake() deadline := time.Now().Add(10 * time.Second) for { var state string s.db.QueryRow("SELECT state FROM asks WHERE question_id=?", q).Scan(&state) if state != runRunning { break } if time.Now().After(deadline) { t.Fatal("the question did not end") } time.Sleep(10 * time.Millisecond) } cancel() e.Wait() } // Astra 4b round 1, finding 2: a question is complete only once its // namespace's exit is verified. Until then (the exit failed or stalled) // its answer is held, recorded against the question's own namespace, // and survives a restart; the verified exit releases it, once. func TestAskHeldUntilTerminationVerified(t *testing.T) { for _, how := range []string{"failed", "stalled"} { t.Run(how, func(t *testing.T) { ctx := context.Background() dir := t.TempDir() s, err := OpenState(ctx, dir) if err != nil { t.Fatal(err) } var verified atomic.Bool e := &StepEngine{State: s, Notify: func() {}, Verify: func(_ context.Context, ns string) bool { return ns == "ns-q1" && verified.Load() }, Ask: func(ctx context.Context, a askRow, _ func(wire.AnswerReport)) askResult { // The run recorded its namespace, then its exit was not // verified (Wait failed, or it outlived the limit). if err := s.setAskNamespace(ctx, a, "ns-q1"); err != nil { t.Fatal(err) } return askResult{Report: wire.AnswerReport{TaskID: a.TaskID, QuestionID: a.QuestionID, Attempt: a.Attempt, State: wire.QuestionAnswered, Text: "An answer."}, Terminated: false} }} runAsk(t, s, e, "q1") if got := outboxAnswers(t, s); len(got) != 0 { t.Fatalf("answered before the exit was verified: %+v", got) } if runs, _ := s.syncAsks(ctx); len(runs) != 1 || runs[0].QuestionID != "q1" { t.Fatalf("a held question is not listed in sync: %+v", runs) } // A restart keeps holding it, and never runs it again. s.Close() if s, err = OpenState(ctx, dir); err != nil { t.Fatal(err) } defer s.Close() ran := 0 e2 := &StepEngine{State: s, Notify: func() {}, Verify: e.Verify, Ask: func(context.Context, askRow, func(wire.AnswerReport)) askResult { ran++; return askResult{} }} cctx, cancel := context.WithCancel(ctx) if err := e2.Start(cctx); err != nil { t.Fatal(err) } if got := outboxAnswers(t, s); len(got) != 0 { t.Fatalf("released at restart without proof: %+v", got) } verified.Store(true) e2.Probe(ctx) e2.Probe(ctx) cancel() e2.Wait() got := outboxAnswers(t, s) if ran != 0 || len(got) != 1 || got["q1"].State != wire.QuestionAnswered || got["q1"].Text != "An answer." { t.Fatalf("after the verified exit: ran %d, reports %+v", ran, got) } }) } } // A running question a previous process left with a namespace whose exit // is unproven is held, not reported, until a probe verifies it. func TestRecoverAsksHoldsUnprovenNamespaces(t *testing.T) { ctx := context.Background() s, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer s.Close() a := askRow{AskCommand: wire.AskCommand{Person: "owner@example.com", TaskID: "tk1", QuestionID: "q1", Attempt: 1}} if err := s.AcceptAsk(ctx, "c1", a.AskCommand); err != nil { t.Fatal(err) } s.setAskNamespace(ctx, a, "ns-gone") ok := false e := &StepEngine{State: s, Notify: func() {}, Verify: func(context.Context, string) bool { return ok }} if err := s.RecoverAsks(ctx, e.Verify); err != nil { t.Fatal(err) } if got := outboxAnswers(t, s); len(got) != 0 { t.Fatalf("reported without proof: %+v", got) } ok = true e.Probe(ctx) if got := outboxAnswers(t, s); got["q1"].Reason != "runner_restarted" { t.Fatalf("after proof: %+v", got) } } // Astra 4b round 1, finding 3: if the final report cannot be saved the // answer is kept and saved again; the provider runs exactly once. func TestAskReportPersistedWithoutRerun(t *testing.T) { ctx := context.Background() s, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer s.Close() var fails atomic.Int32 fails.Store(3) s.fault = func(op string) error { if op == "finish_ask" && fails.Add(-1) >= 0 { return errors.New("injected: database busy") } return nil } var runs atomic.Int32 e := &StepEngine{State: s, Notify: func() {}, Ask: func(_ context.Context, a askRow, _ func(wire.AnswerReport)) askResult { runs.Add(1) return askResult{Report: wire.AnswerReport{TaskID: a.TaskID, QuestionID: a.QuestionID, Attempt: a.Attempt, State: wire.QuestionAnswered, Text: "Once."}, Terminated: true} }} runAsk(t, s, e, "q1") if n := runs.Load(); n != 1 { t.Fatalf("the provider ran %d times", n) } if got := outboxAnswers(t, s); got["q1"].Text != "Once." { t.Fatalf("the answer was lost: %+v", got) } }