#4082·LightRAG

[Feature Request]: Allow clearing only the query/keywords answer cache, independent of document deletion

Author: AdalbertoDamCreated Sep 24, 2026Updated Sep 24, 2026
Labelsenhancement

Do you need to file a feature request?

  • I have searched the existing feature request and this feature request is not already filed.
  • I believe this is a legitimate feature request, not just a question or bug.

Feature Request Description

Summary

There is currently no way to clear only the query-answer cache (cache_type="query"/"keywords" rows in llm_response_cache) through the live server without also deleting every document — an offline CLI tool with this exact scope already exists (see "Prior art already in the repo" below), but it has no REST equivalent. The only cache-clearing path on the server, DELETE /documents?clear_llm_cache=true, is documented as deliberately bundled with full document deletion:

"Clearing the LLM cache is only available here, folded into this endpoint rather than exposed as its own route..." — document_routes.py L5892-L5893

"The REST surface reaches this through DELETE /documents?clear_llm_cache=true, which runs inside the destructive reservation. There is deliberately no endpoint that calls it without one." — LightRAG.aclear_cache() docstring, lightrag.py L5486-L5489

This is not a request to reverse #3926. #3926 removed the old standalone POST /documents/clear_cache because it dropped the entire cache with no pipeline reservation. That removal was correct and this proposal doesn't touch it — see "Why this isn't a rehash of #3920" below for why a query/keywords-only route doesn't reopen the problem #3926 closed.

That design is correct for the extraction cache (cache_type="extract"), which is genuinely unsafe to drop standalone. But the answer cache has no such constraint, and today there is no way to reach it through the live server without taking the whole corpus down with it — an offline CLI tool for exactly this scope already exists (see "Prior art already in the repo" below), but it requires separate process/filesystem access and has no REST equivalent.

Problem

The query-answer cache has no freshness tie to corpus state. Once a query's answer is cached, ingesting new documents never invalidates it — the cache key (generate_cache_key(), {mode}:{cache_type}:{hash} in lightrag/utils.py) is built entirely from the query text, mode, and generation parameters; nothing about it reflects what's currently in the KG or vector store. Re-asking the exact same question after adding a document that should change the answer returns the stale pre-ingestion answer, silently, with no indication it's cached.

The only current remedy, DELETE /documents?clear_llm_cache=true, throws away the corpus to get a fresh cache — not a workable trade for anyone who wants freshness without re-ingesting everything.

Why this isn't a rehash of #3920

#3920 (closed) and its implementing PR #3926 removed a previous standalone POST /documents/clear_cache endpoint, for a real and well-documented reason: that endpoint dropped the entire cache with no pipeline reservation, which (a) wiped extraction rows in-flight ingestion had already paid for, forcing an expensive re-bill on reprocess, and (b) orphaned llm_cache_list references — each text chunk's list of extraction-cache rows it depends on for reachability/reuse.

That failure mode is specific to the extraction cache (cache_type="extract"), not the query/keywords cache this request is about:

The only function that ever appends a cache-key reference to a chunk's llm_cache_list is update_chunk_cache_list (lightrag/utils.py), called solely from inside use_llm_func_with_cache, gated on chunk_id is not None — storage backends' upsert() also default-initialize the field to [] on any text_chunks write, but that's unrelated to reference attachment. Across the whole codebase, use_llm_func_with_cache has exactly 4 call sites: parser/native_base.py (cache_type="smartheading", no chunk_id), operate.py for summary generation (cache_type="summary", no chunk_id), and two entity/relation extraction sites (cache_type="extract", both of which do pass chunk_id). Only "extract" rows ever get attached to llm_cache_list — not even "summary", despite also being an extraction-adjacent cache type.

Every CacheData constructed for cache_type="query"/"keywords" (three call sites, all in operate.py) omits chunk_id entirely, so it's always None — these rows are structurally never candidates for llm_cache_list attachment. This isn't just an artifact of those three call sites; it's a design-level guarantee the codebase states directly: lightrag.py defines _REFERENCE_CARRYING_CACHE_TYPES: frozenset[str] = frozenset({"extract"}), with a comment reading "summary/smartheading/analysis name no chunk, and query/keywords rows hold full LLM answers that no reachability rule covers." docs/design/PurgeRecoveryContract.md says the same thing independently: "query/keywords rows... hold full LLM answers, name no chunk and are covered by no reachability rule at all."

So dropping only cache_type="query"/"keywords" rows cannot reproduce either harm #3920 was about: there's no in-flight extraction work to lose (that's a different cache), and there's nothing left dangling (nothing points at these rows in the first place).

One honest caveat: query/keyword cache entries have no natural chunk_id because they're synthesized across many chunks (or none), not one — the invariant holds structurally, not incidentally, so this isn't a gap waiting to drift on its own. The only realistic way it breaks is a future feature reusing the "query"/"keywords" cache_type string for a genuinely chunk-scoped operation by mistake (e.g. a per-chunk rerank step routed through use_llm_func_with_cache and mislabeled instead of given its own cache_type) — worth guarding with a cheap lint or test asserting cache_type → chunk_id-nullability, either as part of this change or standalone.

Prior art already in the repo

lightrag/tools/clean_llm_query_cache.py already implements exactly this scope as an offline CLI tool — per-backend key-scanning/deletion for cache_type in {"query","keywords"} only, for whichever KV backend is selected at runtime (JsonKVStorage, RedisKVStorage, PGKVStorage, MongoKVStorage, or OpenSearchKVStorage — picked from an interactive menu, one per run, not all simultaneously), explicitly leaving extraction caches untouched, and its QUERY_MODES already covers naive alongside local/global/hybrid/mix. Its only safety caveat is JsonKVStorage-specific (two OS processes cannot safely write the same JSON file concurrently — a file-handle issue, not a data-integrity one), and it has zero awareness of pipeline_status/busy — it's a fully standalone script today.

Scope: cache_type selection, not query-mode selection

Worth being explicit about what axis this route lets a caller choose along, given the removed endpoint's history here.

cache_type (query / keywords / both) is worth exposing, but the two serve different purposes — neither is simply "the small version of the other."

For corpus freshness — what this proposal is otherwise about — the two are not symmetric. Keyword-extraction cache entries are derived from the query text alone and don't go stale as the corpus changes, so clearing "keywords" without also clearing "query" accomplishes close to nothing for corpus freshness: the next identical query just re-extracts keywords (paying for an LLM call) and, if extraction reproduces the same strings — the common case — recomputes the same query-cache hash and serves the same stale answer anyway (verified: get_keywords_from_query runs and its result is folded into the query-cache hash before the query-cache is even looked up — operate.py L4747 vs L4894). Clearing "query" alone, by contrast, is both correct and the cheap option for that goal: it forces regeneration against the current corpus while reusing still-valid keyword extraction.

But "keywords"-only has a genuine, separate use case, already established by the existing CLI tool rather than argued fresh here: a storage/rebuild-cost tradeoff, not a freshness one. clean_llm_query_cache.py's own README documents this as two of its four use cases, symmetric in both directions — "Refresh query caches only... keeping keywords" → "Query caches deleted, keywords preserved for faster rebuild", and "Clean stale keywords... keeping recent query results" → "Keywords deleted, query caches preserved." The same reasoning holds for "query"-only in the other direction: an operator may want to drop one type while preserving the other purely to control what gets re-paid-for (in LLM calls) on the next round of queries, independent of any freshness argument. This proposal doesn't invent that use case — it just gives the live server the same three-way selector (query/keywords/both) the offline tool already ships with.

Query mode (local/global/hybrid/mix/naive) is deliberately not proposed as a selectable filter here. clean_llm_query_cache.py itself doesn't support it either — its own README lists "Selective mode cleanup" under Future Enhancements, not shipped — so scoping this proposal to what that tool already does keeps the ask minimal and grounded in reusable logic rather than a new capability. Given the endpoint's history of two prior reverts, a narrower first ask seems more likely to land than a broader one.

Proposal

  • A new route, e.g. DELETE /documents/cache/query, taking a cache_type selector ("query", "keywords", or both — default both) but no mode filter, clearing the selected type(s) across all query modes, leaving the remaining cache_type values ("extract"/"summary"/"smartheading") untouched.
  • Reuse clean_llm_query_cache.py's existing per-backend key-scanning logic rather than reimplementing it. Concretely: lift its delete_query_caches_json/redis/pg/mongo/opensearch methods onto their respective BaseKVStorage subclasses behind one new method (e.g. delete_by_cache_type(cache_types: set[str]) -> int), then have both the CLI tool and the new route call that instead of each keeping its own copy. The per-backend logic itself is already written and shipped in the CLI tool, so this is relocation onto a shared interface, not new deletion logic — comparably scoped to #3926, which shipped as one PR across the route, lightrag.py, WebUI, and tests. One thing worth fixing during that move rather than carrying forward: delete_query_caches_pg builds its DELETE ... WHERE id LIKE '...' clause via f-string interpolation instead of parameterized values. Not exploitable today (the interpolated values come from the fixed QUERY_MODES constant, not caller input), but worth cleaning up while this code is being relocated onto BaseKVStorage anyway.
  • I believe this route should hold the same _acquire_destructive_busy reservation clear_documents uses, even though the rows aren't referenced anywhere so nothing here is unsafe for data-integrity reasons the way the extraction-cache drop was. The reason is consistency, not correctness: #3920's outcome was that every destructive cache/document operation on this surface holds the reservation, and a new route that doesn't would reopen exactly the asymmetry #3920 closed. Open to being talked out of it if a maintainer sees it differently, but proposing it as the default rather than leaving it open.
  • Deliberately manual/opt-in, not automatically triggered by document ingestion. I looked into auto-invalidating on ingest and don't think it's viable: there's no single reliable "batch finished" signal (the busy → False release path is duplicated across multiple points in pipeline.py and reachable from many call sites, and enqueue-while-processing plus mailbox auto-rescan mean busy: False means "idle right now," not "corpus stopped changing"). Under continuous/trickle ingestion, auto-invalidation would degrade toward per-document cache wipes and defeat the cache's purpose. A manual route puts the "my ingestion job is done" judgment where it's actually reliable — with the caller.

Additional Context

Everything above is checked against main @ [6702eea91]

Happy to prepare a PR for this if the request and scoping above holds up to review — wanted to check the design first given the endpoint's history.