Skip to content

Commit fd9b573

Browse files
asg017claude
andcommitted
Thread the trigger actor through the run instead of stashing it per task
The actor who pressed "Run now" was kept in a scheduler dict keyed only by task name, and popped by whichever run of that task finished first. A manual trigger force-runs regardless of overlap_policy, so a scheduled run already in flight could finish first, consume the stash and drop it (it emits trigger="scheduled"), leaving the actor's own RunFinishedEvent with actor=None. Two quick manual triggers by different users swapped actors the same way: the second trigger overwrote the stash, so the first run to finish was attributed to the second user. `concerns` drives notification routing in consumers, so this notifies the wrong person about the wrong run. The actor belongs to one execution, so carry it there: _spawn_execution takes actor_id and forwards it through _execute_task to _emit_run_finished. A scheduled run passes nothing, which is already the right semantics, and overlapping runs cannot see each other's actor at all. The dict and the "pop unconditionally so it can't leak" mitigation both go away. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
1 parent 66ee71c commit fd9b573

2 files changed

Lines changed: 171 additions & 16 deletions

File tree

‎datasette_cron/scheduler.py‎

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -94,10 +94,6 @@ def __init__(self, datasette):
9494
# fetched.
9595
self._last_tick_finished: float | None = None
9696
self._task_snapshot: list[CronTask] = []
97-
# Task name -> actor id of the person who last pressed "Run now",
98-
# consumed (popped) the moment the resulting run finishes so it
99-
# can't leak onto some later, unrelated run of the same task.
100-
self._last_trigger_actor: dict[str, str] = {}
10197

10298
@property
10399
def internal_db(self) -> InternalDB:
@@ -157,12 +153,16 @@ def _spawn_execution(
157153
force: bool = False,
158154
scheduled_at: str | None = None,
159155
now: datetime | None = None,
156+
actor_id: str | None = None,
160157
) -> str:
161158
"""Spawn _execute_task, respecting overlap_policy unless force=True.
162159
163160
Returns the outcome: "started", "skipped" (blocked by overlap), or
164161
"cancelled" (started after cancelling in-flight runs). Manual
165162
triggers pass force=True so the user's "Run now" always fires.
163+
164+
`actor_id` belongs to *this* execution and travels with it, so
165+
overlapping runs of one task can never claim each other's actor.
166166
"""
167167
name = task.name
168168
running = {t for t in self._running_tasks.get(name, ()) if not t.done()}
@@ -190,6 +190,7 @@ def _spawn_execution(
190190
run_span_kwargs=run_span_kwargs,
191191
scheduled_at=scheduled_at,
192192
now=now,
193+
actor_id=actor_id,
193194
)
194195
)
195196
self._running_tasks.setdefault(name, set()).add(exec_task)
@@ -244,19 +245,17 @@ async def trigger_task(self, name: str, actor_id: str | None = None) -> None:
244245
execution is in flight. The concurrent run is tracked and visible
245246
in the runs table with status='running'.
246247
247-
`actor_id`, when given, names who pressed "Run now"; it is stashed
248-
in-memory (no migration) and attached to the `RunFinishedEvent` this
249-
run produces, if any.
248+
`actor_id`, when given, names who pressed "Run now"; it is carried
249+
by this execution alone (no migration) and attached to the
250+
`RunFinishedEvent` this run produces, if any.
250251
"""
251252
task = await self.internal_db.get_task(name)
252253
if not task:
253254
raise ValueError(f"Task not found: {name}")
254255
handler_fn = self.get_handler(task.handler)
255256
if not handler_fn:
256257
raise ValueError(f"Handler not found: {task.handler}")
257-
if actor_id:
258-
self._last_trigger_actor[name] = actor_id
259-
self._spawn_execution(task, handler_fn, force=True)
258+
self._spawn_execution(task, handler_fn, force=True, actor_id=actor_id)
260259

261260
async def set_enabled(self, name: str, enabled: bool) -> None:
262261
"""Enable or disable a task. A no-op for unknown task names."""
@@ -428,6 +427,7 @@ async def _execute_task(
428427
run_span_kwargs: dict | None = None,
429428
scheduled_at: str | None = None,
430429
now: datetime | None = None,
430+
actor_id: str | None = None,
431431
) -> None:
432432
name = task.name
433433
config = task.config
@@ -594,6 +594,7 @@ def record_attempt_metrics(outcome: str, attempt: int, elapsed: float) -> None:
594594
trace_id,
595595
span_id,
596596
trigger,
597+
actor_id,
597598
)
598599
finally:
599600
# Remove ourselves from the in-flight set; clean up empty entries.
@@ -614,6 +615,7 @@ async def _emit_run_finished(
614615
trace_id: str | None,
615616
span_id: str | None,
616617
trigger: str,
618+
actor_id: str | None,
617619
) -> None:
618620
"""Fire `RunFinishedEvent` on error/cancel/recovery, never on a
619621
routine success.
@@ -623,13 +625,11 @@ async def _emit_run_finished(
623625
(`get_task` in `trigger_task`) and never refreshed mid-run -- so
624626
`task.last_status` is the status *before* this run, exactly the
625627
"previous status" the transition rule needs.
626-
"""
627-
# Pop unconditionally (not only when we go on to emit) -- a manual
628-
# trigger's stashed actor must not leak onto some later, unrelated
629-
# run of the same task just because *this* run was a routine
630-
# success that emits nothing.
631-
actor_id = self._last_trigger_actor.pop(task.name, None)
632628
629+
`actor_id` was handed to the execution that is finishing, so it can
630+
only ever describe this run: scheduled runs pass None, and two
631+
overlapping manual runs each keep their own.
632+
"""
633633
previous = task.last_status
634634
if status == "success" and previous not in ("error", "cancelled"):
635635
return

‎tests/test_events.py‎

Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,22 @@ def track_event(datasette, event):
3030
pm.unregister(name="test_events_capture")
3131

3232

33+
async def _wait_for_run_events(capture, count, timeout=5.0):
34+
"""Poll until `count` RunFinishedEvents have been captured, then return
35+
them. Polling (rather than a fixed sleep) keeps the overlapping-run
36+
tests deterministic without depending on how long a run takes."""
37+
loop = asyncio.get_running_loop()
38+
deadline = loop.time() + timeout
39+
while True:
40+
run_events = [e for e in capture if isinstance(e, RunFinishedEvent)]
41+
if len(run_events) >= count:
42+
return run_events
43+
assert loop.time() < deadline, (
44+
f"Timed out waiting for {count} RunFinishedEvents, got {len(run_events)}"
45+
)
46+
await asyncio.sleep(0.01)
47+
48+
3349
@pytest.mark.asyncio
3450
async def test_failing_handler_emits_one_error_event(capture):
3551
ds, scheduler = await _make_scheduler()
@@ -178,6 +194,145 @@ async def failing_handler(datasette, config):
178194
await scheduler.shutdown()
179195

180196

197+
def _gated_failing_handler(slots):
198+
"""Return a handler whose Nth call sets `entered[N]`, waits for
199+
`release[N]`, then fails -- so a test can interleave two runs of one
200+
task and decide which finishes first. `slots` is (entered, release)."""
201+
entered, release = slots
202+
calls = 0
203+
204+
async def handler(datasette, config):
205+
nonlocal calls
206+
index = calls
207+
calls += 1
208+
entered[index].set()
209+
await release[index].wait()
210+
raise RuntimeError("boom")
211+
212+
return handler
213+
214+
215+
def _two_slots():
216+
return ([asyncio.Event(), asyncio.Event()], [asyncio.Event(), asyncio.Event()])
217+
218+
219+
@pytest.mark.asyncio
220+
async def test_scheduled_run_does_not_steal_an_overlapping_actor(capture):
221+
"""A scheduled run that overlaps a manual one must not take its actor.
222+
223+
The actor travels with the execution, so the run order cannot change who
224+
each event is attributed to. Here the scheduled run is spawned first and
225+
finishes first, while Alex's manual run is still in flight.
226+
"""
227+
ds, scheduler = await _make_scheduler()
228+
229+
slots = _two_slots()
230+
entered, release = slots
231+
scheduler.register_handlers("test", {"gated": _gated_failing_handler(slots)})
232+
await scheduler.add_task(
233+
name="overlap-actor-task",
234+
handler="test:gated",
235+
schedule={"interval": 99999},
236+
overlap="allow",
237+
)
238+
239+
# Run 0 -- scheduled: force the task due and run a single tick.
240+
await scheduler.internal_db.update_next_run(
241+
"overlap-actor-task", "2000-01-01T00:00:00"
242+
)
243+
await scheduler._tick()
244+
await asyncio.wait_for(entered[0].wait(), timeout=2.0)
245+
246+
# Run 1 -- manual: Alex presses "Run now" mid-flight (force ignores
247+
# overlap_policy, so both runs are live at once).
248+
await scheduler.trigger_task("overlap-actor-task", actor_id="alex")
249+
await asyncio.wait_for(entered[1].wait(), timeout=2.0)
250+
251+
# The scheduled run finishes first. Its event must carry no actor...
252+
release[0].set()
253+
run_events = await _wait_for_run_events(capture, 1)
254+
assert run_events[0].actor is None
255+
assert run_events[0].concerns == []
256+
257+
# ...and Alex's own run must still carry Alex when it finishes second.
258+
release[1].set()
259+
run_events = await _wait_for_run_events(capture, 2)
260+
assert run_events[1].actor == {"id": "alex"}
261+
assert run_events[1].concerns == ["alex"]
262+
263+
await scheduler.shutdown()
264+
265+
266+
@pytest.mark.asyncio
267+
async def test_two_manual_triggers_keep_their_own_actors(capture):
268+
"""Two users triggering the same task must not swap actors.
269+
270+
Alex triggers first and finishes first; Bob triggers second. Each event
271+
is attributed to the person who started that run.
272+
"""
273+
ds, scheduler = await _make_scheduler()
274+
275+
slots = _two_slots()
276+
entered, release = slots
277+
scheduler.register_handlers("test", {"gated": _gated_failing_handler(slots)})
278+
await scheduler.add_task(
279+
name="two-actor-task",
280+
handler="test:gated",
281+
schedule={"interval": 99999},
282+
overlap="allow",
283+
)
284+
285+
await scheduler.trigger_task("two-actor-task", actor_id="alex")
286+
await asyncio.wait_for(entered[0].wait(), timeout=2.0)
287+
await scheduler.trigger_task("two-actor-task", actor_id="bob")
288+
await asyncio.wait_for(entered[1].wait(), timeout=2.0)
289+
290+
release[0].set()
291+
run_events = await _wait_for_run_events(capture, 1)
292+
assert run_events[0].concerns == ["alex"]
293+
294+
release[1].set()
295+
run_events = await _wait_for_run_events(capture, 2)
296+
assert run_events[1].concerns == ["bob"]
297+
298+
await scheduler.shutdown()
299+
300+
301+
@pytest.mark.asyncio
302+
async def test_scheduled_run_after_manual_trigger_has_no_actor(capture):
303+
"""An actor must not linger past the run it triggered.
304+
305+
A later scheduled run of the same task is nobody's doing, so its event
306+
carries no actor and concerns nobody.
307+
"""
308+
ds, scheduler = await _make_scheduler()
309+
310+
async def failing_handler(datasette, config):
311+
raise RuntimeError("boom")
312+
313+
scheduler.register_handlers("test", {"fail-handler": failing_handler})
314+
await scheduler.add_task(
315+
name="later-scheduled-task",
316+
handler="test:fail-handler",
317+
schedule={"interval": 99999},
318+
)
319+
320+
await scheduler.trigger_task("later-scheduled-task", actor_id="alex")
321+
run_events = await _wait_for_run_events(capture, 1)
322+
assert run_events[0].actor == {"id": "alex"}
323+
324+
# Now let the schedule fire it: force the task due and run one tick.
325+
await scheduler.internal_db.update_next_run(
326+
"later-scheduled-task", "2000-01-01T00:00:00"
327+
)
328+
await scheduler._tick()
329+
run_events = await _wait_for_run_events(capture, 2)
330+
assert run_events[1].actor is None
331+
assert run_events[1].concerns == []
332+
333+
await scheduler.shutdown()
334+
335+
181336
@pytest.mark.asyncio
182337
async def test_raising_consumer_does_not_change_run_status(capture):
183338
ds, scheduler = await _make_scheduler()

0 commit comments

Comments
 (0)