update()— re-sync a single document or tabledelete_document()— remove a single document and its orphansapply_changes()— heterogeneous batch (added / modified / deleted)finalize()— run once at the end of a batch
apply_changes() routes each list to the right primitive.
Mental Model — What Lives in the Graph
To understand the effect of each primitive, it helps to know the node shapes the lexical graph keeps:
Incremental updates are scoped via these relationships — orphan cleanup never goes global, it only inspects entities the touched document actually referenced.
Document Ids and the Content Hash
Every primitive addresses aDocument by its id:
Pass
document_id= to choose your own. An id may not contain the reserved marker __pending__ (ValueError), which the update cutover uses for its transient documents.
The pipeline stores a SHA-256 content_hash on the Document. Re-ingesting or updating byte-identical content is a no-op: ingest() of prose returns before chunking with metadata["skipped_unchanged"] = True and chunks_indexed = 0, ingest() of a table returns a StructuredIngestionResult with no_op=True, and update() returns no_op=True. No chunker, extractor or LLM runs and nothing of the document is written (ingest() still refreshes the graph’s config node). For a table the hash covers the mapping as well as the rows, so re-declaring a column’s type is never mistaken for unchanged data.
The hash is written last, and only when every write was reported in full. A failed extraction, an edge the graph store dropped after a transient error, or a chunk left without an embedding withholds it, and metadata["incomplete_writes"] lists the shortfalls. The next ingest() or update() of that content then runs again and repairs the document instead of skipping it.
Chunk ids are derived from the document id, the chunk’s position and its text, so re-ingesting the same file writes onto the same chunk nodes. Inserting a paragraph re-ids every later chunk; only byte-identical files are a no-op.
update()
Re-sync a previously-ingested document. The new content replaces the old chunks, entities are re-extracted, and entities that become orphaned (no remaining MENTIONED_IN edges) are cleaned up along with their incident RELATES edges.
update_sync() takes the same arguments.
Parameters
Returns — UpdateResult
metadata carries the structured counts (records, entities, references, edges, …) of the StructuredIngestionResult.
Effect on the graph
A Document records how it was written. Updating a table’s Document from a prose file, or a prose Document from a table, raises
ValueError rather than re-reading one as the other; delete_document() it first if the source really changed kind.
Crash safety — the pending-document cutover
The new content is written under a transient pending Document (<id>__pending__<8 hex>) beside the live one, so the live document stays readable while the update runs. The cutover is a state machine with one load-bearing commit point (mark_pending_committed, which sets ready_to_commit on the pending Document):
- Before the commit, a crash rolls back: the pending Document and its chunks are discarded and the live document is untouched. Entities and
RELATESedges the pending pipeline already wrote are not rolled back. - After the commit, a crash rolls forward: the old chunks are deleted, the pending Document is renamed to the canonical id, and orphan cleanup runs. The cleanup state is written onto the pending Document before the commit, so it survives the crash.
update() and delete_document() against an id first finishes or rolls back whatever a crashed call left on it. Chunks written by update() are keyed on the transient pending id, so the pending and live documents never share chunk nodes during the cutover.
Chunk-level extraction cache
update(..., cache_unchanged_chunks=True) makes editing one paragraph of a 50-chunk document cost about one LLM extraction instead of fifty. New chunks whose text is byte-identical to an existing chunk of the same document skip extraction: their entities, relationships and mentions are rebuilt from the live graph and remapped onto the new chunk ids. Only new or changed chunks go to the extractor. UpdateResult.metadata["cache_stats"] reports cached_chunks and extracted_chunks.
The cache fails open per chunk: a chunk it cannot rebuild is re-extracted, along with any chunk that depends on it. An unreachable graph (DatabaseUnavailableError) and an exhausted latency budget propagate instead, since extraction would bill in full and then fail at the write. A query the server rejects (DatabaseError) falls back to extraction.
The underlying decorator, CachedChunkExtraction(inner, graph_store, document_id), is exported for custom pipelines.
Example
delete_document()
Remove a single document and everything it uniquely owns.
delete_document_sync() takes the same arguments.
Parameters
Returns — DeleteDocumentResult
Effect on the graph
To take a table out entirely, including its stored mapping, use
drop_table(), which calls delete_document() for the table’s rows and then removes what it signed.
The surviving entities’ descriptions are rewritten: what this document’s chunks said about them is taken off, unless another chunk still says it (no LLM call). A summarised entity cannot have text taken out of its summary: when the removed text is no longer said by any remaining edge, it is rebuilt from its remaining MENTIONED_IN edges if every one of them was written by this version (said_version; a table row’s edge does not count), and otherwise its summary is kept and the removed text beside it is still dropped. An unchanged chunk keeps its entities’ summaries for sure only with cache_unchanged_chunks=True; without it the chunk is extracted again, and a summary is kept only if the model describes the entity in the same words. An entity still holding more than five descriptions is summarised by the next finalize(). update() does the same for the chunks a new version replaces. Text a document ingested by an earlier SDK version wrote cannot be told apart, and is kept.
Crash safety
A single atomic write (pending_delete=true + cleanup-state arrays on the doc) is the commit marker. Before that write the live document is untouched. After it, every remaining step is idempotent and resumes on the next call against this id.
Example
apply_changes()
Heterogeneous batch — the convenience wrapper for CI-driven incremental ingestion. Dispatches each list to the right primitive in a fixed order:
deleted→delete_document(); an id that is no Document’s but names a relationship table removes that table’s edges and keeps its mapping (drop_table()removes both)modified→update(if_missing="ingest")(so a “modified” file the graph has never seen is upserted, not errored)added→ingest()
apply_changes_sync() takes the same arguments.
Parameters
The order
deletes → updates → adds is part of the public contract; do not assume reordering is safe. Relationship tables (a RelationshipMapping in the ontology) in added or modified run after all of it, modified first, because their endpoints resolve against nodes the entity tables in the same batch write. A git diff that lists consumed_batch.csv before unit.csv still writes every edge, and each entry keeps its position in the result.
Overlapping ids across input lists raise ValueError at the input boundary — this is almost always a broken git-diff parser.
Tables in a batch. A table (.csv, .tsv, .psv, .tab) in added or modified is written on its own through the structured path its mapping describes, one source at a time, so one bad row cannot fail the rest of the batch. The chunker, extractor, resolver and cache_unchanged_chunks overrides apply to the prose in the batch, not to tables. A table’s entry carries the structured counts (records, entities, references, edges) in its result’s metadata.
Returns — ApplyChangesResult
BatchEntry with error (string) and error_type (exception class name) set; the batch never raises. Branch on entry.is_success:
Effect on the graph
apply_changes() does not itself touch the graph — it dispatches to the primitives documented above and aggregates their results. Two whole-batch consequences worth knowing:
- No automatic
finalize(). Callfinalize()once after the batch, not once per file. Its dedup checks only the entities whose check is pending — the ones the batch added, which have no name vector yet, and any entities an earlier run left pending — so one call judges the whole batch’s new entities together, in fewer LLM calls than one per file, and a second call with nothing pending does no dedup work. - Peak entity cardinality is minimised because deletes run first — orphan candidates are gone before adds can re-introduce overlapping ids.
Canonical CI usage
Concurrency and the update_concurrency trap
Raising update_concurrency above 1 is unsafe in general because the orphan-cleanup correctness proof relies on MENTIONED_IN edges being persisted before any cutover begins. Two concurrent updates sharing an entity e1 are only guaranteed to preserve it because:
- Pre-cutover,
e1still has its oldMENTIONED_INedges. - Post-
pipeline.run()(but pre-cutover), the newMENTIONED_INedges are already written.
test_concurrent_updates_preserve_shared_entity is the tripwire for this invariant — break it before bumping the value.
Concurrent updates to the same document_id are not supported: serialize them yourself.
Updates While finalize() Runs
update(), delete_document(), drop_table() and a table re-sync never wait for a running finalize(). Every SDK query that deletes or re-keys an entity also leaves a deleted record, in the same query, while a dedup run is in progress. A merge the run planned that would touch such an entity is skipped, nothing is written for it, and its group is decided again on the next finalize(); FinalizeResult.dedup_merges_changed counts these. Deletes you issue with your own Cypher are not covered. See Storage for how this stays consistent.
finalize()
Run once after a batch of ingests/updates/deletes. Skipping it leaves cross-document duplicates in place and disables entity-/edge-level vector search. A read on a graph with documents ingested since the last dedup logs a warning that names the missing step.
finalize_sync() takes the same arguments.
finalize() raises DedupRunActiveError when another finalize() is already deduplicating the same graph, from any process or from the same GraphRAG; the running one is left untouched. It raises FalkorDBVersionError before anything is written when the server is older than FalkorDB 4.20.
What it does (in order)
- Removes NULL-name stub entities (legacy cleanup). Entities a table wrote are never removed here, since a table may have no name column.
deduplicate_entities()— incremental: the pending entities (added since the lastfinalize(), or left pending by it) are checked against the whole graph through the__Entity__vector index — the exact phase by canonical name and label, then one judge pass over each pending entity and its nearest names. Every merge is written as a sealed plan and applied one atomic query at a time, so an interruptedfinalize()is finished by the next one. Dedup also writes every new entity’s name embedding (there is no separate entity backfill step). See Storage for the full algorithm. Then every entity holding more than five descriptions gets one LLM summary of them (descriptions_summarised); one whose summary fails keeps them and is listed indescription_summary_failures, to be tried again by the next run.embed_relationships()— embeds fact text onRELATESedges.ensure_indices()— rebuilds/verifies all indexes and waits, up to 10 minutes, for any build in progress.- Names the chunks: an unnamed
Chunkgets"<document id> · chunk <index>", except a table row and a chunk of a documentupdate()is still replacing.finalize(name_chunks=False)skips it. - Checks the graph for what it should report — signed properties left behind, properties more than one table supplies, mappings nobody declared, placeholders nothing filled, entities without a name, near-duplicates that did not merge — and logs each finding at WARNING. Nothing in this step changes the graph.
finalize() calls the LLM through the default judge, and for the description summaries in step 2, which always use the instance’s llm. A DedupJudge of your own (see Storage) keeps dedup LLM-free; the summary pass still runs on llm.
FinalizeResult
finalize() returns a typed FinalizeResult. Nothing it reports is resolved for you; every non-empty list or dict of findings is also logged at WARNING (judge_stats and indexes are logged at INFO).
Counts from the steps
Dedup
Structured sources (see Structured Ingestion)
An existing graph. On a graph whose entities already have name vectors, those entities count as checked; the next
finalize() checks only the new ones. To check every entity once, run finalize(dedup_all=True). Upgrade the FalkorDB server to 4.20 or later before the SDK: see Storage.Choosing the Right Primitive
End-to-End Example
A full runnable example lives ingraphrag_sdk/examples/07_incremental_updates.py. It exercises:
- Initial ingest with a stable
document_id - No-op update (content-hash short-circuit)
- Real update with orphan cleanup
- Adding a second document
- A heterogeneous
apply_changes()batch - A single trailing
finalize() - Verifying with
completion()
See Also
- Ingestion — the underlying pipeline that
ingest()andupdate()both drive. - Structured Ingestion — tables, re-syncs and
drop_table(). - Storage — node/edge shapes, why MERGE makes re-ingestion idempotent, and how
finalize()deduplicates. - Configuration —
finalize()reference and post-ingestion knobs. - Ontology Discovery — if you’re updating against a corpus and don’t have a schema yet, or want to propose schema additions from new documents via
suggest_schema_extensions. - Ontology Evolution — if your schema needs to change between updates (
add_entity,add_attribute,rename_*, etc.) — these are the mutation primitives that the discovery proposal hands off to.