From 6229d4be0b49936ca69fae83ab34a4277a73cae1 Mon Sep 17 00:00:00 2001 From: Dani Date: Fri, 20 Nov 2026 14:41:53 -0500 Subject: [PATCH 1/2] feat(facade): rebuild, app/project guards on update and delete_by_ids (1.3.0) - update() / delete_by_ids() take optional app_id / project_id guards (engine !277): a memory outside that app / project is refused like a missing one. Never filled from the client's defaults, so existing callers keep the id-only behaviour. - rebuild(), rebuild_status(), rebuild_wait() for the new /memory/rebuild (engine !287): deletes are now permanent and leave the profile, session summaries and skills stale until the caller rebuilds. rebuild_wait() explains a missing job_id (nothing_to_do / dry_run) instead of failing in model validation. - delete() / delete_by_ids() docs: permanent, rebuild_required / targets. context(): mention the optional answer mode. Needs the 1.3.0-rc4 generated models (RebuildInput, RebuildStatusInput). Co-Authored-By: Claude Opus 5.5 --- README.md | 7 ++- everos_cloud/client.py | 138 ++++++++++++++++++++++++++++++++++++++--- tests/test_client.py | 106 +++++++++++++++++++++++++++++++ 3 files changed, 239 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 919706b..7c45d2a 100644 --- a/README.md +++ b/README.md @@ -43,9 +43,10 @@ Add a conversation; EverOS turns it into structured, retrievable memory you can - **Knowledge bases** — ingest documents into a searchable topic library alongside conversational memory; ingest is async and reports progress through the task API. - **Multimodal** — attach images, audio, and documents to any message. -- **You stay in control** — correct or delete single memories (scoped to one user when an - agent acts on their behalf), clear a user or session, or purge a whole memory space in - two confirmed steps. +- **You stay in control** — correct or delete single memories (guarded to one user, app or + project when an agent acts on their behalf), clear a user or session, or purge a whole + memory space in two confirmed steps. Deletes are permanent; refresh the profile they + leave stale with `rebuild` when you choose. - **Built for production** — fully managed (no vector DB or extraction pipeline to run), with low-latency retrieval and high-concurrency throughput. The engineering guarantees you don't get from self-hosting. diff --git a/everos_cloud/client.py b/everos_cloud/client.py index 7aee1b2..f4cb45e 100644 --- a/everos_cloud/client.py +++ b/everos_cloud/client.py @@ -61,6 +61,8 @@ PurgeConfirmInput, PurgeRequestData, PurgeRequestInput, + RebuildInput, + RebuildStatusInput, Reason, SearchBody, SearchInput, @@ -80,6 +82,7 @@ DEFAULT_TASK_INTERVAL = 2.0 # seconds before the first task re-poll DEFAULT_TASK_MAX_INTERVAL = 15.0 # ceiling for the backoff between task polls DEFAULT_PURGE_TIMEOUT = 1800.0 # seconds; a purge of a large memory space takes minutes +DEFAULT_REBUILD_TIMEOUT = 1800.0 # seconds; a profile rebuild re-reads every remaining episode # Statuses worth retrying DURING a poll rather than aborting the whole wait. A long # ingest polled at a fixed interval is itself a source of 429s, and a wait that dies @@ -107,6 +110,7 @@ "get_task_status": "task_get", "list_tasks": "task_list", "request_purge": "purge_request", "confirm_purge": "purge_confirm", "get_purge_job": "purge_get", + "rebuild_memory": "rebuild", "get_rebuild_status": "rebuild_status", } _API_ATTRS = ("memory", "storage", "knowledge", "tasks") @@ -116,7 +120,8 @@ # and the contract documents `finished_at` as "absent while the task is not in a # terminal state" — so the timestamp, not the enum, is the load-bearing signal. _TERMINAL_TASK_STATUS = frozenset({"success", "failed"}) -# Same reasoning for purge jobs, whose terminal statuses are spelled differently. +# Same reasoning for purge and rebuild jobs, whose terminal statuses are spelled +# differently. _TERMINAL_PURGE_STATUS = frozenset({"succeeded", "failed"}) _OP_CLASSES = {"add": AddOperation, "update": UpdateOperation, "delete": DeleteOperation} @@ -172,6 +177,13 @@ def _purge_finished(job: Any) -> bool: return getattr(job, "status", None) in _TERMINAL_PURGE_STATUS +def _rebuild_finished(job: Any) -> bool: + """Has this rebuild job ended? Same rule as :func:`_task_finished`.""" + if getattr(job, "finished_at", None) is not None: + return True + return getattr(job, "status", None) in _TERMINAL_PURGE_STATUS + + def _scope_text(scope: tuple) -> str: """``("project", "a1", "p1")`` -> ``"project a1/p1"``, for messages.""" kind, app_id, project_id = scope @@ -450,7 +462,8 @@ def context( """Context Retrieval: an LLM searches in rounds until the evidence suffices. Returns ``SearchData``, the same shape as :meth:`search` — memories, not an - answer. ``episodes[].cited`` marks the ones the model's answer rested on, and + answer (a deployment can enable an answer mode that also fills ``answer``; + EverOS Cloud does not). ``episodes[].cited`` marks the ones the model's answer rested on, and ``score`` is a rank-fusion score, not comparable with search scores. User owners only. The server caps the loop at 45 s and returns what it found so far, which fits the client's default 60 s timeout; a client built with a shorter timeout @@ -533,7 +546,14 @@ def delete( app_id: str | None = None, project_id: str | None = None, ) -> Any: - """Scoped soft-delete of memories. Returns ``DeleteData``.""" + """Delete memories by owner and/or session. **Permanent.** Returns ``DeleteData``. + + Deleted memories are removed for good. A session-only delete also removes that + session's source messages. Memories derived from what was deleted are cleaned up; + the ones only an LLM can regenerate (the profile, session summaries, agent + skills) are kept and marked stale instead: ``rebuild_required`` and ``targets`` + on the result say so. Nothing is regenerated until you call :meth:`rebuild`. + """ payload = DeleteInput( **_clean( user_id=user_id, @@ -545,8 +565,10 @@ def delete( return self._call(self.memory.delete_memory, payload).data # -- single-memory edits ------------------------------------------------- - # These target memories by id, so like the tag calls they carry NO app_id / - # project_id and `_scope` does not apply. Facade names are the last segment of + # These target memories by id, so `_scope` does not apply: the client's app_id / + # project_id defaults are never sent. Here app_id / project_id are optional + # GUARDS, not a scope: passed explicitly, they refuse a memory outside that app / + # project like a missing one; left out, the id alone selects, in any app. Facade names are the last segment of # the route: /memory/update -> update, /memory/delete_by_ids -> delete_by_ids, # /memory/feedback -> feedback. def update( @@ -558,6 +580,8 @@ def update( subject: str | None = None, reason: ReasonLike | None = None, user_id: str | None = None, + app_id: str | None = None, + project_id: str | None = None, memory_type: str = "episode", ) -> Any: """Patch one episode's ``episode`` text, ``summary`` and/or ``subject``. @@ -569,7 +593,10 @@ def update( ``user_id`` limits the edit to that user's memory: a memory owned by anyone else is a 404, exactly like a missing one. In an agent tool, set it from your own session (the signed-in user), never from model output, so a wrong or invented - ``memory_id`` cannot reach another user's memory. + ``memory_id`` cannot reach another user's memory. ``app_id`` / ``project_id`` + do the same for an app or project: a memory outside it is a 404. They are NOT + filled from the client's defaults; pass them when a caller (an agent tool, a + per-app integration) must stay inside one app / project. Profile items are edited with :meth:`edit`, not here. """ @@ -583,6 +610,8 @@ def update( patch=EpisodePatch(**patch), reason=self._to_reason(reason), user_id=user_id, + app_id=app_id, + project_id=project_id, ) ) return self._call(self.memory.update_memory, payload).data @@ -593,16 +622,21 @@ def delete_by_ids( *, reason: ReasonLike | None = None, user_id: str | None = None, + app_id: str | None = None, + project_id: str | None = None, memory_type: str = "episode", ) -> Any: - """Soft-delete 1-50 memories by id. Returns ``DeleteByIdsData``. + """Delete 1-50 memories by id. **Permanent.** Returns ``DeleteByIdsData``. Ids that do not exist are skipped; one malformed id fails the whole batch (422). ``deleted`` on the result counts what this call removed, so a 0 means nothing was. ``user_id`` deletes only that user's memories: ids owned by anyone else are skipped like missing ones. As with :meth:`update`, set it from your own session, - never from model output. To clear a whole user / agent / session, use - :meth:`delete`. + never from model output; ``app_id`` / ``project_id`` (never taken from the + client's defaults) skip ids outside that app / project the same way. As with + :meth:`delete`, a stale profile or summary is reported in ``rebuild_required`` / + ``targets``, to refresh with :meth:`rebuild`. To clear a whole user / agent / + session, use :meth:`delete`. """ payload = DeleteByIdsInput( **_clean( @@ -610,6 +644,8 @@ def delete_by_ids( memory_ids=list(memory_ids), reason=self._to_reason(reason), user_id=user_id, + app_id=app_id, + project_id=project_id, ) ) return self._call(self.memory.delete_memories_by_ids, payload).data @@ -1011,6 +1047,90 @@ def purge_wait( raise err return job + # -- rebuild of stale derived memories --------------------------------------- + # A delete never spends LLM calls, so what only an LLM can regenerate (the profile, + # session summaries, agent skills) is marked stale instead. These calls regenerate + # it, when the caller decides to: the rebuild is free, the extraction it runs is + # metered like any extraction. + def rebuild( + self, + *, + user_id: str | None = None, + agent_id: str | None = None, + targets: Sequence[str] | None = None, + force: bool | None = None, + dry_run: bool | None = None, + app_id: str | None = None, + project_id: str | None = None, + ) -> Any: + """Regenerate what deletes marked stale, for one owner. Returns ``RebuildData``. + + Pass ``user_id`` (profile, session summaries) or ``agent_id`` (skills). + ``targets`` narrows it to some of ``"profile"`` / ``"session_summary"`` / + ``"skill"``; by default everything marked stale is rebuilt. ``force`` rebuilds + the profile / skills even when nothing is marked (an owner with no profile yet + has none to rebuild: the next extraction creates it); ``dry_run`` only reports + what would be rebuilt and spends nothing. Batch your deletes first, then call this + once. + + ``status`` is ``"queued"`` (follow ``job_id`` with :meth:`rebuild_wait`), + ``"already_running"`` (the owner's running job; one at a time), + ``"nothing_to_do"`` or ``"dry_run"`` (no job, ``job_id`` is ``None``). While a + profile rebuild runs, the profile holds only its manually edited items plus what + has been re-extracted so far. + """ + payload = RebuildInput( + **_clean( + user_id=user_id, + agent_id=agent_id, + targets=list(targets) if targets is not None else None, + force=force, + dry_run=dry_run, + **self._scope(app_id, project_id), + ) + ) + return self._call(self.memory.rebuild_memory, payload).data + + def rebuild_status(self, job_id: str) -> Any: + """Read a rebuild job. Returns ``RebuildStatusData`` (``status``, ``progress``).""" + return self._call(self.memory.get_rebuild_status, RebuildStatusInput(job_id=job_id)).data + + def rebuild_wait( + self, + job_id: str, + *, + timeout: float = DEFAULT_REBUILD_TIMEOUT, + interval: float = DEFAULT_TASK_INTERVAL, + max_interval: float = DEFAULT_TASK_MAX_INTERVAL, + raise_on_failure: bool = True, + ) -> Any: + """Poll a rebuild job until it ends and return the terminal ``RebuildStatusData``. + + Same polling as :meth:`task_wait`. Raises ``EverOSError`` if the job fails + (unless ``raise_on_failure=False``, which returns it) or is still running at + ``timeout``; the last job seen is on the error's ``.job``. Timing out only ends + the wait, not the rebuild: call ``rebuild_wait`` again to keep waiting. + """ + if not job_id: + raise ValueError( + "no rebuild job to wait for: rebuild() starts one only when its status is " + "'queued' or 'already_running' ('nothing_to_do' and 'dry_run' have no job_id)" + ) + job = self._poll( + lambda: self.rebuild_status(job_id), + _rebuild_finished, + what=f"rebuild {job_id}", + attr="job", + timeout=timeout, + interval=interval, + max_interval=max_interval, + ) + if raise_on_failure and getattr(job, "status", None) == "failed": + err = EverOSError(f"rebuild {job_id} failed: {getattr(job, 'error', None) or 'no reason given'}") + err.job = job + raise err + return job + # -- storage ------------------------------------------------------------- def presign(self, objects: Sequence[Any]) -> Any: """Presign objects for direct-to-S3 upload (advanced/batch, up to 50). diff --git a/tests/test_client.py b/tests/test_client.py index 3c6ad8e..ac123e1 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -19,6 +19,8 @@ PurgeConfirmInput, PurgeRequestInput, Reason, + RebuildInput, + RebuildStatusInput, SearchBody, SearchInput, TagBindInput, @@ -1076,3 +1078,107 @@ def test_a_write_during_a_purge_surfaces_its_code(): with pytest.raises(EverOSAPIError) as ei: c.flush("s1") assert ei.value.code == "purge_in_progress" + + +# ── app / project guards on update / delete_by_ids (1.3.0) ─────────────────── +def test_update_and_delete_by_ids_send_app_and_project_only_when_given(): + mem = MagicMock() + c = EverOS("sk-test", app_id="my-app", project_id="p1") + c.memory = mem + + c.update("m1", subject="t", app_id="a1", project_id="p9") + c.delete_by_ids(["m1"], user_id="u1", app_id="a1", project_id="p9") + up = mem.update_memory.call_args.args[0] + dl = mem.delete_memories_by_ids.call_args.args[0] + assert (up.app_id, up.project_id) == ("a1", "p9") + assert (dl.app_id, dl.project_id, dl.user_id) == ("a1", "p9", "u1") + + +def test_app_and_project_guards_never_come_from_the_client_scope(): + """A guard, not a scope: a client built for one app must not quietly stop deleting + ids from another app that callers pass today.""" + mem = MagicMock() + c = EverOS("sk-test", app_id="my-app", project_id="p1") + c.memory = mem + + c.update("m1", subject="t") + c.delete_by_ids(["m1"]) + for payload in (mem.update_memory.call_args.args[0], mem.delete_memories_by_ids.call_args.args[0]): + sent = payload.to_dict() + assert "app_id" not in sent and "project_id" not in sent + + +# ── rebuild of stale derived memories (1.3.0) ──────────────────────────────── +def test_rebuild_builds_input_with_the_client_scope(): + """Unlike the guards, rebuild names an owner IN a scope, like delete().""" + mem = MagicMock() + mem.rebuild_memory.return_value = SimpleNamespace(data="R") + c = EverOS("sk-test", app_id="my-app", project_id="p1") + c.memory = mem + + assert c.rebuild(user_id="u1", targets=("profile",), dry_run=True) == "R" + payload = mem.rebuild_memory.call_args.args[0] + assert isinstance(payload, RebuildInput) + assert (payload.user_id, payload.targets, payload.dry_run) == ("u1", ["profile"], True) + assert (payload.app_id, payload.project_id) == ("my-app", "p1") + + c.rebuild(agent_id="assistant-1", app_id="a2", project_id="p2") + sent = mem.rebuild_memory.call_args.args[0].to_dict() + assert sent["agent_id"] == "assistant-1" and (sent["app_id"], sent["project_id"]) == ("a2", "p2") + assert "user_id" not in sent and "targets" not in sent # unset fields stay unset + + +def test_rebuild_status_and_generated_names(): + mem = MagicMock() + mem.get_rebuild_status.return_value = SimpleNamespace(data="S") + c = _client(memory=mem) + + assert c.rebuild_status("job-9") == "S" + payload = mem.get_rebuild_status.call_args.args[0] + assert isinstance(payload, RebuildStatusInput) and payload.job_id == "job-9" + + c2 = EverOS("sk-test") + with pytest.raises(AttributeError) as ei: + c2.rebuild_memory + assert "client.rebuild(" in str(ei.value) + + +def test_rebuild_wait_polls_until_succeeded_and_raises_on_failure(): + mem = MagicMock() + mem.get_rebuild_status.side_effect = [ + SimpleNamespace(data=SimpleNamespace(status="queued", finished_at=None)), + ApiException(status=503, reason="unavailable"), + SimpleNamespace(data=SimpleNamespace(status="succeeded", finished_at="2026-11-20T00:00:00Z")), + ] + c = _client(memory=mem) + assert c.rebuild_wait("job-9", interval=0).status == "succeeded" + assert mem.get_rebuild_status.call_count == 3 + + failed = SimpleNamespace(status="failed", finished_at="2026-11-20T00:00:00Z", error="llm timeout") + mem.get_rebuild_status.side_effect = None + mem.get_rebuild_status.return_value = SimpleNamespace(data=failed) + with pytest.raises(EverOSError) as ei: + c.rebuild_wait("job-9", interval=0) + assert "llm timeout" in str(ei.value) and ei.value.job is failed + assert c.rebuild_wait("job-9", interval=0, raise_on_failure=False) is failed + + +def test_rebuild_wait_times_out_with_the_last_job(): + mem = MagicMock() + mem.get_rebuild_status.return_value = SimpleNamespace( + data=SimpleNamespace(status="running", finished_at=None) + ) + c = _client(memory=mem) + with pytest.raises(EverOSError) as ei: + c.rebuild_wait("job-9", timeout=0, interval=0) + assert ei.value.job.status == "running" + + +def test_rebuild_wait_without_a_job_says_why(): + """nothing_to_do / dry_run return job_id None; waiting on it must explain, not fail + deep inside model validation.""" + mem = MagicMock() + c = _client(memory=mem) + with pytest.raises(ValueError, match="nothing_to_do"): + c.rebuild_wait(None) + mem.get_rebuild_status.assert_not_called() From 3a246c2136787396cc509e3cf715c76c4df0301c Mon Sep 17 00:00:00 2001 From: Dani Date: Fri, 20 Nov 2026 14:55:37 -0500 Subject: [PATCH 2/2] feat(facade): rebuild_wait takes the rebuild() result; cost and add/flush notes - rebuild_wait(client.rebuild(...)) works directly, like purge_confirm takes the purge_request() result; a job_id string still works. - rebuild(): say what it costs (extraction metered, 429 once the quota is exhausted, size it with dry_run) and to take the owner from the session. - add() / flush(): a flush right after a queued add can run before the write lands and extract nothing; add with async_mode=False first. Co-Authored-By: Claude Opus 5.5 --- everos_cloud/client.py | 35 ++++++++++++++++++++++++++--------- tests/test_client.py | 13 +++++++++++++ 2 files changed, 39 insertions(+), 9 deletions(-) diff --git a/everos_cloud/client.py b/everos_cloud/client.py index f4cb45e..24dbc33 100644 --- a/everos_cloud/client.py +++ b/everos_cloud/client.py @@ -402,7 +402,12 @@ def add( app_id: str | None = None, project_id: str | None = None, ) -> Any: - """Add conversation messages to a session. Returns the ``AddData`` result.""" + """Add conversation messages to a session. Returns the ``AddData`` result. + + By default the write is queued (``async_mode`` unset): the call returns before + the messages land. To :meth:`flush` right after, pass ``async_mode=False``, or + the flush can run before the queued write and extract nothing. + """ payload = AddInput( **_clean( session_id=session_id, @@ -512,7 +517,11 @@ def get( return self._call(self.memory.get_memory, payload).data def flush(self, session_id: str, *, app_id: str | None = None, project_id: str | None = None) -> Any: - """Force extraction for a session. Returns ``FlushData``.""" + """Force extraction for a session. Returns ``FlushData``. + + Only extracts what has already landed: after a queued :meth:`add` (the default), + a flush can come too early. Add with ``async_mode=False`` before flushing. + """ payload = FlushInput(**_clean(session_id=session_id, **self._scope(app_id, project_id))) # Method name is being cleaned up (flush_api_v2_memory_flush_post -> flush_memory); # call whichever the installed SDK exposes so the facade survives the rename. @@ -1073,6 +1082,12 @@ def rebuild( what would be rebuilt and spends nothing. Batch your deletes first, then call this once. + The call is free, but the extraction it runs is metered like any extraction (a + profile rebuild re-reads every remaining episode: ``estimated_episodes`` on a + ``dry_run`` sizes it), and it is refused with a 429 once the account's usage + quota is exhausted. As with the delete guards, take the owner from your own + session, never from model output. + ``status`` is ``"queued"`` (follow ``job_id`` with :meth:`rebuild_wait`), ``"already_running"`` (the owner's running job; one at a time), ``"nothing_to_do"`` or ``"dry_run"`` (no job, ``job_id`` is ``None``). While a @@ -1097,7 +1112,7 @@ def rebuild_status(self, job_id: str) -> Any: def rebuild_wait( self, - job_id: str, + job: Any, *, timeout: float = DEFAULT_REBUILD_TIMEOUT, interval: float = DEFAULT_TASK_INTERVAL, @@ -1106,17 +1121,19 @@ def rebuild_wait( ) -> Any: """Poll a rebuild job until it ends and return the terminal ``RebuildStatusData``. - Same polling as :meth:`task_wait`. Raises ``EverOSError`` if the job fails + Pass the result of :meth:`rebuild` (``client.rebuild_wait(client.rebuild(...))``) + or its ``job_id``. Same polling as :meth:`task_wait`. Raises ``EverOSError`` if the job fails (unless ``raise_on_failure=False``, which returns it) or is still running at ``timeout``; the last job seen is on the error's ``.job``. Timing out only ends the wait, not the rebuild: call ``rebuild_wait`` again to keep waiting. """ + job_id = job if isinstance(job, str) or job is None else getattr(job, "job_id", None) if not job_id: raise ValueError( "no rebuild job to wait for: rebuild() starts one only when its status is " "'queued' or 'already_running' ('nothing_to_do' and 'dry_run' have no job_id)" ) - job = self._poll( + last = self._poll( lambda: self.rebuild_status(job_id), _rebuild_finished, what=f"rebuild {job_id}", @@ -1125,11 +1142,11 @@ def rebuild_wait( interval=interval, max_interval=max_interval, ) - if raise_on_failure and getattr(job, "status", None) == "failed": - err = EverOSError(f"rebuild {job_id} failed: {getattr(job, 'error', None) or 'no reason given'}") - err.job = job + if raise_on_failure and getattr(last, "status", None) == "failed": + err = EverOSError(f"rebuild {job_id} failed: {getattr(last, 'error', None) or 'no reason given'}") + err.job = last raise err - return job + return last # -- storage ------------------------------------------------------------- def presign(self, objects: Sequence[Any]) -> Any: diff --git a/tests/test_client.py b/tests/test_client.py index ac123e1..e912ffc 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -1182,3 +1182,16 @@ def test_rebuild_wait_without_a_job_says_why(): with pytest.raises(ValueError, match="nothing_to_do"): c.rebuild_wait(None) mem.get_rebuild_status.assert_not_called() + + +def test_rebuild_wait_takes_the_rebuild_result(): + mem = MagicMock() + mem.get_rebuild_status.return_value = SimpleNamespace( + data=SimpleNamespace(status="succeeded", finished_at="2026-11-20T00:00:00Z") + ) + c = _client(memory=mem) + started = SimpleNamespace(status="queued", job_id="job-7") + assert c.rebuild_wait(started, interval=0).status == "succeeded" + assert mem.get_rebuild_status.call_args.args[0].job_id == "job-7" + with pytest.raises(ValueError, match="nothing_to_do"): + c.rebuild_wait(SimpleNamespace(status="nothing_to_do", job_id=None))