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
40 changes: 30 additions & 10 deletions loopx/control_plane/quota/accounting_artifact_transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,12 @@ function isNodeErrorCode(error: unknown, code: string): boolean {
return error instanceof Error && "code" in error && error.code === code;
}

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;
}

async function pathExists(path: string): Promise<boolean> {
try {
await access(path);
Expand Down Expand Up @@ -584,7 +590,7 @@ async function relocatedRunArtifactPath(
}
const candidate = join(runsDirReal, fileName);
try {
if (!(await lstat(candidate)).isFile()) return null;
if (!isExclusiveRegularFile(await lstat(candidate))) return null;
const targetPath = await realpath(candidate);
if (relative(runsDirReal, targetPath) !== fileName) return null;
} catch (error) {
Expand Down Expand Up @@ -718,13 +724,18 @@ export async function readQuotaSpendEventFromRun(
const candidatePath = staysInsideInitial || relocatedCandidate === null
? resolve(rawPath)
: relocatedCandidate;
let candidateStat;
try {
candidateStat = await lstat(candidatePath);
} catch (error) {
if (isNodeErrorCode(error, "ENOENT")) return null;
throw error;
}
let targetPath: string;
try {
targetPath = await realpath(candidatePath);
} catch (error) {
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
return null;
}
if (isNodeErrorCode(error, "ENOENT")) return null;
throw error;
}
const relativePath = relative(runsDirReal, targetPath);
Expand All @@ -738,6 +749,7 @@ export async function readQuotaSpendEventFromRun(
"quota spend json_path must stay inside the goal runs directory",
);
}
if (!isExclusiveRegularFile(candidateStat)) return null;
let content: string;
try {
content = await readFile(targetPath, "utf8");
Expand Down Expand Up @@ -958,17 +970,25 @@ function validateReceiptPaths(
}

async function rejectSymlinkPath(path: string, label: string): Promise<void> {
let stats;
try {
if ((await lstat(path)).isSymbolicLink()) {
throw new EffectRuntimeRequestError(
`${label} must not be a symbolic link`,
"malformed_transaction_receipt",
);
}
stats = await lstat(path);
} catch (error) {
if (isNodeErrorCode(error, "ENOENT")) return;
throw error;
}
if (stats.isSymbolicLink()) {
throw new EffectRuntimeRequestError(
`${label} must not be a symbolic link`,
"malformed_transaction_receipt",
);
}
if (stats.isFile() && !isExclusiveRegularFile(stats)) {
throw new EffectRuntimeRequestError(
`${label} must not be a hard link`,
"malformed_transaction_receipt",
);
}
}

async function readReceipt(
Expand Down
46 changes: 29 additions & 17 deletions loopx/control_plane/quota/ledger_readback.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,16 +180,28 @@ def _stays_inside_runs_dir(runs_dir: Path, stored_path: str) -> bool:
)


def _exclusive_regular_file(path: Path) -> bool:
"""True when ``path`` is one regular file with no other directory entry.

``lstat`` does not follow a symlink. A hard link is still a regular file,
and ``resolve`` stays on the in-directory name, so ``st_nlink == 1`` is
the exclusive artifact the quota reader can open.
"""

info = path.lstat()
return stat.S_ISREG(info.st_mode) and info.st_nlink == 1


def _relocated_run_artifact_path(
runs_dir: Path,
goal_id: str,
stored_path: str,
extension: str,
) -> Path | None:
"""Same-named regular file in the current runs directory, or None.
"""Same-named exclusive regular file in the current runs directory, or None.

Symlinks, directories, and files whose real path leaves the runs directory
are not substitutes for the stored artifact.
Symlinks, hard links, directories, and files whose real path leaves the
runs directory are not substitutes for the stored artifact.
"""

file_name = _copied_goal_run_file_name(stored_path, goal_id, extension)
Expand All @@ -203,7 +215,7 @@ def _relocated_run_artifact_path(
return None
candidate = runs_real / file_name
try:
if not stat.S_ISREG(candidate.lstat().st_mode):
if not _exclusive_regular_file(candidate):
return None
target = candidate.resolve(strict=True)
except OSError:
Expand All @@ -220,24 +232,24 @@ def relocated_run_artifact_path(
stored_path: str,
extension: str,
) -> Path | None:
"""Same-named regular ``.json`` or ``.md`` file inside ``runs_dir``.
"""Same-named exclusive regular ``.json`` or ``.md`` file inside ``runs_dir``.

Symlinks, directories, and files whose real path leaves the runs directory
are not substitutes. A stored path that is already inside ``runs_dir``, or
that does not name this goal's runs file, returns None so the caller keeps
the stored path.
Symlinks, hard links, directories, and files whose real path leaves the
runs directory are not substitutes. A stored path that is already inside
``runs_dir``, or that does not name this goal's runs file, returns None so
the caller keeps the stored path.
"""

return _relocated_run_artifact_path(runs_dir, goal_id, stored_path, extension)


def _regular_artifact_inside_runs_dir(runs_dir: Path, stored_path: str) -> str | None:
"""Real path of a regular file that stays inside ``runs_dir``.
"""Real path of an exclusive regular file that stays inside ``runs_dir``.

Lexical containment is not enough. ``Path.read_bytes`` follows a symlink,
so a runs-directory path can still name an outside quota event. Symlinks,
directories, and files whose real path leaves the runs directory are not
the stored artifact.
and a hard link is a regular file whose real path stays inside the runs
directory. Symlinks, hard links, directories, and files whose real path
leaves the runs directory are not the stored artifact.
"""

try:
Expand All @@ -248,7 +260,7 @@ def _regular_artifact_inside_runs_dir(runs_dir: Path, stored_path: str) -> str |
if expanded is None:
return None
try:
if not stat.S_ISREG(expanded.lstat().st_mode):
if not _exclusive_regular_file(expanded):
return None
target = expanded.resolve(strict=True)
except OSError:
Expand All @@ -274,9 +286,9 @@ def _quota_event_artifact_path(
"""Path to open, or None when a known runs directory must not leave itself.

Callers that do not know the current runs directory keep the stored path.
Callers that do open a regular file already inside that directory, or the
same-named regular file copied into it, only when its real path stays
there. Every other absolute location stays unread.
Callers that do open an exclusive regular file already inside that
directory, or the same-named exclusive regular file copied into it, only
when its real path stays there. Every other absolute location stays unread.
"""

if runs_dir is None:
Expand Down
187 changes: 187 additions & 0 deletions tests/control_plane/test_quota_ledger_relocated_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from __future__ import annotations

import json
import os
import shutil
from datetime import datetime, timedelta, timezone
from pathlib import Path
Expand Down Expand Up @@ -409,6 +410,192 @@ def test_in_directory_symlink_cannot_zero_a_quota_debit(tmp_path: Path) -> None:
assert outside.read_bytes() == outside_bytes


def test_in_directory_hard_link_cannot_zero_a_quota_debit(tmp_path: Path) -> None:
"""A path already inside the runs directory is still not a hard-link alias.

The stored path names this goal's runs file, so the lexical containment
check keeps it. Replacing that file with a hard link to an outside
artifact that repeats the commit identity and says the debit was zero
must not read as a readable zero spend. The outside bytes stay untouched.
"""

now = datetime.now(timezone.utc)
spend_at = now - timedelta(minutes=5)
runtime = tmp_path / "runtime"
runs = runtime / "goals" / GOAL_ID / "runs"
artifact = runs / "spend.json"
commit = _commit(
"quota_spend_commit_receipt_v0",
"effect-spend",
REQUEST_DIGEST,
)
event = {
"event_type": "quota_slot_spent",
"slots": 2,
"run_generated_at": spend_at.isoformat(),
}
record = {
"generated_at": spend_at.isoformat(),
"goal_id": GOAL_ID,
"classification": "quota_slot_spent",
"quota_event": event,
"quota_spend_commit": commit,
}
_write_record(artifact, record)
row = _row(
artifact,
generated_at=spend_at,
classification="quota_slot_spent",
commit_field="quota_spend_commit",
commit=commit,
)
goal = _goal()
counted, counted_reason = quota_slot_observation(
row,
runs_dir=runs,
goal_id=GOAL_ID,
)
assert counted_reason is None
assert counted == ("spent", spend_at.isoformat(), 2)

outside = tmp_path / "outside-zero.json"
zero_record = {
**record,
"quota_event": {**event, "slots": 0},
}
outside_bytes = json.dumps(zero_record).encode()
outside.write_bytes(outside_bytes)
artifact.unlink()
os.link(outside, artifact)

contribution, reason = quota_slot_observation(
row,
runs_dir=runs,
goal_id=GOAL_ID,
)
assert contribution is None
assert reason == QUOTA_EVENT_UNREADABLE_ARTIFACT_MISSING
ledger = goal_quota_with_spend_ledger(goal, [row], now=now, runs_dir=runs)
assert ledger["spent_slots"] == 0
assert ledger["unreadable_event_count"] == 1
assert ledger["unreadable_event_reasons"] == [QUOTA_EVENT_UNREADABLE_ARTIFACT_MISSING]
status = quota_status(
{**goal, "quota": {**goal["quota"], **ledger}},
waiting_on="codex",
)
assert status["state"] == "blocked_health"
summary = build_usage_summary(
{"runs": [row]},
parse_timestamp=_parse_timestamp,
runtime_root=runtime,
)
assert summary["totals"]["quota_spend_slots_24h"] == 0
assert summary["totals"]["unreadable_event_count_24h"] == 1
assert not artifact.is_symlink()
assert artifact.stat().st_ino == outside.stat().st_ino
assert artifact.stat().st_nlink == 2
assert outside.read_bytes() == outside_bytes


def test_relocated_hard_link_cannot_zero_a_quota_debit(tmp_path: Path) -> None:
"""A copied runs file that shares an outside inode is not the spend artifact.

The index still names the old runtime. The same-named file in the new
runs directory is a hard link to an outside zero-slot artifact that
repeats the commit identity. That alias must not read as a zero spend,
and the reader must not fall back to the old tree.
"""

now = datetime.now(timezone.utc)
spend_at = now - timedelta(minutes=5)
runtime_a = tmp_path / "runtime-a"
runtime_b = tmp_path / "runtime-b"
artifact = runtime_a / "goals" / GOAL_ID / "runs" / "spend.json"
commit = _commit(
"quota_spend_commit_receipt_v0",
"effect-spend",
REQUEST_DIGEST,
)
event = {
"event_type": "quota_slot_spent",
"slots": 2,
"run_generated_at": spend_at.isoformat(),
}
record = {
"generated_at": spend_at.isoformat(),
"goal_id": GOAL_ID,
"classification": "quota_slot_spent",
"quota_event": event,
"quota_spend_commit": commit,
}
_write_record(artifact, record)
row = _row(
artifact,
generated_at=spend_at,
classification="quota_slot_spent",
commit_field="quota_spend_commit",
commit=commit,
)
index_path = artifact.parent / "index.jsonl"
index_path.write_text(json.dumps(row) + "\n", encoding="utf-8")
original_bytes = artifact.read_bytes()
runs_b, index_bytes = _copy_runs(runtime_a, runtime_b)
copied_row = json.loads((runs_b / "index.jsonl").read_text(encoding="utf-8"))
counted, counted_reason = quota_slot_observation(
copied_row,
runs_dir=runs_b,
goal_id=GOAL_ID,
)
assert counted_reason is None
assert counted == ("spent", spend_at.isoformat(), 2)

outside = tmp_path / "outside-zero.json"
zero_record = {
**record,
"quota_event": {**event, "slots": 0},
}
outside_bytes = json.dumps(zero_record).encode()
outside.write_bytes(outside_bytes)
copied = runs_b / artifact.name
copied.unlink()
os.link(outside, copied)

contribution, reason = quota_slot_observation(
copied_row,
runs_dir=runs_b,
goal_id=GOAL_ID,
)
assert contribution is None
assert reason == QUOTA_EVENT_UNREADABLE_ARTIFACT_MISSING
ledger = goal_quota_with_spend_ledger(
_goal(),
[copied_row],
now=now,
runs_dir=runs_b,
)
assert ledger["spent_slots"] == 0
assert ledger["unreadable_event_count"] == 1
assert ledger["unreadable_event_reasons"] == [QUOTA_EVENT_UNREADABLE_ARTIFACT_MISSING]
status = quota_status(
{**_goal(), "quota": {**_goal()["quota"], **ledger}},
waiting_on="codex",
)
assert status["state"] == "blocked_health"
summary = build_usage_summary(
{"runs": [copied_row]},
parse_timestamp=_parse_timestamp,
runtime_root=runtime_b,
)
assert summary["totals"]["quota_spend_slots_24h"] == 0
assert summary["totals"]["unreadable_event_count_24h"] == 1
assert not copied.is_symlink()
assert copied.stat().st_ino == outside.stat().st_ino
assert copied.stat().st_nlink == 2
assert outside.read_bytes() == outside_bytes
assert artifact.read_bytes() == original_bytes
assert (runs_b / "index.jsonl").read_bytes() == index_bytes


def test_copied_commit_digest_must_match_before_the_slots_count(tmp_path: Path) -> None:
now = datetime.now(timezone.utc)
spend_at = now - timedelta(minutes=15)
Expand Down
Loading
Loading