Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 17. Cancellation, Errors, and Task Status

After the streaming task from the previous chapter starts running, users have a few new questions: they got the calculation wrong and want to stop — how do they stop it? After stopping, what is that half-finished thing on the screen? And what should the UI say when an error suddenly appears after a long run, and how do you tell “the click did not register” from “it is still queued” when nothing happens after a click?

Cancellation, failure, timeout, and a request being turned back before it ever reaches the handler function all count as “endings that went badly.” The UI has to state honestly what happened: do not call cancellation a failure, and do not call a failure a success.

The example adds a fifteenth block to the workbench, the task module. One long task of twenty steps at half a second each, a cancellation that takes effect immediately, a cancellation that deliberately queues, plus a timeout you build yourself, two different failures, a clear button, and an entry with a validator.

Why twenty steps at half a second each? To make “cancellation” visible. If the task is too short, it is over the moment you click and there is no chance to cancel; if it is too long, readers get impatient. Ten seconds is just right. Click cancel around the third or fourth second and five or six steps remain on screen while the other fourteen never appear. To see which step it stopped at, just count the steps on screen. Every figure below was captured within that duration.

17.1 Cancellation Tokens and Events Waiting in the Queue

The handler function needs one more parameter.

async IAsyncEnumerable<(string, object)> Steps([EnumeratorCancellation] CancellationToken token)
{
    var done = 0;

    try
    {
        for (var i = 1; i <= TaskBoard.Steps; i++)
        {
            await Task.Delay(TaskBoard.StepDelay, token);
            done = i;

            // The step changes on every frame; gr.Skip() holds the result until the last step.
            yield return (TaskBoard.StepText(done), gr.Skip());
        }
    }
    finally
    {
        // Completion, cancellation, and errors all pass through here: record which step it stopped at, and read it out when the panel is cleared.
        TaskBoard.Stopped(done);
    }

    yield return (TaskBoard.StepText(done), TaskBoard.Finished(done));
}

CancellationToken and Progress are the same kind of thing: injected by the framework, taking up no input slot (Chapter 3, Chapter 16). You do not write it into inputs; if you do, the framework will instead go looking inside the components for a value to fill it with. There is no such thing in a component, so you end up with an empty one.

You might think: why not write my own volatile bool _stop, read that flag once per round inside the handler function to decide whether to continue — why use a token at all? It does work for a single call; the problem shows up in three places. First, the same handler function may be called several times at once, and one bool cannot tell which call is which. Second, the stretch of waiting inside await does not return early just because you flipped the bool; it waits as long as it was going to. Third, the framework knows nothing about that bool — it only knows “do we want the next frame?” A token solves all three at once: one per call, it can interrupt the wait, and the framework recognizes it.

The [EnumeratorCancellation] annotation is for async sequences. It lets the compiler wire the token to the enumerator, so that when whoever runs await foreach cancels, the token reaches this method. Ordinary handler functions (the kind that return Task<string>) do not need this annotation; just list the token as a parameter.

A token alone is not enough. With nobody to trip it, it stays “not cancelled” forever. What trips it is cancels on the binding.

    Dependency longRun = job.Run.Click(Steps, null, [work.Steps, work.Result],
        apiName: "Long task", concurrencyId: "Tasks", concurrencyLimit: ConcurrencyLimit.Of(1));
    job.Stop.Click(Cancel, null, [work.Status], apiName: "Cancel", cancels: [longRun], queue: false);
    job.QueuedStop.Click(Cancel, null, [work.Status],
        apiName: "Queued cancel", cancels: [longRun], concurrencyId: "Tasks", concurrencyLimit: ConcurrencyLimit.Of(1));

What cancels accepts is the binding object itself, that is, the return value of Click (a Dependency). Not the button, not apiName, and not the handler function name. So to cancel an event, you first have to store that binding in a variable. That is the entire purpose of the longRun variable in the example.

Once this is written, one more entry shows up in the config. Open /config and look. Besides the ones you wrote yourself, there is an entry with api_name set to unnamed, queue: false, and cancels pointing at the “Long task” binding, attached to the same trigger as the cancel button. The framework adds this one itself, specifically to send cancellation requests. Write several cancels and you get several such entries. The example has two cancel buttons, so there are two.

Click cancel and the frontend sends three requests in total. POST /gradio_api/run/predict runs your own cancellation handler function, POST /gradio_api/cancel carries event_id and fn_index, and finally POST /gradio_api/reset wraps things up. Of the three, the middle one performs the cancellation, and that is what Figure 17-1 draws.

Figure 17-1 The four steps a cancellation takes

cancels may be cancelling “the run that is executing” or “the run that is still queued.” Both are called cancellation, but they mean different things. The running one means “stop here”; the queued one means “this does not need to start at all.”

The latter is cleaner. In the example, click “Run long task” twice. The first starts running, the second goes into the queue (same group, concurrency limit 1). Click cancel now and the second one never enters the handler function from start to finish. It does not even write the “start” line in the log. Since the handler function never ran once, there are no side effects to clean up — much less trouble than “running halfway and then stopping.”

This distinction is easy to miss because the button the user sees is the same one. Click cancel right after starting the task, while it is still waiting in the queue, and what you cancel is “the run that has not started.” Conversely, if three are already queued, one click of cancel clears only one.

What the cancellation request carries is an event_id, not “this handler function.” You cannot see the difference when there is only one user; it shows up as soon as there are several. The same binding may have several runs going at once: two tabs each running one, or two people each running one. What cancels cancels is “this one run” — the framework identifies the caller by event_id and the binding by fn_index. So you do not need any extra design for “several people using it at once,” and you should not expect one cancel click to stop everyone’s runs; it stops only this one.

17.2 How a Running Handler Function Receives a Cancellation

After the token is tripped, the next await throws OperationCanceledException. The example’s await Task.Delay(TaskBoard.StepDelay, token) behaves exactly like this. Cancellation happens between step 5 and step 6; the wait for step 6 throws immediately, the loop ends, and the sequence produces nothing more.

Once it throws, two things happen at the same time. First, the sequence stops producing and the framework stops pulling; second, finally runs as usual. The example makes use of both. finally records “which step it stopped at” and reads it out to the user when the panel is cleared.

yield return cannot go inside catch (the restriction from Chapter 16), but it can go inside try paired with a finally. That combination happens to separate the two concerns. On cancellation you should not emit one more frame anyway, so catch need not produce anything; everything that needs cleaning up goes in finally.

Do not treat cancellation as failure. Cancellation is something the user actively pressed, not a program going wrong. So do not write throw new Error("The task failed") in the cancellation handler. That sentence would make users think they broke something. The example’s cancellation handler says only “Cancellation requested; the steps already produced stay where they are” — all of it factual.

One more thing is easily overlooked. The token has to actually be passed down. Taking the token as a parameter and then calling await Task.Delay(1000) without it is the same as not taking it at all. The user clicks cancel, the program still runs to the end, and the UI finally shows “Done.”

Every frame in the example’s streaming loop carries the token, so after cancellation it stops after at most another half second. Half a second is the length of one step; cancellation takes effect only at “the next await” and does not cut off the half second already being waited out. That granularity is acceptable; if each of your steps takes five seconds, you need to slice finer inside the step, or users will feel “I clicked and nothing happened.”

The three places you usually need to pass it are these. To wait a while, use Task.Delay(duration, token); to send a request, use SendAsync(request, HttpCompletionOption.ResponseHeadersRead, token); to read an async sequence, use await foreach (var item in Source(token).WithCancellation(token)). Miss one place and cancellation breaks there. It stops only at the next wait that carries the token, and the stretch in between is wasted waiting.

What belongs in finally? Things that “must happen however it ends” — release a semaphore, close a connection, flip the “running” flag back to “idle,” record “which step it stopped at.” The example uses the last one because it is useful to the user. Do not throw an exception inside finally. It would mask the real cancellation exception, and what shows up in the UI becomes “an error popped up after cancelling,” which is even harder to explain.

A token will not interrupt synchronous code for you. This is the easiest trap to step on. A for loop doing pure computation with no await will not throw no matter how many times the token is tripped. Cancellation is cooperative; the code itself has to check the cancellation state. In that kind of loop you check manually.

for (var i = 0; i < rows.Count; i++)
{
    token.ThrowIfCancellationRequested();
    total += Heavy(rows[i]);
}

ThrowIfCancellationRequested throws OperationCanceledException — the same one Task.Delay throws — and the outer finally runs just the same.

Timeout and cancellation throw the same exception, OperationCanceledException. So when you see it in the log, do not rush to write “the user cancelled.” It may also be a time limit you set yourself. The way to tell them apart is the when filter in 17.5. Only if the outer token was tripped is it a user cancellation; if it was not, it is the time limit. Writing those two as the same line in the log makes post-mortem debugging take a long detour.

Here is a counterexample. Write the long task’s wait as Thread.Sleep(500) instead of await Task.Delay(500, token). With that, the cancel button does nothing at all. Thread.Sleep ignores the token, and it holds the thread so that even other requests are affected (the “synchronous blocking kills concurrency” point from Chapter 15). Both streaming and cancellation require the handler function to be “awaitable.”

Streaming handler functions and ordinary handler functions differ here. When an ordinary handler function’s token is tripped, the framework gives up at the “waiting for it to return” step; when a streaming handler function’s token is tripped, it gives up at “the next pull.” With the former you can only rely on the token throwing by itself; with the latter, even if you never pass the token, the framework stops asking for another frame after the next yield return. So streaming cancellation looks more “responsive,” but that is only appearance. The steps that should stop inside the handler function still have to stop themselves.

What if an ordinary handler function simply does not take a token? On the surface it looks the same. Click cancel, the UI stops waiting, and the status line reads “Cancellation requested.” But the code on the server is still running. When it finishes, its result is discarded; if it writes a file, that file has already been written. Cancellation means “the UI stopped waiting,” not “the server stopped working” — those two become one only when you pass the token. Every step in the example carries the token, so “stopped waiting” and “stopped working” happen at the same time.

17.3 The Cancel Button That Does Not Queue

The cancel button says queue: false. This is not optional decoration.

The queue is first-in-first-out (Chapter 15). An event goes in and waits for the ones ahead of it to finish before its turn comes. If the cancel button also queued, it would have to line up behind “the very task it wants to cancel.” By the time its turn comes, the task has already finished.

The example puts two cancel buttons side by side precisely to show this. Both are attached to the same long task, both set concurrencyId: "Tasks" with a concurrency limit of 1, and the only difference is queue.

  • “Cancel” has queue: false, does not enter the queue, and takes effect immediately when clicked;
  • “Queued cancel” has none, enters the queue, and lines up with the long task.

Click “Queued cancel” while the task is running and the UI stays so quiet you suspect the click did not register. The status line keeps reading “Standby” while the steps keep growing. It really is waiting. Only when the task finishes is it let through, and then what it does is “cancel a run that has already ended” — it cancels nothing and leaves only a “Cancellation requested” line in the status.

Figure 17-2 Queued cancel: the status still reads “Standby” while the steps have already reached step 6

Switch to “Cancel” with queue: false, click at the same moment, and it stops after at most another half second. The steps stop at whatever step they were on (step 5 in Figure 17-3), and the status reads “Cancellation requested.”

Figure 17-3 The non-queued cancel stops as soon as you click; the steps already produced stay where they are

Look at the two figures together and the difference is not in the button, but in “the moment its turn comes.”

The cancel button also has a handler function of its own (Cancel in the example) that writes just one status line. That line is not optional either. Without it, nothing on the UI changes after you click cancel. Cancellation itself is silent (17.5), so the user has no evidence that “the click registered.” That is why a cancel button almost always needs a line of text, even if it is only “Cancellation requested.”

Incidentally, this handler function is also outside the queue (queue: false along with its binding). If it queued, the “the click registered” line would also appear only after the task finished, which is the same as not writing it.

Let me also clear up an easy source of confusion. “Queued cancel” queues because it and the long task are in the same concurrency group (concurrencyId: "Tasks"). By default each binding forms its own group, in which case “Queued cancel” would run immediately and you would see no difference at all. It would still cancel the same long task, just with nothing blocking it. The example deliberately sets the groups equal to put “queuing” out in the open.

queue: false has a second benefit: it bypasses the queue size limit. Chapter 15 sets maxSize to 2, and new requests are rejected when the queue is full. If “Cancel” were also in the queue, it would be exactly when you need it most that you could not click it. The “Clear panel” button in the example also has queue: false, for the same reason.

The price is that it is not subject to the concurrency limit. A non-queued event starts running immediately, so its handler function must be very light. Cancel, clear, toggle — buttons like these all meet that condition; they change a few lines of text and do no heavy work. Conversely, a handler function that reads a file or computes for ages written with queue: false is like tearing out the queue’s gate: all the limits from Chapter 15 stop working.

One more detail. When a queue: false event errors out, the user still sees an “Error” block, but since it is not in the queue, the queued count in /gradio_api/queue/status does not change because of it. When debugging “I clicked and nothing happened,” this distinction is useful: check first whether it is in the queue.

To find out how many things are waiting at a given moment, there are two places to look. One is the queue: 1/1 badge in the top-right corner of the panel (Chapter 15) — it is right there in the UI, easy to glance at. The other is to ask the endpoint directly, GET /gradio_api/queue/status, where queue_size is the number waiting; you can ask without the UI at all. Use the latter when writing a load-test script or tracking down “who exactly filled the queue.”

Finally, something common in real use. A user starts a task, sees no response, clicks again, then again. Three are now queued. They click cancel, only one is cleared, the UI is still spinning; they think cancellation is broken and keep clicking. To avoid this, make “the click registered” visible immediately. The button becomes “Cancel,” and the status line reads “Queued, position 2.” The example does not do button states, only status text. “Queued, position 2” explains where you are in the wait, but to mark “you can cancel now” in the UI, the button still has to change to “Cancel.”

17.4 Keeping Completed Results and Clearing Incomplete Output

What should the UI look like after cancellation? The example’s answer comes in two halves.

Frames already delivered stay; undelivered ones are not filled in. The steps cell stops at step 5 and stays at step 5. It does not fall back to blank, nor jump to step 6. Cancellation means “do not compute any further.”

The final result cell stays as it is. The reason lies in how the intermediate frames are written. Every frame outputs (step, gr.Skip()), and gr.Skip() means “leave this cell alone”; only when the loop finishes is a real result emitted once. So at cancellation the result cell still reads “no result yet” and has not been polluted by half-finished data.

Figure 17-4 Halfway through: the steps are growing and the result cell still reads “no result yet”

This figure and Figure 17-3 are two moments of the same thing. In the first the steps are still growing, in the second they have stopped; in both, the result cell reads “no result yet.” That contrast is exactly “keep what is completed, never show what is not.”

Why gr.Skip() instead of “output the previous frame’s value once more”? Because there is no such thing as a “previous frame” inside the handler function. All it has is where the computation currently stands. To output it once more you would have to keep your own lastResult — one more variable, one more assignment, and one more overwrite. With gr.Skip() the framework holds that cell down for you, and the function writes only this one word.

With multiple outputs, the position of gr.Skip() has to line up with outputs. The example’s outputs is [work.Steps, work.Result], so the tuple’s first item is the step (changes every frame) and the second is the result (always Skip). Getting them backwards raises no error; it just means that after cancellation the “Result” cell turns into the step text. Chapter 16 covered this point, and here it shows up again.

The steps cell uses Markdown, so **Steps** renders as bold; switch to Textbox and those two asterisks show up literally (Chapter 8). The division of labor between the two panels is set the same way. The steps are explanatory text showing current progress, so use Markdown; the result may need to be copied away later, and Markdown works for that too, but if you want to leave room for copying, switch to Textbox.

gr.Skip() is not only for streaming. When an ordinary handler function returns several values and you only want to change one of them, return gr.Skip() for the rest and the UI will not flicker. Chapter 3 covered gr.Update(); the difference between the two is this. Update means “change to these properties,” Skip means “leave this cell alone.” Use Update to change one cell’s properties, Skip to leave it completely untouched.

“Clear panel” does exactly one thing: reset all three cells together. It is not split into three buttons, “Clear steps,” “Clear result,” “Clear status.” Split it and the user needs three clicks to get back to the start, and the two intermediate states (only the steps cleared) are meaningless in themselves. If one operation can say it all, do not split it into three steps.

The opposite way of writing it is common: write intermediate results into the result cell too (“currently at step 5”). Then after cancellation the user sees “currently at step 5” and can easily take it away as the answer. The result cell holds only the final result; put intermediate states elsewhere — steps, progress, status, any of them.

Cleanup is a separate matter. After cancellation, the half-finished data left on the UI has to be cleared sooner or later, so the example provides “Clear panel” and, along the way, reads out the line recorded in finally: “last stopped at step 5.” That line is both a receipt for the cleanup and evidence that “cancellation really happened.”

That line is stored inside TaskBoard like this.

    /// <summary>Record which step this run stopped at.</summary>
    public static void Stopped(int done) => Volatile.Write(ref _lastStop, done);

    /// <summary>Which step it stopped at last time, told to the user.</summary>
    public static string LastStop
    {
        get
        {
            var done = Volatile.Read(ref _lastStop);
            return done < 0 ? "Not run yet." : $"Last stopped at step {done}.";
        }
    }

One integer, two atomic reads and writes. Cancellation and clearing can happen at the same time (the user clicks fast), so a plain field will not do.

But to be clear: this _lastStop is one number shared by the entire application, not one per session. If one person stops at step 5 and another clicks clear, the second sees “last stopped at step 5” — someone else’s record. The example writes it this way to keep things simple; a real product would put it in session state (Chapter 14), or just keep it in the UI and not carry it across requests.

There is one more detail at the top of the panel. While the task is running, a thin line runs along the top edge of that block. That is the progress bar’s default style. ProgressDisplay.Minimal draws only the line, no text. Chapter 16 used ProgressDisplay.Full, which adds a small “Step N · xx%” label; the third value is Hidden, which draws nothing. Pick among the three levels by occasion. Use Full for a long task meant for people to watch, Minimal when you only want to show “it’s moving,” and Hidden when the handler function reports no progress at all. Keeping a line that reports no number can only say “it’s running” and cannot say “how far along” — you are better off not drawing it.

There is also a question people often forget. After cancellation, if you refresh the page, is that “half-finished” data still there? The answer is no. The panel’s values follow the session (Chapter 14); a refresh is a new session, and everything goes back to its initial value. So “cleanup” actually has two layers: one is the button, for users who do not want to refresh; the other is the session, for users who have refreshed. Do neither and the UI keeps the old data from last time, and users cannot tell this run’s data from the previous one.

17.5 Telling Cancellation, Failure, and Timeout Apart

The three kinds of “did not finish” look completely different in the UI, and this section lays them out.

Cancellation is silent. After clicking cancel there is no toast and no error block; the UI simply stops changing. That is correct. The user pressed it themselves and does not need to be told again. The example adds a line of status text in the cancellation handler as confirmation that “the click registered,” not as an error.

There are two kinds of failure. When the handler function throws an ordinary exception (the example’s “Fail” button), an “Error” block appears in the result area with no toast. That is because the exception message is for developers and should not be pasted straight onto the user’s screen. Throw Error (the example’s “Business error” button) and a toast pops up in the top-right corner with that sentence appearing verbatim; the result area gets an error block too. It shares the same landing spot as an ordinary exception — the only difference is whether that toast is there.

Figure 17-5 Business error: the toast shows the sentence the handler function wrote

Where is the difference? An ordinary exception means “the program hit something it did not expect”; the user cannot follow the details and should only know “this run did not succeed.” Error means “the program expected this, it is a business rule,” and that sentence is written for the user to read.

Timeout you build yourself. The framework sets no execution time limit for ordinary tasks (17.7 covers this), so the example sets its own.

    /// <summary>
    /// Do a piece of work; if it exceeds <paramref name="limit"/>, give up and return false.
    /// When the caller cancels itself (the token is triggered), it does not count as a timeout and is rethrown as-is.
    /// </summary>
    public static async Task<bool> WorkAsync(TimeSpan work, TimeSpan limit, CancellationToken token)
    {
        using var gate = CancellationTokenSource.CreateLinkedTokenSource(token);
        gate.CancelAfter(limit);

        try
        {
            await Task.Delay(work, gate.Token);
            return true;
        }
        catch (OperationCanceledException) when (!token.IsCancellationRequested)
        {
            return false;
        }
    }

Three lines are the key. CreateLinkedTokenSource joins “user cancellation” and “the time limit you set” together; CancelAfter trips it automatically when the time comes; the when after catch separates the two cases. If the outer token was not tripped, the time limit is up; if the outer token was tripped, it is a user cancellation, and in that case you should not say “timeout.”

Once the handler function gets false, it throws a sentence a person can understand.

async Task<string> Timeout(CancellationToken token)
{
    var finished = await TaskBoard.WorkAsync(TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(3), token);

    if (!finished)
    {
        throw new Error("Waited too long: still not done after three seconds, so this run is dropped.");
    }

    return "**Result** ten seconds of work finished within three seconds.";
}

Figure 17-6 Timeout: the toast says “waited too long” and an error block appears in the result area

The user’s next action is completely different in the three cases. After cancellation they may want to change a parameter and rerun; after failure they should check the log or find a developer; after timeout they should split the task smaller or come back later. Write all three as “something went wrong” and those three actions become indistinguishable.

There are three more things to watch when writing this. First, do not catch everything with catch (Exception). Catch every exception and you mix “user cancellation” together with “the program crashed.” If you catch, catch something specific: give OperationCanceledException its own catch, and do not catch the rest — let them bubble up to the framework and become an error block, which is where they belong.

Second, the granularity of a timeout equals the granularity of await. When CancelAfter reaches its time it only trips the token; the real interruption happens at the next await. If there is a twenty-second stretch of synchronous computation in between, the timeout does not take effect at the third second either — it takes effect after that stretch finishes. To be precise, slice the long computation into segments and check once between segments.

Third, do not turn a timeout into “pretend it finished”. Return an empty result or half-finished data and the user will take it for the answer. Say plainly that it timed out; better to leave that cell empty.

Should you retry automatically? The answer differs in the three cases. A timeout can be retried once, but loosen the time limit a little or the second run ends the same way; with failure it depends on whether the action is idempotent. Querying data can be retried, charging a payment cannot; cancellation must never be retried — the user has clearly said no, and running it again is the worst experience.

Set the three wordings side by side. Cancellation is “you told it to stop, it stopped at step 5”; failure is “it broke on its own, this run did not succeed”; timeout is “it was too slow, no result came back.” The subject of each sentence is different. Cancellation belongs to the user, failure to this run, timeout to the waiting — and each one says what to do next.

It is also worth logging them separately. Log “cancelled at step N” for cancellation, the exception type and message for failure, and “gave up after N seconds” for timeout. All three carry a start time and the number of steps completed. When you later want to know “how long did that run actually take and where did it stall,” those three numbers are what you rely on. The example writes no log because it puts all three things into the UI; an application that really goes live needs both sides.

17.6 Error and Runtime Notifications

This section has two Errors, so tell them apart first. One is the exception type Gradio.Net.Error: throw it with throw new Error("...") and this run counts as failed. The other is the gr.Error(...) method, which only reports one sentence and lets the run continue. Same name, opposite jobs.

The Error exception is the exit the framework leaves for “the business rules say no.” The timeout and business error in 17.5 both use it.

string Biz() => throw new Error("Not allowed by the business: no new orders this month.");

Once thrown, the UI does two things. An “Error” block appears in the result area, and a toast pops up in the top-right corner with the title Error and that sentence as its body, staying for ten seconds by default. Besides that sentence, the type carries four optional parameters: duration (give it null or 0 and it stays until the user closes it), visible, title, and printException. The last one controls logging. For a “normal rejection” like a form filled in wrong, there is no need to write a stack trace into the log every time, so you can set it to false. Ordinary exceptions take a different route: only an error block, no toast, a generic sentence on the UI, with the details kept on the server (17.5).

The four runtime notification functions are another route.

// Illustration: the example calls only one of these functions
gr.Info("This is a piece of information", 8);
gr.Warning("Watch this step");
gr.Error("There is a problem here, the task continues");
gr.Success("All four notifications sent");

All four functions take two parameters: a sentence, and how many seconds to show it; omit the seconds and it defaults to ten. All four return void. The levels are info, warning, error, and success, and the default titles are simply those capitalized: Info, Warning, Error, Success. The toast picks its icon and color by level: red for error, yellow for warning, green for success, neutral gray for info.

They do not change this run. They do not interrupt the handler function, take up no output slot, and do not change values already on the UI. The example’s “Validate and run” uses one of them.

string Checked(string text)
{
    gr.Success("Validation passed, result updated.");
    return $"**Result** Validation passed, received '{text.Trim()}'.";
}

When the input is ok, click it and the result cell updates as usual while a green success toast appears in the top-right corner at the same time; the toast disappears on its own after ten seconds and the result stays. That is exactly where these functions belong: the work is done, so say a line in passing.

One boundary is easy to trip over. These four functions only recognize “the run that is currently executing.” The framework attaches the notification outlet to the handler function’s call: call them from inside the handler function and the message goes out with that run’s stream; call them during page construction, after startup, or from some other background thread and the outlet is empty — the call is quietly dropped and nothing appears on the UI. So they are neither logging functions nor global notification functions; if you want to send one, send it inside the handler function.

You can see what the message looks like without going through the UI. That gr.Success in the example emits a log message frame like this during the run (Chapter 22 explains how to read this stream).

data: {"msg":"log","event_id":"…","log":"Validation passed, result updated.","level":"success","duration":10,"visible":true,"title":"Success"}

The fields are a contract. log holds the body, level holds the level, title holds the title, and visible and duration control whether it is drawn and for how long. Omit the seconds and duration is 10; write 8 and it is 8. The field names match Python’s LogMessage: when the frontend gets a log message, these are exactly the names it reads, and there is no message field in this frame. Put the body in some other field and the message still goes out, but nothing is drawn on the page. So debugging splits into two steps. If there is no log frame at all, check whether the call landed inside the handler function; if there is a frame but no toast, compare those five fields one by one.

The four toasts are drawn in the top-right corner of the page, stacked, and disappear when their time is up. That “they disappear” is the boundary between them and the status panel. One-off notifications go through toasts; conclusions that need to leave a trace go into the panel. What leaves a trace in the example are those Markdown panels. The “Status” cell records cancellation and clearing, the result cell records validation passed. Cancellation writes “Cancellation requested; the steps already produced stay where they are,” clearing writes “Panel cleared. Last stopped at step 5,” and validation passed writes “Validation passed, received ‘ok’.” All three are short and stay there until the next operation changes them.

So there are four routes for giving the user feedback; pick by whether to interrupt and whether to leave a trace.

  • throw new Error("..."). Interrupts the run, error block plus toast, for “this run did not succeed.”
  • Any exception. Interrupts the run, error block only, for “the program hit something it did not expect.”
  • The four notification functions. No interruption, one-off, for “say a line in passing.”
  • A status panel you write yourself. No interruption, leaves a trace, for “something you still need to see next time you open it.”

There is one rule for writing notification text: a single sentence needs two things — what happened, and what to do next. “Something went wrong” gives only the first; “Waited too long. Still not done after three seconds, so this run is dropped” gives both. The toast floats in the top-right corner, covering what the user is looking at, so the body should be no more than a line and a half; if you really need three lines, that is the status panel’s job. Keep the log and the UI separate too. The log holds stack traces, parameters, and timestamps; the UI holds only one sentence and one way out — do not stuff debugging information into a toast.

17.7 Binding-Level Validation and Execution Time Limits

Some requests should never reach the handler function at all: empty input, wrong format, no permission. Letting the handler function check itself works too, but by then it has already “entered the handler function.” It took up a concurrency slot and ran once before discovering it should have been turned back at the door.

A concrete example. An “Import spreadsheet” button, clicked when the user has not selected a file. The handler function’s first line checks “the file is empty, return immediately,” which looks fine, but it has already gone into the queue and taken a slot. A few hundred misclicks a day and these empty runs are queue slots wasted for nothing.

validator is what turns people back at the door. It is an optional parameter on the binding, a delegate by type; the example writes it as Func<string, string?>.

    job.CheckRun.Click(Checked, [job.Check], [work.Result], apiName: "Validate and run", validator: (Func<string, string?>)Validate);
string? Validate(string text) =>
    text.Trim() == "ok" ? null : throw new Error($"Only ok is accepted here, but got '{text.Trim()}'.");

Parameters are injected in the order of inputs, the same contract as handling (Chapter 3). Put one Textbox in inputs and the validator accepts one string; framework-injected parameters like Progress, CancellationToken, and Request can also appear in the validator’s signature. Return null to let it through; return any other string or throw an exception and it is a rejection.

Rejection happens before queuing, so the handler function never runs once, no concurrency slot is taken, and that queue spot is freed immediately. When the queue is full, a batch of bad requests will not shut out the good ones. The endpoint puts the reason in detail. Returning a string gives 422, throwing an exception gives 400; the example takes the latter. On the page the result cell does not change by a single character, the top-right corner states the reason, and the result area is marked “Error” (Figure 17-7).

Figure 17-7 The validator rejects: the result area does not change by a single character and the top-right corner explains why

Returning a string and throwing an exception both reject. The only difference is the status code: returning a string gives 422, throwing gives 400. The example uses throw new Error(...), taking the 400 route; change the validator to text.Trim() == "ok" ? null : "Only ok is accepted here" and it blocks the request just as well, and that sentence on the page is still perfectly readable.

The validator and the checks inside the handler function divide the work differently. What you can decide up front goes in the validator; what you only know after running goes in the handler function. Whether the input is empty, whether it is ok — the validator answers in a second; “whether this file actually has any data” needs opening it first, and that is the handler function’s job. The validator also sees only the values in inputs. To check “does this person have permission” or “is this file still there,” get permission from an injected service (Chapter 21) and check the file’s existence yourself.

Do not do heavy work in the validator. It sits on the request path and runs on every click; query a database or read a large file and the user first feels “I clicked and nothing happened” before seeing the rejection. If you really must query, cache the result in state (Chapter 14). Validate on the frontend too. The frontend layer is “telling you the format is wrong as you type” — fast, with no server resources. The validator layer blocks requests that bypass the UI and go through /call (Chapter 22). Write both: the frontend for experience, the validator for correctness.

One more boundary: the validator is attached to the queue entrance. The direct /run call from Chapter 22 does not go through the queue, so it does not pass the validator either. Call /run/Validate and run directly with bad and the handler function runs as usual and hands back its result as usual. To block every entrance, the check still has to stay in the handler function.

timeLimit is another optional parameter on the binding, typed double?, and null if you omit it. The name tempts you into reading too much into it. It is not “how many seconds this run may take at most,” and not “how many seconds it may wait in the queue at most.” What it governs is the kind of run where the browser feeds the server frame by frame. As Chapter 16 explained, when a media component has streaming: true, the browser sends each frame to /stream/<event_id> and the handler function runs once along with it.

Remember the boundary in three parts.

  • Ordinary tasks are not covered. Add timeLimit: 3 to the example’s “Long task” and try it: that streaming task of twenty steps at half a second each still runs for ten seconds and hands back its result normally. The ten-second task is advanced frame by frame by the queue itself; the client has nothing to send, so there is no clock to watch.
  • Queue waiting is not covered. A request sitting in the queue is not rejected for waiting too long; the limit only affects this run’s budget and sets no countdown for people in the queue.
  • Input-stream runs go by budget. The first call’s duration is recorded as first_iteration, and the time for each later frame wait plus rerun is added to run_time; once the total reaches the limit, generation stops after the current frame is produced. Intermediate frames send process_streaming; with a nonzero limit, the frame carries a time_limit whose value is the limit minus the first call’s duration. The timeout while waiting for the next frame is computed as “limit minus the first call’s duration”; with no limit it starts at 30 seconds, and writing timeLimit: 0 also falls back to 30 seconds; when the first call uses up the entire budget, there is no more waiting. The output stream that the queue advances itself still sends process_generating, with no time_limit.

The corresponding field written into /config is time_limit, and its value is exactly the number you gave the binding. The easiest way to confirm the boundary is to add a very small limit to an ordinary task and see whether it still runs; then try a binding with an input stream. The parameter having a place in the signature and a place in the config, and which segment it actually governs, are two different things.

So the execution time limit for ordinary tasks still has to be built yourself — that is the WorkAsync from 17.5, CancelAfter plus one Error, within twenty lines. When writing it, keep two things separate: the limit has to be told apart from user cancellation (that when filter), and after a timeout you have to give a sentence a person can understand.

Look at validation and the time limit together and they are two halves of the same idea. Validation governs “should this start,” the input-stream budget governs “should this continue.” Both are decided outside the handler function, so the handler function only has to do the work; but an ordinary task’s “should this continue” has no ready-made budget, so that part is still your own job.

17.8 Chapter Summary

The four “endings that went badly” each have their own wording in the UI.

Cancellation rests on two things. The handler function takes an injected CancellationToken, and the binding says cancels: [that binding]. The token has to be passed all the way down — carry it into Task.Delay, SendAsync, and await foreach for cancellation to work; in a synchronous loop you call ThrowIfCancellationRequested yourself, because the token will not interrupt it for you.

The cancel button needs queue: false. A queued cancel waits until the task finishes before its turn comes, and by then there is nothing left to cancel. The same reasoning applies to buttons like clear and toggle; the price is that they are outside the concurrency limit, so their handler functions must be very light.

Split the output into two cells. What is completed goes into the result cell; what is not goes into steps, progress, or status; intermediate frames use gr.Skip() to hold the result cell down. That way after cancellation the user sees “how far it got,” not “a half-finished answer.” Cleanup has two layers too: the button clears once, and refreshing the page clears again.

The three endings must be describable separately. Cancellation is silent, both kinds of failure give an error block (the business error adds a toast on top), and the timeout you build yourself with CancelAfter plus a sentence a person can understand. Write all of them as “something went wrong” and the user has no idea what to do.

The validator stands at the door. What you can decide on the request path does not belong in the handler function. It takes no concurrency slot and changes nothing on the UI. The /run that skips the queue does not pass through it, so when every entrance has to be blocked, the check still needs a copy inside the handler function.

timeLimit governs only input-stream runs. Ordinary tasks and queue waiting are both outside it; the execution time limit for ordinary tasks you build yourself with CancelAfter.

To “let the user see,” there are four routes: the four runtime notification functions like gr.Info, the toast (throw new Error), the error block (any exception), and a status panel you write yourself. One-off notifications use the toast and those four functions; conclusions that need to leave a trace go into the panel.

The token lets the task stop, queue: false lets cancel actually be clicked, the two-cell output makes what stopping looks like clear, and the three wordings let the user know what to do next.

The next chapter changes direction and splits this page into several pages. Dozens of panels stacked on one page take several screens to scroll to the bottom, and finding a button means first remembering which block it is in. That is already “cannot find it.”