Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions loopx/control_plane/goals/checkpoint_commit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@ function unknown(message: string): never {
throw new EffectRuntimeRequestError(`${message}; read back the original Turn before retrying`, "checkpoint_commit_unknown");
}

function isExclusiveRegularFile(stats: { isFile(): boolean; nlink: number }): boolean {
// lstat().isFile() is true for a hard link, and realpath stays on the
// in-directory name. nlink === 1 is the exclusive runs-directory entry.
return stats.isFile() && stats.nlink === 1;
}

function indexBytes(path: string): Buffer {
const bytes = readFileSync(path);
// The ordinary history reader tolerates damaged rows. A commit cannot infer
Expand Down Expand Up @@ -92,7 +98,7 @@ export function inspectCheckpointReplay(value: unknown): JsonObject {
}

/** A copied runtime keeps absolute `<old>/goals/<goalId>/runs/<file>` paths.
* Use that file name only when it is a regular file inside the current runs directory. */
* Use that file name only when it is an exclusive regular file inside the current runs directory. */
function relocatedCheckpointArtifact(rawPath: string, runsDir: string, extension: string, goalId: string): string | null {
if (!isAbsolute(rawPath)) return null;
const normalized = resolve(rawPath);
Expand All @@ -113,7 +119,7 @@ function relocatedCheckpointArtifact(rawPath: string, runsDir: string, extension
const candidate = join(runsDirReal, fileName);
let targetPath: string;
try {
if (!lstatSync(candidate).isFile()) return null;
if (!isExclusiveRegularFile(lstatSync(candidate))) return null;
targetPath = realpathSync(candidate);
} catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; throw error; }
const relativePath = relative(runsDirReal, targetPath);
Expand All @@ -130,8 +136,9 @@ function runPath(value: unknown, runsDir: string, extension: string, goalId: str
const raw = requireNonEmptyString(value, "run artifact path");
const path = resolve(raw);
if (dirname(path) === resolve(runsDir) && path.endsWith(extension)) {
try { if (!lstatSync(path).isFile()) unknown("checkpoint artifact is not a regular file"); }
catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
try {
if (!isExclusiveRegularFile(lstatSync(path))) unknown("checkpoint artifact is not a regular file");
} catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
return path;
}
return relocatedCheckpointArtifact(raw, runsDir, extension, goalId) ?? unknown("checkpoint artifact path is invalid");
Expand Down
90 changes: 89 additions & 1 deletion tests/control_plane/test_checkpoint_relocated_replay.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
"""Public CLI replay returns the verified artifacts from the selected runtime."""
from __future__ import annotations

import errno
import io
import json
import os
from contextlib import redirect_stdout
from pathlib import Path
import shutil

Expand Down Expand Up @@ -88,9 +92,18 @@ def test_public_checkpoint_replay_returns_relocated_artifacts_without_rewriting_
assert json.loads(Path(replay["json_path"]).read_text())["vision_checkpoint"] == committed["vision_checkpoint"]


def _hardlink_or_skip(existing: Path, path: Path) -> None:
try:
os.link(existing, path)
except OSError as exc:
if exc.errno in {errno.EPERM, errno.ENOTSUP, errno.EOPNOTSUPP, errno.EXDEV, errno.ENOSYS}:
pytest.skip(f"hard links are unavailable on this platform: {exc}")
raise


@pytest.mark.parametrize("provider", ["file", "sqlite"])
@pytest.mark.parametrize("field", ["json_path", "markdown_path"])
@pytest.mark.parametrize("failure", ["missing", "symlink"])
@pytest.mark.parametrize("failure", ["missing", "symlink", "hardlink"])
def test_public_checkpoint_replay_rejects_missing_or_linked_relocated_artifacts(
tmp_path: Path, monkeypatch, provider: str, field: str, failure: str,
):
Expand All @@ -99,10 +112,13 @@ def test_public_checkpoint_replay_rejects_missing_or_linked_relocated_artifacts(
)
original_records = _historical_records(runtime)
original_path = Path(committed[field])
original_bytes = original_path.read_bytes()
candidate = relocated / "goals" / GOAL_ID / "runs" / original_path.name
candidate.unlink()
if failure == "symlink":
candidate.symlink_to(original_path)
elif failure == "hardlink":
_hardlink_or_skip(original_path, candidate)
copied_records = _historical_records(relocated)
rc, rejected = _run_cli(registry, relocated, *replay_args, cwd=project)
assert rc == 1 and rejected["ok"] is False, rejected
Expand All @@ -111,8 +127,80 @@ def test_public_checkpoint_replay_rejects_missing_or_linked_relocated_artifacts(
assert rejected["checkpoint_read_context"]["reread_required"] is False
assert _historical_records(relocated) == copied_records
assert _historical_records(runtime) == original_records
assert original_path.read_bytes() == original_bytes
assert _spend_run_count(relocated) == _spend_run_count(runtime) == 0
if failure == "symlink":
assert candidate.is_symlink() and candidate.resolve() == original_path.resolve()
elif failure == "hardlink":
assert not candidate.is_symlink()
assert candidate.stat().st_ino == original_path.stat().st_ino
assert candidate.stat().st_nlink >= 2
else:
assert not candidate.exists()


def _run_cli_inprocess(registry: Path, runtime: Path, *args: str, cwd: Path) -> tuple[int, dict]:
from loopx.cli import main as cli_main

argv = ["--registry", str(registry), "--runtime-root", str(runtime), "--format", "json", *args]
buffer = io.StringIO()
previous = Path.cwd()
os.chdir(cwd)
try:
with redirect_stdout(buffer):
rc = cli_main(argv)
finally:
os.chdir(previous)
return rc, json.loads(buffer.getvalue())


@pytest.mark.parametrize("provider", ["file", "sqlite"])
def test_public_checkpoint_commit_does_not_truncate_hard_linked_artifacts(
tmp_path: Path, monkeypatch, provider: str,
):
"""Plant the commit targets as hard links so writeSynced would share an outside inode."""
from loopx import state_refresh
from loopx.history import reserve_unique_run_paths as reserve_real

isolate_sqlite_runtime(tmp_path, monkeypatch)
project, runtime, registry, binding, delivery, _original = _missing(tmp_path, provider=provider)
rc, context = _run_cli(registry, runtime, "checkpoint-context", *binding, cwd=project)
assert rc == 0, context
replay_args = (
*delivery,
"--vision-unchanged-reason", "The accepted scope and evidence remain applicable.",
"--checkpoint-read-context", context["read_context_id"],
)
outside_json = tmp_path / "outside-checkpoint.json"
outside_markdown = tmp_path / "outside-checkpoint.md"
sentinel_json = b'{"planted":"outside-json"}\n'
sentinel_markdown = b"planted outside markdown\n"
outside_json.write_bytes(sentinel_json)
outside_markdown.write_bytes(sentinel_markdown)
index_path = runtime / "goals" / GOAL_ID / "runs" / "index.jsonl"
index_before = index_path.read_bytes()
planted: dict[str, Path] = {}

def reserve_hardlinked(runs_dir: Path, generated_at: str) -> tuple[Path, Path]:
json_path, markdown_path = reserve_real(runs_dir, generated_at)
json_path.unlink()
if markdown_path.exists():
markdown_path.unlink()
_hardlink_or_skip(outside_json, json_path)
_hardlink_or_skip(outside_markdown, markdown_path)
planted["json"] = json_path
planted["markdown"] = markdown_path
return json_path, markdown_path

monkeypatch.setattr(state_refresh, "reserve_unique_run_paths", reserve_hardlinked)
rc, rejected = _run_cli_inprocess(registry, runtime, *replay_args, cwd=project)
assert outside_json.read_bytes() == sentinel_json
assert outside_markdown.read_bytes() == sentinel_markdown
assert index_path.read_bytes() == index_before
assert planted["json"].stat().st_ino == outside_json.stat().st_ino
assert planted["markdown"].stat().st_ino == outside_markdown.stat().st_ino
assert planted["json"].stat().st_nlink >= 2
assert planted["markdown"].stat().st_nlink >= 2
assert rc == 1 and rejected["ok"] is False, rejected
assert rejected["error_code"] == "checkpoint_commit_unknown", rejected
assert "checkpoint artifact is not a regular file" in rejected["error"]
105 changes: 104 additions & 1 deletion tests/control_plane_ts/checkpoint_commit.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import assert from "node:assert/strict";
import {mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync} from "node:fs";
import {linkSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync} from "node:fs";
import {tmpdir} from "node:os";
import {join, resolve} from "node:path";
import test from "node:test";

import {inspectCheckpointReplay} from "../../loopx/control_plane/goals/checkpoint_commit.ts";
import type {JsonObject} from "../../loopx/control_plane/effect_program.ts";
import {EffectRuntimeRequestError} from "../../loopx/control_plane/effect_runtime_errors.ts";

const goalId = "goal-checkpoint-relocate";
const jsonName = "2026-08-25T12-00-00Z-checkpoint.json";
Expand Down Expand Up @@ -88,6 +89,39 @@ function rejectPrior(runsDir: string, root: string, jsonPath: string, markdownPa
assert.throws(() => inspect(root, prior), invalidPath);
}

function linkOrSkip(t: test.TestContext, existing: string, path: string): void {
try {
linkSync(existing, path);
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code === "EPERM" || code === "ENOTSUP" || code === "EOPNOTSUPP" || code === "EXDEV" || code === "ENOSYS") {
t.skip(`hard links are unavailable on this platform (${code})`);
}
throw error;
}
}

function assertExclusiveHardLink(path: string, outside: string): void {
const linked = lstatSync(path);
const target = lstatSync(outside);
assert.equal(linked.isSymbolicLink(), false);
assert.equal(linked.isFile(), true);
assert.equal(linked.nlink, 2);
assert.equal(linked.ino, target.ino);
}

function assertHardLinkRejected(root: string, prior: JsonObject, message: RegExp): void {
assert.throws(
() => inspect(root, prior),
(error: unknown) => {
assert.ok(error instanceof EffectRuntimeRequestError);
assert.equal(error.code, "checkpoint_commit_unknown");
assert.match(error.message, message);
return true;
},
);
}

test("inspectCheckpointReplay reads checkpoint artifacts copied into a relocated runtime", (t) => {
const fixture = relocatedFixture(t);
const result = inspect(fixture.relocatedRoot, fixture.prior);
Expand Down Expand Up @@ -168,3 +202,72 @@ test("inspectCheckpointReplay rejects a relocated symlink or non-file artifact",
mkdirSync(directory.relocatedJson);
rejectPrior(directory.relocatedRuns, directory.relocatedRoot, directory.originalJson, directory.originalMarkdown);
});

test("inspectCheckpointReplay rejects a relocated hard link with matching checkpoint bytes", (t) => {
const linkedJson = relocatedFixture(t);
const jsonBytes = readFileSync(linkedJson.originalJson);
const markdownBytes = readFileSync(linkedJson.relocatedMarkdown);
const indexBytes = readFileSync(join(linkedJson.relocatedRuns, "index.jsonl"));
rmSync(linkedJson.relocatedJson);
linkOrSkip(t, linkedJson.originalJson, linkedJson.relocatedJson);
assertExclusiveHardLink(linkedJson.relocatedJson, linkedJson.originalJson);
assertHardLinkRejected(linkedJson.relocatedRoot, linkedJson.prior, invalidPath);
assert.deepEqual(readFileSync(linkedJson.originalJson), jsonBytes);
assert.deepEqual(readFileSync(linkedJson.relocatedMarkdown), markdownBytes);
assert.deepEqual(readFileSync(join(linkedJson.relocatedRuns, "index.jsonl")), indexBytes);
assertExclusiveHardLink(linkedJson.relocatedJson, linkedJson.originalJson);

const linkedMarkdown = relocatedFixture(t);
const sharedMarkdown = readFileSync(linkedMarkdown.originalMarkdown);
const markdownIndex = readFileSync(join(linkedMarkdown.relocatedRuns, "index.jsonl"));
rmSync(linkedMarkdown.relocatedMarkdown);
linkOrSkip(t, linkedMarkdown.originalMarkdown, linkedMarkdown.relocatedMarkdown);
assertExclusiveHardLink(linkedMarkdown.relocatedMarkdown, linkedMarkdown.originalMarkdown);
assertHardLinkRejected(linkedMarkdown.relocatedRoot, linkedMarkdown.prior, invalidPath);
assert.deepEqual(readFileSync(linkedMarkdown.originalMarkdown), sharedMarkdown);
assert.deepEqual(readFileSync(join(linkedMarkdown.relocatedRuns, "index.jsonl")), markdownIndex);
assertExclusiveHardLink(linkedMarkdown.relocatedMarkdown, linkedMarkdown.originalMarkdown);
});

test("inspectCheckpointReplay rejects an in-directory hard link to an outside file", (t) => {
const root = runtime(t);
const runsDir = join(root, "goals", goalId, "runs");
mkdirSync(runsDir, {recursive: true});
const jsonPath = join(runsDir, jsonName);
const markdownPath = join(runsDir, markdownName);
writeJson(jsonPath, "current-runtime");
writeFileSync(markdownPath, "current markdown\n");
const outsideJson = join(root, "outside-checkpoint.json");
const outsideMarkdown = join(root, "outside-checkpoint.md");
writeJson(outsideJson, "current-runtime");
writeFileSync(outsideMarkdown, "current markdown\n");
const outsideJsonBytes = readFileSync(outsideJson);
const outsideMarkdownBytes = readFileSync(outsideMarkdown);

rmSync(jsonPath);
linkOrSkip(t, outsideJson, jsonPath);
const jsonPrior = indexPrior(jsonPath, markdownPath);
writeIndex(runsDir, jsonPrior);
const indexBytes = readFileSync(join(runsDir, "index.jsonl"));
assertExclusiveHardLink(jsonPath, outsideJson);
assertHardLinkRejected(root, jsonPrior, /checkpoint artifact is not a regular file/);
assert.deepEqual(readFileSync(outsideJson), outsideJsonBytes);
assert.deepEqual(readFileSync(markdownPath), Buffer.from("current markdown\n"));
assert.deepEqual(readFileSync(join(runsDir, "index.jsonl")), indexBytes);
assertExclusiveHardLink(jsonPath, outsideJson);

rmSync(jsonPath);
writeJson(jsonPath, "current-runtime");
const restoredJson = readFileSync(jsonPath);
rmSync(markdownPath);
linkOrSkip(t, outsideMarkdown, markdownPath);
const markdownPrior = indexPrior(jsonPath, markdownPath);
writeIndex(runsDir, markdownPrior);
const markdownIndex = readFileSync(join(runsDir, "index.jsonl"));
assertExclusiveHardLink(markdownPath, outsideMarkdown);
assertHardLinkRejected(root, markdownPrior, /checkpoint artifact is not a regular file/);
assert.deepEqual(readFileSync(outsideMarkdown), outsideMarkdownBytes);
assert.deepEqual(readFileSync(jsonPath), restoredJson);
assert.deepEqual(readFileSync(join(runsDir, "index.jsonl")), markdownIndex);
assertExclusiveHardLink(markdownPath, outsideMarkdown);
});
Loading