Skip to content

feat: async leaf completion (KEDA ScaledJob + Redis Streams work queue) - #12

Merged
pdettori merged 18 commits into
mainfrom
feat/async-leaf-completion
Jun 28, 2026
Merged

pdettori merged 18 commits into
mainfrom
feat/async-leaf-completion

Conversation

@pdettori

Copy link
Copy Markdown
Member

Summary

Adds true background (async) execution of leaf sessions, realizing MVP spec §9.1. POST /run-leaf {async:true} returns 202 immediately; a KEDA ScaledJob spawns leaf-job pods that drain a Redis Streams work queue, run the unchanged runLeaf to completion, write result_ref + an atomic done-marker, and the orchestrator polls the marker. At-least-once delivery; a crashed leaf re-runs the same sessionId → gate-7 resume; scale-to-zero when the queue drains.

The synchronous POST /run-leaf path is unchanged and runLeaf is 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.md

What's added

  • @sh/work-queue — Redis Streams work queue (XADD/XREADGROUP/XAUTOCLAIM/XACK/XPENDING, heartbeat via XCLAIM JUSTID).
  • harness — atomic done-marker (temp+rename), pure classifyOutcome (ack-vs-reclaim §5 table), leaf-job-runner (processOne: claim → runLeaf → classify → marker → ack/reclaim, dead-letter past maxAttempts), and three optional LeafEnvelope fields (async/doneMarkerRef/tenant) + tenant-namespaced leafSessionId.
  • knative-server — async branch on POST /run-leaf (202 + handle) + GET /run-leaf/status; leaf-job.ts job entrypoint that drains the queue.
  • deploy — idempotent KEDA v2.14.0 install in setup-kind.sh, leaf-scaledjob.yaml, and the gated live smoke leaf-async-smoke.sh.

Testing

  • Unit (vitest, all green): work-queue 4, harness done-marker 5 / classify-outcome 5 / run-leaf 8 (+ existing) / leaf-job-runner 6, knative-server 14.
  • Live gate ASYNC_LIVE_SMOKE=1 deploy/knative/leaf-async-smoke.sh on 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, deterministic bad_inputs.

Notes for reviewers

  • The KEDA ScaledJob uses two redis-streams triggers: lagCount (new/undelivered backlog + scale-to-zero) and pendingEntriesCount (keeps a reclaimer scheduled for a crashed consumer's stuck PEL entry). pendingEntriesCount alone 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 by maxReplicaCount; a future slice could gate reclaim-spawning on min-idle-exceeded entries only.
  • No new Job RBAC — KEDA creates Jobs; the Job pod reuses the existing serverless-harness ServiceAccount.
  • Deferred minors (non-blocking, follow-up): unit coverage for touch()/purge(); status endpoint flattens queued/running (marker is the primary signal, §3.4 secondary path).

Assisted-By: Claude Code

Paolo Dettori added 17 commits June 27, 2026 14:09
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]>
…m) — pendingEntriesCount alone deadlocks

Signed-off-by: Paolo Dettori <[email protected]>
…exit; document KEDA reclaimer churn

Signed-off-by: Paolo Dettori <[email protected]>

@pdettori pdettori left a comment

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.

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;
}

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.

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; }

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 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);

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.

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.)

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 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

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.

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.

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 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;
}

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.

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.

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 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}"

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.

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' EXIT

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 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]>
@pdettori

Copy link
Copy Markdown
Member Author

Addressed all five review suggestions in 1e6735b:

  1. Path-traversal guard on GET /run-leaf/status (resolve + confine to WORK_ROOT, 403 otherwise) + unit test.
  2. Queue close in leaf-job main().catch (queue hoisted to module scope).
  3. Resource requests/limits on the ScaledJob leaf-job container.
  4. Removed the dead leafSessionId import / void line.
  5. trap … EXIT workspace cleanup in the async smoke.

Unit suites green (knative-server 15/15, +1 for the 403 case). Re-ran the live gate (ASYNC_LIVE_SMOKE=1) after rebuilding the image — all 6 §6.2 claims still PASS, including with the new resource limits applied (no OOM).

Assisted-By: Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant