Skip to content

The agent that grows with you

fix(install-e2e): tolerate the update-result consume race and held lock files (#135261)

ethernet4f9b741a3a02
diff --git a/tests-js/source-update-observer.test.mjs b/tests-js/source-update-observer.test.mjs
index 45d219ebfd5..88724f6c276 100644
--- a/tests-js/source-update-observer.test.mjs
+++ b/tests-js/source-update-observer.test.mjs
@@ -1,11 +1,19 @@
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
-import { afterEach, expect, test } from 'vitest'
+import { afterEach, expect, test, vi } from 'vitest'
import { observeSourceUpdate } from '../tests/install/e2e-assets/source-update-observer.mjs'
+// Lets a test play the relaunched app: it unlinks the result file after the
+// observer listed it and before the observer reads it.
+const hooks = vi.hoisted(() => ({ beforeRead: null }))
+vi.mock('node:fs', async importOriginal => {
+ const actual = await importOriginal()
+ return { ...actual, readFileSync: (...args) => { hooks.beforeRead?.(args[0]); return actual.readFileSync(...args) } }
+})
+
const roots = []
-afterEach(() => roots.splice(0).forEach(root => rmSync(root, { recursive: true, force: true })))
+afterEach(() => { hooks.beforeRead = null; roots.splice(0).forEach(root => rmSync(root, { recursive: true, force: true })) })
function fixture() {
const home = mkdtempSync(join(tmpdir(), 'source-update-observer-'))
roots.push(home)
@@ -39,4 +47,13 @@ test('failed handoff fails even at target SHA; success waits for marker removal'
expect(observe('target')).toBe(false)
rmSync(marker)
expect(observe('target')).toBe(true)
-})
\ No newline at end of file
+})
+
+test('a result file consumed by the relaunched app mid-poll does not abort the update', () => {
+ const f = fixture()
+ const observe = observeSourceUpdate({ ...f, expectSha: 'target' })
+ f.write('update_new.json', { outcome: 'success', finished_at: 'now', post_update: { sha: 'target' } })
+ writeFileSync(f.resultPath, JSON.stringify({ ok: true, exit_code: 0 }))
+ hooks.beforeRead = file => { if (file === f.resultPath) rmSync(file) }
+ expect(observe('target')).toBe(true)
+})
diff --git a/tests/install/e2e-assets/source-update-observer.mjs b/tests/install/e2e-assets/source-update-observer.mjs
index beecee4c716..a518f0b74f7 100644
--- a/tests/install/e2e-assets/source-update-observer.mjs
+++ b/tests/install/e2e-assets/source-update-observer.mjs
@@ -2,6 +2,15 @@
import { existsSync, readFileSync, readdirSync } from 'node:fs'
import { join } from 'node:path'
+// The relaunched app consumes (unlinks) the result file as soon as it boots, so
+// a file that was listed a moment ago can be gone by the time it is read.
+function readIfPresent(file) {
+ try { return readFileSync(file, 'utf8') } catch (error) {
+ if (error?.code === 'ENOENT') return null
+ throw error
+ }
+}
+
export function observeSourceUpdate({ home, resultPath, expectSha }) {
const directory = join(home, 'logs/update_receipts')
const files = () => [
@@ -10,12 +19,12 @@ export function observeSourceUpdate({ home, resultPath, expectSha }) {
.filter(name => name.startsWith('update_') && name.endsWith('.json'))
.map(name => join(directory, name)) : []),
]
- const before = new Map(files().map(file => [file, readFileSync(file, 'utf8')]))
+ const before = new Map(files().map(file => [file, readIfPresent(file)]))
return head => {
let complete = false
for (const file of files()) {
- const text = readFileSync(file, 'utf8')
- if (before.get(file) === text) continue
+ const text = readIfPresent(file)
+ if (text === null || before.get(file) === text) continue
let data
try { data = JSON.parse(text.replace(/^\uFEFF/, '')) } catch { continue }
if (file === resultPath) {
diff --git a/tests/install/e2e-assets/verify-user-state.py b/tests/install/e2e-assets/verify-user-state.py
index d3087d721d4..ba7f64ae5df 100644
--- a/tests/install/e2e-assets/verify-user-state.py
+++ b/tests/install/e2e-assets/verify-user-state.py
@@ -277,12 +277,24 @@ def _env_line_summary(path: str) -> dict:
def _entry_record(abs_path: str) -> dict:
+ try:
+ return _read_entry_record(abs_path)
+ except OSError as exc:
+ raise ScanError(f"unreadable {abs_path}: {exc}") from exc
+
+
+def _read_entry_record(abs_path: str) -> dict:
if _is_link(abs_path):
record: dict = {"kind": "symlink", "target": os.readlink(abs_path)}
record["target_resolves"] = os.path.exists(os.path.realpath(abs_path))
return record
if os.path.isdir(abs_path):
return {"kind": "dir"}
+ if os.path.isfile(abs_path) and abs_path.endswith(".lock"):
+ # A lock file is a sentinel a live process holds, never user content. On
+ # Windows the holder's msvcrt byte-range lock makes every read of it
+ # raise EACCES, so reading it would fail the upgrade for the holder.
+ return {"kind": "lock"}
if os.path.isfile(abs_path):
st = os.lstat(abs_path)
record = {"kind": "file", "size": st.st_size}
diff --git a/tests/scripts/test_verify_user_state.py b/tests/scripts/test_verify_user_state.py
index 5f090c6e74c..07d52a5af6a 100644
--- a/tests/scripts/test_verify_user_state.py
+++ b/tests/scripts/test_verify_user_state.py
@@ -341,6 +341,57 @@ def test_cron_ticker_stamps_move_but_user_cron_state_still_fails(tmp_path):
assert report["ok"] is False
+def test_a_lock_file_is_a_sentinel_not_user_content(tmp_path):
+ """A live process's lock file is never user state and is never read.
+
+ Regression for the Windows install/update E2E: the gateway's cron ticker
+ holds a byte-range lock on ``cron/.tick.lock``, so hashing it raised
+ ``PermissionError`` and failed the upgrade for the harness's own ticker.
+ """
+ home = tmp_path / "home"
+ (home / "cron").mkdir(parents=True)
+ lock = home / "cron" / ".tick.lock"
+ lock.write_text("", encoding="utf-8")
+ snap = vus.snapshot_home(str(home))
+ assert snap["entries"]["cron/.tick.lock"] == {"kind": "lock"}
+
+ lock.write_text("held", encoding="utf-8")
+ assert vus.verify_home(str(home), snap)["ok"] is True
+
+
+def test_snapshot_survives_a_byte_range_lock_held_by_another_handle(tmp_path):
+ import msvcrt
+
+ home = tmp_path / "home"
+ (home / "cron").mkdir(parents=True)
+ with open(home / "cron" / ".tick.lock", "w", encoding="utf-8") as holder:
+ msvcrt.locking(holder.fileno(), msvcrt.LK_NBLCK, 1)
+ try:
+ snap = vus.snapshot_home(str(home))
+ finally:
+ msvcrt.locking(holder.fileno(), msvcrt.LK_UNLCK, 1)
+ assert snap["entries"]["cron/.tick.lock"] == {"kind": "lock"}
+
+
[email protected](os.geteuid() == 0 if hasattr(os, "geteuid") else False,
+ reason="root reads a mode-000 file")
+def test_an_unreadable_user_file_fails_the_scan_naming_the_path(tmp_path):
+ """Skipping lock files must not hide a user file the verifier cannot read."""
+ home = tmp_path / "home"
+ (home / "memories").mkdir(parents=True)
+ note = home / "memories" / "note.md"
+ note.write_text("remember\n", encoding="utf-8")
+ note.chmod(0)
+ try:
+ with pytest.raises(vus.ScanError, match="note.md") as caught:
+ vus.snapshot_home(str(home))
+ finally:
+ note.chmod(0o600)
+ assert isinstance(caught.value.__cause__, PermissionError)
+
+
def test_a_dotenv_changed_only_in_comments_is_reported_as_such(tmp_path):
"""The per-key digests ignore comments, order and blanks by design.