Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
91 commits
Select commit Hold shift + click to select a range
f393cb6
feat(standard): list a dataset's tasks by search and category
pierreleca Nov 23, 2026
8ac9175
feat(standard): save a named set of a dataset's tasks and run it with…
pierreleca Nov 23, 2026
f5df65c
feat(standard): let a benchmark's list name the list it is cut from
pierreleca Nov 23, 2026
e2e42bc
feat(catalogue): browse a dataset's tasks, save task sets and choose …
pierreleca Nov 23, 2026
8066f87
feat(catalogue): tick a task with a click on its row, its whole text …
pierreleca Nov 23, 2026
a7b8bfd
fix(catalogue): let a read-only list of tasks show a task's whole tex…
pierreleca Nov 23, 2026
2b15035
fix(runs): show a job's task set as a cell of its dataset card
pierreleca Nov 24, 2026
5501c4c
feat(standard): run chosen tasks of an ended job again in that job
pierreleca Nov 23, 2026
eeed68e
feat(standard): plan a run on the whole and begin it on a part
pierreleca Nov 23, 2026
abed722
feat(runs): run a job's tasks again from its page, where the job ran,…
pierreleca Nov 23, 2026
ac7d5e7
feat(builder): start a plan with all of it or with specific tasks
pierreleca Nov 23, 2026
1940a96
fix(runs): say how much of a part-run's plan has run in its Trials cell
pierreleca Nov 24, 2026
3672c66
Merge remote-tracking branch 'origin/main' into feat/task-sets-and-pages
pierreleca Nov 24, 2026
13ba912
docs(standard): shorten the task set docs to one line a rule
pierreleca Nov 24, 2026
46485fc
Merge branch 'feat/task-sets-and-pages' into feat/run-again-and-in-parts
pierreleca Nov 24, 2026
a6215db
docs(standard): shorten the docs of runs again and in parts
pierreleca Nov 24, 2026
266014b
Merge remote-tracking branch 'origin/main' into feat/task-sets-and-pages
pierreleca Nov 25, 2026
f2660b1
Merge branch 'feat/task-sets-and-pages' into feat/run-again-and-in-parts
pierreleca Nov 25, 2026
cbacf7f
fix(runs): draw a planned task with no result in the outcome cell's form
pierreleca Nov 25, 2026
732de9b
fix(runs): align a queued trial's steps cell with main's steps column
pierreleca Nov 25, 2026
f49334d
Merge remote-tracking branch 'origin/main' into feat/task-sets-and-pages
pierreleca Nov 25, 2026
56b5a54
Merge branch 'feat/task-sets-and-pages' into feat/run-again-and-in-parts
pierreleca Nov 25, 2026
e3e0119
refactor(web): draw the task set parts with the shared classes
pierreleca Nov 25, 2026
02a2ffa
docs(docs): pair the task set pages with their commands
pierreleca Nov 25, 2026
f565779
Merge branch 'feat/task-sets-and-pages' into feat/run-again-and-in-parts
pierreleca Nov 25, 2026
5b5f4a7
refactor(web): draw the run-again parts with the shared dialog and cl…
pierreleca Nov 25, 2026
b5104ef
docs(docs): pair the job page's run-again actions with their command
pierreleca Nov 25, 2026
74c7967
refactor(web): draw the spending cap's Change and Set as an action in…
pierreleca Nov 25, 2026
2d13f68
feat(catalogue): list the tasks of any benchmark from its tasks page
pierreleca Nov 25, 2026
6149c4d
fix(catalogue): drop the New task set menu of a benchmark with severa…
pierreleca Nov 25, 2026
079cf3e
fix(catalogue): give the save form's fields the height of its button
pierreleca Nov 25, 2026
c2f0434
fix(catalogue): open the paste box below the row of chosen tasks
pierreleca Nov 25, 2026
b1eb3f6
fix(catalogue): hide the tasks page's count and message lines while e…
pierreleca Nov 25, 2026
791fb83
feat(catalogue): mark GAIA's three levels as cut from All levels
pierreleca Nov 25, 2026
000837e
feat(catalogue): describe GAIA's and Open Telco's questions for their…
pierreleca Nov 25, 2026
fbded30
feat(standard): draw N of a dataset's tasks at random for a task set
pierreleca Nov 25, 2026
638fa62
Merge remote-tracking branch 'origin/main' into feat/task-sets-and-pages
pierreleca Nov 25, 2026
f0a78a8
fix(catalogue): no rule above the chosen tasks while the search is hi…
pierreleca Nov 25, 2026
cb9ccc9
test(standard): keep a listing test's token value out of the key pattern
pierreleca Nov 25, 2026
5f1201a
fix(standard): redact task listing driver secrets
pierreleca Nov 25, 2026
87d66ef
test(standard): pin task samples for two seeds
pierreleca Nov 25, 2026
0d37e99
fix(web): refuse invalid task sample numbers
pierreleca Nov 25, 2026
b6789d7
fix(standard): read a listing driver's stderr whatever its bytes
pierreleca Nov 25, 2026
f459767
fix(standard): redact a listing driver's secret as JSON or a URL hold…
pierreleca Nov 25, 2026
138c814
fix(standard): keep a listing's task texts whole beside its driver's …
pierreleca Nov 25, 2026
b87332a
test(web): keep the page test's token value out of the key pattern
pierreleca Nov 25, 2026
71cdd91
docs(docs): drop the row on refused draw numbers
pierreleca Nov 25, 2026
b6b4842
Merge branch 'feat/task-sets-and-pages' into feat/run-again-and-in-parts
pierreleca Nov 25, 2026
4491c6b
fix(builder): give the start-with dialog the tasks page's listing notice
pierreleca Nov 25, 2026
289ac3c
test(standard): give a stand-in listing the licences the listing passes
pierreleca Nov 25, 2026
a21647e
fix(runs): give Save as task set's fields the height of its button
pierreleca Nov 25, 2026
d791d1b
fix(catalogue): hide the tasks list's category block while it is empty
pierreleca Nov 25, 2026
22e32a7
Merge branch 'feat/task-sets-and-pages' into feat/run-again-and-in-parts
pierreleca Nov 25, 2026
5e0e81c
fix(catalogue): show the tasks page's save bar once a task is chosen
pierreleca Nov 25, 2026
029a9f5
fix(catalogue): keep a task set's version and date on one line
pierreleca Nov 25, 2026
2a88fa6
Merge branch 'feat/task-sets-and-pages' into feat/run-again-and-in-parts
pierreleca Nov 25, 2026
90d9bc6
Merge remote-tracking branch 'origin/main' into feat/task-sets-and-pages
pierreleca Nov 25, 2026
207fc20
refactor(builder): draw Which tasks? from beside the Dataset step
pierreleca Nov 25, 2026
5268a05
fix(standard): write task sets and the tasks listing through the shar…
pierreleca Nov 25, 2026
93f1ac1
Merge branch 'feat/task-sets-and-pages' into feat/run-again-and-in-parts
pierreleca Nov 25, 2026
6ddce02
fix(standard): write a kept try's no-result mark through the shared w…
pierreleca Nov 25, 2026
4da0d0a
Merge remote-tracking branch 'origin/main' into feat/task-sets-and-pages
pierreleca Nov 26, 2026
6ff9dfe
test(standard): name the job's uuid among a plain run's standard keys
pierreleca Nov 26, 2026
f1cab9f
Merge branch 'feat/task-sets-and-pages' into feat/run-again-and-in-parts
pierreleca Nov 26, 2026
7ac553c
test(standard): leave the job's uuid out of a part's records against …
pierreleca Nov 26, 2026
9b1051c
Merge remote-tracking branch 'origin/main' into feat/run-again-and-in…
pierreleca Nov 27, 2026
54eca70
fix(standard): begin and continue a plan by a set of several datasets
pierreleca Nov 27, 2026
4ddbea3
fix(builder): list the tasks to start with by the tasks page's new form
pierreleca Nov 27, 2026
e0c12f2
fix(runs): link the not-run and no-result counts to the job's record
pierreleca Nov 27, 2026
92b49ad
refactor(standard): name the helper of a set's units by what it gives
pierreleca Nov 27, 2026
7ff47ed
test(web): leave the tasks page's chosen parts out of the dialog's st…
pierreleca Nov 27, 2026
87c6f87
test(standard): run the rest of a job of one dataset of a set of several
pierreleca Nov 27, 2026
262e6c6
fix(standard): write a rerun's job result whole, as a run writes it
pierreleca Nov 27, 2026
bf848e5
fix(standard): keep a job's exchanges choice when its tasks run again
pierreleca Nov 27, 2026
f76fd6d
fix(standard): refuse --start-with on a whole-task Boat run
pierreleca Nov 27, 2026
4580174
fix(standard): keep the job result's permissions when a rerun rewrite…
pierreleca Nov 27, 2026
fab02f8
test(standard): check that a task run again keeps the job's exchanges…
pierreleca Nov 27, 2026
26c6d77
refactor(standard): call a run's first tasks its start and each run a…
pierreleca Nov 27, 2026
385b56c
docs(standard): say "start" and "later run" on the pages, in messages…
pierreleca Nov 27, 2026
9721f86
Merge remote-tracking branch 'origin/main' into feat/run-again-and-in…
pierreleca Nov 27, 2026
1e0122d
fix(standard): find the run of a job by the folder it writes
pierreleca Nov 27, 2026
4554619
fix(standard): say "N of M tasks run" in the Trials cell of a job sta…
pierreleca Nov 27, 2026
aeccd11
Merge remote-tracking branch 'origin/main' into feat/run-again-and-in…
pierreleca Nov 27, 2026
58c4f65
fix(builder): keep keyboard focus on the Specific tasks tile when its…
pierreleca Nov 27, 2026
12a468b
test(builder): take the focus from a removed button in the Start with…
pierreleca Nov 27, 2026
def11d3
Merge remote-tracking branch 'origin/main' into feat/run-again-and-in…
pierreleca Nov 27, 2026
2b867d3
fix(standard): keep a job's reasoning when its tasks run again
pierreleca Nov 27, 2026
856d612
Merge remote-tracking branch 'origin/main' into feat/run-again-and-in…
pierreleca Nov 27, 2026
ff6c114
fix(standard): refuse a re-run whose job records its reasoning in ano…
pierreleca Nov 27, 2026
acefd02
Merge remote-tracking branch 'origin/main' into feat/run-again-and-in…
pierreleca Nov 27, 2026
2eb0b83
fix(runs): name under a job's cap only the tasks still never begun
pierreleca Nov 28, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
147 changes: 118 additions & 29 deletions app/nullius/execution.py

Large diffs are not rendered by default.

10 changes: 10 additions & 0 deletions app/nullius/runs/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,11 +84,17 @@ def job_row(job: parse.Job) -> dict:
"state": job.state,
"n_trials": len(job.trials),
"n_planned": job.n_planned,
# a job started on some of its plan: how the start was named, and how many of the planned tasks have run
"start_with": job.start_with,
"n_tasks": job.n_tasks,
"n_tasks_run": job.n_tasks_run,
"counts": job.counts,
"n_resolved": job.n_resolved,
"n_infra": job.n_infra,
"raw_solve_rate": job.raw_solve_rate,
"adjusted_solve_rate": job.adjusted_solve_rate,
# the mean graded score, over the trials run: a benchmark scored, not solved, has it and no rate
"mean_score": job.mean_score,
"started_at": _stamp(job.started_at),
"finished_at": _stamp(job.finished_at),
}
Expand Down Expand Up @@ -320,6 +326,10 @@ def _show(args) -> int:
print(f" {row['n_trials']} trial(s) of {row['n_planned']} planned: "
f"resolved {row['n_resolved']} · infra {row['n_infra']} · "
f"raw {rate(row['raw_solve_rate'])} · adjusted {rate(row['adjusted_solve_rate'])}")
if job.start_with:
words = (job.runner_items or ["task", "tasks"])[1]
print(f" started on some of its plan: {row['n_tasks_run']} of {row['n_tasks']} planned {words} run; "
f"the rates are over those run")
mix = " · ".join(f"{k} {v}" for k, v in row["counts"].items() if v)
if mix:
print(f" outcomes: {mix}")
Expand Down
24 changes: 21 additions & 3 deletions app/nullius/runs/live.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
:data:`PROGRESS`: its step limit beside its ``step``, its agent's model calls
answered and the run's cap on them. A trial's snapshot holds these three only
once its feed reported one, so a feed without them folds as it always did.
A ``trial.end`` with ``back`` is a try put back in its place after the try
that followed it was stopped: the card is that try's again, at its attempt.

Four rules are load-bearing, and each has a test:

Expand Down Expand Up @@ -58,7 +60,7 @@

import json
import statistics
from dataclasses import dataclass, field
from dataclasses import dataclass, field, replace
from datetime import datetime, timezone
from pathlib import Path

Expand Down Expand Up @@ -229,6 +231,7 @@ class TrialState:
#: (ts, {token field: value}) per report — only the keys that report
#: carried — for the rate window; see Board.tokens_per_sec.
_series: list = field(default_factory=list, repr=False)
_previous: TrialState | None = field(default=None, repr=False)

@property
def state(self) -> str:
Expand Down Expand Up @@ -338,7 +341,7 @@ def winners(self) -> list[dict]:
by_task: dict = {}
for t in self.trials:
if t.task is not None and t.agent is not None:
by_task.setdefault(t.task, []).append(t)
by_task.setdefault(t.task, []).append(t._previous or t)
order = [a for a in self.lane_order() if a is not None]
out = []
for task, members in by_task.items():
Expand Down Expand Up @@ -509,7 +512,7 @@ def _ended(c: dict, finished_at: datetime | None) -> dict:
def _counts(trials: list, n_total: int | None) -> dict:
"""The count block over a list of trials. ``n_total`` is what the feed
declared for the job; a lane passes the trials it has seen."""
done = [t for t in trials if t.outcome is not None]
done = [t._previous or t for t in trials if t.outcome is not None or t._previous is not None]
return {
# Unknown until job.prepare/job.start says, or a trial appears: a
# "0 tasks" header during preparation would be a lie.
Expand All @@ -527,6 +530,7 @@ def _counts(trials: list, n_total: int | None) -> dict:


def _mean_reward(trials: list) -> float | None:
trials = [t._previous or t for t in trials]
rewards = [t.reward for t in trials if t.outcome is not None and t.reward is not None]
return sum(rewards) / len(rewards) if rewards else None

Expand Down Expand Up @@ -556,6 +560,7 @@ def fold(events: list[Event], now: datetime | None = None, notices: list[str] |
``ts`` — replay of a finished file is exact; a live board passes the clock)."""
board = Board(notices=list(notices or []))
by_id: dict[str, TrialState] = {}
manual = False

def trial_of(e: Event) -> TrialState:
t = by_id.get(e.trial)
Expand Down Expand Up @@ -592,7 +597,9 @@ def trial_of(e: Event) -> TrialState:
if not board.agents:
board.agents = list(d.get("agents") or [])
elif e.event == "job.start":
manual = board.finished_at is not None and bool(d.get("tasks"))
board.started_at = e.ts
board.finished_at = None # a job begun again after its end (chosen tasks run again) runs until its next end
board.n_total = _num(d.get("n_total"), int)
board.n_concurrent = _num(d.get("n_concurrent"), int)
board.wall_sec = _num(d.get("wall_sec"))
Expand All @@ -606,6 +613,9 @@ def trial_of(e: Event) -> TrialState:
elif e.event == "trial.phase":
t = trial_of(e)
if t.outcome is not None:
if manual:
# Result aggregates keep the earlier try while the card follows its replacement.
t._previous = replace(t)
# A phase after the trial ended: Harbor retries a trial under its own name (max_retries), so this is
# its next attempt, running again; what the attempt before it ended with is kept beside it.
t.attempt += 1
Expand Down Expand Up @@ -644,6 +654,14 @@ def trial_of(e: Event) -> TrialState:
t.last_line = d["line"]
elif e.event == "trial.end":
t = trial_of(e)
t._previous = None
if d.get("back") is True and t.outcome in (None, "cancelled") and t.attempt > 1:
# A stopped try restores the earlier result even after its cancellation end.
# The restored cost is no longer an earlier attempt's cost.
t.attempt -= 1
t.retried.pop()
if t.cost_before is not None and _num(d.get("cost_usd")) is not None:
t.cost_before = (t.cost_before - _num(d["cost_usd"])) or None
t.outcome = d["outcome"]
t.reward = _num(d.get("reward"))
t.score, t.parts = _num(d.get("score")), _num(d.get("parts"), int)
Expand Down
68 changes: 67 additions & 1 deletion app/nullius/runs/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
# The shape this module produces. A workspace caches parsed Jobs keyed on it,
# so bump it when a Trial or Job field is added, renamed or means something
# new — otherwise a cache written by the old parse is read back as current.
SCHEMA = "24"
SCHEMA = "25"

# What a rate-limit record in `agent/gateway.log` looks like. The agent's SDK
# retries a 429 below the harness, so a limit the run survived leaves nothing in result.json —
Expand Down Expand Up @@ -68,6 +68,42 @@ def _retried_cost(trial_dir: str, n: int) -> float | None:
return sum(costs) if costs else None


def _rerun_mark(res: dict) -> dict:
"""``standard.rerun`` of a standard trial's result, read leniently: the try a person asked for, its time and
reason as text; {} otherwise."""
std = res.get("standard") if isinstance(res.get("standard"), dict) else {}
mark = std.get("rerun")
if not isinstance(mark, dict):
return {}
return {"by": str(mark.get("by") or "hand"), "at": str(mark.get("at") or ""), "reason": redact(str(mark.get("reason") or "")),
"replaced": mark.get("replaced") if isinstance(mark.get("replaced"), dict) else {}}


def _reruns(res: dict) -> list:
"""A job's ``reruns`` (``standard/runner/rerun.py``), each read leniently: what a page lists of each re-run."""
rows = res.get("reruns")
num = lambda v: v if isinstance(v, (int, float)) and not isinstance(v, bool) else None
said = lambda v: {str(k): x for k, x in v.items() if isinstance(x, (str, int, float))} if isinstance(v, dict) else {}
out = []
for r in rows if isinstance(rows, list) else ():
if not isinstance(r, dict):
continue
replaced = [x for x in r.get("replaced") or [] if isinstance(x, dict)] if isinstance(r.get("replaced"), list) else []
begun = [x for x in r.get("begun") or [] if isinstance(x, dict)] if isinstance(r.get("begun"), list) else []
empty = [str(t) for t in r.get("no_result") or [] if isinstance(t, str)] if isinstance(r.get("no_result"), list) else []
out.append({"at": str(r.get("at") or ""), "finished_at": str(r.get("finished_at") or ""),
"reason": redact(str(r.get("reason") or "")),
"trials": [str(t) for t in r.get("trials") or [] if isinstance(t, str)] if isinstance(r.get("trials"), list) else [],
"replaced": [{"trial": str(x.get("trial") or ""), "unit": str(x.get("unit") or ""), "try": num(x.get("try")),
"was": said(x.get("was")), "now": said(x.get("now"))} for x in replaced],
# the tasks it began, planned and never begun before; the trials it took that had no result
**({"begun": [{"trial": str(x.get("trial") or ""), "unit": str(x.get("unit") or ""), "now": said(x.get("now"))}
for x in begun]} if begun else {}),
**({"no_result": empty} if empty else {}),
"max_usd": num(r.get("max_usd")), "spent_usd": num(r.get("spent_usd")), "stopped": r.get("stopped") is True})
return out


def _retries_of(res: dict) -> int:
"""``standard.retries`` of a standard trial's result or job's config: the
retries the trial took, or each attempt could take. 0 otherwise."""
Expand Down Expand Up @@ -306,6 +342,10 @@ class Trial:
# `standard.retries`). 0 when it did not, or does not say: Harbor retries
# under the trial's own name and keeps no count in it.
n_retries: int = 0
# A try a person asked for after the run ended (``standard.rerun``: by
# "hand", ``at``, ``reason``, the result it ``replaced``); {} for every
# other try.
rerun: dict = field(default_factory=dict)
# What the tries before this one cost, summed: kept in the job's
# `retried/` (`tries`), never a trial of their own, but paid for all the
# same, so the job's cost counts them (`Job.total_cost_usd`). None when
Expand Down Expand Up @@ -481,6 +521,16 @@ class Job:
# The task set a Nullius standard job ran (config ``standard.task_set``): its name, its label (its name for a
# job from before labels) and id, its benchmark, and ``units``, its number of ids. {} for every other job.
task_set: dict = field(default_factory=dict)
# A Nullius standard job planned on a whole and started on some of it (config ``standard.start_with``): how the
# start was named, ``by`` count, file, set or ids (named one by one), and ``name`` (the file's, the set's label,
# "the tasks chosen" for ids; "" for a count),
# and ``units``, the start's number of units. {} for every other job: the plan is then the job's from the start.
start_with: dict = field(default_factory=dict)
# Each time chosen trials of a Nullius standard job were run again in it (``result.json`` ``reruns``,
# ``standard/runner/rerun.py``): {at, reason, trials, replaced [{trial, unit, try, was, now}], begun [{trial, unit,
# now}] and no_result [trial] when it had any, max_usd, spent_usd, stopped}, oldest first. [] for a job never
# run again.
reruns: list = field(default_factory=list)
# How the job was launched, as its config.json recorded it with Harbor's
# defaults filled in (launch_of). Empty when config.json is absent.
launch: dict = field(default_factory=dict)
Expand Down Expand Up @@ -522,6 +572,13 @@ def n_planned(self) -> int:
recorded one, else the task count from the config."""
return self.n_total_trials or self.n_tasks

@property
def n_tasks_run(self) -> int:
"""How many of the job's tasks have an attempt that ended: of ``n_tasks`` planned, for a job started on
some of its plan (``start_with``) the tasks run so far."""
return len({re.sub(r"(__u\d+)r\d+$", r"\1", t.trial_name) if self.standard else t.task_name
for t in self.trials})

@property
def is_running(self) -> bool:
"""Trials still executing or queued — the run isn't over yet."""
Expand Down Expand Up @@ -909,6 +966,7 @@ def parse_trial(job_id: str, trial_dir: str) -> Trial | None:
has_trace=os.path.isfile(trace_path),
n_rate_limited_retries=count_rate_limits(os.path.join(trial_dir, "agent", "gateway.log")),
n_retries=_retries_of(res),
rerun=_rerun_mark(res),
retried_cost_usd=_retried_cost(trial_dir, _retries_of(res)),
env_type=((res.get("config") or {}).get("environment") or {}).get("type", ""),
started_at=_iso(res.get("started_at")),
Expand Down Expand Up @@ -1255,8 +1313,16 @@ def parse_job(job_dir: str, reuse=None, trials: bool = True) -> Job:
"id": str(ts.get("id") or ""), "benchmark": str(std.get("benchmark") or ""),
"units": len(ts["units"]) if isinstance(ts.get("units"), list) else 0}
if isinstance(ts.get("name"), str) and ts["name"] else {})
sw = std.get("start_with") if isinstance(std.get("start_with"), dict) else {}
if isinstance(sw.get("units"), list):
src = sw.get("units_file") if isinstance(sw.get("units_file"), dict) else sw.get("task_set") if isinstance(sw.get("task_set"), dict) else {}
by = "file" if sw.get("units_file") else "set" if sw.get("task_set") else "count" if "count" in sw else "ids"
job.start_with = {"by": by, "units": len(sw["units"]),
"name": (str(src.get("label") or src.get("name") or "") if by == "set" else "the tasks chosen" if by == "ids"
else str(src.get("name") or ""))}
job.budget = _budget(res.get("budget"))
job.identity = identity_of(cfg, res, job.agent_version)
job.reruns = _reruns(res)
job.standard = bool(std)
setup = std.get("setup") if isinstance(std.get("setup"), dict) else {}
was = (std.get("benchmark_options") or {}).get("agent") if isinstance(std.get("benchmark_options"), dict) else None
Expand Down
16 changes: 13 additions & 3 deletions app/nullius/standard/calls/ledger.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,15 +119,25 @@ def __init__(self, path: str):
self.path = path

@classmethod
def create(cls, path: str, max_usd: Optional[float] = None, unit_max_usd: Optional[float] = None) -> "Ledger":
"""``max_usd``: the run's cap, or None for a run with a cap per unit alone. ``unit_max_usd``: each unit's."""
def create(cls, path: str, max_usd: Optional[float] = None, unit_max_usd: Optional[float] = None,
seen: Optional[dict] = None) -> "Ledger":
"""``max_usd``: the run's cap, or None for a run with a cap per unit alone. ``unit_max_usd``: each unit's.
``seen``: the replies earlier runs of the job had from each model ([count, output tokens]), so that a later
run's first calls are booked at their average, not guessed."""
os.makedirs(os.path.dirname(path), exist_ok=True)
led = cls(path)
led._write({"max_usd": None if max_usd is None else float(max_usd),
"unit_max_usd": None if unit_max_usd is None else float(unit_max_usd),
"spent_usd": 0.0, "unsettled_usd": 0.0, "held": {}, "closed": False, "seen": {}, "units": {}, "of": {}})
"spent_usd": 0.0, "unsettled_usd": 0.0, "held": {}, "closed": False, "seen": dict(seen or {}), "units": {}, "of": {}})
return led

def replies(self) -> dict:
"""The replies this ledger has had from each model, {model: [count, output tokens]}; {} when it cannot be read."""
try:
return {m: list(v) for m, v in self._read()["seen"].items()}
except (OSError, ValueError, KeyError, TypeError):
return {}

@contextlib.contextmanager
def _locked(self):
try:
Expand Down
Loading
Loading