fix(runtime): page thread history from the before cursor (#8398)

* fix(runtime): page thread history from the before cursor

POST /api/threads/{id}/history passed body.before as config.checkpoint_id
to get_state_history, but LangGraph savers match checkpoint_id exactly in
list(), so a before cursor always returned that single checkpoint. Treat
it as the inclusive start of the walk (anchor, then list(before=anchor)),
which is what the Gateway's degraded raw accessor already does and what
its comment says the graph path does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(gateway): state that the history before cursor is inclusive

LangGraph's own history API treats before as exclusive; spell out that
this endpoint returns the cursor checkpoint first so paging clients do
not double-count the boundary entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(gateway): clarify history pagination after cursor pruning

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
This commit is contained in:
Luck 2026-11-22 10:23:23 +08:00 committed by GitHub
parent b6b0be211e
commit aa78349751
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 78 additions and 3 deletions

View File

@ -664,7 +664,15 @@ class ThreadHistoryRequest(BaseModel):
"""Request body for checkpoint history."""
limit: int = Field(default=10, ge=1, le=100, description="Maximum entries")
before: str | None = Field(default=None, description="Cursor for pagination")
before: str | None = Field(
default=None,
description=(
"Inclusive checkpoint ID cursor. The page starts with the cursor checkpoint if it still exists, "
"followed by older checkpoints up to `limit` entries. If retention removed the cursor, the page starts "
"with the first surviving older checkpoint, if any. When continuing, skip the first entry only if "
"its `checkpoint_id` equals `before`."
),
)
class ThreadBranchRequest(BaseModel):

View File

@ -229,6 +229,12 @@ GET /api/langgraph/threads/{thread_id}/state
POST /api/langgraph/threads/{thread_id}/history
```
Set `before` to the last checkpoint ID from the previous page. The next page
includes that checkpoint if it still exists, followed by older checkpoints,
up to `limit` entries total. If checkpoint retention removed the cursor, the
page starts with the first surviving older checkpoint, if any. Skip the first
entry only when its `checkpoint_id` equals `before`.
Only the newest entry carries `messages`, the `goal` while it is active, and
`goal_outcome` (the latest met goal, kept until the next goal change). Older
entries carry only `title` and `thread_data`. `goal_outcome` is server-owned:

View File

@ -236,7 +236,22 @@ class CheckpointStateAccessor:
if limit is not None and limit <= 0:
return []
result = []
async for snapshot in self.graph.aget_state_history(prepared, limit=limit):
walk_config = prepared
before = None
if prepared["configurable"].get("checkpoint_id"):
# Savers match config.checkpoint_id exactly in ``list``, so
# get_state_history would return only the anchor. Treat it as the
# inclusive start of the walk, like the Gateway's raw accessor.
async for anchor in self.graph.aget_state_history(prepared, limit=1):
raise_if_snapshot_incompatible(anchor, self.mode)
result.append(anchor)
before = prepared
walk_config = {**prepared, "configurable": {k: v for k, v in prepared["configurable"].items() if k != "checkpoint_id"}}
if limit is not None and len(result) >= limit:
return result
remaining = None if limit is None else limit - len(result)
walk_kwargs = {"before": before} if before is not None else {}
async for snapshot in self.graph.aget_state_history(walk_config, limit=remaining, **walk_kwargs):
raise_if_snapshot_incompatible(snapshot, self.mode)
result.append(snapshot)
if limit is not None and len(result) >= limit:

View File

@ -26,7 +26,7 @@ from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import StateGraph
from langgraph.store.memory import InMemoryStore
from app.gateway import context_usage
from app.gateway import checkpoint_retention, context_usage
from app.gateway import services as gateway_services
from app.gateway.routers import thread_runs, threads
from deerflow.agents.thread_state import get_thread_state_schema
@ -35,6 +35,7 @@ from deerflow.persistence.thread_meta.memory import MemoryThreadMetaStore
from deerflow.runtime import RunManager
from deerflow.runtime.checkpoint_mode import checkpoint_metadata_uses_delta, inject_checkpoint_mode
from deerflow.runtime.runs.store.memory import MemoryRunStore
from deerflow.runtime.runs.worker import persist_run_history_metadata
_THREAD_ID = "thread-gateway-parity"
@ -116,6 +117,51 @@ def test_thread_state_endpoints_are_mode_invariant(_stub_app_config, monkeypatch
assert any(full["history_messages"]), "expected history snapshots with messages"
@pytest.mark.parametrize("mode", ["full", "delta"])
def test_history_before_cursor_continues_the_walk(mode: str, _stub_app_config, monkeypatch: pytest.MonkeyPatch) -> None:
"""A history page includes its cursor only while the checkpoint survives."""
app = make_authed_test_app()
store = InMemoryStore()
checkpointer = InMemorySaver()
app.state.store = store
app.state.checkpointer = checkpointer
app.state.thread_store = MemoryThreadMetaStore(store)
app.state.checkpoint_channel_mode = mode
app.state.run_event_store = SimpleNamespace()
app.include_router(threads.router)
graph = _build_reply_graph(mode, checkpointer)
monkeypatch.setattr(gateway_services, "resolve_agent_factory", lambda assistant_id=None: lambda config: graph)
config: dict[str, Any] = {"configurable": {"thread_id": _THREAD_ID}}
inject_checkpoint_mode(config, mode)
for i in range(2):
asyncio.run(graph.ainvoke({"messages": [HumanMessage(content=f"question-{i}", id=f"h{i}")]}, config))
with TestClient(app) as client:
full_page = client.post(f"/api/threads/{_THREAD_ID}/history", json={"limit": 10})
assert full_page.status_code == 200, full_page.text
all_ids = [entry["checkpoint_id"] for entry in full_page.json()]
assert len(all_ids) >= 4
anchor_id = all_ids[1]
paged = client.post(f"/api/threads/{_THREAD_ID}/history", json={"limit": 10, "before": anchor_id})
assert paged.status_code == 200, paged.text
assert [entry["checkpoint_id"] for entry in paged.json()] == all_ids[1:]
assert asyncio.run(persist_run_history_metadata(checkpointer=checkpointer, thread_id=_THREAD_ID, durations={"run-1": 3}))
first_page = client.post(f"/api/threads/{_THREAD_ID}/history", json={"limit": 1})
assert first_page.status_code == 200, first_page.text
cursor = first_page.json()[0]["checkpoint_id"]
assert cursor not in all_ids
report = asyncio.run(checkpoint_retention.enforce_trailing_duration_retention(checkpointer, _THREAD_ID))
assert report.deleted_checkpoint_ids == [cursor]
paged = client.post(f"/api/threads/{_THREAD_ID}/history", json={"limit": 2, "before": cursor})
assert paged.status_code == 200, paged.text
assert [entry["checkpoint_id"] for entry in paged.json()] == all_ids[:2]
@pytest.mark.parametrize("mode", ["full", "delta"])
def test_context_usage_reads_materialized_messages_in_both_modes(
mode: str,