[Feature Request]: UUID-based config storage anchoring and offline migration
Feature Request Description
Persist a minimal identity anchor for the configuration storage at a fixed location, <WORKING_DIR>/_lightrag_config/storage_anchor.json, and record a UUID inside the configuration container itself. Every start verifies backend type + UUID before any embedding baseline is read and before any business storage is initialized. Deleting the anchor file is the sanctioned way to rebind. An offline tool migrates the configuration container across backend types and moves the anchor only after the copy has been verified.
Related: #4006, #4011. Based on dev bc8c8d0a0c326a8bb64efc6d822976196963c706. This amends ConfigurationStorage.md; the implementation must update that contract in the same change (sections listed under Contract updates).
Revision 2. This body replaces the first revision after review. What changed and why is summarized at the end (Changes from revision 1).
Background
The configuration storage exists only on dev. A production deployment upgrading from main will usually have no LIGHTRAG_CONFIG_STORAGE, and for a deployment whose business KV is already on PostgreSQL, putting configuration on PostgreSQL too is the expected outcome; switching every such deployment to JSON would introduce a file-backed configuration storage nobody chose.
But "unset follows LIGHTRAG_KV_STORAGE" re-resolves on every start, so the configuration moves whenever the KV selection changes. The old records stay in the old backend and the new location reads as absent.
What that costs today, stated precisely. Baselines are only ever established on positive evidence (an adoption probe or a confirmed-empty target), and a start with nothing on record is announced (warn_about_unrecorded_baselines). So a drifted start re-probes; it does not silently adopt the configured model. What is lost:
- the recorded per-target baseline is replaced by a fresh probe verdict, which is a sample and weaker than the record;
- records that cannot be re-derived by probing — slice 2's
_lightrag_server/embedding.current/.previous, and every environment setting later moved into the store (Rollout → later) — are lost without a refusal; - a start against an emptied or wrong container is only announced, never refused (the residue A replaced or cleared configuration store loses every baseline).
This issue turns (3) into a refusal whenever an anchor exists, and makes (2) safe before those keys land.
Why a UUID and not only the backend type. A type-only anchor catches the default-drift case above and nothing else. The UUID additionally catches a same-type container change: a connection pointed at another or an empty database, a changed LIGHTRAG_CONFIG_DIR, a restore from a backup older than the identity. The added cost is one registered row and one bind step, and the design below keeps it at that: no pending state, no recovery mode, no migration journal.
This is a container identity, not the deployment id the contract rejects. What discriminates two deployments on one server rejects an id used as a row discriminator, because it would make records read as absent after an ordinary redeploy. Here the UUID lives in the container and travels with it (a dump/restore keeps it), a start without an anchor adopts whatever UUID the container already has, and an ordinary redeploy that keeps WORKING_DIR and the container passes unchanged.
Decisions kept
- An explicit
LIGHTRAG_CONFIG_STORAGEwins; unset, the candidate is resolved fromLIGHTRAG_KV_STORAGEas today. - The admitted set stays
JsonKVStorage,PGKVStorage,MongoKVStorage,OpenSearchKVStorage. An inheritedRedisKVStorageis still refused with a message asking for an explicit admitted backend. - With an anchor present, the candidate must pass the identity check. The server never silently switches to the anchored backend, never migrates, never rebinds.
- Neither the server nor any tool edits
.env, deployment environment variables or credentials.
Example: first upgrade with KV=PG and CONFIG unset binds PG/U1. Later only KV is changed to Mongo: the candidate is Mongo, the anchor says PG, startup is refused. The operator either sets LIGHTRAG_CONFIG_STORAGE=PGKVStorage explicitly (no migration needed) or runs the offline migration to Mongo and then starts.
Identity and persistence contract
1. The anchor file
Path: <WORKING_DIR>/_lightrag_config/storage_anchor.json. It depends only on WORKING_DIR and a name fixed in code, and does not follow LIGHTRAG_CONFIG_DIR: that setting moves the JSON configuration data, and moving the anchor with it would move the checked data and the check together.
{
"schema_version": 1,
"backend": "PGKVStorage",
"storage_uuid": "<UUIDv4>"
}Nothing else: no host, port, database, user, password, connection string or hash of one, no embedding parameters, no business workspace.
- Strict read. Structure, exact
schema_version, an admitted backend name and a well-formed UUID are all validated. Only a genuine "file does not exist" is the no-anchor branch; a permission error, a truncated or corrupt file, or an unknown version refuses startup and is never read as absent. - Durable writes, in two modes. Both write a temp file in the same directory,
fsyncit, publish, thenfsyncthe directory where the platform supports it; a failed write is reported as a failure, never as success.- Bind (a start with no anchor) publishes no-clobber: it never overwrites an existing anchor (e.g. link-then-unlink on POSIX, or a re-check under the lock where no-clobber is unavailable).
- Migration (step 7 of the tool, and nothing else) publishes by atomic replace (
os.replace). - A normal start never overwrites or deletes an existing anchor.
- Persistence is a deployment requirement.
WORKING_DIRmust persist whichever backends are selected, and the anchor must be included in backup, restore and volume migration. A deployment with an ephemeralWORKING_DIR(e.g. the Helm chart withpersistence.enabled=false) loses the anchor on every restart, which makes the check vacuous; the docs must say so, and the no-anchor bind logs at WARNING so it is visible. - Read-only
WORKING_DIR. The first bind has to write the anchor; if it cannot, startup fails loudly. Once an anchor exists, a read-only directory only affects the lock (see Locking).
2. The container's own UUID
A new server-scope key, _lightrag_server/storage_identity, declared in CONFIG_KEY_REGISTRY with SERVER_SCOPE, using the existing row format; value is {"uuid": "<UUIDv4>"}.
- It identifies the whole configuration container, not a workspace, a connection address or a
LightRAGinstance. Every workspace in the container shares it. - It is never overwritten once valid, and never deleted or regenerated by workspace clear/delete, embedding rebuild or configuration-row maintenance. (Verified against dev:
/documents/clearandlightrag-clear-storagedrop data storages only, anddelete_workspace_configurationdeletes registered per-workspace suffixes by key, so neither reaches this row. The registry'sreaders/writersmust list every caller.) - It is read strictly: a backend error, an invalid row schema or a malformed UUID is an error, never "absent".
- It is written through
flush_configuration_storage— the same strict flush the baseline claims use, including the retained-buffer check — and confirmed by a strict read-back. An OpenSearch read-back answered from the process-local buffer is not proof of durability. - A tenant legally named
_lightrag_servercannot collide with it: the scope is compared by identity (SERVER_SCOPE), and a suffix is registered with exactly one scope.
3. Identity is compared, connection details are not
| Change | Result |
|---|---|
| IP, port, DNS or credentials change; backend type and UUID unchanged | passes; connection failures still fail normally |
| same backend type, different UUID | refused |
| anchor present, container UUID missing | refused; no UUID is created |
| backend type changed, even with the same UUID copied over | refused; migrate |
JSON config_dir changed |
judged by the target container's UUID; the fixed anchor is still read |
| identity matches, an embedding baseline does not | refused by the existing baseline contract |
| anchor file deleted by the operator | no-anchor branch: adopt the container's UUID, or create one (see Rebind) |
The UUID identifies a logical container. It is not a tamper-proof credential and does not prove that a database is physically unique or complete. A clone or an old backup can carry the same UUID; detecting same-type clones, rollbacks, or deliberate edits to both sides is out of scope. The type check exists to stop the cross-type copy bypass. Baselines, the coverage gate and per-container markers are all kept and still ANDed.
Startup sequence
The existing nine steps are kept. The anchor work is inserted before step 1 and between steps 1 and 2:
0a. take the shared anchor lock (pre-step-1, not sticky)
0b. strict-read the anchor
0c. resolve the candidate backend; anchor present and type differs
-> refuse before the configuration storage initializes
(existing JSON config_dir claim, unchanged)
1. initialize the configuration storage
1b. BIND, under keyed lock "configuration_identity" (sticky, rolled back
re-read the anchor like a step-2 failure)
strict-read the identity row
anchored: equal -> continue; missing / different / invalid / error -> refuse
not anchored: present -> adopt it
confirmed absent -> create it: upsert, strict flush,
strict read-back, compare
publish the anchor {candidate backend, uuid}
log WARNING: container description, uuid, adopted or created
2-9. unchanged- The Gunicorn master runs 0a–0c in
on_starting, before forking, through the same selection code it already uses for the JSON claim; a type mismatch refuses the master instead of surfacing as every worker failing while the master respawns them. Workers still run 0b–1b themselves. - Steps 0a–0c open nothing, so a failure there is an ordinary, non-sticky failure that releases the lock — consistent with Where stickiness starts. Step 1b follows the existing sticky-failure and rollback rules;
INITIALIZEDkeeps its current meaning. - The anchor is published as soon as the identity is confirmed, before business storages initialize. It records only the identity binding; it says nothing about whether any baseline has been recorded.
- The keyed lock spans the whole read-decide-write, not just the writes. A second worker of the same Gunicorn master waits, then sees an anchor and an equal UUID. The OS lock's per-tree hold count is not a transaction lock between workers.
- Concurrent first binds by separate process trees remain unsupported, as today; the read-back is not claimed as cross-host exclusion.
Crash analysis (why there is no pending state).
| Interrupted after | Next start | Outcome |
|---|---|---|
| identity durable, anchor not published | no anchor, identity present -> adopt | heals by itself |
| anchor publish failed | start fails loudly; retry adopts the durable identity | heals by itself |
| any of steps 2–9 | anchor and identity already consistent | existing sticky-failure rules; a new instance retries |
Residue: if the configuration is repointed between a crash and the next start, the first container keeps an orphan identity row. A later bind to that container adopts it; an anchored start against it refuses on UUID mismatch. Both directions are safe, and the orphan is harmless. This is recorded as an accepted residue in the contract.
Refusals, and the rebind escape hatch
Deleting storage_anchor.json is the sanctioned rebind. The next start takes the no-anchor branch and binds to whatever container the current configuration selects. The guarantee boundary must be documented plainly: deleting the anchor turns drift detection off for that one start, and protection falls back to the existing baseline contract (evidence-only adoption, the unrecorded-baseline announcement, the coverage gate, per-container markers). It is a deliberate downgrade to today's dev guarantees, not a bypass below them.
It is the documented recovery for: a container intentionally emptied or replaced; a database restored from a backup older than the identity; abandoning the old container on purpose.
Refusal messages name the stage, the expected and actual backend type and UUID, and hide credentials. The advice depends on the cause, because type drift is the mistake this feature exists to stop:
| Refusal | First advice | Deleting the anchor |
|---|---|---|
| container UUID missing | if the container was intentionally emptied, replaced or restored from an old backup, delete the anchor file (path given) and restart | primary recovery |
| backend type differs from the anchor | set LIGHTRAG_CONFIG_STORAGE explicitly to the anchored backend, or run lightrag-migrate-config |
listed last, marked as abandoning every record in the old container |
| same type, different UUID | check that the connection settings point at the intended database | listed last, same warning |
Do not delete the anchor while servers are running: running processes do not re-read it, and a respawned Gunicorn worker will rebind to the current container. A dedicated rebind command is not part of this issue; add one only if misuse of the file deletion shows up in practice.
Locking
- A new lock file,
.lightrag_anchor.lock, in the anchor directory. It is distinct from the existing exclusive.lightrag_storage.lockof the JSONconfig_dirclaim, which lives in the same directory whenconfig_diris at its default. - Normal starters take it shared — server, the Gunicorn master in
on_startingbefore forking (workers inherit it), SDK,lightrag-rebuild-vdb,lightrag-clear-storage. The migration tool takes it exclusively. Starters that coexist today are therefore not newly refused (the deployments §One server at a time says a wider claim would break), while a migration is excluded against every process holding the shared lock. - Where the filesystem or platform cannot lock (NFSv3 without lockd, SMB/CIFS, or a platform without shared locks —
msvcrt.lockinghas no shared mode;LockFileExcould provide one), starters fail open with a warning, the posture the existing claim already takes. The migration tool refuses unless given--assume-exclusive, which records that the operator has stopped every reader and writer. - Order: anchor lock, then the JSON
config_dirclaim; identical paths are deduplicated; release in reverse, after the storage teardown (The claim goes back last). - The shared anchor lock, the existing JSON
config_dirclaim and the business-data residue inworking_dir_lock.pyremain three separate statements; this issue changes only the first. - A local directory lock does not protect a service using another
WORKING_DIR. Deployments that share one remote configuration container must all be stopped and coordinated for a migration; no distributed lock or rolling migration is added.
Maintenance tools
lightrag-rebuild-vdb and lightrag-clear-storage take the shared anchor lock, go through the same selection code and verify the identity when an anchor exists, refusing exactly as a start would. They never create or rewrite the anchor or the identity row; with no anchor they run as they do today and log that nothing was verified. Only a server or SDK start binds, and only the migration tool changes a binding.
Offline migration tool: lightrag-migrate-config (cross-type only)
Scope: moves between different backend types. A same-type move (PostgreSQL to another PostgreSQL, Mongo to Mongo, OpenSearch snapshot/reindex, copying the JSON file) is done with the backend's own dump/restore and needs no tool: the identity row travels with the data, and "same type + same UUID" passes. A same-type tool is also not implementable today without refactoring three backends: the PostgreSQL, MongoDB and OpenSearch ClientManagers are class-level singletons that read connection settings from os.environ, which is why migrate_llm_cache already excludes a same-type target.
The UUID is kept. The target receives the source's UUID. The backend type already distinguishes source from target, and pointing back at the source after a migration is refused by type; a fresh UUID would discriminate nothing and would add a second identity to verify.
Inputs. The anchor; the source connection from --source-env (default: the current environment) and the target from --target-env plus the target backend. Because the types differ, the two backends read disjoint connection variables; the tool refuses if the two files set conflicting values for a variable either selected backend reads. It never writes env files and never logs credentials. The anchor and its lock are resolved from the current environment's WORKING_DIR; the tool refuses if either env file names a different WORKING_DIR. A JSON source's config_dir resolves from --source-env, a JSON target's from --target-env. --dry-run is read-only and reports the anchor, source and target, row counts, the workspace scopes found, and the verdict on the target (including "target already holds this identity with N rows; will reconcile").
Steps.
- Take the anchor lock exclusively (see Locking). Strict-read the anchor; no anchor means nothing is bound, and the tool refuses with guidance. The target type must be admitted and different from the anchored type.
- Open the source as the anchored type and strict-read its identity; it must equal the anchor's UUID. An unreadable source refuses — the anchor is never moved without a readable source.
- Open the target and classify it: empty → claim it; identity equal to the anchor's UUID → the residue of an earlier attempt of this migration, resume; anything else (another identity, or rows without this identity) → refuse; no overwrite, no merge.
- Claim: write the target's identity row (same UUID) first, strict flush and read-back. It is the ownership marker that makes retries safe without a migration journal.
- Copy every row of the container, paged through
iter_rows: all server-scope rows and all workspaces' rows, with the key and the row envelope verbatim. The source identity row is not copied as data. A row that is not a well-formed row is refused and listed, never skipped. On resume, source rows are upserted and target rows absent from the source are deleted — permitted only because step 3 proved ownership. - Strict flush (retained-buffer check included), then enumerate the target and compare the key set and normalized content with the source; backend-owned metadata (
_id,create_time/update_time) is not a difference. Any enumeration or read-back error is a failure. - Publish the anchor
{target type, same UUID}atomically. This is the commit point. The tool then tells the operator to setLIGHTRAG_CONFIG_STORAGE=<target>explicitly (it does not edit the environment) and reports that the source was kept.
Failure and recovery.
- Before step 7: the anchor is unchanged. The old environment keeps working on the source; the new environment is refused on type mismatch. Re-running resumes through the ownership marker, and reconciles to the current source if it changed in the meantime.
- After step 7: the migration is complete even if later output fails, and the tool reports "
Source: HKUDS/LightRAG