Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -484,12 +484,12 @@ joins it only behind its session's backlog)
### `[memorize.input_log]`

An append-only JSONL record of accepted `/add` requests, independent of
extraction (issue #537). The first PR ships it **disabled**; deletion and
purge integration, plus the default-on switch, follow separately.
extraction (issue #537). A session deletion removes that session's lines,
and a purge removes the covered scopes' `.input_log/` directories.

| Field | Type | Default | Description |
|---|---|---|---|
| `enabled` | bool | `false` | When on, one line per accepted `/add` goes to `<root>/<app>/<project>/.input_log/YYYY-MM-DD.jsonl`. `/flush` is not logged. |
| `enabled` | bool | `true` | One line per accepted `/add` goes to `<root>/<app>/<project>/.input_log/YYYY-MM-DD.jsonl`. `/flush` is not logged. Off stops new lines; existing lines are still deleted by session deletion/purge. |
| `retention_days` | int | `30` | Daily files older than this are removed when the scope next writes. |
| `max_inline_bytes` | int | `1048576` | A line larger than this keeps text verbatim but replaces each `base64` attachment with its byte length and SHA-256. |

Expand Down
6 changes: 3 additions & 3 deletions src/everos/config/default.toml
Original file line number Diff line number Diff line change
Expand Up @@ -283,9 +283,9 @@ max_replays = 3
row_retention_hours = 168.0

[memorize.input_log]
# First PR ships the log disabled: enabling it also requires the deletion and
# purge path that removes a scope's lines (issue #537, second PR).
enabled = false
# One JSONL line per accepted /add, independent of extraction. Disable to
# stop new lines; session deletion and purge remove existing ones.
enabled = true
retention_days = 30
# A line larger than this keeps text verbatim but replaces each base64
# attachment with its length and SHA-256.
Expand Down
7 changes: 3 additions & 4 deletions src/everos/config/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -778,12 +778,11 @@ class AsyncQueueSettings(BaseModel):
class InputLogSettings(BaseModel):
"""``/add`` input log (``[memorize.input_log]``).

Disabled in the first PR that introduces it: enabling the log also
requires the deletion/purge path that removes a scope's lines, which
follows in the second PR (issue #537).
Enabled by default now that session deletion and purge remove the
corresponding lines (issue #537).
"""

enabled: bool = False
enabled: bool = True
retention_days: int = Field(default=30, ge=1)
max_inline_bytes: int = Field(default=1024 * 1024, ge=1)

Expand Down
18 changes: 10 additions & 8 deletions src/everos/service/bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,12 @@ def build_application(
)
eraser = FencedIndexEraser(index.repositories, fence, sqlite.md_change_state)
marks = MARKS.for_root(root.root)
input_log = InputLogWriter(
root=root.root,
settings=settings.memorize.input_log,
app_dir=app_dir_name,
project_dir=project_dir_name,
)
memory = _build_memory_service(
settings,
providers,
Expand All @@ -410,7 +416,7 @@ def build_application(
OmeEventBus(engine),
eraser,
marks,
root,
input_log,
)
engine.set_run_gate(PurgeRunGate(marks))
purge = PurgeService(
Expand All @@ -424,6 +430,7 @@ def build_application(
index_store=settings.index.backend,
engine=engine,
fence=fence,
input_log=input_log,
)
vector_tables = index.repositories.with_vectors()
return Application(
Expand Down Expand Up @@ -626,19 +633,14 @@ def _build_memory_service(
bus: EventBus,
index_eraser: IndexEraser,
purge_marks: PurgeMarks,
root: MemoryRoot,
input_log: InputLogWriter,
) -> MemoryService:
stores, indexes = deps.stores, deps.indexes
recaller_deps = RecallerDeps(tokenizer=tokenizer)
return MemoryService(
index_eraser=index_eraser,
purge_marks=purge_marks,
input_log=InputLogWriter(
root=root.root,
settings=settings.memorize.input_log,
app_dir=app_dir_name,
project_dir=project_dir_name,
),
input_log=input_log,
raw_file_builder=partial(build_raw_file, settings_source=load_settings),
settings=settings,
boundary=BoundaryDetection(
Expand Down
28 changes: 24 additions & 4 deletions src/everos/service/memory/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,11 @@
from collections.abc import Callable, Sequence
from typing import TYPE_CHECKING, Any

from everos.core.errors import PathTraversalError, SessionBusyError
from everos.core.errors import (
DeletionIncompleteError,
PathTraversalError,
SessionBusyError,
)
from everos.core.observability.logging import get_logger
from everos.memory import DeviceLine, project_device_batch

Expand Down Expand Up @@ -181,14 +185,30 @@ async def delete(
Runs to completion even if the caller goes away: a deletion cut in
half would leave the scope half deleted.
"""
task = self._extractions.supervise(
self._deleter.delete(

async def _delete_and_cleanup() -> Any:
result = await self._deleter.delete(
app_id=app_id,
project_id=project_id,
user_id=user_id,
agent_id=agent_id,
session_id=session_id,
),
)
if session_id is not None and self._input_log is not None:
try:
await self._input_log.delete_session(
app_id=app_id, project_id=project_id, session_id=session_id
)
except Exception as exc:
# The memories are gone but the privacy log is not; report
# the deletion as incomplete so a retry finishes it.
raise DeletionIncompleteError(
"input log cleanup failed; resend the deletion"
) from exc
return result

task = self._extractions.supervise(
_delete_and_cleanup(),
session_id=session_id,
memcell_ids=[],
label="memory_delete",
Expand Down
55 changes: 55 additions & 0 deletions src/everos/service/memory/_input_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import datetime as dt
import hashlib
import json
import shutil
from collections.abc import Callable
from pathlib import Path
from typing import Any
Expand Down Expand Up @@ -68,6 +69,60 @@ async def _write(self, payload: dict[str, Any], *, request_id: str) -> None:
async with self._lock:
await asyncio.to_thread(self._append_sync, directory, now, line)

async def delete_session(
self, *, app_id: str, project_id: str, session_id: str
) -> None:
"""Drop one session's lines from every daily file in the scope."""
directory = (
self._root
/ self._app_dir(app_id)
/ self._project_dir(project_id)
/ _LOG_DIR
)
async with self._lock:
await asyncio.to_thread(self._delete_session_sync, directory, session_id)

def _delete_session_sync(self, directory: Path, session_id: str) -> None:
if not directory.is_dir():
return
for path in directory.glob("*.jsonl"):
original = path.read_text(encoding="utf-8").splitlines()
kept: list[str] = []
for line in original:
try:
record = json.loads(line)
except json.JSONDecodeError:
kept.append(line)
continue
if record.get("session_id") != session_id:
kept.append(line)
if not kept:
path.unlink(missing_ok=True)
elif len(kept) != len(original):
temp = path.with_suffix(".tmp")
temp.write_text("\n".join(kept) + "\n", encoding="utf-8")
temp.replace(path)

async def purge_scope(self, scope: Any) -> None:
"""Remove every ``.input_log`` directory the purge scope covers."""
async with self._lock:
await asyncio.to_thread(self._purge_scope_sync, scope)

def _purge_scope_sync(self, scope: Any) -> None:
if scope.kind == "space":
dirs = list(self._root.glob("*/*/.input_log"))
elif scope.kind == "app":
dirs = list((self._root / str(scope.app_dir)).glob("*/.input_log"))
else:
dirs = [self._root / str(scope.app_dir) / str(scope.project_dir) / _LOG_DIR]
for directory in dirs:
try:
shutil.rmtree(directory)
except FileNotFoundError:
# Already gone is success; any other removal failure must
# escape so the purge runner retries the step.
continue

def _directory(self, payload: dict[str, Any]) -> Path:
app_id = str(payload.get("app_id", "default"))
project_id = str(payload.get("project_id", "default"))
Expand Down
4 changes: 4 additions & 0 deletions src/everos/service/purge/_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ def __init__(
scope_of: Callable[[str, str | None, str | None], PurgeScope],
backoff: Callable[[int], float] = _backoff,
poll_seconds: float = 5.0,
input_log: Any = None,
) -> None:
self._settings = settings
self._marks = marks
Expand All @@ -172,6 +173,7 @@ def __init__(
self._engine = engine
self._fence = fence
self._scope_of = scope_of
self._input_log = input_log
self._backoff = backoff
self._poll = poll_seconds
self._task: asyncio.Task[None] | None = None
Expand Down Expand Up @@ -397,6 +399,8 @@ async def _step_markdown(self, run: _Run) -> int:
# scope is moved there again (a rename onto it would fail).
await self._markdown.empty(run.scope, run.job_id)
moved = await self._markdown.move_out(run.scope, run.job_id)
if self._input_log is not None:
await self._input_log.purge_scope(run.scope)
reading = self._fence.in_flight() # projections that may have read S's files
await self._markdown.restore_counters(run.scope, run.job_id)
await self._markdown.empty(run.scope, run.job_id)
Expand Down
4 changes: 3 additions & 1 deletion src/everos/service/purge/_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from pathlib import Path
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Any

from everos.core.errors import (
NotFoundError,
Expand Down Expand Up @@ -77,6 +77,7 @@ class PurgeService:
index_store: str
engine: OfflineEngine
fence: DeleteFence
input_log: Any = None
_nonces: dict[str, _Nonce] = field(default_factory=dict, init=False)
_reserved: set[str] = field(default_factory=set, init=False)
_recording: asyncio.Event | None = field(default=None, init=False)
Expand Down Expand Up @@ -314,6 +315,7 @@ def start(self) -> None:
engine=self.engine,
fence=self.fence,
scope_of=self.scope_of,
input_log=self.input_log,
)
self._runner.start()

Expand Down
54 changes: 54 additions & 0 deletions tests/unit/test_service/test_delete_cancellation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
"""A cancelled /memory/delete still finishes its input-log cleanup."""

from __future__ import annotations

import asyncio

import pytest

from everos.service.memory._delete import DeleteResult
from tests.fakes import make_memory_service


class _SlowDeleter:
def __init__(self) -> None:
self.started = asyncio.Event()
self.release = asyncio.Event()

async def delete(self, **_: object) -> DeleteResult:
self.started.set()
await self.release.wait()
return DeleteResult(filters=["session_id"], count=0)


class _RecordingInputLog:
def __init__(self) -> None:
self.cleaned = asyncio.Event()

async def delete_session(self, **_: object) -> None:
self.cleaned.set()


async def test_cancelled_delete_still_cleans_the_session_log() -> None:
service = make_memory_service()
deleter = _SlowDeleter()
input_log = _RecordingInputLog()
service._deleter = deleter # type: ignore[attr-defined]
service._input_log = input_log # type: ignore[attr-defined]

task = asyncio.create_task(
service.delete(
app_id="a",
project_id="p",
user_id=None,
agent_id=None,
session_id="s1",
)
)
await deleter.started.wait()
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task

deleter.release.set()
await asyncio.wait_for(input_log.cleaned.wait(), timeout=1.0)
Loading