diff --git a/AGENTS.md b/AGENTS.md index d00135bbfe..d66c73c418 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,7 +36,7 @@ coordinator/ Go control plane (packages live at top level, not internal ├── saferun/ panic-safe goroutine runners ├── stateexport/ consistent encrypted archive of MicroMDM (+ legacy step-ca) state (migration) ├── store/ in-memory or Postgres persistence -├── telemetry/ telemetry event emitter (process logs + Datadog forwarding) +├── telemetry/ event emitter, metrics/, routequeue/, profilequeue/, outcomequeue/ ├── datadog/ Datadog APM / DogStatsD / Logs API client ├── deploy/ container entrypoint (start.sh) └── internal/e2e/ X25519 request-encryption helpers (+ cross-compat/tamper tests) diff --git a/coordinator/api/persistence_sink_wiring_test.go b/coordinator/api/persistence_sink_wiring_test.go new file mode 100644 index 0000000000..9ac7e570a9 --- /dev/null +++ b/coordinator/api/persistence_sink_wiring_test.go @@ -0,0 +1,67 @@ +package api + +import ( + "context" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// Queue ownership must not capture an obsolete store at construction. The +// existing Server adapters resolve the store when a batch is ready to write. +func TestPersistenceSinksUseCurrentStore(t *testing.T) { + for _, kind := range []string{"profile", "outcome"} { + t.Run(kind, func(t *testing.T) { + initial := store.NewMemory(store.Config{}) + current := store.NewMemory(store.Config{}) + s := &Server{store: initial, logger: quietLogger()} + s.profiler = &profiler{enabled: true, sampleRate: 1} + var submit func() + var count func(*store.MemoryStore) int + switch kind { + case "profile": + s.profiler.sink = newProfileSink(s, 4) + t.Cleanup(s.profiler.close) + rp := registry.NewRequestProfile(time.Now(), "current-store", nil, 0) + ap := rp.NewAttempt("attempt", 0, "") + ap.SetOutcome("error", "provider_error", "", "error", "") + submit = func() { + if !s.profiler.sink.Submit(rp, ap) { + t.Fatal("empty profile queue rejected the record") + } + } + count = func(st *store.MemoryStore) int { return len(st.RequestProfilesSince(time.Time{})) } + case "outcome": + s.requestOutcomes = newRequestOutcomeSink(s, 4) + t.Cleanup(s.requestOutcomes.Close) + submit = func() { + now := time.Now() + s.requestOutcomes.Submit(store.RequestOutcomeRecord{CoordRequestID: "current-store", SchemaVersion: store.RequestOutcomeSchemaVersion, Revision: 1, ReceivedAt: now, UpdatedAt: now}) + } + count = func(st *store.MemoryStore) int { + rows, err := st.RequestOutcomes(context.Background(), time.Time{}, time.Now().Add(time.Second), 10) + if err != nil { + t.Fatal(err) + } + return len(rows) + } + } + // No job exists yet. The following channel send orders this lookup + // change before the worker's first build or write. + s.store = current + submit() + deadline := time.Now().Add(3 * time.Second) + for count(current) == 0 && time.Now().Before(deadline) { + time.Sleep(time.Millisecond) + } + if got := count(current); got != 1 { + t.Fatalf("current store has %d rows, want 1", got) + } + if got := count(initial); got != 0 { + t.Fatalf("obsolete constructor store has %d rows, want 0", got) + } + }) + } +} diff --git a/coordinator/api/profiler.go b/coordinator/api/profiler.go index f1ab1d380e..5a7776efb3 100644 --- a/coordinator/api/profiler.go +++ b/coordinator/api/profiler.go @@ -120,7 +120,7 @@ func (p *profiler) close() { if p == nil || p.sink == nil { return } - p.sink.close() + p.sink.Close() } // profilerEnabled reports whether profile records should be created. diff --git a/coordinator/api/profiler_fleet.go b/coordinator/api/profiler_fleet.go index 657acbefe1..de57a6ba2d 100644 --- a/coordinator/api/profiler_fleet.go +++ b/coordinator/api/profiler_fleet.go @@ -57,8 +57,8 @@ func (s *Server) sampleFleetOnce(now time.Time) { coord := s.registry.CoordinatorSample(now) coord.Goroutines = runtime.NumGoroutine() if s.profiler != nil && s.profiler.sink != nil { - coord.ProfileSinkDepth = s.profiler.sink.depth() - coord.ProfileSinkDroppedTotal = s.profiler.sink.droppedTotal() + coord.ProfileSinkDepth = s.profiler.sink.Depth() + coord.ProfileSinkDroppedTotal = s.profiler.sink.DroppedTotal() } if s.routeTelemetry != nil { coord.RouteSinkDroppedTotal = s.routeTelemetry.DroppedTotal() @@ -75,7 +75,7 @@ func (s *Server) sampleFleetOnce(now time.Time) { } s.ddCount("profiler.fleet_snapshot", int64(len(rows)), []string{"status:written"}) if s.profiler != nil && s.profiler.sink != nil { - s.ddGauge("telemetry.sink_depth", float64(s.profiler.sink.depth()), []string{"sink:profile"}) + s.ddGauge("telemetry.sink_depth", float64(s.profiler.sink.Depth()), []string{"sink:profile"}) } if s.routeTelemetry != nil { s.ddGauge("telemetry.sink_depth", float64(s.routeTelemetry.Depth()), []string{"sink:route"}) diff --git a/coordinator/api/profiler_record.go b/coordinator/api/profiler_record.go index d32d0c757b..666e12b4c9 100644 --- a/coordinator/api/profiler_record.go +++ b/coordinator/api/profiler_record.go @@ -343,5 +343,5 @@ func (s *Server) finalizeAttemptProfile(rp *registry.RequestProfile, ap *registr // Flattening and sampling happen on the sink worker (profileSink.build), so // the finalizing goroutine — possibly the provider WS read loop — only // performs one non-blocking channel send here. - s.profiler.sink.submit(rp, ap) + s.profiler.sink.Submit(rp, ap) } diff --git a/coordinator/api/profiler_sink.go b/coordinator/api/profiler_sink.go index 8257638bf2..8a2169b989 100644 --- a/coordinator/api/profiler_sink.go +++ b/coordinator/api/profiler_sink.go @@ -1,165 +1,33 @@ package api -// Batched, bounded, non-blocking sink for profile records. -// -// Separate from the routing-telemetry sink on purpose: profile rows are the -// highest-volume telemetry the coordinator writes, and during the incidents the -// profiler exists to explain (429 cascades, retry storms) the route sink is at -// its busiest. A dedicated buffer means profile pressure can never evict a -// route row, and batching (up to profileBatchMax records or profileBatchWait, -// whichever first) turns per-row store round-trips into one multi-row insert. - import ( - "sync" - "sync/atomic" - "time" - "github.com/eigeninference/d-inference/coordinator/registry" - "github.com/eigeninference/d-inference/coordinator/saferun" "github.com/eigeninference/d-inference/coordinator/store" + "github.com/eigeninference/d-inference/coordinator/telemetry/profilequeue" ) -const ( - profileBatchMax = 64 - profileBatchWait = 250 * time.Millisecond -) - -// profileJob is one finalized attempt awaiting flattening + persistence. The -// record is built on the sink worker, never on the finalizing goroutine (which -// may be the provider WS read loop). -type profileJob struct { - rp *registry.RequestProfile - ap *registry.AttemptProfile -} - -type profileSink struct { - s *Server - ch chan profileJob - done chan struct{} - dropped atomic.Int64 - written atomic.Int64 - closeOnce sync.Once -} +type profileSink = profilequeue.Sink func newProfileSink(s *Server, capacity int) *profileSink { - if capacity <= 0 { - capacity = defaultTelemetrySinkCapacity - } - p := &profileSink{ - s: s, - ch: make(chan profileJob, capacity), - done: make(chan struct{}), - } - go p.worker() - return p -} - -// submit enqueues a finalized attempt without blocking; drops (and counts) -// when full. -func (p *profileSink) submit(rp *registry.RequestProfile, ap *registry.AttemptProfile) bool { - if p == nil || rp == nil || ap == nil { - return false - } - select { - case p.ch <- profileJob{rp: rp, ap: ap}: - return true - default: - n := p.dropped.Add(1) - if crossesPowerOfTen(n-1, n) && p.s != nil && p.s.logger != nil { - p.s.logger.Warn("profile sink dropping records (buffer full) — inference is unaffected", - "dropped_total", n, "capacity", cap(p.ch)) - } - if p.s != nil { - p.s.ddIncr("telemetry.sink_dropped", []string{"sink:profile"}) - } - return false - } -} - -func (p *profileSink) depth() int { - if p == nil { - return 0 - } - return len(p.ch) -} - -func (p *profileSink) droppedTotal() int64 { - if p == nil { - return 0 - } - return p.dropped.Load() -} - -func (p *profileSink) close() { - if p == nil { - return - } - p.closeOnce.Do(func() { close(p.done) }) -} - -// worker drains the channel into batches and writes each batch with one store -// call inside a panic-safe wrapper. It never spawns per-record goroutines. -func (p *profileSink) worker() { - batch := make([]*store.RequestProfileRecord, 0, profileBatchMax) - for { - select { - case <-p.done: - return - case first := <-p.ch: - batch = batch[:0] - if rec := p.build(first); rec != nil { - batch = append(batch, rec) - } - timer := time.NewTimer(profileBatchWait) - collect: - for len(batch) < profileBatchMax { - select { - case job := <-p.ch: - if rec := p.build(job); rec != nil { - batch = append(batch, rec) - } - case <-timer.C: - break collect - case <-p.done: - timer.Stop() - p.flush(batch) - return - } - } - timer.Stop() - p.flush(batch) - } - } -} - -// build flattens a job into a row and applies the sampling rule. Runs on the -// sink worker; panics are contained by the caller's Recover. -func (p *profileSink) build(job profileJob) *store.RequestProfileRecord { - defer saferun.Recover(p.s.logger, "profileSink.build") - rec := p.s.buildProfileRecord(job.rp, job.ap) + return profilequeue.New(profilequeue.Hooks{ + Logger: s.logger, + Build: s.buildQueuedProfile, + Store: func() profilequeue.Writer { return s.store }, + Incr: s.ddIncr, + Count: s.ddCount, + }, capacity) +} + +// buildQueuedProfile runs on the profile worker. The finalizing goroutine +// only enqueues; flattening, provider-profile decoding and sampling stay here. +func (s *Server) buildQueuedProfile(rp *registry.RequestProfile, ap *registry.AttemptProfile) *store.RequestProfileRecord { + rec := s.buildProfileRecord(rp, ap) if rec == nil { return nil } - if !p.s.profiler.alwaysRecord(rec) && !p.s.profiler.sampled(job.rp.CoordRequestID) { - p.s.ddIncr("profiler.records", []string{"status:sampled_out"}) + if !s.profiler.alwaysRecord(rec) && !s.profiler.sampled(rp.CoordRequestID) { + s.ddIncr("profiler.records", []string{"status:sampled_out"}) return nil } return rec } - -func (p *profileSink) flush(batch []*store.RequestProfileRecord) { - if len(batch) == 0 || p.s == nil || p.s.store == nil { - return - } - logger := p.s.logger - defer saferun.Recover(logger, "profileSink") - if err := p.s.store.RecordRequestProfiles(batch); err != nil { - if logger != nil { - logger.Error("request_profiles batch write failed", "rows", len(batch), "error", err) - } - p.s.ddCount("profiler.records", int64(len(batch)), []string{"status:write_failed"}) - return - } - p.written.Add(int64(len(batch))) - p.s.ddCount("profiler.records", int64(len(batch)), []string{"status:written"}) -} diff --git a/coordinator/api/profiler_test.go b/coordinator/api/profiler_test.go index 572c9e1997..4d4ed1e510 100644 --- a/coordinator/api/profiler_test.go +++ b/coordinator/api/profiler_test.go @@ -202,7 +202,7 @@ func TestProfileSinkBatchesIntoStoreAndAdminEndpointsServeThem(t *testing.T) { ap.ProviderID = "prov" ap.Mark(registry.StampWriteSubmitted) ap.SetOutcome("error", "provider_error", "", "error", "") - if !srv.profiler.sink.submit(rp, ap) { + if !srv.profiler.sink.Submit(rp, ap) { t.Fatal("submit dropped with an empty buffer") } } diff --git a/coordinator/api/request_outcome.go b/coordinator/api/request_outcome.go index 892e85f9f8..cc52a81508 100644 --- a/coordinator/api/request_outcome.go +++ b/coordinator/api/request_outcome.go @@ -67,7 +67,7 @@ func (s *Server) observeRequestOutcome(next http.HandlerFunc) http.HandlerFunc { o := &requestOutcome{sink: s.requestOutcomes, finalized: make(map[string]struct{}), record: store.RequestOutcomeRecord{CoordRequestID: meta.coordID, SchemaVersion: store.RequestOutcomeSchemaVersion, ReceivedAt: meta.start, Endpoint: r.URL.Path, RawStage: "drain", Termination: "in_progress", ResponseProgress: "unknown", ProviderOutcome: "no_terminal", ResponseTerminal: "unknown", Attempts: []store.RequestAttemptOutcome{}}} r = r.WithContext(context.WithValue(r.Context(), requestOutcomeKey{}, o)) ow := &outcomeWriter{ResponseWriter: w, outcome: o} - s.requestOutcomes.received.Add(1) + s.requestOutcomes.MarkReceived() s.ddIncr("request_outcomes.received", []string{"endpoint:" + r.URL.Path}) o.mu.Lock() o.publishLocked() @@ -98,7 +98,7 @@ func (o *requestOutcome) publishLocked() { o.record.UpdatedAt = time.Now() r := o.record r.Attempts = append([]store.RequestAttemptOutcome{}, r.Attempts...) - o.sink.submit(r) + o.sink.Submit(r) } func (o *requestOutcome) attemptFinalized(rp *registry.RequestProfile, ap *registry.AttemptProfile) { diff --git a/coordinator/api/request_outcome_admin.go b/coordinator/api/request_outcome_admin.go index 517d7ff381..a32b8abdab 100644 --- a/coordinator/api/request_outcome_admin.go +++ b/coordinator/api/request_outcome_admin.go @@ -41,7 +41,8 @@ func (s *Server) handleAdminRequestOutcomes(w http.ResponseWriter, r *http.Reque } health := map[string]any{"available": false} if q := s.requestOutcomes; q != nil { - health = map[string]any{"available": true, "received": q.received.Load(), "snapshots_written": q.written.Load(), "snapshots_dropped": q.dropped.Load(), "snapshots_write_failed": q.failed.Load(), "snapshots_queued": len(q.ch)} + stats := q.Stats() + health = map[string]any{"available": true, "received": stats.Received, "snapshots_written": stats.Written, "snapshots_dropped": stats.Dropped, "snapshots_write_failed": stats.Failed, "snapshots_queued": stats.Queued} } writeJSON(w, 200, map[string]any{"schema_version": store.RequestOutcomeSchemaVersion, "data": rows, "count": len(rows), "since": since, "until": until, "possibly_truncated": len(rows) == limit, "coverage": "observed_received_cohort", "persistence": "unsampled_best_effort", "process_counters": health}) } diff --git a/coordinator/api/request_outcome_recovery_test.go b/coordinator/api/request_outcome_recovery_test.go index fd0f0e9ae8..94351dc017 100644 --- a/coordinator/api/request_outcome_recovery_test.go +++ b/coordinator/api/request_outcome_recovery_test.go @@ -95,7 +95,7 @@ func TestRequestOutcomePopulationUsesMatchedEscapedRoute(t *testing.T) { for _, path := range []string{"/v1%2Fmessages", "/v1/messages/missing"} { w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, httptest.NewRequest("POST", path, nil)) - if w.Code != 404 || srv.requestOutcomes.received.Load() != 0 { + if w.Code != 404 || srv.requestOutcomes.ReceivedTotal() != 0 { t.Fatalf("unmatched path counted: %s status=%d", path, w.Code) } } diff --git a/coordinator/api/request_outcome_sink.go b/coordinator/api/request_outcome_sink.go index 46d3886a41..6852aabd74 100644 --- a/coordinator/api/request_outcome_sink.go +++ b/coordinator/api/request_outcome_sink.go @@ -2,122 +2,19 @@ package api import ( "context" - "errors" - "sync" - "sync/atomic" - "time" - "github.com/eigeninference/d-inference/coordinator/store" + "github.com/eigeninference/d-inference/coordinator/telemetry/outcomequeue" ) -// A separate queue keeps heavy profiler and routing-telemetry loss independent -// of the compact unsampled ledger. No store IO or waiting on the request path. -type requestOutcomeSink struct { - s *Server - ch chan store.RequestOutcomeRecord - stop chan struct{} - done chan struct{} - mu sync.RWMutex - closed bool - received atomic.Int64 - dropped atomic.Int64 - written atomic.Int64 - failed atomic.Int64 -} +type requestOutcomeSink = outcomequeue.Sink func newRequestOutcomeSink(s *Server, capacity int) *requestOutcomeSink { - q := &requestOutcomeSink{s: s, ch: make(chan store.RequestOutcomeRecord, capacity), stop: make(chan struct{}), done: make(chan struct{})} - go q.run() - return q -} -func (q *requestOutcomeSink) submit(r store.RequestOutcomeRecord) { - if q == nil { - return - } - q.mu.RLock() - defer q.mu.RUnlock() - if !q.closed { - select { - case q.ch <- r: - return - default: - } - } - q.dropped.Add(1) - q.s.ddIncr("request_outcomes.records", []string{"status:dropped"}) -} -func (q *requestOutcomeSink) close() { - if q == nil { - return - } - q.mu.Lock() - if !q.closed { - q.closed = true - close(q.stop) - } - q.mu.Unlock() - select { - case <-q.done: - case <-time.After(2 * time.Second): - if q.s.logger != nil { - q.s.logger.Warn("request outcomes drain incomplete", "dropped", q.dropped.Load(), "queued", len(q.ch)) - } - } -} -func (q *requestOutcomeSink) run() { - defer close(q.done) - ticker := time.NewTicker(100 * time.Millisecond) - defer ticker.Stop() - batch := make([]store.RequestOutcomeRecord, 0, 128) - flush := func() { - if len(batch) == 0 { - return - } - ctx, cancel := context.WithTimeout(context.Background(), time.Second) - err := func() (err error) { - defer func() { - if recover() != nil { - err = errors.New("request outcome store panic") - } - }() - return q.s.store.RecordRequestOutcomes(ctx, batch) - }() - cancel() - if err != nil { - q.failed.Add(int64(len(batch))) - q.s.ddCount("request_outcomes.records", int64(len(batch)), []string{"status:write_failed"}) - if q.s.logger != nil { - q.s.logger.Warn("request outcomes persistence failed", "records", len(batch)) - } - } else { - q.written.Add(int64(len(batch))) - q.s.ddCount("request_outcomes.records", int64(len(batch)), []string{"status:written"}) - } - clear(batch) - batch = batch[:0] - } - for { - select { - case r := <-q.ch: - batch = append(batch, r) - if len(batch) == cap(batch) { - flush() - } - case <-ticker.C: - flush() - case <-q.stop: - for { - select { - case r := <-q.ch: - batch = append(batch, r) - if len(batch) == cap(batch) { - flush() - } - default: - flush() - return - } - } - } - } + return outcomequeue.New(outcomequeue.Hooks{ + Logger: s.logger, + Write: func(ctx context.Context, records []store.RequestOutcomeRecord) error { + return s.store.RecordRequestOutcomes(ctx, records) + }, + Incr: s.ddIncr, + Count: s.ddCount, + }, capacity) } diff --git a/coordinator/api/request_outcome_sink_test.go b/coordinator/api/request_outcome_sink_test.go index 1877d7ea73..2892c81e35 100644 --- a/coordinator/api/request_outcome_sink_test.go +++ b/coordinator/api/request_outcome_sink_test.go @@ -27,28 +27,6 @@ func (s *failedRequestOutcomeStore) RequestOutcomes(context.Context, time.Time, return nil, errors.New("fake failing dependency") } -func TestRequestOutcomeSinkLossIsExplicit(t *testing.T) { - q := &requestOutcomeSink{s: &Server{}, ch: make(chan store.RequestOutcomeRecord, 1)} - q.submit(store.RequestOutcomeRecord{}) - q.submit(store.RequestOutcomeRecord{}) - if q.dropped.Load() != 1 { - t.Fatal("full queue did not count drop") - } - q.closed = true - q.submit(store.RequestOutcomeRecord{}) - if q.dropped.Load() != 2 { - t.Fatal("closed queue did not count drop") - } - for _, panicWrite := range []bool{false, true} { - s := &Server{store: &failedRequestOutcomeStore{Store: store.NewMemory(store.Config{}), panicWrite: panicWrite}} - sink := newRequestOutcomeSink(s, 2) - sink.submit(store.RequestOutcomeRecord{CoordRequestID: "a"}) - sink.close() - if sink.failed.Load() != 1 || sink.written.Load() != 0 { - t.Fatalf("failed sink fabricated persistence: failed=%d written=%d", sink.failed.Load(), sink.written.Load()) - } - } -} func TestRequestOutcomeAdminReadFailureIsNotKnownZero(t *testing.T) { s := &Server{store: &failedRequestOutcomeStore{Store: store.NewMemory(store.Config{})}, adminKey: "outcome-admin"} r := httptest.NewRequest(http.MethodGet, "/v1/admin/request-outcomes", nil) diff --git a/coordinator/api/request_outcome_terminal_test.go b/coordinator/api/request_outcome_terminal_test.go index f0a21f4706..96e30d3a1b 100644 --- a/coordinator/api/request_outcome_terminal_test.go +++ b/coordinator/api/request_outcome_terminal_test.go @@ -47,7 +47,7 @@ func terminalOutcomeServer(t *testing.T) (*Server, *store.MemoryStore) { st := store.NewMemory(store.Config{}) srv := &Server{store: st, logger: quietLogger()} srv.requestOutcomes = newRequestOutcomeSink(srv, 16) - t.Cleanup(srv.requestOutcomes.close) + t.Cleanup(srv.requestOutcomes.Close) return srv, st } diff --git a/coordinator/api/request_outcome_test.go b/coordinator/api/request_outcome_test.go index a5b8754932..1dfb21eddb 100644 --- a/coordinator/api/request_outcome_test.go +++ b/coordinator/api/request_outcome_test.go @@ -88,7 +88,7 @@ func TestRequestOutcomeFailedAndShortWrites(t *testing.T) { st := store.NewMemory(store.Config{}) srv := &Server{store: st} srv.requestOutcomes = newRequestOutcomeSink(srv, 16) - defer srv.requestOutcomes.close() + defer srv.requestOutcomes.Close() handler := srv.observeRequestOutcome(func(w http.ResponseWriter, r *http.Request) { rp := srv.newRequestProfile(r, "m", "m", false) ap := rp.NewAttempt("a", 0, "") @@ -111,7 +111,7 @@ func TestRequestOutcomeLateProviderCompletionPreservesDeparture(t *testing.T) { st := store.NewMemory(store.Config{}) srv := &Server{store: st} srv.requestOutcomes = newRequestOutcomeSink(srv, 16) - defer srv.requestOutcomes.close() + defer srv.requestOutcomes.Close() var ap *registry.AttemptProfile ctx, cancel := context.WithCancel(context.Background()) handler := srv.observeRequestOutcome(func(w http.ResponseWriter, r *http.Request) { @@ -140,7 +140,7 @@ func TestRequestOutcomeSealedWriteFailure(t *testing.T) { st := store.NewMemory(store.Config{}) srv := &Server{store: st} srv.requestOutcomes = newRequestOutcomeSink(srv, 16) - defer srv.requestOutcomes.close() + defer srv.requestOutcomes.Close() coord, err := e2e.DeriveCoordinatorKey(senderTestMnemonic) if err != nil { t.Fatal(err) @@ -195,7 +195,7 @@ func TestRequestOutcomeContentSuccessSurvivesLaterWriteFailure(t *testing.T) { st := store.NewMemory(store.Config{}) srv := &Server{store: st} srv.requestOutcomes = newRequestOutcomeSink(srv, 16) - defer srv.requestOutcomes.close() + defer srv.requestOutcomes.Close() write := func(w http.ResponseWriter, r *http.Request) { rp := srv.newRequestProfile(r, "m", "m", true) ap := rp.NewAttempt("two-write-attempt", 0, "") diff --git a/coordinator/api/server.go b/coordinator/api/server.go index ed80c4e3a7..d6c83eb3ec 100644 --- a/coordinator/api/server.go +++ b/coordinator/api/server.go @@ -907,7 +907,7 @@ func (s *Server) Close() { } s.trustAuthorityMu.Unlock() if s.requestOutcomes != nil { - s.requestOutcomes.close() + s.requestOutcomes.Close() } if s.profiler != nil { s.profiler.close() diff --git a/coordinator/api/telemetry_sink.go b/coordinator/api/telemetry_sink.go index 278ea34817..992e9fe9f3 100644 --- a/coordinator/api/telemetry_sink.go +++ b/coordinator/api/telemetry_sink.go @@ -1,9 +1,9 @@ package api import ( - "github.com/eigeninference/d-inference/coordinator/telemetry" - "github.com/eigeninference/d-inference/coordinator/telemetry/routequeue" "log/slog" + + "github.com/eigeninference/d-inference/coordinator/telemetry/routequeue" ) type telemetrySink = routequeue.Sink @@ -17,5 +17,3 @@ const ( func newTelemetrySink(logger *slog.Logger, capacity, workers int) *telemetrySink { return routequeue.New(logger, capacity, workers) } - -func crossesPowerOfTen(before, after int64) bool { return telemetry.CrossesPowerOfTen(before, after) } diff --git a/coordinator/telemetry/outcomequeue/doc.go b/coordinator/telemetry/outcomequeue/doc.go new file mode 100644 index 0000000000..8c0e4cf187 --- /dev/null +++ b/coordinator/telemetry/outcomequeue/doc.go @@ -0,0 +1,4 @@ +// Package outcomequeue owns the unsampled compact request-outcome buffer. +// It does no classification or billing: callers submit owned snapshots, and +// the worker batches their persistence with a bounded close-time drain. +package outcomequeue diff --git a/coordinator/telemetry/outcomequeue/loss_test.go b/coordinator/telemetry/outcomequeue/loss_test.go new file mode 100644 index 0000000000..5cec5525e5 --- /dev/null +++ b/coordinator/telemetry/outcomequeue/loss_test.go @@ -0,0 +1,35 @@ +package outcomequeue + +import ( + "context" + "errors" + "github.com/eigeninference/d-inference/coordinator/store" + "testing" +) + +func TestRequestOutcomeSinkLossIsExplicit(t *testing.T) { + q := &Sink{ch: make(chan store.RequestOutcomeRecord, 1)} + q.Submit(store.RequestOutcomeRecord{}) + q.Submit(store.RequestOutcomeRecord{}) + if q.dropped.Load() != 1 { + t.Fatal("full queue did not count drop") + } + q.closed = true + q.Submit(store.RequestOutcomeRecord{}) + if q.dropped.Load() != 2 { + t.Fatal("closed queue did not count drop") + } + for _, panicWrite := range []bool{false, true} { + sink := New(Hooks{Write: func(context.Context, []store.RequestOutcomeRecord) error { + if panicWrite { + panic("fake failing dependency") + } + return errors.New("fake failing dependency") + }}, 2) + sink.Submit(store.RequestOutcomeRecord{CoordRequestID: "a"}) + sink.Close() + if sink.failed.Load() != 1 || sink.written.Load() != 0 { + t.Fatalf("failed sink fabricated persistence: failed=%d written=%d", sink.failed.Load(), sink.written.Load()) + } + } +} diff --git a/coordinator/telemetry/outcomequeue/queue.go b/coordinator/telemetry/outcomequeue/queue.go new file mode 100644 index 0000000000..f87b4c0c68 --- /dev/null +++ b/coordinator/telemetry/outcomequeue/queue.go @@ -0,0 +1,60 @@ +package outcomequeue + +import ( + "context" + "github.com/eigeninference/d-inference/coordinator/store" + "log/slog" + "sync" + "sync/atomic" +) + +// Hooks inject the context-aware write and optional diagnostics. Write must +// resolve the active store at call time; the queue never retains a Server. +type Hooks struct { + Logger *slog.Logger + Write func(context.Context, []store.RequestOutcomeRecord) error + Incr func(string, []string) + Count func(string, int64, []string) +} + +// Sink keeps compact outcome loss independent of heavy profiles and routing +// telemetry. Its mutex orders Submit against Close; counters remain private. +type Sink struct { + hooks Hooks + ch chan store.RequestOutcomeRecord + stop chan struct{} + done chan struct{} + mu sync.RWMutex + closed bool + received atomic.Int64 + dropped atomic.Int64 + written atomic.Int64 + failed atomic.Int64 +} + +func New(hooks Hooks, capacity int) *Sink { + q := &Sink{hooks: hooks, ch: make(chan store.RequestOutcomeRecord, capacity), stop: make(chan struct{}), done: make(chan struct{})} + go q.run() + return q +} + +// Submit takes the caller's already-owned snapshot without waiting for IO. +// A full or closed queue drops and counts it; inference remains unaffected. +func (q *Sink) Submit(r store.RequestOutcomeRecord) { + if q == nil { + return + } + q.mu.RLock() + defer q.mu.RUnlock() + if !q.closed { + select { + case q.ch <- r: + return + default: + } + } + q.dropped.Add(1) + if q.hooks.Incr != nil { + q.hooks.Incr("request_outcomes.records", []string{"status:dropped"}) + } +} diff --git a/coordinator/telemetry/outcomequeue/queue_test.go b/coordinator/telemetry/outcomequeue/queue_test.go new file mode 100644 index 0000000000..21f0c6a6e3 --- /dev/null +++ b/coordinator/telemetry/outcomequeue/queue_test.go @@ -0,0 +1,75 @@ +package outcomequeue + +import ( + "context" + "fmt" + "reflect" + "sync" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +func TestRequestOutcomeQueueCloseDrainsBatches(t *testing.T) { + st := store.NewMemory(store.Config{}) + var sizes []int + var mu sync.Mutex + // Fill the owned buffer before starting its worker so this close/drain + // oracle does not depend on racing the periodic flush during submission. + q := &Sink{ch: make(chan store.RequestOutcomeRecord, 300), stop: make(chan struct{}), done: make(chan struct{}), hooks: Hooks{Write: func(ctx context.Context, rows []store.RequestOutcomeRecord) error { + if deadline, ok := ctx.Deadline(); !ok || time.Until(deadline) > time.Second { + return fmt.Errorf("missing one-second write deadline") + } + if err := st.RecordRequestOutcomes(ctx, rows); err != nil { + return err + } + mu.Lock() + sizes = append(sizes, len(rows)) + mu.Unlock() + return nil + }}} + t.Cleanup(q.Close) + now := time.Now() + for i := 0; i < 260; i++ { + q.MarkReceived() + q.Submit(store.RequestOutcomeRecord{CoordRequestID: fmt.Sprintf("request-%d", i), SchemaVersion: store.RequestOutcomeSchemaVersion, Revision: 1, ReceivedAt: now, UpdatedAt: now}) + } + go q.run() + q.Close() + stats := q.Stats() + if stats.Received != 260 || stats.Written != 260 || stats.Dropped != 0 || stats.Failed != 0 || stats.Queued != 0 { + t.Fatalf("incomplete drain: %+v", stats) + } + mu.Lock() + gotSizes := append([]int(nil), sizes...) + mu.Unlock() + if !reflect.DeepEqual(gotSizes, []int{128, 128, 4}) { + t.Fatalf("batch sizes = %v, want [128 128 4]", gotSizes) + } + rows, err := st.RequestOutcomes(context.Background(), now.Add(-time.Second), now.Add(time.Second), 300) + if err != nil || len(rows) != 260 { + t.Fatalf("persisted rows=%d err=%v", len(rows), err) + } + q.Submit(store.RequestOutcomeRecord{}) + if got := q.Stats(); got.Written != 260 || got.Dropped != 1 { + t.Fatalf("post-close snapshot not rejected: %+v", got) + } +} + +func TestRequestOutcomeQueueWriteDeadlineCountsFailure(t *testing.T) { + q := New(Hooks{Write: func(ctx context.Context, _ []store.RequestOutcomeRecord) error { + <-ctx.Done() + return ctx.Err() + }}, 1) + t.Cleanup(q.Close) + q.Submit(store.RequestOutcomeRecord{}) + start := time.Now() + q.Close() + if elapsed := time.Since(start); elapsed > 3*time.Second { + t.Fatalf("close exceeded deadline with scheduler slack: %s", elapsed) + } + if got := q.Stats(); got.Failed != 1 || got.Written != 0 { + t.Fatalf("timed-out write counts = %+v", got) + } +} diff --git a/coordinator/telemetry/outcomequeue/shutdown.go b/coordinator/telemetry/outcomequeue/shutdown.go new file mode 100644 index 0000000000..dd39a7747b --- /dev/null +++ b/coordinator/telemetry/outcomequeue/shutdown.go @@ -0,0 +1,24 @@ +package outcomequeue + +import "time" + +// Close rejects new snapshots and waits up to two seconds for the worker to +// drain accepted records. Each write retains its independent one-second limit. +func (q *Sink) Close() { + if q == nil { + return + } + q.mu.Lock() + if !q.closed { + q.closed = true + close(q.stop) + } + q.mu.Unlock() + select { + case <-q.done: + case <-time.After(2 * time.Second): + if q.hooks.Logger != nil { + q.hooks.Logger.Warn("request outcomes drain incomplete", "dropped", q.dropped.Load(), "queued", len(q.ch)) + } + } +} diff --git a/coordinator/telemetry/outcomequeue/snapshot.go b/coordinator/telemetry/outcomequeue/snapshot.go new file mode 100644 index 0000000000..f4f7c195ff --- /dev/null +++ b/coordinator/telemetry/outcomequeue/snapshot.go @@ -0,0 +1,18 @@ +package outcomequeue + +// Stats samples independent process counters and queue depth. Like the +// underlying atomics, it is observational, not a transactional store snapshot. +type Stats struct { + Received int64 + Written int64 + Dropped int64 + Failed int64 + Queued int +} + +func (q *Sink) MarkReceived() { q.received.Add(1) } +func (q *Sink) ReceivedTotal() int64 { return q.received.Load() } + +func (q *Sink) Stats() Stats { + return Stats{Received: q.received.Load(), Written: q.written.Load(), Dropped: q.dropped.Load(), Failed: q.failed.Load(), Queued: len(q.ch)} +} diff --git a/coordinator/telemetry/outcomequeue/worker.go b/coordinator/telemetry/outcomequeue/worker.go new file mode 100644 index 0000000000..8f2350d0a4 --- /dev/null +++ b/coordinator/telemetry/outcomequeue/worker.go @@ -0,0 +1,70 @@ +package outcomequeue + +import ( + "context" + "errors" + "github.com/eigeninference/d-inference/coordinator/store" + "time" +) + +func (q *Sink) run() { + defer close(q.done) + ticker := time.NewTicker(100 * time.Millisecond) + defer ticker.Stop() + batch := make([]store.RequestOutcomeRecord, 0, 128) + flush := func() { + if len(batch) == 0 { + return + } + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + err := func() (err error) { + defer func() { + if recover() != nil { + err = errors.New("request outcome store panic") + } + }() + return q.hooks.Write(ctx, batch) + }() + cancel() + if err != nil { + q.failed.Add(int64(len(batch))) + if q.hooks.Count != nil { + q.hooks.Count("request_outcomes.records", int64(len(batch)), []string{"status:write_failed"}) + } + if q.hooks.Logger != nil { + q.hooks.Logger.Warn("request outcomes persistence failed", "records", len(batch)) + } + } else { + q.written.Add(int64(len(batch))) + if q.hooks.Count != nil { + q.hooks.Count("request_outcomes.records", int64(len(batch)), []string{"status:written"}) + } + } + clear(batch) + batch = batch[:0] + } + for { + select { + case r := <-q.ch: + batch = append(batch, r) + if len(batch) == cap(batch) { + flush() + } + case <-ticker.C: + flush() + case <-q.stop: + for { + select { + case r := <-q.ch: + batch = append(batch, r) + if len(batch) == cap(batch) { + flush() + } + default: + flush() + return + } + } + } + } +} diff --git a/coordinator/telemetry/profilequeue/doc.go b/coordinator/telemetry/profilequeue/doc.go new file mode 100644 index 0000000000..d3160d82c5 --- /dev/null +++ b/coordinator/telemetry/profilequeue/doc.go @@ -0,0 +1,5 @@ +// Package profilequeue owns the bounded worker for sampled request profiles. +// It builds records off the request path and writes batches through injected +// dependencies. Its buffer and close policy are independent of route and +// compact outcome persistence. +package profilequeue diff --git a/coordinator/telemetry/profilequeue/persist.go b/coordinator/telemetry/profilequeue/persist.go new file mode 100644 index 0000000000..5917a42f0e --- /dev/null +++ b/coordinator/telemetry/profilequeue/persist.go @@ -0,0 +1,36 @@ +package profilequeue + +import ( + "github.com/eigeninference/d-inference/coordinator/saferun" + "github.com/eigeninference/d-inference/coordinator/store" +) + +func (p *Sink) build(job job) *store.RequestProfileRecord { + defer saferun.Recover(p.hooks.Logger, "profileSink.build") + return p.hooks.Build(job.rp, job.ap) +} + +func (p *Sink) flush(batch []*store.RequestProfileRecord) { + if len(batch) == 0 { + return + } + st := p.hooks.Store() + if st == nil { + return + } + logger := p.hooks.Logger + defer saferun.Recover(logger, "profileSink") + if err := st.RecordRequestProfiles(batch); err != nil { + if logger != nil { + logger.Error("request_profiles batch write failed", "rows", len(batch), "error", err) + } + if p.hooks.Count != nil { + p.hooks.Count("profiler.records", int64(len(batch)), []string{"status:write_failed"}) + } + return + } + p.written.Add(int64(len(batch))) + if p.hooks.Count != nil { + p.hooks.Count("profiler.records", int64(len(batch)), []string{"status:written"}) + } +} diff --git a/coordinator/telemetry/profilequeue/queue.go b/coordinator/telemetry/profilequeue/queue.go new file mode 100644 index 0000000000..f16afb3e45 --- /dev/null +++ b/coordinator/telemetry/profilequeue/queue.go @@ -0,0 +1,87 @@ +package profilequeue + +import ( + "log/slog" + "sync" + "sync/atomic" + + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" + "github.com/eigeninference/d-inference/coordinator/telemetry" +) + +const DefaultCapacity = 4096 + +// Writer is the one persistence operation used by the profile worker. +type Writer interface { + RecordRequestProfiles([]*store.RequestProfileRecord) error +} + +// Hooks connect the queue to record construction and telemetry. Store resolves +// the active writer at flush time, preserving the server's live store lookup. +// Build runs only on the worker. Incr and Count may be nil when no metrics are +// installed; Logger may be nil. Callers provide Build and Store. +type Hooks struct { + Logger *slog.Logger + Build func(*registry.RequestProfile, *registry.AttemptProfile) *store.RequestProfileRecord + Store func() Writer + Incr func(string, []string) + Count func(string, int64, []string) +} + +// job retains the finalized attempt until its record can be built on the +// worker. The caller owns the request/attempt lifecycle and finalization. +type job struct { + rp *registry.RequestProfile + ap *registry.AttemptProfile +} + +// Sink owns one bounded queue and one worker. Submit never waits for a build +// or store call. Close signals the worker without waiting: it flushes a batch +// it already holds, but does not promise to drain all buffered jobs. +type Sink struct { + hooks Hooks + ch chan job + done chan struct{} + dropped atomic.Int64 + written atomic.Int64 + closeOnce sync.Once +} + +func New(hooks Hooks, capacity int) *Sink { + if capacity <= 0 { + capacity = DefaultCapacity + } + p := &Sink{hooks: hooks, ch: make(chan job, capacity), done: make(chan struct{})} + go p.worker() + return p +} + +// Submit enqueues a finalized attempt without blocking; full buffers drop +// and count the new job. Nil inputs do not enter the queue or count as drops. +func (p *Sink) Submit(rp *registry.RequestProfile, ap *registry.AttemptProfile) bool { + if p == nil || rp == nil || ap == nil { + return false + } + select { + case p.ch <- job{rp: rp, ap: ap}: + return true + default: + n := p.dropped.Add(1) + if telemetry.CrossesPowerOfTen(n-1, n) && p.hooks.Logger != nil { + p.hooks.Logger.Warn("profile sink dropping records (buffer full) — inference is unaffected", + "dropped_total", n, "capacity", cap(p.ch)) + } + if p.hooks.Incr != nil { + p.hooks.Incr("telemetry.sink_dropped", []string{"sink:profile"}) + } + return false + } +} + +func (p *Sink) Close() { + if p == nil { + return + } + p.closeOnce.Do(func() { close(p.done) }) +} diff --git a/coordinator/telemetry/profilequeue/queue_test.go b/coordinator/telemetry/profilequeue/queue_test.go new file mode 100644 index 0000000000..d28e39e50e --- /dev/null +++ b/coordinator/telemetry/profilequeue/queue_test.go @@ -0,0 +1,169 @@ +package profilequeue + +import ( + "io" + "log/slog" + "reflect" + "sync" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +type recordingWriter struct { + *store.MemoryStore + mu sync.Mutex + batches []int +} + +func (w *recordingWriter) RecordRequestProfiles(rows []*store.RequestProfileRecord) error { + if err := w.MemoryStore.RecordRequestProfiles(rows); err != nil { + return err + } + w.mu.Lock() + w.batches = append(w.batches, len(rows)) + w.mu.Unlock() + return nil +} + +func (w *recordingWriter) batchSizes() []int { + w.mu.Lock() + defer w.mu.Unlock() + return append([]int(nil), w.batches...) +} + +func newWriter() *recordingWriter { + return &recordingWriter{MemoryStore: store.NewMemory(store.Config{})} +} + +func fixtureAttempt(id string) (*registry.RequestProfile, *registry.AttemptProfile) { + rp := registry.NewRequestProfile(time.Now(), id, nil, 0) + return rp, rp.NewAttempt(id, 0, "") +} + +func fixtureRecord(rp *registry.RequestProfile, ap *registry.AttemptProfile) *store.RequestProfileRecord { + return &store.RequestProfileRecord{CoordRequestID: rp.CoordRequestID, RequestID: ap.RequestID, ReceivedAt: rp.T0} +} + +func waitWritten(t *testing.T, q *Sink, want int64) { + t.Helper() + deadline := time.Now().Add(3 * time.Second) + for q.WrittenTotal() != want && time.Now().Before(deadline) { + time.Sleep(time.Millisecond) + } + if got := q.WrittenTotal(); got != want { + t.Fatalf("written = %d, want %d", got, want) + } +} + +func TestProfileQueueBuildDoesNotBlockSubmit(t *testing.T) { + w := newWriter() + started, release := make(chan struct{}), make(chan struct{}) + var releaseOnce sync.Once + unblock := func() { releaseOnce.Do(func() { close(release) }) } + t.Cleanup(unblock) + var buildOnce sync.Once + q := New(Hooks{Store: func() Writer { return w }, Build: func(rp *registry.RequestProfile, ap *registry.AttemptProfile) *store.RequestProfileRecord { + buildOnce.Do(func() { close(started) }) + <-release + return fixtureRecord(rp, ap) + }}, 1) + t.Cleanup(q.Close) + rp, ap := fixtureAttempt("first") + if !q.Submit(rp, ap) { + t.Fatal("first job was rejected") + } + select { + case <-started: + case <-time.After(time.Second): + t.Fatal("worker never started building") + } + rp, ap = fixtureAttempt("second") + if !q.Submit(rp, ap) { + t.Fatal("buffered job was rejected") + } + rp, ap = fixtureAttempt("dropped") + accepted := make(chan bool, 1) + go func() { accepted <- q.Submit(rp, ap) }() + select { + case ok := <-accepted: + if ok { + t.Fatal("full queue accepted a third job") + } + case <-time.After(time.Second): + t.Fatal("submission waited for record construction") + } + if q.Depth() != 1 || q.DroppedTotal() != 1 { + t.Fatalf("queue depth=%d dropped=%d", q.Depth(), q.DroppedTotal()) + } + unblock() + waitWritten(t, q, 2) + if got := w.batchSizes(); !reflect.DeepEqual(got, []int{2}) { + t.Fatalf("quiet queue batches = %v, want [2]", got) + } + for _, row := range w.RequestProfilesSince(time.Time{}) { + if row.RequestID == "dropped" { + t.Fatal("dropped job reached the store") + } + } +} + +func TestProfileQueueBuildFailureKeepsLaterRecords(t *testing.T) { + w := newWriter() + q := New(Hooks{ + Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), + Store: func() Writer { return w }, + Build: func(rp *registry.RequestProfile, ap *registry.AttemptProfile) *store.RequestProfileRecord { + switch ap.RequestID { + case "panic": + panic("owned build fixture") + case "sampled-out": + return nil + } + return fixtureRecord(rp, ap) + }, + }, 4) + t.Cleanup(q.Close) + for _, id := range []string{"panic", "sampled-out", "written"} { + rp, ap := fixtureAttempt(id) + if !q.Submit(rp, ap) { + t.Fatalf("job %q was rejected", id) + } + } + waitWritten(t, q, 1) + rows := w.RequestProfilesSince(time.Time{}) + if len(rows) != 1 || rows[0].RequestID != "written" || q.DroppedTotal() != 0 { + t.Fatalf("rows=%+v dropped=%d", rows, q.DroppedTotal()) + } +} + +func TestProfileQueueBatchLimitAndQuietRemainder(t *testing.T) { + w := newWriter() + // Hold the first build until every job is queued. The 250ms quiet timer + // then starts with a full buffer, independent of fixture scheduling. + release := make(chan struct{}) + var once sync.Once + unblock := func() { once.Do(func() { close(release) }) } + t.Cleanup(unblock) + q := New(Hooks{Build: func(rp *registry.RequestProfile, ap *registry.AttemptProfile) *store.RequestProfileRecord { + <-release + return fixtureRecord(rp, ap) + }, Store: func() Writer { return w }}, 65) + t.Cleanup(q.Close) + for i := 0; i < 65; i++ { + rp, ap := fixtureAttempt(time.Unix(int64(i), 0).Format(time.RFC3339)) + if !q.Submit(rp, ap) { + t.Fatalf("job %d was rejected", i) + } + } + unblock() + waitWritten(t, q, 65) + if got := w.batchSizes(); !reflect.DeepEqual(got, []int{64, 1}) { + t.Fatalf("batches = %v, want [64 1]", got) + } + if got := len(w.RequestProfilesSince(time.Time{})); got != 65 { + t.Fatalf("store has %d records, want 65", got) + } +} diff --git a/coordinator/telemetry/profilequeue/snapshot.go b/coordinator/telemetry/profilequeue/snapshot.go new file mode 100644 index 0000000000..9f82d2afc1 --- /dev/null +++ b/coordinator/telemetry/profilequeue/snapshot.go @@ -0,0 +1,23 @@ +package profilequeue + +// Depth counts buffered jobs; the worker may also hold a batch. +func (p *Sink) Depth() int { + if p == nil { + return 0 + } + return len(p.ch) +} + +func (p *Sink) DroppedTotal() int64 { + if p == nil { + return 0 + } + return p.dropped.Load() +} + +func (p *Sink) WrittenTotal() int64 { + if p == nil { + return 0 + } + return p.written.Load() +} diff --git a/coordinator/telemetry/profilequeue/worker.go b/coordinator/telemetry/profilequeue/worker.go new file mode 100644 index 0000000000..f8e87c3ace --- /dev/null +++ b/coordinator/telemetry/profilequeue/worker.go @@ -0,0 +1,46 @@ +package profilequeue + +import ( + "github.com/eigeninference/d-inference/coordinator/store" + "time" +) + +const ( + batchMax = 64 + batchWait = 250 * time.Millisecond +) + +// worker drains the channel into batches and writes each batch with one store +// call inside a panic-safe wrapper. It never spawns per-record goroutines. +func (p *Sink) worker() { + batch := make([]*store.RequestProfileRecord, 0, batchMax) + for { + select { + case <-p.done: + return + case first := <-p.ch: + batch = batch[:0] + if rec := p.build(first); rec != nil { + batch = append(batch, rec) + } + timer := time.NewTimer(batchWait) + collect: + for len(batch) < batchMax { + select { + case job := <-p.ch: + if rec := p.build(job); rec != nil { + batch = append(batch, rec) + } + case <-timer.C: + break collect + case <-p.done: + timer.Stop() + p.flush(batch) + return + } + } + timer.Stop() + p.flush(batch) + } + } +} diff --git a/docs/AGENTS.md b/docs/AGENTS.md index da90f38458..48711dc4de 100644 --- a/docs/AGENTS.md +++ b/docs/AGENTS.md @@ -1,6 +1,6 @@ # Darkbloom docs — how this documentation is organised and maintained -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` Rules for anyone — human or agent — who reads, writes, or checks a file under `docs/`. The code is the source of truth; a doc that disagrees with the code is diff --git a/docs/README.md b/docs/README.md index 855aeb149c..3afa009c0c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,6 +1,6 @@ # Darkbloom documentation -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` > Darkbloom is a decentralized private-inference network: an OpenAI- and > Anthropic-compatible HTTP API served by a Go coordinator that routes each diff --git a/docs/architecture/cache-aware-routing.md b/docs/architecture/cache-aware-routing.md index 9b31f74dff..26d1287753 100644 --- a/docs/architecture/cache-aware-routing.md +++ b/docs/architecture/cache-aware-routing.md @@ -1,6 +1,6 @@ # Exact Prefix Cache Routing -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` Exact prefix cache routing lets the scheduler prefer a provider that has *proven* it holds a reusable exact token prefix in an advertised resident diff --git a/docs/architecture/components/console-ui.md b/docs/architecture/components/console-ui.md index 606b123efe..cc205dcf7a 100644 --- a/docs/architecture/components/console-ui.md +++ b/docs/architecture/components/console-ui.md @@ -1,6 +1,6 @@ # Console UI (`console-ui/`) -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` The console at `console.darkbloom.dev` is a Next.js 16 App Router / React 19 application (`console-ui/package.json`) that gives consumers a chat client, model catalog, network stats, billing, API-key management, and provider linking. The browser never calls the coordinator for authenticated work: every page fetches same-origin `/api/*` route handlers, which resolve the coordinator URL server-side and forward the caller's own credential. This page explains how those pieces fit; the coordinator routes they call are specified in [`../../reference/api-contracts.md`](../../reference/api-contracts.md). The internal, read-only operator dashboard is a separate app — see [`admin-ui.md`](admin-ui.md). diff --git a/docs/architecture/components/coordinator.md b/docs/architecture/components/coordinator.md index 18895d8949..c86f6a7867 100644 --- a/docs/architecture/components/coordinator.md +++ b/docs/architecture/components/coordinator.md @@ -1,6 +1,6 @@ # Coordinator -> Last updated: 2026-09-13 · commit `2b6a10301` +> Last updated: 2026-09-13 · commit `a3493b5ac` The coordinator is Darkbloom's control plane: one Go HTTP/WebSocket service (binary `coordinator/cmd/coordinator`) that authenticates consumers, picks a @@ -69,6 +69,8 @@ Every directory under `coordinator/` and what it owns. | `coordinator/telemetry` | Structured telemetry emitter. | | `coordinator/telemetry/metrics` | In-process counters, histograms, computed gauges and JSON/Prometheus snapshots (`Registry`, `Histogram`, `Snapshot`). | | `coordinator/telemetry/routequeue` | Bounded FIFO routing-telemetry persistence, grouping, failure handling and shutdown (`Sink`, `SubmitRoute`, `SubmitOutcome`, `CloseAndWait`). | +| `coordinator/telemetry/profilequeue` | Worker-side profile construction and batched persistence, private buffer/drop counters and signal-only close (`Sink`, `Submit`, `Close`). | +| `coordinator/telemetry/outcomequeue` | Independent unsampled outcome snapshot buffer, process counters and bounded close-time drain (`Sink`, `Submit`, `Stats`, `Close`). | | `coordinator/saferun` | Panic-safe goroutine launcher used by every background loop. | | `coordinator/deploy` | `start.sh` container entrypoint (persistent disk, MicroMDM). | diff --git a/docs/architecture/components/mlx-swift.md b/docs/architecture/components/mlx-swift.md index fcf5141a29..47812ca037 100644 --- a/docs/architecture/components/mlx-swift.md +++ b/docs/architecture/components/mlx-swift.md @@ -1,6 +1,6 @@ # MLX stack: the three pinned submodules and the metallib -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` What the provider links from `libs/`, at which commits, what each submodule contributes, how the Metal kernel library (`mlx.metallib`) is built from the diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index 60c826d401..d9a9d911e3 100644 --- a/docs/architecture/hardware-support.md +++ b/docs/architecture/hardware-support.md @@ -1,6 +1,6 @@ # Hardware support and the provider memory model -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` What hardware the provider runs on and how it decides, in bytes, whether a model may load and how much KV cache each resident model may use. Read this to diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 87a4d637f9..7de76107ce 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` How a chat-completion request is served inside the `darkbloom` provider process in v0.9.1: one in-process engine (`mlx-swift-lm` diff --git a/docs/architecture/prefix-cache.md b/docs/architecture/prefix-cache.md index 6c89888d97..ffb59ec843 100644 --- a/docs/architecture/prefix-cache.md +++ b/docs/architecture/prefix-cache.md @@ -1,6 +1,6 @@ # KV cache layouts and prefix caching -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` How the provider lays out a request's KV cache, how it decides whether a previously computed prefix can be reused, and where reusable state lives: diff --git a/docs/architecture/prompt-contract-sidecar.md b/docs/architecture/prompt-contract-sidecar.md index f2a8b5e228..b0187bae6e 100644 --- a/docs/architecture/prompt-contract-sidecar.md +++ b/docs/architecture/prompt-contract-sidecar.md @@ -1,6 +1,6 @@ # Prompt-contract sidecar -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` How the coordinator's `promptsidecar` child process derives deterministic, provider-compatible token boundaries so exact-cache routing can predict which diff --git a/docs/architecture/request-accounting.md b/docs/architecture/request-accounting.md index bf6595211a..fc6a20a2d8 100644 --- a/docs/architecture/request-accounting.md +++ b/docs/architecture/request-accounting.md @@ -1,6 +1,6 @@ # Incoming request accounting -> Last updated: 2026-09-11 · commit `5e41029dd` +> Last updated: 2026-09-13 · commit `a3493b5ac` `request_outcomes` records unsampled observations of incoming inference requests, including early rejections, independently of sampled attempt profiles. Operators use this source to distinguish final request outcomes from internal retries. The dashboard aggregation and presentation work in issue #845 remains open. @@ -25,14 +25,14 @@ flowchart LR Relay --> Finish[Recovered handler return: one request observation] Attempts --> Late[Late provider terminal or bounded fallback] Late --> Revision[Enrich same coordinator UUID] - Finish --> Sink[Dedicated bounded requestOutcomeSink] + Finish --> Sink[Dedicated bounded outcomequeue.Sink] Revision --> Sink Sink --> Ledger[(request_outcomes)] ``` Only the compact fixed schema is unsampled. The existing in-memory request/attempt lifecycle objects collect evidence when the heavy profiler is off; `CompactOnly` preserves the profiler-off timing-header behavior. Heavy `request_profiles` persistence, provider-profile payload retention, sampling and fleet sampling retain their existing switches. -The request sink has 4,096 queued snapshots, one worker, batches of up to 128, and a 100 ms flush interval. Each database transaction has a one-second context deadline. Upserts run through one `pgx.Batch`. A full/closed queue drops the snapshot, while failed transactions increment a separate failure count. No telemetry write blocks the inference path. Shutdown waits up to two seconds for draining. The existing hourly retention loop deletes ledger rows by receipt time after 14 days, even with the heavy profiler off. +The request sink (`coordinator/telemetry/outcomequeue/queue.go`, `Sink`) has 4,096 queued snapshots, one worker, batches of up to 128, and a 100 ms flush interval. Each database transaction has a one-second context deadline. Upserts run through one `pgx.Batch`. A full/closed queue drops the snapshot, while failed transactions increment a separate failure count. No telemetry write blocks the inference path. Shutdown waits up to two seconds for draining. The existing hourly retention loop deletes ledger rows by receipt time after 14 days, even with the heavy profiler off. ## Identity, coverage and time @@ -102,7 +102,8 @@ A raw historical `dispatch_exhausted` can represent a retained real provider err |---|---| | Observation, lifecycle and mapping | `coordinator/api/request_outcome.go` | | Content and write evidence | `coordinator/api/request_outcome_egress.go`, `coordinator/api/sender_encryption.go` | -| Bounded persistence and health | `coordinator/api/request_outcome_sink.go`, `coordinator/api/request_outcome_admin.go` | +| Bounded persistence | `coordinator/telemetry/outcomequeue/` (`Sink`, `Submit`, `Close`, `Stats`); `coordinator/api/request_outcome_sink.go` (`newRequestOutcomeSink`) injects the active-store writer and metrics | +| Health endpoint | `coordinator/api/request_outcome_admin.go` (`handleAdminRequestOutcomes`) reads independent process counters through `Stats` | | Schema, revision merge and reads | `coordinator/store/request_outcomes.go`, `coordinator/store/postgres_request_outcomes.go`, `coordinator/store/memory_request_outcomes.go` | | Live isolated endpoint regressions | `coordinator/api/request_outcome_integration_test.go`, `coordinator/api/request_outcome_test.go`, `coordinator/api/deadline_unreachable_integration_test.go` | | Memory/Postgres parity and retention | `coordinator/store/request_outcomes_test.go` | diff --git a/docs/architecture/security/attestation.md b/docs/architecture/security/attestation.md index d6e0910a11..2f0ca577d2 100644 --- a/docs/architecture/security/attestation.md +++ b/docs/architecture/security/attestation.md @@ -1,6 +1,6 @@ # Provider attestation -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` How the coordinator decides how far to trust a provider connection: three trust levels (`none`, `self_signed`, `hardware`), two flags carried alongside diff --git a/docs/architecture/system-profiler.md b/docs/architecture/system-profiler.md index 89fd5f9afa..83963c3b10 100644 --- a/docs/architecture/system-profiler.md +++ b/docs/architecture/system-profiler.md @@ -1,6 +1,6 @@ # System profiler -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` The profiler answers "where did the time go, and what did the router know when it chose?" for one request, without carrying a single prompt-derived byte. It @@ -28,7 +28,7 @@ per-token cost, or a free-form provider string to storage. | Artefact | Grain | Producer | Sink | Retention | |---|---|---|---|---| -| `request_profiles` row | dispatched attempt (pre-dispatch rejections never produce one) | stamps on `registry.RequestProfile` / `AttemptProfile`, flattened by `buildProfileRecord` (`coordinator/api/profiler_record.go`) | `profileSink` (`coordinator/api/profiler_sink.go`) → multi-row INSERT | `profileRetainProfiles` — value in [`../reference/telemetry-inventory.md#coordinator-per-request-records-postgres`](../reference/telemetry-inventory.md#coordinator-per-request-records-postgres) | +| `request_profiles` row | dispatched attempt (pre-dispatch rejections never produce one) | stamps on `registry.RequestProfile` / `AttemptProfile`, flattened by `buildProfileRecord` (`coordinator/api/profiler_record.go`) | `profilequeue.Sink` (`coordinator/telemetry/profilequeue/queue.go`) → multi-row INSERT | `profileRetainProfiles` — value in [`../reference/telemetry-inventory.md#coordinator-per-request-records-postgres`](../reference/telemetry-inventory.md#coordinator-per-request-records-postgres) | | `fleet_snapshots` row | (provider session, slot) per 60 s + one `provider_id = 'coordinator'` row | `registry.FleetSample`, `CoordinatorSample` (`coordinator/registry/fleet_sample.go`) | sampler goroutine, `pgx.CopyFrom` (`coordinator/store/postgres_profiles.go`) | `profileRetainFleet` — same page | | `X-Timing` additive keys | committed response | `writeTimingHeaderWithProfile` (`coordinator/api/profiler_dispatch.go`) | response header ([`../reference/api-contracts.md#headers`](../reference/api-contracts.md#headers)) | n/a | | Datadog counters | process | [Operations](#operations) | DogStatsD / HTTPS series | n/a | @@ -301,13 +301,21 @@ producer status. | always recorded | `final_status != "success"`; `first_content_us > profileSlowFirstContent = 5 s`; `finalized_us > profileSlowTotal = 30 s`; `attempts_total > 1`; `backup_launched`; `timing_anomaly`; `client_gone_phase` set; `provider_profile_valid = false` with a reason other than `absent` | | `timing_anomaly` | any decreasing pair along `handler_entry_us, parsed_us, reserved_us, attempt_start_us, reserve_done_us, encrypted_us, write_submitted_us, write_dequeued_us, write_done_us, first_chunk_ingress_us, first_content_us, complete_ingress_us` (`profileTimingAnomaly`); never rejects the row | | finalize | two halves (handler, terminal) under `sync.Once`; a fallback timer `profileFallbackGrace = defaultTerminalSettleGrace + 1 s` = 31 s arms when the handler half completes first and on expiry sets `provider_outcome = no_terminal`; a provider frame that owns the terminal claim completes the terminal half itself, the route-outcome funnel completes it only when no frame owns it (`CompleteTerminalUnlessClaimed`) | -| sink | own channel of `defaultTelemetrySinkCapacity = 4096`, one worker, non-blocking submit; drop ⇒ `telemetry.sink_dropped{sink:profile}` and a warning at powers of ten; batches of `profileBatchMax = 64` or `profileBatchWait = 250 ms` | +| sink | own channel of `defaultTelemetrySinkCapacity = 4096`, one worker, non-blocking submit; drop ⇒ `telemetry.sink_dropped{sink:profile}` and a warning at powers of ten; batches of `batchMax = 64` or `batchWait = 250 * time.Millisecond` (`coordinator/telemetry/profilequeue/worker.go`) | | store write | multi-row INSERT padded to `profileInsertShapes = {1, 8, 64}`, `ON CONFLICT (request_id, attempt) DO NOTHING`, 5 s context (`RecordRequestProfiles`, `coordinator/store/postgres_profiles.go`) | | fleet write | never on the sink: one `CopyFrom` per 60 s tick, 10 s context; row-count mismatch is an error | | retention | `PruneTelemetry`: per table, `cutoff = MAX(id) WHERE time < before` via the time index, then `DELETE … WHERE id >= lo AND id < hi` in `profilePruneBatch = 5000` windows, each its own transaction with `SET LOCAL lock_timeout = '2s'`; hourly (`profilePruneInterval`), 10 min context; **runs even when the profiler is off** so old rows stay bounded | | memory store | implements the same `TelemetryStore` methods and prunes its slices (`coordinator/store/interface_domains.go`; `TestMemoryPruneCapsProfilerSlices`) | | `request_waterfall` view | not in the boot migrations; apply by hand with `psql "$EIGENINFERENCE_DATABASE_URL" -f coordinator/store/migrations/request_waterfall.sql`; explicit column list, `LEFT JOIN inference_routes ON (request_id, attempt)`; re-run after adding a column (`TestRequestWaterfallViewListsEveryProfileColumn`) | +The profile queue owns its channel, worker and drop/write counters. The API +adapter supplies record construction, sampling, metrics and a writer resolved +at flush time (`coordinator/api/profiler_sink.go`, `newProfileSink`). `Close` +signals this worker without waiting: it flushes a batch already being collected, +but does not guarantee a drain of buffered jobs. The compact outcome queue has +its own [bounded drain policy](request-accounting.md); neither queue shares the +routing buffer. + ### Operations The only two knobs are the kill switch `EIGENINFERENCE_PROFILER` and the @@ -442,7 +450,8 @@ ring or `DaemonState` mirror. | Knobs, constants, sampling, middleware stamps | `coordinator/api/profiler.go` | | Row builder, folds, always-record, anomaly | `coordinator/api/profiler_record.go` | | Provider profile decode and validation | `coordinator/api/profiler_provider.go` | -| Sink | `coordinator/api/profiler_sink.go`, `coordinator/telemetry/routequeue/` | +| Profile queue and API adapter | `coordinator/telemetry/profilequeue/` (`Sink`, `Submit`, `Close`); `coordinator/api/profiler_sink.go` (`newProfileSink`, `buildQueuedProfile`) | +| Routing queue | `coordinator/telemetry/routequeue/` (`Sink`, `CloseAndWait`) | | Fleet sampler, retention loop, metrics | `coordinator/api/profiler_fleet.go`, `coordinator/registry/fleet_sample.go` | | Dispatch hooks, `X-Timing`, relay stamps | `coordinator/api/profiler_dispatch.go` | | Admin endpoints | `coordinator/api/profiler_admin.go`, `coordinator/api/admin_telemetry.go` | diff --git a/docs/architecture/telemetry.md b/docs/architecture/telemetry.md index 1a370f808b..ca939ee06e 100644 --- a/docs/architecture/telemetry.md +++ b/docs/architecture/telemetry.md @@ -1,6 +1,6 @@ # Telemetry -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` How operational data leaves a provider, what the coordinator does with it, and why nothing on that path can carry a prompt or slow a request. The heartbeat is @@ -253,7 +253,7 @@ appear; request correlation uses `request_id` (`X-Request-ID`) instead. ### Request-level sinks Two bounded, non-blocking sinks (`routequeue.Sink`, `coordinator/telemetry/routequeue/queue.go`; -`profileSink`, `coordinator/api/profiler_sink.go`) carry `inference_routes` +`profilequeue.Sink`, `coordinator/telemetry/profilequeue/queue.go`) carry `inference_routes` outcome writes and `request_profiles` rows off the request path. Each has a 4096-slot channel and a single worker; a full channel drops the write and counts it (`telemetry.sink_dropped{sink:profile}`, or the route sink's atomic @@ -265,6 +265,12 @@ and the `inference.timing.*` histograms are built from the same `inference.request_outcome` and `inference.error` in [`request-outcome-observability.md`](request-outcome-observability.md). +Compact unsampled request observations use a third independent owner, +`coordinator/telemetry/outcomequeue/` (`Sink`). Its receipt counters, batching +and bounded shutdown drain are described in +[request-accounting.md](request-accounting.md). API adapters inject the store +and diagnostics; none of these queue packages depends on the HTTP server. + ## Invariants 1. **No prompt or completion text on any telemetry path.** The field allowlist @@ -341,7 +347,8 @@ for populations, labels and reset semantics (`coordinator/api/cache_model_teleme | Coordinator event emitter | `coordinator/telemetry/emitter.go`; helpers and gauge loop in `coordinator/api/server.go` | | In-process metrics registry | `coordinator/telemetry/metrics/registry.go`; `handleAdminMetrics` in `coordinator/api/server.go` | | Event shape, allowlist, retired ingest | `coordinator/protocol/telemetry.go`, `coordinator/api/telemetry_handlers.go` | -| Sinks | `coordinator/telemetry/routequeue/`, `coordinator/api/profiler_sink.go`, `coordinator/api/profiler_fleet.go` | +| Persistence queues | `coordinator/telemetry/routequeue/`, `coordinator/telemetry/profilequeue/`, `coordinator/telemetry/outcomequeue/` (`Sink`) | +| Profile/fleet API wiring | `coordinator/api/profiler_sink.go` (`newProfileSink`), `coordinator/api/profiler_fleet.go` (`sampleFleetOnce`) | | Disconnect classification | `coordinator/registry/disconnect_classify.go` | | Provider side | `provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Registration.swift` (`buildHeartbeatJSON`), `provider-swift/Sources/ProviderCore/CapacityEventHeartbeats.swift`, `provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Capacity.swift`, `provider-swift/Sources/ProviderCore/Telemetry/TelemetryClient.swift` (no-op facade) | | Tests | `coordinator/api/telemetry_allowlist_parity_test.go`, `coordinator/api/telemetry_handlers_test.go`, `coordinator/protocol/telemetry_symmetry_test.go`, `coordinator/datadog/datadog_test.go`, `coordinator/datadog/metrics_http_test.go`, `provider-swift/Tests/ProviderCoreTests/Telemetry/TelemetrySymmetryTests.swift` | diff --git a/docs/consumer/authentication.md b/docs/consumer/authentication.md index 0dcc10bea6..14ced4ccb6 100644 --- a/docs/consumer/authentication.md +++ b/docs/consumer/authentication.md @@ -1,6 +1,6 @@ # Authentication -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` How to obtain and manage each credential the coordinator accepts, and which routes take it. Every request authenticates with one header, `Authorization: Bearer ` (`extractBearerToken`, `coordinator/api/server.go`); the token is an API key, a Privy session JWT, a device-flow provider token, or the operator's admin key, and `requireAuth` decides which by shape — JWTs (starting `eyJ`) are verified with Privy, the admin key is compared in constant time, everything else is looked up as an API key. For API consumers and console users; the per-route auth column is in [`../reference/api-contracts.md`](../reference/api-contracts.md). diff --git a/docs/consumer/models.md b/docs/consumer/models.md index 48dbb40b68..e5deb80429 100644 --- a/docs/consumer/models.md +++ b/docs/consumer/models.md @@ -1,6 +1,6 @@ # Models reference -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` Reference for `GET /v1/models` and `GET /v1/models/{id}`: every field of a `ModelEntry`, how the `model` you send is resolved, and the capability flags the API exposes and enforces. For SDK users and integrators. The catalog itself is database-driven — builds, capabilities and prices live in the coordinator's registry and price tables, and public names are aliases maintained by operators (`coordinator/api/model_alias_handlers.go`, [`../architecture/model-registry.md`](../architecture/model-registry.md)) — so there is no static list to reproduce here; `GET /v1/models` is the list. diff --git a/docs/consumer/quickstart.md b/docs/consumer/quickstart.md index 6b41017a8d..938eb534d3 100644 --- a/docs/consumer/quickstart.md +++ b/docs/consumer/quickstart.md @@ -1,6 +1,6 @@ # Quickstart: first request in five steps -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` Get an API key from the console, list the models your key can use, and make your first chat completion against `https://api.darkbloom.dev` — first with `curl`, then from the OpenAI and Anthropic SDKs. For developers integrating the API; each step is one action. Route details for everything used here are in [`../reference/api-contracts.md`](../reference/api-contracts.md). diff --git a/docs/developer/build.md b/docs/developer/build.md index 1e830e5ded..fd0fd7db81 100644 --- a/docs/developer/build.md +++ b/docs/developer/build.md @@ -1,6 +1,6 @@ # Build -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` How to build every component of Darkbloom from a fresh clone: the Go coordinator, the Rust prompt-contract sidecar, the Swift provider CLI (with its @@ -88,6 +88,10 @@ understand what `make` runs. ### 3. Coordinator (Go) +The normal Go build includes the telemetry queue packages under +`coordinator/telemetry/`. Their API adapters link them into the same coordinator +binary; no separate worker executable or build flag is required. + The owned two-host Go fixture embeds `e2e/testbed/provider_host.py`; rebuild its test binary after helper or lifecycle changes. The CPU-only `TestPrepareConnectedInputBindings` check uses the actual fixture input/report diff --git a/docs/developer/historical-references.md b/docs/developer/historical-references.md index ead3711ebd..d8eb442622 100644 --- a/docs/developer/historical-references.md +++ b/docs/developer/historical-references.md @@ -1,6 +1,6 @@ # Open historical source references -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` Use this procedure to read the original source behind a frozen report when a file has moved or disappeared from the current tree. Reports keep their diff --git a/docs/developer/navigation.md b/docs/developer/navigation.md index d76103c39b..529a217603 100644 --- a/docs/developer/navigation.md +++ b/docs/developer/navigation.md @@ -1,6 +1,6 @@ # Find and organize code -> Last updated: 2026-09-13 · commit `2b6a10301` +> Last updated: 2026-09-13 · commit `a3493b5ac` Use this guide to find the code behind a behavior and place new files beside their owners. Start from the subsystem, then search for the request, command, @@ -18,7 +18,7 @@ Build and test prerequisites are in [build.md](build.md) and [test.md](test.md). | Behavior | Start here | |---|---| | API request handling, auth, attestation, dispatch | `coordinator/api/`; server construction in `server.go` (`NewServer`) | -| In-process metrics and routing telemetry writes | `coordinator/telemetry/metrics/`, `coordinator/telemetry/routequeue/`; API endpoint instrumentation stays at the request boundary | +| Metrics and asynchronous observation writes | `coordinator/telemetry/metrics/`, `coordinator/telemetry/routequeue/`, `coordinator/telemetry/profilequeue/`, `coordinator/telemetry/outcomequeue/`; API adapters supply request context and persistence dependencies | | Provider selection, admission, queueing | `coordinator/registry/`; request eligibility in `request_traits.go` (`providerEligibleForTraitsLocked`) | | Billing and durable state | `coordinator/billing/`, `coordinator/payments/`, `coordinator/store/` | | Provider inference, downloads, security, local serving | `provider-swift/Sources/ProviderCore/`; entrypoints in `provider-swift/Sources/darkbloom/` | diff --git a/docs/developer/test.md b/docs/developer/test.md index 9da7525ca1..101dd95529 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1,6 +1,6 @@ # Test -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` How to run the unit tests for each component, the end-to-end suite that boots a real coordinator + Swift provider against ephemeral Postgres, and the docs @@ -85,6 +85,15 @@ long pending prompt and a long arrival completing behind a short pending prompt. They use a real isolated coordinator and encrypted WebSocket providers with scripted compute. It does not require model downloads or production access. +Queue tests live with their owners in `coordinator/telemetry/profilequeue/` +and `coordinator/telemetry/outcomequeue/`. They cover nonblocking construction, +batch limits, quiet flushing, write failures and the outcome drain deadline. +The API keeps the live store-binding and full HTTP/accounting fixtures: + +```bash +go test -race ./coordinator/telemetry/profilequeue ./coordinator/telemetry/outcomequeue ./coordinator/api -run 'Profile|RequestOutcome|PersistenceSinks|FleetSample' +``` + The CI formatting step checks tracked Go files with `gofmt`. It excludes `docs/reports/evidence/`, whose captured source bytes are immutable and bound by evidence manifests. Live Go source remains subject to the formatting gate. diff --git a/docs/provider/beta-features.md b/docs/provider/beta-features.md index 6fb16bc4d5..f1c3cc8220 100644 --- a/docs/provider/beta-features.md +++ b/docs/provider/beta-features.md @@ -1,6 +1,6 @@ # Beta features -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` Turn experimental engine behaviour on or off per machine with `darkbloom beta`, which writes keys into `provider.toml` so every serve path (LaunchAgent daemon, diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index 8d76067b11..015d78b93e 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -1,6 +1,6 @@ # Provider CLI reference -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` Reference for the `darkbloom` command-line tool: every subcommand and flag, the files and identifiers it creates, the `provider.toml` keys it reads with their diff --git a/docs/provider/hardware-requirements.md b/docs/provider/hardware-requirements.md index ea5f3ce934..28635af267 100644 --- a/docs/provider/hardware-requirements.md +++ b/docs/provider/hardware-requirements.md @@ -1,6 +1,6 @@ # Provider hardware requirements -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` Reference for what a Mac needs to run the `darkbloom` provider: the minimum requirements, the chip families the provider distinguishes, which catalog diff --git a/docs/provider/quickstart.md b/docs/provider/quickstart.md index afbf173c3f..00eb882067 100644 --- a/docs/provider/quickstart.md +++ b/docs/provider/quickstart.md @@ -1,6 +1,6 @@ # Provider quickstart -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` From a fresh Apple Silicon Mac to a provider that is registered with the coordinator, linked to your account and serving. For operators; install, check, diff --git a/docs/provider/troubleshooting.md b/docs/provider/troubleshooting.md index 68c75aa816..ee0d45edeb 100644 --- a/docs/provider/troubleshooting.md +++ b/docs/provider/troubleshooting.md @@ -1,6 +1,6 @@ # Provider troubleshooting -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` Symptom → check → fix for the `darkbloom` provider: installer exits, `doctor` check names, service lifecycle, coordinator connection, updates, models and the diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index f927f887e2..1d8673c9f1 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1,6 +1,6 @@ # Configuration reference -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` Every environment variable read by the coordinator, the provider CLI (`darkbloom`), console-ui and admin-ui: accepted values, the compiled default, diff --git a/docs/reference/prediction-decision-telemetry.md b/docs/reference/prediction-decision-telemetry.md index 000bb0601e..8fdc858b23 100644 --- a/docs/reference/prediction-decision-telemetry.md +++ b/docs/reference/prediction-decision-telemetry.md @@ -1,6 +1,6 @@ # Prediction decision telemetry -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` Optional attempt records compare what the coordinator selected with what the provider decided. They explain decisions; they do not establish whether a diff --git a/docs/reference/protocol-messages.md b/docs/reference/protocol-messages.md index 3641dd047b..5c06b532cd 100644 --- a/docs/reference/protocol-messages.md +++ b/docs/reference/protocol-messages.md @@ -1,6 +1,6 @@ # Provider ↔ coordinator protocol messages -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` Every JSON frame on the provider WebSocket (`GET /ws/provider`), with the Go type, the Swift type, and the presence rule for each field. Go is the canon diff --git a/docs/reference/ssd-kv-cache.md b/docs/reference/ssd-kv-cache.md index 15717add42..da856d1960 100644 --- a/docs/reference/ssd-kv-cache.md +++ b/docs/reference/ssd-kv-cache.md @@ -1,6 +1,6 @@ # SSD KV cache reference -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` Exact on-disk format, paths, identity binding, environment knobs, size and eviction rules, and per-family reuse capability of the provider's encrypted SSD diff --git a/docs/reference/telemetry-inventory.md b/docs/reference/telemetry-inventory.md index b3e8cad5fe..4ed554275c 100644 --- a/docs/reference/telemetry-inventory.md +++ b/docs/reference/telemetry-inventory.md @@ -1,6 +1,6 @@ # Telemetry inventory -> Last updated: 2026-09-13 · commit `2b6a10301` +> Last updated: 2026-09-13 · commit `a3493b5ac` Every datum the system collects today, with its producer, sink, cadence and retention. Anything not on this page is not emitted by the code at this commit. @@ -230,7 +230,7 @@ Datadog's; nothing is stored locally. | `providers`, `provider_reputation` | one row per provider | `UpsertProvider`, `UpsertReputation`, throttled to 30 s | none | | `provider_sessions` | one row per WebSocket session | `OpenProviderSession`, `TouchProviderSession`, `CloseProviderSession` | none | | `provider_log_reports` | one row per uploaded bundle | `StoreLogReport` | none | -| `request_profiles` | one row per `(request_id, attempt)`, sampled | profile sink (`coordinator/api/profiler_sink.go`), batches of 64 or 250 ms | 14 d, hourly sweep, 5000-id windows | +| `request_profiles` | one row per `(request_id, attempt)`, sampled | `profilequeue.Sink` (`coordinator/telemetry/profilequeue/worker.go`), batches of 64 or 250 ms | 14 d, hourly sweep, 5000-id windows | | `fleet_snapshots` | one row per provider slot plus one `provider_id = "coordinator"` row | fleet sampler (`coordinator/api/profiler_fleet.go`) every 60 s | 30 d, same sweep | The retention sweep (`PruneTelemetry`, `coordinator/store/postgres_profiles.go`) diff --git a/docs/reference/telemetry-schema.md b/docs/reference/telemetry-schema.md index bf29254880..cef97d86c6 100644 --- a/docs/reference/telemetry-schema.md +++ b/docs/reference/telemetry-schema.md @@ -1,6 +1,6 @@ # Telemetry event schema -> Last updated: 2026-09-14 · commit `1edce05ca` +> Last updated: 2026-09-14 · commit `39bb12da8` The shape of a telemetry *event* as it exists in three mirrors (Go, Swift, TypeScript), the closed enums it carries, the field allowlist, and the tests