Repository navigation
feat: async leaf completion (KEDA ScaledJob + Redis Streams work queue) - #12
Conversation
True background leaf execution via KEDA ScaledJob + Redis Streams work queue. Async POST /run-leaf returns 202; leaf-job runs runLeaf to completion, writes result_ref + a done-marker; orchestrator polls. At-least-once delivery with gate-7 resume on crash; scale-to-zero when the queue drains. Reuses runLeaf unchanged. Multi-tenancy (Z1/Z3/Z5), C's cron triggers, and B's human-gate are non-precluding but out of scope. Signed-off-by: Paolo Dettori <[email protected]>
9 TDD tasks: @sh/work-queue (Redis Streams), done-marker, classifyOutcome, envelope async/tenant fields + leafSessionId, leaf-job-runner, async route + status endpoint, leaf-job entrypoint, KEDA install + ScaledJob, and the gated live async smoke (accept, scale-out, done-marker, crash-resume, scale-to-zero). Signed-off-by: Paolo Dettori <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…onId Signed-off-by: Paolo Dettori <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…atus Signed-off-by: Paolo Dettori <[email protected]>
…ssOne) Signed-off-by: Paolo Dettori <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…-resume, scale-to-zero Signed-off-by: Paolo Dettori <[email protected]>
…e claim Signed-off-by: Paolo Dettori <[email protected]>
…aml) Signed-off-by: Paolo Dettori <[email protected]>
…m) — pendingEntriesCount alone deadlocks Signed-off-by: Paolo Dettori <[email protected]>
…unLeaf finds inputs Signed-off-by: Paolo Dettori <[email protected]>
…exit; document KEDA reclaimer churn Signed-off-by: Paolo Dettori <[email protected]>
…s.exit skips finally) Signed-off-by: Paolo Dettori <[email protected]>
pdettori
left a comment
There was a problem hiding this comment.
Self-review (maintainer)
Clean, well-structured implementation that reuses runLeaf unchanged via a thin queue wrapper. The at-least-once delivery semantics, heartbeat-based reclaim, and dead-letter paths are correct. The dual KEDA trigger rationale (lagCount + pendingEntriesCount) is well-documented and the unit test coverage is solid for the core paths.
Suggestions (non-blocking): path traversal guard on the status endpoint, queue close in the catch handler, resource limits on the ScaledJob. All can be addressed in follow-up.
| if (marker) { | ||
| res.writeHead(200, JSON_HEADERS).end(JSON.stringify({ status: marker.status, reason: marker.reason ?? undefined })); | ||
| return; | ||
| } |
There was a problem hiding this comment.
suggestion — path traversal in status endpoint
readDoneMarker receives the raw doneMarker query param and passes it to readFileSync. A caller can read any JSON-parseable file the process has access to (e.g. ?doneMarker=/app/package.json).
Low risk in the current trusted/single-tenant container, but worth a path.resolve + startsWith(prefix) guard before production exposure:
const resolved = path.resolve(doneMarker);
if (!resolved.startsWith('/work/')) { res.writeHead(403, ...).end(...); return; }There was a problem hiding this comment.
Done in 1e6735b. handleLeafStatus now path.resolves the param and confines it to a WORK_ROOT (/work, overridable via LEAF_WORK_DIR) — anything outside returns 403 doneMarker_forbidden, and the resolved path is what's read (so /work/../etc/passwd is blocked). Added a unit test asserting the 403 + that readDoneMarker is not called.
| } | ||
|
|
||
| main().catch(async (err) => { | ||
| console.error("leaf-job error:", err); |
There was a problem hiding this comment.
suggestion — queue not closed on unhandled error
The main().catch() handler exits without closing the queue. The "idle" and "retry" paths both close explicitly, but if an unexpected exception escapes (e.g. Redis connection reset between iterations), the connection is abandoned.
In practice process.exit(1) tears down the process regardless, but for symmetry with the other paths:
main().catch(async (err) => {
console.error("leaf-job error:", err);
try { await queue?.close(); } catch { /* ignore */ }
process.exit(1);
});(queue would need to be hoisted to module scope or wrapped in a cleanup helper.)
There was a problem hiding this comment.
Done in 1e6735b. queue is hoisted to module scope and the main().catch now best-effort await queue?.close() before exit, matching the idle/retry paths.
| valueFrom: { secretKeyRef: { name: llm-credentials, key: auth-token, optional: true } } | ||
| volumeMounts: | ||
| - name: work | ||
| mountPath: /work |
There was a problem hiding this comment.
suggestion — no resource requests/limits
Without bounds, a runaway leaf could OOM the node (especially during LLM streaming with large context). maxReplicaCount: 10 bounds pod count but not per-pod usage.
Suggest adding baseline limits tuned to observed workloads:
resources:
requests: { memory: 256Mi, cpu: 100m }
limits: { memory: 1Gi, cpu: 500m }Non-blocking for dev/Kind but good practice before any shared-cluster use.
There was a problem hiding this comment.
Done in 1e6735b. Added requests: {memory: 256Mi, cpu: 100m} / limits: {memory: 1Gi, cpu: 500m} to the leaf-job container. Re-ran the live gate with the limits in place — all 6 §6.2 claims still PASS (no OOM on the haiku workload).
|
|
||
| return server; | ||
| } | ||
|
|
There was a problem hiding this comment.
nit: void leafSessionId; imports a symbol only to suppress lint. Remove the import until the status-by-session feature actually uses it — dead imports add noise and confuse dependency analysis.
There was a problem hiding this comment.
Done in 1e6735b. Dropped both the void leafSessionId; line and the now-unused import.
|
|
||
| [ "${ASYNC_LIVE_SMOKE:-0}" = "1" ] || { echo "SKIP (set ASYNC_LIVE_SMOKE=1)"; exit 0; } | ||
|
|
||
| ORCH=leaf-orchestrator; SBOX="${KAGENTI_SANDBOX_POD:-sandbox-0}" |
There was a problem hiding this comment.
nit: No trap ... EXIT for workspace cleanup. If the script is killed mid-run (SIGTERM, OOM), orphaned test data stays on the PVC.
trap 'kubectl -n "$NS" exec "$SBOX" -- sh -c "rm -rf /workspace/$RUN" 2>/dev/null || true' EXITThere was a problem hiding this comment.
Done in 1e6735b. Replaced the trailing cleanup line with trap '...rm -rf /workspace/$RUN' EXIT set right after the run vars, so the sandbox workspace is cleaned on any exit (incl. SIGTERM/OOM mid-run).
…f-job queue close on error, ScaledJob resource bounds, drop dead leafSessionId import, smoke EXIT-trap cleanup Signed-off-by: Paolo Dettori <[email protected]>
|
Addressed all five review suggestions in
Unit suites green (knative-server 15/15, +1 for the 403 case). Re-ran the live gate ( Assisted-By: Claude Code |
Summary
Adds true background (async) execution of leaf sessions, realizing MVP spec §9.1.
POST /run-leaf {async:true}returns202immediately; a KEDAScaledJobspawns leaf-job pods that drain a Redis Streams work queue, run the unchangedrunLeafto completion, writeresult_ref+ an atomic done-marker, and the orchestrator polls the marker. At-least-once delivery; a crashed leaf re-runs the samesessionId→ gate-7 resume; scale-to-zero when the queue drains.The synchronous
POST /run-leafpath is unchanged andrunLeafis reused unchanged — the job is a thin queue wrapper. Single-tenant, provider key in env (no Z-track/identity scope).Design:
docs/specs/2026-06-27-async-leaf-completion-design.md· Plan:docs/superpowers/plans/2026-06-27-async-leaf-completion.mdWhat's added
@sh/work-queue— Redis Streams work queue (XADD/XREADGROUP/XAUTOCLAIM/XACK/XPENDING, heartbeat viaXCLAIM JUSTID).harness— atomicdone-marker(temp+rename), pureclassifyOutcome(ack-vs-reclaim §5 table),leaf-job-runner(processOne: claim → runLeaf → classify → marker → ack/reclaim, dead-letter pastmaxAttempts), and three optionalLeafEnvelopefields (async/doneMarkerRef/tenant) + tenant-namespacedleafSessionId.knative-server— async branch onPOST /run-leaf(202+ handle) +GET /run-leaf/status;leaf-job.tsjob entrypoint that drains the queue.setup-kind.sh,leaf-scaledjob.yaml, and the gated live smokeleaf-async-smoke.sh.Testing
ASYNC_LIVE_SMOKE=1 deploy/knative/leaf-async-smoke.shon Kind — all 6 design §6.2 claims PASS: async accept, KEDA scale-out (3 concurrent pods), completion via done-marker with correct verdicts, crash-resume (killed a running leaf-job → reclaimed → resumed → verdict), scale-to-zero, deterministicbad_inputs.Notes for reviewers
ScaledJobuses two redis-streams triggers:lagCount(new/undelivered backlog + scale-to-zero) andpendingEntriesCount(keeps a reclaimer scheduled for a crashed consumer's stuck PEL entry).pendingEntriesCountalone deadlocks (PEL stays 0 until something reads). Trade-off (documented in the manifest): the PEL trigger spawns short-lived no-op reclaimers while a leaf is in-flight, bounded bymaxReplicaCount; a future slice could gate reclaim-spawning on min-idle-exceeded entries only.serverless-harnessServiceAccount.touch()/purge(); status endpoint flattensqueued/running(marker is the primary signal, §3.4 secondary path).Assisted-By: Claude Code