Spaces:
Sleeping

api-relay commited on
Commit
0a855cc
·
verified ·
1 Parent(s): 98cf5b8

Upload 30 files

Browse files
internal/bank/bank.go CHANGED
@@ -134,7 +134,9 @@ type Manager struct {
134
  // Load reads every category/difficulty file under dir.
135
  func Load(dir string, staleAfter int) (*Manager, error) {
136
  if staleAfter <= 0 {
137
- staleAfter = 3
 
 
138
  }
139
  m := &Manager{
140
  dir: dir,
@@ -338,6 +340,31 @@ func (m *Manager) MarkUsed(ids []string, at time.Time) {
338
  }
339
  }
340
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
341
  // Stale lists examples that have exhausted their allowed uses.
342
  func (m *Manager) Stale() []Example {
343
  m.mu.RLock()
 
134
  // Load reads every category/difficulty file under dir.
135
  func Load(dir string, staleAfter int) (*Manager, error) {
136
  if staleAfter <= 0 {
137
+ // Matches the config default. Kept local so a manager built without a
138
+ // config still retires examples instead of serving them forever.
139
+ staleAfter = 5
140
  }
141
  m := &Manager{
142
  dir: dir,
 
340
  }
341
  }
342
 
343
+ // Lifeline is one example's use budget: how many times it has been served and
344
+ // how many serves it has left before it is stale.
345
+ type Lifeline struct {
346
+ Used int `json:"used"`
347
+ Remaining int `json:"remaining"`
348
+ Max int `json:"max"`
349
+ }
350
+
351
+ // Uptake reports the number of times an example has been handed out, and how
352
+ // many serves it has left. Remaining is inclusive of the current use: an
353
+ // example served once with a ceiling of 5 reports 4 left.
354
+ func (m *Manager) Uptake(id string) (used, remaining int) {
355
+ m.mu.RLock()
356
+ defer m.mu.RUnlock()
357
+ used = m.usage[id].Count
358
+ remaining = m.staleAfter - used
359
+ if remaining < 0 {
360
+ remaining = 0
361
+ }
362
+ return used, remaining
363
+ }
364
+
365
+ // StaleAfter reports the configured ceiling.
366
+ func (m *Manager) StaleAfter() int { return m.staleAfter }
367
+
368
  // Stale lists examples that have exhausted their allowed uses.
369
  func (m *Manager) Stale() []Example {
370
  m.mu.RLock()
internal/config/config.go CHANGED
@@ -120,8 +120,11 @@ func Load() Config {
120
 
121
  TrustedProxyHops: envInt("TRUSTED_PROXY_HOPS", 1),
122
 
123
- DrawMax: envInt("DRAW_MAX", 75),
124
- StaleAfterUses: envInt("STALE_AFTER_USES", 3),
 
 
 
125
 
126
  Window: envDur("WINDOW", time.Hour),
127
 
 
120
 
121
  TrustedProxyHops: envInt("TRUSTED_PROXY_HOPS", 1),
122
 
123
+ DrawMax: envInt("DRAW_MAX", 75),
124
+ // Five serves per variant: enough for a question to be answered by more
125
+ // than one model before it retires, few enough that the answer is not
126
+ // memorised by the time it does.
127
+ StaleAfterUses: envInt("STALE_AFTER_USES", 5),
128
 
129
  Window: envDur("WINDOW", time.Hour),
130
 
internal/core/core.go CHANGED
@@ -126,6 +126,16 @@ type Grant struct {
126
  NextDrawAt time.Time
127
  Shortfall int
128
  Notes []string
 
 
 
 
 
 
 
 
 
 
129
  }
130
 
131
  // Hash implements identity.HashFunc with a salted HMAC-SHA256, truncated to
@@ -152,14 +162,6 @@ func (s *Service) Hash(kind, value string) string {
152
  func (s *Service) RequestDraw(ctx context.Context, in DrawInput) (*Grant, error) {
153
  now := s.now()
154
 
155
- // The request id is the correlation handle between a draw and its results,
156
- // so it must never be empty. Trust the caller's if it supplied one, and
157
- // mint one if it did not: a draw without an id could never have its
158
- // feedback verified, which would quietly make the ledger useless.
159
- if in.RequestID == "" {
160
- in.RequestID = newID()
161
- }
162
-
163
  // Identity, counting and the volume ladder run FIRST, before any shape
164
  // check. Previously a bot could send malformed bodies all day and never be
165
  // counted, because every cheap rejection returned before the counters were
@@ -168,6 +170,42 @@ func (s *Service) RequestDraw(ctx context.Context, in DrawInput) (*Grant, error)
168
  if err != nil {
169
  return nil, err
170
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
  markerHashes := make([]string, 0, len(id.Markers))
172
  for _, m := range id.Markers {
173
  markerHashes = append(markerHashes, m.Hash)
@@ -387,6 +425,11 @@ func (s *Service) RequestDraw(ctx context.Context, in DrawInput) (*Grant, error)
387
  s.record(ctx, in.RequestID, rec.ID, "allow", "granted", id, 0)
388
  s.publishIdentity(rec)
389
 
 
 
 
 
 
390
  return &Grant{
391
  RequestID: in.RequestID,
392
  IdentityID: rec.ID,
@@ -396,6 +439,8 @@ func (s *Service) RequestDraw(ctx context.Context, in DrawInput) (*Grant, error)
396
  NextDrawAt: now.Add(s.cfg.Window),
397
  Shortfall: result.Shortfall,
398
  Notes: result.Notes,
 
 
399
  }, nil
400
  }
401
 
@@ -912,6 +957,13 @@ func idOf(rec *store.Record) string {
912
  return rec.ID
913
  }
914
 
 
 
 
 
 
 
 
915
  // newID returns a random 128-bit hex identifier.
916
  func newID() string {
917
  var b [16]byte
 
126
  NextDrawAt time.Time
127
  Shortfall int
128
  Notes []string
129
+
130
+ // Lifeline is the per-example use counter: how many times each question has
131
+ // now been served and how many uses it has left before it goes stale. The
132
+ // counter belongs to the variant, not to the run, so it is shared by
133
+ // everyone who draws it -- two different people asking the same question
134
+ // spend the same budget. It is exposed so a runner can tell the user how
135
+ // long a question has left rather than letting it disappear silently.
136
+ Lifeline map[string]bank.Lifeline
137
+ // StaleAfter is the ceiling Lifeline is measured against.
138
+ StaleAfter int
139
  }
140
 
141
  // Hash implements identity.HashFunc with a salted HMAC-SHA256, truncated to
 
162
  func (s *Service) RequestDraw(ctx context.Context, in DrawInput) (*Grant, error) {
163
  now := s.now()
164
 
 
 
 
 
 
 
 
 
165
  // Identity, counting and the volume ladder run FIRST, before any shape
166
  // check. Previously a bot could send malformed bodies all day and never be
167
  // counted, because every cheap rejection returned before the counters were
 
170
  if err != nil {
171
  return nil, err
172
  }
173
+
174
+ // A draw id belongs to the server. Callers are told what it is, never the
175
+ // other way round, so it is always minted here regardless of what arrived.
176
+ //
177
+ // An earlier version trusted a caller-supplied id and only refused a
178
+ // repeat. That worked, but the client still chose the handle, and the
179
+ // ledger is keyed by that handle alone: any two callers picking the same
180
+ // value collided, with the second report refused as ALREADY_REPORTED even
181
+ // though it answered a different run. Ignoring the field removes the class
182
+ // of bug instead of policing it, and keeps ids unpredictable so one draw
183
+ // cannot be guessed from another.
184
+ in.RequestID = NewRequestID()
185
+
186
+ // Belt and braces: minting is random, but a collision would overwrite a
187
+ // live draw, so it is checked rather than assumed. One retry is enough --
188
+ // at 128 bits a second clash is not a real event.
189
+ if _, taken := s.store.LeaseLedger(in.RequestID); taken {
190
+ in.RequestID = NewRequestID()
191
+ if _, still := s.store.LeaseLedger(in.RequestID); still {
192
+ s.record(ctx, "", "", "deny", "ID_COLLISION", id, 0)
193
+ return nil, apierr.Internal("could not allocate a draw id")
194
+ }
195
+ }
196
+
197
+ // A caller may supply its own id, and nothing stops it repeating one. The
198
+ // ledger is keyed by request id alone -- deliberately, because that is what
199
+ // the reporter has to quote -- so a second draw with an id already in the
200
+ // ledger would overwrite the first. Two different machines would then share
201
+ // a handle: each could file answers under it, and ALREADY_REPORTED would
202
+ // refuse the second. That is the one way two separate runs can collide on a
203
+ // draw id, so it is refused here rather than left to feedback.
204
+ if _, taken := s.store.LeaseLedger(in.RequestID); taken {
205
+ s.record(ctx, in.RequestID, "", "deny", "DUPLICATE_REQUEST_ID", id, 0)
206
+ return nil, apierr.BadRequest(
207
+ "request_id was already used for an earlier draw; use a fresh one or omit it")
208
+ }
209
  markerHashes := make([]string, 0, len(id.Markers))
210
  for _, m := range id.Markers {
211
  markerHashes = append(markerHashes, m.Hash)
 
425
  s.record(ctx, in.RequestID, rec.ID, "allow", "granted", id, 0)
426
  s.publishIdentity(rec)
427
 
428
+ lifeline := make(map[string]bank.Lifeline, len(issued))
429
+ for _, id := range issued {
430
+ used, remaining := s.bank.Uptake(id)
431
+ lifeline[id] = bank.Lifeline{Used: used, Remaining: remaining, Max: s.bank.StaleAfter()}
432
+ }
433
  return &Grant{
434
  RequestID: in.RequestID,
435
  IdentityID: rec.ID,
 
439
  NextDrawAt: now.Add(s.cfg.Window),
440
  Shortfall: result.Shortfall,
441
  Notes: result.Notes,
442
+ Lifeline: lifeline,
443
+ StaleAfter: s.bank.StaleAfter(),
444
  }, nil
445
  }
446
 
 
957
  return rec.ID
958
  }
959
 
960
+ // NewRequestID mints a draw id: 128 random bits, hex encoded. Exposed because
961
+ // the HTTP layer is the only place a draw id may originate, and the core must
962
+ // treat whatever arrives on the wire as untrusted.
963
+ func NewRequestID() string {
964
+ return newID()
965
+ }
966
+
967
  // newID returns a random 128-bit hex identifier.
968
  func newID() string {
969
  var b [16]byte
internal/core/core_test.go ADDED
@@ -0,0 +1,712 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package core
2
+
3
+ import (
4
+ "context"
5
+ "fmt"
6
+ "net/netip"
7
+ "os"
8
+ "path/filepath"
9
+ "strings"
10
+ "testing"
11
+ "time"
12
+
13
+ "github.com/archnemix/archx-eval/relay/internal/bank"
14
+ "github.com/archnemix/archx-eval/relay/internal/config"
15
+ "github.com/archnemix/archx-eval/relay/internal/identity"
16
+ "github.com/archnemix/archx-eval/relay/internal/ratelog"
17
+ "github.com/archnemix/archx-eval/relay/internal/reputation"
18
+ "github.com/archnemix/archx-eval/relay/internal/store"
19
+ )
20
+
21
+ type harness struct {
22
+ svc *Service
23
+ bankM *bank.Manager
24
+ cfg config.Config
25
+ now time.Time
26
+ store *store.Store
27
+ rates *ratelog.Log
28
+ }
29
+
30
+ func newHarness(t *testing.T, examplesPerCat int) *harness {
31
+ t.Helper()
32
+ dir := t.TempDir()
33
+ bankDir := filepath.Join(dir, "bank")
34
+ if err := os.MkdirAll(filepath.Join(bankDir, "python"), 0o750); err != nil {
35
+ t.Fatal(err)
36
+ }
37
+ var b strings.Builder
38
+ for i := 0; i < examplesPerCat; i++ {
39
+ fmt.Fprintf(&b, `{"id":"py-%03d","category":"python","difficulty":"easy","kind":"qa","prompt":"q%d","expected_answer":"a"}`+"\n", i, i)
40
+ }
41
+ if err := os.WriteFile(filepath.Join(bankDir, "python", "easy.jsonl"), []byte(b.String()), 0o640); err != nil {
42
+ t.Fatal(err)
43
+ }
44
+
45
+ cfg := config.Config{
46
+ BankDir: bankDir,
47
+ DataDir: filepath.Join(dir, "data"),
48
+ RateDir: filepath.Join(dir, "rate"),
49
+ DrawMax: 75,
50
+ StaleAfterUses: 3,
51
+ Window: time.Hour,
52
+ RateAllowance: 0.5,
53
+ RateWindow: time.Minute,
54
+ RateSample: time.Second,
55
+ // A floor keeps two rapid test requests from looking like a flood; the
56
+ // production default is 20.
57
+ RateFloor: 10,
58
+ BanWindow: 24 * time.Hour,
59
+ MaxBan: 14 * 24 * time.Hour,
60
+ FeedbackWindow: 24 * time.Hour,
61
+ LedgerKeepDays: 7,
62
+ SaltSecret: "test-salt",
63
+ AllowLoopback: true,
64
+ AccessToken: "test-access-token",
65
+ NetWindow: time.Hour,
66
+ NetMaxDraws: 1000,
67
+ GlobalWindow: time.Hour,
68
+ GlobalMax: 100000,
69
+ }
70
+ st, err := store.Open(cfg.DataDir)
71
+ if err != nil {
72
+ t.Fatalf("store: %v", err)
73
+ }
74
+ bm, err := bank.Load(bankDir, cfg.StaleAfterUses)
75
+ if err != nil {
76
+ t.Fatalf("bank: %v", err)
77
+ }
78
+ rep, err := reputation.Load("")
79
+ if err != nil {
80
+ t.Fatalf("reputation: %v", err)
81
+ }
82
+ rates, err := ratelog.Open(cfg.RateDir, 96*time.Hour)
83
+ if err != nil {
84
+ t.Fatalf("ratelog: %v", err)
85
+ }
86
+ t.Cleanup(func() { _ = rates.Close() })
87
+ svc := New(cfg, st, bm, rep, rates)
88
+ h := &harness{svc: svc, bankM: bm, cfg: cfg, now: time.Date(2026, 11, 13, 12, 0, 0, 0, time.UTC), store: st, rates: rates}
89
+ svc.SetClock(func() time.Time { return h.now })
90
+ rates.SetClock(func() time.Time { return h.now })
91
+ return h
92
+ }
93
+
94
+ func (h *harness) advance(d time.Duration) { h.now = h.now.Add(d) }
95
+
96
+ // reopen simulates a Space restart: fresh store, bank and service over the same
97
+ // directories, which is what the relay does on every wake.
98
+ func (h *harness) reopen() *harness {
99
+ st, err := store.Open(h.cfg.DataDir)
100
+ if err != nil {
101
+ panic("reopen store: " + err.Error())
102
+ }
103
+ bm, err := bank.Load(h.cfg.BankDir, h.cfg.StaleAfterUses)
104
+ if err != nil {
105
+ panic("reopen bank: " + err.Error())
106
+ }
107
+ rep, _ := reputation.Load("")
108
+ // Opened on the harness clock: load applies the retention cutoff, and the
109
+ // harness date is frozen, so the wall clock would discard everything.
110
+ now := h.now
111
+ rates, err := ratelog.OpenAt(h.cfg.RateDir, 96*time.Hour, func() time.Time { return now })
112
+ if err != nil {
113
+ panic("reopen ratelog: " + err.Error())
114
+ }
115
+ svc := New(h.cfg, st, bm, rep, rates)
116
+ h2 := &harness{svc: svc, bankM: bm, cfg: h.cfg, now: h.now, store: st, rates: rates}
117
+ svc.SetClock(func() time.Time { return h2.now })
118
+ rates.SetClock(func() time.Time { return h2.now })
119
+ return h2
120
+ }
121
+
122
+ // draws counts calls so every helper-built draw gets its own request id, the
123
+ // way a real client does. A fixed id is refused now that a repeated one is
124
+ // treated as a collision.
125
+ var draws int
126
+
127
+ func input(ip, machine, disk string) DrawInput {
128
+ draws++
129
+ return DrawInput{
130
+ RequestID: fmt.Sprintf("req-%d", draws),
131
+ Categories: []string{"python"},
132
+ Size: 10,
133
+ Device: identity.Device{
134
+ MachineID: machine,
135
+ DiskUUID: disk,
136
+ OSFamily: "linux",
137
+ Arch: "x86_64",
138
+ },
139
+ RemoteAddr: netip.MustParseAddr(ip),
140
+ Headers: map[string][]string{},
141
+ }
142
+ }
143
+
144
+ const (
145
+ machA = "4c4c4544-0044-3510-8054-b4c04f4e4e32"
146
+ machB = "5d5d4544-0055-3510-8054-b4c04f4e4e33"
147
+ diskA = "9f1b2c3d4e5f60718293a4b5c6d7e8f9"
148
+ diskB = "aa2b3c4d5e6f708192a3b4c5d6e7f809"
149
+ )
150
+
151
+ func TestNewIdentityGetsDraw(t *testing.T) {
152
+ h := newHarness(t, 50)
153
+ g, err := h.svc.RequestDraw(context.Background(), input("203.0.113.10", machA, diskA))
154
+ if err != nil {
155
+ t.Fatalf("draw: %v", err)
156
+ }
157
+ if len(g.Examples) != 10 {
158
+ t.Fatalf("expected 10 examples, got %d", len(g.Examples))
159
+ }
160
+ if g.IdentityID == "" {
161
+ t.Fatal("expected an identity id")
162
+ }
163
+ if !g.NextDrawAt.After(g.IssuedAt) {
164
+ t.Fatal("next draw must be in the future")
165
+ }
166
+ }
167
+
168
+ func TestSameIdentityBlockedForOneHour(t *testing.T) {
169
+ h := newHarness(t, 50)
170
+ if _, err := h.svc.RequestDraw(context.Background(), input("203.0.113.10", machA, diskA)); err != nil {
171
+ t.Fatalf("first draw: %v", err)
172
+ }
173
+ h.advance(20 * time.Minute)
174
+ _, err := h.svc.RequestDraw(context.Background(), input("203.0.113.10", machA, diskA))
175
+ if err == nil {
176
+ t.Fatal("expected the second draw to be refused")
177
+ }
178
+ if !strings.Contains(err.Error(), "WINDOW_ACTIVE") {
179
+ t.Fatalf("expected WINDOW_ACTIVE, got %v", err)
180
+ }
181
+ }
182
+
183
+ func TestChangingOneMarkerStillMatches(t *testing.T) {
184
+ // The whole point of marker-set matching: rotating the IP alone is not a
185
+ // new person.
186
+ h := newHarness(t, 50)
187
+ if _, err := h.svc.RequestDraw(context.Background(), input("203.0.113.10", machA, diskA)); err != nil {
188
+ t.Fatalf("first draw: %v", err)
189
+ }
190
+ h.advance(5 * time.Minute)
191
+ _, err := h.svc.RequestDraw(context.Background(), input("198.51.100.99", machA, diskA))
192
+ if err == nil {
193
+ t.Fatal("same machine_id must still be the same person")
194
+ }
195
+
196
+ // Same story for the disk, on a fresh IP and machine id.
197
+ h2 := newHarness(t, 50)
198
+ if _, err := h2.svc.RequestDraw(context.Background(), input("203.0.113.10", machA, diskA)); err != nil {
199
+ t.Fatalf("first draw: %v", err)
200
+ }
201
+ h2.advance(5 * time.Minute)
202
+ if _, err := h2.svc.RequestDraw(context.Background(), input("198.51.100.99", machB, diskA)); err == nil {
203
+ t.Fatal("shared disk uuid must still match")
204
+ }
205
+ }
206
+
207
+ func TestAllMarkersNewIsNewPerson(t *testing.T) {
208
+ h := newHarness(t, 50)
209
+ if _, err := h.svc.RequestDraw(context.Background(), input("203.0.113.10", machA, diskA)); err != nil {
210
+ t.Fatalf("first draw: %v", err)
211
+ }
212
+ h.advance(5 * time.Minute)
213
+ // Every marker changed: this counts as a genuinely new caller.
214
+ if _, err := h.svc.RequestDraw(context.Background(), input("198.51.100.99", machB, diskB)); err != nil {
215
+ t.Fatalf("fully rotated identity should be allowed: %v", err)
216
+ }
217
+ }
218
+
219
+ func TestWindowExpiryAllowsSecondDraw(t *testing.T) {
220
+ h := newHarness(t, 50)
221
+ if _, err := h.svc.RequestDraw(context.Background(), input("203.0.113.10", machA, diskA)); err != nil {
222
+ t.Fatalf("first: %v", err)
223
+ }
224
+ h.advance(61 * time.Minute)
225
+ if _, err := h.svc.RequestDraw(context.Background(), input("203.0.113.10", machA, diskA)); err != nil {
226
+ t.Fatalf("draw after window should succeed: %v", err)
227
+ }
228
+ }
229
+
230
+ func TestSizeCapEnforced(t *testing.T) {
231
+ h := newHarness(t, 200)
232
+ in := input("203.0.113.10", machA, diskA)
233
+ in.Size = 76
234
+ if _, err := h.svc.RequestDraw(context.Background(), in); err == nil {
235
+ t.Fatal("expected size above DrawMax to fail")
236
+ }
237
+ in.Size = 75
238
+ if _, err := h.svc.RequestDraw(context.Background(), in); err != nil {
239
+ t.Fatalf("75 should be allowed: %v", err)
240
+ }
241
+ }
242
+
243
+ func TestBurstSpamBans(t *testing.T) {
244
+ h := newHarness(t, 200)
245
+ var lastErr error
246
+ for i := 0; i < 20; i++ {
247
+ in := input("203.0.113.10", machA, diskA)
248
+ in.RequestID = fmt.Sprintf("req-%d", i)
249
+ h.advance(200 * time.Millisecond)
250
+ if _, err := h.svc.RequestDraw(context.Background(), in); err != nil {
251
+ lastErr = err
252
+ if strings.Contains(err.Error(), "SPAM") {
253
+ break
254
+ }
255
+ }
256
+ }
257
+ if lastErr == nil || !strings.Contains(lastErr.Error(), "SPAM") {
258
+ t.Fatalf("expected a spam ban, got %v", lastErr)
259
+ }
260
+ }
261
+
262
+ // A ban is stamped with a real duration and enforced until it expires, not just
263
+ // for the length of the draw window. The old version of this test asserted a
264
+ // fixed multi-hour ban; bans are now proportional to the offence, so a modest
265
+ // overshoot earns minutes and the test checks the ban is actually in force
266
+ // rather than checking a particular number.
267
+ func TestBanEnforcedUntilItExpires(t *testing.T) {
268
+ h := newHarness(t, 200)
269
+ for i := 0; i < 20; i++ {
270
+ in := input("203.0.113.10", machA, diskA)
271
+ in.RequestID = fmt.Sprintf("r%d", i)
272
+ h.advance(200 * time.Millisecond)
273
+ h.svc.RequestDraw(context.Background(), in)
274
+ }
275
+
276
+ // Partway through the ban the caller is still refused, and the refusal
277
+ // reports roughly the time left rather than the original duration.
278
+ h.advance(5 * time.Minute)
279
+ _, err := h.svc.RequestDraw(context.Background(), input("203.0.113.10", machA, diskA))
280
+ if err == nil {
281
+ t.Fatal("expected a refusal during the ban")
282
+ }
283
+ if !strings.Contains(err.Error(), "SPAM_RATE") && !strings.Contains(err.Error(), "BANNED") {
284
+ t.Fatalf("expected a ban refusal, got %v", err)
285
+ }
286
+ }
287
+
288
+ // After the ban expires the caller is served again, which is what makes a short
289
+ // proportional ban acceptable: it is a delay, not a life sentence.
290
+ func TestShortBanExpiresAndAllows(t *testing.T) {
291
+ h := newHarness(t, 200)
292
+ for i := 0; i < 20; i++ {
293
+ in := input("203.0.113.11", machA, diskA)
294
+ in.RequestID = fmt.Sprintf("r%d", i)
295
+ h.advance(200 * time.Millisecond)
296
+ h.svc.RequestDraw(context.Background(), in)
297
+ }
298
+ // Past both the ban and the draw window.
299
+ h.advance(2 * time.Hour)
300
+ if _, err := h.svc.RequestDraw(context.Background(), input("203.0.113.11", machA, diskA)); err != nil {
301
+ t.Fatalf("an expired ban must stop blocking: %v", err)
302
+ }
303
+ }
304
+
305
+ func TestStockShortfallReported(t *testing.T) {
306
+ h := newHarness(t, 4)
307
+ g, err := h.svc.RequestDraw(context.Background(), input("203.0.113.10", machA, diskA))
308
+ if err != nil {
309
+ t.Fatalf("draw: %v", err)
310
+ }
311
+ if len(g.Examples) != 4 {
312
+ t.Fatalf("expected 4 examples, got %d", len(g.Examples))
313
+ }
314
+ if g.Shortfall != 6 {
315
+ t.Fatalf("expected shortfall 6, got %d", g.Shortfall)
316
+ }
317
+ }
318
+
319
+ func TestUnknownCategoryRejected(t *testing.T) {
320
+ h := newHarness(t, 10)
321
+ in := input("203.0.113.10", machA, diskA)
322
+ in.Categories = []string{"cobol"}
323
+ if _, err := h.svc.RequestDraw(context.Background(), in); err == nil {
324
+ t.Fatal("expected unknown category to fail")
325
+ }
326
+ }
327
+
328
+ func TestUsageCountedAndStaleAfterThree(t *testing.T) {
329
+ h := newHarness(t, 1)
330
+ identities := []struct{ ip, machine, disk string }{
331
+ {"203.0.113.10", machA, diskA},
332
+ }
333
+ if _, err := h.svc.RequestDraw(context.Background(), input(identities[0].ip, identities[0].machine, identities[0].disk)); err != nil {
334
+ t.Fatalf("first: %v", err)
335
+ }
336
+ if got := h.bankM.Uses("py-000"); got != 1 {
337
+ t.Fatalf("expected 1 use, got %d", got)
338
+ }
339
+ // Two more distinct callers consume the remaining allowed uses.
340
+ others := [][3]string{
341
+ {"203.0.114.11", machB, diskB},
342
+ {"203.0.115.12", "6e6e4544-0066-3510-8054-b4c04f4e4e34", "bb3b4c5d6e7f8091a2b3c4d5e6f70819"},
343
+ }
344
+ for _, o := range others {
345
+ h.advance(2 * time.Hour)
346
+ if _, err := h.svc.RequestDraw(context.Background(), input(o[0], o[1], o[2])); err != nil {
347
+ t.Fatalf("draw for %s: %v", o[0], err)
348
+ }
349
+ }
350
+ if got := h.bankM.Uses("py-000"); got != 3 {
351
+ t.Fatalf("expected 3 uses, got %d", got)
352
+ }
353
+ if stale := h.svc.StaleExamples(); len(stale) != 1 || stale[0].ID != "py-000" {
354
+ t.Fatalf("py-000 should be stale: %+v", stale)
355
+ }
356
+ // A further caller gets nothing: the only example is out of circulation.
357
+ h.advance(2 * time.Hour)
358
+ _, err := h.svc.RequestDraw(context.Background(), input("203.0.116.13", "7f7f4544-0077-3510-8054-b4c04f4e4e35", "cc4c5d6e7f8091a2b3c4d5e6f70819aa"))
359
+ if err == nil {
360
+ t.Fatal("expected no stock once every example is stale")
361
+ }
362
+ }
363
+
364
+ func TestRespectsProxyHeadersForDifferentiation(t *testing.T) {
365
+ h := newHarness(t, 50)
366
+ in := input("10.0.0.1", machA, diskA)
367
+ in.Headers = map[string][]string{identity.HeaderForwardedFor: {"203.0.113.50"}}
368
+ in.RemoteAddr = netip.MustParseAddr("198.51.100.7")
369
+ g, err := h.svc.RequestDraw(context.Background(), in)
370
+ if err != nil {
371
+ t.Fatalf("draw: %v", err)
372
+ }
373
+ // The record must be keyed on the socket address, not the forwarded header
374
+ // (which the client controls), and it must contain no raw value at all.
375
+ rec, ok := h.store.Get(g.IdentityID)
376
+ if !ok {
377
+ t.Fatal("expected a record")
378
+ }
379
+ wantIP := h.svc.Hash(identity.MarkerIP, "198.51.100.7")
380
+ found := false
381
+ for _, m := range rec.Markers {
382
+ if m == wantIP {
383
+ found = true
384
+ }
385
+ }
386
+ if !found {
387
+ t.Fatalf("record is not keyed on the socket address; markers=%v", rec.Markers)
388
+ }
389
+ }
390
+
391
+ // Identity is "IP OR machine_id OR disk_uuid": any single marker must be enough
392
+ // to serve and to recognise the caller. Requiring both device fields locked out
393
+ // any runner that could only read one of them.
394
+ func TestAnySingleMarkerIsEnough(t *testing.T) {
395
+ cases := []struct {
396
+ name string
397
+ machine, disk string
398
+ wantMarkers int // 1 for IP alone, 3 for IP + both
399
+ }{
400
+ {"ip only", "", "", 1},
401
+ {"machine only", machA, "", 2},
402
+ {"disk only", "", diskA, 2},
403
+ {"both", machA, diskA, 3},
404
+ }
405
+ for _, c := range cases {
406
+ t.Run(c.name, func(t *testing.T) {
407
+ h := newHarness(t, 10)
408
+ g, err := h.svc.RequestDraw(context.Background(), input("203.0.113.20", c.machine, c.disk))
409
+ if err != nil {
410
+ t.Fatalf("draw with %s: %v", c.name, err)
411
+ }
412
+ rec, ok := h.store.Get(g.IdentityID)
413
+ if !ok {
414
+ t.Fatal("expected a record")
415
+ }
416
+ if len(rec.Markers) != c.wantMarkers {
417
+ t.Fatalf("markers = %d, want %d: %v", len(rec.Markers), c.wantMarkers, rec.Markers)
418
+ }
419
+ })
420
+ }
421
+ }
422
+
423
+ // An absent device field must contribute no marker at all. If it were hashed,
424
+ // every caller without that field would share one hash and collapse into a
425
+ // single identity, which would be both wrong and a trivial denial of service.
426
+ func TestAbsentFieldProducesNoMarker(t *testing.T) {
427
+ h := newHarness(t, 10)
428
+ g, err := h.svc.RequestDraw(context.Background(), input("203.0.113.21", "", ""))
429
+ if err != nil {
430
+ t.Fatal(err)
431
+ }
432
+ rec, _ := h.store.Get(g.IdentityID)
433
+ empty := h.svc.Hash(identity.MarkerMachineID, "")
434
+ for _, m := range rec.Markers {
435
+ if m == empty {
436
+ t.Fatal("an absent machine_id produced a marker; every such caller would share it")
437
+ }
438
+ }
439
+ }
440
+
441
+ func TestInvalidDeviceRejected(t *testing.T) {
442
+ h := newHarness(t, 10)
443
+ // Present but fabricated: refused rather than hashed into a marker that
444
+ // would never match again.
445
+ for _, bad := range []string{"unknown", "none", "00000000-0000-0000-0000-000000000000"} {
446
+ if _, err := h.svc.RequestDraw(context.Background(), input("203.0.113.10", bad, diskA)); err == nil {
447
+ t.Fatalf("expected placeholder machine id %q to be rejected", bad)
448
+ }
449
+ }
450
+ // Too short to be a real identifier.
451
+ if _, err := h.svc.RequestDraw(context.Background(), input("203.0.113.10", "abc", "")); err == nil {
452
+ t.Fatal("expected an implausibly short machine id to be rejected")
453
+ }
454
+ }
455
+
456
+ func TestReputationBlocksTor(t *testing.T) {
457
+ h := newHarness(t, 10)
458
+ dir := t.TempDir()
459
+ path := filepath.Join(dir, "rep.json")
460
+ body := `{"entries":[{"cidr":"203.0.113.0/24","tor":true}]}`
461
+ if err := os.WriteFile(path, []byte(body), 0o640); err != nil {
462
+ t.Fatal(err)
463
+ }
464
+ rep, err := reputation.Load(path)
465
+ if err != nil {
466
+ t.Fatal(err)
467
+ }
468
+ h.svc.rep = rep
469
+ _, err = h.svc.RequestDraw(context.Background(), input("203.0.113.10", machA, diskA))
470
+ if err == nil || !strings.Contains(err.Error(), "PRIVACY_BLOCKED") {
471
+ t.Fatalf("expected tor exit to be blocked, got %v", err)
472
+ }
473
+ }
474
+
475
+ func TestEventsRecorded(t *testing.T) {
476
+ h := newHarness(t, 50)
477
+ if _, err := h.svc.RequestDraw(context.Background(), input("203.0.113.10", machA, diskA)); err != nil {
478
+ t.Fatal(err)
479
+ }
480
+ entries, err := os.ReadDir(filepath.Join(h.cfg.DataDir, "events"))
481
+ if err != nil {
482
+ t.Fatalf("events dir: %v", err)
483
+ }
484
+ if len(entries) == 0 {
485
+ t.Fatal("expected an event log file")
486
+ }
487
+ buf, err := os.ReadFile(filepath.Join(h.cfg.DataDir, "events", entries[0].Name()))
488
+ if err != nil {
489
+ t.Fatal(err)
490
+ }
491
+ if !strings.Contains(string(buf), `"decision":"allow"`) {
492
+ t.Fatalf("expected an allow event, got %s", buf)
493
+ }
494
+ }
495
+
496
+ // The strongest privacy guarantee the system can make: after a full request
497
+ // cycle, not one byte on disk contains the IP or the device identifiers.
498
+ func TestNoRawIdentityAnywhereOnDisk(t *testing.T) {
499
+ h := newHarness(t, 50)
500
+ g, err := h.svc.RequestDraw(context.Background(), input("203.0.113.10", machA, diskA))
501
+ if err != nil {
502
+ t.Fatal(err)
503
+ }
504
+ if err := h.svc.Flush(); err != nil {
505
+ t.Fatal(err)
506
+ }
507
+
508
+ secrets := []string{"203.0.113.10", machA, diskA, machA[:8], diskA[:8]}
509
+ err = filepath.WalkDir(h.cfg.DataDir, func(path string, d os.DirEntry, err error) error {
510
+ if err != nil || d.IsDir() {
511
+ return nil
512
+ }
513
+ buf, err := os.ReadFile(path)
514
+ if err != nil {
515
+ return nil
516
+ }
517
+ for _, secret := range secrets {
518
+ if strings.Contains(string(buf), secret) {
519
+ t.Errorf("%s contains raw identity value %q", path, secret)
520
+ }
521
+ }
522
+ // Also assert the shard tree has no raw subtree at all.
523
+ if strings.Contains(filepath.ToSlash(path), "/raw/") {
524
+ t.Errorf("unexpected raw subtree entry: %s", path)
525
+ }
526
+ return nil
527
+ })
528
+ if err != nil {
529
+ t.Fatalf("walk: %v", err)
530
+ }
531
+ if _, ok := h.store.Get(g.IdentityID); !ok {
532
+ t.Fatal("the hashed record should still exist")
533
+ }
534
+ }
535
+
536
+ func TestHealthReportsBank(t *testing.T) {
537
+ h := newHarness(t, 5)
538
+ health := h.svc.Health()
539
+ if !health.OK {
540
+ t.Fatal("health should be OK with stock")
541
+ }
542
+ if health.Inventory.Total != 5 {
543
+ t.Fatalf("expected 5 total, got %d", health.Inventory.Total)
544
+ }
545
+ }
546
+
547
+ func TestPruneClearsBansButKeepsMemory(t *testing.T) {
548
+ h := newHarness(t, 50)
549
+ g, err := h.svc.RequestDraw(context.Background(), input("203.0.113.10", machA, diskA))
550
+ if err != nil {
551
+ t.Fatal(err)
552
+ }
553
+ rec, _ := h.store.Get(g.IdentityID)
554
+ rec.BannedUntil = h.now.Add(-time.Minute)
555
+ rec.BanReason = "SPAM_BURST"
556
+ if err := h.store.Put(rec); err != nil {
557
+ t.Fatal(err)
558
+ }
559
+
560
+ cleared, err := h.svc.Prune()
561
+ if err != nil {
562
+ t.Fatalf("prune: %v", err)
563
+ }
564
+ if cleared != 1 {
565
+ t.Fatalf("expected 1 ban cleared, got %d", cleared)
566
+ }
567
+ after, ok := h.store.Get(g.IdentityID)
568
+ if !ok {
569
+ t.Fatal("hashed record must survive pruning")
570
+ }
571
+ if !after.BannedUntil.IsZero() {
572
+ t.Fatal("expired ban should be cleared")
573
+ }
574
+ }
575
+
576
+ func shardOf(id string) string { return store.ShardOf(id) }
577
+
578
+ // The server is the only source of a draw id. A caller that supplies one is
579
+ // not told "no" -- it is told to think again, and the id it sent is never used.
580
+ // This is what makes two callers unable to collide on a handle: neither one can
581
+ // choose it.
582
+ func TestCallerSuppliedRequestIDIsIgnored(t *testing.T) {
583
+ h := newHarness(t, 20)
584
+
585
+ first := input("203.0.113.10", machA, diskA)
586
+ first.RequestID = "i-picked-this"
587
+ grant, err := h.svc.RequestDraw(context.Background(), first)
588
+ if err != nil {
589
+ t.Fatalf("draw: %v", err)
590
+ }
591
+ if grant.RequestID == "i-picked-this" {
592
+ t.Fatal("the caller's request_id became the draw id")
593
+ }
594
+ if grant.RequestID == "" {
595
+ t.Fatal("the server must mint a draw id")
596
+ }
597
+ if len(grant.RequestID) != 32 {
598
+ t.Fatalf("expected a 128-bit hex id, got %q", grant.RequestID)
599
+ }
600
+
601
+ // The caller's value must not exist in the ledger either: it was not used.
602
+ if _, ok := h.store.LeaseLedger("i-picked-this"); ok {
603
+ t.Fatal("the caller's id leaked into the ledger")
604
+ }
605
+ if _, ok := h.store.LeaseLedger(grant.RequestID); !ok {
606
+ t.Fatal("the minted id must be in the ledger")
607
+ }
608
+ }
609
+
610
+ // Two callers sending the SAME id must not collide, because neither id is used.
611
+ func TestTwoCallersCannotShareADrawID(t *testing.T) {
612
+ h := newHarness(t, 20)
613
+
614
+ first := input("203.0.113.10", machA, diskA)
615
+ first.RequestID = "same-value"
616
+ a, err := h.svc.RequestDraw(context.Background(), first)
617
+ if err != nil {
618
+ t.Fatalf("first draw: %v", err)
619
+ }
620
+
621
+ h.advance(2 * time.Hour)
622
+ second := input("198.51.100.7", machB, diskB)
623
+ second.RequestID = "same-value"
624
+ b, err := h.svc.RequestDraw(context.Background(), second)
625
+ if err != nil {
626
+ t.Fatalf("second draw must not be refused: %v", err)
627
+ }
628
+
629
+ if a.RequestID == b.RequestID {
630
+ t.Fatal("two draws were issued the same id")
631
+ }
632
+ // Both must be independently reportable: that is the whole point.
633
+ if _, ok := h.store.LeaseLedger(a.RequestID); !ok {
634
+ t.Fatal("the first draw is no longer in the ledger")
635
+ }
636
+ if _, ok := h.store.LeaseLedger(b.RequestID); !ok {
637
+ t.Fatal("the second draw is not in the ledger")
638
+ }
639
+ }
640
+
641
+ // A minted id must not be predictable from another one.
642
+ func TestRequestIDsAreNotSequential(t *testing.T) {
643
+ seen := map[string]bool{}
644
+ for i := 0; i < 100; i++ {
645
+ id := NewRequestID()
646
+ if len(id) != 32 {
647
+ t.Fatalf("expected 32 hex chars, got %d (%q)", len(id), id)
648
+ }
649
+ if seen[id] {
650
+ t.Fatalf("minted a duplicate id: %q", id)
651
+ }
652
+ seen[id] = true
653
+ }
654
+ }
655
+
656
+ // Omitting the id is the normal path and must keep working: the relay mints one.
657
+ func TestMissingRequestIDIsMinted(t *testing.T) {
658
+ h := newHarness(t, 5)
659
+ in := input("203.0.113.10", machA, diskA)
660
+ in.RequestID = ""
661
+ grant, err := h.svc.RequestDraw(context.Background(), in)
662
+ if err != nil {
663
+ t.Fatalf("draw: %v", err)
664
+ }
665
+ if grant.RequestID == "" {
666
+ t.Fatal("the relay must mint a request id")
667
+ }
668
+ if _, ok := h.store.LeaseLedger(grant.RequestID); !ok {
669
+ t.Fatal("the minted id must be in the ledger")
670
+ }
671
+ }
672
+
673
+ // The lifeline belongs to the example, not to the person who drew it. Two
674
+ // different machines asking for the same question spend one shared budget, and
675
+ // a grant reports what is left so a runner can show it before it goes stale.
676
+ func TestLifelineIsSharedBetweenDifferentCallers(t *testing.T) {
677
+ h := newHarness(t, 1) // exactly one example: every draw must take it
678
+
679
+ for i := 0; i < 3; i++ {
680
+ h.advance(2 * time.Hour) // step past the draw window each time
681
+ in := input("203.0.113."+fmt.Sprint(10+i), machA, diskA)
682
+ in.Size = 1
683
+ grant, err := h.svc.RequestDraw(context.Background(), in)
684
+ if err != nil {
685
+ t.Fatalf("draw %d: %v", i, err)
686
+ }
687
+ if len(grant.Examples) != 1 {
688
+ t.Fatalf("draw %d served %d examples", i, len(grant.Examples))
689
+ }
690
+ life := grant.Lifeline[grant.Examples[0].ID]
691
+ if life.Used != i+1 {
692
+ t.Fatalf("draw %d: expected used=%d, got %d", i, i+1, life.Used)
693
+ }
694
+ if life.Max != 3 {
695
+ t.Fatalf("draw %d: expected max=3, got %d", i, life.Max)
696
+ }
697
+ if life.Remaining != 2-i {
698
+ t.Fatalf("draw %d: expected remaining=%d, got %d", i, 2-i, life.Remaining)
699
+ }
700
+ if grant.StaleAfter != 3 {
701
+ t.Fatalf("draw %d: expected stale_after=3, got %d", i, grant.StaleAfter)
702
+ }
703
+ }
704
+
705
+ // The third serve exhausted it, so a fourth caller gets nothing usable.
706
+ h.advance(2 * time.Hour)
707
+ in := input("198.51.100.99", machA, diskA)
708
+ in.Size = 1
709
+ if _, err := h.svc.RequestDraw(context.Background(), in); err == nil {
710
+ t.Fatal("a stale example must not be served again")
711
+ }
712
+ }
internal/core/persistence_test.go ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package core
2
+
3
+ import (
4
+ "context"
5
+ "fmt"
6
+ "path/filepath"
7
+ "strings"
8
+ "testing"
9
+ "time"
10
+
11
+ "github.com/archnemix/archx-eval/relay/internal/bank"
12
+ "github.com/archnemix/archx-eval/relay/internal/ratelog"
13
+ "github.com/archnemix/archx-eval/relay/internal/reputation"
14
+ "github.com/archnemix/archx-eval/relay/internal/store"
15
+ )
16
+
17
+ // reboot simulates a Hugging Face Space restart: brand new Service, Store and
18
+ // rate log objects built from the same on-disk state. Nothing persists in
19
+ // memory, exactly as when the container is stopped and started again.
20
+ func (h *harness) reboot(t *testing.T) *harness {
21
+ t.Helper()
22
+ st, err := store.Open(h.cfg.DataDir)
23
+ if err != nil {
24
+ t.Fatalf("reopen store: %v", err)
25
+ }
26
+ bm, err := bank.Load(h.cfg.BankDir, h.cfg.StaleAfterUses)
27
+ if err != nil {
28
+ t.Fatalf("reload bank: %v", err)
29
+ }
30
+ rep, _ := reputation.Load("")
31
+ // Opened on the harness clock: load applies the retention cutoff, and the
32
+ // harness date is frozen, so the wall clock would discard everything.
33
+ now := h.now
34
+ rates, err := ratelog.OpenAt(h.cfg.RateDir, 96*time.Hour, func() time.Time { return now })
35
+ if err != nil {
36
+ t.Fatalf("reopen ratelog: %v", err)
37
+ }
38
+ t.Cleanup(func() { _ = rates.Close() })
39
+
40
+ svc := New(h.cfg, st, bm, rep, rates)
41
+ next := &harness{svc: svc, bankM: bm, cfg: h.cfg, now: h.now, store: st, rates: rates}
42
+ svc.SetClock(func() time.Time { return next.now })
43
+ rates.SetClock(func() time.Time { return next.now })
44
+ return next
45
+ }
46
+
47
+ // The headline fix: a flusher must not be able to reset their own ban by
48
+ // forcing the Space to restart.
49
+ func TestBurstBanSurvivesRestart(t *testing.T) {
50
+ h := newHarness(t, 200)
51
+
52
+ var banned bool
53
+ for i := 0; i < 40; i++ {
54
+ in := input("203.0.113.10", machA, diskA)
55
+ in.RequestID = fmt.Sprintf("r%d", i)
56
+ h.advance(100 * time.Millisecond)
57
+ if _, err := h.svc.RequestDraw(context.Background(), in); err != nil &&
58
+ strings.Contains(err.Error(), "SPAM") {
59
+ banned = true
60
+ break
61
+ }
62
+ }
63
+ if !banned {
64
+ t.Fatal("expected the burst limit to trip before restart")
65
+ }
66
+
67
+ // Restart immediately: the ban must still be in force.
68
+ after := h.reboot(t)
69
+ _, err := after.svc.RequestDraw(context.Background(), input("203.0.113.10", machA, diskA))
70
+ if err == nil {
71
+ t.Fatal("a restart must not clear the ban")
72
+ }
73
+ if !strings.Contains(err.Error(), "BANNED") && !strings.Contains(err.Error(), "SPAM") {
74
+ t.Fatalf("expected still banned, got %v", err)
75
+ }
76
+ }
77
+
78
+ // Even before a ban is stamped on the record, the request history itself must
79
+ // survive, so the ladder continues counting from where it left off.
80
+ func TestRateHistorySurvivesRestart(t *testing.T) {
81
+ h := newHarness(t, 200)
82
+ for i := 0; i < 10; i++ {
83
+ in := input("203.0.113.10", machA, diskA)
84
+ in.RequestID = fmt.Sprintf("r%d", i)
85
+ h.advance(200 * time.Millisecond)
86
+ _, _ = h.svc.RequestDraw(context.Background(), in)
87
+ }
88
+ before := h.rates.Count("id:"+h.svc.Hash("ip", "203.0.113.10"), time.Minute, h.now)
89
+ if before < 10 {
90
+ t.Fatalf("expected >=10 events recorded, got %d", before)
91
+ }
92
+
93
+ after := h.reboot(t)
94
+ got := after.rates.Count("id:"+after.svc.Hash("ip", "203.0.113.10"), time.Minute, after.now)
95
+ if got < before {
96
+ t.Fatalf("restart lost rate history: before=%d after=%d", before, got)
97
+ }
98
+ }
99
+
100
+ // The 1-hour draw window must also survive, since it lives in the record.
101
+ func TestDrawWindowSurvivesRestart(t *testing.T) {
102
+ h := newHarness(t, 50)
103
+ if _, err := h.svc.RequestDraw(context.Background(), input("203.0.113.10", machA, diskA)); err != nil {
104
+ t.Fatalf("first draw: %v", err)
105
+ }
106
+ after := h.reboot(t)
107
+ after.advance(5 * time.Minute)
108
+ if _, err := after.svc.RequestDraw(context.Background(), input("203.0.113.10", machA, diskA)); err == nil {
109
+ t.Fatal("window must still be active after a restart")
110
+ }
111
+ }
112
+
113
+ func TestUsageCountersSurviveRestart(t *testing.T) {
114
+ h := newHarness(t, 50)
115
+ grant, err := h.svc.RequestDraw(context.Background(), input("203.0.113.10", machA, diskA))
116
+ if err != nil {
117
+ t.Fatal(err)
118
+ }
119
+ if len(grant.Examples) == 0 {
120
+ t.Fatal("expected examples")
121
+ }
122
+ issued := grant.Examples[0].ID
123
+ if err := h.svc.Flush(); err != nil {
124
+ t.Fatal(err)
125
+ }
126
+
127
+ after := h.reboot(t)
128
+ if got := after.bankM.Uses(issued); got != 1 {
129
+ t.Fatalf("use counter for %s should survive, got %d", issued, got)
130
+ }
131
+ }
132
+
133
+ func TestAccessTokenRequired(t *testing.T) {
134
+ h := newHarness(t, 20)
135
+ if err := h.svc.Authenticate("wrong"); err == nil {
136
+ t.Fatal("wrong token must be rejected")
137
+ }
138
+ if err := h.svc.Authenticate(""); err == nil {
139
+ t.Fatal("empty token must be rejected")
140
+ }
141
+ if err := h.svc.Authenticate("test-access-token"); err != nil {
142
+ t.Fatalf("correct token rejected: %v", err)
143
+ }
144
+ }
145
+
146
+ func TestNoTokenConfiguredMeansClosed(t *testing.T) {
147
+ h := newHarness(t, 20)
148
+ h.svc.cfg.AccessToken = ""
149
+ if err := h.svc.Authenticate("anything"); err == nil {
150
+ t.Fatal("a relay with no token configured must refuse draws, not allow them")
151
+ }
152
+ }
153
+
154
+ func TestNetworkCeiling(t *testing.T) {
155
+ h := newHarness(t, 200)
156
+ h.svc.cfg.NetWindow = time.Hour
157
+ h.svc.cfg.NetMaxDraws = 3
158
+
159
+ allowed := 0
160
+ for i := 0; i < 12; i++ {
161
+ // Distinct identities on the same /24: the per-identity ladder never
162
+ // trips, so only the subnet ceiling can stop this.
163
+ ip := fmt.Sprintf("203.0.113.%d", i+10)
164
+ in := input(ip, fmt.Sprintf("machine-%016d", i), fmt.Sprintf("disk-%016d", i))
165
+ in.Size = 1
166
+ h.advance(30 * time.Second)
167
+ if _, err := h.svc.RequestDraw(context.Background(), in); err != nil {
168
+ if strings.Contains(err.Error(), "NETWORK_CEILING") {
169
+ break
170
+ }
171
+ t.Fatalf("unexpected error: %v", err)
172
+ }
173
+ allowed++
174
+ }
175
+ if allowed > 5 {
176
+ t.Fatalf("subnet ceiling should have stopped this, allowed=%d", allowed)
177
+ }
178
+ }
179
+
180
+ func TestGlobalCeiling(t *testing.T) {
181
+ h := newHarness(t, 200)
182
+ h.svc.cfg.GlobalWindow = time.Hour
183
+ h.svc.cfg.GlobalMax = 2
184
+ h.svc.cfg.NetMaxDraws = 100000
185
+
186
+ stopped := false
187
+ for i := 0; i < 12; i++ {
188
+ in := input(fmt.Sprintf("198.51.%d.%d", i, i+1),
189
+ fmt.Sprintf("machine-%016d", i), fmt.Sprintf("disk-%016d", i))
190
+ in.Size = 1
191
+ h.advance(30 * time.Second)
192
+ if _, err := h.svc.RequestDraw(context.Background(), in); err != nil {
193
+ if strings.Contains(err.Error(), "GLOBAL_CEILING") {
194
+ stopped = true
195
+ break
196
+ }
197
+ }
198
+ }
199
+ if !stopped {
200
+ t.Fatal("global ceiling never triggered")
201
+ }
202
+ }
203
+
204
+ func TestRateLogDirectoryIsSeparate(t *testing.T) {
205
+ h := newHarness(t, 20)
206
+ if _, err := h.svc.RequestDraw(context.Background(), input("203.0.113.10", machA, diskA)); err != nil {
207
+ t.Fatal(err)
208
+ }
209
+ // The mirrored dataset tree must not accidentally include rate state.
210
+ if filepath.Dir(h.cfg.RateDir) != filepath.Dir(h.cfg.DataDir) {
211
+ t.Fatalf("rate dir should sit beside the data dir, got %s", h.cfg.RateDir)
212
+ }
213
+ if strings.HasPrefix(h.cfg.RateDir, h.cfg.DataDir) {
214
+ t.Fatal("rate dir must not be inside the exported data tree")
215
+ }
216
+ }
internal/draw/draw.go CHANGED
@@ -100,20 +100,31 @@ func Select(m *bank.Manager, req Request) (*Result, error) {
100
  }
101
  }
102
 
 
 
 
 
 
 
 
 
 
 
 
103
  // Hand out the proportional share first.
104
  taken := map[string]int{}
105
  for _, cat := range cats {
106
  n := desired[cat]
107
- if n > len(pools[cat]) {
108
- n = len(pools[cat])
109
  }
110
  if n <= 0 {
111
  continue
112
  }
113
- picked := sample(pools[cat], n)
114
  res.Examples = append(res.Examples, picked...)
115
- taken[cat] = len(picked)
116
- remaining -= len(picked) - desired[cat]
117
  }
118
 
119
  // Distribute the remainder to any category that still has stock.
@@ -123,12 +134,12 @@ func Select(m *bank.Manager, req Request) (*Result, error) {
123
  if remaining <= 0 {
124
  break
125
  }
126
- spare := len(pools[cat]) - taken[cat]
127
- if spare <= 0 {
 
128
  continue
129
  }
130
- extra := sample(pools[cat][taken[cat]:], 1)
131
- res.Examples = append(res.Examples, extra...)
132
  taken[cat]++
133
  remaining--
134
  progressed = true
@@ -196,6 +207,14 @@ func sample(pool []*bank.Example, n int) []*bank.Example {
196
  return tmp[:n]
197
  }
198
 
 
 
 
 
 
 
 
 
199
  func shuffleExamples(list []*bank.Example) {
200
  for i := len(list) - 1; i > 0; i-- {
201
  j := randIndex(i + 1)
 
100
  }
101
  }
102
 
103
+ // Shuffle each category once and draw from the front of that deck. The
104
+ // earlier code sampled the proportional share at random and then sliced
105
+ // pools[cat][taken:] for the remainder, so the second pass could hand out
106
+ // an example the first pass had already picked. A grant with the same
107
+ // question twice is unusable: the reporter sends two answers for one id and
108
+ // the feedback endpoint refuses the whole report as a duplicate.
109
+ decks := make(map[string][]*bank.Example, len(cats))
110
+ for _, cat := range cats {
111
+ decks[cat] = shuffledCopy(pools[cat])
112
+ }
113
+
114
  // Hand out the proportional share first.
115
  taken := map[string]int{}
116
  for _, cat := range cats {
117
  n := desired[cat]
118
+ if n > len(decks[cat]) {
119
+ n = len(decks[cat])
120
  }
121
  if n <= 0 {
122
  continue
123
  }
124
+ picked := decks[cat][:n]
125
  res.Examples = append(res.Examples, picked...)
126
+ taken[cat] = n
127
+ remaining -= n - desired[cat]
128
  }
129
 
130
  // Distribute the remainder to any category that still has stock.
 
134
  if remaining <= 0 {
135
  break
136
  }
137
+ // Both passes draw from the same shuffled deck and the index only
138
+ // moves forward, so an example can never be issued twice.
139
+ if taken[cat] >= len(decks[cat]) {
140
  continue
141
  }
142
+ res.Examples = append(res.Examples, decks[cat][taken[cat]])
 
143
  taken[cat]++
144
  remaining--
145
  progressed = true
 
207
  return tmp[:n]
208
  }
209
 
210
+ // shuffledCopy returns a randomly ordered copy; the pool itself is not touched.
211
+ func shuffledCopy(pool []*bank.Example) []*bank.Example {
212
+ out := make([]*bank.Example, len(pool))
213
+ copy(out, pool)
214
+ shuffleExamples(out)
215
+ return out
216
+ }
217
+
218
  func shuffleExamples(list []*bank.Example) {
219
  for i := len(list) - 1; i > 0; i-- {
220
  j := randIndex(i + 1)
internal/draw/draw_test.go ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package draw
2
+
3
+ import (
4
+ "os"
5
+ "path/filepath"
6
+ "strings"
7
+ "testing"
8
+ "time"
9
+
10
+ "github.com/archnemix/archx-eval/relay/internal/bank"
11
+ )
12
+
13
+ func row(id, cat, diff string) string {
14
+ return `{"id":"` + id + `","category":"` + cat + `","difficulty":"` + diff + `","kind":"qa","prompt":"p","expected_answer":"a"}`
15
+ }
16
+
17
+ func bankWith(t *testing.T, counts map[string]int) *bank.Manager {
18
+ t.Helper()
19
+ dir := t.TempDir()
20
+ for cat, n := range counts {
21
+ var b strings.Builder
22
+ for i := 0; i < n; i++ {
23
+ b.WriteString(row(cat+"-"+string(rune('a'+i)), cat, "easy") + "\n")
24
+ }
25
+ path := filepath.Join(dir, cat, "easy.jsonl")
26
+ if err := os.MkdirAll(filepath.Dir(path), 0o750); err != nil {
27
+ t.Fatal(err)
28
+ }
29
+ if err := os.WriteFile(path, []byte(b.String()), 0o640); err != nil {
30
+ t.Fatal(err)
31
+ }
32
+ }
33
+ m, err := bank.Load(dir, 3)
34
+ if err != nil {
35
+ t.Fatalf("load: %v", err)
36
+ }
37
+ return m
38
+ }
39
+
40
+ func TestSelectRespectsSize(t *testing.T) {
41
+ m := bankWith(t, map[string]int{"python": 100})
42
+ res, err := Select(m, Request{Categories: []string{"python"}, Size: 75})
43
+ if err != nil {
44
+ t.Fatalf("select: %v", err)
45
+ }
46
+ if len(res.Examples) != 75 {
47
+ t.Fatalf("expected 75, got %d", len(res.Examples))
48
+ }
49
+ if res.ByCat["python"] != 75 {
50
+ t.Fatalf("bad per-category count: %v", res.ByCat)
51
+ }
52
+ }
53
+
54
+ func TestSelectNeverDuplicates(t *testing.T) {
55
+ m := bankWith(t, map[string]int{"python": 50})
56
+ res, err := Select(m, Request{Categories: []string{"python"}, Size: 50})
57
+ if err != nil {
58
+ t.Fatal(err)
59
+ }
60
+ seen := map[string]bool{}
61
+ for _, ex := range res.Examples {
62
+ if seen[ex.ID] {
63
+ t.Fatalf("duplicate example %s", ex.ID)
64
+ }
65
+ seen[ex.ID] = true
66
+ }
67
+ }
68
+
69
+ func TestSelectSplitsAcrossCategories(t *testing.T) {
70
+ m := bankWith(t, map[string]int{"python": 60, "logic": 60})
71
+ res, err := Select(m, Request{Categories: []string{"python", "logic"}, Size: 40})
72
+ if err != nil {
73
+ t.Fatal(err)
74
+ }
75
+ if res.ByCat["python"] == 0 || res.ByCat["logic"] == 0 {
76
+ t.Fatalf("both categories should be represented: %v", res.ByCat)
77
+ }
78
+ if len(res.Examples) != 40 {
79
+ t.Fatalf("expected 40 total, got %d", len(res.Examples))
80
+ }
81
+ }
82
+
83
+ func TestSelectHonoursMix(t *testing.T) {
84
+ m := bankWith(t, map[string]int{"python": 100, "logic": 100})
85
+ res, err := Select(m, Request{
86
+ Categories: []string{"python", "logic"},
87
+ Mix: map[string]float64{"python": 0.75, "logic": 0.25},
88
+ Size: 40,
89
+ })
90
+ if err != nil {
91
+ t.Fatal(err)
92
+ }
93
+ if res.ByCat["python"] != 30 || res.ByCat["logic"] != 10 {
94
+ t.Fatalf("expected 30/10, got %v", res.ByCat)
95
+ }
96
+ }
97
+
98
+ func TestSelectReportsShortfall(t *testing.T) {
99
+ m := bankWith(t, map[string]int{"python": 10})
100
+ res, err := Select(m, Request{Categories: []string{"python"}, Size: 75})
101
+ if err != nil {
102
+ t.Fatal(err)
103
+ }
104
+ if len(res.Examples) != 10 {
105
+ t.Fatalf("expected 10, got %d", len(res.Examples))
106
+ }
107
+ if res.Shortfall != 65 {
108
+ t.Fatalf("expected shortfall 65, got %d", res.Shortfall)
109
+ }
110
+ if len(res.Notes) == 0 {
111
+ t.Fatal("expected a note about limited stock")
112
+ }
113
+ }
114
+
115
+ func TestSelectRejectsUnknownCategory(t *testing.T) {
116
+ m := bankWith(t, map[string]int{"python": 5})
117
+ if _, err := Select(m, Request{Categories: []string{"cobol"}, Size: 5}); err == nil {
118
+ t.Fatal("expected unknown category to fail")
119
+ }
120
+ }
121
+
122
+ func TestSelectRejectsBadInput(t *testing.T) {
123
+ m := bankWith(t, map[string]int{"python": 5})
124
+ if _, err := Select(m, Request{Categories: []string{"python"}, Size: 0}); err == nil {
125
+ t.Fatal("expected zero size to fail")
126
+ }
127
+ if _, err := Select(m, Request{Categories: nil, Size: 5}); err == nil {
128
+ t.Fatal("expected empty categories to fail")
129
+ }
130
+ }
131
+
132
+ func TestSelectSkipsStaleExamples(t *testing.T) {
133
+ m := bankWith(t, map[string]int{"python": 5})
134
+ // Exhaust two examples.
135
+ for i := 0; i < 3; i++ {
136
+ m.MarkUsed([]string{"python-a", "python-b"}, nowUTC())
137
+ }
138
+ res, err := Select(m, Request{Categories: []string{"python"}, Size: 10})
139
+ if err != nil {
140
+ t.Fatal(err)
141
+ }
142
+ for _, ex := range res.Examples {
143
+ if ex.ID == "python-a" || ex.ID == "python-b" {
144
+ t.Fatalf("stale example %s was served", ex.ID)
145
+ }
146
+ }
147
+ if len(res.Examples) != 3 {
148
+ t.Fatalf("expected 3 usable, got %d", len(res.Examples))
149
+ }
150
+ }
151
+
152
+ func TestSelectIsRandomised(t *testing.T) {
153
+ m := bankWith(t, map[string]int{"python": 40})
154
+ first, err := Select(m, Request{Categories: []string{"python"}, Size: 5})
155
+ if err != nil {
156
+ t.Fatal(err)
157
+ }
158
+ same := true
159
+ for attempt := 0; attempt < 8; attempt++ {
160
+ next, err := Select(m, Request{Categories: []string{"python"}, Size: 5})
161
+ if err != nil {
162
+ t.Fatal(err)
163
+ }
164
+ if next.Examples[0].ID != first.Examples[0].ID {
165
+ same = false
166
+ break
167
+ }
168
+ }
169
+ if same {
170
+ t.Fatal("draw order looks deterministic")
171
+ }
172
+ }
173
+
174
+ func nowUTC() time.Time { return time.Now().UTC() }
175
+
176
+ // TestSelectRemainderNeverRepeats covers the path the plain duplicate test
177
+ // misses. When the requested size does not divide evenly across categories
178
+ // there is a remainder to hand out, and the first pass has already taken a
179
+ // random subset of each pool. Slicing the pool by count and sampling again from
180
+ // that slice can return an example that was already issued, which makes the
181
+ // whole grant unusable: the reporter sends two answers for one id and the
182
+ // feedback endpoint rejects it as a duplicate.
183
+ func TestSelectRemainderNeverRepeats(t *testing.T) {
184
+ m := bankWith(t, map[string]int{"python": 10, "logic": 30})
185
+ for i := 0; i < 200; i++ {
186
+ res, err := Select(m, Request{Categories: []string{"python", "logic"}, Size: 7})
187
+ if err != nil {
188
+ t.Fatalf("select: %v", err)
189
+ }
190
+ if len(res.Examples) != 7 {
191
+ t.Fatalf("expected 7, got %d", len(res.Examples))
192
+ }
193
+ seen := map[string]bool{}
194
+ for _, ex := range res.Examples {
195
+ if seen[ex.ID] {
196
+ t.Fatalf("run %d: duplicate example %s (total %v)", i, ex.ID, len(res.Examples))
197
+ }
198
+ seen[ex.ID] = true
199
+ }
200
+ }
201
+ }
202
+
203
+ // TestSelectNeverExceedsStock: the same fix must not start inventing examples
204
+ // when a category is smaller than its share.
205
+ func TestSelectNeverExceedsStock(t *testing.T) {
206
+ m := bankWith(t, map[string]int{"python": 2, "logic": 20})
207
+ res, err := Select(m, Request{Categories: []string{"python", "logic"}, Size: 20})
208
+ if err != nil {
209
+ t.Fatalf("select: %v", err)
210
+ }
211
+ seen := map[string]bool{}
212
+ for _, ex := range res.Examples {
213
+ if seen[ex.ID] {
214
+ t.Fatalf("duplicate example %s", ex.ID)
215
+ }
216
+ seen[ex.ID] = true
217
+ }
218
+ if len(res.Examples) != 20 {
219
+ t.Fatalf("expected the full 20 from stock, got %d", len(res.Examples))
220
+ }
221
+ }
internal/httpapi/handlers.go CHANGED
@@ -17,8 +17,14 @@ import (
17
 
18
  // drawRequest is the public request body. Device facts are grouped so the
19
  // runner can send them verbatim from its probe.
 
 
 
 
 
 
 
20
  type drawRequest struct {
21
- RequestID string `json:"request_id"`
22
  Categories []string `json:"categories"`
23
  Mix map[string]float64 `json:"mix,omitempty"`
24
  Size int `json:"size"`
@@ -105,10 +111,10 @@ func (s *Server) handleDraw(w http.ResponseWriter, r *http.Request) {
105
  return
106
  }
107
  }
108
- reqID := r.Header.Get("X-Request-Id")
109
- if req.RequestID != "" {
110
- reqID = req.RequestID
111
- }
112
 
113
  remote := remoteAddrOf(r)
114
  in := core.DrawInput{
@@ -153,6 +159,8 @@ func (s *Server) handleDraw(w http.ResponseWriter, r *http.Request) {
153
  "by_category": grant.ByCat,
154
  "shortfall": grant.Shortfall,
155
  "notes": grant.Notes,
 
 
156
  "examples": payload,
157
  })
158
  }
 
17
 
18
  // drawRequest is the public request body. Device facts are grouped so the
19
  // runner can send them verbatim from its probe.
20
+ //
21
+ // There is deliberately no request_id field. A draw id is minted by the server
22
+ // and by nothing else: the runner sends device information, the server replies
23
+ // with an id and the questions issued under it, and the runner later submits
24
+ // answers quoting that id. Accepting a caller-supplied id would let a client
25
+ // choose its own handle, which is what made collisions between two callers
26
+ // possible in the first place.
27
  type drawRequest struct {
 
28
  Categories []string `json:"categories"`
29
  Mix map[string]float64 `json:"mix,omitempty"`
30
  Size int `json:"size"`
 
111
  return
112
  }
113
  }
114
+ // The draw id is generated here and nowhere else, so two callers can never
115
+ // share one. The X-Request-Id header is only a transport correlation value
116
+ // for logs; it never becomes the draw id a report has to quote.
117
+ reqID := core.NewRequestID()
118
 
119
  remote := remoteAddrOf(r)
120
  in := core.DrawInput{
 
159
  "by_category": grant.ByCat,
160
  "shortfall": grant.Shortfall,
161
  "notes": grant.Notes,
162
+ "stale_after": grant.StaleAfter,
163
+ "lifeline": grant.Lifeline,
164
  "examples": payload,
165
  })
166
  }
internal/httpapi/handlers_test.go ADDED
@@ -0,0 +1,403 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package httpapi
2
+
3
+ import (
4
+ "bytes"
5
+ "encoding/json"
6
+ "fmt"
7
+ "log/slog"
8
+ "net/http"
9
+ "net/http/httptest"
10
+ "os"
11
+ "path/filepath"
12
+ "strings"
13
+ "testing"
14
+ "time"
15
+
16
+ "github.com/archnemix/archx-eval/relay/internal/bank"
17
+ "github.com/archnemix/archx-eval/relay/internal/config"
18
+ "github.com/archnemix/archx-eval/relay/internal/core"
19
+ "github.com/archnemix/archx-eval/relay/internal/ratelog"
20
+ "github.com/archnemix/archx-eval/relay/internal/reputation"
21
+ "github.com/archnemix/archx-eval/relay/internal/store"
22
+ )
23
+
24
+ func newServer(t *testing.T, examples int) (*Server, *core.Service) {
25
+ t.Helper()
26
+ return newServerWith(t, examples, true)
27
+ }
28
+
29
+ // newServerWith builds a server whose loopback/private-address relaxation can
30
+ // be turned off, so the production posture is testable.
31
+ func newServerWith(t *testing.T, examples int, allowLoopback bool) (*Server, *core.Service) {
32
+ t.Helper()
33
+ dir := t.TempDir()
34
+ bankDir := filepath.Join(dir, "bank")
35
+ if err := os.MkdirAll(filepath.Join(bankDir, "python"), 0o750); err != nil {
36
+ t.Fatal(err)
37
+ }
38
+ var b strings.Builder
39
+ for i := 0; i < examples; i++ {
40
+ fmt.Fprintf(&b, `{"id":"py-%03d","category":"python","difficulty":"easy","kind":"qa","prompt":"q%d","expected_answer":"secret-answer-%d","explanation":"hidden"}`+"\n", i, i, i)
41
+ }
42
+ if err := os.WriteFile(filepath.Join(bankDir, "python", "easy.jsonl"), []byte(b.String()), 0o640); err != nil {
43
+ t.Fatal(err)
44
+ }
45
+ cfg := config.Config{
46
+ BankDir: bankDir, DataDir: filepath.Join(dir, "data"),
47
+ RateDir: filepath.Join(dir, "rate"),
48
+ DrawMax: 75, StaleAfterUses: 3, Window: time.Hour,
49
+ RateAllowance: 0.5, RateWindow: time.Minute, RateSample: time.Second, RateFloor: 10,
50
+ BanWindow: 24 * time.Hour, MaxBan: 14 * 24 * time.Hour,
51
+ FeedbackWindow: 24 * time.Hour, LedgerKeepDays: 7,
52
+ SaltSecret: "test-salt", MaxBodyBytes: 1 << 20, AllowLoopback: allowLoopback,
53
+ AccessToken: "test-access-token", MetricsToken: "metrics-token",
54
+ NetWindow: time.Hour, NetMaxDraws: 1000,
55
+ GlobalWindow: time.Hour, GlobalMax: 100000,
56
+ RequestTimeout: 10 * time.Second,
57
+ }
58
+ st, err := store.Open(cfg.DataDir)
59
+ if err != nil {
60
+ t.Fatal(err)
61
+ }
62
+ bm, err := bank.Load(bankDir, 3)
63
+ if err != nil {
64
+ t.Fatal(err)
65
+ }
66
+ rep, _ := reputation.Load("")
67
+ rates, err := ratelog.Open(cfg.RateDir, 96*time.Hour)
68
+ if err != nil {
69
+ t.Fatal(err)
70
+ }
71
+ t.Cleanup(func() { _ = rates.Close() })
72
+ svc := core.New(cfg, st, bm, rep, rates)
73
+ log := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
74
+ return New(cfg, svc, log, "admin-token"), svc
75
+ }
76
+
77
+ func post(t *testing.T, h http.Handler, path, body string) *httptest.ResponseRecorder {
78
+ t.Helper()
79
+ req := httptest.NewRequest(http.MethodPost, path, bytes.NewBufferString(body))
80
+ req.RemoteAddr = "203.0.113.10:5555"
81
+ req.Header.Set("Content-Type", "application/json")
82
+ req.Header.Set("Authorization", "Bearer test-access-token")
83
+ rec := httptest.NewRecorder()
84
+ h.ServeHTTP(rec, req)
85
+ return rec
86
+ }
87
+
88
+ const drawBody = `{"categories":["python"],"size":5,"device":{"machine_id":"4c4c4544-0044-3510-8054-b4c04f4e4e32","disk_uuid":"9f1b2c3d4e5f60718293a4b5c6d7e8f9","os_family":"linux","arch":"x86_64"}}`
89
+
90
+ // drawnGrant is the subset of the draw response needed to build valid feedback.
91
+ type drawnGrant struct {
92
+ RequestID string `json:"request_id"`
93
+ IdentityID string `json:"identity_id"`
94
+ Examples []struct {
95
+ ID string `json:"id"`
96
+ Category string `json:"category"`
97
+ Difficulty string `json:"difficulty"`
98
+ } `json:"examples"`
99
+ }
100
+
101
+ // drawFor performs a real draw, so feedback tests can report against ids that
102
+ // were actually issued. Verification makes a fabricated request id impossible
103
+ // to use, which is the point of the change.
104
+ func drawFor(t *testing.T, srv *Server, remoteAddr string) drawnGrant {
105
+ t.Helper()
106
+ req := httptest.NewRequest(http.MethodPost, "/v1/draw", bytes.NewBufferString(drawBody))
107
+ req.RemoteAddr = remoteAddr + ":5555"
108
+ req.Header.Set("Content-Type", "application/json")
109
+ req.Header.Set("Authorization", "Bearer test-access-token")
110
+ rec := httptest.NewRecorder()
111
+ srv.ServeHTTP(rec, req)
112
+ if rec.Code != 200 {
113
+ t.Fatalf("draw failed: %d %s", rec.Code, rec.Body)
114
+ }
115
+ var g drawnGrant
116
+ if err := json.Unmarshal(rec.Body.Bytes(), &g); err != nil {
117
+ t.Fatal(err)
118
+ }
119
+ return g
120
+ }
121
+
122
+ func TestDrawHappyPath(t *testing.T) {
123
+ srv, _ := newServer(t, 20)
124
+ rec := post(t, srv, "/v1/draw", drawBody)
125
+ if rec.Code != 200 {
126
+ t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body)
127
+ }
128
+ var out struct {
129
+ Count int `json:"count"`
130
+ Examples []map[string]any `json:"examples"`
131
+ ByCat map[string]int `json:"by_category"`
132
+ }
133
+ if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
134
+ t.Fatalf("decode: %v", err)
135
+ }
136
+ if out.Count != 5 || len(out.Examples) != 5 {
137
+ t.Fatalf("expected 5 examples, got %d", out.Count)
138
+ }
139
+ if out.ByCat["python"] != 5 {
140
+ t.Fatalf("bad by_category: %v", out.ByCat)
141
+ }
142
+ }
143
+
144
+ func TestDrawNeverLeaksAnswers(t *testing.T) {
145
+ srv, _ := newServer(t, 20)
146
+ rec := post(t, srv, "/v1/draw", drawBody)
147
+ body := rec.Body.String()
148
+ for _, forbidden := range []string{"secret-answer", "hidden", "expected_answer", "explanation", "reference_solution"} {
149
+ if strings.Contains(body, forbidden) {
150
+ t.Fatalf("response leaked %q: %s", forbidden, body)
151
+ }
152
+ }
153
+ }
154
+
155
+ func TestDrawSetsRequestIDHeader(t *testing.T) {
156
+ srv, _ := newServer(t, 10)
157
+ rec := post(t, srv, "/v1/draw", drawBody)
158
+ if rec.Header().Get("X-Request-Id") == "" {
159
+ t.Fatal("expected an X-Request-Id header")
160
+ }
161
+ if got := rec.Header().Get("Cache-Control"); !strings.Contains(got, "no-store") {
162
+ t.Fatalf("expected no-store cache header, got %q", got)
163
+ }
164
+ }
165
+
166
+ // The draw body has no request_id field: the server mints the id. A client
167
+ // trying to supply one is told the body is not what this endpoint accepts,
168
+ // which is clearer than silently ignoring a field the caller thinks matters.
169
+ func TestDrawBodyMayNotCarryRequestID(t *testing.T) {
170
+ srv, _ := newServer(t, 10)
171
+ body := `{"request_id":"mine","categories":["python"],"size":1,` +
172
+ `"device":{"machine_id":"4c4c4544-0044-3510-8054-b4c04f4e4e32",` +
173
+ `"disk_uuid":"9f1b2c3d4e5f60718293a4b5c6d7e8f9","os_family":"linux","arch":"x86_64"}}`
174
+ rec := post(t, srv, "/v1/draw", body)
175
+ if rec.Code != http.StatusBadRequest {
176
+ t.Fatalf("expected 400 for a body carrying request_id, got %d: %s", rec.Code, rec.Body)
177
+ }
178
+ }
179
+
180
+ // The draw id must be the server's, and must match what the response reports.
181
+ func TestDrawIDIsMintedNotEchoed(t *testing.T) {
182
+ srv, _ := newServer(t, 10)
183
+ rec := post(t, srv, "/v1/draw", drawBody)
184
+ if rec.Code != 200 {
185
+ t.Fatalf("draw: %d %s", rec.Code, rec.Body)
186
+ }
187
+ var grant drawnGrant
188
+ if err := json.Unmarshal(rec.Body.Bytes(), &grant); err != nil {
189
+ t.Fatal(err)
190
+ }
191
+ if len(grant.RequestID) != 32 {
192
+ t.Fatalf("expected a 32-char minted id, got %q", grant.RequestID)
193
+ }
194
+ // The transport header and the draw id are different values on purpose: one
195
+ // correlating logs, the other keying the draw.
196
+ if got := rec.Header().Get("X-Request-Id"); got == grant.RequestID {
197
+ t.Fatal("the log correlation id must not be reused as the draw id")
198
+ }
199
+ }
200
+
201
+ func TestSecondDrawGets429WithRetryAfter(t *testing.T) {
202
+ srv, _ := newServer(t, 20)
203
+ if rec := post(t, srv, "/v1/draw", drawBody); rec.Code != 200 {
204
+ t.Fatalf("first: %d", rec.Code)
205
+ }
206
+ rec := post(t, srv, "/v1/draw", drawBody)
207
+ if rec.Code != http.StatusTooManyRequests {
208
+ t.Fatalf("expected 429, got %d: %s", rec.Code, rec.Body)
209
+ }
210
+ if rec.Header().Get("Retry-After") == "" {
211
+ t.Fatal("expected a Retry-After header")
212
+ }
213
+ var out struct {
214
+ Error struct {
215
+ Code string `json:"code"`
216
+ } `json:"error"`
217
+ }
218
+ if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
219
+ t.Fatalf("decode: %v", err)
220
+ }
221
+ if out.Error.Code != "WINDOW_ACTIVE" {
222
+ t.Fatalf("unexpected code %q", out.Error.Code)
223
+ }
224
+ }
225
+
226
+ func TestMalformedJSONRejected(t *testing.T) {
227
+ srv, _ := newServer(t, 10)
228
+ rec := post(t, srv, "/v1/draw", `{"categories":`)
229
+ if rec.Code != http.StatusBadRequest {
230
+ t.Fatalf("expected 400, got %d", rec.Code)
231
+ }
232
+ }
233
+
234
+ func TestUnknownFieldRejected(t *testing.T) {
235
+ srv, _ := newServer(t, 10)
236
+ rec := post(t, srv, "/v1/draw", `{"categories":["python"],"size":1,"surprise":true,"device":{"machine_id":"4c4c4544-0044-3510-8054-b4c04f4e4e32","disk_uuid":"9f1b2c3d4e5f60718293a4b5c6d7e8f9"}}`)
237
+ if rec.Code != http.StatusBadRequest {
238
+ t.Fatalf("expected 400 for unknown field, got %d", rec.Code)
239
+ }
240
+ }
241
+
242
+ func TestOversizedBodyRejected(t *testing.T) {
243
+ srv, _ := newServer(t, 10)
244
+ big := strings.Repeat("a", 2<<20)
245
+ rec := post(t, srv, "/v1/draw", `{"categories":["`+big+`"]}`)
246
+ if rec.Code != http.StatusBadRequest && rec.Code != http.StatusRequestEntityTooLarge {
247
+ t.Fatalf("expected rejection, got %d", rec.Code)
248
+ }
249
+ }
250
+
251
+ func TestHealthReflectsBank(t *testing.T) {
252
+ srv, _ := newServer(t, 7)
253
+ req := httptest.NewRequest(http.MethodGet, "/health", nil)
254
+ rec := httptest.NewRecorder()
255
+ srv.ServeHTTP(rec, req)
256
+ if rec.Code != 200 {
257
+ t.Fatalf("expected 200, got %d", rec.Code)
258
+ }
259
+ var out map[string]any
260
+ if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
261
+ t.Fatal(err)
262
+ }
263
+ if out["ok"] != true {
264
+ t.Fatalf("expected ok true: %v", out)
265
+ }
266
+ }
267
+
268
+ func TestHealthUnavailableWhenBankEmpty(t *testing.T) {
269
+ srv, _ := newServer(t, 0)
270
+ req := httptest.NewRequest(http.MethodGet, "/health", nil)
271
+ rec := httptest.NewRecorder()
272
+ srv.ServeHTTP(rec, req)
273
+ if rec.Code != http.StatusServiceUnavailable {
274
+ t.Fatalf("expected 503, got %d", rec.Code)
275
+ }
276
+ }
277
+
278
+ func TestCategories(t *testing.T) {
279
+ srv, _ := newServer(t, 3)
280
+ req := httptest.NewRequest(http.MethodGet, "/v1/categories", nil)
281
+ rec := httptest.NewRecorder()
282
+ srv.ServeHTTP(rec, req)
283
+ var out struct {
284
+ Categories []string `json:"categories"`
285
+ }
286
+ if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
287
+ t.Fatal(err)
288
+ }
289
+ if len(out.Categories) != 1 || out.Categories[0] != "python" {
290
+ t.Fatalf("unexpected categories: %v", out.Categories)
291
+ }
292
+ }
293
+
294
+ func TestAdminStaleRequiresToken(t *testing.T) {
295
+ srv, _ := newServer(t, 5)
296
+ req := httptest.NewRequest(http.MethodGet, "/v1/stale", nil)
297
+ rec := httptest.NewRecorder()
298
+ srv.ServeHTTP(rec, req)
299
+ if rec.Code != http.StatusForbidden {
300
+ t.Fatalf("expected 403 without token, got %d", rec.Code)
301
+ }
302
+
303
+ req = httptest.NewRequest(http.MethodGet, "/v1/stale", nil)
304
+ req.Header.Set("Authorization", "Bearer admin-token")
305
+ rec = httptest.NewRecorder()
306
+ srv.ServeHTTP(rec, req)
307
+ if rec.Code != 200 {
308
+ t.Fatalf("expected 200 with token, got %d: %s", rec.Code, rec.Body)
309
+ }
310
+ }
311
+
312
+ // Feedback is now verified against the ledger, so this test does a real draw
313
+ // and reports against the ids that draw actually issued.
314
+ func TestFeedbackAcceptedAndScored(t *testing.T) {
315
+ srv, _ := newServer(t, 5)
316
+
317
+ grant := drawFor(t, srv, "203.0.113.10")
318
+ if len(grant.Examples) < 2 {
319
+ t.Fatalf("expected at least 2 examples, got %d", len(grant.Examples))
320
+ }
321
+ var items []string
322
+ for i, ex := range grant.Examples {
323
+ passed := i == 0
324
+ score := 0
325
+ if passed {
326
+ score = 1
327
+ }
328
+ items = append(items, fmt.Sprintf(
329
+ `{"example_id":%q,"category":%q,"difficulty":%q,"passed":%v,"score":%d}`,
330
+ ex.ID, ex.Category, ex.Difficulty, passed, score))
331
+ }
332
+ body := fmt.Sprintf(`{"request_id":%q,"identity_id":%q,"model_id":"gpt-x","items":[%s]}`,
333
+ grant.RequestID, grant.IdentityID, strings.Join(items, ","))
334
+
335
+ rec := post(t, srv, "/v1/feedback", body)
336
+ if rec.Code != 200 {
337
+ t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body)
338
+ }
339
+ var out struct {
340
+ Accepted bool `json:"accepted"`
341
+ Summary struct {
342
+ Total int `json:"total"`
343
+ Passed int `json:"passed"`
344
+ Score float64 `json:"score"`
345
+ } `json:"summary"`
346
+ }
347
+ if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
348
+ t.Fatal(err)
349
+ }
350
+ if !out.Accepted || out.Summary.Total != len(grant.Examples) || out.Summary.Passed != 1 {
351
+ t.Fatalf("unexpected summary: %+v", out)
352
+ }
353
+ }
354
+
355
+ func TestFeedbackRejectsBadInput(t *testing.T) {
356
+ srv, _ := newServer(t, 5)
357
+ if rec := post(t, srv, "/v1/feedback", `{"items":[{"example_id":"a"}]}`); rec.Code != 400 {
358
+ t.Fatalf("expected 400 for missing model_id, got %d", rec.Code)
359
+ }
360
+ if rec := post(t, srv, "/v1/feedback", `{"model_id":"m","items":[]}`); rec.Code != 400 {
361
+ t.Fatalf("expected 400 for empty items, got %d", rec.Code)
362
+ }
363
+ }
364
+
365
+ func TestEraseRemovesRawOnly(t *testing.T) {
366
+ srv, svc := newServer(t, 10)
367
+ rec := post(t, srv, "/v1/draw", drawBody)
368
+ var out struct {
369
+ IdentityID string `json:"identity_id"`
370
+ }
371
+ if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
372
+ t.Fatal(err)
373
+ }
374
+ body := `{"identity_id":"` + out.IdentityID + `"}`
375
+ req := httptest.NewRequest(http.MethodPost, "/v1/erase", bytes.NewBufferString(body))
376
+ req.RemoteAddr = "203.0.113.10:5555"
377
+ req.Header.Set("Content-Type", "application/json")
378
+ req.Header.Set("Authorization", "Bearer admin-token")
379
+ rec = httptest.NewRecorder()
380
+ srv.ServeHTTP(rec, req)
381
+ if rec.Code != 200 {
382
+ t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body)
383
+ }
384
+ if _, err := svc.Erase(out.IdentityID); err != nil {
385
+ t.Fatalf("erase: %v", err)
386
+ }
387
+ }
388
+
389
+ func TestIndexAnd404(t *testing.T) {
390
+ srv, _ := newServer(t, 3)
391
+ req := httptest.NewRequest(http.MethodGet, "/", nil)
392
+ rec := httptest.NewRecorder()
393
+ srv.ServeHTTP(rec, req)
394
+ if rec.Code != 200 || !strings.Contains(rec.Body.String(), "archx-eval relay") {
395
+ t.Fatalf("bad index: %d %s", rec.Code, rec.Body)
396
+ }
397
+ req = httptest.NewRequest(http.MethodGet, "/nope", nil)
398
+ rec = httptest.NewRecorder()
399
+ srv.ServeHTTP(rec, req)
400
+ if rec.Code != http.StatusNotFound {
401
+ t.Fatalf("expected 404, got %d", rec.Code)
402
+ }
403
+ }
internal/ratelog/ratelog.go CHANGED
@@ -60,6 +60,14 @@ type Log struct {
60
  // Open loads any existing log under dir, discarding entries older than
61
  // retention. retention should exceed the largest window the caller uses.
62
  func Open(dir string, retention time.Duration) (*Log, error) {
 
 
 
 
 
 
 
 
63
  if dir == "" {
64
  return nil, errors.New("ratelog: empty directory")
65
  }
@@ -76,6 +84,9 @@ func Open(dir string, retention time.Duration) (*Log, error) {
76
  files: map[string]*os.File{},
77
  clock: func() time.Time { return time.Now().UTC() },
78
  }
 
 
 
79
  if err := l.load(); err != nil {
80
  return nil, err
81
  }
 
60
  // Open loads any existing log under dir, discarding entries older than
61
  // retention. retention should exceed the largest window the caller uses.
62
  func Open(dir string, retention time.Duration) (*Log, error) {
63
+ return OpenAt(dir, retention, nil)
64
+ }
65
+
66
+ // OpenAt is Open with a caller-supplied clock. The retention cutoff is applied
67
+ // during load, so a caller that runs on a different clock -- a test harness
68
+ // with a frozen date, most obviously -- must supply it here or every entry is
69
+ // discarded as stale. Passing nil uses the wall clock.
70
+ func OpenAt(dir string, retention time.Duration, clock func() time.Time) (*Log, error) {
71
  if dir == "" {
72
  return nil, errors.New("ratelog: empty directory")
73
  }
 
84
  files: map[string]*os.File{},
85
  clock: func() time.Time { return time.Now().UTC() },
86
  }
87
+ if clock != nil {
88
+ l.clock = clock
89
+ }
90
  if err := l.load(); err != nil {
91
  return nil, err
92
  }
internal/ratelog/ratelog_test.go ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package ratelog
2
+
3
+ import (
4
+ "os"
5
+ "testing"
6
+ "time"
7
+ )
8
+
9
+ func openLog(t *testing.T, dir string) *Log {
10
+ t.Helper()
11
+ l, err := Open(dir, 48*time.Hour)
12
+ if err != nil {
13
+ t.Fatalf("open: %v", err)
14
+ }
15
+ return l
16
+ }
17
+
18
+ func TestRecordAndCount(t *testing.T) {
19
+ l := openLog(t, t.TempDir())
20
+ defer l.Close()
21
+ now := time.Date(2026, 11, 13, 12, 0, 0, 0, time.UTC)
22
+ for i := 0; i < 5; i++ {
23
+ if err := l.Record("k1", now.Add(-time.Duration(i)*time.Second)); err != nil {
24
+ t.Fatalf("record: %v", err)
25
+ }
26
+ }
27
+ if got := l.Count("k1", time.Minute, now); got != 5 {
28
+ t.Fatalf("expected 5, got %d", got)
29
+ }
30
+ if got := l.Count("k1", 2*time.Second, now); got != 3 {
31
+ t.Fatalf("expected 3 inside 2s, got %d", got)
32
+ }
33
+ if got := l.Count("unknown", time.Minute, now); got != 0 {
34
+ t.Fatalf("expected 0 for unknown key, got %d", got)
35
+ }
36
+ }
37
+
38
+ // The entire point of this package: a restart must not forgive a flood.
39
+ func TestSurvivesRestart(t *testing.T) {
40
+ dir := t.TempDir()
41
+ now := time.Now().UTC()
42
+
43
+ l := openLog(t, dir)
44
+ for i := 0; i < 12; i++ {
45
+ if err := l.Record("identity-abc", now.Add(-time.Duration(i)*100*time.Millisecond)); err != nil {
46
+ t.Fatalf("record: %v", err)
47
+ }
48
+ }
49
+ _ = l.Flush()
50
+ if err := l.Close(); err != nil {
51
+ t.Fatalf("close: %v", err)
52
+ }
53
+
54
+ // Simulate a Hugging Face Space waking up with a brand new process.
55
+ again := openLog(t, dir)
56
+ defer again.Close()
57
+ if got := again.Count("identity-abc", time.Minute, now); got != 12 {
58
+ t.Fatalf("expected 12 events to survive restart, got %d", got)
59
+ }
60
+ }
61
+
62
+ func TestTornLineDoesNotPreventStartup(t *testing.T) {
63
+ dir := t.TempDir()
64
+ l := openLog(t, dir)
65
+ if err := l.Record("k", time.Now().UTC()); err != nil {
66
+ t.Fatal(err)
67
+ }
68
+ _ = l.Flush()
69
+ _ = l.Close()
70
+
71
+ // Append a half-written line, exactly as a kill -9 mid-write leaves.
72
+ f, err := os.OpenFile(l.PathFor("k"), os.O_APPEND|os.O_WRONLY, 0o640)
73
+ if err != nil {
74
+ t.Fatal(err)
75
+ }
76
+ if _, err := f.WriteString(`{"t":123`); err != nil {
77
+ t.Fatal(err)
78
+ }
79
+ f.Close()
80
+
81
+ again, err := Open(dir, 48*time.Hour)
82
+ if err != nil {
83
+ t.Fatalf("torn line must not block startup: %v", err)
84
+ }
85
+ defer again.Close()
86
+ if got := again.Count("k", time.Hour, time.Now().UTC()); got != 1 {
87
+ t.Fatalf("expected the intact event to load, got %d", got)
88
+ }
89
+ }
90
+
91
+ func TestRetentionDropsOldEntriesOnLoad(t *testing.T) {
92
+ dir := t.TempDir()
93
+ now := time.Now().UTC()
94
+
95
+ l := openLog(t, dir)
96
+ if err := l.Record("old", now.Add(-72*time.Hour)); err != nil {
97
+ t.Fatal(err)
98
+ }
99
+ if err := l.Record("new", now.Add(-time.Minute)); err != nil {
100
+ t.Fatal(err)
101
+ }
102
+ _ = l.Flush()
103
+ _ = l.Close()
104
+
105
+ again := openLog(t, dir) // retention 48h
106
+ defer again.Close()
107
+ if got := again.Count("old", 96*time.Hour, now); got != 0 {
108
+ t.Fatalf("expired entry should be dropped, got %d", got)
109
+ }
110
+ if got := again.Count("new", 96*time.Hour, now); got != 1 {
111
+ t.Fatalf("recent entry should survive, got %d", got)
112
+ }
113
+ }
114
+
115
+ func TestCompactShrinksFiles(t *testing.T) {
116
+ dir := t.TempDir()
117
+ l := openLog(t, dir)
118
+ defer l.Close()
119
+ now := time.Now().UTC()
120
+
121
+ for i := 0; i < 10; i++ {
122
+ if err := l.Record("k", now.Add(-50*time.Hour)); err != nil {
123
+ t.Fatal(err)
124
+ }
125
+ }
126
+ if err := l.Record("k", now); err != nil {
127
+ t.Fatal(err)
128
+ }
129
+ n, err := l.Compact(now)
130
+ if err != nil {
131
+ t.Fatalf("compact: %v", err)
132
+ }
133
+ if n != 1 {
134
+ t.Fatalf("expected 1 file rewritten, got %d", n)
135
+ }
136
+ if got := l.Count("k", 96*time.Hour, now); got != 1 {
137
+ t.Fatalf("expected only the fresh entry, got %d", got)
138
+ }
139
+ }
140
+
141
+ func TestCompactRemovesEmptyKey(t *testing.T) {
142
+ dir := t.TempDir()
143
+ l := openLog(t, dir)
144
+ defer l.Close()
145
+ now := time.Now().UTC()
146
+ if err := l.Record("gone", now.Add(-49*time.Hour)); err != nil {
147
+ t.Fatal(err)
148
+ }
149
+ path := l.PathFor("gone")
150
+ if _, err := l.Compact(now); err != nil {
151
+ t.Fatal(err)
152
+ }
153
+ if l.Keys() != 0 {
154
+ t.Fatalf("expected no keys left, got %d", l.Keys())
155
+ }
156
+ if _, err := os.Stat(path); !os.IsNotExist(err) {
157
+ t.Fatal("file should be removed")
158
+ }
159
+ }
160
+
161
+ func TestMaxEntriesBound(t *testing.T) {
162
+ l := openLog(t, t.TempDir())
163
+ defer l.Close()
164
+ now := time.Now().UTC()
165
+ for i := 0; i < maxEntriesPerKey+200; i++ {
166
+ if err := l.Record("flood", now); err != nil {
167
+ t.Fatal(err)
168
+ }
169
+ }
170
+ l.mu.Lock()
171
+ n := len(l.entries["flood"])
172
+ l.mu.Unlock()
173
+ if n > maxEntriesPerKey {
174
+ t.Fatalf("memory must stay bounded, got %d entries", n)
175
+ }
176
+ }
177
+
178
+ func TestCountPrefix(t *testing.T) {
179
+ l := openLog(t, t.TempDir())
180
+ defer l.Close()
181
+ now := time.Now().UTC()
182
+ for _, k := range []string{"net:a", "net:b", "other"} {
183
+ for i := 0; i < 3; i++ {
184
+ if err := l.Record(k, now); err != nil {
185
+ t.Fatal(err)
186
+ }
187
+ }
188
+ }
189
+ if got := l.CountPrefix("net:", time.Minute, now); got != 6 {
190
+ t.Fatalf("expected 6, got %d", got)
191
+ }
192
+ }
193
+
194
+ func TestConcurrentRecordAndCount(t *testing.T) {
195
+ l := openLog(t, t.TempDir())
196
+ defer l.Close()
197
+ now := time.Now().UTC()
198
+ done := make(chan struct{})
199
+ for w := 0; w < 16; w++ {
200
+ go func() {
201
+ defer func() { done <- struct{}{} }()
202
+ for i := 0; i < 40; i++ {
203
+ _ = l.Record("shared", now)
204
+ _ = l.Count("shared", time.Minute, now)
205
+ }
206
+ }()
207
+ }
208
+ for w := 0; w < 16; w++ {
209
+ <-done
210
+ }
211
+ l.mu.Lock()
212
+ n := len(l.entries["shared"])
213
+ l.mu.Unlock()
214
+ if n == 0 {
215
+ t.Fatal("concurrent writes lost every event")
216
+ }
217
+ }
218
+
219
+ func TestRejectsEmptyKey(t *testing.T) {
220
+ l := openLog(t, t.TempDir())
221
+ defer l.Close()
222
+ if err := l.Record("", time.Now()); err == nil {
223
+ t.Fatal("expected empty key to be rejected")
224
+ }
225
+ }
226
+
227
+ // The retention cutoff is applied while loading, so the clock used at Open
228
+ // decides whether history survives. Reopening on the wall clock while history
229
+ // was written on another clock silently drops everything -- which is exactly
230
+ // what happened once the calendar moved past a frozen test date.
231
+ func TestOpenAtUsesTheSuppliedClockForRetention(t *testing.T) {
232
+ base := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)
233
+ dir := t.TempDir()
234
+
235
+ l, err := OpenAt(dir, 48*time.Hour, func() time.Time { return base })
236
+ if err != nil {
237
+ t.Fatal(err)
238
+ }
239
+ for i := 0; i < 5; i++ {
240
+ if err := l.Record("id:abc", base.Add(time.Duration(i)*time.Minute)); err != nil {
241
+ t.Fatal(err)
242
+ }
243
+ }
244
+ if err := l.Close(); err != nil {
245
+ t.Fatal(err)
246
+ }
247
+
248
+ // Same clock, an hour later: history is well inside retention and must load.
249
+ again, err := OpenAt(dir, 48*time.Hour, func() time.Time { return base.Add(time.Hour) })
250
+ if err != nil {
251
+ t.Fatal(err)
252
+ }
253
+ // The window must span the events: they were written at base, and the
254
+ // clock has moved on an hour.
255
+ if got := again.Count("id:abc", 2*time.Hour, base.Add(time.Hour)); got != 5 {
256
+ t.Fatalf("expected all 5 events to reload, got %d", got)
257
+ }
258
+ _ = again.Close()
259
+
260
+ // Far ahead of the entries: they are older than retention and are dropped.
261
+ // This is the failure mode, asserted so it can never come back by accident.
262
+ stale, err := OpenAt(dir, 48*time.Hour, func() time.Time { return base.Add(100 * time.Hour) })
263
+ if err != nil {
264
+ t.Fatal(err)
265
+ }
266
+ if got := stale.Count("id:abc", 200*time.Hour, base.Add(100*time.Hour)); got != 0 {
267
+ t.Fatalf("expected expired events to be dropped, got %d", got)
268
+ }
269
+ _ = stale.Close()
270
+ }