Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

CODING CHALLENGE · N°17

Run the Goal Loop

Medium AI EngineeringAgentsLoop Engineering

The goal loop is the engine of loop engineering: attempt the next task, let a verifier judge it, retry failures, and stop when the goal is met — or stop loudly when the cap trips. Implement the whole outer loop as one pure, testable function.

The problem

Implement run_loop(queue, outcomes, max_iterations). Each iteration the agent attempts the task at the front of the queue, and outcomes[i] is the independent verifier’s verdict for iteration i (if the outcomes list is exhausted, the verdict is a failure). A pass moves the task to done; a fail leaves it at the front to retry. The loop ends when the queue is empty or the iteration cap is hit. Return {"done": […], "remaining": […], "iterations": n, "status": "complete" | "cap"}.

SOLVE IT YOURSELF

Your turn — write it

Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? open the hints under the problem, or Reveal solution is one click away.

YOUR TASK

Implement run_loop(queue, outcomes, max_iterations) — attempt the front task each iteration, let the verifier verdict decide pass/retry, and stop on goal-met or cap-hit with the full result dict.

CPython · WebAssembly
Examples and constraints 4 examples
EXAMPLE 1
Input queue=["a","b"], outcomes=[True, False, True], max_iterations=10
Output {'done': ['a', 'b'], 'remaining': [], 'iterations': 3, 'status': 'complete'}
"b" fails once and is retried — the verifier decides, not the agent
EXAMPLE 2
Input queue=["a","b"], outcomes=[False, False, False], max_iterations=3
Output {'done': [], 'remaining': ['a', 'b'], 'iterations': 3, 'status': 'cap'}
the cap trips with work remaining — the loop ends loudly, not silently
EXAMPLE 3
Input queue=[], outcomes=[True], max_iterations=5
Output {'done': [], 'remaining': [], 'iterations': 0, 'status': 'complete'}
nothing to do → the goal is already met, zero spend
EXAMPLE 4
Input queue=["a"], outcomes=[True], max_iterations=0
Output {'done': [], 'remaining': ['a'], 'iterations': 0, 'status': 'cap'}
edge case: a zero cap with work left is a cap-hit, not a success
CONSTRAINTS
  • One verifier verdict is consumed per iteration: verdict for iteration i is outcomes[i], or a failure once outcomes are exhausted.
  • A failed task stays at the front of the queue — state untouched, retried next iteration.
  • Do not mutate the input queue; return a fresh remaining list.
  • status is "complete" only when the queue emptied; a cap-hit with leftovers is "cap" — even at 0 iterations.
Hints 5 ideas
HINTS — 5 IDEAS
  1. Copy the queue first — the caller’s list must survive the run.
  2. Loop while the queue is non-empty AND iterations < max_iterations.
  3. The verdict for this iteration is outcomes[iterations] if that index exists, else False — read it before incrementing.
  4. On a pass, pop the front task into done. On a fail, do nothing — the front task is automatically the retry target.
  5. Status at the end: "complete" if the queue is empty, otherwise "cap".
Approach, complexity & discussion — open after you solve

Start from brute force

The first draft is usually while queue: with no cap: pop the front task, and if the verifier fails it, append it to the back to retry later. Its space is O(n) for the queue, and it works whenever every task eventually passes, but its time is unbounded. Here exhausted outcomes count as failures, so run_loop(["a"], [], 2) would spin forever. Moving a failure to the back also changes which task each verdict judges: with ["a", "b"] and verdicts False, True, front-retry finishes a while back-retry finishes b. The spec pins front-retry and a hard cap.

The approach

Simulate one verdict per iteration and let the cap end the loop. The reference run_loop first copies the input with queue = list(queue), so the caller’s list survives, then loops while queue and iterations < max_iterations. Each pass reads verdict = outcomes[iterations] if iterations < len(outcomes) else False before iterations += 1, so the counter is exactly the index of the verdict being consumed and a missing verdict is a failure. A pass runs done.append(queue.pop(0)); a fail does nothing, which leaves the same task at the front for the next verdict.

Two invariants carry the proof. done followed by queue always spells the original task order, because tasks only move from the front of one to the end of the other. And iterations rises by one per pass and never exceeds the cap, so the loop always terminates. The status is then a single check: "complete" if the queue emptied, otherwise "cap", even when the cap was 0. The TypeScript runLoop is the same loop with q.shift().

start[0] True → pass[1] False → stay[2] True → passdone []queue [a,b]done [a]queue [b]done [a]queue [b]done [a,b]queue []iterations = 0iterations = 1iterations = 2iterations = 3completea fail leaves the task at the front;the queue emptied before the cap of 10
The first example, one column per iteration. Each verdict is outcomes[iterations] read before the counter moves. The failed verdict leaves b at the front (dashed), and the next verdict judges the same task. The queue empties at 3 iterations, so the status is "complete".

Walk through an example

On the first example, task b fails once and stays at the front until the next verdict passes it.

stepiterations beforefront taskverdictactiondonequeue after
10aoutcomes[0] = Truepop a into done["a"]["b"]
21boutcomes[1] = Falseleave b at the front["a"]["b"]
32boutcomes[2] = Truepop b into done["a", "b"][]
43nonenot readqueue is empty: stop with "complete"["a", "b"][]

Complexity

Time O(n + I + p · n) for n tasks, I iterations (at most max_iterations) and p passes: each iteration is O(1) except a pass, where queue.pop(0) shifts the rest of the list. A collections.deque with popleft() makes it O(n + I). Space O(n) for the copied queue and done. The uncapped draft needs the same space and has no time bound.

Edge cases to test

  • run_loop(["a"], [True], 0) → {"done": [], "remaining": ["a"], "iterations": 0, "status": "cap"}. A zero cap with work left is a cap-hit, not success.
  • run_loop([], [], 0) → "complete" with 0 iterations. An empty queue is a met goal whatever the cap.
  • run_loop(["a"], [], 2) → "cap" after 2 iterations. Exhausted outcomes are failures: indexing past the end raises, and defaulting to True passes work nobody verified.
  • run_loop(["a", "b"], [False, True], 10) → done ["a"], remaining ["b"], 10 iterations, "cap". Once the verdicts run out, the leftover task burns the rest of the cap; moving failures to the back would have finished b instead.
  • After q = ["a", "b"]; run_loop(q, [True, True], 10), q is still ["a", "b"]. Popping from the caller’s list directly would empty it.

Common mistakes

  • Mutating the caller’s queue instead of copying it.
  • Reading outcomes[iterations] after incrementing — an off-by-one that shifts every verdict.
  • Reporting "complete" when the cap tripped with work left — a cap-hit with leftovers is "cap", even at 0 iterations.
  • Forgetting that running out of verdicts means failure, not success.

Follow-ups an interviewer asks next

Give each task its own retry budget.
Keep a count of attempts per task, for example a dict from task to attempts. When a task reaches max_attempts, move it to a failed list and continue with the next one, so one poison task cannot burn the whole global cap. The result then needs a third status, such as "partial", for a run that ended with failures but without hitting the cap.
The process can crash mid-run. Make it resumable.
The function is pure, so the returned dict captures its whole state. Checkpoint it after every iteration, then resume with run_loop(remaining, outcomes[iterations:], max_iterations - iterations). Because a failed task stays at the front and the verdict index equals iterations, the resumed run makes exactly the decisions the uninterrupted run would have made.
Run independent tasks in parallel.
Let several workers pull from one shared queue, each attempting a task and reporting its verdict, and turn the cap into a shared budget that a worker must reserve before starting an attempt. Completion order is no longer deterministic, so record it explicitly, and decide whether a failed task stays claimed by its worker or goes back to the front.
Retry immediately, or back off first?
An immediate retry suits failures the agent can fix by trying again with the verifier’s feedback. Failures caused by something outside the task, such as a rate limit or an unavailable service, should wait with exponential backoff and jitter, and are usually better kept out of the attempt budget meant for real mistakes.

Where this shows up

This is the outer loop of loop engineering — attempt the next task, let an independent verifier judge it, retry failures, and stop on goal-met or a loud cap. It is distinct from the ReAct inner loop (act/observe), and the same bounded-retry-with-verification shape drives CI reruns, job queues, and any agent that must finish a task list without spinning forever.

Writing it as a pure function is the design choice worth copying. In a live agent, “attempt the task” is a model call and “verify” is a test run, a linter, a schema check or a second model acting as judge. Here both are replaced by the outcomes list, so the control logic (which task is next, when to stop, what to report) can be tested in milliseconds with every awkward sequence of verdicts: all fail, verdicts run out, a zero budget. The expensive parts plug in later without changing the loop.

The returned dict is also the run’s audit record. done says what was verified, remaining says what was not, and status says why the loop stopped. An orchestrator above this loop can route on that status alone: "complete" moves on to the next stage, while "cap" pages a person or opens a ticket with the remaining tasks attached. A loop that returns only the finished work hides the difference between “nothing left to do” and “ran out of budget”, which is exactly the difference someone paying for the iterations needs to see.

Keeping the verifier separate from the agent is what makes the counts meaningful. If the agent grades its own work, a pass costs nothing to claim, and done stops being evidence of anything.

Check yourself

What does run_loop(["a", "b", "c"], [False, True, True, False, True], 4) return?

{"done": ["a", "b"], "remaining": ["c"], "iterations": 4, "status": "cap"}. Verdict 0 fails a, verdicts 1 and 2 pass a then b, verdict 3 fails c, and the cap of 4 stops the loop before the final True is read.

What does run_loop(["a", "b"], [True], 3) return?

{"done": ["a"], "remaining": ["b"], "iterations": 3, "status": "cap"}. After the single verdict, every read is past the end of outcomes and counts as a failure, so b burns the two remaining iterations.

A bug increments iterations before reading outcomes[iterations]. What does the first example return now?

{"done": ["a"], "remaining": ["b"], "iterations": 10, "status": "cap"}. The first read is outcomes[1] = False, so the verdict meant for a is skipped, outcomes[2] passes a, and b never gets a verdict before the outcomes run out.

Run the first example with a cap of 2, then resume with run_loop(remaining, outcomes[iterations:], 10 - iterations). Is the combined result the same as one uncapped run?

Yes. The first run returns done ["a"], remaining ["b"] after 2 iterations; the resume reads [True], passes b and completes in 1 iteration. Together that is ["a", "b"] in 3 iterations, because the verdict index always equals iterations and a failed task never leaves the front.

Reference solution

Reference solution — Python
def run_loop(queue, outcomes, max_iterations):
    queue = list(queue)
    done = []
    iterations = 0
    while queue and iterations < max_iterations:
        verdict = outcomes[iterations] if iterations < len(outcomes) else False
        iterations += 1
        if verdict:
            done.append(queue.pop(0))
    return {
        "done": done,
        "remaining": queue,
        "iterations": iterations,
        "status": "complete" if not queue else "cap",
    }


print(run_loop(["a", "b"], [True, False, True], 10))
# -> {'done': ['a', 'b'], 'remaining': [], 'iterations': 3, 'status': 'complete'}
print(run_loop(["a", "b"], [False, False, False], 3))
# -> {'done': [], 'remaining': ['a', 'b'], 'iterations': 3, 'status': 'cap'}
Reference solution — TypeScript
type LoopResult = {
  done: string[];
  remaining: string[];
  iterations: number;
  status: 'complete' | 'cap';
};

function runLoop(queue: string[], outcomes: boolean[], maxIterations: number): LoopResult {
  const q = [...queue];
  const done: string[] = [];
  let iterations = 0;
  while (q.length > 0 && iterations < maxIterations) {
    const verdict = iterations < outcomes.length ? outcomes[iterations] : false;
    iterations++;
    if (verdict) done.push(q.shift()!);
  }
  return { done, remaining: q, iterations, status: q.length === 0 ? 'complete' : 'cap' };
}

console.log(runLoop(['a', 'b'], [true, false, true], 10));
// -> { done: ['a','b'], remaining: [], iterations: 3, status: 'complete' }
console.log(runLoop(['a', 'b'], [false, false, false], 3));
// -> { done: [], remaining: ['a','b'], iterations: 3, status: 'cap' }

Questions about Run the Goal Loop

What is the difference between the goal loop and the ReAct loop?

They run at different levels. The ReAct loop is the inner loop of a single attempt: the model reasons, calls a tool, observes the result, and repeats until it produces an answer. The goal loop sits outside it and manages a list of tasks: it picks the next task, lets the agent attempt it, possibly with a full ReAct loop inside, asks an independent verifier whether the attempt succeeded, and then retries or moves on. The goal loop is also where the global iteration cap lives, which is what stops a stuck agent from spending without limit.

Why does an agent loop need an iteration cap?

Because a verifier can keep failing forever. A task may be impossible, the verifier may be broken, or, as in this problem, the verdicts may simply run out, and an uncapped while loop would then spin, spending tokens or compute on every pass. A cap bounds the worst-case cost to a number chosen in advance. Just as important is how the loop ends: hitting the cap with work left must report a distinct status, here cap, so a caller never mistakes a budget stop for a finished goal.

Why does a failed task stay at the front instead of moving to the back?

Because each verdict judges whatever task is at the front at that moment, and leaving a failed task in place means the next verdict judges a retry of the same task, the way a real agent attempts a fix before moving on. Moving it to the back is a different policy, round robin, and it changes results: with tasks a and b and verdicts False then True, front retry finishes a while round robin finishes b. Neither policy is wrong in general, but a specification has to pick one, and the tests here pin front retry.

Why read the verdict before incrementing the iteration counter?

Because iterations counts the verdicts already consumed, so before the increment it is exactly the index of the current verdict. Reading outcomes at iterations and then adding 1 uses outcomes 0, 1 and 2 in order. Incrementing first shifts every verdict by one: the first verdict is skipped, each attempt is judged by the verdict meant for the next one, and the loop reads past the end sooner. On tasks a and b with verdicts True, False, True and a cap of 10, the shifted version finishes only a and then burns the rest of the cap.

Finished this one? 0 / 76 Challenges done
NextBuild Your Own Agent Loop Next on the “Agents & loop engineering” ladder · rung 5 of 9

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Challenges