Skip to content

With latest_wins, a superseded call still runs its delayed actions and holds up the newer call #306

Closed

Description

@JuroOravec

What happens

A handler declared with @event(latest_wins=True) returns a delayed
action without wait=False, so the actions after it wait for it:

class Events:
    @event(latest_wins=True)
    def search(self, data: SearchIn):
        return [
            actions.Dispatch("Search:done", delay=2),
            actions.Data(find(data.query)),
        ]

The user calls search once, and then again within those 2 seconds,
while the browser is still waiting on the first call's delay:

  • The first call's promise rejects with superseded, as documented.
  • 2 seconds after the first response, the first call's Search:done
    event is still dispatched, although that call was reported as
    replaced.
  • The second call is not sent until the first call's delay ends. A
    delayed action without wait=False holds back later calls, as
    documented, but the first call was already rejected, so the second
    call waits for nothing.
  • When the first call's actions finish, the bridge reports it as a
    success: the loading tracker behind $loading() records a success,
    and citry:events:after fires with {ok: true}, for a call whose
    promise already rejected.

This breaks two documented promises. The latest_wins docstring
(citry/ext/events/handlers.py) says an in-flight call "is abandoned
(its response is ignored when it arrives)". The superseded row of the
stale reasons table in docs_site/content/reference/browser-apis.md
says a newer call replaced this one.

Every action after the delay still runs, delayed or not: Dispatch,
Redirect, PushUrl, ReplaceUrl, and Data. The one exception is a
later Render, which notices the cancellation and stops. A delayed
state action runs too. Citry's own server never delays a State
refresh, but an on_event_result hook or another server that speaks
the protocol can send one. A wait=False action scheduled earlier in
the same list also runs, if its timer fires before the newer call's
result is accepted.

Why

In packages/js/citry-client/src/citry-events-vue.ts,
supersedeEarlier calls cancel() on the active job. That rejects the
caller's promise, but the bridge keeps running the job's remaining
actions, then calls activity.succeed and the after lifecycle as for
any finished call.

applyActions waits on delay() (line 446, used at line 600). Unlike
the code that applies a Render, delay() does not watch
job.cancelled, the promise that rejects when the call is cancelled.
When the timer fires, continuationCurrent still passes. It compares
against acceptedEpoch, the bridge's count of accepted results for
each component instance, and that count has not changed, because the
newer call is still queued behind this one.

Reproduction

Found with a TLA+ model of the bridge (see #308) and confirmed
with this test against the bridge source at 05db9ce6b. It fails with
actual: ['event:old', 'state:old-token'], and the second call
resolves only after both of the first call's delays end:

test("a superseded call changes nothing on the page", async () => {
  const descriptor = {
    componentClassId: "Board_1",
    eventHandlers: {
      move: {
        httpMethod: "POST",
        usesState: true,
        latestCallWins: true,
      },
    },
  };
  const record = [];
  const host = {
    ...basicHost(() => ({ ...contextFor(), descriptor })),
    commitState(_target, token) {
      record.push(`state:${token}`);
    },
    dispatchEvent(name) {
      record.push(`event:${name}`);
    },
  };
  let calls = 0;
  const bridge = bridgeModule.createVueEventsBridge({
    endpoint: "/events",
    host,
    fetch: async (_url, init) => {
      calls += 1;
      const envelope = JSON.parse(init.body);
      return resultResponse(
        envelope,
        calls === 1
          ? [
              { action: "event", eventName: "old", delay: 0.05 },
              {
                action: "state",
                targetRenderId: "server_1",
                stateToken: "old-token",
                publicState: {},
                delay: 0.01,
              },
              { action: "data", value: 1 },
            ]
          : [{ action: "data", value: 2 }],
      );
    },
  });
  const source = { stableId: "board", generation: 1 };
  const first = bridge.send({ source, handler: "move" });
  first.catch(() => {});
  // Call 1 is accepted and waiting on its 50 ms delay.
  await new Promise((resolve) => setTimeout(resolve, 10));
  const second = bridge.send({ source, handler: "move" });
  await assert.rejects(first, /superseded/);
  assert.equal(await second, 2);
  assert.deepEqual(record, []);
});

basicHost, contextFor and resultResponse are the helpers in
packages/js/citry-client/test/vue-events.test.mjs.

Fix direction

When a job is cancelled, stop the rest of its actions:

  • Race the blocking delay() against job.cancelled, as the Render
    code already does, so the queue moves on to the newer call at once.
  • Have continuationCurrent reject a cancelled job. That also covers
    the job's wait=False actions. Clearing their timers directly would
    need per-job tracking, because the bridge stores timers per component
    instance (state.timers), not per job.
  • Report each dropped action through citry:events:stale with reason
    superseded, matching what the caller already sees.

Dropping a superseded call's wait=False actions is a design choice:
the latestCallWins row in packages/protocol/events/v1/spec.md talks
only about the queue. Decide it and say it in the spec.

Two related problems to fix in the same pass:

  • runQueue reports success for a job that has already settled. Gate
    activity.succeed and the after lifecycle on !job.settled. This
    fix stands on its own.
  • applyActionsExternally without a source waits on a plain
    setTimeout that even dispose() does not stop.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugjavascript

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions