diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b7ebb42be..b5d9f395f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -70,6 +70,11 @@ jobs: - name: Test repo scripts run: python3 -m unittest discover -s scripts/tests -p 'test_*.py' + # The Monty forks must match the pinned upstream 1.4.0 crates except + # where a `bashkit fork:` comment marks a local edit. + - name: Check Monty fork drift + run: python3 scripts/check_monty_fork.py + wasm: # std::time panics on wasm32-unknown-unknown, so bashkit routes clock reads # through src/time_compat.rs (web-time on wasm32). This job keeps the crate diff --git a/crates/bashkit-monty-types/src/resource.rs b/crates/bashkit-monty-types/src/resource.rs index 43cda59af..935857770 100644 --- a/crates/bashkit-monty-types/src/resource.rs +++ b/crates/bashkit-monty-types/src/resource.rs @@ -12,7 +12,7 @@ use std::{ error::Error, fmt, sync::{ - OnceLock, + OnceLock, // bashkit fork: hook storage atomic::{AtomicUsize, Ordering}, }, time::Duration, diff --git a/justfile b/justfile index d8b9a3612..b946b427b 100644 --- a/justfile +++ b/justfile @@ -49,6 +49,7 @@ check: just check-doc-links just check-workflow-parity just check-changelog + just check-monty-fork # Validate the CHANGELOG release-section convention (Highlights + What's Changed). check-changelog: @@ -73,6 +74,10 @@ check-workflow-parity: # bare `jq.md` renders fine on bashkit.sh while 404-ing on GitHub. This checks # the source-relative form the site rewriter also accepts. # Validate relative markdown links in docs/ and crates/bashkit/docs/ +# Monty forks differ from upstream 1.4.0 only at `bashkit fork:` markers +check-monty-fork: + python3 scripts/check_monty_fork.py + check-doc-links: python3 scripts/check_doc_links.py diff --git a/knowledge/log.md b/knowledge/log.md index f089e0631..ab46bd027 100644 --- a/knowledge/log.md +++ b/knowledge/log.md @@ -3,6 +3,7 @@ ## 2026-11-06 * **Python wall-clock limit**: Monty 1.x pauses its clock while the VM waits on the host, so `PythonLimits::max_duration` bounded VM time only. A `while True: p.write_text('x')` loop under a 500 ms limit ran 6 s, never yielding its worker thread, so caller-side timeouts could not cancel it and co-tenants on that thread stalled. The host-call loop now enforces the wall-clock deadline (exit 124) and yields at every host call. Found by the multi-tenant stress suite. See [Python Builtin](runtimes/python-builtin.md), TM-PY-036. +* **Monty fork drift check**: `scripts/check_monty_fork.py` compares both forks with the SHA-256-pinned upstream 1.4.0 crates and fails on unmarked edits (it found one unmarked import, now marked); runs in CI lint and `just check`. Re-sync checklist for upstream security fixes added. See [Dependencies](operations/dependencies.md#monty-forks). * **Monty multi-tenant stress**: `python_tenant_stress_tests` mixes hostile and well-behaved `python3` tenants on shared worker threads, abandons calls mid-run, and reuses one session's memory budget many times; each tenant must hit only its own limit. 20-round soak passed locally (80 s). See [Python Builtin](runtimes/python-builtin.md), TM-PY-032. * **Dependabot config parse fix**: #2852 set `versioning-strategy: increase` on a cargo entry, which cargo rejects, so Dependabot refused the whole `dependabot.yml` (red check on `main`). Replaced by committing the two random-fs fixture lockfiles, which also puts them in the advisory scan; a test pins cargo strategies to `auto`/`lockfile-only`. See [Dependencies](operations/dependencies.md). * **Monty fuzz target**: `python_fuzz` fuzzes the forked Monty `python3` with the metered allocator installed (file, stdin, `-c`, CLI args; 32 MiB / 500 ms limits, per-exec wall-clock assertion, leak checks). Nightly in `fuzz.yml`, build-checked in `fuzz-check`. First local run: 282k execs in 8 min, 0 crashes. See [Python Builtin](runtimes/python-builtin.md), TM-PY-032. diff --git a/knowledge/operations/dependencies.md b/knowledge/operations/dependencies.md index 1aab4bc84..451b656f9 100644 --- a/knowledge/operations/dependencies.md +++ b/knowledge/operations/dependencies.md @@ -69,6 +69,24 @@ and a checkpoint hook. They are published with each release before `bashkit`. Upgrade by re-copying upstream source and re-applying the `bashkit fork:` edits. See [Python Builtin](../runtimes/python-builtin.md#monty-14-embedding-forks-per-vm-metering-checkpoint-hook). +`scripts/check_monty_fork.py` (CI lint job, `just check-monty-fork`) diffs both +forks against the SHA-256-pinned upstream 1.4.0 `.crate` files and fails on any +changed region without a `bashkit fork:` marker in or up to three lines above +it, on fork-only files without a marker header, on upstream files missing from +the fork (upstream tests excepted), and on any dependency or feature in a fork +`Cargo.toml` that differs from upstream's (the `monty-types` rename aside). Dependabot does not bump +crates only the forks declare, so upstream security fixes arrive by re-sync: + +1. Watch pydantic/monty releases and security advisories, and `cargo deny` + advisories against the fork's dependency versions (the Audit job). +2. For a fix: re-copy the new upstream release into both forks, re-apply every + `bashkit fork:` edit (the drift check lists what moved), bump `VERSION` and + the two hashes in `check_monty_fork.py`, and copy upstream's new + dependencies and features into each fork `Cargo.toml` (the check compares + them with upstream's normalized manifest). +3. Run `python_fuzz` and the tenant stress soak (`BASHKIT_STRESS_ROUNDS=20`) + before shipping, as the fork's own regression net. + Moving off 0.0.19 dropped the `jiter` Git patch (Monty 1.4 uses published jiter 0.17 with pyo3 0.29), the `get-size2 =0.10.1` hold (Monty's ruff AST moved to `compact_str` 0.10), and the `ruff_python_*` direct dependencies (the diff --git a/scripts/check_monty_fork.py b/scripts/check_monty_fork.py new file mode 100755 index 000000000..f20348b43 --- /dev/null +++ b/scripts/check_monty_fork.py @@ -0,0 +1,197 @@ +#!/usr/bin/env python3 +"""Check that the Monty forks differ from upstream only where marked. + +crates/bashkit-monty and crates/bashkit-monty-types are copies of Monty 1.4.0 +from crates.io with a few local edits, each marked with a `bashkit fork:` +comment. This compares every file in the forks with the pinned upstream +`.crate` and fails on any changed region that has no marker in or just above +it, and on files that exist only in the fork. + +Decision: the upstream archives are pinned by SHA-256 so the check cannot be +satisfied by a swapped download; bump UPSTREAM together with a re-sync. + +Usage: + scripts/check_monty_fork.py # download pinned upstream + scripts/check_monty_fork.py --upstream-dir D # D/-/ already extracted +""" + +from __future__ import annotations + +import argparse +import difflib +import hashlib +import io +import sys +import tarfile +import tempfile +import tomllib +import urllib.request +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +MARKER = 'bashkit fork:' +# Lines above a changed region that may hold its marker comment. +MARKER_WINDOW = 3 +VERSION = '1.4.0' +UPSTREAM = { + # fork directory: (crates.io name, sha256 of the .crate) + 'bashkit-monty': ( + 'monty', + 'b7d354901f6d6655e6bc3826f31c035417025253d7c3f7b3ef1519f681dd3469', + ), + 'bashkit-monty-types': ( + 'monty-types', + '560e0f529ceb10575efb25dabc95d41e9de0f5036fbb46f02c2ac03d83dc89e3', + ), +} +# Fork-only packaging files, not upstream source. Cargo.toml is not diffed as +# text (the fork's is hand-written, upstream's is cargo-normalized); its +# dependencies and features are compared instead, see `manifest_errors`. +FORK_ONLY = {'Cargo.toml', 'LICENSE', 'rustfmt.toml'} +# Upstream files the forks deliberately leave out: upstream tests (not +# vendored) and packaging that cargo regenerates. Any other upstream file +# missing from a fork is an error. +UPSTREAM_DROPPED = ('tests/', 'test_cases/', 'Cargo.lock', 'Cargo.toml.orig', '.cargo_vcs_info.json') +# Dependency tables compared between the fork and upstream manifests. +# dev-dependencies are skipped with the tests that use them. +DEP_TABLES = ('dependencies', 'build-dependencies') +# Dependencies the forks rename on purpose: upstream name -> fork package. +# Their version follows the fork, so only features/optionality are compared. +RENAMED_DEPS = {'monty-types': 'bashkit-monty-types'} + + +def fetch(name: str, sha256: str, dest: Path) -> Path: + url = f'https://static.crates.io/crates/{name}/{name}-{VERSION}.crate' + req = urllib.request.Request(url, headers={'User-Agent': 'bashkit-fork-check'}) + with urllib.request.urlopen(req, timeout=60) as resp: + data = resp.read() + got = hashlib.sha256(data).hexdigest() + if got != sha256: + raise SystemExit(f'{name}-{VERSION}.crate sha256 {got} != pinned {sha256}') + with tarfile.open(fileobj=io.BytesIO(data), mode='r:gz') as tar: + tar.extractall(dest, filter='data') + return dest / f'{name}-{VERSION}' + + +def unmarked_hunks(upstream: list[str], fork: list[str]) -> list[int]: + """1-based fork line numbers of changed regions with no marker nearby.""" + bad = [] + matcher = difflib.SequenceMatcher(a=upstream, b=fork, autojunk=False) + for tag, _i1, _i2, j1, j2 in matcher.get_opcodes(): + if tag == 'equal': + continue + window = fork[max(0, j1 - MARKER_WINDOW) : j2] + if not any(MARKER in line for line in window): + bad.append(j1 + 1) + return bad + + +def read_lines(path: Path) -> list[str] | None: + """Text lines, or None for a file that is not UTF-8 (compared as bytes).""" + try: + return path.read_text(encoding='utf-8').splitlines() + except UnicodeDecodeError: + return None + + +def dep_tables(manifest: dict) -> dict[str, dict]: + tables = {t: manifest.get(t, {}) for t in DEP_TABLES} + for cfg, target in manifest.get('target', {}).items(): + for t in DEP_TABLES: + if t in target: + tables[f'target.{cfg}.{t}'] = target[t] + return {name: deps for name, deps in tables.items() if deps} + + +def dep_spec(name: str, spec: dict | str) -> tuple: + if isinstance(spec, str): + spec = {'version': spec} + version = None if name in RENAMED_DEPS else spec.get('version') + return ( + version, + tuple(sorted(spec.get('features', []))), + spec.get('default-features', spec.get('default_features', True)), + spec.get('optional', False), + ) + + +def manifest_errors(fork_dir: Path, upstream_dir: Path) -> list[str]: + """Dependencies and features must match upstream's normalized manifest.""" + fork = tomllib.loads((fork_dir / 'Cargo.toml').read_text(encoding='utf-8')) + upstream = tomllib.loads((upstream_dir / 'Cargo.toml').read_text(encoding='utf-8')) + where = f'{fork_dir.name}/Cargo.toml' + errors = [] + fork_tables, up_tables = dep_tables(fork), dep_tables(upstream) + for table in sorted(set(fork_tables) | set(up_tables)): + fork_deps, up_deps = fork_tables.get(table, {}), up_tables.get(table, {}) + for name in sorted(set(fork_deps) | set(up_deps)): + if name not in up_deps: + errors.append(f'{where}: [{table}] adds `{name}`, not in upstream') + elif name not in fork_deps: + errors.append(f'{where}: [{table}] drops upstream `{name}`') + else: + fork_spec, up_spec = fork_deps[name], up_deps[name] + renamed = RENAMED_DEPS.get(name) + if renamed and (not isinstance(fork_spec, dict) or fork_spec.get('package') != renamed): + errors.append(f'{where}: [{table}] `{name}` must be package `{renamed}`') + if dep_spec(name, fork_spec) != dep_spec(name, up_spec): + errors.append(f'{where}: [{table}] `{name}` differs from upstream {up_spec!r}') + if fork.get('features', {}) != upstream.get('features', {}): + errors.append(f'{where}: [features] differ from upstream {upstream.get("features", {})!r}') + return errors + + +def check_crate(fork_dir: Path, upstream_dir: Path) -> list[str]: + errors = manifest_errors(fork_dir, upstream_dir) + for path in sorted(upstream_dir.rglob('*')): + rel = path.relative_to(upstream_dir).as_posix() + if path.is_file() and not rel.startswith(UPSTREAM_DROPPED) and not (fork_dir / rel).is_file(): + errors.append(f'{fork_dir.name}/{rel}: upstream file missing from the fork') + for path in sorted(fork_dir.rglob('*')): + if not path.is_file(): + continue + rel = path.relative_to(fork_dir) + if rel.as_posix() in FORK_ONLY: + continue + up = upstream_dir / rel + fork_lines = read_lines(path) + if not up.is_file(): + if fork_lines is None or not any(MARKER in line for line in fork_lines[:MARKER_WINDOW]): + errors.append(f'{fork_dir.name}/{rel}: not in upstream and has no `{MARKER}` header') + continue + up_lines = read_lines(up) + if fork_lines is None or up_lines is None: + if path.read_bytes() != up.read_bytes(): + errors.append(f'{fork_dir.name}/{rel}: binary file differs from upstream') + continue + for line in unmarked_hunks(up_lines, fork_lines): + errors.append(f'{fork_dir.name}/{rel}:{line}: differs from upstream without a `{MARKER}` marker') + return errors + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument('--upstream-dir', type=Path) + parser.add_argument('--root', type=Path, default=ROOT) + args = parser.parse_args(argv) + + errors = [] + with tempfile.TemporaryDirectory() as tmp: + for fork, (name, sha256) in UPSTREAM.items(): + if args.upstream_dir: + upstream = args.upstream_dir / f'{name}-{VERSION}' + else: + upstream = fetch(name, sha256, Path(tmp)) + errors += check_crate(args.root / 'crates' / fork, upstream) + + for e in errors: + print(e, file=sys.stderr) + if errors: + print(f'{len(errors)} fork drift error(s); mark source edits with `// {MARKER} `', file=sys.stderr) + return 1 + print(f'Monty forks match upstream {VERSION} outside `{MARKER}` markers') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/scripts/tests/test_check_monty_fork.py b/scripts/tests/test_check_monty_fork.py new file mode 100644 index 000000000..a7e2fa480 --- /dev/null +++ b/scripts/tests/test_check_monty_fork.py @@ -0,0 +1,153 @@ +"""Tests for scripts/check_monty_fork.py (offline, synthetic upstream trees).""" + +from pathlib import Path +import sys +import tempfile +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import check_monty_fork as cmf # noqa: E402 + +UPSTREAM_SRC = 'fn a() {}\nfn b() {\n 1\n}\nfn c() {}\n' +# cargo-normalized upstream manifest vs the fork's hand-written one. +UPSTREAM_TOML = """[package] +name = "monty" + +[features] +hooks = ["monty-types/hooks"] + +[dependencies.monty-types] +version = "1.4.0" + +[dependencies.serde] +version = "1.0" +features = ["derive"] + +[dev-dependencies.insta] +version = "1" +""" +FORK_TOML = """[package] +name = "bashkit-monty" + +[dependencies] +monty-types = { package = "bashkit-monty-types", path = "../t", version = "0.20.3" } +serde = { version = "1.0", features = ["derive"] } + +[features] +hooks = ["monty-types/hooks"] +""" + + +class CheckMontyForkTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + base = Path(self.tmp.name) + self.up = base / 'up' + self.fork = base / 'fork' + for d in (self.up, self.fork): + (d / 'src').mkdir(parents=True) + (d / 'src' / 'lib.rs').write_text(UPSTREAM_SRC) + (self.up / 'Cargo.toml').write_text(UPSTREAM_TOML) + (self.fork / 'Cargo.toml').write_text(FORK_TOML) + + def tearDown(self): + self.tmp.cleanup() + + def write_fork(self, text): + (self.fork / 'src' / 'lib.rs').write_text(text) + + def test_identical_fork_passes(self): + self.assertEqual(cmf.check_crate(self.fork, self.up), []) + + def test_marked_change_passes(self): + self.write_fork(UPSTREAM_SRC.replace(' 1\n', ' // bashkit fork: why\n 2\n')) + self.assertEqual(cmf.check_crate(self.fork, self.up), []) + + def test_marker_just_above_change_passes(self): + self.write_fork(UPSTREAM_SRC.replace('fn b() {\n 1\n', '// bashkit fork: why\nfn b() {\n 2\n')) + self.assertEqual(cmf.check_crate(self.fork, self.up), []) + + def test_unmarked_change_fails(self): + self.write_fork(UPSTREAM_SRC.replace(' 1\n', ' 2\n')) + errors = cmf.check_crate(self.fork, self.up) + self.assertEqual(len(errors), 1, errors) + self.assertIn('src/lib.rs:3', errors[0]) + + def test_unmarked_deletion_fails(self): + self.write_fork(UPSTREAM_SRC.replace('fn c() {}\n', '')) + self.assertEqual(len(cmf.check_crate(self.fork, self.up)), 1) + + def test_marker_far_above_does_not_cover_change(self): + text = '// bashkit fork: unrelated\n' + UPSTREAM_SRC.replace('fn c() {}', 'fn c() { 0 }') + self.write_fork(text) + self.assertEqual(len(cmf.check_crate(self.fork, self.up)), 1) + + def test_fork_only_file_needs_marker_header(self): + (self.fork / 'src' / 'extra.rs').write_text('fn x() {}\n') + self.assertEqual(len(cmf.check_crate(self.fork, self.up)), 1) + (self.fork / 'src' / 'extra.rs').write_text('// bashkit fork: new hook\nfn x() {}\n') + self.assertEqual(cmf.check_crate(self.fork, self.up), []) + + def test_packaging_files_are_ignored(self): + (self.fork / 'LICENSE').write_text('MIT\n') + (self.fork / 'rustfmt.toml').write_text('disable_all_formatting = true\n') + self.assertEqual(cmf.check_crate(self.fork, self.up), []) + + def test_upstream_tests_and_packaging_may_be_dropped(self): + for rel in ('tests/t.rs', 'test_cases/x.py', 'Cargo.lock', 'Cargo.toml.orig', '.cargo_vcs_info.json'): + (self.up / rel).parent.mkdir(parents=True, exist_ok=True) + (self.up / rel).write_text('x\n') + self.assertEqual(cmf.check_crate(self.fork, self.up), []) + + def test_deleted_upstream_file_fails(self): + (self.up / 'src' / 'gone.rs').write_text('fn g() {}\n') + errors = cmf.check_crate(self.fork, self.up) + self.assertEqual(len(errors), 1, errors) + self.assertIn('src/gone.rs', errors[0]) + + def test_binary_files_compare_as_bytes(self): + (self.up / 'src' / 'blob.bin').write_bytes(b'\xff\x00') + (self.fork / 'src' / 'blob.bin').write_bytes(b'\xff\x00') + self.assertEqual(cmf.check_crate(self.fork, self.up), []) + (self.fork / 'src' / 'blob.bin').write_bytes(b'\xff\x01') + errors = cmf.check_crate(self.fork, self.up) + self.assertEqual(len(errors), 1, errors) + self.assertIn('binary', errors[0]) + + def assert_manifest_error(self, fork_toml, needle): + (self.fork / 'Cargo.toml').write_text(fork_toml) + errors = cmf.check_crate(self.fork, self.up) + self.assertEqual(len(errors), 1, errors) + self.assertIn(needle, errors[0]) + + def test_added_dependency_fails(self): + self.assert_manifest_error(FORK_TOML.replace('[features]', 'evil = "1"\n\n[features]'), 'adds `evil`') + + def test_dropped_dependency_fails(self): + self.assert_manifest_error(FORK_TOML.replace('serde = { version = "1.0", features = ["derive"] }\n', ''), 'drops upstream `serde`') + + def test_changed_dependency_features_fail(self): + self.assert_manifest_error(FORK_TOML.replace('["derive"]', '["derive", "rc"]'), '`serde` differs') + + def test_changed_dependency_version_fails(self): + self.assert_manifest_error(FORK_TOML.replace('version = "1.0"', 'version = "1.1"'), '`serde` differs') + + def test_renamed_dependency_must_point_at_the_fork(self): + self.assert_manifest_error(FORK_TOML.replace('bashkit-monty-types', 'other'), 'must be package `bashkit-monty-types`') + + def test_changed_features_fail(self): + self.assert_manifest_error(FORK_TOML.replace('hooks = ["monty-types/hooks"]', 'hooks = []'), '[features]') + + def test_target_dependencies_are_compared(self): + (self.up / 'Cargo.toml').write_text(UPSTREAM_TOML + '\n[target.\'cfg(unix)\'.dependencies.libc]\nversion = "0.2"\n') + self.assert_manifest_error(FORK_TOML, 'drops upstream `libc`') + + def test_pins_cover_both_forks(self): + self.assertEqual(set(cmf.UPSTREAM), {'bashkit-monty', 'bashkit-monty-types'}) + for name, sha in cmf.UPSTREAM.values(): + self.assertRegex(sha, r'^[0-9a-f]{64}$', name) + + +if __name__ == '__main__': + unittest.main()