Skip to content

chore: enforce forbid-unsafe-code invariant and add pre-push cargo check - #770

Merged
robcohen merged 2 commits into
mainfrom
chore/unsafe-invariant-and-pre-push-check
Apr 11, 2026
Merged

robcohen merged 2 commits into
mainfrom
chore/unsafe-invariant-and-pre-push-check

Conversation

@robcohen

Copy link
Copy Markdown
Member

Implements recommendations 2 and 3 from the weekend code review (internal context). Two small pieces of CI/tooling hygiene aimed at a class of AI-generated PR failures we saw this week.

Why

Closed PRs #768 and #769 had a common failure mode: the author pushed code that didn't compile, then CI caught it 15 jobs deep. #769 specifically added `unsafe { String::from_utf8_unchecked(...) }` to `rustledger-loader`, which has `#![forbid(unsafe_code)]` at `src/lib.rs:28`. `cargo check` correctly rejected it, but the error reads:

```
error: usage of an `unsafe` block
--> crates/rustledger-loader/src/vfs.rs:76:13
```

without mentioning the forbid directive the author was violating. Reviewers had to hunt for context. More importantly, the author clearly hadn't run `cargo check` locally before pushing, otherwise all three compile errors would have been visible in 30 seconds.

Both of these are free to catch.

What this PR adds

1. `scripts/check-unsafe-invariant.sh` (new, 160 lines)

Shell script that enumerates workspace crates with `#![forbid(unsafe_code)]` (9 at time of writing) and greps each for `unsafe {` / `unsafe fn` / `unsafe impl` / `unsafe trait`. On violation, prints both the offending line and the forbid directive line with guidance on how to resolve:

```

FORBID_UNSAFE_CODE VIOLATION in crate: rustledger-loader

Directive: #![forbid(unsafe_code)] at crates/rustledger-loader/src/lib.rs:28

Offending lines:
crates/rustledger-loader/src/lib.rs:991:fn _test_violation() { let _ = unsafe { ... }; }

Either:

  1. Remove the unsafe block/item and use a safe alternative, or
  2. If unsafe is genuinely required, remove the
    #![forbid(unsafe_code)] directive from crates/rustledger-loader/src/lib.rs:28
    and justify the change in the PR description.
    (Reviewers will treat removal of a forbid directive as
    a significant change requiring extra scrutiny.)
    ============================================================
    ```

Runs in milliseconds (grep over source, no compilation). Exits 0/1/2 for clean/violation/invocation-error. Handles invocation from any directory via `git rev-parse --show-toplevel`.

2. `Unsafe Invariant` CI job (`.github/workflows/ci.yml`)

New fast-check job added alongside `Format`. Runs the script above with no toolchain install (~1 second on a fresh runner). Wired into the `build` gate's `needs` list so it must pass for merges. Gets a named CI status, so violations don't have to be dug out of the generic `Check` job's 500-line log.

3. Pre-push hooks (`.pre-commit-config.yaml`)

Two new pre-push hook entries:

  • `cargo-check` — runs `cargo check --workspace --all-features --all-targets` before every push. Unlike clippy/test (which the existing config correctly notes are too slow for pre-push), `cargo check` skips codegen and lint passes and is typically 2-30 seconds on a warm incremental cache. Catches the compile-error class that killed feat: incremental parsing for LSP (5-10x faster) #768/perf: SIMD UTF-8 validation (2-4x faster file loading) #769 before the PR even opens. Use `git push --no-verify` to bypass for intentional WIP pushes.

  • `unsafe-invariant` — same script as the CI job, as a second defense layer. Faster than `cargo check` for the specific forbid-unsafe-code case, and surfaces the clearer error message locally too.

The existing pre-commit-config comment that explains why clippy/test are not pre-push is preserved and extended with an explanation of why `cargo check` is fast enough to be.

How it was tested

  1. Clean tree: `OK: all 9 forbid-unsafe-code crates are clean` — exit 0.
  2. Injected violation: added a test function with `let _ = unsafe { std::mem::transmute::<u8, u8>(0) };` to `rustledger-loader/src/lib.rs`, ran the script, got the violation output above with the correct file:line, correct forbid directive pointer, and exit 1. Reverted immediately.
  3. YAML validation: both `.github/workflows/ci.yml` and `.pre-commit-config.yaml` parsed cleanly via `python3 -c "import yaml; yaml.safe_load(...)"`.
  4. pre-commit hooks ran on commit (rustfmt, typos, gitleaks, commitizen) — all passed.

Risks and limitations

  • The grep is conservative. It matches `unsafe` followed by `{`, `fn`, `impl`, or `trait` as whole words. A string literal containing `"unsafe { ... }"` in, say, a test fixture would produce a false positive. I haven't found any in the current tree, but if one shows up later, the fix is either to rephrase the string or add a `#[allow(...)]` marker the script can skip. I chose this conservative approach because a false positive is cheap (rename the string) but a false negative (missed violation) is the thing we're trying to prevent.
  • The pre-push hook adds 2-30 seconds to every push on warm caches. On cold caches (first push after a dependency update), it can be several minutes. `--no-verify` is the escape hatch.
  • The unsafe-invariant check is redundant with `cargo check` for the compile-error aspect. The value is the clearer error message, faster feedback, and named CI status. It's not meant to replace `cargo check`.

What it does not do

  • Does not run clippy, tests, docs, fuzz, or bench as pre-push hooks. Those continue to run only in CI per the existing policy.
  • Does not modify any production code.
  • Does not change the existing forbid directives in any crate.

Closes no issue (chore). Complements #758 / #767-era reliability work by making it harder to ship obviously-broken code.

Two small pieces of CI/tooling hygiene to prevent a class of
AI-generated PR failures that showed up in this week's review cycle
(closed PRs #768 and #769 for specific examples).

## Why

PR #769 opened with code that added `unsafe { String::from_utf8_unchecked(...) }`
to `rustledger-loader`, a crate with `#![forbid(unsafe_code)]` declared
at `src/lib.rs:28`. `cargo check` correctly rejected it, but the error
message reads:

    error: usage of an `unsafe` block
     --> crates/rustledger-loader/src/vfs.rs:76:13

without mentioning the forbid directive the author was violating.
Reviewers had to hunt for context. More importantly, the PR had 15
separate CI failures because three of its three code changes
referenced hallucinated API surfaces. The author clearly hadn't run
`cargo check` locally before pushing.

Both of these are free to catch:

1. The unsafe violation can be surfaced as a named CI status with a
   clearer error message (this commit adds `scripts/check-unsafe-invariant.sh`
   and a dedicated `Unsafe Invariant` CI job).

2. The "didn't run cargo check locally" class can be caught by a
   pre-push hook that runs `cargo check` before the push even reaches
   the remote.

## What changed

1. **`scripts/check-unsafe-invariant.sh`** — new shell script that
   enumerates workspace crates with `#![forbid(unsafe_code)]` (9 at
   time of writing) and greps each for `unsafe {` / `unsafe fn` /
   `unsafe impl` / `unsafe trait`. On violation, prints both the
   offending line and the forbid directive line, with guidance on
   how to resolve. Runs in milliseconds. Exits 0/1/2 for
   clean/violation/invocation-error.

2. **`.github/workflows/ci.yml`** — new `unsafe-invariant` job added
   alongside the existing `Format` fast-check job. Added to the
   `build` gate's `needs` list so it must pass for merges. Runs
   without installing any toolchain (just shell + grep) so it
   finishes in ~1 second on a fresh runner. Fails loudly and early
   on any forbid-unsafe-code violation.

3. **`.pre-commit-config.yaml`** — two new pre-push hooks:
   - `cargo-check` — runs `cargo check --workspace --all-features
     --all-targets` before push. Typically 2-30 seconds on a warm
     cache. Catches compile errors (hallucinated APIs, missing
     imports, type mismatches, `unsafe` in forbid-unsafe-code crates)
     before the PR is opened. Use `git push --no-verify` to bypass
     for intentional WIP pushes.
   - `unsafe-invariant` — runs the new script from (1) as a second
     layer of defense. Faster than cargo-check for the specific
     forbid-unsafe-code case, and surfaces a clearer error message.

## What it doesn't do

These hooks don't replace clippy, test, or fuzz runs — those still
only happen in CI because they're too slow for pre-push. The
existing comment in `.pre-commit-config.yaml` about why clippy/test
are intentionally NOT pre-push is preserved and extended to explain
why `cargo check` IS fast enough.

## How it was tested

Tested the invariant script three ways:
1. Clean tree: `OK: all 9 forbid-unsafe-code crates are clean`
2. Injected `fn _test_violation() { let _ = unsafe { ... }; }` into
   `rustledger-loader/src/lib.rs` — script correctly reports violation,
   points at both the offending line and the `#![forbid(unsafe_code)]`
   directive at `src/lib.rs:28`, exits 1.
3. YAML syntax of `ci.yml` and `.pre-commit-config.yaml` validated
   via `python3 -c "import yaml; yaml.safe_load(...)"`.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings April 11, 2026 20:37
@robcohen
robcohen requested a review from a team as a code owner April 11, 2026 20:37
@robcohen
robcohen added this pull request to the merge queue Apr 11, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds fast “unsafe-code invariant” enforcement and earlier compile-safety checks to prevent avoidable CI failures (e.g., pushing code that doesn’t compile or introducing unsafe into crates that declare #![forbid(unsafe_code)]).

Changes:

  • Add scripts/check-unsafe-invariant.sh to detect unsafe usage in crates that declare #![forbid(unsafe_code)].
  • Add a dedicated Unsafe Invariant GitHub Actions job and wire it into the build gate.
  • Add pre-push hooks to run cargo check --workspace --all-features --all-targets and the unsafe-invariant script.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 5 comments.

File Description
scripts/check-unsafe-invariant.sh New script to enumerate forbid-unsafe crates and grep for unsafe usage with clearer error output.
.github/workflows/ci.yml Adds a fast unsafe-invariant job and requires it in the merge gate.
.pre-commit-config.yaml Adds pre-push hooks for cargo check and the unsafe-invariant script.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread scripts/check-unsafe-invariant.sh Resolved
Comment thread scripts/check-unsafe-invariant.sh Resolved
Comment thread scripts/check-unsafe-invariant.sh Resolved
Comment thread scripts/check-unsafe-invariant.sh Resolved
Comment thread .pre-commit-config.yaml Resolved
@codecov

codecov Bot commented Apr 11, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Apr 11, 2026 •

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 99%
BQL Compatibility 100%
Full AST Match 98%
Total Files 784
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to Branch Protection failures Apr 11, 2026
You're not authorized to push to this branch. Visit "About protected branches" for more information.
robcohen added a commit that referenced this pull request Apr 11, 2026
Bumps the whole workspace from 0.11.0 to 0.12.0 (minor version bump
under pre-1.0 semver because the cycle since 0.11.0 includes
user-visible breaking changes that release-plz's auto-detection
missed).

release-plz auto-generated a v0.11.1 patch bump from the `fix:` /
`feat:` commits since 0.11.0. That's too conservative. The cycle
since 0.11.0 shipped the following breaking changes, all merged as
`refactor:` / `fix:` without the `!` conventional-commit marker:

- **`rustledger_booking::BookingError`** collapsed three variants
  (`InsufficientUnits`, `NoMatchingLot`, `AmbiguousMatch`) into a
  single `Inventory(AccountedBookingError)` variant (#751). Out-of-tree
  consumers pattern-matching on the old variants break.

- **`rustledger_core::AccountedBookingError`** added as a new
  canonical user-facing type with `BookingError::with_account()` as
  the constructor (#751). Not a break on its own, but part of the
  unification.

- **`rustledger_lsp::handlers::diagnostics::all_diagnostics`**
  signature changed to take an additional `other_buffer_overlays:
  &[(u16, &[Spanned<Directive>])]` parameter for multi-buffer LSP
  overlays (#760 / #764).

- **`rustledger_lsp::handlers::diagnostics::validation_errors_to_diagnostics`**
  signature changed to take an owned `Vec<Spanned<Directive>>`
  instead of borrowed slices (#758). Optimizes a hot path but breaks
  the function's public signature.

- **`rustledger_loader::LoadError::IncludeCycle`** Display format
  rewritten to match Python beancount's `"Duplicate filename
  parsed: ..."` wording (#767). Substring-matching consumers break.

Under pre-1.0 semver, any breaking change should bump the minor
version (0.x → 0.(x+1)). So 0.11.0 → 0.12.0 is correct.

Highlights since 0.11.0:

### Breaking

- Unified `BookingError` under a single `Inventory` variant with one
  canonical `Display` impl, preventing the wording drift that
  produced #748 (#751).
- `LoadError::IncludeCycle` Display now begins with `"Duplicate
  filename parsed: "` to match beancount's wording for conformance
  (#767).
- LSP `all_diagnostics` and `validation_errors_to_diagnostics`
  signatures changed to support the multi-buffer overlay and avoid
  double-cloning directive lists (#758 / #764).

### Features

- LSP live overlay so in-memory buffer edits reflect in diagnostics
  before save, for both the current file (#685 / #758) and any other
  open buffer in a multi-file ledger (#760 / #764).
- Parser `Vec::with_capacity` hints with DoS caps on `source.len()`
  heuristics (#754).
- `working_inventories` cloning in the booking engine now only
  touches accounts actually referenced in the transaction, and
  dedupes repeated account references (#756).

### Fixes

- `InsufficientUnits` booking error wording restored to `"Not enough
  units in ..."` so pta-standards `reduction-exceeds-inventory`
  conformance assertion passes (#748 / #749).
- `noduplicates` plugin now hashes flag, tags, links, cost, and
  price in addition to date and narration — complete beancount
  `hash_entry` parity (#746 / #747).
- Parser test suite: 14 fake-coverage tests replaced with real tests
  that exercise the functions they claim to cover (#766).
- All Copilot inline review comments on #754-#763, #766, #767
  addressed in fix commits.
- Closed PRs #768 (dead incremental parser) and #769 (hallucinated
  simdutf8 API) — no code shipped from these.

### Internal

- Forbid-unsafe-code invariant now has a dedicated CI check and
  pre-push hook (#770).
- New pre-push `cargo check` hook to catch compile errors before PRs
  are opened (#770).

This commit supersedes release-plz's auto-generated v0.11.1 proposal
to produce the minor bump the breaking changes require.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Four inline comments from Copilot, all legitimate:

1. **`\s` is not portable in POSIX grep** (script lines 65 and 111).
   GNU grep on Linux accepts `\s` as an extension, which is why the
   tests passed on the dev machine and in GitHub's Linux runners. But
   `\s` is a PCRE escape, not POSIX BRE/ERE — BSD/macOS grep treats it
   as a literal `s`. If anyone ran the script on macOS, or if GitHub
   Actions ever switched runner images, the forbid-directive lookup
   would silently fail on every file. Replaced both occurrences with
   the POSIX character class `[[:space:]]*`.

2. **Unsafe-detection regex missed `unsafe{}` without space** (line
   124). The previous pattern `unsafe[[:space:]]+(\{|fn|impl|trait)`
   required at least one whitespace between `unsafe` and the
   following token, which correctly handles `unsafe fn` / `unsafe
   impl` / `unsafe trait` (Rust's lexer rejects the no-space forms
   like `unsafefn` as a single identifier anyway), but missed valid
   `unsafe{ body }`.

   Split the alternation so keyword forms still require whitespace
   (preventing `unsafefn` false positives) but block forms allow
   zero whitespace:

       (^|[^[:alnum:]_])unsafe([[:space:]]+(fn|impl|trait)|[[:space:]]*\{)

   Verified on clean tree, on an injected `unsafe{ 42 }` violation,
   and on a negative `unsafefn` identifier case.

   The `unsafe /* comment */ {}` case is still not matched. Copilot
   suggested handling it too, but block-comment regex support adds
   significant complexity for a case that's vanishingly rare in
   practice. Documented as a known limitation in a new comment
   block above the regex.

3. **Comment about test scanning was wrong** (line 122). The old
   comment claimed "Tests are NOT excluded: a forbid-unsafe-code
   crate with test-only unsafe is still a violation because
   `#![forbid]` at the crate root applies to the whole crate
   including tests". That's wrong for integration tests and
   benchmarks — each file under `tests/` and `benches/` is a SEPARATE
   crate target that does not inherit the library crate's root
   attributes. The script only scans `src/`, which correctly covers
   `#[cfg(test)]` modules inside `src/lib.rs` (those DO compile
   under the same attributes) but not the other directories.

   Rewrote the comment to be accurate: scans `src/` only, documents
   that integration tests and benchmarks are separate targets and
   need their own forbid directives if the same guarantee is wanted.

4. **Pre-push hook `types: [rust]` filter was too narrow**
   (.pre-commit-config.yaml). Both the `cargo-check` and
   `unsafe-invariant` hooks were gated on `types: [rust]`, meaning a
   push that touched only `Cargo.toml` or `Cargo.lock` (dependency
   bump, feature flag change, workspace version edit) would skip
   both. For cargo-check specifically, that's the exact class of
   change most likely to introduce compile errors.

   Dropped the `types` filter and added `always_run: true` on both
   hooks. Runs unconditionally on every push. Added comments
   explaining why each hook is `always_run`.

All four fixes verified locally:
- Clean-tree run: "OK: all 9 forbid-unsafe-code crates are clean"
- Injected `unsafe{}` (no space) violation: caught with correct
  file:line and forbid directive pointer, exit 1
- Negative test `unsafefn` identifier: no false positive
- YAML parse: both ci.yml and .pre-commit-config.yaml valid

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@robcohen
robcohen added this pull request to the merge queue Apr 11, 2026
Merged via the queue into main with commit 9bb70ea Apr 11, 2026
30 checks passed
@robcohen
robcohen deleted the chore/unsafe-invariant-and-pre-push-check branch April 11, 2026 21:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants