Skip to content

Commit 01c5909

Browse files
fix(review): close executable and fork identity gaps
1 parent 4c508ed commit 01c5909

4 files changed

Lines changed: 81 additions & 6 deletions

File tree

‎engraphis/core/ids.py‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
"""
1010
from __future__ import annotations
1111

12+
import os
1213
import secrets
1314
import threading
1415
import time
@@ -20,6 +21,20 @@
2021
_ULID_LOCK = threading.Lock()
2122
_LAST_TIMESTAMP_MS = -1
2223
_LAST_RANDOM = -1
24+
_LAST_PID = os.getpid()
25+
26+
27+
def _reset_ulid_state_after_fork() -> None:
28+
"""Drop inherited sequence state and locks in a forked child."""
29+
global _LAST_PID, _LAST_RANDOM, _LAST_TIMESTAMP_MS, _ULID_LOCK
30+
_ULID_LOCK = threading.Lock()
31+
_LAST_PID = os.getpid()
32+
_LAST_TIMESTAMP_MS = -1
33+
_LAST_RANDOM = -1
34+
35+
36+
if hasattr(os, "register_at_fork"):
37+
os.register_at_fork(after_in_child=_reset_ulid_state_after_fork)
2338

2439

2540
# Canonical prefixes for each entity kind.
@@ -59,8 +74,13 @@ def ulid(timestamp_ms: Optional[int] = None) -> str:
5974
ts = timestamp_ms
6075
if not 0 <= ts < _MAX_TIMESTAMP_MS:
6176
raise ValueError("timestamp_ms must be an integer in range [0, 2**48)")
62-
global _LAST_RANDOM, _LAST_TIMESTAMP_MS
77+
global _LAST_PID, _LAST_RANDOM, _LAST_TIMESTAMP_MS
6378
with _ULID_LOCK:
79+
pid = os.getpid()
80+
if pid != _LAST_PID:
81+
_LAST_PID = pid
82+
_LAST_TIMESTAMP_MS = -1
83+
_LAST_RANDOM = -1
6484
if ts == _LAST_TIMESTAMP_MS:
6585
if _LAST_RANDOM >= _MAX_RANDOM:
6686
raise RuntimeError("ULID entropy exhausted within one millisecond")

‎scripts/check_release_readiness.py‎

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import math
1313
import os
1414
import re
15+
import stat
1516
import subprocess
1617
from datetime import datetime, timedelta, timezone
1718
from pathlib import Path
@@ -36,8 +37,8 @@
3637
# ``sitecustomize.py`` executes before the candidate package and can alter
3738
# imports even when the tracked tree is clean.
3839
".bat", ".cjs", ".cmd", ".css", ".dll", ".dylib", ".exe", ".html",
39-
".js", ".jsx", ".mjs", ".node", ".ps1", ".pyd", ".py", ".pyc", ".pyo",
40-
".pyw", ".sh", ".so", ".ts", ".tsx",
40+
".egg", ".js", ".jsx", ".mjs", ".node", ".pth", ".ps1", ".pyd", ".py",
41+
".pyc", ".pyo", ".pyw", ".sh", ".so", ".ts", ".tsx", ".whl", ".zip",
4142
})
4243
_IGNORED_RUNTIME_DIRS = frozenset({
4344
".codex-pytest-tmp", ".hosted-eval-results", ".playwright", ".private-eval",
@@ -47,6 +48,24 @@
4748
})
4849

4950

51+
def _is_ignored_runtime_artifact(root: Path, relative: Path) -> bool:
52+
"""Return whether an ignored path can execute or affect imports."""
53+
if relative.suffix.lower() in _EXECUTABLE_SUFFIXES:
54+
return True
55+
path = root / relative
56+
try:
57+
if path.is_symlink():
58+
return True
59+
mode = path.stat().st_mode
60+
if mode & (stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH):
61+
return True
62+
with path.open("rb") as source:
63+
return source.read(2) == b"#!"
64+
except OSError:
65+
# An unreadable ignored artifact cannot be proven harmless.
66+
return True
67+
68+
5069
def canonical_bytes(value: Any) -> bytes:
5170
return json.dumps(value, sort_keys=True, separators=(",", ":"),
5271
ensure_ascii=True, allow_nan=False).encode("utf-8")
@@ -107,12 +126,11 @@ def _ignored_executable_paths(root: Path) -> list[str]:
107126
if not entry:
108127
continue
109128
relative = Path(os.fsdecode(entry))
110-
if relative.suffix.lower() not in _EXECUTABLE_SUFFIXES:
111-
continue
112129
parts = {part.lower() for part in relative.parts}
113130
if parts & _IGNORED_RUNTIME_DIRS:
114131
continue
115-
suspicious.append(relative.as_posix())
132+
if _is_ignored_runtime_artifact(root, relative):
133+
suspicious.append(relative.as_posix())
116134
return suspicious
117135

118136

‎tests/test_core_ids.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,22 @@ def test_ulids_are_monotonic_within_one_timestamp():
2626
assert values == sorted(values)
2727

2828

29+
def test_ulid_sequence_resets_when_process_id_changes(monkeypatch):
30+
random_values = iter((100, 200))
31+
process_id = 1000
32+
monkeypatch.setattr(ids.os, "getpid", lambda: process_id)
33+
monkeypatch.setattr(ids.secrets, "randbits", lambda _: next(random_values))
34+
35+
first = ids.ulid(timestamp_ms=42_000)
36+
second = ids.ulid(timestamp_ms=42_000)
37+
process_id = 1001
38+
third = ids.ulid(timestamp_ms=42_000)
39+
40+
assert first.endswith(ids._encode(100, 16))
41+
assert second.endswith(ids._encode(101, 16))
42+
assert third.endswith(ids._encode(200, 16))
43+
44+
2945
_CROCKFORD = {
3046
char: index for index, char in enumerate("0123456789ABCDEFGHJKMNPQRSTVWXYZ")
3147
}

‎tests/test_product_release_readiness.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,27 @@ def test_unchecked_hash_bytecode_cannot_qualify_candidate(ledger, tmp_path):
321321
assert not result["valid"]
322322

323323

324+
def test_extensionless_ignored_script_cannot_qualify_candidate(ledger, tmp_path):
325+
repository = tmp_path / "extensionless-script-repo"
326+
repository.mkdir()
327+
(repository / ".gitignore").write_text("release-helper\n", encoding="utf-8")
328+
(repository / "engine.py").write_text("original", encoding="utf-8")
329+
subprocess.run(["git", "init", "--quiet", str(repository)], check=True)
330+
subprocess.run(["git", "add", ".gitignore", "engine.py"], cwd=repository, check=True)
331+
subprocess.run(["git", "-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid",
332+
"commit", "--quiet", "-m", "fixture"], cwd=repository, check=True)
333+
ledger["components"]["engine"]["commit"] = subprocess.check_output(
334+
["git", "rev-parse", "HEAD"], cwd=repository, text=True).strip()
335+
ledger["candidate_id"] = candidate_id(ledger["components"])
336+
for name in RELEASE_GATES:
337+
pass_gate(ledger, tmp_path, name)
338+
(repository / "release-helper").write_text("#!/bin/sh\necho ignored\n", encoding="utf-8")
339+
result = validate(ledger, tmp_path, engine_root=repository)
340+
assert not result["engine_checkout_verified"]
341+
assert any("release-helper" in error for error in result["errors"])
342+
assert not result["valid"]
343+
344+
324345
@pytest.mark.parametrize("flag", ["--assume-unchanged", "--skip-worktree"])
325346
def test_hidden_git_changes_cannot_qualify_candidate(ledger, tmp_path, flag):
326347
repository = tmp_path / "hidden-repo"

0 commit comments

Comments
 (0)