| 1 |
"""`flush_writes` — the push-only shutdown pass. |
| 2 |
|
| 3 |
A session that ends on an error or cancel gets no full reconcile, but the |
| 4 |
writes already on disk are the only copy of the agent's edits. |
| 5 |
`flush_writes` pushes those and does nothing else: no remote deletes, no |
| 6 |
local removals, no pulls. |
| 7 |
""" |
| 8 |
|
| 9 |
from __future__ import annotations |
| 10 |
|
| 11 |
from typing import Any |
| 12 |
from pathlib import Path |
| 13 |
|
| 14 |
import anyio |
| 15 |
import pytest |
| 16 |
|
| 17 |
import anthropic.lib.tools._memories as memories_mod |
| 18 |
from anthropic.lib.tools._memories import MARKER_PATH, SessionMemoryStores |
| 19 |
|
| 20 |
from .conftest import run_sync |
| 21 |
from ._fake_anthropic import MemoryServer, created, updated, fake_anthropic |
| 22 |
|
| 23 |
LOGGER = "anthropic.lib.tools.agent_toolset" |
| 24 |
|
| 25 |
|
| 26 |
async def _downloaded( |
| 27 |
tmp_path: Path, initial: dict[str, str], *, access: str | None = None |
| 28 |
) -> tuple[Path, MemoryServer, SessionMemoryStores]: |
| 29 |
"""A `SessionMemoryStores` with one store already downloaded to disk.""" |
| 30 |
client, server = fake_anthropic(initial, access=access) |
| 31 |
stores = SessionMemoryStores(client, workdir=tmp_path) |
| 32 |
await stores.download(await client.beta.sessions.retrieve("s1")) |
| 33 |
return tmp_path / "memory" / "notes", server, stores |
| 34 |
|
| 35 |
|
| 36 |
@pytest.mark.asyncio() |
| 37 |
async def test_flush_pushes_new_and_changed_files_and_nothing_else( |
| 38 |
tmp_path: Path, caplog: pytest.LogCaptureFixture |
| 39 |
) -> None: |
| 40 |
caplog.set_level("WARNING", logger=LOGGER) |
| 41 |
local, server, stores = await _downloaded( |
| 42 |
tmp_path, |
| 43 |
{ |
| 44 |
"a-pull.md": "v1", |
| 45 |
"b-push.md": "v1", |
| 46 |
"d-local-gone.md": "v1", |
| 47 |
"e-remote-gone.md": "v1", |
| 48 |
"f-remote-gone-edited.md": "v1", |
| 49 |
"g-both.md": "v1", |
| 50 |
}, |
| 51 |
) |
| 52 |
|
| 53 |
(local / "b-push.md").write_text("v2 from agent") |
| 54 |
(local / "c-new.md").write_text("new from agent") |
| 55 |
(local / "d-local-gone.md").unlink() |
| 56 |
(local / "f-remote-gone-edited.md").write_text("v2 from agent") |
| 57 |
(local / "g-both.md").write_text("v2 from agent") |
| 58 |
server.write("a-pull.md", "v2 from server") |
| 59 |
server.delete("e-remote-gone.md") |
| 60 |
server.delete("f-remote-gone-edited.md") |
| 61 |
server.write("g-both.md", "v2 from server") |
| 62 |
|
| 63 |
await stores.flush_writes() |
| 64 |
|
| 65 |
# Only additions went out: the update, the new file, and the re-created |
| 66 |
# edited file whose remote copy was deleted. |
| 67 |
sent = [ |
| 68 |
updated("b-push.md", "v2 from agent", was="v1"), |
| 69 |
created("c-new.md", "new from agent"), |
| 70 |
created("f-remote-gone-edited.md", "v2 from agent"), |
| 71 |
] |
| 72 |
assert sorted(server.received) == sorted(sent) |
| 73 |
# A locally missing file was not deleted remotely. |
| 74 |
assert server.files["d-local-gone.md"] == "v1" |
| 75 |
# A remotely deleted, locally unedited memory was not re-uploaded — and |
| 76 |
# its file was not removed from disk either. |
| 77 |
assert "e-remote-gone.md" not in server.files |
| 78 |
assert (local / "e-remote-gone.md").read_text() == "v1" |
| 79 |
# Remote changes were not pulled. |
| 80 |
assert (local / "a-pull.md").read_text() == "v1" |
| 81 |
# The conflict was left to the server, and logged. |
| 82 |
assert server.files["g-both.md"] == "v2 from server" |
| 83 |
assert (local / "g-both.md").read_text() == "v2 from agent" |
| 84 |
assert "changed both locally and remotely" in caplog.text |
| 85 |
|
| 86 |
# Settled: a second flush pushes nothing more. |
| 87 |
await stores.flush_writes() |
| 88 |
assert sorted(server.received) == sorted(sent) |
| 89 |
|
| 90 |
|
| 91 |
@pytest.mark.asyncio() |
| 92 |
async def test_flush_uploads_several_files_at_once_up_to_the_bound( |
| 93 |
tmp_path: Path, monkeypatch: pytest.MonkeyPatch |
| 94 |
) -> None: |
| 95 |
"""Two uploads are in flight together, and never more than the bound — |
| 96 |
a serial flush would time out waiting for the second to start.""" |
| 97 |
monkeypatch.setattr(memories_mod, "_UPLOAD_CONCURRENCY", 2) |
| 98 |
local, server, stores = await _downloaded(tmp_path, {}) |
| 99 |
for i in range(5): |
| 100 |
(local / f"f{i}.md").write_text(f"file {i}") |
| 101 |
|
| 102 |
in_flight = peak = 0 |
| 103 |
release = anyio.Event() |
| 104 |
|
| 105 |
async def hook(_path: str) -> None: |
| 106 |
nonlocal in_flight, peak |
| 107 |
in_flight += 1 |
| 108 |
peak = max(peak, in_flight) |
| 109 |
try: |
| 110 |
if in_flight == 2 and not release.is_set(): |
| 111 |
# Hold both a little longer so a flush that ignored the bound |
| 112 |
# would have time to start a third upload before they leave. |
| 113 |
await anyio.sleep(0.1) |
| 114 |
release.set() |
| 115 |
with anyio.fail_after(5): |
| 116 |
await release.wait() |
| 117 |
finally: |
| 118 |
in_flight -= 1 |
| 119 |
|
| 120 |
server.upload_hook = hook |
| 121 |
await stores.flush_writes() |
| 122 |
|
| 123 |
assert peak == 2 |
| 124 |
assert server.files == {f"f{i}.md": f"file {i}" for i in range(5)} |
| 125 |
|
| 126 |
|
| 127 |
@pytest.mark.asyncio() |
| 128 |
async def test_a_flush_cut_off_part_way_logs_how_many_files_it_had_not_uploaded( |
| 129 |
tmp_path: Path, caplog: pytest.LogCaptureFixture |
| 130 |
) -> None: |
| 131 |
caplog.set_level("WARNING", logger=LOGGER) |
| 132 |
local, server, stores = await _downloaded(tmp_path, {}) |
| 133 |
for name in ("a.md", "b.md", "c.md", "y.md", "z.md"): |
| 134 |
(local / name).write_text(f"content of {name}") |
| 135 |
|
| 136 |
never = anyio.Event() |
| 137 |
fast_arrived = 0 |
| 138 |
with anyio.CancelScope() as scope: |
| 139 |
|
| 140 |
async def hook(path: str) -> None: |
| 141 |
nonlocal fast_arrived |
| 142 |
if path in ("y.md", "z.md"): |
| 143 |
with anyio.fail_after(5): |
| 144 |
await never.wait() |
| 145 |
else: |
| 146 |
fast_arrived += 1 |
| 147 |
if fast_arrived == 3: |
| 148 |
scope.cancel() |
| 149 |
|
| 150 |
server.upload_hook = hook |
| 151 |
await stores.flush_writes() |
| 152 |
|
| 153 |
def cut_off_lines() -> list[str]: |
| 154 |
return [r.getMessage() for r in caplog.records if "cut off" in r.getMessage()] |
| 155 |
|
| 156 |
assert scope.cancelled_caught |
| 157 |
assert cut_off_lines() == [ |
| 158 |
"memory flush cut off part-way; 2 of 5 changed files had not finished uploading memory_store_id=memstore_notes" |
| 159 |
] |
| 160 |
assert sorted(server.files) == ["a.md", "b.md", "c.md"] |
| 161 |
|
| 162 |
# The three that made it are not sent again; the two that did not are. |
| 163 |
# A flush that finishes in time adds no cut-off line. |
| 164 |
server.upload_hook = None |
| 165 |
await stores.flush_writes() |
| 166 |
assert sorted(server.files) == ["a.md", "b.md", "c.md", "y.md", "z.md"] |
| 167 |
assert sorted(r[1] for r in server.received) == ["a.md", "b.md", "c.md", "y.md", "z.md"] |
| 168 |
assert len(cut_off_lines()) == 1 |
| 169 |
|
| 170 |
|
| 171 |
@pytest.mark.asyncio() |
| 172 |
async def test_flush_adopts_a_file_the_server_already_holds(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None: |
| 173 |
"""A final sync cut off after uploading a file leaves the baseline stale; |
| 174 |
the flush sees the server already has those bytes and records that |
| 175 |
instead of reporting a conflict.""" |
| 176 |
caplog.set_level("WARNING", logger=LOGGER) |
| 177 |
local, server, stores = await _downloaded(tmp_path, {"n.md": "v1"}) |
| 178 |
(local / "n.md").write_text("v2") |
| 179 |
server.write("n.md", "v2") |
| 180 |
|
| 181 |
await stores.flush_writes() |
| 182 |
|
| 183 |
assert server.received == [] |
| 184 |
assert "changed both locally and remotely" not in caplog.text |
| 185 |
|
| 186 |
(local / "n.md").write_text("v3") |
| 187 |
await stores.flush_writes() |
| 188 |
assert server.received == [updated("n.md", "v3", was="v2")] |
| 189 |
|
| 190 |
|
| 191 |
@pytest.mark.asyncio() |
| 192 |
async def test_flush_never_pushes_a_read_only_store(tmp_path: Path) -> None: |
| 193 |
local, server, stores = await _downloaded(tmp_path, {"edit.md": "v1"}, access="read_only") |
| 194 |
|
| 195 |
(local / "edit.md").write_text("v2 from agent") |
| 196 |
(local / "new.md").write_text("new from agent") |
| 197 |
|
| 198 |
await stores.flush_writes() |
| 199 |
|
| 200 |
assert server.received == [] |
| 201 |
assert server.files == {"edit.md": "v1"} |
| 202 |
|
| 203 |
|
| 204 |
@pytest.mark.asyncio() |
| 205 |
async def test_flush_skips_files_the_server_already_refused(tmp_path: Path) -> None: |
| 206 |
local, server, stores = await _downloaded(tmp_path, {"note.md": "v1"}) |
| 207 |
server.max_content_bytes = 64 |
| 208 |
|
| 209 |
(local / "big.md").write_text("x" * 100) |
| 210 |
await run_sync(stores) |
| 211 |
assert sum(1 for r in server.received if r[0] == "create") == 1 |
| 212 |
|
| 213 |
await stores.flush_writes() |
| 214 |
|
| 215 |
# The refused file was not retried; nothing else needed pushing. |
| 216 |
assert sum(1 for r in server.received if r[0] == "create") == 1 |
| 217 |
assert "big.md" not in server.files |
| 218 |
|
| 219 |
|
| 220 |
@pytest.mark.asyncio() |
| 221 |
async def test_flush_pushes_nothing_when_the_marker_check_fails( |
| 222 |
tmp_path: Path, caplog: pytest.LogCaptureFixture |
| 223 |
) -> None: |
| 224 |
caplog.set_level("WARNING", logger=LOGGER) |
| 225 |
local, server, stores = await _downloaded(tmp_path, {"a.md": "v1"}) |
| 226 |
|
| 227 |
(local / MARKER_PATH).unlink() |
| 228 |
(local / "foreign.md").write_text("someone else's notes") |
| 229 |
|
| 230 |
await stores.flush_writes() |
| 231 |
|
| 232 |
assert server.received == [] |
| 233 |
assert "foreign.md" not in server.files |
| 234 |
# Unlike sync's recovery, the flush does not re-download the folder. |
| 235 |
assert not (local / MARKER_PATH).exists() |
| 236 |
assert "not uploading anything from the memory store folder" in caplog.text |
| 237 |
|
| 238 |
|
| 239 |
@pytest.mark.asyncio() |
| 240 |
async def test_flush_never_raises(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None: |
| 241 |
caplog.set_level("WARNING", logger=LOGGER) |
| 242 |
local, server, stores = await _downloaded(tmp_path, {"a.md": "v1"}) |
| 243 |
(local / "a.md").write_text("v2 from agent") |
| 244 |
|
| 245 |
def boom(*_a: Any, **_k: Any) -> Any: |
| 246 |
raise RuntimeError("listing exploded") |
| 247 |
|
| 248 |
stores._client.beta.memory_stores.memories.list = boom # pyright: ignore[reportPrivateUsage] |
| 249 |
await stores.flush_writes() |
| 250 |
|
| 251 |
assert server.received == [] |
| 252 |
assert "memory flush failed" in caplog.text |