Skip to content

fix(engine): count fnmatch label-pattern wildcard groups per raw star, not by path-glob rules - #10128

Merged
loopover-orb[bot] merged 1 commit into
JSONbored:mainfrom
shin-core:fix/label-match-fnmatch-wildcard-count-9994-v2
Jul 31, 2026
Merged

fix(engine): count fnmatch label-pattern wildcard groups per raw star, not by path-glob rules#10128
loopover-orb[bot] merged 1 commit into
JSONbored:mainfrom
shin-core:fix/label-match-fnmatch-wildcard-count-9994-v2

Conversation

@shin-core

Copy link
Copy Markdown
Contributor

What & why

labelPatternToRegExp (packages/loopover-engine/src/scoring/label-match.ts) guards against catastrophic backtracking by counting wildcard groups before compiling a label pattern to a RegExp — reusing change-guardrail.ts's hasUnsafeWildcardCount. But that predicate is the path-glob counter, which deliberately treats a ** pair as one group because the path compiler collapses ** into a single .*.

The fnmatch compiler here has no ** concept — it emits one .* per *. So the count and the compiled regex disagreed for any ** pattern:

pattern path-glob count actual .* groups compiled old result
*a**b 2 3 accepted
**/** 2 4 accepted
a**b**c 2 4 accepted

The cap's own benchmark puts 3 groups at "over 2 seconds at ~4,000 chars" and 4 at "35 seconds at 1,614 chars", so these accepted patterns are exactly the ones that risk a catastrophic-backtracking RegExp.test() on an adversarial near-miss label. labelMatchesPattern's left-hand input is caller-supplied (ScorePreviewInput.labels) and the right-hand patterns are registry labelMultipliers keys the module itself documents as untrusted.

The fix

Count the groups the fnmatch compiler actually emits — one per raw *, with no ** pairing (? compiles to a single . and […] classes are not counted, neither can backtrack ambiguously) — and compare against MAX_GLOB_WILDCARD_GROUPS, now exported from change-guardrail.ts so the two surfaces share one empirically-safe threshold rather than redeclaring it (the exact drift the existing hasUnsafeWildcardCount export comment warns about).

An over-complex pattern degrades to the existing LABEL_PATTERN_NEVER_MATCHES and is still cached, exactly as today — the fail-safe direction here is "no multiplier applies".

Unchanged: hasUnsafeWildcardCount, countWildcardGroups, globToRegExp, matchesAny and every path-glob consumer keep their **-is-one-group semantics byte-identically (correct for the path compiler — rejecting public/**/*.json there would break the content lane). Every ≤2-group label pattern (type:*, kind/*, priority:?, a*b*c, [bc]ug), the [seq]/[!seq]/invalid-range handling, and the LRU cache behaviour are all preserved.

Tests

  • Engine (packages/loopover-engine/test/label-match.test.ts, new — node:test per the content-lane-flag.test.ts convention): *a**b and **/** are rejected (never match); the ≤2-group and non-* cases still match; a rejected pattern is still cached (repeated read served from the cache).
  • Root (test/unit/scoring.test.ts): the same rejection + preserved cases through labelMatchesPattern/labelMultiplierFor. One existing assertion is updated — public/**/*.json (3 compiled groups) is now correctly rejected as a label pattern (it was the path-glob-count's false accept); the comment now states the fnmatch counting rule.
  • All new assertions fail on main and pass with the fix.

Validation

  • Diff coverage on both packages/loopover-engine/src/scoring/label-match.ts and .../signals/change-guardrail.ts is 100% line and branch (engine lines credited via the root-vitest upload; the added test is also in packages/loopover-engine/test/** for the dual-upload union).
  • npm run typecheck clean for these files; npm run engine-parity:drift-check passes; the engine's own node --test suite is green; npm run dead-exports:check clean.
  • git diff --check clean; no schema/migration/generated-artifact change.

Closes #9994

…, not by path-glob rules

labelPatternToRegExp reused change-guardrail's path-glob wildcard-group counter
to guard against catastrophic backtracking, but that counter treats a ** pair as
ONE group (the path compiler collapses ** into a single .*). The fnmatch compiler
here has no ** concept and emits one .* per *, so the count and the compiled regex
disagreed for any ** pattern: *a**b counted 2 but compiled 3 .* groups and was
wrongly accepted, admitting a pattern this compiler builds into a catastrophic-
backtracking RegExp on an adversarial near-miss label.

Count one group per raw * (no ** pairing; ? and [..] are not counted) and compare
against the shared MAX_GLOB_WILDCARD_GROUPS, now exported from change-guardrail
rather than redeclared. An over-complex registry key degrades to the existing
LABEL_PATTERN_NEVER_MATCHES and is still cached. The path-glob counter and every
path consumer keep their **-is-one-group semantics unchanged.

Closes JSONbored#9994
@shin-core
shin-core requested a review from JSONbored as a code owner July 31, 2026 08:14
@loopover-orb

loopover-orb Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

Tip

✅ LoopOver review result - approve/merge recommended

Review updated: 2026-07-31 08:41:06 UTC

4 files · 1 AI reviewer · no blockers · readiness 98/100 · CI green · clean

✅ Suggested Action - Approve/Merge

  • safe to merge

Review summary
This fixes a real correctness bug: label-match.ts was reusing change-guardrail's path-glob wildcard counter, which treats `**` as one group, to guard an fnmatch compiler that emits one `.*` per raw `*` with no globstar collapsing — so `**`-containing patterns like `public/**/*.json` (3 real `.*` groups) were being accepted when they should have been rejected under the shared ReDoS cap. The new `fnmatchWildcardGroups` correctly counts one per raw `*`, `MAX_GLOB_WILDCARD_GROUPS` is now exported and shared rather than redeclared, and the test in test/unit/scoring.test.ts correctly flips the `public/**/*.json` expectation from `1.2` to `1` (previously-accepted glob is now safely rejected). The change is narrowly scoped to the guard/count logic, preserves the existing cache-then-reject flow, and is well-covered by both the new label-match.test.ts and updated scoring.test.ts assertions.

Nits — 5 non-blocking
  • The fix does not update the stale comment at the top of label-match.ts (lines ~40-44, unchanged in this diff) that says '`**/` counts as one wildcard group' — worth double-checking no other comment in the file still implies the old path-glob semantics.
  • packages/loopover-engine/src/scoring/label-match.ts: the literal issue number `engine(scoring): count fnmatch wildcard groups the way labelPatternToRegExp compiles them, not the way path globs do #9994` appears repeatedly in comments; consider a shared reference constant or single canonical comment rather than repeating it four times.
  • test/unit/scoring.test.ts's `public/**/*.json` example is a real registry-config shape mentioned in change-guardrail.ts's own comment as 'a real 2-group glob that must stay accepted there' — worth a one-line note that this is intentionally a *different* compiler with different group semantics, to preempt future confusion when someone edits both files.
  • Consider whether `fnmatchWildcardGroups` and `countWildcardGroups` (change-guardrail.ts) could share a common 'count raw stars' helper with a compiler-specific `**`-collapsing flag, since the two are now conceptually siblings differing only in globstar handling.
  • The PR description says the issue is engine(scoring): count fnmatch wildcard groups the way labelPatternToRegExp compiles them, not the way path globs do #9994 but the external brief notes only 'partial' coverage of that issue — worth confirming the linked issue's full scope is addressed, not just the `label-match.ts` half.

Decision drivers

  • ✅ Code review — No blockers (1 reviewer)
  • ✅ Gate result — Passing (No configured blocker found.)
Context & advisory signals — never blocks the verdict
Signal Result Evidence
Linked issue ✅ Linked #9994
Related work ✅ No active overlap found No same-issue or scoped active PR overlap found.
Change scope ✅ 20/20 Low review scope from cached public metadata (1 linked issue).
Validation posture ✅ 25/25 PR body includes validation/test evidence.
Contributor workload ✅ 10/10 Author activity: 65 registered-repo PR(s), 50 merged, 0 issue(s).
Contributor context ✅ Confirmed Gittensor contributor shin-core; Gittensor profile; 65 PR(s), 0 issue(s).
Improvement ✅ Minor risk: clean · value: minor · LLM: significant
Linked issue satisfaction

Addressed
The diff replaces the reused path-glob predicate with a new fnmatch-specific counter (one group per raw `*`, no `**` pairing) compared against the exported shared MAX_GLOB_WILDCARD_GROUPS constant, matching the required guard shape and fail-safe/caching behavior, and adds tests confirming `**`-containing patterns like `*a**b` and `public/**/*.json` are now rejected while 2-group and non-`*` patter

Review context
  • Author: shin-core
  • Role context: outside_contributor
  • Public audience mode: oss maintainer
  • Lane context: Repository is configured for direct PR review.
  • Public profile languages: TypeScript, JavaScript, Solidity, Dart, Python, CSS, PHP, Rust
  • Official Gittensor activity: 65 PR(s), 0 issue(s).
  • PR-specific overlap: none found.
Contributor next steps
  • Keep the PR focused and include validation evidence before maintainer review.
Signal definitions
  • Related work = same linked issue, overlapping active PRs, or title/path similarity.
  • Change scope = cached public metadata such as size labels, draft state, and review-burden hints.
  • Validation posture = whether the PR provides enough public validation/test evidence for maintainer review.
  • Contributor workload = public contributor activity and cleanup pressure, not a repo-wide quality failure.
  • Contributor context = public GitHub/Gittensor identity context; non-Gittensor status is not a blocker.
🧪 Chat with LoopOver

Ask LoopOver a question about this PR directly in a comment — grounded only in the same cached, public-safe facts shown above, never a new claim.

  • @loopover ask <question> answers contribution-quality Q&A with source citations and freshness.
  • @loopover chat <question> answers in natural prose from cached decision-pack facts via local inference (maintainer/collaborator; read-only).
  • A plain-language @loopover mention with a real question is routed to the closest matching read-only command automatically — no exact syntax required.

Full command reference: https://loopover.ai/docs/loopover-commands

🧪 Experimental — new and may change.

🟩 Safe / merged · 🟦 Advisory · 🟨 Held for review · 🟥 Blocked / closed


💰 Earn for open-source contributions like this. Gittensor lets GitHub contributors earn for the work they already do — register to start earning →.

Checked by LoopOver, a quiet PR intelligence layer for OSS maintainers.

  • Re-run LoopOver review

@superagent-security

Copy link
Copy Markdown
Contributor

Superagent didn't find any vulnerabilities or security issues in this PR.

@loopover-orb loopover-orb Bot added the gittensor:bug Gittensor-scored bug fix — scores a 0.05x multiplier. label Jul 31, 2026
@codecov

codecov Bot commented Jul 31, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.98%. Comparing base (3d7fdbf) to head (0a33f98).
⚠️ Report is 9 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #10128      +/-   ##
==========================================
+ Coverage   91.95%   91.98%   +0.02%     
==========================================
  Files         931      931              
  Lines      113937   113955      +18     
  Branches    27505    27512       +7     
==========================================
+ Hits       104774   104823      +49     
+ Misses       7863     7828      -35     
- Partials     1300     1304       +4     
Flag Coverage Δ
backend 95.66% <100.00%> (-0.01%) ⬇️
engine 72.93% <100.00%> (+0.20%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...ackages/loopover-engine/src/scoring/label-match.ts 92.81% <100.00%> (+23.73%) ⬆️
...es/loopover-engine/src/signals/change-guardrail.ts 97.40% <100.00%> (+0.03%) ⬆️

... and 1 file with indirect coverage changes

@loopover-orb loopover-orb Bot 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.

LoopOver approves — the gate is satisfied and CI is green.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gittensor:bug Gittensor-scored bug fix — scores a 0.05x multiplier.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

engine(scoring): count fnmatch wildcard groups the way labelPatternToRegExp compiles them, not the way path globs do

1 participant