Skip to content

feat(coordinator): structured cancellation telemetry — phase/source/delivered/settlement (DAR-346) - #438

Closed
Gajesh2007 wants to merge 2 commits into
masterfrom
gajesh/dar-346-cancel-telemetry
Closed

Gajesh2007 wants to merge 2 commits into
masterfrom
gajesh/dar-346-cancel-telemetry

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented Jun 21, 2026 •

Copy link
Copy Markdown
Member

DAR-346 — Structured cancellation telemetry

Today the coordinator records most aborted requests as final_status=cancelled + error_class=client_gone — only "the HTTP client closed." Production shows the dominant mode is deliver first token fast → stream 10–75s → connection closes, with only a small fraction being TTFT SLA breaches. This persists a structured, queryable record of why each cancel happened, what we delivered, and how it settled — no prompt/response content, E2E preserved (ciphertext frames counted, never decrypted).

Coordinator-only — ships via a coordinator deploy; no provider release.

What's in it (by phase)

  • Phase 0 — 14 typed inference_routes columns + merge-on-nonzero bridge + memory/postgres stores + CSV; cancel_phase/cancel_source/partial_settlement_status derived centrally from the existing error_class (mirrors the error_reason/DAR-341 pattern).
  • Phase 1 — relay delivery measurement (guarded PendingRequest accumulator at the chat + Responses SSE forward sites): chunks_sent, bytes_sent, last_chunk_at, max_idle_gap_ms; stream_idle_timeout reclassification at ≥15s idle gap.
  • Phase 2 — Datadog inference.cancel{phase,source,model} + partial_settlement + delivered_tokens + bucketed stream.idle_gap (counter, not a histogram — histograms are dead on the agent-less EigenCloud TEE); 5 dashboard widgets; speculative losers excluded from external-cancel rates.
  • Phase 3a — exact estimated_delivered_tokens for settled cancels by reusing the provider's existing settlement (dc5a4136 floors delivered tokens into usage.completion_tokens) — no protocol change.

Acceptance criteria (DAR-346)

  • mid-stream client close after first token → cancel_phase=after_first_token + source + last_chunk_at + chunks_sent + delivered estimate ✓
  • pre-first-token disconnect → before_first_token ✓
  • speculative losers excluded from external client-cancel metrics ✓
  • partial-settlement status queryable ✓
  • Datadog split by phase/source/model ✓

Testing

  • go test ./... green across all 17 coordinator packages; gofmt/vet clean.
  • New: store cross-backend round-trip + merge-preservation, classifier table, idle-refine table, delivery population, UDP-captured metric emission.
  • ⚠️ TestInferenceRoute_Postgres ran only in the memory backend locally (Docker unavailable); CI's postgres:16 exercises the Postgres path. SQL placeholder/column-order consistency hand-verified.

Deferred → DAR-348 (P3)

Explicit InferenceComplete wire fields (cancel_acknowledged, last_generation_at) — marginal forensic value; needs Go+Swift protocol symmetry + a human-gated provider release.

🤖 Generated with Claude Code


View with Codesmith Autofix with Codesmith
Need help on this PR? Tag /codesmith with what you need. Autofix is disabled.

@vercel

vercel Bot commented Jun 21, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
d-inference Ready Ready Preview Jun 21, 2026 5:05am
d-inference-console-ui-dev Ready Ready Preview Jun 21, 2026 5:05am
d-inference-landing Ready Ready Preview Jun 21, 2026 5:05am

Request Review

@github-actions

github-actions Bot commented Jun 21, 2026 •

Copy link
Copy Markdown
Contributor

This PR adds cancellation telemetry instrumentation (delivery counters, cancel signal timestamps, provider-terminal flags) and is security-neutral — it does not strengthen or weaken any threat model control.


Trust Boundaries Touched

  • TB-002 — Coordinator ↔ Provider WebSocket (changes to provider.go and registry.go affect the inference settlement path)

Threat Analysis

Threat Status Notes
T-034 — Provider runs modified code while advertising trusted identity ℹ️ Neutral The new fields (ProviderTerminalReceived, ProviderTerminalAtMs, delivery counters) are observability-only. They record what happened after a cancel/error but do not alter the APNs code-identity round-trip, the CodeAttested routing gate, or the SE signature verification path. No security invariant is changed.

New Attack Surface

None introduced. Specifically:

  • RecordDeliveredChunk (registry.go:233) counts opaque ciphertext bytes forwarded to the client. The comment explicitly notes frames are never decrypted here — no plaintext prompt content flows through this path, so there is no new information-disclosure surface against A-001.
  • DeliverySnapshot() / CancelSignalSentAtSafe() / MarkCancelSignalSent() are all internal struct accessors guarded by existing mutexes (deliveryMu, timingMu). They are not exposed over any API surface.
  • outcome.ProviderTerminalReceived / outcome.ProviderTerminalAtMs in provider.go are written into the route outcome struct on the settlement path. If this struct is persisted to the store, verify that ProviderTerminalAtMs (millisecond epoch) is not surfaced to a consumer-visible API endpoint — doing so would be a minor timing oracle against T-037, but this cannot be confirmed from the diff alone.

Open Findings Resolved

None. No SEC-* findings are closed by this PR.


One flag for the reviewer: provider.go line context shows outcome.ProviderTerminalAtMs = time.Now().UnixMilli() written inside handleInferenceError. If RouteOutcome is serialised to a consumer-facing response or a public telemetry endpoint, the millisecond timestamp could marginally strengthen a timing-based inference about provider-side cancellation latency (relevant to T-037 / TB-002). Confirm ProviderTerminalAtMs is coordinator-internal only before merging.


🔐 Threat model: docs/threat-model.yaml · Updates on each push to this PR

@blacksmith-sh

blacksmith-sh Bot commented Jun 21, 2026 •

Copy link
Copy Markdown
Contributor

Found 1 test failure on Blacksmith runners:

Failure

Test View Logs
github.com/eigeninference/d-inference/e2e/TestIntegration_ConcurrentRequests View Logs

Fix with Codesmith
Need help on this PR? Tag /codesmith with what you need.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 807c747a17

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coordinator/cmd/coordinator/main.go Outdated
Comment on lines 697 to 703
// Graceful shutdown with a deadline.
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 15*time.Second)
defer shutdownCancel()

// DAR-327 merge note: when Phase 3 (#396) lands, srv.BroadcastGoingAway()
// belongs HERE — right after SetDraining(true) and BEFORE cancel() /
// WaitForInflightZero — so providers begin draining+reconnecting while we wait
// for in-flight HTTP to finish. The canonical combined shutdown order is:
// SetDraining → BroadcastGoingAway → cancel → WaitForInflightZero → Shutdown.
cancel() // Stop the eviction loop.

// Wait for already-admitted in-flight requests to finish before shutting the
// HTTP server down. Streaming responses can run well past the 15s Shutdown
// deadline, so we poll Inflight() until it reaches 0 or EIGENINFERENCE_DRAIN_GRACE
// (default 10m) elapses — whichever comes first — instead of cutting them off.
// We never block forever: the grace context bounds the wait, and the hard
// Shutdown deadline below is the final backstop.
grace := api.DrainGraceFromEnv()
graceCtx, graceCancel := context.WithTimeout(context.Background(), grace)
if srv.WaitForInflightZero(graceCtx) {
logger.Info("drain complete; in-flight requests finished", "grace", grace.String())
} else {
logger.Warn("drain grace elapsed; forcing shutdown with requests still in flight",
"grace", grace.String(), "inflight", srv.Inflight())
}
graceCancel()

// Hard backstop: even after the grace wait, give Shutdown a bounded deadline so
// a stuck connection can't block process exit forever.
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 15*time.Second)
defer shutdownCancel()
if err := httpServer.Shutdown(shutdownCtx); err != nil {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve long-running streams during shutdown

When EigenCloud sends SIGTERM while a streaming inference is active, this path now gives http.Server.Shutdown only 15 seconds and then lets the process exit. The previous drain path stopped new inference admission and waited up to EIGENINFERENCE_DRAIN_GRACE, which matters because streams can legitimately run well beyond 15 seconds; with this change those in-flight responses are cut off during routine deploys/restarts.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Resolved in 636391b. This was a revert artifact, not an intended change — the branch was squashed onto an advanced master, so the diff was accidentally reverting #393 (graceful drain). Rebased onto current origin/master; main.go and the drain path are no longer touched by this PR.

Comment thread coordinator/api/consumer.go Outdated
Comment on lines 2040 to 2041
if s.queueBeforeShedEnabled() {
s.ddIncr("routing.decisions", []string{"model:" + model, "model_type:" + s.registry.ModelType(model), "outcome:capacity_queue_spill"})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep dedicated models out of the queue

For dedicated-family models such as the previous default Gemma 4 isolation, this now enters the normal queue whenever queueBeforeShedEnabled() is true. When the dedicated boxes are saturated, the request can sit for the full queue timeout instead of returning the immediate 429/Retry-After that upstream routers use for clean failover, blowing the TTFT SLA for exactly the capacity-pressure case this special path handled.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Resolved in 636391b. Same root cause as the drain finding — the stale-base squash was accidentally reverting #434 (Gemma-4 dedicated routing / early 429 shed). Rebased onto current origin/master; the dedicated-model queue path is no longer touched.

Comment thread coordinator/api/route_outcome.go Outdated
Comment on lines +306 to +311
if snap.MaxIdleGapMs > 0 {
out.MaxIdleGapMs = snap.MaxIdleGapMs
}
// Refine a generic client-close into a stream-idle cancel when a measured
// no-progress gap preceded the close (provider stalled mid-stream).
out.CancelSource = refineCancelSourceForIdle(out.CancelSource, out.CancelPhase, snap.MaxIdleGapMs)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include the final idle gap before classifying cancels

The stream-idle reclassification only uses snap.MaxIdleGapMs, but that value is updated only when a later chunk arrives. In the common idle-timeout case where the last delivered chunk is followed by 15+ seconds of silence and then the client closes, there is no subsequent RecordDeliveredChunk call, so MaxIdleGapMs stays below the threshold and the cancel is persisted as client_closed instead of stream_idle_timeout.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 636391b. applyPendingRouteTelemetry now folds the trailing post-last-chunk gap (time.Since(lastChunkAt) up to cancel-build time) into the idle classification for after-first-token cancels, so a last-chunk → 15s silence → close is correctly labeled stream_idle_timeout. Bounded to cancellations so a normal completion's last-chunk→terminal lag does not inflate the metric.

Comment thread coordinator/api/route_outcome.go Outdated
Comment on lines +287 to +288
if out.CancelPhase != "" {
pr.MarkCancelSignalSent()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Stamp cancel signals when the cancel is sent

For post-commit client disconnects, the cleanup path parks the request and sends the provider cancel immediately, but it does not stamp cancelSignalSentAt; this fallback stamps only when the final outcome is later built, which can be after a provider terminal or after the 30s settlement grace expires. That makes cancel_signal_sent_at_ms late by seconds and corrupts cancel-to-terminal/grace-expiry analysis for the mid-stream cancels this telemetry is meant to diagnose.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 636391b. MarkCancelSignalSent() is now called in the post-commit cleanup defer's consumer-gone branch — at the actual provider-cancel send — so cancel_signal_sent_at_ms reflects send time rather than the later terminal/grace-expiry outcome-build time.

Comment thread coordinator/api/consumer.go Outdated
Comment on lines 2603 to 2604
pr.RecordDeliveredChunk(len(chunk))
emitter.handleChunk(chunk)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Count emitted Responses events, not provider chunks

For /v1/responses streams, emitter.handleChunk translates one provider chunk into zero or multiple client SSE events, while start/finish also emit their own events. Recording the raw provider chunk here before translation means chunks_sent, bytes_sent, and the delivered-token estimate do not represent what reached the client on mid-stream cancels, so DAR-346 delivery telemetry is inaccurate for Responses API requests.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 636391b. Delivery is now counted inside the Responses emitter (emit(), per emitted client event / len(data)), and the raw-provider-chunk RecordDeliveredChunk calls were removed from the relay loop — so chunks_sent/bytes_sent reflect what actually reached the client through the chunk→events translation.

Gajesh2007 added a commit that referenced this pull request Jun 21, 2026
… delivered tokens, settlement (DAR-346)

Persist a structured, queryable record of why each request cancel happened, what
was delivered before it, and how it settled — without storing prompt/response
content and preserving E2E (the coordinator counts opaque ciphertext frames,
never decrypts). Coordinator-only; ships via a coordinator deploy.

Phase 0 — classification persistence:
- 14 new inference_routes columns (cancel_phase, cancel_source,
  partial_settlement_status, settled_partial_tokens/micro_usd,
  cancel_signal_sent_at_ms, provider_terminal_received/at_ms,
  first/last_chunk_at_ms, chunks_sent, bytes_sent, estimated_delivered_tokens,
  max_idle_gap_ms), mirroring the error_reason (DAR-341) field-addition pattern.
- cancel_phase/source/settlement derived centrally from the existing error_class.

Phase 1 — relay delivery measurement:
- guarded PendingRequest accumulator populated at the chat + Responses SSE forward
  sites; counts ciphertext frames only.
- after-first-token client_closed reclassified to stream_idle_timeout when a
  measured no-progress gap >= 15s (incl. the trailing gap up to cancel time)
  preceded the close.

Phase 2 — Datadog metrics + dashboard:
- inference.cancel{phase,source,model}, .partial_settlement, .delivered_tokens,
  stream.idle_gap (bucketed COUNTER, not a histogram — histograms emit nothing on
  the agent-less EigenCloud TEE). 5 widgets; speculative losers excluded.

Phase 3a — exact delivered tokens:
- reuse the provider's existing mid-cancel settlement (dc5a413 floors delivered
  tokens into usage.completion_tokens) as the exact estimated_delivered_tokens
  for settled cancels — no protocol change. Deferred wire fields tracked in DAR-348.

Review fixes (PR #438):
- postgres: cast BIGINT placeholders to ::bigint in UpdateInferenceRouteOutcome —
  Postgres inferred $N as int4 from `$N <> 0`, overflowing on epoch-ms timestamps
  (TestInferenceRoute_Postgres failure).
- stamp cancel_signal_sent_at on the actual provider-cancel send (post-commit
  disconnect path), not late at outcome-build.
- count Responses delivery per emitted client event (in the emitter), not per raw
  provider chunk.
- fold the trailing post-last-chunk idle gap into the stream-idle classification.
@Gajesh2007
Gajesh2007 force-pushed the gajesh/dar-346-cancel-telemetry branch from 807c747 to 636391b Compare June 21, 2026 03:02
@Gajesh2007

Copy link
Copy Markdown
Member Author

@codex review

Note for this pass: the previous review ran against 807c747a, which (due to a stale-base squash) was accidentally reverting #393 and #434 — two of those findings were revert artifacts, not intended changes. That's been fixed by rebasing onto current master and force-pushing 636391b7, which now has a telemetry-only diff. Please review the current commit. The three real findings (trailing idle-gap, cancel-signal stamp timing, Responses event counting) are addressed in 636391b7.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 636391b710

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coordinator/api/route_outcome.go Outdated
Comment on lines +312 to +314
if out.CancelPhase == cancelPhaseAfterFirstToken && !snap.LastChunkAt.IsZero() {
if trailing := float64(time.Since(snap.LastChunkAt).Milliseconds()); trailing > idleGapMs {
idleGapMs = trailing

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bound idle gap at the cancel timestamp

When a streamed request is canceled after at least one chunk and the provider terminal is delayed or never arrives, this code can run from the terminal/grace-expiry path rather than at the client close; time.Since(snap.LastChunkAt) therefore includes the settlement wait after the cancel. A user abort immediately after a chunk can cross the 15s threshold simply because the provider terminal arrives late (or the 30s grace expires), causing the row and Datadog metric to be misclassified as stream_idle_timeout; use the recorded cancel-signal time as the upper bound instead of time.Now().

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 868e145. The trailing gap is now bounded at the cancel-signal time (CancelSignalSentAtSafe() ≈ client close), not time.Now(). Since applyPendingRouteTelemetry can run from the terminal/grace path up to 30s after the close, using the cancel timestamp prevents the settlement wait from inflating the gap and misclassifying a quick user-abort as stream_idle_timeout. Falls back to no trailing fold when the cancel time is unset.

Comment thread coordinator/api/route_outcome.go Outdated
Comment on lines +287 to +288
if out.CancelPhase != "" {
pr.MarkCancelSignalSent()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Stamp cancel signals only at actual sends

When a queued request is canceled before any provider is assigned (e.g. the queue cancel branches in consumer.go/dispatch.go), this unconditional MarkCancelSignalSent writes cancel_signal_sent_at_ms even though no cancel can be sent to a provider. The same fallback also masks send sites that are not marked (the generic post-commit defer sends the provider cancel directly), so those rows get terminal/grace-expiry time instead of the actual send time. This makes the new field unreliable for measuring provider cancel latency; stamp only in the WS-cancel send paths and leave it unset when there was no provider.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 868e145. Removed the build-time fallback MarkCancelSignalSent. cancel_signal_sent_at_ms is now stamped ONLY at actual WS-cancel send sites (cancelDispatch and the post-commit disconnect defer) and left unset when no provider cancel was sent (queued-before-assignment cancels). It is never backfilled to terminal/grace-expiry time. Test updated to assert it is unset without a real send and set after one.

Comment thread coordinator/api/consumer.go Outdated
Comment on lines 2405 to 2406
pr.RecordDeliveredChunk(len(firstChunk))
fmt.Fprintf(w, "%s\n\n", firstChunk)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Count only successfully written chunks

This increments delivery telemetry before attempting the SSE write, so if the client has already disconnected or the write fails, the request still records a delivered chunk/token and updates last_chunk_at_ms. For disconnects around the first streamed chunk, that can turn a zero-delivered client close into an after-first-token cancellation with nonzero delivered counts; record the chunk only after checking the fmt.Fprintf error succeeds.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 868e145. Both chat relay sites and the Responses emitter now record the chunk only when the fmt.Fprintf write returns no error, so a disconnect/failed write around the first chunk no longer turns a zero-delivered close into an after-first-token cancel with nonzero delivered counts / last_chunk_at_ms.

… delivered tokens, settlement (DAR-346)

Persist a structured, queryable record of why each request cancel happened, what
was delivered before it, and how it settled — without storing prompt/response
content and preserving E2E (the coordinator counts opaque ciphertext frames,
never decrypts). Coordinator-only; ships via a coordinator deploy.

Phase 0 — classification persistence: 14 new inference_routes columns
(cancel_phase, cancel_source, partial_settlement_status, settled_partial_*,
cancel_signal_sent_at_ms, provider_terminal_received/at_ms, first/last_chunk_at_ms,
chunks_sent, bytes_sent, estimated_delivered_tokens, max_idle_gap_ms), mirroring
the error_reason (DAR-341) pattern; phase/source/settlement derived centrally from
the existing error_class.

Phase 1 — relay delivery measurement: guarded PendingRequest accumulator at the
chat + Responses SSE forward sites (ciphertext frames only); after-first-token
client_closed reclassified to stream_idle_timeout on a measured >=15s no-progress
gap (incl. the trailing gap, bounded at the cancel-signal time).

Phase 2 — Datadog metrics + dashboard: inference.cancel{phase,source,model},
.partial_settlement, .delivered_tokens, stream.idle_gap (bucketed COUNTER — not a
histogram, which emits nothing on the agent-less EigenCloud TEE). 5 widgets;
speculative losers excluded.

Phase 3a — exact delivered tokens: reuse the provider's existing mid-cancel
settlement (dc5a413 floors delivered tokens into usage.completion_tokens) for
settled cancels — no protocol change. Deferred wire fields tracked in DAR-348.

Review fixes (PR #438):
- postgres: cast BIGINT placeholders to ::bigint in UpdateInferenceRouteOutcome
  (Postgres inferred $N as int4 from `$N <> 0`, overflowing on epoch-ms).
- cancel_signal_sent_at: stamp ONLY at actual WS-cancel send sites (cancelDispatch,
  post-commit disconnect defer); never backfilled to terminal/grace time, unset
  when no provider cancel was sent.
- idle gap: bound the trailing gap at the cancel-signal time, not time.Now(), so a
  late terminal / 30s grace cannot inflate it into a false stream_idle_timeout.
- delivery counting: count Responses delivery per emitted client event (in the
  emitter), and only count chunks whose SSE write actually succeeded.
@Gajesh2007

Copy link
Copy Markdown
Member Author

@codex review

Round-2 findings addressed in 868e145: idle gap now bounded at the cancel-signal time (not time.Now()); cancel_signal_sent_at stamped only at actual WS-cancel sends (no build-time fallback, unset when no provider); delivery counted only on successful SSE writes, and Responses delivery counted per emitted event.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 251e454c1a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +285 to +286
if ts := pr.CancelSignalSentAtSafe(); !ts.IsZero() {
out.CancelSignalSentAtMs = ts.UnixMilli()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Stamp generic post-commit cancels before persisting telemetry

For committed /v1/completions and /v1/messages streams where the client disconnects, the generic cleanup defer in consumer.go still parks the request and calls sendProviderCancel without MarkCancelSignalSent (checked the defer around lines 5652-5664). Because this new telemetry path only copies CancelSignalSentAtSafe() and never backfills it, those actual provider-cancel sends persist no cancel_signal_sent_at_ms, and the trailing idle-gap refinement cannot run, so DAR-346 rows/metrics for those endpoints underreport cancel latency and can miss stream_idle_timeout. Fresh evidence: this second post-commit defer remains unmarked in ed390f4 even though the chat-completions defer was updated.

Useful? React with 👍 / 👎.

out.SettledPartialTokens = usage.CompletionTokens
out.SettledPartialMicroUSD = costMicroUSD
out.ProviderTerminalReceived = true
out.ProviderTerminalAtMs = time.Now().UnixMilli()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Capture provider terminal time before billing work

When a provider completes after the client has disconnected, handleComplete performs settlement and waits on billing/credit work before calling completeRouteOutcome; this stamps provider_terminal_at_ms at outcome-build time rather than when the terminal message was received. Under DB or ledger latency, the recorded terminal can be seconds late, inflating cancel-to-terminal measurements for settled cancellations even when the provider responded promptly; capture the terminal arrival at the start of handleComplete and pass that timestamp through.

Useful? React with 👍 / 👎.

// settlement-grace-expiry path that records no terminal (DAR-346).
outcome.ProviderTerminalReceived = true
outcome.ProviderTerminalAtMs = time.Now().UnixMilli()
s.updateInferenceRouteOutcomeForPending(pr, outcome)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Persist refunded status only after refund succeeds

In the after-disconnect provider-error path, pendingRouteOutcomeWithReason derives partial_settlement_status=refunded and this update is persisted before the asynchronous refundReservedBalance call actually runs. If the store credit fails or stalls under the DB pressure this path is explicitly avoiding, the route row and cancellation metrics still say the partial was refunded even though the reservation was not finalized; move the telemetry update behind a successful refund or use a non-final status until the refund completes.

Useful? React with 👍 / 👎.

Comment on lines +112 to +113
if source == cancelSourceClientClosed && phase == cancelPhaseAfterFirstToken && maxIdleGapMs >= streamIdleGapThresholdMs {
return cancelSourceStreamIdleTimeout

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reclassify idle closes for settled cancellations too

A client can close after a long no-progress gap, then the provider can still finish during the settlement grace; that outcome uses cancel_phase=after_provider_complete, so this predicate skips the trailing-gap upgrade and persists cancel_source=client_closed instead of stream_idle_timeout. Fresh evidence: the new settled-cancel path sets after_provider_complete, but the idle refinement only accepts after_first_token, so OpenRouter-style idle closes are missed exactly when the provider terminal eventually arrives.

Useful? React with 👍 / 👎.

Comment on lines +162 to +163
if _, werr := fmt.Fprintf(e.w, "event: %s\ndata: %s\n\n", eventType, data); werr == nil {
e.pr.RecordDeliveredChunk(len(data))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Don't treat Responses lifecycle events as delivered tokens

For /v1/responses streams, this hook runs for every emitted SSE event, including response.created, response.in_progress, item-added/done, and other lifecycle events that are not model output tokens. applyPendingRouteTelemetry later uses ChunksSent as EstimatedDeliveredTokens when no provider terminal arrives, so an early disconnect after only the initial Responses events records nonzero delivered tokens; keep chunks_sent/bytes_sent per emitted event, but feed the token estimate only from content/reasoning delta events.

Useful? React with 👍 / 👎.

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated Code Review — Layr-Labs/d-inference#

Verdict: REQUEST_CHANGES

Security — ✅ No issues found

Performance — 5 finding(s) (4 blocking)

  • 🟡 [MEDIUM] coordinator/api/consumer.go:2427-2430 — Synchronous fmt.Fprintf in hot streaming path without error handling optimization
    • Suggestion: Consider buffering writes or using a non-blocking approach for delivery counting to avoid blocking the streaming response on slow client connections
  • 🟡 [MEDIUM] coordinator/api/consumer.go:2585-2588 — Synchronous fmt.Fprintf in streaming loop without error handling optimization
    • Suggestion: Consider buffering writes or using a non-blocking approach for delivery counting to avoid blocking the streaming response on slow client connections
  • 🟡 [MEDIUM] coordinator/api/responses_stream.go:162-165 — Synchronous fmt.Fprintf in SSE emitter with delivery counting
    • Suggestion: Consider buffering writes or using a non-blocking approach for delivery counting to avoid blocking SSE events on slow client connections
  • 🔵 [INFO] coordinator/registry/registry.go:237-250 — Mutex-guarded delivery tracking on every chunk in hot streaming path
    • Suggestion: Consider using atomic counters or batching delivery updates to reduce mutex contention in high-throughput streaming scenarios
  • 🟡 [MEDIUM] coordinator/store/postgres.go:1741-1768 — Large UPDATE query with 37 parameters executed on every outcome update
    • Suggestion: Consider batching outcome updates or using a more efficient update strategy to reduce database load and query parsing overhead

Type_diligence — ✅ No issues found

Additive_complexity — 9 finding(s) (6 blocking)

  • 🟡 [MEDIUM] coordinator/api/cancel_classify.go:1-139 — New file with 139 lines of classification logic that could be simplified
    • Suggestion: Consider consolidating the three separate derivation functions into a single function that returns a struct with all three fields, reducing code duplication and making the logic easier to follow
  • 🔵 [INFO] coordinator/api/cancel_classify_test.go:1-186 — Test file has repetitive test case structures
    • Suggestion: Extract common test case validation logic into helper functions to reduce duplication across test methods
  • 🔵 [INFO] coordinator/api/cancel_metrics.go:1-68 — Multiple metric constants and bucketing logic for what appears to be a single feature
    • Suggestion: Consider if all these separate metrics are necessary or if a single metric with different tags would suffice
  • 🔴 [CRITICAL] coordinator/store/interface.go:765-784 — Adding 14 new fields to InferenceRouteRecord struct significantly increases complexity
    • Suggestion: Consider grouping related cancellation fields into a nested struct (e.g., CancellationTelemetry) to reduce the surface area of the main record struct
  • 🔴 [CRITICAL] coordinator/store/interface.go:818-837 — Identical 14 fields duplicated in InferenceRouteOutcome struct
    • Suggestion: Extract cancellation fields into a shared struct that both InferenceRouteRecord and InferenceRouteOutcome can embed to eliminate duplication
  • 🟡 [MEDIUM] coordinator/store/postgres.go:825-840 — Adding 14 new database columns increases schema complexity
    • Suggestion: Consider if all these fields need to be in the main table or if some could be in a separate cancellation_telemetry table with a foreign key
  • 🟡 [MEDIUM] coordinator/store/postgres.go:884-898 — Repetitive ALTER TABLE statements for adding columns
    • Suggestion: Group related columns into fewer ALTER statements or consider a migration script approach
  • 🟡 [MEDIUM] coordinator/store/route_telemetry.go:74-118 — 46 lines of repetitive field merging logic following identical patterns
    • Suggestion: Extract the merge pattern into a helper function or use reflection to reduce the boilerplate code
  • 🔵 [INFO] coordinator/registry/registry.go:207-272 — Adding delivery tracking state and methods increases PendingRequest complexity
    • Suggestion: Consider extracting delivery tracking into a separate component that PendingRequest can compose rather than adding more fields and methods directly

14 finding(s) total, 10 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated Code Review — Layr-Labs/d-inference#

Verdict: REQUEST_CHANGES

Security — ✅ No issues found

Performance — 5 finding(s) (4 blocking)

  • 🟡 [MEDIUM] coordinator/api/consumer.go:2426-2430 — fmt.Fprintf write error check blocks SSE streaming on hot path
    • Suggestion: Move error handling to separate goroutine or use non-blocking write with buffering to avoid blocking the streaming response loop
  • 🟡 [MEDIUM] coordinator/api/consumer.go:2584-2588 — fmt.Fprintf write error check blocks SSE streaming on hot path
    • Suggestion: Move error handling to separate goroutine or use non-blocking write with buffering to avoid blocking the streaming response loop
  • 🟡 [MEDIUM] coordinator/api/responses_stream.go:161-165 — fmt.Fprintf write error check blocks SSE streaming on hot path
    • Suggestion: Move error handling to separate goroutine or use non-blocking write with buffering to avoid blocking the streaming response loop
  • 🔵 [INFO] coordinator/registry/registry.go:238-250 — time.Now() called twice per chunk in RecordDeliveredChunk
    • Suggestion: Call time.Now() once and reuse the value for both gap calculation and lastChunkAt assignment
  • 🟡 [MEDIUM] coordinator/store/postgres.go:1741-1767 — Large SQL UPDATE with 37 parameters may cause memory pressure
    • Suggestion: Consider batching updates or using a more efficient update strategy for high-frequency telemetry updates

Type_diligence — ✅ No issues found

Additive_complexity — 7 finding(s) (6 blocking)

  • 🟡 [MEDIUM] coordinator/api/cancel_classify.go:1-139 — New file with 139 lines of classification logic that could be simplified
    • Suggestion: Consider consolidating the three separate derivation functions into a single function that returns a struct with all three fields, reducing code duplication and making the logic easier to follow
  • 🔵 [INFO] coordinator/api/cancel_metrics.go:1-68 — Separate metrics emission file for what could be inline logic
    • Suggestion: Consider inlining the simple metric emission logic into the main outcome update function rather than creating a separate file and function
  • 🔴 [CRITICAL] coordinator/store/interface.go:765-784 — Adding 14 new fields to InferenceRouteRecord struct significantly increases data model complexity
    • Suggestion: Consider grouping related cancellation fields into a nested struct (e.g., CancellationTelemetry) to reduce the surface area of the main record struct
  • 🔴 [CRITICAL] coordinator/store/interface.go:818-837 — Identical 14 cancellation fields duplicated in InferenceRouteOutcome struct
    • Suggestion: Extract cancellation fields into a shared struct that both InferenceRouteRecord and InferenceRouteOutcome can embed to eliminate duplication
  • 🟡 [MEDIUM] coordinator/store/postgres.go:825-840 — Adding 14 new database columns increases schema complexity
    • Suggestion: Consider using a JSONB column for cancellation telemetry data instead of 14 separate columns to reduce schema bloat
  • 🟡 [MEDIUM] coordinator/store/route_telemetry.go:74-118 — 44 lines of repetitive merge logic for cancellation fields
    • Suggestion: Use reflection or a helper function to reduce the repetitive merge pattern for the 14 cancellation fields
  • 🟡 [MEDIUM] coordinator/registry/registry.go:207-271 — Adding delivery tracking state and methods to PendingRequest increases struct complexity
    • Suggestion: Consider extracting delivery tracking into a separate DeliveryTracker struct that PendingRequest can compose, reducing the main struct's responsibility

12 finding(s) total, 10 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated Code Review — Layr-Labs/d-inference#

Verdict: REQUEST_CHANGES

Security — ✅ No issues found

Performance — 6 finding(s) (6 blocking)

  • 🟡 [MEDIUM] coordinator/api/consumer.go:2426-2430 — fmt.Fprintf write error check blocks SSE streaming hot path
    • Suggestion: Move error handling to separate goroutine or use non-blocking write with buffering
  • 🟡 [MEDIUM] coordinator/api/consumer.go:2584-2588 — fmt.Fprintf write error check blocks SSE streaming hot path
    • Suggestion: Move error handling to separate goroutine or use non-blocking write with buffering
  • 🟡 [MEDIUM] coordinator/api/responses_stream.go:161-165 — fmt.Fprintf write error check blocks SSE streaming hot path
    • Suggestion: Move error handling to separate goroutine or use non-blocking write with buffering
  • 🟡 [MEDIUM] coordinator/registry/registry.go:238-268 — RecordDeliveredChunk called on every SSE frame with mutex lock
    • Suggestion: Use atomic counters or batch updates to reduce lock frequency
  • 🟡 [MEDIUM] coordinator/store/postgres.go:1741-1768 — Large UPDATE query with 37 parameters executed on every outcome update
    • Suggestion: Split into separate queries for different update types or use prepared statements
  • 🟡 [MEDIUM] coordinator/api/cancel_metrics.go:49-67 — Multiple Datadog metric emissions per cancellation outcome
    • Suggestion: Batch metric emissions or use single metric with multiple tags

Type_diligence — ✅ No issues found

Additive_complexity — 7 finding(s) (6 blocking)

  • 🟡 [MEDIUM] coordinator/api/cancel_classify.go:1-139 — New file with 139 lines of classification logic that could be simplified
    • Suggestion: Consider consolidating the three separate derivation functions into a single function that returns a struct with all three fields, reducing code duplication and making the logic easier to follow
  • 🔵 [INFO] coordinator/api/cancel_metrics.go:1-68 — Separate metrics emission file for what could be inline logic
    • Suggestion: Consider inlining the simple metric emission logic into the main outcome update function rather than creating a separate file and function
  • 🔴 [CRITICAL] coordinator/store/interface.go:765-784 — Adding 14 new fields to InferenceRouteRecord struct significantly increases data model complexity
    • Suggestion: Consider grouping related cancellation fields into a nested struct (e.g., CancellationTelemetry) to reduce the surface area of the main record struct
  • 🔴 [CRITICAL] coordinator/store/interface.go:818-837 — Identical 14 cancellation fields duplicated in InferenceRouteOutcome struct
    • Suggestion: Extract cancellation fields into a shared struct that both InferenceRouteRecord and InferenceRouteOutcome can embed to eliminate duplication
  • 🟡 [MEDIUM] coordinator/store/postgres.go:825-840 — Adding 14 new database columns increases schema complexity
    • Suggestion: Consider using a JSONB column for cancellation telemetry data instead of 14 separate columns to reduce schema bloat
  • 🟡 [MEDIUM] coordinator/store/route_telemetry.go:74-118 — 44 lines of repetitive merge logic for cancellation fields
    • Suggestion: Use reflection or a helper function to reduce the repetitive merge pattern for the 14 cancellation fields
  • 🟡 [MEDIUM] coordinator/registry/registry.go:207-271 — Adding delivery tracking state and methods to PendingRequest increases struct complexity
    • Suggestion: Consider extracting delivery tracking into a separate component that PendingRequest can reference, reducing the responsibility of the registry struct

13 finding(s) total, 12 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

Comment on lines 2426 to +2430
firstChunk = rewriteChunkModel(firstChunk, pr)
fmt.Fprintf(w, "%s\n\n", firstChunk)
// Count only what was actually written: a failed write to a gone client
// must not record a delivered chunk (DAR-346).
if _, werr := fmt.Fprintf(w, "%s\n\n", firstChunk); werr == nil {
pr.RecordDeliveredChunk(len(firstChunk))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [MEDIUM] ⚡ fmt.Fprintf write error check blocks SSE streaming hot path

💡 Suggestion: Move error handling to separate goroutine or use non-blocking write with buffering

📊 Score: 3×4 = 12 · Category: blocking_io

Comment on lines 2584 to +2588
chunk = rewriteChunkModel(chunk, pr)
fmt.Fprintf(w, "%s\n\n", chunk)
// Count only what was actually written: a failed write to a gone client
// must not record a delivered chunk (DAR-346).
if _, werr := fmt.Fprintf(w, "%s\n\n", chunk); werr == nil {
pr.RecordDeliveredChunk(len(chunk))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [MEDIUM] ⚡ fmt.Fprintf write error check blocks SSE streaming hot path

💡 Suggestion: Move error handling to separate goroutine or use non-blocking write with buffering

📊 Score: 3×4 = 12 · Category: blocking_io

Comment on lines +161 to 165
// and only when the write succeeds (a gone client must not be counted).
if _, werr := fmt.Fprintf(e.w, "event: %s\ndata: %s\n\n", eventType, data); werr == nil {
e.pr.RecordDeliveredChunk(len(data))
}
e.flusher.Flush()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [MEDIUM] ⚡ fmt.Fprintf write error check blocks SSE streaming hot path

💡 Suggestion: Move error handling to separate goroutine or use non-blocking write with buffering

📊 Score: 3×4 = 12 · Category: blocking_io

Comment on lines +238 to +268
func (pr *PendingRequest) RecordDeliveredChunk(byteLen int) {
if pr == nil {
return
}
now := time.Now()
pr.deliveryMu.Lock()
if !pr.lastChunkAt.IsZero() {
if gap := float64(now.Sub(pr.lastChunkAt).Milliseconds()); gap > pr.maxIdleGapMs {
pr.maxIdleGapMs = gap
}
}
pr.deliveredChunks++
if byteLen > 0 {
pr.deliveredBytes += int64(byteLen)
}
pr.lastChunkAt = now
pr.deliveryMu.Unlock()
}

// DeliverySnapshot returns the current delivery counters under deliveryMu. Safe
// to call from a goroutine other than the relay (e.g. the provider terminal).
func (pr *PendingRequest) DeliverySnapshot() DeliveryStats {
if pr == nil {
return DeliveryStats{}
}
pr.deliveryMu.Lock()
defer pr.deliveryMu.Unlock()
return DeliveryStats{
Chunks: pr.deliveredChunks,
Bytes: pr.deliveredBytes,
LastChunkAt: pr.lastChunkAt,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [MEDIUM] ⚡ RecordDeliveredChunk called on every SSE frame with mutex lock

💡 Suggestion: Use atomic counters or batch updates to reduce lock frequency

📊 Score: 2×5 = 10 · Category: mutex_contention

Comment on lines 1741 to 1768
admitted_but_failed = COALESCE(admitted_but_failed, FALSE) OR $21,
used_backup = COALESCE(used_backup, FALSE) OR $22,
backup_won = COALESCE(backup_won, FALSE) OR $23,
cancel_phase = COALESCE(NULLIF($24, ''), cancel_phase),
cancel_source = COALESCE(NULLIF($25, ''), cancel_source),
partial_settlement_status = COALESCE(NULLIF($26, ''), partial_settlement_status),
settled_partial_tokens = CASE WHEN $27 <> 0 THEN $27 ELSE settled_partial_tokens END,
settled_partial_micro_usd = CASE WHEN $28::bigint <> 0 THEN $28::bigint ELSE settled_partial_micro_usd END,
cancel_signal_sent_at_ms = CASE WHEN $29::bigint <> 0 THEN $29::bigint ELSE cancel_signal_sent_at_ms END,
provider_terminal_received = COALESCE(provider_terminal_received, FALSE) OR $30,
provider_terminal_at_ms = CASE WHEN $31::bigint <> 0 THEN $31::bigint ELSE provider_terminal_at_ms END,
first_chunk_at_ms = CASE WHEN $32::bigint <> 0 THEN $32::bigint ELSE first_chunk_at_ms END,
last_chunk_at_ms = CASE WHEN $33::bigint <> 0 THEN $33::bigint ELSE last_chunk_at_ms END,
chunks_sent = CASE WHEN $34 <> 0 THEN $34 ELSE chunks_sent END,
bytes_sent = CASE WHEN $35::bigint <> 0 THEN $35::bigint ELSE bytes_sent END,
estimated_delivered_tokens = CASE WHEN $36 <> 0 THEN $36 ELSE estimated_delivered_tokens END,
max_idle_gap_ms = CASE WHEN $37 <> 0 THEN $37 ELSE max_idle_gap_ms END,
updated_at = NOW()
WHERE request_id = $1 AND attempt = $2`,
requestID, attempt,
outcome.FinalStatus, outcome.ErrorCode, outcome.ErrorClass, outcome.ErrorReason, outcome.PromptTokens, outcome.CompletionTokens, outcome.ReasoningTokens,
outcome.CostMicroUSD, outcome.ActualTTFTMs, outcome.DispatchToFirstChunkMs, outcome.TotalDurationMs,
outcome.ParseMs, outcome.ReserveMs, outcome.RouteMs, outcome.EncryptMs, outcome.QueueWaitMs, outcome.DispatchMs, outcome.ActualDecodeTPS,
outcome.AdmittedButFailed, outcome.UsedBackup, outcome.BackupWon,
outcome.CancelPhase, outcome.CancelSource, outcome.PartialSettlementStatus, outcome.SettledPartialTokens, outcome.SettledPartialMicroUSD,
outcome.CancelSignalSentAtMs, outcome.ProviderTerminalReceived, outcome.ProviderTerminalAtMs,
outcome.FirstChunkAtMs, outcome.LastChunkAtMs, outcome.ChunksSent, outcome.BytesSent, outcome.EstimatedDeliveredTokens, outcome.MaxIdleGapMs,
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [MEDIUM] ⚡ Large UPDATE query with 37 parameters executed on every outcome update

💡 Suggestion: Split into separate queries for different update types or use prepared statements

📊 Score: 4×3 = 12 · Category: database_query

Comment on lines +765 to 784
// DAR-346 structured cancellation telemetry. Timestamps are epoch
// milliseconds (0 = unset) so they ride the numeric merge-on-nonzero path.
// Every field is a count, timestamp, or normalized enum — never content.
CancelPhase string `json:"cancel_phase,omitempty"`
CancelSource string `json:"cancel_source,omitempty"`
PartialSettlementStatus string `json:"partial_settlement_status,omitempty"`
SettledPartialTokens int `json:"settled_partial_tokens,omitempty"`
SettledPartialMicroUSD int64 `json:"settled_partial_micro_usd,omitempty"`
CancelSignalSentAtMs int64 `json:"cancel_signal_sent_at_ms,omitempty"`
ProviderTerminalReceived bool `json:"provider_terminal_received,omitempty"`
ProviderTerminalAtMs int64 `json:"provider_terminal_at_ms,omitempty"`
FirstChunkAtMs int64 `json:"first_chunk_at_ms,omitempty"`
LastChunkAtMs int64 `json:"last_chunk_at_ms,omitempty"`
ChunksSent int `json:"chunks_sent,omitempty"`
BytesSent int64 `json:"bytes_sent,omitempty"`
EstimatedDeliveredTokens int `json:"estimated_delivered_tokens,omitempty"`
MaxIdleGapMs float64 `json:"max_idle_gap_ms,omitempty"`

CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 [CRITICAL] 🧩 Adding 14 new fields to InferenceRouteRecord struct significantly increases data model complexity

💡 Suggestion: Consider grouping related cancellation fields into a nested struct (e.g., CancellationTelemetry) to reduce the surface area of the main record struct

📊 Score: 4×4 = 16 · Category: additive complexity

Comment on lines +818 to 837

// DAR-346 structured cancellation telemetry. Timestamps are epoch
// milliseconds (0 = unset) so they ride the numeric merge-on-nonzero path.
// Every field is a count, timestamp, or normalized enum — never content.
CancelPhase string `json:"cancel_phase,omitempty"`
CancelSource string `json:"cancel_source,omitempty"`
PartialSettlementStatus string `json:"partial_settlement_status,omitempty"`
SettledPartialTokens int `json:"settled_partial_tokens,omitempty"`
SettledPartialMicroUSD int64 `json:"settled_partial_micro_usd,omitempty"`
CancelSignalSentAtMs int64 `json:"cancel_signal_sent_at_ms,omitempty"`
ProviderTerminalReceived bool `json:"provider_terminal_received,omitempty"`
ProviderTerminalAtMs int64 `json:"provider_terminal_at_ms,omitempty"`
FirstChunkAtMs int64 `json:"first_chunk_at_ms,omitempty"`
LastChunkAtMs int64 `json:"last_chunk_at_ms,omitempty"`
ChunksSent int `json:"chunks_sent,omitempty"`
BytesSent int64 `json:"bytes_sent,omitempty"`
EstimatedDeliveredTokens int `json:"estimated_delivered_tokens,omitempty"`
MaxIdleGapMs float64 `json:"max_idle_gap_ms,omitempty"`
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 [CRITICAL] 🧩 Identical 14 cancellation fields duplicated in InferenceRouteOutcome struct

💡 Suggestion: Extract cancellation fields into a shared struct that both InferenceRouteRecord and InferenceRouteOutcome can embed to eliminate duplication

📊 Score: 4×4 = 16 · Category: duplicate logic

Comment on lines +825 to 840
cancel_phase TEXT,
cancel_source TEXT,
partial_settlement_status TEXT,
settled_partial_tokens INTEGER,
settled_partial_micro_usd BIGINT,
cancel_signal_sent_at_ms BIGINT,
provider_terminal_received BOOL,
provider_terminal_at_ms BIGINT,
first_chunk_at_ms BIGINT,
last_chunk_at_ms BIGINT,
chunks_sent INTEGER,
bytes_sent BIGINT,
estimated_delivered_tokens INTEGER,
max_idle_gap_ms DOUBLE PRECISION,
UNIQUE(request_id, attempt)
)`,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [MEDIUM] 🧩 Adding 14 new database columns increases schema complexity

💡 Suggestion: Consider using a JSONB column for cancellation telemetry data instead of 14 separate columns to reduce schema bloat

📊 Score: 3×3 = 9 · Category: additive complexity

Comment on lines +74 to 118
// DAR-346 cancellation telemetry: same non-zero = "present" rule. Strings
// merge on non-empty, numerics/timestamps on non-zero, the bool on set.
if src.CancelPhase != "" {
dst.CancelPhase = src.CancelPhase
}
if src.CancelSource != "" {
dst.CancelSource = src.CancelSource
}
if src.PartialSettlementStatus != "" {
dst.PartialSettlementStatus = src.PartialSettlementStatus
}
if src.SettledPartialTokens != 0 {
dst.SettledPartialTokens = src.SettledPartialTokens
}
if src.SettledPartialMicroUSD != 0 {
dst.SettledPartialMicroUSD = src.SettledPartialMicroUSD
}
if src.CancelSignalSentAtMs != 0 {
dst.CancelSignalSentAtMs = src.CancelSignalSentAtMs
}
if src.ProviderTerminalReceived {
dst.ProviderTerminalReceived = true
}
if src.ProviderTerminalAtMs != 0 {
dst.ProviderTerminalAtMs = src.ProviderTerminalAtMs
}
if src.FirstChunkAtMs != 0 {
dst.FirstChunkAtMs = src.FirstChunkAtMs
}
if src.LastChunkAtMs != 0 {
dst.LastChunkAtMs = src.LastChunkAtMs
}
if src.ChunksSent != 0 {
dst.ChunksSent = src.ChunksSent
}
if src.BytesSent != 0 {
dst.BytesSent = src.BytesSent
}
if src.EstimatedDeliveredTokens != 0 {
dst.EstimatedDeliveredTokens = src.EstimatedDeliveredTokens
}
if src.MaxIdleGapMs != 0 {
dst.MaxIdleGapMs = src.MaxIdleGapMs
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [MEDIUM] 🧩 44 lines of repetitive merge logic for cancellation fields

💡 Suggestion: Use reflection or a helper function to reduce the repetitive merge pattern for the 14 cancellation fields

📊 Score: 3×4 = 12 · Category: duplicate logic

Comment on lines +207 to 271

// cancelSignalSentAt records when the coordinator sent a cancel to the
// provider for this request (DAR-346 cancellation telemetry). Set from the
// abandon path (cancelDispatch) and read by the outcome writer; guarded by
// timingMu since those run on different goroutines.
cancelSignalSentAt time.Time

// DAR-346 delivery measurement: what actually reached the client before a
// cancel/terminal. Written by the SSE relay goroutine on each forwarded
// ciphertext frame (never decrypted), read by the provider-terminal /
// settlement goroutine via DeliverySnapshot. Guarded by deliveryMu.
deliveryMu sync.Mutex
deliveredChunks int
deliveredBytes int64
lastChunkAt time.Time
maxIdleGapMs float64
}

// DeliveryStats is a point-in-time snapshot of what the SSE relay has delivered
// to the client (DAR-346). All counts are over opaque ciphertext frames.
type DeliveryStats struct {
Chunks int
Bytes int64
LastChunkAt time.Time
MaxIdleGapMs float64
}

// RecordDeliveredChunk accounts one SSE frame forwarded to the client: bumps the
// chunk/byte counters, tracks the largest inter-chunk idle gap (a no-progress
// signal that disambiguates a stream-idle cancel), and stamps the last-delivery
// time. Called from the relay goroutine; safe under deliveryMu.
func (pr *PendingRequest) RecordDeliveredChunk(byteLen int) {
if pr == nil {
return
}
now := time.Now()
pr.deliveryMu.Lock()
if !pr.lastChunkAt.IsZero() {
if gap := float64(now.Sub(pr.lastChunkAt).Milliseconds()); gap > pr.maxIdleGapMs {
pr.maxIdleGapMs = gap
}
}
pr.deliveredChunks++
if byteLen > 0 {
pr.deliveredBytes += int64(byteLen)
}
pr.lastChunkAt = now
pr.deliveryMu.Unlock()
}

// DeliverySnapshot returns the current delivery counters under deliveryMu. Safe
// to call from a goroutine other than the relay (e.g. the provider terminal).
func (pr *PendingRequest) DeliverySnapshot() DeliveryStats {
if pr == nil {
return DeliveryStats{}
}
pr.deliveryMu.Lock()
defer pr.deliveryMu.Unlock()
return DeliveryStats{
Chunks: pr.deliveredChunks,
Bytes: pr.deliveredBytes,
LastChunkAt: pr.lastChunkAt,
MaxIdleGapMs: pr.maxIdleGapMs,
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [MEDIUM] 🧩 Adding delivery tracking state and methods to PendingRequest increases struct complexity

💡 Suggestion: Consider extracting delivery tracking into a separate component that PendingRequest can reference, reducing the responsibility of the registry struct

📊 Score: 3×3 = 9 · Category: additive complexity

@Gajesh2007 Gajesh2007 closed this Sep 14, 2026
@Gajesh2007 Gajesh2007 mentioned this pull request Oct 23, 2026
5 of 8 tasks
jonathan308 added a commit that referenced this pull request Nov 17, 2026
GLM-5.3-Flash JSON answers grammar-constrained by default, with grammar-aware MTP (#2131 + SDK #438) — into dev for 0.10.14

This branch had an error being deployed

1 failed and 3 active deployments
Preview – d-inference — 251e454c Deployed Jun 21, 2026 by vercel[bot]
Preview – d-inference-console-ui-dev — 251e454c Deployed Jun 21, 2026 by vercel[bot]
Preview – d-inference-landing — 251e454c Deployed Jun 21, 2026 by vercel[bot]
benchmarks — 251e454c Deployed Jun 21, 2026 by Gajesh2007 via E2E Benchmarks #1342
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants