From 1786f7ad351dd787bfb8f5fe69ba3658c3950c5a Mon Sep 17 00:00:00 2001 From: Redivesue Date: Sat, 28 Nov 2026 20:22:02 +0800 Subject: [PATCH 01/11] [test] bench: measure job waits, job show and tool-event folding Extend scripts/bench_agent_polling.py for #449 T1 so a change to the wait and query paths can be compared with its base under identical inputs. - --source measures another source tree (for example a worktree of the base commit); the script and its fixtures stay the same on both sides. - Fixtures are built once per configuration (nodes, commits, waiting and finished jobs, workspace projects) and copied per run. - wait: idle windows (cold and warm), unrelated saves during a window, a job settling in process and from another process, and an already settled job. Records snapshot and head reads, CPU, catalog lock hold time, detection latency and whether the answer matches a fresh read. - show: job show for a succeeded job through the real agent gateway and over HTTP, including a held execution lock; records calls, bytes, snapshot reads and an output digest. - events: one turn with many tool events through the API. - --summarize prints n, P50 and P90 (nearest rank) for one or two files. The default scenario keeps its previous output. No model or provider is called. --- scripts/bench_agent_polling.py | 951 ++++++++++++++++++++++++++++++++- 1 file changed, 931 insertions(+), 20 deletions(-) diff --git a/scripts/bench_agent_polling.py b/scripts/bench_agent_polling.py index b464ea473..d6f27e9ae 100644 --- a/scripts/bench_agent_polling.py +++ b/scripts/bench_agent_polling.py @@ -1,40 +1,89 @@ """Measure the agent's per-turn polling, discovery and project-read cost. -The agent waits for generation through the CLI. This compares the cost of the -per-job wait loop with the batched `job.status` query, the full project read with -`project show --summary`, and per-command `--help` discovery with the single -`capabilities` digest. The synthetic project has the same shape as the trace in -issue #449 (many canvas items, a long commit history, several unfinished jobs): +The agent waits for generation through the CLI. Without ``--scenario`` this +compares the per-job wait loop with the batched ``job.status`` query, the full +project read with ``project show --summary``, and per-command ``--help`` +discovery with the single ``capabilities`` digest. The synthetic project has the +same shape as the trace in issue #449 (many canvas items, a long commit history, +several unfinished jobs): python scripts/bench_agent_polling.py python scripts/bench_agent_polling.py --jobs 14 --ticks 60 --commits 600 --nodes 200 --json + +The other scenarios write one JSON line per sample to ``--out`` so a revision +can be compared with another under the same inputs. ``--source`` selects the +source tree that is measured (for example a ``git worktree`` of the base +commit); this script and its fixtures stay the same on both sides: + + python scripts/bench_agent_polling.py --scenario wait --matrix --out after.jsonl + python scripts/bench_agent_polling.py --scenario wait --matrix --source ../od-base --out before.jsonl + python scripts/bench_agent_polling.py --scenario show --out after.jsonl + python scripts/bench_agent_polling.py --scenario events --out after.jsonl + python scripts/bench_agent_polling.py --summarize before.jsonl after.jsonl + +``wait`` covers five cases: an idle window (S1), a window with unrelated saves +(S2), a job settling during the window (S3), a job settled by another process +(S4) and a job that has already settled (S5). ``show`` measures ``job show`` for +a succeeded job through the agent gateway and over HTTP. ``events`` measures how +the API folds many tool events of one turn. ``contention`` (S6) measures lease +renewal, browser heartbeat, change polling, a save and a browser snapshot read +while 1, 5 or 10 waits share the catalog lock; ``--no-contention-saves`` +leaves the head unchanged during the window. Fixtures are built once per +configuration under ``--fixture-dir`` and copied for every run, so both +revisions read identical projects. No model or provider is called. """ import argparse import asyncio +import gc +import hashlib import json +import math +import os +import platform +import random import shutil +import statistics +import subprocess import sys import tempfile +import threading import time +from contextlib import contextmanager from pathlib import Path -from uuid import uuid4 +from uuid import UUID, uuid4 + +HERE = Path(__file__).resolve().parents[1] -SOURCE = Path(__file__).resolve().parents[1] + +def _source_argument(): + for index, value in enumerate(sys.argv): + if value == "--source" and index + 1 < len(sys.argv): + return Path(sys.argv[index + 1]).resolve() + if value.startswith("--source="): + return Path(value.split("=", 1)[1]).resolve() + return HERE + + +# The measured tree must be importable before anything from opendirector is. +SOURCE = _source_argument() sys.path[:0] = [str(SOURCE / "packages/core/src"), str(SOURCE / "apps/api/src")] -from opendirector.application.creation_canvas import CreationCanvas # noqa: E402 +from opendirector.application.creation_canvas import CreationCanvas, asset_ref # noqa: E402 from pydantic import TypeAdapter # noqa: E402 from opendirector.domain.creation.commands import Query, parse_command # noqa: E402 -from opendirector.domain.creation.generation import ImageGenerationSpec, InputSnapshot, Job # noqa: E402 +from opendirector.domain.creation.generation import ( # noqa: E402 + ImageGenerationSpec, InputSnapshot, Job, ResultVersion, TextGenerationSpec) from opendirector.domain.creation.models import ModelSnapshot # noqa: E402 from opendirector.domain.creation.project import ProjectSnapshot # noqa: E402 +from opendirector.domain.generation import GenerationFailure # noqa: E402 +from opendirector.domain.projects import ProjectError # noqa: E402 from opendirector.infrastructure.creation_projects import CreationProjects # noqa: E402 from opendirector.infrastructure.local_projects import LocalProjects # noqa: E402 from opendirector.wiring import configure_runtime # noqa: E402 -sys.path.insert(0, str(SOURCE / "scripts")) -from bench_creation_projects import add_saves, create_project # noqa: E402 +FIXTURE_FORMAT = 1 +TERMINAL = ("failed", "cancelled", "interrupted") def command(kind, project_id, payload, versions=()): @@ -42,6 +91,9 @@ def command(kind, project_id, payload, versions=()): "payload": payload, "expectedVersions": list(versions)}) +# -------------------------------------------------------------------------- +# Original summary (#455). Kept as it was so its numbers stay comparable. + def seed_jobs(projects, project_id, session, count): snapshot = projects.snapshot(project_id) model_id, spec_id = uuid4(), uuid4() @@ -60,6 +112,7 @@ def transform(before): data["jobs"] = jobs return ProjectSnapshot.model_validate(data) projects.commit(seed, transform, session=session) + del snapshot return [job.id for job in jobs] @@ -129,15 +182,11 @@ def measure_discovery(): "capabilitiesVerboseBytes": verbose} -def main(): - configure_runtime() - parser = argparse.ArgumentParser() - parser.add_argument("--jobs", type=int, default=14) - parser.add_argument("--ticks", type=int, default=60) - parser.add_argument("--nodes", type=int, default=200) - parser.add_argument("--commits", type=int, default=600) - parser.add_argument("--json", action="store_true") - options = parser.parse_args() +def run_summary(options): + if SOURCE != HERE: + raise SystemExit("The summary scenario measures this checkout only; use --scenario for --source.") + sys.path.insert(0, str(HERE / "scripts")) + from bench_creation_projects import add_saves, create_project root = Path(tempfile.mkdtemp(prefix="bench-agent-polling-")) result = {"jobs": options.jobs, "ticks": options.ticks} try: @@ -154,5 +203,867 @@ def main(): print(json.dumps(result, ensure_ascii=False, indent=2) if not options.json else json.dumps(result, ensure_ascii=False)) +# -------------------------------------------------------------------------- +# Fixtures shared by both revisions. + +CENTER = {"nodes": 200, "commits": 600, "jobs": 14, "finished": 0, "projects": 1, "verifyBytes": False} +MATRIX = [dict(CENTER)] + [dict(CENTER, **change) for change in ( + {"nodes": 50}, {"nodes": 1000}, {"commits": 1}, {"commits": 2000}, {"jobs": 1}, {"jobs": 50}, + {"finished": 200}, {"projects": 20}, {"projects": 100}, {"verifyBytes": True})] + + +def fixture_key(config, spare): + data = {key: config[key] for key in ("nodes", "commits", "jobs", "finished", "projects")} + data.update(format=FIXTURE_FORMAT, spare=spare) + return hashlib.sha256(json.dumps(data, sort_keys=True).encode()).hexdigest()[:16] + + +class Renewal: + """Keep the fixture's edit lease alive while seeding; never inside a measurement.""" + + def __init__(self, projects, project_id, session): + self.projects, self.project_id, self.session = projects, project_id, session + self.interval = getattr(projects.local, "LEASE_SECONDS", 60) * 0.5 + self.last = time.monotonic() + + def __call__(self): + if time.monotonic() - self.last >= self.interval: + self.projects.heartbeat(self.session, self.project_id) + self.last = time.monotonic() + + +def build_fixture(root, config, spare): + """One project with ``nodes`` items, ``commits`` saves and seeded jobs. + + Items are added in one commit: the per-node path of bench_creation_projects + is quadratic and takes over ten minutes at 1,000 nodes. ``commits`` full + snapshot saves follow, the same shape as an autosaving canvas. + """ + projects = CreationProjects(LocalProjects(root)) + project_id = uuid4() + projects.execute(command("project.create", project_id, {"name": "polling"})) + session = str(uuid4()) + projects.open(project_id, session) + for name, text in (("notes.md", "hello"), ("result.md", "generated text")): + projects.execute(command("asset.writeText", project_id, {"name": name, "text": text}), session=session) + assets = {asset.name: asset for asset in projects.snapshot(project_id).assets} + notes, output = assets["notes.md"], assets["result.md"] + projects.execute(command("canvas.show", project_id, {"item": { + "id": str(uuid4()), "projectId": str(project_id), "kind": "text", "title": "node 0", + "position": {"x": 0, "y": 0}, + "binding": {"role": "material", "objectRef": asset_ref(notes).model_dump(mode="json")}}}), session=session) + template = projects.snapshot(project_id).canvasItems[0].model_dump(mode="json") + + image_model, text_model = uuid4(), uuid4() + image_spec = ImageGenerationSpec(id=uuid4(), projectId=project_id, kind="image", purpose="generation", + modelConfigId=image_model, prompt="A mountain") + image_inputs = InputSnapshot(spec=image_spec, model=ModelSnapshot( + modelConfigId=image_model, kind="image", modelId="demo", url="https://model.test/v1", + protocol="openai", connectionType="api")) + text_spec = TextGenerationSpec(id=uuid4(), projectId=project_id, kind="text", purpose="generation", + modelConfigId=text_model, prompt="Write a line") + text_inputs = InputSnapshot(spec=text_spec, model=ModelSnapshot( + modelConfigId=text_model, kind="agent", modelId="demo", url="https://model.test/v1", + protocol="openai", connectionType="api")) + + def image_job(status="queued"): + return Job(id=uuid4(), projectId=project_id, inputSnapshot=image_inputs, + inputFingerprint=image_inputs.fingerprint(), execution=dict(kind="image", size="2K"), status=status) + waiting = [image_job() for _ in range(config["jobs"])] + spares = [image_job() for _ in range(spare)] + finished = [image_job("cancelled") for _ in range(config["finished"])] + probe = image_job("cancelled") + succeeded = Job(id=uuid4(), projectId=project_id, inputSnapshot=text_inputs, + inputFingerprint=text_inputs.fingerprint(), execution=dict(kind="text"), + status="succeeded", phase="complete", recovery="done", asset=asset_ref(output), adopted=True) + result = ResultVersion(id=uuid4(), projectId=project_id, specId=text_spec.id, jobId=succeeded.id, + asset=succeeded.asset, inputFingerprint=succeeded.inputFingerprint) + generated_item = dict(template, id=str(uuid4()), title="generated", position={"x": 0, "y": 600}, + binding={"role": "generation", "objectRef": {"id": str(text_spec.id)}}) + + def transform(before): + data = before.model_dump(mode="json") + data["canvasItems"] = [template] + [dict(template, id=str(uuid4()), title=f"node {index}", + position={"x": index * 360, "y": 0}) for index in range(1, config["nodes"])] + [generated_item] + data["generationSpecs"] = [image_spec.model_dump(mode="json"), + text_spec.model_copy(update={"currentResultId": result.id}).model_dump(mode="json")] + data["jobs"] = [job.model_dump(mode="json") for job in [*waiting, *spares, *finished, probe, succeeded]] + data["results"] = [result.model_dump(mode="json")] + return ProjectSnapshot.model_validate(data) + projects.commit(command("generationSpec.create", project_id, {"spec": image_spec}), transform, session=session) + + snapshot = projects.snapshot(project_id) + movable = [item for item in snapshot.canvasItems if item.binding.role == "material"] + revisions = {item.id: item.revision for item in movable} + renew = Renewal(projects, project_id, session) + for index in range(config["commits"]): + renew() + item = movable[index % len(movable)] + projects.execute(command("canvas.move", project_id, + {"items": [{"itemId": str(item.id), "position": {"x": index + 1, "y": index}}]}, + [{"objectType": "canvas_item", "id": str(item.id), "revision": revisions[item.id]}]), session=session) + revisions[item.id] += 1 + for index in range(config["projects"] - 1): + projects.execute(command("project.create", uuid4(), {"name": f"other {index:03d}"})) + projects.local.release(session) + return {"projectId": str(project_id), "waiting": [str(job.id) for job in waiting], + "spares": [str(job.id) for job in spares], "probe": str(probe.id), "succeeded": str(succeeded.id), + "movable": [str(item.id) for item in movable[:20]], + "snapshotBytes": len(projects.snapshot(project_id).model_dump_json())} + + +def fixture(directory, config, spare=0): + """Idle and settled windows use projects without spare jobs; visibility + samples need one unfinished job each, so they get their own fixture.""" + target = Path(directory) / fixture_key(config, spare) + meta_file = target / "fixture.json" + if meta_file.is_file(): + return target, json.loads(meta_file.read_text()) + staging = Path(tempfile.mkdtemp(prefix=".building-", dir=directory)) + started = time.perf_counter() + meta = build_fixture(staging / "repository", config, spare) + meta["config"] = {key: config[key] for key in ("nodes", "commits", "jobs", "finished", "projects")} + meta["config"]["spareJobs"] = spare + meta["buildSeconds"] = round(time.perf_counter() - started, 1) + (staging / "fixture.json").write_text(json.dumps(meta)) + staging.rename(target) + return target, meta + + +@contextmanager +def working_copy(fixture_dir): + """A private copy per run; APFS clones make large fixtures cheap on macOS.""" + root = Path(tempfile.mkdtemp(prefix="bench-agent-run-")) + target = root / "repository" + try: + if sys.platform == "darwin": + subprocess.run(["cp", "-cR", str(Path(fixture_dir) / "repository"), str(target)], check=True) + else: + shutil.copytree(Path(fixture_dir) / "repository", target, symlinks=True) + yield target + finally: + shutil.rmtree(root, ignore_errors=True) + + +# -------------------------------------------------------------------------- +# Instrumentation. Wrappers sit on instances, so the measured code is unchanged. + +class Probe: + def __init__(self, projects, canvas=None): + self.projects = projects + # Threads that stand in for other actors (writers) are not the wait's cost. + self.excluded = set() + self.reset() + gc.callbacks.append(self._gc) + self.originals = {} + for name in ("snapshot", "head", "snapshot_if_changed"): + original = getattr(projects, name, None) + if original is not None: + self.originals[name] = original + setattr(projects, name, self._timed(name, original)) + transaction = projects.local.transaction + probe = self + + @contextmanager + def held(): + with transaction() as db: + start = time.perf_counter() + try: + yield db + finally: + if threading.get_ident() not in probe.excluded: + probe.lock.append(time.perf_counter() - start) + projects.local.transaction = held + if canvas is not None: + canvas.job_states = self._timed("job_states", canvas.job_states) + + def reset(self): + self.calls = {"snapshot": [], "head": [], "job_states": [], "snapshot_if_changed": []} + self.copies = 0 + self.lock = [] + self.gc = [] + + def _gc(self, phase, info): + # Full collections over large cached snapshots can pause any read for a + # second; they are reported so an outlier can be attributed, not hidden. + if info.get("generation") != 2: + return + if phase == "start": + self._gc_started = time.perf_counter() + elif getattr(self, "_gc_started", None) is not None: + self.gc.append(time.perf_counter() - self._gc_started) + self._gc_started = None + + def _timed(self, name, function): + def wrapper(*args, **kwargs): + start = time.perf_counter() + value = None + try: + value = function(*args, **kwargs) + return value + finally: + if threading.get_ident() not in self.excluded: + self.calls[name].append(time.perf_counter() - start) + # A gated read copies the snapshot only when the head moved. + if name == "snapshot_if_changed" and isinstance(value, tuple) and value[1] is not None: + self.copies += 1 + return wrapper + + def metrics(self): + def ms(values): + return round(sum(values) * 1000, 3) + gated = self.calls["snapshot_if_changed"] + return {"snapshotReads": len(self.calls["snapshot"]) + self.copies, + "snapshotMs": ms(self.calls["snapshot"]), + "gatedReads": len(gated), "gatedMs": ms(gated), + "headReads": len(self.calls["head"]), "headMs": ms(self.calls["head"]), + "jobStatesReads": len(self.calls["job_states"]), "jobStatesMs": ms(self.calls["job_states"]), + "jobStatesEachMs": [round(value * 1000, 3) for value in self.calls["job_states"]], + "lockHolds": len(self.lock), "lockHoldMs": ms(self.lock), + "gcFullCollections": len(self.gc), "gcFullMs": ms(self.gc)} + + +def open_store(root, verify_bytes): + projects = CreationProjects(LocalProjects(root)) + if verify_bytes: + # Simulates the Windows default; this is not a Windows measurement. + projects._verify_record_bytes = True + return projects + + +def warm_writes(projects, project_id): + """Validate the commit chain before a writer is timed. + + The first commit in a process replays the whole history (seconds at 600 + commits), and opening a project starts that replay on a background thread. + Neither belongs to the cost of a wait, so both finish before sampling. + """ + awaiting = getattr(projects, "_await_current_warm", None) + if awaiting is not None: + awaiting(project_id) + projects.history(project_id) + gc.collect() + + +def settle(projects, project_id, job_id, status): + """Commit a terminal state through the same boundary as a generation checkpoint.""" + before = projects.snapshot(project_id) + job = next(item for item in before.jobs if str(item.id) == str(job_id)) + changes = {"status": status, "phase": "complete" if status != "interrupted" else job.phase} + if status == "failed": + changes["errorDetails"] = GenerationFailure(category="provider", stage="poll", message="bench failure", + suggestion="bench only").model_dump(mode="json") + changes["recovery"] = "retry" + if status == "interrupted": + changes["recovery"] = "review" + updated = Job.model_validate({**job.model_dump(), **changes, "revision": job.revision + 1}) + checkpoint = parse_command(dict(commandId=uuid4(), projectId=project_id, type="job.checkpoint", + expectedVersions=[{"objectType": "job", "id": str(job.id), "revision": job.revision}], + payload=dict(job=updated))) + + def apply(current): + return current.model_copy(update={"jobs": tuple(updated if item.id == job.id else item for item in current.jobs)}) + receipt = projects.commit(checkpoint, apply, source="background") + if receipt.status == "rejected": + raise RuntimeError(f"settle rejected: {receipt.issues}") + + +def source_identity(): + def git(*args): + try: + return subprocess.run(["git", "-C", str(SOURCE), *args], capture_output=True, text=True, + check=True).stdout.strip() + except (OSError, subprocess.CalledProcessError): + return None + import opendirector + module = Path(opendirector.__file__).resolve() + if SOURCE not in module.parents: + raise SystemExit(f"opendirector was imported from {module}, not from --source {SOURCE}") + status = git("status", "--porcelain", "--", "packages", "apps") + return {"sourcePath": str(SOURCE), "sourceSha": git("rev-parse", "HEAD"), "sourceDirty": bool(status), + "os": platform.platform(), "python": platform.python_version(), "cpu": platform.machine()} + + +class Output: + def __init__(self, path, meta): + self.path = Path(path) if path else None + self.meta = meta + + def write(self, record): + line = json.dumps({**record, "meta": self.meta}, ensure_ascii=False) + if self.path: + with self.path.open("a", encoding="utf-8") as stream: + stream.write(line + "\n") + else: + print(line) + + +# -------------------------------------------------------------------------- +# wait: S1-S5. + +def window(projects, canvas, probe, project_id, ids, seconds): + probe.reset() + cpu, start = time.process_time(), time.perf_counter() + state = asyncio.run(canvas.wait_jobs(UUID(project_id), tuple(UUID(i) for i in ids), seconds, "all")) + return state, {"wallMs": round((time.perf_counter() - start) * 1000, 3), + "cpuMs": round((time.process_time() - cpu) * 1000, 3), **probe.metrics()} + + +def run_wait_cold_child(options): + """One idle window in a fresh process: empty caches, warm OS page cache.""" + meta = json.loads(options.child_meta) + projects = open_store(Path(options.work_dir), options.verify_bytes) + canvas = CreationCanvas(projects) + probe = Probe(projects, canvas) + _, metrics = window(projects, canvas, probe, meta["projectId"], meta["waiting"], options.window) + print(json.dumps(metrics)) + + +def run_settle_child(options): + """Another process settles a job; prints the wall clock after the commit returns.""" + configure_runtime() + projects = CreationProjects(LocalProjects(Path(options.work_dir))) + warm_writes(projects, UUID(options.project)) + print("ready", flush=True) + time.sleep(options.delay) + begin = time.perf_counter() + settle(projects, UUID(options.project), options.job, options.status) + print(json.dumps({"committedAt": time.time(), "commitMs": round((time.perf_counter() - begin) * 1000, 3)}), flush=True) + + +def run_wait(options, out): + configs = MATRIX if options.matrix else [dict(CENTER, **{key: value for key, value in ( + ("nodes", options.nodes), ("commits", options.commits), ("jobs", options.jobs), + ("finished", options.finished), ("projects", options.projects)) if value is not None}, + verifyBytes=options.verify_bytes)] + rng = random.Random(options.seed) + for index, config in enumerate(configs): + directory, meta = fixture(options.fixture_dir, config) + label = {**meta["config"], "verifyBytes": config["verifyBytes"]} + label["snapshotBytes"] = meta["snapshotBytes"] + print(f"[{index + 1}/{len(configs)}] {label} (fixture built in {meta['buildSeconds']} s)", file=sys.stderr) + center = options.matrix is False or config == CENTER + parts = set(options.parts.split(",")) + with working_copy(directory) as root: + # S1 cold: a new process per sample. + for sample in range(options.cold if "idle" in parts else 0): + child = subprocess.run([sys.executable, __file__, "--source", str(SOURCE), "--scenario", "_wait-cold", + "--work-dir", str(root), "--child-meta", json.dumps(meta), "--window", str(options.window)] + + (["--verify-bytes"] if config["verifyBytes"] else []), capture_output=True, text=True) + if child.returncode: + out.write({"scenario": "wait.idle", "phase": "cold", "config": label, "sample": sample, + "error": child.stderr[-2000:]}) + continue + out.write({"scenario": "wait.idle", "phase": "cold", "config": label, "sample": sample, + "windowSeconds": options.window, **json.loads(child.stdout.strip().splitlines()[-1])}) + projects = open_store(root, config["verifyBytes"]) + canvas = CreationCanvas(projects) + probe = Probe(projects, canvas) + window(projects, canvas, probe, meta["projectId"], meta["waiting"], 0) # warm-up, discarded + for sample in range(options.warm if "idle" in parts else 0): + _, metrics = window(projects, canvas, probe, meta["projectId"], meta["waiting"], options.window) + out.write({"scenario": "wait.idle", "phase": "warm", "config": label, "sample": sample, + "windowSeconds": options.window, **metrics}) + # S5: already settled, answered at once. + for sample in range(options.warm * 3 if "settled" in parts else 0): + _, metrics = window(projects, canvas, probe, meta["projectId"], [meta["probe"]], 0) + out.write({"scenario": "wait.settled", "phase": "warm", "config": label, "sample": sample, **metrics}) + if center and "busy" in parts: + run_busy(options, out, projects, canvas, probe, meta, label) + if not center or "visibility" not in parts: + continue + spare = options.visibility + options.cross_process + directory, meta = fixture(options.fixture_dir, config, spare) + label = {**meta["config"], "verifyBytes": config["verifyBytes"], "snapshotBytes": meta["snapshotBytes"]} + with working_copy(directory) as root: + projects = open_store(root, config["verifyBytes"]) + canvas = CreationCanvas(projects) + probe = Probe(projects, canvas) + run_visibility(options, out, projects, canvas, probe, meta, label, rng, root) + + +def run_busy(options, out, projects, canvas, probe, meta, label): + """S2: unrelated saves at a fixed rate move the head during the window.""" + session = str(uuid4()) + project_id = UUID(meta["projectId"]) + projects.open(project_id, session) + warm_writes(projects, project_id) + for sample in range(options.busy): + revisions = {item.id: item.revision for item in projects.snapshot(project_id).canvasItems} + stop, latencies, cpu = threading.Event(), [], [0.0] + + def writer(): + probe.excluded.add(threading.get_ident()) + try: + write() + finally: + probe.excluded.discard(threading.get_ident()) + + def write(): + started = time.thread_time() + index = 0 + while not stop.is_set(): + item = UUID(meta["movable"][index % len(meta["movable"])]) + begin = time.perf_counter() + projects.execute(command("canvas.move", project_id, + {"items": [{"itemId": str(item), "position": {"x": index, "y": sample}}]}, + [{"objectType": "canvas_item", "id": str(item), "revision": revisions[item]}]), session=session) + latencies.append((time.perf_counter() - begin) * 1000) + revisions[item] += 1 + index += 1 + stop.wait(1 / options.write_rate) + cpu[0] = (time.thread_time() - started) * 1000 + thread = threading.Thread(target=writer) + thread.start() + _, metrics = window(projects, canvas, probe, meta["projectId"], meta["waiting"], options.window) + stop.set() + thread.join() + out.write({"scenario": "wait.busy", "phase": "warm", "config": label, "sample": sample, + "windowSeconds": options.window, "writeRate": options.write_rate, **metrics, + "writerCpuMs": round(cpu[0], 3), "waitCpuMs": round(metrics["cpuMs"] - cpu[0], 3), + "writes": len(latencies), "writeMs": [round(value, 3) for value in latencies]}) + projects.local.release(session) + + +def run_visibility(options, out, projects, canvas, probe, meta, label, rng, root): + """S3 in process and S4 from another process: a job settles mid-window.""" + spares = list(meta["spares"]) + project_id = meta["projectId"] + warm_writes(projects, UUID(project_id)) + + def check(state, job_id, status): + fresh = canvas.job_states(UUID(project_id), (UUID(job_id),)) + returned = state["jobs"][0] if state["jobs"] else None + return {"status": returned and returned["status"], "expected": status, + "missed": not state["terminal"], "matchesFreshRead": state == fresh} + + for sample in range(options.visibility): + job_id, status = spares.pop(), TERMINAL[sample % len(TERMINAL)] + delay = rng.uniform(0.3, min(2.5, options.window / 2)) + done = {} + + def writer(): + probe.excluded.add(threading.get_ident()) + try: + time.sleep(delay) + begin = time.perf_counter() + settle(projects, UUID(project_id), job_id, status) + done["at"] = time.perf_counter() + done["commitMs"] = round((done["at"] - begin) * 1000, 3) + finally: + probe.excluded.discard(threading.get_ident()) + thread = threading.Thread(target=writer) + thread.start() + state, metrics = window(projects, canvas, probe, project_id, [job_id], options.window) + returned = time.perf_counter() + thread.join() + out.write({"scenario": "wait.settle", "phase": "warm", "config": label, "sample": sample, + "windowSeconds": options.window, "delaySeconds": round(delay, 3), + "detectMs": round((returned - done["at"]) * 1000, 3), "commitMs": done["commitMs"], + **metrics, **check(state, job_id, status)}) + + for sample in range(options.cross_process): + job_id, status = spares.pop(), TERMINAL[sample % len(TERMINAL)] + delay = rng.uniform(0.3, min(2.5, options.window / 2)) + child = subprocess.Popen([sys.executable, __file__, "--source", str(SOURCE), "--scenario", "_settle", + "--work-dir", str(root), "--project", project_id, "--job", job_id, "--status", status, + "--delay", str(delay)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + if child.stdout.readline().strip() != "ready": + child.wait() + out.write({"scenario": "wait.crossProcess", "config": label, "sample": sample, "error": child.stderr.read()[-2000:]}) + continue + state, metrics = window(projects, canvas, probe, project_id, [job_id], options.window) + returned = time.time() + line, error = child.communicate() + report = json.loads(line.strip().splitlines()[-1]) if child.returncode == 0 else {} + committed = report.get("committedAt") + out.write({"scenario": "wait.crossProcess", "phase": "warm", "config": label, "sample": sample, + "windowSeconds": options.window, "delaySeconds": round(delay, 3), + "detectMs": round((returned - committed) * 1000, 3) if committed else None, + "commitMs": report.get("commitMs"), + **({"error": error[-2000:]} if committed is None else {}), **metrics, **check(state, job_id, status)}) + + +# -------------------------------------------------------------------------- +# contention: S6, other catalog-lock users while several waits run. + +def run_contention(options, out): + """Latency of lease renewal, browser heartbeat, change polling, a save and a + browser snapshot read while K waits share the catalog lock.""" + from filelock import Timeout + for nodes in options.contention_nodes: + config = dict(CENTER, nodes=nodes) + directory, meta = fixture(options.fixture_dir, config) + label = {**meta["config"], "verifyBytes": False, "snapshotBytes": meta["snapshotBytes"]} + project_id = UUID(meta["projectId"]) + with working_copy(directory) as root: + projects = open_store(root, False) + canvas = CreationCanvas(projects) + probe = Probe(projects, canvas) + session, agent_session = str(uuid4()), str(uuid4()) + projects.open(project_id, session) + warm_writes(projects, project_id) + with projects.local.transaction() as db: + projects.local.start_agent_session(db, project_id, root, agent_session) + current = probe.originals["snapshot"](project_id) + revisions = {item.id: item.revision for item in current.canvasItems} + cursor = [current.eventCursor] + moves = [0] + + def move(): + item = UUID(meta["movable"][moves[0] % len(meta["movable"])]) + projects.execute(command("canvas.move", project_id, + {"items": [{"itemId": str(item), "position": {"x": moves[0], "y": 1}}]}, + [{"objectType": "canvas_item", "id": str(item), "revision": revisions[item]}]), session=session) + revisions[item] += 1 + moves[0] += 1 + + def changes(): + value = projects.changes(project_id, after=cursor[0]) + cursor[0] = value["nextCursor"] + + operations = { + "renewAgentSession": lambda: projects.local.renew_agent_session(agent_session), + "browserHeartbeat": lambda: projects.heartbeat(session, project_id), + "changes": changes, + "save": move, + "browserSnapshot": lambda: probe.originals["snapshot"](project_id), + } + if not options.contention_saves: + # Without saves the head stays put, as while a user only watches. + operations.pop("save") + for waiters in options.contention_waiters: + for sample in range(options.contention_samples): + latencies = {name: [] for name in operations} + timeouts, stop = [0], threading.Event() + + def operate(): + probe.excluded.add(threading.get_ident()) + try: + while not stop.is_set(): + for name, operation in operations.items(): + begin = time.perf_counter() + try: + operation() + except Timeout: + timeouts[0] += 1 + continue + latencies[name].append(round((time.perf_counter() - begin) * 1000, 3)) + stop.wait(0.1) + finally: + probe.excluded.discard(threading.get_ident()) + + async def waits(): + if not waiters: + # Control: the same operations with no wait running. + return await asyncio.sleep(options.window) + return await asyncio.gather(*(canvas.wait_jobs( + project_id, tuple(UUID(i) for i in meta["waiting"]), options.window, "all") + for _ in range(waiters))) + thread = threading.Thread(target=operate) + burner = (subprocess.Popen([sys.executable, "-c", "while True: pass"]) + if options.contention_burner else None) + probe.reset() + cpu = time.process_time() + thread.start() + asyncio.run(waits()) + stop.set() + thread.join() + if burner is not None: + burner.kill() + burner.wait() + metrics = probe.metrics() + out.write({"scenario": "contention", "phase": "warm", + "config": {**label, "waiters": waiters, "saves": options.contention_saves, + "burner": options.contention_burner}, + "sample": sample, + "windowSeconds": options.window, "timeouts": timeouts[0], + "processCpuMs": round((time.process_time() - cpu) * 1000, 3), + "waitLockHoldMs": metrics["lockHoldMs"], "waitSnapshotReads": metrics["snapshotReads"], + "gcFullMs": metrics["gcFullMs"], **{f"{name}Ms": values for name, values in latencies.items()}}) + projects.local.release_agent_session(agent_session) + projects.local.release(session) + + +# -------------------------------------------------------------------------- +# show: job show for a succeeded job. + +def canonical(value): + return hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False).encode()).hexdigest() + + +def run_show(options, out): + from fastapi.testclient import TestClient + from opendirector import cli + from opendirector.agent.gateway import ToolGateway + from opendirector.agent.context import RunContext + from opendirector.agent.tools import AgentTools + from opendirector.infrastructure.model_configs import ModelConfigs + from opendirector_api.main import create_app + + for nodes in options.show_nodes: + config = dict(CENTER, nodes=nodes) + directory, meta = fixture(options.fixture_dir, config) + label = {**meta["config"], "verifyBytes": False, "snapshotBytes": meta["snapshotBytes"]} + project_id = UUID(meta["projectId"]) + with working_copy(directory) as root: + projects = CreationProjects(LocalProjects(root)) + probe = Probe(projects) + # Agent mode: the real gateway and business tools; only the socket is replaced. + business = AgentTools(projects, None, ModelConfigs(root)) + gateway = ToolGateway(business, RunContext(runtime="codex", project_id=project_id, turn_id=uuid4(), + session=str(uuid4()), directory=root, config=None, messages=[], selected_skills=[])) + loop = asyncio.new_event_loop() + os.environ["OPENDIRECTOR_AGENT_SOCKET"] = "/bench-only.sock" + client = cli.Client(project_id, "http://bench.invalid", None, None) + calls = [] + + def call(name, arguments, *, identity=None): + result = loop.run_until_complete(gateway.call(str(identity or uuid4()), name, arguments)) + encoded = json.dumps(result.value, ensure_ascii=False) + calls.append({"name": name, "type": arguments.get("type"), "bytes": len(encoded.encode())}) + if result.error: + raise ProjectError(result.error, code=result.value.get("code")) + return json.loads(encoded) + client.call = call + + def agent_show(lock_seconds=0.0): + calls.clear() + probe.reset() + if lock_seconds: + loop.run_until_complete(gateway.execution_lock.acquire()) + loop.call_later(lock_seconds, gateway.execution_lock.release) + start = time.perf_counter() + value = client.query("job.get", objectId=meta["succeeded"]) + return value, (time.perf_counter() - start) * 1000 + + agent_show() # warm-up + for phase, lock in (("warm", 0.0), ("writeLockHeld", options.lock_seconds)): + for sample in range(options.show_samples if not lock else max(3, options.show_samples // 5)): + value, elapsed = agent_show(lock) + metrics = probe.metrics() + out.write({"scenario": "show.agent", "phase": phase, "config": label, "sample": sample, + "lockSeconds": lock, "wallMs": round(elapsed, 3), "calls": list(calls), + "callCount": len(calls), "responseBytes": sum(item["bytes"] for item in calls), + "snapshotReads": metrics["snapshotReads"], "snapshotMs": metrics["snapshotMs"], + "hasDelivery": "delivery" in value, "outputDigest": canonical(value), + "deliveryDigest": canonical(value.get("delivery"))}) + del os.environ["OPENDIRECTOR_AGENT_SOCKET"] + loop.close() + + # HTTP mode: the real ASGI application in process. + requests = [] + + def record(response): + response.read() + requests.append({"method": response.request.method, "path": response.request.url.path, + "bytes": len(response.content)}) + with TestClient(create_app(LocalProjects(root))) as http: + http.event_hooks = {"request": [], "response": [record]} + client = cli.Client(project_id, "http://testserver", None, None) + client.http.close() + http.headers.update(client.http.headers) + client.http = http + client.query("job.get", objectId=meta["succeeded"]) # warm-up + for sample in range(options.show_samples): + requests.clear() + start = time.perf_counter() + value = client.query("job.get", objectId=meta["succeeded"]) + elapsed = (time.perf_counter() - start) * 1000 + out.write({"scenario": "show.http", "phase": "warm", "config": label, "sample": sample, + "wallMs": round(elapsed, 3), "requests": list(requests), + "requestCount": len(requests), "responseBytes": sum(item["bytes"] for item in requests), + "hasDelivery": "delivery" in value, "outputDigest": canonical(value), + "deliveryDigest": canonical(value.get("delivery"))}) + + +# -------------------------------------------------------------------------- +# events: one turn with many tool events. + +def run_events(options, out): + from fastapi.testclient import TestClient + from opendirector.infrastructure.model_configs import ModelConfigs + from opendirector_api import agent + from opendirector_api.main import create_app + + count = [0] + + async def stream(self, run): + n = count[0] + for index in range(n): + identity = f"cli:{index:032x}" + yield {"type": "tool", "id": identity, "name": "opendirector job wait", "status": "running"} + if index % 10 == 0: + yield {"type": "delta", "text": f"step {index}. "} + yield {"type": "tool", "id": identity, "name": "opendirector job wait", "status": "complete", + "result": '{"status":"running"}'} + yield {"type": "delta", "text": "done"} + + async def no_skills(*args): + return [] + agent.AgentRuntimes.stream = stream + agent.runtime_available = lambda _: True + agent.skills = no_skills + model = {"id": str(uuid4()), "modelId": "bench-model", "kind": "agent", "url": "http://models.test/v1", + "connectionType": "api", "protocol": "openai", "authMode": "none", "apiKey": ""} + ModelConfigs.resolve = lambda *args: dict(model) + root = Path(tempfile.mkdtemp(prefix="bench-agent-events-")) + try: + with TestClient(create_app(LocalProjects(root)), headers={ + "X-OpenDirector-Request": "1", "X-OpenDirector-Session": str(uuid4())}) as client: + pid = str(uuid4()) + base = f"/api/creation/projects/{pid}" + client.post(base + "/commands", json={"type": "project.create", "projectId": pid, + "commandId": str(uuid4()), "payload": {"name": "events"}}).raise_for_status() + client.post(base + "/open").raise_for_status() + path = base + "/assistant" + for calls in [0, *options.event_calls]: + count[0] = calls + for sample in range(options.event_samples + 1): + conversation = client.post(path + "/conversations", json={"id": str(uuid4())}).json() + cpu, start = time.process_time(), time.perf_counter() + response = client.post(path + "/turns", json={"id": str(uuid4()), "runtime": "default", + "conversationId": conversation["conversationId"], "text": "bench"}) + elapsed = (time.perf_counter() - start) * 1000 + response.raise_for_status() + frames = [json.loads(line[6:]) for line in response.text.splitlines() if line.startswith("data: ")] + saved = frames[-1]["conversation"]["messages"][-1] + if sample == 0: + continue # warm-up + out.write({"scenario": "events.turn", "phase": "warm", + "config": {"toolCalls": calls, "events": calls * 2 + calls // 10 + 1}, + "sample": sample - 1, "wallMs": round(elapsed, 3), + "cpuMs": round((time.process_time() - cpu) * 1000, 3), + "tools": len(saved["tools"]), "toolsDigest": canonical(saved["tools"])}) + finally: + shutil.rmtree(root, ignore_errors=True) + + +# -------------------------------------------------------------------------- +# Summary of one or two JSONL files. + +def percentile(values, fraction): + ordered = sorted(values) + return ordered[max(0, math.ceil(fraction * len(ordered)) - 1)] + + +SUMMARY_METRICS = { + "wait.idle": ("snapshotReads", "headReads", "cpuMs", "lockHoldMs"), + "wait.settled": ("wallMs", "snapshotReads", "headReads"), + "wait.busy": ("snapshotReads", "waitCpuMs", "lockHoldMs", "writeMs"), + "wait.settle": ("detectMs", "commitMs", "snapshotReads"), + "wait.crossProcess": ("detectMs", "commitMs", "snapshotReads"), + "show.agent": ("wallMs", "callCount", "responseBytes", "snapshotReads"), + "show.http": ("wallMs", "requestCount", "responseBytes"), + "events.turn": ("wallMs", "cpuMs"), + "contention": ("renewAgentSessionMs", "browserHeartbeatMs", "changesMs", "saveMs", "browserSnapshotMs", + "waitLockHoldMs", "waitSnapshotReads", "timeouts"), +} + + +def summarize(paths): + groups = {} + for side, path in enumerate(paths): + for line in Path(path).read_text(encoding="utf-8").splitlines(): + record = json.loads(line) + key = (record["scenario"], record.get("phase"), json.dumps(record.get("config"), sort_keys=True)) + groups.setdefault(key, [[] for _ in paths])[side].append(record) + for (scenario, phase, config), sides in sorted(groups.items()): + print(f"\n{scenario} [{phase}] {config}") + for metric in SUMMARY_METRICS.get(scenario, ("wallMs",)): + cells = [] + for records in sides: + values = [] + for record in records: + value = record.get(metric) + if isinstance(value, list): + values.extend(value) + elif isinstance(value, (int, float)): + values.append(value) + errors = sum(1 for record in records if "error" in record) + if values: + cells.append(f"n={len(records)} P50={percentile(values, .5):g} P90={percentile(values, .9):g}" + + (f" errors={errors}" if errors else "")) + else: + cells.append(f"n={len(records)} -" + (f" errors={errors}" if errors else "")) + print(f" {metric:>14}: " + " | ".join(cells)) + for records in sides: + checks = [record for record in records if "matchesFreshRead" in record] + if checks: + print(f" {'correctness':>14}: missed={sum(r['missed'] for r in checks)} " + f"mismatched={sum(not r['matchesFreshRead'] for r in checks)} " + f"wrongStatus={sum(r['status'] != r['expected'] for r in checks)} of {len(checks)}") + digests = {record.get("outputDigest") or record.get("toolsDigest") for record in records} - {None} + if digests: + print(f" {'digests':>14}: {sorted(digests)}") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--scenario", choices=["summary", "wait", "contention", "show", "events", "_wait-cold", "_settle"], + default="summary") + parser.add_argument("--source", default=str(HERE), help="Source tree to measure.") + parser.add_argument("--out", help="Append JSON lines here; stdout when omitted.") + parser.add_argument("--fixture-dir", default=str(Path(tempfile.gettempdir()) / "opendirector-bench-fixtures")) + parser.add_argument("--summarize", nargs="+", metavar="JSONL") + # summary (original) and single-config wait. + parser.add_argument("--jobs", type=int, default=None) + parser.add_argument("--ticks", type=int, default=60) + parser.add_argument("--nodes", type=int, default=None) + parser.add_argument("--commits", type=int, default=None) + parser.add_argument("--finished", type=int, default=None) + parser.add_argument("--projects", type=int, default=None) + parser.add_argument("--verify-bytes", action="store_true", help="Simulate the Windows head-file hash.") + parser.add_argument("--json", action="store_true") + # wait. + parser.add_argument("--matrix", action="store_true", help="Center configuration plus one change per dimension.") + parser.add_argument("--parts", default="idle,settled,busy,visibility", + help="Comma-separated wait cases to run: idle, settled, busy, visibility.") + parser.add_argument("--window", type=float, default=5.0, help="Seconds per measured wait window.") + parser.add_argument("--warm", type=int, default=10) + parser.add_argument("--cold", type=int, default=5) + parser.add_argument("--busy", type=int, default=5) + parser.add_argument("--write-rate", type=float, default=2.0) + parser.add_argument("--visibility", type=int, default=15) + parser.add_argument("--cross-process", type=int, default=6) + parser.add_argument("--seed", type=int, default=449) + # show and events. + parser.add_argument("--show-nodes", type=int, nargs="+", default=[50, 200, 1000]) + parser.add_argument("--show-samples", type=int, default=30) + parser.add_argument("--lock-seconds", type=float, default=2.0) + parser.add_argument("--event-calls", type=int, nargs="+", default=[100, 1000, 2500, 5000]) + parser.add_argument("--event-samples", type=int, default=10) + parser.add_argument("--contention-nodes", type=int, nargs="+", default=[200, 1000]) + parser.add_argument("--contention-waiters", type=int, nargs="+", default=[1, 5, 10]) + parser.add_argument("--contention-samples", type=int, default=3) + parser.add_argument("--contention-saves", action=argparse.BooleanOptionalAction, default=True, + help="Include a save in every operation cycle (the head then moves almost every tick).") + parser.add_argument("--contention-burner", action="store_true", + help="Control for CPU frequency: keep another process busy during each window.") + # internal children. + parser.add_argument("--work-dir") + parser.add_argument("--child-meta") + parser.add_argument("--project") + parser.add_argument("--job") + parser.add_argument("--status") + parser.add_argument("--delay", type=float, default=0.0) + options = parser.parse_args() + if options.summarize: + summarize(options.summarize) + return + configure_runtime() + if options.scenario == "_wait-cold": + return run_wait_cold_child(options) + if options.scenario == "_settle": + return run_settle_child(options) + if options.scenario == "summary": + options.jobs, options.nodes, options.commits = options.jobs or 14, options.nodes or 200, options.commits or 600 + return run_summary(options) + Path(options.fixture_dir).mkdir(parents=True, exist_ok=True) + out = Output(options.out, source_identity()) + {"wait": run_wait, "contention": run_contention, "show": run_show, + "events": run_events}[options.scenario](options, out) + + if __name__ == "__main__": main() From b2df1509401f11efd65b7cce038eaf2c7bf8b0ee Mon Sep 17 00:00:00 2001 From: Redivesue Date: Sun, 29 Nov 2026 03:02:55 +0800 Subject: [PATCH 02/11] [perf] canvas: copy a waited project's snapshot only after a commit job.status and canvas.status waits poll every half second, and every tick deep-copied the whole project snapshot inside the catalog lock. That lock is shared across threads and processes with lease renewal, saves, job checkpoints and change polling, so an idle 60-second wait held it for about 2.4 s on a 200-node project. CommitLog.snapshot_if_changed runs the same recovery, lookup and head validation as snapshot() in one lock acquisition and copies the snapshot only when the head differs from the one the caller already has. Every job, result and canvas change is a commit with a new head, and the job and item views read nothing but the snapshot, so an unchanged head leaves the previous view current. Because the head and snapshot come from one acquisition, a commit between them cannot be missed; journal recovery, blocked projects and a rewritten head are reported on the same tick as before. Each tick still takes the catalog lock exactly once. snapshot(), head(), job_states() and item_status() are unchanged; the waits reuse their view computation through _job_views and _item_view. Measured with scripts/bench_agent_polling.py on macOS (base b834c01d): a 5-second idle wait now copies the snapshot once instead of 11 times; wait CPU falls from 220 to 54 ms and catalog-lock hold from 198 to 35 ms on a 200-node project, and from 483 to 79 ms at 1,000 nodes. Terminal states are reported as quickly as before, in process and from another process, and every returned state matched a fresh read. --- .../application/creation_canvas.py | 32 ++- .../infrastructure/creation_commit_log.py | 26 +++ tests/test_creation_canvas_service.py | 201 +++++++++++++++++- tests/test_creation_storage.py | 66 ++++++ 4 files changed, 313 insertions(+), 12 deletions(-) diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index d8c83cc9d..a2c3a2f73 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -785,7 +785,10 @@ def _mutate(self, data, kind, payload): raise ContractError('capability_unsupported', '未实现该业务命令。') def item_status(self, project_id: UUID, item_id: UUID) -> dict: - snapshot = self.projects.snapshot(project_id) + return self._item_view(self.projects.snapshot(project_id), item_id) + + @staticmethod + def _item_view(snapshot, item_id: UUID) -> dict: item = next((item for item in snapshot.canvasItems if item.id == item_id), None) if item is None: raise ProjectError('画布组件不在当前工程中。', 404) @@ -814,7 +817,9 @@ def item_status(self, project_id: UUID, item_id: UUID) -> dict: def job_states(self, project_id: UUID, object_ids: tuple[UUID, ...] = ()) -> dict: """Read the requested jobs and their deliveries from one snapshot; unfinished jobs when none are named.""" - snapshot = self.projects.snapshot(project_id) + return self._job_views(self.projects.snapshot(project_id), object_ids) + + def _job_views(self, snapshot, object_ids: tuple[UUID, ...] = ()) -> dict: jobs = {job.id: job for job in snapshot.jobs} if object_ids: missing = [str(identity) for identity in object_ids if identity not in jobs] @@ -856,13 +861,26 @@ def unfinished_jobs(self, project_id: UUID) -> tuple[UUID, ...]: return tuple(job.id for job in self.projects.snapshot(project_id).jobs if job.status not in self.TERMINAL_JOB_STATES) + def _refresh(self, project_id: UUID, head, view, build): + """One project read per poll tick; copy and rebuild only after a commit. + + Every job, result and canvas change is a commit with a new head, and the + views read nothing but the snapshot, so an unchanged head leaves the + previous view current. The head and snapshot come from the same record, + so a commit landing between them cannot be missed. + """ + head, snapshot = self.projects.snapshot_if_changed(project_id, head) + return head, view if snapshot is None else build(snapshot) + async def wait_jobs(self, project_id: UUID, object_ids: tuple[UUID, ...] = (), wait_seconds: float = 0, until: str = 'all') -> dict: - """Answer for a whole set of jobs with at most one snapshot read per poll tick.""" + """Answer for a whole set of jobs, copying the snapshot only when the project changed.""" group = object_ids or await asyncio.to_thread(self.unfinished_jobs, project_id) deadline = asyncio.get_running_loop().time() + wait_seconds + head, state = None, None while True: - state = await asyncio.to_thread(self.job_states, project_id, group) + head, state = await asyncio.to_thread(self._refresh, project_id, head, state, + lambda snapshot: self._job_views(snapshot, group)) jobs = state['jobs'] settled = state['terminal'] or (bool(jobs) and until == 'any' and any( job['status'] in self.TERMINAL_JOB_STATES for job in jobs)) @@ -872,14 +890,16 @@ async def wait_jobs(self, project_id: UUID, object_ids: tuple[UUID, ...] = (), w await asyncio.sleep(min(0.5, remaining)) async def wait_item_status(self, project_id: UUID, item_id: UUID, wait_seconds: float = 0) -> dict: - current = await asyncio.to_thread(self.item_status, project_id, item_id) + def build(snapshot): + return self._item_view(snapshot, item_id) + head, current = await asyncio.to_thread(self._refresh, project_id, None, None, build) deadline = asyncio.get_running_loop().time() + wait_seconds while current['status'] in {'queued', 'running'}: remaining = deadline - asyncio.get_running_loop().time() if remaining <= 0: break await asyncio.sleep(min(0.5, remaining)) - updated = await asyncio.to_thread(self.item_status, project_id, item_id) + head, updated = await asyncio.to_thread(self._refresh, project_id, head, current, build) if updated != current: return updated return current diff --git a/packages/core/src/opendirector/infrastructure/creation_commit_log.py b/packages/core/src/opendirector/infrastructure/creation_commit_log.py index 1ad00d6bb..b45644fb0 100644 --- a/packages/core/src/opendirector/infrastructure/creation_commit_log.py +++ b/packages/core/src/opendirector/infrastructure/creation_commit_log.py @@ -394,6 +394,32 @@ def snapshot(self, project_id): raise path, manifest = current + def snapshot_if_changed(self, project_id, known_head): + """The head commit and its snapshot, copied only when the head moved. + + A wait polls the same project every half second, and deep-copying the + whole snapshot on every tick cost CPU and the GIL while nothing had + changed. This follows snapshot() step for step (published manifest, + head validation, retry after a concurrent rename), so locking, journal + recovery and a corrupt head are handled exactly as there, and the head + and snapshot it returns always come from the same record. A commit + always publishes a new head, so an unchanged head means an unchanged + snapshot. + """ + path, manifest = self._published_manifest(project_id) + while True: + try: + record, _ = self._current_record(None, project_id, path, manifest) + head = record.command.commandId + if head == known_head: + return head, None + return head, record.snapshot.model_copy(deep=True) + except (OSError, ProjectError): + current = self._published_manifest(project_id) + if current == (path, manifest): + raise + path, manifest = current + def head(self, project_id): """The current head commit, cheap enough to gate content-addressed caches. diff --git a/tests/test_creation_canvas_service.py b/tests/test_creation_canvas_service.py index 7e28ccb92..575992b46 100644 --- a/tests/test_creation_canvas_service.py +++ b/tests/test_creation_canvas_service.py @@ -407,16 +407,23 @@ def test_canvas_item_status_is_scoped_and_read_only(project): canvas.item_status(pid, uuid4()) +def every_tick_commits(store, monkeypatch): + """Model a project that receives a new commit before every poll tick.""" + snapshot = store.snapshot + monkeypatch.setattr(store, 'snapshot_if_changed', lambda project_id, head: (uuid4(), snapshot(project_id))) + + def test_canvas_item_wait_returns_on_change_and_timeout(project, monkeypatch): import asyncio store, pid, session = project item, _ = media(project) canvas = CreationCanvas(store) + every_tick_commits(store, monkeypatch) states = [{'status': 'running', 'revision': 1}, {'status': 'succeeded', 'revision': 2}] - monkeypatch.setattr(canvas, 'item_status', lambda *args: states.pop(0) if len(states) > 1 else states[0]) + monkeypatch.setattr(canvas, '_item_view', lambda *args: states.pop(0) if len(states) > 1 else states[0]) result = asyncio.run(canvas.wait_item_status(pid, item.id, 2)) assert result['status'] == 'succeeded' - monkeypatch.setattr(canvas, 'item_status', lambda *args: {'status': 'running'}) + monkeypatch.setattr(canvas, '_item_view', lambda *args: {'status': 'running'}) assert asyncio.run(canvas.wait_item_status(pid, item.id, .01)) == {'status': 'running'} @@ -587,17 +594,18 @@ def test_wait_jobs_returns_on_any_or_all_and_stops_at_the_timeout(project, monke store, pid, _ = project jobs = seed_jobs(project, 2) canvas = CreationCanvas(store) + every_tick_commits(store, monkeypatch) windows = [{'jobs': [{'status': 'running'}, {'status': 'queued'}], 'terminal': False}, {'jobs': [{'status': 'succeeded'}, {'status': 'queued'}], 'terminal': False}, {'jobs': [{'status': 'succeeded'}, {'status': 'running'}], 'terminal': False}] - monkeypatch.setattr(canvas, 'job_states', lambda *args: windows[0]) + monkeypatch.setattr(canvas, '_job_views', lambda *args: windows[0]) assert asyncio.run(canvas.wait_jobs(pid, (), 0.01, 'all'))['terminal'] is False calls = [] def sequence(*args): calls.append(1) return windows[min(len(calls) - 1, len(windows) - 1)] - monkeypatch.setattr(canvas, 'job_states', sequence) + monkeypatch.setattr(canvas, '_job_views', sequence) any_result = asyncio.run(canvas.wait_jobs(pid, (), 5, 'any')) assert any_result['jobs'][0]['status'] == 'succeeded' assert len(calls) == 2 @@ -609,16 +617,17 @@ def test_wait_jobs_holds_the_group_it_started_with(project, monkeypatch): store, pid, _ = project jobs = seed_jobs(project, 2) canvas = CreationCanvas(store) + every_tick_commits(store, monkeypatch) seen = [] - def states(project_id, object_ids=()): + def states(snapshot, object_ids=()): seen.append(tuple(object_ids)) settled = len(seen) > 1 return {'jobs': [{'id': str(job.id), 'status': 'failed' if settled and index else 'queued', 'errorDetails': {'category': 'provider'} if settled and index else None} for index, job in enumerate(jobs)], 'terminal': settled} - monkeypatch.setattr(canvas, 'job_states', states) + monkeypatch.setattr(canvas, '_job_views', states) result = asyncio.run(canvas.wait_jobs(pid, (), 5, 'all')) assert seen[0] == tuple(job.id for job in jobs) assert seen[1] == seen[0] @@ -741,3 +750,183 @@ def test_canvas_placement_rejects_entire_batch(project, fault): }[fault] assert not receipt.canvasPlacements assert store.snapshot(pid) == before + + +def settle(store, project_id, job_id, status): + """Commit a terminal state the way a generation checkpoint does.""" + from opendirector.domain.creation.generation import Job + from opendirector.domain.generation import GenerationFailure + job = next(item for item in store.snapshot(project_id).jobs if item.id == job_id) + changes = {'status': status, 'recovery': 'review' if status == 'interrupted' else 'retry'} + if status == 'failed': + changes['errorDetails'] = GenerationFailure(category='provider', stage='poll', message='provider error', + suggestion='check the provider').model_dump(mode='json') + updated = Job.model_validate({**job.model_dump(), **changes, 'revision': job.revision + 1}) + command = parse_command(dict(commandId=uuid4(), projectId=project_id, type='job.checkpoint', + expectedVersions=[dict(objectType='job', id=job.id, revision=job.revision)], payload=dict(job=updated))) + receipt = store.commit(command, lambda current: current.model_copy(update={ + 'jobs': tuple(updated if item.id == job.id else item for item in current.jobs)}), source='background') + assert receipt.status == 'applied' + + +def gated_reads(store, monkeypatch): + """Count gated reads, the snapshot copies among them and the catalog-lock + acquisitions each of them makes (writers and checks are not counted). + locksOfSnapshot is what one snapshot() read takes in the same state.""" + import threading + reads = {'calls': 0, 'copies': 0, 'locksPerRead': []} + gated, transaction = store.snapshot_if_changed, store.local.transaction + inside = threading.local() + + def counted(project_id, head): + reads['calls'] += 1 + inside.locks = 0 + try: + value = gated(project_id, head) + finally: + reads['locksPerRead'].append(inside.locks) + inside.locks = None + reads['copies'] += value[1] is not None + return value + + def locked(): + if getattr(inside, 'locks', None) is not None: + inside.locks += 1 + return transaction() + monkeypatch.setattr(store, 'snapshot_if_changed', counted) + monkeypatch.setattr(store.local, 'transaction', locked) + inside.locks = 0 + store.snapshot(store.list_projects()['projects'][0]['id']) + reads['locksOfSnapshot'] = inside.locks + inside.locks = None + return reads + + +def later(seconds, action): + import threading + thread = threading.Timer(seconds, action) + thread.start() + return thread + + +def test_wait_copies_the_snapshot_once_while_nothing_is_committed(project, monkeypatch): + import asyncio + store, pid, _ = project + jobs = seed_jobs(project, 2) + canvas = CreationCanvas(store) + reads = gated_reads(store, monkeypatch) + result = asyncio.run(canvas.wait_jobs(pid, tuple(job.id for job in jobs), 1.2, 'all')) + assert reads['calls'] >= 3 and reads['copies'] == 1 + # Every tick locks exactly as a full snapshot() read does. + assert set(reads['locksPerRead']) == {reads['locksOfSnapshot']} + assert result['terminal'] is False + assert result == canvas.job_states(pid, tuple(job.id for job in jobs)) + + +@pytest.mark.parametrize('status', ['failed', 'cancelled', 'interrupted']) +def test_wait_reports_a_terminal_state_committed_during_the_wait(project, monkeypatch, status): + import asyncio + import time + store, pid, _ = project + jobs = seed_jobs(project, 2) + canvas = CreationCanvas(store) + reads = gated_reads(store, monkeypatch) + timer = later(0.3, lambda: settle(store, pid, jobs[1].id, status)) + started = time.monotonic() + result = asyncio.run(canvas.wait_jobs(pid, (jobs[1].id,), 5, 'all')) + timer.join() + assert time.monotonic() - started < 2 + assert result == canvas.job_states(pid, (jobs[1].id,)) + assert result['terminal'] is True and result['jobs'][0]['status'] == status + if status == 'failed': + assert result['jobs'][0]['errorDetails']['message'] == 'provider error' + assert reads['copies'] == 2 and set(reads['locksPerRead']) == {reads['locksOfSnapshot']} + + +def test_wait_rereads_after_an_unrelated_commit_and_keeps_waiting(project, monkeypatch): + import asyncio + store, pid, session = project + jobs = seed_jobs(project, 1) + canvas = CreationCanvas(store) + reads = gated_reads(store, monkeypatch) + timer = later(0.3, lambda: send(store, pid, 'asset.writeText', session=session, name='note.md', text='x')) + result = asyncio.run(canvas.wait_jobs(pid, (jobs[0].id,), 1.5, 'all')) + timer.join() + assert result['terminal'] is False and result['jobs'][0]['status'] == 'queued' + assert reads['copies'] == 2 and set(reads['locksPerRead']) == {reads['locksOfSnapshot']} + + +def test_wait_sees_a_commit_from_another_store_on_the_same_workspace(project): + """Another process commits through its own catalog view; the manifest is reread every tick.""" + import asyncio + store, pid, _ = project + jobs = seed_jobs(project, 1) + canvas = CreationCanvas(store) + other = CreationProjects(LocalProjects(store.local.repository)) + timer = later(0.3, lambda: settle(other, pid, jobs[0].id, 'failed')) + result = asyncio.run(canvas.wait_jobs(pid, (jobs[0].id,), 5, 'all')) + timer.join() + assert result['terminal'] is True and result['jobs'][0]['status'] == 'failed' + + +def test_wait_answers_after_the_catalog_lock_is_released(project): + import asyncio + import threading + import time + store, pid, _ = project + jobs = seed_jobs(project, 1) + canvas = CreationCanvas(store) + held, release = threading.Event(), threading.Event() + + def hold(): + with store.local.transaction(): + held.set() + release.wait(5) + holder = threading.Thread(target=hold) + holder.start() + held.wait(5) + timer = later(1.0, release.set) + started = time.monotonic() + result = asyncio.run(canvas.wait_jobs(pid, (jobs[0].id,), 0, 'all')) + holder.join() + timer.join() + assert time.monotonic() - started >= 0.9 + assert result == canvas.job_states(pid, (jobs[0].id,)) + + +def test_wait_rebuilds_delivery_from_the_snapshot_that_moved_the_head(): + import asyncio + from types import SimpleNamespace + from test_creation_contracts import project_example + succeeded = project_example() + job = succeeded.jobs[0] + running = succeeded.model_copy(update={'jobs': (job.model_copy(update={'status': 'running'}), *succeeded.jobs[1:])}) + answers = iter([('a', running), ('a', None), ('b', succeeded)]) + heads = [] + + def snapshot_if_changed(project_id, head): + heads.append(head) + return next(answers) + canvas = CreationCanvas(SimpleNamespace(snapshot_if_changed=snapshot_if_changed)) + result = asyncio.run(canvas.wait_jobs(succeeded.project.id, (job.id,), 5, 'all')) + assert heads == [None, 'a', 'a'] + assert result == canvas._job_views(succeeded, (job.id,)) + assert result['jobs'][0]['delivery']['adopted'] is True + + +def test_canvas_status_wait_copies_once_and_returns_on_a_commit(project, monkeypatch): + import asyncio + store, pid, session = project + jobs = seed_jobs(project, 1) + item_id = uuid4() + assert send(store, pid, 'canvas.show', session=session, item=dict(id=item_id, projectId=pid, kind='image', + binding=dict(role='generation', objectRef=dict(id=jobs[0].inputSnapshot.spec.id)))).status == 'applied' + canvas = CreationCanvas(store) + reads = gated_reads(store, monkeypatch) + idle = asyncio.run(canvas.wait_item_status(pid, item_id, 1.2)) + assert idle == canvas.item_status(pid, item_id) and idle['status'] == 'queued' + assert reads['copies'] == 1 and reads['calls'] >= 3 and set(reads['locksPerRead']) == {reads['locksOfSnapshot']} + timer = later(0.3, lambda: settle(store, pid, jobs[0].id, 'failed')) + changed = asyncio.run(canvas.wait_item_status(pid, item_id, 5)) + timer.join() + assert changed['status'] == 'failed' and changed == canvas.item_status(pid, item_id) diff --git a/tests/test_creation_storage.py b/tests/test_creation_storage.py index 22198bbf7..e292cdd11 100644 --- a/tests/test_creation_storage.py +++ b/tests/test_creation_storage.py @@ -1347,3 +1347,69 @@ def test_a_lapsed_lease_has_a_stable_code_and_a_heartbeat_restores_it(projects): assert lapsed.value.status == 409 and lapsed.value.code == 'session_expired' projects.heartbeat(session, created.projectId) projects.view(created.projectId, client, view, session=session) + + +def count_transactions(store, monkeypatch): + entered = [] + transaction = store.local.transaction + + def counted(): + entered.append(1) + return transaction() + monkeypatch.setattr(store.local, 'transaction', counted) + return entered + + +def test_snapshot_if_changed_copies_only_when_the_head_moves(projects, monkeypatch): + created = create(projects) + entered = count_transactions(projects, monkeypatch) + head, first = projects.snapshot_if_changed(created.projectId, None) + assert head == created.commandId == projects.head(created.projectId) + assert first == projects.snapshot(created.projectId) + entered.clear() + projects.snapshot(created.projectId) + full = len(entered) + entered.clear() + assert projects.snapshot_if_changed(created.projectId, head) == (head, None) + # It locks exactly as snapshot() does, whether or not it copies. + assert len(entered) == full + renamed = rename(created) + projects.execute(renamed) + entered.clear() + projects.snapshot(created.projectId) + full = len(entered) + entered.clear() + moved, second = projects.snapshot_if_changed(created.projectId, head) + assert len(entered) == full + assert moved == renamed.commandId and second == projects.snapshot(created.projectId) + assert second.project.name == 'Renamed' + # The copy is the caller's own, like snapshot(). + assert second is not projects.snapshot_if_changed(created.projectId, None)[1] + + +def test_snapshot_if_changed_finishes_a_pending_publication_like_snapshot(projects): + """head() skips journal recovery; the gated read must not.""" + created = create(projects) + command = rename(created) + fail_at(projects, 'bundle_written') + with pytest.raises(OSError): + projects.execute(command) + assert projects.head(created.projectId) == created.commandId + projects._checkpoint = lambda stage: None + head, snapshot = projects.snapshot_if_changed(created.projectId, created.commandId) + assert head == command.commandId + assert snapshot.project.name == 'Renamed' + assert list(projects.intents.glob('*.json')) == [] + + +def test_snapshot_if_changed_rejects_a_rewritten_head_like_snapshot(projects): + created = create(projects) + head, _ = projects.snapshot_if_changed(created.projectId, None) + file = projects.root / 'Example' / 'commits' / f'{head}.json' + file.write_bytes(file.read_bytes().replace(b'Example', b'Corrupt')) + with pytest.raises(ProjectError) as gated: + projects.snapshot_if_changed(created.projectId, head) + with pytest.raises(ProjectError) as full: + projects.snapshot(created.projectId) + assert gated.value.code == full.value.code == 'storage_unavailable' + assert str(gated.value) == str(full.value) From 4f90aa3032f2033624918300d6a067e774de13b1 Mon Sep 17 00:00:00 2001 From: Redivesue Date: Sun, 29 Nov 2026 03:14:51 +0800 Subject: [PATCH 03/11] [perf] cli: report job show delivery from job.status, not a project read job show and query job.get read the whole project after a succeeded job to work out which canvas items show its asset. In agent mode that was a read_project call: every record plus the model catalog, and, unlike read-only queries, it waited for the turn's execution slot behind any write in progress. job wait already reports delivery from job.status. job show now asks job.status for the one job and takes its delivery, so both commands report delivery through the same server-side code. The fields and their values are unchanged; the previous client-side computation is kept in the test as the reference for adopted, candidate, material-bound and material-override deliveries. Errors propagate as before; generation jobs are never removed, so the second query cannot miss a job the first one found. Measured with scripts/bench_agent_polling.py --scenario show (200-node project): agent-mode response bytes fall from 140,085 to 2,660, HTTP from 125,435 to 2,486, and with a write holding the execution slot for 2 s job show answers in 54 ms instead of 2,034 ms. Output digests match the base commit at 50, 200 and 1,000 nodes. --- packages/core/src/opendirector/cli.py | 22 ++---- tests/test_cli.py | 104 ++++++++++++++++++++------ 2 files changed, 88 insertions(+), 38 deletions(-) diff --git a/packages/core/src/opendirector/cli.py b/packages/core/src/opendirector/cli.py index 1fc317c2a..e82c1f6ee 100644 --- a/packages/core/src/opendirector/cli.py +++ b/packages/core/src/opendirector/cli.py @@ -32,7 +32,6 @@ from typer._click.exceptions import UsageError from opendirector.agent.tools import COMMANDS, command_help -from opendirector.application.creation_canvas import DELIVERY_GUIDANCE from opendirector.domain.creation.assets import ( ASSET_DOWNLOAD_ENGLISH, ASSET_REVISION_HEADER, AssetDownloadFile, AssetDownloadReceipt, ) @@ -709,19 +708,14 @@ def query(self, kind, **arguments): self.request("POST", self.path("/queries"), json={"type": kind, "queryId": str(uuid4()), "projectId": str(self.project), **arguments})) if kind == "job.get" and result.get("status") == "succeeded" and result.get("asset"): - snapshot = self.snapshot() - asset_id = result["asset"]["assetId"] - results = [value for value in snapshot["results"] if value["asset"]["assetId"] == asset_id] - adopted_specs = {spec["id"] for spec in snapshot["generationSpecs"] - if any(value["id"] == spec.get("currentResultId") for value in results)} - items = [item for item in snapshot["canvasItems"] if - (item["binding"]["role"] == "generation" and item["binding"]["objectRef"]["id"] in adopted_specs - and not item["binding"].get("materialOverride")) or - (item["binding"]["role"] == "material" and item["binding"]["objectRef"]["assetId"] == asset_id)] - result = {**result, "delivery": {"registered": True, "asset": result["asset"], - "adopted": bool(adopted_specs), "canvasItems": [{key: item[key] for key in - ("id", "revision", "visible", "position", "width", "height")} for item in items], - "guidance": DELIVERY_GUIDANCE}} + # job wait reports delivery from job.status; job show uses the same + # server-side answer. Reading the whole project here sent every + # record and the model catalog, and in agent mode queued behind the + # turn's writes, just to find the canvas items showing one asset. + views = self.query("job.status", objectIds=[result["id"]], waitSeconds=0)["jobs"] + delivery = views[0].get("delivery") if views else None + if delivery is not None: + result = {**result, "delivery": delivery} return result diff --git a/tests/test_cli.py b/tests/test_cli.py index 0b65d59ad..ca624e097 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -442,37 +442,93 @@ def test_accepted_cli_receipt_provides_wait_commands(monkeypatch): client.http.close() -@pytest.mark.parametrize('adopted', [False, True]) -def test_completed_job_inspection_reuses_registered_result(monkeypatch, tmp_path, adopted): +def previous_delivery(snapshot, job): + """The delivery job show built from a full project read before it asked job.status.""" + from opendirector.application.creation_canvas import DELIVERY_GUIDANCE + asset_id = job["asset"]["assetId"] + results = [value for value in snapshot["results"] if value["asset"]["assetId"] == asset_id] + adopted_specs = {spec["id"] for spec in snapshot["generationSpecs"] + if any(value["id"] == spec.get("currentResultId") for value in results)} + items = [item for item in snapshot["canvasItems"] if + (item["binding"]["role"] == "generation" and item["binding"]["objectRef"]["id"] in adopted_specs + and not item["binding"].get("materialOverride")) or + (item["binding"]["role"] == "material" and item["binding"]["objectRef"]["assetId"] == asset_id)] + return {"registered": True, "asset": job["asset"], "adopted": bool(adopted_specs), + "canvasItems": [{key: item[key] for key in ("id", "revision", "visible", "position", "width", "height")} + for item in items], "guidance": DELIVERY_GUIDANCE} + + +def delivery_variant(variant): + """A real project snapshot whose succeeded job is delivered in one of several ways.""" + from test_creation_contracts import project_example + snapshot = project_example() + job = snapshot.jobs[0] + items = list(snapshot.canvasItems) + generated = next(index for index, item in enumerate(items) if item.binding.role == 'generation') + if variant == 'candidate': + snapshot = snapshot.model_copy(update={'generationSpecs': tuple( + spec.model_copy(update={'currentResultId': None}) for spec in snapshot.generationSpecs)}) + if variant in {'material', 'override'}: + material = next(item for item in items if item.binding.role == 'material') + items.append(material.model_copy(update={'id': uuid4(), 'binding': material.binding.model_copy( + update={'objectRef': job.asset})})) + if variant == 'override': + item = items[generated] + items[generated] = item.model_copy(update={'binding': item.binding.model_copy( + update={'materialOverride': job.asset})}) + return snapshot.model_copy(update={'canvasItems': tuple(items)}), job + + +@pytest.mark.parametrize('variant', ['adopted', 'candidate', 'material', 'override']) +def test_completed_job_inspection_takes_delivery_from_job_status(monkeypatch, variant): + """job show reports the same delivery as before without reading the whole project.""" from copy import deepcopy - asset, result_id, spec_id, item_id = [str(uuid4()) for _ in range(4)] - ref = {'assetId': asset, 'revision': 1, 'kind': 'video', 'fingerprint': 'sha256:' + 'a' * 64} - job = {'status': 'succeeded', 'asset': ref} - snapshot = {'assets': [{'id': asset}], 'results': [{'id': result_id, 'asset': ref}], - 'generationSpecs': [{'id': spec_id, 'currentResultId': result_id if adopted else None}], - 'canvasItems': [{'id': item_id, 'revision': 2, 'visible': True, - 'position': {'x': 400, 'y': 0}, 'width': 352, 'height': 352, - 'binding': {'role': 'generation', 'objectRef': {'id': spec_id}}}]} - before = deepcopy(snapshot) + from types import SimpleNamespace + from opendirector.application.creation_canvas import CreationCanvas + snapshot, job = delivery_variant(variant) + canvas = CreationCanvas(SimpleNamespace(snapshot=lambda _: snapshot)) + record = job.model_dump(mode='json') + before = deepcopy(record) monkeypatch.setenv('OPENDIRECTOR_AGENT_SOCKET', '/test-only.sock') - client = cli.Client(None, 'http://localhost:18765', None, None) + client = cli.Client(snapshot.project.id, 'http://localhost:18765', None, None) calls = [] + def call(name, arguments, **kwargs): - calls.append(name) + calls.append((name, arguments['type'])) assert name == 'query' - return job + if arguments['type'] == 'job.get': + return record + assert arguments == {'type': 'job.status', 'objectIds': [record['id']], 'waitSeconds': 0} + return json.loads(json.dumps(canvas.job_states(snapshot.project.id, (job.id,)))) + + def full_read(): + raise AssertionError('job show must not read the whole project') + monkeypatch.setattr(client, 'call', call) + monkeypatch.setattr(client, 'snapshot', full_read) + try: + response = client.query('job.get', objectId=record['id']) + assert calls == [('query', 'job.get'), ('query', 'job.status')] + assert response['delivery'] == previous_delivery(snapshot.model_dump(mode='json'), record) + assert {key: value for key, value in response.items() if key != 'delivery'} == record + assert record == before and 'delivery' not in record + expected = {'adopted': (True, 1), 'candidate': (False, 0), 'material': (True, 2), 'override': (True, 1)} + assert (response['delivery']['adopted'], len(response['delivery']['canvasItems'])) == expected[variant] + finally: + client.http.close() + + +def test_job_inspection_without_a_result_reads_nothing_more(monkeypatch): + monkeypatch.setenv('OPENDIRECTOR_AGENT_SOCKET', '/test-only.sock') + client = cli.Client(uuid4(), 'http://localhost:18765', None, None) + calls = [] + + def call(name, arguments, **kwargs): + calls.append(arguments['type']) + return {'id': str(uuid4()), 'status': 'running', 'asset': None} monkeypatch.setattr(client, 'call', call) - monkeypatch.setattr(client, 'snapshot', lambda: snapshot) try: - for _ in range(2): - response = client.query('job.get', objectId=str(uuid4())) - delivery = response['delivery'] - assert delivery['registered'] and delivery['asset'] == ref - assert delivery['adopted'] == adopted - assert [item['id'] for item in delivery['canvasItems']] == ([item_id] if adopted else []) - assert snapshot == before - assert calls == ['query', 'query'] - assert 'delivery' not in job + assert 'delivery' not in client.query('job.get', objectId=str(uuid4())) + assert calls == ['job.get'] finally: client.http.close() From ece01ee229565b4032baabc06fd1b1b3c9c5d26b Mon Sep 17 00:00:00 2001 From: Redivesue Date: Sun, 29 Nov 2026 03:17:27 +0800 Subject: [PATCH 04/11] [perf] assistant: index a turn's tool records by call ID Each tool event looked up its record with a linear search and replaced it with list.index, so folding a turn's events was quadratic on the API event loop. The face-replacement trace in #449 had about 1,200 calls in one turn; a CLI wait loop can produce thousands of events. Keep a call ID to position map beside the records. Records are only appended or replaced in place, so positions never move; order, statuses and each call's first textOffset are unchanged. A test folds interleaved updates for 3 and 2,500 calls and compares the saved records with the previous linear fold. Measured with scripts/bench_agent_polling.py --scenario events through the API, alternating with the base commit: one turn with 2,500 calls takes 609 ms instead of 803 ms and with 5,000 calls 1,298 ms instead of 2,054 ms (P50, n=10 each); saved tool records are identical. --- apps/api/src/opendirector_api/agent.py | 13 ++++++-- tests/test_assistant_conversations.py | 46 ++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 3 deletions(-) diff --git a/apps/api/src/opendirector_api/agent.py b/apps/api/src/opendirector_api/agent.py index a75f2562a..31fc050eb 100644 --- a/apps/api/src/opendirector_api/agent.py +++ b/apps/api/src/opendirector_api/agent.py @@ -762,6 +762,11 @@ async def produce_one(chain: Chain, plan: dict) -> tuple[dict | None, str | None text, status, error = '', 'complete', None activities: list[dict] = [] edited_documents: dict[str, int] = {} + # Where each call ID sits in activities. A turn can carry thousands of + # tool events; a linear search per event made folding them quadratic on + # the event loop. Entries are only appended or replaced in place, so + # positions never move. + positions: dict[str, int] = {} sources: dict = {} previous_sources: dict = {} steps = None @@ -838,14 +843,16 @@ async def renew_session() -> None: # Measurement is a side ledger: the per-call numbers must # not become part of the tool call the turn persists. agent_timing.note(timing, event) - previous = next((item for item in activities if item['id'] == event['id']), None) + position = positions.get(event['id']) + previous = activities[position] if position is not None else None activity = {**{key: item for key, item in event.items() if key not in {'type', 'timing'}}, 'textOffset': previous['textOffset'] if previous else len(text)} - if previous is None: + if position is None: + positions[event['id']] = len(activities) activities.append(activity) else: - activities[activities.index(previous)] = activity + activities[position] = activity event = {'type': 'tool', **activity} chain.events.put(event) except asyncio.CancelledError: diff --git a/tests/test_assistant_conversations.py b/tests/test_assistant_conversations.py index 8b60b537d..e69d91512 100644 --- a/tests/test_assistant_conversations.py +++ b/tests/test_assistant_conversations.py @@ -958,3 +958,49 @@ async def stream(self, run, gateway): with store.transaction() as db: assert db.execute('SELECT 1 FROM sessions WHERE id=?', (store.agent_session_key(run_session),)).fetchone() is None + + +def previous_fold(events): + """How a turn folded tool events before they were indexed by call ID.""" + activities, text = [], '' + for event in events: + if event['type'] == 'delta': + text += event['text'] + if event['type'] != 'tool': + continue + previous = next((item for item in activities if item['id'] == event['id']), None) + activity = {**{key: value for key, value in event.items() if key not in {'type', 'timing'}}, + 'textOffset': previous['textOffset'] if previous else len(text)} + if previous is None: + activities.append(activity) + else: + activities[activities.index(previous)] = activity + return activities + + +@pytest.mark.parametrize('calls', [3, 2500]) +def test_tool_records_keep_order_status_and_first_offset_across_many_events(assistant, monkeypatch, calls): + client, path, _ = assistant + events = [{'type': 'delta', 'text': 'Start. '}] + for index in range(calls): + identity = f'cli:{index}' + events.append({'type': 'tool', 'id': identity, 'name': 'opendirector job wait', 'status': 'running', + 'timing': {'spawn': 0.1}}) + if index % 2: + events.append({'type': 'delta', 'text': f'{index} '}) + if index >= 1: + # Interleave: finish the previous call after the next one started. + events.append({'type': 'tool', 'id': f'cli:{index - 1}', 'name': 'opendirector job wait', + 'status': 'failed' if index % 7 == 0 else 'complete', 'result': str(index)}) + events.append({'type': 'tool', 'id': f'cli:{calls - 1}', 'name': 'opendirector job wait', 'status': 'complete'}) + events.append({'type': 'tool', 'id': 'cli:0', 'name': 'opendirector job wait', 'status': 'complete', 'result': 'again'}) + + async def stream(self, run): + for event in events: + yield event + monkeypatch.setattr(agent.AgentRuntimes, 'stream', stream) + cid = client.get(path).json()['conversationId'] + saved = frames(send(client, path, cid, 'Wait'))[-1]['conversation']['messages'][-1] + assert saved['tools'] == previous_fold(events) + assert [item['id'] for item in saved['tools']] == [f'cli:{index}' for index in range(calls)] + assert all('timing' not in item for item in saved['tools']) From 5279eef8aec5fc10d27eabeef01a56b9b6c70211 Mon Sep 17 00:00:00 2001 From: Redivesue Date: Sun, 29 Nov 2026 03:20:57 +0800 Subject: [PATCH 05/11] [bugfix] agent: give every runtime the same command discovery rule The system prompt asks for one opendirector capabilities call and no per-command --help. The per-turn execution context of the native runtimes (OpenCode, Codex, Claude) and of JiuwenSwarm still said to discover commands with opendirector --help and each command's --help, so a turn received both instructions. Per-command help probing was the discovery cost #455 measured at 33 calls before capabilities existed. Both contexts now use CLI_DISCOVERY, defined beside SYSTEM with the same rule. The fake harnesses of the native and JiuwenSwarm runtime tests assert the actual prompt they receive asks for capabilities once and never for opendirector --help; the same tests fail against the base commit. Human terminal usage still documents --help. This removes the conflicting instruction only. Whether a model now issues fewer discovery calls needs a real-model run, which this change does not include. --- docs/architecture/agent-runtime.md | 2 +- packages/core/src/opendirector/agent/jiuwenswarm.py | 5 ++--- packages/core/src/opendirector/agent/native.py | 5 ++--- packages/core/src/opendirector/agent/tools.py | 6 ++++++ tests/test_jiuwenswarm_runtime.py | 2 ++ tests/test_native_runtime.py | 2 ++ 6 files changed, 15 insertions(+), 7 deletions(-) diff --git a/docs/architecture/agent-runtime.md b/docs/architecture/agent-runtime.md index 2be3abacc..33d9f3fcb 100644 --- a/docs/architecture/agent-runtime.md +++ b/docs/architecture/agent-runtime.md @@ -43,7 +43,7 @@ Antigravity 沿用本机 agy 的账号登录,命令行里不传模型凭证。 适配层为每轮创建 `agent-runs//work/`,启动 harness 并注入本轮 CLI 执行入口。子进程 cwd、PWD 和 ACP 工作区始终指向本轮执行目录;会话身份单独持久化。原生工具以此目录为工作目录,通过继承的 PATH 查找 FFmpeg、ffprobe 等程序。 -业务入口使用 Typer CLI,通过 `opendirector --help` 和子命令的 `--help` 渐进发现操作。查询、编辑及生成命令调用共用业务服务。Agent 通过受令牌保护的本轮连接继承工程范围、编辑会话、执行目录和操作回执;CLI 子进程退出不终止已接受的后台任务。普通终端通过现有 HTTP API 连接服务,写入申请独立编辑会话并遵守工程锁,查询不申请租约。`--session` 可使用已有授权会话。`--operation-id` 提供稳定修改身份,同身份相同输入重放返回原回执,不同输入拒绝。 +业务入口使用 Typer CLI。Agent 每轮先运行一次 `opendirector capabilities`,取得全部业务命令及其必填字段,只有某个字段的结构不明确时才用 `opendirector COMMAND --help-field payload` 查看;系统提示和各 runtime 的本轮执行上下文共用同一句发现规则(`CLI_DISCOVERY`),不再提示逐个命令运行 `--help`。人在终端里仍可用 `opendirector --help` 和子命令的 `--help`。查询、编辑及生成命令调用共用业务服务。Agent 通过受令牌保护的本轮连接继承工程范围、编辑会话、执行目录和操作回执;CLI 子进程退出不终止已接受的后台任务。普通终端通过现有 HTTP API 连接服务,写入申请独立编辑会话并遵守工程锁,查询不申请租约。`--session` 可使用已有授权会话。`--operation-id` 提供稳定修改身份,同身份相同输入重放返回原回执,不同输入拒绝。 接受轮次时,服务端校验画布的工程会话,并为本轮签发独立的工程写入租约。运行期间服务端负责续租,画布关闭或断线后仍可执行本轮已授权的写入。运行结束或停止后释放租约。工程路径、对象锁和预期版本仍由共享业务服务校验,重新打开画布后用户可以继续编辑。 diff --git a/packages/core/src/opendirector/agent/jiuwenswarm.py b/packages/core/src/opendirector/agent/jiuwenswarm.py index 8495b4934..17d8430ba 100644 --- a/packages/core/src/opendirector/agent/jiuwenswarm.py +++ b/packages/core/src/opendirector/agent/jiuwenswarm.py @@ -13,7 +13,7 @@ from opendirector.agent.gateway import ToolGateway from opendirector.agent.skill_snapshot import prepare_skills, copy_skill_tree from opendirector.agent.directory_links import link_directory, unlink_directory -from opendirector.agent.tools import SUGGESTED_REPLIES, SYSTEM +from opendirector.agent.tools import CLI_DISCOVERY, SUGGESTED_REPLIES, SYSTEM from opendirector.agent import cli_transport from opendirector.agent.cli_discovery import cli_executable from opendirector.agent.process import terminate @@ -193,8 +193,7 @@ async def stream(self, run: RunContext, gateway: ToolGateway): 'Use inherited PATH to discover installed programs with command -v. ' 'Read source assets at their supplied absolute paths; do not move or modify them. ' 'Write intermediate files and outputs into the execution directory. ' - 'Use opendirector --help to discover project commands and use opendirector for project changes.\n' - + SUGGESTED_REPLIES + '\n' + + CLI_DISCOVERY + SUGGESTED_REPLIES + '\n' + json.dumps(run.messages[-1:] if session_id else run.messages, ensure_ascii=False)), 'agent': {'name': 'opendirector', 'instructions': SYSTEM, 'tools': ['skill_tool', 'list_skill', 'read_file', 'bash']}, diff --git a/packages/core/src/opendirector/agent/native.py b/packages/core/src/opendirector/agent/native.py index 5bb49cba0..e584456e7 100644 --- a/packages/core/src/opendirector/agent/native.py +++ b/packages/core/src/opendirector/agent/native.py @@ -19,7 +19,7 @@ from opendirector.agent.citations import search_sources from opendirector.agent.gateway import ToolGateway from opendirector.agent.process import terminate -from opendirector.agent.tools import ROOT, SUGGESTED_REPLIES, SYSTEM, runtime_instructions +from opendirector.agent.tools import CLI_DISCOVERY, ROOT, SUGGESTED_REPLIES, SYSTEM, runtime_instructions from opendirector.installation import BUNDLED from opendirector.agent.skill_snapshot import prepare_skills from opendirector.agent.directory_links import link_directory, unlink_directory @@ -277,8 +277,7 @@ async def stream(self, run: RunContext, gateway: ToolGateway): 'Use inherited PATH to discover installed programs with Get-Command in PowerShell or command -v in POSIX shells. ' 'Read source assets at their supplied absolute paths; do not move or modify them. ' 'Write all intermediate files and outputs into the execution directory. ' - 'Use opendirector --help to discover OpenDirector commands and opendirector --help for usage. Use opendirector for project changes.\n' - + SUGGESTED_REPLIES) + + CLI_DISCOVERY + SUGGESTED_REPLIES) prompt = execution_context + '\n' + json.dumps(context[-1:] if session_id else context, ensure_ascii=False) skill_instruction = '' if selected: diff --git a/packages/core/src/opendirector/agent/tools.py b/packages/core/src/opendirector/agent/tools.py index 8db4840ea..01c46b8bd 100644 --- a/packages/core/src/opendirector/agent/tools.py +++ b/packages/core/src/opendirector/agent/tools.py @@ -90,6 +90,12 @@ def query_guidance(failure): identifiers and code unchanged. If a tool error is shown in another language, explain it in the user's language. ''' +# Every runtime's per-turn context repeats how to discover commands. It must +# say what SYSTEM says: one capabilities call, not --help for each command, +# or the turn opens with a probe per command group. +CLI_DISCOVERY = ('Run opendirector capabilities once to discover OpenDirector commands and their required fields; ' + 'inspect one field with opendirector COMMAND --help-field payload only when its shape is unclear. ' + 'Use opendirector for project changes.\n') SUGGESTED_REPLIES = ( 'When there are useful next steps, finish the reply with 3 to 5 distinct suggestions the user ' 'could send verbatim. Use single-line plain-text phrases in the language of the user, ' diff --git a/tests/test_jiuwenswarm_runtime.py b/tests/test_jiuwenswarm_runtime.py index d215f1dfc..e049a8cfc 100644 --- a/tests/test_jiuwenswarm_runtime.py +++ b/tests/test_jiuwenswarm_runtime.py @@ -57,6 +57,8 @@ def emit(kind, **fields): assert '3 to 5 distinct suggestions' in prompt, 'missing suggested reply count' assert 'at most 80 characters per suggestion' in prompt, 'missing suggested reply length limit' assert '[opendirector-replies]: #' in prompt.splitlines(), 'missing suggested reply marker' +assert 'Run opendirector capabilities once' in prompt, 'missing single discovery call' +assert 'opendirector --help' not in prompt, 'per-command help discovery contradicts SYSTEM' sid='native-session' if 'Continue plan' in prompt: assert request['session_id']==sid and 'Save plan' not in prompt diff --git a/tests/test_native_runtime.py b/tests/test_native_runtime.py index b23ace852..6079d8c68 100644 --- a/tests/test_native_runtime.py +++ b/tests/test_native_runtime.py @@ -40,6 +40,8 @@ assert 'at most 80 characters per suggestion' in prompt, 'missing suggested reply length limit' assert '[opendirector-replies]: #' in prompt.splitlines(), 'missing suggested reply marker' assert 'Segment plan' not in prompt +assert 'Run opendirector capabilities once' in prompt, 'missing single discovery call' +assert 'opendirector --help' not in prompt, 'per-command help discovery contradicts SYSTEM' if 'Continue plan' in prompt: assert ('Save a plan' in prompt) == (os.environ.get('TEST_MISSING_ROLLOUT') == '1') runtime = os.environ['TEST_RUNTIME'] From fcfa80f1ed06668f32cbb70376788c290aeba814 Mon Sep 17 00:00:00 2001 From: Redivesue Date: Sun, 29 Nov 2026 03:22:45 +0800 Subject: [PATCH 06/11] [test] trace: reconcile job wait records with the #449 statistics Issue #449 published counts for the DeepSeek face-replacement trace (954 complete job.get records, 59 distinct responses, 895 repeats, 9,662,495 result bytes, 14 project reads after successful jobs). Later changes need the same numbers computed the same way. scripts/trace_job_queries.py applies the published selection rules to a trace archive (read in memory and checked against its SHA-256) or its deepseek.jsonl, labels each completed CLI record as a project change, a necessary wait, an avoidable repeat or a delivery read, and lists each job's status changes. --check-published fails with every number it could not reproduce. Its snapshot estimate for head-gated waits is labelled as a model, not a measurement. The tests use a synthetic trace; the real trace is not in the repository and has not been run here. --- scripts/trace_job_queries.py | 197 ++++++++++++++++++++++++++++++++ tests/test_trace_job_queries.py | 88 ++++++++++++++ 2 files changed, 285 insertions(+) create mode 100644 scripts/trace_job_queries.py create mode 100644 tests/test_trace_job_queries.py diff --git a/scripts/trace_job_queries.py b/scripts/trace_job_queries.py new file mode 100644 index 000000000..a32a51f35 --- /dev/null +++ b/scripts/trace_job_queries.py @@ -0,0 +1,197 @@ +"""Reconcile the tool records of an agent trace with the CLI calls behind them. + +Issue #449 published statistics for a DeepSeek face-replacement run: 954 +job.get status queries recorded as complete, 59 distinct responses, 895 +repeats and 9,662,495 bytes of recorded results. This script recomputes them +from the trace so later changes can be compared on the same terms, and labels +each completed CLI record as a project change, a necessary wait (a new answer +for a job), an avoidable repeat (an answer the same job already gave) or a +project read made only to build a delivery: + + python3 scripts/trace_job_queries.py OpenDirector-trace-3f68aec5-under10MB.zip --check-published + python3 scripts/trace_job_queries.py path/to/deepseek.jsonl --json + +A zip is read in memory and checked against --sha256; nothing in it is +extracted or executed. The selection follows the published rules: top-level +type "tool", status "complete", name "opendirector job wait" and +arguments.type "job.get", grouped by arguments.objectId; attempts are counted +from "running" records. The snapshot estimate at the end is a model, not a +measurement: it assumes no other commit lands while the jobs are waited on. +""" +from __future__ import annotations + +import argparse +import hashlib +import io +import json +from pathlib import Path +import sys +import zipfile + +PUBLISHED_SHA256 = 'aa0416ebdda89248914ed46a9a15161db7c75181b5b4d099390ccec082617244' +PUBLISHED = { + 'records': 2715, + 'cliAttempts': 1053, + 'cliFailures': 16, + 'jobStatusQueries': 954, + 'jobStatuses': {'running': 825, 'queued': 114, 'succeeded': 14, 'failed': 1}, + 'distinctResponses': 59, + 'repeatedResponses': 895, + 'jobStatusResultBytes': 9662495, + 'deliveryProjectReads': 14, +} +WAIT_COMMAND = 'opendirector job wait' +TERMINAL = {'succeeded', 'failed', 'cancelled', 'interrupted'} + + +def read_lines(path, member='deepseek.jsonl', sha256=PUBLISHED_SHA256): + """Return the trace lines and the archive digest (None for a plain file).""" + path = Path(path) + data = path.read_bytes() + if not zipfile.is_zipfile(io.BytesIO(data)): + return data.decode('utf-8').splitlines(), None + digest = hashlib.sha256(data).hexdigest() + if sha256 and digest != sha256: + raise SystemExit(f'Archive SHA-256 {digest} differs from the expected {sha256}.') + with zipfile.ZipFile(io.BytesIO(data)) as archive: + names = [name for name in archive.namelist() if Path(name).name == member] + if len(names) != 1: + raise SystemExit(f'Expected one {member} in the archive, found {len(names)}.') + return archive.read(names[0]).decode('utf-8').splitlines(), digest + + +def parse(lines): + records, malformed = [], 0 + for line in lines: + if not line.strip(): + continue + try: + value = json.loads(line) + except ValueError: + malformed += 1 + continue + if isinstance(value, dict): + records.append(value) + else: + malformed += 1 + return records, malformed + + +def result_status(record): + try: + value = json.loads(record.get('result') or '') + except ValueError: + return None + return value.get('status') if isinstance(value, dict) else None + + +def is_cli(record): + return isinstance(record.get('name'), str) and record['name'].startswith('opendirector') + + +def label(record, seen): + """Classify one completed CLI record; seen maps job ID to its earlier answers.""" + arguments = record.get('arguments') if isinstance(record.get('arguments'), dict) else {} + if 'payload' in arguments: + return 'projectChange' + if record.get('name') == WAIT_COMMAND and arguments.get('type') == 'job.get': + answers = seen.setdefault(arguments.get('objectId'), set()) + result = record.get('result') + if result in answers: + return 'avoidableRepeat' + answers.add(result) + return 'necessaryWait' + if record.get('name') == WAIT_COMMAND and not arguments: + return 'deliveryProjectRead' + return 'other' + + +def reconcile(records): + tools = [record for record in records if record.get('type') == 'tool'] + cli = [record for record in tools if is_cli(record)] + queries = [record for record in tools if record.get('status') == 'complete' + and record.get('name') == WAIT_COMMAND + and isinstance(record.get('arguments'), dict) and record['arguments'].get('type') == 'job.get'] + statuses, groups, result_bytes = {}, {}, 0 + for record in queries: + status = result_status(record) + statuses[status] = statuses.get(status, 0) + 1 + groups.setdefault(record['arguments'].get('objectId'), []).append(record.get('result')) + result_bytes += len((record.get('result') or '').encode('utf-8')) + distinct = sum(len(set(results)) for results in groups.values()) + labels, seen = {}, {} + for record in cli: + if record.get('status') == 'complete': + kind = label(record, seen) + labels[kind] = labels.get(kind, 0) + 1 + jobs = [] + for job_id, results in groups.items(): + sequence = [json.loads(result).get('status') if result else None for result in results] + changes = [status for index, status in enumerate(sequence) if index == 0 or status != sequence[index - 1]] + jobs.append({'jobId': job_id, 'queries': len(results), 'distinctResponses': len(set(results)), + 'statusChanges': changes, 'terminal': bool(sequence and sequence[-1] in TERMINAL)}) + return { + 'records': len(records), + 'toolRecords': len(tools), + 'cliAttempts': sum(1 for record in cli if record.get('status') == 'running'), + 'cliFailures': sum(1 for record in cli if record.get('status') == 'failed'), + 'jobStatusQueries': len(queries), + 'jobStatuses': {str(key): value for key, value in sorted(statuses.items(), key=lambda item: -item[1])}, + 'completeWhileUnfinished': sum(value for key, value in statuses.items() if key not in TERMINAL), + 'distinctResponses': distinct, + 'repeatedResponses': len(queries) - distinct, + 'jobStatusResultBytes': result_bytes, + 'deliveryProjectReads': labels.get('deliveryProjectRead', 0), + 'completedCliLabels': labels, + 'jobs': jobs, + 'estimate': estimate(len(queries), distinct, labels.get('deliveryProjectRead', 0)), + } + + +def estimate(queries, distinct, delivery_reads): + """Server-side snapshot copies for the same waits, as a model. + + Before: one copy per job.get and one per delivery read. With head-gated + waits a copy is needed only when an answer changes, so the distinct + responses bound it from below; any unrelated commit while waiting adds one + more. job show takes delivery from job.status, so delivery reads go away. + """ + return {'kind': 'model estimate, not a measurement', + 'snapshotCopiesBefore': queries + delivery_reads, + 'snapshotCopiesAfterLowerBound': distinct, + 'deliveryProjectReadsAfter': 0} + + +def differences(numbers, expected=PUBLISHED): + return {key: {'expected': value, 'actual': numbers.get(key)} + for key, value in expected.items() if numbers.get(key) != value} + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('trace', help='The trace archive or its deepseek.jsonl.') + parser.add_argument('--sha256', default=PUBLISHED_SHA256, help='Expected archive digest; empty to skip.') + parser.add_argument('--check-published', action='store_true', help='Fail unless the #449 numbers are reproduced.') + parser.add_argument('--json', action='store_true') + options = parser.parse_args(argv) + lines, digest = read_lines(options.trace, sha256=options.sha256) + records, malformed = parse(lines) + numbers = reconcile(records) + numbers.update(archiveSha256=digest, malformedLines=malformed) + if options.json: + print(json.dumps(numbers, ensure_ascii=False, indent=2)) + else: + for key in ('records', 'cliAttempts', 'cliFailures', 'jobStatusQueries', 'jobStatuses', + 'completeWhileUnfinished', 'distinctResponses', 'repeatedResponses', + 'jobStatusResultBytes', 'deliveryProjectReads', 'completedCliLabels', 'estimate'): + print(f'{key}: {numbers[key]}') + if options.check_published: + missing = differences(numbers) + if missing: + print(json.dumps({'notReproduced': missing}, ensure_ascii=False), file=sys.stderr) + return 1 + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/test_trace_job_queries.py b/tests/test_trace_job_queries.py new file mode 100644 index 000000000..b10124cb1 --- /dev/null +++ b/tests/test_trace_job_queries.py @@ -0,0 +1,88 @@ +"""The #449 baseline is only useful if the reconciliation rules are pinned. + +A synthetic trace with known answers covers the published selection rules: +complete job.get records under job wait, grouped by job, deduplicated by their +exact result, attempts counted from running records, and delivery reads with +empty arguments. The real trace is not part of the repository. +""" +import hashlib +import importlib.util +import json +from pathlib import Path +import zipfile + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location('trace_job_queries', ROOT / 'scripts/trace_job_queries.py') +trace = importlib.util.module_from_spec(spec) +spec.loader.exec_module(trace) + + +def tool(status, name='opendirector job wait', arguments=None, result=None, identity='cli:1'): + record = {'type': 'tool', 'id': identity, 'name': name, 'status': status, 'arguments': arguments or {}} + if result is not None: + record['result'] = result + return record + + +def answer(job, status): + return json.dumps({'id': job, 'status': status}, indent=2) + + +def synthetic(): + records = [{'type': 'delta', 'text': 'Working'}] + submit = {'type': 'generation.submit', 'payload': {'specId': 's'}} + records += [tool('running', 'opendirector generation submit', submit), + tool('complete', 'opendirector generation submit', submit, '{"status": "accepted"}'), + tool('running', 'opendirector generation submit', submit), + tool('failed', 'opendirector generation submit', submit)] + for job, statuses in (('a', ['queued', 'running', 'running', 'running', 'succeeded']), + ('b', ['running', 'running', 'failed'])): + for status in statuses: + query = {'type': 'job.get', 'objectId': job} + records += [tool('running', arguments=query), tool('complete', arguments=query, result=answer(job, status))] + records += [tool('running'), tool('complete', result='{"project": {}}')] + records.append({'type': 'tool', 'id': 'deepseek:1', 'name': 'bash', 'status': 'complete'}) + return records + + +def test_reconciliation_counts_follow_the_published_rules(): + numbers = trace.reconcile(synthetic()) + assert numbers['jobStatusQueries'] == 8 + assert numbers['jobStatuses'] == {'running': 5, 'queued': 1, 'succeeded': 1, 'failed': 1} + assert numbers['completeWhileUnfinished'] == 6 + assert numbers['distinctResponses'] == 5 and numbers['repeatedResponses'] == 3 + assert numbers['cliAttempts'] == 11 and numbers['cliFailures'] == 1 + assert numbers['deliveryProjectReads'] == 1 + assert numbers['completedCliLabels'] == {'projectChange': 1, 'necessaryWait': 5, 'avoidableRepeat': 3, + 'deliveryProjectRead': 1} + assert numbers['jobStatusResultBytes'] == sum( + len(answer(job, status).encode()) for job, statuses in ( + ('a', ['queued', 'running', 'running', 'running', 'succeeded']), ('b', ['running', 'running', 'failed'])) + for status in statuses) + assert [job['statusChanges'] for job in numbers['jobs']] == [['queued', 'running', 'succeeded'], ['running', 'failed']] + assert numbers['estimate']['snapshotCopiesBefore'] == 9 + assert numbers['estimate']['snapshotCopiesAfterLowerBound'] == 5 + + +def test_archive_is_read_in_memory_and_checked_against_its_digest(tmp_path): + archive = tmp_path / 'trace.zip' + with zipfile.ZipFile(archive, 'w') as stream: + stream.writestr('trace/deepseek.jsonl', '\n'.join(json.dumps(record) for record in synthetic())) + digest = hashlib.sha256(archive.read_bytes()).hexdigest() + lines, seen = trace.read_lines(archive, sha256=digest) + assert seen == digest and trace.reconcile(trace.parse(lines)[0])['jobStatusQueries'] == 8 + assert list(tmp_path.iterdir()) == [archive] + with pytest.raises(SystemExit, match='differs'): + trace.read_lines(archive, sha256='0' * 64) + + +def test_check_published_reports_every_number_it_could_not_reproduce(tmp_path, capsys): + file = tmp_path / 'deepseek.jsonl' + file.write_text('\n'.join(json.dumps(record) for record in synthetic()) + '\nnot json\n') + assert trace.main([str(file), '--check-published', '--json']) == 1 + report = json.loads(capsys.readouterr().err)['notReproduced'] + assert report['jobStatusQueries'] == {'expected': 954, 'actual': 8} + assert set(report) == set(trace.PUBLISHED) + assert trace.parse(file.read_text().splitlines())[1] == 1 From d7487bf452ddbcce5331dc3a9ebe7e0fd6b7544f Mon Sep 17 00:00:00 2001 From: Redivesue Date: Sun, 29 Nov 2026 03:40:46 +0800 Subject: [PATCH 07/11] [feat] agent: record what each job and canvas wait observed A tool record's status is the outcome of the call. A job.status window that returns while jobs are still running is a successful call, so it is saved as complete; in the #449 trace 939 complete job queries were for queued or running jobs, and the record alone could not tell a settled wait from a timed-out window. The CLI transport now saves waitOutcome beside a successful job.status or canvas.status record: whether the wait settled, and the job status counts or the item status it saw. status keeps its meaning and nothing in the interface reads the new field yet: how the execution record should show an unsettled wait is decision 1 of the RFC. trace_job_queries.py counts settled and unsettled recorded waits when a trace has the field. ChatTool declares the optional field; there is no user-visible text. --- docs/architecture/agent-runtime.md | 4 +- .../src/opendirector/agent/cli_transport.py | 3 + .../core/src/opendirector/agent/gateway.py | 23 +++++ scripts/trace_job_queries.py | 14 ++- src/backend/chat.ts | 8 ++ tests/test_trace_job_queries.py | 9 ++ tests/test_wait_outcome.py | 99 +++++++++++++++++++ 7 files changed, 158 insertions(+), 2 deletions(-) create mode 100644 tests/test_wait_outcome.py diff --git a/docs/architecture/agent-runtime.md b/docs/architecture/agent-runtime.md index 33d9f3fcb..0aab105f8 100644 --- a/docs/architecture/agent-runtime.md +++ b/docs/architecture/agent-runtime.md @@ -43,7 +43,9 @@ Antigravity 沿用本机 agy 的账号登录,命令行里不传模型凭证。 适配层为每轮创建 `agent-runs//work/`,启动 harness 并注入本轮 CLI 执行入口。子进程 cwd、PWD 和 ACP 工作区始终指向本轮执行目录;会话身份单独持久化。原生工具以此目录为工作目录,通过继承的 PATH 查找 FFmpeg、ffprobe 等程序。 -业务入口使用 Typer CLI。Agent 每轮先运行一次 `opendirector capabilities`,取得全部业务命令及其必填字段,只有某个字段的结构不明确时才用 `opendirector COMMAND --help-field payload` 查看;系统提示和各 runtime 的本轮执行上下文共用同一句发现规则(`CLI_DISCOVERY`),不再提示逐个命令运行 `--help`。人在终端里仍可用 `opendirector --help` 和子命令的 `--help`。查询、编辑及生成命令调用共用业务服务。Agent 通过受令牌保护的本轮连接继承工程范围、编辑会话、执行目录和操作回执;CLI 子进程退出不终止已接受的后台任务。普通终端通过现有 HTTP API 连接服务,写入申请独立编辑会话并遵守工程锁,查询不申请租约。`--session` 可使用已有授权会话。`--operation-id` 提供稳定修改身份,同身份相同输入重放返回原回执,不同输入拒绝。 +业务入口使用 Typer CLI。Agent 每轮先运行一次 `opendirector capabilities`,取得全部业务命令及其必填字段,只有某个字段的结构不明确时才用 `opendirector COMMAND --help-field payload` 查看;系统提示和各 runtime 的本轮执行上下文共用同一句发现规则(`CLI_DISCOVERY`),不再提示逐个命令运行 `--help`。人在终端里仍可用 `opendirector --help` 和子命令的 `--help`。 + +工具记录的 `status` 表示这次调用本身的结果:一个等待窗口在 job 仍未结束时返回,也是 `complete`。`job.status` 和 `canvas.status` 的等待另外记录 `waitOutcome`(`kind`、`settled`,以及各 job 状态的计数或画布项状态),用来区分已结束的等待和超时返回的窗口。执行记录如何展示这一区别尚未确定(见 #449 的决定 1)。查询、编辑及生成命令调用共用业务服务。Agent 通过受令牌保护的本轮连接继承工程范围、编辑会话、执行目录和操作回执;CLI 子进程退出不终止已接受的后台任务。普通终端通过现有 HTTP API 连接服务,写入申请独立编辑会话并遵守工程锁,查询不申请租约。`--session` 可使用已有授权会话。`--operation-id` 提供稳定修改身份,同身份相同输入重放返回原回执,不同输入拒绝。 接受轮次时,服务端校验画布的工程会话,并为本轮签发独立的工程写入租约。运行期间服务端负责续租,画布关闭或断线后仍可执行本轮已授权的写入。运行结束或停止后释放租约。工程路径、对象锁和预期版本仍由共享业务服务校验,重新打开画布后用户可以继续编辑。 diff --git a/packages/core/src/opendirector/agent/cli_transport.py b/packages/core/src/opendirector/agent/cli_transport.py index 9e5e2f003..b0a02abdc 100644 --- a/packages/core/src/opendirector/agent/cli_transport.py +++ b/packages/core/src/opendirector/agent/cli_transport.py @@ -8,6 +8,7 @@ import sys import time +from opendirector.agent.gateway import wait_outcome from opendirector.domain.projects import ProjectError @@ -69,9 +70,11 @@ async def connection(reader, writer): if outcome.error and isinstance(outcome.value, dict) and isinstance(outcome.value.get('code'), str): response['code'] = outcome.value['code'] detail = json.dumps(outcome.value, ensure_ascii=False, indent=2) + observed = None if outcome.error else wait_outcome(name, arguments, outcome.value) await queue.put({**outcome.event(display_name), 'id': 'cli:' + key, 'arguments': arguments, 'result': detail[:65536], 'resultTruncated': len(detail) > 65536, + **({'waitOutcome': observed} if observed else {}), 'timing': {'spawn': spawn, 'work': round(time.monotonic() - received, 3)}}) except (ProjectError, ValueError, KeyError, OSError, TimeoutError) as failure: response = {'error': str(failure)} diff --git a/packages/core/src/opendirector/agent/gateway.py b/packages/core/src/opendirector/agent/gateway.py index 3cb2fd3f7..48df0a628 100644 --- a/packages/core/src/opendirector/agent/gateway.py +++ b/packages/core/src/opendirector/agent/gateway.py @@ -77,6 +77,29 @@ def _command_conflict(call_id: str) -> ToolResult: return ToolResult(value=value, error=COMMAND_CONFLICT_ZH) +def wait_outcome(name, arguments, value): + """What a completed wait actually observed, recorded beside the tool record. + + A wait window is a successful call even when its jobs are still running, so + the record's status alone cannot tell a finished wait from one that timed + out (#449). This records the observed states as data; how the execution + record presents them is left to the interface. + """ + if name != 'query' or not isinstance(arguments, dict) or not isinstance(value, dict): + return None + kind = arguments.get('type') + if kind == 'job.status' and isinstance(value.get('jobs'), list): + statuses = {} + for job in value['jobs']: + status = job.get('status') if isinstance(job, dict) else None + if isinstance(status, str): + statuses[status] = statuses.get(status, 0) + 1 + return {'kind': kind, 'settled': value.get('terminal') is True, 'statuses': statuses} + if kind == 'canvas.status' and isinstance(value.get('status'), str): + return {'kind': kind, 'settled': value['status'] not in {'queued', 'running'}, 'status': value['status']} + return None + + def _read_only(name, arguments) -> bool: """Whether this call may skip the execution lock. diff --git a/scripts/trace_job_queries.py b/scripts/trace_job_queries.py index a32a51f35..1a4540bbe 100644 --- a/scripts/trace_job_queries.py +++ b/scripts/trace_job_queries.py @@ -138,6 +138,8 @@ def reconcile(records): 'jobStatusQueries': len(queries), 'jobStatuses': {str(key): value for key, value in sorted(statuses.items(), key=lambda item: -item[1])}, 'completeWhileUnfinished': sum(value for key, value in statuses.items() if key not in TERMINAL), + # Newer traces record what each wait observed; older ones have no such field. + 'recordedWaits': waits(tools), 'distinctResponses': distinct, 'repeatedResponses': len(queries) - distinct, 'jobStatusResultBytes': result_bytes, @@ -148,6 +150,16 @@ def reconcile(records): } +def waits(tools): + """Complete wait records by whether the wait they report had settled.""" + counted = {'settled': 0, 'unsettled': 0} + for record in tools: + outcome = record.get('waitOutcome') + if record.get('status') == 'complete' and isinstance(outcome, dict): + counted['settled' if outcome.get('settled') is True else 'unsettled'] += 1 + return counted + + def estimate(queries, distinct, delivery_reads): """Server-side snapshot copies for the same waits, as a model. @@ -182,7 +194,7 @@ def main(argv=None): print(json.dumps(numbers, ensure_ascii=False, indent=2)) else: for key in ('records', 'cliAttempts', 'cliFailures', 'jobStatusQueries', 'jobStatuses', - 'completeWhileUnfinished', 'distinctResponses', 'repeatedResponses', + 'completeWhileUnfinished', 'recordedWaits', 'distinctResponses', 'repeatedResponses', 'jobStatusResultBytes', 'deliveryProjectReads', 'completedCliLabels', 'estimate'): print(f'{key}: {numbers[key]}') if options.check_published: diff --git a/src/backend/chat.ts b/src/backend/chat.ts index c75bb3d31..bcc7d1bcf 100644 --- a/src/backend/chat.ts +++ b/src/backend/chat.ts @@ -48,6 +48,14 @@ export interface ChatTool { arguments?: Record; result?: string; resultTruncated?: boolean; + /** What a completed job.status or canvas.status wait observed. `status` stays + * the call's outcome, so a timed-out window is `complete` with `settled: false`. */ + waitOutcome?: { + kind: "job.status" | "canvas.status"; + settled: boolean; + statuses?: Record; + status?: string; + }; } export interface ConversationSummary { id: string; diff --git a/tests/test_trace_job_queries.py b/tests/test_trace_job_queries.py index b10124cb1..18fae5cbc 100644 --- a/tests/test_trace_job_queries.py +++ b/tests/test_trace_job_queries.py @@ -66,6 +66,15 @@ def test_reconciliation_counts_follow_the_published_rules(): assert numbers['estimate']['snapshotCopiesAfterLowerBound'] == 5 +def test_recorded_wait_outcomes_separate_settled_from_timed_out_windows(): + status = {'type': 'job.status'} + records = [dict(tool('complete', arguments=status, result='{}'), waitOutcome={'kind': 'job.status', 'settled': False}), + dict(tool('complete', arguments=status, result='{}'), waitOutcome={'kind': 'job.status', 'settled': True}), + dict(tool('failed', arguments=status), waitOutcome={'kind': 'job.status', 'settled': False})] + assert trace.reconcile(records)['recordedWaits'] == {'settled': 1, 'unsettled': 1} + assert trace.reconcile(synthetic())['recordedWaits'] == {'settled': 0, 'unsettled': 0} + + def test_archive_is_read_in_memory_and_checked_against_its_digest(tmp_path): archive = tmp_path / 'trace.zip' with zipfile.ZipFile(archive, 'w') as stream: diff --git a/tests/test_wait_outcome.py b/tests/test_wait_outcome.py new file mode 100644 index 000000000..7291690a0 --- /dev/null +++ b/tests/test_wait_outcome.py @@ -0,0 +1,99 @@ +"""A completed wait records what it observed, not only that the call succeeded. + +Issue #449 counted 939 complete job queries for jobs that were still queued or +running. The record's status stays the transport outcome; waitOutcome carries +the business states the wait saw, so a timed-out window is distinguishable +from a settled one in the saved record. +""" +import asyncio +import json +import shutil +import tempfile +from pathlib import Path +from types import SimpleNamespace +from uuid import uuid4 + +import pytest + +from capabilities import requires_posix +from opendirector.agent.cli_transport import start_server +from opendirector.agent.gateway import ToolResult, wait_outcome + + +def test_job_wait_outcome_counts_states_and_reports_settlement(): + window = {'jobs': [{'status': 'running'}, {'status': 'queued'}, {'status': 'succeeded'}], 'terminal': False} + assert wait_outcome('query', {'type': 'job.status'}, window) == { + 'kind': 'job.status', 'settled': False, 'statuses': {'running': 1, 'queued': 1, 'succeeded': 1}} + settled = {'jobs': [{'status': 'failed'}, {'status': 'succeeded'}], 'terminal': True} + assert wait_outcome('query', {'type': 'job.status'}, settled)['settled'] is True + assert wait_outcome('query', {'type': 'job.status'}, {'jobs': [], 'terminal': True}) == { + 'kind': 'job.status', 'settled': True, 'statuses': {}} + + +def test_canvas_wait_outcome_and_non_waits(): + assert wait_outcome('query', {'type': 'canvas.status'}, {'status': 'running'}) == { + 'kind': 'canvas.status', 'settled': False, 'status': 'running'} + assert wait_outcome('query', {'type': 'canvas.status'}, {'status': 'idle'})['settled'] is True + for name, arguments, value in (('query', {'type': 'job.get'}, {'status': 'running'}), + ('read_project', {}, {'project': {}}), + ('query', {'type': 'job.status'}, {'error': 'missing'}), + ('query', ['job.status'], {'jobs': []})): + assert wait_outcome(name, arguments, value) is None + + +class _Gateway: + closed = False + + def __init__(self, project_id, result): + self.run = SimpleNamespace(project_id=project_id) + self.result = result + + async def call(self, key, name, arguments): + return self.result + + +def transported(result, arguments): + """Send one CLI request through the real transport and return its two events.""" + # A short directory keeps the socket path inside the AF_UNIX limit. + directory = Path(tempfile.mkdtemp(prefix='od-')) + socket = str(directory / 'cli.sock') + + async def scenario(): + queue = asyncio.Queue() + project = uuid4() + server, _ = await start_server(_Gateway(project, result), queue, socket, set()) + try: + reader, writer = await asyncio.open_unix_connection(socket) + writer.write((json.dumps({'id': '1', 'cliCommand': 'opendirector job wait', 'projectId': str(project), + 'name': 'query', 'arguments': arguments}) + '\n').encode()) + await writer.drain() + response = json.loads(await reader.readline()) + writer.close() + await writer.wait_closed() + return response, await asyncio.wait_for(queue.get(), 5), await asyncio.wait_for(queue.get(), 5) + finally: + server.close() + await server.wait_closed() + try: + return asyncio.run(scenario()) + finally: + shutil.rmtree(directory, ignore_errors=True) + + +@requires_posix() +def test_a_timed_out_wait_window_is_complete_with_an_unsettled_outcome(): + value = {'jobs': [{'id': 'a', 'status': 'running'}], 'terminal': False} + response, running, finished = transported(ToolResult(value=value), {'type': 'job.status', 'waitSeconds': 60}) + assert response['value'] == value + assert 'waitOutcome' not in running + assert finished['status'] == 'complete' + assert finished['waitOutcome'] == {'kind': 'job.status', 'settled': False, 'statuses': {'running': 1}} + + +@requires_posix() +@pytest.mark.parametrize('arguments', [{'type': 'job.status'}, {'type': 'job.get', 'objectId': 'a'}]) +def test_failed_calls_and_other_queries_carry_no_outcome(arguments): + _, _, failed = transported(ToolResult(value={'error': 'gone'}, error='gone'), arguments) + assert failed['status'] == 'failed' and 'waitOutcome' not in failed + _, _, other = transported(ToolResult(value={'status': 'running'}), {'type': 'job.get', 'objectId': 'a'}) + assert 'waitOutcome' not in other From 03896ba0f6499accb6550c501b69684963c1a531 Mon Sep 17 00:00:00 2001 From: Redivesue Date: Sun, 29 Nov 2026 12:05:25 +0800 Subject: [PATCH 08/11] [feat] assistant: show waits that returned before their jobs finished MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The execution record counted every complete call as done. A job.status window that returned while its jobs were still running is a complete call, so the #449 trace showed 939 such queries as finished work. A complete record whose waitOutcome is unsettled now reads "Not finished" (未结束), is left out of the done count, and the summaries add "N returned before jobs finished" (N 次返回时任务未结束). Calls that did not complete keep their status, and records saved before waitOutcome existed read as before. Both strings are added in zh-CN and en-US. This is a proposal for decision 1 of RFC #449; the maintainers may prefer another presentation of the same recorded outcome. Checked with unit tests and, in the browser, both languages on the reply fixture: summaries, per-record labels, no cross-language leak, and no overflow at a 320 px panel width. assistant_wait_outcome.mjs repeats those checks for the gate lane; Playwright is not installed locally, so the script itself has not been run here. --- docs/architecture/agent-runtime.md | 2 +- scripts/check-browser-manifest.mjs | 1 + scripts/run-browser-suite.mjs | 1 + src/canvas/AssistantReply.tsx | 23 +++++----- src/canvas/assistantActivity.ts | 18 ++++++++ src/i18n/messages/en-US/assistant.ts | 2 + src/i18n/messages/zh-CN/assistant.ts | 2 + tests/assistantActivity.test.ts | 17 ++++++- tests/browser/assistant_wait_outcome.mjs | 58 ++++++++++++++++++++++++ tests/browser/manifest.json | 7 +++ 10 files changed, 118 insertions(+), 13 deletions(-) create mode 100644 tests/browser/assistant_wait_outcome.mjs diff --git a/docs/architecture/agent-runtime.md b/docs/architecture/agent-runtime.md index 0aab105f8..e0e8338f3 100644 --- a/docs/architecture/agent-runtime.md +++ b/docs/architecture/agent-runtime.md @@ -45,7 +45,7 @@ Antigravity 沿用本机 agy 的账号登录,命令行里不传模型凭证。 业务入口使用 Typer CLI。Agent 每轮先运行一次 `opendirector capabilities`,取得全部业务命令及其必填字段,只有某个字段的结构不明确时才用 `opendirector COMMAND --help-field payload` 查看;系统提示和各 runtime 的本轮执行上下文共用同一句发现规则(`CLI_DISCOVERY`),不再提示逐个命令运行 `--help`。人在终端里仍可用 `opendirector --help` 和子命令的 `--help`。 -工具记录的 `status` 表示这次调用本身的结果:一个等待窗口在 job 仍未结束时返回,也是 `complete`。`job.status` 和 `canvas.status` 的等待另外记录 `waitOutcome`(`kind`、`settled`,以及各 job 状态的计数或画布项状态),用来区分已结束的等待和超时返回的窗口。执行记录如何展示这一区别尚未确定(见 #449 的决定 1)。查询、编辑及生成命令调用共用业务服务。Agent 通过受令牌保护的本轮连接继承工程范围、编辑会话、执行目录和操作回执;CLI 子进程退出不终止已接受的后台任务。普通终端通过现有 HTTP API 连接服务,写入申请独立编辑会话并遵守工程锁,查询不申请租约。`--session` 可使用已有授权会话。`--operation-id` 提供稳定修改身份,同身份相同输入重放返回原回执,不同输入拒绝。 +工具记录的 `status` 表示这次调用本身的结果:一个等待窗口在 job 仍未结束时返回,也是 `complete`。`job.status` 和 `canvas.status` 的等待另外记录 `waitOutcome`(`kind`、`settled`,以及各 job 状态的计数或画布项状态),用来区分已结束的等待和超时返回的窗口。执行记录把 `complete` 且 `waitOutcome.settled` 为 `false` 的等待显示为"未结束",进度"已完成"不计入它们,并单独显示"N 次返回时任务未结束";没有 `waitOutcome` 的旧记录照常显示。这一展示方式是对 #449 决定 1 的提议,仍以维护者的结论为准。查询、编辑及生成命令调用共用业务服务。Agent 通过受令牌保护的本轮连接继承工程范围、编辑会话、执行目录和操作回执;CLI 子进程退出不终止已接受的后台任务。普通终端通过现有 HTTP API 连接服务,写入申请独立编辑会话并遵守工程锁,查询不申请租约。`--session` 可使用已有授权会话。`--operation-id` 提供稳定修改身份,同身份相同输入重放返回原回执,不同输入拒绝。 接受轮次时,服务端校验画布的工程会话,并为本轮签发独立的工程写入租约。运行期间服务端负责续租,画布关闭或断线后仍可执行本轮已授权的写入。运行结束或停止后释放租约。工程路径、对象锁和预期版本仍由共享业务服务校验,重新打开画布后用户可以继续编辑。 diff --git a/scripts/check-browser-manifest.mjs b/scripts/check-browser-manifest.mjs index 7bf4c35fb..7afd68480 100644 --- a/scripts/check-browser-manifest.mjs +++ b/scripts/check-browser-manifest.mjs @@ -55,6 +55,7 @@ const KNOWN_LANES = new Set(["gate", "extended", ...FIXTURE_LANES, "production", // These scenarios exercise the welcome dialog itself. const welcomeExempt = new Set([ "assistant_activity.mjs", + "assistant_wait_outcome.mjs", "bilingual_defaults.mjs", "first_run.mjs", "model_editor_hosts.mjs", diff --git a/scripts/run-browser-suite.mjs b/scripts/run-browser-suite.mjs index dff0f3fb5..f563f33cb 100644 --- a/scripts/run-browser-suite.mjs +++ b/scripts/run-browser-suite.mjs @@ -22,6 +22,7 @@ const workflows = [ { name: "locale", script: "tests/browser/locale.mjs" }, { name: "creation closure", script: "scripts/verify_creation_browser.mjs" }, { name: "assistant activity", script: "tests/browser/assistant_activity.mjs" }, + { name: "assistant wait outcome", script: "tests/browser/assistant_wait_outcome.mjs" }, { name: "generation reference", script: "tests/browser/canvas_generation_reference.mjs", diff --git a/src/canvas/AssistantReply.tsx b/src/canvas/AssistantReply.tsx index dae6a71f1..9a3508642 100644 --- a/src/canvas/AssistantReply.tsx +++ b/src/canvas/AssistantReply.tsx @@ -6,30 +6,33 @@ import type { Translate } from "../i18n/I18nProvider.tsx"; import type { MessageKey } from "../i18n/types.ts"; import { CanvasIcon } from "./CanvasIcon"; import { AssistantLinkInfo } from "./AssistantLinkInfo"; -import { activityProgress, replySections, toolLabel } from "./assistantActivity.ts"; +import { activityProgress, replySections, toolCounts, toolDisplayStatus, toolLabel } from "./assistantActivity.ts"; +import type { ToolDisplayStatus } from "./assistantActivity.ts"; import { assistantToolText } from "./assistantToolText.ts"; import { assistantCitationFormatter } from "./assistantCitations.ts"; import { defaultTranslate } from "./assistantTranslate.ts"; import { chatTurnTiming } from "./turnTiming.ts"; import { hidePartialSuggestionMarker, parseSuggestedReplies } from "./suggestedReplies.ts"; -const STATUS: Record = { +const STATUS: Record = { running: "assistant.reply.status.running", complete: "assistant.reply.status.complete", + unsettled: "assistant.reply.status.unsettled", failed: "assistant.reply.status.failed", interrupted: "assistant.reply.status.interrupted", }; function ToolActivity({ tool, t }: { tool: ChatTool; t: Translate }) { + const status = toolDisplayStatus(tool); return ( -
+
{toolLabel(tool, t)} - {t(STATUS[tool.status])} + {t(STATUS[status])}
@@ -59,14 +62,11 @@ function ToolGroup({ tools, t }: { tools: ChatTool[]; t: Translate }) { const [open, setOpen] = useState(false); const [hiddenCount, setHiddenCount] = useState(null); const hidden = hiddenCount ?? Math.max(0, tools.length - 50); - const completed = tools.filter((tool) => tool.status === "complete").length; - const failed = tools.filter((tool) => tool.status === "failed"); - const interrupted = tools.filter((tool) => tool.status === "interrupted"); - const running = tools.filter((tool) => tool.status === "running"); + const counts = toolCounts(tools); return (
{ const next = event.currentTarget.open; @@ -77,7 +77,7 @@ function ToolGroup({ tools, t }: { tools: ChatTool[]; t: Translate }) { {t("assistant.reply.tools", { count: tools.length })} - {t("assistant.reply.progress", { done: completed, total: tools.length })}{failed.length > 0 && ` · ${t("assistant.reply.failedCount", { count: failed.length })}`}{interrupted.length > 0 && ` · ${t("assistant.reply.interruptedCount", { count: interrupted.length })}`} + {t("assistant.reply.progress", { done: counts.complete, total: tools.length })}{counts.unsettled > 0 && ` · ${t("assistant.reply.unsettledCount", { count: counts.unsettled })}`}{counts.failed > 0 && ` · ${t("assistant.reply.failedCount", { count: counts.failed })}`}{counts.interrupted > 0 && ` · ${t("assistant.reply.interruptedCount", { count: counts.interrupted })}`} {open &&
@@ -134,6 +134,7 @@ export const AssistantReply = memo(function AssistantReply({ ); const timing = chatTurnTiming(message, t); const sections = useMemo(() => replySections(message), [message]); + const history = toolCounts(message.tools ?? []); const lastPart = sections.reply.at(-1) ?? sections.activity.at(-1); const tail = lastPart?.type === "text" && lastPart.id === "tail" ? lastPart.text : ""; const suggestionBlock = useMemo(() => parseSuggestedReplies(tail), [tail]); @@ -162,7 +163,7 @@ export const AssistantReply = memo(function AssistantReply({ {t("assistant.reply.tools", { count: message.tools?.length ?? 0 })} - {t("assistant.reply.progress", { done: message.tools?.filter((tool) => tool.status === "complete").length ?? 0, total: message.tools?.length ?? 0 })}{message.tools?.some((tool) => tool.status === "failed") && ` · ${t("assistant.reply.failedCount", { count: message.tools.filter((tool) => tool.status === "failed").length })}`} + {t("assistant.reply.progress", { done: history.complete, total: message.tools?.length ?? 0 })}{history.unsettled > 0 && ` · ${t("assistant.reply.unsettledCount", { count: history.unsettled })}`}{history.failed > 0 && ` · ${t("assistant.reply.failedCount", { count: history.failed })}`}
{sections.activity.map(renderPart)}
diff --git a/src/canvas/assistantActivity.ts b/src/canvas/assistantActivity.ts index 393b95a69..45a5ba039 100644 --- a/src/canvas/assistantActivity.ts +++ b/src/canvas/assistantActivity.ts @@ -35,6 +35,24 @@ export function toolLabel( return typeof operation === "string" ? `${name} ${operation}` : name; } +/** How a record reads in the execution history. */ +export type ToolDisplayStatus = ChatTool["status"] | "unsettled"; + +/** + * A job or canvas wait that returned before its jobs finished is a successful + * call, so its status is complete, but it is not finished work. waitOutcome + * records what the wait observed; only those windows read as unsettled. + */ +export function toolDisplayStatus(tool: ChatTool): ToolDisplayStatus { + return tool.status === "complete" && tool.waitOutcome?.settled === false ? "unsettled" : tool.status; +} + +export function toolCounts(tools: readonly ChatTool[]): Record { + const counts: Record = { running: 0, complete: 0, unsettled: 0, failed: 0, interrupted: 0 }; + for (const tool of tools) counts[toolDisplayStatus(tool)] += 1; + return counts; +} + export type ReplyPart = | { type: "text"; id: string; text: string } | { type: "tools"; id: string; tools: ChatTool[] }; diff --git a/src/i18n/messages/en-US/assistant.ts b/src/i18n/messages/en-US/assistant.ts index 3e7bfc22e..54947276f 100644 --- a/src/i18n/messages/en-US/assistant.ts +++ b/src/i18n/messages/en-US/assistant.ts @@ -101,6 +101,7 @@ export const assistant = { "assistant.reply.status.complete": "Complete", "assistant.reply.status.failed": "Failed", "assistant.reply.status.interrupted": "Interrupted", + "assistant.reply.status.unsettled": "Not finished", "assistant.reply.tools": { one: "Activity · {count} call", other: "Activity · {count} calls", @@ -108,6 +109,7 @@ export const assistant = { "assistant.reply.progress": "{done}/{total} complete", "assistant.reply.failedCount": "{count} failed", "assistant.reply.interruptedCount": "{count} interrupted", + "assistant.reply.unsettledCount": "{count} returned before jobs finished", "assistant.reply.showEarlier": { one: "Show {count} earlier call", other: "Show {count} earlier calls", diff --git a/src/i18n/messages/zh-CN/assistant.ts b/src/i18n/messages/zh-CN/assistant.ts index 5363288c0..4790b4645 100644 --- a/src/i18n/messages/zh-CN/assistant.ts +++ b/src/i18n/messages/zh-CN/assistant.ts @@ -100,6 +100,7 @@ export const assistant = { "assistant.reply.status.complete": "已完成", "assistant.reply.status.failed": "失败", "assistant.reply.status.interrupted": "已中断", + "assistant.reply.status.unsettled": "未结束", "assistant.reply.tools": { one: "执行记录 · {count} 次调用", other: "执行记录 · {count} 次调用", @@ -107,6 +108,7 @@ export const assistant = { "assistant.reply.progress": "{done}/{total} 已完成", "assistant.reply.failedCount": "{count} 失败", "assistant.reply.interruptedCount": "{count} 中断", + "assistant.reply.unsettledCount": "{count} 次返回时任务未结束", "assistant.reply.showEarlier": { one: "显示更早的 {count} 次调用", other: "显示更早的 {count} 次调用", diff --git a/tests/assistantActivity.test.ts b/tests/assistantActivity.test.ts index b05a17a63..e0f0f30b1 100644 --- a/tests/assistantActivity.test.ts +++ b/tests/assistantActivity.test.ts @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import test from "node:test"; import type { ChatMessage, ChatTool } from "../src/backend/chat.ts"; -import { activityProgress, replyParts, replySections } from "../src/canvas/assistantActivity.ts"; +import { activityProgress, replyParts, replySections, toolCounts, toolDisplayStatus } from "../src/canvas/assistantActivity.ts"; const tool = (id: string, offset: number, status: ChatTool["status"] = "complete"): ChatTool => ({ id, textOffset: offset, name: "web_fetch", status, @@ -64,3 +64,18 @@ test("folds intermediate narration and calls while keeping final reply outside", assert.equal(done.activity.length, 4); assert.equal(replySections({ ...message([], "直接回复"), status: "complete" }).activity.length, 0); }); + +test("a wait that returned before its jobs finished is not counted as finished work", () => { + const wait = (settled: boolean, status: ChatTool["status"] = "complete"): ChatTool => ({ + ...tool(`wait-${settled}-${status}`, 0, status), name: "query", arguments: { type: "job.status" }, + waitOutcome: { kind: "job.status", settled, statuses: settled ? { succeeded: 1 } : { running: 1 } }, + }); + assert.equal(toolDisplayStatus(wait(false)), "unsettled"); + assert.equal(toolDisplayStatus(wait(true)), "complete"); + // Records saved before waitOutcome existed keep their status. + assert.equal(toolDisplayStatus(tool("old", 0)), "complete"); + // The transport outcome still wins for calls that did not complete. + assert.equal(toolDisplayStatus(wait(false, "failed")), "failed"); + assert.deepEqual(toolCounts([wait(false), wait(false), wait(true), tool("a", 0), tool("b", 0, "interrupted")]), + { running: 0, complete: 2, unsettled: 2, failed: 0, interrupted: 1 }); +}); diff --git a/tests/browser/assistant_wait_outcome.mjs b/tests/browser/assistant_wait_outcome.mjs new file mode 100644 index 000000000..0e5d82176 --- /dev/null +++ b/tests/browser/assistant_wait_outcome.mjs @@ -0,0 +1,58 @@ +/** A wait that returned before its jobs finished is not shown as finished work, in either language. */ +import assert from "node:assert/strict"; +import { launchBrowser } from "./engine.mjs"; + +const base = process.env.CREATION_WEB_URL ?? "http://127.0.0.1:5179"; +const browser = await launchBrowser(); +const page = await browser.newPage({ locale: "en-US", viewport: { width: 900, height: 900 } }); +page.setDefaultTimeout(10000); +const errors = []; +page.on("pageerror", (error) => errors.push(error.message)); +const wait = (id, settled) => ({ + id, name: "opendirector job wait", textOffset: 0, status: "complete", + arguments: { type: "job.status", waitSeconds: 60 }, + waitOutcome: { kind: "job.status", settled, statuses: settled ? { succeeded: 2 } : { running: 2 } }, +}); +const tools = [ + wait("cli:1", false), + wait("cli:2", false), + wait("cli:3", true), + // A record saved before waitOutcome existed keeps reading as complete. + { id: "cli:4", name: "opendirector project show", textOffset: 0, status: "complete" }, +]; +const reply = { id: "reply", role: "assistant", status: "complete", text: "Both images are ready.", tools }; +const expected = { + "en-US": { summary: "2/4 complete · 2 returned before jobs finished", record: "Not finished", done: "Complete" }, + "zh-CN": { summary: "2/4 已完成 · 2 次返回时任务未结束", record: "未结束", done: "已完成" }, +}; +try { + await page.goto(base + "/tests/browser/assistant_activity.html"); + await page.evaluate(async () => { + const { mountReply } = await import("/tests/browser/assistant_activity_fixture.tsx"); + window.replyFixture = mountReply(document.getElementById("activity-test")); + }); + for (const [locale, text] of Object.entries(expected)) { + await page.evaluate(({ value, locale }) => window.replyFixture.render(value, false, locale), { value: reply, locale }); + const history = page.locator(".cw-chat-execution-history"); + await history.locator(":scope > summary small").getByText(text.summary, { exact: true }).waitFor(); + await history.locator(":scope > summary").click(); + const group = history.locator(".cw-chat-tool-group > details"); + await group.locator(":scope > summary small").getByText(text.summary, { exact: true }).waitFor(); + await group.locator(":scope > summary").click(); + const records = group.locator(".cw-chat-tool-group-items > details"); + await page.waitForFunction(() => document.querySelectorAll(".cw-chat-tool-group-items > details").length === 4); + assert.deepEqual(await records.evaluateAll((items) => items.map((item) => item.className)), [ + "cw-chat-activity is-unsettled", "cw-chat-activity is-unsettled", + "cw-chat-activity is-complete", "cw-chat-activity is-complete"]); + assert.deepEqual(await records.locator(":scope > summary small").allInnerTexts(), + [text.record, text.record, text.done, text.done]); + // Neither language leaks into the other. + const other = locale === "en-US" ? expected["zh-CN"] : expected["en-US"]; + assert.equal(await page.getByText(other.record, { exact: true }).count(), 0); + await history.locator(":scope > summary").click(); + } + assert.deepEqual(errors, []); + console.log("assistant wait outcome: unsettled waits shown in en-US and zh-CN"); +} finally { + await browser.close(); +} diff --git a/tests/browser/manifest.json b/tests/browser/manifest.json index 29b719a17..358b5962d 100644 --- a/tests/browser/manifest.json +++ b/tests/browser/manifest.json @@ -70,6 +70,13 @@ ], "note": "Mounts /tests/browser/assistant_activity_fixture.tsx through Vite. vite preview cannot serve that module, so this script is not in the production lane." }, + { + "file": "assistant_wait_outcome.mjs", + "lanes": [ + "gate" + ], + "note": "Mounts /tests/browser/assistant_activity_fixture.tsx through Vite to check unsettled job waits in en-US and zh-CN; not in the production lane for the same reason as assistant_activity.mjs." + }, { "file": "assistant_auxiliary_panels.mjs", "fixture": true, From 2f9eded888d46634a58043ea8e411394b76dbd93 Mon Sep 17 00:00:00 2001 From: Redivesue Date: Fri, 4 Dec 2026 16:52:51 +0800 Subject: [PATCH 09/11] [refactor] agent: share discovery rule, deduplicate snapshot read, and trim inline comments (#449) --- apps/api/src/opendirector_api/agent.py | 4 -- docs/architecture/agent-runtime.md | 2 +- packages/core/src/opendirector/agent/tools.py | 15 ++++--- packages/core/src/opendirector/cli.py | 4 -- .../infrastructure/creation_commit_log.py | 33 ++++----------- scripts/bench_agent_polling.py | 41 +++---------------- scripts/trace_job_queries.py | 3 +- src/backend/chat.ts | 2 - src/canvas/assistantActivity.ts | 6 --- tests/assistantActivity.test.ts | 2 - tests/browser/assistant_wait_outcome.mjs | 3 -- tests/test_assistant_conversations.py | 1 - tests/test_creation_canvas_service.py | 1 - tests/test_creation_storage.py | 2 - tests/test_wait_outcome.py | 2 - 15 files changed, 22 insertions(+), 99 deletions(-) diff --git a/apps/api/src/opendirector_api/agent.py b/apps/api/src/opendirector_api/agent.py index 31fc050eb..37fb0ca47 100644 --- a/apps/api/src/opendirector_api/agent.py +++ b/apps/api/src/opendirector_api/agent.py @@ -762,10 +762,6 @@ async def produce_one(chain: Chain, plan: dict) -> tuple[dict | None, str | None text, status, error = '', 'complete', None activities: list[dict] = [] edited_documents: dict[str, int] = {} - # Where each call ID sits in activities. A turn can carry thousands of - # tool events; a linear search per event made folding them quadratic on - # the event loop. Entries are only appended or replaced in place, so - # positions never move. positions: dict[str, int] = {} sources: dict = {} previous_sources: dict = {} diff --git a/docs/architecture/agent-runtime.md b/docs/architecture/agent-runtime.md index e0e8338f3..add7c4d89 100644 --- a/docs/architecture/agent-runtime.md +++ b/docs/architecture/agent-runtime.md @@ -45,7 +45,7 @@ Antigravity 沿用本机 agy 的账号登录,命令行里不传模型凭证。 业务入口使用 Typer CLI。Agent 每轮先运行一次 `opendirector capabilities`,取得全部业务命令及其必填字段,只有某个字段的结构不明确时才用 `opendirector COMMAND --help-field payload` 查看;系统提示和各 runtime 的本轮执行上下文共用同一句发现规则(`CLI_DISCOVERY`),不再提示逐个命令运行 `--help`。人在终端里仍可用 `opendirector --help` 和子命令的 `--help`。 -工具记录的 `status` 表示这次调用本身的结果:一个等待窗口在 job 仍未结束时返回,也是 `complete`。`job.status` 和 `canvas.status` 的等待另外记录 `waitOutcome`(`kind`、`settled`,以及各 job 状态的计数或画布项状态),用来区分已结束的等待和超时返回的窗口。执行记录把 `complete` 且 `waitOutcome.settled` 为 `false` 的等待显示为"未结束",进度"已完成"不计入它们,并单独显示"N 次返回时任务未结束";没有 `waitOutcome` 的旧记录照常显示。这一展示方式是对 #449 决定 1 的提议,仍以维护者的结论为准。查询、编辑及生成命令调用共用业务服务。Agent 通过受令牌保护的本轮连接继承工程范围、编辑会话、执行目录和操作回执;CLI 子进程退出不终止已接受的后台任务。普通终端通过现有 HTTP API 连接服务,写入申请独立编辑会话并遵守工程锁,查询不申请租约。`--session` 可使用已有授权会话。`--operation-id` 提供稳定修改身份,同身份相同输入重放返回原回执,不同输入拒绝。 +工具记录的 `status` 表示这次调用本身的结果:一个等待窗口在 job 仍未结束时返回,也是 `complete`。`job.status` 和 `canvas.status` 的等待另外记录 `waitOutcome`(`kind`、`settled`,以及各 job 状态的计数或画布项状态),用来区分已结束的等待和超时返回的窗口。执行记录把 `complete` 且 `waitOutcome.settled` 为 `false` 的等待显示为"未结束",进度"已完成"不计入它们,并单独显示"N 次返回时任务未结束";没有 `waitOutcome` 的旧记录照常显示。查询、编辑及生成命令调用共用业务服务。Agent 通过受令牌保护的本轮连接继承工程范围、编辑会话、执行目录和操作回执;CLI 子进程退出不终止已接受的后台任务。普通终端通过现有 HTTP API 连接服务,写入申请独立编辑会话并遵守工程锁,查询不申请租约。`--session` 可使用已有授权会话。`--operation-id` 提供稳定修改身份,同身份相同输入重放返回原回执,不同输入拒绝。 接受轮次时,服务端校验画布的工程会话,并为本轮签发独立的工程写入租约。运行期间服务端负责续租,画布关闭或断线后仍可执行本轮已授权的写入。运行结束或停止后释放租约。工程路径、对象锁和预期版本仍由共享业务服务校验,重新打开画布后用户可以继续编辑。 diff --git a/packages/core/src/opendirector/agent/tools.py b/packages/core/src/opendirector/agent/tools.py index 01c46b8bd..c74520f20 100644 --- a/packages/core/src/opendirector/agent/tools.py +++ b/packages/core/src/opendirector/agent/tools.py @@ -64,10 +64,14 @@ def query_guidance(failure): if name not in EXCLUDED} for command_name, command_model in COMMANDS.items(): assert command_model.__doc__ and command_model.__doc__.strip(), f'Missing command metadata: {command_name}' -SYSTEM = '''You are OpenDirector, a video creation assistant. +CLI_DISCOVERY_RULE = ( + 'Run opendirector capabilities once, and inspect a command with opendirector COMMAND --help-field payload ' + 'only when one field\'s shape is unclear. Do not run --help for each command.' +) +SYSTEM = f'''You are OpenDirector, a video creation assistant. Respond directly when the user's request can be answered without project state or tool execution. When the task needs project capabilities, run the opendirector executable on PATH through the harness's native shell tool. -Run opendirector capabilities once, and inspect a command with opendirector COMMAND --help-field payload only when one field's shape is unclear. Do not run --help for each command. +{CLI_DISCOVERY_RULE} Accepted receipts return ready-to-run next commands with current revisions; use them instead of re-reading the project. Wait for generation with opendirector job wait --all; one call covers every unfinished job, so do not start one wait per job. After performing requested creative work, summarize the delivered result and material limitations. Keep execution IDs, revisions and receipts in tool details unless requested. @@ -90,12 +94,7 @@ def query_guidance(failure): identifiers and code unchanged. If a tool error is shown in another language, explain it in the user's language. ''' -# Every runtime's per-turn context repeats how to discover commands. It must -# say what SYSTEM says: one capabilities call, not --help for each command, -# or the turn opens with a probe per command group. -CLI_DISCOVERY = ('Run opendirector capabilities once to discover OpenDirector commands and their required fields; ' - 'inspect one field with opendirector COMMAND --help-field payload only when its shape is unclear. ' - 'Use opendirector for project changes.\n') +CLI_DISCOVERY = f'{CLI_DISCOVERY_RULE} Use opendirector for project changes.\n' SUGGESTED_REPLIES = ( 'When there are useful next steps, finish the reply with 3 to 5 distinct suggestions the user ' 'could send verbatim. Use single-line plain-text phrases in the language of the user, ' diff --git a/packages/core/src/opendirector/cli.py b/packages/core/src/opendirector/cli.py index e82c1f6ee..d2a6374fd 100644 --- a/packages/core/src/opendirector/cli.py +++ b/packages/core/src/opendirector/cli.py @@ -708,10 +708,6 @@ def query(self, kind, **arguments): self.request("POST", self.path("/queries"), json={"type": kind, "queryId": str(uuid4()), "projectId": str(self.project), **arguments})) if kind == "job.get" and result.get("status") == "succeeded" and result.get("asset"): - # job wait reports delivery from job.status; job show uses the same - # server-side answer. Reading the whole project here sent every - # record and the model catalog, and in agent mode queued behind the - # turn's writes, just to find the canvas items showing one asset. views = self.query("job.status", objectIds=[result["id"]], waitSeconds=0)["jobs"] delivery = views[0].get("delivery") if views else None if delivery is not None: diff --git a/packages/core/src/opendirector/infrastructure/creation_commit_log.py b/packages/core/src/opendirector/infrastructure/creation_commit_log.py index b45644fb0..3bca2c3ca 100644 --- a/packages/core/src/opendirector/infrastructure/creation_commit_log.py +++ b/packages/core/src/opendirector/infrastructure/creation_commit_log.py @@ -382,36 +382,13 @@ def _current(self, db, project_id, path, manifest): """ return self._current_record(db, project_id, path, manifest)[0] - def snapshot(self, project_id): - path, manifest = self._published_manifest(project_id) - while True: - try: - record, _ = self._current_record(None, project_id, path, manifest) - return record.snapshot.model_copy(deep=True) - except (OSError, ProjectError): - current = self._published_manifest(project_id) - if current == (path, manifest): - raise - path, manifest = current - - def snapshot_if_changed(self, project_id, known_head): - """The head commit and its snapshot, copied only when the head moved. - - A wait polls the same project every half second, and deep-copying the - whole snapshot on every tick cost CPU and the GIL while nothing had - changed. This follows snapshot() step for step (published manifest, - head validation, retry after a concurrent rename), so locking, journal - recovery and a corrupt head are handled exactly as there, and the head - and snapshot it returns always come from the same record. A commit - always publishes a new head, so an unchanged head means an unchanged - snapshot. - """ + def _read_snapshot(self, project_id, known_head=None): path, manifest = self._published_manifest(project_id) while True: try: record, _ = self._current_record(None, project_id, path, manifest) head = record.command.commandId - if head == known_head: + if known_head is not None and head == known_head: return head, None return head, record.snapshot.model_copy(deep=True) except (OSError, ProjectError): @@ -420,6 +397,12 @@ def snapshot_if_changed(self, project_id, known_head): raise path, manifest = current + def snapshot(self, project_id): + return self._read_snapshot(project_id)[1] + + def snapshot_if_changed(self, project_id, known_head): + return self._read_snapshot(project_id, known_head) + def head(self, project_id): """The current head commit, cheap enough to gate content-addressed caches. diff --git a/scripts/bench_agent_polling.py b/scripts/bench_agent_polling.py index d6f27e9ae..457729d58 100644 --- a/scripts/bench_agent_polling.py +++ b/scripts/bench_agent_polling.py @@ -65,7 +65,6 @@ def _source_argument(): return HERE -# The measured tree must be importable before anything from opendirector is. SOURCE = _source_argument() sys.path[:0] = [str(SOURCE / "packages/core/src"), str(SOURCE / "apps/api/src")] @@ -91,8 +90,6 @@ def command(kind, project_id, payload, versions=()): "payload": payload, "expectedVersions": list(versions)}) -# -------------------------------------------------------------------------- -# Original summary (#455). Kept as it was so its numbers stay comparable. def seed_jobs(projects, project_id, session, count): snapshot = projects.snapshot(project_id) @@ -203,8 +200,6 @@ def run_summary(options): print(json.dumps(result, ensure_ascii=False, indent=2) if not options.json else json.dumps(result, ensure_ascii=False)) -# -------------------------------------------------------------------------- -# Fixtures shared by both revisions. CENTER = {"nodes": 200, "commits": 600, "jobs": 14, "finished": 0, "projects": 1, "verifyBytes": False} MATRIX = [dict(CENTER)] + [dict(CENTER, **change) for change in ( @@ -345,15 +340,13 @@ def working_copy(fixture_dir): shutil.rmtree(root, ignore_errors=True) -# -------------------------------------------------------------------------- -# Instrumentation. Wrappers sit on instances, so the measured code is unchanged. class Probe: def __init__(self, projects, canvas=None): self.projects = projects - # Threads that stand in for other actors (writers) are not the wait's cost. self.excluded = set() self.reset() + gc.callbacks[:] = [cb for cb in gc.callbacks if getattr(cb, "__self__", None).__class__ is not Probe] gc.callbacks.append(self._gc) self.originals = {} for name in ("snapshot", "head", "snapshot_if_changed"): @@ -384,8 +377,6 @@ def reset(self): self.gc = [] def _gc(self, phase, info): - # Full collections over large cached snapshots can pause any read for a - # second; they are reported so an outlier can be attributed, not hidden. if info.get("generation") != 2: return if phase == "start": @@ -404,7 +395,6 @@ def wrapper(*args, **kwargs): finally: if threading.get_ident() not in self.excluded: self.calls[name].append(time.perf_counter() - start) - # A gated read copies the snapshot only when the head moved. if name == "snapshot_if_changed" and isinstance(value, tuple) and value[1] is not None: self.copies += 1 return wrapper @@ -426,7 +416,6 @@ def ms(values): def open_store(root, verify_bytes): projects = CreationProjects(LocalProjects(root)) if verify_bytes: - # Simulates the Windows default; this is not a Windows measurement. projects._verify_record_bytes = True return projects @@ -498,8 +487,6 @@ def write(self, record): print(line) -# -------------------------------------------------------------------------- -# wait: S1-S5. def window(projects, canvas, probe, project_id, ids, seconds): probe.reset() @@ -545,7 +532,6 @@ def run_wait(options, out): center = options.matrix is False or config == CENTER parts = set(options.parts.split(",")) with working_copy(directory) as root: - # S1 cold: a new process per sample. for sample in range(options.cold if "idle" in parts else 0): child = subprocess.run([sys.executable, __file__, "--source", str(SOURCE), "--scenario", "_wait-cold", "--work-dir", str(root), "--child-meta", json.dumps(meta), "--window", str(options.window)] @@ -559,12 +545,11 @@ def run_wait(options, out): projects = open_store(root, config["verifyBytes"]) canvas = CreationCanvas(projects) probe = Probe(projects, canvas) - window(projects, canvas, probe, meta["projectId"], meta["waiting"], 0) # warm-up, discarded + window(projects, canvas, probe, meta["projectId"], meta["waiting"], 0) for sample in range(options.warm if "idle" in parts else 0): _, metrics = window(projects, canvas, probe, meta["projectId"], meta["waiting"], options.window) out.write({"scenario": "wait.idle", "phase": "warm", "config": label, "sample": sample, "windowSeconds": options.window, **metrics}) - # S5: already settled, answered at once. for sample in range(options.warm * 3 if "settled" in parts else 0): _, metrics = window(projects, canvas, probe, meta["projectId"], [meta["probe"]], 0) out.write({"scenario": "wait.settled", "phase": "warm", "config": label, "sample": sample, **metrics}) @@ -684,8 +669,6 @@ def writer(): **({"error": error[-2000:]} if committed is None else {}), **metrics, **check(state, job_id, status)}) -# -------------------------------------------------------------------------- -# contention: S6, other catalog-lock users while several waits run. def run_contention(options, out): """Latency of lease renewal, browser heartbeat, change polling, a save and a @@ -730,7 +713,6 @@ def changes(): "browserSnapshot": lambda: probe.originals["snapshot"](project_id), } if not options.contention_saves: - # Without saves the head stays put, as while a user only watches. operations.pop("save") for waiters in options.contention_waiters: for sample in range(options.contention_samples): @@ -755,7 +737,6 @@ def operate(): async def waits(): if not waiters: - # Control: the same operations with no wait running. return await asyncio.sleep(options.window) return await asyncio.gather(*(canvas.wait_jobs( project_id, tuple(UUID(i) for i in meta["waiting"]), options.window, "all") @@ -785,8 +766,6 @@ async def waits(): projects.local.release(session) -# -------------------------------------------------------------------------- -# show: job show for a succeeded job. def canonical(value): return hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False).encode()).hexdigest() @@ -809,7 +788,6 @@ def run_show(options, out): with working_copy(directory) as root: projects = CreationProjects(LocalProjects(root)) probe = Probe(projects) - # Agent mode: the real gateway and business tools; only the socket is replaced. business = AgentTools(projects, None, ModelConfigs(root)) gateway = ToolGateway(business, RunContext(runtime="codex", project_id=project_id, turn_id=uuid4(), session=str(uuid4()), directory=root, config=None, messages=[], selected_skills=[])) @@ -837,7 +815,7 @@ def agent_show(lock_seconds=0.0): value = client.query("job.get", objectId=meta["succeeded"]) return value, (time.perf_counter() - start) * 1000 - agent_show() # warm-up + agent_show() for phase, lock in (("warm", 0.0), ("writeLockHeld", options.lock_seconds)): for sample in range(options.show_samples if not lock else max(3, options.show_samples // 5)): value, elapsed = agent_show(lock) @@ -851,7 +829,6 @@ def agent_show(lock_seconds=0.0): del os.environ["OPENDIRECTOR_AGENT_SOCKET"] loop.close() - # HTTP mode: the real ASGI application in process. requests = [] def record(response): @@ -864,7 +841,7 @@ def record(response): client.http.close() http.headers.update(client.http.headers) client.http = http - client.query("job.get", objectId=meta["succeeded"]) # warm-up + client.query("job.get", objectId=meta["succeeded"]) for sample in range(options.show_samples): requests.clear() start = time.perf_counter() @@ -877,8 +854,6 @@ def record(response): "deliveryDigest": canonical(value.get("delivery"))}) -# -------------------------------------------------------------------------- -# events: one turn with many tool events. def run_events(options, out): from fastapi.testclient import TestClient @@ -929,7 +904,7 @@ async def no_skills(*args): frames = [json.loads(line[6:]) for line in response.text.splitlines() if line.startswith("data: ")] saved = frames[-1]["conversation"]["messages"][-1] if sample == 0: - continue # warm-up + continue out.write({"scenario": "events.turn", "phase": "warm", "config": {"toolCalls": calls, "events": calls * 2 + calls // 10 + 1}, "sample": sample - 1, "wallMs": round(elapsed, 3), @@ -939,8 +914,6 @@ async def no_skills(*args): shutil.rmtree(root, ignore_errors=True) -# -------------------------------------------------------------------------- -# Summary of one or two JSONL files. def percentile(values, fraction): ordered = sorted(values) @@ -1006,7 +979,6 @@ def main(): parser.add_argument("--out", help="Append JSON lines here; stdout when omitted.") parser.add_argument("--fixture-dir", default=str(Path(tempfile.gettempdir()) / "opendirector-bench-fixtures")) parser.add_argument("--summarize", nargs="+", metavar="JSONL") - # summary (original) and single-config wait. parser.add_argument("--jobs", type=int, default=None) parser.add_argument("--ticks", type=int, default=60) parser.add_argument("--nodes", type=int, default=None) @@ -1015,7 +987,6 @@ def main(): parser.add_argument("--projects", type=int, default=None) parser.add_argument("--verify-bytes", action="store_true", help="Simulate the Windows head-file hash.") parser.add_argument("--json", action="store_true") - # wait. parser.add_argument("--matrix", action="store_true", help="Center configuration plus one change per dimension.") parser.add_argument("--parts", default="idle,settled,busy,visibility", help="Comma-separated wait cases to run: idle, settled, busy, visibility.") @@ -1027,7 +998,6 @@ def main(): parser.add_argument("--visibility", type=int, default=15) parser.add_argument("--cross-process", type=int, default=6) parser.add_argument("--seed", type=int, default=449) - # show and events. parser.add_argument("--show-nodes", type=int, nargs="+", default=[50, 200, 1000]) parser.add_argument("--show-samples", type=int, default=30) parser.add_argument("--lock-seconds", type=float, default=2.0) @@ -1040,7 +1010,6 @@ def main(): help="Include a save in every operation cycle (the head then moves almost every tick).") parser.add_argument("--contention-burner", action="store_true", help="Control for CPU frequency: keep another process busy during each window.") - # internal children. parser.add_argument("--work-dir") parser.add_argument("--child-meta") parser.add_argument("--project") diff --git a/scripts/trace_job_queries.py b/scripts/trace_job_queries.py index 1a4540bbe..a4f6bbb26 100644 --- a/scripts/trace_job_queries.py +++ b/scripts/trace_job_queries.py @@ -126,7 +126,7 @@ def reconcile(records): labels[kind] = labels.get(kind, 0) + 1 jobs = [] for job_id, results in groups.items(): - sequence = [json.loads(result).get('status') if result else None for result in results] + sequence = [result_status({'result': result}) for result in results] changes = [status for index, status in enumerate(sequence) if index == 0 or status != sequence[index - 1]] jobs.append({'jobId': job_id, 'queries': len(results), 'distinctResponses': len(set(results)), 'statusChanges': changes, 'terminal': bool(sequence and sequence[-1] in TERMINAL)}) @@ -138,7 +138,6 @@ def reconcile(records): 'jobStatusQueries': len(queries), 'jobStatuses': {str(key): value for key, value in sorted(statuses.items(), key=lambda item: -item[1])}, 'completeWhileUnfinished': sum(value for key, value in statuses.items() if key not in TERMINAL), - # Newer traces record what each wait observed; older ones have no such field. 'recordedWaits': waits(tools), 'distinctResponses': distinct, 'repeatedResponses': len(queries) - distinct, diff --git a/src/backend/chat.ts b/src/backend/chat.ts index bcc7d1bcf..0223ea3e1 100644 --- a/src/backend/chat.ts +++ b/src/backend/chat.ts @@ -48,8 +48,6 @@ export interface ChatTool { arguments?: Record; result?: string; resultTruncated?: boolean; - /** What a completed job.status or canvas.status wait observed. `status` stays - * the call's outcome, so a timed-out window is `complete` with `settled: false`. */ waitOutcome?: { kind: "job.status" | "canvas.status"; settled: boolean; diff --git a/src/canvas/assistantActivity.ts b/src/canvas/assistantActivity.ts index 45a5ba039..ef1b5af00 100644 --- a/src/canvas/assistantActivity.ts +++ b/src/canvas/assistantActivity.ts @@ -35,14 +35,8 @@ export function toolLabel( return typeof operation === "string" ? `${name} ${operation}` : name; } -/** How a record reads in the execution history. */ export type ToolDisplayStatus = ChatTool["status"] | "unsettled"; -/** - * A job or canvas wait that returned before its jobs finished is a successful - * call, so its status is complete, but it is not finished work. waitOutcome - * records what the wait observed; only those windows read as unsettled. - */ export function toolDisplayStatus(tool: ChatTool): ToolDisplayStatus { return tool.status === "complete" && tool.waitOutcome?.settled === false ? "unsettled" : tool.status; } diff --git a/tests/assistantActivity.test.ts b/tests/assistantActivity.test.ts index e0f0f30b1..b5eb8fb60 100644 --- a/tests/assistantActivity.test.ts +++ b/tests/assistantActivity.test.ts @@ -72,9 +72,7 @@ test("a wait that returned before its jobs finished is not counted as finished w }); assert.equal(toolDisplayStatus(wait(false)), "unsettled"); assert.equal(toolDisplayStatus(wait(true)), "complete"); - // Records saved before waitOutcome existed keep their status. assert.equal(toolDisplayStatus(tool("old", 0)), "complete"); - // The transport outcome still wins for calls that did not complete. assert.equal(toolDisplayStatus(wait(false, "failed")), "failed"); assert.deepEqual(toolCounts([wait(false), wait(false), wait(true), tool("a", 0), tool("b", 0, "interrupted")]), { running: 0, complete: 2, unsettled: 2, failed: 0, interrupted: 1 }); diff --git a/tests/browser/assistant_wait_outcome.mjs b/tests/browser/assistant_wait_outcome.mjs index 0e5d82176..4af0aee6a 100644 --- a/tests/browser/assistant_wait_outcome.mjs +++ b/tests/browser/assistant_wait_outcome.mjs @@ -1,4 +1,3 @@ -/** A wait that returned before its jobs finished is not shown as finished work, in either language. */ import assert from "node:assert/strict"; import { launchBrowser } from "./engine.mjs"; @@ -17,7 +16,6 @@ const tools = [ wait("cli:1", false), wait("cli:2", false), wait("cli:3", true), - // A record saved before waitOutcome existed keeps reading as complete. { id: "cli:4", name: "opendirector project show", textOffset: 0, status: "complete" }, ]; const reply = { id: "reply", role: "assistant", status: "complete", text: "Both images are ready.", tools }; @@ -46,7 +44,6 @@ try { "cw-chat-activity is-complete", "cw-chat-activity is-complete"]); assert.deepEqual(await records.locator(":scope > summary small").allInnerTexts(), [text.record, text.record, text.done, text.done]); - // Neither language leaks into the other. const other = locale === "en-US" ? expected["zh-CN"] : expected["en-US"]; assert.equal(await page.getByText(other.record, { exact: true }).count(), 0); await history.locator(":scope > summary").click(); diff --git a/tests/test_assistant_conversations.py b/tests/test_assistant_conversations.py index e69d91512..5afd2e491 100644 --- a/tests/test_assistant_conversations.py +++ b/tests/test_assistant_conversations.py @@ -989,7 +989,6 @@ def test_tool_records_keep_order_status_and_first_offset_across_many_events(assi if index % 2: events.append({'type': 'delta', 'text': f'{index} '}) if index >= 1: - # Interleave: finish the previous call after the next one started. events.append({'type': 'tool', 'id': f'cli:{index - 1}', 'name': 'opendirector job wait', 'status': 'failed' if index % 7 == 0 else 'complete', 'result': str(index)}) events.append({'type': 'tool', 'id': f'cli:{calls - 1}', 'name': 'opendirector job wait', 'status': 'complete'}) diff --git a/tests/test_creation_canvas_service.py b/tests/test_creation_canvas_service.py index 575992b46..350c20ea0 100644 --- a/tests/test_creation_canvas_service.py +++ b/tests/test_creation_canvas_service.py @@ -817,7 +817,6 @@ def test_wait_copies_the_snapshot_once_while_nothing_is_committed(project, monke reads = gated_reads(store, monkeypatch) result = asyncio.run(canvas.wait_jobs(pid, tuple(job.id for job in jobs), 1.2, 'all')) assert reads['calls'] >= 3 and reads['copies'] == 1 - # Every tick locks exactly as a full snapshot() read does. assert set(reads['locksPerRead']) == {reads['locksOfSnapshot']} assert result['terminal'] is False assert result == canvas.job_states(pid, tuple(job.id for job in jobs)) diff --git a/tests/test_creation_storage.py b/tests/test_creation_storage.py index e292cdd11..216b7d8af 100644 --- a/tests/test_creation_storage.py +++ b/tests/test_creation_storage.py @@ -1371,7 +1371,6 @@ def test_snapshot_if_changed_copies_only_when_the_head_moves(projects, monkeypat full = len(entered) entered.clear() assert projects.snapshot_if_changed(created.projectId, head) == (head, None) - # It locks exactly as snapshot() does, whether or not it copies. assert len(entered) == full renamed = rename(created) projects.execute(renamed) @@ -1383,7 +1382,6 @@ def test_snapshot_if_changed_copies_only_when_the_head_moves(projects, monkeypat assert len(entered) == full assert moved == renamed.commandId and second == projects.snapshot(created.projectId) assert second.project.name == 'Renamed' - # The copy is the caller's own, like snapshot(). assert second is not projects.snapshot_if_changed(created.projectId, None)[1] diff --git a/tests/test_wait_outcome.py b/tests/test_wait_outcome.py index 7291690a0..f886c30f6 100644 --- a/tests/test_wait_outcome.py +++ b/tests/test_wait_outcome.py @@ -53,8 +53,6 @@ async def call(self, key, name, arguments): def transported(result, arguments): - """Send one CLI request through the real transport and return its two events.""" - # A short directory keeps the socket path inside the AF_UNIX limit. directory = Path(tempfile.mkdtemp(prefix='od-')) socket = str(directory / 'cli.sock') From 42815adb256401d6123540e4b881b6c309742b74 Mon Sep 17 00:00:00 2001 From: Redivesue Date: Fri, 4 Dec 2026 17:21:45 +0800 Subject: [PATCH 10/11] [test] assistant: verify waitOutcome SSE streaming and persistence; drop unused import (#449) --- scripts/bench_agent_polling.py | 1 - tests/test_assistant_conversations.py | 29 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/scripts/bench_agent_polling.py b/scripts/bench_agent_polling.py index 457729d58..8f144026c 100644 --- a/scripts/bench_agent_polling.py +++ b/scripts/bench_agent_polling.py @@ -43,7 +43,6 @@ import platform import random import shutil -import statistics import subprocess import sys import tempfile diff --git a/tests/test_assistant_conversations.py b/tests/test_assistant_conversations.py index 5afd2e491..b177ed34f 100644 --- a/tests/test_assistant_conversations.py +++ b/tests/test_assistant_conversations.py @@ -1003,3 +1003,32 @@ async def stream(self, run): assert saved['tools'] == previous_fold(events) assert [item['id'] for item in saved['tools']] == [f'cli:{index}' for index in range(calls)] assert all('timing' not in item for item in saved['tools']) + + +def test_wait_outcome_streams_over_sse_and_persists_across_conversation_reload(assistant, monkeypatch): + client, path, _ = assistant + unsettled = {'kind': 'job.status', 'settled': False, 'statuses': {'running': 2}} + settled = {'kind': 'job.status', 'settled': True, 'statuses': {'succeeded': 2}} + events = [ + {'type': 'tool', 'id': 'cli:1', 'name': 'opendirector job wait', 'status': 'running', + 'arguments': {'type': 'job.status', 'waitSeconds': 60}}, + {'type': 'tool', 'id': 'cli:1', 'name': 'opendirector job wait', 'status': 'complete', + 'arguments': {'type': 'job.status', 'waitSeconds': 60}, 'waitOutcome': unsettled}, + {'type': 'tool', 'id': 'cli:2', 'name': 'opendirector job wait', 'status': 'complete', + 'arguments': {'type': 'job.status', 'waitSeconds': 60}, 'waitOutcome': settled}, + {'type': 'delta', 'text': 'Done.'}, + ] + + async def stream(self, run): + for event in events: + yield event + + monkeypatch.setattr(agent.AgentRuntimes, 'stream', stream) + cid = client.get(path).json()['conversationId'] + streamed = frames(send(client, path, cid, 'Check jobs')) + tool_frames = [frame for frame in streamed if frame.get('type') == 'tool' and frame.get('waitOutcome')] + assert [frame['waitOutcome'] for frame in tool_frames] == [unsettled, settled] + + reloaded = client.get(path).json()['messages'][-1] + assert [tool['status'] for tool in reloaded['tools']] == ['complete', 'complete'] + assert [tool.get('waitOutcome') for tool in reloaded['tools']] == [unsettled, settled] From 74ceb5a90f50189d76af38f63a3c5935c6b50453 Mon Sep 17 00:00:00 2001 From: Redivesue Date: Fri, 4 Dec 2026 18:58:01 +0800 Subject: [PATCH 11/11] [test] browser: close nested tool group and wait for visible status in assistant_wait_outcome (#449) --- tests/browser/assistant_wait_outcome.mjs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/browser/assistant_wait_outcome.mjs b/tests/browser/assistant_wait_outcome.mjs index 4af0aee6a..8fdb865cb 100644 --- a/tests/browser/assistant_wait_outcome.mjs +++ b/tests/browser/assistant_wait_outcome.mjs @@ -38,7 +38,8 @@ try { await group.locator(":scope > summary small").getByText(text.summary, { exact: true }).waitFor(); await group.locator(":scope > summary").click(); const records = group.locator(".cw-chat-tool-group-items > details"); - await page.waitForFunction(() => document.querySelectorAll(".cw-chat-tool-group-items > details").length === 4); + await records.first().locator(":scope > summary small").getByText(text.record, { exact: true }).waitFor(); + assert.equal(await records.count(), 4); assert.deepEqual(await records.evaluateAll((items) => items.map((item) => item.className)), [ "cw-chat-activity is-unsettled", "cw-chat-activity is-unsettled", "cw-chat-activity is-complete", "cw-chat-activity is-complete"]); @@ -46,6 +47,7 @@ try { [text.record, text.record, text.done, text.done]); const other = locale === "en-US" ? expected["zh-CN"] : expected["en-US"]; assert.equal(await page.getByText(other.record, { exact: true }).count(), 0); + await group.locator(":scope > summary").click(); await history.locator(":scope > summary").click(); } assert.deepEqual(errors, []);