-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
2742 lines (2659 loc) · 114 KB
/
Copy pathmain.go
File metadata and controls
2742 lines (2659 loc) · 114 KB
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 main
import (
"context"
"database/sql"
"encoding/hex"
"errors"
"flag"
"fmt"
"net"
"net/http"
"net/netip"
"os"
"os/signal"
"path/filepath"
"reflect"
"strconv"
"strings"
"syscall"
"time"
"github.com/augstar/macprovider-coordinator/internal/audit"
"github.com/augstar/macprovider-coordinator/internal/auth"
"github.com/augstar/macprovider-coordinator/internal/autotune"
"github.com/augstar/macprovider-coordinator/internal/billing"
"github.com/augstar/macprovider-coordinator/internal/buyer"
"github.com/augstar/macprovider-coordinator/internal/catalogbind"
"github.com/augstar/macprovider-coordinator/internal/config"
"github.com/augstar/macprovider-coordinator/internal/explorer"
"github.com/augstar/macprovider-coordinator/internal/mdm"
"github.com/augstar/macprovider-coordinator/internal/onboarding"
"github.com/augstar/macprovider-coordinator/internal/payout"
"github.com/augstar/macprovider-coordinator/internal/pool"
"github.com/augstar/macprovider-coordinator/internal/pow"
"github.com/augstar/macprovider-coordinator/internal/providerevents"
"github.com/augstar/macprovider-coordinator/internal/providerhttp"
"github.com/augstar/macprovider-coordinator/internal/referralapi"
"github.com/augstar/macprovider-coordinator/internal/requestlog"
"github.com/augstar/macprovider-coordinator/internal/rewards"
"github.com/augstar/macprovider-coordinator/internal/stats"
statshardware "github.com/augstar/macprovider-coordinator/internal/stats/hardware"
statsmetrics "github.com/augstar/macprovider-coordinator/internal/stats/metrics"
"github.com/augstar/macprovider-coordinator/internal/stats/poolsnapshot"
statsprewarm "github.com/augstar/macprovider-coordinator/internal/stats/prewarm"
statsrollup "github.com/augstar/macprovider-coordinator/internal/stats/rollup"
statsstore "github.com/augstar/macprovider-coordinator/internal/stats/store"
"github.com/augstar/macprovider-coordinator/internal/tier2"
providerws "github.com/augstar/macprovider-coordinator/internal/ws"
prom "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
// SPEC-017 v0.1.8 — register the Postgres driver under the
// "postgres" name used by internal/stats.Open. lib/pq is the
// only Postgres driver in go.mod for v0.1; switching to pgx
// requires a SPEC v0.2 conversation.
_ "github.com/lib/pq"
"github.com/rs/zerolog"
)
// parseRFC3339Strict parses an RFC 3339 timestamp and returns an
// explicit error on parse failure. Used in the stats rollup
// boot path where backfill_mode = "partial" requires the
// boundary to be valid (round-1 ARCH r1 HIGH 2 fix).
func parseRFC3339Strict(s string) (time.Time, error) {
return time.Parse(time.RFC3339, s)
}
// version is overridden at build time via
//
// go build -ldflags "-X main.version=$(git describe --always --dirty --tags)"
//
// (see scripts/build-linux.sh). Defaults to "dev" for local `go run`.
var version = "dev"
func main() {
// SPEC-017 v0.1.8 Step 4.A — subcommand dispatch. When the
// first positional arg is a known operator-CLI verb, route
// to the corresponding handler and exit with its code. The
// daemon path is preserved below for argv shapes that DON'T
// match (the historical `coordinator --config=... --version`
// invocations).
//
// Why before flag.Parse(): the daemon's flag set rejects
// non-flag positional args ("partner-keys" would error out
// of flag.Parse with "flag provided but not defined"). We
// intercept first.
if len(os.Args) >= 2 {
arg1 := os.Args[1]
switch arg1 {
case "partner-keys":
os.Exit(runPartnerKeys(os.Args[2:]))
case "visibility":
os.Exit(runVisibility(os.Args[2:]))
case "migrate-indexes":
os.Exit(runMigrateIndexes(os.Args[2:]))
case "backfill-attempt-n":
os.Exit(runBackfillAttemptN(os.Args[2:]))
case "stats-migrate":
os.Exit(runStatsMigrate(os.Args[2:]))
}
// Round-1 CODE H1 fix: a non-flag first positional that
// is NEITHER a known daemon flag NOR a known CLI verb is
// a typo. Reject with usage so an operator who mistypes
// `coordinator visiblity revert ...` doesn't silently
// start the daemon (which would try to load
// coordinator.yaml). Daemon flags begin with `-`; CLI
// verbs are enumerated below.
if !strings.HasPrefix(arg1, "-") {
fmt.Fprintf(os.Stderr, "coordinator: unknown subcommand %q\n", arg1)
fmt.Fprintln(os.Stderr, "usage:")
fmt.Fprintln(os.Stderr, " coordinator --config <path> [--config-overlay <path>] [--validate-config]")
fmt.Fprintln(os.Stderr, " coordinator --version (print build version)")
fmt.Fprintln(os.Stderr, " coordinator partner-keys <issue|revoke|list> [flags]")
fmt.Fprintln(os.Stderr, " coordinator visibility revert --id <pid> --reason TEXT")
fmt.Fprintln(os.Stderr, " coordinator migrate-indexes --config <path> (one-shot operator migration)")
fmt.Fprintln(os.Stderr, " coordinator backfill-attempt-n --config <path> (one-shot attempt_n backfill)")
fmt.Fprintln(os.Stderr, " coordinator stats-migrate [--admin-dsn DSN] [--check] (SPEC-017 stats/rewards migrations)")
os.Exit(2)
}
}
configPath := flag.String("config", "coordinator.yaml", "path to coordinator YAML config")
configOverlay := flag.String("config-overlay", "", "optional YAML overlay merged after --config (overlay keys override)")
validateConfig := flag.Bool("validate-config", false, "load config (with overlay if set), validate, and exit")
showVersion := flag.Bool("version", false, "print build version and exit")
flag.Parse()
if *showVersion {
fmt.Println(version)
return
}
cfg, err := config.LoadWithOverlay(*configPath, *configOverlay)
if err != nil {
fmt.Fprintf(os.Stderr, "config: %v\n", err)
os.Exit(1)
}
if *validateConfig {
fmt.Println("config: ok")
return
}
autotuneFeeds, err := buyer.LoadAutotuneFeeds(cfg.AutotuneFeeds)
if err != nil {
fmt.Fprintf(os.Stderr, "autotune feeds: %v\n", err)
os.Exit(1)
}
var autotuneCatalog *autotune.Catalog
var autotuneCompatibleCatalogs []*autotune.Catalog
if len(autotuneFeeds.AutotuneCandidatesJSON) > 0 {
autotuneCatalog, err = autotune.ParseCatalog(autotuneFeeds.AutotuneCandidatesJSON)
if err != nil {
fmt.Fprintf(os.Stderr, "autotune candidate catalog: %v\n", err)
os.Exit(1)
}
if autotune.IsPermanentlyRejectedReleaseID(autotuneCatalog.Version) {
fmt.Fprintf(os.Stderr, "autotune candidate catalog: release ID %q is permanently rejected\n", autotuneCatalog.Version)
os.Exit(1)
}
autotuneCatalog.SignerKeyID = autotuneFeeds.AutotuneCandidatesVerification.KeyID
autotuneCompatibleCatalogs, err = loadPreviousAutotuneCatalog(cfg.AutotuneFeeds)
if err != nil {
fmt.Fprintf(os.Stderr, "autotune previous catalog: %v\n", err)
os.Exit(1)
}
}
providerhttp.Init(cfg.ProviderHTTP.TimeoutS)
logger := zerolog.New(os.Stdout).With().Timestamp().Logger()
compatibilityPolicyMode := "unconfigured"
if cfg.Coordinator.CompatibilitySet.Configured() {
compatibilityPolicyMode = "configured"
}
logger.Info().
Str("compatibility_policy", compatibilityPolicyMode).
Str("recommended_compatibility_set_id", cfg.Coordinator.CompatibilitySet.TargetID).
Int("accepted_compatibility_set_count", len(cfg.Coordinator.CompatibilitySet.AcceptedIDs)).
Int("first_hop_bridge_set_count", len(cfg.Coordinator.CompatibilitySet.FirstHopBridgeIDs)).
Msg("provider compatibility-set admission policy initialized")
if err := tier2.Configure(cfg.Tier2, logger); err != nil {
fmt.Fprintf(os.Stderr, "tier2: %v\n", err)
os.Exit(1)
}
// #608 Partial: fail closed when active Tier-2 rows conflict with the
// current autotune admission identity for the same model_id. Does not
// introduce a Tier-2 fallback (Entry 170 / #609); only rejects drift.
if err := catalogbind.RequireActiveReleaseBinding(autotuneCatalog, tier2.Default()); err != nil {
fmt.Fprintf(os.Stderr, "catalog binding: %v\n", err)
os.Exit(1)
}
metricsRegistry := prom.NewRegistry()
metricsHandle := statsmetrics.New(metricsRegistry)
registry := pool.NewRegistry(cfg.Providers)
startedAt := time.Now().UTC()
tokenStore, err := auth.OpenStore(cfg.Storage.DBPath)
if err != nil {
fmt.Fprintf(os.Stderr, "storage: %v\n", err)
os.Exit(1)
}
defer tokenStore.Close()
reqLogStore, err := requestlog.OpenStore(cfg.Storage.DBPath)
if err != nil {
fmt.Fprintf(os.Stderr, "requestlog: %v\n", err)
os.Exit(1)
}
defer reqLogStore.Close()
// SPEC-002 v1.4.2 R-2 / ISS-188: request_log.external_request_id
// is added by OpenStore as an additive column. The matching partial-
// NULL reconciliation index is NOT auto-built here — the request-log
// store caps the pool at one writer connection (see
// requestlog.OpenStore SetMaxOpenConns(1)), so running CREATE INDEX
// from the daemon would contend with the 6s-timeout INSERT hot
// path. The index ships via the `coordinator migrate-indexes`
// subcommand, intended to be invoked once per deploy by the
// operator runbook before binding traffic (or during a maintenance
// window).
canaryStore, err := setupCanarySanctionStore(context.Background(), cfg, reqLogStore.DB(), registry)
if err != nil {
fmt.Fprintf(os.Stderr, "canary sanction storage: %v\n", err)
os.Exit(1)
}
auditStore, err := audit.OpenStore(cfg.Storage.DBPath)
if err != nil {
fmt.Fprintf(os.Stderr, "audit log storage: %v\n", err)
os.Exit(1)
}
defer auditStore.Close()
admissionStore, err := providerws.NewSQLiteAdmissionStore(reqLogStore.DB())
if err != nil {
fmt.Fprintf(os.Stderr, "admission storage: %v\n", err)
os.Exit(1)
}
connectionEventStore, err := providerevents.Open(providerevents.DefaultDBPath(cfg.Storage.DBPath))
if err != nil {
fmt.Fprintf(os.Stderr, "provider connection events storage: %v\n", err)
os.Exit(1)
}
defer connectionEventStore.Close()
if err := connectionEventStore.ReconcileBounds(context.Background()); err != nil {
fmt.Fprintf(os.Stderr, "provider connection events reconcile: %v\n", err)
os.Exit(1)
}
billingStore, err := billing.NewStore(reqLogStore.DB())
if err != nil {
fmt.Fprintf(os.Stderr, "billing: %v\n", err)
os.Exit(1)
}
// R4 fix (CODE-M2): set the route-layer flag atomic BEFORE the
// startup snapshot so the snapshot's canonical hash captures the
// initial flag state (SPEC-005 v0.4 §11.6.4 / §13.2). The
// "startup" source suppresses the billing_config_flag_changed
// audit emit per SPEC §11.6.4 (no prior acknowledged value).
if err := billingStore.SetForceVoidEnabled(context.Background(), cfg.Billing.QuarantineResolutionForceVoidEnabled, "startup"); err != nil {
fmt.Fprintf(os.Stderr, "billing force-void flag init: %v\n", err)
os.Exit(1)
}
if err := billingStore.SetForceCreditEnabled(context.Background(), cfg.Billing.QuarantineResolutionForceCreditEnabled, "startup"); err != nil {
fmt.Fprintf(os.Stderr, "billing force-credit flag init: %v\n", err)
os.Exit(1)
}
billingStore.SetForceCreditSettlementHoldSeconds(int64(cfg.Billing.ForceCreditSettlementHoldSeconds))
snapshotID, err := billingStore.InsertConfigSnapshot(context.Background(), cfg.Rewards, time.Now().UTC())
if err != nil {
fmt.Fprintf(os.Stderr, "billing config snapshot: %v\n", err)
os.Exit(1)
}
// SPEC-017 v0.1.8 Step 1 — Postgres pools for the Network
// Stats API. Fail-closed per BUILD §C.3: any missing required
// runtime DSN or any failed startup smoke aborts coordinator
// boot BEFORE any HTTP listener binds. When cfg.Stats.Enabled
// is false (the v0.1 default), Open returns stats.ErrDisabled
// and the /v1/stats/* mux subtree is NOT registered later;
// 404 from the existing mux fallback is the correct posture
// (NOT a custom JSON envelope, which would violate the §5.9
// closed code vocabulary — BUILD §C.4).
//
// The CLI operator DSN (cfg.Stats.PartnerKeysAdminDSN) is
// declared but INTENTIONALLY NOT OPENED here — the
// coordinator process should never hold an
// INSERT-on-partner_keys connection at runtime. Step 4.A's
// `coordinator partner-keys issue/revoke` subcommands open
// that DSN at invocation time only. SECURITY §B.1 invariant.
var statsPools *stats.Pools
if cfg.Stats.Enabled {
statsCfg := stats.Config{
Enabled: cfg.Stats.Enabled,
ReaderDSN: cfg.Stats.ReaderDSN,
RollupDSN: cfg.Stats.RollupDSN,
PartnerKeys: stats.PartnerKeysConfig{LastUsedAtUpdatesEnabled: cfg.Stats.PartnerKeys.LastUsedAtUpdatesEnabled, WriterDSN: cfg.Stats.PartnerKeys.WriterDSN},
PartnerKeysAdminDSN: cfg.Stats.PartnerKeysAdminDSN,
Rollup: stats.RollupConfig{
BackfillMode: cfg.Stats.Rollup.BackfillMode,
PartialHistorySince: cfg.Stats.Rollup.PartialHistorySince,
LateEventsRetentionDays: cfg.Stats.Rollup.LateEventsRetentionDays,
UsdPerMillionCredits: cfg.Stats.Rollup.UsdPerMillionCredits,
DriftThresholdRatio: cfg.Stats.Rollup.DriftThresholdRatio,
NightlyRebuildHourUTC: cfg.Stats.Rollup.NightlyRebuildHourUTC,
LateEventsLookbackHours: cfg.Stats.Rollup.LateEventsLookbackHours,
},
CORS: stats.CORSConfig{
AccessControlMaxAgeSeconds: cfg.Stats.CORS.AccessControlMaxAgeSeconds,
PartnerOriginAllowlist: cfg.Stats.CORS.PartnerOriginAllowlist,
},
TrustedProxies: cfg.Stats.TrustedProxies,
}
var err error
statsPools, err = stats.Open(context.Background(), statsCfg)
if err != nil {
fmt.Fprintf(os.Stderr, "stats: %v\n", err)
os.Exit(1)
}
// MIGRATIONS ARE NOT RUN AT COORDINATOR BOOT (round-1
// CRITICAL fix across all three lanes: SECURITY r1
// CRIT-2, CODE r1 HIGH C2, ARCH r1 HIGH C1). The earlier
// draft applied migrations through the stats_rollup
// runtime pool with a STATS_SKIP_MIGRATIONS_AT_BOOT=1
// opt-out — that defaulted to over-privileging the
// runtime role and made the safe production path a
// remember-this-env-var footgun. Migrations are now
// operator-side: invoke `statsmigrations.Apply` from an
// admin DSN via psql or a follow-up
// `coordinator stats migrate --admin-dsn=...`
// subcommand. The integration test harness applies
// migrations through its own admin DSN.
logger.Info().Msg("SPEC-017 stats pools opened (reader, rollup); migrations are operator-applied; /v1/stats/* will be mounted by Step 3")
} else {
logger.Info().Msg("SPEC-017 stats DISABLED via config (default); /v1/stats/* not registered")
}
defer func() {
if statsPools != nil {
_ = statsPools.Close()
}
}()
shutdownCtx, stopBackground := context.WithCancel(context.Background())
defer stopBackground()
// SPEC-017 v0.1.8 Step 2 — rollup runner. Reads OLTP source
// tables via `statsPools.Rollup`, writes the seven
// stats_* + stats_components_health + stats_rewards_populated
// surfaces, and emits structured drift-detection events. Per
// SPEC §7.2.5 the rollup MUST NOT use Reader / ProviderPortal
// pools — `New(statsPools.Rollup, ...)` enforces.
//
// poolsnapshot.NewWithHardware wires the live §5.1.1 snapshot fields
// (nodes_online, nodes_hardware_attested, utilization, RAM,
// models_serving) from the in-process pool.Registry and enriches
// hardware capacity from an async stats_rollup-side cache. The
// snapshot path itself remains memory-only: no DB lookups on buyer,
// routing, streaming, heartbeat, or public stats request paths.
var statsRollup *statsrollup.Runner
if statsPools != nil {
// Round-1 ARCH r1 HIGH 2 fix: BackfillMode must be the
// authoritative selector. "full" forces
// PartialHistorySinceUnix = 0 (the boundary the rollup
// queries against; 0 = no lower-bound filter); "partial"
// requires a non-empty partial_history_since and fails
// startup if it doesn't parse.
mode := cfg.Stats.Rollup.BackfillMode
if mode == "" {
mode = "partial"
}
var partialUnix int64
switch mode {
case "full":
partialUnix = 0
case "partial":
// Round-2 ARCH r2 HIGH 2 fix: backfill_mode = "partial"
// requires a non-empty RFC 3339 partial_history_since
// when stats.enabled = true. Path A semantics demand
// a rollup-start boundary that Step 3 can emit as
// the JSON `partial_history_since` field. Empty +
// partial would silently behave like "full" while
// leaving Step 3 with no field to emit — two
// conforming sessions could disagree about which
// path is in effect. Force the operator to be
// explicit.
if cfg.Stats.Rollup.PartialHistorySince == "" {
fmt.Fprintf(os.Stderr, "stats rollup: stats.rollup.partial_history_since must be non-empty when backfill_mode = 'partial'; use backfill_mode = 'full' for unconstrained history\n")
os.Exit(1)
}
parsed, perr := parseRFC3339Strict(cfg.Stats.Rollup.PartialHistorySince)
if perr != nil {
fmt.Fprintf(os.Stderr, "stats rollup: stats.rollup.partial_history_since must parse as RFC 3339 when backfill_mode = 'partial' (got %q): %v\n", cfg.Stats.Rollup.PartialHistorySince, perr)
os.Exit(1)
}
partialUnix = parsed.Unix()
default:
fmt.Fprintf(os.Stderr, "stats rollup: stats.rollup.backfill_mode must be 'partial' or 'full' (got %q)\n", mode)
os.Exit(1)
}
rollupCfg := statsrollup.Config{
BackfillMode: mode,
PartialHistorySinceUnix: partialUnix,
LateEventsRetentionDays: cfg.Stats.Rollup.LateEventsRetentionDays,
UsdPerMillionCredits: cfg.Stats.Rollup.UsdPerMillionCredits,
DriftThresholdRatio: cfg.Stats.Rollup.DriftThresholdRatio,
NightlyRebuildHourUTC: cfg.Stats.Rollup.NightlyRebuildHourUTC,
LateEventsLookbackHours: cfg.Stats.Rollup.LateEventsLookbackHours,
}
hardwareCache := statshardware.NewCache(statsPools.Rollup)
hardwareCtx, cancelHardwareRefresh := context.WithTimeout(shutdownCtx, 2*time.Second)
if err := hardwareCache.Refresh(hardwareCtx); err != nil {
logger.Warn().Err(err).Msg("stats hardware cache initial refresh failed; hardware overview fields will remain zero until refresh succeeds")
}
cancelHardwareRefresh()
hardwareCache.Start(shutdownCtx, func(err error) {
logger.Warn().Err(err).Msg("stats hardware cache refresh failed; retaining previous hardware snapshot")
})
var err error
statsRollup, err = statsrollup.New(statsPools.Rollup, rollupCfg, poolsnapshot.NewWithHardware(registry, hardwareCache), logger.With().Str("subsystem", "stats_rollup").Logger())
if err != nil {
fmt.Fprintf(os.Stderr, "stats rollup: %v\n", err)
os.Exit(1)
}
statsRollup.Start(shutdownCtx)
logger.Info().Str("backfill_mode", mode).Int64("partial_history_since_unix", partialUnix).Msg("SPEC-017 stats rollup started (overview/timeseries/leaderboards/rewards_populated/nightly_rebuild)")
}
// SPEC-MALIBU-EMISSION-LEDGER — bootstrap accrual worker (default-off).
var rewardsRunner *rewards.Runner
var rewardsDB *sql.DB
if strings.TrimSpace(cfg.MalibuEmission.WriterDSN) != "" {
var err error
rewardsDB, err = sql.Open("postgres", cfg.MalibuEmission.WriterDSN)
if err != nil {
fmt.Fprintf(os.Stderr, "malibu_emission: open writer pool: %v\n", err)
os.Exit(1)
}
rewardsDB.SetMaxOpenConns(4)
rewardsDB.SetMaxIdleConns(2)
rewardsDB.SetConnMaxLifetime(5 * time.Minute)
defer rewardsDB.Close()
}
if cfg.MalibuEmission.Enabled {
if rewardsDB == nil {
fmt.Fprintf(os.Stderr, "malibu_emission: writer_dsn is required when enabled\n")
os.Exit(1)
}
sqlitePath := strings.TrimSpace(cfg.MalibuEmission.SQLitePayoutDBPath)
if sqlitePath == "" {
sqlitePath = cfg.Storage.DBPath
}
rewardsCfg := rewards.Config{
Enabled: true,
WriterDSN: cfg.MalibuEmission.WriterDSN,
TickInterval: time.Duration(cfg.MalibuEmission.TickIntervalSeconds) * time.Second,
ProviderDailyCapMALIBU: cfg.MalibuEmission.ProviderDailyCapMALIBU,
WalletDailyCapMALIBU: cfg.MalibuEmission.WalletDailyCapMALIBU,
SQLitePayoutDBPath: sqlitePath,
WalletMirrorInterval: time.Duration(cfg.MalibuEmission.WalletMirrorIntervalSeconds) * time.Second,
UnlockEvalInterval: time.Duration(cfg.MalibuEmission.UnlockEvalIntervalSeconds) * time.Second,
MaxSerializableRetries: cfg.MalibuEmission.MaxSerializableRetries,
BaseUSDCBalanceRPCURLs: cfg.MalibuEmission.BaseUSDCBalanceRPCURLs,
}
var err error
rewardsRunner, err = rewards.New(rewardsDB, rewardsCfg, logger.With().Str("subsystem", "malibu_emission").Logger(), rewards.RunnerDeps{})
if err != nil {
fmt.Fprintf(os.Stderr, "malibu_emission: %v\n", err)
os.Exit(1)
}
rewardsRunner.Start(shutdownCtx)
logger.Info().Msg("SPEC-MALIBU-EMISSION-LEDGER accrual runner started")
} else {
logger.Info().Msg("malibu_emission DISABLED via config (default)")
}
// Round-3 ARCH r3 LOW 2 fix: defers run LIFO, so a non-signal
// return path would call `Wait()` BEFORE the
// `stopBackground()` registered earlier — blocking forever on
// still-running rollup goroutines. Combining cancellation +
// drain in one defer registered AFTER the rollup is
// constructed guarantees cancellation always precedes Wait.
defer func() {
stopBackground()
if statsRollup != nil {
statsRollup.Wait()
}
}()
wsOpts := []providerws.Option{}
var grandfatherBefore *time.Time
if raw := strings.TrimSpace(cfg.Referrals.GrandfatherBefore); raw != "" && cfg.Referrals.RequireForRegistration {
parsed, err := time.Parse(time.RFC3339, raw)
if err != nil {
logger.Fatal().Err(err).Msg("parse referral grandfather cutoff")
}
grandfatherBefore = &parsed
}
referralPolicy := auth.ReferralPolicy{
RequireForRegistration: cfg.Referrals.RequireForRegistration,
EnableSocialBonus: cfg.Referrals.EnableSocialInviteBonus,
Campaign: cfg.Referrals.Campaign,
PolicyVersion: cfg.Referrals.PolicyVersion,
GrandfatherBefore: grandfatherBefore,
CurrentKeyID: cfg.Referrals.CurrentKeyID,
HMACKeys: cfg.Referrals.HMACKeys,
ProviderBaseUses: cfg.Referrals.ProviderBaseUses,
SocialBonusUses: cfg.Referrals.SocialBonusUses,
SocialBonusMaxGrants: cfg.Referrals.SocialBonusMaxGrants,
ChallengeTTL: time.Duration(cfg.Referrals.ChallengeTTLS) * time.Second,
SocialVerificationDwell: time.Duration(cfg.Referrals.SocialVerificationDwellS) * time.Second,
}
wsOpts = append(wsOpts, providerws.WithVersion(version))
wsOpts = append(wsOpts, providerws.WithReferralPolicy(referralPolicy))
wsOpts = append(wsOpts, providerws.WithAdmissionStore(admissionStore))
wsOpts = append(wsOpts, providerws.WithConnectionEventStore(connectionEventStore))
wsOpts = append(wsOpts, providerws.WithConnectionEventMetrics(metricsHandle))
if canaryStore != nil {
wsOpts = append(wsOpts, providerws.WithCanarySanctionStore(canaryStore))
}
// SPEC-003 v0.8 FR-C9.1 — the token validator is always wired now,
// even when require_provider_tokens=false, because the same store
// is the issuance backend for self-serve provisional tokens. Pre-
// v0.8 the conditional made `s.tokens != nil` mean "enforce
// strictly"; v0.8 separates issuance from enforcement so the store
// is always available for FR-C9.1 mint-on-first-admit even during
// the settling window before the operator flips the flag.
wsOpts = append(wsOpts, providerws.WithTokenValidator(tokenStore))
// SPEC-003 v0.8 FR-C9.1/FR-C9.4 — separate TokenIssuer wiring for
// minting + TOFU. Same concrete store today; the split is at the
// interface layer (codex architect review on PR #44, interface
// segregation MINOR).
wsOpts = append(wsOpts, providerws.WithTokenIssuer(tokenStore))
wsOpts = append(wsOpts, providerws.WithBootstrapTokenStore(tokenStore))
wsOpts = append(wsOpts, providerws.WithGitHubAuthStore(tokenStore))
// Issue #585: request, dual-control approval, one-shot consumption,
// admission-key CAS, and recovery audit share the token store's SQLite
// transaction boundary. Generic Postgres signature exemptions are never
// recovery authority.
wsOpts = append(wsOpts, providerws.WithAdmissionIdentityRecoveryAdminStore(tokenStore))
// Issue #764 tripwire. Deliberately OUTSIDE the statsPools branch: the
// capacity ceiling is always active, so its counter must always be wired —
// a coordinator without a stats database must not silently lose the signal.
wsOpts = append(wsOpts, providerws.WithCapacityOverClaimMetrics(metricsHandle))
if statsPools != nil {
wsOpts = append(wsOpts, providerws.WithIdlePrewarmRecorder(statsprewarm.NewRecorder(statsPools.Rollup)))
wsOpts = append(wsOpts, providerws.WithIdlePrewarmMetrics(metricsHandle))
wsOpts = append(wsOpts, providerws.WithModelHashMismatchMetrics(metricsHandle))
wsOpts = append(wsOpts, providerws.WithCredentialBootstrapMetrics(metricsHandle))
}
if autotuneCatalog != nil {
bridgeDeadline, err := cfg.AutotuneFeeds.ProviderAdmissionBridgeDeadlineTime()
if err != nil {
logger.Fatal().Err(err).Msg("parse provider catalog admission bridge deadline")
}
wsOpts = append(wsOpts,
providerws.WithAutotuneCatalog(autotuneCatalog, autotuneCompatibleCatalogs...),
providerws.WithAutotuneCatalogEnforcement(cfg.AutotuneFeeds.EnforceProviderAdmission, bridgeDeadline),
)
catalogLog := logger.Info().
Str("autotune_catalog_version", autotuneCatalog.Version).
Int("autotune_compatible_previous_releases", len(autotuneCompatibleCatalogs)).
Str("autotune_catalog_signer_key_id", autotuneCatalog.SignerKeyID).
Bool("autotune_provider_admission_enforced", cfg.AutotuneFeeds.EnforceProviderAdmission)
if !cfg.AutotuneFeeds.EnforceProviderAdmission {
catalogLog = catalogLog.
Time("autotune_provider_admission_bridge_deadline", bridgeDeadline).
Dur("autotune_provider_admission_bridge_remaining", time.Until(bridgeDeadline))
}
catalogLog.Msg("provider catalog compatibility enabled")
}
var onboardingStore *onboarding.PGStore
if shouldOpenOnboardingStore(cfg.Onboarding) {
if cfg.Onboarding.AppTrackRegisterEnabled {
onboardingStore, err = onboarding.OpenPGStoreWithAuthPolicyDSNs(
cfg.Onboarding.PostgresDSN,
cfg.Onboarding.AuthPolicyRequestDSN,
cfg.Onboarding.AuthPolicyApproveDSN,
cfg.Onboarding.AuthPolicyCutoverDSN,
cfg.Onboarding.HardwareTrustRequestDSN,
cfg.Onboarding.HardwareTrustApproveDSN,
)
} else {
// Keep the primary authority available to reconcile referral mints
// created before an operator disabled the public registration route.
onboardingStore, err = onboarding.OpenPGStore(cfg.Onboarding.PostgresDSN)
}
if err != nil {
logger.Fatal().Err(err).Msg("open onboarding postgres store")
}
defer onboardingStore.Close()
if err := onboardingStore.Smoke(context.Background()); err != nil {
logger.Fatal().Err(err).Msg("onboarding postgres smoke failed")
}
if cfg.Onboarding.AppTrackRegisterEnabled {
wsOpts = append(wsOpts, providerws.WithIdentitySignatureStore(onboardingStore))
wsOpts = append(wsOpts, providerws.WithProviderAuthPolicyAdminStore(onboardingStore))
wsOpts = append(wsOpts, providerws.WithHardwareTrustAdminStore(onboardingStore))
}
}
var autotuneEvidenceStore autotune.EvidenceStore
if autotuneCatalog != nil && onboardingStore != nil && onboardingStore.DB() != nil {
autotuneEvidenceStore = autotune.NewPGEvidenceStore(onboardingStore.DB())
wsOpts = append(wsOpts, providerws.WithAutotuneEvidenceStore(autotuneEvidenceStore))
}
if autotuneEvidenceStore != nil && cfg.ProofOfWeights.AutotuneEvidenceTTLDays > 0 {
logger.Info().
Int("autotune_evidence_ttl_days", cfg.ProofOfWeights.AutotuneEvidenceTTLDays).
Str("autotune_catalog_version", autotuneCatalog.Version).
Msg("proof-of-weights admission cap observation enabled")
} else if autotuneEvidenceStore != nil {
logger.Info().
Int("autotune_evidence_ttl_days", cfg.ProofOfWeights.AutotuneEvidenceTTLDays).
Msg("proof-of-weights admission cap observation disabled because evidence TTL is not positive")
}
if cfg.ProofOfWeights.RequireAutotuneHelloGate {
if autotuneCatalog == nil {
logger.Fatal().Msg("proof_of_weights.require_autotune_hello_gate requires autotune candidate catalog feeds")
}
if onboardingStore == nil || onboardingStore.DB() == nil {
logger.Fatal().Msg("proof_of_weights.require_autotune_hello_gate requires onboarding postgres store")
}
if autotuneEvidenceStore == nil {
autotuneEvidenceStore = autotune.NewPGEvidenceStore(onboardingStore.DB())
}
wsOpts = append(wsOpts, providerws.WithAutotuneHelloGate(autotuneCatalog, autotuneEvidenceStore))
// Issue #582 FIX A/B: active-session trust enforcement (bounded
// revalidation sweep + advisory-locked registration re-check) rides the
// same provider_onboarding handle and is wired alongside the admission
// trust join so it is active exactly when the hello gate is.
wsOpts = append(wsOpts, providerws.WithProviderTrustChecker(onboardingStore))
logger.Info().
Int("autotune_evidence_ttl_days", cfg.ProofOfWeights.AutotuneEvidenceTTLDays).
Str("autotune_catalog_version", autotuneCatalog.Version).
Msg("proof-of-weights autotune hello gate enabled")
}
if cfg.ProofOfWeights.TelemetryDrift.Enabled {
if autotuneCatalog == nil {
logger.Fatal().Msg("proof_of_weights.telemetry_drift.enabled requires autotune candidate catalog feeds")
}
if onboardingStore == nil || onboardingStore.DB() == nil {
logger.Fatal().Msg("proof_of_weights.telemetry_drift.enabled requires onboarding postgres store")
}
driftCfg, err := pow.TelemetryDriftConfigFrom(
true,
cfg.ProofOfWeights.TelemetryDrift.TPSRatioThreshold,
cfg.ProofOfWeights.TelemetryDrift.TPSMinAbsolute,
cfg.ProofOfWeights.TelemetryDrift.TPSMinRequestsWindow,
cfg.ProofOfWeights.TelemetryDrift.HashAlertOnStatus,
cfg.ProofOfWeights.TelemetryDrift.HashAlertOnArtifactDrift,
cfg.ProofOfWeights.TelemetryDrift.OPoIPassRateWindow,
cfg.ProofOfWeights.TelemetryDrift.OPoIPassRateThreshold,
cfg.ProofOfWeights.TelemetryDrift.AlertCooldownSeconds,
cfg.ProofOfWeights.TelemetryDrift.QuarantineMissingBenchmark,
)
if err != nil {
logger.Fatal().Err(err).Msg("proof_of_weights.telemetry_drift config invalid")
}
if autotuneEvidenceStore == nil {
autotuneEvidenceStore = autotune.NewPGEvidenceStore(onboardingStore.DB())
}
ttl := time.Duration(cfg.ProofOfWeights.AutotuneEvidenceTTLDays) * 24 * time.Hour
wsOpts = append(wsOpts, providerws.WithTelemetryDriftEvaluator(pow.NewEvaluator(driftCfg, autotuneCatalog, autotuneEvidenceStore, ttl)))
logger.Info().
Float64("tps_ratio_threshold", driftCfg.TPSRatioThreshold).
Int("tps_min_requests_window", driftCfg.TPSMinRequestsWindow).
Int("opoi_pass_rate_window", driftCfg.OPoIPassRateWindow).
Bool("quarantine_missing_benchmark", driftCfg.QuarantineMissingBenchmark).
Msg("proof-of-weights telemetry drift alerts enabled")
}
if cfg.Auth.RequireProviderTokens {
logger.Info().
Bool("allow_tokenless_provisional_bootstrap", cfg.Auth.AllowTokenlessProvisionalBootstrap).
Msg("provider WS token validation REQUIRED (auth.require_provider_tokens=true)")
} else {
logger.Info().Msg("provider WS token validation NOT required (auth.require_provider_tokens=false); tokenless provisional admissions will self-mint per SPEC-003 FR-C9")
}
if cfg.Explorer.Enabled {
wsOpts = append(wsOpts, providerws.WithExplorerHandler(explorer.NewHandler(cfg, reqLogStore.DB(), registry, startedAt)))
logger.Info().Str("path", cfg.Explorer.BindPath).Msg("operator explorer enabled")
}
// M2-2 / ARCH-2: hand the pool emitter a non-blocking channel send
// instead of the synchronous SQLite write. The pool already releases
// Registry.mu before invoking the emitter (see ApplyHeartbeat), and
// a dedicated drain goroutine performs the EmitSwap write so a
// SQLite busy_timeout stall (~5s worst case) cannot back-pressure
// the heartbeat handler. R-7.10.8 best-effort semantics permit
// dropping on overflow — logged at WARN.
//
// Shutdown ordering (code-auditor flagged a race in the close-based
// design): swapCh is NEVER closed. Both sender (swapEmitter) and
// receiver (drain goroutine) coordinate via shutdownCtx.Done() so
// late heartbeats arriving after shutdown can never panic on
// send-on-closed-channel. Late events accumulate in the cap-64
// buffer until full, then drop with a WARN.
swapCh := make(chan pool.SwapEvent, 64)
swapDrained := make(chan struct{})
receiptRotationCh := make(chan pool.ReceiptRotationEvent, 64)
receiptRotationDrained := make(chan struct{})
logSwapAuditFailure := func(event pool.SwapEvent, err error) {
loadingWindowMS := int64(0)
if !event.LoadingStartedAt.IsZero() {
loadingWindowMS = event.CompletedAt.Sub(event.LoadingStartedAt).Milliseconds()
}
logger.Warn().
Err(err).
Str("provider_id", event.ProviderID).
Str("assigned_id", event.AssignedID).
Str("from_model_id", event.FromModelID).
Str("to_model_id", event.ToModelID).
Str("to_model_hash", event.ToModelHash).
Int64("loading_window_ms", loadingWindowMS).
Str("hash_verification_result", string(event.HashVerificationResult)).
Msg("operator_model_swap audit write failed")
}
go func() {
defer close(swapDrained)
for {
select {
case <-shutdownCtx.Done():
// Drain any remaining buffered events (best-effort) and
// return. New sends after this point hit swapEmitter's
// own shutdownCtx guard and become silent drops.
for {
select {
case event := <-swapCh:
if err := auditStore.EmitSwap(context.Background(), event); err != nil {
logSwapAuditFailure(event, err)
}
default:
return
}
}
case event := <-swapCh:
// Use a fresh background context here so a slow audit
// write near shutdown isn't truncated by ctx cancellation
// — the event was already accepted into the queue.
if err := auditStore.EmitSwap(context.Background(), event); err != nil {
logSwapAuditFailure(event, err)
}
}
}
}()
logReceiptRotationAuditFailure := func(event pool.ReceiptRotationEvent, err error) {
logger.Warn().
Err(err).
Str("provider_id", event.ProviderID).
Time("rotated_at", event.RotatedAt).
Msg("receipt_rotation_detected audit write failed")
}
go func() {
defer close(receiptRotationDrained)
for {
select {
case <-shutdownCtx.Done():
for {
select {
case event := <-receiptRotationCh:
if err := auditStore.EmitReceiptRotation(context.Background(), event); err != nil {
logReceiptRotationAuditFailure(event, err)
}
default:
return
}
}
case event := <-receiptRotationCh:
if err := auditStore.EmitReceiptRotation(context.Background(), event); err != nil {
logReceiptRotationAuditFailure(event, err)
}
}
}
}()
logSwapDropped := func(event pool.SwapEvent, reason string) {
// Symmetry with logSwapAuditFailure: a dropped event must be
// reconstructable from the log line. Include the same identity
// fields plus loading_window_ms so an auditor can confirm what
// was lost.
loadingWindowMS := int64(0)
if !event.LoadingStartedAt.IsZero() {
loadingWindowMS = event.CompletedAt.Sub(event.LoadingStartedAt).Milliseconds()
}
logger.Warn().
Str("reason", reason).
Str("provider_id", event.ProviderID).
Str("assigned_id", event.AssignedID).
Str("from_model_id", event.FromModelID).
Str("from_model_hash", event.FromModelHash).
Str("to_model_id", event.ToModelID).
Str("to_model_hash", event.ToModelHash).
Int64("loading_window_ms", loadingWindowMS).
Str("hash_verification_result", string(event.HashVerificationResult)).
Msg("operator_model_swap event dropped (best-effort per R-7.10.8)")
}
swapEmitter := func(event pool.SwapEvent) {
// shutdownCtx.Done() check ordering: select picks randomly when
// multiple cases are ready, so we can't both rely on it AND let
// the buffered send race it. The double-check is cheap and the
// inner select handles steady-state.
if shutdownCtx.Err() != nil {
logSwapDropped(event, "shutdown")
return
}
select {
case swapCh <- event:
default:
logSwapDropped(event, "queue_full_cap_64")
}
}
receiptRotationEmitter := func(event pool.ReceiptRotationEvent) {
if shutdownCtx.Err() != nil {
logger.Warn().Str("provider_id", event.ProviderID).Str("reason", "shutdown").Msg("receipt_rotation_detected event dropped")
return
}
select {
case receiptRotationCh <- event:
default:
logger.Warn().Str("provider_id", event.ProviderID).Str("reason", "queue_full_cap_64").Msg("receipt_rotation_detected event dropped")
}
}
wsOpts = append(wsOpts, providerws.WithRegistryOptions(
pool.WithSwapEmitter(swapEmitter),
pool.WithReceiptRotationEmitter(receiptRotationEmitter),
))
wsServer := providerws.NewServer(cfg, registry, logger, wsOpts...)
if rewardsRunner != nil {
rewardsRunner.SetConnectivity(rewards.NewPoolHeartbeatBridge(wsServer.PoolSnapshot))
}
buyerServer := buyer.NewServer(
registry,
logger,
startedAt,
buyer.WithVersion(version),
buyer.WithPreflightConfig(cfg.Routing.PreflightThresholdTokens, time.Duration(cfg.Routing.PreflightTimeoutS)*time.Second),
buyer.WithRecoveryConfig(time.Duration(cfg.Pool.DegradedBackoffS)*time.Second, cfg.Pool.DegradedMaxRetries, cfg.Pool.DegradedProbeAfter502),
buyer.WithBreakerConfig(cfg.Pool.BreakerFailureThreshold, time.Duration(cfg.Pool.BreakerWindowS)*time.Second),
buyer.WithFailoverConfig(cfg.Routing.FailoverEnabled, time.Duration(cfg.Routing.FailoverTimeoutS)*time.Second),
buyer.WithRoutingConfig(cfg.Routing),
buyer.WithTier2Config(cfg.Tier2),
buyer.WithModelVersionFloors(cfg.CoordinatorAdvertisedVersion.PerModelRequiredBinaryVersion),
buyer.WithLimitsConfig(cfg.Limits),
buyer.WithTrustedProxies(mustParseTrustedProxies(cfg, logger)),
buyer.WithOperatorKey(cfg.Auth.OperatorKey),
buyer.WithGatewayServiceToken(cfg.Auth.GatewayServiceToken),
buyer.WithRequireGatewayContext(cfg.Coordinator.RequireGatewayContext),
buyer.WithRelay(wsServer.DispatchInference, time.Duration(cfg.Routing.RequestTimeoutS)*time.Second),
buyer.WithSettlementRelay(wsServer.DispatchInferenceWithSettlement),
buyer.WithAdmission(wsServer.Admission(), cfg.Admission.ProvisionalTierWeight),
buyer.WithRequestLog(reqLogStore),
buyer.WithBilling(billingStore, cfg.Rewards),
buyer.WithBillingSnapshotID(snapshotID),
buyer.WithRateCardUSDPerMillionCredits(cfg.Stats.Rollup.UsdPerMillionCredits),
buyer.WithAutotuneFeeds(autotuneFeeds),
buyer.WithStreamingMetricsMaxSamples(cfg.Stats.StreamingMetrics.MaxSamples),
buyer.WithPreflight(func(provider pool.Provider, requestID string, estimatedTokens int, timeout time.Duration) (buyer.PreflightResult, bool, error) {
ack, ok, err := wsServer.Preflight(provider, requestID, estimatedTokens, timeout)
return buyer.PreflightResult{Accepted: ack.Accepted, Reason: ack.Reason}, ok, err
}),
)
providerAddr := listenAddress(cfg.Listen.BindAddress, cfg.Listen.ProviderPort)
buyerAddr := listenAddress(cfg.Listen.BindAddress, cfg.Listen.BuyerPort)
providerMux := http.NewServeMux()
providerMux.Handle("/", wsServer.Handler())
providerMux.Handle("/internal/", buyerServer.InternalHandler())
// SPEC-005 v0.4 (issue #169) — `billing.quarantine_resolution_force_void_enabled`
// gates the §11.6 force-void endpoint at the route layer. Default
// false: endpoint returns HTTP 404 until the operator explicitly
// flips the flag via the existing config-reload primitive.
// The flag is held as an atomic on billingStore; SIGHUP reload
// calls billingStore.SetForceVoidEnabled which emits the
// `billing_config_flag_changed` audit event on real flips.
var idlePrewarmReader *statsprewarm.Reader
if statsPools != nil {
idlePrewarmReader = statsprewarm.NewReader(statsPools.Reader)
}
// SPEC-005 vX.Y+1 §9.5b — the `/admin/ledger/payout-ready`
// reorg-compensation endpoint caps provider_credits at the same
// immutable §5.2 per-payout ceiling the runner enforces
// (payout.security.per_payout_cap_usdc_base_units). payout.security.*
// is not live-reloaded, so the cap is threaded in as a scalar here.
billingHandler := billingStore.HandlersWithQuarantineGatesIdlePrewarmAndPayoutCap(
cfg.Auth.OperatorKey,
tokenStore,
cfg.Auth.RequireProviderTokens,
cfg.Endpoints.ProviderEarnings.RateLimitPerMinute,
cfg.Billing.QuarantineResolutionForceVoidEnabled,
cfg.Billing.QuarantineResolutionForceCreditEnabled,
idlePrewarmReader,
cfg.Payout.Security.PerPayoutCapUSDCBaseUnits,
)
// §11.5 launch-gate item 10 — operator-visible startup state.
logger.Info().
Bool("billing.quarantine_resolution_force_void_enabled", cfg.Billing.QuarantineResolutionForceVoidEnabled).
Bool("billing.quarantine_resolution_force_credit_enabled", cfg.Billing.QuarantineResolutionForceCreditEnabled).
Int("billing.force_credit_settlement_hold_seconds", cfg.Billing.ForceCreditSettlementHoldSeconds).
Str("event", "spec005_v0_4_route_layer_flag_init").
Msg("quarantine force-void route-layer flag initialized")
providerMux.Handle("/admin/ledger/", billingHandler)
if rewardsDB != nil {
providerMux.Handle("/admin/trust-promotion/", rewards.TrustPromotionMux(rewards.TrustAdminDeps{
DB: rewardsDB,
OperatorKeys: cfg.Auth.OperatorKeys,
}))
}
// SPEC-016 §4.1 — wire the payout package. Migrations + asserts
// run unconditionally so a future flip of payout.enabled does
// not require a schema migration window. §3.3 challenge/register
// mount whenever hot_wallet_address is set (registration-only
// when payout.enabled=false; #954 / SPEC v0.1.26). Admin payout
// routes and the runner require payout.enabled=true.
// Adapt billingStore to the payout.PayoutClaimer interface — the
// concrete ClaimPayoutReady method satisfies it without modification.
payoutAddresses, payoutMuxHandler, payoutS2, err := setupPayout(context.Background(), reqLogStore.DB(), cfg, tokenStore, billingStore, billingHandler, logger)
if err != nil {
fmt.Fprintf(os.Stderr, "payout: %v\n", err)
os.Exit(1)
}
_ = payoutAddresses // satisfies billing.PayoutAddressReader (used by Step 4 reconcile)
if cfg.Auth.RequireProviderTokens {
if payoutMuxHandler != nil {
// Mount at BOTH /providers/ (§3.3; §7.3 when fully
// enabled) and /admin/payout/ (§6.4.1 pause/resume in
// registration-only; full admin suite when payoutS2 is
// wired). Per architect r1 [arch:3.2]: a single
// /providers/ mount makes /admin/payout/* unreachable.
providerMux.Handle("/providers/", payoutMuxHandler)
providerMux.Handle("/admin/payout/", payoutMuxHandler)
} else {
providerMux.Handle("/providers/", billingHandler)
}
}
// Start the runner lifecycle if Step 2 is wired.
if payoutS2 != nil {
payoutS2.runner.Start(shutdownCtx)
// Codex Step 3 r1 [arch:3.1] MAJOR closure: the poller
// owns its own lifecycle via Start/Stop; shutdownCtx is
// threaded into every poll cycle so a graceful shutdown
// interrupts mid-RPC instead of using context.Background().
payoutS2.reorg.Start(shutdownCtx)
// Step 3 §4.8a + §4.8c reaper.
if payoutS2.reaper != nil {
payoutS2.reaper.Start(shutdownCtx)
}
// Step 4 §7.4 chain-balance worker.
if payoutS2.chainWorker != nil {
payoutS2.chainWorker.Start(shutdownCtx)
}
// #165 R1 architect HIGH closure: drive the chronic-outage
// Evaluate on a window-internal cadence independent of the
// runner ticker. RunInterval can be up to 24h per §6.5 but
// the tracker window defaults to 10min, so per-cycle Evaluate
// would prune samples before observing them. Run() ticks at
// min(window/2, 1min).
if payoutS2.chronic != nil {
go payoutS2.chronic.Run(shutdownCtx)
}
// Step 4 §6.5 SIGHUP-only payout.tuning.* reload. Reading
// the YAML on SIGHUP MUST NOT touch payout.security.* (the
// loader is read-only on the security namespace); the
// TuningProvider.Reload helper applies bound re-enforcement
// AND emits payout_config_reloaded / payout_config_reload_rejected
// per SPEC §6.5.
go startPayoutSIGHUPListener(shutdownCtx, *configPath, *configOverlay, payoutS2.tuning, payoutS2.rpcs, logger)
}
// SPEC-017 v0.1.8 Step 3 — /v1/stats/* mux subtree. Mounts
// only when stats.enabled = true. The handler stack uses
// the stats_reader pool exclusively (no admin DSN, no
// rollup pool). Per BUILD §2 Step 3 the same binary serves
// both coordinator.streamvc.live/v1/stats/* and
// stats.streamvc.live/v1/stats/*; nginx vhost config
// (Step 4.B) routes both to this provider port.
if statsPools != nil {
// SPEC-017 v0.1.8 Step 4.C — Prometheus metrics. The
// coordinator owns its own registry (not the global
// DefaultRegisterer) so concurrent test runs don't
// double-register. SPEC-026 adds /admin/metrics below;
// /metrics remains as a loopback-compatible alias only.
statsHandler := stats.NewMuxWithMetricsAndRateLimit(
statsstore.New(statsPools.Reader),
stats.CORSConfig{
AccessControlMaxAgeSeconds: cfg.Stats.CORS.AccessControlMaxAgeSeconds,
PartnerOriginAllowlist: cfg.Stats.CORS.PartnerOriginAllowlist,
},
cfg.Stats.Rollup.BackfillMode,
cfg.Stats.Rollup.PartialHistorySince,
cfg.Stats.TrustedProxies,
logger.With().Str("subsystem", "stats_handlers").Logger(),
metricsHandle,
stats.RateLimitConfig{
MaxBuckets: cfg.Stats.RateLimit.MaxBuckets,
IdleTTL: time.Duration(cfg.Stats.RateLimit.IdleTTLSeconds) * time.Second,
PreflightRPM: cfg.Stats.RateLimit.PreflightRPM,
},
).Handler()
providerMux.Handle("/v1/stats/", statsHandler)
providerMux.Handle("/metrics", promhttp.HandlerFor(metricsRegistry, promhttp.HandlerOpts{}))
logger.Info().Msg("SPEC-017 stats handlers + /metrics mounted on provider port")
// Wire rollup lag observation periodically — gauge value
// = now - stats_components_health.generated_at per
// component. Background goroutine; cancelled with
// shutdownCtx.
if statsRollup != nil {
statsRollup.WithMetrics(metricsHandle)
go observeRollupLag(shutdownCtx, statsPools.Reader, metricsHandle, logger)
}
}
providerMux.Handle("/admin/metrics", operatorMetricsHandler(cfg.Auth.OperatorKey, metricsRegistry))
var register http.HandlerFunc