Skip to content

[Bug]: ollama + library path silently drops ~96% of edges: no source_file backfill, on_chunk_done fires after the checkpoint and without the chunk's allowlist, #2973 recovery is case-sensitive, and MAX_OUTPUT_TOKENS is inert #3982

Open

Description

@Rasco94

Pre-flight checks

What happened?

We run graphify nightly over a ~21k-document corpus (Markdown + PDF, mostly Italian prose, not code) with a small local model, calling extract_corpus_parallel() as a library rather than through the CLI. The resulting graphs are far emptier than the extraction work we pay for. The gap traces to four separate things on the ollama/cache path. They compound, so I am filing them together — happy to split if you prefer.

Expected: a chunk the model answered successfully persists its nodes and its edges, or says what it dropped.
Actual: on this backend a successful chunk routinely persists nothing at all, silently, and is re-extracted and dropped again the next night.

Across our nightly logs, 394 of 1163 completed chunks persisted zero cache entries (33.9%), each logged as a success.


1. Nothing backfills source_file on edges, and save_semantic_cache drops every item without one

The extraction schema asks the model for source_file on nodes and edges (llm.py:510). A small local model fills it on nodes and forgets it on edges. Measured on our corpus with qwen2.5:14b: nodes 99%, edges 4%.

save_semantic_cache groups by that field and skips anything missing it (cache.py:1463-1477):

for e in edges:
    e = _normalized(e)
    src = e.get("source_file", "")
    if src:
        by_file[src]["edges"].append(e)

No else, no counter, no warning. 96% of the edges the model just produced never reach the cache. On the next incremental run those files are cache hits — with almost no edges — so the loss is permanent, not retried.

The information needed to repair this is already in hand and costs no model call: an edge's source/target are node ids from the same chunk, and those nodes do carry source_file. A deterministic pass took our edge coverage from 4% to 99%:

nsrc = {n["id"]: n["source_file"] for n in nodes if n.get("source_file")}
for e in edges:
    if not e.get("source_file"):
        v = nsrc.get(e.get("source")) or nsrc.get(e.get("target"))
        if v:
            e["source_file"] = v

Suggestion: do this inside extract_corpus_parallel before _checkpoint_chunk, and warn() with a count for whatever still has no source_file, instead of dropping it silently.

2. on_chunk_done cannot persist a corrected chunk without defeating #2973 and #1757

A caller that wants to apply the fix above must re-persist the chunk, and the callback makes that impossible to do correctly:

  • _checkpoint_chunk(result, chunk) runs before on_chunk_done(idx, total, result) (llm.py:2729-2730), so a callback can only write after the uncorrected version is already on disk.
  • The callback signature is (idx, total, chunk_result). It never receives chunk, so the caller cannot reconstruct allowed = [unit_path(item) for item in chunk] — the exact value _checkpoint_chunk passes as allowed_source_files.

Without that list the caller's save_semantic_cache runs with allowed_source_files=None, which disables both:

So the caller's write is strictly worse than the checkpoint it overwrites, and nothing in the callback's arguments allows better.

Suggestion: pass the chunk's resolved paths to the callback — on_chunk_done(idx, total, result, allowed), or an allowed= kwarg keeping the old arity working — and/or offer a hook that runs before _checkpoint_chunk so a caller can correct result in place and let the library persist it with the right scope.

3. #2973's basename recovery is exact-match, so a lowercasing model is never recovered

_recover_group_path matches on ap.name == cache_path.name (cache.py:1512):

candidates = [ap for ap in allowed_paths if ap.name == cache_path.name]
if len(candidates) == 1:

Our model's dominant source_file failure is not a mangled basename — it lowercases the path and drops intermediate directories. When the basename itself contains uppercase (g0/SPEC-CONGELATA.md), the exact comparison finds zero candidates and the group falls through to the silent skip, although a case-insensitive comparison would have matched exactly one file in the chunk.

Suggestion: when the exact match yields nothing, retry with ap.name.casefold() == cache_path.name.casefold(), keeping the same "recover only if exactly one candidate" rule. Conservative, and one extra pass over a list at most chunk_size long.

4. GRAPHIFY_MAX_OUTPUT_TOKENS has no effect on the ollama backend

_call_openai_compat sends the cap as max_completion_tokens (llm.py:1408). Ollama's OpenAI-compatible endpoint ignores that field. Measured against ollama directly, same model and server, only the field name changed:

field sent value asked completion_tokens returned finish_reason
max_completion_tokens 15 195 stop
max_tokens 15 15 length

Consequence: the output cap a user sets is silently inert on ollama, so --api-timeout is the only thing bounding generation. It also makes the finish_reason == "length" path at llm.py:1485 unreachable there, so the adaptive "retry with smaller input" signal never fires. In our run with GRAPHIFY_MAX_OUTPUT_TOKENS=3000, a two-file chunk returned 6722 output tokens.

Suggestion: in the ollama branch — where extra_body is already being assembled — also set kwargs["max_tokens"] = max_completion_tokens.

Related, minor: the num_ctx derived at llm.py:1443 is capped by the server's OLLAMA_CONTEXT_LENGTH. We requested 14000 and /api/ps reported context_length: 11000, so the derived value is a request and not a guarantee; a note to that effect in the comment would help.


Why these matter together

Each is survivable with a hosted model that fills source_file on every item. Together, on a small local model, a nightly incremental run can bill a full extraction and persist almost none of its edges while reporting success. Ours did exactly that for weeks.

Steps to reproduce

Extract as a library (not via the CLI) against a local ollama:

export OLLAMA_BASE_URL=http://127.0.0.1:11436/v1
export GRAPHIFY_OLLAMA_NUM_CTX=14000
export GRAPHIFY_MAX_OUTPUT_TOKENS=3000
export GRAPHIFY_TOKEN_BUDGET=7000

then, in Python:

from pathlib import Path
from graphify.llm import extract_corpus_parallel

files = [Path("docs/a.md"), Path("docs/sub/B-UPPER.md")]   # prose, not code
r = extract_corpus_parallel(files, backend="ollama", model="qwen2.5:14b",
                            root=Path("."), max_concurrency=1, token_budget=7000)

n, e = r["nodes"], r["edges"]
print("nodes with source_file:", sum(1 for x in n if x.get("source_file")), "/", len(n))
print("edges with source_file:", sum(1 for x in e if x.get("source_file")), "/", len(e))
print("output tokens:", r["output_tokens"], "(cap asked: 3000)")

Point 4 on its own, no graphify involved — send the same request twice, changing only the field name, and compare usage.completion_tokens:

curl -s http://127.0.0.1:11436/v1/chat/completions -H 'Content-Type: application/json' \
  -d '{"model":"qwen2.5:14b","messages":[{"role":"user","content":"List 60 Italian city names, comma separated."}],"max_completion_tokens":15,"stream":false}'

curl -s http://127.0.0.1:11436/v1/chat/completions -H 'Content-Type: application/json' \
  -d '{"model":"qwen2.5:14b","messages":[{"role":"user","content":"List 60 Italian city names, comma separated."}],"max_tokens":15,"stream":false}'

Error output or graph output

# point 4, measured:
max_completion_tokens=15  ->  195 tokens, finish_reason "stop"
max_tokens=15             ->   15 tokens, finish_reason "length"

# a real two-file chunk, GRAPHIFY_MAX_OUTPUT_TOKENS=3000:
input_tokens 6572   output_tokens 6722

# our nightly, aggregated from its own logs:
chunks persisting >0 cache entries:  769
chunks persisting  0 cache entries:  394   (33.9%, each logged as a success)

# the silent skip itself produces no output at all — that absence is the report.

Graphify version

0.9.73 (every line number above is from the installed 0.9.73 wheel; the behavior was first seen on 0.8.18)

Operating System

Linux

Additional context

Backend ollama, model qwen2.5:14b (Q4_K_M), 3× Tesla P40, Ubuntu. Corpus ~21k documents, mostly Italian prose. Points 1-3 are read from the 0.9.73 source; point 4 is measured against the live server as shown above.

Activity

  1. github-actions commented on Oct 1, 2026

    @github-actions

    Thanks for opening this issue, @Rasco94. A maintainer will take a look soon.

    If you would like to discuss it in real time, come say hi on our Discord server. For longer-form questions and ideas there is also GitHub Discussions.

    To help us triage, please make sure the report includes what you expected, what actually happened, and the steps (and a small sample) to reproduce it.

  2. Rasco94 commented on Oct 1, 2026

    @Rasco94
    Author

    Correction to point 3, and a much larger measurement that replaces it

    I filed point 3 on a hypothesis I had not verified. I have now measured it and it is wrong, so here is the correction plus what the data actually shows. Points 1, 2 and 4 are unaffected.

    What I claimed, and why it was wrong

    I wrote that our model "lowercases the path and drops intermediate directories", and asked for a casefold() fallback in _recover_group_path. I checked that against every built graph we have — 110 graph.json files, 21,379 nodes — by taking each node's source_file and testing whether it resolves to a real file under that project's source root.

    Of the 25 unresolvable examples I sampled, 0 had any uppercase in the basename and 24 had a basename that does not exist anywhere under the source root. So a case-insensitive comparison would have recovered none of them. The casefold() suggestion is still a cheap hardening, but it is not the fix for this, and I should not have presented it as our failure mode.

    What is actually happening: the model invents paths wholesale

    nodes with a resolvable source_file :  3,007
    nodes with an unresolvable one      : 18,261   (85.4%)
    nodes with no source_file at all    :    111
    

    The unresolvable values are not corrupted versions of real paths — they are inventions, and several look like the schema's own placeholder shape:

    diana-rag/insight_1.md   ...   diana-rag/insight_10.md
    logs/2024-04-05_15-30-00.log
    email_006.txt       invoice_002.txt      payment_confirmation.md
    session_01.md       system_alerts.md     project_notes.md
    

    Per project, several graphs have zero resolvable source_file values:

    project (ours) unresolvable resolvable
    A 2,927 0
    B 2,540 16
    C 1,979 0
    D 1,395 1,572
    E 1,218 0

    That is the same class as #2217 (model-invented source_file bypassing the #1895 filter) — I am adding the magnitude we see on a small local model, since #2217 does not quantify it.

    Why this makes points 1 and 2 worse, not milder

    #2973's recovery matches an unresolvable source_file by basename against the dispatched allowlist. When the basename is invented, there is nothing to match, so the recovery cannot fire however it compares strings — and the group goes to the silent skip. On this backend the recovery path is effectively unreachable.

    But the attribution is still recoverable deterministically in the common case, without a model call:

    • A chunk that dispatched exactly one file: every unresolvable source_file in its result can only belong to that file. Assign it.
    • A chunk that dispatched N files: attribution is genuinely unknown. That is the case that must be counted and warned, not dropped in silence — which is the substance of point 1.

    A concrete shape, where _checkpoint_chunk already has allowed in hand:

    if len(allowed) == 1:
        only = allowed[0]
        for item in (*nodes, *edges, *hyperedges):
            src = item.get("source_file")
            if src and not source_path(src).is_file():
                item["source_file"] = str(only)     # can only be this file

    Revised ask

    Replacing point 3 with:

    1. Attribute an unresolvable source_file to the chunk's only dispatched file when the chunk dispatched one (deterministic, no model call).
    2. When attribution is impossible, warn() with a count instead of dropping silently — the same gap as point 1.
    3. Keep the casefold() fallback only as incidental hardening; it is not what our data needed.

    One genuinely useful thing I noticed while measuring: when an allowlist is passed, 0.9.73 does emit RuntimeWarning: semantic cache skipped out-of-scope source_file '<path>'; the file was not dispatched for extraction. That is a real improvement over 0.8.18, which said nothing. The remaining silence is the if src: drop in point 1 and the unresolvable-path skip above — neither of which produces any message.

    Measured on graphify 0.9.73 and 0.8.18, backend ollama, model qwen2.5:14b (Q4_K_M), Linux, 110 graphs built from a ~21k-document mostly-Italian-prose corpus.

  3. Rasco94 commented on Oct 2, 2026

    @Rasco94
    Author

    Follow-up: we implemented the single-dispatched-file attribution from the correction above, and it recovers the work. Measured on 0.9.73.

    Short version: on 0.9.73 the loss is no longer silent — your own warning names it exactly — and the single-file case is recoverable deterministically. Numbers below, in case they are useful for deciding where the fix belongs.

    0.9.73 already tells you why the work is lost

    Running our nightly path on 0.9.73 for the first time, the cache wrote nothing and said:

    save_semantic_cache: all 10 source_file group(s) were skipped because their paths
    do not resolve to real files. This usually means ``root`` is anchored to the wrong
    directory (e.g. the --out directory instead of the corpus root). Pass the corpus
    directory as ``root`` and the output directory as ``cache_root`` (#1991).
    

    Our root is the corpus root and cache_root is the output directory — i.e. exactly what the warning advises. The paths do not resolve because the model invented them. So on a weak local backend that warning's suggested cause is a red herring, while the condition it reports is the real and common one. It might be worth softening the wording to mention model mis-attribution as the other cause.

    It also surfaced a second failure shape we had not separated from pure invention — a dropped path segment:

    semantic cache skipped out-of-scope source_file 'cantieri-2026-09-01/02-cantiere-fabbrica-cammina.md'
    

    where the real path is cantieri-2026-09-01/02-cantiere-fabbrica-cammina/02-cantiere-fabbrica-cammina.md. Both shapes occur: fully invented names, and real names with a directory level missing.

    The single-file case is unambiguous, and recovering it is enough to matter

    We implemented the rule from the correction above in our own wrapper, by intercepting save_semantic_cache: when allowed_source_files contains exactly one path, any source_file that does not resolve can only be that file, so rewrite it. When the allowlist has N entries we touch nothing — attributing at random would write an entry that makes a never-extracted file look done, which is precisely what the #1757 guard exists to prevent.

    Measured on the same project, same corpus, same model, cache on (the real incremental path):

    cache entries written graph edges extracted
    0.8.18 (our previous version) 0 58 / 54 63
    0.9.73, strict allowlist only 0 58 / 54 63
    0.9.73 + single-file attribution 1 57 / 61 72

    The entry that lands: 29 nodes, 31 edges, 31/31 edges carrying source_file, partial: None, attributed to the correct file. And the loop closes — a re-read now reports:

    CACHE: 3 reused, 0 to extract        (was: 2 reused, 1 to extract, every single run)
    Extract done in 0.0s: 72n 72e (0 in / 0 out tokens)
    

    Before this, that file was re-extracted and discarded on every nightly run. Across our logs that pattern accounted for 394 of 1163 chunks (33.9%) historically, and 17 of 23 chunks (74%) on the most recent night.

    Where we think it belongs upstream

    _checkpoint_chunk already has allowed = [unit_path(item) for item in chunk] in hand, so the one-file case is available right there:

    if len(allowed) == 1:
        only = allowed[0]
        for item in (*nodes, *edges, *hyperedges):
            src = item.get("source_file")
            if src and not source_path(src).is_file():
                item["source_file"] = str(only)     # can only be this file

    and for len(allowed) > 1, a warn() with the count of unattributable groups instead of the silent skip — which is point 1 of the original report.

    We are happy to open a PR if that shape is acceptable; say the word and we will match your conventions and add a test for both branches (one-file recovers, N-files warns and does not guess).

    Measured on graphify 0.9.73, backend ollama, qwen2.5:14b (Q4_K_M), 3× Tesla P40, Linux, ~21k-document Italian-prose corpus.

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