Coverage for core / src / sensorkit / common / dag.py: 99%

259 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-11-24 01:04 +0000

1# SPDX-License-Identifier: Apache-2.0 

2"""Dependency graphs and asynchronous execution. 

3 

4`Node` holds one unit of work with a payload interpreted by the caller's 

5dispatcher. `GraphBuilder` adds nodes and dependencies, then checks for cycles. 

6`DagRunner` executes the graph and returns node outcomes in a `RunReport`. 

7The caller decides whether those outcomes should raise an exception. 

8 

9A soft edge requires completion. A hard edge requires success; an unsuccessful 

10dependency skips its dependents unless that dependency uses `on_failure="continue"`. 

11The dependency's failure policy controls propagation: 

12 

13- `stop` stops further dispatch. 

14- `skip` skips hard dependents and allows independent work to continue. 

15- `continue` treats outgoing hard edges as completion dependencies. 

16 

17`Node.optional` excludes a failed node from required failures. 

18`Node.override` records an outcome without dispatching. Its reason also follows 

19any skips it causes; these are excluded from required failures. 

20`RunReport.failures` contains required failed or skipped nodes, excluding 

21canceled nodes and skips caused only by overrides. 

22 

23Cancellation cancels in-flight nodes and waits for them to finish. The caller's 

24`Absorbed` predicate classifies each cancellation as a requested abort or a 

25cancellation to propagate. A requested abort returns an aborted result. Any 

26unrecognized cancellation propagates after in-flight work finishes. 

27""" 

28 

29from __future__ import annotations 

30 

31import asyncio 

32from collections import Counter 

33from collections.abc import Awaitable, Callable, Iterable 

34from dataclasses import dataclass 

35from typing import Literal 

36 

37from loguru import logger 

38 

39type Absorbed = Callable[[BaseException], bool] 

40"""Predicate recognizing cancellation as a caller-requested abort. 

41 

42The caller distinguishes an abort from service shutdown because both arrive as 

43cancellation. Each cancellation is classified as it arrives. Once a cancellation 

44is rejected by the predicate, it propagates after in-flight work finishes. 

45Omitting the predicate propagates every cancellation. 

46""" 

47 

48type OnFailure = Literal["stop", "skip", "continue"] 

49"""How far a node's failure spreads. A frontend's table-level setting is the 

50default its nodes take.""" 

51 

52 

53@dataclass(frozen=True) 

54class NodeOverride: 

55 """What to record for a node instead of dispatching it. 

56 

57 `reason` is required, since a report of a step not running has to say who 

58 decided. 

59 """ 

60 

61 outcome: Literal["ok", "skipped"] 

62 reason: str 

63 

64 

65@dataclass(frozen=True) 

66class Node: 

67 id: int 

68 label: str # one-line human description 

69 group: str # display grouping: phase / step 

70 payload: object # frontend-defined; opaque here 

71 on_failure: OnFailure = "stop" # failure propagation policy 

72 optional: bool = False # True: my failure degrades, not fails 

73 delay_s: float = 0.0 # timed start after deps resolve 

74 override: NodeOverride | None = None # set: don't dispatch, record this 

75 

76 

77@dataclass(frozen=True) 

78class Graph: 

79 nodes: tuple[Node, ...] 

80 deps: dict[int, frozenset[int]] # all dependencies (scheduling order) 

81 hard: dict[int, frozenset[int]] # subset whose failure skips this node 

82 

83 def topo_order(self) -> list[int]: 

84 """Node ids in an order where every dependency precedes its dependents. 

85 

86 Raises: 

87 ValueError: The graph has a dependency cycle. The message names one 

88 cycle by its node labels. 

89 """ 

90 indeg = Counter({n.id: len(self.deps[n.id]) for n in self.nodes}) 

91 dependents: dict[int, list[int]] = {n.id: [] for n in self.nodes} 

92 

93 for nid, ds in self.deps.items(): 

94 for d in ds: 

95 dependents[d].append(nid) 

96 

97 order = [nid for nid, deg in indeg.items() if deg == 0] 

98 

99 for nid in order: 

100 indeg.subtract(dependents[nid]) 

101 order.extend(dep for dep in dependents[nid] if indeg[dep] == 0) 

102 

103 if len(order) < len(self.nodes): 

104 labels = {n.id: n.label for n in self.nodes} 

105 cycle = self._cycle(set(indeg) - set(order)) 

106 raise ValueError("dependency cycle in graph: " + " -> ".join( 

107 labels[nid] for nid in cycle)) 

108 

109 return order 

110 

111 def _cycle(self, stuck: set[int]) -> list[int]: 

112 """One cycle among the nodes the topological sort could not order. 

113 

114 Each of them waits on another of them, so following those edges 

115 revisits a node. 

116 """ 

117 path: list[int] = [] 

118 nid = min(stuck) 

119 

120 while nid not in path: 

121 path.append(nid) 

122 nid = min(self.deps[nid] & stuck) 

123 

124 return path[path.index(nid):] + [nid] 

125 

126 def format(self) -> str: 

127 """Dry-run view, grouping nodes into topological levels. 

128 

129 The header names the prevailing `on_failure`. A node is annotated only 

130 where it deviates, is optional, or is overridden, and an override's 

131 reason replaces the rest. 

132 

133 !!! warning "A level is not a barrier" 

134 

135 A level is each node's earliest possible depth, and nothing 

136 synchronizes it. Peers on one line need not start together, and peers 

137 on different lines are ordered only by edges. Read edges, not levels, 

138 to see what waits for what. 

139 """ 

140 level: dict[int, int] = {} 

141 for nid in self.topo_order(): 

142 level[nid] = 1 + max((level[d] for d in self.deps[nid]), default=-1) 

143 

144 groups: dict[int, list[Node]] = {} 

145 for n in self.nodes: 

146 groups.setdefault(level[n.id], []).append(n) 

147 

148 prevailing = Counter(n.on_failure for n in self.nodes).most_common(1) 

149 default = prevailing[0][0] if prevailing else "stop" 

150 

151 def marks(n: Node) -> str: 

152 if n.override is not None: 

153 return f" (override {n.override.outcome}: {n.override.reason})" 

154 flags = ([n.on_failure] if n.on_failure != default else []) + ( 

155 ["optional"] if n.optional else []) 

156 return f" ({', '.join(flags)})" if flags else "" 

157 

158 lines = [f"on_failure: {default}"] 

159 for lvl in sorted(groups): 

160 labels = dict.fromkeys(n.group for n in groups[lvl]) 

161 lines.append(f"[{' + '.join(labels)}]") 

162 lines += [f" {n.label}{marks(n)}" for n in groups[lvl]] 

163 

164 return "\n".join(lines) 

165 

166 

167class GraphBuilder: 

168 """Mutable accumulator for a `Graph`. 

169 

170 Ids follow insertion order, and a compiler may index back into nodes it has 

171 added to decide later edges. `build` freezes the edges and checks for cycles. 

172 """ 

173 

174 def __init__(self) -> None: 

175 self._nodes: list[Node] = [] 

176 self._soft: list[set[int]] = [] 

177 self._hard: list[set[int]] = [] 

178 

179 def __len__(self) -> int: 

180 return len(self._nodes) 

181 

182 def __getitem__(self, nid: int) -> Node: 

183 return self._nodes[nid] 

184 

185 def add(self, label: str, group: str, payload: object, *, 

186 soft: Iterable[int] = (), hard: Iterable[int] = (), 

187 on_failure: OnFailure = "stop", optional: bool = False, 

188 delay_s: float = 0.0, override: NodeOverride | None = None) -> int: 

189 """Append a node and return its id.""" 

190 nid = len(self._nodes) 

191 self._nodes.append(Node(id=nid, label=label, group=group, 

192 payload=payload, on_failure=on_failure, 

193 optional=optional, delay_s=delay_s, 

194 override=override)) 

195 self._soft.append(set(soft)) 

196 self._hard.append(set(hard)) 

197 return nid 

198 

199 def require(self, nid: int, deps: Iterable[int]) -> None: 

200 """Add hard edges to an already-added node, for dependencies only known 

201 once the rest of a phase has been built.""" 

202 self._hard[nid] |= set(deps) 

203 

204 def order(self, nid: int, deps: Iterable[int]) -> None: 

205 """Add soft edges to an already-added node, for ordering only known once 

206 the rest of a phase has been built.""" 

207 self._soft[nid] |= set(deps) 

208 

209 def build(self) -> Graph: 

210 graph = Graph( 

211 nodes=tuple(self._nodes), 

212 deps={i: frozenset(self._soft[i] | self._hard[i]) 

213 for i in range(len(self._nodes))}, 

214 hard={i: frozenset(self._hard[i]) 

215 for i in range(len(self._nodes))}, 

216 ) 

217 graph.topo_order() # raises on cycles 

218 return graph 

219 

220 

221type Dispatch = Callable[[Node], Awaitable[object]] 

222 

223 

224@dataclass 

225class NodeResult: 

226 status: Literal["ok", "failed", "skipped", "cancelled"] 

227 error: BaseException | None = None 

228 value: object = None # whatever the dispatcher returned 

229 # The override reason when nothing was dispatched, this node's or the one its 

230 # skip follows from. Status is left as is, so edge rules read it unchanged. 

231 overridden: str | None = None 

232 

233 def report_line(self, node: Node) -> str | None: 

234 """One report line for a node worth mentioning, or None for a plain 

235 success.""" 

236 if self.overridden: 

237 head = f" {'overridden':<10}" 

238 return f"{head} {node.group}: {node.label}: {self.overridden}" 

239 if self.status == "ok": 

240 return None 

241 

242 why = f": {self.error}" if self.error else "" 

243 return f" {self.status:<10} {node.group}: {node.label}{why}" 

244 

245 

246@dataclass 

247class RunReport: 

248 """Node outcomes for one graph run, including optional failures.""" 

249 

250 name: str 

251 graph: Graph 

252 results: dict[int, NodeResult] 

253 aborted: bool = False 

254 

255 def with_status(self, *statuses: str) -> list[tuple[Node, NodeResult]]: 

256 return [(n, self.results[n.id]) for n in self.graph.nodes 

257 if n.id in self.results and self.results[n.id].status in statuses] 

258 

259 @property 

260 def failures(self) -> list[tuple[Node, BaseException | None]]: 

261 """Non-optional nodes that failed or never ran, which a frontend's raise 

262 policy reads. 

263 

264 A skipped node carries no error, and its cause is among `causes`. Overridden 

265 nodes and the skips following from them are excluded. 

266 """ 

267 return [(n, r.error) for n, r in self.with_status("failed", "skipped") 

268 if not n.optional and r.overridden is None] 

269 

270 @property 

271 def overridden(self) -> list[tuple[Node, str]]: 

272 """Nodes an override kept from running, and the skips that followed, each 

273 with its reason.""" 

274 return [ 

275 (n, r.overridden) 

276 for n in self.graph.nodes 

277 if (r := self.results.get(n.id)) is not None and r.overridden is not None 

278 ] 

279 

280 @property 

281 def causes(self) -> list[tuple[Node, BaseException | None]]: 

282 """The failures everything else followed from. 

283 

284 A node skips only when a hard dependency did not succeed, so the roots are 

285 exactly the failed nodes. 

286 """ 

287 return [(n, r.error) for n, r in self.with_status("failed")] 

288 

289 @property 

290 def degraded(self) -> list[tuple[Node, BaseException | None]]: 

291 return [(n, r.error) for n, r in self.with_status("failed") 

292 if n.optional] 

293 

294 @property 

295 def ok(self) -> bool: 

296 return not self.aborted and all( 

297 r.status == "ok" for r in self.results.values()) 

298 

299 def summary(self) -> str: 

300 # Overridden nodes count as their own kind, since an operator most needs to 

301 # tell a decided skip from a failure. 

302 counts = Counter("overridden" if r.overridden else r.status for r in self.results.values()) 

303 

304 head = f"[{self.name}] " + " ".join( 

305 f"{k}={counts[k]}" for k in 

306 ("ok", "failed", "skipped", "overridden", "cancelled") 

307 if k in counts) 

308 if self.aborted: 

309 head += " (aborted)" 

310 

311 lines = [head] 

312 for n in self.graph.nodes: 

313 r = self.results.get(n.id) 

314 if r is not None and (line := r.report_line(n)) is not None: 

315 lines.append(line) 

316 

317 return "\n".join(lines) 

318 

319 

320def log_summary(report: RunReport) -> None: 

321 """Log what a run did, since a report otherwise reaches nobody unless a 

322 frontend raises on it. 

323 

324 Warns for anything short of a clean run, so a degraded outcome is visible 

325 without one. 

326 """ 

327 if report.ok: 

328 logger.info(report.summary()) 

329 else: 

330 logger.warning(report.summary()) 

331 

332 

333class RunState: 

334 """Bookkeeping for one execution: what has resolved, what is in flight, what 

335 is left, and the rules for moving a node from one to the other. 

336 

337 Nothing here dispatches. A runner settles the state, starts whatever is ready, 

338 and hands each task back as it ends. `drain` is where the in-flight ones go 

339 when the run is cancelled. 

340 """ 

341 

342 def __init__(self, graph: Graph, 

343 results: dict[int, NodeResult] | None = None): 

344 self.graph = graph 

345 self.nodes = {n.id: n for n in graph.nodes} 

346 self.results: dict[int, NodeResult] = {} if results is None else results 

347 self.running: dict[asyncio.Task, int] = {} 

348 self.pending = set(self.nodes) 

349 self.stop = False 

350 

351 def ready(self, nid: int) -> bool: 

352 return all(d in self.results for d in self.graph.deps[nid]) 

353 

354 def blockers(self, nid: int) -> list[NodeResult]: 

355 """Resolutions of a node's hard dependencies that keep it from running. 

356 

357 Ordering edges are satisfied by any resolution, and so is a hard 

358 dependency that declared `on_failure="continue"`, since it states its own 

359 failure propagation policy. 

360 """ 

361 return [ 

362 r 

363 for d in self.graph.hard[nid] 

364 if (r := self.results.get(d)) is not None 

365 and r.status != "ok" 

366 and self.nodes[d].on_failure != "continue" 

367 ] 

368 

369 def skip_pass(self) -> bool: 

370 moved = False 

371 for nid in list(self.pending): 

372 if not (causes := self.blockers(nid)): 

373 continue 

374 # A skip following only from overridden steps is the override's doing 

375 # rather than a failure, so it carries the reason on and stays out of 

376 # `failures`. One genuine failure among the causes makes it an 

377 # ordinary skip again. 

378 excused = (causes[0].overridden 

379 if all(c.overridden for c in causes) else None) 

380 self.results[nid] = NodeResult("skipped", overridden=excused) 

381 self.pending.discard(nid) 

382 moved = True 

383 

384 return moved 

385 

386 def resolve_skips(self) -> None: 

387 """Skip every node a hard dependency blocks, cascading along hard edges.""" 

388 while self.skip_pass(): 

389 pass 

390 

391 def override_pass(self) -> bool: 

392 moved = False 

393 for nid in sorted(self.pending): 

394 if self.ready(nid) and (ov := self.nodes[nid].override) is not None: 

395 self.results[nid] = NodeResult(ov.outcome, overridden=ov.reason) 

396 self.pending.discard(nid) 

397 moved = True 

398 

399 return moved 

400 

401 def settle(self) -> None: 

402 """Resolve everything that resolves without dispatching. 

403 

404 An overridden node can make dependents ready or skip them, and both must 

405 settle before anything ready dispatches. Skips resolve first each round, so 

406 a node whose hard dependency genuinely failed keeps its cause. 

407 """ 

408 moved = True 

409 while moved: 

410 self.resolve_skips() 

411 if self.stop: 

412 return 

413 moved = self.override_pass() 

414 

415 def take_ready(self) -> list[int]: 

416 """Remove and return the pending nodes whose dependencies have resolved.""" 

417 nids = [nid for nid in sorted(self.pending) if self.ready(nid)] 

418 self.pending.difference_update(nids) 

419 return nids 

420 

421 def record(self, task: asyncio.Task) -> None: 

422 """Record how a dispatched node ended, and whether it stops the run.""" 

423 nid = self.running.pop(task) 

424 

425 if task.cancelled(): 

426 self.results[nid] = NodeResult("cancelled") 

427 elif (err := task.exception()) is not None: 

428 self.results[nid] = NodeResult("failed", err) 

429 self.stop = self.stop or self.nodes[nid].on_failure == "stop" 

430 else: 

431 self.results[nid] = NodeResult("ok", value=task.result()) 

432 

433 def cancel_pending(self) -> None: 

434 for nid in self.pending: 

435 self.results[nid] = NodeResult("cancelled") 

436 self.pending.clear() 

437 

438 async def drain(self, absorbed: Absorbed | None = None 

439 ) -> asyncio.CancelledError | None: 

440 """Cancel the in-flight nodes, wait for every one to end, then record how 

441 each ended. 

442 

443 A cancellation reaching the drain itself is passed on to the nodes still 

444 running and held, so the drain never ends before its nodes do. 

445 

446 Args: 

447 absorbed: Which of those cancellations were the caller's own domain 

448 abort, asked as each arrives until one is declined. 

449 

450 Returns: 

451 The first cancellation reaching the drain that `absorbed` declined. 

452 """ 

453 declined: asyncio.CancelledError | None = None 

454 

455 for task in self.running: 

456 task.cancel() 

457 

458 while not all(task.done() for task in self.running): 

459 try: 

460 await asyncio.wait(self.running) 

461 except asyncio.CancelledError as e: 

462 if declined is None and not _claims(absorbed, e): 

463 declined = e 

464 

465 for task in self.running: 

466 task.cancel() 

467 

468 for task in list(self.running): 

469 self.record(task) 

470 

471 return declined 

472 

473 

474def _claims(absorbed: Absorbed | None, 

475 cancellation: asyncio.CancelledError) -> bool: 

476 """Whether the caller recognizes a cancellation as its own domain abort.""" 

477 return absorbed is not None and absorbed(cancellation) 

478 

479 

480class DagRunner: 

481 """Execute dependency graphs using a caller-supplied dispatcher. 

482 

483 Callers can compile and inspect a graph before executing it. 

484 """ 

485 

486 def __init__(self, dispatch: Dispatch): 

487 self.dispatch = dispatch 

488 

489 async def execute(self, graph: Graph, *, name: str = "", 

490 absorbed: Absorbed | None = None, 

491 results: dict[int, NodeResult] | None = None) -> RunReport: 

492 """Run a graph to its end, or until a cancellation drains it. 

493 

494 Args: 

495 graph: What to run. 

496 name: What the report is called. 

497 absorbed: Which cancellations were the caller's own domain abort. 

498 results: Where each node's result is recorded as it ends. A caller 

499 passes its own to keep them once a cancellation propagates, 

500 since no report is returned then. 

501 

502 Returns: 

503 What every node did, marked aborted where `absorbed` recognized every 

504 cancellation that reached the run. 

505 

506 Raises: 

507 asyncio.CancelledError: The first cancellation `absorbed` declined, 

508 once every in-flight node has ended and been recorded. 

509 """ 

510 state = RunState(graph, results) 

511 

512 try: 

513 while True: 

514 self._start_ready(state) 

515 if not state.running: 

516 if state.pending and not state.stop: 

517 raise RuntimeError( # unreachable: builder checks cycles 

518 f"{name}: dependency deadlock") 

519 break 

520 

521 done, _ = await asyncio.wait( 

522 state.running, return_when=asyncio.FIRST_COMPLETED) 

523 for task in done: 

524 state.record(task) 

525 

526 state.resolve_skips() 

527 state.cancel_pending() 

528 

529 return RunReport(name, graph, state.results) 

530 

531 except asyncio.CancelledError as cancellation: 

532 # Classified now, since the caller's intent may change while the 

533 # nodes drain. A hard cancellation is final, so nothing later is 

534 # asked about. 

535 hard = not _claims(absorbed, cancellation) 

536 

537 # Drain in-flight nodes whoever cancelled, or their work outlives 

538 # the run. 

539 declined = await state.drain(None if hard else absorbed) 

540 state.cancel_pending() 

541 

542 if hard: 

543 raise 

544 

545 if declined is None: 

546 return RunReport(name, graph, state.results, aborted=True) 

547 

548 # Chained to the cancellation whose drain it arrived during. 

549 raise declined from cancellation 

550 

551 def _start_ready(self, state: RunState) -> None: 

552 """Settle what needs no dispatch, then dispatch whatever is left ready.""" 

553 state.settle() 

554 if state.stop: 

555 return 

556 

557 for nid in state.take_ready(): 

558 task = asyncio.create_task(self._run_node(state.nodes[nid])) 

559 state.running[task] = nid 

560 

561 async def _run_node(self, node: Node) -> object: 

562 if node.delay_s > 0: 

563 await asyncio.sleep(node.delay_s) 

564 return await self.dispatch(node)