Skip to content

Type RECORDING_SCHEMAS as a TypedDict, resolving 42 fan-out mypy errors - #436

Merged
squid-protocol merged 2 commits into
mainfrom
fix/431-analysis-lens-schema-typing
Jul 25, 2026
Merged

squid-protocol merged 2 commits into
mainfrom
fix/431-analysis-lens-schema-typing

Conversation

@squid-protocol

Copy link
Copy Markdown
Owner

Summary

Part of #429/#431 (mypy epic), one file per session as agreed. This session: `gitgalaxy/standards/analysis_lens.py`.

`RECORDING_SCHEMAS` mixes `List[str]` values (`RISK_SCHEMA`, `SIGNAL_SCHEMA`, `SAT_SCHEMA`, `GPU_TEXTURE_LOOKUPS`) with `Dict[str, str]` values (`FRIENDLY_MAP`, `EXPOSURE_LABELS`) in one untyped dict literal. Mypy widened the inferred value type to `Collection[str]`, which has no `.index()` -- every consumer calling `SIGNAL_SCHEMA.index(...)` (`galaxyscope.py`, `signal_processor.py`, `record_keeper.py`, `prism.py`, ...) inherited that as an error, even though none of those files' own code was wrong.

Added a `RecordingSchemas` `TypedDict` declaring each key's real type. Type-only change -- all existing `.get("KEY", default)` call sites already use literal string keys, so behavior is unchanged.

228 → 186 unique baseline entries. Baseline regenerated accordingly.

Found (but not fixing here, per the 1-file-per-session pace) a second, separate root cause: `galaxyscope.py`'s `observation` dict mixes `str`/`float`/`None` assignments across different code paths, producing similar `"object" has no attribute ...` fan-out. Next session's candidate.

Test plan

  • `analysis_lens.py` itself has zero mypy errors after this change
  • `mypy_audit.py --ci` clean against the regenerated baseline
  • `flake8`, `dead_key_audit.py --ci`, full `pytest tests/` (866 passed, 1 deselected, 1 pre-existing xfail) all clean

…rs (#431)

RECORDING_SCHEMAS mixes List[str] values (RISK_SCHEMA, SIGNAL_SCHEMA,
SAT_SCHEMA, GPU_TEXTURE_LOOKUPS) with Dict[str, str] values (FRIENDLY_MAP,
EXPOSURE_LABELS) in one untyped dict literal. Mypy widened the inferred
value type to Collection[str] -- the join of list and dict that still
supports string iteration -- which has no .index(). Every consumer that
does SIGNAL_SCHEMA.index(...) (galaxyscope.py, signal_processor.py,
record_keeper.py, prism.py, ...) inherited that as an error, even though
none of those files' own code is wrong.

Added a RecordingSchemas TypedDict declaring each key's real type and
annotated RECORDING_SCHEMAS with it. All existing .get("KEY", default)
call sites already use literal string keys, so this is a type-only
change with no behavior difference.

228 -> 186 unique baseline entries (#430's baseline regenerated
accordingly). First of #431's confirmed root-cause fixes; the "object"-
typed heterogeneous-dict-literal pattern (e.g. galaxyscope.py's
`observation` dict) is a separate, second root cause, left for next.

Verified: analysis_lens.py itself has zero mypy errors after this change;
flake8 and full pytest suite (866 passed, 1 deselected, 1 pre-existing
xfail) both clean.
@github-actions

Copy link
Copy Markdown
Contributor

🐦‍⬛ Muninn Security Scan

✅ No security issues found.

🐦‍⬛ Powered by Muninn · Skald Lab

The baseline pushed with #436 was regenerated in a full-precision venv
(networkx/tiktoken/pandas/xgboost installed), not the leaner env
mypy-audit.yml actually uses (mypy + PyYAML only) -- CI correctly caught
this as a "new" error (galaxyscope.py:70's importlib.util usage) that
had silently stopped erroring locally once those extra packages were
present. Regenerated against the matching minimal environment and added
a docstring note so this doesn't happen again.
@squid-protocol
squid-protocol merged commit 63174f6 into main Jul 25, 2026
26 checks passed
@squid-protocol
squid-protocol deleted the fix/431-analysis-lens-schema-typing branch July 25, 2026 16:43
squid-protocol added a commit that referenced this pull request Jul 25, 2026
Four distinct fixes:

- _process_file_worker's `observation` dict: un-annotated literal dict
  with 4 initial str/dict-valued keys, but later code paths assign
  float/None values into it too. Annotated as Dict[str, Any] (matching
  the function's own declared return type) instead of leaving mypy to
  infer a narrow type from the literal's first 4 keys. Resolved 10 of
  the 14 -- the "Collection[str]"-family fan-out this session's errors
  were mostly made of.
- `import importlib` without `import importlib.util`: worked at runtime
  only because something else transitively imported importlib.util
  first. Changed to `import importlib.util` directly.
- `self.neighborhood_tracker = defaultdict(int)`: mypy can't infer a key
  type from an empty defaultdict. Annotated DefaultDict[str, int],
  matching how it's actually keyed (str(path_obj.parent)).
- `run_xray_audit`/`run_firewall_audit`'s `config: Optional[ResolvedConfig]`
  signatures: both functions' own docstrings already documented that the
  caller may hand over either a ResolvedConfig or a plain dict ("only
  .get() works uniformly across both") -- the signature just never said
  so. Broadened to Optional[Union[ResolvedConfig, Dict[str, Any]]] in
  both binary_anomaly_detector.py and supply_chain_firewall.py to match
  the already-intentional, already-documented behavior; galaxyscope.py's
  call site (passing self.config, a plain dict) was correct as-is.

187 -> 173 unique baseline entries. Baseline regenerated in the same
minimal environment mypy-audit.yml uses (mypy + PyYAML only), per the
docstring note added after #436's environment mismatch.

Verified: galaxyscope.py, binary_anomaly_detector.py, and
supply_chain_firewall.py all report zero mypy errors after this change.
flake8, dead_key_audit.py --ci, and full pytest suite (866 passed,
1 deselected, 1 pre-existing xfail) all clean.

Co-authored-by: Joe Esquibel <[email protected]>
squid-protocol added a commit that referenced this pull request Jul 25, 2026
Two distinct fixes:

- `folder_stats: Dict[str, FolderStats] = {}`: the per-folder rollup
  accumulator mixes int, float, and List[float] values in one dict
  literal, which mypy widened to "object" -- producing a cascade of
  "object has no attribute append", "Unsupported operand types for +",
  and "No overload variant of sum/max/round matches" errors everywhere
  the accumulated stats get consumed. Added a FolderStats TypedDict
  declaring each field's real type instead. Resolved 15 of 16.

- `ai_score`: first assigned as a bare float (from `float(str(...))`
  or a `0.0` fallback), then later reassigned to None in the
  zero_dependency_mode branch -- that None is intentional (record_keeper
  already maps bypassed zero-dep metrics to real SQL NULL rather than
  0.0, specifically to avoid an unavailable metric looking like a
  measured "zero risk" in the database -- see e7e1acf). Annotated
  `Optional[float]` at first assignment instead of changing the None.
  pagerank_score/blast_radius/betweenness_score/closeness_score/
  producer_ratio/ecosystem_role already infer Optional[float] cleanly
  from the same if/else with no prior binding, so they needed no change.

173 -> 157 unique baseline entries. Regenerated in the minimal
mypy-audit.yml environment per #436's lesson.

Verified: record_keeper.py reports zero mypy errors after this change.
flake8, dead_key_audit.py --ci, full pytest suite (866 passed,
1 deselected, 1 pre-existing xfail) all clean.
squid-protocol added a commit that referenced this pull request Jul 25, 2026
Two distinct fixes:

- `folder_stats: Dict[str, FolderStats] = {}`: the per-folder rollup
  accumulator mixes int, float, and List[float] values in one dict
  literal, which mypy widened to "object" -- producing a cascade of
  "object has no attribute append", "Unsupported operand types for +",
  and "No overload variant of sum/max/round matches" errors everywhere
  the accumulated stats get consumed. Added a FolderStats TypedDict
  declaring each field's real type instead. Resolved 15 of 16.

- `ai_score`: first assigned as a bare float (from `float(str(...))`
  or a `0.0` fallback), then later reassigned to None in the
  zero_dependency_mode branch -- that None is intentional (record_keeper
  already maps bypassed zero-dep metrics to real SQL NULL rather than
  0.0, specifically to avoid an unavailable metric looking like a
  measured "zero risk" in the database -- see e7e1acf). Annotated
  `Optional[float]` at first assignment instead of changing the None.
  pagerank_score/blast_radius/betweenness_score/closeness_score/
  producer_ratio/ecosystem_role already infer Optional[float] cleanly
  from the same if/else with no prior binding, so they needed no change.

173 -> 157 unique baseline entries. Regenerated in the minimal
mypy-audit.yml environment per #436's lesson.

Verified: record_keeper.py reports zero mypy errors after this change.
flake8, dead_key_audit.py --ci, full pytest suite (866 passed,
1 deselected, 1 pre-existing xfail) all clean.

Co-authored-by: Joe Esquibel <[email protected]>
squid-protocol added a commit that referenced this pull request Jul 25, 2026
Root cause + six smaller follow-on fixes:

- LENS_CONFIG (language_standards.py) mixes Set[str]/Dict[str,str]/
  List[Dict]/Dict[str,float] values in one dict literal, widened by mypy
  to Collection[object] -- the same class of bug as #436's RECORDING_SCHEMAS,
  producing 16 direct "Collection[object] has no attribute get/items"
  errors in language_lens.py plus 4 more in prism.py. Added a LensConfig
  TypedDict. All consumers already use literal string keys.

- `target_id`: two genuinely independent uses of the same name in
  different branches of one function -- one always a plain str (a
  self-contained prose-extension shortcut that returns immediately),
  the other legitimately Optional[str] (an anchor-map lookup). Renamed
  the first to prose_target_id instead of fighting mypy's narrowing
  across two unrelated code paths sharing one name.

- `lock_tier`: first assigned as int (4), later assigned 1.5/1.7 --
  sub-tiers are intentional (see "Tier 1.5"/"Tier 1.7" in the code and
  DetectorResult's own lock_tier: Union[int, float]). Annotated float
  at declaration; _forge_result's tier: int parameter widened to match.

- `local_tally`: missing annotation on an empty dict accumulator.
  Dict[str, int].

- Two `max(d, key=d.get)` calls: dict.get is overloaded (1-arg vs
  2-arg-with-default), which mypy can't resolve when passed bare as a
  key function. Switched both to `key=lambda k: d[k]` -- safe since key
  is only ever invoked on d's own members.

- `regex_hits`: assigned int(0), later multiplied by 0.7 (a language
  handicap). Annotated float at declaration -- its only consumer is a
  final `/loc` density calculation that was always going to produce a
  float anyway.

- `_find_balanced_end`'s `limit`: self.thresholds is Dict[str, float]
  (mixing float confidence values with integer limits like
  HANDSHAKE_LOOKAHEAD_LIMIT), so the range()-bound computed from it
  needs an explicit int() -- a character-position limit was always
  meant to be a whole number. Fixed the return-value mismatch too, same
  root cause.

157 -> 126 unique baseline entries.

Verified: language_lens.py reports zero mypy errors after this change.
flake8, dead_key_audit.py --ci, full pytest suite (866 passed,
1 deselected, 1 pre-existing xfail) all clean.
squid-protocol added a commit that referenced this pull request Jul 25, 2026
Root cause + six smaller follow-on fixes:

- LENS_CONFIG (language_standards.py) mixes Set[str]/Dict[str,str]/
  List[Dict]/Dict[str,float] values in one dict literal, widened by mypy
  to Collection[object] -- the same class of bug as #436's RECORDING_SCHEMAS,
  producing 16 direct "Collection[object] has no attribute get/items"
  errors in language_lens.py plus 4 more in prism.py. Added a LensConfig
  TypedDict. All consumers already use literal string keys.

- `target_id`: two genuinely independent uses of the same name in
  different branches of one function -- one always a plain str (a
  self-contained prose-extension shortcut that returns immediately),
  the other legitimately Optional[str] (an anchor-map lookup). Renamed
  the first to prose_target_id instead of fighting mypy's narrowing
  across two unrelated code paths sharing one name.

- `lock_tier`: first assigned as int (4), later assigned 1.5/1.7 --
  sub-tiers are intentional (see "Tier 1.5"/"Tier 1.7" in the code and
  DetectorResult's own lock_tier: Union[int, float]). Annotated float
  at declaration; _forge_result's tier: int parameter widened to match.

- `local_tally`: missing annotation on an empty dict accumulator.
  Dict[str, int].

- Two `max(d, key=d.get)` calls: dict.get is overloaded (1-arg vs
  2-arg-with-default), which mypy can't resolve when passed bare as a
  key function. Switched both to `key=lambda k: d[k]` -- safe since key
  is only ever invoked on d's own members.

- `regex_hits`: assigned int(0), later multiplied by 0.7 (a language
  handicap). Annotated float at declaration -- its only consumer is a
  final `/loc` density calculation that was always going to produce a
  float anyway.

- `_find_balanced_end`'s `limit`: self.thresholds is Dict[str, float]
  (mixing float confidence values with integer limits like
  HANDSHAKE_LOOKAHEAD_LIMIT), so the range()-bound computed from it
  needs an explicit int() -- a character-position limit was always
  meant to be a whole number. Fixed the return-value mismatch too, same
  root cause.

157 -> 126 unique baseline entries.

Verified: language_lens.py reports zero mypy errors after this change.
flake8, dead_key_audit.py --ci, full pytest suite (866 passed,
1 deselected, 1 pre-existing xfail) all clean.

Co-authored-by: Joe Esquibel <[email protected]>
squid-protocol added a commit that referenced this pull request Sep 3, 2026
…temmed file in the scan (#2684) (#2687)

* fix(core-engine): a bare filename must not credit every same-stemmed file (#2684)

`_resolve_dependency_graph`'s popularity tally ends its stem fallback with
`"/" not in clean_path`, which is true of EVERY bare filename, so a single
import token credited every file in the scan sharing its stem -- unscoped by
language, directory or repository. Because that tally (not the DAG) gates
galaxyscope's Contextual Baseline Fix, each bogus credit also converted a
file's orphaned logic into API surface and wiped its tech debt.

Measured over language-crucible before the fix: 203 credits came from that
clause alone and 136 of them (67%) crossed a repository boundary. The
fallout is not subtle -- zig's `codegen.zig` credited gnucobol's `codegen.c`,
vscode's `editor.css` credited three.js's `Editor.js`, three.js's
`EventDispatcher.js` credited symfony's `EventDispatcher.php`, Flutter's
`basic.dart` credited a COBOL `BASIC.cbl`, and `#include <windows.h>` from
C++ credited a `windows.Dockerfile`.

The guard: if an import token names an extension, that extension says which
languages the target can be written in, so a candidate whose own extension
shares no language with it is not the file being imported, whatever its stem
says. Permissive at both edges -- a token with no extension is left alone
(COBOL's `COPY SQLCA` names no file type) and so is any extension the
registry does not know -- so it fires only on a positive contradiction.

That precision is what makes it safe: `.h` maps to c/cpp/objective-c and
`.y` to c/yacc, so a header still credits its own language's sources,
including the real generated-parser case this was found through --
gnucobol's `scanner.l` including `parser.h` keeps crediting that repo's own
`parser.y`, while the four cross-language `Parser.*` victims in unrelated
repos lose it.

javascript/typescript are declared interchangeable because TypeScript's ESM
imports name the *emitted* file: `import "./lifecycle.js"` resolving to
lifecycle.ts is the documented norm, not a stem collision. vscode exercises
it, and the first cut of this guard broke it.

The strict tests fail on origin/main (4 of them, including every row of the
cross-language table). One trap they cover: the harness must populate
`ext_tally`, or `foo.h` is rewritten to `foo/h` before the stem stage is
reached and the negative cases pass for entirely the wrong reason.

mypy baseline entry rekeyed 320 -> 368 by hand for the pure line shift --
NOT regenerated, because this venv is full-precision and the audit's own
docstring records that regenerating outside CI's lean env silently produced
a baseline that passed locally and failed in CI (PR #436).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* test(golden-master): re-bless for the tally extension guard (#2684)

214 differences in each fixture, regenerated with `crucible_check.py
--update --yes` (user-authorised). The zero-dep diff is byte-identical to
the one measured and attributed before the bless.

The only `7. Structural Signatures` columns that move are `Orphaned Logic`
and `Exposed API / Public Exports`, on the same 12 files -- these are
outputs of the Contextual Baseline Fix, not counts of anything extracted.
`Popularity Rank` does not move at all: that column reports the network
sensor's in_degree, a different quantity from the tally this fixes.

Each of the 12 is attributed to the single cross-language credit it loses:

  cobol/gnucobol_internals/codegen.c   <- zig's codegen.zig
  javascript/threejs/Editor.js         <- vscode's editor.css
  php/symfony/EventDispatcher.php      <- three.js's EventDispatcher.js
  php/symfony/Parser.php               <- a cobol flex file's parser.h
  php/magento2/Http.php                <- objective-c's HTTP.h
  perl/spamassassin/Parser.pm          <- the same parser.h
  perl/spamassassin/HTML.pm            <- objective-c's HTML.h
  typescript/assemblyscript/parser.ts  <- the same parser.h
  zig/bun/Parser.zig                   <- the same parser.h
  shell/serenity/package.sh            <- zig's Package.zig
  cobol/.../BASIC.cbl                  <- Flutter's basic.dart
  dockerfile/moby/.../windows.Dockerfile <- C++ #include <windows.h>

Tech debt rises on all 12, which is the correction, not a regression: none
of them was ever imported by the file that was crediting it. The legitimate
neighbour survives -- gnucobol's own parser.y keeps the credit from the
scanner.l in the same repo, and is absent from this list.

Everything else in the 214 is coordinate ripple and the group/global
aggregates downstream of those 12.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: Joe Esquibel <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
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