Skip to content

Workspaces: counting a workspace's runs decodes every trial of every job #309

Description

@harenome

Priority

high. The time is spent in the backend (app/nullius/workspace.py), called by the Workspaces route (app/web/workspaces.py). Labelled P1: every restart pays it again, with every cache current.

Components

  • app/nullius (backend)
  • app/web (routes)
  • templates and static files
  • docs and the site
  • catalogue (benchmarks, agents, capabilities)
  • the standard (ports, kits, relay, runs)
  • CI, workflows and skills

Today

To show a workspace's counts of runs and checks, /workspaces reads every job of every workspace with all its trials, although the counts use only job-level fields. #232 keeps the result in _COUNTS, in memory, so the next request is fast; the first request after each start reads everything again, with every job cache current.

Measured on main (ca2eb76) in a rootless python:3.12 container, on profiles from the generator below: W workspaces, each with one root of J ended Harbor jobs of T trials (WxJxT; 20x20x50 is 20,000 trials). Each row is 3 fresh starts; /workspaces is the first page asked for, then asked again. Median, with the range of the 3 starts.

Before the start 20x20x50: first 100x20x50: first Next
Caches present and current 1.23 s (1.07-1.25) 4.98 s (4.96-5.09) 0.02-0.07 s
No job caches 15.0 s (12.0-20.0) 65.7 s (60.6-69.0) 0.02-0.08 s

The first row is the everyday restart. A cProfile of its first request (werkzeug ProfilerMiddleware, which slows it down):

   ncalls  cumtime  function
       20    1.157  web/workspaces.py:62(_counts)
       20    1.144  web/runs.py:105(_grouped)
       20    1.089  nullius/workspace.py:485(load_jobs)
      400    1.049  nullius/workspace.py:414(_read_cache)
      400    0.544  nullius/workspace.py:352(job_from_dict)
      502    0.494  json/__init__.py:274(load)
      400    0.003  web/runs.py:153(_tally)
       20    0.008  nullius/workspace.py:313(heads)

_counts calls runs._grouped(ws), which calls workspace.load_jobs: each job's cache file (76 KB for 50 trials) is decoded and rebuilt with all its trials (job_from_dict). runs._tally then reads only job-level fields. The key that _COUNTS already uses (the roots, the job roots, workspace.heads of them, the run records' ids and states) costs 0.008 s for all 20 workspaces. Opening /runs first does not help: it reads the open workspace only.

Reproduction

Save as gen.py at the root of a checkout of main:

"""Write a profile of W workspaces x J Harbor jobs x T trials into $NULLIUS_HOME.

usage: NULLIUS_HOME=/profile PYTHONPATH=app python3 gen.py W J T
Each workspace has one root holding J ended jobs; one trial in three has a trajectory.
"""
import json, os, random, sys
from datetime import datetime, timedelta

from nullius import paths, workspace

W, J, T = map(int, sys.argv[1:4])
rng = random.Random(0)
AGENTS = [("claude-code", "anthropic/claude-sonnet-4-5"), ("codex", "openai/gpt-5"), ("oracle", None), ("nop", None)]
T0 = datetime(2026, 9, 1)


def dump(path, obj):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, "w") as fh:
        json.dump(obj, fh)


def iso(t):
    return t.isoformat()


def job(jd, j, agent, model, start):
    name, rewards, n_err = os.path.basename(jd), {}, 0
    for k in range(T):
        tn, s = f"task-{k:03d}__{j:04d}{k:03d}", start + timedelta(seconds=30 * k)
        reward, exc = rng.choice([(1.0, None), (0.0, None), (None, "ApiRateLimitError")])
        n_err += exc is not None
        if reward is not None:
            rewards.setdefault(str(reward), []).append(tn)
        dump(f"{jd}/{tn}/result.json", {
            "id": f"{j}-{k}", "task_name": f"bench/task-{k:03d}", "trial_name": tn, "trial_uri": f"file://{jd}/{tn}",
            "source": "bench", "config": {"task": {"name": f"bench/task-{k:03d}", "source": "bench"}, "trial_name": tn,
                                          "agent": {"name": agent, "model_name": model, "kwargs": {}}, "job_id": name},
            "agent_info": {"name": agent, "version": "1.0.0", "model_info": model and {"name": model.split("/")[1], "provider": model.split("/")[0]}},
            "agent_result": {"n_input_tokens": rng.randint(10**4, 10**6), "n_cache_tokens": 0, "n_output_tokens": rng.randint(10**3, 10**5),
                             "cost_usd": round(rng.uniform(0.01, 3), 4)},
            "verifier_result": reward is not None and {"rewards": {"reward": reward}} or None,
            "exception_info": exc and {"exception_type": exc, "exception_message": exc, "exception_traceback": "", "occurred_at": iso(s)},
            "started_at": iso(s), "finished_at": iso(s + timedelta(seconds=600)),
            **{p: {"started_at": iso(s + timedelta(seconds=a)), "finished_at": iso(s + timedelta(seconds=b))} for p, a, b in
               [("environment_setup", 0, 20), ("agent_setup", 20, 40), ("agent_execution", 40, 500), ("verifier", 500, 600)]}})
        if k % 3 == 0 and model:
            steps = [{"step_id": i, "timestamp": iso(s), "source": "agent", "message": "",
                      "tool_calls": [{"tool_call_id": f"c{i}", "function_name": "bash", "arguments": {"cmd": "ls"}}],
                      "observation": {"results": [{"source_call_id": f"c{i}", "content": "x = 1\n" * 40}]}} for i in range(1, 11)]
            dump(f"{jd}/{tn}/agent/trajectory.json", {"schema_version": "ATIF-v1.7", "session_id": tn, "steps": steps,
                                                      "agent": {"name": agent, "version": "1", "model_name": model}})
    dump(f"{jd}/config.json", {"job_name": name, "n_attempts": 1, "agents": [{"name": agent, "model_name": model, "kwargs": {}}],
                               "datasets": [{"name": "bench", "version": "1.0", "n_tasks": T}]})
    end = iso(start + timedelta(hours=2))
    dump(f"{jd}/result.json", {"id": name, "started_at": iso(start), "updated_at": end, "finished_at": end, "n_total_trials": T,
                               "stats": {"n_completed_trials": T, "n_errored_trials": n_err, "n_running_trials": 0, "n_pending_trials": 0,
                                         "evals": {f"{agent}__bench": {"n_trials": T, "n_errors": n_err, "metrics": [{"mean": 0.5}],
                                                                       "reward_stats": {"reward": rewards}}}}})


home = paths.workspaces_dir()
for w in range(W):
    root = os.path.join(os.path.dirname(home), "results", f"ws{w:03d}")
    for j in range(J):
        start = T0 + timedelta(hours=3 * (w * J + j))
        job(f"{root}/{start:%Y-%m-%d__%H-%M-%S}-j{j:03d}", w * J + j, *AGENTS[j % len(AGENTS)], start)
    workspace.create(home, [root], label=f"ws {w:03d}")
print(W, "workspaces,", W * J, "jobs,", W * J * T, "trials")

Generate a profile, then start the app on it and time two requests. The profile must be mounted at the same path at every start: the cache file is named after the real path of the job folder.

P=$PWD/profile-20x20x50; mkdir -p "$P"
podman run --rm -v "$PWD:/src:ro,Z" -v "$P:/profile:Z" -e NULLIUS_HOME=/profile -e PYTHONPATH=/src/app \
  docker.io/library/python:3.12 python /src/gen.py 20 20 50

start() {   # a fresh server, then the given pages in order
  podman run -d --rm --init --name nullius-ws -p 127.0.0.1:5093:8000 -v "$PWD:/src:ro,Z" -v "$P:/profile:Z" \
    -e NULLIUS_HOME=/profile docker.io/library/python:3.12 \
    sh -c 'pip install -q -r /src/app/requirements.txt && exec python /src/app/app.py --host 0.0.0.0 --port 8000' >/dev/null
  until curl -so /dev/null http://127.0.0.1:5093/static/style.css; do sleep 1; done
  for p in "$@"; do curl -so /dev/null -w "$p %{time_total}s\n" "http://127.0.0.1:5093$p"; done
  podman rm -f nullius-ws >/dev/null
}

rm -rf "$P"/data/workspaces/*/jobs; start /workspaces /workspaces   # no caches; leaves them current
start /workspaces /workspaces                                       # caches current

Wanted

A restart with current caches shows /workspaces about as fast as the next request: a closed workspace whose jobs had all ended is counted from job-level data kept on disk, not from its trials. For example, a small summary beside the workspace's job caches holding the counts (or each job's fields that _tally reads, without trials), stored under the key that _COUNTS uses and read when that key matches.

Acceptance

  • The counts of a closed workspace whose jobs had all ended are written to disk beside its job caches, with the key _COUNTS uses, and read back after a restart when the key matches.
  • A test shows that, after a restart, those counts come back without workspace.job_from_dict or parse.parse_job being called for the workspace's jobs.
  • A test shows that a moved head, a changed root or a changed run record makes the stored counts unused, and the workspace counted again.
  • A workspace with a job still running, and the open workspace, are counted as today, never from the stored counts.
  • The counts on /workspaces are the same as today for open, closed and running workspaces (a test compares them).
  • At 20x20x50 and 100x20x50 with the caches current, counting the closed workspaces on the first /workspaces after a start takes under 0.02 s, and the whole first request under 0.3 s, measured in the pull request (today 1.07-1.25 s and about 5 s). The rest of that first request is the page's first template compile and the open workspace's own load, which any first page after a start pays.

Dependencies and related

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

    P1Next: a wrong result or a broken path, with no way around itenhancementNew feature or request

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions