Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(memory): retry captions after attachment preflight failure (#1481)
rkrkrkkb8e056ea44ea
diff --git a/core/memory/attachments.py b/core/memory/attachments.pyindex 8e751da64..47d97ef26 100644--- a/core/memory/attachments.py+++ b/core/memory/attachments.py@@ -53,6 +53,9 @@ _BUNDLE_FILENAME_PATTERN = re.compile(r"(0[0-7])\.([a-z0-9]{1,8})")_STAGING_NAME_PATTERN = re.compile(r"([0-9a-f]{32})\.tmp")_VALID_KINDS = frozenset({"image", "audio", "doc", "pdf", "html", "email"})_INVALID_PERCENT_ESCAPE = re.compile(r"%(?![0-9A-Fa-f]{2})")+_DETERMINISTIC_STORAGE_ERRNOS = frozenset(+ {errno.ENOENT, errno.ENOTDIR, getattr(errno, "ELOOP", errno.ENOENT)}+)def attachment_pin_root(effective_home: Path | str | None = None) -> Path:@@ -70,6 +73,10 @@ class AttachmentPinError(OSError):self.error = error+class AttachmentBundleInvalidError(AttachmentPinError):+ """Internal proof that retrying the same pinned bundle cannot make it valid."""++@dataclass(frozen=True, slots=True)class PinnedAttachment:"""Persistable metadata for one file in an Avibe-owned bundle."""@@ -157,18 +164,18 @@ def decode_pinned_bundle(bundle_id: str, payload: str) -> PinnedBundle:try:value = json.loads(payload)except (TypeError, ValueError) as error:- raise AttachmentPinError(+ raise AttachmentBundleInvalidError("memory_store_unavailable","pinned attachment manifest is invalid",) from errorif not isinstance(value, dict) or set(value) != {"version", "total_bytes", "attachments"}:- raise AttachmentPinError(+ raise AttachmentBundleInvalidError("memory_store_unavailable","pinned attachment manifest is invalid",)items = value.get("attachments")if value.get("version") != 1 or not isinstance(items, list):- raise AttachmentPinError(+ raise AttachmentBundleInvalidError("memory_store_unavailable","pinned attachment manifest is invalid",)@@ -201,7 +208,7 @@ def decode_pinned_bundle(bundle_id: str, payload: str) -> PinnedBundle:total_bytes=value["total_bytes"],)except (KeyError, TypeError, ValueError) as error:- raise AttachmentPinError(+ raise AttachmentBundleInvalidError("memory_store_unavailable","pinned attachment manifest is invalid",) from error@@ -365,7 +372,7 @@ class AttachmentPinStore:total_bytes=bundle.total_bytes,)except (AttributeError, TypeError, ValueError) as error:- raise AttachmentPinError(+ raise AttachmentBundleInvalidError("memory_store_unavailable","pinned attachment metadata is invalid",) from error@@ -380,7 +387,7 @@ class AttachmentPinStore:for index, pinned in enumerate(checked.attachments))if observed_files != expected_files:- raise AttachmentPinError(+ raise AttachmentBundleInvalidError("memory_store_unavailable","attachment bundle does not match its manifest",)@@ -966,8 +973,17 @@ def _require_private_directory(info: os.stat_result, label: str) -> None:def _require_private_file(info: os.stat_result, label: str) -> None:if not stat.S_ISREG(info.st_mode) or stat.S_IMODE(info.st_mode) != 0o600:- raise AttachmentPinError("memory_store_unavailable", f"{label} is not private")- _require_current_owner(info, label, storage=True)+ raise AttachmentBundleInvalidError(+ "memory_store_unavailable",+ f"{label} is not private",+ )+ try:+ _require_current_owner(info, label, storage=True)+ except AttachmentPinError as error:+ raise AttachmentBundleInvalidError(+ error.error,+ str(error),+ ) from errordef _require_safe_source_directory(info: os.stat_result) -> None:@@ -1115,7 +1131,7 @@ def _verify_pinned_file(bundle_fd: int, filename: str, pinned: PinnedAttachment)before = os.fstat(descriptor)_require_private_file(before, "pinned attachment")if before.st_size != pinned.size_bytes:- raise AttachmentPinError(+ raise AttachmentBundleInvalidError("memory_store_unavailable","pinned attachment has an unexpected size",)@@ -1127,7 +1143,7 @@ def _verify_pinned_file(bundle_fd: int, filename: str, pinned: PinnedAttachment)breakread_bytes += len(chunk)if read_bytes > pinned.size_bytes:- raise AttachmentPinError(+ raise AttachmentBundleInvalidError("memory_store_unavailable","pinned attachment has an unexpected size",)@@ -1138,7 +1154,7 @@ def _verify_pinned_file(bundle_fd: int, filename: str, pinned: PinnedAttachment)or digest.hexdigest() != pinned.sha256or not _same_source_file(before, after)):- raise AttachmentPinError(+ raise AttachmentBundleInvalidError("memory_store_unavailable","pinned attachment integrity check failed",)@@ -1268,7 +1284,7 @@ def _validate_private_bundle(parent_fd: int, name: str) -> tuple[str, ...]:maximum=MAX_PINNED_ATTACHMENTS,)if not 1 <= len(filenames) <= MAX_PINNED_ATTACHMENTS:- raise AttachmentPinError(+ raise AttachmentBundleInvalidError("memory_store_unavailable","attachment bundle has an invalid file count",)@@ -1280,7 +1296,7 @@ def _validate_private_bundle(parent_fd: int, name: str) -> tuple[str, ...]:or match.group(1) != f"{index:02d}"or match.group(2) not in SUPPORTED_ATTACHMENT_EXTENSIONS):- raise AttachmentPinError(+ raise AttachmentBundleInvalidError("memory_store_unavailable","attachment bundle contains an unexpected file",)@@ -1290,13 +1306,13 @@ def _validate_private_bundle(parent_fd: int, name: str) -> tuple[str, ...]:raise _storage_failure(error, "attachment bundle entry could not be inspected") from error_require_private_file(info, "pinned attachment")if info.st_size > MAX_PINNED_ATTACHMENT_BYTES:- raise AttachmentPinError(+ raise AttachmentBundleInvalidError("memory_store_unavailable","attachment bundle contains an oversized file",)total_bytes += info.st_sizeif total_bytes > MAX_PINNED_BUNDLE_BYTES:- raise AttachmentPinError(+ raise AttachmentBundleInvalidError("memory_store_unavailable","attachment bundle exceeds its size limit",)@@ -1439,4 +1455,9 @@ def _storage_failure(error: OSError, message: str) -> AttachmentPinError:if error.errno in {errno.ENOSPC, getattr(errno, "EDQUOT", errno.ENOSPC)}else "memory_store_unavailable")- return AttachmentPinError(code, message)+ failure_type = (+ AttachmentBundleInvalidError+ if error.errno in _DETERMINISTIC_STORAGE_ERRNOS+ else AttachmentPinError+ )+ return failure_type(code, message)diff --git a/core/memory/coordinator.py b/core/memory/coordinator.pyindex e4b87ad26..e77e4e308 100644--- a/core/memory/coordinator.py+++ b/core/memory/coordinator.py@@ -12,6 +12,7 @@ from datetime import datetime, timedelta, timezonefrom typing import Any, Literalfrom core.memory.attachments import (+ AttachmentBundleInvalidError,AttachmentPinError,AttachmentPinStore,decode_pinned_bundle,@@ -530,13 +531,11 @@ class SessionFlushCoordinator:attachment_payload,)except AttachmentPinError as failure:- await self._settle_failure(+ await self._settle_attachment_preflight_failure(row,lease_owner=lease_owner,- outcome=MessageFailure(- error=failure.error,- retryable=False,- ),+ failure=failure,+ retryable=False,)return Falsetry:@@ -545,13 +544,11 @@ class SessionFlushCoordinator:bundle,)except AttachmentPinError as failure:- await self._settle_failure(+ await self._settle_attachment_preflight_failure(row,lease_owner=lease_owner,- outcome=MessageFailure(- error=failure.error,- retryable=True,- ),+ failure=failure,+ retryable=True,)return Falsecapture = ProviderCapture(@@ -714,6 +711,34 @@ class SessionFlushCoordinator:lease_owner=lease_owner,)+ async def _settle_attachment_preflight_failure(+ self,+ row: QueueRow,+ *,+ lease_owner: str,+ failure: AttachmentPinError,+ retryable: bool,+ ) -> None:+ bundle_id = None+ if isinstance(failure, AttachmentBundleInvalidError):+ bundle_id = await self._store_call(+ self._store._downgrade_claimed_attachment_to_text,+ row,+ lease_owner=lease_owner,+ now=self._current_time(),+ )+ if bundle_id is None:+ await self._settle_failure(+ row,+ lease_owner=lease_owner,+ outcome=MessageFailure(+ error=failure.error,+ retryable=retryable,+ ),+ )+ return+ await self._release_bundle(bundle_id)+async def _settle_failure(self,row: QueueRow,diff --git a/core/memory/store.py b/core/memory/store.pyindex d048f5303..97bc26db1 100644--- a/core/memory/store.py+++ b/core/memory/store.py@@ -1602,6 +1602,76 @@ class MemoryStore:).fetchone()return current is not None+ def _downgrade_claimed_attachment_to_text(+ self,+ row: QueueRow,+ *,+ lease_owner: str,+ now: datetime,+ ) -> str | None:+ """Atomically return one exact attachment claim as text-only work."""++ now_iso = _iso_from_datetime(now)+ with self._transaction() as conn:+ current = conn.execute(+ """+ SELECT q.payload_text, q.attachment_bundle_id+ FROM memory_capture_queue AS q+ JOIN memory_attachment_bundle AS bundle+ ON bundle.bundle_id = q.attachment_bundle_id+ WHERE q.source_message_digest = ? AND q.epoch = ?+ AND q.state = 'processing' AND q.lease_owner = ?+ AND q.lease_token = ? AND q.payload_attachments IS NOT NULL+ AND q.attachment_bundle_id IS NOT NULL+ AND bundle.state = 'pinned'+ """,+ (+ row.source_message_digest,+ row.epoch,+ lease_owner,+ row.lease_token,+ ),+ ).fetchone()+ if current is None:+ return None+ payload_text = current["payload_text"]+ if not isinstance(payload_text, str) or not payload_text.strip():+ return None+ bundle_id = str(current["attachment_bundle_id"])+ updated = conn.execute(+ """+ UPDATE memory_capture_queue+ SET state = 'pending', payload_attachments = NULL,+ attachment_bundle_id = NULL, lease_owner = NULL,+ lease_at = NULL+ WHERE source_message_digest = ? AND epoch = ?+ AND state = 'processing' AND lease_owner = ? AND lease_token = ?+ AND payload_attachments IS NOT NULL AND attachment_bundle_id = ?+ """,+ (+ row.source_message_digest,+ row.epoch,+ lease_owner,+ row.lease_token,+ bundle_id,+ ),+ )+ if updated.rowcount != 1:+ return None+ releasing = conn.execute(+ """+ UPDATE memory_attachment_bundle+ SET state = 'releasing', updated_at = ?+ WHERE bundle_id = ? AND state = 'pinned'+ """,+ (now_iso, bundle_id),+ )+ if releasing.rowcount != 1:+ raise RuntimeError("Memory attachment release intent was lost")+ # The same commit records cleanup intent, so cancellation or a crash+ # leaves boot reconciliation a durable bundle to finish releasing.+ return bundle_id+def settle(self,row: QueueRow,diff --git a/tests/scenarios/memory_im_attachment_capture/catalog.yaml b/tests/scenarios/memory_im_attachment_capture/catalog.yamlindex b11fd438c..2b176d628 100644--- a/tests/scenarios/memory_im_attachment_capture/catalog.yaml+++ b/tests/scenarios/memory_im_attachment_capture/catalog.yaml@@ -76,3 +76,10 @@ scenarios:layer: scenariodelivery_slice: 5test: tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py::test_enabled_platform_attachment_fact_reaches_memory_admission+ - id: MEMORY-IM-ATTACH-009+ name: Claimed attachment preflight failure retries its caption as text-only+ status: covered+ kind: degradation+ layer: scenario+ delivery_slice: 6+ test: tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py::test_claimed_attachment_preflight_failure_retries_caption_as_text_onlydiff --git a/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_catalog.py b/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_catalog.pyindex f769e3278..933757529 100644--- a/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_catalog.py+++ b/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_catalog.py@@ -65,6 +65,7 @@ def test_memory_im_attachment_catalog_is_indexed_and_locks_the_approved_contract("MEMORY-IM-ATTACH-006", "platform_contract", 5),("MEMORY-IM-ATTACH-007", "platform_contract", 5),("MEMORY-IM-ATTACH-008", "platform_contract", 5),+ ("MEMORY-IM-ATTACH-009", "degradation", 6),],)def test_memory_im_attachment_covered_scenario_contract(@@ -87,6 +88,7 @@ def test_memory_im_attachment_covered_scenario_contract("MEMORY-IM-ATTACH-006","MEMORY-IM-ATTACH-007","MEMORY-IM-ATTACH-008",+ "MEMORY-IM-ATTACH-009",}assert rows[scenario_id]["status"] == "covered"assert rows[scenario_id]["kind"] == kinddiff --git a/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py b/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.pyindex ae5b4d66f..7772d1c68 100644--- a/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py+++ b/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py@@ -215,6 +215,40 @@ def test_invalid_sibling_preserves_valid_attachment_and_leaves_no_memory_leak(assert not tuple(harness.home.rglob("*.part"))+def test_claimed_attachment_preflight_failure_retries_caption_as_text_only(+ tmp_path,+ monkeypatch,+) -> None:+ """Scenario: MEMORY-IM-ATTACH-009."""++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "avibe-home"))+ harness = MemoryIMAttachmentScenarioHarness(tmp_path)+ original_drain = harness.module.drain++ async def corrupt_bundle_then_drain() -> int:+ bundle_root = harness.home / "memory" / "attachments" / "bundles"+ pinned_file = next(bundle_root.glob("*/*"))+ pinned_file.write_bytes(b"corrupt after durable enqueue")+ return await original_drain()++ monkeypatch.setattr(harness.module, "drain", corrupt_bundle_then_drain)+ asyncio.run(+ harness.capture(+ text="Keep this caption even if the image breaks",+ payloads={"evidence.png": ("image/png", PNG_BYTES)},+ )+ )++ assert len(harness.provider.captures) == 1+ assert harness.provider.captures[0].text == (+ "Keep this caption even if the image breaks"+ )+ assert harness.provider.captures[0].attachments == ()+ assert harness.provider.observed_payloads == []+ assert harness.provider.call_log == []+ assert harness.memory_bundle_entries == ()++class _ScenarioPrincipals:def principal_for_user_key(self, user_key: str) -> str:assert user_key.split(":", 1)[0] in {"discord", "telegram", "lark", "wechat"}diff --git a/tests/test_memory_attachments.py b/tests/test_memory_attachments.pyindex c670d6d93..1c48ccaf6 100644--- a/tests/test_memory_attachments.py+++ b/tests/test_memory_attachments.py@@ -15,6 +15,7 @@ import pytestimport core.memory.attachments as attachment_moduleimport core.memory.confined_filesystem as confined_filesystem_modulefrom core.memory.attachments import (+ AttachmentBundleInvalidError,AttachmentPinError,AttachmentPinStore,PinnedAttachment,@@ -349,6 +350,7 @@ def test_provider_projection_rejects_tampered_pinned_bytes(attachment_roots) ->store.provider_attachments(bundle)_assert_pin_error(error, "memory_store_unavailable")+ assert isinstance(error.value, AttachmentBundleInvalidError)def test_provider_projection_rejects_untracked_bundle_file(attachment_roots) -> None:@@ -365,6 +367,7 @@ def test_provider_projection_rejects_untracked_bundle_file(attachment_roots) ->store.provider_attachments(bundle)_assert_pin_error(error, "memory_store_unavailable")+ assert isinstance(error.value, AttachmentBundleInvalidError)def test_reconcile_preserves_references_and_removes_releasing_orphans_and_staging(@@ -424,6 +427,7 @@ def test_attachment_reads_translate_temporary_ordering_database_failure(store.reconcile({bundle.bundle_id}, set())_assert_pin_error(raised, "memory_store_unavailable")+ assert not isinstance(raised.value, AttachmentBundleInvalidError)assert isinstance(raised.value.__cause__,confined_filesystem_module.ConfinedFilesystemError,diff --git a/tests/test_memory_flush_coordinator.py b/tests/test_memory_flush_coordinator.pyindex 04ad599a9..86f24d596 100644--- a/tests/test_memory_flush_coordinator.py+++ b/tests/test_memory_flush_coordinator.py@@ -1,7 +1,9 @@from __future__ import annotationsimport asyncio+import errnoimport gc+import sqlite3import threadingfrom collections import dequefrom datetime import UTC, datetime, timedelta@@ -10,6 +12,8 @@ from pathlib import Pathimport pytestfrom config import paths+from core.memory import attachments as attachment_module+from core.memory import confined_filesystem as confined_filesystem_modulefrom core.memory.attachments import (AttachmentPinStore,PinnedBundle,@@ -150,6 +154,7 @@ def _enqueue_attachment_bundle(bundle: PinnedBundle,*,source: str,+ payload_text: str = "remember the attachment",) -> QueueRow:result = store.enqueue_request(source_message_id=source,@@ -157,7 +162,7 @@ def _enqueue_attachment_bundle(principal_id=PRINCIPAL,project_ref=PROJECT,provenance="user_input",- payload_text="remember the attachment",+ payload_text=payload_text,payload_attachments=encode_pinned_bundle(bundle),attachment_bundle_id=bundle.bundle_id,attachment_bundle_relative_path=bundle.relative_path,@@ -3336,7 +3341,469 @@ async def test_cancelled_add_after_provider_entry_remains_ambiguous(tmp_path: Pa-async def test_attachment_preflight_failure_is_bounded_without_session_fence(+def test_claimed_attachment_downgrade_is_atomic_and_lease_fenced(+ tmp_path: Path,+) -> None:+ store = _store(tmp_path)+ _attachment_store, bundle, _pinned_path = _pin_attachment_bundle()+ original = _enqueue_attachment_bundle(+ store,+ bundle,+ source="atomic-text-downgrade",+ )+ stale = store.claim_due(+ lease_owner="first-worker",+ now="2026-01-01T00:00:00.000Z",+ )+ assert stale is not None++ assert (+ store._downgrade_claimed_attachment_to_text(+ stale,+ lease_owner="wrong-worker",+ now=datetime(2026, 1, 1, 0, 0, 1, tzinfo=UTC),+ )+ is None+ )+ assert store.return_unsubmitted_claim(stale, lease_owner="first-worker")+ current = store.claim_due(+ lease_owner="second-worker",+ now="2026-01-01T00:00:02.000Z",+ )+ assert current is not None+ assert current.lease_token == stale.lease_token + 1+ assert (+ store._downgrade_claimed_attachment_to_text(+ stale,+ lease_owner="second-worker",+ now=datetime(2026, 1, 1, 0, 0, 3, tzinfo=UTC),+ )+ is None+ )++ assert (+ store._downgrade_claimed_attachment_to_text(+ current,+ lease_owner="second-worker",+ now=datetime(2026, 1, 1, 0, 0, 4, tzinfo=UTC),+ )+ == bundle.bundle_id+ )+ downgraded = store.get_queue_row(original.source_message_digest)+ assert downgraded is not None+ assert (+ downgraded.source_message_digest,+ downgraded.created_at,+ downgraded.payload_text,+ downgraded.state,+ downgraded.attempts,+ downgraded.payload_attachments,+ downgraded.attachment_bundle_id,+ downgraded.lease_owner,+ downgraded.lease_at,+ ) == (+ original.source_message_digest,+ original.created_at,+ "remember the attachment",+ "pending",+ 0,+ None,+ None,+ None,+ None,+ )+ assert store.attachment_bundle_sets() == (+ frozenset(),+ frozenset({bundle.bundle_id}),+ )+ assert (+ store._downgrade_claimed_attachment_to_text(+ current,+ lease_owner="second-worker",+ now=datetime(2026, 1, 1, 0, 0, 5, tzinfo=UTC),+ )+ is None+ )+++def test_claimed_attachment_downgrade_rolls_back_caption_and_bundle_together(+ tmp_path: Path,+) -> None:+ store = _store(tmp_path)+ _attachment_store, bundle, _pinned_path = _pin_attachment_bundle()+ _enqueue_attachment_bundle(store, bundle, source="rollback-text-downgrade")+ claimed = store.claim_due(+ lease_owner="worker",+ now="2026-01-01T00:00:00.000Z",+ )+ assert claimed is not None+ with sqlite3.connect(store.path) as conn:+ conn.execute(+ """+ CREATE TRIGGER fail_attachment_release+ BEFORE UPDATE OF state ON memory_attachment_bundle+ WHEN NEW.state = 'releasing'+ BEGIN+ SELECT RAISE(ABORT, 'forced release failure');+ END+ """+ )++ with pytest.raises(sqlite3.IntegrityError, match="forced release failure"):+ store._downgrade_claimed_attachment_to_text(+ claimed,+ lease_owner="worker",+ now=datetime(2026, 1, 1, 0, 0, 1, tzinfo=UTC),+ )++ preserved = store.get_queue_row(claimed.source_message_digest)+ assert preserved is not None+ assert (+ preserved.state,+ preserved.payload_text,+ preserved.payload_attachments,+ preserved.attachment_bundle_id,+ preserved.lease_owner,+ preserved.lease_token,+ preserved.attempts,+ ) == (+ "processing",+ claimed.payload_text,+ claimed.payload_attachments,+ bundle.bundle_id,+ "worker",+ claimed.lease_token,+ 0,+ )+ assert store.attachment_bundle_sets() == (+ frozenset({bundle.bundle_id}),+ frozenset(),+ )++[email protected]("failure", ["decode", "missing", "tamper"])+async def test_attachment_preflight_failure_retries_caption_as_text_only(+ tmp_path: Path,+ failure: str,+) -> None:+ store = _store(tmp_path)+ attachment_store, bundle, pinned_path = _pin_attachment_bundle()+ original = _enqueue_attachment_bundle(+ store,+ bundle,+ source=f"{failure}-text-downgrade",+ )+ if failure == "decode":+ with sqlite3.connect(store.path) as conn:+ conn.execute(+ """+ UPDATE memory_capture_queue+ SET payload_attachments = '{}'+ WHERE source_message_digest = ?+ """,+ (original.source_message_digest,),+ )+ elif failure == "missing":+ pinned_path.unlink()+ else:+ pinned_path.write_bytes(b"tampered after enqueue")++ provider = FakeMemoryProvider()+ releases: list[str] = []+ coordinator = SessionFlushCoordinator(+ store=store,+ provider=provider,+ enabled=lambda: True,+ attachment_store=attachment_store,+ release_attachment=releases.append,+ )+ claimed = store.claim_due(+ lease_owner="worker",+ now="2026-01-01T00:00:00.000Z",+ )+ assert claimed is not None++ assert not await coordinator.deliver(claimed, lease_owner="worker")++ downgraded = store.get_queue_row(original.source_message_digest)+ assert downgraded is not None+ assert (+ downgraded.source_message_digest,+ downgraded.created_at,+ downgraded.payload_text,+ downgraded.state,+ downgraded.attempts,+ downgraded.payload_attachments,+ downgraded.attachment_bundle_id,+ ) == (+ original.source_message_digest,+ original.created_at,+ "remember the attachment",+ "pending",+ 0,+ None,+ None,+ )+ assert releases == [bundle.bundle_id]+ assert store.attachment_bundle_sets() == (frozenset(), frozenset())+ assert not pinned_path.exists()+ assert provider.captures == []++ retry = store.claim_due(+ lease_owner="retry-worker",+ now="2026-01-01T00:00:01.000Z",+ )+ assert retry is not None+ assert retry.source_message_digest == original.source_message_digest+ assert await coordinator.deliver(retry, lease_owner="retry-worker")+ assert len(provider.captures) == 1+ assert provider.captures[0].text == "remember the attachment"+ assert provider.captures[0].attachments == ()+ assert releases == [bundle.bundle_id]+++ ("failure", "expected_state"),+ [("decode", "dead"), ("revalidation", "pending")],+)+async def test_captionless_attachment_preflight_failure_always_makes_progress(+ tmp_path: Path,+ failure: str,+ expected_state: str,+) -> None:+ store = _store(tmp_path)+ attachment_store, bundle, pinned_path = _pin_attachment_bundle()+ original = _enqueue_attachment_bundle(+ store,+ bundle,+ source=f"captionless-{failure}-failure",+ payload_text="",+ )+ if failure == "decode":+ with sqlite3.connect(store.path) as conn:+ conn.execute(+ """+ UPDATE memory_capture_queue+ SET payload_attachments = '{}'+ WHERE source_message_digest = ?+ """,+ (original.source_message_digest,),+ )+ else:+ pinned_path.write_bytes(b"tampered after enqueue")+ coordinator = SessionFlushCoordinator(+ store=store,+ provider=FakeMemoryProvider(),+ enabled=lambda: True,+ attachment_store=attachment_store,+ )+ claimed = store.claim_due(+ lease_owner="worker",+ now="2026-01-01T00:00:00.000Z",+ )+ assert claimed is not None++ assert not await coordinator.deliver(claimed, lease_owner="worker")++ terminal = store.get_queue_row(original.source_message_digest)+ assert terminal is not None+ assert (terminal.state, terminal.attempts) == (expected_state, 1)+ if failure == "decode":+ assert (+ terminal.payload_text,+ terminal.payload_attachments,+ terminal.attachment_bundle_id,+ ) == (None, None, None)+ assert store.attachment_bundle_sets() == (frozenset(), frozenset())+ else:+ assert terminal.payload_text == ""+ assert terminal.payload_attachments == original.payload_attachments+ assert terminal.attachment_bundle_id == bundle.bundle_id+ assert store.attachment_bundle_sets() == (+ frozenset({bundle.bundle_id}),+ frozenset(),+ )++[email protected]("failure_source", ["file-open", "directory-order"])+async def test_transient_attachment_projection_failure_retries_original_bundle(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ failure_source: str,+) -> None:+ store = _store(tmp_path)+ attachment_store, bundle, pinned_path = _pin_attachment_bundle()+ original = _enqueue_attachment_bundle(+ store,+ bundle,+ source="transient-projection-failure",+ )+ provider = FakeMemoryProvider()+ current = [datetime(2026, 1, 1, tzinfo=UTC)]+ coordinator = SessionFlushCoordinator(+ store=store,+ provider=provider,+ enabled=lambda: True,+ now=lambda: current[0],+ attachment_store=attachment_store,+ )+ claimed = store.claim_due(+ lease_owner="worker",+ now="2026-01-01T00:00:00.000Z",+ )+ assert claimed is not None+ failed = False+ if failure_source == "file-open":+ original_operation = attachment_module.os.open++ def fail_once(*args, **kwargs):+ nonlocal failed+ if not failed:+ failed = True+ raise OSError(errno.EMFILE, "temporary descriptor exhaustion")+ return original_operation(*args, **kwargs)++ monkeypatch.setattr(attachment_module.os, "open", fail_once)+ else:+ original_operation = confined_filesystem_module.sqlite3.connect++ def fail_once(*args, **kwargs):+ nonlocal failed+ if not failed and args and args[0] == "":+ failed = True+ raise sqlite3.OperationalError("temporary ordering unavailable")+ return original_operation(*args, **kwargs)++ monkeypatch.setattr(confined_filesystem_module.sqlite3, "connect", fail_once)+ assert not await coordinator.deliver(claimed, lease_owner="worker")++ retryable = store.get_queue_row(original.source_message_digest)+ assert retryable is not None+ assert (+ retryable.state,+ retryable.attempts,+ retryable.payload_text,+ retryable.payload_attachments,+ retryable.attachment_bundle_id,+ ) == (+ "pending",+ 1,+ "remember the attachment",+ original.payload_attachments,+ bundle.bundle_id,+ )+ assert store.attachment_bundle_sets() == (+ frozenset({bundle.bundle_id}),+ frozenset(),+ )+ assert pinned_path.exists()+ assert provider.captures == []++ if failure_source == "file-open":+ monkeypatch.setattr(attachment_module.os, "open", original_operation)+ else:+ monkeypatch.setattr(+ confined_filesystem_module.sqlite3,+ "connect",+ original_operation,+ )+ current[0] += timedelta(seconds=30)+ retry = store.claim_due(+ lease_owner="retry-worker",+ now="2026-01-01T00:00:30.000Z",+ )+ assert retry is not None+ assert await coordinator.deliver(retry, lease_owner="retry-worker")+ assert len(provider.captures) == 1+ assert provider.captures[0].attachments+++async def test_cancel_after_downgrade_leaves_releasing_bundle_for_boot_recovery(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ store = _store(tmp_path)+ attachment_store, bundle, pinned_path = _pin_attachment_bundle()+ original = _enqueue_attachment_bundle(+ store,+ bundle,+ source="cancelled-text-downgrade",+ )+ with sqlite3.connect(store.path) as conn:+ conn.execute(+ """+ UPDATE memory_capture_queue+ SET payload_attachments = '{}'+ WHERE source_message_digest = ?+ """,+ (original.source_message_digest,),+ )++ release_entered = threading.Event()+ release_continue = threading.Event()+ release_finished = threading.Event()+ original_release = attachment_store.release++ def blocked_release(bundle_id: str) -> None:+ release_entered.set()+ release_continue.wait(timeout=2)+ original_release(bundle_id)+ release_finished.set()++ monkeypatch.setattr(attachment_store, "release", blocked_release)+ provider = FakeMemoryProvider()+ coordinator = SessionFlushCoordinator(+ store=store,+ provider=provider,+ enabled=lambda: True,+ attachment_store=attachment_store,+ )+ claimed = store.claim_due(+ lease_owner="worker",+ now="2026-01-01T00:00:00.000Z",+ )+ assert claimed is not None+ delivery = asyncio.create_task(coordinator.deliver(claimed, lease_owner="worker"))+ assert await asyncio.to_thread(release_entered.wait, 1)++ committed = store.get_queue_row(original.source_message_digest)+ assert committed is not None+ assert (+ committed.state,+ committed.payload_text,+ committed.payload_attachments,+ committed.attachment_bundle_id,+ committed.attempts,+ ) == ("pending", "remember the attachment", None, None, 0)+ assert store.attachment_bundle_sets() == (+ frozenset(),+ frozenset({bundle.bundle_id}),+ )++ delivery.cancel()+ release_continue.set()+ with pytest.raises(asyncio.CancelledError):+ await delivery+ assert await asyncio.to_thread(release_finished.wait, 1)+ assert provider.captures == []+ assert store.attachment_bundle_sets() == (+ frozenset(),+ frozenset({bundle.bundle_id}),+ )++ monkeypatch.setattr(attachment_store, "release", original_release)+ restarted = SessionFlushCoordinator(+ store=store,+ provider=provider,+ enabled=lambda: True,+ attachment_store=attachment_store,+ )+ await restarted.recover(lease_owner="next-boot")+ assert store.attachment_bundle_sets() == (frozenset(), frozenset())+ assert not pinned_path.exists()+++async def test_attachment_preflight_downgrade_survives_deferred_bundle_release(tmp_path: Path,) -> None:store = _store(tmp_path)@@ -3349,44 +3816,52 @@ async def test_attachment_preflight_failure_is_bounded_without_session_fence(pinned_path.chmod(0o644)provider = FakeMemoryProvider()- current = [datetime(2026, 1, 1, tzinfo=UTC)]coordinator = SessionFlushCoordinator(store=store,provider=provider,enabled=lambda: True,- now=lambda: current[0],+ now=lambda: datetime(2026, 1, 1, tzinfo=UTC),attachment_store=attachment_store,)await coordinator.recover(lease_owner="initial-boot")await _run_processing_actions(coordinator)- for expected_attempts, delay in ((1, 30), (2, 120), (3, 0)):- claimed = store.claim_due(- lease_owner=f"worker-{expected_attempts}",- now=current[0].isoformat(timespec="milliseconds").replace("+00:00", "Z"),- )- assert claimed is not None- assert not await coordinator.deliver(- claimed,- lease_owner=f"worker-{expected_attempts}",- )- queued = store.list_queue_rows()[0]- assert queued.attempts == expected_attempts- expected_state = "dead" if expected_attempts == 3 else "pending"- assert queued.state == expected_state- session_state = store.get_session_flush_state(row.provider_session_ref)- assert session_state is not None and session_state.state == "idle"- current[0] += timedelta(seconds=delay)+ claimed = store.claim_due(+ lease_owner="worker",+ now="2026-01-01T00:00:00.000Z",+ )+ assert claimed is not None+ assert not await coordinator.deliver(claimed, lease_owner="worker")+ queued = store.list_queue_rows()[0]+ assert (+ queued.state,+ queued.attempts,+ queued.payload_text,+ queued.payload_attachments,+ queued.attachment_bundle_id,+ ) == ("pending", 0, "remember the attachment", None, None)+ session_state = store.get_session_flush_state(row.provider_session_ref)+ assert session_state is not None and session_state.state == "idle"assert store.attachment_bundle_sets() == (frozenset(),frozenset({bundle.bundle_id}),)+ retry = store.claim_due(+ lease_owner="retry-worker",+ now="2026-01-01T00:00:01.000Z",+ )+ assert retry is not None+ assert await coordinator.deliver(retry, lease_owner="retry-worker")+ assert len(provider.captures) == 1+ assert provider.captures[0].text == "remember the attachment"+ assert provider.captures[0].attachments == ()+restarted = SessionFlushCoordinator(store=store,provider=provider,enabled=lambda: True,- now=lambda: current[0],+ now=lambda: datetime(2026, 1, 1, tzinfo=UTC),attachment_store=attachment_store,)await restarted.recover(lease_owner="restarted-worker")@@ -3395,6 +3870,10 @@ async def test_attachment_preflight_failure_is_bounded_without_session_fence(frozenset(),frozenset({bundle.bundle_id}),)+ pinned_path.chmod(0o600)+ await restarted.recover(lease_owner="repaired-worker")+ assert store.attachment_bundle_sets() == (frozenset(), frozenset())+ assert not pinned_path.exists()later = _enqueue(store,@@ -3409,11 +3888,12 @@ async def test_attachment_preflight_failure_is_bounded_without_session_fence(for expected in (later, unrelated):claimed = store.claim_due(lease_owner="later-worker",- now=current[0].isoformat(timespec="milliseconds").replace("+00:00", "Z"),+ now="2026-01-01T00:00:02.000Z",)assert claimed is not Noneassert await restarted.deliver(claimed, lease_owner="later-worker")assert [capture.text for capture in provider.captures] == [+ "remember the attachment",later.payload_text,unrelated.payload_text,]