Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(memory): align write deadlines and expose recovery outcomes (#2022)

rkrkrkk06a864947556
diff --git a/avibe_memory/everos.py b/avibe_memory/everos.py
index 2c50a3561..214dab625 100644
--- a/avibe_memory/everos.py
+++ b/avibe_memory/everos.py
@@ -53,8 +53,12 @@ _SIDECAR_TIMEOUT_SECONDS = 20.0
_AGENTIC_TIMEOUT_HEADER = "X-Avibe-Memory-Agentic-Timeout-Seconds"
_AGENTIC_ROUND_HEADER = "X-Avibe-Memory-Agentic-Round"
_SIDECAR_TIMEOUT_RESPONSE_MARGIN_SECONDS = 0.05
-_ADD_TIMEOUT_SECONDS = 30.0
-_FLUSH_TIMEOUT_SECONDS = 300.0
+# Both routes await memorize() in the pinned EverOS runtime. Keep the
+# transport outside its enforced invocation deadline so a slow success can reply.
+MEMORIZE_TIMEOUT_SECONDS = 360.0
+_WRITE_RESPONSE_MARGIN_SECONDS = 10.0
+_ADD_TIMEOUT_SECONDS = MEMORIZE_TIMEOUT_SECONDS + _WRITE_RESPONSE_MARGIN_SECONDS
+_FLUSH_TIMEOUT_SECONDS = _ADD_TIMEOUT_SECONDS
PROCESSING_PROBE_REQUEST_TIMEOUT_SECONDS = 8.0
PROCESSING_PROBE_DEADLINE_MARGIN_SECONDS = 2.0
PROCESSING_PROBE_MAX_ENDPOINTS = 4
@@ -412,7 +416,7 @@ class EverOSPort:
request_id is None
or status not in {"extracted", "no_extraction"}
):
- return FlushUnknown(reason="transport")
+ return FlushUnknown(reason="invalid_response")
return FlushSucceeded(request_id=request_id, status=status)
error = envelope.get("error") if envelope is not None else None
error_code = error.get("code") if isinstance(error, dict) else None
@@ -465,7 +469,10 @@ class EverOSPort:
logger.warning("EverOS sidecar connection timeout route=%s latency_ms=%s", route, _elapsed_ms(started))
raise MemoryProviderSystemFailure() from exc
except httpx.TimeoutException as exc:
- logger.warning("EverOS sidecar timeout route=%s latency_ms=%s", route, _elapsed_ms(started))
+ logger.warning(
+ "EverOS sidecar timeout route=%s latency_ms=%s timeout_kind=%s",
+ route, _elapsed_ms(started), type(exc).__name__,
+ )
raise MemoryProviderFailure(
"memory_provider_timeout",
ambiguous=True,
diff --git a/avibe_memory/module.py b/avibe_memory/module.py
index 5b61ae965..7eddc0f8f 100644
--- a/avibe_memory/module.py
+++ b/avibe_memory/module.py
@@ -52,6 +52,7 @@ from avibe_memory.types import (
CaptureRequest,
CaptureSkipped,
MemoryErrorCode,
+ MemoryFailureLogEntry,
MemoryItem,
MemoryItems,
MemoryListItem,
@@ -273,10 +274,15 @@ class MemoryModule:
finally:
lock.release()
- def pause_claims(self) -> None:
- """Synchronously fence new volatile writer admissions."""
+ def write_failure_observations(self) -> tuple[MemoryFailureLogEntry, ...]:
+ """Return bounded process-local write evidence, including child recoveries."""
- self._writer.pause_intake()
+ return self._writer.failure_observations()
+
+ def pause_claims(self, *, unavailable: bool = False) -> None:
+ """Fence admissions and, after a child failure, queued provider calls."""
+
+ self._writer.pause_intake(unavailable=unavailable)
async def quiesce_claims(self, *, timeout_seconds: float | None = None) -> bool:
"""Fence claims and join in-flight add and flush work under one deadline."""
diff --git a/avibe_memory/observations.py b/avibe_memory/observations.py
index 08edadfc8..01fb68872 100644
--- a/avibe_memory/observations.py
+++ b/avibe_memory/observations.py
@@ -37,7 +37,7 @@ class FlushRejected:
@dataclass(frozen=True)
class FlushUnknown:
- reason: Literal["timeout", "transport"]
+ reason: Literal["timeout", "transport", "invalid_response"]
@dataclass(frozen=True)
diff --git a/avibe_memory/process.py b/avibe_memory/process.py
index fac2e5fa2..310c99e82 100644
--- a/avibe_memory/process.py
+++ b/avibe_memory/process.py
@@ -43,6 +43,7 @@ from avibe_memory.confined_filesystem import (
required_no_follow_flag,
)
from avibe_memory.everos import (
+ MEMORIZE_TIMEOUT_SECONDS,
EverOSPort,
MULTIMODAL_EXPLICIT_ENV,
PROCESSING_PROBE_MAX_DEADLINE_SECONDS,
@@ -2103,6 +2104,7 @@ def _write_memory_child_config(
"",
"[memorize]",
'mode = "chat"',
+ f"session_lock_timeout_seconds = {MEMORIZE_TIMEOUT_SECONDS}",
"",
"[rerank]",
'model = ""',
diff --git a/avibe_memory/processing_record.py b/avibe_memory/processing_record.py
index 46f361c16..ef59f749d 100644
--- a/avibe_memory/processing_record.py
+++ b/avibe_memory/processing_record.py
@@ -401,7 +401,7 @@ class MemoryProcessingRecord:
durable = observation.items
source = (
SourceObservation(
- "unavailable",
+ "partial" if durable else "unavailable",
reason=observation.unavailable_reason,
)
if observation.unavailable_reason is not None
diff --git a/avibe_memory/runtime.py b/avibe_memory/runtime.py
index ad1c02f91..fec70aad0 100644
--- a/avibe_memory/runtime.py
+++ b/avibe_memory/runtime.py
@@ -1226,10 +1226,12 @@ class MemoryRuntime:
reason = acquired.local_observation_reason(maintenance_reason)
if not acquired.same_lifecycle(before) or reason is not None:
return FailureLogObservation((), reason or "busy")
- # Per-call durable failure history was retired with the delivery
- # protocol. Keep the diagnostics capability explicit: unavailable
- # is distinct from an authorized empty result.
- return FailureLogObservation((), "memory_failure_history_unavailable")
+ # These bounded observations survive child recovery, not controller
+ # restart. Do not present them as a complete durable failure history.
+ return FailureLogObservation(
+ self.module.write_failure_observations(),
+ "memory_failure_history_unavailable",
+ )
async def _processing_record_sources(
self,
@@ -1384,6 +1386,7 @@ class MemoryRuntime:
payload: dict[str, Any] = {
"status": "ok",
"items": [asdict(entry) for entry in anomalies.items],
+ "source": asdict(anomalies.source),
}
return payload
@@ -2373,7 +2376,7 @@ class MemoryRuntime:
if self._closing or self.needs_repair:
return
- self.module.pause_claims()
+ self.module.pause_claims(unavailable=True)
self._runtime_error = "memory_sidecar_unavailable"
async def _recover_current_sidecar(self) -> bool:
diff --git a/avibe_memory/types.py b/avibe_memory/types.py
index 5fefaf7d4..75256941d 100644
--- a/avibe_memory/types.py
+++ b/avibe_memory/types.py
@@ -409,4 +409,5 @@ class MemoryFailureLogEntry:
attempts: int = 0
state: str = "unknown"
operation: str = "unknown"
- generation: int = 0
+ generation: int | None = None
+ affected_count: int = 1
diff --git a/avibe_memory/writer.py b/avibe_memory/writer.py
index 8817be9b5..ec78a37cc 100644
--- a/avibe_memory/writer.py
+++ b/avibe_memory/writer.py
@@ -7,9 +7,10 @@ import logging
import time
from collections import OrderedDict, deque
from collections.abc import Awaitable, Callable
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from datetime import datetime, timezone
from typing import Literal
+from uuid import uuid4
from avibe_memory.attachments import AttachmentPinError, AttachmentPinStore, PinnedBundle
from core.blocking import run_blocking
@@ -28,7 +29,9 @@ from avibe_memory.everos import (
)
from avibe_memory.observations import AddResult, FlushResult
from avibe_memory.store import MemoryStore, VolatileAdmission
-from avibe_memory.types import CaptureAttachment, ProviderSessionRef
+from avibe_memory.types import (
+ CaptureAttachment, MemoryFailureKind, MemoryFailureLogEntry, ProviderSessionRef,
+)
logger = logging.getLogger(__name__)
@@ -54,6 +57,7 @@ class _CaptureItem:
bundle: PinnedBundle | None
reservation: "WriterReservation"
raw_session_id: str
+ submitted: bool = False # Provider invocation began; completion may still be unknown.
@dataclass(slots=True)
@@ -148,6 +152,8 @@ class BestEffortMemoryWriter:
self._unavailable = False
self._attachments_disabled = False
self.dropped = 0
+ self._failures: deque[MemoryFailureLogEntry] = deque(maxlen=50)
+ self._drop_observation_id: str | None = None
@property
def unavailable(self) -> bool:
@@ -157,8 +163,46 @@ class BestEffortMemoryWriter:
def attachments_enabled(self) -> bool:
return not self._attachments_disabled
+ def failure_observations(self) -> tuple[MemoryFailureLogEntry, ...]:
+ """Recent process-local anomalies; retained across native child recovery."""
+
+ return tuple(reversed(self._failures))
+
+ def _record_failure(
+ self, kind: MemoryFailureKind, error: str, *,
+ state: str, operation: str, request_id: str | None = None, attempts: int = 0,
+ ) -> None:
+ occurred_at = self._now()
+ if occurred_at.tzinfo is None:
+ occurred_at = occurred_at.replace(tzinfo=timezone.utc)
+ entry = MemoryFailureLogEntry(
+ id=uuid4().hex, kind=kind,
+ occurred_at=occurred_at.astimezone(timezone.utc).isoformat(timespec="milliseconds"),
+ error_code=error, state=state, operation=operation, request_id=request_id, attempts=attempts,
+ )
+ self._failures.append(entry)
+ # Stable, content-free evidence also survives a controller restart in
+ # the ordinary service log. Never include captures or exception bodies.
+ logger.warning(
+ "Memory write observation id=%s kind=%s operation=%s state=%s",
+ entry.id, kind, operation, state,
+ )
+
+ def _record_unsubmitted_drop(self) -> None:
+ self.dropped += 1
+ if self._failures and self._failures[-1].id == self._drop_observation_id:
+ previous = self._failures[-1]
+ self._failures[-1] = replace(previous, affected_count=previous.affected_count + 1)
+ logger.warning("Memory unsubmitted drops id=%s count=%s", previous.id, previous.affected_count + 1)
+ else:
+ self._record_failure(
+ "delivery_abandoned", "memory_sidecar_unavailable",
+ state="not_submitted", operation="add",
+ )
+ self._drop_observation_id = self._failures[-1].id
+
def dropped_count(self) -> int:
- """Return the process-local count of queue insertions discarded as full."""
+ """Return process-local queue saturation and recovery-drop counts."""
return self.dropped
@@ -175,9 +219,12 @@ class BestEffortMemoryWriter:
def replace_provider(self, provider: MemoryProviderPort) -> None:
self._provider = provider
self._unavailable = False
+ self._drop_observation_id = None
- def pause_intake(self) -> None:
+ def pause_intake(self, *, unavailable: bool = False) -> None:
self._intake_paused = True
+ if unavailable:
+ self._unavailable = True
def resume_intake(self) -> None:
# ``_closed`` independently fences a settling cleanup. Clearing the
@@ -189,6 +236,8 @@ class BestEffortMemoryWriter:
"""Forget process-local duplicate claims after a completed Clear."""
self._duplicate_lru.clear()
+ self._failures.clear()
+ self._drop_observation_id = None
def reserve(
self,
@@ -494,40 +543,41 @@ class BestEffortMemoryWriter:
)
attempt = 0
while attempt < MAX_ATTEMPTS:
- if not self._enabled():
+ if not self._enabled() or self._unavailable:
await self._cleanup_item(item)
return
attempt += 1
self._active_provider_calls += 1
try:
+ item.submitted = True
result = await self._provider.add(capture)
except asyncio.CancelledError:
await self._ambiguous_outcome(
- "memory_provider_timeout",
- recover=False,
+ "memory_sidecar_unavailable" if self._unavailable else "memory_processing_interrupted",
+ recover=False, attempts=attempt,
)
await self._cleanup_item(item)
raise
except MemoryProviderSystemFailure as failure:
if failure.ambiguous:
- await self._ambiguous_outcome(failure.error)
+ await self._ambiguous_outcome(failure.error, attempts=attempt)
await self._cleanup_item(item)
return
- if attempt < MAX_ATTEMPTS:
+ if attempt < MAX_ATTEMPTS and not self._unavailable:
continue
- await self._terminal_failure(item, failure.error)
+ await self._terminal_failure(item, failure.error, attempts=attempt)
return
except MemoryProviderFailure as failure:
if failure.ambiguous:
- await self._ambiguous_outcome(failure.error)
+ await self._ambiguous_outcome(failure.error, attempts=attempt)
await self._cleanup_item(item)
return
- if failure.retryable and attempt < MAX_ATTEMPTS:
+ if failure.retryable and attempt < MAX_ATTEMPTS and not self._unavailable:
continue
- await self._terminal_failure(item, failure.error)
+ await self._terminal_failure(item, failure.error, attempts=attempt)
return
except Exception:
- await self._ambiguous_outcome("memory_provider_response_invalid")
+ await self._ambiguous_outcome("memory_provider_response_invalid", attempts=attempt)
await self._cleanup_item(item)
return
finally:
@@ -546,6 +596,7 @@ class BestEffortMemoryWriter:
and capture.text.strip()
and attachment_add_rejection_proves_no_write(capture, result)
and attempt < MAX_ATTEMPTS
+ and not self._unavailable
):
attachments = ()
capture = ProviderCapture(
@@ -555,9 +606,12 @@ class BestEffortMemoryWriter:
sender_name=capture.sender_name,
)
continue
- await self._terminal_failure(item, "memory_processing_failed")
+ await self._terminal_failure(
+ item, "memory_processing_failed", request_id=result.request_id,
+ unknown=result.server_fault, attempts=attempt, provider_error=result.error_code,
+ )
return
- await self._ambiguous_outcome("memory_provider_response_invalid")
+ await self._ambiguous_outcome("memory_provider_response_invalid", attempts=attempt)
await self._cleanup_item(item)
return
@@ -588,10 +642,17 @@ class BestEffortMemoryWriter:
pending.last_ack_at = now
await self._cleanup_item(item)
- async def _terminal_failure(self, item: _CaptureItem, error: str) -> None:
+ async def _terminal_failure(
+ self, item: _CaptureItem, error: str, *, attempts: int, request_id: str | None = None,
+ unknown: bool = False, provider_error: str | None = None,
+ ) -> None:
if not self._enabled():
await self._cleanup_item(item)
return
+ self._record_failure(
+ "result_unknown" if unknown else "delivery_abandoned", provider_error or error,
+ state="unknown" if unknown else "failed", operation="add", request_id=request_id, attempts=attempts,
+ )
try:
await run_blocking(self._store.set_last_error, error)
except Exception:
@@ -602,6 +663,8 @@ class BestEffortMemoryWriter:
if not item.reservation.active:
return
try:
+ if self._unavailable and not item.submitted:
+ self._record_unsubmitted_drop()
if item.bundle is not None and self._attachment_store is not None:
try:
await run_blocking(
@@ -642,7 +705,7 @@ class BestEffortMemoryWriter:
continue
result: FlushResult | None = None
for attempt in range(1, MAX_ATTEMPTS + 1):
- if not self._enabled():
+ if not self._enabled() or self._unavailable:
self._pending.pop(key, None)
return
self._active_provider_calls += 1
@@ -651,37 +714,58 @@ class BestEffortMemoryWriter:
except asyncio.CancelledError:
self._pending.pop(key, None)
await self._ambiguous_outcome(
- "memory_provider_timeout",
- recover=False,
+ "memory_sidecar_unavailable" if self._unavailable else "memory_processing_interrupted",
+ recover=False, operation="flush", attempts=attempt,
)
raise
except MemoryProviderFailure as failure:
if failure.ambiguous:
self._pending.pop(key, None)
- await self._ambiguous_outcome(failure.error)
+ await self._ambiguous_outcome(failure.error, operation="flush", attempts=attempt)
return
- if failure.retryable and attempt < MAX_ATTEMPTS:
+ if failure.retryable and attempt < MAX_ATTEMPTS and not self._unavailable:
continue
- result = FlushRejected(None, failure.error, True)
+ self._record_failure(
+ "distillation_rejected", failure.error, state="failed",
+ operation="flush", attempts=attempt,
+ )
+ self._pending.pop(key, None)
+ result = None # Already recorded; continue with the next pending session.
+ break
except Exception:
self._pending.pop(key, None)
- await self._ambiguous_outcome("memory_provider_response_invalid")
+ await self._ambiguous_outcome("memory_provider_response_invalid", operation="flush", attempts=attempt)
return
finally:
self._active_provider_calls = max(0, self._active_provider_calls - 1)
- if isinstance(result, FlushRetryable) and attempt < MAX_ATTEMPTS:
+ if isinstance(result, FlushRetryable) and attempt < MAX_ATTEMPTS and not self._unavailable:
continue
break
if isinstance(result, FlushUnknown):
self._pending.pop(key, None)
- await self._ambiguous_outcome("memory_provider_timeout")
+ await self._ambiguous_outcome(
+ {
+ "timeout": "memory_provider_timeout",
+ "transport": "memory_sidecar_unavailable",
+ "invalid_response": "memory_provider_response_invalid",
+ }[result.reason],
+ operation="flush", attempts=attempt,
+ )
return
if isinstance(result, FlushSucceeded) and (
result.status not in {"extracted", "no_extraction"}
or not _valid_receipt(result.request_id)
):
- await self._ambiguous_outcome("memory_provider_response_invalid")
+ await self._ambiguous_outcome("memory_provider_response_invalid", operation="flush", attempts=attempt)
return
+ if isinstance(result, (FlushRejected, FlushRetryable)):
+ unknown = isinstance(result, FlushRejected) and result.server_fault
+ self._record_failure(
+ "result_unknown" if unknown else "distillation_rejected",
+ result.error_code or "memory_processing_failed", state="unknown" if unknown else "failed",
+ operation="flush", attempts=attempt,
+ request_id=result.request_id if isinstance(result, FlushRejected) else None,
+ )
if isinstance(result, (FlushSucceeded, FlushRejected, FlushRetryable)):
# A retryable response that survives the fixed attempt budget
# is settled as volatile loss; never leave a scheduled marker
@@ -724,11 +808,16 @@ class BestEffortMemoryWriter:
except asyncio.CancelledError:
return
- async def _ambiguous_outcome(self, _error: str, *, recover: bool = True) -> None:
+ async def _ambiguous_outcome(
+ self, error: str, *, attempts: int, recover: bool = True, operation: str = "add",
+ ) -> None:
if not self._enabled():
return
+ self._record_failure("result_unknown", error, state="unknown", operation=operation, attempts=attempts)
self._unavailable = True
self._intake_paused = True
+ if self._pending:
+ logger.warning("Memory flush tracking discarded sessions=%s", len(self._pending))
self._pending.clear()
if self._ambiguous_stop_reap is not None:
try:
diff --git a/docs/CLI.md b/docs/CLI.md
index 00cca8c7e..07dd4bbd8 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -233,6 +233,16 @@ scan or backfill is performed by this feature.
Read scoped local Memory or submit context for best-effort, process-local capture — facts the user explicitly asked to remember, and conclusions the Agent distills on its own from the conversation and from work on this machine, including lasting environment or account facts it meets in files or tool output — through the existing mode-0600 controller socket. Acceptance does not guarantee provider delivery or persistence. This command does not start a service and has no clear, configuration, export, or delete subcommands.
+Memory Settings' Processing Record retains up to 50 recent write anomalies for
+this service process. It distinguishes an unknown submitted result from captures
+discarded before submission; consecutive discarded captures share an
+`affected_count`. Native engine recovery preserves these observations, while a
+service restart or explicit data clear removes them. The source is partial,
+not a complete failure history; sanitized service logs retain operational events.
+An unknown capture is never automatically replayed. A healthy engine does not
+prove an earlier write completed. Add and flush wait for the native six-minute
+processing budget plus a ten-second response margin.
+
`status` works from a normal terminal. `profile`, `list`, `search`, and `remember`
require an eligible Agent shell where Avibe has injected the current Session
context; running them from a normal terminal returns `memory_access_denied`.
diff --git a/docs/plans/memory-issue-2020-write-timeout.md b/docs/plans/memory-issue-2020-write-timeout.md
new file mode 100644
index 000000000..eb7a30076
--- /dev/null
+++ b/docs/plans/memory-issue-2020-write-timeout.md
@@ -0,0 +1,124 @@
+# Memory write deadline and recovery observations (#2020)
+
+## Goal and evidence
+
+A valid native add can take longer than Avibe's 30-second response wait.
+The adapter then reports an ambiguous result and the existing recovery closes
+both the native child and volatile writer generation. Health after recovery
+does not establish whether that write completed.
+
+The released EverOS 1.2.3 archive was verified against SHA-256
+`296f320ec9acc55fc01f5c4f6ff2a4a338710a33b73e41615f957ce0569e3e07`.
+Both HTTP write routes await `memorize()`, whose outer `asyncio.timeout` covers
+lock acquisition and processing. Its default is 360 seconds.
+
+## Smallest complete change
+
+1. Generate an explicit native memorize deadline of 360 seconds from one
+ constant. Both add and flush clients allow 370 seconds (10-second response
+ margin). Keep connection setup at three seconds. HTTPX bounds I/O phases;
+ this is not claimed to be an independently enforced total HTTP wall-clock
+ deadline. The native invocation owns the processing deadline.
+2. Preserve the existing bounded recovery and no-replay policy. Successful
+ receipts still use the current success path. Terminal errors now retain
+ sanitized observations; server errors do not prove that no write occurred.
+3. Keep at most 50 recent anomalies in the existing writer object. Expose them
+ through the existing Processing Record and failure API. A native child
+ restart does not clear them; a controller restart or explicit data clear
+ does. The source remains `partial`, never a complete durable history.
+4. Distinguish an in-flight `unknown` result from queued `not_submitted`
+ captures. Consecutive queued drops aggregate in `affected_count` so a full
+ queue does not evict the unknown observation. Barriers are not captures.
+ Emit content-free events to ordinary service logs for longer-lived evidence.
+
+### Deliberate scope choice
+
+The initial design offered either preserving unsent captures or exposing their
+best-effort disposal. This implementation chooses explicit disposal: normal
+Wake closes the writer in multiple authority transitions. Retaining queued
+payloads across it would require a second recovery lifecycle and attachment /
+identity fencing changes. That cost is unnecessary to repair premature timeout
+and silent disposal. No queue, schema migration, receipt-reconciliation service,
+or automatic replay is introduced.
+
+Tracking discarded pending flush sessions is logged separately; these sessions
+already have add receipts and are not reported as lost messages. A native 5xx
+response ends the call but does not establish absence of partial writes. It is
+reported as unknown without restarting a responsive native child solely for
+that HTTP response.
+
+## Acceptance invariants and validation
+
+- A native operation within its processing budget can return before the adapter
+ abandons its response, for both add and flush.
+- Unknown submissions are never replayed. Recovery cannot erase their recent
+ observations or make unsubmitted captures indistinguishable from them.
+- Queue disposal counts actual captures; barrier count is never a loss count.
+- Subsequent successful work does not erase earlier anomalies.
+- Diagnostic records are bounded and contain no payload or credential text.
+- Authority-changing close/reset retains its existing semantics.
+
+Fast tests cover adapter timeout propagation, unknown outcome/no replay,
+worker-drain and close-drain disposal, bounded/coalesced observations, successful
+continuation and Processing Record projection. Existing cancellation, attachment,
+process and lifecycle tests remain applicable.
+
+An opt-in released-artifact test runs the real native HTTP routes and memorize
+lock/deadline over a real Unix socket with a synthetic local pipeline. A
+31-second call succeeds; response loss after a synthetic write is ambiguous;
+a later write succeeds. All HOME/XDG/provider paths are disposable and no keys
+or external providers are used. This verifies the actual bundled synchronous
+contract; it does not measure an external LLM or claim end-to-end extraction
+quality. Unified Incus/IM acceptance remains an integration check before release.
+
+## Delivery checklist
+
+- [x] Red regressions before implementation.
+- [x] Timeout and observation changes without a persistent workflow.
+- [x] Isolated released-artifact contract trial.
+- [ ] Focused validation, PR review and CI.
+
+## Review boundary audit
+
+Review of `abce9c5` identified three diagnostic projection gaps (count, source
+scope and attempt count). Review of `9da60f3` identified two classification gaps
+(supervisor-crash disposal and non-ambiguous flush exceptions). Before further
+edits the orchestrator audited the whole boundary: ambiguous transport failures
+and supervisor crashes both fence queued provider calls; intentional authority
+changes retain their prior semantics. Non-ambiguous exceptions retain their
+original error and failed classification rather than becoming synthetic HTTP
+server failures. These changes use existing writer state only.
+
+Review of `2427c87` exposed the remaining diagnostic boundary class: captures
+already dequeued but still preparing attachments, coalescing across distinct
+recoveries, and loss of provider rejection codes. The orchestrator chose one
+cleanup accounting point guarded by the existing reservation lifetime. A capture
+records whether provider invocation began; only unavailable, never-submitted
+captures count as disposal. Provider replacement closes the coalescing incident.
+Native rejection codes remain diagnostic-only; persisted `last_error` retains
+its released generic code. No workflow or storage state is added.
+
+Review of `d3d7e15` found cancellation mislabeled as a transport timeout. The
+orchestrator audited both operation cancellation branches: an already-unavailable
+writer reports sidecar unavailability; other cancellation reports processing
+interruption. Actual transport timeouts retain their adapter-owned classification.
+The change is diagnostic-only and does not modify stop/reap or replay behavior.
+
+Review of `9a9e8ff` found three remaining members of the boundary/diagnostic
+class: flush retries and later sessions ignored the crash fence, invalid flush
+responses were labeled transport failures, and opaque rejection codes entered
+service logs. The orchestrator retained the existing model: check availability
+before every flush attempt, carry one invalid-response reason in the shared
+result contract, and log only internal observation classification. Opaque codes
+remain in bounded process-local observations only. Regression coverage includes
+all flush continuation outcomes and both rejection operations with a secret/newline
+canary; no new recovery state or sanitization framework is needed.
+
+Review of `7e65afc92` found three members of the settlement/projection class:
+definite failures were lost when a crash prevented a retry, the failures endpoint
+dropped the partial-source qualifier, and observations fabricated generation 0.
+The orchestrator chose to settle known add/flush failures before the crash fence
+blocks further attempts (including attachment fallback), reuse the existing source
+projection in the failures response, and mark unsupported generation metadata null.
+The UI omits unknown generation while retaining real values from older responses.
+No epoch queries, additional lifecycle state, or durable history is introduced.
diff --git a/tests/helpers/memory_native_write_server.py b/tests/helpers/memory_native_write_server.py
new file mode 100644
index 000000000..01b07b66d
--- /dev/null
+++ b/tests/helpers/memory_native_write_server.py
@@ -0,0 +1,62 @@
+"""Isolated native HTTP/memorize contract fixture, never a production launcher.
+
+Run only via test_memory_native_write_contract.py. The real route and memorize
+lock/deadline execute; the costly pipeline is replaced by a synthetic local write.
+"""
+
+import asyncio
+import importlib
+import json
+import sys
+from pathlib import Path
+
+import uvicorn
+from fastapi import FastAPI
+
+from everos.config.settings import load_settings
+from everos.entrypoints.api.routes.memorize import router
+
+native = importlib.import_module("everos.service.memorize")
+root = Path(sys.argv[1])
+assert load_settings().memorize.session_lock_timeout_seconds == 360.0
+
+
+async def synthetic_pipeline(payload, **kwargs):
+ text = payload["messages"][0]["content"] if payload["messages"] else "flush"
+ if text == "slow":
+ await asyncio.sleep(31)
+ # Prove a representative write is confined to the disposable root.
+ (root / f"{text}.receipt").write_text("synthetic committed")
+ return native.MemorizeResult(message_count=len(payload["messages"]), status="accumulated")
+
+
+native._memorize_locked = synthetic_pipeline
+app = FastAPI()
+app.include_router(router, prefix="/api/v2")
+
+
+class LoseResponse:
+ async def __call__(self, scope, receive, send):
+ if scope["type"] != "http":
+ return await app(scope, receive, send)
+ request = await receive()
+ body = json.loads(request.get("body", b"{}"))
+ lose = any(m.get("content") == "lose" for m in body.get("messages", []))
+ first = True
+
+ async def replay():
+ nonlocal first
+ if first:
+ first = False
+ return request
+ return await receive()
+
+ async def delayed_send(message):
+ if lose and message["type"] == "http.response.start":
+ await asyncio.sleep(1)
+ await send(message)
+
+ await app(scope, replay, delayed_send)
+
+
+uvicorn.run(LoseResponse(), uds=str(root / "native.sock"), access_log=False, log_level="error")
diff --git a/tests/scenarios/memory_repair/catalog.yaml b/tests/scenarios/memory_repair/catalog.yaml
index 5ab5e9ec5..e0d9953ea 100644
--- a/tests/scenarios/memory_repair/catalog.yaml
+++ b/tests/scenarios/memory_repair/catalog.yaml
@@ -255,3 +255,27 @@ scenarios:
when: An old memory is captured and Wake replaces the child before a new capture
then: Old and newly processed inputs are both recallable
evidence_boundary: External model responses are deterministic doubles; Incus deployment requires unavailable seed configuration
+ - id: MEMORY-WAKE-206
+ name: Native write acknowledgement outlasts legitimate synchronous processing
+ status: partial
+ kind: degradation
+ layer: integration
+ test: tests/test_memory_native_write_contract.py::test_native_slow_ack_response_loss_and_continued_writes
+ related_tests:
+ - tests/test_memory_everos.py::test_write_transport_outlasts_native_memorize_deadline
+ given: Verified released native artifact with isolated HOME and Unix socket
+ when: Processing takes over thirty seconds or a response is withheld after submission
+ then: A valid slow acknowledgement succeeds and response loss stays ambiguous without replay
+ evidence_boundary: Real native routes and memorize lock/deadline; synthetic pipeline writes, no external LLM or extraction-quality claim
+ - id: MEMORY-WAKE-207
+ name: Recovery keeps unknown writes distinct from unsubmitted capture disposal
+ status: covered
+ kind: recovery
+ layer: contract
+ test: tests/test_memory_writer.py::test_unknown_write_and_unsubmitted_drops_remain_visible_after_recovery
+ related_tests:
+ - tests/test_memory_writer.py::test_recovery_close_reports_only_unsubmitted_captures
+ - tests/test_memory_runtime.py::test_write_anomaly_is_visible_through_processing_record
+ given: An in-flight write, unsent captures and barriers share the bounded writer
+ when: Response loss triggers recovery and later submissions succeed
+ then: The in-flight write is never replayed and recent partial diagnostics distinguish unknown from not submitted without counting barriers as messages
diff --git a/tests/scenarios/memory_repair/observations.yaml b/tests/scenarios/memory_repair/observations.yaml
index b941ac1b1..d82358e15 100644
--- a/tests/scenarios/memory_repair/observations.yaml
+++ b/tests/scenarios/memory_repair/observations.yaml
@@ -27,3 +27,8 @@ observations:
- MEMORY-WAKE-204
- MEMORY-WAKE-205
observation: Darwin arm64 tests inject the psutil boot-time read locally; public references survive the display-time shift. The real EverOS 1.2.3 pipeline requires 1024-dimensional embedding responses. Native production Wake, claims, writer, extraction, indexing and keyword recall run with test-owned storage and loopback model doubles; this is not model-quality or four-platform deployment evidence. Local Incus provisioning is blocked before target creation by required IM/model seed configuration.
+ - id: MEMORY-REPAIR-OBS-005
+ scenarios:
+ - MEMORY-WAKE-206
+ - MEMORY-WAKE-207
+ observation: Released darwin-arm64 EverOS 1.2.3 archive SHA-256 296f320ec9acc55fc01f5c4f6ff2a4a338710a33b73e41615f957ce0569e3e07 passed the isolated native route/memorize contract trial on 2026-09-17. A synthetic pipeline acknowledges after 31 seconds; withholding its response reports an ambiguous write and a later request succeeds. Real external models and unified Incus surfaces remain residual integration checks.
diff --git a/tests/test_memory_everos.py b/tests/test_memory_everos.py
index 541bb70dc..616cb5c89 100644
--- a/tests/test_memory_everos.py
+++ b/tests/test_memory_everos.py
@@ -634,7 +634,7 @@ def test_flush_treats_unusable_2xx_body_as_unknown_without_replaying_write(caplo
ack, result = asyncio.run(run())
assert ack == AddAck(request_id=None, status=None)
- assert result == FlushUnknown(reason="transport")
+ assert result == FlushUnknown(reason="invalid_response")
assert requests == ["/api/v2/memory/add", "/api/v2/memory/flush"]
assert "add returned 2xx with an unusable response body" in caplog.text
assert "flush returned 2xx with an unusable response body" in caplog.text
@@ -658,7 +658,7 @@ def test_flush_treats_unsupported_2xx_status_as_unknown(caplog) -> None:
ack, result = asyncio.run(run())
assert ack == AddAck(request_id=None, status=None)
- assert result == FlushUnknown(reason="transport")
+ assert result == FlushUnknown(reason="invalid_response")
assert "add returned an unsupported status value" in caplog.text
assert "flush returned an unsupported status value" in caplog.text
@@ -674,7 +674,7 @@ def test_flush_rejects_invalid_success_receipt(request_id: str) -> None:
with _sidecar_transport(handler):
result = asyncio.run(EverOSPort(Path("/tmp/everos.sock")).flush(SESSION_REF))
- assert result == FlushUnknown(reason="transport")
+ assert result == FlushUnknown(reason="invalid_response")
@pytest.mark.parametrize(
@@ -2649,3 +2649,19 @@ def test_sidecar_failure_logs_never_contain_capture_or_response_canaries(caplog)
assert rejection.error_code is None
assert capture_canary not in caplog.text
assert response_canary not in caplog.text
+
+
+def test_write_transport_outlasts_native_memorize_deadline():
+ """Both native write routes await the same bounded memorize invocation."""
+ def handler(request):
+ assert request.extensions["timeout"]["read"] > 360.0
+ status = "accumulated" if request.url.path.endswith("/add") else "no_extraction"
+ return httpx.Response(200, json={"request_id": "test", "data": {"status": status}})
+
+ async def run():
+ provider = EverOSPort(Path("/tmp/unused-memory-test.sock"))
+ await provider.add(ProviderCapture(SESSION_REF, "synthetic", 1))
+ await provider.flush(SESSION_REF)
+
+ with _sidecar_transport(handler):
+ asyncio.run(run())
diff --git a/tests/test_memory_native_write_contract.py b/tests/test_memory_native_write_contract.py
new file mode 100644
index 000000000..146c10c8b
--- /dev/null
+++ b/tests/test_memory_native_write_contract.py
@@ -0,0 +1,69 @@
+"""Opt-in test against an extracted, verified released Memory runtime archive.
+
+AVIBE_TEST_NATIVE_PYTHON=/path/to/extracted/bin/python pytest -q -s \
+ tests/test_memory_native_write_contract.py
+
+No provider credentials, real user data, or external API calls are used.
+"""
+
+import asyncio
+import os
+import subprocess
+import tempfile
+from pathlib import Path
+
+import pytest
+
+from avibe_memory.everos import AddAck, EverOSPort, MemoryProviderFailure, ProviderCapture
+from avibe_memory.types import ProviderSessionRef
+
+
+async def test_native_slow_ack_response_loss_and_continued_writes():
+ """MEMORY-WAKE-206: slow native success and response loss are distinct."""
+ python = os.environ.get("AVIBE_TEST_NATIVE_PYTHON")
+ if not python:
+ pytest.skip("requires a verified extracted native runtime archive")
+ # Short path also satisfies macOS's Unix socket path length limit.
+ with tempfile.TemporaryDirectory(prefix="mem2020-", dir="/tmp") as directory:
+ root = Path(directory)
+ env = {"PATH": "/usr/bin:/bin", "HOME": str(root), "EVEROS_ROOT": str(root / "data"),
+ "XDG_CONFIG_HOME": str(root / "config"), "XDG_DATA_HOME": str(root / "data"),
+ "XDG_CACHE_HOME": str(root / "cache"), "XDG_STATE_HOME": str(root / "state"),
+ "ENV": "prod", "PYTHONNOUSERSITE": "1"}
+ helper = Path(__file__).parent / "helpers" / "memory_native_write_server.py"
+ with (root / "stderr").open("w+") as output:
+ child = subprocess.Popen([python, "-I", str(helper.resolve()), str(root)],
+ cwd=root, env=env, stdout=output, stderr=output)
+ try:
+ for _ in range(200):
+ if child.poll() is not None:
+ output.seek(0)
+ pytest.fail(output.read())
+ if (root / "native.sock").exists():
+ break
+ await asyncio.sleep(.05)
+ else:
+ pytest.fail("native fixture failed to start")
+ ref = ProviderSessionRef("synthetic-owner", 0, "default", "synthetic-session")
+ provider = EverOSPort(root / "native.sock")
+ started = asyncio.get_running_loop().time()
+ ack = await provider.add(ProviderCapture(ref, "slow", 1))
+ assert asyncio.get_running_loop().time() - started > 30
+ assert isinstance(ack, AddAck) and ack.request_id
+ assert (root / "slow.receipt").read_text() == "synthetic committed"
+ lossy = EverOSPort(root / "native.sock", add_timeout_seconds=.1)
+ with pytest.raises(MemoryProviderFailure) as failure:
+ await lossy.add(ProviderCapture(ref, "lose", 2))
+ assert failure.value.ambiguous
+ assert (root / "lose.receipt").is_file()
+ ack = await provider.add(ProviderCapture(ref, "continued", 3))
+ assert isinstance(ack, AddAck) and ack.request_id
+ assert child.poll() is None
+ finally:
+ child.terminate()
+ try:
+ child.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ child.kill()
+ child.wait(timeout=5)
diff --git a/tests/test_memory_process.py b/tests/test_memory_process.py
index a9b22010f..2e889441d 100644
--- a/tests/test_memory_process.py
+++ b/tests/test_memory_process.py
@@ -594,6 +594,9 @@ def test_generated_ome_profile_strategies_follow_switch(tmp_path: Path, profile_
attachments = tmp_path / "attachments"
memory_dir.mkdir(parents=True); (memory_dir / "generated").mkdir(); provider_root.mkdir(parents=True); attachments.mkdir(parents=True)
_write_memory_child_config(memory_dir=memory_dir, provider_root=provider_root, attachments_root=attachments, settings=EverOSProcessSettings(profile_enabled=profile_enabled))
+ from avibe_memory.everos import MEMORIZE_TIMEOUT_SECONDS
+ native = tomllib.loads((provider_root / "everos.toml").read_text())
+ assert native["memorize"]["session_lock_timeout_seconds"] == MEMORIZE_TIMEOUT_SECONDS
ome = tomllib.loads((provider_root / "ome.toml").read_text())
strategies = ome["strategies"]
assert strategies["trigger_profile_clustering"]["enabled"] is profile_enabled
diff --git a/tests/test_memory_runtime.py b/tests/test_memory_runtime.py
index 41798d16a..af62151ad 100644
--- a/tests/test_memory_runtime.py
+++ b/tests/test_memory_runtime.py
@@ -735,3 +735,77 @@ def test_aggregate_list_cursor_is_bound_to_selected_owner() -> None:
projects=projects,
fingerprint=agent_fingerprint,
)
+
+
+async def test_write_anomaly_is_visible_through_processing_record(tmp_path):
+ runtime = _runtime(tmp_path)
+ writer = runtime.module._writer
+ writer._record_failure(
+ "result_unknown", "memory_provider_timeout", state="unknown", operation="add",
+ )
+ observation = await runtime._processing_record_failure_log(None)
+ assert observation.items[0].kind == "result_unknown"
+ assert observation.unavailable_reason == "memory_failure_history_unavailable"
+ from avibe_memory.processing_record import MemoryProcessingRecord, MemoryProcessingRecordPort
+ from types import SimpleNamespace
+ record = MemoryProcessingRecord(SimpleNamespace(failure_log=runtime._processing_record_failure_log))
+ projection = await record._read_durable_anomalies(None, asyncio.get_running_loop().time() + 5)
+ assert projection.source.status == "partial"
+ assert projection.items == observation.items
+
+ async def read_failures(**_kwargs):
+ return projection, None
+
+ runtime._processing_record.read_failures = read_failures
+ payload = await runtime.failure_log_payload()
+ assert payload["source"]["status"] == "partial"
+ assert payload["source"]["reason"] == "memory_failure_history_unavailable"
+ assert payload["items"][0]["generation"] is None
+ await runtime.close()
+
+
[email protected]("worker_drains", [False, True])
+async def test_supervisor_crash_reports_unsubmitted_captures(tmp_path, monkeypatch, worker_drains):
+ """MEMORY-WAKE-207: crash callback fences queued delivery before Wake."""
+ from avibe_memory.everos import FakeMemoryProvider
+ from avibe_memory.store import VolatileAdmission
+ from avibe_memory.types import ProviderSessionRef
+ from avibe_memory.writer import MAX_WRITER_PERMITS
+
+ runtime = _runtime(tmp_path)
+ writer = runtime.module._writer
+ provider = FakeMemoryProvider()
+ writer.replace_provider(provider)
+ monkeypatch.setattr(writer, "_enabled", lambda: True)
+ start = writer._ensure_worker
+ monkeypatch.setattr(writer, "_ensure_worker", lambda: None)
+ ref = ProviderSessionRef("u-" + "1" * 32, 0, "default", "synthetic-session")
+ for index in range(2):
+ reservation = writer.reserve(f"digest-{index}")
+ assert not isinstance(reservation, str)
+ assert writer.offer_capture(
+ reservation, VolatileAdmission("accepted", f"digest-{index}", ref, index + 1, "raw-session"),
+ text="synthetic capture", attachments=(), bundle=None,
+ ) == "queued"
+ assert writer.offer_barrier("raw-session") == "queued"
+
+ runtime._current_sidecar_unavailable()
+ if worker_drains:
+ start()
+ await writer.wait_idle_for_tests()
+
+ async def wake():
+ assert writer._queue.empty()
+ assert writer._permits == MAX_WRITER_PERMITS
+ return {"ok": True}
+
+ monkeypatch.setattr(runtime, "wake", wake)
+ assert await runtime._recover_current_sidecar()
+ assert provider.captures == []
+ assert writer.dropped_count() == 2
+ entries = runtime.module.write_failure_observations()
+ assert len(entries) == 1
+ assert (entries[0].state, entries[0].affected_count, entries[0].attempts) == ("not_submitted", 2, 0)
+ await runtime.close()
diff --git a/tests/test_memory_writer.py b/tests/test_memory_writer.py
index 6cbb896bc..4b0b0cc70 100644
--- a/tests/test_memory_writer.py
+++ b/tests/test_memory_writer.py
@@ -555,8 +555,10 @@ async def test_quiesce_deadline_leaves_blocking_cleanup_fenced_in_background(
@pytest.mark.asyncio
[email protected]("crashed", [False, True])
async def test_quiesce_cancels_inflight_call_and_releases_volatile_resources(
tmp_path: Path,
+ crashed: bool,
) -> None:
entered = asyncio.Event()
stop_calls = 0
@@ -605,10 +607,17 @@ async def test_quiesce_cancels_inflight_call_and_releases_volatile_resources(
_ref(1), "raw-session-1", deque(["digest-1"]), 0.0, 0.0
)
+ if crashed:
+ writer.pause_intake(unavailable=True)
assert await writer.quiesce(timeout_seconds=1.0)
assert stop_calls == 1
assert recoveries == [False]
+ assert writer.dropped_count() == 0
+ assert writer.failure_observations()[0].state == "unknown"
+ assert writer.failure_observations()[0].error_code == (
+ "memory_sidecar_unavailable" if crashed else "memory_processing_interrupted"
+ )
assert attachment_store.released == ["bundle-0"]
assert writer._permits == MAX_WRITER_PERMITS
assert writer._pending == {}
@@ -616,8 +625,10 @@ async def test_quiesce_cancels_inflight_call_and_releases_volatile_resources(
@pytest.mark.asyncio
[email protected]("crashed", [False, True])
async def test_cancelled_flush_reaps_sidecar_before_releasing_barrier(
tmp_path: Path,
+ crashed: bool,
) -> None:
flush_entered = asyncio.Event()
reap_entered = asyncio.Event()
@@ -647,6 +658,8 @@ async def test_cancelled_flush_reaps_sidecar_before_releasing_barrier(
assert writer.offer_barrier("raw-session-0") == "queued"
await flush_entered.wait()
+ if crashed:
+ writer.pause_intake(unavailable=True)
closing = asyncio.create_task(writer.close())
await reap_entered.wait()
@@ -658,11 +671,16 @@ async def test_cancelled_flush_reaps_sidecar_before_releasing_barrier(
assert writer._permits == MAX_WRITER_PERMITS
assert writer._pending == {}
assert recoveries == [False]
+ assert writer.failure_observations()[0].error_code == (
+ "memory_sidecar_unavailable" if crashed else "memory_processing_interrupted"
+ )
@pytest.mark.asyncio
[email protected]("crashed", [False, True])
async def test_close_during_attachment_projection_releases_reservation(
tmp_path: Path,
+ crashed: bool,
monkeypatch: pytest.MonkeyPatch,
) -> None:
projection_entered = asyncio.Event()
@@ -702,7 +720,13 @@ async def test_close_during_attachment_projection_releases_reservation(
) == "queued"
await projection_entered.wait()
+ if crashed:
+ writer.pause_intake(unavailable=True)
await asyncio.wait_for(writer.close(), timeout=1.0)
+ assert writer.dropped_count() == int(crashed)
+ if crashed:
+ assert writer.failure_observations()[0].state == "not_submitted"
+ assert writer.failure_observations()[0].attempts == 0
assert attachment_store.released == ["bundle-0"]
assert writer._permits == MAX_WRITER_PERMITS
@@ -1161,3 +1185,243 @@ def test_writer_bounds_are_fixed_and_not_user_tunable() -> None:
assert MAX_WRITER_PERMITS == MAX_DUPLICATE_ENTRIES == MAX_PENDING_SESSIONS == 256
assert MAX_PENDING_MESSAGE_IDS == MAX_UNFLUSHED_MESSAGES == 100
assert MAX_UNFLUSHED_AGE_SECONDS == 30 * 60
+
+
+async def test_unknown_write_and_unsubmitted_drops_remain_visible_after_recovery(tmp_path):
+ """MEMORY-WAKE-207: recovery cannot erase unknown work observations."""
+ provider = FakeMemoryProvider(ingest_failures=deque([
+ MemoryProviderFailure("memory_provider_timeout", ambiguous=True),
+ ]))
+ writer = _writer(tmp_path, provider, ambiguous_stop_reap=lambda _: True)
+ start = writer._ensure_worker
+ writer._ensure_worker = lambda: None
+ _reserve_and_offer(writer, 0)
+ _reserve_and_offer(writer, 1)
+ assert writer.offer_barrier("raw-session-1") == "queued"
+ writer._ensure_worker = start
+ start()
+ await writer.wait_idle_for_tests()
+ await writer.close()
+ recovered = FakeMemoryProvider()
+ writer.replace_provider(recovered)
+ writer.resume_intake()
+ _reserve_and_offer(writer, 2)
+ await writer.wait_idle_for_tests()
+ entries = writer.failure_observations()
+ assert [(e.kind, e.state, e.operation) for e in entries] == [
+ ("delivery_abandoned", "not_submitted", "add"),
+ ("result_unknown", "unknown", "add"),
+ ]
+ assert len(recovered.captures) == 1
+ assert "message-" not in repr(entries)
+ assert writer.dropped_count() == 1
+ assert writer._permits == MAX_WRITER_PERMITS
+ await writer.close()
+
+
+async def test_recovery_close_reports_only_unsubmitted_captures(tmp_path):
+ writer = _writer(tmp_path, FakeMemoryProvider())
+ writer._ensure_worker = lambda: None
+ _reserve_and_offer(writer, 1)
+ assert writer.offer_barrier("raw-session-1") == "queued"
+ writer._unavailable = True
+ await writer.close()
+ assert [(e.kind, e.state) for e in writer.failure_observations()] == [
+ ("delivery_abandoned", "not_submitted"),
+ ]
+ assert writer.dropped_count() == 1
+ assert writer._permits == MAX_WRITER_PERMITS
+ writer.reset_duplicate_generation()
+ assert writer.failure_observations() == ()
+
+
+async def test_failure_evidence_is_bounded_and_server_errors_do_not_claim_no_write(tmp_path):
+ writer = _writer(tmp_path, FakeMemoryProvider(add_results=deque([
+ AddRejected("synthetic", "INTERNAL_ERROR", server_fault=True),
+ ])))
+ _reserve_and_offer(writer, 0)
+ await writer.wait_idle_for_tests()
+ entry = writer.failure_observations()[0]
+ assert (entry.kind, entry.state, entry.request_id) == ("result_unknown", "unknown", "synthetic")
+ for _ in range(MAX_WRITER_PERMITS):
+ writer._record_unsubmitted_drop()
+ assert writer.failure_observations()[0].affected_count == MAX_WRITER_PERMITS
+ assert writer.failure_observations()[1] == entry
+ for _ in range(60):
+ writer._record_failure("result_unknown", "memory_provider_timeout", state="unknown", operation="add")
+ assert len(writer.failure_observations()) == 50
+ await writer.close()
+
+
[email protected]("operation", ["add", "flush"])
[email protected]("attempts", [1, MAX_ATTEMPTS])
[email protected]("unknown", [False, True])
+async def test_submitted_anomalies_report_actual_provider_attempts(tmp_path, operation, attempts, unknown):
+ calls = 0
+
+ async def fail(*_args):
+ nonlocal calls
+ calls += 1
+ raise MemoryProviderFailure(
+ "memory_provider_timeout", retryable=calls < attempts,
+ ambiguous=unknown and calls == attempts,
+ )
+
+ provider = FakeMemoryProvider()
+ setattr(provider, operation, fail)
+ writer = _writer(tmp_path, provider, ambiguous_stop_reap=lambda _: True)
+ if operation == "add":
+ _reserve_and_offer(writer, 0)
+ await writer.wait_idle_for_tests()
+ else:
+ ref = _ref()
+ writer._pending[ref.serialize()] = _PendingSession(ref, "raw-session-0", deque(["digest"]), 0, 0)
+ await writer._flush_barrier(_BarrierItem(raw_session_id="raw-session-0"))
+ assert calls == attempts
+ entry = writer.failure_observations()[0]
+ assert entry.attempts == calls
+ assert entry.state == ("unknown" if unknown else "failed")
+ assert entry.error_code == "memory_provider_timeout"
+ await writer.close()
+
+
+async def test_explicit_flush_failure_does_not_skip_other_sessions_in_barrier(tmp_path):
+ refs = [_ref(0), _ref(1)]
+ calls = []
+
+ async def flush(ref):
+ calls.append(ref)
+ if ref == refs[0]:
+ raise MemoryProviderFailure("memory_capability_unavailable", retryable=False)
+ return FlushSucceeded("synthetic", "no_extraction")
+
+ provider = FakeMemoryProvider()
+ provider.flush = flush
+ writer = _writer(tmp_path, provider)
+ for ref in refs:
+ writer._pending[ref.serialize()] = _PendingSession(ref, "shared-raw-session", deque(["digest"]), 0, 0)
+ await writer._flush_barrier(_BarrierItem(raw_session_id="shared-raw-session"))
+ assert calls == refs
+ assert not writer._pending
+ assert len(writer.failure_observations()) == 1
+ assert writer.failure_observations()[0].state == "failed"
+ await writer.close()
+
+
+async def test_separate_recoveries_do_not_coalesce_drop_observations(tmp_path):
+ writer = _writer(tmp_path, FakeMemoryProvider())
+ writer._ensure_worker = lambda: None
+ for index in range(2):
+ writer.replace_provider(FakeMemoryProvider())
+ writer.resume_intake()
+ _reserve_and_offer(writer, index)
+ writer.pause_intake(unavailable=True)
+ await writer.close()
+ entries = writer.failure_observations()
+ assert len(entries) == 2
+ assert entries[0].id != entries[1].id
+ assert [entry.affected_count for entry in entries] == [1, 1]
+
+
[email protected]("operation", ["add", "flush"])
[email protected]("code", ["UNSUPPORTED_FORMAT", "secret-canary\nforged-log-line", None])
+async def test_rejection_observation_preserves_provider_code(tmp_path, operation, code, caplog):
+ from avibe_memory.observations import FlushRejected
+ provider = FakeMemoryProvider(
+ add_results=deque([AddRejected("synthetic", code, False)]),
+ flush_results=deque([FlushRejected("synthetic", code, False)]),
+ )
+ writer = _writer(tmp_path, provider)
+ if operation == "add":
+ _reserve_and_offer(writer, 0)
+ await writer.wait_idle_for_tests()
+ assert writer._store.get_meta().last_error == "memory_processing_failed"
+ else:
+ ref = _ref()
+ writer._pending[ref.serialize()] = _PendingSession(ref, "raw-session-0", deque(["digest"]), 0, 0)
+ await writer._flush_barrier(_BarrierItem(raw_session_id="raw-session-0"))
+ assert writer.failure_observations()[0].error_code == (code or "memory_processing_failed")
+ if code:
+ assert code not in caplog.text
+ await writer.close()
+
+
[email protected]("outcome", ["retryable", "exception", "success"])
+async def test_flush_crash_fences_all_subsequent_calls(tmp_path, outcome):
+ calls = []
+
+ async def flush(ref):
+ calls.append(ref)
+ writer.pause_intake(unavailable=True)
+ if outcome == "exception":
+ raise MemoryProviderFailure("memory_sidecar_unavailable", retryable=True)
+ return FlushRetryable() if outcome == "retryable" else FlushSucceeded("receipt", "extracted")
+
+ provider = FakeMemoryProvider()
+ provider.flush = flush
+ writer = _writer(tmp_path, provider)
+ for ref in [_ref(0), _ref(1)]:
+ writer._pending[ref.serialize()] = _PendingSession(ref, "shared", deque(["digest"]), 0, 0)
+ await writer._flush_barrier(_BarrierItem(raw_session_id="shared"))
+ assert calls == [_ref(0)]
+ entries = writer.failure_observations()
+ if outcome == "success":
+ assert not entries
+ else:
+ assert len(entries) == 1
+ assert (entries[0].state, entries[0].attempts) == ("failed", 1)
+ await writer.close()
+
+
[email protected]("reason,error", [
+ ("timeout", "memory_provider_timeout"),
+ ("transport", "memory_sidecar_unavailable"),
+ ("invalid_response", "memory_provider_response_invalid"),
+])
+async def test_flush_unknown_preserves_cause_without_retry(tmp_path, reason, error):
+ from avibe_memory.observations import FlushUnknown
+ provider = FakeMemoryProvider(flush_results=deque([FlushUnknown(reason)]))
+ writer = _writer(tmp_path, provider, ambiguous_stop_reap=lambda _: True)
+ ref = _ref()
+ writer._pending[ref.serialize()] = _PendingSession(ref, "shared", deque(["digest"]), 0, 0)
+ await writer._flush_barrier(_BarrierItem(raw_session_id="shared"))
+ entry = writer.failure_observations()[0]
+ assert (entry.error_code, entry.state, entry.attempts) == (error, "unknown", 1)
+ assert not writer._pending
+ await writer.close()
+
+
[email protected]("system_failure", [False, True])
+async def test_crash_during_definite_add_failure_is_observed_once(tmp_path, system_failure):
+ from avibe_memory.everos import MemoryProviderSystemFailure
+ calls = 0
+
+ async def add(_capture):
+ nonlocal calls
+ calls += 1
+ writer.pause_intake(unavailable=True)
+ if system_failure:
+ raise MemoryProviderSystemFailure("memory_sidecar_unavailable")
+ raise MemoryProviderFailure("memory_sidecar_unavailable", retryable=True)
+
+ provider = FakeMemoryProvider()
+ provider.add = add
+ writer = _writer(tmp_path, provider)
+ _reserve_and_offer(writer, 0)
+ await writer.wait_idle_for_tests()
+ assert calls == 1
+ entries = writer.failure_observations()
+ assert len(entries) == 1
+ assert (entries[0].state, entries[0].attempts, entries[0].affected_count) == ("failed", 1, 1)
+ assert entries[0].generation is None
+ await writer.close()
diff --git a/ui/src/components/settings/SettingsMemoryPage.test.tsx b/ui/src/components/settings/SettingsMemoryPage.test.tsx
index 84fd83590..2a8127f2c 100644
--- a/ui/src/components/settings/SettingsMemoryPage.test.tsx
+++ b/ui/src/components/settings/SettingsMemoryPage.test.tsx
@@ -328,7 +328,7 @@ describe('SettingsMemoryPage', () => {
expect(screen.queryByRole('button', { name: 'run-repair' })).toBeNull();
});
- it('treats intentionally unretained failure history as an informational notice', async () => {
+ it.each(['unavailable', 'partial'] as const)('shows the %s failure-history limitation as a notice', async (sourceStatus) => {
api.getMemoryProcessingRecord.mockResolvedValue({
status: 'ok',
runtime: { source: status('running').source, health: null },
@@ -339,7 +339,7 @@ describe('SettingsMemoryPage', () => {
},
anomalies: {
source: {
- status: 'unavailable',
+ status: sourceStatus,
observed_at: null,
reason: 'memory_failure_history_unavailable',
},
diff --git a/ui/src/components/settings/SettingsMemoryPage.tsx b/ui/src/components/settings/SettingsMemoryPage.tsx
index 3c8a3ed92..afc5486ba 100644
--- a/ui/src/components/settings/SettingsMemoryPage.tsx
+++ b/ui/src/components/settings/SettingsMemoryPage.tsx
@@ -77,7 +77,8 @@ export const SettingsMemoryPage: React.FC = () => {
const settings = settingsRead.data;
const runtimeState = statusRead.data?.state;
const processingRecord = processingRecordRead.data;
- const anomalySourceReason = processingRecord?.anomalies.source.status === 'unavailable'
+ const anomalySourceReason = (processingRecord?.anomalies.source.status === 'unavailable'
+ || processingRecord?.anomalies.source.status === 'partial')
? processingRecord.anomalies.source.reason
: null;
const anomalySourceMessage = anomalySourceReason
diff --git a/ui/src/components/settings/memory/MemoryStatusPanel.test.tsx b/ui/src/components/settings/memory/MemoryStatusPanel.test.tsx
index f678dd46e..b502f94bc 100644
--- a/ui/src/components/settings/memory/MemoryStatusPanel.test.tsx
+++ b/ui/src/components/settings/memory/MemoryStatusPanel.test.tsx
@@ -1,6 +1,6 @@
/* @vitest-environment jsdom */
-import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { cleanup, fireEvent, render, screen, within } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { MemoryStatus } from '../../../context/ApiContext';
@@ -52,6 +52,30 @@ describe('MemoryStatusPanel', () => {
},
);
+ it.each([256, undefined])('shows affected counts and submission state with healthy runtime (%s)', (count) => {
+ render(<MemoryStatusPanel {...props(status('running'))}
+ failuresNotice="memory.processingRecord.reason.memory_failure_history_unavailable"
+ failures={[{
+ id: 'drop', kind: 'delivery_abandoned', state: 'not_submitted', operation: 'add',
+ occurred_at: '2026-09-17T00:00:00Z', error_code: null, attempts: 0,
+ generation: null, request_id: null, affected_count: count,
+ }, {
+ id: 'unknown', kind: 'result_unknown', state: 'unknown', operation: 'flush',
+ occurred_at: '2026-09-17T00:00:00Z', error_code: null, attempts: 3,
+ generation: 0, request_id: null,
+ }]} />);
+ const dropped = within(screen.getByTestId('memory-anomaly-delivery_abandoned'));
+ expect(dropped.getByText('memory.processingRecord.anomalyState.notSubmitted')).toBeTruthy();
+ expect(dropped.getByText('memory.processingRecord.field.affectedCount').parentElement?.textContent)
+ .toContain(String(count ?? 1));
+ expect(dropped.queryByText('memory.processingRecord.field.generation')).toBeNull();
+ const unknown = within(screen.getByTestId('memory-anomaly-result_unknown'));
+ expect(unknown.getByText('memory.processingRecord.field.generation')).toBeTruthy();
+ expect(unknown.getByText('memory.processingRecord.anomalyState.unknown')).toBeTruthy();
+ expect(unknown.getByText('memory.processingRecord.field.attempts').parentElement?.textContent).toContain('3');
+ expect(screen.getByText('memory.processingRecord.reason.memory_failure_history_unavailable')).toBeTruthy();
+ });
+
it('offers destructive Repair only when the caller marks it supported', () => {
const onRepair = vi.fn();
render(
diff --git a/ui/src/components/settings/memory/MemoryStatusPanel.tsx b/ui/src/components/settings/memory/MemoryStatusPanel.tsx
index a98328b4d..e3cfe8f82 100644
--- a/ui/src/components/settings/memory/MemoryStatusPanel.tsx
+++ b/ui/src/components/settings/memory/MemoryStatusPanel.tsx
@@ -130,7 +130,10 @@ const FailureRow: React.FC<{ entry: MemoryFailureLogEntry }> = ({ entry }) => {
value={entry.error_code ? memoryErrorMessage(t, entry.error_code) : '-'}
/>
<Field label={t('memory.processingRecord.field.attempts')} value={entry.attempts} />
- <Field label={t('memory.processingRecord.field.generation')} value={entry.generation} />
+ <Field label={t('memory.processingRecord.field.affectedCount')} value={entry.affected_count ?? 1} />
+ {entry.generation != null ? (
+ <Field label={t('memory.processingRecord.field.generation')} value={entry.generation} />
+ ) : null}
<div className="sm:col-span-2">
<Field label={t('memory.processingRecord.field.requestId')} value={entry.request_id ?? '-'} />
</div>
diff --git a/ui/src/components/settings/memory/memoryStatusPresentation.ts b/ui/src/components/settings/memory/memoryStatusPresentation.ts
index f401df8af..6905ac6dc 100644
--- a/ui/src/components/settings/memory/memoryStatusPresentation.ts
+++ b/ui/src/components/settings/memory/memoryStatusPresentation.ts
@@ -25,6 +25,9 @@ const ANOMALY_LABEL_KEYS = {
result_unknown: 'memory.status.failureLog.kind.result_unknown',
},
state: {
+ unknown: 'memory.processingRecord.anomalyState.unknown',
+ failed: 'memory.processingRecord.anomalyState.failed',
+ not_submitted: 'memory.processingRecord.anomalyState.notSubmitted',
dead: 'memory.processingRecord.anomalyState.dead',
degraded: 'memory.processingRecord.anomalyState.degraded',
manual_required: 'memory.processingRecord.anomalyState.manualRequired',
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 3be57e07c..0fa37795f 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -2015,6 +2015,7 @@ export type MemoryStatus = {
export type MemoryStatusResult = MemoryStatus | MemoryFailure | { error: string };
export type MemoryFailureLogEntry = {
+ affected_count?: number;
id: string;
kind: string;
state: string;
@@ -2022,12 +2023,13 @@ export type MemoryFailureLogEntry = {
occurred_at: string;
error_code: string | null;
attempts: number;
- generation: number;
+ generation: number | null;
request_id: string | null;
};
export type MemoryFailureLog = {
status: 'ok';
+ source?: MemoryProcessingSourceStatus;
items: MemoryFailureLogEntry[];
};
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 9645223d7..60f871536 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2170,6 +2170,7 @@
"memory_runtime_install_requires_disabled_memory": "Turn Memory off in Settings \u2192 Memory before repairing a running Memory runtime.",
"memory_reconcile_failed": "Avibe couldn't apply the Memory settings. Check the runtime logs for the failing step.",
"memory_sidecar_unavailable": "The Memory sidecar isn't reachable right now.",
+ "memory_processing_interrupted": "Memory processing was interrupted before completion could be confirmed.",
"memory_provider_timeout": "The Memory request timed out.",
"memory_provider_response_invalid": "Memory returned an invalid response.",
"memory_capability_unavailable": "Memory models are temporarily unavailable. Try again when the configured model service is available.",
@@ -4774,7 +4775,7 @@
},
"reason": {
"busy": "Source data is busy",
- "memory_failure_history_unavailable": "Capture failure history is not retained",
+ "memory_failure_history_unavailable": "Only recent failures from this service process are available; complete failure history is not retained.",
"native_memcells_unavailable": "Native messages cannot be read",
"native_runs_unavailable": "Native runs cannot be read",
"native_semantic_unavailable": "Linked memory files cannot be read",
@@ -4847,7 +4848,10 @@
"dead": "Dead",
"degraded": "Degraded",
"manualRequired": "Manual review required",
- "rejected": "Rejected"
+ "rejected": "Rejected",
+ "unknown": "Result unknown",
+ "failed": "Failed",
+ "notSubmitted": "Not submitted"
},
"anomalyOperation": {
"add": "Add",
@@ -4861,6 +4865,7 @@
"occurredAt": "Occurred at",
"errorCode": "Error code",
"attempts": "Attempts",
+ "affectedCount": "Affected items",
"generation": "Data version",
"requestId": "Request ID"
},
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 1fc58c7dd..bfe13ad46 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2170,6 +2170,7 @@
"memory_runtime_install_requires_disabled_memory": "记忆运行时正在使用中。请先在「设置 → 记忆」中关闭记忆,再修复。",
"memory_reconcile_failed": "Avibe 无法应用记忆设置。请查看运行时日志了解失败步骤。",
"memory_sidecar_unavailable": "记忆 sidecar 当前不可访问。",
+ "memory_processing_interrupted": "记忆处理被中断,无法确认是否已完成。",
"memory_provider_timeout": "记忆请求超时。",
"memory_provider_response_invalid": "记忆返回了无效的响应。",
"memory_capability_unavailable": "记忆模型暂时不可用。请在已配置的模型服务恢复后重试。",
@@ -4774,7 +4775,7 @@
},
"reason": {
"busy": "来源数据正忙",
- "memory_failure_history_unavailable": "捕获失败历史不会持久保留",
+ "memory_failure_history_unavailable": "仅提供本次服务进程保留的近期异常,不包含完整失败历史。",
"native_memcells_unavailable": "无法读取原生消息",
"native_runs_unavailable": "无法读取原生运行记录",
"native_semantic_unavailable": "无法读取已关联的记忆文件",
@@ -4847,7 +4848,10 @@
"dead": "已放弃",
"degraded": "已降级",
"manualRequired": "需要人工检查",
- "rejected": "已拒绝"
+ "rejected": "已拒绝",
+ "unknown": "结果未知",
+ "failed": "失败",
+ "notSubmitted": "尚未提交"
},
"anomalyOperation": {
"add": "添加",
@@ -4861,6 +4865,7 @@
"occurredAt": "发生时间",
"errorCode": "错误代码",
"attempts": "尝试次数",
+ "affectedCount": "影响条数",
"generation": "数据版本",
"requestId": "请求 ID"
},