From f0bf933238756734280aa7285bd23a43d7ed8736 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Sat, 7 Nov 2026 12:58:03 +0000 Subject: [PATCH 1/3] fix(deps): let a Monty fork dependency move ahead of upstream when marked MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The forks must match upstream Monty 1.4.0, and the drift check reads that strictly for `Cargo.toml` dependencies. But nine crates are declared both in a fork and in bashkit's own crates, and Dependabot deliberately does not ignore those: bashkit has to be able to move them and to receive their advisories. A proposal for one edits the fork manifest too, so every such bump was unmergeable — #2860 (fancy-regex 0.17 -> 0.20, getrandom 0.3 -> 0.4) is the shape, and it would have returned every week. Holding the fork at upstream's version was not free either: two majors of fancy-regex sat in the graph. A fork dependency's version may now diverge when its line carries a `bashkit fork:` marker, the same mechanism source edits use. Adding or dropping a dependency stays unmarkable, since re-sync cannot reconcile a crate upstream does not have, and a marker on a dependency that already matches upstream is an error so a note left behind by a re-sync cannot excuse the next bump. The marker window is the comment block above the line plus the line itself, with no few-lines fallback: a dependency table is one entry per line, and the fallback let one note cover its neighbours. With that, this takes #2860's content: fancy-regex 0.20 and getrandom 0.4 in `bashkit-monty`, which drops fancy-regex 0.17 and its regex tree from the graph (777 -> 776 crates) and retires the now-unused vet exemption. fancy-regex 0.20 made `Captures` generic over the haystack type, so two marked `Captures<'_, str>` edits come with it. `re` is reachable from untrusted Python, so the behavior 0.20 changed is pinned rather than assumed: `regex_semantics` asserts `\xHH` above 0x7F matches the codepoint and word-boundary alternation still matches, both against what CPython prints. fancy-regex's subroutine calls are not in the fork's feature set, so 0.20's `max_prog_size` guards a blowup that is not reachable here. Claude-Session: https://claude.ai/code/session_01Wy7MByvAMwapenBYpmq9HN --- .github/dependabot.yml | 5 ++ Cargo.lock | 17 +--- crates/bashkit-monty/Cargo.toml | 12 ++- crates/bashkit-monty/src/types/re_match.rs | 4 +- crates/bashkit-monty/src/types/re_pattern.rs | 4 +- .../integration/python_integration_tests.rs | 61 +++++++++++++++ knowledge/operations/dependencies.md | 34 ++++++++ scripts/check_monty_fork.py | 78 ++++++++++++++++++- scripts/tests/test_check_monty_fork.py | 75 ++++++++++++++++++ supply-chain/config.toml | 4 - 10 files changed, 271 insertions(+), 23 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 787c80496..358479997 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -52,6 +52,11 @@ updates: # CI). Deps the forks share with bashkit's own crates (fancy-regex, # chrono, sha2, ...) are not listed: bashkit must be able to move them, # and CI shows whether the fork still builds. + # A shared dep's proposal edits the fork manifest too (it is declared + # there as well as in the workspace), which check_monty_fork.py rejects + # unless the fork's line carries a `bashkit fork:` marker. So taking one + # of those bumps means moving the fork line and marking it, not just the + # workspace line; fancy-regex and getrandom are marked that way today. # scripts/tests/test_dependabot_coverage.py keeps this list complete. - dependency-name: "ahash" - dependency-name: "hashbrown" diff --git a/Cargo.lock b/Cargo.lock index 264933999..e24b7d415 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -455,7 +455,7 @@ dependencies = [ "criterion", "ed25519-dalek", "fail", - "fancy-regex 0.20.0", + "fancy-regex", "fetchkit", "fetchkit-cli", "flate2", @@ -617,8 +617,8 @@ dependencies = [ "ahash", "bashkit-monty-types", "chrono", - "fancy-regex 0.17.0", - "getrandom 0.3.4", + "fancy-regex", + "getrandom 0.4.3", "hashbrown 0.16.1", "indexmap", "itertools 0.14.0", @@ -2133,17 +2133,6 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" -[[package]] -name = "fancy-regex" -version = "0.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72cf461f865c862bb7dc573f643dd6a2b6842f7c30b07882b56bd148cc2761b8" -dependencies = [ - "bit-set 0.8.0", - "regex-automata", - "regex-syntax", -] - [[package]] name = "fancy-regex" version = "0.20.0" diff --git a/crates/bashkit-monty/Cargo.toml b/crates/bashkit-monty/Cargo.toml index 9eff48d5b..d90bc6487 100644 --- a/crates/bashkit-monty/Cargo.toml +++ b/crates/bashkit-monty/Cargo.toml @@ -39,8 +39,16 @@ doctest = false monty-types = { package = "bashkit-monty-types", path = "../bashkit-monty-types", version = "0.20.3" } ahash = { version = "0.8.0", features = ["serde"] } chrono = { version = "0.4", features = ["serde"] } -fancy-regex = { version = "0.17.0" } -getrandom = { version = "0.3" } +# bashkit fork: declared by bashkit's own crates too (workspace: 0.20), so +# upstream's 0.17 here put two majors of fancy-regex in the graph. Also what +# Dependabot keeps proposing: it does not ignore shared deps, and the proposal +# edits this manifest. Drop the marker when upstream Monty reaches 0.20. +fancy-regex = { version = "0.20.0" } +# bashkit fork: same, aligned with the workspace's 0.4. This does not drop +# 0.3 from the graph (ahash, fastbloom and rand_core still pull it); it stops +# Dependabot re-proposing a fork edit the drift check would reject. Drop the +# marker when upstream Monty reaches 0.4. +getrandom = { version = "0.4" } hashbrown = { version = "0.16" } indexmap = { version = "2" } itertools = { version = "0.14.0" } diff --git a/crates/bashkit-monty/src/types/re_match.rs b/crates/bashkit-monty/src/types/re_match.rs index 58a203fb8..4818e7689 100644 --- a/crates/bashkit-monty/src/types/re_match.rs +++ b/crates/bashkit-monty/src/types/re_match.rs @@ -83,7 +83,9 @@ impl ReMatch { /// `subject` is the already-refcounted subject `Value` this match keeps alive /// (the caller clones it per match); `regex` supplies named-group mappings. pub fn from_captures( - caps: &fancy_regex::Captures<'_>, + // bashkit fork: fancy-regex 0.20 made `Captures` generic over the + // haystack type; the fork is ahead of upstream's 0.17 (see Cargo.toml). + caps: &fancy_regex::Captures<'_, str>, subject: Value, all_ascii: bool, regex: &fancy_regex::Regex, diff --git a/crates/bashkit-monty/src/types/re_pattern.rs b/crates/bashkit-monty/src/types/re_pattern.rs index b49dfb614..f7821a582 100644 --- a/crates/bashkit-monty/src/types/re_pattern.rs +++ b/crates/bashkit-monty/src/types/re_pattern.rs @@ -180,7 +180,9 @@ impl RePattern { /// Builds a single `ReMatch` heap value from a capture result, keeping the /// subject alive by refcount (`subject.clone_with_heap`) rather than copying /// its text. `all_ascii` is precomputed by the caller (once per `finditer`). - fn build_match(&self, caps: &fancy_regex::Captures<'_>, subject: &Value, all_ascii: bool, heap: &Heap) -> Value { + // bashkit fork: fancy-regex 0.20 made `Captures` generic over the haystack + // type; the fork is ahead of upstream's 0.17 (see Cargo.toml). + fn build_match(&self, caps: &fancy_regex::Captures<'_, str>, subject: &Value, all_ascii: bool, heap: &Heap) -> Value { let m = ReMatch::from_captures(caps, subject.clone_with_heap(heap), all_ascii, &self.compiled); Value::Ref(heap.allocate(HeapData::ReMatch(Box::new(m)))) } diff --git a/crates/bashkit/tests/integration/python_integration_tests.rs b/crates/bashkit/tests/integration/python_integration_tests.rs index 0abb6884e..7c65e184f 100644 --- a/crates/bashkit/tests/integration/python_integration_tests.rs +++ b/crates/bashkit/tests/integration/python_integration_tests.rs @@ -1658,6 +1658,67 @@ mod edge_cases { } } +// ============================================================================= +// 14b. `re` SEMANTICS ACROSS A fancy-regex MAJOR +// ============================================================================= + +// The `re` module runs backreference/lookaround patterns on fancy-regex, so a +// major bump there can move Python-visible behavior. The fork is held at a +// version ahead of upstream Monty's (see crates/bashkit-monty/Cargo.toml), and +// 0.20 changed two things these cases pin: `\xHH` above 0x7F in Unicode mode +// now matches the codepoint rather than the raw byte, and word boundaries +// compile to one delegated engine instead of one branch per alternative. +// Every expected value here is what CPython 3.11 prints for the same program. +mod regex_semantics { + use super::*; + + async fn re_line(body: &str) -> String { + let mut bash = bash_python(); + let r = bash + .exec(&format!("python3 - <<'PYEOF'\nimport re\n{body}\nPYEOF")) + .await + .unwrap(); + assert_eq!(r.exit_code, 0, "stderr: {}", r.stderr); + r.stdout.to_string() + } + + #[tokio::test] + async fn high_escape_matches_the_codepoint_not_the_raw_byte() { + // CPython: `re.match('\xff', '\xff')` matches U+00FF. + let out = re_line("print(bool(re.match(chr(0xff), chr(0xff))))").await; + assert_eq!(out, "True\n"); + } + + #[tokio::test] + async fn non_ascii_class_range_matches() { + // Case-folding prefilters for non-ASCII ranges changed in 0.20; a + // missed candidate start position would show up as a false negative. + let out = re_line( + "print(bool(re.search('[' + chr(0xe0) + '-' + chr(0xff) + ']', 'z' + chr(0xe9) + 'z')))", + ) + .await; + assert_eq!(out, "True\n"); + } + + #[tokio::test] + async fn word_boundary_alternation_matches() { + let out = re_line(r"print(bool(re.search(r'\b(?:foo|bar|baz)\b', 'a bar b')))").await; + assert_eq!(out, "True\n"); + } + + #[tokio::test] + async fn backreference_substitution_is_unchanged() { + let out = re_line(r"print(re.sub(r'(\w)\1', 'X', 'aabb'))").await; + assert_eq!(out, "XX\n"); + } + + #[tokio::test] + async fn fixed_width_lookbehind_matches() { + let out = re_line(r"print(bool(re.search(r'(?<=ab)c', 'abc')))").await; + assert_eq!(out, "True\n"); + } +} + // ============================================================================= // 15. COMPLEX SCRIPTS // ============================================================================= diff --git a/knowledge/operations/dependencies.md b/knowledge/operations/dependencies.md index 0b9878e81..6ed9fc4a7 100644 --- a/knowledge/operations/dependencies.md +++ b/knowledge/operations/dependencies.md @@ -95,6 +95,40 @@ crates only the forks declare, so upstream security fixes arrive by re-sync: 3. Run `python_fuzz` and the tenant stress soak (`BASHKIT_STRESS_ROUNDS=300`, as nightly runs it) before shipping, as the fork's own regression net. +### A fork dependency may be marked ahead of upstream + +A dependency's *version* may diverge when the fork's `Cargo.toml` line carries +a `bashkit fork: ` marker, in the comment block directly above it or at +the end of the line. Adding or dropping a dependency is never markable: re-sync +cannot reconcile a crate upstream does not have. A marker on a dependency that +matches upstream is itself an error, so a note left behind by a re-sync cannot +silently excuse the next bump. Unlike source edits there is no few-plain-lines +fallback: a dependency table is one entry per line, so the comment block is the +whole window, and one note cannot cover the entries around it. + +This exists for the nine crates the forks share with bashkit's own crates +(`chrono`, `fancy-regex`, `getrandom`, `indexmap`, `num-bigint`, `num-traits`, +`serde`, `sha1`, `sha2`). They are declared twice, once in a fork and once in +the workspace, and Dependabot deliberately does not ignore them — bashkit has +to be able to move them and to receive their advisories. But a proposal for one +edits the fork manifest as well, so a strict fork-equals-upstream rule made +every such bump unmergeable: #2860 (fancy-regex 0.17 -> 0.20, getrandom +0.3 -> 0.4) is the shape, and it would have come back every week. Holding the +fork at upstream's version instead put two majors of fancy-regex in the graph. + +`fancy-regex` and `getrandom` are marked today. Taking a shared bump therefore +means moving the fork line too, marking it, and re-applying whatever source +adaptation the new major needs — fancy-regex 0.20 made `Captures` generic over +the haystack type, so `re_match.rs` and `re_pattern.rs` carry marked +`Captures<'_, str>` edits. Because the `re` module is reachable from untrusted +Python, a major there can move Python-visible behavior: +`python_integration_tests::regex_semantics` pins the cases 0.20 changed +(`\xHH` above 0x7F matching the codepoint, word-boundary alternation) against +what CPython prints. fancy-regex's subroutine calls, whose compile-time +inlining 0.20's `max_prog_size` exists to bound, are not enabled by the fork's +default feature set, so no new compile-time blowup is reachable (TM-PY-033 +still covers runtime backtracking). + 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 index d1cd01242..fedb413c2 100755 --- a/scripts/check_monty_fork.py +++ b/scripts/check_monty_fork.py @@ -21,6 +21,7 @@ import difflib import hashlib import io +import re import sys import tarfile import tempfile @@ -97,6 +98,72 @@ def marker_window(fork: list[str], j1: int, j2: int) -> list[str]: return fork[min(start, max(0, j1 - MARKER_WINDOW)) : j2] +# `name = ...` at the start of a line: a dependency entry in a `[dependencies]` +# style table. Quoted keys are accepted because TOML allows them. +TOML_ENTRY = re.compile(r'^\s*(?:"(?P[^"]+)"|(?P[A-Za-z0-9_.+-]+))\s*=') +TOML_TABLE = re.compile(r'^\s*\[\s*([^\]]+?)\s*\]\s*$') + + +def is_toml_comment(line: str) -> bool: + """A comment line, which in TOML binds to the entry below it.""" + return line.lstrip().startswith('#') + + +def toml_marker_window(lines: list[str], j: int) -> list[str]: + """Lines that may carry the marker for the entry declared at line `j`. + + The contiguous comment block directly above the entry, in full, plus the + entry's own line (a short note often sits at the end of it). + + Decision: no `MARKER_WINDOW` fallback here, unlike source. A dependency + table is one entry per line, so "a few plain lines above" would reach over + the preceding dependencies and let one note excuse several bumps. The + comment block stops at the first non-comment line instead. + """ + start = j + while start > 0 and is_toml_comment(lines[start - 1]): + start -= 1 + return lines[start : j + 1] + + +def marked_deps(fork_dir: Path) -> set[str]: + """Dependency names in the fork manifest carrying a `bashkit fork:` marker. + + Decision: a *version* divergence may be marked, the way a source edit is. + A dependency the fork shares with bashkit's own crates is declared twice, + once here and once in the workspace, so pinning this one to upstream puts + two majors of the same crate in the graph; the alternative, telling + Dependabot to leave the name alone, would freeze it for bashkit too + (`serde`, `chrono`, `sha2` among them). Adding or dropping a dependency + stays unmarkable: re-sync cannot reconcile a crate upstream does not have. + """ + marked = set() + lines = (fork_dir / 'Cargo.toml').read_text(encoding='utf-8').splitlines() + table = None + for j, line in enumerate(lines): + header = TOML_TABLE.match(line) + if header: + table = header.group(1) + # `[dependencies.serde]` marks that one dependency. + parts = [p.strip() for p in table.split('.')] + if len(parts) >= 2 and parts[-2] in DEP_TABLES: + if any(MARKER in w for w in toml_marker_window(lines, j)): + marked.add(parts[-1]) + continue + if table is None: + continue + # Only a dependency table's entries; `[features]` entries look the same. + if table.split('.')[-1] not in DEP_TABLES: + continue + entry = TOML_ENTRY.match(line) + if not entry: + continue + name = entry.group('quoted') or entry.group('bare') + if any(MARKER in w for w in toml_marker_window(lines, j)): + marked.add(name) + return marked + + def unmarked_hunks(upstream: list[str], fork: list[str]) -> list[int]: """1-based fork line numbers of changed regions with no marker nearby.""" bad = [] @@ -144,6 +211,7 @@ def manifest_errors(fork_dir: Path, upstream_dir: Path) -> list[str]: upstream = tomllib.loads((upstream_dir / 'Cargo.toml').read_text(encoding='utf-8')) where = f'{fork_dir.name}/Cargo.toml' errors = [] + marked = marked_deps(fork_dir) 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, {}) @@ -157,8 +225,16 @@ def manifest_errors(fork_dir: Path, upstream_dir: Path) -> list[str]: 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): + differs = dep_spec(name, fork_spec) != dep_spec(name, up_spec) + if differs and name not in marked: errors.append(f'{where}: [{table}] `{name}` differs from upstream {up_spec!r}') + elif not differs and name in marked and name not in RENAMED_DEPS: + # A note left behind by a re-sync would silently excuse the + # next bump of this crate. + errors.append( + f'{where}: [{table}] `{name}` matches upstream but has a ' + f'`{MARKER}` marker; drop the marker' + ) if fork.get('features', {}) != upstream.get('features', {}): errors.append(f'{where}: [features] differ from upstream {upstream.get("features", {})!r}') return errors diff --git a/scripts/tests/test_check_monty_fork.py b/scripts/tests/test_check_monty_fork.py index 9a298bbd9..e17a7592e 100644 --- a/scripts/tests/test_check_monty_fork.py +++ b/scripts/tests/test_check_monty_fork.py @@ -195,6 +195,81 @@ 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`') + # A dependency the fork shares with bashkit's own crates has to be able to + # move ahead of upstream: the two declarations are separate, so holding the + # fork at upstream's version puts two majors of the same crate in the + # graph. Marked divergence is how that is recorded, the same way a source + # edit is. + def test_marked_dependency_version_divergence_passes(self): + fork = FORK_TOML.replace( + 'serde = { version = "1.0", features = ["derive"] }', + '# bashkit fork: shared with bashkit, moved ahead of upstream\n' + 'serde = { version = "1.1", features = ["derive"] }', + ) + (self.fork / 'Cargo.toml').write_text(fork) + self.assertEqual(cmf.check_crate(self.fork, self.up), []) + + def test_marker_on_the_dependency_line_passes(self): + fork = FORK_TOML.replace( + 'serde = { version = "1.0", features = ["derive"] }', + 'serde = { version = "1.1", features = ["derive"] } ' + '# bashkit fork: moved ahead of upstream', + ) + (self.fork / 'Cargo.toml').write_text(fork) + self.assertEqual(cmf.check_crate(self.fork, self.up), []) + + def test_marker_does_not_excuse_adding_or_dropping_a_dependency(self): + # Divergence in a *version* is reviewable; a dependency upstream does + # not have is a different crate in the graph, and re-sync cannot + # reconcile it. The marker must not reach those. + added = FORK_TOML.replace( + '[features]', + '# bashkit fork: why\nevil = "1"\n\n[features]', + ) + self.assert_manifest_error(added, 'adds `evil`') + dropped = FORK_TOML.replace( + 'serde = { version = "1.0", features = ["derive"] }\n', + '# bashkit fork: why\n', + ) + self.assert_manifest_error(dropped, 'drops upstream `serde`') + + def test_marker_for_a_dependency_that_matches_upstream_is_stale(self): + # After a re-sync the fork's version catches up and the note is dead + # weight; left in place it would silently excuse the next bump. + fork = FORK_TOML.replace( + 'serde = { version = "1.0", features = ["derive"] }', + '# bashkit fork: stale note\nserde = { version = "1.0", features = ["derive"] }', + ) + self.assert_manifest_error(fork, '`serde` matches upstream') + + def test_a_comment_block_marks_only_the_dependency_below_it(self): + # One dep's note must not excuse the next dep's drift. + fork = FORK_TOML.replace( + 'monty-types = { package = "bashkit-monty-types", path = "../t", version = "0.20.3" }\n' + 'serde = { version = "1.0", features = ["derive"] }', + '# bashkit fork: note for monty-types\n' + 'monty-types = { package = "bashkit-monty-types", path = "../t", version = "0.20.3" }\n' + 'serde = { version = "1.1", features = ["derive"] }', + ) + (self.fork / 'Cargo.toml').write_text(fork) + errors = cmf.check_crate(self.fork, self.up) + self.assertTrue(any('`serde` differs' in e for e in errors), errors) + + def test_marker_in_a_features_table_does_not_mark_a_dependency(self): + # `[features]` entries look like `name = ...` too; only dependency + # tables may carry a dependency marker. + fork = FORK_TOML.replace( + 'serde = { version = "1.0", features = ["derive"] }', + 'serde = { version = "1.1", features = ["derive"] }', + ).replace( + 'hooks = ["monty-types/hooks"]\n', + '# bashkit fork: not a dependency marker\nserde = ["monty-types/hooks"]\n', + 1, + ) + (self.fork / 'Cargo.toml').write_text(fork) + errors = cmf.check_crate(self.fork, self.up) + self.assertTrue(any('`serde` differs' in e for e in errors), errors) + def test_pins_cover_both_forks(self): self.assertEqual(set(cmf.UPSTREAM), {'bashkit-monty', 'bashkit-monty-types'}) for name, sha in cmf.UPSTREAM.values(): diff --git a/supply-chain/config.toml b/supply-chain/config.toml index ad7f6b068..8e77b63ba 100644 --- a/supply-chain/config.toml +++ b/supply-chain/config.toml @@ -721,10 +721,6 @@ criteria = "safe-to-deploy" version = "0.5.1" criteria = "safe-to-deploy" -[[exemptions.fancy-regex]] -version = "0.17.0" -criteria = "safe-to-deploy" - [[exemptions.fancy-regex]] version = "0.20.0" criteria = "safe-to-deploy" From 477ee0f9675322c898403a8ba72c334b5c294164 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Sat, 7 Nov 2026 13:09:41 +0000 Subject: [PATCH 2/3] fix(deps): scope fork dep markers per table and compare dependency sources MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two precision gaps in the marker logic, both found in review of this change. `marked_deps` keyed markers by bare dependency name while `manifest_errors` checked per (table, name), so a note on `[dependencies] serde` also silenced a `[build-dependencies] serde` drift — compile-time code behind a runtime note. Markers are now keyed by (table, name). Target tables key the same in both places: `marked_deps` reads raw header text, `dep_tables` keys from parsed TOML, and `normalize_table` strips quotes so `[target.'cfg(...)'.dependencies]` agrees with `target.cfg(...).dependencies`. `dep_spec` compared only version, features, default-features and optional, so the keys that decide *which* crate is built were invisible: an unmarked edit keeping version and features identical while adding `path = "../evil"`, a git source, or a different `package` passed silently. Those keys are now compared on their own and are never markable — a marker records a reviewed version move, and re-sync cannot reconcile a different source. The declared renames keep their `package`/`path`; the existing rename check still validates them. Pre-existing for the source keys, but this change makes the manifest comparison the load-bearing control for version policy, so it is closed here. Claude-Session: https://claude.ai/code/session_01Wy7MByvAMwapenBYpmq9HN --- knowledge/operations/dependencies.md | 26 ++++++-- scripts/check_monty_fork.py | 66 ++++++++++++++++--- scripts/tests/test_check_monty_fork.py | 88 ++++++++++++++++++++++++++ 3 files changed, 164 insertions(+), 16 deletions(-) diff --git a/knowledge/operations/dependencies.md b/knowledge/operations/dependencies.md index 6ed9fc4a7..6b334b5ad 100644 --- a/knowledge/operations/dependencies.md +++ b/knowledge/operations/dependencies.md @@ -99,12 +99,26 @@ crates only the forks declare, so upstream security fixes arrive by re-sync: A dependency's *version* may diverge when the fork's `Cargo.toml` line carries a `bashkit fork: ` marker, in the comment block directly above it or at -the end of the line. Adding or dropping a dependency is never markable: re-sync -cannot reconcile a crate upstream does not have. A marker on a dependency that -matches upstream is itself an error, so a note left behind by a re-sync cannot -silently excuse the next bump. Unlike source edits there is no few-plain-lines -fallback: a dependency table is one entry per line, so the comment block is the -whole window, and one note cannot cover the entries around it. +the end of the line. What a marker does **not** cover: + +- **Adding or dropping** a dependency. Re-sync cannot reconcile a crate + upstream does not have. +- **Where the crate comes from** — `package`, `path`, `git`, `branch`, `rev`, + `tag`, `registry`. These decide *which* crate is built rather than which + version of it, so they are compared separately and are never markable. An + edit keeping version and features identical while adding `path = "../evil"` + or swapping `package` would otherwise read as upstream's dependency; only the + declared renames (`monty-types`) carry `package` and `path`, and the rename + check validates those on their own. +- **The same crate in another table.** A marker is scoped to the table it sits + in, so a note on `[dependencies] serde` does not silence a + `[build-dependencies] serde` drift — the second runs at compile time. + +A marker on a dependency that matches upstream is itself an error, so a note +left behind by a re-sync cannot silently excuse the next bump. Unlike source +edits there is no few-plain-lines fallback: a dependency table is one entry per +line, so the comment block is the whole window, and one note cannot cover the +entries around it. This exists for the nine crates the forks share with bashkit's own crates (`chrono`, `fancy-regex`, `getrandom`, `indexmap`, `num-bigint`, `num-traits`, diff --git a/scripts/check_monty_fork.py b/scripts/check_monty_fork.py index fedb413c2..dd9cda451 100755 --- a/scripts/check_monty_fork.py +++ b/scripts/check_monty_fork.py @@ -61,6 +61,12 @@ # 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'} +# Keys that decide *which* crate is built rather than which version of it. +# Compared separately from the version and never markable: a marker records a +# reviewed version move, and re-sync cannot reconcile a different source. An +# edit that keeps version and features identical while adding `path` or `git`, +# or swapping `package`, would otherwise read as upstream's dependency. +SOURCE_KEYS = ('package', 'path', 'git', 'branch', 'rev', 'tag', 'registry', 'registry-index') def fetch(name: str, sha256: str, dest: Path) -> Path: @@ -126,8 +132,19 @@ def toml_marker_window(lines: list[str], j: int) -> list[str]: return lines[start : j + 1] -def marked_deps(fork_dir: Path) -> set[str]: - """Dependency names in the fork manifest carrying a `bashkit fork:` marker. +def normalize_table(raw: str) -> str: + """A raw TOML table header as `dep_tables` keys it (quotes stripped). + + `[target.'cfg(unix)'.dependencies]` parses to the key + `target.cfg(unix).dependencies`. Splitting on `.` assumes no cfg + expression contains a literal dot, which none does; the real-fork run and + `test_a_target_table_marker_is_keyed_like_dep_tables` keep the two in step. + """ + return '.'.join(seg.strip().strip('\'"') for seg in raw.split('.')) + + +def marked_deps(fork_dir: Path) -> set[tuple[str, str]]: + """`(table, dependency)` pairs in the fork manifest carrying a marker. Decision: a *version* divergence may be marked, the way a source edit is. A dependency the fork shares with bashkit's own crates is declared twice, @@ -135,7 +152,13 @@ def marked_deps(fork_dir: Path) -> set[str]: two majors of the same crate in the graph; the alternative, telling Dependabot to leave the name alone, would freeze it for bashkit too (`serde`, `chrono`, `sha2` among them). Adding or dropping a dependency - stays unmarkable: re-sync cannot reconcile a crate upstream does not have. + stays unmarkable: re-sync cannot reconcile a crate upstream does not have, + and so does a change of source (see `SOURCE_KEYS`). + + Decision: the marker is scoped to its table, not to the crate name. The + same crate in `[dependencies]` and in `[build-dependencies]` sits at + different points in the build -- the second runs at compile time -- so a + note on one must not silence drift in the other. """ marked = set() lines = (fork_dir / 'Cargo.toml').read_text(encoding='utf-8').splitlines() @@ -145,22 +168,23 @@ def marked_deps(fork_dir: Path) -> set[str]: if header: table = header.group(1) # `[dependencies.serde]` marks that one dependency. - parts = [p.strip() for p in table.split('.')] + parts = normalize_table(table).split('.') if len(parts) >= 2 and parts[-2] in DEP_TABLES: if any(MARKER in w for w in toml_marker_window(lines, j)): - marked.add(parts[-1]) + marked.add(('.'.join(parts[:-1]), parts[-1])) continue if table is None: continue # Only a dependency table's entries; `[features]` entries look the same. - if table.split('.')[-1] not in DEP_TABLES: + key = normalize_table(table) + if key.split('.')[-1] not in DEP_TABLES: continue entry = TOML_ENTRY.match(line) if not entry: continue name = entry.group('quoted') or entry.group('bare') if any(MARKER in w for w in toml_marker_window(lines, j)): - marked.add(name) + marked.add((key, name)) return marked @@ -193,6 +217,17 @@ def dep_tables(manifest: dict) -> dict[str, dict]: return {name: deps for name, deps in tables.items() if deps} +def dep_source(name: str, spec: dict | str) -> dict: + """The keys saying where a dependency comes from, for a non-renamed dep. + + The declared renames legitimately carry `package` and `path` (each fork + points at its sibling), and `manifest_errors` checks those on their own. + """ + if name in RENAMED_DEPS or not isinstance(spec, dict): + return {} + return {k: spec[k] for k in SOURCE_KEYS if k in spec} + + def dep_spec(name: str, spec: dict | str) -> tuple: if isinstance(spec, str): spec = {'version': spec} @@ -225,12 +260,23 @@ def manifest_errors(fork_dir: Path, upstream_dir: Path) -> list[str]: 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}`') + fork_source = dep_source(name, fork_spec) + source_differs = fork_source != dep_source(name, up_spec) + if source_differs: + errors.append( + f'{where}: [{table}] `{name}` comes from somewhere other than ' + f'upstream {fork_source!r}; a `{MARKER}` marker does not cover ' + 'a change of source' + ) + is_marked = (table, name) in marked differs = dep_spec(name, fork_spec) != dep_spec(name, up_spec) - if differs and name not in marked: + if differs and not is_marked: errors.append(f'{where}: [{table}] `{name}` differs from upstream {up_spec!r}') - elif not differs and name in marked and name not in RENAMED_DEPS: + elif not differs and is_marked and name not in RENAMED_DEPS and not source_differs: # A note left behind by a re-sync would silently excuse the - # next bump of this crate. + # next bump of this crate. Not reported when the source + # already differs: the marker is not stale there, it just + # does not cover what was changed, which is said above. errors.append( f'{where}: [{table}] `{name}` matches upstream but has a ' f'`{MARKER}` marker; drop the marker' diff --git a/scripts/tests/test_check_monty_fork.py b/scripts/tests/test_check_monty_fork.py index e17a7592e..446aa3929 100644 --- a/scripts/tests/test_check_monty_fork.py +++ b/scripts/tests/test_check_monty_fork.py @@ -270,6 +270,94 @@ def test_marker_in_a_features_table_does_not_mark_a_dependency(self): errors = cmf.check_crate(self.fork, self.up) self.assertTrue(any('`serde` differs' in e for e in errors), errors) + def test_a_marker_does_not_reach_the_same_crate_in_another_table(self): + # A marker is scoped to the table it sits in. `[dependencies] serde` + # and `[build-dependencies] serde` are different positions in the + # build -- the second runs at compile time -- so a note on one must + # not silence drift in the other. + (self.up / 'Cargo.toml').write_text( + UPSTREAM_TOML + '\n[build-dependencies.serde]\nversion = "1.0"\n' + ) + (self.fork / 'Cargo.toml').write_text( + FORK_TOML.replace( + 'serde = { version = "1.0", features = ["derive"] }', + '# bashkit fork: runtime serde moved ahead of upstream\n' + 'serde = { version = "1.1", features = ["derive"] }', + ) + + '\n[build-dependencies]\nserde = { version = "1.2" }\n' + ) + errors = cmf.check_crate(self.fork, self.up) + self.assertTrue( + any('[build-dependencies]' in e and '`serde` differs' in e for e in errors), + errors, + ) + self.assertFalse( + [e for e in errors if e.startswith('fork/Cargo.toml: [dependencies] `serde`')], + errors, + ) + + # Where a dependency comes from is not a version, so a marker cannot excuse + # it: re-sync cannot reconcile a different source, and an identical version + # says nothing about what was actually built. + def test_source_substitution_fails_even_with_identical_version(self): + self.assert_manifest_error( + FORK_TOML.replace( + 'serde = { version = "1.0", features = ["derive"] }', + 'serde = { version = "1.0", features = ["derive"], path = "../evil" }', + ), + '`serde` comes from', + ) + + def test_a_marker_does_not_excuse_a_source_substitution(self): + self.assert_manifest_error( + FORK_TOML.replace( + 'serde = { version = "1.0", features = ["derive"] }', + '# bashkit fork: why\n' + 'serde = { version = "1.0", features = ["derive"], git = "https://e.example/s" }', + ), + '`serde` comes from', + ) + + def test_repackaging_a_dependency_fails(self): + # `package = ...` swaps which crate is built while the version and + # features still read as upstream's; only the declared renames may. + self.assert_manifest_error( + FORK_TOML.replace( + 'serde = { version = "1.0", features = ["derive"] }', + 'serde = { package = "evil-serde", version = "1.0", features = ["derive"] }', + ), + '`serde` comes from', + ) + + def test_a_target_table_marker_is_keyed_like_dep_tables(self): + # `marked_deps` reads the raw header text while `manifest_errors` keys + # tables from parsed TOML; a quoted cfg must normalize to the same key + # in both, or a marker in a target table would never match. + cfg = "cfg(all(target_arch = \"wasm32\", target_os = \"unknown\"))" + (self.up / 'Cargo.toml').write_text( + UPSTREAM_TOML + f"\n[target.'{cfg}'.dependencies.web-time]\nversion = \"1.0\"\n" + ) + marked = FORK_TOML + ( + f"\n[target.'{cfg}'.dependencies]\n" + '# bashkit fork: moved ahead of upstream\n' + 'web-time = { version = "1.1" }\n' + ) + (self.fork / 'Cargo.toml').write_text(marked) + self.assertEqual(cmf.check_crate(self.fork, self.up), []) + + # And without the marker the same drift is still reported. + (self.fork / 'Cargo.toml').write_text( + FORK_TOML + + f"\n[target.'{cfg}'.dependencies]\nweb-time = {{ version = \"1.1\" }}\n" + ) + errors = cmf.check_crate(self.fork, self.up) + self.assertTrue(any('`web-time` differs' in e for e in errors), errors) + + def test_the_declared_rename_keeps_its_path_and_package(self): + # monty-types legitimately points at the sibling fork by path, which + # the source check must not flag. + self.assertEqual(cmf.check_crate(self.fork, self.up), []) + def test_pins_cover_both_forks(self): self.assertEqual(set(cmf.UPSTREAM), {'bashkit-monty', 'bashkit-monty-types'}) for name, sha in cmf.UPSTREAM.values(): From 43c752046c504038cc6f95b40fb0cbac26e0a0fb Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Sat, 7 Nov 2026 13:18:20 +0000 Subject: [PATCH 3/3] fix(deps): reject a patch or replace table in a fork manifest `[patch.crates-io]` and `[replace]` redirect a crate's source without touching the dependency line, so the per-dependency source check never sees them: a fork could point `serde` at a git fork while its `[dependencies]` line stayed identical to upstream's and the drift check passed clean. Rejected on sight rather than compared, and no marker covers them. Upstream Monty 1.4 has neither table and a fork has no reason to, so comparing versions inside one would be code for a case that should not exist. `[patch]` in a non-root manifest is inert today, but the forks are published crates and a consumer may build one as its own workspace root, so this does not rest on that. Claude-Session: https://claude.ai/code/session_01Wy7MByvAMwapenBYpmq9HN --- knowledge/operations/dependencies.md | 5 +++++ scripts/check_monty_fork.py | 12 ++++++++++++ scripts/tests/test_check_monty_fork.py | 22 ++++++++++++++++++++++ 3 files changed, 39 insertions(+) diff --git a/knowledge/operations/dependencies.md b/knowledge/operations/dependencies.md index 6b334b5ad..92593db1a 100644 --- a/knowledge/operations/dependencies.md +++ b/knowledge/operations/dependencies.md @@ -113,6 +113,11 @@ the end of the line. What a marker does **not** cover: - **The same crate in another table.** A marker is scoped to the table it sits in, so a note on `[dependencies] serde` does not silence a `[build-dependencies] serde` drift — the second runs at compile time. +- **A `[patch]` or `[replace]` table.** These redirect a source without + touching the dependency line the per-dependency check reads, so they are + rejected on sight rather than compared; upstream has neither. `[patch]` in a + non-root manifest is inert today, but the forks are published crates and a + consumer may build one as its own workspace root. A marker on a dependency that matches upstream is itself an error, so a note left behind by a re-sync cannot silently excuse the next bump. Unlike source diff --git a/scripts/check_monty_fork.py b/scripts/check_monty_fork.py index dd9cda451..6a59edb5b 100755 --- a/scripts/check_monty_fork.py +++ b/scripts/check_monty_fork.py @@ -58,6 +58,12 @@ # Dependency tables compared between the fork and upstream manifests. # dev-dependencies are skipped with the tests that use them. DEP_TABLES = ('dependencies', 'build-dependencies') +# Tables that redirect a crate's source without touching the dependency line, +# so the per-dependency source check never sees them. Upstream has neither, and +# a fork has no reason to: rejected outright rather than compared, and no +# marker covers them. `[patch]` in a non-root manifest is inert today, but the +# forks are published crates and a consumer may build one as its own root. +SOURCE_REDIRECT_TABLES = ('patch', 'replace') # 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'} @@ -281,6 +287,12 @@ def manifest_errors(fork_dir: Path, upstream_dir: Path) -> list[str]: f'{where}: [{table}] `{name}` matches upstream but has a ' f'`{MARKER}` marker; drop the marker' ) + for table in SOURCE_REDIRECT_TABLES: + if table in fork: + errors.append( + f'{where}: [{table}] redirects dependency sources and upstream has ' + f'none; remove it (no `{MARKER}` marker covers a source redirect)' + ) if fork.get('features', {}) != upstream.get('features', {}): errors.append(f'{where}: [features] differ from upstream {upstream.get("features", {})!r}') return errors diff --git a/scripts/tests/test_check_monty_fork.py b/scripts/tests/test_check_monty_fork.py index 446aa3929..f8fa7398d 100644 --- a/scripts/tests/test_check_monty_fork.py +++ b/scripts/tests/test_check_monty_fork.py @@ -318,6 +318,28 @@ def test_a_marker_does_not_excuse_a_source_substitution(self): '`serde` comes from', ) + def test_a_patch_table_fails(self): + # `[patch]` redirects a crate's source without touching the + # `[dependencies]` line the per-dep source check reads, so it would + # otherwise slip past. Upstream Monty 1.4 has none. + self.assert_manifest_error( + FORK_TOML + '\n[patch.crates-io]\nserde = { git = "https://e.example/s" }\n', + '[patch] redirects', + ) + + def test_a_replace_table_fails(self): + self.assert_manifest_error( + FORK_TOML + '\n[replace]\n"serde:1.0.0" = { git = "https://e.example/s" }\n', + '[replace] redirects', + ) + + def test_a_marker_does_not_excuse_a_patch_table(self): + self.assert_manifest_error( + FORK_TOML + + '\n# bashkit fork: why\n[patch.crates-io]\nserde = { git = "https://e.example/s" }\n', + '[patch] redirects', + ) + def test_repackaging_a_dependency_fails(self): # `package = ...` swaps which crate is built while the version and # features still read as upstream's; only the declared renames may.