Skip to content

HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.

A delete removes what it says, at once or after 30 days (#430)

github-actions[bot]ff6baf9a5807
diff --git a/Dockerfile b/Dockerfile
index 9588d682..07e94f52 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -167,7 +167,8 @@ RUN chmod +x /tmp/install-kits.sh \
COPY gateway/ /app/gateway/
COPY runner/ /app/runner/
COPY docker/entrypoint.sh /app/entrypoint.sh
-RUN chmod +x /app/entrypoint.sh
+COPY docker/hr-retention /usr/local/bin/hr-retention
+RUN chmod +x /app/entrypoint.sh /usr/local/bin/hr-retention
# Next.js standalone output: server + only the modules it actually needs.
COPY --from=ui /ui/.next/standalone /app/ui/
diff --git a/docker/hr-retention b/docker/hr-retention
new file mode 100755
index 00000000..a40ecd51
--- /dev/null
+++ b/docker/hr-retention
@@ -0,0 +1,27 @@
+#!/bin/sh
+# hr-retention: the retention sweep and restore, for the operator, from inside the container.
+#
+# docker exec harnessrouter hr-retention what is due now (nothing is removed)
+# docker exec harnessrouter hr-retention sweep remove what is due now
+# docker exec harnessrouter hr-retention restore <kind> <id> bring back one item within its 30 days
+#
+# The server sweeps by itself when it starts and once a day; this is for looking, and for
+# restoring a harness, response, environment or upload deleted less than 30 days ago.
+set -eu
+key=""
+for f in /proc/[0-9]*/environ; do
+ key=$(tr '\0' '\n' < "$f" 2>/dev/null | sed -n 's/^HARNESS_INTERNAL_KEY=//p' | head -n 1) || true
+ [ -n "$key" ] && break
+done
+[ -n "$key" ] || { echo "hr-retention: the server is not running in this container" >&2; exit 1; }
+call() {
+ curl -sS -X POST "http://127.0.0.1:8080/internal/retention/$1" -H "x-harness-internal: $key" \
+ -H "content-type: application/json" -d "$2" | python3 -m json.tool
+}
+case "${1:-}" in
+ "") call sweep '{"dry_run": true}' ;;
+ sweep) call sweep '{"dry_run": false}' ;;
+ restore) [ $# -eq 3 ] || { echo "usage: hr-retention restore <kind> <id>" >&2; exit 2; }
+ call restore "$(python3 -c 'import json,sys; print(json.dumps({"kind": sys.argv[1], "id": sys.argv[2]}))' "$2" "$3")" ;;
+ *) echo "usage: hr-retention [sweep | restore <kind> <id>]" >&2; exit 2 ;;
+esac
diff --git a/docs/self-hosting-guide.md b/docs/self-hosting-guide.md
index 70de6cfb..c09b9eb2 100644
--- a/docs/self-hosting-guide.md
+++ b/docs/self-hosting-guide.md
@@ -6,6 +6,7 @@ Detailed installation, configuration, API, and deployment instructions. For the
- [Install](#install)
- [Restarts, upgrades, and backups](#restarts-upgrades-and-backups)
+- [What a delete removes, and when](#what-a-delete-removes-and-when)
- [Starter kits](#starter-kits)
- [Plugins](#plugins)
- [Environments](#environments)
@@ -463,6 +464,45 @@ backup. Preserve the volume's permissions and keep any configured encryption key
alongside your deployment records. Restore the volume and the same configuration before starting
the replacement instance.
+## What a delete removes, and when
+
+Deleting follows one rule on this instance, the same as on the hosted service. Some things go at
+once and cannot be brought back; the others are kept for 30 days, can be restored by whoever runs
+the instance, and are then removed.
+
+| What is deleted | What happens |
+|---|---|
+| A task (a session) | Removed at once, for good: its conversation and trace, its responses, the files it produced and their previews, its list of changed files, its media, the record of every plugin call it made, its checkpoint and its working folder. A marker that holds its id and the time of the delete, and nothing of its content, stays for a day so that a turn still finishing cannot write it back, then goes too. |
+| An API key | Removed at once. It stops working immediately and leaves the list of keys. |
+| A credential | Removed at once: a plugin's stored secrets when the plugin is removed, a database connection when it is removed from a harness or its harness is deleted, a stored tool token deleted with `DELETE /v1/mcp-secrets/{ref}`. |
+| A harness | Kept 30 days, then removed with its skill bundles and plugin packages. A restored harness comes back without its credentials, since those went at once. The tasks and responses that used it are kept. |
+| A response deleted on its own | Unreadable at once, kept 30 days, then removed. A response of a deleted task goes with the task. |
+| An environment | Its `/env/<name>` path goes at once, so no task sees it and the name is free; its files and builds are kept 30 days, then removed. |
+| An upload (`DELETE /v1/files/{id}`) | Refused to new tasks at once, kept 30 days, then removed. |
+
+Nothing that has not been deleted expires. The server removes what has come due when it starts and
+once a day after that. The first start of 0.32.0 removes what earlier versions only marked as
+deleted more than 30 days before, and what tasks deleted before 0.32.0 left behind. Earlier
+versions did not keep the time of a delete, so such a record counts from its last activity: for a
+harness, the later of its last change and the last task it ran; for a response, when it was made. **Back up the volume before upgrading
+to 0.32.0** if anything deleted earlier should be kept.
+
+Backups are the caveat to all of this. Removing something from the instance does not remove it
+from a copy of the volume taken before the delete: a backup keeps whatever it held, for as long
+as the backup is kept. Rotate backups to match the promise you make to the people using the
+instance.
+
+To see what is due, remove it now, or bring something back within its 30 days:
+
+```bash
+docker exec harnessrouter hr-retention # what is due (removes nothing)
+docker exec harnessrouter hr-retention sweep # remove it now
+docker exec harnessrouter hr-retention restore harnesses chrn_... # or responses, environments, uploads
+```
+
+An environment cannot be restored while another environment holds its name; rename that one
+first.
+
## Starter kits
Starter kits are worked examples, and they are here to show you what this can be pointed at.
@@ -1137,6 +1177,7 @@ All paths below are relative to the API base above and use the same Bearer key.
| Read session history | `GET /v1/sessions/{session_id}/turns` |
| Upload inputs or retrieve outputs | `POST /v1/files`; `GET /v1/sessions/{session_id}/files` |
| Cancel work | `POST /v1/responses/{response_id}/cancel` |
+| Delete | `DELETE /v1/sessions/{session_id}`, `DELETE /v1/responses/{response_id}`, `DELETE /v1/harnesses/{harness_id}`, `DELETE /v1/files/{file_id}`, `DELETE /v1/mcp-secrets/{ref}`; what each removes and when is in [What a delete removes, and when](#what-a-delete-removes-and-when) |
| Describe the API | `GET /v1/openapi.json`, the surface above as an OpenAPI document, readable without a login |
| Inspect execution | `GET /v1/sessions/{session_id}/turns` for the turns; `GET /v1/traces/{session_id}/all` for the stored event stream of the harness as newline-delimited JSON, one event per line (`content-type: application/x-ndjson`; assistant, tool and result events as the CLI emitted them); `/v1/traces/{session_id}/events?chunk=N` reads one stored chunk. Provider-call spans (the model requests behind a turn) are part of the hosted service's observability, not of this edition |
diff --git a/gateway/app.py b/gateway/app.py
index 8d707970..e0091865 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -4993,8 +4993,8 @@ async def get_trace_all(sid: str, request: Request, compact: int = 0) -> Respons
@app.delete("/v1/sessions/{sid}")
@app.delete("/v1/traces/{sid}")
async def delete_trace(sid: str, request: Request) -> dict:
- """Delete a session for good: its trace manifest + event chunks, its durable workspace
- tarball, and tombstone the session vertex. /v1/sessions/{sid} is the protocol's name for it;
+ """Delete a session for good, at once: everything it left (`_session_purge`), and its record
+ reduced to a marker that holds no content. /v1/sessions/{sid} is the protocol's name for it;
/v1/traces/{sid} is the older path the Traces app calls, the same handler."""
p = await _principal(request)
org = str(p.get("org") or "")
@@ -5019,7 +5019,8 @@ async def delete_trace(sid: str, request: Request) -> dict:
# serving the full conversation. Sessions §6 says deletion MUST make the session
# unreadable, and the published link is the reader its owner is least likely to remember.
try:
- await _vg_upsert("HarnessSession", sid, {"status": "deleted", "shared": "0"})
+ await _vg_upsert("HarnessSession", sid, {"status": "deleted", "shared": "0",
+ "deleted_at": str(_now_ms())})
except Exception: # noqa: BLE001
pass
# Clear local token lookups as well. Every public read checks durable share state, so
@@ -5032,7 +5033,64 @@ async def delete_trace(sid: str, request: Request) -> dict:
await _stop_session(org, sid, v)
except Exception: # noqa: BLE001
pass
- base = await _trace_base(sid)
+ await _session_purge(sid, v)
+ await _session_strip(sid, v)
+ # drop in-process state (the vertex was tombstoned first, above)
+ _SHARE_TOKEN_CACHE.clear()
+ _session_trace.pop(sid, None)
+ return {"id": sid, "object": "session", "deleted": True}
+
+
+# What a deleted session's marker keeps: the ids that find what it left, and nothing a person
+# wrote. A finalize or a reconcile can land after the delete, and the tombstone is what refuses
+# them (`_session_write_allowed`, `_index_put`); the retention sweep removes the marker a day later,
+# after purging again whatever such a late write managed to put back.
+_SESSION_MARKER = ("tenant", "workspace", "harness_id", "member_id", "member", "created_at_inv",
+ "trace_blob", "status", "shared", "deleted_at")
+
+
+async def _session_strip(sid: str, v: dict | None) -> None:
+ """Reduce a deleted session's record to its marker. The store merges on write, so the record
+ is removed and the marker written fresh; a write landing between the two is a status write
+ the next sweep strips again."""
+ cur = await BACKING.graph.get(sid) or dict(v or {})
+ keep = {k: str(cur.get(k) or "") for k in _SESSION_MARKER if cur.get(k)}
+ keep.update({"status": "deleted", "shared": "0"})
+ keep.setdefault("deleted_at", str(_now_ms()))
+ with contextlib.suppress(Exception):
+ await BACKING.graph.delete(sid, "HarnessSession")
+ with contextlib.suppress(Exception):
+ await BACKING.graph.upsert("HarnessSession", sid, keep)
+
+
+async def _session_records(label: str, field: str, sid: str, index: dict | None) -> list[str]:
+ """The ids of one kind of record a session owns. The sweep hands in an index it built once:
+ a lookup by property reads every record of the label, and a volume with thousands of deleted
+ sessions would otherwise read every response once per session."""
+ if index is not None:
+ return list(index.get(label, {}).get(sid, ()))
+ return [str(r["id"]) for r in await BACKING.graph.find(label, {field: sid}) if r.get("id")]
+
+
+async def _session_index() -> dict:
+ """Every session's responses and plugin calls, by session id, in one read of each label."""
+ idx: dict = {}
+ for label, field in (("HarnessResponse", "session_id"), (_PLUG_CALL_LABEL, "session")):
+ by: dict[str, list[str]] = {}
+ for r in await BACKING.graph.find(label):
+ if r.get(field) and r.get("id"):
+ by.setdefault(str(r[field]), []).append(str(r["id"]))
+ idx[label] = by
+ return idx
+
+
+async def _session_purge(sid: str, v: dict | None, index: dict | None = None) -> None:
+ """Everything a session left, removed: its transcript and trace, its responses, the files its
+ tasks produced, their previews and change list, its media, the record of every plugin call it
+ made, its checkpoint and its live working folder. Richard's rule (2026-10-08, the same on the
+ hosted service): deleting a task removes it at once and for good. Idempotent, so the retention
+ sweep runs it again for every marker before removing the marker."""
+ base = _prefix_from_vertex(sid, v)
# 1) trace manifest + event chunks (drives the Recents/Traces list)
if base:
manifest = {}
@@ -5054,7 +5112,25 @@ async def delete_trace(sid: str, request: Request) -> dict:
# remove the flat index AND the per-harness/per-member mirrors (harness/member from the
# manifest we just read; falls back to a bare flat-key delete if the manifest was unreadable)
await _deindex_manifest(base, manifest, _session_trace.get(sid) or {}, v or {})
- # 2) durable session workspace tarball, and anything the media server holds for it
+ # 2) its responses. Response §7 keeps a response deleted on its own for 30 days; a response
+ # of a deleted session goes with the session.
+ with contextlib.suppress(Exception):
+ for rid in await _session_records("HarnessResponse", "session_id", sid, index):
+ _resp_cache_forget(rid)
+ await _blob_delete(f"responses/{rid}.json", kb=RESP_BLOB_KB)
+ await BACKING.graph.delete(rid, "HarnessResponse")
+ # 3) everything stored under its id: the checkpoint and the media scene (sessions/<sid>/ in
+ # the session store), the change list (sessions/<sid>/ in the response store), the files its
+ # tasks produced (containers/<sid>/) and their rendered previews (previews/<sid>/)
+ for kb, prefix in ((BLOB_KB, f"sessions/{sid}/"), (RESP_BLOB_KB, f"sessions/{sid}/"),
+ (RESP_BLOB_KB, f"containers/{sid}/"), (RESP_BLOB_KB, f"previews/{sid}/")):
+ with contextlib.suppress(Exception):
+ for it in await _blob_list_all(prefix, kb=kb):
+ await _blob_delete(str(it.get("file_id") or ""), kb=kb)
+ purge = getattr(BACKING.blob, "purge", None) # what a listing does not show
+ if purge:
+ with contextlib.suppress(Exception):
+ await purge(kb, prefix)
await _blob_delete(_ws_blob(sid), kb=BLOB_KB)
# The live working folder is the session's memory on this box (the tarball above is its
# durable copy); §6 says deletion frees it. Only the runner can remove it: the folder belongs
@@ -5066,10 +5142,10 @@ async def delete_trace(sid: str, request: Request) -> dict:
except Exception: # noqa: BLE001
pass
await _media_session_purge(sid)
- # 3) drop in-process state (the vertex was tombstoned first, above)
- _SHARE_TOKEN_CACHE.clear()
- _session_trace.pop(sid, None)
- return {"id": sid, "object": "session", "deleted": True}
+ # 4) the record of every plugin call it made
+ with contextlib.suppress(Exception):
+ for cid in await _session_records(_PLUG_CALL_LABEL, "session", sid, index):
+ await BACKING.graph.delete(cid, _PLUG_CALL_LABEL)
# ── connection admin (org admins manage their own provider connections) ──────────
@@ -5811,6 +5887,10 @@ def _rid(prefix: str) -> str:
return f"{prefix}_{uuid.uuid4().hex}"
+def _now_ms() -> int:
+ return int(time.time() * 1000)
+
+
async def _vg_upsert(label: str, vid: str, props: dict, *, raise_on_fail: bool = False) -> None:
"""Generic coalesce-upsert for any VG vertex label (HarnessResponse / HarnessApiKey).
Best-effort by default; VG is closed-world on labels so an unregistered label silently no-ops.
@@ -8332,6 +8412,308 @@ async def _owned_org(request: Request, org: str) -> dict:
return p
+# ── retention: when what was deleted is removed ──────────────────────────────────────────────
+# Richard's rule (2026-10-08), the hosted service's too, and published in the self-hosting guide:
+# for good, at once: tasks (sessions, with everything they left), API keys, credentials
+# 30 days, restorable, gone: harnesses, responses deleted on their own, environments, uploads
+# Each delete does its own "at once" part. This sweep removes what has come due: what a delete
+# could not finish, the marker a deleted session keeps for a day, and every 30-day kind past its
+# 30 days. It runs when the server starts and every day after, so the first start of a version
+# that has it removes everything a volume already held marked deleted for longer than 30 days
+# (Richard, 2026-10-08: "remove old ones at once"). A record marked before delete times were
+# written counts from its last write, and the answer says how many did.
+#
+# The shapes are the hosted service's (POST /internal/retention/sweep and /restore), so one
+# operator tool reads both. Arenas and accounts are hosted kinds; this server has neither.
+_RETAIN_MS = 30 * 86_400_000
+_MARKER_MS = 86_400_000
+_RETENTION_SWEEP_S = int(os.environ.get("HR_RETENTION_SWEEP_S", "86400"))
+_RETENTION_KINDS = ("sessions", "responses", "harnesses", "api_keys", "environments", "uploads", "credentials")
+_FOR_GOOD = frozenset({"sessions", "api_keys", "credentials"})
+
+
+def _stamp_ms(v) -> int:
+ """A time as any version wrote it, in milliseconds: seconds or milliseconds, a number or its
+ text. 0 when there is none."""
+ try:
+ f = float(str(v if v is not None else "").strip() or 0)
+ except ValueError:
+ return 0
+ return int(f * 1000) if 0 < f < 1e11 else int(f)
+
+
+def _true(v) -> bool:
+ return str(v) in ("1", "true", "True")
+
+
+async def _retention_due(kind: str, now: int) -> tuple[list[dict], int]:
+ """The items of one kind that are due, oldest first, each {"id", "row"}; and how many of them
+ had no delete time of their own."""
+ rows: list[tuple[int, bool, dict]] = [] # (counted-from time, had a delete time, row)
+
+ def add(row: dict, at_field: str, *fallbacks: str) -> None:
+ at = _stamp_ms(row.get(at_field))
+ own = at > 0 or kind in ("api_keys", "credentials") # due at once: no clock to count from
+ for f in fallbacks:
+ if at:
+ break
+ at = _stamp_ms(row.get(f))
+ rows.append((at, own, row))
+
+ if kind == "sessions":
+ # A session deleted before this version has no delete time and everything it left still
+ # beside it: due at once, since a task's delete is for good.
+ for r in await BACKING.graph.find("HarnessSession", {"status": "deleted"}):
+ add(r, "deleted_at")
+ due = [(at, own, r) for at, own, r in rows if not at or now - at >= _MARKER_MS]
+ elif kind == "api_keys":
+ for r in await BACKING.graph.find("HarnessApiKey"):
+ if _true(r.get("revoked")) or r.get("kind") != "harness_api_key":
+ add(r, "revoked_at")
+ due = rows
+ elif kind == "credentials":
+ for r in await BACKING.graph.find(_CONNECTION_LABEL, {"deleted": "1"}):
+ add(r, "deleted_at", "updated_at")
+ blank = getattr(BACKING.secrets, "blank", None)
+ if blank:
+ for tenant, name in await blank():
+ rows.append((0, True, {"id": f"secret:{tenant}/{name}", "tenant": tenant, "name": name}))
+ due = rows
+ elif kind == "responses":
+ for r in await BACKING.graph.find("HarnessResponse", {"status": "deleted"}):
+ add(r, "deleted_at", "created_at")
+ due = [(at, own, r) for at, own, r in rows if not at or now - at >= _RETAIN_MS]
+ elif kind == "harnesses":
+ # A harness deleted before delete times were kept counts from its last activity: the later
+ # of its last edit and the last task it ran, which the delete came after (Richard,
+ # 2026-10-08, "Last activity"). Its last edit alone can be months before a delete made
+ # yesterday by someone who had kept using it.
+ last_task: dict[str, int] = {}
+ for sv in await BACKING.graph.find("HarnessSession"):
+ h = str(sv.get("harness_id") or "")
+ if h:
+ t = max(_stamp_ms(sv.get("updated_at")), _stamp_ms(sv.get("created_at")))
+ last_task[h] = max(last_task.get(h, 0), t)
+ for r in await BACKING.graph.find("Harness", {"deleted": "1"}):
+ if not _stamp_ms(r.get("deleted_at")):
+ r = {**r, "_last_activity": str(max(_stamp_ms(r.get("updated_at")), _stamp_ms(r.get("created_at")),
+ last_task.get(str(r.get("id") or ""), 0)) or "")}
+ add(r, "deleted_at", "_last_activity")
+ due = [(at, own, r) for at, own, r in rows if not at or now - at >= _RETAIN_MS]
+ elif kind == "environments":
+ for r in await BACKING.graph.find("Environment", {"deleted": "1"}):
+ add(r, "deleted_at", "updated_at", "created_at")
+ due = [(at, own, r) for at, own, r in rows if not at or now - at >= _RETAIN_MS]
+ elif kind == "uploads":
+ for it in await _blob_list_all("uploads/", kb=RESP_BLOB_KB):
+ key = str(it.get("file_id") or "")
+ if not key.endswith(".meta"):
+ continue
+ fid = key[len("uploads/"):-len(".meta")]
+ meta = await _upload_meta(fid)
+ if meta and meta.get("deleted_at"):
+ add({"id": fid, **meta}, "deleted_at")
+ due = [(at, own, r) for at, own, r in rows if now - at >= _RETAIN_MS]
+ else:
+ return [], 0
+ due.sort(key=lambda t: t[0])
+ return [{"id": str(r.get("id") or ""), "row": r} for _, _, r in due if r.get("id")], \
+ sum(1 for _, own, _ in due if not own)
+
+
+def _harness_blobs(v: dict) -> set[str]:
+ """The skill bundles and plugin packages a harness record names."""
+ try:
+ skills = json.loads(v.get("skills") or "[]")
+ except Exception: # noqa: BLE001
+ skills = []
+ org = str(v.get("org") or "")
+ keys = {f"skills/{sk['blob']}.json" for sk in (skills if isinstance(skills, list) else [])
+ if isinstance(sk, dict) and sk.get("blob")}
+ return keys | {_plugin_blob_key(org, str(pe["blob"])) for pe in _plugins_of(v) if pe.get("blob")}
+
+
+async def _harness_blob_refs() -> "collections.Counter[str]":
+ """How many harness records name each bundle. A client may write a bundle's id onto another
+ harness, so a removed harness's bundle goes only when no record left names it."""
+ refs: "collections.Counter[str]" = collections.Counter()
+ for h in await BACKING.graph.find("Harness"):
+ refs.update(_harness_blobs(h))
+ return refs
+
+
+async def _retention_remove(kind: str, item: dict, ctx: dict) -> str | None:
+ """Remove one due item for good. Answers why it was left, or None when it is gone."""
+ iid, row = item["id"], item["row"]
+ if kind == "sessions":
+ if "by_session" not in ctx:
+ ctx["by_session"] = await _session_index()
+ await _session_purge(iid, row, ctx["by_session"])
+ await BACKING.graph.delete(iid, "HarnessSession")
+ elif kind == "api_keys":
+ await BACKING.graph.delete(iid, "HarnessApiKey")
+ elif kind == "credentials":
+ if iid.startswith("secret:"):
+ await BACKING.secrets.delete(row["tenant"], row["name"])
+ else:
+ await BACKING.graph.delete(iid, _CONNECTION_LABEL)
+ elif kind == "responses":
+ _resp_cache_forget(iid)
+ await _blob_delete(f"responses/{iid}.json", kb=RESP_BLOB_KB)
+ await BACKING.graph.delete(iid, "HarnessResponse")
+ elif kind == "harnesses":
+ org = str(row.get("org") or "")
+ # credentials were removed at the delete; again here for a harness deleted before that
+ await _hosted_scrub_removed(org, iid, _mcp_list(row), [])
+ for c in await BACKING.graph.find(_CONNECTION_LABEL, {"harness": iid}):
+ if c.get("id"):
+ await BACKING.graph.delete(str(c["id"]), _CONNECTION_LABEL)
+ if "blob_refs" not in ctx:
+ ctx["blob_refs"] = await _harness_blob_refs()
+ refs = ctx["blob_refs"]
+ await BACKING.graph.delete(iid, "Harness")
+ for key in sorted(_harness_blobs(row)):
+ refs[key] -= 1
+ if refs[key] <= 0:
+ await _blob_delete(key, kb=BLOB_KB)
+ elif kind == "environments":
+ try:
+ r = await _env_runner("DELETE", f"/environments/{iid}", iid)
+ except HTTPException:
+ return "the runner that holds environments did not answer"
+ if r.status_code >= 400:
+ return f"the runner could not remove its files (HTTP {r.status_code})"
+ await BACKING.graph.delete(iid, "Environment")
+ elif kind == "uploads":
+ await _blob_delete(f"uploads/{iid}", kb=RESP_BLOB_KB)
+ await _blob_delete(f"uploads/{iid}.meta", kb=RESP_BLOB_KB)
+ return None
+
+
+async def _retention_sweep(dry_run: bool, kinds: list[str] | None = None, limit: int | None = None) -> dict:
+ now = _now_ms()
+ out: dict = {"dry_run": dry_run, ("would_remove" if dry_run else "removed"): {},
+ "no_delete_time": {}, "left": {}}
+ listed = out["would_remove" if dry_run else "removed"]
+ done = True
+ ctx: dict = {}
+ for kind in kinds or _RETENTION_KINDS:
+ due, no_time = await _retention_due(kind, now)
+ batch = due[:limit] if limit else due
+ if len(batch) < len(due):
+ done = False
+ listed[kind] = []
+ if no_time:
+ out["no_delete_time"][kind] = no_time
+ for item in batch:
+ if dry_run:
+ listed[kind].append(item["id"])
+ continue
+ try:
+ why = await _retention_remove(kind, item, ctx)
+ except Exception as e: # noqa: BLE001 — one item must not stop the sweep
+ why = f"{type(e).__name__}"
+ if why:
+ out["left"].setdefault(kind, why)
+ done = False
+ else:
+ listed[kind].append(item["id"])
+ # Nothing due is left: after a sweep, nothing it could not remove; after a dry run, nothing
+ # to list (a dry run removes nothing, so anything it lists is still due).
+ out["done"] = done and not (dry_run and any(listed.values()))
+ return out
+
+
+class RetentionSweepBody(BaseModel):
+ dry_run: bool = False
+ kinds: list[str] | None = None
+ limit: int | None = Field(default=None, ge=1)
+
+
[email protected]("/internal/retention/sweep", dependencies=[Depends(_internal_only)])
+async def retention_sweep(body: RetentionSweepBody) -> dict:
+ """Remove what has come due now, or (`dry_run`) list it. `limit` caps each kind per call, and
+ `done` says nothing due is left, so a capped run is called again until it is."""
+ kinds = [k for k in (body.kinds or []) if k not in ("arenas", "accounts")]
+ bad = [k for k in kinds if k not in _RETENTION_KINDS]
+ if bad:
+ raise uhp_error(400, "invalid_input", f"No retention kind {bad[0]!r} on this server.", "kinds",
+ {"supported": list(_RETENTION_KINDS)})
+ return await _retention_sweep(body.dry_run, kinds or None, body.limit)
+
+
+class RetentionRestoreBody(BaseModel):
+ kind: str
+ id: str
+
+
[email protected]("/internal/retention/restore", dependencies=[Depends(_internal_only)])
+async def retention_restore(body: RetentionRestoreBody) -> dict:
+ """Bring back one item deleted within its 30 days. A kind removed at once cannot come back
+ (409); an item the sweep removed, or never was, is gone (410)."""
+ kind, iid = body.kind, body.id
+ if kind in _FOR_GOOD:
+ raise uhp_error(409, "not_restorable", f"A deleted {kind[:-1].replace('_', ' ')} is removed at once and cannot be restored.", "kind")
+ gone = uhp_error(410, "gone", "Nothing deleted with that id is kept.", "id")
+ if kind == "responses":
+ raw = await _blob_get(f"responses/{iid}.json", kb=RESP_BLOB_KB) if re.fullmatch(r"[A-Za-z0-9_-]+", iid) else None
+ try:
+ rec = json.loads(raw) if raw else None
+ except ValueError:
+ rec = None
+ if not isinstance(rec, dict) or not rec.get("_deleted"):
+ raise gone
+ rec.pop("_deleted", None)
+ rec.pop("_deleted_at", None)
+ _resp_cache_forget(iid)
+ await _blob_put(f"responses/{iid}.json", json.dumps(rec, default=str).encode(), kb=RESP_BLOB_KB)
+ await _vg_upsert("HarnessResponse", iid, {"status": str(rec.get("status") or "completed"), "deleted_at": ""})
+ elif kind in ("harnesses", "environments"):
+ label = "Harness" if kind == "harnesses" else "Environment"
+ v = await BACKING.graph.get(iid, label=label)
+ if not v or not _true(v.get("deleted")):
+ raise gone
+ if label == "Environment" and any(
+ str(r.get("id")) != iid and not _true(r.get("deleted"))
+ for r in await BACKING.graph.find("Environment", {"slug": str(v.get("slug") or "")})):
+ raise uhp_error(409, "environment_exists",
+ f"Another environment is mounted at /env/{v.get('slug')} now; rename it first.", "id")
+ await _vg_upsert(label, iid, {"deleted": "0", "deleted_at": "", "updated_at": str(_now_ms())})
+ elif kind == "uploads":
+ meta = await _upload_meta(iid)
+ if not meta or not meta.get("deleted_at") or await _blob_get(f"uploads/{iid}", kb=RESP_BLOB_KB) is None:
+ raise gone
+ meta.pop("deleted_at", None)
+ await _blob_put(f"uploads/{iid}.meta", json.dumps(meta).encode(), kb=RESP_BLOB_KB)
+ else:
+ raise uhp_error(400, "invalid_input", f"No retention kind {kind!r} on this server.", "kind",
+ {"supported": list(_RETENTION_KINDS)})
+ return {"kind": kind, "id": iid, "restored": True}
+
+
[email protected]_event("startup")
+async def _start_retention_sweep() -> None:
+ async def loop() -> None:
+ await asyncio.sleep(30) # after startup's own work, not in its way
+ while True:
+ try:
+ run_it = True
+ if control_store.enabled():
+ with contextlib.suppress(Exception):
+ run_it = await control_store.try_lock("retention-sweep", max(60, _RETENTION_SWEEP_S - 60))
+ if run_it:
+ res = await _retention_sweep(False)
+ n = {k: len(v) for k, v in res["removed"].items() if v}
+ if n or res["left"]:
+ print(f"[retention] removed {n or 'nothing'}"
+ + (f"; counted from the last write: {res['no_delete_time']}" if res["no_delete_time"] else "")
+ + (f"; left: {res['left']}" if res["left"] else ""), flush=True)
+ except Exception as e: # noqa: BLE001
+ print(f"[retention] sweep failed: {type(e).__name__}", flush=True)
+ await asyncio.sleep(_RETENTION_SWEEP_S)
+ asyncio.create_task(loop())
+
+
@app.get("/internal/storage-usage", dependencies=[Depends(_internal_only)])
async def storage_usage() -> dict:
"""Total durable workspace bytes per org, for the daily storage.gb_day billing sweep.
@@ -9277,13 +9659,17 @@ async def delete_response(response_id: str, request: Request):
# 403) so a cross-org id probe can't confirm existence. Legacy records with no _org stay owned.
if str(rec.get("_org") or principal.get("org", "")) != principal.get("org", "") or not await _response_in_reach(principal, rec):
raise uhp_error(404, "response_not_found", "No response with that id.", "response_id")
+ # Kept 30 days, restorable, then removed by the retention sweep (Richard's rule, 2026-10-08).
+ # Unreadable from now: `_resp_get` answers None for a record marked deleted.
+ now = _now_ms()
rec["_deleted"] = True
+ rec["_deleted_at"] = now
try:
_resp_cache_forget(response_id)
await _blob_put(f"responses/{response_id}.json", json.dumps(rec, default=str).encode(), kb=RESP_BLOB_KB)
except Exception: # noqa: BLE001
pass
- await _vg_upsert("HarnessResponse", response_id, {"status": "deleted"})
+ await _vg_upsert("HarnessResponse", response_id, {"status": "deleted", "deleted_at": str(now)})
# ── Session sharing + artifact serving by path (HRP-011) ─────────────────────────────────
@@ -9682,6 +10068,40 @@ async def upload_file(request: Request, purpose: str = Form("user_data"), file:
"filename": file.filename, "purpose": purpose}
+_UPLOAD_ID = re.compile(r"file_[0-9a-f]{32}")
+
+
+async def _upload_meta(fid: str) -> dict | None:
+ """An upload's sidecar, or None when there is no such upload. An upload from before sidecars
+ existed answers an empty one."""
+ if not _UPLOAD_ID.fullmatch(fid or ""):
+ return None
+ raw = await _blob_get(f"uploads/{fid}.meta", kb=RESP_BLOB_KB)
+ if raw is None:
+ return {} if await _blob_get(f"uploads/{fid}", kb=RESP_BLOB_KB) is not None else None
+ try:
+ meta = json.loads(raw.decode())
+ except Exception: # noqa: BLE001
+ return {}
+ return meta if isinstance(meta, dict) else {}
+
+
[email protected]("/v1/files/{file_id}")
+async def delete_file(file_id: str, request: Request) -> dict:
+ """Delete an upload. Kept 30 days, restorable, then removed by the retention sweep (Richard's
+ rule, 2026-10-08); from now on a task that names it is refused as an unknown id is. The same
+ owner rule as a read: another organization's upload answers 404."""
+ principal = await _principal(request)
+ org = str(principal.get("org") or "")
+ meta = await _upload_meta(file_id)
+ if meta is None or meta.get("deleted_at") or (meta.get("org") and str(meta["org"]) != org):
+ raise uhp_error(404, "file_not_found", f"No file with id {file_id}.", "file_id")
+ meta["deleted_at"] = _now_ms()
+ if not await _blob_put(f"uploads/{file_id}.meta", json.dumps(meta).encode(), kb=RESP_BLOB_KB):
+ raise HTTPException(502, "the file could not be deleted; try again")
+ return {"id": file_id, "object": "file", "deleted": True}
+
+
async def _resolve_uploads(files_in: list[dict], org: str) -> None:
"""Inline the uploads a task references by file_id, for THIS org only.
@@ -9702,7 +10122,8 @@ async def _resolve_uploads(files_in: list[dict], org: str) -> None:
except Exception: # noqa: BLE001
meta = {}
owner = str(meta.get("org") or "")
- data = None if (owner and owner != org) else await _blob_get(f"uploads/{fid}", kb=RESP_BLOB_KB)
+ gone = bool(meta.get("deleted_at"))
+ data = None if (gone or (owner and owner != org)) else await _blob_get(f"uploads/{fid}", kb=RESP_BLOB_KB)
if data is None:
raise uhp_error(404, "file_not_found", f"No file with id {fid}.", "input")
f["content_b64"] = base64.b64encode(data).decode()
@@ -10448,6 +10869,12 @@ async def revoke_key(org: str, kid: str, request: Request) -> dict:
await control_store.apikey_revoke(kid)
except Exception: # noqa: BLE001 — graph is authoritative; the store tombstone is a fast-path
pass
+ # Then removed at once, with no undo (Richard's rule, 2026-10-08): the record goes, and with
+ # it the key's name and last use. Revoked first so a removal that fails still leaves it dead;
+ # the retention sweep removes what a failed removal left. A last-use stamp landing after
+ # this writes a record with no kind, which no lookup accepts and the sweep removes.
+ with contextlib.suppress(Exception):
+ await BACKING.graph.delete(kid, "HarnessApiKey")
return {"id": kid, "revoked": True}
@@ -10652,6 +11079,25 @@ async def put_mcp_secret(org: str, ref: str, body: McpSecretBody, request: Reque
return await _mcp_secret_store(org, ref, body.token)
[email protected]("/v1/orgs/{org}/mcp-secrets/{ref}")
+async def delete_mcp_secret(org: str, ref: str, request: Request) -> dict:
+ await _owned_org(request, org)
+ return await _mcp_secret_delete(org, ref)
+
+
+async def _mcp_secret_delete(org: str, ref: str) -> dict:
+ """Remove a stored MCP server token, at once and for good: a credential is not kept after its
+ delete (Richard's rule, 2026-10-08), and before this the only way to be rid of one was to
+ overwrite it. A harness that still names the reference runs without it."""
+ tenant = _org_tenant(org)
+ if not tenant:
+ raise HTTPException(400, "no org to remove the secret for")
+ safe = re.sub(r"[^a-z0-9]+", "-", ref.lower()).strip("-") or "mcp"
+ key = f"{_MCP_SECRET_PREFIX}{safe}"
+ await BACKING.secrets.delete(tenant, key)
+ return {"ref": f"vault:{key}", "deleted": True}
+
+
@app.post("/v1/orgs/{org}/mcp-test")
async def test_mcp(org: str, body: McpTestBody, request: Request) -> dict:
await _owned_org(request, org)
@@ -10672,6 +11118,12 @@ async def put_mcp_secret_public(ref: str, body: McpSecretBody, request: Request)
return await _mcp_secret_store(org, ref, body.token)
[email protected]("/v1/mcp-secrets/{ref}")
+async def delete_mcp_secret_public(ref: str, request: Request) -> dict:
+ org, _ = await _pub_org_member(request)
+ return await _mcp_secret_delete(org, ref)
+
+
@app.post("/v1/mcp-test")
async def test_mcp_public(body: McpTestBody, request: Request) -> dict:
org, _ = await _pub_org_member(request)
@@ -10828,19 +11280,22 @@ def _hosted_keys(servers: list[dict]) -> set[str]:
async def _hosted_scrub_removed(org: str, hid: str, before: list[dict], after: list[dict]) -> None:
- """Overwrite the record behind every hosted entry this write removed.
+ """Remove the record behind every hosted entry this write removed.
Dropping the entry and leaving its connection string encrypted on disk would be a surprise of
the worst kind: removing the tool, or deleting the agent, is the most decisive thing the
surface offers. Shared by every write that can drop an entry, so they cannot promise
- differently.
+ differently. Removed rather than overwritten: a credential goes at once and for good, even
+ when its harness is deleted and later restored (Richard's rule, 2026-10-08), and an empty
+ overwrite needed an encryption key the store may not have, so on such an instance the
+ connection string stayed exactly as it was.
THE RECORD MUST BE THIS HARNESS'S — the same binding _hosted_resolve refuses a read on. `auth`
is a client-writable field and harness ids are public, so anyone may name another agent's ref
on an entry of their own; removing it would otherwise destroy a connection they were never
given. Losing a database is the louder of the two surprises, so the check belongs on both.
Positive evidence of foreign ownership is what skips the scrub: a record we cannot read is one
- we overwrite, because leaving a connection string behind is the failure this function exists
+ we remove, because leaving a connection string behind is the failure this function exists
to prevent.
"""
gone = _hosted_keys(before) - _hosted_keys(after)
@@ -10855,7 +11310,7 @@ async def _hosted_scrub_removed(org: str, hid: str, before: list[dict], after: l
flush=True)
continue
with contextlib.suppress(Exception): # an unwritable store must not block the write
- await BACKING.secrets.put(tenant, key, "", require_encryption=True)
+ await BACKING.secrets.delete(tenant, key)
scrubbed += 1
if scrubbed:
print(f"[sql] {hid}: disconnected ({scrubbed} record(s) scrubbed)", flush=True)
@@ -11014,7 +11469,7 @@ async def _mcp_migrate(org: str, hid: str, v: dict | None) -> dict | None:
await _vg_upsert("Harness", hid, {"mcp_servers": json.dumps(servers), _DS_PROP_LEGACY: ""})
with contextlib.suppress(Exception): # an unwritable store must not strand the conversion
tenant = org if _vault_tenant_ok(org) else GLOBAL_TENANT
- await BACKING.secrets.put(tenant, old_key, "", require_encryption=True)
+ await BACKING.secrets.delete(tenant, old_key)
print(f"[migrate] {hid}: database is now an ordinary MCP server", flush=True)
return {**v, "mcp_servers": json.dumps(servers), _DS_PROP_LEGACY: ""}
@@ -11088,12 +11543,13 @@ async def _connection_vertex_put(org: str, hid: str, v: dict | None, entry_id: s
async def _connection_vertex_drop(hid: str, key: str) -> None:
- """The entry is gone, so the configuration is gone with it (the record was scrubbed already)."""
+ """The entry is gone, so the configuration is gone with it (the record was removed already):
+ removed, not marked, since it describes a credential that is gone for good."""
with contextlib.suppress(Exception):
for row in await BACKING.graph.find(_CONNECTION_LABEL, {"harness": hid, "secret_key": key}):
vid = str(row.get("id") or "")
if vid:
- await _vg_upsert(_CONNECTION_LABEL, vid, {"deleted": "1", "updated_at": str(int(time.time() * 1000))})
+ await BACKING.graph.delete(vid, _CONNECTION_LABEL)
async def _connections_of(org: str, hid: str) -> list[dict]:
@@ -14217,8 +14673,10 @@ async def _media_harness_purge(hid: str) -> None:
async def _media_session_purge(sid: str) -> None:
- """Deleting the video deletes its media and tombstones its jobs. Called from the one place
- that deletes a session, so there is no second answer to 'is it gone'."""
+ """Deleting the video deletes its media and its jobs. Called from the one place that deletes
+ a session, so there is no second answer to 'is it gone'. A job still running is first marked
+ deleted, which is what stops the sweeper; then every job's record is removed, finished ones
+ included, because a job's record is the session's (Richard's rule, 2026-10-08)."""
with contextlib.suppress(Exception):
for it in await _blob_list_all(f"media/{sid}/", kb=BLOB_KB):
await _blob_delete(str(it.get("file_id") or ""), kb=BLOB_KB)
@@ -14227,6 +14685,10 @@ async def _media_session_purge(sid: str) -> None:
with contextlib.suppress(Exception):
for job in await _media_jobs_of(sid):
await _vg_upsert(_MEDIA_JOB_LABEL, job["id"], {"deleted": "1", "status": "deleted"})
+ with contextlib.suppress(Exception):
+ for row in await BACKING.graph.find(_MEDIA_JOB_LABEL, {"session": sid}):
+ if row.get("id"):
+ await BACKING.graph.delete(str(row["id"]), _MEDIA_JOB_LABEL)
# ── plugs: services connected once for a workspace, reached through one hosted server ─────────
@@ -16727,10 +17189,14 @@ async def delete_environment(env_id: str, request: Request) -> dict:
v = await _environment_refresh(v)
if str(v.get("status") or "") == "building":
raise uhp_error(409, "environment_busy", "A build is running; wait for it before deleting.")
- r = await _env_runner("DELETE", f"/environments/{env_id}", env_id, params={"slug": str(v.get("slug") or "")})
+ # Kept 30 days, restorable, then removed with its files by the retention sweep (Richard's
+ # rule, 2026-10-08). What goes now is its place at /env/<slug>: no session sees it from here,
+ # and the name is free for another environment.
+ r = await _env_runner("DELETE", f"/environments/{env_id}/mount", env_id, params={"slug": str(v.get("slug") or "")})
if r.status_code >= 500:
- raise _env_runner_error(r, "the environment's files could not be removed")
- await _vg_upsert("Environment", env_id, {"deleted": "1", "updated_at": str(int(time.time() * 1000))})
+ raise _env_runner_error(r, "the environment could not be taken down")
+ now = str(_now_ms())
+ await _vg_upsert("Environment", env_id, {"deleted": "1", "deleted_at": now, "updated_at": now})
return {"id": env_id, "deleted": True}
@@ -17579,16 +18045,23 @@ async def delete_harness(org: str, hid: str, request: Request) -> dict:
_caller = await _owned_org(request, org)
# V1C02-005: only delete a harness that belongs to the caller's org.
cur = await _harness_in_reach(_caller, hid, deleted_ok=True)
- cur = await _mcp_migrate(org, hid, cur)
- await _vg_upsert("Harness", hid, {"deleted": "1"})
- # a deleted agent must not still be holding a database password, and must not still be
- # spending at a provider
- await _hosted_scrub_removed(org, hid, _mcp_list(cur), [])
- await _media_harness_purge(hid)
- await _plugins_discard(org, cur)
+ await _harness_delete(org, hid, cur)
return {"id": hid, "deleted": True}
+async def _harness_delete(org: str, hid: str, v: dict) -> None:
+ """The one delete both routes call. The harness is kept 30 days, restorable, and then removed
+ with its plugin packages by the retention sweep (Richard's rule, 2026-10-08); the sessions and
+ responses that used it are not touched (Harnesses §5.3). What cannot wait goes now: a deleted
+ agent must not still be holding a database password, and must not still be spending at a
+ provider. A second delete keeps the first one's time, so it cannot extend the 30 days."""
+ v = await _mcp_migrate(org, hid, v)
+ if str(v.get("deleted")) not in ("1", "true", "True") or not v.get("deleted_at"):
+ await _vg_upsert("Harness", hid, {"deleted": "1", "deleted_at": str(_now_ms())})
+ await _hosted_scrub_removed(org, hid, _mcp_list(v), [])
+ await _media_harness_purge(hid)
+
+
# ── workspaces: the DIRECTORY, server-side (fix for the localStorage split-brain) ──────
# Harnesses, tasks and keys were always stamped with a workspace id in the store — but the
# REGISTRY of workspaces (id, name, description) had no server-side home on self-host: the
@@ -18734,11 +19207,5 @@ async def delete_harness_public(hid: str, request: Request) -> dict:
_caller = await _pub_principal(request)
org = _caller["org"]
v = await _harness_in_reach(_caller, hid, deleted_ok=True)
- v = await _mcp_migrate(org, hid, v)
- await _vg_upsert("Harness", hid, {"deleted": "1"})
- # a deleted agent must not still be holding a database password, and must not still be
- # spending at a provider
- await _hosted_scrub_removed(org, hid, _mcp_list(v), [])
- await _media_harness_purge(hid)
- await _plugins_discard(org, v)
+ await _harness_delete(org, hid, v)
return {"id": hid, "deleted": True}
diff --git a/gateway/backing.py b/gateway/backing.py
index 0c122121..885010b4 100644
--- a/gateway/backing.py
+++ b/gateway/backing.py
@@ -34,6 +34,7 @@ import mimetypes
import os
import posixpath
import re
+import shutil
import sqlite3
import tarfile
import time
@@ -271,6 +272,28 @@ class FileBlobStore:
return True
return await asyncio.to_thread(_do)
+ async def purge(self, kb: str, prefix: str) -> None:
+ """Remove everything under a folder-shaped prefix ("sessions/<sid>/"), including the
+ temporary files a torn write leaves and `list` does not show. A deleted session's folder
+ held a lone `changed.json.tmp` after every listed object was gone (hr-test copy,
+ 2026-10-08)."""
+ def _do():
+ base = (self._root / kb).resolve()
+ if not prefix.endswith("/") or prefix.strip("/") == "":
+ return
+ top = (base / prefix).resolve()
+ if top == base or base not in top.parents or not top.is_dir():
+ return
+ shutil.rmtree(top, ignore_errors=True)
+ for parent in top.parents:
+ if parent == base or base not in parent.parents:
+ break
+ try:
+ parent.rmdir()
+ except OSError:
+ break
+ await asyncio.to_thread(_do)
+
async def list(self, kb: str, prefix: str, limit: int = 20, cursor: str | None = None) -> dict:
# Walk only the subtree the prefix names: everything before its last "/" is a directory
# under the store, the rest a name prefix inside it. Walking the whole store cost every
@@ -408,6 +431,28 @@ class FileSecretStore:
self._p(tenant, name).unlink()
await asyncio.to_thread(_do)
+ async def blank(self) -> list[tuple[str, str]]:
+ """Every stored secret whose value is empty, as (tenant, name). Before 0.32.0 a removed
+ credential was overwritten with nothing rather than deleted; the retention sweep removes
+ those files. A value that cannot be opened (encrypted, and no key) is not reported."""
+ def _do():
+ out: list[tuple[str, str]] = []
+ if not self._root.is_dir():
+ return out
+ for tdir in sorted(self._root.iterdir()):
+ if not tdir.is_dir():
+ continue
+ for f in sorted(tdir.iterdir()):
+ if not f.is_file():
+ continue
+ try:
+ if self._open(f.read_text()) == "":
+ out.append((tdir.name, f.name))
+ except Exception: # noqa: BLE001 — unreadable is not empty
+ continue
+ return out
+ return await asyncio.to_thread(_do)
+
# ── selection ─────────────────────────────────────────────────────────────────────
diff --git a/gateway/tests/test_database_mcp.py b/gateway/tests/test_database_mcp.py
index 81a45765..6ac5f908 100644
--- a/gateway/tests/test_database_mcp.py
+++ b/gateway/tests/test_database_mcp.py
@@ -342,9 +342,9 @@ def test_deleting_the_harness_does_not_leave_the_credential_behind(api, connecte
assert PG_DSN == (_record(connected) or {})["dsn"]
assert api.delete(f"/v1/harnesses/{connected}").json()["deleted"] is True
- # The file may remain (the store has no delete); what it holds must not.
+ # Removed, not overwritten: a credential goes at once and for good (2026-10-08).
assert not asyncio.run(app.BACKING.secrets.get(app._tenants_for(ORG)[0], key))
- assert PASSWORD not in stored.read_text()
+ assert not stored.exists()
def test_another_org_cannot_see_or_use_a_database(client, api, connected):
diff --git a/gateway/tests/test_retention.py b/gateway/tests/test_retention.py
new file mode 100644
index 00000000..7a267196
--- /dev/null
+++ b/gateway/tests/test_retention.py
@@ -0,0 +1,418 @@
+"""What a delete removes, and when: Richard's rule (2026-10-08), the same as the hosted service's.
+
+For good, at once: a task (its session, with everything it left), an API key, a credential.
+Kept 30 days, restorable, then removed by the retention sweep: a harness, a response deleted on
+its own, an environment, an upload.
+
+Every test reads the stores back on disk: a record that is only marked deleted, or a file that is
+only unreachable through the API, fails it.
+"""
+import asyncio
+import json
+import pathlib
+import sqlite3
+import sys
+import uuid
+
+import pytest
+from fastapi import HTTPException
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+import app as gw # noqa: E402
+
+ORG = "local"
+ME = {"org": ORG, "member": "owner", "workspace": "", "workspace_default": False}
+DAY = 86_400_000
+
+
+class _Req:
+ def __init__(self):
+ self.headers, self.method = {}, "DELETE"
+ self.url = type("U", (), {"path": "/"})()
+
+
+def run(coro):
+ return asyncio.run(coro)
+
+
[email protected](autouse=True)
+def as_owner(monkeypatch):
+ async def who(request):
+ return dict(ME)
+
+ async def owned_org(request, org):
+ return dict(ME)
+ monkeypatch.setattr(gw, "_principal", who)
+ monkeypatch.setattr(gw, "_pub_principal", who)
+ monkeypatch.setattr(gw, "_owned_org", owned_org)
+ monkeypatch.setattr(gw.control_store, "enabled", lambda: False)
+
+
+def _files_naming(token: str) -> list[str]:
+ """Every stored file whose path names the token, in the blob and secret stores the server
+ uses (read off the stores: another test module may have pointed them elsewhere)."""
+ roots = (gw.BACKING.blob._root, gw.BACKING.secrets._root)
+ return [str(p) for r in roots if r.exists() for p in r.rglob("*") if p.is_file() and token in str(p)]
+
+
+def _rows_naming(token: str) -> list[tuple]:
+ """Every graph record whose id or properties name the token."""
+ with sqlite3.connect(gw.BACKING.graph._path) as c:
+ return c.execute("SELECT vid, label FROM vertices WHERE vid LIKE ? OR props LIKE ?",
+ (f"%{token}%", f"%{token}%")).fetchall()
+
+
+def _blob(key, kb=None):
+ return run(gw._blob_get(key, kb=kb or gw.BLOB_KB))
+
+
+def _put(key, data: bytes, kb=None):
+ assert run(gw._blob_put(key, data, kb=kb or gw.BLOB_KB))
+
+
+def _sweep(at_ms=None, **kw):
+ """The sweep as it runs on a given day."""
+ real = gw._now_ms
+ if at_ms is not None:
+ gw._now_ms = lambda: at_ms
+ try:
+ return run(gw._retention_sweep(kw.pop("dry_run", False), **kw))
+ finally:
+ gw._now_ms = real
+
+
+def _restore(kind, iid):
+ return run(gw.retention_restore(gw.RetentionRestoreBody(kind=kind, id=iid)))
+
+
+def _status(coro) -> int:
+ with pytest.raises(HTTPException) as e:
+ asyncio.run(coro)
+ return e.value.status_code
+
+
+# ── a task: everything it left, at once ─────────────────────────────────────────────────────
+def _a_session_with_everything() -> tuple[str, str]:
+ sid = "hsess_" + uuid.uuid4().hex
+ rid = "resp_" + uuid.uuid4().hex
+ base = f"{ORG}/9999_{sid}"
+ run(gw.BACKING.graph.upsert("HarnessSession", sid, {
+ "tenant": ORG, "workspace": "", "harness_id": "chrn_x", "member_id": "owner", "status": "idle",
+ "title": "Quarterly numbers for the board", "trace_blob": base, "checkpoint_bytes": "10"}))
+ # the transcript and trace
+ _put(gw._manifest_key(base), json.dumps({"session_id": sid, "chunks": ["events/0001.jsonl"]}).encode(), gw.TRACE_KB)
+ _put(f"{base}/events/0001.jsonl", b'{"text": "the board numbers"}', gw.TRACE_KB)
+ _put(f"{base}/all.jsonl", b"transcript", gw.TRACE_KB)
+ # a response
+ run(gw._resp_put(rid, {"id": rid, "status": "completed", "output": [{"text": "the answer"}]},
+ ORG, sid, None, "completed", 1.0, True))
+ # produced files, their previews, the change list, the checkpoint, media and its scene
+ _put(f"containers/{sid}/report.pdf", b"%PDF report", gw.RESP_BLOB_KB)
+ _put(f"containers/{sid}/report.pdf.meta", b"{}", gw.RESP_BLOB_KB)
+ _put(f"previews/{sid}/f1/page-1.png", b"png", gw.RESP_BLOB_KB)
+ _put(f"sessions/{sid}/changed.json", b'{"files": ["report.pdf"]}', gw.RESP_BLOB_KB)
+ _put(gw._ws_blob(sid), b"tarball")
+ _put(f"media/{sid}/m1.mp4", b"video")
+ _put(gw._media_scene_key(sid), b"{}")
+ # a torn write: the temporary file a listing does not show
+ torn = gw.BACKING.blob._root / gw.RESP_BLOB_KB / "sessions" / sid / "changed.json.tmp"
+ torn.parent.mkdir(parents=True, exist_ok=True)
+ torn.write_bytes(b'{"files": [')
+ run(gw.BACKING.graph.upsert(gw._MEDIA_JOB_LABEL, "mjob_" + uuid.uuid4().hex[:16],
+ {"session": sid, "status": "done", "prompt": "a sunrise"}))
+ # a plugin call
+ run(gw.BACKING.graph.upsert(gw._PLUG_CALL_LABEL, "pcall_" + uuid.uuid4().hex,
+ {"session": sid, "tool": "create_issue", "usd": "0.0"}))
+ return sid, rid
+
+
+def test_a_deleted_task_leaves_no_file_and_no_record_but_a_marker():
+ sid, rid = _a_session_with_everything()
+ assert len(_files_naming(sid)) >= 9 and len(_rows_naming(sid)) >= 4 # the fixture is real
+
+ out = run(gw.delete_trace(sid, _Req()))
+ assert out == {"id": sid, "object": "session", "deleted": True}
+
+ assert _files_naming(sid) == []
+ assert _files_naming(rid) == []
+ assert _rows_naming(sid) == [(sid, "HarnessSession")] # the marker, and nothing else
+ marker = run(gw.BACKING.graph.get(sid))
+ assert marker["status"] == "deleted" and marker["shared"] == "0" and marker.get("deleted_at")
+ assert set(marker) - {"id"} <= set(gw._SESSION_MARKER)
+ assert "title" not in marker and "checkpoint_bytes" not in marker
+ assert _status(gw._owned_session(_Req(), sid)) == 404
+
+
+def test_the_marker_goes_a_day_later_and_cannot_be_restored():
+ sid, _ = _a_session_with_everything()
+ run(gw.delete_trace(sid, _Req()))
+ now = gw._now_ms()
+ assert sid not in _sweep(now + DAY // 2)["removed"]["sessions"]
+ assert _sweep(now + DAY + 1000)["removed"]["sessions"].count(sid) == 1
+ assert _rows_naming(sid) == []
+ assert _status(gw.retention_restore(gw.RetentionRestoreBody(kind="sessions", id=sid))) == 409
+
+
+def test_a_task_deleted_before_this_version_loses_what_it_left_on_the_first_sweep():
+ """The volumes this version starts on: a tombstone with everything still beside it."""
+ sid, rid = _a_session_with_everything()
+ run(gw.BACKING.graph.upsert("HarnessSession", sid, {"status": "deleted", "shared": "0"}))
+ assert _files_naming(sid)
+ res = _sweep()
+ assert sid in res["removed"]["sessions"] and res["no_delete_time"].get("sessions", 0) >= 1
+ assert _files_naming(sid) == [] and _files_naming(rid) == [] and _rows_naming(sid) == []
+
+
+# ── a response: 30 days, restorable ─────────────────────────────────────────────────────────
+def _a_response() -> str:
+ sid = "hsess_" + uuid.uuid4().hex
+ rid = "resp_" + uuid.uuid4().hex
+ run(gw.BACKING.graph.upsert("HarnessSession", sid, {"tenant": ORG, "workspace": "", "status": "idle"}))
+ run(gw._resp_put(rid, {"id": rid, "_org": ORG, "_session_id": sid, "status": "completed"},
+ ORG, sid, None, "completed", 1.0, True))
+ return rid
+
+
+def test_a_deleted_response_is_kept_30_days_restorable_then_removed():
+ rid = _a_response()
+ run(gw.delete_response(rid, _Req()))
+ assert run(gw._resp_get(rid)) is None # unreadable at once
+ now = gw._now_ms()
+ assert rid not in _sweep(now + 29 * DAY)["removed"]["responses"]
+ assert _restore("responses", rid) == {"kind": "responses", "id": rid, "restored": True}
+ assert run(gw._resp_get(rid))["status"] == "completed"
+ assert run(gw.BACKING.graph.get(rid))["status"] == "completed"
+
+ run(gw.delete_response(rid, _Req()))
+ assert rid in _sweep(gw._now_ms() + 30 * DAY + 1000)["removed"]["responses"]
+ assert _files_naming(rid) == [] and _rows_naming(rid) == []
+ assert _status(gw.retention_restore(gw.RetentionRestoreBody(kind="responses", id=rid))) == 410
+
+
+# ── a harness: its credentials at once, the rest after 30 days ─────────────────────────────
+def _a_harness(*, blob="", plugin_blob="") -> tuple[str, str]:
+ hid = "chrn_" + uuid.uuid4().hex
+ key = gw._hosted_secret_key(hid, "mcp.database")
+ run(gw._hosted_put_record(ORG, key, {"server": "database", "harness": hid, "engine": "postgres",
+ "dsn": "postgres://u:[email protected]/x"}))
+ servers = [{"id": "mcp.database", "name": "database", "url": "https://gateway.example/x", "auth": f"vault:{key}"}]
+ skills = [{"name": "big", "blob": blob}] if blob else []
+ plugins = [{"name": "kit", "blob": plugin_blob}] if plugin_blob else []
+ run(gw.BACKING.graph.upsert("Harness", hid, {
+ "org": ORG, "workspace": "", "name": "Analyst", "deleted": "0", "mcp_servers": json.dumps(servers),
+ "skills": json.dumps(skills), "plugins": json.dumps(plugins), "updated_at": str(gw._now_ms())}))
+ run(gw._connection_vertex_put(ORG, hid, {"workspace": ""}, "mcp.database", key, "postgres", "db.example", "x", False))
+ return hid, key
+
+
+def _secret_file(key: str) -> list[str]:
+ return [str(p) for p in gw.BACKING.secrets._root.rglob("*") if p.is_file() and p.name == key]
+
+
+def test_a_deleted_harness_loses_its_credential_at_once_and_comes_back_without_it():
+ hid, key = _a_harness()
+ assert _secret_file(key) and run(gw.BACKING.graph.find(gw._CONNECTION_LABEL, {"harness": hid}))
+ run(gw.delete_harness_public(hid, _Req()))
+ assert _secret_file(key) == [] # removed, not overwritten
+ assert run(gw.BACKING.graph.find(gw._CONNECTION_LABEL, {"harness": hid})) == []
+ v = run(gw.BACKING.graph.get(hid))
+ assert v["deleted"] == "1" and v.get("deleted_at")
+ assert _status(gw._harness_in_reach(ME, hid)) == 404
+
+ assert _restore("harnesses", hid)["restored"] is True
+ assert run(gw._harness_in_reach(ME, hid))["name"] == "Analyst"
+ assert _secret_file(key) == []
+
+
+def test_a_harness_is_removed_after_30_days_with_its_bundles_unless_another_names_one():
+ shared = "skb_" + uuid.uuid4().hex
+ own = "skb_" + uuid.uuid4().hex
+ pkg = uuid.uuid4().hex
+ hid, _ = _a_harness(blob=own, plugin_blob=pkg)
+ other, _ = _a_harness(blob=shared)
+ run(gw.BACKING.graph.upsert("Harness", hid, {"skills": json.dumps([{"name": "a", "blob": own}, {"name": "b", "blob": shared}])}))
+ for b in (own, shared):
+ _put(f"skills/{b}.json", b"[]")
+ _put(gw._plugin_blob_key(ORG, pkg), b"{}")
+
+ run(gw.delete_harness_public(hid, _Req()))
+ assert _blob(f"skills/{own}.json") and _blob(gw._plugin_blob_key(ORG, pkg)) # kept for a restore
+ assert hid not in _sweep(gw._now_ms() + 29 * DAY)["removed"]["harnesses"]
+ assert hid in _sweep(gw._now_ms() + 30 * DAY + 1000)["removed"]["harnesses"]
+ assert run(gw.BACKING.graph.get(hid)) is None and _rows_naming(hid) == []
+ assert _blob(f"skills/{own}.json") is None and _blob(gw._plugin_blob_key(ORG, pkg)) is None
+ assert _blob(f"skills/{shared}.json") == b"[]" # the other harness still names it
+ assert _status(gw.retention_restore(gw.RetentionRestoreBody(kind="harnesses", id=hid))) == 410
+ assert run(gw.BACKING.graph.get(other))["deleted"] == "0"
+
+
+def test_a_harness_deleted_before_this_version_counts_from_its_last_task_too():
+ """Its last edit was 40 days ago, but it ran a task 3 days ago, so its delete came after that."""
+ hid, _ = _a_harness()
+ now = gw._now_ms()
+ run(gw.BACKING.graph.upsert("Harness", hid, {"deleted": "1", "updated_at": str(now - 40 * DAY)}))
+ run(gw.BACKING.graph.upsert("HarnessSession", "hsess_" + uuid.uuid4().hex,
+ {"tenant": ORG, "harness_id": hid, "status": "idle", "updated_at": str(now - 3 * DAY)}))
+ assert hid not in _sweep(dry_run=True, kinds=["harnesses"])["would_remove"]["harnesses"]
+ assert hid in _sweep(now + 28 * DAY, dry_run=True, kinds=["harnesses"])["would_remove"]["harnesses"]
+
+
+def test_a_harness_deleted_before_this_version_counts_from_its_last_write():
+ old, _ = _a_harness()
+ recent, _ = _a_harness()
+ now = gw._now_ms()
+ run(gw.BACKING.graph.upsert("Harness", old, {"deleted": "1", "updated_at": str(now - 40 * DAY)}))
+ run(gw.BACKING.graph.upsert("Harness", recent, {"deleted": "1", "updated_at": str(now - 5 * DAY)}))
+ dry = _sweep(dry_run=True, kinds=["harnesses"])
+ assert old in dry["would_remove"]["harnesses"] and recent not in dry["would_remove"]["harnesses"]
+ assert dry["no_delete_time"]["harnesses"] >= 1 and dry["done"] is False
+ assert run(gw.BACKING.graph.get(old)) is not None # a dry run removes nothing
+ res = _sweep(kinds=["harnesses"])
+ assert old in res["removed"]["harnesses"] and run(gw.BACKING.graph.get(old)) is None
+ assert run(gw.BACKING.graph.get(recent))["deleted"] == "1"
+
+
+# ── an API key: at once ─────────────────────────────────────────────────────────────────────
+def test_a_revoked_key_is_removed_at_once_and_no_longer_opens_anything():
+ tok = "sk-hr-" + uuid.uuid4().hex
+ sha = gw._hash_key(tok)
+ run(gw.BACKING.graph.upsert("HarnessApiKey", sha, {"kind": "harness_api_key", "org": ORG, "member": "owner",
+ "name": "laptop", "revoked": "0"}))
+ assert run(gw._apikey_resolve(tok))["org"] == ORG
+ assert run(gw.revoke_key(ORG, sha, _Req())) == {"id": sha, "revoked": True}
+ assert run(gw.BACKING.graph.get(sha)) is None and _rows_naming(sha) == []
+ assert run(gw._apikey_resolve(tok)) is None
+ assert _status(gw.retention_restore(gw.RetentionRestoreBody(kind="api_keys", id=sha))) == 409
+
+
+def test_keys_revoked_before_this_version_are_removed_by_the_sweep():
+ sha = gw._hash_key("sk-hr-" + uuid.uuid4().hex)
+ run(gw.BACKING.graph.upsert("HarnessApiKey", sha, {"kind": "harness_api_key", "org": ORG, "revoked": "1"}))
+ assert sha in _sweep(kinds=["api_keys"])["removed"]["api_keys"]
+ assert run(gw.BACKING.graph.get(sha)) is None
+
+
+# ── credentials blanked by an older version ─────────────────────────────────────────────────
+def test_credentials_an_older_version_only_blanked_are_removed():
+ blank = "harness-hosted-" + uuid.uuid4().hex[:12]
+ kept = "harness-mcp-" + uuid.uuid4().hex[:12]
+ run(gw.BACKING.secrets.put(ORG, blank, "", require_encryption=True))
+ run(gw.BACKING.secrets.put(ORG, kept, "a-live-token"))
+ cid = "hconn_" + uuid.uuid4().hex[:24]
+ run(gw.BACKING.graph.upsert(gw._CONNECTION_LABEL, cid, {"harness": "chrn_x", "host": "db.example", "deleted": "1"}))
+ res = _sweep(kinds=["credentials"])
+ assert f"secret:{ORG}/{blank}" in res["removed"]["credentials"] and cid in res["removed"]["credentials"]
+ assert _secret_file(blank) == [] and run(gw.BACKING.graph.get(cid)) is None
+ assert run(gw.BACKING.secrets.get(ORG, kept)) == "a-live-token"
+
+
+def test_a_stored_tool_token_can_be_deleted():
+ run(gw.put_mcp_secret(ORG, "Linear Token", gw.McpSecretBody(token="lin_live"), _Req()))
+ key = gw._MCP_SECRET_PREFIX + "linear-token"
+ assert _secret_file(key)
+ assert run(gw.delete_mcp_secret(ORG, "Linear Token", _Req()))["deleted"] is True
+ assert _secret_file(key) == []
+
+
+# ── an environment: its path at once, its files after 30 days ───────────────────────────────
+def _an_environment(monkeypatch, slug=None):
+ calls = []
+
+ class _R:
+ status_code = 200
+
+ async def runner(method, path, env_id, **kw):
+ calls.append((method, path, (kw.get("params") or {}).get("slug", "")))
+ return _R()
+ monkeypatch.setattr(gw, "_env_runner", runner)
+
+ async def refresh(v):
+ return v
+ monkeypatch.setattr(gw, "_environment_refresh", refresh)
+ eid = "henv_" + uuid.uuid4().hex
+ slug = slug or "env-" + uuid.uuid4().hex[:8]
+ run(gw.BACKING.graph.upsert("Environment", eid, {"org": ORG, "workspace": "", "name": slug, "slug": slug,
+ "status": "ready", "deleted": "0", "updated_at": str(gw._now_ms())}))
+ return eid, slug, calls
+
+
+def test_a_deleted_environment_frees_its_path_keeps_its_files_30_days_then_goes(monkeypatch):
+ eid, slug, calls = _an_environment(monkeypatch)
+ run(gw.delete_environment(eid, _Req()))
+ assert calls == [("DELETE", f"/environments/{eid}/mount", slug)] # the path, not the files
+ assert run(gw.BACKING.graph.get(eid))["deleted"] == "1"
+ assert _restore("environments", eid)["restored"] is True
+ run(gw.delete_environment(eid, _Req()))
+ calls.clear()
+ assert eid in _sweep(gw._now_ms() + 30 * DAY + 1000, kinds=["environments"])["removed"]["environments"]
+ assert calls == [("DELETE", f"/environments/{eid}", "")] # never the name: it may be another's
+ assert run(gw.BACKING.graph.get(eid)) is None
+
+
+def test_an_environment_whose_name_was_taken_is_not_restored_over_the_new_one(monkeypatch):
+ eid, slug, _ = _an_environment(monkeypatch)
+ run(gw.delete_environment(eid, _Req()))
+ _an_environment(monkeypatch, slug=slug)
+ assert _status(gw.retention_restore(gw.RetentionRestoreBody(kind="environments", id=eid))) == 409
+
+
+def test_an_environment_whose_runner_did_not_answer_is_left_and_said_so(monkeypatch):
+ eid, _, _ = _an_environment(monkeypatch)
+ run(gw.delete_environment(eid, _Req()))
+
+ async def down(method, path, env_id, **kw):
+ raise gw.uhp_error(502, "environment_unavailable", "The runner did not answer.")
+ monkeypatch.setattr(gw, "_env_runner", down)
+ res = _sweep(gw._now_ms() + 31 * DAY, kinds=["environments"])
+ assert eid not in res["removed"]["environments"] and res["left"]["environments"] and res["done"] is False
+ assert run(gw.BACKING.graph.get(eid)) is not None
+
+
+# ── an upload: DELETE /v1/files/{id}, 30 days, restorable ───────────────────────────────────
+def _an_upload(org=ORG) -> str:
+ fid = "file_" + uuid.uuid4().hex
+ _put(f"uploads/{fid}", b"q3 numbers", gw.RESP_BLOB_KB)
+ _put(f"uploads/{fid}.meta", json.dumps({"filename": "q3.csv", "media_type": "text/csv", "org": org}).encode(), gw.RESP_BLOB_KB)
+ return fid
+
+
+def test_a_deleted_upload_is_refused_to_tasks_restorable_then_removed():
+ fid = _an_upload()
+ assert run(gw.delete_file(fid, _Req())) == {"id": fid, "object": "file", "deleted": True}
+ assert _status(gw._resolve_uploads([{"file_id": fid}], ORG)) == 404
+ assert _status(gw.delete_file(fid, _Req())) == 404
+ assert _restore("uploads", fid)["restored"] is True
+ files = [{"file_id": fid}]
+ run(gw._resolve_uploads(files, ORG))
+ assert files[0]["filename"] == "q3.csv"
+
+ run(gw.delete_file(fid, _Req()))
+ assert fid not in _sweep(gw._now_ms() + 29 * DAY, kinds=["uploads"])["removed"]["uploads"]
+ assert fid in _sweep(gw._now_ms() + 30 * DAY + 1000, kinds=["uploads"])["removed"]["uploads"]
+ assert _files_naming(fid) == []
+ assert _status(gw.retention_restore(gw.RetentionRestoreBody(kind="uploads", id=fid))) == 410
+
+
+def test_another_organizations_upload_cannot_be_deleted():
+ fid = _an_upload(org="org-other")
+ assert _status(gw.delete_file(fid, _Req())) == 404
+ assert _blob(f"uploads/{fid}", gw.RESP_BLOB_KB) == b"q3 numbers"
+
+
+# ── the sweep itself ────────────────────────────────────────────────────────────────────────
+def test_a_capped_sweep_says_when_it_is_done():
+ rids = [_a_response() for _ in range(3)]
+ for rid in rids:
+ run(gw.delete_response(rid, _Req()))
+ later = gw._now_ms() + 31 * DAY
+ first = _sweep(later, kinds=["responses"], limit=2)
+ assert len(first["removed"]["responses"]) == 2 and first["done"] is False
+ rest = _sweep(later, kinds=["responses"], limit=50)
+ assert set(first["removed"]["responses"]) | set(rest["removed"]["responses"]) >= set(rids)
+ assert rest["done"] is True
+
+
+def test_the_sweep_route_refuses_a_kind_it_does_not_know_and_skips_hosted_only_ones():
+ assert _status(gw.retention_sweep(gw.RetentionSweepBody(dry_run=True, kinds=["sessionz"]))) == 400
+ out = run(gw.retention_sweep(gw.RetentionSweepBody(dry_run=True, kinds=["arenas"])))
+ assert out["dry_run"] is True and "would_remove" in out and out["done"] is True # nothing due
diff --git a/runner/environments.py b/runner/environments.py
index 8d8aff34..36f1fe3b 100644
--- a/runner/environments.py
+++ b/runner/environments.py
@@ -979,15 +979,24 @@ def ensure_mount(env_id: str, slug: str) -> str:
return link
-def drop_mount(slug: str) -> None:
- link = mount_path(slug)
- if os.path.islink(link):
- os.unlink(link)
+def drop_mount(slug: str, env_id: str = "") -> None:
+ """Take the path down. Given the environment, only while the path is still that environment's:
+ a deleted environment's name is free at once, and another environment may hold it by the time
+ this one is removed for good."""
+ base = os.path.realpath(ENV_MOUNT)
+ link = os.path.normpath(os.path.join(base, str(slug or "")))
+ if not slug_ok(slug) or not link.startswith(base + os.sep):
+ raise HTTPException(400, "environment slug is not a path segment")
+ if not os.path.islink(link):
+ return
+ if env_id and os.readlink(link) != str(active_link(env_id)):
+ return
+ os.unlink(link)
def delete_environment(env_id: str, slug: str = "") -> dict:
if slug:
- drop_mount(slug)
+ drop_mount(slug, env_id)
d = env_dir(env_id)
if d.exists():
shutil.rmtree(d, ignore_errors=True)
@@ -1156,6 +1165,13 @@ def r_delete_env(env_id: str, slug: str = "") -> dict:
return delete_environment(env_id, slug)
[email protected]("/environments/{env_id}/mount")
+def r_unmount_env(env_id: str, slug: str) -> dict:
+ """A deleted environment, kept for 30 days: its files stay, its path goes."""
+ drop_mount(slug, env_id)
+ return {"id": env_id, "mounted": False}
+
+
@router.get("/environments/{env_id}")
def r_get(env_id: str) -> JSONResponse:
return JSONResponse({"id": env_id, "source": source_stat(env_id), "versions": versions(env_id),
diff --git a/runner/tests/test_environments.py b/runner/tests/test_environments.py
index 59b27fd8..f256884a 100644
--- a/runner/tests/test_environments.py
+++ b/runner/tests/test_environments.py
@@ -363,3 +363,31 @@ def test_a_git_import_lands_files_and_directories_and_never_follows_a_link(store
assert os.stat(src / "src" / "run.sh").st_mode & 0o111
assert "HR_SECRET_KEY" not in seen["env"] and "HARNESS_INTERNAL_KEY" not in seen["env"]
assert seen["env"]["GIT_TERMINAL_PROMPT"] == "0"
+
+
+def test_a_deleted_environment_takes_down_only_its_own_path(store):
+ """Deleting keeps the files for 30 days and frees the name at once; by the time the files go,
+ another environment may be mounted under that name, and its path must stay."""
+ def point(env_id, slug):
+ E.env_dir(env_id).mkdir(parents=True, exist_ok=True)
+ os.makedirs(E.ENV_MOUNT, exist_ok=True)
+ link = E.mount_path(slug)
+ if os.path.lexists(link):
+ os.unlink(link)
+ os.symlink(str(E.active_link(env_id)), link)
+
+ a, b = "henv_" + "a" * 32, "henv_" + "b" * 32
+ point(a, "data")
+ E.drop_mount("data", a) # the delete: its path goes, its files stay
+ assert not os.path.lexists(E.mount_path("data")) and E.env_dir(a).is_dir()
+ point(b, "data") # the name is taken by another environment
+ E.drop_mount("data", a)
+ E.delete_environment(a) # the sweep, 30 days later: no name given
+ assert os.readlink(E.mount_path("data")) == str(E.active_link(b))
+ assert not E.env_dir(a).exists()
+
+
+def test_taking_a_path_down_refuses_a_name_that_is_not_one_segment(store):
+ for slug in ("../outside", "a/b", "", ".."):
+ with pytest.raises(HTTPException):
+ E.drop_mount(slug, "henv_" + "a" * 32)