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 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
package httpapi

import (
	"crypto/rand"
	"encoding/hex"
	"net/http"
	"net/netip"
	"strings"
	"time"

	"github.com/archnemix/archx-eval/relay/internal/apierr"
	"github.com/archnemix/archx-eval/relay/internal/bank"
	"github.com/archnemix/archx-eval/relay/internal/core"
	"github.com/archnemix/archx-eval/relay/internal/identity"
	"github.com/archnemix/archx-eval/relay/internal/store"
)

// drawRequest is the public request body. Device facts are grouped so the
// runner can send them verbatim from its probe.
//
// There is deliberately no request_id field. A draw id is minted by the server
// and by nothing else: the runner sends device information, the server replies
// with an id and the questions issued under it, and the runner later submits
// answers quoting that id. Accepting a caller-supplied id would let a client
// choose its own handle, which is what made collisions between two callers
// possible in the first place.
type drawRequest struct {
	Categories []string           `json:"categories"`
	Mix        map[string]float64 `json:"mix,omitempty"`
	Size       int                `json:"size"`
	Device     devicePayload      `json:"device"`
}

type devicePayload struct {
	MachineID   string  `json:"machine_id"`
	DiskUUID    string  `json:"disk_uuid"`
	OSFamily    string  `json:"os_family"`
	Arch        string  `json:"arch"`
	RunnerVer   string  `json:"runner_version"`
	PythonVer   string  `json:"python_version"`
	DeviceClass string  `json:"device_class"`
	DMIProduct  string  `json:"dmi_product"`
	Hypervisor  bool    `json:"hypervisor"`
	ClockSkewS  float64 `json:"clock_skew_s"`
}

func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		writeError(w, apierr.NotFound("no such endpoint"))
		return
	}
	writeJSON(w, 200, map[string]any{
		"service": "archx-eval relay",
		"version": core.Version,
		"endpoints": []string{
			"GET  /health",
			"GET  /v1/categories",
			"POST /v1/draw",
			"POST /v1/feedback",
		},
		"limits": map[string]any{
			"max_draw":    s.cfg.DrawMax,
			"window":      s.cfg.Window.String(),
			"stale_after": s.cfg.StaleAfterUses,
		},
	})
}

func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
	h := s.svc.Health()
	status := 200
	if !h.OK {
		status = 503
	}
	writeJSON(w, status, h)
}

func (s *Server) handleCategories(w http.ResponseWriter, r *http.Request) {
	writeJSON(w, 200, map[string]any{"categories": s.svc.Categories()})
}

func (s *Server) handleDraw(w http.ResponseWriter, r *http.Request) {
	// Closed loop: every draw must be attributable to a registered runner.
	if err := s.svc.Authenticate(bearerToken(r)); err != nil {
		writeError(w, err)
		return
	}

	// Account for this request BEFORE the body is parsed. Without this a bot
	// could send malformed JSON for ever: decoding fails here, the request
	// never reaches the ladder, and flooding costs it nothing.
	if err := s.svc.Admit(core.DrawInput{
		Admitted:   true,
		RequestID:  r.Header.Get("X-Request-Id"),
		RemoteAddr: remoteAddrOf(r),
		Headers:    collectHeaders(r),
	}); err != nil {
		s.logDeny(r.Header.Get("X-Request-Id"), err)
		writeError(w, err)
		return
	}

	var req drawRequest
	if err := decodeJSON(r, &req); err != nil {
		writeError(w, err)
		return
	}
	for _, c := range req.Categories {
		if hasControlChars(c) {
			writeError(w, apierr.BadRequest("category names may not contain control characters"))
			return
		}
	}
	// The draw id is generated here and nowhere else, so two callers can never
	// share one. The X-Request-Id header is only a transport correlation value
	// for logs; it never becomes the draw id a report has to quote.
	reqID := core.NewRequestID()

	remote := remoteAddrOf(r)
	in := core.DrawInput{
		Admitted:   true,
		RequestID:  reqID,
		Categories: req.Categories,
		Mix:        req.Mix,
		Size:       req.Size,
		Device: identity.Device{
			MachineID:   req.Device.MachineID,
			DiskUUID:    req.Device.DiskUUID,
			OSFamily:    strings.ToLower(strings.TrimSpace(req.Device.OSFamily)),
			Arch:        strings.ToLower(strings.TrimSpace(req.Device.Arch)),
			RunnerVer:   req.Device.RunnerVer,
			PythonVer:   req.Device.PythonVer,
			DeviceClass: req.Device.DeviceClass,
			DMIProduct:  req.Device.DMIProduct,
			Hypervisor:  req.Device.Hypervisor,
			ClockSkewS:  req.Device.ClockSkewS,
		},
		RemoteAddr: remote,
		Headers:    collectHeaders(r),
	}

	grant, err := s.svc.RequestDraw(r.Context(), in)
	if err != nil {
		s.logDeny(reqID, err)
		writeError(w, err)
		return
	}

	payload := make([]map[string]any, 0, len(grant.Examples))
	for _, ex := range grant.Examples {
		payload = append(payload, renderExample(ex))
	}
	writeJSON(w, 200, map[string]any{
		"request_id":   grant.RequestID,
		"identity_id":  grant.IdentityID,
		"issued_at":    grant.IssuedAt,
		"next_draw_at": grant.NextDrawAt,
		"count":        len(grant.Examples),
		"by_category":  grant.ByCat,
		"shortfall":    grant.Shortfall,
		"notes":        grant.Notes,
		"stale_after":  grant.StaleAfter,
		"lifeline":     grant.Lifeline,
		"examples":     payload,
	})
}

// renderExample strips everything the caller must not see: reference solutions,
// test bodies, expected answers and provenance notes.
func renderExample(ex *bank.Example) map[string]any {
	out := map[string]any{
		"id":         ex.ID,
		"category":   ex.Category,
		"difficulty": ex.Difficulty,
		"kind":       ex.Kind,
		"prompt":     ex.Prompt,
	}
	if ex.Context != "" {
		out["context"] = ex.Context
	}
	if ex.Language != "" {
		out["language"] = ex.Language
	}
	if ex.Entrypoint != "" {
		out["entrypoint"] = ex.Entrypoint
	}
	if ex.Starter != "" {
		out["starter_code"] = ex.Starter
	}
	if len(ex.Tags) > 0 {
		out["tags"] = ex.Tags
	}
	return out
}

func (s *Server) handleFeedback(w http.ResponseWriter, r *http.Request) {
	var body struct {
		RequestID  string         `json:"request_id"`
		IdentityID string         `json:"identity_id"`
		ModelID    string         `json:"model_id"`
		RunnerVer  string         `json:"runner_version"`
		OS         string         `json:"os"`
		Arch       string         `json:"arch"`
		DurationS  float64        `json:"duration_s"`
		Partial    bool           `json:"partial"`
		Items      []feedbackItem `json:"items"`
	}
	// Partial is a deliberate opt-in, so it is carried separately for the text
	// validator below rather than widening its anonymous struct.
	_ = body.Partial
	if err := decodeJSON(r, &body); err != nil {
		writeError(w, err)
		return
	}
	if len(body.Items) > 500 {
		writeError(w, apierr.BadRequest("at most 500 items may be reported at once"))
		return
	}
	if err := validateFeedbackText(body); err != nil {
		writeError(w, err)
		return
	}

	exampleIDs := make([]string, 0, len(body.Items))
	for _, it := range body.Items {
		if strings.TrimSpace(it.ExampleID) == "" {
			writeError(w, apierr.BadRequest("every item needs an example_id"))
			return
		}
		exampleIDs = append(exampleIDs, it.ExampleID)
	}

	// Verification happens before anything is stored: the report must match a
	// draw this relay actually issued, to this identity, and not already
	// answered. Unverified results never reach the dataset.
	res, err := s.svc.VerifyFeedback(core.FeedbackInput{
		RequestID:  body.RequestID,
		IdentityID: body.IdentityID,
		ModelID:    body.ModelID,
		RunnerVer:  body.RunnerVer,
		OS:         body.OS,
		Arch:       body.Arch,
		DurationS:  body.DurationS,
		ExampleIDs: exampleIDs,
		Partial:    body.Partial,
		RemoteAddr: remoteAddrOf(r),
		Headers:    r.Header,
	}, time.Now().UTC())
	if err != nil {
		writeError(w, err)
		return
	}
	var scoreSum float64
	catSum := map[string]float64{}
	catN := map[string]int{}
	for _, it := range body.Items {
		res.Items = append(res.Items, store.ResultItem{
			ExampleID:  it.ExampleID,
			Category:   it.Category,
			Difficulty: it.Difficulty,
			Answer:     it.Answer,
			Code:       it.Code,
			Passed:     it.Passed,
			Score:      clamp01(it.Score),
			LatencyMS:  it.LatencyMS,
			Error:      it.Error,
		})
		if it.Passed {
			res.Summary.Passed++
		}
		scoreSum += clamp01(it.Score)
		catSum[it.Category] += clamp01(it.Score)
		catN[it.Category]++
	}
	res.Summary.Score = scoreSum / float64(len(res.Items))
	for cat, sum := range catSum {
		if catN[cat] > 0 {
			res.Summary.ByCat[cat] = sum / float64(catN[cat])
		}
	}
	if err := s.svc.SubmitResult(res); err != nil {
		writeError(w, apierr.Internal("could not record results"))
		return
	}
	writeJSON(w, 200, map[string]any{
		"accepted": true,
		"summary":  res.Summary,
	})
}

type feedbackItem struct {
	ExampleID  string  `json:"example_id"`
	Category   string  `json:"category"`
	Difficulty string  `json:"difficulty"`
	Answer     string  `json:"answer"`
	Code       string  `json:"code"`
	Passed     bool    `json:"passed"`
	Score      float64 `json:"score"`
	LatencyMS  int     `json:"latency_ms"`
	Error      string  `json:"error"`
}

func clamp01(f float64) float64 {
	if f < 0 {
		return 0
	}
	if f > 1 {
		return 1
	}
	return f
}

func (s *Server) handleStale(w http.ResponseWriter, r *http.Request) {
	if !s.requireAdmin(w, r) {
		return
	}
	stale := s.svc.StaleExamples()
	writeJSON(w, 200, map[string]any{
		"count":    len(stale),
		"examples": stale,
	})
}

func (s *Server) handleErase(w http.ResponseWriter, r *http.Request) {
	if !s.requireAdmin(w, r) {
		return
	}
	var body struct {
		IdentityID string `json:"identity_id"`
	}
	if err := decodeJSON(r, &body); err != nil {
		writeError(w, err)
		return
	}
	if body.IdentityID == "" {
		writeError(w, apierr.BadRequest("identity_id is required"))
		return
	}
	known, err := s.svc.Erase(body.IdentityID)
	if err != nil {
		writeError(w, apierr.Internal("erase failed"))
		return
	}
	// There is no personal data to delete: only salted hashes are stored, and a
	// hash is not personal data. The endpoint stays so a compliance request has
	// an honest, documented answer instead of a 404.
	writeJSON(w, 200, map[string]any{
		"identity_known": known,
		"erased":         false,
		"detail":         "no raw personal data is stored: identities are kept as salted hashes only",
	})
}

func (s *Server) logDeny(reqID string, err error) {
	e, ok := apierr.As(err)
	if !ok {
		return
	}
	if e.Status == 429 || e.Status == 403 {
		s.log.Warn("refused",
			"request_id", reqID,
			"code", e.Code,
			"retry_after_s", int(e.RetryAfter.Seconds()),
		)
	}
}

func remoteAddrOf(r *http.Request) netip.Addr {
	host := r.RemoteAddr
	if i := strings.LastIndex(host, ":"); i > 0 {
		host = host[:i]
	}
	host = strings.Trim(host, "[]")
	if a, err := netip.ParseAddr(host); err == nil {
		return a
	}
	return netip.Addr{}
}

func collectHeaders(r *http.Request) map[string][]string {
	out := make(map[string][]string, len(r.Header)+2)
	for k, v := range r.Header {
		kk := canonicalHeader(k)
		out[kk] = append(out[kk], v...)
	}
	return out
}

func canonicalHeader(k string) string {
	parts := strings.Split(strings.ToLower(k), "-")
	for i, p := range parts {
		if p == "" {
			continue
		}
		parts[i] = strings.ToUpper(p[:1]) + p[1:]
	}
	return strings.Join(parts, "-")
}

// bearerToken extracts the access token from the standard header, falling back
// to a custom header for clients that cannot set Authorization.
func bearerToken(r *http.Request) string {
	if v := r.Header.Get("Authorization"); v != "" {
		return strings.TrimSpace(strings.TrimPrefix(v, "Bearer "))
	}
	return strings.TrimSpace(r.Header.Get("X-Access-Token"))
}

// Field caps. These exist so the feedback endpoint cannot be used as free
// object storage: every accepted byte becomes our bandwidth, disk and bill.
const (
	maxAnswerBytes = 8 << 10
	maxCodeBytes   = 64 << 10
	maxErrorBytes  = 512
	maxModelIDLen  = 128
)

func validateFeedbackText(body struct {
	RequestID  string         `json:"request_id"`
	IdentityID string         `json:"identity_id"`
	ModelID    string         `json:"model_id"`
	RunnerVer  string         `json:"runner_version"`
	OS         string         `json:"os"`
	Arch       string         `json:"arch"`
	DurationS  float64        `json:"duration_s"`
	Partial    bool           `json:"partial"`
	Items      []feedbackItem `json:"items"`
}) error {
	if len(body.ModelID) > maxModelIDLen {
		return apierr.BadRequest("model_id is too long")
	}
	if len(body.RunnerVer) > 64 || len(body.OS) > 32 || len(body.Arch) > 32 {
		return apierr.BadRequest("runner metadata is too long")
	}
	for _, it := range body.Items {
		if len(it.ExampleID) > 128 {
			return apierr.BadRequest("example_id is too long")
		}
		if len(it.Answer) > maxAnswerBytes {
			return apierr.BadRequest("answer is too long")
		}
		if len(it.Code) > maxCodeBytes {
			return apierr.BadRequest("code is too long")
		}
		if len(it.Error) > maxErrorBytes {
			return apierr.BadRequest("error is too long")
		}
		if len(it.Category) > 64 || len(it.Difficulty) > 32 {
			return apierr.BadRequest("category or difficulty is too long")
		}
		// Control characters would let a caller forge lines in the append-only
		// JSONL result log. Reject rather than sanitise: silent rewriting of a
		// submitted answer would corrupt the benchmark data.
		for _, field := range []string{it.ExampleID, it.Category, it.Difficulty} {
			if hasControlChars(field) {
				return apierr.BadRequest("identifiers may not contain control characters")
			}
		}
	}
	return nil
}

func hasControlChars(s string) bool {
	for _, r := range s {
		if r < 0x20 || r == 0x7f {
			return true
		}
	}
	return false
}

func newRequestID() string {
	var b [8]byte
	if _, err := rand.Read(b[:]); err != nil {
		return "req-unknown"
	}
	return hex.EncodeToString(b[:])
}