relock
Project Overview
An orders API changes its date format. The agent learns to send 2026-03-14 and finishes
the task. Tomorrow it opens a fresh session, retrieves its old instructions, and sends
03/14/2026 again. I built relock for the part of that bug that lives
in memory. It’s a Python library that lets a tool-using agent revise the procedure it followed
when a real outcome contradicts what the procedure predicted.
The application supplies short procedures, each with a stable key, individual clauses and the tools it applies to. relock handles recall, evidence and revision history. The smallest setup uses the Python standard library, a SQLite database and a tool that can explain a rejected argument. It runs locally without a model call or an API key.
How a Procedure Changes
In relock, an episode is one task. When the orders agent recalls a procedure, relock
records which version it read. Wrapping get_orders records a prediction
that the call will succeed. That gives a later failure a specific
procedure, tool and version to attach to.
A typed validation failure carries full weight under the default policy. Two such failures can change a fresh rule. A rule with a long record of successes needs more evidence. Timeouts, rate limits and instructions encountered in a document contribute zero. A correction from a person can take effect immediately when the host application has authenticated them.
The default rewriter uses correction text supplied by a trusted source. A host can cite a particular clause when recording its prediction. The automatic tool wrapper leaves that choice open, so the rewriter looks for a clause whose wording matches the correction. If the evidence has no usable correction, it can leave the edit pending. An optional LLM rewriter proposes clause edits under the same validation rules.
Run the Orders Example
Install the core with python -m pip install relock-memory on Python 3.10 or later.
The script below starts with an empty in-memory database. A local function checks the shape of
a date, and a single conditional stands in for a model reading its instructions. That makes
the result repeatable and lets you see exactly what the library contributes.
import re
import relock_memory as relock
mem = relock.Memory(":memory:")
mem.add(
"Fetch orders by date",
["Select the current account.", "Send the date as MM/DD/YYYY."],
key="orders.fetch",
tools=["get_orders"],
)
@mem.wrap
def get_orders(day):
if not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}", day):
raise relock.ToolError(
"Date format rejected.", correction="Send the date as YYYY-MM-DD."
)
return f"Fetched orders for {day}."
for _ in range(3):
with mem.episode("Orders for March 14") as ep:
rules = ep.recall("fetch orders by date").render()
day = "2026-03-14" if "YYYY-MM-DD" in rules else "03/14/2026"
try:
print(get_orders(day))
except relock.ToolError as error:
print(error)
for version in mem.history("orders.fetch"):
print(version.version, version.status, version.clause("c2").text)
mem.close()
Date format rejected.
Date format rejected.
Fetched orders for 2026-03-14.
1 superseded Send the date as MM/DD/YYYY.
2 active Send the date as YYYY-MM-DD.
On the first call the evidence is pending. The second rejection reaches the threshold and
revises clause c2. On the third call the agent reads the new format. Both versions
still contain the account-selection clause, and both date instructions are available in history.
Ordinary recall serves only the active version.
Two Cases That Shaped the Implementation
A successful retry can hide a stale rule
Suppose the agent gets an error with a correction, follows it immediately and succeeds on retry. Which instruction did that success validate? Counting it for the old rule would cancel the evidence that the rule needs fixing. In v0.3.1, relock ignores that success as a confirmation when it follows a corrective failure on the same tool in the same episode. A later independent success on that tool and version can still cancel evidence from a one-off failure. Read the regression tests.
Two workers can recall the same version
Both workers may have read version 1 by the time the first publishes version 2. Inside its write transaction, the store checks that the version being replaced is still active. The second worker’s late evidence about version 1 produces a conflict. A partial unique index enforces one active version per item in SQLite and PostgreSQL. Rolling back copies the earlier clauses into a new version, so the audit trail still explains how the item got there. See the concurrency and rollback tests.
Connecting It to an Agent
| Where the agent runs | How outcomes reach memory |
|---|---|
| Python | Wrap a sync or async tool with @mem.wrap and open an episode around each task. Put ep.recall(query).render() in the agent’s prompt. |
| LangChain or LangGraph | A callback handler observes tool results. The agent can keep its existing tools and orchestration. |
| MCP client | The client can ask the server to run a named verifier. The verifier’s exit status supplies the evidence. The agent’s own report is logged separately. |
| HTTP client | The host opens an episode, recalls instructions, submits a real tool result and closes the episode. The repository includes TypeScript, Rust and curl clients. |
Keyword retrieval uses BM25 by default. An application that already has an embedding model can supply it and combine the two rankings. SQLite fits a local agent. PostgreSQL lets several workers share the same history. If you run several HTTP replicas, route each episode’s requests to one replica because its open edit window lives in that process. See the deployment notes.
What the Benchmark Measured
In RelapseBench, eight hosted models used four memory strategies across ten synthetic tool contracts. In the longest sessions, old documentation and an injected page remained in context. With relock, 701 of 716 scored calls followed the corrected rule (98%). Storing each lesson as a separate note produced 434 of 718 (60%). Keeping the evidence checks and still appending the note produced 530 of 718 (74%). These counts exclude provider errors.
The tasks each have one clearly correct tool argument, and the tool supplies the correction after a mistake. For an agent whose failures are ambiguous, the first engineering job is deciding what outcome it can reliably check. The companion article examines the other baselines, individual tasks and where the models still went wrong. Read the RelapseBench field notes.