Skip to content

fix: apply reviewed maintenance repairs for #3400 - #3685

Closed
kovtcharov wants to merge 9 commits into
amd:kalin/shell-session-3380-cleanfrom
kovtcharov:codex/maintenance-pr-3400
Closed

kovtcharov wants to merge 9 commits into
amd:kalin/shell-session-3380-cleanfrom
kovtcharov:codex/maintenance-pr-3400

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

Follow-up fixes for #3400. Local repairs in worktrees/3400; no commits/pushes.

This PR targets the original feature branch because the current account cannot push to amd/gaia. It carries the prepared maintenance changes for that PR.

Test plan

  • Previously completed local validation: Validation: 380 native Windows tests passed across session execution, tool integration, guardrails, grants, encoding, tool bundles and registration counts (3 SWIG warnings). Real child timeout/cleanup/cwd/env tests are included. Three targeted POSIX tests passed through Git Bash with its usr/bin on PATH; without awk on PATH, manually verified clear exit 127 and error output. Black/isort and Flake8 with repository settings passed on changed files; diff check clean.
  • Fresh CI on the combined feature branch.
  • Remaining live-model, hardware or platform checks described in the original PR, where applicable.
  • Human review before merging the original PR.

Ovtcharov and others added 7 commits September 8, 2026 10:47
Ports the C++ toolbelt's ShellSession (cpp/include/gaia/process.h, amd#2810) to
Python. What persists is the session state, not a resident child: each command
runs a generated script that restores the session's directory and variables,
sources the command from its own file, then reports the resulting pwd and
environment to a side file the session absorbs.

Not wired into the shell tool yet.
…and a reset

A directory change or a variable set in one call is now still in effect for the
next. Adds get_shell_state so the agent can read where it is rather than infer
it, set_shell_variable because the shell's own export is not on the read-only
whitelist, and reset_shell_session to recover a session that is wedged or in the
wrong place.

Command validation is unchanged and still applies per segment. Two seams needed
care: a skill-granted binary still runs as argv, never as a string handed to a
shell, and a cd into a directory the path policy refuses is not absorbed -
otherwise persistence would be a way to read files by bare name from anywhere.
Also closes the chat agent's shell session in its teardown path, so the temp
directory goes with the agent rather than waiting on the OS.
Also registers the session's bandit suppressions and drops the Popen kwargs
dict that hid the call's overload from mypy.
…p asserting expansion

The manifest's hand-typed tools_count still claimed 67; the three session tools
take the flagship registry to 70.

The environment test asserted a variable by echoing $VAR, which the POSIX path
deliberately refuses to expand — re-quoting the validated tokens is what stops a
variable the agent set from naming a file the path validator only ever saw as
'$X'. It now reads the value back through the probe and the environment a child
is handed, with a second test pinning that no interpolation happens.
On a Linux host the session told the model it had changed AWKPATH and
AWKLIBPATH after every single command, and replayed both into the next
script. gawk setenv()s them into its own process environment before
BEGIN runs, and the session's bookkeeping dump is a gawk one-liner — so
they land in the captured environment even though the shell never set
them.

The test that should have caught this allowed up to a quarter of the
parent environment as spurious divergence, so one or two false positives
passed in silence. It now asserts exactly zero, which means taking its
own session: pytest rewrites PYTEST_CURRENT_TEST between the fixture's
setup phase and the call phase, and a baseline captured in setup sees
that as a genuine change.
Local repairs in `worktrees/3400`; no commits/pushes.
@github-actions github-actions Bot added tests Test changes agents labels Sep 11, 2026
@kovtcharov
kovtcharov marked this pull request as ready for review September 17, 2026 20:04
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Request changes (one small fix)

This tightens the persistent shell session: terminal size no longer shows up as an "agent changed this variable", the session's temp directory now cleans itself up if an agent is abandoned without being closed, the cd permission check no longer pops a user prompt, and a failed state capture is reported instead of swallowed. Direction is right on all four; one of them swaps a "never fails" cleanup for one that can throw at the worst moment.

What to fix before merge

  • Temp-directory cleanup can now raise and take a command's result with it. The old cleanup ignored errors; the new one doesn't. It runs at the end of a command when the session was closed mid-flight — exactly the hung-command case this code was written for — so on Windows a file still held by a just-killed child turns a finished command into an exception instead of a result. One keyword argument fixes it, and it matches how the neighbouring file deletions in the same block already behave (log, don't throw).

Worth a second look, not blocking

  • Reporting a failed state capture as exit code 127 hides the command's real exit code, and the same 127 is already used for "couldn't enter the directory", so a reader can't tell the three cases apart. Un-suppressing that bookkeeping step's error text also means it now lands in what the model reads back as the command's own stderr. The Windows branch of the same script got no equivalent check, so this failure is loud on Linux/macOS and still silent on Windows. Either way, nothing in the diff tests it.

Real-world evidence

N/A — no evidence bundle was produced for this PR, and the shell tools' surface couldn't be exercised here (the review environment had no working shell, so gh pr view and any CLI run were unavailable). The verdict rests on static review alone. The change is CLI/agent-tool-facing, so a short run_shell_command transcript showing a cd + export + get_shell_state round trip — plus one run that exits non-zero — would close the gap.

🔍 Technical details

Issues

🟡 TemporaryDirectory.cleanup() raises where shutil.rmtree(ignore_errors=True) did not (src/gaia/agents/tools/shell_session.py:365)

_discard_temp_dir is called from two places: close() (shell_session.py:356) and the finally of run() (shell_session.py:492, reached when the session was closed while the command was still running — the #2600 straggler path the docstring calls out). cleanup() propagates PermissionError / OSError; a raise from that finally discards the ShellResult that run() was about to return. Note the asymmetry three lines above: the per-file os.remove loop already catches OSError and logs it, so the module has already decided teardown failures are not fatal.

Python ≥3.10 is the floor (setup.py:353), so ignore_cleanup_errors is available, and it also covers the implicit finalizer path the new GC test relies on:

            self._temp_directory = tempfile.TemporaryDirectory(
                prefix="gaia_shell_", ignore_cleanup_errors=True
            )

🟡 || exit 127 overwrites the command's exit code and unmutes the bookkeeping group's stderr (shell_session.py:540)

Two changes in one line. { pwd; printf …; awk … } > state_file || exit 127 replaces exit $__gaia_rc (shell_session.py:542) whenever the capture fails — so a command that really exited 0 or 2 is reported as 127, which _build_script already uses for "cd failed" (shell_session.py:523) and which a real command can also return. Dropping 2>/dev/null sends awk's/pwd's own diagnostics into the subprocess stderr that run_shell_command hands back as the command's stderr (shell_tools.py:1154).

Agreed the old 2>/dev/null was a silent-degradation violation; the fix shape is the question. Surfacing it through the existing dedicated channel keeps both signals intact — ShellResult.cwd_change_rejected already sets response["warning"] (shell_tools.py:1163-1164) and a state_capture_failed sibling would fit there. Failing that, at least use a distinct sentinel and keep the group's stderr redirected, so the three 127s stay distinguishable.

The cmd.exe branch (shell_session.py:556-561) writes its state block with no if errorlevel check and still exit /b %__GAIA_RC%, so the new loudness is POSIX-only — worth matching, or noting why not.

No test covers either behaviour: a case where the state file is unwritable (or awk unavailable) asserting what return_code and stderr come back would pin it.

Nits

🟢 Function-local imports in tests (tests/unit/test_shell_session.py:258, tests/unit/test_shell_tools_session.py:174) — import gc and from unittest.mock import MagicMock sit inside the test bodies; both files already import at module scope.

🟢 The GC test depends on refcount timing (test_shell_session.py:252-268) — del shell; gc.collect() works on CPython but any lingering frame reference (a failed assertion earlier in the test, a debugger) makes it flaky. Asserting on shell._temp_directory._finalizer having run, or wrapping the session in a weakref, is sturdier. Low priority — the current form does test the real thing.

Strengths

  • prompt_user=False on the cwd guard closes a quiet escalation (shell_tools.py:355-356). Previously a cd into a forbidden directory could trigger the interactive prompt in PathValidator._prompt_user_for_access, and an "[a]lways" answer would permanently widen allowed_paths from what is really just internal state absorption. The new test asserts both the return value and the keyword, so it can't silently regress.
  • COLUMNS/LINES in _VOLATILE_ENV_NAMES is the right layer — the existing _absorb_state loops already exclude volatile names from both the override and the unset sides (shell_session.py:620, 625), so terminal resize noise can't masquerade as an agent change in either direction.
  • The manifest tool counts are drift-guarded, not hand-trusted — test_chat_fix_contracts.py introspects the real registry per profile, so these literals fail CI rather than rot.

…esult

Closing a session while a command is still running hands the temp-directory
removal to that command, which does it from run()'s finally. TemporaryDirectory
.cleanup() propagates OSError, so on Windows a file still held by a just-killed
child turned a finished command into an exception instead of a ShellResult --
exactly the hung-command case this path exists for.

Log and continue, matching the per-file os.remove loop three lines above, which
had already made that call for this module. Not ignore_cleanup_errors=True: that
is crash-safe but silent, and would drop the diagnostic the neighbouring code
deliberately keeps.

The new test pins the contract run()'s finally depends on; it raises
PermissionError out of _discard_temp_dir without the fix.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

The blocking item is fixed, but with a different fix than the one suggested — the suggested one is crash-safe and silent, and this file had already decided the other way three lines above.

A failed temp-directory teardown no longer costs the caller a finished command. It now logs and continues, exactly like the per-file deletion loop immediately above it, so the crash goes away and the diagnostic survives. ignore_cleanup_errors=True would have bought the first and thrown away the second.

The second finding — three different conditions all reporting exit code 127 — is real, and I have deliberately not touched it. Picking a new sentinel and deciding whether the Windows branch follows is a shape decision that belongs with #3400, which this PR is stacked on and which is still waiting on a design call. Fixing it here would commit that decision by accident.

Worth knowing regardless of the review: this can't merge ahead of #3400.

🔍 Technical details

Fixed in e6b96b05c — src/gaia/agents/tools/shell_session.py:365:

    def _discard_temp_dir(self) -> None:
        directory, self._temp_directory = self._temp_directory, None
        self._temp_dir = None
        if directory is not None:
            # Runs from run()'s finally: a raise here would discard the
            # ShellResult the command already produced.
            try:
                directory.cleanup()
            except OSError as exc:
                logger.warning(
                    "Could not remove shell session temp directory %s: %s",
                    directory.name, exc,
                )

Why not ignore_cleanup_errors=True: it suppresses the error on both paths, including the explicit close() call where nothing is racing and a failure genuinely wants reporting. The os.remove loop at shell_session.py:486-490 already catches OSError and logs — matching it keeps one teardown policy in the module instead of two.

On the claim that the flag "covers the implicit finalizer path the new GC test relies on" — it isn't load-bearing there. TemporaryDirectory's finalizer runs under weakref.finalize, so an exception from it is already non-propagating (CPython prints Exception ignored in: and moves on); it could never have taken out a caller. And test_unused_host_session_cleans_up_when_collected asserts the directory is gone, so error-tolerance would not help it pass — only actual removal does.

The missing test now exists. test_undeletable_temp_dir_does_not_swallow_the_command_result replaces cleanup with one that raises OSError(13), asserts _discard_temp_dir returns normally, and asserts the warning was emitted — so a future change back to silent-ignore fails too. Verified load-bearing by reverting the fix:

src\gaia\agents\tools\shell_session.py:369: in _discard_temp_dir
    directory.cleanup()
E   PermissionError: [Errno 13] file in use by another process
FAILED tests/unit/test_shell_session.py::TestExecution::test_undeletable_temp_dir_does_not_swallow_the_command_result

With the fix, tests/unit/test_shell_session.py + tests/unit/test_shell_tools_session.py: 43 passed. black and isort clean.

On the 127 collision. Agreed on the substance: { pwd; printf …; awk … } > state_file || exit 127 (shell_session.py:540) overwrites a real exit code, collides with the cd-failed 127 at :523, and un-redirecting the group's stderr routes awk/pwd diagnostics into what run_shell_command hands back as the command's own stderr. Also agreed the original 2>/dev/null was the wrong answer. The open question is the replacement — a state_capture_failed flag alongside cwd_change_rejected, versus a distinct numeric sentinel — and whether cmd.exe (:556-561) grows the matching check. That is #3400's call, not a maintenance PR's.

Evidence gap noted in the review: the shell surface was exercised here — 43 real-subprocess tests on Windows, including the new teardown case. What is still unexercised is the run-mid-close race under a real hung command, which is what the 127 path serves.

…nd's result

`_discard_temp_dir` runs from `run()`'s `finally` when the session was closed
while the command was still going — the straggler path this code exists for.
`TemporaryDirectory.cleanup()` propagates, so on Windows a file a just-killed
child still holds would raise there and discard the `ShellResult` that was
about to be returned.

`ignore_cleanup_errors=True` matches what the per-file `os.remove` loop three
lines above already does, and covers the implicit finalizer too.

Co-Authored-By: Claude Opus 5 <[email protected]>
@github-actions github-actions Bot added the documentation Documentation changes label Sep 23, 2026
@itomek

itomek commented Sep 25, 2026

Copy link
Copy Markdown
Collaborator

Closing this as superseded — the design it repairs is no longer on its own base branch.

kalin/shell-session-3380-clean replaced the persistent shell session with a different implementation: a 699-line component that generated a per-command shell script, ran it in a subprocess, and parsed a pwd/environment dump back out became a 100-line object that holds a working directory and nothing else. Every fix in this PR patches that removed machinery — the awk environment dump, the temp-directory teardown, the exit 127 sentinel. The new file's own docstring names those same bugs as the reason for the rewrite.

Nothing is lost. #3400 carries the replacement and has since gained its own follow-up fix; #3380 still tracks the feature. Your own note here — "this can't merge ahead of #3400" — is what this comment is agreeing with, one step further. The exit 127 collision you deliberately deferred is moot: there is no exit 127 on the branch anymore.

Two scraps survive and both are already nits on #3400 rather than reasons to keep this open: close_shell_session() still has no caller, and docs/sdk/mixins/tool-mixins.mdx doesn't list the two session tools.

🔍 Technical details

Refs. Base branch head 35bafdc9; this PR's head 308a1f9b; merge-base 38bc3669. The PR was never rebased onto the redesign — the merge-base still predates it, and git cherry marks all 9 commits +.

src/gaia/agents/tools/shell_session.py

this PR base branch
lines 699 100
imports subprocess, tempfile, … pathlib, typing only
awk ENVIRON dump yes 0
tempfile.TemporaryDirectory yes 0
exit 127 2 0
public surface script gen + Popen + state parse cwd / set_cwd / reset / close

Scoped precisely: the session object no longer spawns anything. shell_tools.py still imports subprocess — execution moved out of the session into module-level _run_pipeline / _run_step.

Per-commit applicability. 179199b0 (awk's own variables) → no awk on base. e6b96b05 + 308a1f9b (temp-dir teardown) → no temp dir on base. ad5d4042 (bandit suppressions for the session's Popen calls) → those calls don't exist; base's .security-suppressions.json has no shell_session.py entry. 1c5b3dc6 (prompt_user=False cwd guard) → base unified the guard with the same _path_allowed that working_directory already used; that code is origin/main's verbatim, and _prompt_user_for_access auto-denies when non-interactive.

Not reparable by rebase. 12 of 15 files conflict, and shell_session.py plus its test conflict add/add — stages 2 and 3 with no stage 1, i.e. no common ancestor blob for a merge to reconcile.

The merge direction is regressive. Taking this PR's side reverts hub/agents/gaia/python/gaia-agent.yaml from version: 0.2.0 / tools_count: 83 / min_gaia_version: 0.24.1 to 0.1.1 / 71 / 0.23.0, and drops ~190 lines of security tests including the gh auth status --show-token credential-leak guard. The three files that merge cleanly are the hazardous ones: tests/unit/test_shell_tools_session.py and docs/sdk/mixins/tool-mixins.mdx call and document set_shell_variable, which has zero occurrences anywhere on base — so they'd land a red test file and false docs with no conflict marker.

CI. No test job ever ran here. All ~30 lanes are pull_request-gated to main and this targets a feature branch; only label and pr-rereview execute.

@itomek itomek closed this Sep 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants