Repository navigation
Read the calls of a Bazel workspace's files - #2148
Conversation
`scan --mode vendored` and agent mode (`scan --mode agent`, `apply`) patch a Go module by keeping a patched copy of it in the checkout, under `.socket/vendor/golang` or `.socket/go-patches`, and pointing `go.mod` at it with a directory `replace`. Only the hosted flow had a test on a real Bazel. This adds the two other modes for the same gazelle `go_deps` workspace, on Bazel 9.3.2, 8.8.2 and 7.7.2, and records what the code does there today. The next build is patched in both modes, and the undo is clean (`vendor --revert`) or leaves only the emptied `.socket/manifest.json` (`rollback`). The user's next step breaks the build: - `bazel run //:gazelle` writes a BUILD.bazel into the copy. gazelle's `go_deps` copies the directory with that file, and every target that uses the module fails to load: `No repository visible as '@rules_go'`. - When the module ships a BUILD file of its own, `bazel build //...` fails right after the command: the copy is a package of the checkout whose load of `@io_bazel_rules_go` nothing maps. Each test asserts that break by its error, so that the commit that fixes it has to change the expectation. The fixture gains a `gazelle` target, and its BUILD file is now the one gazelle writes, so a gazelle run on the unpatched checkout changes nothing and what a later run writes comes from the patch. Agent mode copies the module from the user's module cache; the test lays that directory out itself, so the runner needs no Go toolchain beyond the one rules_go downloads. gazelle is built from Go modules of its own: a flow that runs it has proxy.golang.org last in its GOPROXY list, after the stand-in that serves the module under test. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Vendored and agent mode patch a Go module by keeping a copy of it under the project's `.socket` directory and pointing `go.mod` at it with a directory `replace`. In a Bazel workspace that copy is a directory Bazel and gazelle walk like any other. The next build is patched, and then the user's ordinary steps break it, on Bazel 9.3.2, 8.8.2 and 7.7.2 with gazelle's `go_deps`: - `bazel run //:gazelle` writes a BUILD.bazel into the copy, `go_deps` copies the directory with it, and every target that uses the module fails to load (`No repository visible as '@rules_go'`); - when the module ships a BUILD file of its own, `bazel build //...` fails right after the command. One line in the `.bazelignore` at the root of the workspace prevents both, and socket-patch now writes it. This is the first Bazel file socket-patch writes. Where it applies A project is in a Bazel workspace when its directory, or one above it up to the root of its git checkout, holds a regular file `MODULE.bazel`, `REPO.bazel`, `WORKSPACE` or `WORKSPACE.bazel`. Those are the names Bazel's client looks for from the working directory up (`WorkspaceLayout::InWorkspace`, src/main/cpp/workspace_layout.cc line 36 at the tags 7.7.2, 8.8.2 and 9.3.2). The nearest such directory is the Bazel root; a directory of that name does not count. Without such a file nothing is read or written, and the run writes the same files as before, byte for byte. The checkout is the one `repo_root::find_git_repo` finds, and it counts only when its `.git` belongs to a trusted owner (`GitRepo::trusted`: the user, root, or the user sudo ran for; a root process trusts any), which is the rule the `socket.yml` lookup has for the repository root. Without it, another user's `/tmp/.git` and `/tmp/MODULE.bazel` on a shared machine would make a command in `/tmp/job/proj` create `/tmp/.bazelignore`. A project in no such checkout (a Docker build context, an unpacked source archive, a checkout of another user) is looked for in its own directory only: nothing above it is read, so a workspace file there gives no line and no warning. Neither does a Bazel root above the root of the checkout (a git submodule, several checkouts below one workspace): this repository reads no project file outside the checkout, so a look there could see the workspace file and not whether the line is in place, and its warning would never end. The nearest directory with a workspace file is the root. In a workspace that is nested in a larger one the line is therefore in the inner file, which a run from the outer workspace does not read. Measured on Bazel 9.3.2 with gazelle 0.54.0, outside the committed tests: from the outer root `bazel build //...` loads the packages of the inner tree, a BUILD file in the copy among them, and `bazel run //:gazelle` writes a BUILD.bazel into the copy, after which the inner build fails as above; with the line in the outer file, by its path from the outer root, neither happens. The writes are not widened for that. The docs name these limits and the line to add by hand. What is written - While `<project>/.socket/vendor/golang` or `<project>/.socket/go-patches` exists, the root's `.bazelignore` names it by its path from the root, on a line of its own under the comment line `# socket-patch: patched Go module copies, not Bazel packages (to opt out, comment out the next line)`. The pair is added at the end of the file, in the file's line breaks, and the file is created when missing. Never `.socket` alone: other things live there. - Nothing is added when a line already covers the directory: the path or a directory above it, with or without a trailing `/` or a leading `./`. Bazel reads a line literally, so a line with a blank before or after it, a pattern or a string prefix covers nothing. - Nothing is added either when the user declined the pair: the comment line with the path line commented out under it (`#`, blanks, the path, which may end in one `/` or start with `./` as in a line that covers). No command adds a line for that directory, warns about it or touches the two lines again, on removal either. Deleting the pair is no opt-out: the next command writes it back. Neither is commenting out both lines, or a path line changed in another way. - socket-patch knows its pair by the start of the comment line, `# socket-patch:`, not by the whole sentence: a path line under a line that starts so is its own, and that path line commented out is the opt-out. A later release can reword the comment without leaving the pairs of this one behind. - Only a directory that is not found is gone. One that cannot be probed (a directory above it that may not be searched, a transient error) keeps its pair, and gets none. - Once the directory is gone the pair is removed, and the file is the one of before, byte for byte. A file whose last line has no line break gets a line break and the pair without a final one, and loses that line break again with the pair: exactly the one the comment line ends in, which is the one that was written before it, so that a last byte that is a carriage return on its own stays. Bazel and gazelle honour a last line without a line break: the agent test on real Bazel has one. A file left empty is deleted, an empty one the user had included: it cannot be told from one socket-patch created. Only a line under such a comment line is ever removed. - The line follows the directory, not the `replace`: `rollback --preserve-state` drops the `replace` and keeps the vendored copy, whose BUILD files would be back in the workspace without the line. - A read-only file is neither replaced nor deleted. The file is opened for appending before any change, a removal included, because a rename or an unlink succeeds in a writable directory. - A file that is not updated is the new warning `bazelignore_not_updated`: it could not be read or written (a directory or a symbolic link in its place, a read-only directory, a read-only file). The detail names the line to add, or says that the lines of a copy that is gone can be deleted. The command succeeds as before. - A human run reads `Updated <path>` or `Removed <path>` on stdout when the file changed, once for each file, in words that hold for lines that came and for lines that went, and the warning on stderr. Under `--json` the warning is a run-level `warnings[]` entry; there is no new field. Which commands `commands::sync_bazelignore` is the one place the CLI asks for the file, behind one gate: not in a dry run and not in a `--global` run. Each command that can write or remove a copy calls it once, after its last step that can change a copy or take one back: `apply` (and with it `scan --mode agent` and `get`), the vendored step of `scan` and `get`, `vendor`, `vendor --revert`, `rollback`, `remove`, `repair` (also when it failed), and a hosted scan that took the lock, since a takeover removes the vendored copy. A hosted scan that took no lock may write nothing (`patches.enabled: false` in `socket.yml`, a rollout cap, no granted reference) and leaves this file alone too. The eject of a hosted project calls it after its rollback, so that an eject which vendored the Go module and was then rolled back leaves no pair for a copy that is gone again. `apply` and `vendor` in a project with no manifest end before that step. A run whose `--ecosystems` leaves `golang` out adds no line. It still takes away the pair of a copy that is gone, because `remove` of a Go patch and `vendor --revert` remove the Go copy whatever that option says. With a `--manifest-path` into another project the agent copies are those of `--cwd` and the vendored ones those of the manifest's project, so the helper brings the file of each project's Bazel root in line. `scan --prune` comes to the file a second time, after a pass that reverted a vendored entry or swept an orphan directory, which can remove the last copy after the scan's own step. That second call only takes a pair away: it adds no line and gives no warning, so the run warns once and no state is kept between the two. What it costs: a warning the scan's own step gave for a copy the pass then removed is out of date, and a file the pass cannot write is reported by the next command. The scan's own call cannot be left to that pass instead: the pass also follows the nested apply of `scan --mode agent --prune`, and it does not run at all when it cannot take the apply lock. The file is written after the commands' group commits, outside them: it is no part of a commit journal. A run that dies in between leaves a copy without its line, which the next command adds; a command that fails after it removed a copy can leave the pair behind, which ignores nothing, until the next command. A file several projects share Two projects under one Bazel root share the file, and each command holds only its own project's apply lock. So the edit, from its read to its write, is made under an advisory lock on the root directory itself: `fs2` on a handle to the directory, with contention told as the apply lock tells it (`apply_lock::is_lock_contended`). No lock file is made, in the workspace or anywhere else. A run that finds nothing to change takes no lock, also when the file cannot be read and the project has no copy to name in it. Where the directory cannot be locked (Windows, where it cannot be opened this way; a file system without such locks), or the lock stays held for a second, the edit is made without it: an add is still one appending write, which keeps what another project adds at that moment, and a removal replaces the file and can then lose such a pair until the next command in that project. With the lock, a removal in one project against an add in its sibling keeps the added pair in every one of 25 rounds of a unit test, which asserts that half on Unix only; without the lock that test fails. What a run costs The Bazel root and the bound of the checkout come from one walk up (`search_dirs`), which runs with the rest of the edit on the blocking pool. For a project outside a Bazel workspace, `d` directories below the root of its checkout, that is 2 path canonicalisations, `d + 2` stats of `.git` and `4 (d + 1)` stats of the four names, and nothing else. In a Bazel workspace it adds two stats of the copy directories and one read of `.bazelignore`; the lock and the write come only when something changes. (Counted from the code, not traced.) A side effect The line does more than keep gazelle out. Bazel leaves an ignored directory out of every `glob()` of a package above it (9.3.2, 8.8.2 and 7.7.2), so a target that hands the project's Go files to a `go` command of its own through such a glob no longer receives the copies. Built on Bazel 9.3.2 with a genrule that runs the Go SDK's `go build` over `glob(["**/*.go", "**/go.mod", "**/go.sum"])`, outside the committed tests: without the line it builds patched until the first `bazel run //:gazelle`, whose BUILD file in the copy takes the copy out of the glob in the same way, and then fails (`replacement directory ./.socket/vendor/golang/... does not exist`) together with every rules_go target that uses the module. With the line the rules_go targets build, and that genrule fails with the same error from the start; it builds when it names the copy's files as labels beside the glob, or runs outside the sandbox. A workspace that has such a target and never runs gazelle can decline the line as above. Not covered Only Go module copies get a line. Other ecosystems keep unpacked packages under `.socket/vendor/<ecosystem>` too (a crate can ship a BUILD.bazel); nothing was measured for them under Bazel, so nothing is written for them. A BUILD file that gazelle wrote into a copy before the line existed stays there: the next `scan --mode vendored` rebuilds the copy, and in agent mode the BUILD files under `.socket/go-patches` have to be deleted by hand. A project directory whose path from the root starts with `#` or white space, or holds `*`, `?` or `[`, cannot be named in `.bazelignore`: its line is written, and Bazel or gazelle does not honour it. `ignore_directories` in REPO.bazel is not read; a workspace that has it gets the line too. Tests The real-Bazel tests now assert the fixed outcome: the build prints the patched marker after the command and `bazel build //...` passes, the two tests of a module without a BUILD file build it again after `bazel run //:gazelle`, which writes nothing, and the undo takes the line away. The agent test starts from a `.bazelignore` of the user's whose last line has no line break, and ends with that file as it was. Tests without Bazel hold: the root finder (each of the four names, a directory of such a name, a link, a file above the checkout, a checkout of an owner that is not trusted and a project in no checkout, which both reach no further than the project); the line rules (what covers, the opt-out and what is none, a pair under another wording of the comment, the pair in LF and CRLF files and after a last line without a line break, the removal that leaves the file of before, a last carriage return included, a run that leaves Go out); the write (appended to the file that is there, a read-only file and a link left alone on an add and on a removal, a copy directory that cannot be probed, the lock on the root directory and none where nothing can change); two edits at once; and through the built binary each command's call: that a dry run of ten commands writes nothing in either mode, that a declined pair stays declined over scan, repair, apply, rollback and revert, that a rolled-back eject leaves the project as it was, that a prune pass and a hosted takeover take the line away with the last copy, that `--ecosystems npm` adds no line and takes the pair of a copy it removed away, that a scan which `socket.yml` lets write nothing leaves the file alone in every mode, that a manifest in another project brings both files in line, that a file which cannot be written is one warning for each command (in the envelope, and on stderr for a scan whose prune pass comes to the file a second time), what a human run prints for lines that came, lines that went and a file that went, that a project in no git checkout below a Bazel root gets no line and no warning, and that the same run in a project with no Bazel workspace file writes the same files, byte for byte but for the time in a vendored copy's marker, and no `.bazelignore`. No test depends on what lies above the temp directory: they pass with it inside a git checkout and outside one. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
`vex` and `--vex` read what socket-patch wrote and what the project's package manager installed. They read no Bazel file, so under Bazel a document can say `not_affected` for a package Bazel builds unpatched. Before the product learns to tell, this records where the document and the build agree today. It changes tests, one docs section and four workflow path lists; no file under `crates/*/src`. Each of the eight real-Bazel flows whose build is patched (Go hosted, vendored, agent, and vendored with a module that ships a BUILD file; npm hosted and vendored; PyPI hosted; RubyGems hosted) now also asserts: - the command of the mode, given `--vex`, writes the document of its own run in the checkout Bazel has built in; - `vex` writes one before the patched build and one after it, and one with `--no-verify`; - after the undo `vex` writes none and removes the last: exit 2 `manifest_not_found`, or exit 1 `no_patches` after an agent rollback, which keeps its emptied manifest; - the command and `vex` write the same two documents in a checkout that no Bazel has built in, whose files outside `.socket/` are those of the checkout that built patched. A document is held to one statement: `not_affected`, `inline_mitigations_already_exist`, the advisory of the record, the package as the one subcomponent of the product, and `Patched via Socket patch <id>` with the id of this run, ` (redirected)` or ` (vendored)` by mode, and `; not verified on disk` exactly under `--no-verify`. The envelope is held to its exact warnings. Agent mode's `apply --vex` and the second scan of the npm flows are held to the same. All of it passes on Bazel 9.3.2, 8.8.2 and 7.7.2 (macOS arm64) as the product is: no expectation had to follow a wrong document. One thing a reader of such a document should know is now asserted. For a hosted pin no form hashes a file, since the bytes come with the next build and `vex` never reads Bazel's output: the statement rests on the lock entry and the patch record. The scan says so (`vex_hosted_unverified` in `vex.warnings`); stand-alone `vex` gives no warning, before the build or after it. The added socket-patch runs take 0.2 to 0.5 seconds per flow. `e2e_vex_lockfile/bazel_beside.rs` holds what later changes must keep. A pnpm project in `web/`, beside a root `MODULE.bazel` or `WORKSPACE` that builds Java and names none of its files, gets from `vex --json`, `vex` and `apply --vex` the exit code, both streams and the document it gets without Bazel, byte for byte but for the checkout's path, the document id and the time, for a hosted pin and for an installed patch. With Bazel files that do name the project's lock the output is the same today as well (tried, not kept): that is the case later work changes. In the harness a VEX document goes beside the workspace copy, so no comparison of a checkout's files sees one, and `Cell::twin` is a shutdown plus the new `Cell::unbuilt`. The push paths of the four Bazel workflows gain `crates/socket-patch-core/src/vex/**`. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A code review of the VEX assertions in the real-Bazel flows found gaps in what the tests hold. This closes them. It changes tests, one docs sentence and the path lists of the four Bazel workflows; no file under `crates/*/src`. - The documents of a flow are compared with each other. Each one was checked alone, and its package through a normalising function, so the `%40` and the `@` spelling of an npm scope both passed and nothing showed that the forms write the same document. Now every document read in a checkout (of the run, of `vex`, of `vex --no-verify`) must equal the first one read there in every string but the document id, the timestamps and the `; not verified on disk` mark, and the documents of the checkout that Bazel has not built in must equal those of the one it has. The check of each document alone stays. The product spells all of it alike in all eight flows on Bazel 9.3.2, 8.8.2 and 7.7.2: no expectation had to differ per form. - `vex --output <file>` with no `--product`, the command a user types, runs once after the patched build in every flow. In the npm and the Go checkouts it exits 0 without a warning and writes the same document for the product of the project's own file, beside Bazel's links: `pkg:npm/socket-fixture@0.0.0` from `package.json`, `pkg:golang/example.com/consumer` from `go.mod`. The PyPI and the RubyGems fixture have no file a product is read from: there it exits 2 with `product_undetected` and writes no document. - The marker of a vendored copy is compared between the two checkouts as well, as JSON without `vendoredAt`, its one time field. The whole file was left out before, so a marker with another purl, patch id or advisory passed. - The `; not verified on disk` mark is the constant the product exports, `socket_patch_core::vex::NOT_VERIFIED_SUFFIX`. - The two hermetic tests of `e2e_vex_lockfile/bazel_beside.rs` tell each form the id of its document (`--doc-id`, and `--vex-doc-id` for `apply`) in place of rewriting the ids in what a run printed. - `docs/ecosystems.md` says that for PyPI on Bazel 8.5 and later a hosted scan leaves `MODULE.bazel.lock` stale: a build with `--lockfile_mode=error` fails until the lock is updated and committed. The PyPI flow already asserts both. - The pull request path lists of the four Bazel workflows gain `crates/socket-patch-core/src/vex/**` and `crates/socket-patch-cli/src/commands/vex*.rs`, the three files of the `vex` command. The flows hold exact VEX output, and the first commit added the core directory to the push lists only: a pull request that changed VEX code started no Bazel leg and could break all eight flows on main unseen. One hermetic test holds the two comparisons themselves: two spellings of a scope are two wordings, and a marker that names another package is another tree. The fixture checks hold the two product names to the fixtures' `package.json` and `go.mod`. Each new or changed assertion fails under one mutation, the real-Bazel ones on Bazel 9.3.2. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Whether a patch reaches a Bazel build depends on which file the
workspace's rules read: `npm.npm_translate_lock(pnpm_lock = ...)`,
`pip.parse(requirements_lock = ..., requirements_by_platform = {...})`,
`ruby.bundle_fetch(gemfile_lock = ..., gem_checksums = {...})`,
`go_deps.from_file(go_mod = ...)`. socket-patch has no reader of Bazel
files. This adds one, as library code in
`crates/socket-patch-core/src/bazel/` beside `bazel_root`. Nothing calls
it yet and no command changes: its first caller is the VEX step that
withholds a statement for a copy Bazel does not build.
What it reads
`starlark.rs` lists every call `name(...)` and `a.b(...)` of a file, at
any depth: the callee as written, its line and bytes, and each argument,
positional, by keyword, `*` or `**`. An argument is a string literal
(either quote, tripled or raw, decoded as Bazel's lexer decodes it), a
list of strings, a dict from strings to strings or lists of strings, a
bare name, or "other". A call says whether it is a whole statement, an
argument of another call, in a comprehension; only the first says that
it runs, and once. Beside the calls it lists what each statement binds
(`x = f(...)`, `x = y`, the symbols of a `load` with their aliases) and
every other place a name stands, marked where the name may be given a
value there: a tuple target, the variable of a comprehension. A name
means what the last statement before it bound it to. That is how these
files run: Bazel allows no `if`, `for` or `def` statement and no
`lambda` in them (`DotBazelFileSyntaxChecker`, the same at 7.7.2, 8.8.2
and 9.3.2). Tokens end where Bazel's lexer ends them: a name that ends a
line and a parenthesis that starts the next are two statements, and the
`for` of `0for` is a word of its own.
`workspace.rs` reads MODULE.bazel and the files it includes, through a
view: a function from a path below the Bazel root to text, absent or
unreadable, so the same code serves a checkout on disk and files held in
memory. `disk()` is the view of a checkout and opens nothing outside the
Bazel root. `Workspace::tags(extension, tag)` returns the calls of one
tag of one module extension, with the file and line of each. An
extension is known by the module and the `.bzl` file that define it
(through the name a `bazel_dep(repo_name = ...)` gives the module, or
the root module itself), never by the name of its proxy: rules_go's
`go_sdk.from_file` and gazelle's `go_deps.from_file` take the same
`go_mod`. `Workspace::label` reads a label of a tag as Bazel does: from
the root package, whichever file the tag is written in
(`StarlarkBazelModule.create`), with the root module's own repository
name as the main repository. `include` is read by Bazel's rules
(`CompiledModuleFile.checkModuleFileSyntax`,
`ModuleFileFunction.advanceHorizon`; it exists from 7.2.0): a statement
of its own with one string that starts with `//` and ends in
`.MODULE.bazel`.
Why nothing is evaluated, and what is reported instead
To evaluate Starlark is to run the workspace's code and its rulesets'.
The reader states what the text says outright and says where it cannot,
as doubts: those of the workspace (`Workspace::doubts`), which are about
every answer, and those of one answer (`Tags::doubts`). With neither,
the calls listed are the calls of that tag which the files of a
workspace Bazel accepts can make. That is held by tests, one for each
way found so far to write a call that would not be listed, and not
proven; what Bazel is told outside the files (a flag, an override on the
command line) is not known to the reader. A doubt is:
- a file that is missing, cannot be read, is not UTF-8, is over 1 MiB,
is reached through a path or a link that leaves the Bazel root, or
includes itself; a 257th file, or text past 8 MiB in all;
- a string or a bracket that is never closed, which Bazel refuses too;
- an `include`, `use_extension`, `module` or `bazel_dep` whose label or
name is not written as a plain string, or that may not run: one that
gives a name or a file and is not a whole statement (behind `and`, in
a conditional, in a comprehension);
- an `include` with a second argument (9.3.2 takes `dev_dependency`);
- one of those four names, `use_repo` or `inject_repo` used other than
to call it: under such a name, `getattr` calls a tag;
- `True`, `False` or `None` where the file may give it another value:
Bazel then reads `repo_name = None` otherwise;
- for the extension asked about, a proxy used for anything but calling
a tag on it or as the whole first argument of `use_repo` or
`inject_repo`. `override_repo` is such a use: it puts another
repository in the place of one the extension makes.
A computed argument is no doubt: the call is listed and the argument is
"other", never a guess. A label can name a target of a BUILD file
instead of a file; the reader gives its path, and whether the file
exists is for the caller to ask. WORKSPACE files and the `.bzl` files
they load are not read yet; `load` bindings and labels relative to a
package are there for them, and what a name is bound to inside a
function of a `.bzl` file is not told yet.
The reader takes any bytes and panics on none. It makes one pass over
the bytes and one over the tokens, with no recursion, a name bound again
shares what it stands for, and a query looks at each call, binding and
use once, so the work grows with the size of the files. The tests hold
that with the largest file that is read in each shape that nests or
repeats, with one long symbol, call or label that many names stand for,
and with a sample file cut and altered at every byte.
Measured, outside the tree, on the 17,842 MODULE.bazel, *.MODULE.bazel,
WORKSPACE, WORKSPACE.bazel, WORKSPACE.bzlmod and .bzl files of 35
repositories (rulesets with their examples, Bazel itself, the Bazel
Central Registry): 17,841 are read and one is refused, a fixture with
an unclosed string. Of 13,664 directories with a MODULE.bazel, 13,653
are read without a doubt. The four lookups find 941
`go_deps.from_file`, 389 `npm_translate_lock`, 984 `pip.parse` and 42
`bundle_fetch` calls; a second reading of the same files with regular
expressions finds the same calls with the same string arguments in
every directory, and 66 of them were compared by eye. What a person
can read there and the reader reports as a doubt: an include through a
directory link that leaves the Bazel root (8 directories), and a
`repo_name` given as a constant (1). What it lists without a value: 18
lock arguments that are computed, each in a comprehension. The largest
of those workspaces is 55 KiB in 70 files. A workspace made to be
costly, 8 MiB of nothing but names, takes about 1 GiB for under a
second.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The reader of `MODULE.bazel` files in
`crates/socket-patch-core/src/bazel/` still has no caller. This closes
the cases where a caller would have got a certain answer that was
wrong, or a reader that held far more than its input. No command
changes.
What a reader holds is bounded
The bounds were 1 MiB for a file, 256 files and 8 MiB of text for a
workspace. That bounds the text, not the index: every call, argument
and use owns its strings and vectors. `MODULE.bazel` and seven included
files of 1 MiB of `f(a,b,c,d)` lines made a release build hold 541 MiB
of live allocations (790 MiB resident), nested `f(f(f(` 1,082 MiB, and
one `tags()` query over a proxy that is used on every line 749 MiB.
Now a file may have 131,072 tokens (`starlark::MAX_TOKENS`), and so may
the files of one workspace together: `index` refuses a file with more,
and `Workspace::read` hands each file what the ones before it left. A
file that does not fit is a doubt about every answer ("it is too large
to read with certainty ...") and takes nothing from what is left, so a
smaller file after it is still read. An index holds at most one call,
argument, binding, use or string for a token; a test asserts that for
27 shapes. Two things grew with the input beside the index and are
bounded too. A list of doubts keeps its first 1,024: a file that names
`use_repo` on every line held 180 MiB, most of it doubts. And the label
of an included file may be 4,096 bytes long, because every doubt names
the path of its file.
Measured in a release build as peak live allocations, with the resident
size in brackets, for the largest workspace of each shape that is still
read:
calls `f(a,b,c,d)` 14.7 MiB (20.6)
arguments `f(a,a,...)` 13.9 MiB (19.2)
uses `a a a` 13.4 MiB (20.8)
bindings `a=b` 12.3 MiB (18.3)
nested calls `f(f(f(` 27.0 MiB (31.1)
strings of a list 6.9 MiB (8.9)
a proxy used on every line,
with one query 13.4 MiB (21.1)
nested calls, and seven files
of one 1 MiB name each 34.0 MiB (43.3)
255 files of 32 KB of calls 10.3 MiB (15.9)
The seven-file inputs above are now refused, and take 6 to 7 MiB. The
bound is far from real files: the largest of 13,664 real workspaces has
4,669 tokens in 70 files, 28 times fewer; the largest `MODULE.bazel`
has 3,316; and the largest of 17,842 files of any kind, a 289 KB `.bzl`
file that no workspace reads yet, has 39,954.
A WORKSPACE file beside MODULE.bazel is reported
Bazel 7 takes repositories from a `WORKSPACE` file beside
`MODULE.bazel` by default, Bazel 8 under `--enable_workspace`, Bazel 9
never: the flag defaults to true at 7.7.2 and to false at 8.8.2
(`BuildLanguageOptions.java` 7.7.2:265, 8.8.2:289) and is a no-op at
9.3.2 (`BazelRulesModule.java`:880), which has no
`WorkspaceFileFunction`. The reader said nothing of that file: a
`MODULE.bazel` without a pip tag beside a `WORKSPACE` that calls
`pip_parse(requirements_lock = ...)` gave no call and no doubt.
`Workspace::read` now asks the view for the file Bazel would take:
`WORKSPACE.bzlmod`, else `WORKSPACE.bazel`, else `WORKSPACE`
(`WorkspaceFileFunction.compute` 7.7.2:124-137, 8.8.2:132-145;
`BazelSkyframeExecutorConstants.java` 7.7.2:51, 8.8.2:32). Bazel takes
the first that is a file (`ExternalPackageHelper.checkWorkspaceFile`
7.7.2:69, 8.8.2:75), so a directory of that name is passed over: a
disk that folds case has one for `workspace`. When the file holds a
call other than `workspace(...)`, `Workspace::legacy` holds its name
and its index, or why it could not be read.
It is a field of its own and no doubt, because whether Bazel reads the
file is not in these files. A caller that knows the release, from a
`.bazelversion`, can pass over it; a caller that looks for one ruleset
can see whether the file calls it; and both can tell it from a
`MODULE.bazel` that could not be read, which is a doubt whatever the
release. Without either, an answer is certain only when the field is
`None` too. The file is read with or without a `MODULE.bazel`, last,
and within the bounds of the workspace.
Of the 13,664 real workspaces 137 have such a file, 22 of them one that
defines something, and 4 of those call a rule that reads a lock or
names packages: `maven_install` twice, `go_repository`, and a gazelle
repository macro. None calls `pip_parse`, `npm_translate_lock` or
`bundle_fetch`.
Statements Bazel refuses are doubts
A call in the body of an `if`, `for` or `def` statement was listed as a
statement that runs, with no doubt: `if False:` and an indented
`pip.parse(...)` came back as a call that runs. Bazel refuses such a
`MODULE.bazel` (`DotBazelFileSyntaxChecker.java`, identical at 7.7.2,
8.8.2 and 9.3.2: `visit(DefStatement)` :120, `visit(ForStatement)`
:138, `visit(IfStatement)` :149, and `visit(LoadStatement)` :110 for a
file that may not load, which a module file is:
`CompiledModuleFile.java` 7.7.2:96, 8.8.2:111, 9.3.2:109), and the
reading rested on that alone. `starlark::File::blocks` now lists the
statements that start with one of the three words, and in a module
file each is a doubt about every answer. So is a `load`. None of the
13,787 real module files has either, so no real workspace gains a
doubt.
`disk()` reads what the run has written
A later caller writes `MODULE.bazel` and reads the workspace in the
same run. `disk()` opened files itself, so it did not see a write that
a group commit still holds in memory. It now asks the group commit
first, for a path made of plain names only, and puts what it gets
through the same size and UTF-8 checks. A file the run has removed is
absent.
`disk()` also reads one byte more than the bound of a file, and refuses
a file that has it. Before, a file that grew after its size was taken
was cut at 1 MiB and parsed as if it ended there. The root is resolved
once, when the view is made, and no longer for every file. Its doc now
says what is not guaranteed: another process that swaps a directory for
a link between the resolving of a path and its opening is not seen.
Smaller changes
- The bindings of `load` (`Bound::Loaded`) are gone: 18 code lines and
two tests. Bazel takes no `load` in a module file, no reader used
them, and they come back with the reader of `WORKSPACE` files that
needs them. `load` stays a call in the index.
- `tags()` takes the `use_repo` arguments of each file from
`Workspace::read` instead of collecting them again for every query,
and passes over a file that does not ask for the extension.
- A file with a byte that is not UTF-8 is still refused, although Bazel
builds one whose byte is in a comment: 0 of 17,842 real files have
one, and the module doc now names the limit.
Checked
- 17,842 real Bazel files: 17,841 indexed, the same one refused, no
panic. 13,664 workspaces: none gains a doubt, and the files read and
the hub calls with every argument are the same as before in all of
them. An independent reading by regular expressions agrees on every
hub call.
- 161 hand-written hostile cases give the same output as before, but
for the four new doubts of one case. 82,000 fuzz inputs: no panic,
none over 200 ms.
- 20 mutations, at least one for each new check: each is caught by a
named test.
- The `bazel::` unit tests are 75, from 69. The two files hold 937 code
lines, from 888, and the cap of the `bazel` group in
scripts/loc-budget.json follows the code: 1,131, from 1,082.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
PR SummaryLow Risk Overview
Reviewed by Cursor Bugbot for commit dbb795b. Configure here. |
…to bazel-vex/03-not-in-build
Windows refuses to open a directory with "Access is denied", so the regular-file check after the open never ran there: a WORKSPACE.bazel directory became a doubt instead of being passed over for WORKSPACE, and the_checkout_on_disk_is_read_through_the_same_code failed on the Windows test shard. Check for a directory before opening. Assisted-by: Claude Code:claude-opus-5-5
…vex/03-not-in-build
|
[agent] PR shepherd: review brief for the approver What it does: Adds a library that reads a Bazel workspace's Risk: low. No user-visible change: outside Look here:
Verified:
Changes I made: none. Open questions: these are minor and none blocks merging; they could be follow-ups.
This PR is stacked on #2123, which needs an owner decision, so I left auto-merge off, as on #2139. Generated by Claude Code |
Wenxin Jiang (Wenxin-Jiang)
left a comment
There was a problem hiding this comment.
[agent] Reviewed at d4ca751. The tokenizer, string decoder and list/dict readers have no reachable out-of-range index and no recursion, and the byte, token, file and doubt caps hold. Every shape tried (tuple rebinding of a proxy, a non-statement use_extension, aliases, getattr, rebinding True/None, keyword-form include, @@ labels, include cycles) ends in a doubt or an unlisted call, never a wrong certain answer. CI: the cancelled run 44490464543 was a duplicate started in the same second; its twin 44490465779 is green on this head. Non-blocking: lambda raises no doubt, unlike if/for/def, and a comma inside one splits the call argument (Bazel refuses lambda in MODULE.bazel, so this is not reachable today); the library has no callers in this PR. Lands after #2139.
…nto bazel-vex/01-assert-document
…to bazel-vex/02-reader
# Conflicts: # crates/socket-patch-core/src/bazel/mod.rs # scripts/loc-budget.json
The parent branches landed on main as squash commits (#2123, #2139, #2148), so this re-applies only this PR's own changes on top of main. main (#2155) turned build_document_with into the one builder, taking an Attested struct and adding code_not_present; this PR had added a separate build_document_with_affected. The affected PURLs are now an `affected` field of Attested, handled by build_document_with: - an affected PURL still gets a statement of its own with status `affected` and its action statement; - a not_affected statement keeps main's justification rule (vulnerable_code_not_present only when no subcomponent is patched); - `vex` passes both code_not_present and affected. Tests of the affected statements now go through build_document_with. CLI_CONTRACT.md keeps main's folded warning text and adds this PR's partialFailure-on-affected sentence. The bazel LOC budget is main's plus this PR's growth. Assisted-by: Claude Code:claude-opus-5-5
No user-visible change.
What this is
Library code only: a reader of a Bazel workspace's
MODULE.bazelfiles, incrates/socket-patch-core/src/bazel/. Nothing calls it yet and no command changes.Whether a patch reaches a Bazel build depends on which file the workspace's rules read:
npm.npm_translate_lock(pnpm_lock = ...),pip.parse(requirements_lock = ...),ruby.bundle_fetch(gemfile_lock = ..., gem_checksums = {...}),go_deps.from_file(go_mod = ...), amaven.installhub's lock. socket-patch has no reader of Bazel files today, so a VEX document or a "patched" report cannot be checked against what Bazel builds. This is that reader, on its own so that it can be reviewed apart from its callers. Two callers follow, each a pull request of its own: the notice for a Maven hub that builds an unpatched jar, and the VEX step that withholds a statement for a copy Bazel does not build.Contents
bazel/starlark.rs: tokens, and every call, binding and use of a name in one filebazel/workspace.rs:MODULE.bazelwith its includes, theWORKSPACEfile beside it, labels, the calls of one tag of one module extensionbazel/mod.rsscripts/loc-budget.json: thebazelgroup's cap follows the codeImplementation: 940 code lines (1,401 lines outside the test modules). Tests: 2,502 lines, 53 unit tests. Fixtures: 0. No new dependency.
What it reads
starlark::index): every callname(...)anda.b(...)at any depth, with its line, its arguments (positional, keyword,*,**) and whether it is a whole statement, an argument of another call, or inside a comprehension. An argument is a string literal, a list of strings, a dict of those, a bare name, or "other". It also lists what each statement binds and every other place a name stands. Tokens end where Bazel's lexer ends them.Workspace::read):MODULE.bazeland the files it includes, and theWORKSPACEfile Bazel would take beside them, through a view: a function from a path below the Bazel root to text, absent or unreadable.disk()is the view of a checkout: it opens nothing outside the Bazel root, and a file the same run has written but not yet committed reads as the run left it.Workspace::tags(extension, tag)): the calls of one tag of one module extension, each with its file and line. An extension is known by the module and.bzlfile that define it, through the namebazel_dep(repo_name = ...)gives the module, never by the name of its proxy.Workspace::labelreads a label in a tag as Bazel does, from the root package.Nothing is evaluated
To evaluate Starlark would be to run the workspace's code and its rulesets'. The reader states what the text says outright and says where it cannot, as doubts: those of the workspace (about every answer) and those of one answer. A caller is certain only when both lists are empty and no
WORKSPACEfile is reported inWorkspace::legacy(or the caller knows that Bazel does not read that file, for example from a.bazelversionof 9 or later), and must say nothing, or say that it could not read the workspace, otherwise.A doubt is, for example: a file that is missing, not UTF-8, over 1 MiB, past the 131,072 tokens of a workspace, or reached through a link that leaves the Bazel root; an
if,forordefstatement or aload, which Bazel refuses in a module file; aninclude,use_extension,moduleorbazel_depwhose label or name is not a plain string or that may not run;True,FalseorNonewhere the file may give it another value; a proxy handed to anything but a tag call,use_repoorinject_repo(sooverride_repoon the extension asked about is a doubt). The two commit messages list them all, with the lines of Bazel's source at 7.7.2, 8.8.2 and 9.3.2 that each rule was read from.Bounds
A hostile workspace cannot make the reader hang, open a file outside the Bazel root, or hold more than a few tens of MiB: 1 MiB per file, 256 files asked for (and the three names of a
WORKSPACEfile), 8 MiB of text and 131,072 tokens in all, 1,024 doubts in a list; a file that cannot be had is asked for once. Measured in a release build over 25 hostile shapes, each at the largest size that is still read: at most 34 MiB of live allocations (43 MiB resident). Before the bound on tokens the same shapes at 8 MiB held 250 MiB to 1.1 GiB.What it was checked against
MODULE.bazelfiles, 330 WORKSPACE files, 3,725.bzlfiles): no panic, one file refused (an unclosed string in a fixture that Bazel refuses too). Of 13,664 workspaces, 13,653 are read without a doubt. 22 have aWORKSPACEfile that defines something, which is reported apart; 4 of those call a rule that reads a lock or names packages. The hub calls found (go_deps.from_file941,npm_translate_lock389,pip.parse982,bundle_fetch42) agree with an independent reading by regular expressions in every workspace. That run used a scratch driver and is not part of the repository.bazel_depthat does not run taken as running;None,TrueandFalserebound; memory and time that grew with the square of the input). Each is fixed and has a named test that failed before the fix. 26 mutations of the fixes: 25 are caught by a named test, and the one line no test caught was removed as unneeded.cargo fmt --check;cargo clippy --workspace --all-features -- -D warnings;cargo check --workspace --all-targets --all-features; the 75 unit tests ofbazel::; the wholesocket-patch-coreunit suite (7,976 passed);--test cli --test spawn_env_hygiene;scripts/tests;scripts/loc-budget.py.Not claimed
WORKSPACEfile at the Bazel root is indexed and handed to the caller with its calls, but no query reads it and what it loads is not followed..bzlfiles are tokenized without a panic and never read. Bindings and "whole statement" do not hold inside adef.repo_namegiven as a constant (1), anincludewithdev_dependency(Bazel 9 only; none in the 132 includes seen).WORKSPACEfile came back as a file that could not be read. The third commit asks for the kind of a path before the open, and the unit tests then pass on Windows (run 44458138306). That run is still red for one other test,scan_project_discovery_e2e::agent_scan_names_a_python_project_below_with_its_own_venv, in a file this pull request does not touch: it builds a virtualenv with the Unix layout.Size
940 code lines is above the 540 first planned. The bindings of
loadwere cut after review (18 lines; they come back with the reader of WORKSPACE files); the bounds, theWORKSPACEfile, the read of pending writes and the refused statements added 67. What could be cut next, with nothing depending on it today: followingx = y(about 8; no alias of a call in anyMODULE.bazelseen), and string escape decoding (about 28; no hub call seen needs it).Code review
A review of the first commit found eight things. The second commit (
dbb795ba5) answers them. Numbers are from a release build and from the 17,842 real Bazel files the first commit was checked against.MODULE.bazelwith seven included files of 1 MiB off(a,b,c,d)lines made the reader hold 541 MiB (790 MiB resident), and nested calls 1,082 MiB. Fixed: one file, and the files of one workspace together, may have 131,072 tokens. A file that does not fit is a doubt about every answer, and a smaller file after it is still read. A list of doubts keeps its first 1,024, and the label of an included file may be 4,096 bytes long. The worst of 25 hostile shapes at the largest size that is still read now holds 34 MiB (43 MiB resident). The bound is 28 times the largest of 13,664 real workspaces (4,669 tokens) and 3.3 times the largest real file of any kind (a.bzlfile of 39,954 tokens, which no workspace reads yet).WORKSPACEfile besideMODULE.bazelwas not mentioned, although Bazel 7 reads it by default and Bazel 8 when told to. AMODULE.bazelwithout a pip tag beside aWORKSPACEthat callspip_parsegave no call and no doubt. Fixed: the reader asks for the file Bazel would take (WORKSPACE.bzlmod, elseWORKSPACE.bazel, elseWORKSPACE) and, when it holds a call other thanworkspace(...), reports its name and its calls inWorkspace::legacy, or why it could not be read. It is a field of its own and not a doubt, because whether Bazel reads that file is not in these files: a caller that knows the release can pass over it, and a caller that looks for one ruleset can see whether the file calls it. 137 of 13,664 real workspaces have such a file, 22 define something in it, and 4 call a rule that reads a lock or names packages (maven_installtwice,go_repository, a gazelle repository macro).disk()did not see a file the same run had written and not yet committed. Fixed: it asks the run's pending writes first, for a path inside the Bazel root only, and applies the same size and UTF-8 checks. A file the run removed is absent.if,forordefstatement was listed as a statement that runs. Bazel refuses such aMODULE.bazel, and the answer rested on that alone. Fixed: each such statement, and aload, is a doubt about every answer. No real module file has one.disk()says what is not guaranteed.loadare cut (18 code lines and two tests). They come back with the reader ofWORKSPACEfiles that needs them.disk()resolves the root once instead of for every file.tags()takes each file'suse_repoarguments from the read instead of collecting them on every query, and passes over a file that does not ask for the extension. The two small maps that depend on the question are still built per query.Checked on the second commit: the same real files (no panic, no workspace gains a doubt, every hub call and every list of files read unchanged), 161 hostile cases, 82,000 fuzz inputs, 20 mutations of the new checks (each caught by a named test), the 75 unit tests of
bazel::and the wholesocket-patch-coreunit suite (7,976 passed).🤖 Generated with Claude Code