Skip to content

fix(provider): settle delivered tokens on client-gone cancels - #433

Merged
Gajesh2007 merged 1 commit into
masterfrom
fix/dar-343-client-gone-payout
Jun 20, 2026
Merged

Gajesh2007 merged 1 commit into
masterfrom
fix/dar-343-client-gone-payout

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented Jun 20, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Make provider cancellation settlement explicit: pre-output cancels still emit 499/refund, while cancels after visible output emit inference_complete with billable usage.
  • Add a testable StreamedGenerationUsage helper that prefers provider-reported usage, otherwise settles from conservative delivered-token floors.
  • Use a tokenizer-derived delivered completion-token floor for mid-stream cancels instead of only counting SSE frames.

Fixes DAR-343.

Verification

  • go test ./api -run 'ClientGone|Settlement|CompleteAfterGrace|HandleComplete' from coordinator/
  • swift test --filter UsageAccountingTests from provider-swift/
  • swift build from provider-swift/
  • git diff --check

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 20, 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 20, 2026 10:08pm
d-inference-console-ui-dev Ready Ready Preview Jun 20, 2026 10:08pm
d-inference-landing Ready Ready Preview Jun 20, 2026 10:08pm

Request Review

@github-actions

Copy link
Copy Markdown
Contributor

This PR refactors cancel-path billing settlement to correctly account for partially-delivered streams; it is neutral-to-positive on security posture with one billing-integrity concern worth noting.


Trust Boundaries Touched

  • TB-002 (Coordinator → Provider WebSocket) — billing terminal messages sent from provider
  • TB-007 (Provider Inference Engine) — inference cancellation and usage accounting
  • TB-008 (Coordinator → Payments) — provider-reported token counts feed the ledger

Threat Assessment

T-010 (TB-002 / T-007 — Cancellation handling) ℹ️ Neutral / slight improvement
The new code path in ProviderLoop.swift:1460–1492 correctly separates "cancelled with nothing delivered → 499 refund" from "cancelled mid-stream with visible output → inference_complete with settled usage." This is cleaner than the old single-branch check and makes the cancellation-billing path more auditable. The residual "cannot interrupt an active GPU forward pass" limitation (documented in T-010 / TB-007) is unchanged.

T-008 (TB-007 — Plaintext SSE chunk fallback on encryption failure) ℹ️ Neutral
The diff does not touch the encryption path (ProviderLoop.swift:436–451, SEC-016). The fail-open plaintext fallback remains open as before.

T-009 (TB-002 — Swift provider excluded from private-text routing) ℹ️ Neutral
No changes to privacy capability flags or the routing gate. SEC-017 remains open.

T-034 (TB-009 — APNs code-identity gate) ℹ️ Neutral
No changes to the APNs challenge flow or the CodeAttested gate.


New Concern: Provider-Controlled Token Counts Feed the Billing Ledger

Not covered by an existing threat entry — flagging as new attack surface.

UsageAccounting.swift:95–100 (cancelledUsageInfo) and the settlement block in ProviderLoop.swift:1505–1513 write settledUsage.promptTokens / .completionTokens / .reasoningTokens back into the mutable local counters that are subsequently sent in the inference_complete message. The values are derived from:

  1. promptTokens — sourced from the upstream usage frame (provider-controlled when running a proxied/relay model) or the re-templated floor (computed locally from streamingRequest).
  2. completionTokens — sourced from the upstream usage frame or, when zero, from contentFrameCount (the count of SSE frames the provider sent, not independently verified by the coordinator).
  3. reasoningTokens — re-tokenized locally from reasoningText which the provider accumulates itself.

The coordinator currently trusts these token counts for billing (TB-008 / T-030 area). A malicious provider could:

  • Inflate contentFrameCount by emitting many small SSE frames before a cancel to drive up the deliveredCompletionTokenFloor path (UsageAccounting.swift:93).
  • Emit a cancel at exactly the right moment to land in the .complete branch with an inflated floor, since cancelledUsageInfo chooses max(deliveredCompletionTokenFloor, contentFrameCount) as the floor (UsageAccounting.swift:93).

Recommendation: The coordinator should independently cap or verify provider-reported token counts against the actual prompt length and any coordinator-side byte/frame counters before crediting the ledger. At minimum, document that provider-reported usage is untrusted input and should be bounded server-side.


Open Findings Resolved by This PR

None of the tracked SEC-* findings (SEC-007, SEC-016, SEC-017, SEC-035, etc.) are closed by this change.


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

@blacksmith-sh

blacksmith-sh Bot commented Jun 20, 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: e0ec98028c

ℹ️ 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 +1468 to +1470
deliveredCompletionTokenFloor: tokenizer.inner.encode(
text: fullResponseText, addSpecialTokens: false
).count,

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 Avoid billing from the hash accumulator

When a canceled stream has emitted tool-call deltas before the final usage chunk, fullResponseText already contains the encodeToolCallsForHash representation, including artificial \u{1F}tool_call: sentinels and canonical JSON added only for attestation hashing. Tokenizing that string here makes the new cancellation settlement charge tokens for bytes that were not model output, so tool-call requests that are canceled after partial output can be overbilled instead of using a conservative delivered-token floor. Keep a separate text/token-floor accumulator that does not include the hash-only markers.

Useful? React with 👍 / 👎.

@Gajesh2007
Gajesh2007 merged commit dc5a413 into master Jun 20, 2026
14 of 17 checks passed

@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 — 3 finding(s) (1 blocking)

  • 🟡 [MEDIUM] provider-swift/Sources/ProviderCore/ProviderLoop.swift:1467-1475 — Tokenizer encoding called twice for reasoning text in cancellation path
    • Suggestion: Cache the tokenizer.inner.encode result for reasoningText and reuse it instead of encoding twice
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/ProviderLoop.swift:1481-1484 — Tokenizer encoding of fullResponseText for deliveredCompletionTokenFloor
    • Suggestion: Consider caching this encoding result if fullResponseText is large, as tokenization can be expensive for long texts
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/ProviderLoop.swift:1540-1548 — Duplicate tokenizer encoding of reasoningText in non-cancelled path
    • Suggestion: Extract the reasoning text tokenization logic to avoid duplication between cancelled and non-cancelled paths

Type_diligence — ✅ No issues found

Additive_complexity — 4 finding(s) (1 blocking)

  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Inference/UsageAccounting.swift:67-95 — StreamedGenerationUsage struct has complex initialization with many parameters and validation logic
    • Suggestion: Consider using a builder pattern or factory methods to reduce parameter count and make initialization clearer
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Inference/UsageAccounting.swift:97-101 — cancelledTerminal method is a thin wrapper around cancelledUsageInfo with pattern matching
    • Suggestion: Consider inlining this logic or making the relationship more explicit to reduce indirection
  • 🟡 [MEDIUM] provider-swift/Sources/ProviderCore/ProviderLoop.swift:1450-1507 — Complex usage settlement logic embedded in the main provider loop instead of being delegated to the UsageAccounting module
    • Suggestion: Move the tokenizer-based settlement logic into StreamedGenerationUsage methods to keep the provider loop focused on coordination
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/ProviderLoop.swift:1474-1479 — Tokenizer encoding logic duplicated for reasoning tokens and delivered completion token floor
    • Suggestion: Extract a helper method for tokenizer-based token counting to avoid repetition

7 finding(s) total, 2 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

Comment on lines +1467 to +1475
contentFrameCount: contentFrameCount,
deliveredCompletionTokenFloor: tokenizer.inner.encode(
text: fullResponseText, addSpecialTokens: false
).count,
hasVisibleOutput: Self.hasVisibleStreamOutput(
contentFrameCount: contentFrameCount,
fullResponseText: fullResponseText
)
)

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] ⚡ Tokenizer encoding called twice for reasoning text in cancellation path

💡 Suggestion: Cache the tokenizer.inner.encode result for reasoningText and reuse it instead of encoding twice

📊 Score: 3×4 = 12 · Category: Repeated work

Comment on lines +1481 to +1484
guard case .complete(let settledUsage) = terminal else {
// Cancelled with nothing delivered: 499 so the coordinator refunds.
providerStats.incrementCancellationsBeforeOutput()
send.send(.inferenceError(

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.

🔵 [INFO] ⚡ Tokenizer encoding of fullResponseText for deliveredCompletionTokenFloor

💡 Suggestion: Consider caching this encoding result if fullResponseText is large, as tokenization can be expensive for long texts

📊 Score: 2×3 = 6 · Category: Repeated work

Comment on lines +67 to +95
struct StreamedGenerationUsage: Equatable, Sendable {
var promptTokens: Int
var completionTokens: Int
var reasoningTokens: Int
var contentFrameCount: Int
var deliveredCompletionTokenFloor: Int
var hasVisibleOutput: Bool

init(
promptTokens: Int,
completionTokens: Int,
reasoningTokens: Int = 0,
contentFrameCount: Int,
deliveredCompletionTokenFloor: Int = 0,
hasVisibleOutput: Bool
) {
self.promptTokens = max(0, promptTokens)
self.completionTokens = max(0, completionTokens)
self.reasoningTokens = max(0, reasoningTokens)
self.contentFrameCount = max(0, contentFrameCount)
self.deliveredCompletionTokenFloor = max(0, deliveredCompletionTokenFloor)
self.hasVisibleOutput = hasVisibleOutput
}

func cancelledTerminal(promptTokenFloor: @autoclosure () -> Int) -> CancelledGenerationTerminal {
guard let usage = cancelledUsageInfo(promptTokenFloor: promptTokenFloor()) else {
return .refund
}
return .complete(usage)

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.

🔵 [INFO] 🧩 StreamedGenerationUsage struct has complex initialization with many parameters and validation logic

💡 Suggestion: Consider using a builder pattern or factory methods to reduce parameter count and make initialization clearer

📊 Score: 2×3 = 6 · Category: over-abstraction

Comment on lines +97 to +101

func cancelledUsageInfo(promptTokenFloor: @autoclosure () -> Int) -> UsageInfo? {
guard hasVisibleOutput else { return nil }
let completionFloor = max(deliveredCompletionTokenFloor, contentFrameCount)
let settledCompletionTokens = completionTokens > 0 ? completionTokens : completionFloor

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.

🔵 [INFO] 🧩 cancelledTerminal method is a thin wrapper around cancelledUsageInfo with pattern matching

💡 Suggestion: Consider inlining this logic or making the relationship more explicit to reduce indirection

📊 Score: 1×2 = 2 · Category: duplicate logic

Comment on lines +1450 to 1507
if cancelledMidStream {
if reasoningTokens == 0 && !reasoningText.isEmpty {
let completionFloor = completionTokens > 0 ? completionTokens : contentFrameCount
if completionFloor > 0 {
reasoningTokens = min(
tokenizer.inner.encode(
text: reasoningText, addSpecialTokens: false
).count,
completionFloor
)
}
}

let partialUsage = StreamedGenerationUsage(
promptTokens: promptTokens,
completionTokens: completionTokens,
reasoningTokens: reasoningTokens,
contentFrameCount: contentFrameCount,
deliveredCompletionTokenFloor: tokenizer.inner.encode(
text: fullResponseText, addSpecialTokens: false
).count,
hasVisibleOutput: Self.hasVisibleStreamOutput(
contentFrameCount: contentFrameCount,
fullResponseText: fullResponseText
)
)
let terminal = partialUsage.cancelledTerminal(promptTokenFloor: Self.promptTokenFloor(
request: streamingRequest,
tokenizer: tokenizer,
reasoningEffort: reasoningEffort
))
return
guard case .complete(let settledUsage) = terminal else {
// Cancelled with nothing delivered: 499 so the coordinator refunds.
providerStats.incrementCancellationsBeforeOutput()
send.send(.inferenceError(
requestId: requestId,
error: "request cancelled",
statusCode: 499,
errorReason: nil
))
return
}
if completionTokens == 0 {
log.warning(
"[\(requestId)] usage chunk missing/zero completion tokens (cancelled mid-stream); "
+ "billing \(settledUsage.completionTokens) delivered completion tokens as a floor."
)
}
if promptTokens == 0 && settledUsage.promptTokens > 0 {
log.warning(
"[\(requestId)] usage chunk missing/zero prompt tokens (cancelled mid-stream); "
+ "billing \(settledUsage.promptTokens) re-templated prompt tokens as a floor."
)
}
promptTokens = Int(clamping: settledUsage.promptTokens)
completionTokens = Int(clamping: settledUsage.completionTokens)
reasoningTokens = Int(clamping: settledUsage.reasoningTokens)
}

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] 🧩 Complex usage settlement logic embedded in the main provider loop instead of being delegated to the UsageAccounting module

💡 Suggestion: Move the tokenizer-based settlement logic into StreamedGenerationUsage methods to keep the provider loop focused on coordination

📊 Score: 3×4 = 12 · Category: misplaced responsibility

Comment on lines +1474 to +1479
)
)
let terminal = partialUsage.cancelledTerminal(promptTokenFloor: Self.promptTokenFloor(
request: streamingRequest,
tokenizer: tokenizer,
reasoningEffort: reasoningEffort

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.

🔵 [INFO] 🧩 Tokenizer encoding logic duplicated for reasoning tokens and delivered completion token floor

💡 Suggestion: Extract a helper method for tokenizer-based token counting to avoid repetition

📊 Score: 2×3 = 6 · Category: duplicate logic

jonathan308 added a commit that referenced this pull request Nov 16, 2026
Brings in the 0.10.14 fold, including #2154/#2164 (Qwen image caps of 64
under a per-request image budget; the media gate covers the shares),
#2163/#2176 (GLM media reservation and long-video fit) and the SDK pin of
#434. Conflicts:

- libs/mlx-swift-lm: dev pins fe9b528243 (#434); this branch pins
  86316143a0, #433's merge commit on top of it. Kept 86316143a0.
- LaunchAgent.inferencePassthroughEnvKeys and its doc comment: kept dev's
  GLM switches and this branch's two Qwen video keys.
- docs/reference/configuration.md: kept dev's GLM rows and image-cap row
  and this branch's tower-patches wording and Qwen video row.
- docs/architecture/inference.md: kept dev's image-budget sentences and
  inline-video bullet, then this branch's Qwen video bullet, which now
  says the image share sizes only images and clips keep their budget.

MediaIngest.swift merged without conflicts: the image share is
UserInput.Processing.maxPixels (set in buildUserInput), the video budget
is UserInput.Processing.video (set in EngineV2VisionPrefill).

This branch had an error being deployed

1 failed and 3 active deployments
Preview – d-inference-console-ui-dev — e0ec9802 Deployed Jun 20, 2026 by vercel[bot]
Preview – d-inference — e0ec9802 Deployed Jun 20, 2026 by vercel[bot]
Preview – d-inference-landing — e0ec9802 Deployed Jun 20, 2026 by vercel[bot]
benchmarks — e0ec9802 Deployed Jun 20, 2026 by Gajesh2007 via E2E Benchmarks #1304
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