Repository navigation
audit: drop unused imports from 11 src modules (nightly) - #504
haiyuan-eng-google merged 1 commit into
Conversation
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
left a comment
There was a problem hiding this comment.
Blind independent Astra review of head 7a9e22a47dc0bdbb1495c7b1b68291ace540409c against main at 6e536dc81ae58640a27842c3f043a9bf5e88b9a5.
Rejection criteria established before reading the description/diff:
- 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.
- Deleting an import changes an availability gate, import side effect, or reachable runtime behavior, including function-local imports and runtime annotations.
- 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
left a comment
There was a problem hiding this comment.
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.patchstring 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 ImportErrorflag, 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
7a9e22ais 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.
- 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. - 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
.pyfile (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 byX.<name>; patch.object,setattr,getattr,hasattr,delattrormonkeypatchon a touched module, including dynamic names;importlib,__import__andsys.modulesuse;vars,dir,getmembersor__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 grepover all tracked file types for<module>.<name>finds onlyinsights.jsonindocs/proposal_bigquery_agent_cli.md:541, which is an output filename. Every stringmock.patchtarget on a touched module iscli._build_client,cli._build_view_manager,ontology_materializer.OntologyMaterializerorontology_materializer.make_bq_client. All in-repo imports ofResolvedProperty,PropertyBinding,CompileResultandResolvedGraphgo through their canonical modules (resolved_spec,bigquery_ontology/binding_models, and theextractor_compilationpackage). -
None of the touched files defines
__all__, nothing star-imports them, and the onlysys.modulesalias istrace_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.
-
- 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_hintson every class, function, method and property defined in the 11 modules. For every model I also randataclasses.fields, checked__pydantic_complete__and ranmodel_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--helpthrough 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 missescli.py:202/211/216/243). I ranfeedback.compute_question_distributionagainst a fake BQ client in every mode:frequently_askedandfrequently_unanswered, which the suite never reaches (feedback.py:691/702uncovered);- 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_specandgoogle.cloud.bigqueryare already insys.modulesoncecli/feedbackare imported, and google-cloud-bigquery is a hard dependency. -
I tested the
ttl_importergate with rdflib present, withrdflibblocked, and withrdflib.namespaceblocked._RDFLIB_AVAILABLEand the_require_rdflib()ImportError message are the same on base and head in all three cases. -
For
measurement.py:extractor_compilation/__init__.py:59-61imports.compilerbefore.measurement(:70), andcompiler.pyhas no import-time side effects.
-
- Full test suite.
pytest --tb=short -qwith the CI extras gives 5278 passed / 83 skipped on base, and the same on head.- With the
owlextra 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_importercoverage.
- Formatting, using the CI pins (pyink 25.12.0, isort 9.0.2).
- On the 11 changed files,
pyink --checkreports them unchanged andisort --check-onlyreturns 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 examplesclaim checks out: 361 files unchanged.git diff --checkis clean.
- On the 11 changed files,
- CI.
- Run 36848488492 has
head_sha7a9e22a and is green: Format, Test 3.10–3.14, Build, Configurator smoke, CLA, scan-pr and check-changes. zizmor was skipped. - The merge ref
af7be79has the same tree (56ca7e1) as7a9e22a, because main is still6e536dc. - Every Test job log reports 5280 passed / 81 skipped. That matches the main push run 36748361857 for
6e536dcon each Python version. vulture src --min-confidence 60prints 272 lines on both sides, identical apart from line numbers.
- Run 36848488492 has
Findings
P0 / P1: none.
P2: none.
P3 (non-blocking; I'm not asking for changes in this PR):
cli.py:191-> "ResolvedGraph"is still an unresolvable forward reference. Ruff reports F821 on base and on head, andget_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-levelif TYPE_CHECKING:import. The same pattern already exists atontology_materializer.py:489-490("Ontology","Binding") andttl_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.- CI installs only
.[dev,streamlit], without theowlextra, so the rdflib-backed tests are skipped in CI. Under the CI extrasttl_importer.pyis 17% covered. As a result, the PR's pytest and CI evidence doesn't exercise theXSDremoval. I ran those tests with rdflib (results above, clean). This is a CI coverage gap to handle separately, not a defect in this PR. - 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-32andtests/test_cli.py(8 sites) import these names fromontology_models. Pyflakes also flags two unused locals in touched files, both outside this PR's scope:graph_ddl_compiler.py:109entity_binding_map(already listed in the PR) andcli.py:1206matched(deliberatelydel'd, with a comment explaining why). - These were importable module attributes, so code like
from bigquery_ontology.graph_ddl_compiler import PropertyBindingwould 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
…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.
…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.
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, Xbecomesfrom 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 jsonnever shows up there.ruff --select F401checks each file, which is how these were found.Removed (16 names)
ai_ml_integration.py:62datetime.timedeltacli.py:197.resolved_spec.ResolvedGraphin_load_spec_from_argseval_validator.py:36dataclasses.fieldextractor_compilation/diagnostics.py:75typing.Anyextractor_compilation/measurement.py:52.compiler.CompileResult(the package__init__still imports.compilerfirst)feedback.py:34-36, 691dataclass,field,json, and a function-localgoogle.cloud.bigqueryinsights.py:40, 42, 45asyncio,dataclass,jsonontology_materializer.py:79.resolved_spec.ResolvedPropertyontology_models.py:42typing.Anyttl_importer.py:57rdflib.XSD(the other rdflib imports still gate_RDFLIB_AVAILABLE)bigquery_ontology/graph_ddl_compiler.py:61.binding_models.PropertyBindingHow each one was proven unused
ruff check --select F401flags the name in its own file.An AST and text scan of every tracked file (
git ls-files) found none of the following:<module>.<name>patch.object/setattr/getattr/monkeypatchon it"bigquery_agent_analytics.feedback.json".md,.ipynb,.yaml,.tomlor.shfiles, including indocs/,deploy/,producers/andplugins/The only text hit was
insights.jsonindocs/proposal_bigquery_agent_cli.md:541, which is an output filename (> insights.json).A second pass looked for bare-string name lists and non-constant
getattrcalls in files that touch each module. It found nothing for the removed names.tests/test_pr123_performance_regressions.py:369-370. Those reach the shim exports throughgetattrover a list of names.The touched modules have no
__all__, no star-imports, and nosys.modulesaliasing. The only alias insrc/istrace_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 thetrace_evaluatorshim and asserted attests/test_pr123_performance_regressions.py:369-370.ontology_models.py:169-172(Extracted*): re-exports imported fromontology_models(tests/test_ontology_models.py:29and others).client.py:86AI_GENERATE_JUDGE_BATCH_QUERY: compat alias added in feat: unify performance evaluation with compatible evaluator APIs #123 and named indocs/design.md:285.__init__.pyhits: these are public re-exports.Found but not changed here (follow-ups, outside this PR's import-only scope)
resolved_spec.py:496session_col(F841): computed frombinding.from_session_columnand 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:109entity_binding_map(F841): referenced only at its definition.owl_importer.py:1114parsed: thefloat(value)call is a validity probe; only the name is unused. Keep._streaming_evaluation.py:144is_launch_trigger_row: no caller insrc/,tests/,deploy/ordocs/.scripts/quality_report.py:55,59,353imports 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.pyandexamples/context_graph/run_agent.py: unused imports.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 withpip install -e ".[dev,streamlit]\"(the same extras as CI). "Before" ismainat6e536dc; "after" is this branch.pytest --tb=short -q(full suite, as inci.yml)ruff check --select F401,F841,F811 src scripts examples testsvulture src --min-confidence 60importof the 11 touched modules plus both packagesbq-agent-sdk / bqaa / gm / bqaa-revalidate-extractors --helpFormat, matching the CI pins (
pyink>=24.3.0,<26gives 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 examplesreports 361 files unchanged.isort --check-only src tests scripts examplesreturns rc=0.git diff --checkis 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
mainpush run for6e536dc(36748361857), so no test was lost or newly skipped.No version bump, no CHANGELOG edit, and no reviewers requested.
🤖 Generated with Claude Code