Skip to content

audit: drop unused imports from 11 src modules (nightly) - #504

Merged
haiyuan-eng-google merged 1 commit into
GoogleCloudPlatform:mainfrom
caohy1988:nightly/dsh-deadcode-20261001
Oct 1, 2026
Merged

haiyuan-eng-google merged 1 commit into
GoogleCloudPlatform:mainfrom
caohy1988:nightly/dsh-deadcode-20261001

Conversation

@caohy1988

@caohy1988 caohy1988 commented Oct 1, 2026 •

Copy link
Copy Markdown
Collaborator

Nightly dead-code audit, one theme: remove unused imports from src/. This only deletes import lines; no logic, signature or public API change. It changes 11 files: 18 lines deleted and 2 edited (from typing import Any, X becomes from typing import X).

Follow-up to #490 and #496. Those sweeps started from vulture, which counts a name as used when any module uses it. So a per-file unused import json never shows up there. ruff --select F401 checks each file, which is how these were found.

Removed (16 names)

File Removed
ai_ml_integration.py:62 datetime.timedelta
cli.py:197 function-local .resolved_spec.ResolvedGraph in _load_spec_from_args
eval_validator.py:36 dataclasses.field
extractor_compilation/diagnostics.py:75 typing.Any
extractor_compilation/measurement.py:52 .compiler.CompileResult (the package __init__ still imports .compiler first)
feedback.py:34-36, 691 dataclass, field, json, and a function-local google.cloud.bigquery
insights.py:40, 42, 45 asyncio, dataclass, json
ontology_materializer.py:79 .resolved_spec.ResolvedProperty
ontology_models.py:42 typing.Any
ttl_importer.py:57 rdflib.XSD (the other rdflib imports still gate _RDFLIB_AVAILABLE)
bigquery_ontology/graph_ddl_compiler.py:61 .binding_models.PropertyBinding

How each one was proven unused

  1. ruff check --select F401 flags the name in its own file.

  2. An AST and text scan of every tracked file (git ls-files) found none of the following:

    • a from-import of the name from that module (absolute or relative)
    • attribute access <module>.<name>
    • patch.object / setattr / getattr / monkeypatch on it
    • a dotted string reference such as "bigquery_agent_analytics.feedback.json"
    • a mention in .md, .ipynb, .yaml, .toml or .sh files, including in docs/, deploy/, producers/ and plugins/

    The only text hit was insights.json in docs/proposal_bigquery_agent_cli.md:541, which is an output filename (> insights.json).

  3. A second pass looked for bare-string name lists and non-constant getattr calls in files that touch each module. It found nothing for the removed names.

    • Positive control: the same pass does find the known dynamic references at tests/test_pr123_performance_regressions.py:369-370. Those reach the shim exports through getattr over a list of names.
  4. The touched modules have no __all__, no star-imports, and no sys.modules aliasing. The only alias in src/ is trace_evaluator → performance_evaluator, which this PR does not touch. No test reads these files as text.

Kept on purpose (ruff still flags them)

  • performance_evaluator.py:59,61: re-exported through the trace_evaluator shim and asserted at tests/test_pr123_performance_regressions.py:369-370.
  • ontology_models.py:169-172 (Extracted*): re-exports imported from ontology_models (tests/test_ontology_models.py:29 and others).
  • client.py:86 AI_GENERATE_JUDGE_BATCH_QUERY: compat alias added in feat: unify performance evaluation with compatible evaluator APIs #123 and named in docs/design.md:285.
  • The 201 __init__.py hits: these are public re-exports.

Found but not changed here (follow-ups, outside this PR's import-only scope)

  • resolved_spec.py:496 session_col (F841): computed from binding.from_session_column and never used. This may be a value that was meant to be used rather than dead code, so the owner should look at it; it should not just be deleted.
  • graph_ddl_compiler.py:109 entity_binding_map (F841): referenced only at its definition.
  • owl_importer.py:1114 parsed: the float(value) call is a validity probe; only the name is unused. Keep.
  • _streaming_evaluation.py:144 is_launch_trigger_row: no caller in src/, tests/, deploy/ or docs/.
  • scripts/quality_report.py:55,59,353 imports and :3303 _select_trajectory_sessions: no references found outside the script.
  • scripts/check_streamlit_queries_sync.py:419,576: unused locals (F841).
  • examples/e2e_demo.py and examples/context_graph/run_agent.py: unused imports.
  • Not dead (vulture false positives): 10 tests/ helpers that vulture flags are all @pytest.fixture(autouse=True). The Typer commands, callbacks and console-script entry points vulture flags are also used.

Before and after evidence

Local runs used Python 3.13.7, macOS arm64, and a fresh venv with pip install -e ".[dev,streamlit]\" (the same extras as CI). "Before" is main at 6e536dc; "after" is this branch.

Check Before After
pytest --tb=short -q (full suite, as in ci.yml) 5278 passed, 83 skipped, 0 failed 5278 passed, 83 skipped, 0 failed
ruff check --select F401,F841,F811 src scripts examples tests 335 319 (exactly the 16 removed names; no new hit)
vulture src --min-confidence 60 272 lines 272 lines (identical)
import of the 11 touched modules plus both packages OK OK
bq-agent-sdk / bqaa / gm / bqaa-revalidate-extractors --help rc=0 rc=0

Format, matching the CI pins (pyink>=24.3.0,<26 gives pyink 25.12.0; isort 9.0.2):

  • bash autoformat.sh && git diff --exit-code src/ tests/ examples/ scripts/ dashboards/ (the CI Format check step) is clean.
  • pyink --check src tests scripts examples reports 361 files unchanged.
  • isort --check-only src tests scripts examples returns rc=0.
  • git diff --check is clean.

CI on 7a9e22a

Run 36848488492 is green: Test (Python 3.10-3.14), Format check, Build package, Configurator browser smoke, CLA, scan-pr and check-changes all pass. The zizmor jobs were skipped.

Every Test job reports 5280 passed, 81 skipped. That is identical to the main push run for 6e536dc (36748361857), so no test was lost or newly skipped.

No version bump, no CHANGELOG edit, and no reviewers requested.

🤖 Generated with Claude Code

Import-line deletions only; no logic, signature or public API change.
Every removed name is flagged by `ruff check --select F401` and has no
reference anywhere in the tracked tree: no from-import, attribute
access, mock.patch / monkeypatch / getattr target, or mention in docs,
notebooks, deploy/ or producers/. None of the touched modules defines
__all__, is star-imported, or is aliased through sys.modules.

Removed:
- ai_ml_integration.py: datetime.timedelta
- cli.py: function-local resolved_spec.ResolvedGraph in
  _load_spec_from_args
- eval_validator.py: dataclasses.field
- extractor_compilation/diagnostics.py: typing.Any
- extractor_compilation/measurement.py: .compiler.CompileResult (the
  package __init__ still imports .compiler first)
- feedback.py: dataclasses.dataclass, dataclasses.field, json, and a
  function-local google.cloud.bigquery import
- insights.py: asyncio, dataclasses.dataclass, json
- ontology_materializer.py: resolved_spec.ResolvedProperty
- ontology_models.py: typing.Any
- ttl_importer.py: rdflib.XSD (the remaining rdflib imports still gate
  _RDFLIB_AVAILABLE)
- bigquery_ontology/graph_ddl_compiler.py: binding_models.PropertyBinding

Kept on purpose although ruff flags them:
- performance_evaluator.py utils imports: re-exported through the
  trace_evaluator shim and asserted by
  test_trace_shim_preserves_public_and_private_exports
- ontology_models.py extracted_models imports: re-exports
- client.py AI_GENERATE_JUDGE_BATCH_QUERY: compat alias from GoogleCloudPlatform#123,
  named in docs/design.md
- package __init__ re-exports

Follow-up to GoogleCloudPlatform#490 and GoogleCloudPlatform#496. vulture did not report these because it
counts a name as used when any other module uses it; ruff F401 checks
each file.

@caohy1988 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Blind independent Astra review of head 7a9e22a47dc0bdbb1495c7b1b68291ace540409c against main at 6e536dc81ae58640a27842c3f043a9bf5e88b9a5.

Rejection criteria established before reading the description/diff:

  1. A deleted binding has a live code/type use or a repository consumer, including re-exports, aliased attribute access, patch strings, dynamic access, or documentation promising that binding.
  2. Deleting an import changes an availability gate, import side effect, or reachable runtime behavior, including function-local imports and runtime annotations.
  3. The diff exceeds the import-only scope, required head CI fails, or independent before/after checks reveal regressions or contradict the proof claims.

What I tried:

  • Read the PR description and full base-to-head diff; confirmed exactly 11 source files, +2/-18, only imports and associated blank lines; non-import ASTs are identical in all 11 files; no version, release, or intent/spec/plan changes.
  • Independently enumerated the removed bindings and scanned tracked files with AST and text searches for from-imports, aliases/attributes, dotted strings, patch/getattr/setattr/importlib usage, re-export declarations, annotations, and documentation. Checked each of: ai_ml_integration.timedelta; cli._load_spec_from_args's local ResolvedGraph; eval_validator.field; diagnostics.Any; measurement.CompileResult; feedback.dataclass/field/json and compute_question_distribution's local bigquery; insights.asyncio/dataclass/json; ontology_materializer.ResolvedProperty; ontology_models.Any; ttl_importer.XSD; graph_ddl_compiler.PropertyBinding. No consumer relying on a deleted binding found. Documentation mentions of CompileResult/ResolvedProperty/XSD describe the originating types or RDF vocabulary, not exports from the changed modules; insights.json is an output filename.
  • Checked import order and side effects: extractor_compilation.init imports compiler before measurement; ontology_materializer retains other resolved_spec imports; graph_ddl_compiler retains binding_models imports. TTL retains rdflib/OWL/RDF/RDFS/SKOS imports and its availability gate. Verified TTL import both without rdflib and with rdflib 7.6.0; the latter reports _RDFLIB_AVAILABLE=True. Feedback dispatches immediately to helpers that retain their own bigquery imports. Both resolved_spec and google.cloud.bigquery are already loaded after normal package/CLI import. CLI valid loading branches retain resolved_spec imports, while invalid argument branches raise the intended BadParameter.
  • Fresh worktree venv: Python 3.12.9, dev+streamlit extras, pyink 25.12.0, isort 9.0.2, ruff 0.16.9, vulture 2.16. Initial unconstrained cryptography 50.0.2 native build failed because this machine lacked the x86 Rust target; used cryptography 46.0.7. Smoke commands explicitly used PYTHONPATH=src.
  • Imported all 11 touched modules and both parent packages; repeated imports under python -W error successfully. All five console entry points --help passed: bq-agent-sdk, bqaa, gm, bqaa-revalidate-extractors, bqaa-materialize-window.
  • Probed CLI no-input/mixed/partial/env guards and both combined/separated successful dispatches; probed all four feedback dispatch branches. Evaluated get_type_hints for module-defined classes/functions and class methods and compared annotation failures against base.
  • Focused CLI/feedback/models/materializer tests: 263 passed. Extractor diagnostics/measurement, OWL bridge/importer and ontology graph DDL tests with rdflib: 167 passed.
  • Full pytest --tb=short -q in this head worktree and an independent git archive of base: both 5278 passed / 83 skipped / 0 failed (head 250.95s; base 286.32s).
  • ruff F401/F841/F811 over src/scripts/examples/tests: base 335, head 319; exactly the 16 stated import diagnostics disappeared, no new diagnostic. Vulture: 272 findings on both, identical messages/files after accounting for shifted line numbers. Touched-file F401/F821 check has only four retained re-export F401 flags and four unchanged baseline annotation F821 flags.
  • pyink --check and isort --check-only on touched files passed; full-repository pyink --check src tests scripts examples reports 361 unchanged files and isort --check-only passes; git diff --check passed.
  • Independently queried PR checks and the Actions head SHA: all required checks pass on exactly this head; zizmor jobs skip. Read head run 36848488492 and base run 36748361857 test logs: all five Python versions 3.10–3.14 report 5280 passed / 81 skipped on both.

Findings by severity:

  • P0/P1: none.
  • P2: none introduced by this diff.
  • P3: ontology_models.py:169–172 still has four F401 warnings for ExtractedEdge/ExtractedGraph/ExtractedNode/ExtractedProperty. They are real re-exports consumed at tests/test_ontology_models.py:29–32; keep them. A follow-up could make re-export intent explicit to ruff.
  • P3, baseline only: cli.py:191's string ResolvedGraph annotation already fails get_type_hints on the base because the original import is function-local, not in function globals. The removed import never fixed annotation resolution. ttl_importer.import_owl_to_graph_spec likewise already has an unresolved GraphSpec annotation; ontology_materializer has unchanged Ontology/Binding annotation F821 warnings. These do not demonstrate a regression from this cleanup.

Limitations: repository searches cannot establish usage in untracked downstream applications. Local runs independently reproduce the evidence under Python 3.12.9 rather than the author's historical Python 3.13.7 environment. No peer review/comment or forbidden context was read. No tracked source modification, push, merge, or reviewer request was made.

VERDICT: APPROVE @ 7a9e22a

@caohy1988 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fable blind review: PR #504 @ 7a9e22a (independent; I read only the PR description, the diff, repo code and CI logs. I read no other review or comment on this PR before posting.)

Rejection criteria (written before reading the diff)

  • R1 (P0/P1): A removed name is still used, either in its own module (function bodies, string or forward annotations resolved at runtime by pydantic, dataclasses or typing.get_type_hints) or elsewhere (from <mod> import <name>, <mod>.<name>, mock.patch string targets, getattr/importlib, __all__, shim or compat re-exports, docs or examples). Rejected if any import, CLI entry point, test or reachable path raises ImportError, AttributeError or NameError.
  • R2 (P1): A removed import had an import-time side effect or availability gate (optional-dependency probe, try/except ImportError flag, early ImportError on a missing extra). Rejected if removing it changes behavior.
  • R3 (P1/P2): The diff touches anything other than import lines (logic, version, CHANGELOG, intent/spec/plan files). Also rejected if CI on 7a9e22a is not green, if pyink<26 or isort fails, or if a proof claim in the PR body or commit message is false when re-run.

None of the three criteria is met.

What I tried

Local setup: macOS arm64, Python 3.13.7, a fresh venv with pip install -e ".[dev,streamlit]" (the ci.yml extras). Base is a clean git archive of 6e536dc.

  1. Diff against the contract. 11 files under src/, +2/−18. The diff removes exactly the 16 claimed names. The only other lines removed are the 2 blank lines that followed the deleted function-local imports. There is no version, CHANGELOG or intent/spec/plan change.
  2. Re-verified all 16 names myself.
    • ruff check --select F401,F841,F811 src scripts examples tests (ruff 0.16.9) goes from 335 to 319. A JSON diff keyed on (file, code, message) shows exactly these 16 removed and nothing added.

    • I wrote my own AST scan over every tracked .py file (467) and every notebook code cell (14 notebooks). It looks for:

      • absolute and relative from-imports of each name from its module;
      • module aliases (import m as X, from pkg import m) followed by X.<name>;
      • patch.object, setattr, getattr, hasattr, delattr or monkeypatch on a touched module, including dynamic names;
      • importlib, __import__ and sys.modules use;
      • vars, dir, getmembers or __dict__ on a touched module;
      • string constants such as "…feedback.json".

      It found 0 hits. As a positive control, the same scan does find known references (cli.app, ttl_importer.ttl_import, ontology_models.ExtractedNode, cli_module.main). The 5 notebook cells it cannot parse are shell ! continuations with no imports from touched modules.

    • git grep over all tracked file types for <module>.<name> finds only insights.json in docs/proposal_bigquery_agent_cli.md:541, which is an output filename. Every string mock.patch target on a touched module is cli._build_client, cli._build_view_manager, ontology_materializer.OntologyMaterializer or ontology_materializer.make_bq_client. All in-repo imports of ResolvedProperty, PropertyBinding, CompileResult and ResolvedGraph go through their canonical modules (resolved_spec, bigquery_ontology/binding_models, and the extractor_compilation package).

    • None of the touched files defines __all__, nothing star-imports them, and the only sys.modules alias is trace_evaluator → performance_evaluator. Neither the extractor import allowlist (ast_validator._ALLOWED_IMPORTS_FROM) nor the smoke-test unpickle allowlist (smoke_test._SAFE_UNPICKLE_GLOBALS) names a touched module.

  3. Tried to break it.
    • python -W error -c "import <m>" in a fresh interpreter succeeds for all 11 modules and both packages.

    • I ran typing.get_type_hints on every class, function, method and property defined in the 11 modules. For every model I also ran dataclasses.fields, checked __pydantic_complete__ and ran model_rebuild(force=True). All 326 results are identical on base and head. The 3 NameErrors already happen on base (see P3-1).

    • All 5 console scripts (bq-agent-sdk, bqaa, gm, bqaa-revalidate-extractors, bqaa-materialize-window) exit 0 with --help. I also ran --help through CliRunner on all 33 (sub)command paths. Exit codes and output hashes match between base and head.

    • NameError probe for the two function-local removals. I ran every branch of cli._load_spec_from_args: all 6, including the 4 error branches the suite never reaches (coverage misses cli.py:202/211/216/243). I ran feedback.compute_question_distribution against a fake BQ client in every mode:

      • frequently_asked and frequently_unanswered, which the suite never reaches (feedback.py:691/702 uncovered);
      • AI.GENERATE and legacy ML.GENERATE_TEXT;
      • no model (fallback), custom categories, and grouping failure (fallback).

      All 13 outcomes match between base and head. Both deleted imports were also no-ops at runtime. resolved_spec and google.cloud.bigquery are already in sys.modules once cli/feedback are imported, and google-cloud-bigquery is a hard dependency.

    • I tested the ttl_importer gate with rdflib present, with rdflib blocked, and with rdflib.namespace blocked. _RDFLIB_AVAILABLE and the _require_rdflib() ImportError message are the same on base and head in all three cases.

    • For measurement.py: extractor_compilation/__init__.py:59-61 imports .compiler before .measurement (:70), and compiler.py has no import-time side effects.

  4. Full test suite.
    • pytest --tb=short -q with the CI extras gives 5278 passed / 83 skipped on base, and the same on head.
    • With the owl extra added (rdflib 7.6.0), base and head both give 5394 passed / 67 skipped. A per-test JUnit diff over 5461 cases shows 0 outcome changes. The 190 tests in the 5 ttl/owl test files pass, with 83% ttl_importer coverage.
  5. Formatting, using the CI pins (pyink 25.12.0, isort 9.0.2).
    • On the 11 changed files, pyink --check reports them unchanged and isort --check-only returns rc=0.
    • Over the CI scope (src tests examples scripts dashboards), pyink reports 366 files unchanged and isort returns rc=0.
    • The PR body's pyink --check src tests scripts examples claim checks out: 361 files unchanged. git diff --check is clean.
  6. CI.
    • Run 36848488492 has head_sha 7a9e22a and is green: Format, Test 3.10–3.14, Build, Configurator smoke, CLA, scan-pr and check-changes. zizmor was skipped.
    • The merge ref af7be79 has the same tree (56ca7e1) as 7a9e22a, because main is still 6e536dc.
    • Every Test job log reports 5280 passed / 81 skipped. That matches the main push run 36748361857 for 6e536dc on each Python version.
    • vulture src --min-confidence 60 prints 272 lines on both sides, identical apart from line numbers.

Findings

P0 / P1: none.

P2: none.

P3 (non-blocking; I'm not asking for changes in this PR):

  1. cli.py:191 -> "ResolvedGraph" is still an unresolvable forward reference. Ruff reports F821 on base and on head, and get_type_hints(cli._load_spec_from_args) raises NameError on both. The deleted function-local import looks like it was meant to back that annotation, but a binding inside the function body is never visible to the function's own annotations, at runtime or to type checkers. So deleting it is correct and changes nothing. A natural follow-up is a module-level if TYPE_CHECKING: import. The same pattern already exists at ontology_materializer.py:489-490 ("Ontology", "Binding") and ttl_importer.py:828 ('GraphSpec'). The commit message's "no reference anywhere" is true of the removed binding, but it doesn't mention this leftover textual use.
  2. CI installs only .[dev,streamlit], without the owl extra, so the rdflib-backed tests are skipped in CI. Under the CI extras ttl_importer.py is 17% covered. As a result, the PR's pytest and CI evidence doesn't exercise the XSD removal. I ran those tests with rdflib (results above, clean). This is a CI coverage gap to handle separately, not a defect in this PR.
  3. The only F401 left in the 11 touched files is ontology_models.py:169-172 (Extracted*), and keeping it is right because it is a re-export: tests/test_ontology_models.py:29-32 and tests/test_cli.py (8 sites) import these names from ontology_models. Pyflakes also flags two unused locals in touched files, both outside this PR's scope: graph_ddl_compiler.py:109 entity_binding_map (already listed in the PR) and cli.py:1206 matched (deliberately del'd, with a comment explaining why).
  4. These were importable module attributes, so code like from bigquery_ontology.graph_ddl_compiler import PropertyBinding would now fail. None of the names is in __all__ or documented, and every in-repo user imports them from the canonical module. The risk is negligible for an Alpha package; I mention it only for completeness.

VERDICT: APPROVE @ 7a9e22a

@haiyuan-eng-google
haiyuan-eng-google merged commit eb9d430 into GoogleCloudPlatform:main Oct 1, 2026
15 checks passed
haiyuan-eng-google pushed a commit that referenced this pull request Oct 8, 2026
…umns (#514)

* chore(release): 0.6.0 — span OTel correlation, ViewManager denied_columns

Bump [project].version from 0.5.4 to 0.6.0 and cut CHANGELOG.md for
the 10 PRs merged since v0.5.4 (#502, #504–#510, #512, #513).

[Unreleased] becomes [0.6.0] - 2026-10-08 with a release-highlights
lead, and a new empty [Unreleased] sits above it. The #510 entries
already under [Unreleased] are kept and checked against the code:
denied_columns is keyword-only and exact-case, a bare string raises
TypeError, the six per-event views it skips are named, the CLI exits 2
on an invalid name, and the event-specific view columns move two
positions later. The SDK.md correlation guide moves to Documentation.
Every other PR in the range gets an entry marked as in the wheel or
repo side; the Removed entry lists the incidental module attributes
#504 dropped.

0.6.0 rather than 0.5.5: besides new public API, per-event views now
select two more columns ahead of the event-specific ones, and over an
events table without an attributes column they deploy only with
denied_columns=["attributes"].

No code, dependency or workflow change.

* docs(changelog): scope the non-string ID guarantee to the attributes fallback

The [0.6.0] Span entry said the three correlation IDs stay None on rows
"with non-string values". Span.from_bigquery_row() applies that check
only to values it reads from attributes: a truthy same-named column
value is returned unchanged ({"otel_span_id": 123} gives 123), while a
non-string value in attributes is ignored and gives None. Say that the
attributes fallback ignores non-string values, and that the fields stay
None on rows without those columns or keys.

CHANGELOG wording only; the version stays 0.6.0.
haiyuan-eng-google pushed a commit that referenced this pull request Oct 12, 2026
…523)

Nightly dead-code audit. Deletions only (9 files, +1/-50), no behavior
change. Each removed name had no reference outside its own definition
in any tracked file (code, tests, notebooks, docs, deploy, pyproject):

- _streaming_evaluation: is_launch_trigger_row() and
  DEFAULT_POLL_INTERVAL_MINUTES, both unused since the module landed.
  The scheduler cadence is POLL_SCHEDULE in
  deploy/streaming_evaluation/setup.sh.
- context_graph: _INSERT_BIZ_NODES_QUERY (store_biz_nodes writes with a
  load job) and _CANDIDATES_FOR_SESSION_QUERY (no reader).
- materialize_window: _DEFAULT_GRAPH_NAME_SENTINEL, never read; the
  graph name defaults to graph_name or binding_obj.ontology.
- graph_ddl_compiler._resolve: dead local entity_binding_map.
- resolved_spec.resolve_from_graph_spec: dead local session_col.
  ResolvedEntity has no session-column field; relationships keep theirs.
- scripts/quality_report.py: ThreadPoolExecutor and math imports, left
  behind by #351 and #432. The _embed_texts alias block is unchanged.
- examples: unused imports in e2e_demo.py and context_graph/run_agent.py,
  and an unused _HERE in a2a_joint_lineage_demo/run_analyst_agent.py.

Several of these were deferred as follow-ups in #504.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants