Repository navigation
fix: make tmux-compat polling backpressure deterministic #12832
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
31 commits
Select commit
Hold shift + click to select a range
d68ae17
test: cover targeted tmux compat read budget
austinywang df3ea68
fix: cache targeted tmux pane reads per connection
austinywang 89c573a
test: exercise tmux commands against production polling limiter
austinywang ae639d3
fix: honor polling backpressure within the CLI request deadline
austinywang 1e75269
test: make polling admission and protocol failure checks deterministic
austinywang efb20d4
chore: keep transport extraction and test fixture focused
austinywang 3f669c7
chore: remove fixture trailing blank lines
austinywang 1a58732
Merge remote-tracking branch 'origin/main' into issue-12757-tmux-rate…
austinywang 8bcf5b2
Merge remote-tracking branch 'origin/main' into issue-12757-tmux-rate…
austinywang c01e9b5
test: bound tmux-compat backpressure checks by causality, not wall-cl…
austinywang 8008b7c
test: order renderer windows before presentation setup
lawrencecchen 97c6088
test: align renderer fixtures with native callback lifecycle
lawrencecchen 5c30554
test: keep renderer presentation suite within budget
lawrencecchen f6a67df
test: sync the CLI help contract with the shipped vm sizes and Cloud …
austinywang 88ad621
test: keep exec-based transfer progress coverage to pull
austinywang 0633852
fix: clear the Swift warnings that put main over its warning budget
austinywang 7037793
test: let the custom-path re-entry fixture answer inject-settings
austinywang e58fbe7
test: expect the Campfire extension's queued hook delivery
austinywang ebe4f61
chore: match #12759's text for two CI fixes so the branches merge cle…
austinywang 3bab274
Update app-host fixtures for current remote and group behavior
lawrencecchen accdec4
Fix app-host fixture contracts
lawrencecchen 5f94b9c
Align Cloud fixtures with current projection contracts
lawrencecchen 48d73a0
test: keep Cloud fixture updates within source budgets
lawrencecchen 7bda7ff
Stabilize portal visibility test lifecycle fixtures
lawrencecchen e58e599
test: fit visibility lifecycle fixture budget
lawrencecchen 993d91a
fix: import terminal surface in visibility fixtures
lawrencecchen f9178e0
test: preserve visibility fixture budget after import
lawrencecchen 8d7a3c2
Authorize portal test surfaces through isolated workspaces
lawrencecchen 7907779
Exercise workspace reveal through noninteractive layout settlement
lawrencecchen e9a53ed
Merge remote-tracking branch 'origin/main' into issue-12757-tmux-rate…
austinywang d9d87d3
chore: keep CloudTreeNodeActions within its file length budget
austinywang File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,225 @@ | ||
| import Foundation | ||
| import CoreFoundation | ||
| import CmuxControlSocket | ||
| import Darwin | ||
|
|
||
| extension SocketClient { | ||
| func sendV2( | ||
| method: String, | ||
| params: [String: Any] = [:], | ||
| responseTimeout: TimeInterval? = nil, | ||
| deadline: Date? = nil | ||
| ) throws -> [String: Any] { | ||
| var tracedParams = params | ||
| if method.hasPrefix("vm.") { | ||
| for (key, env) in [("cloud_operation_id", "CMUX_CLOUD_OPERATION_ID"), | ||
| ("cloud_trace_id", "CMUX_CLOUD_TRACE_ID"), | ||
| ("cloud_parent_span_id", "CMUX_CLOUD_PARENT_SPAN_ID")] { | ||
| if let value = ProcessInfo.processInfo.environment[env] { tracedParams[key] = value } | ||
| } | ||
| } | ||
| let requestID = UUID().uuidString | ||
| var request: [String: Any] = [ | ||
| "id": requestID, | ||
| "method": method, | ||
| "params": tracedParams | ||
| ] | ||
| if let ruleID = ProcessInfo.processInfo.environment["CMUX_AUTOMATION_RULE_ID"], | ||
| !ruleID.isEmpty { | ||
| request["automation_origin"] = Self.automationOriginPayload(ruleID: ruleID) | ||
| } | ||
| guard JSONSerialization.isValidJSONObject(request) else { | ||
| throw CLIError(message: "Failed to encode v2 request") | ||
| } | ||
|
|
||
| let requestData = try JSONSerialization.data(withJSONObject: request, options: []) | ||
| guard let requestLine = String(data: requestData, encoding: .utf8) else { | ||
| throw CLIError(message: "Failed to encode v2 request") | ||
| } | ||
|
|
||
| // One total deadline includes every server-directed backoff and retry. | ||
| let operationDeadline = min( | ||
| deadline ?? .distantFuture, | ||
| Date.now.addingTimeInterval(responseTimeout ?? Self.responseTimeoutSeconds) | ||
| ) | ||
| let uptimeDeadline = ProcessInfo.processInfo.systemUptime + max(0, operationDeadline.timeIntervalSinceNow) | ||
| while true { | ||
| let raw = try send(command: requestLine, responseTimeout: responseTimeout, deadline: operationDeadline) | ||
|
|
||
| // The server may return plain-text errors (e.g., "ERROR: Access denied ...") | ||
| // before the JSON protocol starts. Surface these directly instead of letting | ||
| // JSONSerialization throw a confusing parse error. | ||
| if raw.hasPrefix("ERROR:") { | ||
| throw CLIError(message: raw) | ||
| } | ||
|
|
||
| guard let responseData = raw.data(using: .utf8) else { | ||
| throw CLIError(message: "Invalid UTF-8 v2 response") | ||
| } | ||
| guard let response = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: Any] else { | ||
| throw CLIError(message: "Invalid v2 response: \(raw)") | ||
| } | ||
|
|
||
| if let ok = response["ok"] as? Bool, ok { | ||
| return (response["result"] as? [String: Any]) ?? [:] | ||
| } | ||
|
|
||
| if let error = response["error"] as? [String: Any] { | ||
| let code = (error["code"] as? String) ?? "error" | ||
| let message = (error["message"] as? String) ?? "Unknown v2 error" | ||
| let action = error["action"] as? String | ||
| let data = error["data"] as? [String: Any] | ||
| let failure = CLIError( | ||
| message: formatV2Error( | ||
| code: code, | ||
| message: message, | ||
| action: action, | ||
| reason: error["reason"] as? String, | ||
| details: safeV2Details(error["details"]) | ||
| ), | ||
| v2Code: error["code"] as? String, | ||
| isStructuredProtocolResponse: true, | ||
| v2Retryable: data?["retryable"] as? Bool == true, | ||
| vmBackendCode: data?["backend_code"] as? String, | ||
| vmBackendHTTPStatus: (data?["http_status"] as? NSNumber)?.intValue | ||
| ) | ||
| // Admission rejects these reads before dispatch. Mutations, relay | ||
| // requests, transport failures, and malformed responses never retry. | ||
| if !isRelayBacked, | ||
| response["ok"] as? Bool == false, | ||
| response["id"] as? String == requestID, | ||
| ControlCommandExecutionPolicy.pollingMethods.contains(method), | ||
| code == "rate_limited", | ||
| let delay = Self.pollingRetryDelay(data?["retry_after_ms"]), | ||
| delay < operationDeadline.timeIntervalSinceNow, | ||
| delay < uptimeDeadline - ProcessInfo.processInfo.systemUptime { | ||
| Self.waitForPollingAdmission(seconds: delay) | ||
| guard Date.now < operationDeadline, | ||
| ProcessInfo.processInfo.systemUptime < uptimeDeadline else { | ||
| throw failure | ||
| } | ||
| continue | ||
| } | ||
| throw failure | ||
| } | ||
|
|
||
| throw CLIError(message: "v2 request failed") | ||
| } | ||
| } | ||
|
|
||
| private static func pollingRetryDelay(_ value: Any?) -> TimeInterval? { | ||
| guard let number = value as? NSNumber, | ||
| CFGetTypeID(number) != CFBooleanGetTypeID() else { return nil } | ||
| guard let milliseconds = value as? Int, milliseconds > 0 else { return nil } | ||
| return Double(milliseconds) / 1_000 | ||
| } | ||
|
|
||
| /// A genuine server-requested delay on the CLI's existing synchronous socket | ||
| /// path, never an app/main-actor wait. Monotonic time and EINTR handling keep | ||
| /// signals from shortening admission backoff; the caller bounds it by the | ||
| /// original request deadline. Migrating the blocking CLI transport to async | ||
| /// is separate from honoring its protocol's backpressure contract. | ||
| private static func waitForPollingAdmission(seconds: TimeInterval) { | ||
| let until = ProcessInfo.processInfo.systemUptime + seconds | ||
| while true { | ||
| let remaining = until - ProcessInfo.processInfo.systemUptime | ||
| guard remaining > 0 else { return } | ||
| var duration = timespec( | ||
| tv_sec: Int(remaining), | ||
| tv_nsec: Int((remaining - remaining.rounded(.down)) * 1_000_000_000) | ||
| ) | ||
| if nanosleep(&duration, nil) == 0 { return } | ||
| if errno != EINTR { return } | ||
| } | ||
| } | ||
|
|
||
| private func formatV2Error( | ||
| code: String, | ||
| message: String, | ||
| action: String? = nil, | ||
| reason: String? = nil, | ||
| details: String? = nil | ||
| ) -> String { | ||
| let header: String | ||
| if code == "vm_error" { | ||
| header = message | ||
| } else if message.contains("\n") { | ||
| header = "\(code):\n\(message)" | ||
| } else { | ||
| header = "\(code): \(message)" | ||
| } | ||
| var sections = [header] | ||
| if let reason = trimmedNonEmptyV2Text(reason) { | ||
| sections.append("Reason:\n\(indentV2ErrorLines(reason))") | ||
| } | ||
| if let action = trimmedNonEmptyV2Text(action) { | ||
| sections.append("What to do:\n\(indentV2ErrorLines(action))") | ||
| } | ||
| if let details = trimmedNonEmptyV2Text(details) { | ||
| sections.append("Details:\n\(indentV2ErrorLines(details))") | ||
| } | ||
| return sections.joined(separator: "\n\n") | ||
| } | ||
|
|
||
| private func safeV2Details(_ value: Any?) -> String? { | ||
| guard let value else { return nil } | ||
| if let string = value as? String { | ||
| return trimmedNonEmptyV2Text(string) | ||
| } | ||
| if let dictionary = value as? [String: Any] { | ||
| let allowedKeys = Set([ | ||
| "amount", | ||
| "code", | ||
| "duration", | ||
| "durationMs", | ||
| "field", | ||
| "idempotencyKeySet", | ||
| "imageRequested", | ||
| "limit", | ||
| "operation", | ||
| "retryable", | ||
| "status", | ||
| "type", | ||
| "vmId", | ||
| ]) | ||
| let lines = dictionary.keys.sorted().compactMap { key -> String? in | ||
| guard allowedKeys.contains(key), let value = dictionary[key], !(value is NSNull) else { return nil } | ||
| return "\(key): \(safeV2DetailValue(value))" | ||
| } | ||
| return lines.isEmpty ? nil : lines.joined(separator: "\n") | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| private func safeV2DetailValue(_ value: Any) -> String { | ||
| if let string = value as? String { | ||
| return string.replacingOccurrences(of: "\n", with: "\\n") | ||
| .replacingOccurrences(of: "\r", with: "\\r") | ||
| } | ||
| if let number = value as? NSNumber { | ||
| if CFGetTypeID(number) == CFBooleanGetTypeID() { | ||
| return number.boolValue ? "true" : "false" | ||
| } | ||
| return "\(number)" | ||
| } | ||
| if value is [String: Any] || value is [Any] { | ||
| return "available" | ||
| } | ||
| return String(describing: value) | ||
| .replacingOccurrences(of: "\n", with: "\\n") | ||
| .replacingOccurrences(of: "\r", with: "\\r") | ||
| } | ||
|
|
||
| private func trimmedNonEmptyV2Text(_ value: String?) -> String? { | ||
| let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines) | ||
| return trimmed?.isEmpty == false ? trimmed : nil | ||
| } | ||
|
|
||
| private func indentV2ErrorLines(_ value: String) -> String { | ||
| value | ||
| .split(separator: "\n", omittingEmptySubsequences: false) | ||
| .map { " \($0)" } | ||
| .joined(separator: "\n") | ||
| } | ||
|
|
||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: manaflow-ai/cmux
Length of output: 20734
🏁 Script executed:
Repository: manaflow-ai/cmux
Length of output: 50372
🏁 Script executed:
Repository: manaflow-ai/cmux
Length of output: 26473
🏁 Script executed:
Repository: manaflow-ai/cmux
Length of output: 35262
🏁 Script executed:
Repository: manaflow-ai/cmux
Length of output: 34945
🏁 Script executed:
Repository: manaflow-ai/cmux
Length of output: 49922
🏁 Script executed:
Repository: manaflow-ai/cmux
Length of output: 50056
🏁 Script executed:
Repository: manaflow-ai/cmux
Length of output: 50373
🏁 Script executed:
Repository: manaflow-ai/cmux
Length of output: 50372
🏁 Script executed:
Repository: manaflow-ai/cmux
Length of output: 14942
🏁 Script executed:
Repository: manaflow-ai/cmux
Length of output: 50372
🏁 Script executed:
Repository: manaflow-ai/cmux
Length of output: 50372
Validate the response ID before accepting success.
SocketClient.sendreturns the next wire frame without correlating it. Although the app server normally echoesControlRequest.id, this success branch accepts anyok: trueresult, including one with a missing or different ID. Return a mismatch error before both success and error handling, and add a test for an unrelated successful response. Add matching localized catalog entries for the new error key.Proposed fix
📝 Committable suggestion
🤖 Prompt for AI Agents