Skip to content

Fix package prompt cancellation and stale file-read isolation - #16

Open
UlfBissbort wants to merge 1 commit into
ageron:mainfrom
UlfBissbort:fix/package-prompt-lifecycle
Open

UlfBissbort wants to merge 1 commit into
ageron:mainfrom
UlfBissbort:fix/package-prompt-lifecycle

Conversation

@UlfBissbort

Copy link
Copy Markdown

Summary

This PR fixes two small lifecycle bugs in web/package-dialog.mjs. Both have the same shape: async work that belongs to an old prompt affects a newer one.

  1. A new request for a package can inherit the cancellation of an earlier request for the same URL.
  2. A file read started in a closed package dialog can close or modify the dialog that replaced it.

The fixes are two small guards (2 lines added, 3 lines changed). Four new regression tests fail on current main and pass with the fixes.

Bug 1: a new request can join a prompt that is already cancelled

When the last requester of a prompt leaves, leave() aborts the group's controller immediately. However, the group stays in this.current until the dialog's rejection reaches settle(), a few microtasks later. During that window, request() still treats the group as joinable, because it only skips settled groups:

[this.current,...this.queue].find(g=>g && !g.retry && !g.settled && g.url===url)

In the diagram below, the green box is the window in which B joins a group that is already cancelled:

sequenceDiagram
    participant A as Requester A
    participant P as PackagePrompts
    participant D as Dialog
    participant B as Requester B

    A->>P: request a.tar.zst
    P->>D: open prompt for group G
    A->>P: abort
    rect rgba(110, 200, 140, 0.25)
        Note over P: G is aborted but still current
        B->>P: request a.tar.zst
        Note over P: G is not settled, so B joins G
    end
    D-->>P: rejects with AbortError
    P-->>A: rejected
    P-->>B: rejected, B was never cancelled
Loading

B is rejected with AbortError, although nothing cancelled B. It should get a fresh prompt instead.

How likely is this in practice? Probably rare today. The window only lasts a few microtasks, and package requests normally come from worker messages, which arrive as separate tasks. We did not find a current UI path that hits it, so this is best seen as a latent bug in the coordinator's contract. It would surface as soon as some caller re-requests a package in reaction to a cancellation.

The fix skips aborted groups when looking for a group to join:

g=>g && !g.retry && !g.settled && !g.controller.signal.aborted && g.url===url

B then creates its own group, which waits in the queue until the old one settles. We considered settling or removing the group directly in leave() instead, but then B's prompt could open while the old dialog is still closing, with both using the same DOM elements. The guard preserves the existing rule that only one prompt is active at a time, and it does not change the queue order.

Bug 2: a late file read can act on the replacement dialog

When the user picks a file, openDialog() starts file.arrayBuffer() and awaits it. When the read completes, it checks whether it should still act:

if(signal.aborted || !dialog.open)return;
cleanup();resolve(bytes);

The problem is that dialog.open describes the shared <dialog> element, not this particular call to openDialog(). If the user closes the dialog and another prompt opens before the read finishes, dialog.open is true again, so the old read acts on the new prompt (green box):

sequenceDiagram
    participant U as User
    participant O as Prompt 1
    participant S as Shared dialog element
    participant N as Prompt 2

    U->>O: choose a large file
    O->>O: start file read
    U->>S: close dialog
    S-->>O: close event, Prompt 1 rejected
    N->>S: showModal, open is true again
    rect rgba(110, 200, 140, 0.25)
        O->>O: read completes
        Note over O: checks dialog.open, which is true
        O->>S: cleanup calls dialog.close
    end
    Note over N: Prompt 2 is closed by Prompt 1
Loading

The signal.aborted check does not help here: closing the dialog rejects the call, but it does not abort its signal. What happens to the new prompt depends on how the old read ends:

  • If the read succeeds, the old cleanup() closes the new dialog.
  • If the read fails, the old error message is written into the new dialog's status line, and its Load button is re-enabled.

A user could hit this with two notebooks that need different packages: pick a large bundle for the first, close its dialog, and let the second notebook's prompt open before the read finishes. In a real browser, dialog.close() fires a close event, so we expect the second prompt to reject itself and its run to fail as cancelled. Our tests confirm that the old read closes or modifies the new dialog; we have not yet confirmed the resulting close event in a browser.

The fix gives each openDialog() call its own finished flag, set by its own cleanup():

let finished=false;
const cleanup=()=>{
  finished=true;
  // ...existing cleanup...
};
// After the read succeeds:
if(finished || signal.aborted || !dialog.open)return;
// After the read fails:
if(!finished && !signal.aborted && dialog.open) {/* show the error */}

arrayBuffer() cannot be cancelled, so the fix does not try to stop the read; it just makes a late result harmless. The attachment dialog already protects against the same situation (see the test "closing a pending attachment import releases the dialog and cannot affect a reopened notebook" in tests/attachment-dialog.test.mjs).

Tests

  • tests/workbench.test.mjs covers bug 1, with the first request aborted before the dialog opens, and after it opens. The second request is made before the old rejection is processed, and the test checks that it gets a new, non-aborted prompt and receives the selected bytes.
  • tests/package-dialog.test.mjs (new) covers bug 2, with the old read succeeding, and failing. It calls the real packageDialog.open() with a minimal fake document and a file whose read the test resolves by hand.

Results on main at 8476cc5:

  • The 4 new tests fail without the fixes, and pass with them.
  • node --test tests/*.test.mjs: 116 passed, 0 failed, 7 skipped (the local-server tests, which need the native binary).
  • We ran the tests with Node 25.9. CI uses Node 22, which we have not tested locally. We did not run the browser or WASM tests.

How we found these

We were trying out a model checker on Roclet (Zef-Spec, a tool we are developing, not public yet). The package prompts were a good target: a small state machine with async transitions, where the bugs come from timing rather than types.

Here is what happened, in order:

  1. While reading PackagePrompts, we suspected the window between abort and settle.
  2. A deterministic Node test confirmed it against the real code.
  3. Looking at the surrounding dialog lifecycle, we found the stale read and reproduced it the same way.
  4. We then wrote both behaviors as small specs, and checked them exhaustively, once with the original logic and once with the fixes.

The key modeling decision was to treat "abort", "dialog rejects" and "settle() runs" as separate steps, and likewise "user closes the dialog", "replacement opens" and "old read completes". It is tempting to model each group of steps as a single atomic transition, but then both bugs disappear from the model.

For the original logic, the checker returned these shortest counterexamples:

Bug 1: request_first → abort_first_alone → request_second_join → settle_cancel_first_with_live_joiner
Bug 2: open_old → start_file_read → user_close_old → open_replacement → late_read_error_affects_replacement
Model Original logic With the fix
Prompt queue 4-step counterexample (13 states explored) Property holds in all 31 reachable states
Dialog lifetime 5-step counterexample (17 states explored) Property holds in all 16 reachable states

These models are deliberately tiny: two requesters and one URL for the queue, one old dialog and one replacement for the dialog. "Holds" means the property holds in that model, not that the whole package flow is proven correct. The JS tests are what connect the models to the actual code.

What the spec looks like

Here is the core of the queue model. g0 is the first prompt group; j0 and j1 are the two requesters. The closing phase means "aborted but not settled yet", which is exactly the window from bug 1.

# Phases of g0 that a new request may join. The original logic also
# allows "closing": aborted but not yet settled. The fixed logic does not.
joinable = one_of(
    "g0", "opening", "active",
    *(["closing"] if broken else []),
)
waiting_on_old = all_of(
    equal("j1", "waiting"),
    equal("owner1", "g0"),
)

rule(
    "abort_first_alone",
    [equal("j0", "waiting"), ET.Not(operand=waiting_on_old)],
    {"j0": "cancelled", "g0": "closing"},
)

rule(
    "request_second_join",
    [equal("j1", "fresh"), joinable],
    {
        "j1": "waiting",
        "owner1": "g0",
        "joined_aborted": equal("g0", "closing"),
    },
)

rule(
    "settle_cancel_first_with_live_joiner",
    [equal("g0", "closing"), waiting_on_old],
    {
        "g0": "settled",
        "j1": "cancelled",
        "inherited_cancel": True,
    },
)

ET.Invariant(
    "live_request_does_not_inherit_prior_cancellation",
    formal=equal("inherited_cancel", False),
)

Each rule is an event with guards (when it may happen) and updates (what it changes). rule, equal, one_of and all_of are small helpers in our script that build Zef-Spec nodes such as ET.Rule, ET.Eq, ET.Or and ET.And. The checker explores every order in which the events can happen, and reports the shortest sequence that breaks the invariant.

If you would like to run the models yourself, I am, of course, happy to make Zef-Spec available. The tests in this PR do not need it.

This branch has not been deployed

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