Practical technical guides / Agent-era architecture: workflow orchestration (completion detection)

Seal the Agent Work Set Before Declaring a Run Complete

An empty queue is not a finished run when a planner still adds work. Count admissions and require a seal; the empty-queue rule declared done with 9 of 12 left.

By Sandeep Belgavi · Published 2026-11-16

Complete means sealed and nothing outstanding
Original explanatory diagram; synthetic values where shown.

An empty queue is not a finished run when a planner still adds work. Count admissions and require a seal; the empty-queue rule declared done with 9 of 12 left.

The run that finished too early

Tanishka's help-desk agent at Belgavi's Book Store prepares a weekly returns report. A planner model reads the week's cases, decides which ones need a closer look, and hands each one to a worker that fetches the order, checks the return against the policy and writes a line of the report. The planner does not decide everything at once. It reads a page of cases, admits three subtasks, reads the next page, admits three more, and so on. When nothing is left to do, the orchestrator closes the report and emails it.

One week the report had three lines instead of twelve. Nothing failed. The orchestrator's completion rule was the one most job runners use: the run is complete when the queue is empty and no worker is busy. The first three subtasks finished in under a second. The planner, meanwhile, was still reading the second page of cases, which took a second and a half. For a moment there was no pending work, so the run was declared complete. The other nine subtasks were admitted afterwards, ran, and wrote their lines into a report that had already been sent.

The problem is older than agents. It is termination detection for a dynamic work set: knowing that no more work will arrive is a different fact from knowing that no work is outstanding right now. With a fixed workflow, the orchestrator knows the work set in advance, so the two facts coincide. With a planner that decides as it goes, they do not, and a model's thinking time makes the gap long enough to hit every week.

What stays deterministic

The planner is free to decide what work exists. Completion must not depend on its timing. The fix is to make the end of planning an explicit event and to count work, not observe queues:

  • Admit increments an outstanding counter before a subtask is handed out.
  • Done decrements it when the subtask finishes, successfully or not.
  • Seal is called once by the planner when it will admit nothing more.
  • Complete is true only when the set is sealed and the counter is zero.

After the seal, the planner cannot admit more work into this run; an attempt is refused and visible. A running subtask may still admit children, but it must admit them before it calls its own done, so the counter cannot touch zero in between. This is the same rule as Go's sync.WaitGroup documentation, which says that Add calls with a positive delta made while the counter is zero must happen before Wait, and as Java's Phaser, where parties register before they arrive.

A small runtime

The companion example's runtime is a counter and a flag behind one condition variable:

class WorkSet:
    def __init__(self):
        self._cv = threading.Condition()
        self._outstanding = 0
        self._sealed = False

    def admit(self, by_running_item=False):
        with self._cv:
            if self._sealed and not by_running_item:
                raise SealedError('the planner sealed this work set')
            if self._sealed and self._outstanding == 0:
                raise SealedError('the run is already complete')
            self._outstanding += 1

    def done(self):
        with self._cv:
            self._outstanding -= 1
            self._cv.notify_all()

    def seal(self):
        with self._cv:
            self._sealed = True
            self._cv.notify_all()

    def wait(self, timeout=None):
        with self._cv:
            return self._cv.wait_for(lambda: self._sealed and self._outstanding == 0, timeout)

In a distributed orchestrator the same state lives in a durable record: a row with the run id, an admitted count, a finished count and a sealed flag, updated in the same transaction that enqueues or completes a subtask. Durable execution engines give you the same structure when the planner is a workflow that awaits its children: the workflow function itself is the seal, because it cannot return while it still has children to await.

The worked example

The companion model replays one run with seeded synthetic durations: four planner rounds, three subtasks per round, subtasks lasting 200 to 800 ms, and 1,500 ms of planner thinking between rounds. It compares three completion rules.

RuleDeclared completeLast subtask finishedSubtasks after the declaration
Empty queue652 ms5,261 ms9
Quiet period of 500 ms1,152 ms5,261 ms9
Quiet period of 2,000 ms7,261 ms5,261 ms0
Sealed barrier5,261 ms5,261 ms0

The quiet-period rule is the common patch: wait a while after the queue empties in case more work arrives. It works only when the quiet period exceeds the planner's longest pause, and then it adds that delay to every run. A 2,000 ms window was correct here and cost 2,000 ms; the next time the planner calls a slower model, the window is wrong again. The seal is exact in both directions: never early, and no waiting after the last subtask.

When the planner pauses only 100 ms between rounds, the empty-queue rule happens to work, because the queue never empties before the last round. That is why this bug survives testing on fast fixtures and appears in production with a real model.

Children and the order of two lines

The seal does not cover a subtle case. Suppose a subtask may spawn a follow-up, such as fetching the original invoice when a return is disputed. With the barrier rule and half of the subtasks spawning a child, the example declares completion exactly at the last subtask, 7,181 ms, provided each child is admitted before its parent calls done. Swap those two lines, so the parent calls done and then admits the child, and the counter briefly reaches zero after the seal. The run was declared complete at 5,892 ms with three subtasks still to run.

The interactive lab lets you change the order and watch the trace: the decision line appears between a finish and an admission that belong to the same parent.

Migrating an existing orchestrator

Most existing job runners already have a notion of a job with tasks. The change is mostly in who is allowed to say that the job is finished:

  1. Record admitted and finished counts per run, in the store that already holds task state.
  2. Give the planner an explicit seal operation, and call it from deterministic code when the planner's loop ends, not from the model's text. A model saying it is done is a signal to stop planning, not a completion fact.
  3. Make admission after the seal an error that is logged and surfaced, rather than silently starting work that no report will include.
  4. Require children to be admitted by their parent before the parent completes, and enforce it in the worker library.
  5. Replace queue-empty and quiet-period checks with the sealed-and-zero condition, and keep a timeout that fails the run, rather than completing it, if the seal never arrives.

Failure modes

  • Planner crashes before sealing. The run never completes. That is the correct failure: a stuck run with an alert is better than a report that silently omits work. Pair the seal with a run deadline.
  • Seal called twice or from the wrong place. Make seal idempotent and record who called it.
  • Lost done. A worker that dies without reporting leaves the counter above zero. Use leases or heartbeats on subtasks so the orchestrator can mark them failed and decrement deterministically.
  • Counting by observation. Recomputing outstanding work by listing queue contents reintroduces the race. Count transitions, in the same transaction as the transition.
  • Retries counted twice. A retried subtask is the same admission. Key admissions by subtask id so a redelivered admit does not increment again.

When you do not need this

If the work set is fixed before execution, for example a workflow graph validated up front, the orchestrator already knows when it is finished. If the planner admits all work in one step, sealing happens implicitly at that step. The seal earns its place when an agent decides incrementally what to do, which is most agent loops that fan out.

Verification

Test completion with adversarial timing rather than realistic timing: planner pauses longer than any subtask, children spawned at the last moment, admissions attempted after the seal. The companion tests run the barrier rule across 200 seeds and three spawn rates with planner pauses from 0 to almost 1.4 seconds, and require zero subtasks after the declaration every time. In production, log admitted, finished and sealed for every run, and alert on any subtask that finishes after its run was declared complete. That count should be zero, and it is cheap to watch.

Interactive experiment

Agent Work Set: Admission, Completion and the Seal Barrier. Synthetic browser-local fixtures, adjustable inputs, decision traces and JSON export.

Primary references and authorship

Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/agent_work_set_seal. Views are my own and do not represent any employer, past or present.