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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a855cc
 
 
 
 
 
 
face17f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package core is the relay's decision engine: it wires identity, storage,
// limits and the bank together into the two operations the API exposes.
//
// It knows nothing about HTTP. That keeps the policy testable in isolation and
// means the transport can change without touching a single rule.
package core

import (
	"context"
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"net/netip"
	"os"
	"path/filepath"
	"time"

	"github.com/archnemix/archx-eval/relay/internal/apierr"
	"github.com/archnemix/archx-eval/relay/internal/bank"
	"github.com/archnemix/archx-eval/relay/internal/config"
	"github.com/archnemix/archx-eval/relay/internal/draw"
	"github.com/archnemix/archx-eval/relay/internal/identity"
	"github.com/archnemix/archx-eval/relay/internal/limits"
	"github.com/archnemix/archx-eval/relay/internal/ratelog"
	"github.com/archnemix/archx-eval/relay/internal/reputation"
	"github.com/archnemix/archx-eval/relay/internal/store"
	"github.com/archnemix/archx-eval/relay/internal/syncctl"
)

// Service is the relay core.
type Service struct {
	cfg   config.Config
	store *store.Store
	bank  *bank.Manager
	rep   *reputation.Table
	pol   limits.Policy
	salt  []byte

	// sync queues state changes for the dataset. It is optional: when nil the
	// relay runs in local-only mode. Even when present it never blocks a
	// request, because Enqueue is an in-memory operation.
	sync *syncctl.Controller

	// rates is the durable sliding-window log behind the spam ladder and the
	// network ceilings. It survives a process restart, which matters because
	// a Hugging Face Space stops and restarts constantly.
	rates *ratelog.Log

	now func() time.Time
}

// New builds a Service. Callers own the returned value's lifecycle.
func New(cfg config.Config, st *store.Store, bm *bank.Manager, rep *reputation.Table, rates *ratelog.Log) *Service {
	return &Service{
		cfg:   cfg,
		store: st,
		bank:  bm,
		rep:   rep,
		salt:  cfg.Salt(),
		rates: rates,
		now:   func() time.Time { return time.Now().UTC() },
		pol: limits.Policy{
			Window:        cfg.Window,
			RateAllowance: cfg.RateAllowance,
			RateWindow:    cfg.RateWindow,
			RateSample:    cfg.RateSample,
			RateFloor:     cfg.RateFloor,
			BanWindow:     cfg.BanWindow,
			MaxBan:        cfg.MaxBan,
			// Bands are ordered by severity; the first that fits wins. They are
			// deliberately generous at the bottom so a polling loop that trips
			// 1.5x loses minutes, not days.
			BanBands: []limits.BanBand{
				{Over: 1.0, Ban: 10 * time.Minute},
				{Over: 2.0, Ban: 1 * time.Hour},
				{Over: 3.0, Ban: 6 * time.Hour},
				{Over: 10.0, Ban: 24 * time.Hour},
				{Over: 50.0, Ban: 7 * 24 * time.Hour},
			},
		},
	}
}

// WithSync attaches the dataset write controller.
func (s *Service) WithSync(c *syncctl.Controller) *Service {
	s.sync = c
	return s
}

// SyncStats reports controller health, or nil when sync is disabled.
func (s *Service) SyncStats() *syncctl.Stats {
	if s.sync == nil {
		return nil
	}
	st := s.sync.Stats()
	return &st
}

// SetClock overrides the clock (tests only).
func (s *Service) SetClock(f func() time.Time) { s.now = f }

// DrawInput is the caller-supplied half of a draw request.
type DrawInput struct {
	// Admitted is set by Admit. When false, RequestDraw records the IP marker
	// itself, so a caller that skips the HTTP layer still gets accurate
	// counting instead of silently losing every event.
	Admitted   bool
	RequestID  string
	Categories []string
	Mix        map[string]float64
	Size       int
	Device     identity.Device
	RemoteAddr netip.Addr
	Headers    map[string][]string
}

// Grant is a successful draw.
type Grant struct {
	RequestID  string
	IdentityID string
	Examples   []*bank.Example
	ByCat      map[string]int
	IssuedAt   time.Time
	NextDrawAt time.Time
	Shortfall  int
	Notes      []string

	// Lifeline is the per-example use counter: how many times each question has
	// now been served and how many uses it has left before it goes stale. The
	// counter belongs to the variant, not to the run, so it is shared by
	// everyone who draws it -- two different people asking the same question
	// spend the same budget. It is exposed so a runner can tell the user how
	// long a question has left rather than letting it disappear silently.
	Lifeline map[string]bank.Lifeline
	// StaleAfter is the ceiling Lifeline is measured against.
	StaleAfter int
}

// Hash implements identity.HashFunc with a salted HMAC-SHA256, truncated to
// 32 hex characters. The truncation keeps marker files short while leaving
// 128 bits of collision resistance, which is plenty for this corpus.
func (s *Service) Hash(kind, value string) string {
	mac := hmac.New(sha256.New, s.salt)
	mac.Write([]byte(kind))
	mac.Write([]byte{0})
	mac.Write([]byte(value))
	return hex.EncodeToString(mac.Sum(nil))[:32]
}

// RequestDraw runs the full admission pipeline.
//
// Order is deliberate and cheap-first:
//  1. identity validation (free)
//  2. VPN/privacy refusal (free)
//  3. spam ladder (memory only)
//  4. marker lookup (a handful of file reads)
//  5. draw window (uses the record we already fetched)
//  6. stock check (must happen before we record anything)
//  7. persist usage and only then hand over examples
func (s *Service) RequestDraw(ctx context.Context, in DrawInput) (*Grant, error) {
	now := s.now()

	// Identity, counting and the volume ladder run FIRST, before any shape
	// check. Previously a bot could send malformed bodies all day and never be
	// counted, because every cheap rejection returned before the counters were
	// touched. A refusal must cost the caller something, or flooding is free.
	id, err := identity.FromRequest(in.RemoteAddr, in.Headers, in.Device, s.Hash, s.cfg.AllowLoopback, s.cfg.TrustedProxyHops)
	if err != nil {
		return nil, err
	}

	// A draw id belongs to the server. Callers are told what it is, never the
	// other way round, so it is always minted here regardless of what arrived.
	//
	// An earlier version trusted a caller-supplied id and only refused a
	// repeat. That worked, but the client still chose the handle, and the
	// ledger is keyed by that handle alone: any two callers picking the same
	// value collided, with the second report refused as ALREADY_REPORTED even
	// though it answered a different run. Ignoring the field removes the class
	// of bug instead of policing it, and keeps ids unpredictable so one draw
	// cannot be guessed from another.
	in.RequestID = NewRequestID()

	// Belt and braces: minting is random, but a collision would overwrite a
	// live draw, so it is checked rather than assumed. One retry is enough --
	// at 128 bits a second clash is not a real event.
	if _, taken := s.store.LeaseLedger(in.RequestID); taken {
		in.RequestID = NewRequestID()
		if _, still := s.store.LeaseLedger(in.RequestID); still {
			s.record(ctx, "", "", "deny", "ID_COLLISION", id, 0)
			return nil, apierr.Internal("could not allocate a draw id")
		}
	}

	// A caller may supply its own id, and nothing stops it repeating one. The
	// ledger is keyed by request id alone -- deliberately, because that is what
	// the reporter has to quote -- so a second draw with an id already in the
	// ledger would overwrite the first. Two different machines would then share
	// a handle: each could file answers under it, and ALREADY_REPORTED would
	// refuse the second. That is the one way two separate runs can collide on a
	// draw id, so it is refused here rather than left to feedback.
	if _, taken := s.store.LeaseLedger(in.RequestID); taken {
		s.record(ctx, in.RequestID, "", "deny", "DUPLICATE_REQUEST_ID", id, 0)
		return nil, apierr.BadRequest(
			"request_id was already used for an earlier draw; use a fresh one or omit it")
	}
	markerHashes := make([]string, 0, len(id.Markers))
	for _, m := range id.Markers {
		markerHashes = append(markerHashes, m.Hash)
	}

	// Network ban first: it is the cheapest check and the one that survives an
	// attacker rotating their IP.
	// The ban key must be the SAME key the rate log and the ban writer use,
	// otherwise the stored ban is invisible to the check: the subnet ban did
	// nothing at all until this was fixed.
	netHash := s.netKey(id.Network)
	if d := s.subnetBanDecision(netHash, now); !d.Allow {
		s.record(ctx, in.RequestID, "", "deny", d.Code, id, int(d.RetryAfter.Seconds()))
		return nil, limits.Refuse(d)
	}

	// The volume ladder is evaluated for EVERY marker, not just the first. The
	// ban key used to be markers[0], which is the IP hash, so rotating the IP
	// while keeping the same machine escaped a ban that was already earned.
	if d, banRec := s.evaluateVolumeForMarkers(markerHashes, now); !d.Allow {
		if banRec != nil {
			// Escalate from the minimum band, then multiply by the number of
			// bans this identity has already collected in the window. Without
			// this the ladder restarts at the floor every time a ban expires,
			// so a caller could serve a short ban and repeat for ever.
			if base := limits.BanForCode(s.pol, d.Code); base > 0 {
				if escalated, _ := limits.EvaluateHistory(s.pol, banRec.BanHistory, now, base); escalated > 0 {
					d.Ban = escalated
					d.RetryAfter = escalated
				}
			}
			limits.ApplyBan(banRec, d, now)
			if err := s.store.Put(banRec); err != nil {
				return nil, apierr.Internal("could not record the ban")
			}
			s.publishIdentity(banRec)
		}
		s.record(ctx, in.RequestID, idOf(banRec), "ban", d.Code, id, int(d.RetryAfter.Seconds()))
		return nil, limits.Refuse(d)
	}
	// The IP marker is already counted when Admit ran before body parsing; the
	// device markers are new either way. Network and global counters are
	// recorded only here, because a valid draw is what consumes bank stock.
	start := 0
	if in.Admitted {
		start = 1
	}
	for _, h := range markerHashes[start:] {
		if err := s.rates.Record("id:"+h, now); err != nil {
			fmt.Fprintf(os.Stderr, "warn: rate event not persisted: %v\n", err)
		}
	}
	if err := s.rates.Record(s.netKey(id.Network), now); err != nil {
		fmt.Fprintf(os.Stderr, "warn: network rate event not persisted: %v\n", err)
	}
	if err := s.rates.Record(globalKey, now); err != nil {
		fmt.Fprintf(os.Stderr, "warn: global rate event not persisted: %v\n", err)
	}

	// Only now are shape errors able to return, and they have already been
	// counted against the caller.
	if err := draw.ValidateMix(in.Mix); err != nil {
		return nil, apierr.BadRequest(err.Error())
	}
	size := in.Size
	if size == 0 {
		size = s.cfg.DrawMax
		return nil, apierr.BadRequest("size is required")
	}
	if size < 0 {
		return nil, apierr.BadRequest("size must be positive")
	}
	if size > s.cfg.DrawMax {
		return nil, apierr.BadRequest(fmt.Sprintf("size may not exceed %d", s.cfg.DrawMax))
	}
	// Bound the request shape itself: an unbounded category list or mix map is
	// cheap to send and expensive to process.
	if len(in.Categories) > 32 {
		return nil, apierr.BadRequest("at most 32 categories may be requested")
	}
	if len(in.Mix) > 32 {
		return nil, apierr.BadRequest("at most 32 mix weights may be supplied")
	}

	if s.rep.Loaded() {
		if entry, ok := s.rep.Lookup(id.IP); ok {
			if entry.Tor {
				s.record(ctx, in.RequestID, "", "deny", "TOR_EXIT", id, 0)
				return nil, apierr.Forbidden("PRIVACY_BLOCKED", "requests via Tor are not accepted")
			}
			id.Privacy = identity.SoftFlagsFromIP(id.Privacy, entry.Hosting || entry.VPN, entry.Abuser)
		} else if identity.LooksHosted(id.IP) {
			id.Privacy = identity.SoftFlagsFromIP(id.Privacy, true, 0)
		}
	} else if identity.LooksHosted(id.IP) {
		id.Privacy = identity.SoftFlagsFromIP(id.Privacy, true, 0)
	}
	if id.Privacy.Blocked() {
		s.record(ctx, in.RequestID, "", "deny", "PRIVACY_BLOCKED", id, 0)
		return nil, apierr.Forbidden("PRIVACY_BLOCKED",
			"this request appears to come from a masked network and is not accepted")
	}

	// Network and global ceilings: a single subnet, or the service as a whole,
	// may not convert traffic into bank inventory faster than this. Checked
	// before the draw so a refused request consumes nothing.
	if d := s.evaluateCeilings(id.Network, now); !d.Allow {
		// A tripped network ceiling becomes a stored ban. Without this the
		// subnet control was the weakest one: it lived only in the expiring
		// rate log, so an attacker rotating addresses inside the prefix got a
		// clean slate mid-attack.
		if d.Code == "NETWORK_CEILING" {
			// RetryAfter is already the ban length: escalating it is what
			// makes a subnet that keeps hammering cost more each time.
			key := s.netKey(id.Network)
			var prior []time.Time
			if b, ok := s.store.GetSubnetBan(key); ok && b != nil {
				prior = b.BanHistory
			}
			ban, _ := limits.EvaluateHistory(s.pol, prior, now, d.RetryAfter)
			if ban <= 0 {
				ban = d.RetryAfter
			}
			s.banSubnet(key, d.Reason, ban, now)
			d.Ban = ban
			d.RetryAfter = ban
		} else if d.Code == "IDENTITY_BANNED" || d.Code == "NETWORK_BANNED" {
			d.Ban = 0
		}
		s.record(ctx, in.RequestID, "", "deny", d.Code, id, int(d.RetryAfter.Seconds()))
		return nil, limits.Refuse(d)
	}

	matches, err := s.store.Lookup(markerHashes)
	if err != nil {
		return nil, apierr.Internal("identity lookup failed")
	}
	var rec *store.Record
	if len(matches) > 0 {
		rec = matches[0]
		for _, m := range matches {
			if m.LastSeen.After(rec.LastSeen) {
				rec = m
			}
		}
	}

	if d := limits.EvaluateWindow(s.pol, rec, now); !d.Allow {
		if rec != nil {
			// Refused while banned: serve the remaining ban, do NOT stamp
			// another. Another stamp here would escalate on every refused
			// request and turn one flood into a permanent ban.
			rec.Requests++
			rec.LastSeen = now
			s.mergeMarkers(rec, markerHashes)
			if err := s.store.Put(rec); err != nil {
				return nil, apierr.Internal("could not update identity")
			}
		}
		s.record(ctx, in.RequestID, idOf(rec), "deny", d.Code, id, int(d.RetryAfter.Seconds()))
		return nil, limits.Refuse(d)
	}

	// Stock check before we commit to issuing anything.
	result, err := draw.Select(s.bank, draw.Request{
		Categories: in.Categories,
		Mix:        in.Mix,
		Size:       size,
	})
	if err != nil {
		s.record(ctx, in.RequestID, idOf(rec), "deny", "INSUFFICIENT_STOCK", id, 0)
		return nil, err
	}

	issued := make([]string, 0, len(result.Examples))
	for _, ex := range result.Examples {
		issued = append(issued, ex.ID)
	}

	if rec == nil {
		rec = &store.Record{
			ID:        newID(),
			Markers:   markerHashes,
			FirstSeen: now,
		}
	} else {
		s.mergeMarkers(rec, markerHashes)
	}
	rec.LastSeen = now
	rec.Requests++
	rec.Draws++
	rec.LastDraw = now
	if err := s.store.Put(rec); err != nil {
		return nil, apierr.Internal("could not persist identity")
	}
	s.bank.MarkUsed(issued, now)
	if err := s.bank.SaveUsage(); err != nil {
		// Usage persistence is important but must not fail the user's draw:
		// the in-memory counter already prevents double-issue this process.
		fmt.Fprintf(os.Stderr, "warn: usage save failed: %v\n", err)
	}
	// Record what was issued, so feedback can later be checked against it. This
	// is the whole integrity mechanism: without it /v1/feedback accepts any
	// invented request id and the results dataset becomes whatever a script
	// last posted.
	entry := store.LedgerEntry{
		RequestID:  in.RequestID,
		IdentityID: rec.ID,
		ExampleIDs: issued,
		IssuedAt:   now,
	}
	if err := s.store.AppendLedger(entry); err != nil {
		// A draw without a ledger row cannot be verified later, so it must fail
		// rather than quietly produce unverifiable results.
		return nil, apierr.Internal("could not record the issued draw")
	}
	s.record(ctx, in.RequestID, rec.ID, "allow", "granted", id, 0)
	s.publishIdentity(rec)

	lifeline := make(map[string]bank.Lifeline, len(issued))
	for _, id := range issued {
		used, remaining := s.bank.Uptake(id)
		lifeline[id] = bank.Lifeline{Used: used, Remaining: remaining, Max: s.bank.StaleAfter()}
	}
	return &Grant{
		RequestID:  in.RequestID,
		IdentityID: rec.ID,
		Examples:   result.Examples,
		ByCat:      result.ByCat,
		IssuedAt:   now,
		NextDrawAt: now.Add(s.cfg.Window),
		Shortfall:  result.Shortfall,
		Notes:      result.Notes,
		Lifeline:   lifeline,
		StaleAfter: s.bank.StaleAfter(),
	}, nil
}

// Authenticate verifies the caller's access token. Draws are closed-loop: a
// token is required so that every draw can be traced to a registered runner,
// which is what makes the abuse ladder enforceable at all.
func (s *Service) Authenticate(token string) error {
	if s.cfg.AccessToken == "" {
		return apierr.Forbidden("ACCESS_DISABLED",
			"this relay has no access token configured and is not accepting draws")
	}
	if !constantTimeEqual(token, s.cfg.AccessToken) {
		return apierr.Forbidden("ACCESS_DENIED", "a valid access token is required")
	}
	return nil
}

func constantTimeEqual(a, b string) bool {
	if len(a) != len(b) {
		return false
	}
	var diff byte
	for i := 0; i < len(a); i++ {
		diff |= a[i] ^ b[i]
	}
	return diff == 0
}

// upsert finds an existing record or builds an unsaved one.
func (s *Service) upsert(ctx context.Context, id *identity.Identity, markers []string, now time.Time) (*store.Record, error) {
	matches, err := s.store.Lookup(markers)
	if err != nil {
		return nil, apierr.Internal("identity lookup failed")
	}
	if len(matches) > 0 {
		rec := matches[0]
		s.mergeMarkers(rec, markers)
		rec.LastSeen = now
		return rec, nil
	}
	return &store.Record{ID: newID(), Markers: markers, FirstSeen: now, LastSeen: now}, nil
}

// mergeMarkers keeps a record's marker set current as a caller's device data
// drifts (a new NIC, a reimaged disk) without ever dropping a known marker.
func (s *Service) mergeMarkers(rec *store.Record, markers []string) {
	have := make(map[string]bool, len(rec.Markers))
	for _, m := range rec.Markers {
		have[m] = true
	}
	for _, m := range markers {
		if !have[m] {
			rec.Markers = append(rec.Markers, m)
			have[m] = true
		}
	}
}

// publishIdentity queues the hashed record for the dataset.
//
// The raw row is deliberately NOT queued. The dataset is a git repository, and
// git history is permanent: a committed IP address stays recoverable in the
// commit graph even after the file is deleted, so publishing raw identifiers
// would make the retention promise impossible to keep. Raw rows stay on the
// Space's persistent volume and are pruned locally after 30 days.
func (s *Service) publishIdentity(rec *store.Record) {
	if s.sync == nil || rec == nil {
		return
	}
	if buf, err := store.MarshalRecord(rec); err == nil {
		s.sync.Enqueue(store.RecordPath(rec.ID), buf)
	}
}

func (s *Service) record(ctx context.Context, reqID, id, decision, reason string, ident *identity.Identity, retry int) {
	if ident == nil {
		return
	}
	ev := store.Event{
		TS:         s.now(),
		RequestID:  reqID,
		IdentityID: id,
		Decision:   decision,
		Reason:     reason,
		IPHash:     s.Hash(identity.MarkerIP, ident.IP.String()),
		NetHash:    s.Hash("net", ident.Network.String()),
		Country:    ident.Country,
		OS:         ident.Device.OSFamily,
		Arch:       ident.Device.Arch,
		RetryAfter: retry,
	}
	if err := s.store.AppendEvent(ev); err != nil {
		fmt.Fprintf(os.Stderr, "warn: event not persisted: %v\n", err)
		return
	}
	if s.sync != nil {
		if buf, err := s.store.ReadEventDay(ev.TS); err == nil {
			s.sync.Enqueue(store.EventPath(ev.TS), buf)
		}
		if buf, err := s.store.ReadLedgerDay(ev.TS); err == nil {
			s.sync.Enqueue("ledger/"+ev.TS.UTC().Format("2006-01-02")+".jsonl", buf)
		}
	}
}

// rateKey is the durable log key for an identity. Identity markers are already
// salted hashes, so the key leaks nothing.
// banBaseFor recovers the base ban length for a record from the ladder, so an
// extension escalates from the right starting point instead of from whatever
// is left of the current ban.
func (s *Service) banBaseFor(rec *store.Record) time.Duration {
	return limits.BanForCode(s.pol, rec.BanReason)
}

func (s *Service) rateKey(markers []string) string {
	if len(markers) == 0 {
		return ""
	}
	return "id:" + markers[0]
}

func (s *Service) netKey(p netip.Prefix) string {
	if !p.IsValid() {
		return ""
	}
	return "net:" + s.Hash("net", p.String())
}

const globalKey = "global"

// evaluateVolume rebuilds the request history from the durable log and asks
// the limits package for a verdict.
// evaluateVolumeForMarkers runs the volume ladder against every marker the
// caller presented and returns the worst decision.
//
// Banning on only markers[0] (the IP hash) was a hole: rotating the IP while
// keeping the same machine escaped a ban already earned. Any single marker
// tripping the ladder is now enough.
func (s *Service) evaluateVolumeForMarkers(markerHashes []string, now time.Time) (limits.Decision, *store.Record) {
	var worst limits.Decision
	var worstRec *store.Record
	for _, h := range markerHashes {
		// If this marker is already serving a ban, do not treat every further
		// request as a fresh offence: one attack must cost one ban. The number
		// of bans is what drives escalation, so re-stamping on each refused
		// request turned a single flood into a two-week ban for the whole /24.
		if recs, err := s.store.Lookup([]string{h}); err == nil {
			alreadyBanned := false
			for _, r := range recs {
				if r.Banned(now) {
					alreadyBanned = true
					break
				}
			}
			if alreadyBanned {
				continue
			}
		}
		d := s.evaluateVolume("id:"+h, now)
		if d.Allow {
			continue
		}
		if d.Ban > worst.Ban {
			worst = d
			// A ban needs a record to hang off; find the one this marker
			// belongs to, or create it.
			if rec, err := s.upsert(context.Background(), nil, []string{h}, now); err == nil {
				worstRec = rec
			}
		}
	}
	if worst.Ban == 0 {
		return limits.Decision{Allow: true}, nil
	}
	// Escalate by recent ban history so "serve ten minutes, repeat" cannot loop
	// for ever. The history is read from the record we are about to stamp.
	if worstRec != nil {
		if dur, prior := limits.EvaluateHistory(s.pol, worstRec.BanHistory, now, worst.Ban); dur > 0 {
			worst.Ban = dur
			worst.RetryAfter = dur
			if prior > 0 {
				worst.Reason = fmt.Sprintf("%s (repeat offence: %d ban(s) in the last %s)",
					worst.Reason, prior, s.pol.BanWindow)
			}
		}
	}
	return worst, worstRec
}

// Admit performs the accounting that must happen before the request body is
// parsed.
//
// This exists because body decoding happens in the HTTP layer, so a request
// with malformed JSON never reached any counter: a bot could send rubbish all
// day for free, and the ladder never saw it. Identity is derived from the
// address alone here, the subnet ban and the volume ladder are enforced, and
// the counters are recorded. Device markers cannot be known yet; they are
// recorded later by RequestDraw.
func (s *Service) Admit(in DrawInput) error {
	_ = in.Admitted
	now := s.now()
	id, err := identity.FromRequest(in.RemoteAddr, in.Headers, identity.Device{}, s.Hash, s.cfg.AllowLoopback, s.cfg.TrustedProxyHops)
	if err != nil {
		return err
	}
	markerHashes := make([]string, 0, len(id.Markers))
	for _, m := range id.Markers {
		markerHashes = append(markerHashes, m.Hash)
	}

	netHash := s.netKey(id.Network)
	if d := s.subnetBanDecision(netHash, now); !d.Allow {
		s.record(context.Background(), in.RequestID, "", "deny", d.Code, id, int(d.RetryAfter.Seconds()))
		return limits.Refuse(d)
	}

	// A caller already serving a ban is refused here, before the body is read.
	// Without this they kept receiving 400s for malformed bodies during their
	// own ban, which looks like "the ban did not apply" both to them and to
	// anyone reading the logs.
	for _, h := range markerHashes {
		recs, err := s.store.Lookup([]string{h})
		if err != nil {
			continue
		}
		for _, r := range recs {
			if r.Banned(now) {
				d := limits.Decision{
					Code:       "IDENTITY_BANNED",
					Reason:     r.BanReason,
					RetryAfter: r.BannedUntil.Sub(now),
				}
				s.record(context.Background(), in.RequestID, r.ID, "deny", d.Code, id, int(d.RetryAfter.Seconds()))
				return limits.Refuse(d)
			}
		}
	}

	// A caller already serving a ban is refused here, before the body is read.
	// Without this they kept receiving 400s for malformed bodies during their
	// own ban, which looks like "the ban never applied" to them and to anyone
	// reading the logs.
	for _, h := range markerHashes {
		recs, lerr := s.store.Lookup([]string{h})
		if lerr != nil {
			continue
		}
		for _, r := range recs {
			if r.Banned(now) {
				d := limits.Decision{
					Code:       "IDENTITY_BANNED",
					Reason:     r.BanReason,
					RetryAfter: r.BannedUntil.Sub(now),
				}
				s.record(context.Background(), in.RequestID, r.ID, "deny", d.Code, id, int(d.RetryAfter.Seconds()))
				return limits.Refuse(d)
			}
		}
	}

	if d, banRec := s.evaluateVolumeForMarkers(markerHashes, now); !d.Allow {
		if banRec != nil {
			if base := limits.BanForCode(s.pol, d.Code); base > 0 {
				if escalated, _ := limits.EvaluateHistory(s.pol, banRec.BanHistory, now, base); escalated > 0 {
					d.Ban = escalated
					d.RetryAfter = escalated
				}
			}
			limits.ApplyBan(banRec, d, now)
			_ = s.store.Put(banRec)
			s.publishIdentity(banRec)
		}
		s.record(context.Background(), in.RequestID, idOf(banRec), "ban", d.Code, id, int(d.RetryAfter.Seconds()))
		return limits.Refuse(d)
	}

	for _, h := range markerHashes {
		if err := s.rates.Record("id:"+h, now); err != nil {
			fmt.Fprintf(os.Stderr, "warn: rate event not persisted: %v\n", err)
		}
	}
	// Network and global counters are NOT recorded here: they exist to cap how
	// fast the bank can be drained, and only a valid draw drains it. A rejected
	// garbage request should cost the caller, not consume the subnet's budget.
	return nil
}

// subnetBanDecision reports whether this network prefix is currently banned.
func (s *Service) subnetBanDecision(netHash string, now time.Time) limits.Decision {
	if netHash == "" {
		return limits.Decision{Allow: true}
	}
	b, ok := s.store.GetSubnetBan(netHash)
	if !ok || b == nil || !now.Before(b.BannedUntil) {
		return limits.Decision{Allow: true}
	}
	return limits.Decision{
		Code:       "NETWORK_BANNED",
		Reason:     b.Reason,
		RetryAfter: b.BannedUntil.Sub(now),
	}
}

// banSubnet records a network-level ban. This is what makes the network
// ceiling durable: the ceiling itself is evaluated from the rate log, which
// expires, but once tripped the punishment is stored so rotating the IP inside
// the same prefix does not reset it.
func (s *Service) banSubnet(netHash, reason string, ban time.Duration, now time.Time) {
	if netHash == "" || ban <= 0 {
		return
	}
	b, _ := s.store.GetSubnetBan(netHash)
	if b == nil {
		b = &store.SubnetBan{NetHash: netHash}
	}
	b.BanCount++
	b.Reason = reason
	b.BannedUntil = now.Add(ban)
	b.BanHistory = append(b.BanHistory, now)
	if len(b.BanHistory) > 64 {
		b.BanHistory = b.BanHistory[len(b.BanHistory)-64:]
	}
	if err := s.store.PutSubnetBan(b); err != nil {
		fmt.Fprintf(os.Stderr, "warn: subnet ban not persisted: %v\n", err)
	}
}

func (s *Service) evaluateVolume(key string, now time.Time) limits.Decision {
	if key == "" {
		return limits.Decision{Allow: true}
	}
	// The peak rate over the window is what matters, not a raw count: it tells
	// a burst apart from a steady drip at the same average.
	times := s.rates.Times(key, s.pol.RateWindow, now)
	return limits.EvaluateVolume(s.pol, times, now)
}

func (s *Service) evaluateCeilings(p netip.Prefix, now time.Time) limits.Decision {
	if s.cfg.NetMaxDraws > 0 {
		if n := s.rates.Count(s.netKey(p), s.cfg.NetWindow, now); n > s.cfg.NetMaxDraws {
			return limits.Decision{
				Code:       "NETWORK_CEILING",
				Reason:     "this network has reached its draw ceiling",
				RetryAfter: s.cfg.NetWindow,
			}
		}
	}
	if s.cfg.GlobalMax > 0 {
		if n := s.rates.Count(globalKey, s.cfg.GlobalWindow, now); n > s.cfg.GlobalMax {
			return limits.Decision{
				Code:       "GLOBAL_CEILING",
				Reason:     "the bank is at capacity for this window",
				RetryAfter: s.cfg.GlobalWindow,
			}
		}
	}
	return limits.Decision{Allow: true}
}

// Health summarises readiness.
type Health struct {
	OK            bool            `json:"ok"`
	Version       string          `json:"version"`
	UptimeSeconds int64           `json:"uptime_s"`
	Bank          map[string]int  `json:"bank"`
	Inventory     bank.Counts     `json:"inventory"`
	Questions     []bank.Question `json:"questions,omitempty"`
	Records       int             `json:"records"`
	Markers       int             `json:"markers"`
	Reputation    int             `json:"reputation_ranges"`
	SaltIsDefault bool            `json:"salt_is_default"`
	Sync          *syncctl.Stats  `json:"sync,omitempty"`
}

var startedAt = time.Now()

// Version is stamped at build time via ldflags.
var Version = "dev"

// Health reports service state without touching the bank lists.
func (s *Service) Health() Health {
	recs, markers := s.store.Stats()
	return Health{
		OK:            s.bank.Size() > 0,
		Version:       Version,
		UptimeSeconds: int64(time.Since(startedAt).Seconds()),
		Bank:          s.bank.Stats(),
		Inventory:     s.bank.Inventory(),
		Questions:     s.bank.Questions(),
		Records:       recs,
		Markers:       markers,
		Reputation:    s.rep.Size(),
		SaltIsDefault: s.cfg.SaltIsDefault(),
		Sync:          s.SyncStats(),
	}
}

// Categories lists servable categories.
func (s *Service) Categories() []string { return s.bank.Categories() }

// StaleExamples exposes the stale list for the daily curator job.
func (s *Service) StaleExamples() []bank.Example { return s.bank.Stale() }

// Prune clears expired bans. No personal data is stored, so there is nothing
// to expire; the retention obligation disappears with the raw values.
func (s *Service) Prune() (int, error) { return s.store.Prune(s.now()) }

// PruneLedger drops ledger days older than the configured retention and forgets
// subnet bans that have been expired for longer than the ban window. Both are
// called from the housekeeping ticker.
func (s *Service) PruneLedger(now time.Time) (int, int, error) {
	days := s.cfg.LedgerKeepDays
	if days <= 0 {
		days = 7
	}
	files, err := s.store.PruneLedger(now, days)
	if err != nil {
		return 0, 0, err
	}
	keep := s.cfg.BanWindow
	if keep <= 0 {
		keep = 24 * time.Hour
	}
	bans, err := s.store.PruneSubnetBans(now, keep)
	return files, bans, err
}

// Maintain compacts and fsyncs the durable rate log. Called on a timer.
func (s *Service) Maintain(now time.Time) (int, error) {
	n, err := s.rates.Compact(now)
	if err != nil {
		return n, err
	}
	return n, s.rates.Flush()
}

// Flush persists counters and the manifest.
func (s *Service) Flush() error {
	if err := s.bank.SaveUsage(); err != nil {
		return err
	}
	return s.store.FlushIndex()
}

// FlushRates fsyncs the durable rate log; called on shutdown.
func (s *Service) FlushRates() error { return s.rates.Flush() }

// PublishableSubtrees is the single canonical list of store subtrees that may
// be mirrored to the dataset. "raw" is absent on purpose: raw identity rows
// must never enter a git repository, whose history is permanent.
//
// Both the live sync controller and the one-shot -sync export read this list,
// so the two paths cannot drift apart (a real leak happened when they did).
var PublishableSubtrees = []string{"identities", "markers", "events", "results"}

// ExportSnapshot copies the publishable store tree into dir for the dataset
// mirror.
func (s *Service) ExportSnapshot(dir string) ([]string, error) {
	if err := s.Flush(); err != nil {
		return nil, err
	}
	src := s.cfg.DataDir
	var written []string
	for _, sub := range PublishableSubtrees {
		from := filepath.Join(src, sub)
		to := filepath.Join(dir, sub)
		n, err := copyTree(from, to)
		if err != nil {
			return written, err
		}
		written = append(written, n...)
	}
	return written, nil
}

func copyTree(from, to string) ([]string, error) {
	var out []string
	err := filepath.Walk(from, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			if os.IsNotExist(err) {
				return nil
			}
			return err
		}
		if info.IsDir() {
			return nil
		}
		rel, err := filepath.Rel(from, path)
		if err != nil {
			return err
		}
		buf, err := os.ReadFile(path)
		if err != nil {
			return err
		}
		dest := filepath.Join(to, rel)
		if err := os.MkdirAll(filepath.Dir(dest), 0o750); err != nil {
			return err
		}
		if err := os.WriteFile(dest, buf, 0o640); err != nil {
			return err
		}
		out = append(out, filepath.ToSlash(filepath.Join(filepath.Base(from), rel)))
		return nil
	})
	if os.IsNotExist(err) {
		return out, nil
	}
	return out, err
}

func idOf(rec *store.Record) string {
	if rec == nil {
		return ""
	}
	return rec.ID
}

// NewRequestID mints a draw id: 128 random bits, hex encoded. Exposed because
// the HTTP layer is the only place a draw id may originate, and the core must
// treat whatever arrives on the wire as untrusted.
func NewRequestID() string {
	return newID()
}

// newID returns a random 128-bit hex identifier.
func newID() string {
	var b [16]byte
	if _, err := rand.Read(b[:]); err != nil {
		// crypto/rand failure is not recoverable in any useful way here.
		panic("core: entropy source unavailable")
	}
	return hex.EncodeToString(b[:])
}

// SubmitResult records a benchmark report from a front-end runner.
func (s *Service) SubmitResult(r store.Result) error {
	return s.store.AppendResult(r)
}

// Erase reports whether an identity is known. There is no personal data to
// delete: only hashes are stored, so the endpoint is retained for compatibility
// and answers "nothing to erase" rather than pretending to remove something.
func (s *Service) Erase(id string) (bool, error) {
	_, known := s.store.Get(id)
	return known, nil
}

// SyncFlush publishes everything queued for the dataset. Used by -sync, by
// shutdown, and by tests.
func (s *Service) SyncFlush(ctx context.Context) error {
	if s.sync == nil {
		return nil
	}
	return s.sync.FlushNow(ctx)
}