← Back to Pull requests

fix(tasks): fail tasks whose running instance stopped renewing its lease #292

Merged
mcollina merged 11 files (655 lines) on Oct 15, 2026 06:47 UTC
View on GitHub
mcollina mcollina commented on Oct 13, 2026 11:22 UTC
Author

Problem

Task-augmented tools/call tasks recorded no lease or heartbeat. If the instance running a task died or closed, nothing noticed. tasks/get kept reporting working, and tasks/result blocked until the task's ttl ran out (an hour by default) and then answered "not found".

Fix

  • The instance running a task takes a lease on it (leaseExpiresAt on the task record, which is not sent over the wire). It renews the lease every third of taskLeaseMs with an unref'd interval and stops when the task finishes or the app closes (TaskLeases, closed in the onClose hook).

  • For any non-terminal task that has a lease, tasks/get, tasks/result and the tasks/result poll loop ask the store (failExpiredLease) whether the lease has lapsed. The handler never compares the lease against its own clock, so a reader whose clock runs behind cannot delay the failure. When the lease has lapsed, the store marks the task failed with the status message "Task owner lost" and the handler wakes any local waiters.

  • New optional TaskStore methods renewLease / failExpiredLease, implemented in both stores as compare-and-set operations:

  • - MemoryTaskStore: the check and the write happen with no intervening await.
    - RedisTaskStore: Lua scripts with KEEPTTL. Both the renewal and the expiry check use Redis TIME, so clock skew between instances cannot fail a task that is still running.
  • New plugin option taskLeaseMs (default 30000), documented in the README.
  • A custom TaskStore that does not implement the two new methods keeps working as before, without leases.

    Tests

  • Store unit tests for both backends cover these cases:

  • - a lapsed lease is failed
    - a renewed lease is not failed
    - tasks with no lease, terminal tasks and missing tasks are left alone
    - retention is preserved
  • TaskLeases renews until stopped or closed.

  • Memory over-the-wire test: a tool that runs well past taskLeaseMs keeps its lease and completes.

  • Redis multi-instance test: instance A runs a hanging tool, B starts tasks/result, and A closes. B's tasks/result returns promptly with "Task owner lost", and tasks/get reports failed.

  • Redis test: an orphaned record with an expired lease, written directly, is failed by tasks/get and tasks/result.

  • Redis multi-instance test with the reader's Date.now running five minutes behind Redis: tasks/result and tasks/get still fail the orphaned tasks promptly.
  • This change touches handleTasksGet / handleTasksResult / awaitTaskTerminal in handlers.ts, adding one line at each read. Expect a trivial conflict with any parallel tasks/result lifecycle work.

    Fixes #250

    Orphaned tasks also stop holding the caller's quota: when a create hits taskMaxRetainedPerPrincipal, tasks whose lease has lapsed are failed first and can then be evicted like any finished task. Before this, a caller whose instances all died could get "Task limit reached" until they polled every orphan or its ttl ran out.

    🤖 Generated with Claude Code

    https://claude.ai/code/session_01UF4S3w7iA83V9DVsasLJzM

    Diff: 655 lines (+636 / -19) across 11 files Reviewer: rozzilla Review duration: 2605m
    All Vouch review confidence checks passed
    Residual risk 0.08 = Change Risk (0.56) × (1 − Review Confidence (0.86)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.56 · 655 lines diff across 11 files
    0.56
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.82 · 2 substantive comment(s)
    0.82
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    86%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Real PR Conversation Timeline
    4 items
    rozzilla rozzilla commented on code on Oct 14, 2026 08:39 UTC
    Code Review
    src/handlers.ts:1
    @@ -934,14 +938,35 @@ async function handleTasksGet (
         return createError(request.id, INVALID_PARAMS, 'Missing required parameter: taskId')
       }
     
    -  const task = assertTaskAccess(await taskStore.get(taskId), dependencies)
    +  const found = assertTaskAccess(await taskStore.get(taskId), dependencies)
    +  const task = found && await failIfOwnerLost(found, dependencies)
       if (!task) {
         return createError(request.id, INVALID_PARAMS, 'Failed to retrieve task: Task not found')
       }
     
       return createResponse(request.id, toWireTask(task))
     }
     
    +/**
    + * If the instance running `task` has stopped renewing its lease (it died or
    + * shut down), mark the task failed rather than let it read `working` until its
    + * ttl. The store does this as a compare-and-set, so a renewal or completion that
    + * lands first wins. Returns the task as it now stands.
    + */
    +async function failIfOwnerLost (task: TaskRecord, dependencies: HandlerDependencies): Promise<TaskRecord | null> {

    failIfOwnerLost() checks local Date.now() before calling Redis’s authoritative expiry check. A reader five minutes behind Redis delays failure by five minutes, leaving tasks/result blocked. we should delegate expiry checking to the store, and have a slow-reader-clock regression test.

    mcollina mcollina commented on code on Oct 14, 2026 10:14 UTC
    Code Review
    src/handlers.ts:1
    @@ -934,14 +938,35 @@ async function handleTasksGet (
         return createError(request.id, INVALID_PARAMS, 'Missing required parameter: taskId')
       }
     
    -  const task = assertTaskAccess(await taskStore.get(taskId), dependencies)
    +  const found = assertTaskAccess(await taskStore.get(taskId), dependencies)
    +  const task = found && await failIfOwnerLost(found, dependencies)
       if (!task) {
         return createError(request.id, INVALID_PARAMS, 'Failed to retrieve task: Task not found')
       }
     
       return createResponse(request.id, toWireTask(task))
     }
     
    +/**
    + * If the instance running `task` has stopped renewing its lease (it died or
    + * shut down), mark the task failed rather than let it read `working` until its
    + * ttl. The store does this as a compare-and-set, so a renewal or completion that
    + * lands first wins. Returns the task as it now stands.
    + */
    +async function failIfOwnerLost (task: TaskRecord, dependencies: HandlerDependencies): Promise<TaskRecord | null> {

    Removed the local Date.now() pre-check in 0d78c43: failIfOwnerLost() now skips the store only for terminal tasks or tasks with no leaseExpiresAt, and otherwise lets failExpiredLease decide (Redis server TIME for RedisTaskStore). Added a two-instance Redis test where the reader's Date.now runs five minutes behind; tasks/result and tasks/get still fail the orphaned tasks promptly (it timed out before the fix).

    rozzilla rozzilla approved these changes on Oct 14, 2026 10:39 UTC
    Approved Reviewer

    Approved these changes.

    Reviewers
    Assignees
    mcollina mcollina
    Labels
    risk: low confidence: 86.1% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 56.5% (MEDIUM) · Higher = larger blast radius
    56.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 86.1% · Lower = rushed or shallow review
    86.1%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 7.9% · Safe to merge
    7.9%