Skip to content

Commit fb790dc

Browse files
authored
fix(roles): classify Python __main__ entrypoints as entry (#2392) (#2411)
* fix(python): resolve module imports to files and aliased module calls (#2387) Python emitted zero `imports` edges, leaving `deps`, `impact` and `map` blind on every Python repo, and `import lib as L` + `L.f()` resolved to nothing, so the callee was reported as dead code. Two defects sat behind that: 1. Neither resolver had a Python branch. A dotted module path is not a filesystem path, so it fell through to the bare-specifier fallback and was echoed back unchanged, matching no file node. Python's relative imports share JS's leading-dot spelling but mean "climb the package tree", so they were mis-resolved by the generic relative branch too. 2. The extractor put the alias in `Import.source` for `import lib as L`, which can never resolve to a file, and `import a, b` collapsed into one record naming only `a`. Resolution derives the import root from package layout — walk up while each level has `__init__.py` — so the PyPA "src layout" and a flat layout work under one rule with no configuration, and honours pyproject-declared roots (`pythonpath`, `package-dir`, poetry `from`, setuptools `where`) for roots no convention implies. Module bindings are now recorded in a new `namespaceBindings` field, which call resolution reads to resolve `L.f()` as "f, as declared in the module L refers to". `from pkg import submod` is resolved as a submodule when `pkg/submod.py` exists, so it both binds a namespace and depends on the module that actually changed rather than only on `pkg/__init__.py`. Mirrored in crates/codegraph-core; both engines verified to produce identical edge sets on the fixtures. * fix(roles): classify Python __main__ entrypoints as entry (#2392) Role classification recognized neither of Python's canonical entrypoint conventions, so a repo whose only entrypoints are Python reported zero `entry` symbols and `codegraph roles --role entry` came back empty — precisely the "where does this start?" question a new agent asks first. Neither existing signal could see them: Python has no `export` keyword, and a guard can sit in any file (`app/oio.py:1786` on data-ingestion-pipe), so no path pattern covers it either. The convention is a property of the call site, not the declaration — a guard routinely invokes a `main` imported from another module — so the extractor flags the call and the build sets a new `nodes.entrypoint` column on whatever that call resolves to. Covered: a call inside an `if __name__ == "__main__":` block anywhere, and a module-level call in a `__main__.py` (`python -m pkg`). Both require module level — a call nested in a function the module defines is invoked by that function, not by the runtime. Entrypoints are also seeded as reachability roots, so the transitive dead-code pass no longer treats a `main()`-only call tree as a dead-code candidate. The column is added in the idempotent ensure-columns block rather than as a numbered migration: a bare ALTER ... ADD COLUMN is not replay-safe against a database stamped back to an earlier schema_version. Mirrored in crates/codegraph-core; both engines verified to agree on the entrypoint flag and the resulting roles. Console-script entrypoints (`[project.scripts]`) are the third convention, tracked as a follow-up in #2408. * fix(roles): scope entrypoint marking to Python files, clear stale cross-file attribution (#2411) Addresses two issues found in Greptile review of #2411: - mark_entrypoint_targets ran an UPDATE-with-JOIN for every file in the build, even though only the Python extractor ever flags a call as an entrypoint. On a full build of this repo (954 files, effectively none Python), that showed up as a 66% full-build regression in the pre-publish benchmark gate (4844ms -> 8032ms, threshold 25%). Scoping the clear/mark queries to `.py` files only is always correct (no other extractor ever sets `call.entrypoint`) and restores full-build time to parity with the pre-#2392 baseline (measured locally: 1986ms vs the 4844ms baseline, native engine, dist build). - Clearing a stale `entrypoint` flag was keyed on the file's *current* outgoing `calls` edges, which cannot find a target declared in a *different* file once that file's guard call is deleted or renamed: the edge is already purged (as part of reprocessing the changed file) by the time the clear query runs. Added `nodes.entrypoint_source_file`, set whenever a target is marked and read back (not re-derived from edges) when clearing, so the clear survives the edge's lifecycle. - That fix alone left `nodes.role` stale even though `nodes.entrypoint` cleared correctly: incremental role classification only reclassifies changed files plus neighbours discovered via a live-edge join, and a cross-file entrypoint target is invisible to that join for the same reason the clear query was — the connecting edge may have just been deleted. mark_entrypoint_targets now returns every touched target's file, which run_role_classification folds into the incremental classification scope alongside removal_reverse_deps (same class of gap as #1027's removal-reverse-deps seeding). Single-file attribution (one entrypoint_source_file per target) doesn't handle two different files both legitimately claiming the same target as their entrypoint; tracked as a follow-up (#2419) rather than solved here with a many-to-many table, since it needs a second target to legitimately share an entrypoint call name. docs check acknowledged: bug fix only, no new language/CLI/architecture surface. * fix(extractors): exclude nested __main__ guards from entrypoint detection (#2411) Greptile review finding on #2411: a `__main__` guard syntactically nested inside a function or class definition is only executed if and when that function is later called — never automatically by the runtime — but visit_entrypoint_calls treated its consequence as module-level regardless. The bug: `guarded` is `false` both at true module level (before any guard is seen) and inside a nested def, so the guard-recognition branch had no way to tell those two situations apart — it sets `guarded`, it doesn't read it. Adds `at_module_level`, a second flag that starts `true` and (unlike `guarded`) never turns back on once a function/class boundary is crossed. A guard's consequence is now only recognized while `at_module_level` holds. docs check acknowledged: bug fix only, no new language/CLI/architecture surface. * fix(roles): mirror Rust's entrypoint scope, staleness, and role-scope fixes (JS/WASM) (#2411) TS/WASM-engine mirror of the same fix landed for the native engine: - Scope markEntrypointTargets's clear/mark statements to `.py` files — call.entrypoint is only ever set by the Python extractor, so running them for every file was a guaranteed no-op for anything else and the source of the 66% full-build regression in the pre-publish benchmark gate (measured locally: 6350ms dev vs the 15537ms wasm baseline — restored to well under baseline, not just under threshold). - Add nodes.entrypoint_source_file (migrations.ts) and use it to clear a stale entrypoint flag, instead of re-deriving the target from the file's current outgoing `calls` edges — which can't find a target declared in a *different* file once the guard call that pointed to it is deleted or renamed, because that edge is already purged by the time the clear query runs. - Add PipelineContext#entrypointTouchedFiles, populated by markEntrypointTargets and folded into classifyRoles's incremental file scope: a touched target's own file is frequently not one of the reparsed files, and classifyNodeRolesIncremental's neighbour-expansion join can't discover it either, for the same live-edge-only reason the clear query couldn't. Without this, nodes.entrypoint clears correctly but the cached nodes.role for the same row stays stale at "entry". docs check acknowledged: bug fix only, no new language/CLI/architecture surface. Impact: 4 functions changed, 12 affected * fix(extractors): exclude nested __main__ guards from entrypoint detection, JS/WASM (#2411) TS/WASM mirror of the Rust fix: a `__main__` guard syntactically nested inside a function or class is only executed if and when that def is later called, never automatically by the runtime, but collectEntrypointCallLines treated its consequence as module-level regardless — `guarded` reads `false` both at true module level and inside a nested def, so the branch that recognizes a guard had no way to tell those two situations apart. Adds `atModuleLevel`, a second flag that starts `true` and (unlike `guarded`) never turns back on once a function/class boundary is crossed. A guard's consequence is now only recognized while it holds. docs check acknowledged: bug fix only, no new language/CLI/architecture surface. Impact: 2 functions changed, 5 affected * test: cover nested __main__ guard exclusion and cross-file entrypoint staleness (#2411) Regression coverage for the two Greptile-review fixes on #2392, run against both engines (native and wasm) via the existing describe.each: - a guard nested inside a function, and one nested inside a class, must not be treated as module level; - an incremental rebuild that deletes a guard whose target lives in a *different* file must clear both nodes.entrypoint and nodes.role on that target, not just the raw flag. docs check acknowledged: test-only change. * fix(extractors): recognize a guard nested in a module-level class body (#2411) Greptile review finding: a class body, unlike a function body, is a normal statement sequence Python executes immediately while evaluating the `class` statement, so a guard directly inside a module-level class body runs exactly when the module does. The at_module_level/atModuleLevel fix landed earlier in this same review round treated class_definition the same as function_definition for "leaves runtime scope", which wrongly excluded this case (and, on inspection, so did the pre-existing `guarded` flag itself, whose reset also included class_definition — the same class of bug repo-wide, not something the at_module_level addition introduced). Both flags now only reset on function_definition. A guard nested inside a class defined inside a function is unaffected and stays excluded — the class's own body only runs once that function is called. docs check acknowledged: bug fix only, no new language/CLI/architecture surface. Impact: 2 functions changed, 5 affected * fix(roles): clear entrypoint attribution owned by a deleted file (#2411, #2425) Greptile review finding, matching a follow-up I had already filed as #2425 before this review round flagged it independently: mark_entrypoint_targets/markEntrypointTargets only iterates fileSymbols — the files actually reparsed this build — to clear a stale entrypoint flag when its attributing call is edited or removed from an existing file. A file that is deleted outright is never a member of fileSymbols in any build, so that clear path never runs for it: a cross-file target attributed to a deleted guard file kept entrypoint=1/role="entry" indefinitely. Added clear_entrypoint_attribution_for_removed_files (Rust) / clearEntrypointAttributionForRemovedFiles (TS), called from the same pre-purge point as the existing capture_removed_file_neighbors / captureRemovedFileNeighbors (#1839) — the last point a removed file's owned data is still live evidence. Returns the cleared targets' files, folded into the same incremental role-reclassification scope removal_reverse_deps/entrypointTouchedFiles already feed. docs check acknowledged: bug fix only, no new language/CLI/architecture surface. Impact: 4 functions changed, 6 affected * test: cover module-level class guards and file-deletion entrypoint staleness (#2411) Regression coverage for the two Greptile findings addressed in the preceding two commits, run against both engines: - a guard nested inside a module-level class body must be marked entry; one nested inside a class defined inside a function must not; - deleting a guard's source file outright (not just editing it) must clear the cross-file target's entrypoint flag and role the same way editing the guard already did. docs check acknowledged: test-only change.
1 parent 12ec6a3 commit fb790dc

16 files changed

Lines changed: 1264 additions & 12 deletions

File tree

‎crates/codegraph-core/src/db/connection.rs‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -921,6 +921,37 @@ impl NativeDatabase {
921921
if !has_column(conn, "nodes", "accessor_kind") {
922922
let _ = conn.execute_batch("ALTER TABLE nodes ADD COLUMN accessor_kind TEXT");
923923
}
924+
// #2392: added here rather than as a numbered migration because a
925+
// bare `ALTER TABLE ... ADD COLUMN` is not replay-safe — a DB
926+
// stamped back to an earlier schema_version (as
927+
// `migration_v28_deletes_pre_existing_duplicate_edges_before_indexing`
928+
// does) would re-run it against a table that already has the
929+
// column and abort the whole upgrade. This block is idempotent by
930+
// construction and runs on every open, so it covers fresh and
931+
// legacy databases alike.
932+
if !has_column(conn, "nodes", "entrypoint") {
933+
let _ =
934+
conn.execute_batch("ALTER TABLE nodes ADD COLUMN entrypoint INTEGER DEFAULT 0");
935+
}
936+
let _ = conn.execute_batch(
937+
"CREATE INDEX IF NOT EXISTS idx_nodes_entrypoint ON nodes(entrypoint) WHERE entrypoint = 1",
938+
);
939+
// #2411 (review fix): the file whose call site attributed the
940+
// current `entrypoint` flag. A rebuild needs this to clear a
941+
// stale flag when the attributing call is deleted or renamed —
942+
// re-deriving from live `calls` edges doesn't work for a target
943+
// declared in a *different* file than the guard, because that
944+
// edge is already purged (as part of reprocessing the changed
945+
// file) by the time the clear query would run. Reading this
946+
// column instead makes the clear correct regardless of the
947+
// edge's lifecycle.
948+
if !has_column(conn, "nodes", "entrypoint_source_file") {
949+
let _ =
950+
conn.execute_batch("ALTER TABLE nodes ADD COLUMN entrypoint_source_file TEXT");
951+
}
952+
let _ = conn.execute_batch(
953+
"CREATE INDEX IF NOT EXISTS idx_nodes_entrypoint_source_file ON nodes(entrypoint_source_file)",
954+
);
924955
let _ = conn.execute_batch(
925956
"UPDATE nodes SET qualified_name = name WHERE qualified_name IS NULL",
926957
);

‎crates/codegraph-core/src/domain/graph/builder/pipeline.rs‎

Lines changed: 154 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,22 @@ fn save_and_purge_changed(
274274
let removed_file_neighbors =
275275
detect_changes::capture_removed_file_neighbors(conn, &change_result.removed);
276276

277+
// Clear entrypoint attribution owned by files about to be removed, for
278+
// the identical reason and at the identical point as the neighbor
279+
// capture just above — a deleted file's own `nodes` rows (source of the
280+
// `entrypoint_source_file` value on its targets) are gone once
281+
// `purge_changed_files` runs below, and `mark_entrypoint_targets` never
282+
// revisits a deleted file (#2425). Folded into `removal_reverse_deps`
283+
// since both exist purely to seed Stage 8's incremental role
284+
// reclassification with files that can no longer be found by that
285+
// stage's own live-edge neighbour discovery.
286+
removal_reverse_deps.extend(
287+
detect_changes::clear_entrypoint_attribution_for_removed_files(
288+
conn,
289+
&change_result.removed,
290+
),
291+
);
292+
277293
// A file about to be (re)inserted can no longer be "deleted" — clear any
278294
// stale advisory left over from a prior removal at this same path before
279295
// capturing this build's actual removals, and before purging deletes the
@@ -437,6 +453,129 @@ fn run_structure_phase(
437453
}
438454
}
439455

456+
/// Set `nodes.entrypoint` on whatever the extractor's entrypoint-flagged calls
457+
/// resolved to (#2392) — Python's `if __name__ == "__main__":` guard and
458+
/// `__main__.py` module level.
459+
///
460+
/// Identifies targets from the committed `calls` edges: an entrypoint call is
461+
/// module-level by construction (see `collect_entrypoint_call_lines`), so its
462+
/// edge is always sourced from the file node, and matching that edge's target
463+
/// by the called name identifies it.
464+
///
465+
/// Cleared per file first via `entrypoint_source_file` — the file whose call
466+
/// site last attributed the flag — rather than by re-querying the file's
467+
/// current outgoing `calls` edges: when a guard's target is declared in a
468+
/// *different* file and the guard is later deleted or renamed, the old edge
469+
/// is already purged (as part of reprocessing the changed file) by the time
470+
/// this runs, so a query keyed on live edges can never find it again to
471+
/// clear it (review finding on #2411). The attribution column has no such
472+
/// lifecycle dependency — it is set directly on the target and only ever
473+
/// read back for the exact file that set it.
474+
///
475+
/// Scoped to `.py` files: `call.entrypoint` is only ever set by the Python
476+
/// extractor (`mark_entrypoint_calls`), so a non-Python file can never have
477+
/// contributed an entrypoint attribution in this build or any earlier one —
478+
/// running the clear/mark queries for it is always a guaranteed no-op.
479+
/// Skipping them is what keeps this stage O(python files) instead of O(all
480+
/// files); running an UPDATE per file unconditionally showed up as a 66%
481+
/// full-build regression on a 954-file, effectively-Python-free tree (#2411
482+
/// CI).
483+
///
484+
/// Note: attribution is single-owner (one `entrypoint_source_file` per
485+
/// target). If two different files both legitimately call the same target as
486+
/// their entrypoint, whichever marks it last wins the attribution, and the
487+
/// other file's later removal won't clear it (harmless — the target simply
488+
/// stays correctly flagged) but its own removal will. Tracked as a follow-up
489+
/// (#2419) rather than solved here with a many-to-many table, since it needs
490+
/// a second target to legitimately share an entrypoint call name, which is
491+
/// unusual enough not to hold up this fix.
492+
///
493+
/// Returns the files any touched target lives in, so the caller can fold them
494+
/// into the incremental role-classification scope (see the call site in
495+
/// `run_role_classification`): a target's own file is frequently *not* the
496+
/// file being rebuilt (that's the whole cross-file case above), and
497+
/// `find_neighbour_files`'s live-edge join can't discover it either, for the
498+
/// identical reason the clear query couldn't — the edge that would connect
499+
/// them may have just been deleted. Without this, `nodes.entrypoint` clears
500+
/// correctly but the cached `nodes.role` for the same row is left stale at
501+
/// `"entry"`, same class of bug as #1027's removal-reverse-deps seeding.
502+
///
503+
/// Mirrors `markEntrypointTargets` in stages/build-edges.ts.
504+
fn mark_entrypoint_targets(
505+
conn: &Connection,
506+
file_symbols: &BTreeMap<String, FileSymbols>,
507+
) -> HashSet<String> {
508+
let mut touched_files: HashSet<String> = HashSet::new();
509+
if !file_symbols.keys().any(|f| f.ends_with(".py")) {
510+
return touched_files;
511+
}
512+
513+
let Ok(mut find_stale) =
514+
conn.prepare("SELECT file FROM nodes WHERE entrypoint_source_file = ?1")
515+
else {
516+
return touched_files;
517+
};
518+
let Ok(mut clear) = conn.prepare(
519+
"UPDATE nodes SET entrypoint = 0, entrypoint_source_file = NULL
520+
WHERE entrypoint_source_file = ?1",
521+
) else {
522+
return touched_files;
523+
};
524+
let Ok(mut find_targets) = conn.prepare(
525+
"SELECT tgt.file FROM edges e
526+
JOIN nodes src ON e.source_id = src.id
527+
JOIN nodes tgt ON e.target_id = tgt.id
528+
WHERE e.kind = 'calls' AND src.kind = 'file' AND src.file = ?1
529+
AND (tgt.name = ?2 OR tgt.name LIKE ?3)",
530+
) else {
531+
return touched_files;
532+
};
533+
let Ok(mut mark) = conn.prepare(
534+
"UPDATE nodes SET entrypoint = 1, entrypoint_source_file = ?1
535+
WHERE id IN (
536+
SELECT e.target_id FROM edges e
537+
JOIN nodes src ON e.source_id = src.id
538+
JOIN nodes tgt ON e.target_id = tgt.id
539+
WHERE e.kind = 'calls' AND src.kind = 'file' AND src.file = ?1
540+
AND (tgt.name = ?2 OR tgt.name LIKE ?3)
541+
)",
542+
) else {
543+
return touched_files;
544+
};
545+
546+
for (rel_path, symbols) in file_symbols {
547+
if !rel_path.ends_with(".py") {
548+
continue;
549+
}
550+
551+
if let Ok(rows) =
552+
find_stale.query_map(rusqlite::params![rel_path], |row| row.get::<_, String>(0))
553+
{
554+
touched_files.extend(rows.filter_map(|r| r.ok()));
555+
}
556+
let _ = clear.execute(rusqlite::params![rel_path]);
557+
558+
let mut seen: HashSet<&str> = HashSet::new();
559+
for call in &symbols.calls {
560+
if !call.entrypoint.unwrap_or(false) || !seen.insert(call.name.as_str()) {
561+
continue;
562+
}
563+
// A method entrypoint (`Runner().start()`) is declared as
564+
// `Owner.start`, so match the bare name or any `*.name` form.
565+
let suffix = format!("%.{}", call.name);
566+
if let Ok(rows) = find_targets
567+
.query_map(rusqlite::params![rel_path, call.name, &suffix], |row| {
568+
row.get::<_, String>(0)
569+
})
570+
{
571+
touched_files.extend(rows.filter_map(|r| r.ok()));
572+
}
573+
let _ = mark.execute(rusqlite::params![rel_path, call.name, suffix]);
574+
}
575+
}
576+
touched_files
577+
}
578+
440579
/// Stage 8 (roles): classify roles for the affected file set. Removal
441580
/// reverse-deps need to be seeded explicitly because their fan-in/out can
442581
/// no longer be discovered via neighbour expansion once the deleted file's
@@ -447,17 +586,26 @@ fn run_role_classification(
447586
removal_reverse_deps: Vec<String>,
448587
is_full_build: bool,
449588
) {
589+
// Program-entrypoint flags must be current before roles are computed, and
590+
// the edges they are derived from are complete by this stage — the same
591+
// position the TS path uses (end of `buildEdges`, before `buildStructure`).
592+
// The returned files are folded in below alongside `removal_reverse_deps`
593+
// — same reason: a touched target's role can't be trusted to be
594+
// rediscovered by neighbour expansion.
595+
let entrypoint_touched_files = mark_entrypoint_targets(conn, file_symbols);
596+
450597
let changed_files: Vec<String> = file_symbols.keys().cloned().collect();
451598
let changed_file_list: Option<Vec<String>> = if is_full_build {
452599
None
453600
} else {
454601
let mut files = changed_files;
455-
if !removal_reverse_deps.is_empty() {
456-
let existing: HashSet<String> = files.iter().cloned().collect();
457-
for f in removal_reverse_deps {
458-
if !existing.contains(&f) {
459-
files.push(f);
460-
}
602+
let mut seen: HashSet<String> = files.iter().cloned().collect();
603+
for f in removal_reverse_deps
604+
.into_iter()
605+
.chain(entrypoint_touched_files)
606+
{
607+
if seen.insert(f.clone()) {
608+
files.push(f);
461609
}
462610
}
463611
Some(files)

‎crates/codegraph-core/src/domain/graph/builder/stages/detect_changes.rs‎

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -881,6 +881,55 @@ pub fn capture_removed_file_neighbors(conn: &Connection, removed_files: &[String
881881
neighbors.into_iter().collect()
882882
}
883883

884+
/// Clears `nodes.entrypoint`/`entrypoint_source_file` attribution owned by
885+
/// files about to be removed, BEFORE `purge_changed_files` deletes the
886+
/// `nodes` rows those files own — and returns the *targets'* files, so the
887+
/// caller can fold them into incremental role reclassification the same way
888+
/// `removal_reverse_deps` already is.
889+
///
890+
/// `mark_entrypoint_targets` (pipeline.rs) only iterates `file_symbols` — the
891+
/// files actually reparsed this build — to clear a stale entrypoint flag when
892+
/// its attributing call is edited or removed from an existing file. A file
893+
/// that is deleted outright is never a member of `file_symbols` in any build,
894+
/// so that clear never runs for it: a cross-file target attributed to a
895+
/// deleted guard file would keep `entrypoint = 1` and `role = "entry"`
896+
/// indefinitely (review finding on #2411, tracked as #2425 before Greptile
897+
/// flagged it independently in the same review round). Reading and clearing
898+
/// here, one step earlier in the pipeline — mirroring
899+
/// `capture_removed_file_neighbors` immediately above — closes that gap the
900+
/// same way it closes the analogous one for directory metrics. Mirrors
901+
/// `clearEntrypointAttributionForRemovedFiles` in `detect-changes.ts`.
902+
pub fn clear_entrypoint_attribution_for_removed_files(
903+
conn: &Connection,
904+
removed_files: &[String],
905+
) -> Vec<String> {
906+
if removed_files.is_empty() {
907+
return Vec::new();
908+
}
909+
910+
let mut touched_files: HashSet<String> = HashSet::new();
911+
let Ok(mut find_stmt) =
912+
conn.prepare("SELECT file FROM nodes WHERE entrypoint_source_file = ?1")
913+
else {
914+
return Vec::new();
915+
};
916+
let Ok(mut clear_stmt) = conn.prepare(
917+
"UPDATE nodes SET entrypoint = 0, entrypoint_source_file = NULL
918+
WHERE entrypoint_source_file = ?1",
919+
) else {
920+
return Vec::new();
921+
};
922+
923+
for f in removed_files {
924+
if let Ok(rows) = find_stmt.query_map([f], |row| row.get::<_, String>(0)) {
925+
touched_files.extend(rows.flatten());
926+
}
927+
let _ = clear_stmt.execute([f]);
928+
}
929+
930+
touched_files.into_iter().collect()
931+
}
932+
884933
/// True if `table` can be queried without error. Used for
885934
/// `deleted_export_advisories` (added in migration v21), which an older,
886935
/// not-yet-migrated schema may not have.
@@ -1577,6 +1626,8 @@ mod tests {
15771626
file TEXT NOT NULL,
15781627
line INTEGER,
15791628
content_hash TEXT,
1629+
entrypoint INTEGER DEFAULT 0,
1630+
entrypoint_source_file TEXT,
15801631
UNIQUE(name, kind, file, line)
15811632
);
15821633
CREATE TABLE edges (
@@ -1982,6 +2033,69 @@ mod tests {
19822033
assert!(neighbors.is_empty());
19832034
}
19842035

2036+
// ── clear_entrypoint_attribution_for_removed_files (#2425) ──────────
2037+
2038+
#[test]
2039+
fn clears_entrypoint_attribution_owned_by_a_removed_file() {
2040+
// shared_main lives in lib.py but is attributed to run.py's guard —
2041+
// deleting run.py must clear shared_main's flag even though the
2042+
// target itself is untouched.
2043+
let conn = test_conn();
2044+
let target = insert_node(&conn, "shared_main", "function", "lib.py", 1);
2045+
conn.execute(
2046+
"UPDATE nodes SET entrypoint = 1, entrypoint_source_file = 'run.py' WHERE id = ?1",
2047+
[target],
2048+
)
2049+
.unwrap();
2050+
2051+
let touched =
2052+
clear_entrypoint_attribution_for_removed_files(&conn, &["run.py".to_string()]);
2053+
assert_eq!(touched, vec!["lib.py".to_string()]);
2054+
2055+
let (entrypoint, source_file): (i64, Option<String>) = conn
2056+
.query_row(
2057+
"SELECT entrypoint, entrypoint_source_file FROM nodes WHERE id = ?1",
2058+
[target],
2059+
|row| Ok((row.get(0)?, row.get(1)?)),
2060+
)
2061+
.unwrap();
2062+
assert_eq!(entrypoint, 0);
2063+
assert_eq!(source_file, None);
2064+
}
2065+
2066+
#[test]
2067+
fn does_not_touch_attribution_owned_by_a_file_that_is_not_removed() {
2068+
let conn = test_conn();
2069+
let target = insert_node(&conn, "shared_main", "function", "lib.py", 1);
2070+
conn.execute(
2071+
"UPDATE nodes SET entrypoint = 1, entrypoint_source_file = 'run.py' WHERE id = ?1",
2072+
[target],
2073+
)
2074+
.unwrap();
2075+
2076+
let touched =
2077+
clear_entrypoint_attribution_for_removed_files(&conn, &["unrelated.py".to_string()]);
2078+
assert!(touched.is_empty());
2079+
2080+
let entrypoint: i64 = conn
2081+
.query_row(
2082+
"SELECT entrypoint FROM nodes WHERE id = ?1",
2083+
[target],
2084+
|row| row.get(0),
2085+
)
2086+
.unwrap();
2087+
assert_eq!(
2088+
entrypoint, 1,
2089+
"unrelated removal must not clear a live attribution"
2090+
);
2091+
}
2092+
2093+
#[test]
2094+
fn clear_entrypoint_attribution_empty_for_no_removed_files() {
2095+
let conn = test_conn();
2096+
assert!(clear_entrypoint_attribution_for_removed_files(&conn, &[]).is_empty());
2097+
}
2098+
19852099
// ── deleted-export advisories (#1938) ───────────────────────────────
19862100

19872101
/// Schema for the advisory tests: `test_conn()` plus the `exported`

0 commit comments

Comments
 (0)