Debian Codegraph @

src/anthropic/lib/tools/_memories.py

raw
1 """Session-level memory-store download and sync.
2
3 A session may have several memory stores attached. This module resolves
4 where each store's folder goes on disk, opens a `LocalFileStore`
5 there, and reconciles each folder with its remote store — the merge rules
6 live on `SessionMemoryStores`.
7 """
8
9 from __future__ import annotations
10
11 import os
12 import hashlib
13 import logging
14 from time import monotonic
15 from typing import TYPE_CHECKING, Literal, NamedTuple, cast
16 from pathlib import Path
17 from dataclasses import field, dataclass
18
19 import anyio
20
21 from ._file_store import FileStore, FileStoreError, LocalFileStore
22 from ..._exceptions import APIStatusError
23
24 if TYPE_CHECKING:
25 from collections.abc import AsyncIterator
26
27 from ..._client import AsyncAnthropic
28 from ...types.beta import BetaManagedAgentsSession
29 from ...types.beta.sessions import BetaManagedAgentsMemoryStoreResource
30 from ...types.beta.memory_stores import BetaManagedAgentsMemory, BetaManagedAgentsMemoryView
31
32 __all__ = [
33 "SessionMemoryStores",
34 "SessionMemoryError",
35 "MemoryDeleteMode",
36 "DEFAULT_MEMORY_SYNC_INTERVAL",
37 "MIN_MEMORY_SYNC_INTERVAL",
38 "MEMORY_FLUSH_TIMEOUT",
39 "MARKER_PATH",
40 ]
41
42 #: Whether a locally deleted file may delete its server memory — `"log_only"` is the dry run.
43 MemoryDeleteMode = Literal["enabled", "log_only", "disabled"]
44
45 #: How often (seconds) the worker syncs the session's memory stores back
46 #: while the session runs. Checked after each dispatched tool call.
47 DEFAULT_MEMORY_SYNC_INTERVAL = 15.0
48
49 #: Smallest sync interval (seconds). Anything below it is rejected —
50 #: each sync lists every attached store, so sub-second cadences would
51 #: hammer the memory endpoints.
52 MIN_MEMORY_SYNC_INTERVAL = 5.0
53
54
55 def _check_sync_interval(interval: float) -> None:
56 # Phrased so NaN fails: `NaN < floor` is False, so the inverse test
57 # `interval < floor` would wave NaN through — and a NaN interval makes
58 # every cadence check due, the exact hammering the floor exists to stop.
59 if not interval >= MIN_MEMORY_SYNC_INTERVAL:
60 raise ValueError(f"sync interval must be at least {MIN_MEMORY_SYNC_INTERVAL} seconds, got {interval}")
61
62
63 #: Bound (seconds) the worker puts on each shielded teardown pass — the final
64 #: sync, then the flush — so a slow server cannot stall teardown.
65 MEMORY_FLUSH_TIMEOUT = 30.0
66
67 #: Reserved marker at every store root — two lines: `version <n>` and the
68 #: store's `memory_store_id`; a sync trusts the folder only when both match.
69 #: Never itself synced.
70 MARKER_PATH = ".anthropic-memory-store"
71
72 _MARKER_VERSION = 1
73
74
75 def _marker_sha(memory_store_id: str) -> str:
76 return hashlib.sha256(f"version {_MARKER_VERSION}\n{memory_store_id}".encode("utf-8")).hexdigest()
77
78
79 #: How long (seconds) a file must stay missing before its server delete goes out.
80 DELETE_CORROBORATION_SECONDS = 30.0
81
82 #: Page sizes for memory listings — the API's maximum per view: `basic`
83 #: pages carry up to 100 items, `full` pages are capped by the server.
84 _LIST_PAGE_SIZE = 100
85 _FULL_LIST_PAGE_SIZE = 20
86
87 #: How many single-memory content fetches may be in flight at once during
88 #: one store's pull pass. Well inside the client's keepalive pool (100),
89 #: so every fetch reuses a warm connection; a sync rarely pulls more than
90 #: a handful of memories, so a higher cap buys nothing in the common case.
91 _FETCH_CONCURRENCY = 16
92
93 #: How many uploads one store's flush keeps in flight. At ~0.3s per upload,
94 #: 32 clears the server's 2000-memories-per-store cap inside
95 #: `MEMORY_FLUSH_TIMEOUT`; eight stores at once stay far below the
96 #: client's connection limit.
97 _UPLOAD_CONCURRENCY = 32
98
99 #: Bounds of the per-sync delete cap — the floor keeps small stores'
100 #: legitimate deletions from crawling.
101 _DELETE_CAP_FLOOR = 8
102 _DELETE_CAP_CEILING = 50
103
104 log = logging.getLogger("anthropic.lib.tools.agent_toolset")
105
106
107 class _MarkerScan(NamedTuple):
108 """One directory scan — the marker checked and removed in the same read as the file listing."""
109
110 files: dict[str, str]
111 #: The scan found a marker naming this store — the only state that may drive uploads or deletes.
112 marker_ok: bool
113 #: Why the marker check failed; `None` when it passed.
114 distrust_reason: str | None
115
116
117 class SessionMemoryError(Exception):
118 """A memory store could not be materialised on disk.
119
120 Raised by `SessionMemoryStores.download`; the worker lets it fail
121 the work item.
122 """
123
124
125 @dataclass
126 class _AttachedStore:
127 """One attached store: its `FileStore` on disk plus the sync baseline."""
128
129 memory_store_id: str
130 files: FileStore
131 read_only: bool
132 #: `{rel_path → content sha}` as of the last download or successful sync.
133 baseline: dict[str, str] = field(default_factory=dict[str, str])
134 #: `{rel_path → sha}` the server refused; retried only after the file changes.
135 refused_shas: dict[str, str] = field(default_factory=dict[str, str])
136 #: `{rel_path → monotonic time first seen missing}`; the server delete waits for a later sync.
137 pending_deletes: dict[str, float] = field(default_factory=dict[str, float])
138
139
140 @dataclass
141 class _DeletePass:
142 """One sync's server-delete discipline: the mode, the cap, and what was held back."""
143
144 mode: MemoryDeleteMode
145 cap: int
146 #: Skip the waiting window — no later sync is coming to confirm.
147 waive_window: bool = False
148 attempted: int = 0
149 capped: int = 0
150 suppressed: int = 0
151
152 def take_slot(self) -> bool:
153 if self.attempted >= self.cap:
154 self.capped += 1
155 return False
156 self.attempted += 1
157 return True
158
159
160 class SessionMemoryStores:
161 """The memory stores attached to one session, materialised on disk.
162
163 `download` opens a `._file_store.LocalFileStore` at each
164 attached store's directory (its `mount_path`, or a workdir fallback
165 — see `download`), pulls its memories,
166 and records each one's `content_sha256` as the sync baseline. Each
167 sync (`sync_if_due` on the worker's cadence, `finish` once
168 at the end) reconciles disk against server, per store and per path:
169
170 - a memory changed only remotely is written to disk;
171 - a file changed only locally is uploaded — an update with a
172 `content_sha256` precondition, or a create for a new file;
173 - a file changed on both sides logs a warning and takes the server
174 version;
175 - a file the server refuses (too large, invalid content) is skipped —
176 warned once and retried only after the file changes; other files keep
177 syncing;
178 - a file deleted locally is deleted on the server, guarded by an
179 `expected_content_sha256` precondition — a concurrent server-side
180 edit wins and the file is restored instead. The delete never goes
181 out on the first sync that sees the file missing: it waits
182 `DELETE_CORROBORATION_SECONDS`, re-checks the file and the
183 marker, and each sync sends a bounded number — the rest wait.
184 `sync_deletions="log_only"` runs the same checks and only logs;
185 `"disabled"` turns server deletes off;
186 - a memory deleted on the server is deleted on disk — unless the file
187 holds an un-pushed edit, making it the only copy: a writable store
188 re-creates the memory, a read-only store keeps the file unsynced;
189 - a store attached read-only pulls but never pushes.
190
191 A download pulls the whole store, so it lists with content included.
192 The recurring syncs instead run two phases: a content-free listing
193 (paths and shas) drives the merge decisions, then only the memories
194 actually being written to disk are fetched, a bounded number at a
195 time. A sync that finds nothing changed moves no content at all.
196
197 A file whose write to disk failed is never in the baseline, so its
198 absence reads as a failed download — it is pulled again, never deleted.
199 A write never re-creates a store folder that vanished mid-sync: it fails,
200 and the next sync's scan finds whatever is at the path by then — nothing
201 (re-downloaded) or someone else's files (left alone) — under the rules below.
202
203 `download` stamps `MARKER_PATH` into the folder, and every
204 sync checks it in the same directory scan it syncs from:
205
206 - the folder or marker gone with no files left, or the marker intact
207 but every one of two-or-more files gone at once: the store is
208 re-downloaded — a full local wipe never propagates;
209 - the marker gone or naming another store while files remain: the sync
210 does nothing — those files never upload and never drive deletes.
211
212 `download` raises `SessionMemoryError` on the first store it
213 cannot materialise. The syncs never raise: mid-session, one bad store
214 or one bad file is logged and the rest continue. Instances are not safe for
215 concurrent use. The worker builds one on its token-scoped sub-client (the
216 memory endpoints reject the environment key): `sync_if_due` after each
217 tool call, `finish` once at a clean end, a bounded
218 `flush_writes` in every teardown, `dispose` last.
219 """
220
221 def __init__(
222 self,
223 client: AsyncAnthropic,
224 *,
225 workdir: str | os.PathLike[str],
226 sync_interval: float = DEFAULT_MEMORY_SYNC_INTERVAL,
227 sync_deletions: MemoryDeleteMode = "enabled",
228 ) -> None:
229 _check_sync_interval(sync_interval)
230 self._client = client
231 self._workdir = workdir
232 self._sync_interval = sync_interval
233 self._sync_deletions: MemoryDeleteMode = sync_deletions
234 self._last_sync = monotonic()
235 self._finished = False
236 self._stores: list[_AttachedStore] = []
237
238 @property
239 def roots(self) -> list[Path]:
240 """Every attached store's folder on disk.
241
242 The worker adds these to the file tools' allowed roots, so a store
243 mounted outside the working directory stays reachable.
244 """
245 return [s.files.root().path for s in self._stores]
246
247 @property
248 def read_only_roots(self) -> list[Path]:
249 """Root directories of stores attached read-only.
250
251 The file tools consult this to refuse writes into read-only stores.
252 """
253 return [s.files.root().path for s in self._stores if s.read_only]
254
255 def _store_root(self, resource: BetaManagedAgentsMemoryStoreResource) -> Path:
256 """Where one store's files land on disk.
257
258 The store's files land at its `mount_path` — the very location the
259 agent's system prompt tells it to read. A `mount_path` we cannot use
260 verbatim is refused rather than quietly relocated: the agent would read
261 an empty folder at the path it was told about, and write notes somewhere
262 the next session looks for nothing.
263 """
264 if resource.mount_path:
265 if not FileStore.is_path_legal(resource.mount_path):
266 raise SessionMemoryError(
267 f"memory store mount_path is not a clean absolute path: {resource.mount_path!r} "
268 f"(memory_store_id={resource.memory_store_id})"
269 )
270 return Path(resource.mount_path)
271 # No mount_path at all: nothing points the agent anywhere, so the
272 # workdir is as good a home as any.
273 return Path(self._workdir) / "memory" / (resource.name or resource.memory_store_id)
274
275 async def download(self, session: BetaManagedAgentsSession) -> None:
276 """Download every attached store's memories to disk.
277
278 `session` arrives already fetched — one snapshot shared with the
279 skills download.
280 """
281 plan = [(r, self._store_root(r)) for r in session.resources if r.type == "memory_store"]
282 for resource, root in plan:
283 store: _AttachedStore | None = None
284 try:
285 store = _AttachedStore(
286 memory_store_id=resource.memory_store_id,
287 # utf8_only: a binary file is refused at put/get, not mid-sync.
288 files=await LocalFileStore.open(root, utf8_only=True),
289 read_only=resource.access == "read_only",
290 )
291 # A root `open` did not create is a dead run's leftovers;
292 # the first sync would upload them into the customer's store.
293 if not store.files.root().removed_on_dispose:
294 # The configured path, not root().path — that one is
295 # resolved and would name a symlinked mount's target.
296 raise SessionMemoryError(
297 f"something already exists at the memory store's path: {root} "
298 f"(memory_store_id={resource.memory_store_id}); "
299 "it must not exist when the session starts"
300 )
301 try:
302 await store.files.create_root()
303 except OSError as e:
304 # An unmountable root fails the item, not just one file.
305 raise SessionMemoryError(
306 f"cannot create the memory store's folder: {root} "
307 f"(memory_store_id={resource.memory_store_id}): {e}; "
308 "the worker host must make this mount path writable"
309 ) from e
310 await self._stamp_and_pull(store)
311 log.info(
312 "downloaded %d memories memory_store_id=%s -> %s",
313 len(store.baseline),
314 store.memory_store_id,
315 store.files.root().path,
316 )
317 self._stores.append(store)
318 except Exception as e:
319 # A half-downloaded folder self-destructs; `dispose` leaves
320 # a refused pre-existing directory exactly as found.
321 if store is not None:
322 try:
323 await store.files.dispose()
324 except OSError:
325 pass
326 # Every store must land: a session missing a folder its system
327 # prompt names runs with amnesia and syncs nothing back.
328 if isinstance(e, SessionMemoryError):
329 raise
330 raise SessionMemoryError(
331 f"failed to download memory store memory_store_id={resource.memory_store_id}: {e}"
332 ) from e
333 self._last_sync = monotonic()
334
335 async def finish(self) -> None:
336 """The session's last sync — once, at a clean end.
337
338 Same reconciliation as the cadence syncs, but server deletes skip
339 the waiting window (the cap still applies). Raises on a second
340 call — a repeat would keep skipping the window.
341 """
342 if self._finished:
343 raise RuntimeError("finish() was already called: it is the session's last sync and runs once")
344 self._finished = True
345 await self._sync_all(final=True)
346
347 async def _sync_all(self, *, final: bool) -> None:
348 async with anyio.create_task_group() as tg:
349 for store in self._stores:
350 tg.start_soon(self._sync_store, store, final)
351 self._last_sync = monotonic()
352
353 async def _scan_marker(self, store: _AttachedStore) -> _MarkerScan:
354 local = await store.files.hashtree()
355 marker = local.pop(MARKER_PATH, None)
356 if marker == _marker_sha(store.memory_store_id):
357 return _MarkerScan(files=local, marker_ok=True, distrust_reason=None)
358 return _MarkerScan(
359 files=local,
360 marker_ok=False,
361 distrust_reason=(
362 "the marker file does not match this store" if marker is not None else "the marker file is gone"
363 ),
364 )
365
366 async def _sync_store(self, store: _AttachedStore, final: bool = False) -> None:
367 try:
368 scan = await self._scan_marker(store)
369 local = scan.files
370 if not scan.marker_ok:
371 if local:
372 log.warning(
373 "%s; leaving the memory store folder as found and not syncing root=%s memory_store_id=%s",
374 scan.distrust_reason,
375 store.files.root().path,
376 store.memory_store_id,
377 )
378 return
379 await self._recover(store, "the folder or its marker is gone")
380 return
381 # One file gone is a delete; every file gone at once is a wipe.
382 if not local and len(store.baseline) > 1:
383 await self._recover(store, "every memory file is gone at once")
384 return
385
386 remote = {item.path.lstrip("/"): item async for item in self._list_memories(store.memory_store_id)}
387
388 deletes = _DeletePass(
389 mode=self._sync_deletions,
390 cap=max(_DELETE_CAP_FLOOR, min(_DELETE_CAP_CEILING, len(store.baseline) // 4)),
391 waive_window=final,
392 )
393 pulls: list[tuple[str, BetaManagedAgentsMemory]] = []
394 baseline: dict[str, str] = {}
395 for rel in sorted({*remote, *local, *store.baseline}):
396 remote_item = remote.get(rel)
397 local_sha = local.get(rel)
398 base_sha = store.baseline.get(rel)
399 # Branch server-delete candidates off so the delete discipline
400 # stays out of the merge rules.
401 if (
402 local_sha is None
403 and base_sha is not None
404 and remote_item is not None
405 and remote_item.content_sha256 == base_sha
406 and not store.read_only
407 ):
408 sha = await self._corroborated_delete(store, rel, remote_item, base_sha, deletes=deletes)
409 else:
410 sha = await self._sync_path(store, rel, remote_item, local_sha, pulls=pulls)
411 if sha is not None:
412 baseline[rel] = sha
413 store.baseline = baseline
414 # The content pass: everything above moved only shas.
415 await self._pull_all(store, pulls)
416 if deletes.suppressed:
417 log.debug(
418 "server deletes are disabled; %d locally deleted memories stay on the server memory_store_id=%s",
419 deletes.suppressed,
420 store.memory_store_id,
421 )
422 if deletes.capped:
423 log.warning(
424 "delete cap reached: %s %d deletes, held %d for later syncs memory_store_id=%s",
425 "would send" if deletes.mode == "log_only" else "sent",
426 deletes.attempted,
427 deletes.capped,
428 store.memory_store_id,
429 )
430 except Exception as e:
431 log.warning("memory sync failed memory_store_id=%s: %s", store.memory_store_id, e)
432
433 async def sync_if_due(self) -> None:
434 """Run one sync when `sync_interval` has elapsed since the last.
435
436 Stores sync in parallel; a store's own paths reconcile in a
437 deterministic order. Never raises — a failure on one store is
438 logged and the others continue.
439 """
440 if monotonic() - self._last_sync < self._sync_interval:
441 return
442 await self._sync_all(final=False)
443
444 async def flush_writes(self) -> None:
445 """Upload new and changed files; send no deletes and pull nothing.
446
447 The push-only rescue pass for a session ending on an error or cancel —
448 best-effort, bounded by the caller. Each store uploads a bounded number
449 of files at a time; a store cut off part-way logs how many changed
450 files it had not uploaded. Skips read-only stores, refused files, files
451 the server already holds, and folders that fail the marker check.
452 Never raises.
453 """
454 async with anyio.create_task_group() as tg:
455 for store in self._stores:
456 tg.start_soon(self._flush_store, store)
457
458 async def _flush_store(self, store: _AttachedStore) -> None:
459 dirty: dict[str, str] = {}
460 unsent: set[str] = set()
461 try:
462 if store.read_only:
463 return
464 scan = await self._scan_marker(store)
465 if not scan.marker_ok:
466 log.warning(
467 "%s; not uploading anything from the memory store folder root=%s memory_store_id=%s",
468 scan.distrust_reason,
469 store.files.root().path,
470 store.memory_store_id,
471 )
472 return
473 dirty = {
474 rel: sha
475 for rel, sha in scan.files.items()
476 if sha != store.baseline.get(rel) and store.refused_shas.get(rel) != sha
477 }
478 if not dirty:
479 return
480 unsent.update(dirty)
481 remote = {item.path.lstrip("/"): item async for item in self._list_memories(store.memory_store_id)}
482 limiter = anyio.CapacityLimiter(_UPLOAD_CONCURRENCY)
483
484 async def upload_one(rel: str, local_sha: str, existing: BetaManagedAgentsMemory | None) -> None:
485 async with limiter:
486 sha = await self._upload(store, rel, local_sha, existing=existing)
487 unsent.discard(rel)
488 if sha is not None:
489 store.baseline[rel] = sha
490
491 async with anyio.create_task_group() as tg:
492 for rel in sorted(dirty):
493 local_sha = dirty[rel]
494 base_sha = store.baseline.get(rel)
495 existing = remote.get(rel)
496 if existing is not None and existing.content_sha256 == local_sha:
497 store.baseline[rel] = local_sha
498 unsent.discard(rel)
499 continue
500 if existing is not None and existing.content_sha256 != base_sha:
501 # A push-only pass cannot pull the winner over the file.
502 log.warning(
503 "memory changed both locally and remotely; the flush leaves the "
504 "remote version path=%s memory_store_id=%s",
505 rel,
506 store.memory_store_id,
507 )
508 unsent.discard(rel)
509 continue
510 tg.start_soon(upload_one, rel, local_sha, existing)
511 except Exception as e:
512 log.warning("memory flush failed memory_store_id=%s: %s", store.memory_store_id, e)
513 except anyio.get_cancelled_exc_class():
514 if unsent:
515 log.warning(
516 "memory flush cut off part-way; %d of %d changed files had not finished uploading "
517 "memory_store_id=%s",
518 len(unsent),
519 len(dirty),
520 store.memory_store_id,
521 )
522 raise
523
524 async def dispose(self) -> None:
525 """Remove every store directory that `download` created.
526
527 Pre-existing directories are left alone — that is
528 `FileStore.dispose`'s own rule. A folder that holds files
529 but fails the marker check is also kept — sync promised to leave
530 it as found, and the next download refuses it visibly.
531 """
532 for store in self._stores:
533 # The caller is tearing down and will not retry.
534 try:
535 root = store.files.root()
536 scan = await self._scan_marker(store)
537 if not scan.marker_ok and scan.files:
538 log.warning(
539 "%s; leaving the memory store folder on disk root=%s memory_store_id=%s",
540 scan.distrust_reason,
541 root.path,
542 store.memory_store_id,
543 )
544 continue
545 await store.files.dispose()
546 except (FileStoreError, OSError) as e:
547 log.warning(
548 "failed to remove the memory store folder root=%s memory_store_id=%s: %s",
549 store.files.root().path,
550 store.memory_store_id,
551 e,
552 )
553 continue
554 if root.removed_on_dispose:
555 log.info("removed memory store dir %s memory_store_id=%s", root.path, store.memory_store_id)
556
557 async def _recover(self, store: _AttachedStore, reason: str) -> None:
558 """Rebuild a destroyed folder from the server; sends no deletes, no uploads."""
559 log.warning(
560 "%s; re-downloading the memory store folder instead of syncing root=%s memory_store_id=%s",
561 reason,
562 store.files.root().path,
563 store.memory_store_id,
564 )
565 await store.files.create_root()
566 await self._stamp_and_pull(store)
567
568 async def _stamp_and_pull(self, store: _AttachedStore) -> None:
569 """Write the trust marker, then pull every remote memory; pushes nothing.
570
571 The baseline is cleared and rebuilt from successful writes only, so a
572 failure mid-pull leaves no entry a later pass could read as a delete.
573 Every memory is needed here, so the listing carries the content —
574 pages cost far fewer round-trips than a request per memory.
575 """
576 store.baseline = {}
577 # The disk was just rebuilt, so earlier absence observations mean nothing.
578 store.pending_deletes.clear()
579 await store.files.put(MARKER_PATH, f"version {_MARKER_VERSION}\n{store.memory_store_id}")
580 async for item in self._list_memories(store.memory_store_id, view="full"):
581 rel = item.path.lstrip("/")
582 if await self._write(store, rel, item.content or ""):
583 store.baseline[rel] = item.content_sha256
584
585 async def _sync_path(
586 self,
587 store: _AttachedStore,
588 rel: str,
589 remote: BetaManagedAgentsMemory | None,
590 local_sha: str | None,
591 *,
592 pulls: list[tuple[str, BetaManagedAgentsMemory]],
593 ) -> str | None:
594 base_sha = store.baseline.get(rel)
595 if local_sha is not None:
596 store.pending_deletes.pop(rel, None)
597
598 if remote is None:
599 if local_sha is None:
600 store.pending_deletes.pop(rel, None)
601 return None
602 if base_sha is not None:
603 if local_sha == base_sha:
604 fresh = await self._remove_local(store, rel, base_sha)
605 if fresh is None:
606 return None
607 if fresh == base_sha:
608 return base_sha
609 local_sha = fresh
610 # An un-pushed edit exists only in this file, so the remote
611 # delete loses: fall through and re-create it (writable) or
612 # keep it on disk unsynced (read-only).
613 if store.read_only:
614 log.warning(
615 "memory deleted remotely but edited locally; keeping the file, "
616 "which a read-only store cannot push path=%s memory_store_id=%s",
617 rel,
618 store.memory_store_id,
619 )
620 elif store.refused_shas.get(rel) != local_sha:
621 log.info(
622 "memory deleted remotely but edited locally; re-creating it from the file "
623 "path=%s memory_store_id=%s",
624 rel,
625 store.memory_store_id,
626 )
627 if store.read_only:
628 return None
629 if store.refused_shas.get(rel) == local_sha:
630 return None
631 return await self._upload(store, rel, local_sha, existing=None)
632
633 remote_sha = remote.content_sha256
634 remote_changed = remote_sha != base_sha
635 locally_edited = local_sha is not None and local_sha not in (base_sha, remote_sha)
636 # Read-only stores never push, so their local edits don't count.
637 local_changed = not store.read_only and locally_edited
638
639 if local_sha is None and base_sha is not None:
640 # Only successful writes enter the baseline, so this file was
641 # verifiably on disk and is now gone: a real local deletion.
642 if remote_changed:
643 log.warning(
644 "memory deleted locally but changed remotely; restoring the remote version "
645 "path=%s memory_store_id=%s",
646 rel,
647 store.memory_store_id,
648 )
649 store.pending_deletes.pop(rel, None)
650 pulls.append((rel, remote))
651 return base_sha
652
653 if remote_changed:
654 if local_sha == remote_sha:
655 # The file already holds the remote bytes — adopt without a fetch.
656 return remote_sha
657 # Read-only edits never push, but overwriting one still logs.
658 if locally_edited:
659 log.warning(
660 "memory changed both locally and remotely; keeping the remote version path=%s memory_store_id=%s",
661 rel,
662 store.memory_store_id,
663 )
664 pulls.append((rel, remote))
665 return base_sha
666 if local_changed:
667 if store.refused_shas.get(rel) == local_sha:
668 return remote_sha
669 # local_changed implies local_sha is present.
670 return await self._upload(store, rel, cast(str, local_sha), existing=remote) or remote_sha
671 return remote_sha
672
673 async def _remove_local(self, store: _AttachedStore, rel: str, expect_sha: str) -> str | None:
674 """Remove the file for a memory the server no longer has, if it still holds `expect_sha`.
675
676 Returns `None` when the file is gone from disk, `expect_sha` when it must
677 stay in the baseline (I/O error, remove failed), or the file's fresh sha when
678 it was edited since the scan.
679 """
680 try:
681 fresh_sha = await store.files.hash_file(rel)
682 except (FileStoreError, OSError):
683 return expect_sha
684 if fresh_sha is None:
685 return None
686 if fresh_sha != expect_sha:
687 return fresh_sha
688 try:
689 await store.files.remove(rel)
690 except (FileStoreError, OSError) as e:
691 log.warning(
692 "failed to remove memory deleted remotely path=%s memory_store_id=%s: %s",
693 rel,
694 store.memory_store_id,
695 e,
696 )
697 return expect_sha
698 return None
699
700 async def _write(self, store: _AttachedStore, rel: str, content: str) -> bool:
701 """Write a memory's content to disk; `False` (and a warning) on failure.
702
703 A `..` component in the wire path reaches here as
704 `FileStoreError` — that is the escape guard.
705 """
706 try:
707 await store.files.put(rel, content)
708 except (FileStoreError, OSError) as e:
709 log.warning("failed to write memory path=%s memory_store_id=%s: %s", rel, store.memory_store_id, e)
710 return False
711 return True
712
713 async def _pull_all(self, store: _AttachedStore, pulls: list[tuple[str, BetaManagedAgentsMemory]]) -> None:
714 """Fetch and write the given memories, `_FETCH_CONCURRENCY` at a time.
715
716 The sync's content pass: the listing carried no content, so each
717 memory is fetched individually and written as it arrives. On
718 success the path's baseline advances; on a failed fetch or write
719 the old entry stays and the next sync retries. A 404 means the
720 memory was deleted after the listing — the next sync reconciles it.
721 """
722 if not pulls:
723 return
724 limiter = anyio.CapacityLimiter(_FETCH_CONCURRENCY)
725
726 async def pull_one(rel: str, listed: BetaManagedAgentsMemory) -> None:
727 # The write stays inside the limiter so a slow disk cannot let
728 # fetched bodies pile up beyond the concurrency bound.
729 async with limiter:
730 try:
731 item = await self._client.beta.memory_stores.memories.retrieve(
732 listed.id, memory_store_id=store.memory_store_id, view="full"
733 )
734 except Exception as e:
735 if isinstance(e, APIStatusError) and e.status_code == 404:
736 return
737 log.warning(
738 "failed to fetch memory content path=%s memory_store_id=%s: %s", rel, store.memory_store_id, e
739 )
740 return
741 if await self._write(store, rel, item.content or ""):
742 store.baseline[rel] = item.content_sha256
743
744 async with anyio.create_task_group() as tg:
745 for rel, listed in pulls:
746 tg.start_soon(pull_one, rel, listed)
747
748 async def _list_memories(
749 self, memory_store_id: str, *, view: BetaManagedAgentsMemoryView = "basic"
750 ) -> AsyncIterator[BetaManagedAgentsMemory]:
751 """The store's memories — `basic` view (shas, no content) at
752 `_LIST_PAGE_SIZE` per page unless the caller needs `full`
753 pages. `memory_prefix` rollups and the reserved marker path are
754 skipped."""
755 limit = _LIST_PAGE_SIZE if view == "basic" else _FULL_LIST_PAGE_SIZE
756 async for item in self._client.beta.memory_stores.memories.list(memory_store_id, view=view, limit=limit):
757 if item.type != "memory":
758 continue
759 if item.path.lstrip("/") == MARKER_PATH:
760 log.warning(
761 "the server listed the reserved marker path; skipping path=%s memory_store_id=%s",
762 item.path,
763 memory_store_id,
764 )
765 continue
766 yield item
767
768 async def _upload(
769 self, store: _AttachedStore, rel: str, local_sha: str | None, *, existing: BetaManagedAgentsMemory | None
770 ) -> str | None:
771 """Push one local file; `None` keeps the old baseline so the next pass retries.
772
773 A refusal the server would repeat (400/413, the utf-8 gate) enters
774 `refused_shas`: warned once, retried only after the file changes.
775 """
776 try:
777 data = await store.files.get(rel)
778 if data is None:
779 return None
780 if existing is None:
781 item = await self._client.beta.memory_stores.memories.create(
782 store.memory_store_id, path="/" + rel, content=data.decode("utf-8")
783 )
784 else:
785 item = await self._client.beta.memory_stores.memories.update(
786 existing.id,
787 memory_store_id=store.memory_store_id,
788 content=data.decode("utf-8"),
789 precondition={"type": "content_sha256", "content_sha256": existing.content_sha256},
790 )
791 except Exception as e:
792 status = e.status_code if isinstance(e, APIStatusError) else None
793 if existing is not None and status == 404:
794 # Deleted remotely since the listing, so this file is now the only copy.
795 return await self._upload(store, rel, local_sha, existing=None)
796 permanent = isinstance(e, FileStoreError) or status in (400, 413)
797 if existing is not None and status == 409:
798 # The precondition lost a race: the remote moved under us, so
799 # the push is dropped. The next sync pulls the winner over the
800 # file; from the shutdown flush there is no next sync.
801 log.warning(
802 "memory changed both locally and remotely; the upload was refused and the "
803 "local edit loses path=%s memory_store_id=%s",
804 rel,
805 store.memory_store_id,
806 )
807 elif permanent and local_sha is not None:
808 store.refused_shas[rel] = local_sha
809 log.warning(
810 "the server rejected this memory file, so it stays un-synced until its content "
811 "changes path=%s memory_store_id=%s rejection=%s",
812 rel,
813 store.memory_store_id,
814 e,
815 )
816 else:
817 log.warning("failed to upload memory path=%s memory_store_id=%s: %s", rel, store.memory_store_id, e)
818 return None
819 store.refused_shas.pop(rel, None)
820 return item.content_sha256
821
822 async def _corroborated_delete(
823 self,
824 store: _AttachedStore,
825 rel: str,
826 remote: BetaManagedAgentsMemory,
827 base_sha: str,
828 *,
829 deletes: _DeletePass,
830 ) -> str | None:
831 """Send the server delete only after the file's absence is confirmed.
832
833 Records the miss on the first sync; deletes on a later one after
834 the window, a fresh re-check, and the per-pass cap.
835 """
836 if deletes.mode == "disabled":
837 deletes.suppressed += 1
838 return base_sha
839 first_absent = store.pending_deletes.setdefault(rel, monotonic())
840 if not deletes.waive_window and monotonic() - first_absent < DELETE_CORROBORATION_SECONDS:
841 return base_sha
842 try:
843 # Re-check now — the folder may have been destroyed mid-sync.
844 marker_ok = await store.files.hash_file(MARKER_PATH) == _marker_sha(store.memory_store_id)
845 still_absent = await store.files.hash_file(rel) is None
846 except (FileStoreError, OSError):
847 marker_ok = still_absent = False
848 if not marker_ok:
849 return base_sha
850 if not still_absent:
851 store.pending_deletes.pop(rel, None)
852 return base_sha
853 if not deletes.take_slot():
854 return base_sha
855 if deletes.mode == "log_only":
856 # Repeats every sync — the dry run mirrors what "enabled" would keep trying.
857 log.info(
858 "log-only: sync would delete this memory on the server path=%s memory_store_id=%s",
859 rel,
860 store.memory_store_id,
861 )
862 return base_sha
863 sha = await self._delete_remote(store, rel, remote, base_sha)
864 if sha is None:
865 store.pending_deletes.pop(rel, None)
866 return sha
867
868 async def _delete_remote(
869 self, store: _AttachedStore, rel: str, remote: BetaManagedAgentsMemory, base_sha: str
870 ) -> str | None:
871 try:
872 await self._client.beta.memory_stores.memories.delete(
873 remote.id,
874 memory_store_id=store.memory_store_id,
875 expected_content_sha256=base_sha,
876 )
877 except Exception as e:
878 status = e.status_code if isinstance(e, APIStatusError) else None
879 if status == 404:
880 return None # already gone remotely too
881 if status in (409, 412):
882 log.warning(
883 "memory deleted locally but changed remotely; keeping the remote version "
884 "path=%s memory_store_id=%s",
885 rel,
886 store.memory_store_id,
887 )
888 else:
889 log.warning("failed to delete memory path=%s memory_store_id=%s: %s", rel, store.memory_store_id, e)
890 return base_sha
891 log.info("propagated local deletion path=%s memory_store_id=%s", rel, store.memory_store_id)
892 return None