Ingestion¶
This page describes what happens to a memory after an agent calls add_memory: how Spongram
acknowledges it, stores it in a durable queue, hands it to Graphiti for extraction, and keeps
retrying until it is in the graph. It also covers deduplication, what deliberate deletes do to
the queue, the operator routes that expose the queue, and brain export and import.
Edition terms used below: a server is any deployment with SPONGRAM_EDITION=cloud
(the default), self-hosted included; the Cloud control plane is a server that also sets
SPONGRAM_CLOUD_CONTROL_ENABLED=true; the desktop edition is SPONGRAM_EDITION=local.
The path of a memory¶
- The MCP client calls
add_memoryon Spongram. The request never goes to Graphiti directly. - Spongram authenticates the brain key, injects the brain's
group_id, validates and completes the tags insource_description(see Tagging and scope), and keeps only the arguments it supports:name,episode_body,source,source_descriptionanduuid. Any other argument is removed. - If
episode_bodyis longer than the chunk budget, it is split into several episodes (see Oversized episodes). - The resulting JSON-RPC envelope is written to the table
spongram_pending_episodes, and the client receives its answer at once. Extraction has not started yet. - A background worker forwards queued rows to Graphiti one at a time, in
idorder. - Graphiti extracts entities and facts, computes embeddings and writes them to the graph. All of its model calls go back through Spongram's internal inference proxy.
- On a server, a reconciler later checks that each forwarded episode really exists in the graph and queues it again if it does not.
The acknowledgement has the shape Graphiti itself returns for a queued episode:
{
"jsonrpc": "2.0",
"id": 7,
"result": {
"content": [{"type": "text", "text": "Episode 'Deploy decision' queued for processing in group 'g_xxx'"}],
"structuredContent": {"result": {"message": "Episode 'Deploy decision' queued for processing in group 'g_xxx'"}},
"isError": false
}
}
Note
A successful add_memory means "durably accepted", not "searchable". The memory appears in
search results once Graphiti has finished extracting it, typically some seconds later and
longer for large episodes or a slow model.
The never-drop guarantee¶
An add_memory call has exactly two outcomes: the episode is stored in the queue and
acknowledged, or the call is refused with an explicit error and nothing is stored. Once a row
exists, no code path gives up on it: there is no maximum number of attempts and no terminal
failure state. A row leaves the active queue only by reaching the graph or by being
retired on purpose.
The explicit refusals are:
| Status | When | Edition |
|---|---|---|
503 with Retry-After: 2 |
The admission locks could not be taken within 5 seconds, after 3 attempts. Nothing was written; the client should retry. | Cloud control plane |
422 |
SPONGRAM_CONSTITUTION_ENABLED is on and source_description fails the policy (for example a missing project= tag). Off by default. |
All |
402 |
The desktop licence is locked; reads still work. | Desktop |
Row states¶
The status column holds one of four values. Three further states are derived from other
columns and are what the admin UI and the health endpoint report.
| State | How it is stored | Meaning |
|---|---|---|
pending (due) |
status = 'pending', next_attempt_at empty or in the past |
Waiting for the worker. |
| retrying | status = 'pending', next_attempt_at in the future, retry_count below 6 |
A forward failed; the next attempt is scheduled. |
| parked | status = 'pending', next_attempt_at in the future, retry_count 6 or more |
Still retried, every 6 hours, until it succeeds or an operator acts. |
processing |
status = 'processing', started_at set |
The worker is forwarding the row. |
completed |
status = 'completed', completed_at set |
Graphiti accepted the episode. On a server extraction continues asynchronously after this point. |
| retired | retired_at set, whatever the status |
Deliberately withdrawn. Never forwarded, never replayed, not counted, not a duplicate. |
failed |
Allowed by the column constraint | Not used. No code writes it; a migration turned old failed rows back into pending. |
"Parked" is not a column value on purpose: a parked row is an ordinary pending row with a far deadline, so every path that handles pending rows also handles parked ones.
The queue worker¶
One worker runs per Spongram process. It claims the lowest-id due row (with
FOR UPDATE SKIP LOCKED on PostgreSQL), marks it processing, and posts the stored envelope to
Graphiti over its own long-lived MCP session. When the queue is empty it sleeps for up to one
second and is woken immediately by a new add_memory.
A forward counts as failed, and the row is rescheduled, when:
- no MCP session with Graphiti could be opened;
- the request raised a transport error;
- Graphiti answered with a status of 400 or more;
- Graphiti answered 200 with
result.isError: truein the body (this is how the desktop edition's embedded engine reports an extraction failure).
If Graphiti answers 404 because it has forgotten the worker's session, the call was not
executed: the worker opens a new session and sends the row once more before counting a failure.
A row left in processing for more than 300 seconds (the worker stopped mid-forward) is put
back to pending, at startup and periodically while the worker is idle. This reclaim does not
increase retry_count: a restart is not a failure of the episode.
Retry schedule¶
Each failure increases retry_count and sets next_attempt_at:
| Failure number | Wait before the next attempt |
|---|---|
| 1 | 30 seconds |
| 2 | 2 minutes |
| 3 | 10 minutes |
| 4 | 30 minutes |
| 5 | 1 hour |
| 6 and beyond | 6 hours (parked) |
The reason for the last failure is kept in last_error, with the HTTP status in
forward_status.
Oversized episodes¶
An episode_body longer than SPONGRAM_EPISODE_BODY_MAX_CHARS (default 10000 characters) is
split before it is queued, so that the extraction prompt stays within the model's context
window. The split follows paragraphs first, then lines, then sentences, and falls back to a
hard cut. Each part becomes its own row and its own episode:
- the name gets a
(part k/N)suffix; source_descriptionis copied unchanged, so every part has the same tags;- a client
uuidis kept on the first part only.
The client receives a single acknowledgement stating that the episode was split into N parts. Raise the limit only if your extraction model has a larger context window.
Idempotency¶
Every queued row carries a content_hash: the SHA-256 of group_id, name, episode_body,
source_description and uuid. When a new add_memory has the same hash as a row of the same
brain that is not retired and is either pending, processing, or completed less than 24
hours ago, no new row is inserted. The client still receives the normal success answer, and the
counter spongram_episodes_deduplicated_total{instance_id} is incremented.
Consequences:
- A client that retries the same call, or two hooks that capture the same text, produce one episode.
- The same text under two different
project=tags is two episodes, becausesource_descriptionis part of the hash. - Parts of a split episode are deduplicated one by one.
- The same text sent again after 24 hours is stored again.
Client-supplied uuid¶
Passing uuid to add_memory asks Graphiti to update an existing episode. If no episode with
that uuid exists in the brain, Graphiti would refuse the call on every attempt. In the server
edition the worker therefore checks the graph before forwarding: when no Episodic node has
that uuid and the brain's group_id, the uuid is removed from the envelope, a note is
appended to last_error, and Graphiti creates a new episode. The memory is kept rather than
retried forever. If the check itself fails, the envelope is sent unchanged.
The reconciler¶
Graphiti accepts an episode in a few milliseconds and extracts it afterwards. If that later
extraction fails, the queue row is already completed. The reconciler closes this gap. It runs
on a server only, about every 5 minutes while the worker is idle, and performs two
passes:
| Pass | Rows examined | Volume per cycle |
|---|---|---|
| Fresh | completed between 30 minutes and 24 hours ago, newest first |
Pages of 50 rows, up to 20 pages |
| Catch-up | completed between 24 hours and 30 days ago, oldest first |
50 rows, continuing where the previous cycle stopped |
The 30-minute margin leaves Graphiti time to finish: replaying an episode that is still being extracted would create a duplicate.
For each row the reconciler asks the graph whether the episode exists:
- a row whose payload carries a
uuidmatches anEpisodicnode with the samegroup_idanduuid; - any other row matches an
Episodicnode with the samegroup_id, the same fullnameand the samecontent. Comparing the content means that two different episodes sharing a name are never confused, and an identical episode is never written twice.
A row with no match goes back to pending with retry_count + 1 and a new next_attempt_at.
What the reconciler cannot recover:
- a row without a
name(it cannot be matched safely; it stays replayable by an operator); - a row completed more than 30 days ago;
- a retired row, by design;
- anything in the desktop edition, which has no reconciler. There the embedded engine extracts during the forward, so a failure is reported directly and rescheduled.
Alongside the reconciler, and also on a server only, an audit compares the number of rows completed in the last 10 minutes
with the number of episodes created in the graph over the same window, and logs
SUSPECTED INGESTION LOSS at critical level when more than one is missing.
Extraction by Graphiti¶
For each episode Graphiti creates an Episodic node holding the text, then calls the language
model to extract entities and the facts that relate them. Entities are typed with the list
configured in the Graphiti image: Person, Organization, Service, Library, Object,
Document, Concept, Project, Preference, Requirement, Procedure, Location, Event
and Topic. Entities become Entity nodes; facts become RELATES_TO relationships carrying the fact text and its validity dates
(valid_at, invalid_at). Graphiti also computes embeddings with the configured embedding
model; their dimension is fixed when the brain is created and cannot change afterwards.
Graphiti's chat and embedding requests are addressed to Spongram's internal inference proxy, which attributes usage to the brain and forwards to the configured provider (see Inference providers).
Model reasoning during extraction¶
For providers of the vLLM family, the inference proxy decides whether the model's reasoning
("thinking") mode is on, per calling role. The level is off by default for every role and is
set with SPONGRAM_THINKING_GRAPHITI (also SPONGRAM_THINKING_SLEEPER,
SPONGRAM_THINKING_DISTILL) to off, low, medium or xhigh. An unknown value falls back to
off.
Graphiti makes many model calls per episode, so turning reasoning on for the whole graphiti
role multiplies extraction time. One call can be set on its own:
SPONGRAM_THINKING_GRAPHITI_ENTITIES applies only to the entity-extraction call, which runs
once per episode and decides whether the text contains anything to extract. Empty or unset, that
call follows the role level; an unknown value is ignored. Use it when your extraction model
sometimes returns an empty entity list for texts that clearly name entities; expect each memory
to take noticeably longer to extract. Set these variables on the spongram service, not on
graphiti-mcp. At startup the service logs the levels in effect on a line starting with
thinking levels:.
Retry of transient upstream errors¶
Model servers load and unload models, and answer 502/503 or refuse connections while they
do. The inference proxy absorbs these windows instead of failing the extraction:
| Aspect | Behaviour |
|---|---|
| Retried | HTTP 429, 502, 503, 504; connection refused, connect timeout, connection closed by the upstream |
| Never retried | A read timeout: the model is working, and a second request would double the load |
| Backoff | 2 s, doubling, capped at 30 s, with 20 % jitter |
| Budget | SPONGRAM_INFERENCE_RETRY_BUDGET_SEC; default 120 s, or 60 s when the provider URL is on localhost |
| Switch | SPONGRAM_INFERENCE_RETRY_ENABLED, on by default |
| Circuit breaker | One incoming request records at most one failure, however many attempts it made |
| Metrics | spongram_inference_retries_total{role,endpoint,reason}, spongram_inference_retry_exhausted_total{role,endpoint} |
One graph writer per brain¶
On a server, the Graphiti image holds a lock per brain (group_id). The ingestion
queue holds it while an episode is being extracted, and the three delete tools
(delete_episode, delete_entity_edge, clear_graph) take it before touching the graph.
Without it, a delete running during an extraction can overwrite what the extraction has just
written.
A delete waits for the episode in progress for at most SPONGRAM_DELETE_LOCK_WAIT_SECONDS
(default 45, set on the graphiti-mcp service). Past that delay the tool answers that a
memory of this brain is being written and that nothing was deleted. This is a definite refusal:
the agent can call the tool again. During a long import, where each episode may take longer
than the wait to extract, deletes on that brain are therefore refused most of the time.
Warning
The lock lives in the memory of the graphiti-mcp process, as do Graphiti's own queues.
Run graphiti-mcp as a single replica.
Retirement: deliberate deletes are not replayed¶
The reconciler replays episodes that are missing from the graph. An episode the user deleted
is also missing from the graph, so the queue must know the difference. That is the role of
retired_at.
| Action | Rows retired |
|---|---|
delete_episode |
The completed rows of that episode: same full name and content as the node read before the delete, or the episode's uuid in the payload. They are retired before the delete is sent. |
clear_graph, answered with a readable success |
Every row of the brain. |
clear_graph, no readable success |
Only completed rows, and only if the brain held episodes before the call and holds none after. Rows still waiting are kept. |
Operator retire route |
One pending or completed row, with a mandatory reason. |
If delete_episode comes back as a readable failure and the episode is still in the graph, the
rows are given back to the reconciler. If the outcome is unknown (timeout, dropped connection),
they stay retired: the user asked for the deletion. Spongram never re-sends a delete_episode,
because a second attempt would report "not found" for a deletion that succeeded.
Retiring is a recorded act, not a loss: the row stays in the table with its payload.
Operator routes¶
These routes exist on a server only and require the admin token. They never delete a row. See the HTTP API for authentication.
| Route | Effect |
|---|---|
GET /admin/api/spongram/instances/{instance_id}/ingestion |
Counts (pending, processing, retrying, parked, completed_24h), parked_threshold, and up to 100 rows that are retrying or parked, oldest first, with retry_count, next_attempt_at, last_error and a parked flag. |
POST /admin/api/spongram/instances/{instance_id}/ingestion/replay-all |
Makes every retrying or parked row of the brain due now. Returns {"replayed": n}. |
POST /admin/api/spongram/instances/{instance_id}/ingestion/{row_id}/replay |
Makes one row due now. 409 if it is being processed; {"replayed": 0} if it was already due. |
POST /admin/api/spongram/instances/{instance_id}/ingestion/{row_id}/retire |
Sets retired_at. Body {"reason": "..."}, not blank. 409 for a processing or already retired row. |
curl -X POST \
-H "Authorization: Bearer <admin-token>" \
https://spongram.example.com/admin/api/spongram/instances/12/ingestion/replay-all
Retiring a completed row does not change its status; its only effect is that the reconciler
stops looking at it. Use it for a row that can never succeed.
The queue is also visible without the admin token in /healthz, under
components.pending_episodes_worker: queue_depth counts rows that are due or being processed,
and parked counts parked rows across all brains. A queue_depth of 0 means every due
episode has been forwarded, not that extraction has finished.
Brain export and import¶
A brain can be exported to a JSON document and replayed into another brain.
| Edition | Export | Import |
|---|---|---|
| Server (admin token) | GET /admin/api/spongram/instances/{instance_id}/brain/export |
POST /admin/api/spongram/instances/{instance_id}/brain/import |
| Desktop | GET /v1/brain/export |
POST /v1/brain/import |
The export has "format": "spongram-brain/v1" and contains exported_at, group_id,
embedding_dim, counts, the episodes (name, body, source, source_description, dates),
and the entities and edges for inspection. When the corresponding features are enabled it
also contains personas, skills and project_aliases (see Personas and
Project aliases).
Import replays the episodes only. Entities, facts and embeddings are never imported: they are extracted again by the target brain's own models, which is why a dump stays usable across model changes of the same dimension. The rules:
embedding_dimin the dump must equal the target brain's; otherwise400.- At most 50 000 episodes, and a body of at most 100 MB. A request without a valid
Content-Lengthheader, or above the limit, is refused with413. - The target brain must be
active(409otherwise). - Each episode is queued as a new
add_memorywith itsname,episode_body,sourceandsource_description. Original episode identifiers and dates are not carried over. - An episode without a
project=tag receivesproject=global, as a live call would. - Oversized bodies are split as described above.
- The answer is
{"enqueued": <episodes>}plus the persona and alias counts when applicable. Extraction then proceeds through the queue at its normal pace.
Note
Imports bypass the 24-hour deduplication. An import is often a refill: the brain was emptied and the same dump is loaded again. If those episodes were queued less than 24 hours earlier, deduplication would acknowledge each of them without writing anything. In the desktop edition, which has no reconciler, they would then never come back. The content hash is still stored, so later live writes are deduplicated against the imported rows. Importing the same dump twice into a brain that still holds it therefore creates every episode twice.