Skip to content

_check_shrink: on a full rebuild every lost node is "accounted", so an extractor that errors out silently shrinks the graph instead of refusing the write #2660

Closed

Description

On a full rebuild every source file is in rebuilt_sources, so _check_shrink's _accounted() returns True for every lost node — including nodes lost because an extractor bailed out with {"error": ...} rather than because the symbol was legitimately removed. The guard's own docstring says it exists to catch "SILENT shrinkage from failed extraction chunks", and this is exactly that case, but it is waved through and the smaller graph is written.

The rebuild reports success and _rebuild_code returns True.

Reproduction

graphifyy 0.9.27, Python 3.12.13, Windows 10. GRAPHIFY_MAX_WORKERS=1, force=False throughout.

Repo with two files:

# app.py
def alpha(): return beta()
def beta(): return 1
-- schema.sql
create table cliente (id int primary key, nombre text);
create table lead (id int primary key, cliente_id int references cliente(id));
create view lead_full as select * from lead join cliente on cliente.id = lead.cliente_id;
  1. Normal rebuild → 7 nodes, 4 of them from schema.sql.
  2. Delete graphify-out/cache/ only, keeping graph.json (so existing_data is present).
  3. Rebuild again with tree_sitter_sql made unimportable, to force extract_sql down its ImportError branch:
import sys
class Blocker:
    def find_spec(self, name, path=None, target=None):
        if name == 'tree_sitter_sql':
            raise ImportError("tree_sitter_sql not installed (simulated)")
        return None
sys.meta_path.insert(0, Blocker())

from graphify.watch import _rebuild_code
from pathlib import Path
print(_rebuild_code(Path("."), force=False))

Result:

[graphify watch] Rebuilt: 3 nodes, 3 edges, 1 communities
[graphify watch] graph.json, graph.html and GRAPH_REPORT.md updated in ...
warning: 1 .sql file(s) contributed nothing to the graph because a dependency is
  missing: tree_sitter_sql not installed. ... (#1745)
_rebuild_code returned: True

graph.json on disk goes from 7 nodes to 3, losing all 4 SQL nodes. No "Refusing to overwrite" warning. Blocking the import is only a deterministic stand-in for the real trigger — see below.

Why the guard misses it

def _accounted(n: dict) -> bool:
    sf = n.get("source_file")
    return (not sf
            or sf in rebuilt_sources
            or _norm_source_file(sf) in rebuilt_sources)
if all(_accounted(n) for n in lost):
    return True

rebuilt_sources is "the set of source files re-extracted this run". On a full rebuild that is every file, so all(_accounted(...)) is vacuously satisfied and the guard returns True before reaching the refusal path. The per-source accounting added in #1116 / #2056 correctly stops legitimate refactors from needing --force, but it cannot distinguish "this file was re-extracted and the symbol is genuinely gone" from "this file was re-extracted and the extractor failed".

The information needed is already there

The same run already knows which files failed: per_file[i]["error"] is what #1745 reads to emit the contributed nothing ... dependency is missing warning. So the two facts sit side by side in one run — "these files produced an error" and "these nodes disappeared" — and are never joined.

A minimal fix would be to treat a file whose extraction returned an error as not accounted, so its lost nodes fall through to the refusal path:

def _accounted(n: dict) -> bool:
    sf = n.get("source_file")
    if sf and _norm_source_file(sf) in errored_sources:
        return False          # extraction failed — loss is not explained
    return (not sf
            or sf in rebuilt_sources
            or _norm_source_file(sf) in rebuilt_sources)

That keeps the #1116 behaviour for genuine deletions while restoring the guard for the failure mode it was written for. A weaker alternative would be to skip the whole shrink bypass whenever any file in the run carries an error.

How I hit this in the real world

Not synthetic. A repo of 124 files with 8 tracked .sql files rebuilds through the post-commit hook. Under parallel extraction (max_workers = os.cpu_count() = 8 here), the workers intermittently fail to import the native tree_sitter_sql extension, extract_sql reports that ImportError as "not installed", and the graph is written with zero SQL nodes:

Mode Nodes .sql nodes Warning
Parallel, 8 workers 310 0 tree_sitter_sql not installed
GRAPHIFY_MAX_WORKERS=1 364 54 none

Same interpreter, same files, force=False in both. tree_sitter_sql is installed and works — calling extract_sql directly on those files returns 15/6/3 nodes with no error.

The worker-side import failure is its own separate problem and I am not asking for it to be fixed here. The reason it is worth mentioning is that the shrink guard is precisely the net meant to stop a flaky extractor from reaching disk, and it did not: the degraded graph was written and the loss went unnoticed across several commits. It stayed invisible because the graph still looked plausible — only a later diff showed the entire database layer was gone.

Suggested severity

Data-loss-adjacent rather than a crash: no error surfaces, exit status is success, and the previous good graph is overwritten. The graphify-out/<date>/ backup is what makes it recoverable.

Activity

  1. safishamsi commented on Aug 12, 2026

    @safishamsi
    Member

    Fixed in v0.9.41 (graphifyy==0.9.41 on PyPI). graphify update now refuses to overwrite the graph with a shrunken one when the shrink was caused by an extractor failure this run (the #2543 failed_sources set is threaded into the shrink guard), so a transient extractor failure can no longer silently replace good data; a genuine deletion still shrinks the graph. Thanks @ousamabenyounes (PR #2663).

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