oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package thin
2
3import (
4 "bytes"
5 "context"
6 "crypto/rand"
7 "encoding/json"
8 "errors"
9 "os"
10 "path/filepath"
11 "runtime"
12 "strconv"
13 "strings"
14 "sync/atomic"
15 "testing"
16 "time"
17
18 "amadan.net/oficina/equipo/internal/wire"
19)
20
21// Astra 4b round 1, finding 1: an answering session's git output is
22// bounded while it is read; a huge patch never lands in runner memory,
23// and git is stopped and reaped once the bound is reached.
24func TestAnswerGitOutputBoundedWhileRead(t *testing.T) {
25 if testing.Short() {
26 t.Skip("writes 16 MiB")
27 }
28 root := t.TempDir()
29 work := filepath.Join(root, "work")
30 gitT(t, root, "init", "-q", "-b", "main", work)
31 os.WriteFile(filepath.Join(work, "a.txt"), []byte("a\n"), 0644)
32 gitT(t, work, "add", "-A")
33 gitT(t, work, "commit", "-qm", "base")
34 base := gitT(t, work, "rev-parse", "HEAD")
35 var big bytes.Buffer
36 raw := make([]byte, 48<<17)
37 rand.Read(raw)
38 for i := 0; i < len(raw); i += 48 {
39 big.WriteString(strconv.Quote(string(raw[i:i+48])) + "\n")
40 }
41 os.WriteFile(filepath.Join(work, "big.txt"), big.Bytes(), 0644)
42 big.Reset()
43 raw = nil
44 gitT(t, work, "add", "-A")
45 gitT(t, work, "commit", "-qm", "big")
46 cand := gitT(t, work, "rev-parse", "HEAD")
47 gitDir := filepath.Join(work, ".git")
48 for _, c := range []struct{ name, args string }{{"git_diff", `{}`}, {"git_show", `{"commit":"` + cand + `"}`}} {
49 runtime.GC()
50 var a, b runtime.MemStats
51 runtime.ReadMemStats(&a)
52 out, bad := answerGit(context.Background(), "/usr/bin/git", gitDir, base, cand, c.name, json.RawMessage(c.args))
53 runtime.ReadMemStats(&b)
54 if bad || len(out) > wire.MaxDiffBytes+200 || !strings.Contains(out, "[cut;") {
55 t.Fatalf("%s: %d bytes, error %v", c.name, len(out), bad)
56 }
57 if grew := b.TotalAlloc - a.TotalAlloc; grew > 4<<20 {
58 t.Fatalf("%s allocated %d MiB reading git's output", c.name, grew>>20)
59 }
60 }
61}
62
63// Astra 4b round 1, minor: git_show takes only commits git_log shows,
64// base..candidate: not the base, nor anything before it.
65func TestAnswerGitShowKeepsToTheChange(t *testing.T) {
66 root := t.TempDir()
67 work := filepath.Join(root, "work")
68 gitT(t, root, "init", "-q", "-b", "main", work)
69 os.WriteFile(filepath.Join(work, "a.txt"), []byte("first\n"), 0644)
70 gitT(t, work, "add", "-A")
71 gitT(t, work, "commit", "-qm", "older history")
72 older := gitT(t, work, "rev-parse", "HEAD")
73 os.WriteFile(filepath.Join(work, "a.txt"), []byte("second\n"), 0644)
74 gitT(t, work, "commit", "-qam", "the base")
75 base := gitT(t, work, "rev-parse", "HEAD")
76 os.WriteFile(filepath.Join(work, "a.txt"), []byte("third\n"), 0644)
77 gitT(t, work, "commit", "-qam", "the change")
78 cand := gitT(t, work, "rev-parse", "HEAD")
79 gd := filepath.Join(work, ".git")
80 if out, bad := answerGit(context.Background(), "/usr/bin/git", gd, base, cand, "git_show", json.RawMessage(`{"commit":"`+cand+`"}`)); bad || !strings.Contains(out, "the change") {
81 t.Fatalf("the change itself: %q", out)
82 }
83 for _, c := range []string{base, older} {
84 if out, bad := answerGit(context.Background(), "/usr/bin/git", gd, base, cand, "git_show", json.RawMessage(`{"commit":"`+c+`"}`)); !bad {
85 t.Fatalf("git_show answered outside base..candidate: %q", out)
86 }
87 }
88}
89
90func outboxAnswers(t *testing.T, s *State) map[string]wire.AnswerReport {
91 t.Helper()
92 frames, _, err := s.Unacked(context.Background(), 0)
93 if err != nil {
94 t.Fatal(err)
95 }
96 out := map[string]wire.AnswerReport{}
97 for _, f := range frames {
98 if f.Type == wire.FrameAnswer {
99 var r wire.AnswerReport
100 json.Unmarshal(f.Data, &r)
101 if wire.QuestionTerminal(r.State) {
102 out[r.QuestionID] = r
103 }
104 }
105 }
106 return out
107}
108
109// runAsk runs the engine until the question leaves the running state.
110func runAsk(t *testing.T, s *State, e *StepEngine, q string) {
111 t.Helper()
112 ctx, cancel := context.WithCancel(context.Background())
113 if err := e.Start(ctx); err != nil {
114 t.Fatal(err)
115 }
116 if err := s.AcceptAsk(context.Background(), "c-"+q, wire.AskCommand{Person: "owner@example.com", TaskID: "tk1", QuestionID: q, Attempt: 1}); err != nil {
117 t.Fatal(err)
118 }
119 e.Wake()
120 deadline := time.Now().Add(10 * time.Second)
121 for {
122 var state string
123 s.db.QueryRow("SELECT state FROM asks WHERE question_id=?", q).Scan(&state)
124 if state != runRunning {
125 break
126 }
127 if time.Now().After(deadline) {
128 t.Fatal("the question did not end")
129 }
130 time.Sleep(10 * time.Millisecond)
131 }
132 cancel()
133 e.Wait()
134}
135
136// Astra 4b round 1, finding 2: a question is complete only once its
137// namespace's exit is verified. Until then (the exit failed or stalled)
138// its answer is held, recorded against the question's own namespace,
139// and survives a restart; the verified exit releases it, once.
140func TestAskHeldUntilTerminationVerified(t *testing.T) {
141 for _, how := range []string{"failed", "stalled"} {
142 t.Run(how, func(t *testing.T) {
143 ctx := context.Background()
144 dir := t.TempDir()
145 s, err := OpenState(ctx, dir)
146 if err != nil {
147 t.Fatal(err)
148 }
149 var verified atomic.Bool
150 e := &StepEngine{State: s, Notify: func() {}, Verify: func(_ context.Context, ns string) bool { return ns == "ns-q1" && verified.Load() },
151 Ask: func(ctx context.Context, a askRow, _ func(wire.AnswerReport)) askResult {
152 // The run recorded its namespace, then its exit was not
153 // verified (Wait failed, or it outlived the limit).
154 if err := s.setAskNamespace(ctx, a, "ns-q1"); err != nil {
155 t.Fatal(err)
156 }
157 return askResult{Report: wire.AnswerReport{TaskID: a.TaskID, QuestionID: a.QuestionID, Attempt: a.Attempt, State: wire.QuestionAnswered, Text: "An answer."}, Terminated: false}
158 }}
159 runAsk(t, s, e, "q1")
160 if got := outboxAnswers(t, s); len(got) != 0 {
161 t.Fatalf("answered before the exit was verified: %+v", got)
162 }
163 if runs, _ := s.syncAsks(ctx); len(runs) != 1 || runs[0].QuestionID != "q1" {
164 t.Fatalf("a held question is not listed in sync: %+v", runs)
165 }
166 // A restart keeps holding it, and never runs it again.
167 s.Close()
168 if s, err = OpenState(ctx, dir); err != nil {
169 t.Fatal(err)
170 }
171 defer s.Close()
172 ran := 0
173 e2 := &StepEngine{State: s, Notify: func() {}, Verify: e.Verify, Ask: func(context.Context, askRow, func(wire.AnswerReport)) askResult { ran++; return askResult{} }}
174 cctx, cancel := context.WithCancel(ctx)
175 if err := e2.Start(cctx); err != nil {
176 t.Fatal(err)
177 }
178 if got := outboxAnswers(t, s); len(got) != 0 {
179 t.Fatalf("released at restart without proof: %+v", got)
180 }
181 verified.Store(true)
182 e2.Probe(ctx)
183 e2.Probe(ctx)
184 cancel()
185 e2.Wait()
186 got := outboxAnswers(t, s)
187 if ran != 0 || len(got) != 1 || got["q1"].State != wire.QuestionAnswered || got["q1"].Text != "An answer." {
188 t.Fatalf("after the verified exit: ran %d, reports %+v", ran, got)
189 }
190 })
191 }
192}
193
194// A running question a previous process left with a namespace whose exit
195// is unproven is held, not reported, until a probe verifies it.
196func TestRecoverAsksHoldsUnprovenNamespaces(t *testing.T) {
197 ctx := context.Background()
198 s, err := OpenState(ctx, t.TempDir())
199 if err != nil {
200 t.Fatal(err)
201 }
202 defer s.Close()
203 a := askRow{AskCommand: wire.AskCommand{Person: "owner@example.com", TaskID: "tk1", QuestionID: "q1", Attempt: 1}}
204 if err := s.AcceptAsk(ctx, "c1", a.AskCommand); err != nil {
205 t.Fatal(err)
206 }
207 s.setAskNamespace(ctx, a, "ns-gone")
208 ok := false
209 e := &StepEngine{State: s, Notify: func() {}, Verify: func(context.Context, string) bool { return ok }}
210 if err := s.RecoverAsks(ctx, e.Verify); err != nil {
211 t.Fatal(err)
212 }
213 if got := outboxAnswers(t, s); len(got) != 0 {
214 t.Fatalf("reported without proof: %+v", got)
215 }
216 ok = true
217 e.Probe(ctx)
218 if got := outboxAnswers(t, s); got["q1"].Reason != "runner_restarted" {
219 t.Fatalf("after proof: %+v", got)
220 }
221}
222
223// Astra 4b round 1, finding 3: if the final report cannot be saved the
224// answer is kept and saved again; the provider runs exactly once.
225func TestAskReportPersistedWithoutRerun(t *testing.T) {
226 ctx := context.Background()
227 s, err := OpenState(ctx, t.TempDir())
228 if err != nil {
229 t.Fatal(err)
230 }
231 defer s.Close()
232 var fails atomic.Int32
233 fails.Store(3)
234 s.fault = func(op string) error {
235 if op == "finish_ask" && fails.Add(-1) >= 0 {
236 return errors.New("injected: database busy")
237 }
238 return nil
239 }
240 var runs atomic.Int32
241 e := &StepEngine{State: s, Notify: func() {}, Ask: func(_ context.Context, a askRow, _ func(wire.AnswerReport)) askResult {
242 runs.Add(1)
243 return askResult{Report: wire.AnswerReport{TaskID: a.TaskID, QuestionID: a.QuestionID, Attempt: a.Attempt, State: wire.QuestionAnswered, Text: "Once."}, Terminated: true}
244 }}
245 runAsk(t, s, e, "q1")
246 if n := runs.Load(); n != 1 {
247 t.Fatalf("the provider ran %d times", n)
248 }
249 if got := outboxAnswers(t, s); got["q1"].Text != "Once." {
250 t.Fatalf("the answer was lost: %+v", got)
251 }
252}
253