From c64fe9aa53f55ac5915b7d9bbdedbf530d082e9d Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:22:49 +0800 Subject: [PATCH] fix(control-plane): prune stale runtime locators, tighten server/SQLite hygiene, and clarify CLI diagnostics Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/cli_commands/quota_context.py | 22 +- .../coordination/authority_state_log.ts | 10 +- .../coordination/authority_store_codec.ts | 41 +- .../coordination/sqlite_authority_store.ts | 67 +- loopx/control_plane/effect_runtime.py | 406 ++++++++- .../control_plane/effect_runtime_exchange.ts | 103 ++- .../control_plane/effect_runtime_handlers.ts | 12 +- loopx/control_plane/effect_runtime_server.ts | 121 ++- .../control_plane/work_items/stride_policy.ts | 2 +- .../test_effect_runtime_locator_recovery.py | 778 ++++++++++++++++++ .../test_quota_settlement_cli.py | 28 +- .../effect_runtime_hygiene.test.ts | 275 +++++++ tests/control_plane_ts/stride_policy.test.ts | 5 +- 13 files changed, 1743 insertions(+), 127 deletions(-) create mode 100644 tests/control_plane_ts/effect_runtime_hygiene.test.ts diff --git a/loopx/cli_commands/quota_context.py b/loopx/cli_commands/quota_context.py index 29327421d4..398ef5699c 100644 --- a/loopx/cli_commands/quota_context.py +++ b/loopx/cli_commands/quota_context.py @@ -1,7 +1,7 @@ from __future__ import annotations import argparse -from collections.abc import Callable, Mapping +from collections.abc import Callable, Iterable, Mapping from dataclasses import dataclass from pathlib import Path @@ -118,6 +118,17 @@ def _scheduler_execution_context_from_args( return None +def _format_runtime_profile_choices( + profiles: Iterable[SchedulerRuntimeProfile], +) -> str: + names = sorted(profile.value for profile in profiles) + if len(names) <= 1: + return "".join(names) + if len(names) == 2: + return f"{names[0]} or {names[1]}" + return f"{', '.join(names[:-1])}, or {names[-1]}" + + def validate_quota_command_context_request( args: argparse.Namespace, ) -> tuple[ @@ -260,10 +271,13 @@ def validate_quota_command_context_request( if begin_turn: profile = scheduler_runtime_profile_for_execution_context(scheduler_context) if profile not in GUIDED_START_TURN_RUNTIME_PROFILES: + allowed_profiles = _format_runtime_profile_choices( + GUIDED_START_TURN_RUNTIME_PROFILES + ) raise QuotaCommandValidationError( - "--begin-turn requires runtime-profile codex_app_heartbeat, " - "trae_app, or codex_app_ssh_goal; every other host starts its turn by " - "passing its own --turn-instance-id" + f"--begin-turn requires runtime-profile {allowed_profiles}; " + "every other host starts its turn by passing its own " + "--turn-instance-id" ) if ( (heartbeat_turn_id or begin_turn) diff --git a/loopx/control_plane/coordination/authority_state_log.ts b/loopx/control_plane/coordination/authority_state_log.ts index 1b82928d20..f5651af431 100644 --- a/loopx/control_plane/coordination/authority_state_log.ts +++ b/loopx/control_plane/coordination/authority_state_log.ts @@ -23,6 +23,7 @@ import { canonicalAuthorityObject, canonicalAuthoritySha256, copyAuthorityJson, + hashCanonicalCommitEnvelope, isAuthorityJsonObject, } from "./authority_store_codec.ts"; @@ -238,12 +239,9 @@ export class AuthorityStateReplay { // Canonicalize the ordinary envelope, inserting our owned projection's // exact bytes at its key. This is the existing v0 digest, not a Merkle hash // or a new persistent proof. Integer-like keys obey native JSON ordering. - const envelope = canonicalAuthorityObject({...fields, next_projection: null}, "commit proof"); - const keys = Object.keys(envelope), split = keys.indexOf("next_projection"); - const field = (key: string) => JSON.stringify(key) + ":" + JSON.stringify(envelope[key]); - const before = keys.slice(0, split).map(field), after = keys.slice(split + 1).map(field); - const hash = createHash("sha256").update("{" + (before.length ? before.join(",") + "," : "") + '"next_projection":'); - return this.#updateProjection(hash).update((after.length ? "," + after.join(",") : "") + "}").digest("hex"); + return hashCanonicalCommitEnvelope(fields, (hash) => { + this.#updateProjection(hash); + }); } #updateProjection(hash: Hash): Hash { diff --git a/loopx/control_plane/coordination/authority_store_codec.ts b/loopx/control_plane/coordination/authority_store_codec.ts index 93bd923468..8e44485628 100644 --- a/loopx/control_plane/coordination/authority_store_codec.ts +++ b/loopx/control_plane/coordination/authority_store_codec.ts @@ -1,4 +1,4 @@ -import { createHash } from "node:crypto"; +import { createHash, type Hash } from "node:crypto"; import type { JsonObject } from "../effect_program.ts"; import type { AuthorityStoreCommit } from "./authority_store.ts"; @@ -147,20 +147,16 @@ function cloneAuthorityJson(value: unknown, stack: Set, canonicalKeys: b stack.add(value); try { const keys = Object.keys(value); - if (!canonicalKeys) { - // Fill without inherited setters (including __proto__), then normalize - // to the same ordinary object as Object.fromEntries. No per-field tuples. - const copy: JsonObject = Object.create(null); - for (const key of keys) copy[key] = cloneAuthorityJson(value[key], stack, false); - return Object.setPrototypeOf(copy, Object.prototype); + if (canonicalKeys && keys.length > 1) { + keys.sort(authorityUnicodeCompare); } - keys.sort(authorityUnicodeCompare); - return Object.fromEntries( - keys.map((key) => [ - key, - cloneAuthorityJson(value[key], stack, canonicalKeys), - ]), - ); + // Fill without inherited setters (including __proto__), then normalize + // to an ordinary object. Avoids intermediate per-field tuple arrays. + const copy: JsonObject = Object.create(null); + for (const key of keys) { + copy[key] = cloneAuthorityJson(value[key], stack, canonicalKeys); + } + return Object.setPrototypeOf(copy, Object.prototype); } finally { stack.delete(value); } @@ -196,6 +192,23 @@ export function canonicalAuthoritySha256(value: unknown): string { return createHash("sha256").update(canonicalAuthorityBytes(value)).digest("hex"); } +/** + * Hash a commit envelope when the caller already owns the canonicalized + * `next_projection` bytes or stream, avoiding a duplicate full-tree clone. + */ +export function hashCanonicalCommitEnvelope( + fields: Omit, + writeProjection: (hash: Hash) => void, +): string { + const envelope = canonicalAuthorityObject({...fields, next_projection: null}, "commit proof"); + const keys = Object.keys(envelope), split = keys.indexOf("next_projection"); + const field = (key: string) => JSON.stringify(key) + ":" + JSON.stringify(envelope[key]); + const before = keys.slice(0, split).map(field), after = keys.slice(split + 1).map(field); + const hash = createHash("sha256").update("{" + (before.length ? before.join(",") + "," : "") + '"next_projection":'); + writeProjection(hash); + return hash.update((after.length ? "," + after.join(",") : "") + "}").digest("hex"); +} + export function parseAuthorityCursor(value: string | null): bigint { if (value === null) return 0n; if (typeof value !== "string" || !/^[1-9]\d*$/.test(value)) { diff --git a/loopx/control_plane/coordination/sqlite_authority_store.ts b/loopx/control_plane/coordination/sqlite_authority_store.ts index deb33f19c1..0bc78f1e0e 100644 --- a/loopx/control_plane/coordination/sqlite_authority_store.ts +++ b/loopx/control_plane/coordination/sqlite_authority_store.ts @@ -3,14 +3,14 @@ import { createHash, randomUUID } from "node:crypto"; import { existsSync, mkdirSync, statSync } from "node:fs"; import {sqliteAuthorityRuntime} from "./sqlite_runtime.ts"; import { dirname, join } from "node:path"; -import type { DatabaseSync } from "node:sqlite"; +import type { DatabaseSync, StatementSync } from "node:sqlite"; import type { JsonObject } from "../effect_program.ts"; import type { AuthorityStore, AuthorityStoreCommit, AuthorityStoreCommitResult, AuthorityStoreCommittedTransaction, AuthorityStoreIdentityResult, AuthorityStoreLoadResult, AuthorityStoreSnapshotResult, AuthorityStoreReadFailure, AuthorityStoreHead, AuthorityStoreReceiptResult, AuthorityStoreReceiptBatchResult, AuthorityStoreScanResult } from "./authority_store.ts"; import { AuthorityStoreProtocolError, canonicalAuthorityBytes, canonicalAuthorityObject, - canonicalAuthorityObjectList, canonicalAuthoritySha256, + canonicalAuthorityObjectList, canonicalAuthoritySha256, hashCanonicalCommitEnvelope, normalizeAuthorityStoreCommit, requireAuthorityStoreId } from "./authority_store_codec.ts"; import { AUTHORITY_STATE_CHECKPOINT_INTERVAL, @@ -18,7 +18,6 @@ import { authorityStateCheckpointCursor, authorityStateDelta, authorityStateDeltaReconstructs, - authorityStateDigest, authorityStateReplayBudget, decodeAuthorityStateDelta, isAuthorityStateCheckpoint, @@ -187,8 +186,10 @@ export class SqliteAuthorityStore implements AuthorityStore { db.exec("PRAGMA busy_timeout = 5000; PRAGMA foreign_keys = ON;"); if (write) { db.exec("PRAGMA journal_mode = WAL; PRAGMA synchronous = FULL;"); - db.exec("BEGIN IMMEDIATE"); + let inTransaction = false; try { + db.exec("BEGIN IMMEDIATE"); + inTransaction = true; const version = Number(db.prepare("PRAGMA user_version").get()?.user_version ?? 0); if (version === 0) { // Never adopt an unrelated/unversioned database. @@ -201,7 +202,13 @@ export class SqliteAuthorityStore implements AuthorityStore { } this.identity(db); db.exec("COMMIT"); - } catch (error) { db.exec("ROLLBACK"); throw error; } + inTransaction = false; + } catch (error) { + if (inTransaction) { + try { db.exec("ROLLBACK"); } catch { /* close abandons active transaction */ } + } + throw error; + } } else this.identity(db); return db; } catch (error) { db.close(); throw error; } @@ -283,11 +290,16 @@ export class SqliteAuthorityStore implements AuthorityStore { return {cursor: row.cursor, digest: row.state_digest, replay}; } - private loadCheckpoint(db: DatabaseSync, cursor: bigint): SqliteReplayCursor { + private loadCheckpoint( + db: DatabaseSync, + cursor: bigint, + checkpointStmt?: StatementSync, + ): SqliteReplayCursor { const expected = authorityStateCheckpointCursor(cursor); - const row = db.prepare( + const stmt = checkpointStmt ?? db.prepare( "SELECT cursor, projection, projection_digest FROM checkpoints WHERE cursor = ?", - ).get(expected.toString()); + ); + const row = stmt.get(expected.toString()); if (!row) protocol("SQLite authority checkpoint is missing for its window"); const replay = new AuthorityStateReplay(this.parseJson(row.projection, "SQLite checkpoint projection")); const digest = this.requireDigest(row.projection_digest, "SQLite checkpoint digest"); @@ -361,8 +373,11 @@ export class SqliteAuthorityStore implements AuthorityStore { } const projection = canonicalAuthorityObject(this.parseJson(row.projection, "SQLite head projection"), "SQLite head projection"); + const projectionJson = JSON.stringify(projection); const digest = this.requireDigest(row.state_digest, "SQLite head state digest"); - if (authorityStateDigest(projection) !== digest) protocol("SQLite authority head digest mismatch"); + if (createHash("sha256").update(projectionJson, "utf8").digest("hex") !== digest) { + protocol("SQLite authority head digest mismatch"); + } const retained = db.prepare(`SELECT ${COMMIT_COLUMNS} FROM commits WHERE cursor = ?`).get(row.sequence); if (!retained) protocol("SQLite authority head has no retained transaction"); const newest = this.decodeCommitRow(retained as unknown as Record); @@ -374,8 +389,10 @@ export class SqliteAuthorityStore implements AuthorityStore { : newest.parent_state_digest !== parent?.state_digest) { protocol("SQLite authority head parent lineage is invalid"); } - if (newest.commit_digest !== - commitDigest(identity, cursor, newest.operation_id, projection, newest.events, newest.receipts)) { + if (newest.commit_digest !== hashCanonicalCommitEnvelope( + commitFields(identity, cursor, newest.operation_id, newest.events, newest.receipts), + (hash) => { hash.update(projectionJson, "utf8"); }, + )) { protocol("SQLite committed row digest mismatch"); } // Recovery of this head resumes from one retained checkpoint, so its @@ -514,26 +531,31 @@ export class SqliteAuthorityStore implements AuthorityStore { const next = (cursor ?? 0n) + 1n; if (next > MAX_SEQUENCE) protocol("SQLite authority sequence exhausted"); const before = current?.state ?? {cursor: 0n, projection: {}, digest: ""}; - const nextState = canonicalAuthorityObject(normalized.next_projection, "SQLite authority state"); + const nextState = normalized.next_projection; const delta = authorityStateDelta(before.projection, nextState); // The encoder is proved before it is persisted: replaying the stored // delta must reproduce the committed projection byte for byte. if (!authorityStateDeltaReconstructs(before.projection, delta, nextState)) { protocol("SQLite authority state delta does not reconstruct its commit"); } - const stateDigest = authorityStateDigest(nextState); + const nextStateJson = JSON.stringify(nextState); + const stateDigest = createHash("sha256").update(nextStateJson, "utf8").digest("hex"); + const nextCommitDigest = hashCanonicalCommitEnvelope( + commitFields(identity, next, normalized.operation_id, normalized.events, normalized.receipts), + (hash) => { hash.update(nextStateJson, "utf8"); }, + ); if (isAuthorityStateCheckpoint(next)) { db.prepare("INSERT INTO checkpoints VALUES (?, ?, ?)") - .run(next.toString(), JSON.stringify(nextState), stateDigest); + .run(next.toString(), nextStateJson, stateDigest); } db.prepare("INSERT INTO commits VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(next.toString(), normalized.operation_id, - commitDigest(identity, next, normalized.operation_id, nextState, normalized.events, normalized.receipts), + nextCommitDigest, stateDigest, cursor === null ? null : before.digest, JSON.stringify(delta), JSON.stringify(normalized.events), JSON.stringify(normalized.receipts)); db.prepare(`INSERT INTO head VALUES (1, ?, ?, ?) ON CONFLICT(singleton) DO UPDATE SET cursor = excluded.cursor, projection = excluded.projection, - state_digest = excluded.state_digest`).run(next.toString(), JSON.stringify(nextState), stateDigest); + state_digest = excluded.state_digest`).run(next.toString(), nextStateJson, stateDigest); committing = true; db.exec("COMMIT"); transactionOpen = false; return {status: "applied", provider_revision: `${identity}:${next}`, cursor: next.toString()}; @@ -570,9 +592,9 @@ export class SqliteAuthorityStore implements AuthorityStore { const head = this.current(db); if (head === null) return missing(); const ranges = new Map(); + const selectByOperation = db.prepare(`SELECT ${COMMIT_COLUMNS} FROM commits WHERE operation_id = ?`); const selected = operationIds.map(id => { - const row = db!.prepare(`SELECT ${COMMIT_COLUMNS} FROM commits WHERE operation_id = ?`) - .get(id) as unknown as Record | undefined; + const row = selectByOperation.get(id) as unknown as Record | undefined; if (!row) return null; const cursor = this.decodeCommitRow(row).cursor; const checkpoint = authorityStateCheckpointCursor(cursor); @@ -655,12 +677,15 @@ export class SqliteAuthorityStore implements AuthorityStore { return {schema_version: "loopx_sqlite_authority_history_audit_v0", status: "verified", commits: 0, checkpoints: 0}; } const counted = db.prepare("SELECT COUNT(*) AS count FROM checkpoints").get(); + const pageStmt = db.prepare(`SELECT ${COMMIT_COLUMNS} FROM commits WHERE cursor > ? ORDER BY cursor LIMIT ?`); + const checkpointStmt = db.prepare( + "SELECT cursor, projection, projection_digest FROM checkpoints WHERE cursor = ?", + ); let state: SqliteReplayCursor = {cursor: 0n, digest: "", replay: new AuthorityStateReplay({})}; let cursor = 0n; let commits = 0; for (;;) { - const rows = db.prepare(`SELECT ${COMMIT_COLUMNS} FROM commits WHERE cursor > ? ORDER BY cursor LIMIT ?`) - .all(cursor.toString(), BigInt(AUDIT_PAGE)) as unknown as Record[]; + const rows = pageStmt.all(cursor.toString(), BigInt(AUDIT_PAGE)) as unknown as Record[]; if (rows.length === 0) break; for (const raw of rows) { const row = this.decodeCommitRow(raw); @@ -668,7 +693,7 @@ export class SqliteAuthorityStore implements AuthorityStore { // delta can never diverge from the history it claims to extend. const replayed = this.verifyCommitRow(row, identity, {kind: "predecessor", state}); if (isAuthorityStateCheckpoint(row.cursor)) { - const checkpoint = this.loadCheckpoint(db, row.cursor); + const checkpoint = this.loadCheckpoint(db, row.cursor, checkpointStmt); const sealed = this.verifyCommitRow(row, identity, {kind: "sealed", state: checkpoint}); if (sealed.digest !== replayed.digest || sealed.replay.canonicalJson() !== replayed.replay.canonicalJson()) { diff --git a/loopx/control_plane/effect_runtime.py b/loopx/control_plane/effect_runtime.py index f03bf53c4a..90b8436b96 100644 --- a/loopx/control_plane/effect_runtime.py +++ b/loopx/control_plane/effect_runtime.py @@ -14,6 +14,7 @@ import tempfile import time import uuid +from collections import deque from collections.abc import Iterable, Iterator, Mapping from contextlib import ExitStack, closing, contextmanager, suppress from contextvars import ContextVar @@ -89,6 +90,30 @@ RUNTIME_RETRY_SETTLE_SECONDS = 0.25 RUNTIME_LOCATOR_RECOVERY_TIMEOUT_SECONDS = 1.0 _RUNTIME_PID_MAX = 0xFFFFFFFF +_STALE_RUNTIME_DESCRIPTOR_GRACE_SECONDS = 60.0 +_STALE_RUNTIME_DESCRIPTOR_MAX_INSPECT = 64 +_STALE_RUNTIME_DESCRIPTOR_MAX_REMOVALS = 32 +_STALE_RUNTIME_DESCRIPTOR_MAX_BYTES = 16 * 1024 +_STALE_RUNTIME_DESCRIPTOR_MAX_SCAN_STEPS = 512 +_STALE_CLEANUP_SWEEP_LIMIT = 4 +_STALE_CLEANUP_SWEEP_IDLE_SECONDS = 300.0 +_STALE_CLEANUP_SEEN_LOCK_LIMIT = 65536 + + +@dataclass +class _StaleCleanupSweep: + scandir_cm: Any + iterator: Iterator[os.DirEntry[str]] | None + pending_candidates: deque[os.DirEntry[str]] + seen_lock_names: set[str] + dir_identity: tuple[int, int] + scandir_fn: object + last_used_monotonic: float + + +_stale_cleanup_sweeps: dict[str, _StaleCleanupSweep] = {} +_stale_cleanup_sweeps_lock = Lock() +_stale_cleanup_generation = 0 DEFAULT_REQUEST_TIMEOUT_SECONDS = 10.0 # Canonical writers may wait 30 seconds for the per-Goal maintenance lock and # another 5 seconds for the provider lock. Keep the client connected through @@ -288,11 +313,7 @@ def _source_digest_location( def _private_directory(path: Path) -> bool: - try: - metadata = os.lstat(path) - except OSError: - return False - return stat.S_ISDIR(metadata.st_mode) and metadata.st_uid == os.getuid() and not metadata.st_mode & 0o077 + return _private_directory_identity(path) is not None def _read_source_digest(path: Path, key: str) -> str | None: @@ -744,6 +765,7 @@ def restart_effect_runtime(*, timeout: float = 5.0, wait_for_exit: bool = False) exit-time cache write, whereas filesystem cleanup requires observed exit. """ if _uses_stdio_runtime(): + close_stale_cleanup_sweeps() return _restart_stdio_runtime(timeout) fingerprint = _runtime_fingerprint() info_path = _runtime_info_path(fingerprint) @@ -766,6 +788,7 @@ def _stop_effect_runtime( """ identity = runtime_identity_from_info(info) if info is None: + close_stale_cleanup_sweeps(runtime_dir=info_path.parent) return _restart_result("not_running", stopped=False, identity=identity, info_path=info_path) pid, serving_token = info.get("pid"), info.get("token") # A runtime that is already closing must still be reported as pending @@ -793,6 +816,7 @@ def _stop_effect_runtime( stopped = True break time.sleep(0.05) + close_stale_cleanup_sweeps(runtime_dir=info_path.parent) return _restart_result( "stopped" if stopped else "shutdown_pending", stopped=stopped, identity=identity, info_path=info_path, ) @@ -971,15 +995,386 @@ def _runtime_info_for_request(path: Path, *, fingerprint: str) -> _RuntimeInfo | info = _read_info(path, fingerprint=fingerprint) if info is not None: return info + _cleanup_stale_runtime_descriptors(path.parent, exclude_path=path) return _recover_runtime_info(path, _inspect_info(path, fingerprint=fingerprint), fingerprint=fingerprint) +def _runtime_descriptor_lock_file_active( + lock_path: Path, + *, + now: float, + grace_seconds: float, + json_owner: bool, +) -> bool: + try: + st = lock_path.lstat() + except FileNotFoundError: + return False + except OSError: + return True + if not stat.S_ISREG(st.st_mode): + return True + if hasattr(os, "getuid") and st.st_uid != os.getuid(): + return True + if now - st.st_mtime < grace_seconds: + return True + if not json_owner: + holder_pid = _start_lock_holder_pid(lock_path) + return holder_pid is None or _recorded_pid_alive(holder_pid) is not False + try: + raw = lock_path.read_text(encoding="utf-8") + payload = json.loads(raw) + except (OSError, UnicodeError, json.JSONDecodeError): + return True + if not isinstance(payload, dict): + return True + return _recorded_pid_alive(payload.get("pid")) is not False + + +def _runtime_descriptor_has_active_lock( + info_path: Path, + *, + seen_lock_names: set[str], + now: float, + grace_seconds: float, +) -> bool: + name = info_path.name + ts_lock_prefix = f"{name}.ts-effect.lock" + if any( + entry_name.startswith(ts_lock_prefix + ".claim.") + or entry_name.startswith(ts_lock_prefix + ".released.") + or entry_name.startswith(ts_lock_prefix + ".stale.") + for entry_name in seen_lock_names + ): + return True + for suffix_path in ( + info_path.with_name(f"{ts_lock_prefix}.claim"), + info_path.with_name(f"{ts_lock_prefix}.released"), + ): + try: + suffix_path.lstat() + return True + except FileNotFoundError: + pass + except OSError: + return True + ts_lock = info_path.with_name(ts_lock_prefix) + if _runtime_descriptor_lock_file_active( + ts_lock, now=now, grace_seconds=grace_seconds, json_owner=True, + ): + return True + suffix = name[len("runtime-"):-len(".json")] + start_lock = info_path.with_name(f"start-{suffix}.lock") + return _runtime_descriptor_lock_file_active( + start_lock, now=now, grace_seconds=grace_seconds, json_owner=False, + ) + + +def _cleanup_cursor_key(runtime_dir: Path) -> str: + try: + return os.path.normcase(str(runtime_dir.resolve())) + except OSError: + return os.path.normcase(str(runtime_dir)) + + +def _private_directory_identity(path: Path) -> tuple[int, int] | None: + try: + metadata = os.lstat(path) + except OSError: + return None + if ( + not stat.S_ISDIR(metadata.st_mode) + or (hasattr(os, "getuid") and metadata.st_uid != os.getuid()) + or bool(metadata.st_mode & 0o077) + ): + return None + return metadata.st_dev, metadata.st_ino + + +def _close_sweep_iterator(sweep: _StaleCleanupSweep) -> None: + sweep.iterator = None + cm = sweep.scandir_cm + sweep.scandir_cm = None + if cm is None: + return + exit_fn = getattr(cm, "__exit__", None) + if callable(exit_fn): + with suppress(OSError, RuntimeError): + exit_fn(None, None, None) + + +def _close_sweeps(sweeps: Iterable[_StaleCleanupSweep]) -> None: + for sweep in sweeps: + _close_sweep_iterator(sweep) + + +def close_stale_cleanup_sweeps(*, runtime_dir: Path | None = None) -> None: + """Close cached directory sweeps held for bounded stale-descriptor cleanup.""" + global _stale_cleanup_generation + to_close: list[_StaleCleanupSweep] = [] + with _stale_cleanup_sweeps_lock: + _stale_cleanup_generation += 1 + if runtime_dir is None: + to_close.extend(_stale_cleanup_sweeps.values()) + _stale_cleanup_sweeps.clear() + else: + sweep = _stale_cleanup_sweeps.pop(_cleanup_cursor_key(runtime_dir), None) + if sweep is not None: + to_close.append(sweep) + _close_sweeps(to_close) + + +def _reset_stale_cleanup_sweeps_after_fork() -> None: + global _stale_cleanup_sweeps_lock, _stale_cleanup_generation + _stale_cleanup_sweeps_lock = Lock() + _stale_cleanup_generation += 1 + sweeps = list(_stale_cleanup_sweeps.values()) + _stale_cleanup_sweeps.clear() + _close_sweeps(sweeps) + + +if hasattr(os, "register_at_fork"): + os.register_at_fork(after_in_child=_reset_stale_cleanup_sweeps_after_fork) +atexit.register(close_stale_cleanup_sweeps) + + +# Only evict *other* dirs when idle-closing: closing and reopening os.scandir +# for the active key resets the cursor and stalls >=300s low-frequency misses. +def _checkout_stale_cleanup_sweep( + key: str, *, dir_identity: tuple[int, int], scandir_fn: object, +) -> tuple[_StaleCleanupSweep | None, int]: + now_mono = time.monotonic() + to_close: list[_StaleCleanupSweep] = [] + with _stale_cleanup_sweeps_lock: + expired_keys = [ + k for k, s in _stale_cleanup_sweeps.items() + if k != key and now_mono - s.last_used_monotonic >= _STALE_CLEANUP_SWEEP_IDLE_SECONDS + ] + for expired_key in expired_keys: + to_close.append(_stale_cleanup_sweeps.pop(expired_key)) + sweep = _stale_cleanup_sweeps.pop(key, None) + if sweep is not None and (sweep.dir_identity != dir_identity or sweep.scandir_fn is not scandir_fn): + to_close.append(sweep) + sweep = None + generation = _stale_cleanup_generation + _close_sweeps(to_close) + return sweep, generation + + +def _open_stale_cleanup_sweep( + runtime_dir: Path, *, dir_identity: tuple[int, int], scandir_fn: object, +) -> _StaleCleanupSweep | None: + try: + cm = os.scandir(runtime_dir) + except OSError: + return None + try: + entries = cm.__enter__() + iterator = iter(entries) + except OSError: + with suppress(OSError, RuntimeError): + cm.__exit__(None, None, None) + return None + return _StaleCleanupSweep( + scandir_cm=cm, iterator=iterator, pending_candidates=deque(), seen_lock_names=set(), + dir_identity=dir_identity, scandir_fn=scandir_fn, last_used_monotonic=time.monotonic(), + ) + + +def _advance_stale_cleanup_sweep( + sweep: _StaleCleanupSweep, *, exclude_name: str | None, max_inspect: int, max_scan_steps: int, +) -> bool: + window_steps = 0 + while ( + sweep.iterator is not None + and len(sweep.pending_candidates) < max_inspect + and window_steps < max_scan_steps + ): + try: + entry = next(sweep.iterator) + except StopIteration: + _close_sweep_iterator(sweep) + break + except OSError: + _close_sweep_iterator(sweep) + return False + window_steps += 1 + entry_name = entry.name + if ( + len(sweep.seen_lock_names) < _STALE_CLEANUP_SEEN_LOCK_LIMIT + and any( + m in entry_name + for m in (".ts-effect.lock.claim.", ".ts-effect.lock.released.", ".ts-effect.lock.stale.") + ) + ): + sweep.seen_lock_names.add(entry_name) + if entry_name.startswith("runtime-") and entry_name.endswith(".json") and entry_name != exclude_name: + sweep.pending_candidates.append(entry) + return True + + +def _checkin_stale_cleanup_sweep(key: str, sweep: _StaleCleanupSweep, *, generation: int) -> None: + if sweep.iterator is None and not sweep.pending_candidates: + _close_sweep_iterator(sweep) + return + to_close: list[_StaleCleanupSweep] = [] + with _stale_cleanup_sweeps_lock: + if generation != _stale_cleanup_generation or key in _stale_cleanup_sweeps: + to_close.append(sweep) + else: + while len(_stale_cleanup_sweeps) >= _STALE_CLEANUP_SWEEP_LIMIT: + to_close.append(_stale_cleanup_sweeps.pop(next(iter(_stale_cleanup_sweeps)))) + sweep.last_used_monotonic = time.monotonic() + _stale_cleanup_sweeps[key] = sweep + _close_sweeps(to_close) + + +def _try_unlink_stale_descriptor( + runtime_dir: Path, + entry: os.DirEntry[str], + *, + seen_lock_names: set[str], + now: float, + grace_seconds: float, + no_follow: int, +) -> bool: + candidate = runtime_dir / entry.name + try: + st = entry.stat(follow_symlinks=False) + except OSError: + return False + if not stat.S_ISREG(st.st_mode): + return False + if hasattr(os, "getuid") and st.st_uid != os.getuid(): + return False + if now - st.st_mtime < grace_seconds: + return False + if _runtime_descriptor_has_active_lock( + candidate, seen_lock_names=seen_lock_names, now=now, grace_seconds=grace_seconds, + ): + return False + try: + fd = os.open(candidate, os.O_RDONLY | no_follow) + except OSError: + return False + try: + with os.fdopen(fd, "rb") as file: + fst = os.fstat(file.fileno()) + if ( + not stat.S_ISREG(fst.st_mode) + or fst.st_dev != st.st_dev + or fst.st_ino != st.st_ino + or (hasattr(os, "getuid") and fst.st_uid != os.getuid()) + ): + return False + raw = file.read(_STALE_RUNTIME_DESCRIPTOR_MAX_BYTES + 1) + except OSError: + return False + if len(raw) > _STALE_RUNTIME_DESCRIPTOR_MAX_BYTES: + return False + try: + payload = json.loads(raw) + except (UnicodeError, ValueError, RecursionError): + return False + if ( + not isinstance(payload, dict) + or payload.get("schema_version") != EFFECT_RUNTIME_INFO_SCHEMA_VERSION + or not isinstance(payload.get("fingerprint"), str) + ): + return False + if _recorded_pid_alive(payload.get("pid")) is not False: + return False + try: + current_st = candidate.lstat() + except OSError: + return False + if ( + current_st.st_dev != st.st_dev + or current_st.st_ino != st.st_ino + or current_st.st_mtime_ns != st.st_mtime_ns + ): + return False + if _runtime_descriptor_has_active_lock( + candidate, seen_lock_names=seen_lock_names, now=time.time(), grace_seconds=grace_seconds, + ): + return False + try: + candidate.unlink(missing_ok=True) + except OSError: + return False + return True + + +def _cleanup_stale_runtime_descriptors( + runtime_dir: Path, + *, + exclude_path: Path | None = None, + grace_seconds: float = _STALE_RUNTIME_DESCRIPTOR_GRACE_SECONDS, + max_inspect: int = _STALE_RUNTIME_DESCRIPTOR_MAX_INSPECT, + max_removals: int = _STALE_RUNTIME_DESCRIPTOR_MAX_REMOVALS, +) -> int: + """Opportunistically unlink bounded dead-PID runtime-*.json descriptors.""" + if max_inspect <= 0 or max_removals <= 0: + return 0 + dir_identity = _private_directory_identity(runtime_dir) + if dir_identity is None: + return 0 + exclude_name: str | None = None + if exclude_path is not None: + with suppress(OSError): + if exclude_path.parent.resolve() == runtime_dir.resolve(): + exclude_name = exclude_path.name + key = _cleanup_cursor_key(runtime_dir) + scandir_fn = os.scandir + sweep, generation = _checkout_stale_cleanup_sweep( + key, dir_identity=dir_identity, scandir_fn=scandir_fn, + ) + if sweep is None: + sweep = _open_stale_cleanup_sweep( + runtime_dir, dir_identity=dir_identity, scandir_fn=scandir_fn, + ) + if sweep is None: + return 0 + healthy = _advance_stale_cleanup_sweep( + sweep, + exclude_name=exclude_name, + max_inspect=max_inspect, + max_scan_steps=max(max_inspect * 8, _STALE_RUNTIME_DESCRIPTOR_MAX_SCAN_STEPS), + ) + now = time.time() + inspected = 0 + removed = 0 + no_follow = getattr(os, "O_NOFOLLOW", 0) + while sweep.pending_candidates and inspected < max_inspect and removed < max_removals: + entry = sweep.pending_candidates.popleft() + if exclude_name is not None and entry.name == exclude_name: + continue + inspected += 1 + if _try_unlink_stale_descriptor( + runtime_dir, + entry, + seen_lock_names=sweep.seen_lock_names, + now=now, + grace_seconds=grace_seconds, + no_follow=no_follow, + ): + removed += 1 + if healthy: + _checkin_stale_cleanup_sweep(key, sweep, generation=generation) + else: + sweep.pending_candidates.clear() + _close_sweep_iterator(sweep) + return removed + + def _inspect_runtime_locator( fingerprint: str, *, recover: bool, ) -> tuple[_RuntimeLocatorState, bool | None, _RuntimeLocatorDiagnostic | None, _RuntimeInfo | None]: path = _runtime_info_path(fingerprint) + if recover: + _cleanup_stale_runtime_descriptors(path.parent, exclude_path=path) info = _read_info(path, fingerprint=fingerprint) if info is not None: return "valid", True, None, info @@ -1242,6 +1637,7 @@ def _start_runtime(*, fingerprint: str, info_path: Path) -> _RuntimeInfo: deadline=time.monotonic() + budget, check_running_diagnostic=check_running, ) if info is not None: + _cleanup_stale_runtime_descriptors(runtime_dir, exclude_path=info_path) return info failure = _published_startup_failure(startup_stderr) if failure is not None: diff --git a/loopx/control_plane/effect_runtime_exchange.ts b/loopx/control_plane/effect_runtime_exchange.ts index 4ed054db1d..8d53a76603 100644 --- a/loopx/control_plane/effect_runtime_exchange.ts +++ b/loopx/control_plane/effect_runtime_exchange.ts @@ -53,74 +53,101 @@ export function oversizedEffectRuntimeRequest(): Buffer { ))); } -async function encodeResponse(response: JsonObject, sink: FileHandle | null): Promise { - const encoded = encode(response); +async function writeEncodedResponse( + requestId: unknown, + encoded: Buffer, + sink: FileHandle | null, +): Promise { if (encoded.length <= MAX_INLINE_RESPONSE_BYTES) return encoded; // A success may already be durable. Return no frame when the existing // bounded snapshot path cannot deliver it, so callers recover its receipt. if (sink === null) return null; return encode({ schema_version: RESPONSE_SCHEMA, - request_id: response.request_id, + request_id: requestId, ok: true, result_ref: await writePrivateResponse(sink, encoded), }); } +function decodeExchangeEnvelope( + line: string, + token: string, + onRequestId: (id: string) => void, +): { requestId: string; method: string; paramsRef: unknown; inlineParams: JsonObject; responseSinkRef: unknown } { + let parsed: unknown; + try { + parsed = JSON.parse(line); + } catch { + throw new EffectRuntimeRequestError( + "Effect runtime request is not valid JSON", + "malformed_json", + ); + } + const request = requiredObject(parsed, "Effect runtime request"); + const requestId = requiredString(request.request_id, "request_id"); + onRequestId(requestId); + if (request.schema_version !== REQUEST_SCHEMA || request.token !== token) { + throw new EffectRuntimeRequestError( + "Effect runtime request authentication failed", + "authentication_failed", + ); + } + const method = requiredString(request.method, "method"); + if (request.params_ref !== undefined || request.response_sink !== undefined) { + if (!LOCAL_SNAPSHOT_METHODS.has(method) || request.response_sink === undefined || + (request.params_ref !== undefined && request.params !== undefined)) { + throw new EffectRuntimeRequestError("local snapshot transport is unavailable for this request"); + } + } + return { + requestId, + method, + paramsRef: request.params_ref, + inlineParams: asParams(request.params), + responseSinkRef: request.response_sink, + }; +} + export async function exchangeEffectRuntimeRequest( - line: string, token: string, handlers: ReadonlyMap, + rawLine: string, token: string, handlers: ReadonlyMap, ): Promise { + let line: string | undefined = rawLine; let requestId = "unknown"; let sink: FileHandle | null = null; - let response: JsonObject; + let encoded: Buffer; try { - let parsed: unknown; - try { - parsed = JSON.parse(line); - } catch { - throw new EffectRuntimeRequestError( - "Effect runtime request is not valid JSON", - "malformed_json", - ); - } - const request = requiredObject(parsed, "Effect runtime request"); - requestId = requiredString(request.request_id, "request_id"); - if (request.schema_version !== REQUEST_SCHEMA || request.token !== token) { - throw new EffectRuntimeRequestError( - "Effect runtime request authentication failed", - "authentication_failed", - ); - } - const method = requiredString(request.method, "method"); - if (request.params_ref !== undefined || request.response_sink !== undefined) { - if (!LOCAL_SNAPSHOT_METHODS.has(method) || request.response_sink === undefined || - (request.params_ref !== undefined && request.params !== undefined)) { - throw new EffectRuntimeRequestError("local snapshot transport is unavailable for this request"); - } - sink = await openPrivateResponseSink(request.response_sink); + const envelope = decodeExchangeEnvelope(line, token, (id) => { requestId = id; }); + // Drop the raw wire string before running async snapshot reads or handlers. + line = undefined; + if (envelope.responseSinkRef !== undefined) { + sink = await openPrivateResponseSink(envelope.responseSinkRef); } - let params: JsonObject; - if (request.params_ref !== undefined) { - const ref = requiredObject(request.params_ref, "params snapshot reference"); + let params: JsonObject | undefined; + if (envelope.paramsRef !== undefined) { + const ref = requiredObject(envelope.paramsRef, "params snapshot reference"); if (ref.schema_version !== "loopx_effect_runtime_snapshot_v0") { throw new EffectRuntimeRequestError("invalid local snapshot schema"); } params = requiredObject(await readPrivateJsonSnapshot(ref), "snapshot params"); } else { - params = asParams(request.params); + params = envelope.inlineParams; } - const result = await dispatchEffectRuntimeMethod(handlers, method, params); - response = { + const callParams = params; + params = undefined; + const result = await dispatchEffectRuntimeMethod(handlers, envelope.method, callParams); + encoded = encode({ schema_version: RESPONSE_SCHEMA, request_id: requestId, ok: true, result, - }; + }); } catch (error) { - response = failure(requestId, error); + line = undefined; + encoded = encode(failure(requestId, error)); } try { - return await encodeResponse(response, sink); + return await writeEncodedResponse(requestId, encoded, sink); } finally { await sink?.close(); } diff --git a/loopx/control_plane/effect_runtime_handlers.ts b/loopx/control_plane/effect_runtime_handlers.ts index 0588049fad..1a8b0a711d 100644 --- a/loopx/control_plane/effect_runtime_handlers.ts +++ b/loopx/control_plane/effect_runtime_handlers.ts @@ -47,10 +47,16 @@ function lazyHandler( load: () => Promise, select: (module: Module) => EffectRuntimeHandler, ): EffectRuntimeHandler { - let handler: Promise | undefined; + let resolved: EffectRuntimeHandler | undefined; + let loading: Promise | undefined; return async (params) => { - handler ??= load().then(select); - return (await handler)(params); + if (resolved !== undefined) return resolved(params); + loading ??= load().then(select).then((fn) => { + resolved = fn; + loading = undefined; + return fn; + }); + return (await loading)(params); }; } diff --git a/loopx/control_plane/effect_runtime_server.ts b/loopx/control_plane/effect_runtime_server.ts index f632c7af47..6c10ccbc46 100644 --- a/loopx/control_plane/effect_runtime_server.ts +++ b/loopx/control_plane/effect_runtime_server.ts @@ -82,7 +82,7 @@ let publishedInfoPath: string | undefined; const fingerprint = parseArg("--fingerprint"); const token = requiredString(process.env.LOOPX_EFFECT_RUNTIME_TOKEN, "runtime token"); const idleMs = parseIdleMs(process.env.LOOPX_EFFECT_RUNTIME_IDLE_MS); -let idleTimer: NodeJS.Timeout; +let idleTimer: ReturnType | undefined; let pendingRequests = 0; let resolveDrain: (() => void) | undefined; let publicationComplete = false; @@ -98,9 +98,11 @@ const handlers = createEffectRuntimeHandlers({ function resetIdleTimer(server: ReturnType): void { clearTimeout(idleTimer); + idleTimer = undefined; // Idleness starts after effects finish, not when their sockets connect. if (!publicationComplete || pendingRequests > 0 || shutdownRequested || !server.listening) return; idleTimer = setTimeout(() => { + idleTimer = undefined; server.close(); // close() waits for every connection; one whose peer died without a // request would keep this process alive but no longer listening. @@ -110,24 +112,97 @@ function resetIdleTimer(server: ReturnType): void { } const sockets = new Set(); +const pendingDispatchSockets = new Set(); + +async function dispatchSocketRequest( + server: ReturnType, + socket: Socket, + requestLine: string, +): Promise { + let line: string | undefined = requestLine; + pendingRequests += 1; + clearTimeout(idleTimer); + idleTimer = undefined; + try { + // The locator becomes visible inside the publication lock. A first + // response must wait for its release: otherwise an immediate process + // death can strand an incomplete cleanup claim before the next write. + await publicationReady; + const input = line; + line = undefined; + const frame = await exchangeEffectRuntimeRequest(input, token, handlers); + if (frame === null || socket.destroyed || !socket.writable) socket.destroy(); + else { + socket.setTimeout(idleMs); + socket.end(frame); + } + } catch { + socket.destroy(); + } finally { + line = undefined; + pendingRequests -= 1; + if (pendingRequests === 0) { + resolveDrain?.(); + resolveDrain = undefined; + } + // Stop accepting new work immediately on shutdown, but drain every + // already accepted handler, including those whose caller disconnected. + if (shutdownRequested) { + if (server.listening) server.close(); + for (const idleSocket of pendingDispatchSockets) idleSocket.destroy(); + } + resetIdleTimer(server); + } +} + const server = createServer((socket) => { sockets.add(socket); - socket.on("close", () => sockets.delete(socket)); + pendingDispatchSockets.add(socket); resetIdleTimer(server); socket.setEncoding("utf8"); + let raw = ""; + let receivedBytes = 0; + let dispatched = false; + const clearIncomingBuffer = (): void => { + raw = ""; + receivedBytes = 0; + socket.removeAllListeners("data"); + }; + socket.setTimeout(idleMs); + socket.on("timeout", () => { + if (!dispatched || socket.writableFinished) { + clearIncomingBuffer(); + socket.destroy(); + } + }); // A caller may close while a response is still buffered (for example after // reaching its byte budget). That socket's failure must not kill the shared // runtime or another in-flight operation. Business receipt recovery stays // with the caller; disconnecting never retries or reverses the handler. - socket.on("error", () => socket.destroy()); - let raw = ""; - let receivedBytes = 0; + socket.on("error", () => { + clearIncomingBuffer(); + pendingDispatchSockets.delete(socket); + socket.destroy(); + }); + socket.on("end", () => { + if (!dispatched) { + clearIncomingBuffer(); + pendingDispatchSockets.delete(socket); + } + }); + socket.on("close", () => { + clearIncomingBuffer(); + pendingDispatchSockets.delete(socket); + sockets.delete(socket); + }); socket.on("data", (chunk: string) => { receivedBytes += Buffer.byteLength(chunk, "utf8"); if (receivedBytes > MAX_REQUEST_BYTES) { - raw = ""; + dispatched = true; + clearIncomingBuffer(); + pendingDispatchSockets.delete(socket); socket.pause(); - socket.removeAllListeners("data"); + socket.setTimeout(idleMs); socket.end(oversizedEffectRuntimeRequest()); return; } @@ -135,35 +210,19 @@ const server = createServer((socket) => { // Earlier chunks had no delimiter. Scanning the accumulated string on each // chunk repeatedly flattens it; only the newly received chunk can finish it. if (!chunk.includes("\n")) return; + dispatched = true; + const line = raw.slice(0, raw.indexOf("\n")); + clearIncomingBuffer(); + pendingDispatchSockets.delete(socket); + socket.setTimeout(0); socket.pause(); - pendingRequests += 1; - clearTimeout(idleTimer); - void (async () => { - try { - // The locator becomes visible inside the publication lock. A first - // response must wait for its release: otherwise an immediate process - // death can strand an incomplete cleanup claim before the next write. - await publicationReady; - const frame = await exchangeEffectRuntimeRequest( - raw.slice(0, raw.indexOf("\n")), token, handlers, - ); - if (frame === null) socket.destroy(); - else socket.end(frame); - } catch { - socket.destroy(); - } finally { - pendingRequests -= 1; - if (pendingRequests === 0) resolveDrain?.(); - // Stop accepting new work immediately on shutdown, but drain every - // already accepted handler, including those whose caller disconnected. - if (shutdownRequested && server.listening) server.close(); - resetIdleTimer(server); - } - })(); + void dispatchSocketRequest(server, socket, line); }); }); server.on("close", () => { + clearTimeout(idleTimer); + idleTimer = undefined; void (async () => { // TCP close does not wait for a handler after its client times out. if (pendingRequests > 0) { diff --git a/loopx/control_plane/work_items/stride_policy.ts b/loopx/control_plane/work_items/stride_policy.ts index bd26ed6f08..2f72571de6 100644 --- a/loopx/control_plane/work_items/stride_policy.ts +++ b/loopx/control_plane/work_items/stride_policy.ts @@ -345,7 +345,7 @@ export function strideReviewMismatch(decision: JsonObject, context: JsonObject, } if (hasDeclaredWork && (review.adoption === "executed" || review.adoption === "partially_executed" || review.goal_gain !== "unknown") && !cited.some(ref => linked.has(ref))) { - return "Execution and goal-gain claims require subsequent evidence for the declared work; unrelated activity is insufficient."; + return 'Execution and goal-gain claims require subsequent evidence for the declared work tied to reference_decision_ref; unrelated activity is insufficient (use "unknown" for adoption and goal_gain if closing a different track).'; } } const basis = context.explore_basis as JsonObject | undefined; diff --git a/tests/control_plane/test_effect_runtime_locator_recovery.py b/tests/control_plane/test_effect_runtime_locator_recovery.py index c03f2abda8..41efa3d237 100644 --- a/tests/control_plane/test_effect_runtime_locator_recovery.py +++ b/tests/control_plane/test_effect_runtime_locator_recovery.py @@ -8,6 +8,7 @@ import subprocess import sys import time +from collections.abc import Iterator from pathlib import Path from uuid import uuid4 @@ -479,3 +480,780 @@ def test_linux_zombie_thread_group_is_reported_not_alive_during_locator_recovery zombie = False assert effect_runtime._pid_is_alive(424242) is True + + +def test_cleanup_stale_runtime_descriptors_respects_liveness_grace_locks_and_bounds( + tmp_path: Path, + monkeypatch, +) -> None: + _isolate_runtime(tmp_path, monkeypatch) + runtime_dir = effect_runtime._runtime_dir() + runtime_dir.mkdir(parents=True, mode=0o700) + + dead_proc = subprocess.Popen([sys.executable, "-c", "pass"]) + dead_pid = dead_proc.pid + dead_proc.wait(timeout=10) + assert effect_runtime._pid_is_alive(dead_pid) is False + + stale_old = time.time() - 3600.0 + fingerprints = { + "dead_clean_a": "a" * 64, + "dead_clean_b": "b" * 64, + "dead_recent": "c" * 64, + "dead_start_lock": "d" * 64, + "dead_ts_lock": "e" * 64, + "dead_claim_lock": "f" * 64, + "alive_old": "1" * 64, + "oversized_pid": "2" * 64, + } + + def write_descriptor(fp: str, pid: object, *, mtime: float | None = stale_old) -> Path: + path = runtime_dir / f"runtime-{fp[:16]}.json" + path.write_text( + json.dumps({ + "schema_version": effect_runtime.EFFECT_RUNTIME_INFO_SCHEMA_VERSION, + "fingerprint": fp, + "host": "127.0.0.1", + "port": 1, + "token": f"token-{fp[:8]}", + "pid": pid, + }), + encoding="utf-8", + ) + if mtime is not None: + os.utime(path, (mtime, mtime)) + return path + + dead_a = write_descriptor(fingerprints["dead_clean_a"], dead_pid) + dead_b = write_descriptor(fingerprints["dead_clean_b"], dead_pid) + dead_recent = write_descriptor(fingerprints["dead_recent"], dead_pid, mtime=None) + dead_start = write_descriptor(fingerprints["dead_start_lock"], dead_pid) + dead_ts = write_descriptor(fingerprints["dead_ts_lock"], dead_pid) + dead_claim = write_descriptor(fingerprints["dead_claim_lock"], dead_pid) + alive_old = write_descriptor(fingerprints["alive_old"], os.getpid()) + oversized_pid = write_descriptor(fingerprints["oversized_pid"], 10**30) + unrelated_json = runtime_dir / "other.json" + unrelated_json.write_text("{}", encoding="utf-8") + os.utime(unrelated_json, (stale_old, stale_old)) + symlink_dead = runtime_dir / f"runtime-{'3' * 16}.json" + symlink_dead.symlink_to(dead_a) + + start_lock = runtime_dir / f"start-{fingerprints['dead_start_lock'][:16]}.lock" + start_lock.write_text(f"{os.getpid()}\n", encoding="utf-8") + os.utime(start_lock, (stale_old, stale_old)) + + ts_lock = Path(f"{dead_ts}.ts-effect.lock") + ts_lock.write_text(json.dumps({"pid": os.getpid(), "token": "live"}), encoding="utf-8") + os.utime(ts_lock, (stale_old, stale_old)) + + claim_lock = Path(f"{dead_claim}.ts-effect.lock.claim.{'0' * 64}") + claim_lock.write_text(json.dumps({"pid": dead_pid, "token": "claim"}), encoding="utf-8") + os.utime(claim_lock, (stale_old, stale_old)) + + # The caller's own target descriptor stays intact so readiness keeps its diagnostic. + current_fp = effect_runtime._runtime_fingerprint() + current_path = write_descriptor(current_fp, dead_pid) + + readiness = effect_runtime.collect_effect_runtime_readiness() + assert readiness["runtime_lifecycle"]["diagnostic_code"] == "runtime_locator_pid_not_alive" + + assert not dead_a.exists() + assert not dead_b.exists() + assert dead_recent.exists() + assert dead_start.exists() + assert dead_ts.exists() + assert dead_claim.exists() + assert alive_old.exists() + assert oversized_pid.exists() + assert unrelated_json.exists() + assert symlink_dead.is_symlink() + assert current_path.exists() + + # Publication (_start_runtime) also performs bounded stale descriptor cleanup. + numbered_fps = [f"{idx:016x}{'0' * 48}" for idx in range(10)] + for fp in numbered_fps: + write_descriptor(fp, dead_pid) + + class _DummyProcess: + def poll(self) -> None: + return None + + def terminate(self) -> None: + return None + + monkeypatch.setattr(effect_runtime, "_node_executable", lambda: "node") + monkeypatch.setattr(effect_runtime, "_read_info", lambda *_a, **_k: None) + monkeypatch.setattr(effect_runtime.subprocess, "Popen", lambda *_a, **_k: _DummyProcess()) + monkeypatch.setattr( + effect_runtime, + "_await_startup_publication", + lambda *_a, **_k: {"ready": True, "pid": os.getpid()}, + ) + effect_runtime._start_runtime(fingerprint=current_fp, info_path=current_path) + remaining_numbered = [ + p for fp in numbered_fps if (p := runtime_dir / f"runtime-{fp[:16]}.json").exists() + ] + assert remaining_numbered == [] + + # Bounded removal limit caps per-pass unlinks. + try: + extra_fps = [f"{100 + idx:016x}{'0' * 48}" for idx in range(40)] + for fp in extra_fps: + write_descriptor(fp, dead_pid) + removed = effect_runtime._cleanup_stale_runtime_descriptors( + runtime_dir, exclude_path=current_path, max_inspect=64, max_removals=5, + ) + assert removed == 5 + still_present = sum(1 for fp in extra_fps if (runtime_dir / f"runtime-{fp[:16]}.json").exists()) + assert still_present == 35 + finally: + effect_runtime.close_stale_cleanup_sweeps() + + +def test_cold_miss_cleanup_bounds_scandir_and_advances_across_240_descriptors( + tmp_path: Path, + monkeypatch, +) -> None: + dead_proc = subprocess.Popen([sys.executable, "-c", "pass"]) + dead_pid = dead_proc.pid + dead_proc.wait(timeout=10) + assert effect_runtime._pid_is_alive(dead_pid) is False + + stale_old = time.time() - 3600.0 + max_inspect = effect_runtime._STALE_RUNTIME_DESCRIPTOR_MAX_INSPECT + real_scandir = effect_runtime.os.scandir + + def make_runtime_dir(name: str) -> Path: + root = tmp_path / name + root.mkdir(parents=True, mode=0o700) + return root + + def write_desc(directory: Path, fp: str, pid: int, *, mtime: float | None) -> Path: + path = directory / f"runtime-{fp[:16]}.json" + path.write_text( + json.dumps({ + "schema_version": effect_runtime.EFFECT_RUNTIME_INFO_SCHEMA_VERSION, + "fingerprint": fp, + "host": "127.0.0.1", + "port": 1, + "token": f"tok-{fp[:8]}", + "pid": pid, + }), + encoding="utf-8", + ) + if mtime is not None: + os.utime(path, (mtime, mtime)) + return path + + # 1. Cold miss on 240 fresh descriptors stops scandir at <= max_inspect entries. + fresh_dir = make_runtime_dir("fresh_240") + for idx in range(240): + write_desc(fresh_dir, f"{0x1000 + idx:016x}{'0' * 48}", os.getpid(), mtime=None) + fresh_target_fp = "f" * 64 + fresh_target = fresh_dir / f"runtime-{fresh_target_fp[:16]}.json" + + stale_dir = make_runtime_dir("stale_240") + stale_paths = [ + write_desc(stale_dir, f"{0x2000 + idx:016x}{'0' * 48}", dead_pid, mtime=stale_old) + for idx in range(240) + ] + stale_target_fp = "e" * 64 + stale_target = stale_dir / f"runtime-{stale_target_fp[:16]}.json" + + mixed_dir = make_runtime_dir("mixed_240") + alive_paths = [ + write_desc(mixed_dir, f"{0x3000 + idx:016x}{'0' * 48}", os.getpid(), mtime=stale_old) + for idx in range(80) + ] + dead_beyond = [ + write_desc(mixed_dir, f"{0x4000 + idx:016x}{'0' * 48}", dead_pid, mtime=stale_old) + for idx in range(159) + ] + locked_beyond = write_desc(mixed_dir, f"{0x5000:016x}{'0' * 48}", dead_pid, mtime=stale_old) + locked_ts = Path(f"{locked_beyond}.ts-effect.lock") + locked_ts.write_text(json.dumps({"pid": os.getpid(), "token": "live"}), encoding="utf-8") + os.utime(locked_ts, (stale_old, stale_old)) + mixed_target_fp = "d" * 64 + mixed_target = mixed_dir / f"runtime-{mixed_target_fp[:16]}.json" + + # Real >512 directory with 600 non-removable leading entries and 8 stale tail entries + # placed at actual os.scandir() indices >= 512 (no synthetic sorting). + tail_alive_dir = make_runtime_dir("tail_alive_608") + for idx in range(608): + write_desc(tail_alive_dir, f"{0x6000 + idx:016x}{'0' * 48}", os.getpid(), mtime=stale_old) + with real_scandir(tail_alive_dir) as raw_entries: + actual_order = [entry.name for entry in raw_entries] + assert len(actual_order) == 608 + tail_stale_names = set(actual_order[600:608]) + tail_alive_paths = [tail_alive_dir / name for name in actual_order[:600]] + tail_stale_paths = [tail_alive_dir / name for name in actual_order[600:608]] + for stale_path in tail_stale_paths: + existing_payload = json.loads(stale_path.read_text(encoding="utf-8")) + stale_path.write_text( + json.dumps({**existing_payload, "pid": dead_pid}), + encoding="utf-8", + ) + os.utime(stale_path, (stale_old, stale_old)) + with real_scandir(tail_alive_dir) as raw_after: + stale_positions = [ + idx for idx, entry in enumerate(raw_after) if entry.name in tail_stale_names + ] + assert len(stale_positions) == 8 and min(stale_positions) >= 512 + tail_alive_target_fp = "c" * 64 + tail_alive_target = tail_alive_dir / f"runtime-{tail_alive_target_fp[:16]}.json" + + # >512 directory with 600 non-runtime files preceding 8 stale runtime descriptors. + tail_nonruntime_dir = make_runtime_dir("tail_nonruntime_608") + misc_paths = [] + for idx in range(600): + misc_path = tail_nonruntime_dir / f"misc-{idx:04d}.tmp" + misc_path.write_text("{}", encoding="utf-8") + misc_paths.append(misc_path) + nonruntime_stale_paths = [ + write_desc(tail_nonruntime_dir, f"{0x7000 + idx:016x}{'0' * 48}", dead_pid, mtime=stale_old) + for idx in range(8) + ] + nonruntime_target_fp = "b" * 64 + nonruntime_target = tail_nonruntime_dir / f"runtime-{nonruntime_target_fp[:16]}.json" + + target_dirs = { + fresh_dir.resolve(), + stale_dir.resolve(), + mixed_dir.resolve(), + tail_alive_dir.resolve(), + tail_nonruntime_dir.resolve(), + } + scandir_opens: dict[Path, int] = {} + scandir_closes: dict[Path, int] = {} + total_yields = [0] + + def make_counted_scandir(*, sort_dirs: set[Path] | None = None): + resolved_sort = {p.resolve() for p in (sort_dirs or set())} + + def counted_scandir(path=None): + if path is None: + return real_scandir() + try: + resolved = Path(path).resolve() + except OSError: + return real_scandir(path) + if resolved not in target_dirs: + return real_scandir(path) + + cm = real_scandir(path) + scandir_opens[resolved] = scandir_opens.get(resolved, 0) + 1 + should_sort = resolved in resolved_sort + + class _BoundedScanCM: + def __init__(self) -> None: + self._entered = False + self._iter: Iterator[os.DirEntry[str]] | None = None + + def _ensure_iter(self) -> Iterator[os.DirEntry[str]]: + if self._iter is None: + inner = cm.__enter__() + self._entered = True + self._iter = ( + iter(sorted(inner, key=lambda entry: entry.name)) + if should_sort + else iter(inner) + ) + return self._iter + + def __enter__(self) -> _BoundedScanCM: + self._ensure_iter() + return self + + def __exit__(self, exc_type, exc, tb): + return self.close(exc_type, exc, tb) + + def __iter__(self) -> _BoundedScanCM: + self._ensure_iter() + return self + + def __next__(self) -> os.DirEntry[str]: + item = next(self._ensure_iter()) + total_yields[0] += 1 + return item + + def close(self, exc_type=None, exc=None, tb=None): + if self._entered: + self._entered = False + scandir_closes[resolved] = scandir_closes.get(resolved, 0) + 1 + return cm.__exit__(exc_type, exc, tb) + return False + + return _BoundedScanCM() + + return counted_scandir + + def run_cold_miss(target: Path, fp: str) -> int: + before = total_yields[0] + assert effect_runtime._runtime_info_for_request(target, fingerprint=fp) is None + return total_yields[0] - before + + try: + effect_runtime.close_stale_cleanup_sweeps() + + # 1. Cold miss on 240 fresh descriptors stops scandir at <= max_inspect entries. + with monkeypatch.context() as mp: + mp.setattr(effect_runtime.os, "scandir", make_counted_scandir()) + first_yields = run_cold_miss(fresh_target, fresh_target_fp) + assert first_yields <= max_inspect + assert scandir_opens[fresh_dir.resolve()] == 1 + assert sum(1 for _ in fresh_dir.glob("runtime-*.json")) == 240 + + # 2. Repeated cold misses on 240 stale descriptors reclaim all 240 via 1 resumable sweep. + per_call_yields: list[int] = [] + with monkeypatch.context() as mp: + mp.setattr(effect_runtime.os, "scandir", make_counted_scandir()) + for _ in range(8): + per_call_yields.append(run_cold_miss(stale_target, stale_target_fp)) + assert len(per_call_yields) == 8 + assert max(per_call_yields) <= max_inspect + assert scandir_opens[stale_dir.resolve()] == 1 + assert scandir_closes[stale_dir.resolve()] == 1 + assert all(not p.exists() for p in stale_paths) + + # 3. Advancing sweep skips >64 leading alive entries and reclaims stale entries behind them, + # while protecting active lock files checked directly per candidate. + per_call_inspections: list[set[Path]] = [] + orig_lock_check = effect_runtime._runtime_descriptor_has_active_lock + + def counting_lock_check(info_path, *args, **kwargs): + per_call_inspections[-1].add(info_path) + return orig_lock_check(info_path, *args, **kwargs) + + per_call_yields.clear() + with monkeypatch.context() as mp: + mp.setattr(effect_runtime, "_runtime_descriptor_has_active_lock", counting_lock_check) + mp.setattr(effect_runtime.os, "scandir", make_counted_scandir(sort_dirs={mixed_dir})) + for _ in range(7): + per_call_inspections.append(set()) + per_call_yields.append(run_cold_miss(mixed_target, mixed_target_fp)) + assert len(per_call_inspections[0]) == max_inspect + assert all(len(seen) <= max_inspect for seen in per_call_inspections) + assert per_call_yields[0] == max_inspect + assert max(per_call_yields) <= max_inspect + assert all(p.exists() for p in alive_paths) + assert all(not p.exists() for p in dead_beyond) + assert locked_beyond.exists() + + # 4. Real >512 directory (actual os.scandir order): 600 non-removable leading entries + 8 stale + # descriptors past raw index 512 get reached and reclaimed on the 10th call with <=64 yields/call. + per_call_inspections.clear() + per_call_yields.clear() + with monkeypatch.context() as mp: + mp.setattr(effect_runtime, "_runtime_descriptor_has_active_lock", counting_lock_check) + mp.setattr(effect_runtime.os, "scandir", make_counted_scandir()) + for _ in range(10): + per_call_inspections.append(set()) + per_call_yields.append(run_cold_miss(tail_alive_target, tail_alive_target_fp)) + assert max(per_call_yields) <= max_inspect + assert scandir_opens[tail_alive_dir.resolve()] == 1 + assert scandir_closes[tail_alive_dir.resolve()] == 1 + assert all(len(seen) <= max_inspect for seen in per_call_inspections) + assert all(p.exists() for p in tail_alive_paths) + assert all(not p.exists() for p in tail_stale_paths) + + # 5. >512 non-runtime prefix: hits 512 window_steps on first cold miss, resumes past 512 on second. + per_call_yields.clear() + with monkeypatch.context() as mp: + mp.setattr(effect_runtime.os, "scandir", make_counted_scandir(sort_dirs={tail_nonruntime_dir})) + per_call_yields.append(run_cold_miss(nonruntime_target, nonruntime_target_fp)) + assert per_call_yields[0] == effect_runtime._STALE_RUNTIME_DESCRIPTOR_MAX_SCAN_STEPS + assert all(p.exists() for p in nonruntime_stale_paths) + per_call_yields.append(run_cold_miss(nonruntime_target, nonruntime_target_fp)) + assert per_call_yields[1] == 96 + assert scandir_opens[tail_nonruntime_dir.resolve()] == 1 + assert scandir_closes[tail_nonruntime_dir.resolve()] == 1 + assert all(p.exists() for p in misc_paths) + assert all(not p.exists() for p in nonruntime_stale_paths) + finally: + effect_runtime.close_stale_cleanup_sweeps() + assert effect_runtime.os.scandir is real_scandir + + +def _make_tracked_scandir( + counted_dirs: set[Path], + real_scandir, + scandir_opens: dict[Path, int], + scandir_closes: dict[Path, int], + total_yields: list[int], +): + def tracked_scandir(path=None): + if path is None: + return real_scandir() + try: + resolved = Path(path).resolve() + except OSError: + return real_scandir(path) + if resolved not in counted_dirs: + return real_scandir(path) + cm = real_scandir(path) + scandir_opens[resolved] = scandir_opens.get(resolved, 0) + 1 + + class _TrackedScanCM: + def __init__(self) -> None: + self._entered = False + self._iter: Iterator[os.DirEntry[str]] | None = None + + def _ensure_iter(self) -> Iterator[os.DirEntry[str]]: + if self._iter is None: + self._iter = iter(cm.__enter__()) + self._entered = True + return self._iter + + def __enter__(self) -> _TrackedScanCM: + self._ensure_iter() + return self + + def __exit__(self, exc_type, exc, tb): + return self.close(exc_type, exc, tb) + + def __iter__(self) -> _TrackedScanCM: + self._ensure_iter() + return self + + def __next__(self) -> os.DirEntry[str]: + item = next(self._ensure_iter()) + total_yields[0] += 1 + return item + + def close(self, exc_type=None, exc=None, tb=None): + if self._entered: + self._entered = False + scandir_closes[resolved] = scandir_closes.get(resolved, 0) + 1 + return cm.__exit__(exc_type, exc, tb) + return False + + return _TrackedScanCM() + + return tracked_scandir + + +def test_cold_miss_resumable_sweep_reclaims_large_tail_and_closes_handles( + tmp_path: Path, + monkeypatch, +) -> None: + dead_proc = subprocess.Popen([sys.executable, "-c", "pass"]) + dead_pid = dead_proc.pid + dead_proc.wait(timeout=10) + assert effect_runtime._pid_is_alive(dead_pid) is False + + stale_old = time.time() - 3600.0 + max_inspect = effect_runtime._STALE_RUNTIME_DESCRIPTOR_MAX_INSPECT + real_scandir = effect_runtime.os.scandir + + def seed_real_tail_dir( + name: str, + prefix_count: int, + *, + expire_prefix: bool, + ) -> tuple[Path, Path, str, list[Path], list[Path]]: + root = tmp_path / name + root.mkdir(parents=True, mode=0o700) + alive_pid = os.getpid() + schema_json = json.dumps(effect_runtime.EFFECT_RUNTIME_INFO_SCHEMA_VERSION) + total = prefix_count + 8 + for idx in range(total): + fp = f"{idx:016x}{'0' * 48}" + payload = ( + f'{{"schema_version":{schema_json},' + f'"fingerprint":"{fp}","host":"127.0.0.1","port":1,"token":"t-{idx}","pid":{alive_pid}}}' + ) + desc_path = root / f"runtime-{fp[:16]}.json" + desc_path.write_text(payload, encoding="utf-8") + if expire_prefix: + os.utime(desc_path, (stale_old, stale_old)) + with real_scandir(root) as raw_entries: + actual_order = [entry.name for entry in raw_entries] + assert len(actual_order) == total + prefix_paths = [root / entry_name for entry_name in actual_order[:prefix_count]] + tail_paths = [root / entry_name for entry_name in actual_order[prefix_count:]] + tail_names = {p.name for p in tail_paths} + for stale_path in tail_paths: + existing = json.loads(stale_path.read_text(encoding="utf-8")) + stale_path.write_text(json.dumps({**existing, "pid": dead_pid}), encoding="utf-8") + os.utime(stale_path, (stale_old, stale_old)) + with real_scandir(root) as raw_after: + stale_positions = [ + idx for idx, entry in enumerate(raw_after) if entry.name in tail_names + ] + assert len(stale_positions) == 8 and min(stale_positions) >= prefix_count + target_fp = "f" * 64 + target = root / f"runtime-{target_fp[:16]}.json" + return root, target, target_fp, prefix_paths, tail_paths + + dir_16k, target_16k, fp_16k, prefix_16k, tail_16k = seed_real_tail_dir( + "tail_16384", 16384, expire_prefix=False, + ) + dir_17k, target_17k, fp_17k, prefix_17k, tail_17k = seed_real_tail_dir( + "tail_17000", 17000, expire_prefix=True, + ) + + schema_json = json.dumps(effect_runtime.EFFECT_RUNTIME_INFO_SCHEMA_VERSION) + lru_dirs: list[tuple[Path, Path, str]] = [] + for lru_idx in range(effect_runtime._STALE_CLEANUP_SWEEP_LIMIT + 2): + lru_dir = tmp_path / f"lru_{lru_idx}" + lru_dir.mkdir(parents=True, mode=0o700) + for idx in range(max_inspect + 8): + fp = f"{0x9000 + lru_idx * 1000 + idx:016x}{'0' * 48}" + payload = ( + f'{{"schema_version":{schema_json},' + f'"fingerprint":"{fp}","host":"127.0.0.1","port":1,"token":"t-{idx}","pid":{os.getpid()}}}' + ) + (lru_dir / f"runtime-{fp[:16]}.json").write_text(payload, encoding="utf-8") + lru_target_fp = f"{lru_idx + 1:064x}" + lru_dirs.append((lru_dir, lru_dir / f"runtime-{lru_target_fp[:16]}.json", lru_target_fp)) + + counted_dirs = { + dir_16k.resolve(), + dir_17k.resolve(), + *(d.resolve() for d, _, _ in lru_dirs), + } + scandir_opens: dict[Path, int] = {} + scandir_closes: dict[Path, int] = {} + total_yields = [0] + counted_scandir = _make_tracked_scandir( + counted_dirs, real_scandir, scandir_opens, scandir_closes, total_yields, + ) + + try: + effect_runtime.close_stale_cleanup_sweeps() + + # Real 16,384-prefix dir (old raw_offset wrap point): 257 calls, <= 64 raw scandir yields per call. + yields_16k: list[int] = [] + with monkeypatch.context() as mp: + mp.setattr(effect_runtime.os, "scandir", counted_scandir) + for _ in range(257): + before = total_yields[0] + assert effect_runtime._runtime_info_for_request(target_16k, fingerprint=fp_16k) is None + yields_16k.append(total_yields[0] - before) + assert len(yields_16k) == 257 + assert max(yields_16k) <= max_inspect + assert scandir_opens[dir_16k.resolve()] == 1 + assert scandir_closes[dir_16k.resolve()] == 1 + assert all(not p.exists() for p in tail_16k) + assert all(p.exists() for p in prefix_16k) + + # Real 17,000-prefix dir (beyond old 16,384 wrap point): 266 calls (< 285), <= 64 yields/call. + yields_17k: list[int] = [] + with monkeypatch.context() as mp: + mp.setattr(effect_runtime.os, "scandir", counted_scandir) + for _ in range(266): + before = total_yields[0] + assert effect_runtime._runtime_info_for_request(target_17k, fingerprint=fp_17k) is None + yields_17k.append(total_yields[0] - before) + assert len(yields_17k) == 266 + assert max(yields_17k) <= max_inspect + assert scandir_opens[dir_17k.resolve()] == 1 + assert scandir_closes[dir_17k.resolve()] == 1 + assert all(not p.exists() for p in tail_17k) + assert all(p.exists() for p in prefix_17k) + + # LRU eviction, runtime stop, & explicit close release open scandir handles without leaks. + stop_dir, stop_target, stop_fp = lru_dirs[0] + stop_resolved = stop_dir.resolve() + with monkeypatch.context() as mp: + mp.setattr(effect_runtime.os, "scandir", counted_scandir) + for _, lru_target, lru_fp in lru_dirs: + assert effect_runtime._runtime_info_for_request(lru_target, fingerprint=lru_fp) is None + assert len(effect_runtime._stale_cleanup_sweeps) <= effect_runtime._STALE_CLEANUP_SWEEP_LIMIT + effect_runtime.close_stale_cleanup_sweeps() + assert effect_runtime._stale_cleanup_sweeps == {} + assert effect_runtime._runtime_info_for_request(stop_target, fingerprint=stop_fp) is None + assert effect_runtime._cleanup_cursor_key(stop_dir) in effect_runtime._stale_cleanup_sweeps + stop_result = effect_runtime._stop_effect_runtime(stop_target, None, timeout=0.05) + assert stop_result["status"] == "not_running" + assert effect_runtime._cleanup_cursor_key(stop_dir) not in effect_runtime._stale_cleanup_sweeps + for lru_dir, _, _ in lru_dirs: + resolved = lru_dir.resolve() + expected_count = 2 if resolved == stop_resolved else 1 + assert scandir_opens[resolved] == expected_count + assert scandir_closes[resolved] == expected_count + finally: + effect_runtime.close_stale_cleanup_sweeps() + assert effect_runtime.os.scandir is real_scandir + + +def test_cold_miss_resumable_sweep_spans_idle_timeout_cross_dir_and_inode_swap( + tmp_path: Path, + monkeypatch, +) -> None: + dead_proc = subprocess.Popen([sys.executable, "-c", "pass"]) + dead_pid = dead_proc.pid + dead_proc.wait(timeout=10) + assert effect_runtime._pid_is_alive(dead_pid) is False + + stale_old = time.time() - 3600.0 + max_inspect = effect_runtime._STALE_RUNTIME_DESCRIPTOR_MAX_INSPECT + real_scandir = effect_runtime.os.scandir + schema_json = json.dumps(effect_runtime.EFFECT_RUNTIME_INFO_SCHEMA_VERSION) + + def write_descriptor( + directory: Path, + fp: str, + pid: int, + *, + mtime: float | None, + ) -> Path: + path = directory / f"runtime-{fp[:16]}.json" + path.write_text( + f'{{"schema_version":{schema_json},"fingerprint":"{fp}",' + f'"host":"127.0.0.1","port":1,"token":"t-{fp[:8]}","pid":{pid}}}', + encoding="utf-8", + ) + if mtime is not None: + os.utime(path, (mtime, mtime)) + return path + + # 1. Low-frequency cold misses spaced 301s apart (> 300s idle timeout) across 600 protected + # prefix entries (alive PID, active lock, and within-grace descriptor) + 8 dead-PID tail + # descriptors finish in 10 calls with <= 64 raw scandir yields/call and clean EOF close. + low_freq_dir = tmp_path / "low_freq_608" + low_freq_dir.mkdir(parents=True, mode=0o700) + for idx in range(608): + write_descriptor(low_freq_dir, f"{0x10000 + idx:016x}{'0' * 48}", os.getpid(), mtime=stale_old) + with real_scandir(low_freq_dir) as raw_entries: + actual_order = [entry.name for entry in raw_entries] + assert len(actual_order) == 608 + alive_prefix = [low_freq_dir / name for name in actual_order[:598]] + locked_prefix = low_freq_dir / actual_order[598] + grace_prefix = low_freq_dir / actual_order[599] + tail_stale_names = set(actual_order[600:608]) + tail_stale_paths = [low_freq_dir / name for name in actual_order[600:608]] + + # Convert prefix[598] to dead-PID guarded by active .ts-effect.lock, prefix[599] to fresh grace, + # and the final 8 entries to expired dead-PID descriptors at real scandir indices >= 600. + locked_payload = json.loads(locked_prefix.read_text(encoding="utf-8")) + locked_prefix.write_text(json.dumps({**locked_payload, "pid": dead_pid}), encoding="utf-8") + os.utime(locked_prefix, (stale_old, stale_old)) + locked_ts = Path(f"{locked_prefix}.ts-effect.lock") + locked_ts.write_text(json.dumps({"pid": os.getpid(), "token": "live"}), encoding="utf-8") + os.utime(locked_ts, (stale_old, stale_old)) + + grace_payload = json.loads(grace_prefix.read_text(encoding="utf-8")) + grace_prefix.write_text(json.dumps({**grace_payload, "pid": dead_pid}), encoding="utf-8") + + for stale_path in tail_stale_paths: + existing = json.loads(stale_path.read_text(encoding="utf-8")) + stale_path.write_text(json.dumps({**existing, "pid": dead_pid}), encoding="utf-8") + os.utime(stale_path, (stale_old, stale_old)) + + with real_scandir(low_freq_dir) as raw_after: + stale_positions = [ + idx for idx, entry in enumerate(raw_after) if entry.name in tail_stale_names + ] + assert len(stale_positions) == 8 and min(stale_positions) >= 600 + + low_freq_target_fp = "a" * 64 + low_freq_target = low_freq_dir / f"runtime-{low_freq_target_fp[:16]}.json" + + # 2. Cross-directory idle eviction + directory identity replacement fixtures. + idle_dir_a = tmp_path / "idle_dir_a" + idle_dir_a.mkdir(parents=True, mode=0o700) + for idx in range(max_inspect + 12): + write_descriptor(idle_dir_a, f"{0x20000 + idx:016x}{'0' * 48}", os.getpid(), mtime=stale_old) + idle_a_target_fp = "b" * 64 + idle_a_target = idle_dir_a / f"runtime-{idle_a_target_fp[:16]}.json" + + idle_dir_b = tmp_path / "idle_dir_b" + idle_dir_b.mkdir(parents=True, mode=0o700) + for idx in range(max_inspect + 12): + write_descriptor(idle_dir_b, f"{0x30000 + idx:016x}{'0' * 48}", os.getpid(), mtime=stale_old) + idle_b_target_fp = "c" * 64 + idle_b_target = idle_dir_b / f"runtime-{idle_b_target_fp[:16]}.json" + + replace_dir = tmp_path / "replace_dir" + replace_dir.mkdir(parents=True, mode=0o700) + for idx in range(max_inspect + 12): + write_descriptor(replace_dir, f"{0x40000 + idx:016x}{'0' * 48}", os.getpid(), mtime=stale_old) + replace_target_fp = "d" * 64 + replace_target = replace_dir / f"runtime-{replace_target_fp[:16]}.json" + + counted_dirs = { + low_freq_dir.resolve(), + idle_dir_a.resolve(), + idle_dir_b.resolve(), + replace_dir.resolve(), + } + scandir_opens: dict[Path, int] = {} + scandir_closes: dict[Path, int] = {} + total_yields = [0] + monotonic_clock = [10000.0] + tracked_scandir = _make_tracked_scandir( + counted_dirs, real_scandir, scandir_opens, scandir_closes, total_yields, + ) + + try: + effect_runtime.close_stale_cleanup_sweeps() + + # Low-frequency 301s steps complete sweep across 608+ entries in 10 calls with <= 64 yields/call. + low_freq_yields: list[int] = [] + with monkeypatch.context() as mp: + mp.setattr(effect_runtime.time, "monotonic", lambda: monotonic_clock[0]) + mp.setattr(effect_runtime.os, "scandir", tracked_scandir) + for call_idx in range(10): + if call_idx > 0: + monotonic_clock[0] += effect_runtime._STALE_CLEANUP_SWEEP_IDLE_SECONDS + 1.0 + before = total_yields[0] + assert effect_runtime._runtime_info_for_request( + low_freq_target, fingerprint=low_freq_target_fp, + ) is None + low_freq_yields.append(total_yields[0] - before) + assert len(low_freq_yields) == 10 + assert max(low_freq_yields) <= max_inspect + 1 + assert sum(low_freq_yields) == 609 + assert scandir_opens[low_freq_dir.resolve()] == 1 + assert scandir_closes[low_freq_dir.resolve()] == 1 + assert all(p.exists() for p in alive_prefix) + assert locked_prefix.exists() + assert grace_prefix.exists() + assert all(not p.exists() for p in tail_stale_paths) + + # Cross-directory idle eviction: dir_A stays open until dir_B checks out >= 300s later. + idle_a_key = effect_runtime._cleanup_cursor_key(idle_dir_a) + idle_b_key = effect_runtime._cleanup_cursor_key(idle_dir_b) + with monkeypatch.context() as mp: + mp.setattr(effect_runtime.time, "monotonic", lambda: monotonic_clock[0]) + mp.setattr(effect_runtime.os, "scandir", tracked_scandir) + assert effect_runtime._runtime_info_for_request(idle_a_target, fingerprint=idle_a_target_fp) is None + assert scandir_opens[idle_dir_a.resolve()] == 1 + assert scandir_closes.get(idle_dir_a.resolve(), 0) == 0 + assert idle_a_key in effect_runtime._stale_cleanup_sweeps + + monotonic_clock[0] += effect_runtime._STALE_CLEANUP_SWEEP_IDLE_SECONDS + 1.0 + assert effect_runtime._runtime_info_for_request(idle_b_target, fingerprint=idle_b_target_fp) is None + assert scandir_closes[idle_dir_a.resolve()] == 1 + assert idle_a_key not in effect_runtime._stale_cleanup_sweeps + assert idle_b_key in effect_runtime._stale_cleanup_sweeps + effect_runtime.close_stale_cleanup_sweeps() + assert scandir_closes[idle_dir_b.resolve()] == 1 + + # Directory identity change (path recreated with a new inode) closes stale sweep and starts fresh. + replace_resolved = replace_dir.resolve() + old_stat = os.lstat(replace_dir) + with monkeypatch.context() as mp: + mp.setattr(effect_runtime.time, "monotonic", lambda: monotonic_clock[0]) + mp.setattr(effect_runtime.os, "scandir", tracked_scandir) + assert effect_runtime._runtime_info_for_request(replace_target, fingerprint=replace_target_fp) is None + assert scandir_opens[replace_resolved] == 1 + assert scandir_closes.get(replace_resolved, 0) == 0 + + old_backup = tmp_path / "replace_dir_old" + replace_dir.rename(old_backup) + replace_dir.mkdir(parents=True, mode=0o700) + new_stat = os.lstat(replace_dir) + assert (new_stat.st_dev, new_stat.st_ino) != (old_stat.st_dev, old_stat.st_ino) + fresh_stale = [ + write_descriptor(replace_dir, f"{0x50000 + idx:016x}{'0' * 48}", dead_pid, mtime=stale_old) + for idx in range(4) + ] + assert effect_runtime._runtime_info_for_request(replace_target, fingerprint=replace_target_fp) is None + assert scandir_opens[replace_resolved] == 2 + assert scandir_closes[replace_resolved] == 2 + assert all(not p.exists() for p in fresh_stale) + finally: + effect_runtime.close_stale_cleanup_sweeps() + assert effect_runtime.os.scandir is real_scandir diff --git a/tests/control_plane/test_quota_settlement_cli.py b/tests/control_plane/test_quota_settlement_cli.py index 0572c28107..236b31aeeb 100644 --- a/tests/control_plane/test_quota_settlement_cli.py +++ b/tests/control_plane/test_quota_settlement_cli.py @@ -5118,6 +5118,7 @@ def test_unbound_visible_goal_spend_returns_typed_mismatch_without_receipt( def test_begin_turn_rejects_a_non_receipt_runtime_profile(tmp_path: Path) -> None: project, runtime, registry_path = _write_fixture(tmp_path) + _initialize_fixture_authority(project, runtime) guard_rc, guard = _run_cli( registry_path, @@ -5139,10 +5140,31 @@ def test_begin_turn_rejects_a_non_receipt_runtime_profile(tmp_path: Path) -> Non # Kiro CLI, ZCode, agy, Gemini CLI, Cursor and custom runners all land on # generic_cli and mint their own identity instead. assert guard["reason"] == ( - "--begin-turn requires runtime-profile codex_app_heartbeat, " - "trae_app, or codex_app_ssh_goal; every other host starts its turn by " - "passing its own --turn-instance-id" + "--begin-turn requires runtime-profile antigravity_app, " + "codex_app_heartbeat, codex_app_ssh_goal, or trae_app; every other " + "host starts its turn by passing its own --turn-instance-id" + ) + from loopx.control_plane.scheduler.execution_context import ( + GUIDED_START_TURN_RUNTIME_PROFILES, + ) + + for allowed in GUIDED_START_TURN_RUNTIME_PROFILES: + assert allowed.value in guard["reason"] + + antigravity_rc, antigravity_guard = _run_cli( + registry_path, + runtime, + "quota", + "should-run", + "--runtime-profile", + "antigravity_app", + "--goal-id", + GOAL_ID, + "--agent-id", + AGENT_ID, + "--begin-turn", ) + assert antigravity_rc == 0, antigravity_guard @pytest.mark.parametrize( diff --git a/tests/control_plane_ts/effect_runtime_hygiene.test.ts b/tests/control_plane_ts/effect_runtime_hygiene.test.ts new file mode 100644 index 0000000000..fb8822b777 --- /dev/null +++ b/tests/control_plane_ts/effect_runtime_hygiene.test.ts @@ -0,0 +1,275 @@ +import assert from "node:assert/strict"; +import {spawn} from "node:child_process"; +import {once} from "node:events"; +import {mkdtemp, readFile, rm} from "node:fs/promises"; +import {connect, type Socket} from "node:net"; +import {tmpdir} from "node:os"; +import {join} from "node:path"; +import {setTimeout as delay} from "node:timers/promises"; +import test from "node:test"; +import {createRequire} from "node:module"; + +import { + canonicalAuthorityObject, + hashCanonicalCommitEnvelope, +} from "../../loopx/control_plane/coordination/authority_store_codec.ts"; +import {commitDigest, SqliteAuthorityStore} from "../../loopx/control_plane/coordination/sqlite_authority_store.ts"; +import {createEffectRuntimeHandlers} from "../../loopx/control_plane/effect_runtime_handlers.ts"; +import {exchangeEffectRuntimeRequest} from "../../loopx/control_plane/effect_runtime_exchange.ts"; + +test("effect_runtime_server retires promptly on shutdown despite orphaned silent and aborted sockets", {timeout: 30_000}, async (t) => { + const root = await mkdtemp(join(tmpdir(), "loopx-server-hygiene-")); + t.after(() => rm(root, {recursive: true, force: true})); + const infoPath = join(root, "runtime.json"); + const token = "hygiene-test-token"; + const child = spawn(process.execPath, [ + "--no-warnings", "--experimental-sqlite", "--experimental-strip-types", + "loopx/control_plane/effect_runtime_server.ts", + "--info", infoPath, "--fingerprint", "hygiene-fixture", + ], { + env: {...process.env, LOOPX_EFFECT_RUNTIME_TOKEN: token, LOOPX_EFFECT_RUNTIME_IDLE_MS: "60000"}, + stdio: "ignore", + }); + const exited = once(child, "close"); + t.after(async () => { + if (child.exitCode === null) child.kill(); + await exited; + }); + + let info: {port: number; token: string} | undefined; + for (let i = 0; i < 200; i += 1) { + try { + info = JSON.parse(await readFile(infoPath, "utf8")); + break; + } catch { + if (child.exitCode !== null) throw new Error("server exited before publishing locator"); + await delay(20); + } + } + assert.ok(info); + + const openSockets: Socket[] = []; + t.after(() => { + for (const sock of openSockets) sock.destroy(); + }); + + const rpc = (method: string, params: Record = {}): Promise => + new Promise((resolve, reject) => { + const sock = connect(info!.port, "127.0.0.1"); + sock.setEncoding("utf8"); + sock.setTimeout(5_000, () => sock.destroy(new Error("RPC timeout"))); + sock.on("error", reject); + sock.on("connect", () => { + sock.write(JSON.stringify({ + schema_version: "loopx_effect_runtime_request_v0", + token, + request_id: `req-${Math.random()}`, + method, + params, + }) + "\n"); + }); + let raw = ""; + sock.on("data", chunk => { raw += chunk; }); + sock.on("end", () => { + try { resolve(JSON.parse(raw)); } + catch (err) { reject(err); } + }); + }); + + // Orphaned silent connection that never sends a newline and never closes. + const silentSocket = connect(info.port, "127.0.0.1"); + openSockets.push(silentSocket); + await once(silentSocket, "connect"); + + // Client sending a partial unterminated frame and half-closing without newline. + const partialSocket = connect(info.port, "127.0.0.1"); + openSockets.push(partialSocket); + await once(partialSocket, "connect"); + partialSocket.end('{"incomplete":true'); + await once(partialSocket, "close"); + + // Oversized frame cleanly rejected. + const oversized = await new Promise((resolve, reject) => { + const sock = connect(info!.port, "127.0.0.1"); + sock.setEncoding("utf8"); + sock.on("error", reject); + sock.on("connect", () => { + sock.write("a".repeat(8 * 1024 * 1024 + 64)); + }); + let raw = ""; + sock.on("data", c => { raw += c; }); + sock.on("end", () => resolve(JSON.parse(raw))); + }); + assert.equal(oversized.ok, false); + assert.equal(oversized.error.code, "request_too_large"); + + // Repeated RPCs succeed cleanly. + for (let i = 0; i < 10; i += 1) { + const ping = await rpc("runtime.ping"); + assert.equal(ping.ok, true); + assert.equal(ping.result.ready, true); + } + + // Requesting shutdown must retire cleanly even with silentSocket still connected. + const shutdown = await rpc("runtime.shutdown"); + assert.equal(shutdown.ok, true); + assert.equal(shutdown.result.stopped, true); + const [code] = await Promise.race([ + exited, + delay(5_000).then(() => { throw new Error("runtime.shutdown wedged on orphaned silent socket"); }), + ]); + assert.equal(code, 0); +}); + +test("effect_runtime_server times out orphaned silent sockets while staying alive for dispatched requests", {timeout: 15_000}, async (t) => { + const root = await mkdtemp(join(tmpdir(), "loopx-server-timeout-")); + t.after(() => rm(root, {recursive: true, force: true})); + const infoPath = join(root, "runtime.json"); + const token = "timeout-test-token"; + const child = spawn(process.execPath, [ + "--no-warnings", "--experimental-sqlite", "--experimental-strip-types", + "loopx/control_plane/effect_runtime_server.ts", + "--info", infoPath, "--fingerprint", "timeout-fixture", + ], { + env: {...process.env, LOOPX_EFFECT_RUNTIME_TOKEN: token, LOOPX_EFFECT_RUNTIME_IDLE_MS: "350"}, + stdio: "ignore", + }); + const exited = once(child, "close"); + t.after(async () => { + if (child.exitCode === null) child.kill(); + await exited; + }); + + let info: {port: number} | undefined; + for (let i = 0; i < 200; i += 1) { + try { info = JSON.parse(await readFile(infoPath, "utf8")); break; } + catch { await delay(20); } + } + assert.ok(info); + + const silent = connect(info.port, "127.0.0.1"); + await once(silent, "connect"); + const silentClosed = once(silent, "close"); + + // Keep server busy every 120ms so server-wide idleTimer stays reset; per-socket + // idle timeout must still reap the orphaned silent connection. + let closed = false; + void silentClosed.then(() => { closed = true; }); + for (let i = 0; i < 8 && !closed; i += 1) { + await delay(120); + await new Promise((resolve, reject) => { + const sock = connect(info!.port, "127.0.0.1"); + sock.on("error", reject); + sock.on("connect", () => sock.write(JSON.stringify({ + schema_version: "loopx_effect_runtime_request_v0", + token, request_id: `keep-${i}`, method: "runtime.ping", params: {}, + }) + "\n")); + sock.on("end", () => resolve()); + sock.resume(); + }); + } + await silentClosed; + assert.equal(closed, true); +}); + +test("exchangeEffectRuntimeRequest reuses resolved handlers cleanly across repeated dispatches", async () => { + const token = "exchange-token"; + const handlers = createEffectRuntimeHandlers({fingerprint: "exchange-fp", requestShutdown: () => undefined}); + for (let i = 0; i < 5; i += 1) { + const raw = await exchangeEffectRuntimeRequest( + JSON.stringify({ + schema_version: "loopx_effect_runtime_request_v0", + token, + request_id: `req-${i}`, + method: "task_lease.write_scopes.overlap", + params: {left: ["docs/**"], right: ["docs/a.md"]}, + }), + token, + handlers, + ); + assert.ok(raw !== null); + const parsed = JSON.parse(raw.toString("utf8")); + assert.equal(parsed.ok, true); + assert.equal(parsed.result.overlap, true); + } + const rejectedRaw = await exchangeEffectRuntimeRequest( + JSON.stringify({ + schema_version: "loopx_effect_runtime_request_v0", + token: "wrong-token", + request_id: "req-auth-fail", + method: "runtime.ping", + params: {}, + }), + token, + handlers, + ); + assert.ok(rejectedRaw !== null); + const rejected = JSON.parse(rejectedRaw.toString("utf8")); + assert.equal(rejected.ok, false); + assert.equal(rejected.request_id, "req-auth-fail"); + assert.equal(rejected.error.code, "authentication_failed"); +}); + +test("hashCanonicalCommitEnvelope matches commitDigest across special keys and preserves BEGIN failure", async (t) => { + const projection = JSON.parse( + '{"": {"k": 1}, "__proto__": {"m": "v"}, "10": "ten", "2": "two", "z": [{"__proto__": "nested"}]}', + ) as Record; + const canonicalProjection = canonicalAuthorityObject(projection, "projection"); + const events = [{kind: "observed", sequence: 1}]; + const receipts = [{ok: true}]; + const expected = commitDigest("sqlite:" + "a".repeat(32), 2n, "op-special", projection, events, receipts); + const actual = hashCanonicalCommitEnvelope( + { + expected_provider_revision: `sqlite:${"a".repeat(32)}:1`, + operation_id: "op-special", + events, + receipts, + }, + (hash) => { + hash.update(JSON.stringify(canonicalProjection), "utf8"); + }, + ); + assert.equal(actual, expected); + + const dir = await mkdtemp(join(tmpdir(), "loopx-sqlite-hygiene-")); + t.after(() => rm(dir, {recursive: true, force: true})); + const store = new SqliteAuthorityStore(dir, "goal-hygiene"); + const r1 = await store.commitAuthority({ + expected_provider_revision: null, + operation_id: "op-special-1", + next_projection: projection, + events, + receipts, + }); + assert.equal(r1.status, "applied"); + const r2 = await store.commitAuthority({ + expected_provider_revision: r1.status === "applied" ? r1.provider_revision : null, + operation_id: "op-special-2", + next_projection: {...projection, extra: 2}, + events, + receipts, + }); + assert.equal(r2.status, "applied"); + assert.equal((await store.loadAuthority()).status, "loaded"); + assert.equal((await store.readReceipts(["op-special-1", "op-special-2", "missing-op"])).status, "receipts"); + assert.equal((await store.verifyAuthorityHistory()).status, "verified"); + + // Verify open() rollback guard preserves BEGIN IMMEDIATE error without masking by ROLLBACK error. + const {DatabaseSync} = createRequire(import.meta.url)("node:sqlite"); + const holder = new DatabaseSync(store.path); + holder.exec("BEGIN EXCLUSIVE"); + try { + const busy = await store.commitAuthority({ + expected_provider_revision: r2.status === "applied" ? r2.provider_revision : null, + operation_id: "op-busy", + next_projection: projection, + events: [], + receipts: [], + }); + assert.equal(busy.status, "failed"); + assert.equal(busy.reason_code, "provider_transaction_failed"); + } finally { + holder.exec("ROLLBACK"); + holder.close(); + } +}); diff --git a/tests/control_plane_ts/stride_policy.test.ts b/tests/control_plane_ts/stride_policy.test.ts index c52c15ff02..a747e39d19 100644 --- a/tests/control_plane_ts/stride_policy.test.ts +++ b/tests/control_plane_ts/stride_policy.test.ts @@ -71,7 +71,10 @@ test("another Todo's activity cannot establish execution or benefit of the decla observation_refs: ["evidence:experiment"]}]}}; const review = {reference_decision_ref: previous, adoption: "executed", information_gain: "new_evidence", goal_gain: "improved", evidence_refs: ["evidence:other"], lesson: "An unrelated task completed."}; - assert.match(String(strideReviewMismatch({...proposal, previous_review: review}, context)), /declared work/); + const mismatch = String(strideReviewMismatch({...proposal, previous_review: review}, context)); + assert.match(mismatch, /declared work/); + assert.match(mismatch, /reference_decision_ref/); + assert.match(mismatch, /"unknown" for adoption and goal_gain/); assert.equal(strideReviewMismatch({...proposal, previous_review: {...review, adoption: "not_executed", goal_gain: "unknown"}}, context), null); // Negative experiments may complete; neither a score threshold nor success is required.