The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(installer): hold the venv rollback source through dependency validation (#83149)
Tekniumaa5a960675d9
diff --git a/scripts/install.ps1 b/scripts/install.ps1index 00dd9c65772..6554e201d37 100644--- a/scripts/install.ps1+++ b/scripts/install.ps1@@ -2502,23 +2502,25 @@ function Install-Venv {throw "uv reported success but venv interpreter is missing at $venvPythonExe"}- # The replacement is usable. The old tree is no longer needed for rollback;- # deletion is safe here because it cannot gut the live venv. A locked old- # tree remains parked and is retried by the cleanup pass below.+ # The replacement has a working interpreter, but the transaction is only+ # committed after Install-Dependencies' baseline-import gate passes -- the+ # bootstrap runs the stages as separate processes, and every dependency+ # tier (or the import validation) can still fail after this stage+ # succeeds. Record the parked backup so the dependency stage can restore+ # it on failure and commit its cleanup only after validation (#83149).if ($venvParked) {- Remove-Item -LiteralPath $venvBackupName -Recurse -Force -ErrorAction SilentlyContinue- if (Test-Path -LiteralPath $venvBackupName) {- Write-Warn "Old venv parked at $venvBackupName (a process still holds files in it); it will be cleaned up on the next install"- } else {- $venvParked = $false- }+ Set-Content -LiteralPath (Join-Path $InstallDir "venv.pending-backup") -Value $venvBackupName -Encoding ascii+ Write-Info "Previous venv parked at $venvBackupName until the dependency install is verified"}# Clean up parked venvs from previous installs whose handles have since# been released. Best-effort -- a still-held tree just stays for next time.- Get-ChildItem -Directory -Filter "venv.stale.*" -ErrorAction SilentlyContinue | ForEach-Object {- Remove-Item -Recurse -Force $_.FullName -ErrorAction SilentlyContinue- }+ # The backup parked THIS run is excluded: it is the rollback source until+ # Install-Dependencies commits the transaction.+ Get-ChildItem -Directory -Filter "venv.stale.*" -ErrorAction SilentlyContinue |+ Where-Object { $_.Name -ne $venvBackupName } | ForEach-Object {+ Remove-Item -Recurse -Force $_.FullName -ErrorAction SilentlyContinue+ }# Neutralize any inherited UV_PYTHON (e.g. $env:UV_PYTHON = "3.14" left in# the user's shell). uv honours UV_PYTHON over an existing venv for the@@ -2584,6 +2586,55 @@ function Install-Venv {Write-Success "Virtual environment ready (Python $PythonVersion)"}+function Get-PendingVenvBackup {+ # Rollback source recorded by Install-Venv (#83149). Returns the parked+ # directory name, or $null when there is nothing to roll back to. A marker+ # pointing at a directory that no longer exists is stale -- drop it.+ $markerPath = Join-Path $InstallDir "venv.pending-backup"+ if (-not (Test-Path -LiteralPath $markerPath -PathType Leaf)) { return $null }+ $name = (Get-Content -LiteralPath $markerPath -ErrorAction SilentlyContinue | Select-Object -First 1)+ if ($name) { $name = $name.Trim() }+ if (-not $name -or -not (Test-Path -LiteralPath (Join-Path $InstallDir $name))) {+ Remove-Item -LiteralPath $markerPath -Force -ErrorAction SilentlyContinue+ return $null+ }+ return $name+}++function Complete-VenvTransaction {+ # Commit: dependency install + baseline imports passed, so the previous+ # venv is no longer needed as a rollback source. Best-effort delete; a+ # tree still held open just stays parked for the next install's sweep.+ $backupName = Get-PendingVenvBackup+ if (-not $backupName) { return }+ $backupPath = Join-Path $InstallDir $backupName+ Remove-Item -LiteralPath $backupPath -Recurse -Force -ErrorAction SilentlyContinue+ if (Test-Path -LiteralPath $backupPath) {+ Write-Warn "Old venv parked at $backupName (a process still holds files in it); it will be cleaned up on the next install"+ }+ Remove-Item -LiteralPath (Join-Path $InstallDir "venv.pending-backup") -Force -ErrorAction SilentlyContinue+}++function Restore-VenvBackup {+ # Rollback: the dependency stage failed after Install-Venv replaced the+ # venv. Park the unusable replacement and restore the previous working+ # venv so Hermes (and the venv-blocker probe) stay usable (#83149).+ $backupName = Get-PendingVenvBackup+ if (-not $backupName) { return }+ try {+ if (Test-Path -LiteralPath (Join-Path $InstallDir "venv")) {+ $failedVenvName = "venv.failed.{0}-{1}" -f (Get-Date -Format "yyyyMMddHHmmss"), ([Guid]::NewGuid().ToString("N"))+ Rename-Item -LiteralPath (Join-Path $InstallDir "venv") -NewName $failedVenvName -ErrorAction Stop+ Write-Warn "Failed replacement parked at $failedVenvName"+ }+ Rename-Item -LiteralPath (Join-Path $InstallDir $backupName) -NewName "venv" -ErrorAction Stop+ Remove-Item -LiteralPath (Join-Path $InstallDir "venv.pending-backup") -Force -ErrorAction SilentlyContinue+ Write-Warn "Restored previous virtual environment after failed dependency install"+ } catch {+ Write-Warn "Could not restore previous venv (still parked at $backupName): $($_.Exception.Message)"+ }+}+function Install-Dependencies {Write-Info "Installing dependencies..."@@ -2618,6 +2669,12 @@ function Install-Dependencies {# without any hash verification -- they exist to keep installs working# when the lockfile is stale, missing, or out-of-sync with the# current extras spec, NOT because they're equivalent in posture.+ #+ # Everything through the baseline-import gate runs inside the venv+ # transaction opened by Install-Venv (#83149): on any failure the parked+ # previous venv is restored before the error propagates, and the parked+ # tree is deleted only after the imports prove the replacement usable.+ try {if (Test-Path "uv.lock") {Write-Info "Trying tier: hash-verified (uv.lock) ..."# Critical flag choice: `--extra all`, NOT `--all-extras`.@@ -2759,6 +2816,19 @@ except Exception:Write-Success "Baseline imports verified in venv"}+ # Commit the venv transaction: the dependency install completed and the+ # baseline imports passed, so the previous venv is no longer needed as a+ # rollback source (#83149).+ Complete-VenvTransaction+ } catch {+ # Dependency install or import validation failed: restore the previous+ # working venv (parked by Install-Venv) before surfacing the error, so+ # a failed update leaves Hermes and its blocker probe usable.+ Restore-VenvBackup+ Pop-Location+ throw+ }+if (-not $NoVenv) {# uv on Windows can register hermes.exe in dist-info/RECORD but fail to# materialise the .exe (file lock during self-update, distlib edge case).diff --git a/tests/test_install_ps1_venv_transaction_boundary.py b/tests/test_install_ps1_venv_transaction_boundary.pynew file mode 100644index 00000000000..52f4183ec85--- /dev/null+++ b/tests/test_install_ps1_venv_transaction_boundary.py@@ -0,0 +1,106 @@+"""Transaction-boundary regression for Windows venv recreation (#83149).++Review finding on PR #83194 (egilewski): the rollback source (the parked+previous venv) was deleted as soon as ``Install-Venv`` saw a working+interpreter in the replacement — but ``Install-Dependencies`` is a separate,+later stage (a separate *process* under the stage-per-process bootstrap) and+every dependency tier or the baseline-import gate can still fail after that+point. Deleting the backup early re-creates exactly the availability failure+the transactional recreate exists to prevent.++The contract locked here:++* ``Install-Venv`` records the parked backup in ``venv.pending-backup``+ instead of deleting it, and its stale-tree sweep excludes that backup.+* ``Install-Dependencies`` restores the previous venv on failure+ (``Restore-VenvBackup``) and commits the cleanup only after the+ baseline-import gate passes (``Complete-VenvTransaction``).++The script only runs on Windows, so Linux CI locks the contract at the+source level, same approach as tests/test_install_ps1_venv_recreate_safety.py.+"""++from pathlib import Path++INSTALL_PS1 = Path(__file__).resolve().parents[1] / "scripts" / "install.ps1"+++def _function_body(source: str, function_name: str) -> str:+ start = source.index(f"function {function_name}")+ opening_brace = source.index("{", start)+ depth = 0+ for index in range(opening_brace, len(source)):+ if source[index] == "{":+ depth += 1+ elif source[index] == "}":+ depth -= 1+ if depth == 0:+ return source[opening_brace : index + 1]+ raise AssertionError(f"unterminated function: {function_name}")+++def _source() -> str:+ return INSTALL_PS1.read_text(encoding="ascii")+++def test_install_venv_does_not_delete_backup_before_dependency_stage() -> None:+ """The parked previous venv must survive Install-Venv's success path."""+ body = _function_body(_source(), "Install-Venv")++ # The success path records the rollback source instead of deleting it.+ assert "venv.pending-backup" in body+ # The only backup deletion allowed inside Install-Venv is the *rollback*+ # rename in the catch block; a Remove-Item of the backup must not appear.+ assert "Remove-Item -LiteralPath $venvBackupName" not in body+++def test_install_venv_stale_sweep_excludes_current_backup() -> None:+ """The venv.stale.* sweep must not delete this run's rollback source."""+ body = _function_body(_source(), "Install-Venv")++ sweep_at = body.index('Get-ChildItem -Directory -Filter "venv.stale.*"')+ window = body[sweep_at : sweep_at + 400]+ assert "$_.Name -ne $venvBackupName" in window, (+ "the stale-tree sweep must exclude the backup parked by this run"+ )+++def test_install_dependencies_restores_backup_on_failure() -> None:+ """A failed dependency tier or import gate must restore the parked venv."""+ body = _function_body(_source(), "Install-Dependencies")++ assert "Restore-VenvBackup" in body+ catch_at = body.index("Restore-VenvBackup")+ assert "throw" in body[catch_at : catch_at + 400], (+ "rollback must rethrow the original failure after restoring"+ )+++def test_install_dependencies_commits_only_after_import_gate() -> None:+ """Backup cleanup must come after the baseline-import verification."""+ body = _function_body(_source(), "Install-Dependencies")++ import_gate = body.index("Baseline imports verified in venv")+ commit = body.index("Complete-VenvTransaction")+ assert import_gate < commit, (+ "the venv transaction must commit only after imports prove the "+ "replacement usable"+ )+++def test_restore_helper_parks_failed_replacement_and_restores_previous() -> None:+ body = _function_body(_source(), "Restore-VenvBackup")++ park = body.index("venv.failed.")+ restore = body.index('-NewName "venv"')+ assert park < restore, (+ "the failed replacement must be parked before the previous venv is "+ "renamed back into place"+ )+++def test_commit_helper_deletes_backup_and_clears_marker() -> None:+ body = _function_body(_source(), "Complete-VenvTransaction")++ assert "Remove-Item" in body+ assert "venv.pending-backup" in bodydiff --git a/website/docs/getting-started/updating.md b/website/docs/getting-started/updating.mdindex 6be78d26733..8f1a82d824e 100644--- a/website/docs/getting-started/updating.md+++ b/website/docs/getting-started/updating.md@@ -110,7 +110,7 @@ A second, separate guard refuses to touch the venv while any process is running#### Windows venv recreation is transactional-When the Windows installer must recreate an existing `venv`, it first moves the old directory to a unique `venv.stale.*` name, then creates and verifies the replacement. The old tree is deleted only after `venv\Scripts\python.exe` exists in the new tree.+When the Windows installer must recreate an existing `venv`, it first moves the old directory to a unique `venv.stale.*` name, then creates and verifies the replacement. The old tree is deleted only after the dependency install completes and the baseline imports pass in the new tree — until then it is the rollback source (recorded in `venv.pending-backup`).If the move cannot be completed, the installer stops and leaves the live `venv` untouched. If `uv` fails or reports success without creating the interpreter, any partial replacement is moved to `venv.failed.*` and the previous venv is restored. This keeps the health and blocker checks usable after a failed install.