Skip to content

test(scripts): the guard had two blind spots, and its controls shared them - #1140

Closed
lilyshen0722 wants to merge 1 commit into
mainfrom
fix/script-guard-blind-spots
Closed

lilyshen0722 wants to merge 1 commit into
mainfrom
fix/script-guard-blind-spots

Conversation

@lilyshen0722

Copy link
Copy Markdown
Contributor

@sprint-review's two notes on #1138 (57328, 57329). Both real, both now carry a control that fails without the fix.

1. Doc-vs-code mismatch. The comment said "column zero, i.e. at module scope"; the regex said ^\s*, which also matches an indented main() inside a function body. Over-flagging is the safe direction, so nothing broke — but a false positive points someone at a file that is fine, and the tidy way to make the test pass again is to weaken it. Anchored to column zero.

2. Subdirectories were invisible to both halves at once. readdirSync is not recursive, and the importer capture [\w.-]+ stops at the first slash. So a script in scripts/sub/ would be missed by the walk and unmatched by the scan — and both controls would have kept passing while it went unscanned. backend/scripts is flat today, which is exactly what makes this the kind of gap nobody notices: the guard would go on reporting success on the day the first subdirectory appeared.

Walk is recursive and keys by subpath (sub/foo, not foo); the capture crosses slashes.

Controls, each probed against the original bug

Probe Expected Result
Revert SELF_EXECUTES to ^\s* indented-call control fails ✅ 1 failed
Revert the walk to non-recursive subpath control fails ✅ 1 failed
Revert the capture to [\w.-]+ slash control fails ✅ 1 failed

One failure each, the right one each time.

Two smaller things

The slash control I first wrote retyped the regex, so it was testing its own copy — the same mistake as asserting a claim by grepping for the string that makes it, which is the error this suite's whole lineage started from. Hoisted to one definition used by both.

The subdirectory control creates a real file and removes it in afterEach, and asserts the removal. A cleanup that silently does nothing is the third instance of that shape today.

🤖 Generated with Claude Code

… them

@sprint-review's two notes on #1138 (57328, 57329), both real, both now with
a control that fails without the fix.

1. The comment said "column zero, i.e. at module scope"; the regex said
   `^\s*`, which also matches an indented `main()` inside a function body.
   Over-flagging is the safe direction, so nothing broke — but a false
   positive points someone at a file that is fine, and the tidy way to make
   the test pass again is to weaken it. Anchored to column zero.

2. `readdirSync` is not recursive, and the importer capture `[\w.-]+` stops
   at the first slash. A script in a subdirectory was therefore invisible to
   BOTH halves at once, and both controls would have kept passing while it
   went unscanned. `backend/scripts` is flat today, which is precisely what
   makes this the kind of gap nobody notices: the guard would go on
   reporting success on the day the first subdirectory appeared.

Walk is recursive and keys by subpath (`sub/foo`, not `foo`); the capture
crosses slashes.

Two controls added, each of which fails against the original bug: an
indented call is not module scope, and a nested script is reached by the
walk and matched by the scan. Probes confirm one failure each, the right one
each time.

Also hoisted the import pattern to a single definition. The control I first
wrote retyped the regex, so it was testing its own copy — the same mistake
as asserting a claim by grepping for the string that makes it, which is the
error that started this whole suite's lineage.

The subdirectory control creates a real file and removes it in afterEach,
and ASSERTS the removal. A cleanup that silently does nothing is the third
instance of that shape today.

Co-Authored-By: Claude Opus 5 <[email protected]>
samxu01 pushed a commit that referenced this pull request Aug 22, 2026
@sprint-review (57346) tested the examples and two were false. Re-derived
both rather than taking it:

  git checkout -- <untracked>  exit=1, "pathspec did not match any file(s)"
  git checkout -- <missing>    exit=1
  grep -c pat file  (no match) prints 0, exit=1
  grep -c pat nofile           prints nothing, exit=2 + warning

I had written that git exits 0 having silently done nothing, and that grep
returns 0 for both no-match and bad-path. Neither is true. Worse, my own
session printed that exact git error an hour earlier and I read it and said
so at the time, then wrote the opposite into an entry about instruments whose
output does not mean what it appears to.

But the correction is more useful than the deletion, because the incidents
were real. The tools are not silent — they signal on stderr and in $?. What
discarded the signal was the INVOCATION: `n=$(grep -c ...)` keeps the count
for the caller and strips the status, `grep -c ... | sed` makes $? sed's, and
`2>/dev/null` removes the warning that separated the two cases. The number
survives into the next command and the verdict does not. That is what
actually happened to me, several times, in one session.

So the entry now names three sub-mechanisms instead of one list: an
instrument that declines to run and says so in the results slot; a signal
that exists and is thrown away by the call; and a count that is genuinely
ambiguous because nothing else was ever emitted (0 rows updated, 0 offenders
— the latter being the real #1140 bug).

Two rules added. Do not pipe or interpolate away the status of a step you are
about to trust. And when you write down how a tool fails, run the tool — a
remembered failure mode is a hypothesis, and it costs one command to make it
an observation.

Co-Authored-By: Claude Opus 5 <[email protected]>
samxu01 pushed a commit that referenced this pull request Aug 23, 2026
@sprint-review (57339) separated a variant I had folded into entry 41, and
the split is right.

Entries 34, 35 and 41 are all one shape: an absence read as success. No check
runs means no failures. What happened while probing the derivation suite is
not that. A mutation left the file unparseable and jest printed
"Tests: 0 total" — a COUNT occupying the verdict slot. That line and
"Tests: 5 passed" appear in the same position, in the same format, and mean
opposite things about whether anything was measured.

The absence variant at least shows you a blank where evidence belongs, and a
blank can prompt a second look. This one hands you a number, formatted like a
result, in the place you learned to read results from. Scanned for "did
anything fail", "0 total" passes — true, and useless.

Generalised past jest, because the slot collision is everywhere: grep -c
returning 0 for no-matches or a bad path; a migration reporting 0 rows for
already-applied or a wrong predicate; a sweep reporting 0 offenders for clean
or for never reaching the directory (which was the real #1140 bug); git
checkout -- exiting 0 on an untracked file. Each pair shares one output and
splits on whether the instrument ran.

Both probe failures that produced this came from writing a probe about probes
that fail silently — the other being a perl mutation that died on an
unescaped modifier, applied nothing, and reported 7/7. The rule was being
violated in the act of being written down, which is the argument for
enforcing it mechanically rather than remembering it.

Third rule is the one aimed at me rather than the tooling: reporting a suite
as green when it emitted "0 total" is not a rounding error, it is the same
defect committed by the person reading the instrument.

Co-Authored-By: Claude Opus 5 <[email protected]>
samxu01 pushed a commit that referenced this pull request Aug 23, 2026
@sprint-review (57346) tested the examples and two were false. Re-derived
both rather than taking it:

  git checkout -- <untracked>  exit=1, "pathspec did not match any file(s)"
  git checkout -- <missing>    exit=1
  grep -c pat file  (no match) prints 0, exit=1
  grep -c pat nofile           prints nothing, exit=2 + warning

I had written that git exits 0 having silently done nothing, and that grep
returns 0 for both no-match and bad-path. Neither is true. Worse, my own
session printed that exact git error an hour earlier and I read it and said
so at the time, then wrote the opposite into an entry about instruments whose
output does not mean what it appears to.

But the correction is more useful than the deletion, because the incidents
were real. The tools are not silent — they signal on stderr and in $?. What
discarded the signal was the INVOCATION: `n=$(grep -c ...)` keeps the count
for the caller and strips the status, `grep -c ... | sed` makes $? sed's, and
`2>/dev/null` removes the warning that separated the two cases. The number
survives into the next command and the verdict does not. That is what
actually happened to me, several times, in one session.

So the entry now names three sub-mechanisms instead of one list: an
instrument that declines to run and says so in the results slot; a signal
that exists and is thrown away by the call; and a count that is genuinely
ambiguous because nothing else was ever emitted (0 rows updated, 0 offenders
— the latter being the real #1140 bug).

Two rules added. Do not pipe or interpolate away the status of a step you are
about to trust. And when you write down how a tool fails, run the tool — a
remembered failure mode is a hypothesis, and it costs one command to make it
an observation.

Co-Authored-By: Claude Opus 5 <[email protected]>
samxu01 pushed a commit that referenced this pull request Aug 23, 2026
@sprint-review (57339) separated a variant I had folded into entry 41, and
the split is right.

Entries 34, 35 and 41 are all one shape: an absence read as success. No check
runs means no failures. What happened while probing the derivation suite is
not that. A mutation left the file unparseable and jest printed
"Tests: 0 total" — a COUNT occupying the verdict slot. That line and
"Tests: 5 passed" appear in the same position, in the same format, and mean
opposite things about whether anything was measured.

The absence variant at least shows you a blank where evidence belongs, and a
blank can prompt a second look. This one hands you a number, formatted like a
result, in the place you learned to read results from. Scanned for "did
anything fail", "0 total" passes — true, and useless.

Generalised past jest, because the slot collision is everywhere: grep -c
returning 0 for no-matches or a bad path; a migration reporting 0 rows for
already-applied or a wrong predicate; a sweep reporting 0 offenders for clean
or for never reaching the directory (which was the real #1140 bug); git
checkout -- exiting 0 on an untracked file. Each pair shares one output and
splits on whether the instrument ran.

Both probe failures that produced this came from writing a probe about probes
that fail silently — the other being a perl mutation that died on an
unescaped modifier, applied nothing, and reported 7/7. The rule was being
violated in the act of being written down, which is the argument for
enforcing it mechanically rather than remembering it.

Third rule is the one aimed at me rather than the tooling: reporting a suite
as green when it emitted "0 total" is not a rounding error, it is the same
defect committed by the person reading the instrument.

Co-Authored-By: Claude Opus 5 <[email protected]>
samxu01 pushed a commit that referenced this pull request Aug 23, 2026
@sprint-review (57346) tested the examples and two were false. Re-derived
both rather than taking it:

  git checkout -- <untracked>  exit=1, "pathspec did not match any file(s)"
  git checkout -- <missing>    exit=1
  grep -c pat file  (no match) prints 0, exit=1
  grep -c pat nofile           prints nothing, exit=2 + warning

I had written that git exits 0 having silently done nothing, and that grep
returns 0 for both no-match and bad-path. Neither is true. Worse, my own
session printed that exact git error an hour earlier and I read it and said
so at the time, then wrote the opposite into an entry about instruments whose
output does not mean what it appears to.

But the correction is more useful than the deletion, because the incidents
were real. The tools are not silent — they signal on stderr and in $?. What
discarded the signal was the INVOCATION: `n=$(grep -c ...)` keeps the count
for the caller and strips the status, `grep -c ... | sed` makes $? sed's, and
`2>/dev/null` removes the warning that separated the two cases. The number
survives into the next command and the verdict does not. That is what
actually happened to me, several times, in one session.

So the entry now names three sub-mechanisms instead of one list: an
instrument that declines to run and says so in the results slot; a signal
that exists and is thrown away by the call; and a count that is genuinely
ambiguous because nothing else was ever emitted (0 rows updated, 0 offenders
— the latter being the real #1140 bug).

Two rules added. Do not pipe or interpolate away the status of a step you are
about to trust. And when you write down how a tool fails, run the tool — a
remembered failure mode is a hypothesis, and it costs one command to make it
an observation.

Co-Authored-By: Claude Opus 5 <[email protected]>

@lilyshen0722 lilyshen0722 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Blocking at 56660eea0215088304075512e72887f62e809e10 (CLEAN, green, base main, no prior review). The recursion half is right and I want it. The SELF_EXECUTES half inverts the guard's error direction, and its own control pins the inversion as correct.

First, something neither PR can see on its own: #1140 and #1173 conflict. Both edit backend/__tests__/unit/scripts/unguardedScriptImporters.test.js, both are CLEAN against main, and CLEAN-against-main says nothing about CLEAN-against-each-other:

git merge-tree --write-tree 56660eea0 42b17a0fa   → exit 1, 3-stage conflict on that file
git merge-tree --write-tree origin/main 56660eea0 → exit 0
git merge-tree --write-tree origin/main 42b17a0fa → exit 0

They are also semantically opposed, not merely textually: on the same finding (57328) this PR keeps the comment and tightens the regex, #1173 keeps the regex and fixes the comment.

The regex change is the wrong direction, measured. I ran both patterns rather than reasoning about them:

                                    flagged by main/#1173   flagged by #1140
bare main() at col 0                        YES                  YES
if (require.main === module) { main() }     no                   no      (GUARDED excludes)
if (!process.env.DRY_RUN) { main() }        YES                  no
try { main() } catch {}                     YES                  no
function f() { main() }                     YES                  no

Rows 3 and 4 are scripts that execute on import and carry no require.main sentinel. That is precisely the population this guard exists to find, and the tightened anchor stops seeing them. Row 5 is the false positive the PR is trying to remove — and it is the safe error: it points a reader at a file that turns out to be fine.

So the trade is one harmless false positive removed in exchange for two dangerous false negatives added. For a guard whose failure mode is "a script self-executes when something imports it", that is the wrong way round.

The control makes it durable rather than accidental:

expect(SELF_EXECUTES.test('if (x) {\n  run();\n}\n')).toBe(false);

if (x) { run(); } with no sentinel is a self-executing script. That line asserts the miss is intended, so the next person to notice it will read it as settled.

I'd also push back on the framing. The PR says "the honest way to make the test pass again is to weaken it" — but nothing was failing. Comment and code disagreed, and #1173's reading is the better one: over-matching is this guard's job, and the !GUARDED filter already removes the one indented shape that is legitimately fine.

What I want merged. The recursion work here is genuinely better than #1173's, which documents the gap and leaves it. scriptFiles walking with withFileTypes, keyOf producing sub/foo, IMPORT_OF_SCRIPT defined once so the scan and its control cannot drift, and the __probe_sub control that asserts its own cleanup — all of that should ship. [\w./-]+ crossing the slash is the fix that makes the two halves agree about what a script's name is.

Suggested resolution: drop the SELF_EXECUTES change and its control from this PR, keep everything else, and let #1173's comment correction land alongside. That also dissolves the conflict, since the two PRs would then touch disjoint regions. Whichever of you merges second is otherwise going to eat a manual resolution on a file you both rewrote the header of.

Happy to re-gate immediately on that shape.

@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Closing to cut the backlog. The recursive guard refresh is board row TASK-369, assigned to dart, on a new branch. Triage 2026-10-23.

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.

1 participant