Skip to content

SQL extractor emits reads_from edges to bare, unqualified stub IDs that collide across languages #2577

Closed

Description

@scademir

Summary

The SQL extractor emits reads_from edges to bare, unqualified stub node IDs (slug, name, position, levels, public). Because those IDs carry no schema, file, or language namespace, they collide with same-named nodes from other languages during the build. In our repo a SQL column named slug bound to a TypeScript function slug() in a .tsx file, producing a phantom SQL→TypeScript edge marked [EXTRACTED].

That single phantom edge became the highest-betweenness node in a 9,294-node graph (0.106) — because it was one of the only paths between the SQL half and the TypeScript half, every cross-language shortest path routed through it. GRAPH_REPORT.md then surfaced it as the #1 "Suggested Question," i.e. the tool's headline insight was its own extraction bug.

Version: graphifyy 0.9.37 · Windows 11 · Python 3.14 · extraction is AST-only (no LLM).

Three distinct defects

1. A CTE name is emitted as a table reads_from target.
with levels(role, lvl) as (values ...) → two reads_from edges to a stub named levels. A CTE is not a table.

2. An INSERT column list is parsed as table references.

insert into public.stages (organization_id, pipeline_id, name, slug, position, is_won, is_lost)

emits six reads_from edges — one per column — each to a stub named after the column, as if it were a table.

3. The edge is attributed to the wrong enclosing function.
All of the above are credited to fn_role_at_least(), which ends 28 lines above the statement. The statement lives in a different function entirely (fn_seed_stages()). The enclosing object appears to resolve to the last CREATE FUNCTION seen before the parse failure rather than the one containing the line — so source_location and the edge's source node disagree.

All are labeled [EXTRACTED], the highest-confidence tier. The audit trail distinguishes "read from the AST" from "model-reasoned" (INFERRED), and these name-resolution guesses land in the wrong bucket — which is what let a phantom edge pass review.

Reproducer A — minimal, synthetic (defects 1 and 3)

schema.sql:

CREATE OR REPLACE FUNCTION "public"."fn_role_at_least"("p_min" "text") RETURNS boolean
    LANGUAGE "sql" STABLE
    AS $$
  with levels(role, lvl) as (
    values ('viewer',1),('admin',4)
  )
  select coalesce(
    (select user_lvl.lvl >= min_lvl.lvl
     from levels user_lvl
     join levels min_lvl on min_lvl.role = p_min),
    false
  );
$$;
from pathlib import Path
from graphify.extract import extract
res = extract([Path("schema.sql")], cache_root=Path("."), parallel=False)
for e in res["edges"]:
    if e.get("relation") == "reads_from":
        print(e["source"], "->", repr(e["target"]), e["confidence"], e["source_location"])

Actual:

..._fn_role_at_least -> 'levels' EXTRACTED L9
..._fn_role_at_least -> 'levels' EXTRACTED L10

Expected: no reads_from edge (levels is a CTE), or an edge to a CTE-scoped node ID that cannot collide.

Reproducer B — cross-language binding (all three defects)

Same schema.sql as above, plus a second function below it whose PL/pgSQL body contains an INSERT with a column named slug, and a sibling ui.tsx:

function slug(t: string): string { return t.toLowerCase(); }
export function NavHub() { return slug("hello"); }

Extracting both files together yields:

'"public"."fn_role_at_least"()' --reads_from--> id='pipeline_id' [EXTRACTED] L52
'"public"."fn_role_at_least"()' --reads_from--> id='name'        [EXTRACTED] L52
'"public"."fn_role_at_least"()' --reads_from--> id='ui_slug'     [EXTRACTED] L52   <-- the .tsx function
'"public"."fn_role_at_least"()' --reads_from--> id='position'    [EXTRACTED] L52
'"public"."fn_role_at_least"()' --reads_from--> id='is_won'      [EXTRACTED] L52
'"public"."fn_role_at_least"()' --reads_from--> id='is_lost'     [EXTRACTED] L52

Note id='ui_slug' — with the .tsx absent the target is the bare stub 'slug'; with it present the SQL "table" reference binds directly to the TypeScript function node. The stub is not merely unqualified, it actively resolves across languages.

The exact 61-line SQL slice that produces this is attached below; it is ordinary Postgres DDL (a trigger that seeds default pipeline stages).

schema.sql slice for Reproducer B
CREATE OR REPLACE FUNCTION "public"."fn_role_at_least"("p_org" "uuid", "p_min" "text") RETURNS boolean
    LANGUAGE "sql" STABLE SECURITY DEFINER
    SET "search_path" TO 'public'
    AS $$
  with levels(role, lvl) as (
    values ('viewer',1),('agent',2),('manager',3),('admin',4)
  )
  select coalesce(
    (select user_lvl.lvl >= min_lvl.lvl
     from levels user_lvl
     join levels min_lvl on min_lvl.role = p_min
     where user_lvl.role = public.fn_user_role_in_org(p_org)),
    false
  );
$$;


ALTER FUNCTION "public"."fn_role_at_least"("p_org" "uuid", "p_min" "text") OWNER TO "postgres";


CREATE OR REPLACE FUNCTION "public"."fn_seed_default_pipeline_for_org"() RETURNS "trigger"
    LANGUAGE "plpgsql"
    SET "search_path" TO 'public', 'pg_temp'
    AS $$
declare
  v_pipeline_id uuid;
  v_position numeric := 1000;
  r record;
begin
  insert into public.crm_pipelines (organization_id, name, slug, is_default, position)
  values (new.id, 'Orders', 'orders', true, 1000)
  returning id into v_pipeline_id;

  for r in
    select * from (values
      ('Abandoned cart', 'abandoned_cart', false, false),
      ('Awaiting payment', 'awaiting_payment', false, false),
      ('Paid', 'paid', true, false),
      ('Cancelled', 'cancelled', false, true)
    ) as t(stage_name, stage_slug, won, lost)
  loop
    insert into public.crm_stages (organization_id, pipeline_id, name, slug, position, is_won, is_lost)
    values (new.id, v_pipeline_id, r.stage_name, r.stage_slug, v_position, r.won, r.lost);
    v_position := v_position + 1000;
  end loop;

  return new;
end$$;


ALTER FUNCTION "public"."fn_seed_default_pipeline_for_org"() OWNER TO "postgres";

Where it comes from

graphify/extractors/sql.py:

  • _walk_from_refs (~L304-316) and the fb_proc_or_trigger branch (~L288-299) resolve a reference with table_nids.get(_norm_ident(tbl)) or _ref_stub(tbl). The _ref_stub fallback produces an unqualified global ID, which is what enables the cross-file, cross-language collision.

  • The ERROR branch already documents this exact hazard and opts out (~L244):

    "We deliberately do not scan the body for FROM/JOIN references: PL/pgSQL loop variables and locals would produce junk reads_from targets."

    The fb_proc_or_trigger branch and _walk_from_refs do scan, so the hazard the comment describes lands anyway through the other path.

Scale in a real corpus

Extracting one 7k-line baseline.sql alone: 217 nodes, 53 of them stubs (24%). Nine have bare, collision-prone names: contacts, levels, messages, name, organizations, position, public, slug, ttfr. Every one of those is a live collision risk against any TypeScript/Python identifier of the same name — and name, position, and slug are about as common as identifiers get.

Suggested fixes (in impact order)

  1. Namespace stub IDs — e.g. sqlstub:<schema>.<name> — so an unresolved SQL reference can never bind to a node from another language. This alone removes the false edge.
  2. Don't treat an INSERT column list as table references; only the target relation of INSERT INTO <relation> is a table.
  3. Register CTE names (WITH <name> AS) in a per-statement scope and exclude them from table resolution.
  4. Fix enclosing-object attribution so the edge's source node and its source_location cannot disagree — or drop the edge when they do.
  5. Downgrade name-resolution guesses to INFERRED. The EXTRACTED/INFERRED split is the main reason to trust this tool's output; a resolution guess presented as a parsed fact is the part that made this hard to catch.

Activity

  1. safishamsi commented on Aug 9, 2026

    @safishamsi
    Member

    Fixed in v0.9.38. A WITH cte AS (...) name is now scoped to its query and no longer emitted as a reads_from table target, so it no longer mints a bare stub that could bind to an unrelated same-named symbol in another language. An outer real table sharing a subquery-CTE`s name still resolves. Thanks @wilyan09007 for the fix (PR #2579).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions