Repository navigation
Retry Codex resume lock failures and preserve cwd #5611
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
Closed
Closed
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
b4ef42d
test: cover codex resume lock retry
austinywang f6786a5
fix: retry codex resume lock failures
austinywang 560eea9
Merge remote-tracking branch 'origin/main' into issue-5557-codex-resu…
austinywang 38d4092
fix: return codex resume startup input
austinywang c0cb09a
fix: address resume launcher review feedback
austinywang 4d0ef75
Merge remote-tracking branch 'origin/main' into issue-5557-codex-resu…
austinywang dc09af3
chore: regenerate Swift file length budget
austinywang 4f2dd84
Merge remote-tracking branch 'origin/main' into issue-5557-codex-resu…
austinywang 86eb18d
docs: avoid conflict marker scan false positive
austinywang bae572c
chore: refresh Swift file length budget
austinywang d113dc8
fix: avoid transcript capture during resume retry
austinywang 8f319a0
fix: keep resume retry signature gated
austinywang 22da1d5
fix: capture retry output with bounded fifo
austinywang 2c2c314
fix: preserve retry matching without fifo
austinywang 6faa3e7
fix: remove retry logs between attempts
austinywang 5abf929
merge: sync with origin main
austinywang e8f4a08
merge: resolve conflicts with main
austinywang 0c94af5
fix: bound Codex resume retry capture
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
117 changes: 117 additions & 0 deletions
117
Packages/macOS/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentResumeRetryPolicy.swift
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,117 @@ | ||
| import Foundation | ||
|
|
||
| /// Describes when an agent resume command should be retried after a transient startup failure. | ||
| /// | ||
| /// The policy is intentionally narrow: callers opt in for known retryable agents, and shell | ||
| /// launchers only retry fast failures whose bounded startup capture contains one of | ||
| /// ``outputNeedles``. Callers that already have failed process output can use ``matches(output:)`` | ||
| /// to check the same known retryable signatures. | ||
| public struct AgentResumeRetryPolicy: Sendable, Equatable { | ||
| /// The maximum number of retries after the first failed launch attempt. | ||
| public let maximumRetries: Int | ||
|
|
||
| /// The delay between retry attempts, before the per-process stagger is added. | ||
| public let delaySeconds: Double | ||
|
|
||
| /// The startup window, in whole seconds, during which a failed shell launch may be retried. | ||
| public let startupFailureWindowSeconds: Int | ||
|
|
||
| /// Case-insensitive output fragments that identify a retryable transient failure. | ||
| public let outputNeedles: [String] | ||
|
|
||
| /// Creates a retry policy for a generated resume launcher. | ||
| /// | ||
| /// - Parameters: | ||
| /// - maximumRetries: The maximum number of retries after the first failed launch attempt. | ||
| /// - delaySeconds: The delay between retry attempts. | ||
| /// - outputNeedles: Case-insensitive output fragments that identify retryable failures. | ||
| /// - startupFailureWindowSeconds: The shell-launch startup window that allows retrying a | ||
| /// failed attempt without recording an interactive transcript. | ||
| public init( | ||
| maximumRetries: Int, | ||
| delaySeconds: Double, | ||
| outputNeedles: [String], | ||
| startupFailureWindowSeconds: Int = 5 | ||
| ) { | ||
| self.maximumRetries = max(0, maximumRetries) | ||
| self.delaySeconds = max(0, delaySeconds) | ||
| self.startupFailureWindowSeconds = max(0, startupFailureWindowSeconds) | ||
| self.outputNeedles = outputNeedles | ||
| .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } | ||
| .filter { !$0.isEmpty } | ||
| } | ||
|
|
||
| /// A policy that never retries. | ||
| public static let disabled = AgentResumeRetryPolicy( | ||
| maximumRetries: 0, | ||
| delaySeconds: 0, | ||
| outputNeedles: [], | ||
| startupFailureWindowSeconds: 0 | ||
| ) | ||
|
|
||
| /// Retries Codex's transient shared-state SQLite lock failure. | ||
| public static let codexStateDatabaseLock = AgentResumeRetryPolicy( | ||
| maximumRetries: 3, | ||
| delaySeconds: 0.25, | ||
| outputNeedles: [ | ||
| "database is locked", | ||
| "another Codex process is using its local data", | ||
| ], | ||
| startupFailureWindowSeconds: 5 | ||
| ) | ||
|
|
||
| /// Returns `true` when this policy can retry at least one failure. | ||
| public var isEnabled: Bool { | ||
| maximumRetries > 0 && !outputNeedles.isEmpty | ||
| } | ||
|
|
||
| /// Chooses the retry policy for a captured agent kind and launcher. | ||
| /// | ||
| /// - Parameters: | ||
| /// - agentKind: The raw agent kind, such as `"codex"`. | ||
| /// - launcher: The captured launcher name, such as `"codexTeams"`. | ||
| /// - Returns: ``codexStateDatabaseLock`` for Codex launches; otherwise ``disabled``. | ||
| public static func policy(agentKind: String?, launcher: String? = nil) -> AgentResumeRetryPolicy { | ||
| if normalized(agentKind) == "codex" || normalized(launcher) == "codexteams" { | ||
| return .codexStateDatabaseLock | ||
| } | ||
| return .disabled | ||
| } | ||
|
|
||
| /// Returns `true` when process output contains a retryable signature. | ||
| /// | ||
| /// - Parameter output: Combined stdout/stderr from the failed attempt. | ||
| /// - Returns: `true` when `output` contains a retryable signature; otherwise `false`. | ||
| public func matches(output: String) -> Bool { | ||
| guard isEnabled else { return false } | ||
| let lowercasedOutput = output.lowercased() | ||
| return outputNeedles.contains { lowercasedOutput.contains($0.lowercased()) } | ||
| } | ||
|
|
||
| var shellGrepPattern: String { | ||
| outputNeedles | ||
| .filter { !$0.isEmpty } | ||
| .map(Self.extendedGrepEscaped) | ||
| .joined(separator: "|") | ||
| } | ||
|
|
||
| private static func normalized(_ value: String?) -> String? { | ||
| guard let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines), | ||
| !trimmed.isEmpty else { | ||
| return nil | ||
| } | ||
| return trimmed.lowercased() | ||
| } | ||
|
|
||
| private static func extendedGrepEscaped(_ value: String) -> String { | ||
| let specialCharacters = #"[]\.^$*+?{}()|"# | ||
| var result = "" | ||
| for character in value { | ||
| if specialCharacters.contains(character) { | ||
| result.append("\\") | ||
| } | ||
| result.append(character) | ||
| } | ||
| return result | ||
| } | ||
| } | ||
17 changes: 17 additions & 0 deletions
17
Packages/macOS/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentResumeShellQuoting.swift
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,17 @@ | ||
| import Foundation | ||
|
|
||
| struct AgentResumeShellQuoting: Sendable, Equatable { | ||
| func singleQuoted(_ value: String) -> String { | ||
| if value.utf8.contains(where: { $0 >= 0x80 }) { | ||
| return asciiPrintfCommandSubstitution(for: value) | ||
| } | ||
| return "'" + value.replacingOccurrences(of: "'", with: "'\\''") + "'" | ||
| } | ||
|
|
||
| private func asciiPrintfCommandSubstitution(for value: String) -> String { | ||
| let octalBytes = value.utf8 | ||
| .map { String(format: #"\%03o"#, Int($0)) } | ||
| .joined() | ||
| return #""$(printf '"# + octalBytes + #"')""# | ||
| } | ||
|
austinywang marked this conversation as resolved.
|
||
| } | ||
180 changes: 180 additions & 0 deletions
180
Packages/macOS/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentResumeShellScriptBuilder.swift
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,180 @@ | ||
| import Foundation | ||
|
|
||
| /// Builds zsh launcher-script lines for an agent resume command. | ||
| /// | ||
| /// The builder owns the shell shape shared by local app restores and CLI-created resume surfaces: | ||
| /// run the supplied command in a child shell, optionally retry a known transient failure, then exec | ||
| /// a fresh login shell from the saved working directory so a failed or exited agent leaves the | ||
| /// visible terminal where the session lived. | ||
| public struct AgentResumeShellScriptBuilder: Sendable, Equatable { | ||
| private let quoting = AgentResumeShellQuoting() | ||
|
|
||
| /// Creates a shell-script builder. The type holds no runtime state. | ||
| public init() {} | ||
|
|
||
| /// Builds the launcher lines that run `command` and then return to a login shell. | ||
| /// | ||
| /// The command is executed exactly as supplied. If the command must start from a directory, the | ||
| /// caller should include that `cd` in the command text. The `workingDirectory` value controls the | ||
| /// directory restored before the final login shell is `exec`ed. | ||
| /// | ||
| /// - Parameters: | ||
| /// - command: The shell command to run in the child shell. | ||
| /// - workingDirectory: The directory for the final visible shell after the command exits. | ||
| /// - retryPolicy: A bounded retry policy for transient launch failures. | ||
| /// - Returns: zsh script lines to append after a shebang. | ||
| public func commandThenReturnLines( | ||
| command: String, | ||
| workingDirectory: String? = nil, | ||
| retryPolicy: AgentResumeRetryPolicy = .disabled | ||
| ) -> [String] { | ||
| var lines = [ | ||
| #"_cmux_resume_shell="${SHELL:-/bin/zsh}""#, | ||
| ] | ||
| if retryPolicy.isEnabled { | ||
| lines.append(contentsOf: retryingCommandLines(command: command, retryPolicy: retryPolicy)) | ||
| } else { | ||
| lines.append(contentsOf: plainCommandLines(command: command)) | ||
| } | ||
| lines.append(contentsOf: zshIntegrationReentryLines) | ||
| if let workingDirectory, | ||
| !workingDirectory.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { | ||
| lines.append(#"{ cd -- \#(quoting.singleQuoted(workingDirectory)) 2>/dev/null || true; }"#) | ||
| } | ||
| lines.append(#"exec -l "$_cmux_resume_shell""#) | ||
| return lines | ||
| } | ||
|
|
||
| private var zshIntegrationReentryLines: [String] { | ||
| [ | ||
| #"if [[ "${_cmux_resume_shell:t}" == "zsh" && -n "${CMUX_SHELL_INTEGRATION_DIR:-}" && -r "${CMUX_SHELL_INTEGRATION_DIR}/.zshenv" ]]; then"#, | ||
| #" if [[ -n "${ZDOTDIR+X}" ]]; then"#, | ||
| #" export CMUX_ZSH_ZDOTDIR="$ZDOTDIR""#, | ||
| #" else"#, | ||
| #" unset CMUX_ZSH_ZDOTDIR"#, | ||
| #" fi"#, | ||
| #" export ZDOTDIR="$CMUX_SHELL_INTEGRATION_DIR""#, | ||
| #"fi"#, | ||
| ] | ||
| } | ||
|
|
||
| private func plainCommandLines(command: String) -> [String] { | ||
| let quotedCommand = quoting.singleQuoted(command) | ||
| return [ | ||
| #"case "${_cmux_resume_shell:t}" in"#, | ||
| #" zsh|bash) "$_cmux_resume_shell" -lic \#(quotedCommand) ;;"#, | ||
| #" csh|tcsh) "$_cmux_resume_shell" -c \#(quotedCommand) ;;"#, | ||
| #" *) "$_cmux_resume_shell" -c \#(quotedCommand) ;;"#, | ||
| #"esac"#, | ||
| ] | ||
| } | ||
|
|
||
| private func retryingCommandLines(command: String, retryPolicy: AgentResumeRetryPolicy) -> [String] { | ||
| let quotedCommand = quoting.singleQuoted(command) | ||
| let quotedPattern = quoting.singleQuoted(retryPolicy.shellGrepPattern) | ||
| let retryCount = max(0, retryPolicy.maximumRetries) | ||
| let retryDelay = String(format: "%.3f", max(0, retryPolicy.delaySeconds)) | ||
| let retryStartupSeconds = max(0, retryPolicy.startupFailureWindowSeconds) | ||
| return [ | ||
| #"_cmux_resume_command=\#(quotedCommand)"#, | ||
| #"_cmux_resume_retry_limit="${CMUX_AGENT_RESUME_RETRY_LIMIT:-\#(retryCount)}""#, | ||
| #"case "$_cmux_resume_retry_limit" in"#, | ||
| #" ''|*[!0-9]*) _cmux_resume_retry_limit=\#(retryCount) ;;"#, | ||
| #"esac"#, | ||
| #"_cmux_resume_retry_delay="${CMUX_AGENT_RESUME_RETRY_DELAY_SECONDS:-\#(retryDelay)}""#, | ||
| #"case "$_cmux_resume_retry_delay" in"#, | ||
| #" ''|*[!0-9.]*) _cmux_resume_retry_delay=\#(retryDelay) ;;"#, | ||
| #"esac"#, | ||
| #"_cmux_resume_retry_startup_seconds="${CMUX_AGENT_RESUME_RETRY_STARTUP_SECONDS:-\#(retryStartupSeconds)}""#, | ||
| #"case "$_cmux_resume_retry_startup_seconds" in"#, | ||
| #" ''|*[!0-9]*) _cmux_resume_retry_startup_seconds=\#(retryStartupSeconds) ;;"#, | ||
| #"esac"#, | ||
| #"_cmux_resume_retry=0"#, | ||
| #"_cmux_resume_log="""#, | ||
| #"_cmux_resume_pipe="""#, | ||
| #"_cmux_resume_cleanup_log() {"#, | ||
| #" if [ -n "$_cmux_resume_log" ]; then"#, | ||
| #" rm -f -- "$_cmux_resume_log" 2>/dev/null || true"#, | ||
| #" fi"#, | ||
| #" if [ -n "$_cmux_resume_pipe" ]; then"#, | ||
| #" rm -f -- "$_cmux_resume_pipe" 2>/dev/null || true"#, | ||
| #" fi"#, | ||
| #"}"#, | ||
| #"_cmux_resume_capture_log() {"#, | ||
| #" /bin/dd bs=1 count=4096 of="$1" 2>/dev/null"#, | ||
| #" /bin/cat >/dev/null"#, | ||
| #"}"#, | ||
| #"trap _cmux_resume_cleanup_log EXIT INT TERM"#, | ||
| #"while true; do"#, | ||
| #" _cmux_resume_log="${TMPDIR:-/tmp}/cmux-agent-resume-${$}-${_cmux_resume_retry}.log""#, | ||
| #" _cmux_resume_pipe="${TMPDIR:-/tmp}/cmux-agent-resume-${$}-${_cmux_resume_retry}.fifo""#, | ||
| #" rm -f -- "$_cmux_resume_log" "$_cmux_resume_pipe" 2>/dev/null || true"#, | ||
| #" : > "$_cmux_resume_log" 2>/dev/null && chmod 600 "$_cmux_resume_log" 2>/dev/null || true"#, | ||
| #" _cmux_resume_script_output="""#, | ||
| #" _cmux_resume_capture_pid="""#, | ||
| #" if [ -x /usr/bin/script ] && [ -x /usr/bin/mkfifo ] && /usr/bin/mkfifo "$_cmux_resume_pipe" 2>/dev/null; then"#, | ||
| #" _cmux_resume_capture_log "$_cmux_resume_log" < "$_cmux_resume_pipe" &"#, | ||
| #" _cmux_resume_capture_pid=$!"#, | ||
| #" _cmux_resume_script_output="$_cmux_resume_pipe""#, | ||
| #" fi"#, | ||
| #" _cmux_resume_started_at=$(/bin/date +%s 2>/dev/null || echo 0)"#, | ||
| #" case "${_cmux_resume_shell:t}" in"#, | ||
| #" zsh|bash)"#, | ||
| #" if [ -n "$_cmux_resume_capture_pid" ] && [ -x /usr/bin/script ]; then"#, | ||
| #" /usr/bin/script -q -F "$_cmux_resume_script_output" "$_cmux_resume_shell" -lic "$_cmux_resume_command""#, | ||
| #" else"#, | ||
| #" "$_cmux_resume_shell" -lic "$_cmux_resume_command""#, | ||
| #" fi"#, | ||
| #" ;;"#, | ||
| #" csh|tcsh)"#, | ||
| #" if [ -n "$_cmux_resume_capture_pid" ] && [ -x /usr/bin/script ]; then"#, | ||
| #" /usr/bin/script -q -F "$_cmux_resume_script_output" "$_cmux_resume_shell" -c "$_cmux_resume_command""#, | ||
| #" else"#, | ||
| #" "$_cmux_resume_shell" -c "$_cmux_resume_command""#, | ||
| #" fi"#, | ||
| #" ;;"#, | ||
| #" *)"#, | ||
| #" if [ -n "$_cmux_resume_capture_pid" ] && [ -x /usr/bin/script ]; then"#, | ||
| #" /usr/bin/script -q -F "$_cmux_resume_script_output" "$_cmux_resume_shell" -c "$_cmux_resume_command""#, | ||
| #" else"#, | ||
| #" "$_cmux_resume_shell" -c "$_cmux_resume_command""#, | ||
| #" fi"#, | ||
| #" ;;"#, | ||
| #" esac"#, | ||
| #" _cmux_resume_status=$?"#, | ||
| #" if [ -n "$_cmux_resume_capture_pid" ]; then"#, | ||
| #" wait "$_cmux_resume_capture_pid" 2>/dev/null || true"#, | ||
| #" fi"#, | ||
| #" rm -f -- "$_cmux_resume_pipe" 2>/dev/null || true"#, | ||
| #" if [ "$_cmux_resume_status" -eq 0 ]; then"#, | ||
| #" break"#, | ||
| #" fi"#, | ||
| #" _cmux_resume_finished_at=$(/bin/date +%s 2>/dev/null || echo 0)"#, | ||
| #" _cmux_resume_elapsed=$((_cmux_resume_finished_at - _cmux_resume_started_at))"#, | ||
| #" if [ "$_cmux_resume_elapsed" -lt 0 ]; then"#, | ||
| #" _cmux_resume_elapsed=$_cmux_resume_retry_startup_seconds"#, | ||
| #" fi"#, | ||
| #" if [ "$_cmux_resume_elapsed" -gt "$_cmux_resume_retry_startup_seconds" ]; then"#, | ||
| #" break"#, | ||
| #" fi"#, | ||
| #" if ! /usr/bin/grep -Eiq \#(quotedPattern) "$_cmux_resume_log" 2>/dev/null; then"#, | ||
| #" break"#, | ||
| #" fi"#, | ||
| #" if [ "$_cmux_resume_retry" -ge "$_cmux_resume_retry_limit" ]; then"#, | ||
| #" break"#, | ||
| #" fi"#, | ||
| #" _cmux_resume_cleanup_log"#, | ||
| #" _cmux_resume_retry=$((_cmux_resume_retry + 1))"#, | ||
| #" if [ "$_cmux_resume_retry_delay" != "0" ]; then"#, | ||
| #" sleep "$_cmux_resume_retry_delay""#, | ||
| #" _cmux_resume_stagger=$((($$ + _cmux_resume_retry) % 7))"#, | ||
| #" if [ "$_cmux_resume_stagger" -gt 0 ]; then"#, | ||
| #" sleep "0.${_cmux_resume_stagger}""#, | ||
| #" fi"#, | ||
| #" fi"#, | ||
| #"done"#, | ||
| #"_cmux_resume_cleanup_log"#, | ||
| #"trap - EXIT INT TERM"#, | ||
| ] | ||
| } | ||
| } |
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.
Uh oh!
There was an error while loading. Please reload this page.