Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
67 changes: 67 additions & 0 deletions coordinator/api/persistence_sink_wiring_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}
2 changes: 1 addition & 1 deletion coordinator/api/profiler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 3 additions & 3 deletions coordinator/api/profiler_fleet.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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"})
Expand Down
2 changes: 1 addition & 1 deletion coordinator/api/profiler_record.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
166 changes: 17 additions & 149 deletions coordinator/api/profiler_sink.go
Original file line number Diff line number Diff line change
@@ -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"})
}
2 changes: 1 addition & 1 deletion coordinator/api/profiler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
}
Expand Down
4 changes: 2 additions & 2 deletions coordinator/api/request_outcome.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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) {
Expand Down
3 changes: 2 additions & 1 deletion coordinator/api/request_outcome_admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -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})
}
2 changes: 1 addition & 1 deletion coordinator/api/request_outcome_recovery_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
Expand Down
Loading
Loading