Skip to content

feat(provisioner): sweep orphaned workload sandboxes (phase 2) - #615

Merged
pdettori merged 2 commits into
rossoctl:mainfrom
moonlight16:feat/workload-reconciler
Oct 27, 2026
Merged

pdettori merged 2 commits into
rossoctl:mainfrom
moonlight16:feat/workload-reconciler

Conversation

@moonlight16

@moonlight16 moonlight16 commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

This closes the last open acceptance item of #476 (per-workload sandboxes and storage): when a workload's delete fails partway, its sandbox objects no longer stay behind forever. The provisioner now finds them and deletes them.

How it works today

  1. DELETE /workloads/{id} asks the provisioner to remove the workload's StatefulSet (its sandbox pods), Service, Secret (its attach token) and PVC (its storage).
  2. If the pods are slow to stop, the worker answers 202 and the record stays deleting until the client repeats the DELETE.
  3. If the client never repeats it, or the record is lost, the objects stay forever and keep counting against the owner's sandbox cap.

What this PR changes

  1. Every MOCA_PROVISIONER_RECONCILE_S (default 5 minutes), the provisioner loop that already renews tokens also lists the workloads' StatefulSets, Services and PVCs.

  2. For each workload, it reads the workload's record from Redis (read-only). Each read times out after MOCA_PROVISIONER_REDIS_TIMEOUT_MS (default 2 seconds): that workload is skipped for the pass, and a hung Redis never blocks the owner's other requests or the next pass.

  3. It deletes a workload's objects only when both are true:

    • the record is missing, deleted, deleting or from another generation;
    • all of the workload's objects are older than MOCA_PROVISIONER_ORPHAN_GRACE_S (default 10 minutes).

    The delay keeps it away from a workload that's still being created. A live workload is never deleted, however old.

    When the record is only missing, it deletes the StatefulSet, Secret and Service (freeing the sandboxes and the cap) but keeps the PVC, and logs it. The PVC is deleted only for deleted, deleting or another generation.

  4. Before deleting, it re-reads the objects and the record under the owner's queue, so it can't race that owner's create or delete. It deletes in DELETE's order: StatefulSet, Secret, Service, PVC last. One failing workload never stops the others.

  5. For deleting records, it finishes the sandbox side; the owner repeats the DELETE to remove the Context.

Safety

  • It only deletes. It creates and signs nothing, so a forged record (spec §9) can cause denial of service at most.
  • A missing record never deletes a workload's storage: an emptied or wrong Redis looks the same as a lost record. The docs say how to remove a kept PVC by hand.
  • If most records are missing at once (at least 2, and more than half of those read), the pass deletes nothing and logs ORPHAN SWEEP ABORTED.
  • Every Redis read times out, so a Redis that stops answering can't stall the sweep or the owner's queue.
  • It uses the deployment's one read-write Redis password (there are no Redis ACL users yet); spec §9 now says so.
  • Anything it can't match to its record (missing or bad annotations, objects that disagree, a record it can't parse) is logged and skipped, never deleted. No pass runs while Redis is down.
  • The provisioner still can't read Secrets; it deletes them by their known name. Its role gains only list on Services and PVCs.
  • It gets Redis access through its own NetworkPolicy (a network firewall rule), limited to Redis and DNS.
  • Default installs are unchanged; everything ships in the opt-in workload-sandboxes component.

Tested

  • Unit tests with a fake Kubernetes API, plus one against real Redis. They cover each record state, the grace period, malformed annotations, failure isolation, a sweep racing a create, and the owner's cap freed afterwards.
  • On Kind with SH_WORKLOAD_SANDBOXES=1:
    • a workload whose record was deleted, and one marked deleted, both lost all four objects after the grace period (run before the review fixes; a workload whose record is gone now keeps its PVC, covered by unit tests);
    • a live workload was untouched;
    • workload-admission.sh passed 52 of 52, including the new permission checks.

🤖 Generated with Claude Code

@pdettori pdettori added the ready-for-ai-review Request automated AI code review from clawgenti label Oct 26, 2026

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

The orphan judgement is sound. The record is always written before any Kubernetes object. Only a missing, deleted/deleting or other-generation record with every object older than the grace leads to a delete, and it's re-checked against fresh reads under the owner's queue. One failing workload doesn't stop the pass, and passes can't overlap. RBAC adds only namespaced list on services and PVCs, the Redis egress NetworkPolicy is scoped to same-namespace app: redis:6379, redis ^6.3.0 is already in the workspace (no new transitive packages), and the env var docs match the code. One must-fix: the Redis read has no timeout, so a hung Redis stalls the sweep forever and blocks the owner's PUT/DELETE queue. There are also two safety suggestions: an emptied Redis would wipe every workload, and the credential is broader than "GET only".

Author: moonlight16 (MEMBER — maintainer)
Areas reviewed: TypeScript (provisioner), K8s manifests/RBAC/NetworkPolicy, Shell tests, Docs/spec, dependency manifest
Agent/IDE config (.claude/.vscode): none
Commits: 1 commit, all signed-off: yes
CI status: passing (including k8s-kind-e2e). Merges cleanly with #618, with no semantic interaction.

Comment thread packages/provisioner/src/provisioner.ts Outdated
const age = ageS(obj, nowOf(deps));
if (age === null || age < graceS) return 'kept';
}
const verdict = await judge(deps, k, recordKey, gen);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

must-fix: This second judge() runs inside serialized(k.own, …), and records.get() has no timeout. node-redis sets no command timeout by default (knative-server/src/server.ts:203 adds its own bound for this reason), and disableOfflineQueue only helps once the client knows it's disconnected. If Redis stops answering on a half-open or blackholed socket, isReady stays true and this GET hangs. That blocks the owner's queue, so every PUT, DELETE and re-mint for that owner hangs too, and running in orphanSweeper never clears, so no later pass starts. The first judge() at line 1067 stalls the same way, outside the queue. Please bound the GET (e.g. a Promise.race timeout in redisRecords().get, main.ts:84) and let a timeout count as failed for that workload. A test with a never-resolving records.get would pin this.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f8891ff. Every record read now times out (MOCA_PROVISIONER_REDIS_TIMEOUT_MS, default 2000), same Promise.race pattern as knative-server. A timeout on the first read fails that workload for the pass. A timeout on the read under the owner's queue throws out of serialized(), so the queue is released and nothing is deleted. Tests: a never-resolving GET on the first read, and on the queued read with a DELETE and a PUT waiting behind it (both finish within the timeout, the pass ends, and the next orphanSweeper pass runs).

Comment thread packages/provisioner/src/provisioner.ts Outdated
gen: string,
): Promise<Verdict> {
const raw = await deps.records.get(recordKey);
if (raw === null) return { keep: false, why: 'record missing' };

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: record missing alone is enough to delete, and it can't be told apart from an emptied or wrong Redis: lost AOF/PVC, a FLUSHALL, a restore, or REDIS_URL pointing at another instance or db index. The ready check only covers "unreachable". With an empty but reachable Redis, one pass after the grace deletes every workload's StatefulSet and PVC, including writable workspaces that exist nowhere else. Consider a cheap guard: abort the pass when all (or more than N%) of the listed records are missing; require two consecutive passes that see it missing; or never delete PVCs on missing, only on an explicit deleted/deleting or another generation.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done both in f8891ff. (a) If the first look finds at least 2 workloads and more than half of the records it read missing, the pass deletes nothing and logs ORPHAN SWEEP ABORTED (MISSING_ABORT_FRACTION / MISSING_ABORT_MIN in provisioner.ts). (b) A missing record alone never deletes the PVC: StatefulSet, Secret and Service go (freeing the sandboxes and the cap), and the claim is kept and logged 'kept PVC : record missing'. Only deleted/deleting or another generation deletes it. Lone kept claims don't count toward the guard on later passes. Spec §6.2 and docs/context-service.md say how to remove a kept PVC by hand.

- { name: MOCA_PROVISIONER_RECONCILE_S, value: '300' }
# The orphan sweep (spec §6.2), on the same loop: a workload's objects whose Redis record
# is missing, deleted, deleting or of another generation are deleted once all of them are
# older than this grace. It reads Redis with the deployment's one credential (GET only).

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: "GET only" describes this code, not the credential. REDIS_URL is the deployment's full read-write password, so the provisioner can now write sh:sandbox:records, and redis.yaml notes that whoever writes it picks the executor for every turn. The provisioner is also reachable from model code via the seed port. Either use a restricted ACL user (+get ~sh:wl:*), or update spec §9's "compromised provisioner" bullet. Also stale: deploy/k8s/README.md's moca-redis consumer list and rotation steps (no moca-provisioner restart), and redis.yaml's "only three callers" header.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Docs fixed in f8891ff: spec §9's compromised-provisioner bullet now says it holds the deployment's read-write Redis password, so it could write sh:sandbox:records. I also fixed the README moca-redis consumer list, the rotation steps (restart moca-provisioner), redis.yaml's header, and the 'GET only' comments. I didn't add an ACL user here because the deployment has no Redis ACL setup yet (spec §3.1). A restricted user would mean setup.sh generating and rotating a second credential plus redis.conf ACL lines, which is a change for every Redis caller, not just this sweep. I'd suggest a follow-up issue: 'Redis ACL users per component (provisioner: +get ~sh:wl:*)'.

await put;
expect(await sweep).toEqual({ swept: 0, skipped: 0, failed: 0 });
expect(left(r)).toMatchObject({ sts: true, svc: true, secret: true });
// The Service the PUT re-created is young: no delete was even judged for it.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: This race test passes because of the grace re-check, not the record re-check: the Service the PUT re-creates is young, so the age < graceS loop returns kept before the second judge() (provisioner.ts:1084) runs. Nothing covers the case that re-read exists for: all objects old, the record missing at first look, then live again by the time the sweep holds the owner's queue. Add a variant where the PUT blocks on something other than object creation, so the fresh judge() is what keeps them.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in f8891ff: all objects old, record missing at the first look, then live again when the sweep gets the owner's queue. The PUT blocks on its owner-cap list (it's a scale-up, so nothing gets re-created and nothing is young). The test checks that the second record read happens and keeps everything. I removed the second judge() locally and it fails (swept: 1).

Comment thread packages/provisioner/src/provisioner.ts Outdated
if ('bad' in keys) return skip(keys.bad);
const { k, recordKey, gen } = keys;
// Already going (a claim its finalizer holds until the pod is gone): nothing left to delete. The
// Secret went before the Service and claim (removeWorkload), so none is left behind unseen.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: "none is left behind unseen" only holds for deletes made with the new removeWorkload order. The old order (StatefulSet, Service, PVC, then Secret) can leave a lone <wl>-attach Secret, and the sweep can't list Secrets, so it's never collected. Worth a line in the spec's "Secrets are not listed" bullet or an upgrade note.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Noted in f8891ff: the spec's 'Secrets are not listed' bullet and a docs/context-service.md upgrade note say an older delete order can leave a lone -attach Secret the sweep can't see. They show how to find it: kubectl -n moca-sandbox get secret -l app=moca-workload-sandbox,app.kubernetes.io/managed-by=moca-provisioner -L moca.dev/workload, then delete the ones with no StatefulSet.

Comment thread packages/provisioner/test/sweep.test.ts Outdated
expect(await sweepOrphans(d, GRACE)).toEqual({ swept: 1, skipped: 0, failed: 0 });
expect(left(live)).toMatchObject({ sts: true, svc: true, secret: true });
expect(left(gone)).toMatchObject({ sts: false, svc: false, secret: false });
store.close();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: store.close() only runs when the test passes. If an assertion fails, the client's reconnect loop keeps the worker alive. Move it to try/finally or afterAll.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f8891ff: store.close() is now in a finally.

moonlight16 added a commit to moonlight16/moca that referenced this pull request Oct 27, 2026
- every Redis read in the sweep times out (MOCA_PROVISIONER_REDIS_TIMEOUT_MS,
  default 2000): a hung GET fails that workload, releases the owner's queue,
  and the pass ends
- a missing record never deletes the PVC: StatefulSet, Secret and Service go,
  the claim is kept and logged; only deleted/deleting or another generation
  delete it
- a pass whose first look finds at least 2 and more than half of the records
  missing deletes nothing (logged ORPHAN SWEEP ABORTED)
- spec §9: the provisioner holds the read-write Redis credential; README
  consumer list and rotation steps, redis.yaml header updated
- tests: the re-read record keeps old objects under the owner's queue, hung
  Redis reads, emptied-Redis guard; real-Redis store closed in finally
- docs: how to remove a kept PVC, and a lone <wl>-attach Secret an older delete
  order may have left

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Jeremy Cohn <[email protected]>
@moonlight16

Copy link
Copy Markdown
Member Author

@ingpaolodettori-dev thanks for the review. All six points are addressed in f8891ff (replies inline). Could you take another look?

The last open acceptance item of rossoctl#476: a workload whose delete fails partway
no longer leaves its sandbox objects behind (spec §6.2).

- the reconcile loop lists workload StatefulSets, Services and PVCs, reads
  each workload's record from Redis (GET only), and deletes the objects when
  the record is missing, deleted, deleting or of another generation AND every
  object is older than MOCA_PROVISIONER_ORPHAN_GRACE_S (default 600)
- re-checked under the owner's queue before deleting; delete-only; anything
  it cannot match to its record is logged and skipped
- delete order StatefulSet, Secret, Service, PVC, for DELETE too
- Redis access: REDIS_URL from moca-redis, its own NetworkPolicy, Redis
  ingress; Role gains list on Services and PVCs (Secrets stay unreadable)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Jeremy Cohn <[email protected]>
- every Redis read in the sweep times out (MOCA_PROVISIONER_REDIS_TIMEOUT_MS,
  default 2000): a hung GET fails that workload, releases the owner's queue,
  and the pass ends
- a missing record never deletes the PVC: StatefulSet, Secret and Service go,
  the claim is kept and logged; only deleted/deleting or another generation
  delete it
- a pass whose first look finds at least 2 and more than half of the records
  missing deletes nothing (logged ORPHAN SWEEP ABORTED)
- spec §9: the provisioner holds the read-write Redis credential; README
  consumer list and rotation steps, redis.yaml header updated
- tests: the re-read record keeps old objects under the owner's queue, hung
  Redis reads, emptied-Redis guard; real-Redis store closed in finally
- docs: how to remove a kept PVC, and a lone <wl>-attach Secret an older delete
  order may have left

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Jeremy Cohn <[email protected]>
@moonlight16
moonlight16 force-pushed the feat/workload-reconciler branch from f8891ff to b76c369 Compare October 27, 2026 00:24

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up to the ec2a9ba review. I checked all six points against the code, and each one is fixed: the bounded Redis read under the owner queue, the empty-Redis guard plus keeping the claim on a missing record, the credential docs, the re-read race test, the old-order Secret note, and store.close() in finally. The rebase onto e0d43c4 resolves the configuration.md conflict with #618 and keeps both sides' text, and CI is green on this head. I have one non-blocking suggestion inline about PVCs kept on missing records.

if (verdict.keep) return verdict.why ? skip(verdict.why) : 'kept';
// A missing record never deletes the claim: only an explicit deleted/deleting or another
// generation does (spec §6.2).
const keepClaim = verdict.why === MISSING;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Keeping the claim is the right call, but nothing ever collects it now. A kept PVC stays until an operator runs kubectl delete pvc, and it keeps counting against the moca-sandbox ResourceQuota (persistentvolumeclaims: 32, requests.storage: 320Gi). If someone misses the per-pass kept PVC stderr line, those claims add up until new mounted workloads fail to create a PVC on quota, which is a confusing place to find out. Consider surfacing the count, e.g. kept in SweepResult and a "N PVC(s) kept on missing records" summary line in orphanSweeper next to swept. Or add a line to the context-service.md note saying kept claims count against the quota.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. I'll take it in a small follow-up: a kept count in SweepResult with a "N PVC(s) kept on missing records" summary line next to swept, plus a line in the context-service.md note that kept claims count against the moca-sandbox ResourceQuota.

@pdettori
pdettori merged commit 0264588 into rossoctl:main Oct 27, 2026
15 checks passed
pdettori added a commit to pdettori/moca that referenced this pull request Nov 16, 2026
Sixteen ADRs still said Proposed although their decisions are in code
on main. Each status line now names the merged PRs that implemented it
and the date the core landed (format of ADR-0042), and notes what is
still owed where only part is built:

- 0028 (rossoctl#170, rossoctl#201, rossoctl#340; its KEDA transport removed by ADR-0041)
- 0029 (rossoctl#171), 0030 (rossoctl#214), 0031 (rossoctl#214, rossoctl#225)
- 0032 (rossoctl#249, rossoctl#350, as amended by MI1)
- 0035 (rossoctl#251; ADR-0048 adds lease mode beside it)
- 0036 (rossoctl#347), 0038 (rossoctl#458), 0039 (rossoctl#467), 0040 (rossoctl#481)
- 0043 (rossoctl#560, rossoctl#588, rossoctl#600, rossoctl#615), 0044 (rossoctl#563), 0045 (rossoctl#620)
- 0046 (phase 1: rossoctl#630, rossoctl#641, rossoctl#646; phase 2 owed)
- 0047 (M1 and M3: rossoctl#704, rossoctl#713, rossoctl#717, rossoctl#765; M2 owed)
- 0048 (rossoctl#706, rossoctl#763, rossoctl#802, rossoctl#808, rossoctl#814; off by default until the
  security review's lease sections are signed off)

The README index follows, and its 0033 row, which still said Proposed
after rossoctl#249 accepted the ADR, is corrected.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-ai-review Request automated AI code review from clawgenti

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants