Coverage for app / services / swarms / advice.py: 87%
179 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""What the record says about a swarm's shape — advice read from its runs and
2the evaluations that ran it, never asked of a model.
4A swarm costs more than one agent, and earns it only on work that splits
5into pieces done apart. Whether it does is in the record: how its lead
6planned, whether the pieces waited on each other, how often its reviews sent
7work back, whether runs stopped short of their caps, who was never given
8work — and, where an evaluation ran it beside single agents, which scored
9better per dollar. Each kind of advice is one registered class
10(:func:`register_advice`), read over the same :class:`Record`, and says what
11it saw in figures and what to try; a kind with too little to go on says
12nothing rather than guess.
14The runs read are the viewer's own of this swarm (runs belong to whoever
15dispatched them), an evaluation's included, newest first; the evaluations,
16those of the swarm's own workspace that have a variant answering with it.
17"""
19from __future__ import annotations
21from abc import ABC, abstractmethod
22from dataclasses import asdict, dataclass, field
23from typing import Any, ClassVar
25from sqlalchemy.orm import Session
27from app.db.postgres.enums import RunnableEnum, SwarmEnum
28from app.db.postgres.models import (
29 Experiment,
30 ExperimentBatch,
31 ExperimentVariant,
32 Swarm,
33 SwarmRun,
34)
35from app.services.swarms import topologies
36from app.services.swarms.schemas import Approach, TaskBrief
38RunStatus = SwarmEnum.RunStatus
39TaskKind = SwarmEnum.TaskKind
40TaskStatus = SwarmEnum.TaskStatus
42#: The finished runs read, newest first.
43RECENT_RUNS = 20
44#: A run that answered, from all or part of its work.
45ANSWERED = frozenset({RunStatus.completed, RunStatus.partial})
46FINISHED = ANSWERED | {RunStatus.failed}
47#: Scores this close are the same score.
48SCORE_TOLERANCE = 0.02
51@dataclass(frozen=True)
52class Comparison:
53 """One evaluation's newest finished run, as advice reads it: the
54 swarm's row and every other variant's."""
56 experiment_id: str
57 experiment_name: str
58 batch_id: str
59 finished: Any
60 swarm: dict[str, Any]
61 others: list[dict[str, Any]]
64@dataclass
65class Record:
66 """What advice reads."""
68 swarm: Swarm
69 runs: list[SwarmRun]
70 comparisons: list[Comparison] = field(default_factory=list)
72 @property
73 def planned(self) -> list[SwarmRun]:
74 """Runs whose lead's plan was read."""
75 return [
76 r for r in self.runs if isinstance(r.plan, dict) and r.plan.get("approach")
77 ]
80@dataclass(frozen=True)
81class Advice:
82 key: str
83 #: What it says, in a line.
84 title: str
85 #: What the record shows, in figures.
86 detail: str
87 #: What to try: ``evaluate`` (compare it with single agents), ``edit``
88 #: (change its shape, roster or caps) or ``open_evaluation``.
89 action: str
90 #: ``attention`` for something worth changing, ``good`` for a measured
91 #: strength.
92 tone: str = "attention"
93 evidence: dict[str, Any] = field(default_factory=dict)
94 experiment_id: str | None = None
96 def wire(self) -> dict[str, Any]:
97 return asdict(self)
100class AdviceKind(ABC):
101 key: ClassVar[str]
102 #: What it looks for, for the catalogue.
103 description: ClassVar[str]
105 @abstractmethod
106 def read(self, record: Record) -> Advice | None:
107 """What the record says, or None when it says nothing of this kind."""
110_KINDS: dict[str, AdviceKind] = {}
113def register_advice(cls: type[AdviceKind]) -> type[AdviceKind]:
114 _KINDS[cls.key] = cls()
115 return cls
118def kinds() -> list[dict[str, str]]:
119 return [{"key": k.key, "description": k.description} for k in _KINDS.values()]
122def _work(run: SwarmRun) -> list[Any]:
123 """A run's pieces of work, each once — not their redos."""
124 return [
125 t
126 for t in run.tasks or []
127 if t.kind == TaskKind.work
128 and t.status != TaskStatus.cancelled
129 and not TaskBrief.from_stored(t.brief).redoes
130 ]
133def _share(part: int, whole: int) -> str:
134 return f"{part} of {whole}"
137@register_advice
138class OnePiece(AdviceKind):
139 key = "one_piece"
140 description = "Its lead mostly planned the work as one piece."
142 def read(self, record: Record) -> Advice | None:
143 planned = record.planned
144 if len(planned) < 3:
145 return None
146 single = [r for r in planned if r.plan.get("approach") == Approach.one_agent]
147 if len(single) * 2 < len(planned):
148 return None
149 return Advice(
150 key=self.key,
151 title="Most of its runs needed one agent",
152 detail=(
153 f"In {_share(len(single), len(planned))} recent runs the lead "
154 "planned the work as one piece: one agent did it, and the plan "
155 "cost extra. Its lead alone may do as well for less."
156 ),
157 action="evaluate",
158 evidence={"runs": len(planned), "one_piece": len(single)},
159 )
162@register_advice
163class Sequential(AdviceKind):
164 key = "sequential"
165 description = "Its pieces mostly waited on one another."
167 def read(self, record: Record) -> Advice | None:
168 pieces = [p for r in record.planned for p in _work(r) if (p.depth or 0) == 1]
169 if len(pieces) < 6:
170 return None
171 waited = [p for p in pieces if p.depends_on]
172 if len(waited) * 2 < len(pieces):
173 return None
174 return Advice(
175 key=self.key,
176 title="Its work runs one piece after another",
177 detail=(
178 f"{_share(len(waited), len(pieces))} pieces in recent runs waited "
179 "for another to finish first. A team gains on work done apart; "
180 "work in sequence suits a pipeline, or one agent."
181 ),
182 action="edit",
183 evidence={"pieces": len(pieces), "waited": len(waited)},
184 )
187@register_advice
188class SentBack(AdviceKind):
189 key = "sent_back"
190 description = "Its reviews often sent pieces back."
192 def read(self, record: Record) -> Advice | None:
193 pieces = [p for r in record.runs for p in _work(r)]
194 redone = [
195 t
196 for r in record.runs
197 for t in r.tasks or []
198 if t.kind == TaskKind.work and TaskBrief.from_stored(t.brief).redoes
199 ]
200 if len(pieces) < 5 or len(redone) * 10 < len(pieces) * 3:
201 return None
202 lighter = any(
203 str(t.tier) == SwarmEnum.Tier.lighter for r in record.runs for t in _work(r)
204 )
205 fix = (
206 "Its workers answer on a lighter model: try each agent's own."
207 if lighter
208 else "Brief the workers better: a note on each says what it is for."
209 )
210 return Advice(
211 key=self.key,
212 title="Its reviews often send work back",
213 detail=(
214 f"Reviews sent back {_share(len(redone), len(pieces))} pieces in "
215 f"recent runs, each done again at extra cost. {fix}"
216 ),
217 action="edit",
218 evidence={"pieces": len(pieces), "sent_back": len(redone)},
219 )
222@register_advice
223class StoppedEarly(AdviceKind):
224 key = "stopped_early"
225 description = "Its runs often stopped short of their caps."
227 def read(self, record: Record) -> Advice | None:
228 runs = [r for r in record.runs if r.status in FINISHED]
229 if len(runs) < 2:
230 return None
231 short = [r for r in runs if r.wrap_up_reason in ("budget", "time")]
232 if len(short) * 2 < len(runs):
233 return None
234 money = sum(1 for r in short if r.wrap_up_reason == "budget")
235 why = "its budget" if money * 2 >= len(short) else "its time"
236 return Advice(
237 key=self.key,
238 title="Its runs often stop early",
239 detail=(
240 f"{_share(len(short), len(runs))} recent runs wrapped up when "
241 f"{why} ran low, answering from part of the work. Raise the "
242 "budget or time cap, or ask for fewer pieces."
243 ),
244 action="edit",
245 evidence={"runs": len(runs), "stopped": len(short), "for_budget": money},
246 )
249@register_advice
250class IdleMembers(AdviceKind):
251 key = "idle_members"
252 description = "Members its leads never gave work."
254 def read(self, record: Record) -> Advice | None:
255 planned = [r for r in record.planned if r.plan.get("approach") == Approach.team]
256 if len(planned) < 3:
257 return None
258 topology = topologies.get(str(record.swarm.topology))
259 if topology is None or not topology.plans:
260 return None
261 lead_role = topology.roles[0].key
262 worked = {str(t.agent_id) for r in planned for t in r.tasks or []}
263 idle = [
264 entry
265 for entry in record.swarm.roster or []
266 if isinstance(entry, dict)
267 and entry.get("role") != lead_role
268 and str(entry.get("agent_id")) not in worked
269 ]
270 if not idle:
271 return None
272 named = {
273 str(m.get("agent_id")): str(m.get("agent_name") or "")
274 for r in planned
275 for m in (r.config or {}).get("roster") or []
276 if isinstance(m, dict)
277 }
278 names = sorted({named.get(str(e["agent_id"])) or "" for e in idle} - {""})
279 who = ", ".join(names) or f"{len(idle)} of its members"
280 return Advice(
281 key=self.key,
282 title="Some members are never given work",
283 detail=(
284 f"{who} had no piece in {len(planned)} recent runs. Remove them, "
285 "or say what each is for in a note, which the lead reads."
286 ),
287 action="edit",
288 evidence={"runs": len(planned), "idle": len(idle)},
289 )
292def _cost(row: dict[str, Any]) -> float | None:
293 value = row.get("cost_per_case_usd")
294 return float(value) if isinstance(value, (int, float)) else None
297def _per_answer(first: float | None, second: float | None) -> str:
298 if first is None or second is None:
299 return ""
300 return f", for ${first:.3f} an answer against ${second:.3f}"
303@register_advice
304class Measured(AdviceKind):
305 key = "measured"
306 description = "How it scored beside single agents in an evaluation."
308 def read(self, record: Record) -> Advice | None:
309 for comparison in record.comparisons:
310 swarm = comparison.swarm
311 score = swarm.get("mean_score")
312 singles = [
313 o
314 for o in comparison.others
315 if (o.get("target") or {}).get("type") != "swarm"
316 and o.get("mean_score") is not None
317 ]
318 if score is None or not singles:
319 continue
320 best = max(singles, key=lambda o: o["mean_score"])
321 own_cost, best_cost = _cost(swarm), _cost(best)
322 label = (best.get("target") or {}).get("label") or "A single agent"
323 evidence = {
324 "swarm_score": score,
325 "single_score": best["mean_score"],
326 "swarm_cost_per_answer": own_cost,
327 "single_cost_per_answer": best_cost,
328 }
329 if best["mean_score"] >= score - SCORE_TOLERANCE:
330 return Advice(
331 key=self.key,
332 title="A single agent did as well",
333 detail=(
334 f"In “{comparison.experiment_name}”, {label} scored "
335 f"{best['mean_score']:.2f} against the swarm's {score:.2f}"
336 f"{_per_answer(best_cost, own_cost)}."
337 ),
338 action="open_evaluation",
339 evidence=evidence,
340 experiment_id=comparison.experiment_id,
341 )
342 return Advice(
343 key=self.key,
344 title="It beats a single agent",
345 detail=(
346 f"In “{comparison.experiment_name}”, it scored {score:.2f} "
347 f"against {best['mean_score']:.2f} for {label}, the best "
348 f"single agent{_per_answer(own_cost, best_cost)}."
349 ),
350 action="open_evaluation",
351 tone="good",
352 evidence=evidence,
353 experiment_id=comparison.experiment_id,
354 )
355 return None
358# ── Reading the record ───────────────────────────────────────────────────────
361def recent_runs(db: Session, swarm: Swarm, user_id: Any) -> list[SwarmRun]:
362 return (
363 db.query(SwarmRun)
364 .filter(
365 SwarmRun.swarm_id == swarm.id,
366 SwarmRun.user_id == user_id,
367 SwarmRun.status.in_([s.value for s in FINISHED]),
368 # First requests only: a follow-up is small by nature, and would
369 # read as a shape too big for its work.
370 SwarmRun.thread_seq == 1,
371 )
372 .order_by(SwarmRun.created_at.desc())
373 .limit(RECENT_RUNS)
374 .all()
375 )
378def comparisons(db: Session, swarm: Swarm) -> list[Comparison]:
379 """Each evaluation of the swarm's workspace with a variant answering
380 with it: its newest finished run, newest evaluation first."""
381 same_owner = [
382 column.is_(None) if value is None else column == value
383 for column, value in (
384 (Experiment.owner_user_id, swarm.owner_user_id),
385 (Experiment.owner_organisation_id, swarm.owner_organisation_id),
386 (Experiment.owner_project_id, swarm.owner_project_id),
387 )
388 ]
389 variants = (
390 db.query(ExperimentVariant)
391 .join(Experiment, Experiment.id == ExperimentVariant.experiment_id)
392 .filter(
393 ExperimentVariant.config["target"]["swarm_id"].as_string() == str(swarm.id),
394 *same_owner,
395 )
396 .all()
397 )
398 out: list[Comparison] = []
399 seen: set[str] = set()
400 for variant in variants:
401 experiment_id = str(variant.experiment_id)
402 if experiment_id in seen:
403 continue
404 seen.add(experiment_id)
405 batch = (
406 db.query(ExperimentBatch)
407 .filter(
408 ExperimentBatch.experiment_id == variant.experiment_id,
409 ExperimentBatch.status == RunnableEnum.Status.completed,
410 )
411 .order_by(ExperimentBatch.created_at.desc())
412 .first()
413 )
414 rows = [
415 r
416 for r in (batch.leaderboard if batch else None) or []
417 if isinstance(r, dict)
418 ]
419 own = next(
420 (r for r in rows if str(r.get("variant_id")) == str(variant.id)), None
421 )
422 if own is None:
423 continue
424 experiment = db.get(Experiment, variant.experiment_id)
425 out.append(
426 Comparison(
427 experiment_id=experiment_id,
428 experiment_name=str(getattr(experiment, "name", "") or "An evaluation"),
429 batch_id=str(batch.id),
430 finished=batch.created_at,
431 swarm=own,
432 others=[r for r in rows if r is not own],
433 )
434 )
435 out.sort(key=lambda c: str(c.finished or ""), reverse=True)
436 return out
439def advise(record: Record) -> list[Advice]:
440 """Every kind's advice on ``record``, in registry order."""
441 return [a for kind in _KINDS.values() if (a := kind.read(record)) is not None]
444def for_swarm(db: Session, swarm: Swarm, user_id: Any) -> list[Advice]:
445 return advise(
446 Record(
447 swarm=swarm,
448 runs=recent_runs(db, swarm, user_id),
449 comparisons=comparisons(db, swarm),
450 )
451 )