Repository navigation
fix(provider): settle delivered tokens on client-gone cancels - #433
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
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
Threat AssessmentT-010 (TB-002 / T-007 — Cancellation handling) ℹ️ Neutral / slight improvement T-008 (TB-007 — Plaintext SSE chunk fallback on encryption failure) ℹ️ Neutral T-009 (TB-002 — Swift provider excluded from private-text routing) ℹ️ Neutral T-034 (TB-009 — APNs code-identity gate) ℹ️ Neutral New Concern: Provider-Controlled Token Counts Feed the Billing LedgerNot covered by an existing threat entry — flagging as new attack surface.
The coordinator currently trusts these token counts for billing (TB-008 / T-030 area). A malicious provider could:
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 PRNone of the tracked SEC-* findings (SEC-007, SEC-016, SEC-017, SEC-035, etc.) are closed by this change. 🔐 Threat model: |
|
Found 1 test failure on Blacksmith runners: Failure
|
There was a problem hiding this comment.
💡 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".
| deliveredCompletionTokenFloor: tokenizer.inner.encode( | ||
| text: fullResponseText, addSpecialTokens: false | ||
| ).count, |
There was a problem hiding this comment.
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 👍 / 👎.
ethenotethan
left a comment
There was a problem hiding this comment.
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
| contentFrameCount: contentFrameCount, | ||
| deliveredCompletionTokenFloor: tokenizer.inner.encode( | ||
| text: fullResponseText, addSpecialTokens: false | ||
| ).count, | ||
| hasVisibleOutput: Self.hasVisibleStreamOutput( | ||
| contentFrameCount: contentFrameCount, | ||
| fullResponseText: fullResponseText | ||
| ) | ||
| ) |
There was a problem hiding this comment.
🟡 [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
| guard case .complete(let settledUsage) = terminal else { | ||
| // Cancelled with nothing delivered: 499 so the coordinator refunds. | ||
| providerStats.incrementCancellationsBeforeOutput() | ||
| send.send(.inferenceError( |
There was a problem hiding this comment.
🔵 [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
| 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) |
There was a problem hiding this comment.
🔵 [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
|
|
||
| func cancelledUsageInfo(promptTokenFloor: @autoclosure () -> Int) -> UsageInfo? { | ||
| guard hasVisibleOutput else { return nil } | ||
| let completionFloor = max(deliveredCompletionTokenFloor, contentFrameCount) | ||
| let settledCompletionTokens = completionTokens > 0 ? completionTokens : completionFloor |
There was a problem hiding this comment.
🔵 [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
| 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) | ||
| } |
There was a problem hiding this comment.
🟡 [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
| ) | ||
| ) | ||
| let terminal = partialUsage.cancelledTerminal(promptTokenFloor: Self.promptTokenFloor( | ||
| request: streamingRequest, | ||
| tokenizer: tokenizer, | ||
| reasoningEffort: reasoningEffort |
There was a problem hiding this comment.
🔵 [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
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).

Summary
Fixes DAR-343.
Verification
go test ./api -run 'ClientGone|Settlement|CompleteAfterGrace|HandleComplete'fromcoordinator/swift test --filter UsageAccountingTestsfromprovider-swift/swift buildfromprovider-swift/git diff --checkNeed help on this PR? Tag
/codesmithwith what you need. Autofix is disabled.