Repository navigation
fix(static_yara): surface dropped rule files instead of reporting completed - #557
Conversation
…pleted A rule file passed through --yara-rules-dir that YARA cannot compile, or that SkillSpector cannot decode as UTF-8/base64, is dropped whole with no signal above debug-level logging. _load_rules already counted these (materialize_skipped + compile_skipped) but only logged the total; node() never saw it, so every scanned component could still report COMPLETED and the recommendation stayed SAFE, because the rule that would have flagged something simply never ran. --fail-on-incomplete correctly has nothing to key off, so it exits 0. Kept _load_rules's existing single-value signature: every current monkeypatch.setattr(static_yara, "_load_rules", ...) test double in the suite returns a bare yara.Rules object, and changing the return shape to a tuple would have broken all 15 of them for an internal detail those tests don't exercise. The skip count is instead recorded on the same module-level cache the compiled rules already live on, read back via the new rules_skipped_count(), and folded into a PARTIAL ledger event scoped to the rule set (not a scanned skill file, hence the synthetic "yara_rules/" path and LedgerRecordType.SYSTEM) using the existing READ_ERROR reason. That event flows through node()'s existing degraded/completed decision unchanged, so --fail-on-incomplete now has something real to key off. Test builds a valid rule and a syntactically broken one in the same --yara-rules-dir (a real YARA syntax error, not a decode failure, to match the issue's own repro), asserts the valid rule still fires, the analyzer status is not "completed", and the ledger records the drop. Negative control: reverting only the source fails with status == "completed" — the exact false-SAFE the issue reports. Fixes NVIDIA#554 Signed-off-by: Souptik Chakraborty <62941615+Souptik96@users.noreply.github.com>
rng1995
left a comment
There was a problem hiding this comment.
[SkillSpector Review]
Reviewed current head 4e753fe71cae2a3ecfe7df258c760115a1ed3f6c, including the complete two-file diff, surrounding rule-cache and analyzer-status logic, tests, existing discussion, and exact-head checks. The mixed valid/invalid-rule case is now surfaced in the ledger, and all five hosted checks pass.
Changes are requested because the skipped-rule count is stored in a module global and read separately after _load_rules returns. Concurrent scans with different rule directories can interleave those operations, so one scan can consume another rule set's count and still report completed after its own rule was dropped. Bind the skip metadata atomically to the returned/cached compiled rule set (or protect the load-and-read operation with appropriate synchronization) and add a deterministic concurrency regression.
yashrajp22
left a comment
There was a problem hiding this comment.
The review of head 4e753fe71cae2a3ecfe7df258c760115a1ed3f6c is complete. Two additional fixes are needed: the synthetic rule-load event can collide with a real file, and rejected rules still lack the default-level diagnostics requested in #554. The existing skip-count concurrency finding also remains reproducible; I have not duplicated that comment.
The ordinary mixed valid/invalid-rule case now correctly produces a nonfatal partial report, strict CLI exit 1, and safe_to_install=false through programmatic MCP.
Validation used fresh wheels and pinned source for base c13f70ebf14905912c616a58c9a8cb8112ef94a4 and this head. All 12 complete sample directories ran in all four combinations (48 scans), with matching source/wheel reports. The 98 selected tests passed in each HEAD mode. Focused checks covered malformed syntax/encoding/BOM, cache transitions, concurrency, ledger identity, CLI/MCP, suppression and all report formats, resource/failure precedence, and recursive/transitive aggregation. Greptile's cache-metadata observation was independently reproduced and grouped with the existing shared-metadata finding.
Scope: Linux and offline checks; transitive remote targets were mapped to local fixtures. Nine sample reports remain partial for unrelated reference/obfuscation limitations, so this is not an all-rule accuracy or live-provider result. The PR contribution is based on 2e9ae8d1cfa6e339f7035f876d3ac2e1c6ce24e6; unrelated AS3 differences from newer main were kept separate.
…iles Addresses the three review findings on NVIDIA#557. All three share one shape: the dropped-rule total was reported through a channel not tied to the scan that produced it. 1. Skip count raced across concurrent scans (rng1995, P1) `node()` called `_load_rules()` and then read `rules_skipped_count()` as a separate step. Two concurrent MCP/graph scans can interleave between those: scan B loads its own rule set and overwrites `_rules_skipped_count` before scan A reads it, so A runs rules A while reporting B's total. If B skipped nothing, A reports `completed` even though one of A's own rules was dropped -- the false-clean result NVIDIA#554 exists to prevent. Adds `load_rules_with_skips()`, which returns the rules and their own skip count from one transaction guarded by a reentrant `_RULES_LOCK`, and switches `node()` to it. `_load_rules()` keeps its single-value signature, and `load_rules_with_skips` calls it through the module global, so every existing `monkeypatch.setattr(static_yara, "_load_rules", ...)` double still applies. `rules_skipped_count()` is retained for single-threaded callers and now reads under the lock. The three cache globals are documented as one logical value that must only be written or read as a set. The lock serializes rule compilation across concurrent scans. That is a deliberate trade: compilation is cached and already deadline-bounded, and a scanner reporting a false clean is worse than one loading rules serially. 2. Rule-load event collided with a component of the same name (yashrajp22) `ledger_event` derives the work identity as `analyzer_id or f"{record_type}:{phase}"`, and the synthetic `yara_rules/` scope normalizes to `yara_rules`. Passing `analyzer_id=ANALYZER_ID` therefore produced the same work ID as the planned work item for a scanned component literally named `yara_rules`: both planned targets resolved to two matching events, and reconciliation raised a fatal `unaccounted_work` with `execution_successful=false` and CLI exit 2, instead of the nonfatal partial scan this event is meant to record. Omits `analyzer_id` on that one event so the identity falls back to `system:static`, which is disjoint from every analyzer work item by construction. As the review noted, renaming the synthetic path alone would only move the collision to the next unlucky filename. 3. Rejected rules were invisible at default log level (yashrajp22, NVIDIA#554) Both rejection handlers logged at DEBUG, so a malformed `acme.yar`, a BOM rule, or a non-UTF-8 `.yar` produced no default-level warning, and the public ledger event is scoped to the rule set rather than the file. The operator could see that a detector was dropped but not which one to repair. Both handlers now log at WARNING, naming the file and a bounded reason. `_build_namespace_map` optionally fills a `{namespace: filename}` map -- passed in rather than returned, to keep its two-value signature -- so the compile path can name `acme.yar` instead of the extension-stripped namespace `acme`. `_bounded_rejection_reason` collapses newlines and caps the echoed text at 200 characters, because rule sources are attacker-influenced when `--yara-rules-dir` points at untrusted content and YARA errors can quote the offending source line. Tests New `TestRuleSkipAccounting` (9 tests): a deterministic pairing test, a serialization test that asserts the lock is genuinely held for the whole load-and-read transaction rather than racing and hoping, a contended two-thread test over 50 observations, the `yara_rules` work-ID collision case asserting both event and planned-work IDs stay distinct, three parametrized rejection-diagnostic cases (malformed, BOM, non-UTF-8), and two bounding tests. The contended test surfaces worker-thread exceptions and asserts an observation count, so it cannot pass vacuously when the scans never ran. The autouse cache fixture now also resets `_rules_skipped_count`, which is part of that cache and would otherwise leak between tests. Verification - Negative control: all 9 new tests fail with the source change reverted and the tests kept; 9/9 pass with it. - `tests/nodes/analyzers/test_static_yara.py`: 96 passed. - Full suite: 18 pre-existing failures, byte-identical to the same run on unmodified `4e753fe` (build_context, compare_scan_accuracy, create_github_release, input_handler, json_container_ownership, security_end_to_end -- all environmental, none in the touched files). - `ruff check`, `ruff format --check`, and `mypy` clean on both files. - Windows / Python 3.13 only; the pre-existing failures above are consistent with that environment rather than with this change. Signed-off-by: Souptik Chakraborty <62941615+Souptik96@users.noreply.github.com>
|
Thanks both — the reviews were specific enough to fix directly, and @rng1995's point about the two globals was the one I should have caught myself. All three turned out to be the same shape: the dropped-rule total was reported through a channel that wasn't tied to the scan that produced it — a module global read after the fact, a ledger work ID shared with component work, and a DEBUG log nobody sees at default verbosity. ① Skip count bound to its rules — @rng1995 [P1]
Done both. New
Confirmed the interleaving before fixing it — scan A drops one rule, scan B loads a clean set, A then reads B's count: For the regression you asked for, I did not want a test that passes on timing luck, so there are two. One trade to flag explicitly: the lock serializes rule compilation across concurrent scans. I judged that acceptable because compilation is cached and already deadline-bounded, and a scanner reporting a false clean is worse than one loading rules serially. If you would rather not serialize compilation, the alternative is caching ② Rule-load work ID can no longer collide — @yashrajp22
Agreed, and that last sentence is why I did not just rename the path. Reproduced your exact case first (a component named The regression asserts both the event IDs and the advertised ③ Rejected rules named at default level — @yashrajp22, #554
Both handlers now log at WARNING with the filename and a bounded reason. Your three cases: This needed one change beyond the log level, which is worth calling out: the compile path only had the namespace, and
Verification
One thing I found in my own tests rather than let it sit: the contended-threads test initially passed vacuously, because an exception inside a worker thread does not fail a pytest test. It now captures worker exceptions and asserts an observation count of 50, so it cannot pass when the scans never ran. Also extended the autouse cache fixture to reset Disclosure: written with AI assistance under my direction. I reproduced each finding before fixing it, ran the negative control and full-suite comparison myself, and reviewed this comment before posting. |
rng1995
left a comment
There was a problem hiding this comment.
[SkillSpector Review]
Re-reviewed current head 6e07493c9956dcf2ad7b2f032f58b125cc978fa9 against all three prior threads, the complete rule-cache/ledger/logging diff, concurrency tests, surrounding no-rules paths, and exact-head checks.
The lock now makes a successful load-and-count transaction atomic, and the work-ID collision plus default-level rejected-file reporting are addressed. One cache-integrity path remains. _load_rules() sets _rules_skipped_count and returns without replacing or clearing _compiled_rules / _rules_hash when no rule files exist or compilation yields no rules. A later request for the previously cached hash then returns those cached rules paired with the intervening load's count. For example, load A with one valid and one rejected rule, load an empty/all-rejected set B, then load A again: the A cache hit can report B's count (including zero), recreating a false-complete YARA scan. Keep rules, hash, and skip count as one immutable cache entry or invalidate the cached rules/hash on every non-populating path; add this A→B→A sequence as a regression.
All six exact-head checks pass, but this remaining completeness-accounting defect and active change requests block merging.
Priority: P0 — incorrect rule-drop accounting can make an incomplete malware scan look complete.
|
Thanks — you were right, and the A→B→A sequence you described reproduces exactly.
Confirmed on Fixed by taking both of the options you offered rather than one. The three globals Same script after the fix: Added the regression you asked for as Negative control: with the source fix reverted and the tests kept, all six fail. Three
Two trade-offs worth naming. First, clearing the entry means A is recompiled after an
|
_load_rules() set _rules_skipped_count and returned on both non-populating paths -- no rule files found, and compilation yielding nothing -- without replacing or clearing _compiled_rules / _rules_hash. The entry left behind still matched the earlier load's hash, so a later request for it hit the cache and paired those rules with the intervening load's count. Loading A (one valid rule, one rejected), then an empty or all-rejected B, then A again reported zero dropped rules for A, and node() went back to reporting a completed scan while one of A's own detectors had never run. Collapse the three globals into a frozen _RuleCacheEntry holding rules, hash and skip count, published only by replacing the entry wholesale, and clear that entry on every path that does not produce usable rules. A cache hit now takes its count from the entry, so the number cannot come from another load. _rules_skipped_count remains as the transaction-local channel _load_rules uses to publish the count to load_rules_with_skips, and is cleared at the start of the locked transaction so a load that raises cannot leave a previous total readable. _load_rules keeps its single-value signature, so existing monkeypatch.setattr(static_yara, "_load_rules", ...) doubles stay valid, and the reentrant-lock transaction is unchanged. Adds the A->B->A regression over both non-populating paths with asymmetric counts, cache-entry invalidation and immutability checks, and an end-to-end rescan test asserting the dropped rule is still surfaced. Signed-off-by: Souptik Chakraborty <62941615+Souptik96@users.noreply.github.com>
95572b6 to
6abb623
Compare
|
Force-pushed to add the missing DCO |
rng1995
left a comment
There was a problem hiding this comment.
[SkillSpector Review]
Re-reviewed current head 6abb623158ebbce9e92c60ecc51766975903f443 against all three inline threads and the subsequent cache-integrity change request.
The concurrency and A→B→A cache-count defects are fixed: the load/count transaction is locked, cache entries bind rules/hash/count, and non-populating loads invalidate the entry. Rejected-file WARNING diagnostics are also addressed. Distinct work IDs fix the original fatal ledger reconciliation failure.
One related path collision remains, described inline. A benign, fully read file named yara_rules, referenced from SKILL.md, is still mistaken for the synthetic rule-load scope during finalization. With one valid condition: false custom rule and one syntactically broken custom rule, the real CLI reports a false HIGH AE1, risk score 25, and 50% file coverage. Changing only the referenced filename to normal.txt produces no findings, score 0, and 100% file coverage. Both correctly remain nonfatal partial scans because a rule was rejected. Rule-load incompleteness must not invent a file-specific analysis-evasion finding based on the file's name.
Validation on the reviewed source, macOS/Python 3.12: 102 YARA tests and 185 related ledger/finalizer/deadline/budget/report tests passed; Ruff lint and formatting passed. CLI smoke confirmed ordinary exit 0 and --fail-on-incomplete exit 1, including a cache hit. All six hosted checks pass. The full local suite was not rerun.
Please distinguish rule-set scope from artifact paths throughout reference/coverage finalization and add an end-to-end regression for the referenced yara_rules case. Approval is withheld for this remaining report-integrity defect.
The rule-load event for dropped YARA rules is labelled with the path `yara_rules`. Finalization groups reference outcomes and per-component coverage by path, so a benign, fully read file of that name linked from SKILL.md was charged with the rule set's partial outcome: a false HIGH AE1, risk score 25 and 50% coverage. Renaming the file made it vanish. Every relative path is also a legal file name, so no label can be made collision-free. Give these rows their own LedgerRecordType.RULE_SET and exclude them by type, not by name: - _reference_coverage_findings() ignores rule-set rows when deciding whether a referenced artifact was incompletely inspected. - finalize_ledger() does not fold rule-set targets into per-component coverage. - The public exception row carries scope="rule_set", which is part of the merge key so it never merges with a real file's row, and SARIF gives it no physical location. The scan stays a nonfatal partial scan, and --fail-on-incomplete still exits 1, because a rule really was dropped. Signed-off-by: Souptik Chakraborty <62941615+Souptik96@users.noreply.github.com>
The Markdown and terminal completeness tables printed the rule-load exception under its path label `yara_rules`, exactly like a real file of that name, even though JSON carries scope="rule_set" and SARIF gives it no physical location. Prefix the location with "rule set" when the row is scoped to a rule set, so the two can be told apart in every format. Signed-off-by: Souptik Chakraborty <62941615+Souptik96@users.noreply.github.com>
|
Thanks, confirmed. I reproduced it through the real CLI on Fixed in 61e9821, plus a small follow-up in 4cdb77d for the Markdown and terminal reports (below). You were right that changing the label wouldn't fix it. Any relative path is also a valid file name, so no label can be guaranteed not to collide. The fix tells these rows apart by record type, not by name:
The work identity is now Same CLI repro after the fix: Both runs are still nonfatal partial scans, because a rule really was dropped. Regression tests:
Negative control (source reverted, tests kept): all 3 fail. Only Validation for 61e9821 (Windows, CPython 3.12.13): Markdown and terminal reports (4cdb77d). Those two tables still listed the row under the bare path |
rng1995
left a comment
There was a problem hiding this comment.
[SkillSpector Review]
Hi @Souptik96, thank you for closing the last report-integrity gap in the dropped-YARA-rule fix and for the before/after CLI tables that made it easy to verify!
Value and readiness: This head delivers #554. A rejected custom rule now makes the scan a nonfatal partial result (strict exit 1, MCP safe_to_install=false), and the rejected file is named at WARNING level. The rule-set row no longer affects path-keyed coverage or AE1. The fix itself is correct and every earlier finding is resolved. One required change remains: the rebase. It is not mechanical, because GitHub reports conflicts with main in _reference_coverage_findings, the function this fix changes, so the rebase has to carry the fix into main's rewritten version (details below). No CI has run on 4cdb77d4 yet. Once the rebased head is pushed and green, I expect to approve after a short re-check of the ported loop.
Previous findings:
- Skip count read from a separate global after
_load_rules(rng1995, P1): Resolved (unchanged since 6abb623).load_rules_with_skips(static_yara.py:558) holds_RULES_LOCKacross both the load and the count read. - A→B→A cache returned B's count for A's rules (rng1995): Resolved. Both non-populating paths clear the entry (
static_yara.py:522,:545). A cache hit readscached.skipped_count(:531). - Rule-load work ID collided with a component named
yara_rules(yashrajp22): Resolved. The event omitsanalyzer_id, so its identity isrule_set:static, which cannot match any analyzer work item. - Rejected rules only logged at DEBUG (yashrajp22): Resolved. Decode and compile rejections log at WARNING with the filename and a reason capped at 200 characters (
static_yara.py:420,:461). - Rule-set scope leaked into path-keyed accounting and produced a false HIGH AE1 (rng1995, P2): Resolved in 61e9821 and 4cdb77d:
- The event now uses
LedgerRecordType.RULE_SET(inspection_ledger.py:43). _reference_coverage_findingsskips RULE_SET rows (finalize_inspection_ledger.py:38).finalize_ledgerexcludes RULE_SET work IDs from per-component coverage (inspection_ledger.py:891-898).- The public row carries
scope: "rule_set", which is part of the merge key (:635), so it cannot merge with a real file's row. - The SARIF notification has no physical location (
report.py:734). - Markdown and terminal output label the row as "rule set".
- The end-to-end CliRunner regression runs once with the linked file named
yara_rulesand once withnormal.txt. Both runs must show no AE1, score 0, 100% coverage, exactly onerule_setrow, strict exit 1, and a SARIF notification with no location.
- The event now uses
Material findings
-
[Blocker: rebase]
src/skillspector/nodes/finalize_inspection_ledger.py:38:mainrewrote_reference_coverage_findings. It now buildsevents_by_path(onmain, around lines 534-548), and both_has_only_format_limitationsand the AE1 diagnostics read from it. When you rebase:- Put the
record_type == LedgerRecordType.RULE_SET→continuecheck at the top of that loop, next to the existing reference-caveat skip. Taking either side of the conflict as-is would drop the fix or dropmain's PNG handling. - In
report.py, keep bothfinalize_ledgerandRULE_SET_SCOPEin the import. - In
tests/nodes/test_finalize_inspection_ledger.py, keep bothmain's format-only PNG tests andtest_rule_set_row_is_excluded_from_path_keyed_accounting_by_type.
I checked
main's other new consumers, and none needs a further change:_status_paths_with_incomplete_evidence: static_yara still reportsdegradedwith no reason code, so no paths become invalid.- The fatal-row dedupe for failed inventory items in
finalize_ledger: the rule-set row is nonfatal. _ledger_event_is_canonical: the path normalizes toyara_rulesand the work ID recomputes fromrule_set:static.
- Put the
-
[Non-blocking]
docs/scan-completeness.md:130lists the public exception fields but not the newscopefield. Consider one sentence saying thatscope: "rule_set"(JSONledger_exceptions[], SARIFproperties.scope) marks a row whosepathlabels an analyzer's rule set rather than a skill artifact. Consumers should not join it to file paths.
PIC tradeoffs: The PR adds a public, optional scope field to ledger exception rows and a new internal record type. The change is additive, and I found no strict schema that rejects it. Consumers that group exceptions by path alone would still need to check scope.
Verification and gaps:
- I read the full seven-file diff and the 6abb623..4cdb77d delta.
- I traced the RULE_SET row through ledger creation,
finalize_ledger, AE1 generation, exception merging, SARIF, Markdown, terminal output, and transitive re-pathing incli._source_aware_ledger(record type andrule_set:staticidentity are preserved). - I ran
git merge-treeagainst currentmain(2226747e) to confirm the three conflicting files, and checkedmain's new finalizer logic for interactions. - The tests and the CLI repro were not executed locally, per policy.
- No CI has run on this head because of the conflict. The previous head 6abb623 had all six checks green.
- Merge needs a rebase, six green checks on the rebased head, and a re-check of the ported loop. @yashrajp22's earlier change request (two findings, both resolved in 6e07493) is still recorded and should be re-reviewed or dismissed.
Decision: Changes Requested (reviewed head 4cdb77d4cff86e80c4f31b08185d861c3ec4922e)
Resolve conflicts with main's rewritten AE1 reference coverage: - finalize_inspection_ledger: keep main's events_by_path loop and skip RULE_SET rows at its top, next to the reference-caveat skip, so a rule-set label still never feeds path-keyed AE1 or format-limit checks. - report: import RULE_SET_SCOPE alongside main's finalize_ledger and sanitize_llm_provenance. - tests: keep main's new finalizer and report tests and add this PR's rule-set tests unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Narendran Raghavan <nraghavan@nvidia.com>
|
[SkillSpector Review] Hi @Souptik96, a quick heads-up so nothing gets lost: to unblock this PR, a maintainer merged current What the merge does:
The source change against |
rng1995
left a comment
There was a problem hiding this comment.
[SkillSpector Review]
Hi @Souptik96, thank you for your patience while this was brought up to date with main!
Value and readiness: The only blocker from my 2026-10-02 review was the rebase onto main's rewritten _reference_coverage_findings. That is now done in merge commit e8c505c (a maintainer merge of main, no force-push), and all six CI checks pass on it. The fix for #554 is unchanged: a rejected custom rule makes the scan a nonfatal partial result, the rejected file is named at WARNING level, and the rule-set row stays out of path-keyed coverage and AE1. This is ready to merge once the remaining earlier change request from another reviewer is cleared.
Previous findings:
- Rebase required; the fix had to be ported into
main's rewritten_reference_coverage_findings(Blocker): Resolved.finalize_inspection_ledger.pykeepsmain'sevents_by_pathloop and skipsLedgerRecordType.RULE_SETrows at its top, next to the reference-caveat skip.report.pyimportsRULE_SET_SCOPEalongsidemain'sfinalize_ledgerandsanitize_llm_provenance. Your two rule-set tests were added unchanged next tomain's new finalizer and report tests. The PR'ssrc/change againstmainmatches the reviewed change line for line, apart from the import blockmainhad already restructured. - Skip count read from a separate global (concurrency) and rule-set path accounting (earlier rounds): Resolved, as recorded in the 2026-10-02 review. Resolving those two remaining threads now.
docs/scan-completeness.mddoes not mention the newscope: "rule_set"field (Non-blocking): still open and optional.
Material findings
None.
PIC tradeoffs: Unchanged: the PR adds an optional public scope field to ledger exception rows. It is additive, and no strict schema rejects it.
Verification and gaps: I compared the merged head against the reviewed change. The PR's source diff against main is identical to the reviewed one apart from the import block. All six hosted CI checks passed on e8c505c. The merge resolution was written by a maintainer, not by the PR author. Tests were not run locally, per policy; CI ran the full suite on the merged tree. yashrajp22's earlier change request (both points verified fixed, with evidence in the resolved threads) still needs their re-review or a maintainer dismissal before this can merge.
Decision: Approved (reviewed head e8c505c38ebac51d1701ab47a3689597e76c9252)
yashrajp22
left a comment
There was a problem hiding this comment.
The earlier collision, skip-count race, and warning-detail issues are addressed. Fresh source and wheel checks reproduce two remaining issues below; both selected HEAD pytest runs passed 35 tests.
load_rules_with_skips() and _load_rules() took _RULES_LOCK with an unconditional wait, which cannot honour _RULE_LOAD_DEADLINE. A scan queued behind another scan's slow rule load in the same MCP/graph process waited that load out: with scan A paused 3 s in the rule-read path, scan B with a 1.5 s budget returned after about 3 s. Take the lock through _rules_lock_within_deadline(), which waits at most the workflow wall-clock time left in the caller's budget and on expiry raises the existing runtime_limit _YaraRuleResourceLimitError, so node() returns the same partial runtime_limit result it already returns for other rule-load deadlines. The wait is bounded by the wall-clock deadline, not the active-processing allowance, because waiting uses no thread CPU. - No deadline set (direct callers outside node()): blocks as before. - Reentrant hold (the nested _load_rules() call): acquires at once. - The snapshot stays atomic: rules and skip count are still read inside one hold of the lock, or not at all. It is a small class, not a contextlib.contextmanager generator: the generator re-raises by assigning __traceback__, which the frozen, slotted _YaraRuleResourceLimitError rejects with a TypeError, turning every rule-load limit raised under the lock into a crash. Signed-off-by: Souptik Chakraborty <62941615+Souptik96@users.noreply.github.com>
…coping _source_aware_ledger() re-scopes each child ledger row with the row's own identity, so the static_yara rule-set row keeps rule_set:static. _source_aware_status_events() rebuilt the matching planned target with the analyzer ID instead, got a different scoped work ID, and dropped the target as unretained. In a root plus two-child run with a rejected rule in each scope, JSON kept all three rule-set exceptions but the static_yara counts fell from 6 planned / 3 partial to 4 / 1. Both paths now build the scoped ID through one helper, _source_scoped_work_id(). The status path looks up the identity behind each target's child work ID from the child ledger (_ledger_work_identities()), and falls back to the analyzer ID only for targets with no ledger row, so the two cannot diverge again. Signed-off-by: Souptik Chakraborty <62941615+Souptik96@users.noreply.github.com>
|
@yashrajp22 thank you for the review and the two repros. @rng1995 thank you for merging 1. Rule-load lock ignored the caller's deadline (
2. Rule-set identity lost in transitive status scoping (
Verification
Not verified
|
Preserve main's Markdown escaping alongside rule-set exception labels and update the rendering regression expectations. Signed-off-by: Narendran Raghavan <nraghavan@nvidia.com>
rng1995
left a comment
There was a problem hiding this comment.
Re-reviewed commit 7215857c179cf0db5bcbd6abc2d1abaf8ddf9408. All substantive prior review findings are addressed, and all six inline review threads are resolved.
- Compiled rules and skipped-rule metadata remain an atomic, coherent cache snapshot, including non-populating loads.
- Rejected rules have bounded WARNING diagnostics. Rule-set events retain distinct work identities and stay out of file coverage and AE1 accounting, with appropriate JSON, SARIF, Markdown, and terminal rendering.
- Contended rule-lock acquisition honors the caller's workflow deadline while preserving reentrant locking and the existing runtime_limit result.
- Transitive status scoping preserves each child rule-set identity; the root-plus-two-child regression reports 6 planned / 3 partial items with no unaccounted work.
Merged current main (a0d489e6) into the branch without rebasing or force-pushing. The Markdown conflict resolution preserves main's escaping helper and the rule-set label; regression expectations were updated for the escaped text. Independent review found no remaining issues.
Validation: DCO, change detection, lint/formatting, TypeScript tests, and Docker smoke tests passed. The full hosted unit suite is still running; this approval records the completed code review, and merge will wait for its successful result. Local review covered the focused concurrency, cache, collision, finalization, reporting, and transitive regressions. The merged-tree run had 979 passing tests; after adapting the Markdown expectations to main's escaping, all 31 focused Markdown/rule-set report tests passed. The remaining local CLI help startup timeout also reproduces on unchanged main; its timeout was not changed.
The optional documentation note for scope: "rule_set" remains a non-blocking follow-up. Approved.
Fixes #554
What was wrong
A rule file passed through
--yara-rules-dirthat YARA cannot compile, or that SkillSpector cannot decode as UTF-8/base64, is dropped whole with only debug-level logging._load_rulesalready counted these (materialize_skipped + compile_skipped), but only logged the total —node()never saw it, so every scanned component could still reportCOMPLETED,analysis_completeness: complete, and the recommendation stayed SAFE, because the rule that would have flagged something simply never ran.--fail-on-incompletecorrectly has nothing to key off, so it exits 0.Reproduced with the issue's own scenario: a workspace with a valid custom rule and a syntactically broken one in the same
--yara-rules-dir. The good rule fires, but the run reports a clean scan regardless.What this changes, and a design choice I want to flag
_rules_skipped_count, read back via the newrules_skipped_count()), and folded into aPARTIALledger event innode(), using the existingREAD_ERRORreason andLedgerRecordType.SYSTEM(it isn't scoped to a scanned skill file, so I used a synthetic"yara_rules/"path — ledger paths must be relative POSIX, and the real rules directory is absolute).degraded/completeddecision innode()unchanged, so this is additive to the existing status machinery rather than a new mechanism._load_rules's return signature. My first pass returned(compiled_rules, skipped_count)as a tuple, which is the more obvious API, but 15 tests intest_static_yara.pydomonkeypatch.setattr(static_yara, "_load_rules", lambda _extra_dir: rules), returning a bareyara.Rulesobject — all of them would have silently broken by unpacking ayara.Rulesas a 2-tuple. I chose the module-global read-back instead specifically to avoid that blast radius for an internal detail those tests don't exercise. Happy to go the tuple route instead if you'd rather have the cleaner API and take the test-file diff — just say so.SYNTAX_ERROR(already reserved for "Python source could not be parsed" perREASON_MESSAGES) or invent a newLedgerReasonfor this;READ_ERROR's existing message ("File content could not be read") is generic enough to cover both the decode and compile failure cases the count already sums together.Testing
New test builds a valid rule and a syntactically broken one (missing closing brace, a real YARA syntax error, matching the issue's own repro rather than a decode failure) in the same
--yara-rules-dir, asserts the valid rule still fires, the analyzer status is not"completed", and the ledger records the drop withobserved_artifacts=1.Negative control, reverting only
static_yara.pyand keeping the test:Restoring the fix, all 87 tests in the file pass again.
I did not reproduce this on Windows (the issue notes the same result on Windows 10 and Ubuntu/WSL2) — tested on Linux only, CPython 3.12.14, yara-python==4.5.4 (same version the issue reports).