fix(runtime): compose cached delta history in the inner saver's canonical order (#8243)

* fix(runtime): compose cached delta history in the inner saver's canonical order

_channel_writes() re-sorted a checkpoint's pending_writes by task_id
only. The canonical per-checkpoint order is writes_sort_key =
(task_path, task_id, idx): InMemorySaver returns pending_writes through
_ordered_writes, which sorts by task_path first, and its native
get_delta_channel_history walk collects with the same order.

A stable task_id-only sort therefore reorders writes on fan-out
supersteps whenever task_path order differs from task_id order, and the
cached history then disagrees with the authoritative walk: an
order-sensitive reducer rebuilds a different value from cache than from
the inner saver.

get_tuple() already hands us the canonical order for every supported
backend (the SQL savers emit ORDER BY task_id, idx), so simply filter
by channel and drop the re-sort.

* docs(runtime): attribute sqlite ordering correctly and bump cache format to v2

Two follow-ups from review:

- _channel_writes() claimed the SQL savers emit ORDER BY task_id, idx.
  Only postgres does (array_agg(... ORDER BY cw.task_id, cw.idx));
  sqlite's pending_writes_sql has no ORDER BY and load_pending_writes
  sorts in Python by writes_sort_key(task_path, task_id, idx). The
  docstring now attributes each backend's ordering correctly, and notes
  the dropped task_id re-sort broke sqlite the same way it broke
  InMemorySaver.
- CACHE_FORMAT_VERSION 1 -> 2: entries composed under the old
  task_id-sorted order still pass valid_history_entry (shape-only) and
  are keyed identically, so a Redis-backed deployment would keep serving
  mis-ordered histories until TTL expiry. The versioned default prefix
  orphans them on upgrade. Test pin and both mdx pages updated.

* test(runtime): pin the default prefix assertion to CACHE_FORMAT_VERSION

test_key_prefix_override_wins hard-coded startswith("ckpt-hist:v1:") and
broke when the format version moved to 2. Derive the expectation from
CACHE_FORMAT_VERSION so future bumps do not need to touch this test, and
refresh the fake v1 prefix in the thread-purge test for consistency.

* fix(runtime): attribute the postgres pending-writes order to _load_writes

langgraph-checkpoint-postgres 3.1.3 (pinned in backend/uv.lock) aggregates
pending writes with a bare array_agg(...) in SELECT_SQL -- no ORDER BY -- and
the canonical writes_sort_key order comes from _load_writes sorting in
Python, the same mechanism sqlite uses. The docstring claimed postgres orders
with array_agg(... ORDER BY cw.task_id, cw.idx); that ordered aggregate only
exists in the legacy pending-sends migration. Also record that the dropped
task_id re-sort broke postgres the same way it broke sqlite/InMemorySaver.

* fix(runtime): purge legacy Redis checkpoint history on thread cleanup

* docs(checkpoint-cache): clarify no-TTL purge residue

---------

Co-authored-by: laoyyu <laoyyu@users.noreply.github.com>
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
This commit is contained in:
laoyyu 2026-11-22 21:44:23 +08:00 committed by GitHub
parent 29c5a1d7d0
commit 1dafd8a3b4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
12 changed files with 187 additions and 53 deletions

View File

@ -88,6 +88,7 @@ Open http://localhost:2026.
- All configuration options, providers and manual setup: [Configuration](docs/guide/configuration.md)
- Docker details, sizing, upgrades, startup modes and production deployment: [Running the Application](docs/guide/deployment.md)
- Upgrading a custom Redis checkpoint cache prefix: [Redis checkpoint history cache upgrade](docs/guide/deployment.md#redis-checkpoint-history-cache-upgrade)
- Running on a server or exposing it beyond localhost: read the [Security Notice](docs/guide/security.md) first
## From Deep Research to Super Agent Harness

View File

@ -48,6 +48,9 @@ make test-blocking-io
LLM error fallback.
- **Delta resume and rollback rewrite the current head.** They do not fork.
Reject a missing tuple or pending sends before the first write.
- **Redis history cache purges include the previous default namespace.** On
the v1-to-v2 upgrade, purge thread data under both prefixes for the same
database identity. Custom namespaces have an operator-managed migration.
## Admission and terminal commit

View File

@ -20,7 +20,12 @@ import hashlib
from dataclasses import dataclass
from typing import Any, Protocol
CACHE_FORMAT_VERSION = 1
# v2: delta-history composition now keeps the inner saver's canonical
# ``writes_sort_key`` order instead of re-sorting by ``task_id``. Entries
# cached under v1 may hold mis-ordered histories yet still pass
# ``valid_history_entry`` (a shape-only check), so upgraded readers skip
# them by using a new default prefix.
CACHE_FORMAT_VERSION = 2
def valid_history_entry(entry: Any, *, channel: str | None = None) -> bool:

View File

@ -54,11 +54,15 @@ def checkpoint_cache_db_hash(db_config: Any) -> str:
return hashlib.sha256(identity.encode()).hexdigest()[:12]
def _default_key_prefix(app_config: AppConfig, version: int) -> str:
return f"ckpt-hist:v{version}:{checkpoint_cache_db_hash(app_config.database)}"
def checkpoint_cache_key_prefix(app_config: AppConfig) -> str:
cache_config = app_config.database.checkpoint_cache
if cache_config.key_prefix:
return cache_config.key_prefix
return f"ckpt-hist:v{CACHE_FORMAT_VERSION}:{checkpoint_cache_db_hash(app_config.database)}"
return _default_key_prefix(app_config, CACHE_FORMAT_VERSION)
@contextlib.asynccontextmanager
@ -91,6 +95,8 @@ async def make_checkpoint_cache(
_resolve_redis_url(config),
serde=serde,
ttl_seconds=config.ttl_seconds,
# v1 keys may still contain thread data, including keys without a TTL.
legacy_key_prefix=_default_key_prefix(app_config, 1) if not config.key_prefix else None,
)
logger.info("Checkpoint history cache initialised: redis (ttl_seconds=%d)", config.ttl_seconds)
try:

View File

@ -58,12 +58,14 @@ class RedisCheckpointHistoryCache:
serde: Any,
ttl_seconds: int,
max_connections: int | None = None,
legacy_key_prefix: str | None = None,
) -> None:
self._client = _create_client(redis_url, max_connections=max_connections)
self._serde = serde
# ttl_seconds=0 is an explicit opt-out of expiry (no SETEX) — not the
# default, and leaked/orphaned keys then rely on redis maxmemory only.
self._ttl = ttl_seconds if ttl_seconds > 0 else None
self._legacy_key_prefix = legacy_key_prefix
self._hits = 0
self._misses = 0
self._write_serialization_failures = 0
@ -133,9 +135,12 @@ class RedisCheckpointHistoryCache:
_warn("checkpoint history cache write failed; skipping: %s", exc)
async def adelete_thread(self, key_prefix: str, thread_id: str) -> None:
"""SCAN+UNLINK every entry of one thread. Failure degrades to
TTL-bounded residual retention; the source-of-truth delete already
happened, so this never raises."""
"""Purge the thread from the active and previous default namespaces."""
await self._purge_prefix(key_prefix, thread_id)
if self._legacy_key_prefix is not None and self._legacy_key_prefix != key_prefix:
await self._purge_prefix(self._legacy_key_prefix, thread_id)
async def _purge_prefix(self, key_prefix: str, thread_id: str) -> None:
stem = thread_key_stem(key_prefix, thread_id)
# The configured namespace is a literal key prefix, not a Redis glob.
pattern = "".join("\\" + char if char in "\\*?[]" else char for char in stem) + "*"
@ -152,7 +157,7 @@ class RedisCheckpointHistoryCache:
if cursor == 0:
break
except _redis_error() as exc:
_warn("checkpoint history cache thread purge failed; residual entries expire via TTL: %s", exc)
_warn("checkpoint history cache thread purge failed; cached entries may remain: %s", exc)
def stats(self) -> CheckpointCacheStats:
return CheckpointCacheStats(

View File

@ -1,9 +1,8 @@
"""Read-through delta-history cache wrapper for a canonical BaseCheckpointSaver.
The inner saver must return delta history in ascending ``(task_id, idx)``
order per checkpoint, with each task's ``pending_writes`` in ``idx`` order.
The in-repo memory, sqlite, and postgres backends satisfy this contract;
the base saver's default history walk alone does not guarantee it.
The inner saver must return each checkpoint's ``pending_writes`` in the
same order used by its delta history walk. The supported memory, SQLite,
and PostgreSQL savers use ``writes_sort_key(task_path, task_id, idx)``.
Correctness argument (spec §3): a checkpoint's delta history is a pure
function of its sealed ancestor chain — the LangGraph contract excludes the
@ -53,22 +52,13 @@ def _checkpoint_ref(tup: CheckpointTuple) -> tuple[str, str, str]:
def _channel_writes(tup: CheckpointTuple, channel: str) -> list[PendingWrite]:
"""Writes for one channel in the inner saver's canonical delta order.
The wrapper assumes the inner saver's ``get_delta_channel_history`` uses
ascending ``(task_id, idx)`` order per checkpoint; the base implementation
instead iterates ``pending_writes`` in storage order. For supported savers,
``CheckpointTuple.pending_writes`` carries each task's writes in ``idx``
order, but across tasks it follows
*storage/completion* order, which the InMemorySaver backend leaves in task
arrival order rather than ``task_id`` order. Composing from that raw order
makes the cached history disagree with the inner saver on fan-out
supersteps (several parallel tasks writing one channel). A stable sort by
``task_id`` restores the canonical ``(task_id, idx)`` order while preserving
each task's internal ``idx`` sequence; it is a no-op on backends that
already return writes ``ORDER BY task_id, idx`` (sqlite, postgres).
``InMemorySaver`` sorts stored writes with ``writes_sort_key``. SQLite's
``load_pending_writes`` and PostgreSQL's ``_load_writes`` apply the same
key to writes returned by the database. Filtering preserves the delta
walk's replay order. Sorting by ``task_id`` alone can reorder parallel
writes whose task paths sort differently and change the reducer's result.
"""
writes = [w for w in (tup.pending_writes or []) if w[1] == channel]
writes.sort(key=lambda w: w[0])
return writes
return [w for w in (tup.pending_writes or []) if w[1] == channel]
class CachedHistorySaver(BaseCheckpointSaver):

View File

@ -10,7 +10,7 @@ from langgraph.checkpoint.memory import InMemorySaver
from deerflow.runtime.checkpoint_cache.memory import MemoryCheckpointHistoryCache
from deerflow.runtime.checkpointer.cached_saver import CachedHistorySaver
PREFIX = "ckpt-hist:v1:testdb"
PREFIX = "test-history-cache"
class _DictSaver(BaseCheckpointSaver):
@ -478,3 +478,69 @@ def test_sync_fanout_compose_matches_inner_canonical_order():
assert _write_task_ids(composed) == _write_task_ids(expected)
assert composed[_FANOUT_CHANNEL]["writes"] == expected[_FANOUT_CHANNEL]["writes"]
# ----------------------------------------------------------------------
# Fan-out with distinct task_paths: canonical order is
# ``writes_sort_key`` = (task_path, task_id, idx), NOT task_id alone.
#
# ``InMemorySaver.get_tuple`` / its native delta walk both return a
# checkpoint's ``pending_writes`` via ``_ordered_writes``, which sorts by
# ``writes_sort_key`` (task_path first). Composing from ``get_tuple``'s
# order therefore already matches the authoritative walk; re-sorting by
# ``task_id`` alone reorders writes whenever the two orders differ.
# ----------------------------------------------------------------------
def _seed_fanout_distinct_task_paths(saver: InMemorySaver) -> dict:
"""Same chain as _seed_fanout_thread, but the two fan-out writes have
distinct task_paths whose order is the REVERSE of their task_id order."""
thread_id = f"fanout-tp-{uuid4().hex}"
base = {"configurable": {"thread_id": thread_id, "checkpoint_ns": ""}}
cfg0 = saver.put(base, empty_checkpoint(), {}, {})
c1 = empty_checkpoint()
c1["channel_values"] = {_FANOUT_CHANNEL: ["seed"]}
c1["channel_versions"] = {_FANOUT_CHANNEL: "1"}
cfg1 = saver.put(cfg0, c1, {}, {_FANOUT_CHANNEL: "1"})
# task_id order: task-a < task-z; task_path order: "1|aaa" < "1|zzz".
# Canonical (task_path, task_id, idx) replays task-z FIRST.
saver.put_writes(cfg1, [(_FANOUT_CHANNEL, ["fan-z"])], "task-z", "1|aaa")
saver.put_writes(cfg1, [(_FANOUT_CHANNEL, ["fan-a"])], "task-a", "1|zzz")
return saver.put(cfg1, empty_checkpoint(), {}, {})
@pytest.mark.anyio
async def test_fanout_distinct_task_paths_compose_matches_inner_order():
"""A task_id-only sort would replay task-a before task-z; the inner
saver's canonical task_path order replays task-z first."""
oracle = InMemorySaver()
oracle_cfg = _seed_fanout_distinct_task_paths(oracle)
expected = await oracle.aget_delta_channel_history(config=oracle_cfg, channels=[_FANOUT_CHANNEL])
assert _write_task_ids(expected) == ["task-z", "task-a"] # canonical order
inner = InMemorySaver()
cfg = _seed_fanout_distinct_task_paths(inner)
saver = _wrap(inner, MemoryCheckpointHistoryCache(max_entries=16))
composed = await saver.aget_delta_channel_history(config=cfg, channels=[_FANOUT_CHANNEL])
assert _write_task_ids(composed) == _write_task_ids(expected)
assert composed[_FANOUT_CHANNEL]["writes"] == expected[_FANOUT_CHANNEL]["writes"]
def test_sync_fanout_distinct_task_paths_compose_matches_inner_order():
"""Sync twin: the sync compose path preserves the same canonical order."""
oracle = InMemorySaver()
oracle_cfg = _seed_fanout_distinct_task_paths(oracle)
expected = oracle.get_delta_channel_history(config=oracle_cfg, channels=[_FANOUT_CHANNEL])
assert _write_task_ids(expected) == ["task-z", "task-a"]
inner = InMemorySaver()
cfg = _seed_fanout_distinct_task_paths(inner)
saver = _wrap(inner, MemoryCheckpointHistoryCache(max_entries=16))
composed = saver.get_delta_channel_history(config=cfg, channels=[_FANOUT_CHANNEL])
assert _write_task_ids(composed) == _write_task_ids(expected)
assert composed[_FANOUT_CHANNEL]["writes"] == expected[_FANOUT_CHANNEL]["writes"]

View File

@ -11,6 +11,7 @@ from unittest.mock import AsyncMock, Mock
import pytest
from langgraph.channels import DeltaChannel
from langgraph.checkpoint.base import empty_checkpoint
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer
from langgraph.graph import StateGraph
@ -99,7 +100,7 @@ def test_make_history_key_is_stable_and_scoped():
assert k1 != make_history_key("ckpt-hist:v1:db0", "t1", "", "c2", "messages")
assert k1 != make_history_key("ckpt-hist:v1:db0", "t1", "", "c1", "todos")
assert k1 != make_history_key("ckpt-hist:v1:db9", "t1", "", "c1", "messages")
assert CACHE_FORMAT_VERSION == 1
assert CACHE_FORMAT_VERSION == 2
def test_get_many_miss_then_hit():
@ -719,7 +720,7 @@ async def test_zero_ttl_disables_expiry_explicitly(monkeypatch: pytest.MonkeyPat
async def test_adelete_thread_purges_matching_keys_only(monkeypatch: pytest.MonkeyPatch):
fake = _FakeRedis()
cache = _make_cache(monkeypatch, fake)
prefix = "ckpt-hist:v1:db0"
prefix = f"ckpt-hist:v{CACHE_FORMAT_VERSION}:db0"
await cache.aset_many(
{
f"{prefix}:t1:aaa": _redis_entry(1),
@ -744,6 +745,42 @@ async def test_adelete_thread_outage_degrades_without_raising(monkeypatch: pytes
assert "thread purge failed" in caplog.text
@pytest.mark.anyio
@pytest.mark.parametrize("key_prefix", ["", "tenant-history"])
async def test_thread_delete_after_redis_cache_upgrade(monkeypatch: pytest.MonkeyPatch, key_prefix: str) -> None:
config = _redis_app_config(
{
"backend": "sqlite",
"checkpoint_channel_mode": "delta",
"checkpoint_cache": {"type": "redis", "ttl_seconds": 0, "key_prefix": key_prefix},
}
)
fake = _FakeRedis()
cache = _make_cache(monkeypatch, fake, ttl_seconds=0)
async with make_checkpointer(config) as saver:
thread = {"configurable": {"thread_id": "t1", "checkpoint_ns": ""}}
checkpoint = empty_checkpoint()
saved = await saver.aput(thread, checkpoint, {}, {})
assert await saver.aget_tuple(saved) is not None
legacy_prefix = f"ckpt-hist:v1:{checkpoint_cache_db_hash(config.database)}"
active_key = make_history_key(checkpoint_cache_key_prefix(config), "t1", "", checkpoint["id"], "messages")
legacy_key = make_history_key(legacy_prefix, "t1", "", checkpoint["id"], "messages")
sibling_key = make_history_key(legacy_prefix, "t10", "", checkpoint["id"], "messages")
other_db_key = make_history_key("ckpt-hist:v1:other-db", "t1", "", checkpoint["id"], "messages")
await cache.aset_many({key: _redis_entry(1) for key in (active_key, legacy_key, sibling_key, other_db_key)})
assert fake.ttls[legacy_key] is None
await saver.adelete_thread("t1")
assert await saver.aget_tuple(saved) is None
expected = {sibling_key, other_db_key}
if key_prefix:
expected.add(legacy_key)
assert set(fake.store) == expected
@pytest.mark.anyio
async def test_provider_memory_default():
from deerflow.runtime.checkpoint_cache.memory import MemoryCheckpointHistoryCache
@ -798,12 +835,21 @@ def test_key_prefix_override_wins():
app_config = _redis_app_config({"backend": "sqlite", "checkpoint_cache": {"key_prefix": "custom:"}})
assert checkpoint_cache_key_prefix(app_config) == "custom:"
default = checkpoint_cache_key_prefix(_redis_app_config({"backend": "sqlite"}))
assert default.startswith("ckpt-hist:v1:")
assert default.startswith(f"ckpt-hist:v{CACHE_FORMAT_VERSION}:")
# --- test_checkpoint_cache_redis_literal_purge ---
@pytest.fixture
def redis_cache(monkeypatch: pytest.MonkeyPatch) -> tuple[RedisCheckpointHistoryCache, AsyncMock]:
client = AsyncMock()
client.connection_pool = Mock()
client.connection_pool.get_encoder.return_value.encode.side_effect = lambda value: value.encode("utf-8")
monkeypatch.setattr("deerflow.runtime.checkpoint_cache.redis._create_client", lambda *args, **kwargs: client)
return RedisCheckpointHistoryCache("redis://unused", serde=None, ttl_seconds=60), client
@pytest.mark.anyio
@pytest.mark.parametrize(
("prefix", "thread_id", "sibling_thread_id", "pattern"),
@ -816,15 +862,11 @@ def test_key_prefix_override_wins():
("plain", "t1*", "t10", r"plain:t1\*:*"),
],
)
async def test_purge_escapes_namespace_and_filters_results(prefix, thread_id, sibling_thread_id, pattern):
async def test_purge_escapes_namespace_and_filters_results(redis_cache, prefix, thread_id, sibling_thread_id, pattern):
# Exercise the actual purge method without needing a running Redis server.
# The expected SCAN pattern is a wire-level Redis glob contract; returned
# keys also include a foreign namespace to pin the final deletion fence.
cache = RedisCheckpointHistoryCache.__new__(RedisCheckpointHistoryCache)
client = AsyncMock()
cache._client = client
client.connection_pool = Mock()
client.connection_pool.get_encoder.return_value.encode.side_effect = lambda value: value.encode("utf-8")
cache, client = redis_cache
owned = make_history_key(prefix, thread_id, "", "c1", "messages").encode()
foreign = make_history_key("tenant-other", thread_id, "", "c1", "messages").encode()
sibling = make_history_key(prefix, sibling_thread_id, "", "c1", "messages").encode()
@ -846,23 +888,17 @@ async def test_purge_escapes_namespace_and_filters_results(prefix, thread_id, si
@pytest.mark.anyio
async def test_purge_does_not_unlink_empty_filtered_page():
cache = RedisCheckpointHistoryCache.__new__(RedisCheckpointHistoryCache)
cache._client = AsyncMock()
cache._client.connection_pool = Mock()
cache._client.connection_pool.get_encoder.return_value.encode.side_effect = lambda value: value.encode("utf-8")
cache._client.scan.return_value = (0, [b"other:t1:history"])
async def test_purge_does_not_unlink_empty_filtered_page(redis_cache):
cache, client = redis_cache
client.scan.return_value = (0, [b"other:t1:history"])
await cache.adelete_thread("owned", "t1")
cache._client.unlink.assert_not_awaited()
client.unlink.assert_not_awaited()
@pytest.mark.anyio
async def test_purge_uses_client_encoding_for_byte_key_fence():
async def test_purge_uses_client_encoding_for_byte_key_fence(redis_cache):
"""A non-UTF-8 Redis client must still unlink its own non-ASCII keys."""
cache = RedisCheckpointHistoryCache.__new__(RedisCheckpointHistoryCache)
client = AsyncMock()
cache._client = client
client.connection_pool = Mock()
cache, client = redis_cache
client.connection_pool.get_encoder.return_value.encode.side_effect = lambda value: value.encode("latin-1")
owned = make_history_key("café", "t1", "", "c1", "messages").encode("latin-1")
sibling = make_history_key("café", "t10", "", "c1", "messages").encode("latin-1")

View File

@ -109,6 +109,7 @@ async def test_checkpoint_cache_redis_context_drains_close_across_repeated_cance
max_entries=128,
redis_url="redis://localhost:6379/0",
ttl_seconds=60,
key_prefix="",
)
)
)

View File

@ -306,6 +306,15 @@ rolling upgrade, route keyed runs with ID-less input and their retries to
upgraded workers until all Gateway workers are upgraded; older workers may
reject those retries with 409. See the [run API contract](../../backend/docs/API.md#create-run).
### Redis checkpoint history cache upgrade
The v2 cache rebuilds histories under a new default prefix. Deleting or pruning
a thread also purges its v1 entries for the same database, including entries
without expiry. If `database.checkpoint_cache.key_prefix` is set, stop all
workers using that prefix, clear this deployment's Redis checkpoint history
keys, and then start the upgraded workers. Custom prefixes keep the same name
across cache versions.
## Option 2: Local Development
If you prefer running services locally:

View File

@ -64,10 +64,16 @@ That is why the whole policy is performance-only and safe to differ per worker.
| `thread_id` is left readable | Ops can identify a thread's keys without recomputing the digest |
| The remaining components are hashed with NUL separators | A namespace containing `:` cannot produce an ambiguous key |
| Thread purge stem | `{key_prefix}:{thread_id}:` — a prefix match, never per-key invalidation |
| Default prefix | `ckpt-hist:v{CACHE_FORMAT_VERSION}:{hash12(database identity)}`, with `CACHE_FORMAT_VERSION = 1` |
| Default prefix | `ckpt-hist:v{CACHE_FORMAT_VERSION}:{hash12(database identity)}`, with `CACHE_FORMAT_VERSION = 2` |
| `database.checkpoint_cache.key_prefix` | Replaces the whole derived prefix |
| Database identity | Credential-free: postgres `host:port/database:schema`, the sqlite path, else `memory`. Rotating credentials does not change the namespace, so a credential rotation cannot cold-start the cache and orphan keys until TTL. Two deployments sharing one redis get different prefixes by default. |
### Upgrading the Redis history cache from v1 to v2
With the default prefix, upgraded workers rebuild histories in v2. Thread deletion and pruning also purge that thread's v1 entries for the same database, even if `ttl_seconds: 0` disables expiry.
If you set `database.checkpoint_cache.key_prefix`, stop all workers using that prefix and clear its Redis checkpoint history keys before starting upgraded workers. The custom prefix stays the same across versions, so it can still return histories in the old write order until you clear it. On a shared Redis instance, delete only this deployment's checkpoint history keys.
## Compose instead of walk
Real runs create several checkpoints per super-step and only some are ever materialized as targets, so a target's direct parent is usually an unwarmed intermediate checkpoint. Composing only one level deep therefore measured zero cache hits on a 500-step sqlite run. The wrapper composes instead:
@ -148,9 +154,9 @@ Every redis failure is performance-only. The source of truth has already been up
| --- | --- | --- |
| `mget` fails | `checkpoint history cache mget failed; treating as all-miss: %s` | Every requested key counts as a miss; histories are recomposed |
| Write fails | `checkpoint history cache write failed; skipping: %s` | The write is skipped; the next read simply recomputes |
| Thread purge fails | `checkpoint history cache thread purge failed; residual entries expire via TTL: %s` | The source delete already happened; residual copies expire via `ttl_seconds`; this path never raises |
| Thread purge fails | `checkpoint history cache thread purge failed; cached entries may remain: %s` | The source delete already happened. Residual keys expire only if they have a TTL |
The TTL is a leak safety net, not a correctness mechanism, because entries are immutable and no read depends on them. `ttl_seconds: 0` opts out of expiry entirely, so orphaned keys then rely on the redis `maxmemory` policy alone. A failed purge is the only way a deleted thread's history lingers, and only until the TTL.
The TTL is a leak safety net, not a correctness mechanism, because entries are immutable and no read depends on them. `ttl_seconds: 0` opts out of expiry entirely, so orphaned keys then rely on the redis `maxmemory` policy alone. A failed purge is the only way a deleted thread's history lingers; residual keys expire at the configured TTL, or remain operator-managed when `ttl_seconds: 0`.
## Stats

View File

@ -63,10 +63,16 @@ import { Callout } from "nextra/components";
| `thread_id` 保持可读 | 运维不必重算摘要就能认出某个线程的键 |
| 其余成分以 NUL 分隔后哈希 | 含 `:` 的命名空间不可能产生有歧义的键 |
| 线程清理前缀 | `{key_prefix}:{thread_id}:`,按前缀匹配,绝不做逐键失效 |
| 默认前缀 | `ckpt-hist:v{CACHE_FORMAT_VERSION}:{hash12(database identity)}`,其中 `CACHE_FORMAT_VERSION = 1` |
| 默认前缀 | `ckpt-hist:v{CACHE_FORMAT_VERSION}:{hash12(database identity)}`,其中 `CACHE_FORMAT_VERSION = 2` |
| `database.checkpoint_cache.key_prefix` | 整体替换派生前缀 |
| 数据库身份 | 不含凭据:postgres 为 `host:port/database:schema`,sqlite 为文件路径,其余为 `memory`。轮换凭据不会改变命名空间,否则一次凭据轮换就会让缓存变冷、并让旧键一直孤儿到 TTL。两个部署共用同一个 redis 时,默认前缀不同。 |
### 将 Redis 历史缓存从 v1 升级到 v2
使用默认前缀时,升级后的 worker 会在 v2 命名空间中重建历史。删除或裁剪线程时,也会清理同一数据库下该线程的 v1 缓存条目,包括 `ttl_seconds: 0` 时写入的无过期条目。
如果配置了 `database.checkpoint_cache.key_prefix`,请先停止所有使用该前缀的 worker,清理该前缀下的 Redis 检查点历史缓存,再启动升级后的 worker。自定义前缀不会随版本变化,清理前仍可能读到按旧顺序保存的历史。多个部署共用 Redis 时,只清理本部署的检查点历史缓存键。
## 用合成代替回溯
真实运行中每个 super-step 会创建多个检查点,只有其中一部分会被真正物化成读取目标,因此目标的直接父级通常是尚未预热的中间检查点。只合成一层时,实测在 500 步的 sqlite 运行上是零命中。于是包装器改为逐层合成:
@ -136,9 +142,9 @@ redis 客户端是惰性导入的;缺少可选依赖时构造 redis 后端会
| --- | --- | --- |
| `mget` 失败 | `checkpoint history cache mget failed; treating as all-miss: %s` | 所有请求的键都按未命中处理,历史被重新合成 |
| 写入失败 | `checkpoint history cache write failed; skipping: %s` | 跳过该次写入,下次读取直接重算 |
| 线程清理失败 | `checkpoint history cache thread purge failed; residual entries expire via TTL: %s` | 源删除已经完成;残余副本会随 `ttl_seconds` 过期;这条路径从不抛异常 |
| 线程清理失败 | `checkpoint history cache thread purge failed; cached entries may remain: %s` | 源数据已删除。残余键只有设置了 TTL 才会过期 |
TTL 是防泄漏网而非正确性机制,因为条目不可变、没有任何读取依赖它。`ttl_seconds: 0` 表示彻底关闭过期,此时孤儿键只依赖 redis 的 `maxmemory` 策略。清理失败是已删除线程的历史残留下来的唯一途径,且只残留到 TTL 到期。
TTL 是防泄漏网而非正确性机制,因为条目不可变、没有任何读取依赖它。`ttl_seconds: 0` 表示彻底关闭过期,此时孤儿键只依赖 redis 的 `maxmemory` 策略。清理失败是已删除线程的历史残留下来的唯一途径;残余键会在配置的 TTL 到期后过期,若 `ttl_seconds: 0`,则需由运维处理。
## stats