diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7e3e8358..51995176 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,7 +16,7 @@ jobs: test: runs-on: ubuntu-latest # Allow the full suite and the Python 3.12 DOM checks to finish on hosted runners. - timeout-minutes: 45 + timeout-minutes: 55 strategy: fail-fast: false matrix: @@ -347,6 +347,11 @@ jobs: } assert totals == {"tests": 5, "skipped": 0, "failures": 0, "errors": 0}, totals PY + - name: Exercise candidate spelling on macOS + run: >- + uv run pytest -q -p no:cacheprovider + tests/workflows/test_candidate_case_spelling.py + tests/workflows/test_candidate_source_casepaths.py arcbench-checkers: name: ARC-Bench browser and SQLite fixtures diff --git a/configs/README.md b/configs/README.md index 4ae33415..ba822d87 100644 --- a/configs/README.md +++ b/configs/README.md @@ -158,6 +158,8 @@ For native Claude 4 models that support sampling, an explicit `top_p` takes precedence over `temperature`, following the [Anthropic sampling requirements](https://github.com/anthropics/skills/blob/main/skills/claude-api/shared/model-migration.md#sampling-parameters---temperature--top_p--top_k). With `top_p` unset, ordinary requests retain the configured temperature. +Use `OpenCollab(config={"top_p": None})` to select provider-default sampling +for one SDK client when the environment or env file sets a global value. ## Thinking diff --git a/docs/duo.md b/docs/duo.md index 2e24f442..c22d053a 100644 --- a/docs/duo.md +++ b/docs/duo.md @@ -255,6 +255,10 @@ caller's runtime configuration. Duo's output records `winner` and `adopted` separately, because a failed adoption may fall back to the other candidate. `status` is `done` after successful adoption, `incomplete` when no candidate is adopted, or `error` when the task is missing. +When the shared budget prevents B from starting, Duo can adopt A if it has a +deliverable diff, completed cleanup and a current passing test without a current +failure. The result records `candidate-b-budget-exhausted` and marks B as skipped. +Without an eligible A, the workflow returns the budget stop. The output also retains selection reasons, candidate evidence, adoption attempts and token consumption. Duo addresses candidate selection through behavior evidence and the default-B preference. Task correctness is established by the caller's actual diff --git a/docs/duo/README.zh-CN.md b/docs/duo/README.zh-CN.md index d40b5f9c..6e46aa64 100644 --- a/docs/duo/README.zh-CN.md +++ b/docs/duo/README.zh-CN.md @@ -105,4 +105,6 @@ Git 候选从源目录当前受跟踪文件和未被忽略的未跟踪文件开 结果分别记录 `winner` 与 `adopted`,采用失败时可能回退另一候选。成功采用后 `status` 为 `done`,没有候选被采用时为 `incomplete`,缺少任务时为 `error`。结果同时保留选择理由、证据、采用尝试和 token 消耗。Duo 根据行为证据和默认偏好 B 的规则选择候选,任务正确性由调用方的实际检查及适用时评测器的正式评分确定。 +共享预算耗尽而 B 无法启动时,若 A 有可交付改动、清理已完成,且当前测试记录至少有一项通过、没有失败,Duo 可以采用 A。结果会记录 `candidate-b-budget-exhausted`,并将 B 标为跳过。A 的改动或证据未达到这些条件时,工作流返回预算耗尽。 + OpenCollab-Eval 负责题面、环境准备、隐藏测试隔离、候选捕获和正式评分,运行方式见[评测快速开始](https://github.com/RISE-X-Lab/OpenCollab-Eval#duo-quick-start)。 diff --git a/docs/reconstruct.md b/docs/reconstruct.md index 628c64c7..bd798e11 100644 --- a/docs/reconstruct.md +++ b/docs/reconstruct.md @@ -68,8 +68,51 @@ task = ReconstructionTask( ) ``` -`evaluate` should run the candidate where the agent's own code runs (for -example inside the agent's Docker container), never in the harness process. +`evaluate` receives a temporary copy of the archived candidate, with the same +filename and permissions. The staging directory preserves the candidate's +package layout and links to accessible sibling files, such as +`candidate.json`, and packages. Staging uses the workspace root when writable, +then the candidate's parent, then the archive directory. +Run the copy in the agent's execution environment, never in the harness process. +The staging directory is removed when the evaluation ends. + +For a Python package, use the module's configured name and start the +subprocess in the staged Python import root. The callback path can be under +any of the staging locations above. A temporary directory name can include +a dot. Module execution may use an alias path to the same staged file. +Standalone files use the ordinary staging directory when the filesystem +cannot create the alias. The final path components match +`candidate_file` relative to the Python import root. This example assumes a +local agent environment and a module that takes a JSON input list and prints +a JSON output list. + +```python +import asyncio +import json +import sys +from pathlib import Path + +candidate_file = "src/catalog/pricing/offer.py" +module_path = Path(candidate_file).relative_to("src") +module_name = ".".join(module_path.with_suffix("").parts) + +async def run_candidate(program_path, inputs): + import_root = program_path.parents[len(module_path.parts) - 1] + process = await asyncio.create_subprocess_exec( + sys.executable, "-m", module_name, json.dumps(inputs), + cwd=import_root, + stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, + ) + stdout, stderr = await process.communicate() + if process.returncode: + return [{"ok": False, "error": stderr.decode().strip()} for _ in inputs] + return [{"ok": True, "output": value} for value in json.loads(stdout)] +``` + +Set `module_path = Path(candidate_file)` when the workspace root is the project's +Python import root. The subprocess imports the staged file under its usual +package name, so relative and absolute imports share the same package. + `kind` is one of `list`, `two_lists`, `int`, `pair`, `string`, `points` or `other`; `other` disables the coverage gate and the domain check. diff --git a/docs/weave.md b/docs/weave.md index 971da08c..3742ee88 100644 --- a/docs/weave.md +++ b/docs/weave.md @@ -204,6 +204,11 @@ An adapter's `save_state(data)` hook receives independent JSON snapshots for storage. Supply a saved snapshot as the JSON `state` input or through `WeaveState(saved_snapshot)` with `run_weave`. Reuse the saved `run_id` when calling the SDK or pass it as `workflow run weave --run-id RUN_ID` through -the CLI. Generated groups continue at their checks, checked groups -retain their generation results, and consumed repair rounds remain counted. -The saved group fields must agree with the supplied groups. +the CLI. Generated groups and completed repair sessions continue at +verification. A repair round stays pending when a verification command is +skipped or times out. The report records both execution and timeout for a +command that starts and exceeds its deadline. The next invocation uses the +pre-repair check to measure progress. +Checked groups retain their generation results, and started repair rounds +still count toward the limit. The saved group fields must agree with the +supplied groups. diff --git a/opencollab/adapters/_candidate_adoption.py b/opencollab/adapters/_candidate_adoption.py index a02287cc..c673668d 100644 --- a/opencollab/adapters/_candidate_adoption.py +++ b/opencollab/adapters/_candidate_adoption.py @@ -537,6 +537,8 @@ async def _adoption_transaction( environment: Any, workspace: str, paths: Sequence[str], *, repository: bool, replay: Callable[[str, str | None, str | None], Awaitable[None]], attributes_file: str | None = None, + before_publication: Callable[[], Awaitable[None]] | None = None, + restore_spelling: Callable[[], Awaitable[None]] | None = None, ) -> AsyncIterator[None]: # Own a missing or non-directory ancestor too, so rollback also reverses # directory creation and file/directory replacements without following links. @@ -733,6 +735,8 @@ async def remove_backup(path: str, *, retain_detached: bool = False) -> None: ) publication_started = False try: + if before_publication is not None: + await before_publication() if "activate-originals" in snapshot.splitlines(): # Filesystems without hard links keep the original by # moving it aside and giving Git an equivalent working copy. @@ -760,6 +764,8 @@ async def recover() -> tuple[bool, bool]: receipt = _complete(await environment.exec_cmd( command, timeout=900, ), "candidate adoption recovery") + if publication_started and restore_spelling is not None: + await restore_spelling() shell_overlapped = shell_commands is not None and ( active > 0 or last_started is not shell_commands.last_started ) diff --git a/opencollab/adapters/_candidate_case_publish.py b/opencollab/adapters/_candidate_case_publish.py new file mode 100644 index 00000000..79595304 --- /dev/null +++ b/opencollab/adapters/_candidate_case_publish.py @@ -0,0 +1,233 @@ +"""Prepare worktree patches whose paths differ only in spelling.""" + +from __future__ import annotations + +import logging +import posixpath +import shlex +from collections import defaultdict +from collections.abc import AsyncIterator, Callable, Iterator, Sequence +from contextlib import asynccontextmanager +from typing import Any + +from opencollab.adapters._candidate_adoption import _CHECK_PARENTS, _adoption_command +from opencollab.adapters._candidate_casepaths import ( + _EXACT_ENTRIES, + _case_aliases, + _case_key, + _with_native_case_entries, +) +from opencollab.adapters._git_patch_bytes import _complete, _patch_temporary +from opencollab.adapters.git_patch import _RAW_ATTRIBUTES, _git_command_and_config_guard +from opencollab.application.async_timeout import await_owned_operation +from opencollab.application.exception_notes import add_exception_note + +logger = logging.getLogger(__name__) + + +def _ancestors(path: str) -> Iterator[str]: + while path: + yield path + path = posixpath.dirname(path) + + +async def _case_targets( + environment: Any, workspace: str, paths: Sequence[str], *, repository: bool = True, +) -> dict[str, str]: + by_spelling: dict[str, set[str]] = defaultdict(set) + for path in paths: + for name in _ancestors(path): + by_spelling[_case_key(name)].add(name) + pairs = [(new, old) for names in by_spelling.values() for new in names for old in names if old != new] + return dict(await _case_aliases(environment, workspace, pairs, repository=repository)) + + +def _current_spelling(path: str, aliases: dict[str, str]) -> str: + for prefix in _ancestors(path): + if prefix in aliases: + return aliases[prefix] + path[len(prefix):] + return path + + +async def _case_identity(environment: Any, workspace: str, path: str) -> str: + inspect = _EXACT_ENTRIES + 'exact_path "$1" && identity "$1"' + if not path.isascii(): + inspect = _with_native_case_entries(environment, r''' +path = exact_path(sys.argv[1]) +entry = identity(path) if path is not None else None +if entry is None: + raise SystemExit(f"worktree entry changed at {sys.argv[1]}") +print(entry) +''', inspect) + script = f"cd -- {shlex.quote(workspace)} || exit\nset -- {shlex.quote(path)}\n{inspect}" + return _complete(await environment.exec_cmd(script, timeout=120), f"candidate spelling identity for {path}").strip() + + +async def _case_move( + environment: Any, workspace: str, source: str, destination: str, identity: str, *, restoring: bool = False, +) -> None: + # GNU mv can reject two spellings of one entry before calling rename. + fallback = ( + _EXACT_ENTRIES + 'source=$1; target=$2; entry=$3\n' + 'if [ "$4" = true ] && exact_path "$target" && ! exact_path "$source"; then exit 0; fi\n' + 'exact_path "$source" && ! exact_path "$target" && ' + '[ "$entry" = "$(identity "$source")" ] && [ "$entry" = "$(identity "$target")" ] && ' + 'mv -f -- "$source" "$target" && exact_path "$target" && ! exact_path "$source"' + ) + move = _with_native_case_entries(environment, r''' +source, target, entry, restoring = sys.argv[1:] +original = exact_path(source) +present_target = exact_path(target) +if restoring == "true" and original is None and present_target is not None: + sys.exit(0) +if original is None or present_target is not None or identity(original) != entry or identity(target) != entry: + raise SystemExit(f"worktree entry changed at {source}") +actual_name = os.path.basename(original) +target_name = os.path.basename(target) +if actual_name == normalize("NFD", actual_name): + target_name = normalize("NFD", target_name) +os.rename(original, os.path.join(os.path.dirname(original), target_name)) +names.cache_clear() +if exact_path(target) is None or exact_path(source) is not None: + raise SystemExit(f"worktree spelling did not change at {target}") +''', fallback) + arguments = shlex.join((source, destination, identity, "true" if restoring else "false")) + script = ( + f"cd -- {shlex.quote(workspace)} || exit\n" + f"set -- {arguments}\n{move}" + ) + _complete(await environment.exec_cmd(script, timeout=120), f"candidate spelling change for {source}") + + +async def _normalize_case_index( + environment: Any, workspace: str, indexed: Callable[[str], str], + current: dict[str, str], aliases: dict[str, str], *, repository: bool = True, +) -> tuple[tuple[str, str], ...]: + renamed = {path: old for path, old in current.items() if path != old} + inspected = sorted(set(renamed) | set(renamed.values())) + entries: dict[str, str] = {} + for start in range(0, len(inspected), 128): + batch = shlex.join(inspected[start:start + 128]) + output = _complete(await environment.exec_cmd( + indexed(f"--literal-pathspecs ls-files --stage -z -- {batch}"), timeout=120, + ), "candidate case postimage") + for line in filter(None, output.split("\0")): + metadata, _, path = line.partition("\t") + entries[path] = metadata + destinations = {path: renamed[path] for path in entries.keys() & renamed.keys()} + if len(set(destinations.values())) != len(destinations) or entries.keys() & destinations.values(): + raise RuntimeError("candidate patch uses multiple spellings for the same worktree path") + + moves = set() + if destinations: + originals = "".join(f"{path}\0" for path in sorted(destinations)) + index_entries = [] + for path, old in sorted(destinations.items()): + mode, blob, _stage = entries[path].split() + index_entries.append(f"{mode} {blob}\t{old}\0") + for name in _ancestors(path): + present_name = aliases.get(name) + if present_name and posixpath.basename(present_name) != posixpath.basename(name): + target = posixpath.join(posixpath.dirname(present_name), posixpath.basename(name)) + moves.add((present_name, target)) + async with _patch_temporary( + environment, workspace, originals, prefix=".candidate-case-remove-", repository=repository, + ) as remove, _patch_temporary( + environment, workspace, "".join(index_entries), prefix=".candidate-case-index-", + repository=repository, + ) as replace: + _complete(await environment.exec_cmd( + indexed(f"update-index --force-remove -z --stdin < {shlex.quote(remove)}") + " && " + + indexed(f"update-index -z --index-info < {shlex.quote(replace)}"), timeout=900, + ), "candidate case index spelling") + # Rename the leaves before their parent directories. + return tuple(sorted(moves, key=lambda change: (-change[0].count("/"), change[0]))) + + +@asynccontextmanager +async def _normalized_case_patch( + environment: Any, workspace: str, command: str, patch_file: str, paths: Sequence[str], + aliases: dict[str, str], *, has_private_index: bool, repository: bool = True, +) -> AsyncIterator[tuple[str | None, tuple[str, ...], tuple[tuple[str, str], ...]]]: + current = {path: _current_spelling(path, aliases) for path in paths} + worktree_paths = tuple(sorted(set(current.values()))) + async with _patch_temporary( + environment, workspace, "", prefix=".candidate-case-publication-", cleanup_best_effort=True, + repository=repository, + ) as marker: + directory = shlex.quote(marker + ".files") + + def temporary(name: str) -> str: + return f"{directory}/{name}" + + initialize = f"mkdir -m 700 -- {directory}" + if not repository and not has_private_index: + git, _guard = _git_command_and_config_guard() + git_dir = temporary("git") + attributes = shlex.quote(f"* {_RAW_ATTRIBUTES}") + initialize += ( + f" && {git} init --bare --quiet --template= {git_dir} && " + f"mkdir -p -- {git_dir}/info && printf '%s\\n' {attributes} > {git_dir}/info/attributes" + ) + command = ( + f"{git} -C {shlex.quote(workspace)} --git-dir={git_dir} --work-tree={shlex.quote(workspace)} " + "-c core.bare=false -c core.autocrlf=false" + ) + + def indexed(arguments: str) -> str: + if has_private_index: + return f"{command} {arguments}" + return f"(export GIT_INDEX_FILE={temporary('index')}; {command} {arguments})" + + failure: BaseException | None = None + try: + present = temporary("present") + collect = ( + f"{initialize} && cd -- {shlex.quote(workspace)} || exit\n" + f"workspace={shlex.quote(workspace)}\nconflict() {{ return 1; }}\n" + _CHECK_PARENTS + + f"for path in {shlex.join(worktree_paths)}; do " + 'if check_parents "$workspace/$path" && { [ -f "$path" ] || [ -L "$path" ]; }; then ' + '''printf '%s\\0' "$path" || exit; fi; done''' + + f" > {present} && {indexed('read-tree --empty')} && " + f"if [ -s {present} ]; then " + + indexed(f"--literal-pathspecs add --force --pathspec-from-file={present} --pathspec-file-nul") + + f"; fi && {indexed('write-tree')}" + ) + async with _adoption_command(environment, workspace, collect, repository=repository) as script: + before = _complete(await environment.exec_cmd(script, timeout=900), "candidate case preimage").strip() + _complete(await environment.exec_cmd( + indexed(f"apply --cached --binary --whitespace=nowarn -- {shlex.quote(patch_file)}"), timeout=120, + ), "candidate case patch preparation") + + moves = await _normalize_case_index( + environment, workspace, indexed, current, aliases, repository=repository, + ) + + normalized = marker + ".files/apply.patch" + _complete(await environment.exec_cmd( + indexed( + "-c core.quotePath=true --no-pager diff --cached --binary --full-index --no-renames " + "--no-ext-diff --no-textconv --no-color --src-prefix=a/ --dst-prefix=b/ " + f"{shlex.quote(before)} > {shlex.quote(normalized)}" + ), timeout=900, + ), "candidate worktree patch preparation") + result = await environment.exec_cmd(f"test -s {shlex.quote(normalized)}", timeout=30) + _complete(result, "candidate worktree patch inspection", allowed=(0, 1)) + yield normalized if result.returncode == 0 else None, worktree_paths, moves + except BaseException as error: + failure = error + raise + finally: + try: + _complete(await await_owned_operation( + environment.exec_cmd(f"rm -rf -- {directory}", timeout=120), + propagate_cancellation=True, + ), "candidate case publication cleanup") + except Exception as cleanup: + if failure is None: + logger.warning( + "Could not confirm cleanup of case publication files at %s", marker + ".files", + exc_info=cleanup, + ) + else: + add_exception_note(failure, f"candidate case publication cleanup failed: {cleanup}") diff --git a/opencollab/adapters/_candidate_casepaths.py b/opencollab/adapters/_candidate_casepaths.py new file mode 100644 index 00000000..a785cc7e --- /dev/null +++ b/opencollab/adapters/_candidate_casepaths.py @@ -0,0 +1,234 @@ +"""Exact worktree names for Git indexes on case-insensitive filesystems.""" + +from __future__ import annotations + +import posixpath +import shlex +import sys +import unicodedata +from collections import defaultdict +from collections.abc import AsyncIterator, Iterable, Sequence +from contextlib import AsyncExitStack, asynccontextmanager +from typing import Any + +from opencollab.adapters._candidate_adoption import _adoption_command +from opencollab.adapters._env_vm import VMEnvironment +from opencollab.adapters._git_patch_bytes import _complete, _patch_temporary +from opencollab.adapters.git_patch import _stage_case_rename_command + +_EXACT_ENTRIES = r''' +exact_path() ( + directory=. + rest=$1 + while [ -d "$directory" ] && [ ! -L "$directory" ]; do + name=${rest%%/*} + matched= + for entry in "$directory"/* "$directory"/.[!.]* "$directory"/..?*; do + [ "${entry##*/}" = "$name" ] || continue + if [ -e "$entry" ] || [ -L "$entry" ]; then matched=$entry; break; fi + done + [ -n "$matched" ] || return 1 + case "$rest" in + */*) directory=$matched; rest=${rest#*/} ;; + *) return 0 ;; + esac + done + return 1 +) + +identity() { stat -c '%d:%i' -- "$1" 2>/dev/null || stat -f '%d:%i' -- "$1" 2>/dev/null; } +''' + +_CANONICAL_CASE_ENTRIES = r''' +import os +import sys +from collections import defaultdict +from functools import lru_cache +from unicodedata import normalize + +def identity(path): + try: + entry = os.lstat(path) + except (FileNotFoundError, NotADirectoryError): + return None + return f"{entry.st_dev}:{entry.st_ino}" + +@lru_cache(maxsize=512) +def names(directory): + actual = set(os.listdir(directory)) + canonical = defaultdict(list) + for name in actual: + canonical[normalize("NFC", name)].append(name) + return actual, canonical + +def exact_path(path): + directory = "." + for component in path.split("/"): + if os.path.islink(directory): + return None + try: + actual, canonical = names(directory) + except (FileNotFoundError, NotADirectoryError): + return None + spelled = os.path.join(directory, component) + if component in actual: + directory = spelled + continue + matches = canonical.get(normalize("NFC", component), ()) + if len(matches) != 1: + return None + actual_path = os.path.join(directory, matches[0]) + entry = identity(spelled) + if entry is None or identity(actual_path) != entry: + return None + directory = actual_path + return directory +''' + + +def _case_key(path: str) -> str: + return unicodedata.normalize("NFC", path).casefold() + + +def _with_native_case_entries(environment: Any, body: str, fallback: str) -> str: + delegate = getattr(environment, "_delegate", environment) + python = "python3" + if getattr(delegate, "local_filesystem", False): + python = sys.executable + elif isinstance(delegate, VMEnvironment): + python = delegate.connection.python + command = shlex.join((python, "-I", "-S", "-c", _CANONICAL_CASE_ENTRIES + body)) + return f'if command -v {shlex.quote(python)} >/dev/null 2>&1; then {command} "$@"; else\n{fallback}\nfi' + + +def _case_workspace_hint(workspace: str, git: str) -> str: + configured = f"({git} config --bool --get core.ignorecase || test $? = 1)" + directory = posixpath.normpath(workspace) + while directory and directory != "/": + parent, name = posixpath.split(directory) + for index, character in enumerate(name): + if character.isascii() and character.isalpha(): + other = name[:index] + character.swapcase() + name[index + 1:] + alternate = shlex.quote(posixpath.join(parent, other)) + # Git configuration can travel with a repository to a different filesystem. + return f"if [ {shlex.quote(directory)} -ef {alternate} ]; then printf true; else {configured}; fi" + directory = parent + return configured + + +async def _case_aliases( + environment: Any, workspace: str, pairs: Sequence[tuple[str, str]], *, repository: bool = True, +) -> tuple[tuple[str, str], ...]: + if not pairs: + return () + paths = shlex.join(path for pair in pairs for path in pair) + inspect = ( + _EXACT_ENTRIES + 'while [ "$#" -gt 0 ]; do old=$1; new=$2; shift 2; ' + 'if exact_path "$old" || ! exact_path "$new"; then continue; fi; ' + 'from=$(identity "$old") && to=$(identity "$new") || continue; ' + '''if [ "$from" = "$to" ]; then printf '%s\\0%s\\0' "$old" "$new"; fi; done''' + ) + if not paths.isascii(): + # Git can precompose paths even when the directory stores decomposed names. + inspect = _with_native_case_entries(environment, r''' +items = iter(sys.argv[1:]) +for old, new in zip(items, items): + if exact_path(old) is None and exact_path(new) is not None: + original = identity(old) + if original is not None and original == identity(new): + sys.stdout.buffer.write(os.fsencode(old) + b"\0" + os.fsencode(new) + b"\0") +''', inspect) + script = f"cd -- {shlex.quote(workspace)} || exit\nset -- {paths}\n{inspect}" + async with _adoption_command(environment, workspace, script, repository=repository) as command: + listing = _complete(await environment.exec_cmd(command, timeout=120), "candidate case aliases") + names = listing.removesuffix("\0").split("\0") if listing else () + return tuple(zip(names[::2], names[1::2])) + + +def _case_rename_pairs(old_names: Iterable[str], new_names: Iterable[str]) -> tuple[tuple[str, str], ...]: + tracked: dict[str, list[str]] = defaultdict(list) + for path in old_names: + tracked[_case_key(path)].append(path) + return tuple( + (old, new) for new in new_names for old in tracked.get(_case_key(new), ()) if old != new + ) + + +async def _find_case_renames( + environment: Any, workspace: str, git: str, *, + base_revision: str | None = None, worktree_git: str | None = None, repository: bool = True, +) -> tuple[tuple[str, str], ...]: + untracked = _complete(await environment.exec_cmd( + f"{git} -c core.ignorecase=false ls-files --others -z", timeout=900, + ), "candidate untracked case names") + staged = "" + if base_revision is not None: + staged = _complete(await environment.exec_cmd( + f"{worktree_git or git} diff --cached --no-renames --no-ext-diff --no-textconv " + f"--name-only --diff-filter=A -z " + f"{shlex.quote(base_revision)} --", timeout=900, + ), "candidate staged case names") + if not untracked and not staged: + return () + listing = _complete(await environment.exec_cmd( + f"{git} ls-files --cached -z", timeout=900, + ), "candidate tracked case names") + others = tuple(filter(None, untracked.split("\0"))) + staged_paths = tuple(filter(None, staged.split("\0"))) + tracked = tuple(dict.fromkeys((*filter(None, listing.split("\0")), *staged_paths))) + staged_names = {_case_key(path) for path in staged_paths} + # An overlay can contain the stale and exact names together. + targets = (*others, *(name for name in tracked if _case_key(name) in staged_names)) + return await _case_aliases( + environment, + workspace, + _case_rename_pairs(tracked, targets), + repository=repository, + ) + + +@asynccontextmanager +async def _case_rename_files( + environment: Any, workspace: str, pairs: Sequence[tuple[str, str]], *, repository: bool = True, +) -> AsyncIterator[tuple[str, str] | None]: + if not pairs: + yield None + return + async with AsyncExitStack() as files: + removed, added = [ + await files.enter_async_context(_patch_temporary( + environment, workspace, "".join(f"{path}\0" for path in dict.fromkeys(names)), + prefix=".candidate-case-paths-", repository=repository, + )) + for names in zip(*pairs) + ] + yield removed, added + + +async def _stage_case_renames( + environment: Any, workspace: str, git: str, pairs: Sequence[tuple[str, str]], *, repository: bool = True, +) -> None: + async with _case_rename_files(environment, workspace, pairs, repository=repository) as names: + if names is not None: + _complete(await environment.exec_cmd( + _stage_case_rename_command(git, names), timeout=900, + ), "candidate case rename capture") + + +async def _capture_case_renames(environment: Any, workspace: str, git: str) -> None: + aliases = await _find_case_renames(environment, workspace, git, base_revision="HEAD") + await _stage_case_renames(environment, workspace, git, aliases) + + +async def _seed_case_rename_index( + environment: Any, workspace: str, git: str, base_revision: str, *, worktree_git: str, +) -> tuple[tuple[str, str], ...]: + ignore_case = _complete(await environment.exec_cmd( + f"{git} read-tree {shlex.quote(base_revision)} && {_case_workspace_hint(workspace, git)}", + timeout=900, + ), "candidate index initialization").strip() + if ignore_case != "true": + return () + return await _find_case_renames( + environment, workspace, git, base_revision=base_revision, worktree_git=worktree_git, + ) diff --git a/opencollab/adapters/_candidate_increment.py b/opencollab/adapters/_candidate_increment.py index 676e2822..5355cc46 100644 --- a/opencollab/adapters/_candidate_increment.py +++ b/opencollab/adapters/_candidate_increment.py @@ -9,11 +9,21 @@ from typing import Any from opencollab.adapters._candidate_adoption import _CHECK_PARENTS, _adoption_command, _adoption_transaction +from opencollab.adapters._candidate_case_publish import ( + _case_identity, + _case_move, + _case_targets, + _current_spelling, + _normalized_case_patch, +) +from opencollab.adapters._candidate_casepaths import _case_key from opencollab.adapters._candidate_physical import _physical_git from opencollab.adapters._env_docker import DockerEnvironment from opencollab.adapters._git_patch_bytes import _complete, _patch_temporary from opencollab.adapters.git_patch import _git_command_and_config_guard from opencollab.adapters.tools.base import host_write_locks +from opencollab.application.async_timeout import await_owned_operation +from opencollab.application.workflow_candidates import CandidateWorkspaceTrackingError from opencollab.patches import patch_paths @@ -108,7 +118,7 @@ async def read_attribute_paths() -> tuple[str | None, str | None]: async def _apply_increment( environment: Any, workspace: str, patch: str, preserve_paths: Sequence[str] = (), *, repository: bool = True, strict: bool = False, - physical_paths: Sequence[str] = (), + physical_paths: Sequence[str] = (), expected_revision: str | None = None, ) -> None: """Apply one complete increment atomically without changing the real index.""" if not isinstance(patch, str) or not patch.strip(): @@ -116,6 +126,14 @@ async def _apply_increment( preserved = tuple(_safe_path(path) for path in preserve_paths) # Directory copies can sit below an unrelated Git worktree. git_prefix = "git" if repository else "GIT_DIR=/dev/null git" + + async def check_revision() -> None: + current = _complete(await environment.exec_cmd( + f"git -C {shlex.quote(workspace)} rev-parse --verify HEAD", timeout=120, + ), "candidate source revision").strip() + if current != expected_revision: + raise CandidateWorkspaceTrackingError("source worktree changed during candidate adoption") + async with _patch_temporary( environment, workspace, patch, prefix=".candidate-adopt-", suffix=".patch", cleanup_best_effort=True, repository=repository, @@ -163,7 +181,12 @@ async def read_attributes_file() -> str | None: command = repository_git if attributes_file is not None: command += f" -c core.attributesFile={shlex.quote(attributes_file)}" - async with AsyncExitStack() as resources: + aliases = await _case_targets(environment, workspace, paths, repository=repository) + if aliases and physical_paths: + physical_paths = tuple(dict.fromkeys(( + *physical_paths, *(_current_spelling(path, aliases) for path in physical_paths), + ))) + async with AsyncExitStack() as prepared, AsyncExitStack() as resources: operation = "candidate adoption" if physical_paths and repository: if guard: @@ -174,14 +197,43 @@ async def read_attributes_file() -> str | None: environment, workspace, physical_paths, strict=strict, )) operation = "physical candidate adoption" + apply_file, worktree_paths, moves = candidate_file, paths, () + if aliases: + apply_file, worktree_paths, moves = await prepared.enter_async_context(_normalized_case_patch( + environment, workspace, command, candidate_file, paths, aliases, + has_private_index=bool(physical_paths), repository=repository, + )) + # Renaming a directory also moves descendants outside the Git patch. + moved_roots = tuple(_case_key(source) for source, _destination in moves) + if any( + keep == root or keep.startswith(root + "/") or root.startswith(keep + "/") + for keep in map(_case_key, preserved) for root in moved_roots + ): + raise ValueError("candidate patch overlaps a preserved path") # Let Git reject unsafe path aliases before a recursive backup can # encounter repository metadata. Publication can still fail later. - check = f"{command} apply --check --binary --whitespace=nowarn -- {shlex.quote(candidate_file)}" - _complete(await environment.exec_cmd(check, timeout=120), operation) + if apply_file is not None: + check = f"{command} apply --check --binary --whitespace=nowarn -- {shlex.quote(apply_file)}" + _complete(await environment.exec_cmd(check, timeout=120), operation) + + published_moves: list[tuple[str, str, str]] = [] + + async def publish_spelling() -> None: + for source, destination in moves: + identity = await _case_identity(environment, workspace, source) + # The rename can complete before its command result is received. + published_moves.append((source, destination, identity)) + await _case_move(environment, workspace, source, destination, identity) + + async def restore_spelling() -> None: + for source, destination, identity in reversed(published_moves): + await _case_move(environment, workspace, destination, source, identity, restoring=True) async def replay( staged: str, git_directory: str | None, saved_attributes_file: str | None, ) -> None: + if apply_file is None: + return async with AsyncExitStack() as metadata: replay_git = repository_git if physical_paths and repository: @@ -198,23 +250,31 @@ async def replay( replay_git += f" -C {shlex.quote(staged)}" _complete(await environment.exec_cmd( f"{replay_git} apply --whitespace=nowarn --check --binary" - f" -- {shlex.quote(candidate_file)}", timeout=120, + f" -- {shlex.quote(apply_file)}", timeout=120, ), "candidate recovery replay check") # A failed replay still records the files Git was able to write. result = await environment.exec_cmd( f"{replay_git} apply --whitespace=nowarn --binary" - f" -- {shlex.quote(candidate_file)}", timeout=120, + f" -- {shlex.quote(apply_file)}", timeout=120, ) _complete(result, "candidate recovery replay", allowed=(0, 128)) async with _adoption_transaction( - environment, workspace, paths, repository=repository, + environment, workspace, worktree_paths, repository=repository, replay=replay, attributes_file=attributes_file, + before_publication=check_revision if expected_revision is not None else None, + restore_spelling=restore_spelling if moves else None, ): try: - _complete(await environment.exec_cmd( - f"{command} apply --binary --whitespace=nowarn -- {shlex.quote(candidate_file)}", - timeout=120, - ), operation) + if apply_file is not None: + _complete(await environment.exec_cmd( + f"{command} apply --binary --whitespace=nowarn -- {shlex.quote(apply_file)}", + timeout=120, + ), operation) + if moves: + await await_owned_operation(publish_spelling(), propagate_cancellation=True) + # A Git checkout can move HEAD while worktree-only apply is running. + if expected_revision is not None: + await check_revision() finally: await resources.aclose() diff --git a/opencollab/adapters/_candidate_physical.py b/opencollab/adapters/_candidate_physical.py index 83741624..07edb02f 100644 --- a/opencollab/adapters/_candidate_physical.py +++ b/opencollab/adapters/_candidate_physical.py @@ -9,14 +9,19 @@ from dataclasses import dataclass from typing import Any +from opencollab.adapters._candidate_case_publish import ( + _case_identity, + _case_move, + _case_targets, + _normalized_case_patch, +) +from opencollab.adapters._candidate_casepaths import _case_workspace_hint, _find_case_renames, _stage_case_renames from opencollab.adapters._env_worktree_submodules import _source_available_submodule_paths from opencollab.adapters._git_patch_bytes import _complete, _complete_patch, _patch_temporary -from opencollab.adapters.git_patch import _submodule_patch_guard +from opencollab.adapters.git_patch import _RAW_ATTRIBUTES, _submodule_patch_guard from opencollab.application.async_timeout import await_owned_operation from opencollab.patches import patch_paths, split_patch_blocks -_RAW_ATTRIBUTES = "-text -eol -filter -ident -working-tree-encoding" - def _git_prefix(workspace: str, strict: bool = False) -> str: environment = "GIT_NO_REPLACE_OBJECTS=1 " @@ -176,9 +181,16 @@ async def _physical_tree( timeout=900, ), "physical candidate file enumeration") async with _physical_git(environment, workspace, strict=strict, metadata=metadata) as (git, _directory): - _complete(await environment.exec_cmd( + ignore_case = _complete(await environment.exec_cmd( f"{git} read-tree {shlex.quote(base_revision)} && " f"{git} update-index -z --index-info < {shlex.quote(staged_file)} && " + f"{_case_workspace_hint(workspace, real_git)}", + timeout=900, + ), "physical candidate index initialization").strip() + if ignore_case == "true": + aliases = await _find_case_renames(environment, workspace, git, base_revision=base_revision) + await _stage_case_renames(environment, workspace, git, aliases) + _complete(await environment.exec_cmd( f"{git} add -u && " f"if [ -s {shlex.quote(paths_file)} ]; then " f"{git} --literal-pathspecs add --force --pathspec-from-file={shlex.quote(paths_file)} " @@ -396,15 +408,39 @@ async def _replay_physical_tree(environment: Any, workspace: str, before: str, p f"mkdir -- {shlex.quote(snapshot)} && {physical} read-tree {shlex.quote(before)} && " f"{physical} checkout-index --all --prefix={shlex.quote(snapshot + '/')}", timeout=900, ), "worktree physical replay setup") - async with _patch_temporary( - environment, workspace, patch, prefix=".worktree-replay-", suffix=".patch", - ) as patch_file: + paths = patch_paths(patch) + aliases = await _case_targets(environment, snapshot, paths, repository=False) + + async def apply(path: str) -> None: _complete(await environment.exec_cmd( f"{replay} read-tree {shlex.quote(before)} && " - f"{replay} apply --binary --whitespace=nowarn -- {shlex.quote(patch_file)}", timeout=900, + f"{replay} apply --binary --whitespace=nowarn -- {shlex.quote(path)}", timeout=900, ), "worktree physical patch replay") + + async with _patch_temporary( + environment, workspace, patch, prefix=".worktree-replay-", suffix=".patch", + ) as patch_file: + if aliases: + async with _normalized_case_patch( + environment, snapshot, physical, patch_file, paths, aliases, + has_private_index=True, repository=False, + ) as (normalized, _worktree_paths, moves): + if normalized is not None: + await apply(normalized) + for source, target in moves: + identity = await _case_identity(environment, snapshot, source) + await _case_move(environment, snapshot, source, target, identity) + _complete(await environment.exec_cmd( + f"{physical} read-tree {shlex.quote(before)}", timeout=900, + ), "worktree physical replay index") + renames = await _find_case_renames(environment, snapshot, physical, repository=False) + await _stage_case_renames(environment, snapshot, physical, renames, repository=False) + removed = {old for old, _new in renames} + paths = [path for path in paths if path not in removed] + else: + await apply(patch_file) _complete(await environment.exec_cmd( - f"{physical} --literal-pathspecs add --all --force -- {shlex.join(patch_paths(patch))}", timeout=900, + f"{physical} --literal-pathspecs add --all --force -- {shlex.join(paths)}", timeout=900, ), "worktree replay contents capture") return _complete(await environment.exec_cmd( f"{physical} write-tree", diff --git a/opencollab/adapters/_candidate_source.py b/opencollab/adapters/_candidate_source.py index 6ecf7f55..d391385b 100644 --- a/opencollab/adapters/_candidate_source.py +++ b/opencollab/adapters/_candidate_source.py @@ -3,9 +3,23 @@ from __future__ import annotations import shlex +from collections.abc import Sequence +from contextlib import AsyncExitStack from dataclasses import dataclass from typing import Any +from opencollab.adapters._candidate_case_publish import ( + _case_identity, + _case_move, + _case_targets, + _current_spelling, + _normalize_case_index, +) +from opencollab.adapters._candidate_casepaths import ( + _case_rename_files, + _case_workspace_hint, + _find_case_renames, +) from opencollab.adapters._candidate_physical import ( _has_worktree_conversions, _initialized_submodule_paths, @@ -14,7 +28,87 @@ _submodule_base_tree, _tree_patch, ) -from opencollab.adapters._git_patch_bytes import _complete, _patch_temporary +from opencollab.adapters._git_patch_bytes import _complete, _complete_patch, _patch_temporary +from opencollab.adapters.git_patch import _git_command_and_config_guard, guarded_staged_diff_command +from opencollab.patches import patch_paths + + +async def _strict_worktree_patch( + environment: Any, workspace: str, revision: str, *, + operation: str, timeout: float, untracked_exclusions: Sequence[str] = (), + reject_ignored_untracked: bool = True, +) -> str: + git, guard = _git_command_and_config_guard() + prefix = f"cd -- {shlex.quote(workspace)} && " + ignore_case = _complete(await environment.exec_cmd( + prefix + _case_workspace_hint(workspace, git), timeout=timeout, + ), "team worktree case matching").strip() + async with AsyncExitStack() as files: + case_names = None + if ignore_case == "true": + index = await files.enter_async_context(_patch_temporary( + environment, workspace, "", prefix=".candidate-team-source-index-", + )) + indexed = f"GIT_INDEX_FILE={shlex.quote(index)} {git}" + _complete(await environment.exec_cmd( + f"{prefix}{guard}{indexed} read-tree {shlex.quote(revision)}", timeout=timeout, + ), "team worktree rename index") + git_at_root = f"{indexed} -C {shlex.quote(workspace)} -c safe.directory={shlex.quote(workspace)}" + worktree_git = f"{git} -C {shlex.quote(workspace)}" + aliases = await _find_case_renames( + environment, workspace, git_at_root, base_revision=revision, worktree_git=worktree_git, + ) + case_names = await files.enter_async_context(_case_rename_files(environment, workspace, aliases)) + return await _complete_patch( + await environment.exec_cmd(prefix + guarded_staged_diff_command( + base_revision=revision, + reject_ignored_untracked=reject_ignored_untracked, + exclude_untracked_paths=untracked_exclusions, + case_rename_files=case_names, + ), timeout=timeout), + operation, environment, workspace, revision, None, captured_blobs=True, + ) + + +async def _apply_owned_source_patch( + environment: Any, workspace: str, base_revision: str, patch: str, patch_file: str, *, git: str, guard: str, +) -> None: + paths = patch_paths(patch) + aliases = await _case_targets(environment, workspace, paths) + command = f"cd -- {shlex.quote(workspace)} && {guard}" + options = f"--binary --whitespace=nowarn -- {shlex.quote(patch_file)}" + if not aliases: + _complete(await environment.exec_cmd( + f"{command}{git} apply --index {options}", timeout=900, + ), "candidate source contents") + return + async with _patch_temporary(environment, workspace, "", prefix=".candidate-source-checkout-") as index: + before_tree = shlex.quote(base_revision) + indexed = f"GIT_INDEX_FILE={shlex.quote(index)} {git}" + target_tree = _complete(await environment.exec_cmd( + f"{command}{indexed} read-tree {before_tree} && {indexed} apply --cached {options} && " + f"{indexed} write-tree", + timeout=900, + ), "candidate source target tree").strip() + paths_on_disk = {path: _current_spelling(path, aliases) for path in paths} + moves = await _normalize_case_index( + environment, workspace, lambda arguments: f"{command}{indexed} {arguments}", paths_on_disk, aliases, + ) + checkout_tree = _complete(await environment.exec_cmd( + f"{command}{indexed} write-tree", timeout=900, + ), "candidate source checkout tree").strip() + # Keep Git's sparse checkout behavior while moving case aliases explicitly. + _complete(await environment.exec_cmd( + f"{command}{git} update-index --refresh && {git} read-tree -m -u --no-recurse-submodules " + f"{before_tree} {shlex.quote(checkout_tree)}", + timeout=900, + ), "candidate source contents") + for source, destination in moves: + identity = await _case_identity(environment, workspace, source) + await _case_move(environment, workspace, source, destination, identity) + _complete(await environment.exec_cmd( + f"{command}{git} read-tree {shlex.quote(target_tree)}", timeout=900, + ), "candidate source index") @dataclass(slots=True) diff --git a/opencollab/adapters/_env_docker.py b/opencollab/adapters/_env_docker.py index d60793da..487ed688 100644 --- a/opencollab/adapters/_env_docker.py +++ b/opencollab/adapters/_env_docker.py @@ -688,6 +688,7 @@ async def read_text_range( physical = await self._contained_file_path(path) quoted_path = shlex.quote(physical) marker = _output_marker() + stdout_byte_limit = byte_cap + len(marker.encode("utf-8")) + 1 command = _framed(marker, ( f"[ -f {quoted_path} ] && [ -r {quoted_path} ] || exit 66; " "command -v awk >/dev/null && command -v sed >/dev/null && command -v tr >/dev/null && " @@ -703,7 +704,7 @@ async def read_text_range( command, timeout=120.0, strict_stdout=True, - stdout_byte_limit=byte_cap + len(marker.encode("utf-8")) + 1, + stdout_byte_limit=stdout_byte_limit, login=False, ) if result.returncode != 0: @@ -713,13 +714,22 @@ async def read_text_range( selected = lines[:limit] joined = "\n".join(selected) chars_truncated = len(joined) > max_chars or result.stdout_truncated + total_lines = None if chars_truncated: selected = joined[:max_chars].split("\n") has_more = True + # A complete capture with no lookahead row reached EOF. + if ( + 0 < len(lines) <= limit + and not result.stdout_truncated + and result.stdout_bytes is not None + and len(result.stdout_bytes) <= stdout_byte_limit + ): + total_lines = offset - 1 + len(lines) return TextFileRange( selected, offset, - None, + total_lines, has_more, chars_truncated=chars_truncated, ) diff --git a/opencollab/adapters/_env_process.py b/opencollab/adapters/_env_process.py index c673baec..306ecd8c 100644 --- a/opencollab/adapters/_env_process.py +++ b/opencollab/adapters/_env_process.py @@ -208,14 +208,26 @@ def send(sig: signal.Signals) -> None: except ProcessLookupError: pass - send(signal.SIGTERM) - if not await _wait_for_group_exit(group_id, term_grace): - send(signal.SIGKILL) + signal_denied = None + try: + send(signal.SIGTERM) + if not await _wait_for_group_exit(group_id, term_grace): + send(signal.SIGKILL) + except PermissionError as exc: + if sys.platform != "darwin": + raise + # Darwin can deny a signal while the group's last members are exiting. + signal_denied = exc try: await asyncio.wait_for(process.wait(), timeout=kill_grace) - except asyncio.TimeoutError: + except asyncio.TimeoutError as exc: + if signal_denied is not None: + raise signal_denied from exc return False - return await _wait_for_group_exit(group_id, kill_grace) + quiesced = await _wait_for_group_exit(group_id, kill_grace) + if not quiesced and signal_denied is not None: + raise signal_denied + return quiesced async def _require_process_exit( process: asyncio.subprocess.Process, diff --git a/opencollab/adapters/_safe_file_common.py b/opencollab/adapters/_safe_file_common.py index 06c72e6c..9c08945d 100644 --- a/opencollab/adapters/_safe_file_common.py +++ b/opencollab/adapters/_safe_file_common.py @@ -46,7 +46,13 @@ def _read_text_line( if remaining is not None: if len(content) > remaining: parts.append(content[:remaining]) - return "".join(parts), False, True + at_eof = not ended and len(chunk) < _RANGE_READ_CHUNK_CHARS + if ended: + try: + at_eof = handle.read(1) == "" + except UnicodeDecodeError: + at_eof = False + return "".join(parts), at_eof, True parts.append(content) remaining -= len(content) if ended: diff --git a/opencollab/adapters/_safe_file_range.py b/opencollab/adapters/_safe_file_range.py index c0d31869..fc842c93 100644 --- a/opencollab/adapters/_safe_file_range.py +++ b/opencollab/adapters/_safe_file_range.py @@ -59,7 +59,7 @@ def _read_text_range( return TextFileRange( selected, offset, - None, + line_number if at_eof else None, True, chars_truncated=True, ) diff --git a/opencollab/adapters/_team_candidate_environment.py b/opencollab/adapters/_team_candidate_environment.py index b85bd3cd..0e8a2ae3 100644 --- a/opencollab/adapters/_team_candidate_environment.py +++ b/opencollab/adapters/_team_candidate_environment.py @@ -7,8 +7,9 @@ from typing import Any from opencollab.adapters._candidate_physical import _has_worktree_conversions +from opencollab.adapters._candidate_source import _strict_worktree_patch from opencollab.adapters._git_patch_bytes import _complete, _complete_patch, _patch_temporary -from opencollab.adapters.git_patch import _git_command_and_config_guard, guarded_staged_diff_command +from opencollab.adapters.git_patch import _git_command_and_config_guard class _TeamCandidateEnvironment: @@ -69,14 +70,9 @@ def _capture_environment(self, *, allow_delivered: bool = False) -> Any: async def get_diff(self) -> str: owner = self._capture_environment() self._delivery_pending = True - root = self._lease.candidate_workspace - result = await owner.exec_cmd( - f"cd -- {shlex.quote(root)} && " - + guarded_staged_diff_command(base_revision=self._lease.base_revision), - ) - patch = await _complete_patch( - result, "worktree diff extraction", owner, root, - self._lease.base_revision, None, captured_blobs=True, + patch = await _strict_worktree_patch( + owner, self._lease.candidate_workspace, self._lease.base_revision, + operation="worktree diff extraction", timeout=120, ) await self._lease._assert_physical_submodules() self._delivery_pending = False diff --git a/opencollab/adapters/candidate_workspace.py b/opencollab/adapters/candidate_workspace.py index e2ca1da6..7bedaf7a 100644 --- a/opencollab/adapters/candidate_workspace.py +++ b/opencollab/adapters/candidate_workspace.py @@ -14,6 +14,13 @@ from typing import Any, ClassVar from opencollab.adapters._candidate_adoption import _mounted_recovery_paths +from opencollab.adapters._candidate_casepaths import ( + _capture_case_renames, + _case_key, + _case_rename_files, + _case_workspace_hint, + _seed_case_rename_index, +) from opencollab.adapters._candidate_increment import _apply_increment as _apply_increment from opencollab.adapters._candidate_increment import _safe_path from opencollab.adapters._candidate_physical import ( @@ -28,7 +35,7 @@ _submodule_base_tree, _tree_patch, ) -from opencollab.adapters._candidate_source import _source_snapshot +from opencollab.adapters._candidate_source import _apply_owned_source_patch, _source_snapshot, _strict_worktree_patch from opencollab.adapters._env_docker import DockerEnvironment from opencollab.adapters._env_local import LocalEnvironment from opencollab.adapters._env_process import ProcessCleanupError @@ -39,12 +46,13 @@ from opencollab.adapters.env import DockerWorkspaceEnvironment from opencollab.adapters.git_patch import ( _git_command_and_config_guard, + _stage_case_rename_command, _submodule_patch_guard, _submodule_status_command, - guarded_staged_diff_command, ) from opencollab.application.async_timeout import await_owned_operation from opencollab.application.exception_notes import add_exception_note +from opencollab.patches import patch_paths CANDIDATE_WORKSPACE_GIT_TIMEOUT_SECONDS = 900.0 @@ -266,22 +274,25 @@ async def diff(self, exclude_paths: Sequence[str] = ()) -> str: ) # Stage the current contents in an owned temporary index. Candidate # commits and index resets leave the same delivered file changes. - _complete( + ignore_case = _complete( await self.base_environment.exec_cmd( - f"{git} read-tree HEAD && {git} add --all -- .", + f"{git} read-tree HEAD && {git} add --all -- . && " + f"{_case_workspace_hint(self.candidate_workspace, git)}", timeout=CANDIDATE_WORKSPACE_GIT_TIMEOUT_SECONDS, ), "candidate contents capture", - ) + ).strip() + if ignore_case == "true": + await _capture_case_renames(self.base_environment, self.candidate_workspace, git) original_git = f"git -C {shlex.quote(self.candidate_workspace)}" - known = _complete( - await self.base_environment.exec_cmd( - f"{original_git} ls-tree -r --name-only -z {shlex.quote(self.base_revision)} " - f"&& {original_git} ls-files --cached -z", - timeout=CANDIDATE_WORKSPACE_GIT_TIMEOUT_SECONDS, - ), - "candidate known paths", - ) + known: set[str] = set() + for query in (f"ls-tree -r --name-only -z {shlex.quote(self.base_revision)}", "ls-files --cached -z"): + known.update(_complete( + await self.base_environment.exec_cmd( + f"{original_git} {query}", timeout=CANDIDATE_WORKSPACE_GIT_TIMEOUT_SECONDS, + ), + "candidate known paths", + ).split("\0")) remaining = _complete( await self.base_environment.exec_cmd( f"{git} ls-files --others -z", @@ -292,7 +303,7 @@ async def diff(self, exclude_paths: Sequence[str] = ()) -> str: # Retain existing source and staged files when new ignore rules hide # them. The remaining listing supplies current files, so deletions # and file/directory replacements follow their actual contents. - omitted = sorted(set(known.split("\0")).intersection(remaining.split("\0")) - {""}) + omitted = sorted(known.intersection(remaining.split("\0")) - {""}) if omitted: async with _candidate_temporary( self.base_environment, self.source_workspace, @@ -473,16 +484,20 @@ async def _source_patch( f"GIT_INDEX_FILE={shlex.quote(source_index)} " f"git --no-optional-locks -c core.filemode=true -C {shlex.quote(repository_root)}" ) - _complete( - await self._environment.exec_cmd( - f"{git} read-tree {shlex.quote(base_revision)} && " - f"{repository_git} ls-files --stage -z > {shlex.quote(source_paths)} && " - f"{git} update-index -z --index-info < {shlex.quote(source_paths)} && " - f"{git} add -u", - timeout=CANDIDATE_WORKSPACE_GIT_TIMEOUT_SECONDS, - ), - "candidate source contents staging", + aliases = await _seed_case_rename_index( + self._environment, repository_root, git, base_revision, worktree_git=repository_git, ) + async with _case_rename_files(self._environment, repository_root, aliases) as names: + recase = _stage_case_rename_command(git, names) + " && " if names else "" + _complete( + await self._environment.exec_cmd( + f"{repository_git} ls-files --stage -z > {shlex.quote(source_paths)} && " + f"{git} update-index -z --index-info < {shlex.quote(source_paths)} && " + f"{recase}{git} add -u", + timeout=CANDIDATE_WORKSPACE_GIT_TIMEOUT_SECONDS, + ), + "candidate source contents staging", + ) await _assert_patchable_submodules( self._environment, repository_root, base_revision, index_file=source_index, reject_ignored_untracked=False, @@ -558,18 +573,10 @@ async def _acquire( *await _mounted_recovery_paths(self._environment, repository_root), ) if strict_capture: - source_patch = await _complete_patch( - await self._environment.exec_cmd( - f"cd -- {shlex.quote(repository_root)} && " - + guarded_staged_diff_command( - base_revision=base_revision, - reject_ignored_untracked=False, - exclude_untracked_paths=source_untracked, - ), - timeout=CANDIDATE_WORKSPACE_GIT_TIMEOUT_SECONDS, - ), - "team source contents capture", self._environment, repository_root, - base_revision, None, captured_blobs=True, + source_patch = await _strict_worktree_patch( + self._environment, repository_root, base_revision, + operation="team source contents capture", timeout=CANDIDATE_WORKSPACE_GIT_TIMEOUT_SECONDS, + untracked_exclusions=source_untracked, reject_ignored_untracked=False, ) async with AsyncExitStack() as capture_resources: converted = await _has_worktree_conversions( @@ -640,18 +647,6 @@ async def _acquire( timeout=CANDIDATE_WORKSPACE_GIT_TIMEOUT_SECONDS, ) _complete(result, f"candidate worktree setup for {label}") - candidate_workspace = path - if workspace_prefix: - candidate_workspace = posixpath.join(path, _safe_path(workspace_prefix)) - _complete( - await self._environment.exec_cmd( - f"mkdir -p -- {shlex.quote(candidate_workspace)}", - timeout=CANDIDATE_WORKSPACE_GIT_TIMEOUT_SECONDS, - ), - "candidate workspace directory", - ) - lease.environment = await self._candidate_environment(candidate_workspace) - await lease.environment.setup() if isinstance(self._environment, LocalEnvironment): source_repository = os.path.realpath(repository_root) source_workspace = os.path.realpath(self._workspace) @@ -661,6 +656,31 @@ async def _acquire( except ValueError as exc: raise RuntimeError("candidate source workspace is outside its Git repository") from exc + candidate_workspace = posixpath.join(path, _safe_path(workspace_prefix)) if workspace_prefix else path + + async def start_environment() -> None: + if workspace_prefix: + _complete( + await self._environment.exec_cmd( + f"mkdir -p -- {shlex.quote(candidate_workspace)}", + timeout=CANDIDATE_WORKSPACE_GIT_TIMEOUT_SECONDS, + ), + "candidate workspace directory", + ) + lease.environment = await self._candidate_environment(candidate_workspace) + await lease.environment.setup() + + # Source materialization can replace a scoped local directory. + scope = _case_key(workspace_prefix.rstrip("/")) + defer_anchor = isinstance(self._environment, LocalEnvironment) and bool(scope) and ( + source_capture is not None or any( + relative == scope or relative.startswith(scope + "/") or scope.startswith(relative + "/") + for relative in map(_case_key, patch_paths(source_patch)) + ) + ) + if not defer_anchor: + await start_environment() + async def git_in(workspace: str, *arguments: str) -> Any: return await self._environment.exec_cmd( shlex.join(("git", "-C", workspace, *arguments)), @@ -702,22 +722,13 @@ async def git_marker_exists(source_module: str) -> bool: self._environment, repository_root, source_patch, prefix=".candidate-source-", suffix=".patch", ) as source_file: - apply_command = ( - f"git -C {shlex.quote(path)} apply --index --binary --whitespace=nowarn " - f"-- {shlex.quote(source_file)}" - ) + git = f"git -C {shlex.quote(path)}" + guard = "" if strict_capture: git, guard = _git_command_and_config_guard() - apply_command = ( - f"cd -- {shlex.quote(path)} && {guard}{git} " - f"apply --index --binary --whitespace=nowarn -- {shlex.quote(source_file)}" - ) - _complete( - await self._environment.exec_cmd( - apply_command, - timeout=CANDIDATE_WORKSPACE_GIT_TIMEOUT_SECONDS, - ), - "candidate source contents", + await _apply_owned_source_patch( + self._environment, path, base_revision, source_patch, source_file, + git=git, guard=guard, ) # The candidate's index records its starting contents, including # source untracked files, while the source index stays untouched. @@ -743,8 +754,6 @@ async def git_marker_exists(source_module: str) -> bool: strict=strict_capture, ) if physical_source_patch.strip(): - from opencollab.patches import patch_paths - async with _candidate_temporary( self._environment, path, physical_source_patch, prefix=".candidate-physical-source-", suffix=".patch", @@ -757,6 +766,8 @@ async def git_marker_exists(source_module: str) -> bool: f"git -C {shlex.quote(path)} update-ref refs/worktree/opencollab-physical-source " f"{shlex.quote(source_capture.tree)}", ), "candidate physical source reference") + if defer_anchor: + await start_environment() # A worktree-local ref retains the original contents for recovery # throughout the lease, including after commits or Git collection. _complete( @@ -952,6 +963,8 @@ async def adopt( self, patch: str, preserve_paths: Sequence[str] = (), + *, + expected_revision: str | None = None, ) -> None: if not isinstance(patch, str) or not patch.strip(): raise ValueError("candidate patch must be non-empty") @@ -961,11 +974,12 @@ async def adopt( ) await _apply_increment( self._environment, await self._repository_root(), patch, preserved, + expected_revision=expected_revision, ) async def adopt_run(self, candidate: Any, preserve_paths: Sequence[str] = ()) -> None: if candidate.delivery_diff is None or candidate.delivery_source_diff != candidate.diff: - await self.adopt(candidate.diff, preserve_paths) + await self.adopt(candidate.diff, preserve_paths, expected_revision=candidate.source_revision) return patch = candidate.effective_diff if not patch.strip(): @@ -977,6 +991,7 @@ async def adopt_run(self, candidate: Any, preserve_paths: Sequence[str] = ()) -> root = await self._repository_root() await _apply_increment( self._environment, root, patch, preserved, + expected_revision=candidate.source_revision, physical_paths=tuple(dict.fromkeys(( *candidate.delivery_paths, *await _physical_paths(self._environment, root, patch), diff --git a/opencollab/adapters/cli/main.py b/opencollab/adapters/cli/main.py index 0ac78e83..2bb19c87 100644 --- a/opencollab/adapters/cli/main.py +++ b/opencollab/adapters/cli/main.py @@ -355,7 +355,8 @@ async def _run( # and lines are read straight from stdin. has_screen = sys.stdin.isatty() and sys.stdout.isatty() prompt = LivePrompt(tui, console=console, interactive=has_screen) - model_cfg = _initial_model_config(cfg, team_config_path) + team = load_team_config(path=team_config_path) + model_cfg = resolve_model_route(cfg, team.role_for(team.entry).model) tui.print_welcome( model=model_cfg["model"], provider=model_cfg["provider"], @@ -406,6 +407,7 @@ async def read_question(text: str) -> str: ctx, builder=build_scheduler, use_worktrees=use_worktrees, interactive=True, session_file=session_file, auto_save=True, team_config_path=team_config_path, + resolved_team_config=team, allow_unisolated_child_shell=allow_local_child_shell, run_id=getattr(ctx.tracer, "run_id", None), ) diff --git a/opencollab/adapters/cli/workflow.py b/opencollab/adapters/cli/workflow.py index 855a5e6c..e85c16b1 100644 --- a/opencollab/adapters/cli/workflow.py +++ b/opencollab/adapters/cli/workflow.py @@ -28,7 +28,8 @@ from opencollab.application.ports import EventPublisherPort from opencollab.application.workflow_registry import Registry from opencollab.bootstrap.session_factory import WORKFLOW_RUN_PREFIX, make_run_dir -from opencollab.bootstrap.workflow_runtime import discover_workflows, run_workflow +from opencollab.bootstrap.workflow_runtime import WorkflowRuntimeResult, discover_workflows, run_workflow +from opencollab.domain.json_data import loads_finite_json app = typer.Typer(name="workflow", help="Run deterministic Python workflows.") console = Console() @@ -59,6 +60,15 @@ async def emit(self, event: Any) -> None: marker = "==" if kind == "phase" else "--" self._console.print(Text(f"{marker} {message}", style="dim")) +class _WorkflowOutputError(ValueError): + runtime_result: WorkflowRuntimeResult + +def _format_workflow_output(output: Any) -> str: + try: + return json.dumps(output, indent=2, default=str, allow_nan=False) + except (TypeError, ValueError, OverflowError, RecursionError) as exc: + raise _WorkflowOutputError(f"Could not serialize workflow result as JSON. {exc}") from None + @app.command(name="list") def list_cmd( workspace: str = typer.Option(".", "--workspace", "-w", help="Working directory"), @@ -91,7 +101,7 @@ def run_cmd( budget: Optional[int] = typer.Option( None, "--budget", - help="Max token budget (default: max(config budget, 1000000); workflows fan out many sessions)", + help="Max token budget. An explicit value overrides unbounded mode. The bounded default is at least 1,000,000.", ), concurrency: int = typer.Option(4, "--concurrency", "-c", help="Max concurrent agent sessions"), task_concurrency: Optional[int] = typer.Option( @@ -130,7 +140,7 @@ def run_cmd( raise typer.Exit(code=1) from None try: - parsed_args = json.loads(args) + parsed_args = loads_finite_json(args) except json.JSONDecodeError as exc: console.print(f"[red]Invalid --args JSON:[/red] {exc}") raise typer.Exit(code=1) from None @@ -166,27 +176,34 @@ def run_cmd( save_dir = make_run_dir(workspace, prefix=WORKFLOW_RUN_PREFIX) if save else None event_sink: EventPublisherPort = _ConsoleEventSink(console) - result = run_with_bounded_shutdown( - run_workflow( - spec, - parsed_args, - cfg=cfg, - workspace=workspace, - event_sink=event_sink, - budget=budget, - max_concurrency=concurrency, - task_concurrency=task_concurrency, - agent_profile=agent_profile, - **({"isolation": isolation} if isolation is not None else {}), - **({"cleanup_timeout": cleanup_timeout} if cleanup_timeout is not None else {}), - **({"run_id": run_id} if run_id is not None else {}), - save_dir=save_dir, - trace=trace, - return_details=True, - ), - shutdown_timeout=(cleanup_timeout if cleanup_timeout is not None else - (cfg.get("vm") or {}).get("cleanup_timeout", 2.0)), - ) + output_error = None + try: + result = run_with_bounded_shutdown( + run_workflow( + spec, + parsed_args, + cfg=cfg, + workspace=workspace, + event_sink=event_sink, + budget=budget, + limit_mode="explicit" if budget is not None else "environment", + max_concurrency=concurrency, + task_concurrency=task_concurrency, + agent_profile=agent_profile, + **({"isolation": isolation} if isolation is not None else {}), + **({"cleanup_timeout": cleanup_timeout} if cleanup_timeout is not None else {}), + **({"run_id": run_id} if run_id is not None else {}), + save_dir=save_dir, + trace=trace, + return_details=True, + format_output=_format_workflow_output, + ), + shutdown_timeout=(cleanup_timeout if cleanup_timeout is not None else + (cfg.get("vm") or {}).get("cleanup_timeout", 2.0)), + ) + except _WorkflowOutputError as exc: + result = exc.runtime_result + output_error = exc for failure in getattr(result, "agent_failures", ()): if (failure["exception_type"], failure["provider_error_type"]) == ("AgentStopped", "content_filter"): message = f"-- agent stopped ({failure['label']}): {_FILTERED_OUTPUT_REASON}" @@ -196,7 +213,12 @@ def run_cmd( if trace: trace_path = os.path.join(save_dir, "orchestration.jsonl") console.print(f"[dim]== orchestration at {trace_path}[/dim]") - typer.echo(json.dumps(result.output, indent=2, default=str)) + if output_error is not None: + typer.echo(str(output_error), err=True) + for note in getattr(output_error, "__notes__", ()): + typer.echo(note, err=True) + raise typer.Exit(code=1) from None + typer.echo(result.output) if result.stop_reason is not None: raise typer.Exit(code=1) diff --git a/opencollab/adapters/git_patch.py b/opencollab/adapters/git_patch.py index 081402f5..aa1da307 100644 --- a/opencollab/adapters/git_patch.py +++ b/opencollab/adapters/git_patch.py @@ -5,6 +5,8 @@ import shlex from collections.abc import Sequence +_RAW_ATTRIBUTES = "-text -eol -filter -ident -working-tree-encoding" + def _git_command_and_config_guard(*, allow_core_worktree: bool = False) -> tuple[str, str]: """Share existing repository configuration restrictions with Git tools.""" @@ -157,6 +159,7 @@ def guarded_staged_diff_command( exclude_paths: Sequence[str] = (), exclude_untracked_paths: Sequence[str] = (), reject_ignored_untracked: bool = True, + case_rename_files: tuple[str, str] | None = None, ) -> str: """Stage through a temporary index without repository-local diff hooks. @@ -184,6 +187,9 @@ def guarded_staged_diff_command( git_command, unsafe_config_guard = _git_command_and_config_guard() git_index_command = f'GIT_INDEX_FILE="$idx" {git_command}' + case_renames = ( + _stage_case_rename_command(git_index_command, case_rename_files) + " && " if case_rename_files else "" + ) untracked_pathspec = "" if exclude_untracked_paths: untracked_pathspec = " -- . " + " ".join( @@ -240,6 +246,7 @@ def guarded_staged_diff_command( f"{git_index_command} read-tree {shlex.quote(base_revision)} && " f'{git_command} ls-files --stage -z > "$tracked" && ' f'{git_index_command} update-index -z --index-info < "$tracked" && ' + f"{case_renames}" f'{git_index_command} add -u && ' f"{ignored_guard}" f"{stage_untracked}" @@ -251,4 +258,13 @@ def guarded_staged_diff_command( f"{shlex.quote(base_revision)}" ) + +def _stage_case_rename_command(git: str, path_lists: tuple[str, str]) -> str: + removed, added = map(shlex.quote, path_lists) + return ( + f"{git} update-index --force-remove -z --stdin < {removed} && " + f"{git} --literal-pathspecs add --force --pathspec-from-file={added} --pathspec-file-nul" + ) + + __all__ = ["guarded_staged_diff_command"] diff --git a/opencollab/adapters/llm/_chat_response.py b/opencollab/adapters/llm/_chat_response.py index f6ac22cd..4b85b1b8 100644 --- a/opencollab/adapters/llm/_chat_response.py +++ b/opencollab/adapters/llm/_chat_response.py @@ -180,8 +180,9 @@ def _build_chat_response( # chain-of-thought in ``reasoning_content`` and the answer in ``content``. # Keep the reasoning for trajectory observability; the shared rescue rung # falls back to it only when the turn is otherwise empty. + content_from_reasoning = False if finish_reason != "content_filter": - content = rescue_empty_turn(content, tool_calls, reasoning) + content, content_from_reasoning = rescue_empty_turn(content, tool_calls, reasoning) return LLMResponse( content=content, tool_calls=tool_calls, @@ -189,6 +190,7 @@ def _build_chat_response( finish_reason=finish_reason, reasoning=reasoning, provider_model=provider_model, + content_from_reasoning=content_from_reasoning, ) def _parse_response( diff --git a/opencollab/adapters/llm/_chat_stream.py b/opencollab/adapters/llm/_chat_stream.py index eccb018c..2243b0f0 100644 --- a/opencollab/adapters/llm/_chat_stream.py +++ b/opencollab/adapters/llm/_chat_stream.py @@ -4,8 +4,13 @@ import asyncio import logging +from collections.abc import Awaitable, Callable, Iterator +from contextlib import contextmanager from dataclasses import dataclass, field -from typing import Any +from functools import partial +from typing import Any, TypeVar + +from openai import AsyncStream from opencollab.adapters.llm._chat_response import ( _build_chat_response, @@ -13,9 +18,11 @@ _normalize_tool_arguments, _reported_chat_usage, ) +from opencollab.adapters.llm._transport_wait import _TransportInterruption, _wait_for_transport from opencollab.adapters.llm.errors import StreamedUsageUnavailableError, TransientProviderError from opencollab.adapters.llm.first_token import CHAT_STREAM, begin_attempt, mark_first_token from opencollab.adapters.llm.types import LLMResponse +from opencollab.application.async_timeout import await_owned_operation # Streaming request fields stay framework-controlled so ``extra_body`` # cannot enable streaming. Omit both fields for non-streamed requests. @@ -49,6 +56,7 @@ class _ChatStreamState: usage_object: Any = None provider_model: str | None = None chunk_count: int = 0 + close_error: Exception | None = None @dataclass class _UsageCarrier: @@ -249,28 +257,101 @@ def _stream_state_to_response( ) return response -async def _next_chunk(iterator: Any, budget: float | None, *, stage: str) -> Any: +_T = TypeVar("_T") + +async def _wait_for_chat_transport( + operation: Awaitable[_T], + timeout: float | None, + settle_cancelled: Callable[[_T], Awaitable[object]] | None = None, + *, + repeat_cancellation: bool = True, +) -> _T: + cancellation: asyncio.CancelledError | None = None + + def observe(interruption: _TransportInterruption) -> None: + nonlocal cancellation + if isinstance(interruption, asyncio.CancelledError): + cancellation = interruption + + try: + result = await _wait_for_transport( + operation, timeout, on_interrupt=observe, repeat_cancellation=repeat_cancellation, + ) + except (Exception, asyncio.CancelledError) as exc: + if cancellation is not None and exc is not cancellation: + raise cancellation from exc + raise + if cancellation is not None: + if settle_cancelled is not None: + await settle_cancelled(result) + raise cancellation + return result + +async def _next_chunk( + iterator: Any, budget: float | None, *, stage: str, state: _ChatStreamState, +) -> Any: + async def settle_usage(chunk: Any) -> None: + usage = getattr(chunk, "usage", None) + if usage is not None: + state.usage_object = usage + try: if budget is None: return await iterator.__anext__() - return await asyncio.wait_for(iterator.__anext__(), timeout=budget) + return await _wait_for_chat_transport(iterator.__anext__(), budget, settle_usage) except asyncio.TimeoutError as exc: detail = "from the provider transport" if budget is None else f"after {budget:g}s" raise TransientProviderError( f"chat completion {stage} timeout {detail}" ) from exc -async def _close_stream(stream: Any) -> None: - """Release the socket without replacing a finished read or its original error.""" +async def _close_stream( + stream: Any, *, timeout: float | None, preserve_cancellation: bool = False, +) -> Exception | None: close = getattr(stream, "close", None) if close is None: - return + return None + native = isinstance(stream, AsyncStream) try: result = close() if asyncio.iscoroutine(result): - await result - except Exception: + if native: + result = _wait_for_chat_transport(result, timeout, repeat_cancellation=False) + if native and not preserve_cancellation: + await result + else: + await await_owned_operation(result, propagate_cancellation=not preserve_cancellation) + except asyncio.CancelledError: + if not preserve_cancellation: + raise + except Exception as exc: logging.getLogger(__name__).debug("chat stream close failed", exc_info=True) + if native: + return exc + return None + +@contextmanager +def _defer_native_close(stream: Any) -> Iterator[None]: + if not isinstance(stream, AsyncStream): + yield + return + + # Keep SDK-owned HTTP close out of the timed chunk iterator. + response = stream.response + close = response.aclose + has_override = "aclose" in vars(response) + + async def defer_close() -> None: + return None + + response.aclose = defer_close + try: + yield + finally: + if has_override: + response.aclose = close + else: + del response.aclose async def _consume_chat_stream( stream: Any, first_chunk_timeout: float | None, idle_timeout: float | None @@ -297,24 +378,30 @@ async def _drain_chat_stream( ) -> None: iterator = stream.__aiter__() first = True + cancelled = False try: - while True: - try: - chunk = await _next_chunk( - iterator, - first_chunk_timeout if first else idle_timeout, - stage="first-chunk" if first else "stream-idle", - ) - except StopAsyncIteration: - break - if first: - # Before ``_absorb_chunk``: the measurement is when the bytes - # landed, not when parsing them finished. - mark_first_token(CHAT_STREAM) - first = False - _absorb_chunk(chunk, state) + with _defer_native_close(stream): + while True: + try: + chunk = await _next_chunk( + iterator, + first_chunk_timeout if first else idle_timeout, + stage="first-chunk" if first else "stream-idle", + state=state, + ) + except StopAsyncIteration: + break + if first: + # Before ``_absorb_chunk``: the measurement is when the bytes + # landed, not when parsing them finished. + mark_first_token(CHAT_STREAM) + first = False + _absorb_chunk(chunk, state) + except asyncio.CancelledError: + cancelled = True + raise finally: - await _close_stream(stream) + state.close_error = await _close_stream(stream, timeout=idle_timeout, preserve_cancellation=cancelled) async def _create_and_consume_chat_stream( client: Any, @@ -329,9 +416,10 @@ async def _create_and_consume_chat_stream( if first_chunk_timeout is None: event_stream = await client.chat.completions.create(**kwargs) else: - event_stream = await asyncio.wait_for( + event_stream = await _wait_for_chat_transport( client.chat.completions.create(**kwargs), - timeout=first_chunk_timeout, + first_chunk_timeout, + partial(_close_stream, timeout=idle_timeout, preserve_cancellation=True), ) except asyncio.TimeoutError as exc: detail = "from the provider transport" if first_chunk_timeout is None else f"after {first_chunk_timeout:g}s" @@ -340,7 +428,7 @@ async def _create_and_consume_chat_stream( # Opening the stream spends part of the first-chunk allowance; charge it. remaining = None if deadline is None else deadline - loop.time() if remaining is not None and remaining <= 0: - await _close_stream(event_stream) + await _close_stream(event_stream, timeout=idle_timeout) raise TransientProviderError( f"chat completion first-chunk timeout after {first_chunk_timeout:g}s" ) diff --git a/opencollab/adapters/llm/_transport_wait.py b/opencollab/adapters/llm/_transport_wait.py new file mode 100644 index 00000000..2ba554eb --- /dev/null +++ b/opencollab/adapters/llm/_transport_wait.py @@ -0,0 +1,50 @@ +"""Timed ownership of provider transport operations.""" + +from __future__ import annotations + +import asyncio +import sys +from collections.abc import Awaitable, Callable +from typing import TypeVar + +_T = TypeVar("_T") +_TransportInterruption = asyncio.CancelledError | asyncio.TimeoutError + +async def _wait_for_transport( + operation: Awaitable[_T], + timeout: float | None, + *, + on_interrupt: Callable[[_TransportInterruption], None] | None = None, + repeat_cancellation: bool = True, +) -> _T: + if sys.version_info >= (3, 12) and on_interrupt is None and repeat_cancellation: + return await asyncio.wait_for(operation, timeout) + # Retain terminal usage when a cancelled transport still delivers a result. + task = asyncio.ensure_future(operation) + try: + # Older wait_for implementations can consume a concurrent caller cancellation. + if not task.done() and (timeout is None or timeout > 0): + await asyncio.wait((task,), timeout=timeout) + if not task.done(): + raise asyncio.TimeoutError + except (asyncio.CancelledError, asyncio.TimeoutError) as interruption: + if task.done(): + if on_interrupt is not None and isinstance(interruption, asyncio.CancelledError) and not task.cancelled(): + on_interrupt(interruption) + return task.result() + if on_interrupt is not None: + on_interrupt(interruption) + task.cancel() + while not task.done(): + try: + await asyncio.wait((task,)) + except asyncio.CancelledError as cancellation: + if isinstance(interruption, asyncio.TimeoutError): + interruption = cancellation + if on_interrupt is not None: + on_interrupt(interruption) + if repeat_cancellation and not task.done(): + task.cancel() + if task.cancelled(): + raise interruption + return task.result() diff --git a/opencollab/adapters/llm/anthropic_provider.py b/opencollab/adapters/llm/anthropic_provider.py index a0f09108..090256c9 100644 --- a/opencollab/adapters/llm/anthropic_provider.py +++ b/opencollab/adapters/llm/anthropic_provider.py @@ -483,7 +483,7 @@ def _parse_response(resp: Any) -> LLMResponse: # Keep the thinking text for trajectory observability; the shared rescue # rung falls back to it only when the turn is otherwise empty. reasoning = thinking_text or None - content = rescue_empty_turn(content, tool_calls, reasoning) + content, content_from_reasoning = rescue_empty_turn(content, tool_calls, reasoning) return LLMResponse( content=content or None, @@ -491,6 +491,7 @@ def _parse_response(resp: Any) -> LLMResponse: usage=_parse_usage(resp.usage), finish_reason=resp.stop_reason, reasoning=reasoning, + content_from_reasoning=content_from_reasoning, provider_model=( value if isinstance((value := getattr(resp, "model", None)), str) and value diff --git a/opencollab/adapters/llm/client.py b/opencollab/adapters/llm/client.py index 2809a681..fb1b0a3e 100644 --- a/opencollab/adapters/llm/client.py +++ b/opencollab/adapters/llm/client.py @@ -358,12 +358,17 @@ async def complete( start = time.monotonic() response = None + caller_cancellation: asyncio.CancelledError | None = None provider_error: BaseException | None = None settlement_error: BaseException | None = None settled_usage = None first_attempt = True initial_limit: int | None = None + def retain_cancellation(cancellation: asyncio.CancelledError) -> None: + nonlocal caller_cancellation + caller_cancellation = cancellation + def request_limit() -> int | None: limit = max_output_tokens if before_request is not None: @@ -436,6 +441,8 @@ def prepare_attempt() -> int | None: provider_error_time_budget=retry_budget, before_attempt=prepare_attempt, on_attempt_usage=on_attempt_usage, + # Session owners capture late replies even after their caller stops. + on_cancelled=retain_cancellation if usage_origin is None else None, ) else: response = await complete_openai( @@ -460,7 +467,8 @@ def prepare_attempt() -> int | None: ) except BaseException as exc: provider_error = exc - raise + if caller_cancellation is None or not isinstance(exc, Exception): + raise finally: outcome = response if response is not None else provider_error settled_usage = getattr(outcome, "usage", None) @@ -509,4 +517,7 @@ def prepare_attempt() -> int | None: finally: if settlement_error is not None: raise settlement_error + if caller_cancellation is not None: + caller_cancellation.usage = settled_usage + raise caller_cancellation from provider_error return response diff --git a/opencollab/adapters/llm/openai_provider.py b/opencollab/adapters/llm/openai_provider.py index 51aef665..b25a2d46 100644 --- a/opencollab/adapters/llm/openai_provider.py +++ b/opencollab/adapters/llm/openai_provider.py @@ -17,6 +17,7 @@ _create_and_consume_chat_stream, _stream_state_to_response, ) +from opencollab.adapters.llm.errors import StreamedUsageUnavailableError, TransientProviderError from opencollab.adapters.llm.first_token import ( NOT_STREAMED, begin_attempt, @@ -276,9 +277,12 @@ async def request_once() -> LLMResponse: state = await _create_and_consume_chat_stream( client, kwargs, first_event_timeout, stream_idle_timeout ) - return _stream_state_to_response( - state, kwargs["messages"], kwargs.get("tools") - ) + try: + return _stream_state_to_response(state, kwargs["messages"], kwargs.get("tools")) + except (StreamedUsageUnavailableError, TransientProviderError) as exc: + if state.close_error is not None: + raise state.close_error from exc + raise except BaseException as exc: usage = ( _reported_chat_usage(state.usage_object) if state is not None diff --git a/opencollab/adapters/llm/responses_errors.py b/opencollab/adapters/llm/responses_errors.py index 30f6fbf4..8c26c0ff 100644 --- a/opencollab/adapters/llm/responses_errors.py +++ b/opencollab/adapters/llm/responses_errors.py @@ -13,7 +13,11 @@ "rate_limit_error", "rate_limit_exceeded", "server_error", + "server_is_overloaded", + "stream_interrupted", + "stream_truncated", "upstream_error", + "upstream_timeout", "vector_store_timeout", } ) @@ -39,11 +43,13 @@ def __init__( code: str | None = None, status_code: int | None = None, param: str | None = None, + provider_model: str | None = None, ) -> None: super().__init__(message) self.code = code self.status_code = status_code self.param = param + self.provider_model = provider_model self.body = {"error": {"code": code, "message": message, "param": param}} class ResponsesEmptyOutputError(ResponsesProtocolError, TransientEmptyOutputError): diff --git a/opencollab/adapters/llm/responses_provider.py b/opencollab/adapters/llm/responses_provider.py index 722d0dc8..eefc6401 100644 --- a/opencollab/adapters/llm/responses_provider.py +++ b/opencollab/adapters/llm/responses_provider.py @@ -19,6 +19,7 @@ from opencollab.adapters.llm._responses_output import ( _semantic_output_item as _semantic_output_item, ) +from opencollab.adapters.llm._transport_wait import _TransportInterruption, _wait_for_transport from opencollab.adapters.llm.errors import TransientProviderError from opencollab.adapters.llm.first_token import NOT_STREAMED, RESPONSES_STREAM, begin_attempt, mark_first_token from opencollab.adapters.llm.openai_provider import _FRAMEWORK_CONTROLLED_THINKING_FIELDS, _thinking_request_params @@ -257,7 +258,7 @@ async def _next_event(iterator: Any, timeout: float | None, *, stage: str) -> An try: if timeout is None: return await iterator.__anext__() - return await asyncio.wait_for(iterator.__anext__(), timeout=timeout) + return await _wait_for_transport(iterator.__anext__(), timeout) except asyncio.TimeoutError as exc: detail = "from the provider transport" if timeout is None else f"after {timeout:g}s" raise ResponsesStreamInterruptedError( @@ -294,21 +295,29 @@ def _error_message(error: Any) -> str: return str(error.get("message") or error.get("code") or error.get("reason") or "unknown Responses error") return str(error or "unknown Responses error") -def _raise_response_error(error: Any) -> None: +def _raise_response_error(error: Any, *, provider_model: str | None) -> None: message = _error_message(error) code = error.get("code") if isinstance(error, dict) else None param = error.get("param") if isinstance(error, dict) else None if code in _TRANSIENT_RESPONSE_CODES or any( fragment in message.lower() for fragment in _TRANSIENT_RESPONSE_MESSAGES ): - status_code = 429 if code == "rate_limit_exceeded" else 503 - raise ResponsesTransientEventError(message, code=code, status_code=status_code, param=param) + status_code = {"rate_limit_exceeded": 429, "upstream_timeout": 504}.get(code, 503) + raise ResponsesTransientEventError( + message, code=code, status_code=status_code, param=param, provider_model=provider_model, + ) status_code = 400 if code in {"context_length_exceeded", "string_above_max_length"} else None - raise ResponsesTerminalEventError(message, code=code, status_code=status_code, param=param) + raise ResponsesTerminalEventError( + message, code=code, status_code=status_code, param=param, provider_model=provider_model, + ) + +def _reported_response_model(response: Any) -> str | None: + model = getattr(response, "model", None) + return model if isinstance(model, str) and model else None def _response_model(response: Any) -> str: - actual_model = getattr(response, "model", None) - if not isinstance(actual_model, str) or not actual_model: + actual_model = _reported_response_model(response) + if actual_model is None: raise ResponsesProtocolError("terminal Responses object is missing model identity") return actual_model @@ -360,7 +369,9 @@ def _validate_terminal_response( if reason not in {"max_tokens", "max_output_tokens"}: message = f"incomplete Responses object has unsupported reason {reason!r}" if reason == "content_filter": - raise ResponsesTerminalEventError(message, code=reason) + raise ResponsesTerminalEventError( + message, code=reason, provider_model=_reported_response_model(response), + ) raise ResponsesProtocolError(message) finish_reason = "max_tokens" return _response_model(response), finish_reason @@ -369,11 +380,15 @@ def _handle_event(event: Any, state: _StreamState, expected_model: str | None = event_type = _event_type(event) if event_type in {"error", "response.failed"}: state.completed_response = getattr(event, "response", None) - _raise_response_error(_event_error_data(event)) + _raise_response_error( + _event_error_data(event), provider_model=_reported_response_model(state.completed_response), + ) if event_type == "response.incomplete": response = getattr(event, "response", None) if getattr(response, "status", None) != "incomplete": - raise ResponsesTerminalEventError(_error_message(_event_error_data(event))) + raise ResponsesTerminalEventError( + _error_message(_event_error_data(event)), provider_model=_reported_response_model(response), + ) state.completed_response = response _validate_terminal_response(response, expected_model) return True @@ -407,20 +422,24 @@ def _handle_event(event: Any, state: _StreamState, expected_model: str | None = raise ResponsesProtocolError(f"unsupported Responses event {event_type!r}") return False -async def _close_finished_stream(stream: Any) -> None: - """Release the socket without replacing a finished read or its original error. - - ``AsyncStream.close`` awaits the HTTP response close. A reset at that point - is not a failed generation: the terminal event is already in memory, and a - retryable close error would drop it and bill the request again. - """ +async def _close_finished_stream( + stream: Any, *, terminal_received: bool, timeout: float | None, +) -> None: close = getattr(stream, "close", None) if close is None: return try: result = close() if asyncio.iscoroutine(result): - await result + if terminal_received: + await _wait_for_transport(result, timeout, repeat_cancellation=False) + else: + await result + except asyncio.CancelledError: + # The request owner still propagates caller cancellation. A completed + # terminal event can be parsed and accounted after closing is interrupted. + if not terminal_received: + raise except Exception: logging.getLogger(__name__).debug("responses stream close failed", exc_info=True) @@ -467,7 +486,9 @@ async def _drain_stream( if _handle_event(event, state, expected_model): break finally: - await _close_finished_stream(stream) + await _close_finished_stream( + stream, terminal_received=state.completed_response is not None, timeout=idle_timeout, + ) if state.argument_fragments: _, finish_reason = _validate_terminal_response(state.completed_response, expected_model) output = _validated_response_items(to_plain_data(getattr(state.completed_response, "output", None))) @@ -496,7 +517,7 @@ async def _create_and_consume_stream( if first_event_timeout is None: event_stream = await client.responses.create(**kwargs) else: - event_stream = await asyncio.wait_for( + event_stream = await _wait_for_transport( client.responses.create(**kwargs), timeout=first_event_timeout, ) @@ -585,11 +606,15 @@ def _parse_stream( _merge_terminal_projection(streamed, terminal) for streamed, terminal in zip(state.output_items, final_items, strict=True) ] - content = "".join(_output_text(item) for item in state.output_items) or None reasoning = "\n".join(text for text in (_reasoning_text(item) for item in state.output_items) if text) or None + answer_parts: list[str] = [] + commentary_parts: list[str] = [] tool_calls: list[dict[str, Any]] = [] for item in state.output_items: - if item.get("type") == "function_call": + if item["type"] == "message": + parts = commentary_parts if item.get("phase") == "commentary" else answer_parts + parts.append(_output_text(item)) + elif item["type"] == "function_call": tool_calls.append( { "id": item["call_id"], @@ -597,6 +622,7 @@ def _parse_stream( "function": {"name": item.get("name"), "arguments": item["arguments"]}, } ) + content = "".join(answer_parts) or None if forced_text_tool is not None and tool_calls: raise ResponsesProtocolError("JSON Schema tool response unexpectedly contained function calls") if forced_text_tool is not None and finish_reason == "stop": @@ -614,18 +640,21 @@ def _parse_stream( except ValueError as exc: raise ResponsesProtocolError(str(exc)) from exc tool_calls = [tool_call] - state.output_items = [item for item in state.output_items if item.get("type") == "reasoning"] + state.output_items = [ + item for item in state.output_items + if item["type"] == "reasoning" or (item["type"] == "message" and item.get("phase") == "commentary") + ] state.output_items.append(synthetic_item) content = None usage = parse_responses_usage( state.completed_response, messages, - content, + "".join(commentary_parts) + (content or ""), tool_calls, tools, reasoning=reasoning, ) - content = rescue_empty_turn(content, tool_calls, reasoning) + content, content_from_reasoning = rescue_empty_turn(content, tool_calls, reasoning) if not content and not tool_calls and finish_reason != "max_tokens": raise ResponsesEmptyOutputError("response.completed contained no message or function call") return LLMResponse( @@ -634,6 +663,7 @@ def _parse_stream( usage=usage, finish_reason=("tool_calls" if tool_calls and finish_reason == "stop" else finish_reason), reasoning=reasoning, + content_from_reasoning=content_from_reasoning, provider_items=state.output_items, provider_model=actual_model, ) @@ -648,8 +678,8 @@ def parse_responses_response( ) -> LLMResponse: """Parse one terminal non-streaming Responses object.""" if getattr(response, "status", None) == "failed": - _response_model(response) - _raise_response_error(to_plain_data(getattr(response, "error", None))) + provider_model = _response_model(response) + _raise_response_error(to_plain_data(getattr(response, "error", None)), provider_model=provider_model) _validate_terminal_response(response, expected_model) state = _StreamState(completed_response=response) output = to_plain_data(getattr(response, "output", None)) @@ -690,6 +720,7 @@ async def complete_responses( stream: bool = True, before_attempt: Callable[[], int | None] | None = None, on_attempt_usage: Callable[[Usage], None] | None = None, + on_cancelled: Callable[[asyncio.CancelledError], None] | None = None, ) -> LLMResponse: """Run one locally replayable Responses request and require typed completion.""" external_isolation = os.environ.get("OPENCOLLAB_EXTERNAL_PROVIDER_ISOLATION") == "1" @@ -715,10 +746,21 @@ async def complete_responses( capabilities = model_capabilities(model) stream = stream and capabilities.supports_responses_streaming failed_usages: list[Usage | None] = [] + attempt_usage: Usage | None = None callback_timeout: asyncio.TimeoutError | None = None + round_interruption: _TransportInterruption | None = None + + def interrupt_round(exc: _TransportInterruption) -> None: + nonlocal round_interruption + round_interruption = exc + if on_cancelled is not None and isinstance(exc, asyncio.CancelledError): + on_cancelled(exc) def prepare_attempt() -> None: - nonlocal callback_timeout + nonlocal attempt_usage, callback_timeout + if round_interruption is not None: + raise round_interruption + attempt_usage = None try: if before_attempt is not None and (limit := before_attempt()) is not None: kwargs["max_output_tokens"] = limit @@ -729,13 +771,16 @@ def prepare_attempt() -> None: def report_failure(_exc: BaseException) -> None: nonlocal callback_timeout try: - if failed_usages and (usage := failed_usages[-1]) is not None and on_attempt_usage is not None: - on_attempt_usage(usage) + if attempt_usage is not None and on_attempt_usage is not None: + on_attempt_usage(attempt_usage) except asyncio.TimeoutError as exc: callback_timeout = exc raise + if round_interruption is not None: + raise round_interruption async def request_once() -> LLMResponse: + nonlocal attempt_usage terminal = None try: if not stream: @@ -764,8 +809,8 @@ async def request_once() -> LLMResponse: converted_tools, ) except BaseException as exc: - usage = _reported_responses_usage(terminal) or getattr(exc, "usage", None) - failed_usages.append(usage) + attempt_usage = _reported_responses_usage(terminal) or getattr(exc, "usage", None) + failed_usages.append(attempt_usage) raise if retry_budget is not None: @@ -774,7 +819,7 @@ async def bounded_request_once() -> LLMResponse: if round_timeout is None: return await request_once() try: - return await asyncio.wait_for(request_once(), timeout=round_timeout) + return await _wait_for_transport(request_once(), round_timeout) except asyncio.TimeoutError as exc: raise TransientProviderError(f"Responses request timeout after {round_timeout:g}s") from exc @@ -791,10 +836,9 @@ async def run() -> LLMResponse: try: try: - if round_timeout is None or retry_budget is not None: - response = await run() - else: - response = await asyncio.wait_for(run(), timeout=round_timeout) + response = await _wait_for_transport( + run(), round_timeout if retry_budget is None else None, on_interrupt=interrupt_round, + ) except asyncio.TimeoutError as exc: if exc is callback_timeout or round_timeout is None: raise diff --git a/opencollab/adapters/llm/retry.py b/opencollab/adapters/llm/retry.py index a72f7e01..f12ec930 100644 --- a/opencollab/adapters/llm/retry.py +++ b/opencollab/adapters/llm/retry.py @@ -15,11 +15,13 @@ from typing import Any, ParamSpec, TypeVar from opencollab.adapters.llm.errors import TransientProviderError, is_context_overflow_error +from opencollab.application._session_run_usage import _save_native_retry_usage +from opencollab.application.ports import ProviderTerminalEventError # HTTP statuses worth retrying: timeouts, conflicts, rate limits, server errors. -RETRYABLE_STATUS_CODES = {408, 409, 429, 500, 502, 503, 504, 529} +RETRYABLE_STATUS_CODES = {408, 409, 429, 500, 502, 503, 504, 522, 529} -# Error-message fragments that signal a transient failure when no status is set. +# Transient failure descriptions for statusless errors and gateway responses. RETRYABLE_MESSAGE_FRAGMENTS = ( "rate limit", "429", @@ -83,7 +85,7 @@ class RetryTimeBudget: """Shared retry-only time allowance for one agent or workflow run.""" total_seconds: float - remaining_seconds: float = field(init=False) + _balance_seconds: float = field(init=False, repr=False) def __post_init__(self) -> None: if ( @@ -92,15 +94,32 @@ def __post_init__(self) -> None: or self.total_seconds < 0 ): raise ValueError("retry time budget must be a finite non-negative number") - self.remaining_seconds = float(self.total_seconds) + self._balance_seconds = float(self.total_seconds) + + @property + def remaining_seconds(self) -> float: + return max(0.0, self._balance_seconds) def consume(self, seconds: float) -> bool: """Consume retry time atomically between event-loop suspension points.""" seconds = max(0.0, seconds) - if seconds > self.remaining_seconds: - self.remaining_seconds = 0.0 + fits = seconds <= self._balance_seconds + # Retain overruns when another caller has reserved a wait it can still cancel. + self._balance_seconds -= seconds + return fits + + async def _wait_for_retry(self, delay: float) -> bool: + if delay > self.remaining_seconds or not self.consume(delay): return False - self.remaining_seconds -= seconds + started = None + try: + await _save_native_retry_usage() + started = time.monotonic() + await asyncio.sleep(delay) + except BaseException: + elapsed = 0.0 if started is None else max(0.0, time.monotonic() - started) + self._balance_seconds += max(0.0, delay - elapsed) + raise return True _P = ParamSpec("_P") @@ -173,9 +192,11 @@ async def with_retry( MAX_EXPONENTIAL_RETRY_DELAY_SECONDS, ) delay = max(0.0, base + random.uniform(0.0, RETRY_JITTER_MAX_SECONDS)) - if retry_time_budget is not None and not retry_time_budget.consume(delay): + if retry_time_budget is None: + await _save_native_retry_usage() + await asyncio.sleep(delay) + elif not await retry_time_budget._wait_for_retry(delay): raise - await asyncio.sleep(delay) attempt += 1 def _http_status_of(error: BaseException) -> int | None: @@ -190,46 +211,37 @@ def _http_status_of(error: BaseException) -> int | None: return None def is_retryable_error(error: Exception) -> bool: - """Whether ``error`` looks transient (retryable status code or message).""" - if isinstance(error, TransientProviderError): - return True - # The session handles context overflow by compacting before retry. Exclude # it here even when its message contains a transient-error fragment. if is_context_overflow_error(error): return False - status = getattr(error, "status_code", None) - if status in RETRYABLE_STATUS_CODES: - return True - - response = getattr(error, "response", None) - if response is not None: - resp_status = getattr(response, "status_code", None) - if resp_status in RETRYABLE_STATUS_CODES: - return True - - msg = str(error).lower() - if any(k in msg for k in RETRYABLE_MESSAGE_FRAGMENTS): - return True - - # Follow the exception cause/context chain because SDK wrappers often - # preserve the useful transport error only as ``__cause__``. + retryable_hint = False current: BaseException | None = error seen: set[int] = set() - gateway_refusal = False - has_http_status = False while current is not None and id(current) not in seen: seen.add(id(current)) - has_http_status = has_http_status or _http_status_of(current) is not None + # Status and typed terminal errors take precedence over wrapper text. + status = _http_status_of(current) + if status is not None: + if status in RETRYABLE_STATUS_CODES: + return True + if status in {520, 521, 524}: + message = str(current).lower() + return any(fragment in message for fragment in RETRYABLE_MESSAGE_FRAGMENTS) + return False + if isinstance(current, TransientProviderError): + return True + if isinstance(current, ProviderTerminalEventError): + return False class_name = type(current).__name__.lower() if class_name in _TRANSIENT_TRANSPORT_CLASS_NAMES: - return True + retryable_hint = True message = str(current).lower() if class_name in _STATUSLESS_PROVIDER_ERROR_CLASS_NAMES and any( fragment in message for fragment in _TRANSIENT_GATEWAY_MESSAGE_FRAGMENTS ): - gateway_refusal = True + retryable_hint = True if any( fragment in message for fragment in _TRANSIENT_TRANSPORT_MESSAGE_FRAGMENTS @@ -242,22 +254,32 @@ def is_retryable_error(error: Exception) -> bool: "remoteprotocolerror", "timeouterror", }: - return True + retryable_hint = True current = current.__cause__ or current.__context__ - # A wrapper or cause carrying a status also excludes the gateway rule. - return gateway_refusal and not has_http_status + message = str(error).lower() + return retryable_hint or any(fragment in message for fragment in RETRYABLE_MESSAGE_FRAGMENTS) def extract_retry_after_seconds( error: Exception, *, now: datetime | None = None, ) -> float | None: - """The Retry-After header value from ``error``'s response, if present.""" + """Read the provider's retry delay in seconds.""" response = getattr(error, "response", None) headers = getattr(response, "headers", None) if response is not None else None if not headers: return None + milliseconds = headers.get("Retry-After-Ms") or headers.get("retry-after-ms") + if milliseconds is not None: + try: + seconds = float(milliseconds) / 1000 + except (TypeError, ValueError, OverflowError): + pass + else: + if math.isfinite(seconds) and seconds >= 0: + return min(seconds, MAX_RETRY_AFTER_SECONDS) + value = headers.get("Retry-After") or headers.get("retry-after") if value is None: return None diff --git a/opencollab/adapters/llm/types.py b/opencollab/adapters/llm/types.py index f066a46d..a15cbe1c 100644 --- a/opencollab/adapters/llm/types.py +++ b/opencollab/adapters/llm/types.py @@ -94,6 +94,7 @@ class LLMResponse: # Transport timing set by ``LLMClient.complete`` on every provider path. # ``None`` identifies responses built outside the client. transport_timing: dict[str, Any] | None = None + content_from_reasoning: bool = False def to_plain_data(value: Any) -> Any: """Convert SDK model objects into JSON-compatible Python values.""" @@ -126,19 +127,14 @@ def rescue_empty_turn( content: str | None, tool_calls: list[dict[str, Any]], reasoning: str | None, -) -> str | None: - """Use reasoning text when a completion contains neither answer nor tool call. - - Providers separate ``reasoning`` from ``content``. Falling back keeps an - empty answer from ending the session. Preserve ``content`` when an answer - or tool call already exists. - """ +) -> tuple[str | None, bool]: + """Return display text and whether it came from the reasoning fallback.""" if ( (content is None or not content.strip()) and not tool_calls ): - return reasoning - return content + return reasoning, reasoning is not None + return content, False @dataclass(frozen=True) class ModelCapabilities: diff --git a/opencollab/adapters/safe_files.py b/opencollab/adapters/safe_files.py index ec68c755..4f927c4a 100644 --- a/opencollab/adapters/safe_files.py +++ b/opencollab/adapters/safe_files.py @@ -253,6 +253,7 @@ def write_regular_file_atomic( mode: int = 0o600, context: str = "atomic output", create_only: bool = False, + on_replace: Callable[[], None] | None = None, ) -> None: """Write a bounded temporary and publish it with one atomic rename.""" target = _absolute(path) @@ -283,6 +284,8 @@ def write_regular_file_atomic( os.unlink(temporary) else: os.replace(temporary, target) + if on_replace is not None: + on_replace() _fsync_directory(target.parent) finally: if fd >= 0: diff --git a/opencollab/adapters/session_environments.py b/opencollab/adapters/session_environments.py index 1b0373fc..ee91c038 100644 --- a/opencollab/adapters/session_environments.py +++ b/opencollab/adapters/session_environments.py @@ -2,17 +2,29 @@ import asyncio from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass, field from functools import partial +from graphlib import CycleError, TopologicalSorter from typing import Any from opencollab.adapters.docker_isolation import DockerIsolationPool from opencollab.adapters.env import LocalEnvironment +from opencollab.adapters.vm_isolation import VMIsolationPool from opencollab.adapters.worktree_pool import WorktreePool from opencollab.application.async_timeout import await_owned_operation from opencollab.application.isolation import isolation_name from opencollab.application.ports import EnvironmentPort, WorktreePoolPort +@dataclass +class _EnvironmentOwner: + environment: EnvironmentPort + pool: WorktreePoolPort + references: int = 0 + lock: asyncio.Lock = field(default_factory=asyncio.Lock) + sources: dict[int, EnvironmentPort] = field(default_factory=dict) + + class SessionEnvironmentPool: """Own per-run strategy pools; injected factories create a fresh pool per strategy.""" @@ -37,9 +49,9 @@ def __init__( self._options = dict(owned_save_dir=owned_save_dir, enable_adoption=enable_adoption, owned_output_paths=owned_output_paths) self._pools: dict[str, WorktreePoolPort] = {} - self._owners: dict[int, tuple[EnvironmentPort, WorktreePoolPort]] = {} - self._references: dict[int, int] = {} + self._owners: dict[int, _EnvironmentOwner] = {} self._lifecycle = asyncio.Condition() + self._release_lock = asyncio.Lock() self._inflight = 0 self._closed = False for name in (self._default, *self._roles.values()): @@ -91,6 +103,12 @@ def _pool(self, name: str, source: EnvironmentPort) -> WorktreePoolPort: self._pools[key] = pool return self._pools[key] + def _borrowable_owner(self, env: EnvironmentPort) -> _EnvironmentOwner | None: + owner = self._owners.get(id(env)) + if (owner is not None and owner.references == 0) or getattr(env, "revoked", False): + raise RuntimeError("session environment is unavailable for acquisition") + return owner + async def acquire( self, role: str, *, source: EnvironmentPort | None = None, isolation: str | bool | None = None, @@ -102,11 +120,17 @@ async def acquire( try: name = isolation_name(isolation, default=self._roles.get(role) or self._default) base = self._source if source is None else source + self._borrowable_owner(base) pool = self._pool(name, base) env = await pool.acquire(role, source=base) - if env is not base or id(env) in self._owners: - self._owners.setdefault(id(env), (env, pool)) - self._references[id(env)] = self._references.get(id(env), 0) + 1 + identity = id(env) + owner = self._borrowable_owner(env) + if env is not base: + if owner is None: + owner = self._owners[identity] = _EnvironmentOwner(env, pool) + owner.sources[id(base)] = base + if owner is not None: + owner.references += 1 if self._closed: await self.release_env(env) raise RuntimeError("session environment pool closed during acquisition") @@ -136,27 +160,67 @@ async def adopt_captured(self, patch, physical_paths): await self._delivery_pool().adopt_captured(patch, physical_paths) async def release_env(self, env: EnvironmentPort) -> None: - owner = self._owners.get(id(env)) - if owner is not None: - if self._references[id(env)] > 1: - self._references[id(env)] -= 1 + await self._release_env(env) + + async def _release_env(self, env: EnvironmentPort, *, all_references: bool = False) -> None: + identity = id(env) + owner = self._owners.get(identity) + if owner is None: + return + async with owner.lock: + if self._owners.get(identity) is not owner: + return + if not all_references and owner.references > 1: + owner.references -= 1 return - await owner[1].release_env(env) - self._owners.pop(id(env), None) - self._references.pop(id(env), None) + # Keep failed cleanups available for retry without lending the workspace again. + owner.references = 0 + await owner.pool.release_env(env) + del self._owners[identity] async def release(self) -> None: self._closed = True - await await_owned_operation(self._release(), propagate_cancellation=True) + # A VM capacity wait needs the shutdown signal before we drain acquisitions. + for pool in self._pools.values(): + if isinstance(pool, VMIsolationPool): + pool.stop_acquiring() + async with self._release_lock: + await await_owned_operation(self._release(), propagate_cancellation=True) async def _release(self) -> None: async with self._lifecycle: while self._inflight: await self._lifecycle.wait() - # A later environment may use an earlier strategy's workspace as its source. - for env, _pool in reversed(tuple(self._owners.values())): - self._references[id(env)] = 1 - await self.release_env(env) + # A reused environment can depend on a workspace acquired after it. + owners = dict(reversed(self._owners.items())) + order = TopologicalSorter({identity: () for identity in owners}) + for identity, owner in owners.items(): + for source in owner.sources: + if source in owners: + order.add(source, identity) + + retained_sources: set[int] = set() + first_failure: Exception | None = None + try: + order.prepare() + except CycleError: + first_failure = RuntimeError("session environment cleanup has cyclic source dependencies") + while order.is_active(): + ready = order.get_ready() + for identity in ready: + owner = owners[identity] + if identity not in retained_sources: + try: + await self._release_env(owner.environment, all_references=True) + except Exception as exc: + if first_failure is None: + first_failure = exc + else: + continue + retained_sources.update(owner.sources) + order.done(*ready) + if first_failure is not None: + raise first_failure failures = [] for key, pool in reversed(tuple(self._pools.items())): try: diff --git a/opencollab/adapters/storage.py b/opencollab/adapters/storage.py index 83c040f0..ba1044db 100644 --- a/opencollab/adapters/storage.py +++ b/opencollab/adapters/storage.py @@ -3,9 +3,10 @@ import errno import fcntl import json +import logging import os import threading -from collections.abc import Iterator +from collections.abc import Callable, Iterator from contextlib import ExitStack, contextmanager from dataclasses import dataclass, field from typing import Any, BinaryIO @@ -20,7 +21,12 @@ write_regular_bytes_atomic, write_regular_file_atomic, ) -from opencollab.application.ports import SnapshotCapacityError, SnapshotSequenceConflict +from opencollab.application.ports import ( + _AUTOSAVE_EXPORT_SOURCE_SEQUENCE, + SnapshotCapacityError, + SnapshotSequenceConflict, + _checkpoint_publication, +) from opencollab.application.session_snapshot import decode_anthropic_history from opencollab.domain.session import same_snapshot_value @@ -30,7 +36,35 @@ _AUTOSAVE_JOURNAL_VERSION = 1 _AUTOSAVE_JOURNAL_SUFFIX = ".journal" _AUTOSAVE_JOURNAL_LOCK_SUFFIX = ".lock" +_AUTOSAVE_OWNERSHIP_LOCK_SUFFIX = ".autosave.lock" _JOURNAL_LOCK_TIMEOUT_SECONDS = 10.0 +logger = logging.getLogger(__name__) + +_FileRevision = tuple[int, int, int, int, int] +_AutosaveFileRevisions = tuple[_FileRevision | None, _FileRevision | None] + + +@dataclass(frozen=True) +class _AutosaveCursor: + path: str + revisions: _AutosaveFileRevisions + sequence: int + + +def _file_revision(info: os.stat_result) -> _FileRevision: + return info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns + + +def _regular_file_revision(path: str) -> _FileRevision | None: + try: + fd = _open_regular_read(path) + except FileNotFoundError: + return None + try: + return _file_revision(os.fstat(fd)) + finally: + os.close(fd) + @dataclass class _JournalLockEntry: @@ -145,6 +179,58 @@ def write(self, text: str) -> int: class SessionStore: allowed_roles = {"system", "developer", "user", "assistant", "tool"} + _autosave_cursor: _AutosaveCursor | None = None + + def try_autosave_lock( + self, path: str, *, expected_sequence: int | None = None, + ) -> Callable[[], None] | None: + # Keep the sidecar inode stable while snapshots and journals are replaced. + lock_path = f"{path}{_AUTOSAVE_OWNERSHIP_LOCK_SUFFIX}" + handle = open_regular_text_append(lock_path) + try: + fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + except BaseException as exc: + handle.close() + if isinstance(exc, OSError) and exc.errno in {errno.EACCES, errno.EAGAIN, errno.EWOULDBLOCK}: + return None + raise + try: + if expected_sequence is not None: + with _journal_operation_lock(path): + sequence = self._autosave_sequence_for_ownership(path) + if sequence > expected_sequence: + raise SnapshotSequenceConflict( + f"refusing stale autosave sequence {expected_sequence}; " + f"persisted sequence {sequence} is newer" + ) + except BaseException: + handle.close() + raise + return handle.close + + def _autosave_file_revisions(self, path: str) -> _AutosaveFileRevisions: + return _regular_file_revision(path), _regular_file_revision(self._journal_path(path)) + + def _autosave_sequence_for_ownership(self, path: str) -> int: + cursor = self._autosave_cursor + if cursor is not None and cursor.path == os.path.abspath(path): + try: + if cursor.revisions == self._autosave_file_revisions(path): + return cursor.sequence + except OSError: + pass + sequence = self._newest_persisted_sequence(path) + self._remember_autosave_cursor(path, sequence) + return sequence + + def _remember_autosave_cursor(self, path: str, sequence: int) -> None: + # The caller holds the journal lock across the read or publication. + try: + key = os.path.abspath(path) + revisions = self._autosave_file_revisions(path) + except OSError: + return + self._autosave_cursor = _AutosaveCursor(key, revisions, sequence) def has_snapshot(self, path: str) -> bool: """Return whether a base or recoverable journal sidecar is present.""" @@ -161,14 +247,25 @@ def save( obj = {**(meta or {}), "messages": messages} with _journal_operation_lock(path): records = self._read_journal_records(path) + destination_sequence = None if records: - # A full replacement supersedes every durable delta. Publish - # its cursor with the base before clearing the sidecar, so a - # crash between these writes cannot replay an older state. - obj[_AUTOSAVE_SEQUENCE_KEY] = self._newest_persisted_sequence(path) + 1 - self._atomic_json_write(path, obj) + destination_sequence = self._newest_persisted_sequence(path) + elif _AUTOSAVE_SEQUENCE_KEY in obj: + try: + destination_sequence = self._persisted_base_sequence(path) + except ValueError: + # An explicit export may replace a non-snapshot file. + destination_sequence = None + if destination_sequence is not None: + # An export supersedes the destination even after journal compaction. + source_sequence = self._snapshot_sequence(obj) + if destination_sequence >= source_sequence and _AUTOSAVE_SEQUENCE_KEY in obj: + obj.setdefault(_AUTOSAVE_EXPORT_SOURCE_SEQUENCE, source_sequence) + obj[_AUTOSAVE_SEQUENCE_KEY] = max(source_sequence, destination_sequence + 1) if records: - write_regular_bytes_atomic(self._journal_path(path), b"", max_bytes=0) + self._publish_checkpoint_unlocked(path, obj, defer_journal_reset=True) + else: + self._write_snapshot(path, obj) def save_manifest(self, path: str, manifest: dict[str, Any]) -> None: self._ensure_parent(path) @@ -181,12 +278,17 @@ def load_snapshot(self, path: str, system_prompt: str) -> dict[str, Any]: # observe the old base together with the already-compacted journal (or # vice versa). with _journal_operation_lock(path, reading=True) as journal_locked: - return self._load_snapshot_unlocked( + snapshot = self._load_snapshot_unlocked( path, system_prompt, read_journal=journal_locked, ) + if journal_locked: + self._remember_autosave_cursor(path, self._snapshot_sequence(snapshot)) + return snapshot def _load_snapshot_unlocked( - self, path: str, fallback_system_prompt: str | None, *, read_journal: bool = True, + self, path: str, fallback_system_prompt: str | None, *, + read_journal: bool = True, + pending_record: dict[str, Any] | None = None, ) -> dict[str, Any]: """Load a locked snapshot or a standalone read-only export.""" try: @@ -194,6 +296,8 @@ def _load_snapshot_unlocked( except FileNotFoundError: text = None records = self._read_journal_records(path) if read_journal else [] + if pending_record is not None: + records.append(pending_record) if text is None and not records: raise FileNotFoundError(path) @@ -221,11 +325,23 @@ def _load_snapshot_unlocked( sequence = self._snapshot_sequence(snapshot) for record in records: record_sequence = self._record_integer(record, "sequence", minimum=1) + retry_snapshot = None if record_sequence <= sequence: - continue + if record is not pending_record: + continue + if record_sequence < sequence: + raise SnapshotSequenceConflict( + f"refusing stale autosave sequence {record_sequence}; " + f"persisted sequence is {sequence}" + ) + retry_snapshot = {**snapshot, "messages": messages} replace_from = self._record_integer(record, "replace_from", minimum=0) message_count = self._record_integer(record, "message_count", minimum=0) if replace_from > len(messages): + if retry_snapshot is not None: + raise SnapshotSequenceConflict( + f"refusing conflicting autosave sequence {record_sequence}" + ) raise ValueError( "Invalid autosave journal: replace_from exceeds restored messages" ) @@ -277,6 +393,12 @@ def _load_snapshot_unlocked( **restored_meta, _AUTOSAVE_SEQUENCE_KEY: record_sequence, } + if retry_snapshot is not None and not self._checkpoint_states_equal( + retry_snapshot, {**snapshot, "messages": messages}, + ): + raise SnapshotSequenceConflict( + f"refusing conflicting autosave sequence {record_sequence}" + ) sequence = record_sequence self._validate_messages(messages) @@ -426,13 +548,27 @@ def _validate_tool_calls( ) def _parse_document(self, text: str) -> dict[str, Any] | list[dict[str, Any]]: - if not text.strip(): + document = text.strip() + if not document: return [] try: obj = json.loads(text) except json.JSONDecodeError: return self._parse_jsonl(text) if isinstance(obj, dict): + # A single JSONL message also parses as one JSON object. + snapshot_fields = { + "messages", "snapshot_version", "session_state", "pending_messages", + "aid", "run_id", "model", _AUTOSAVE_SEQUENCE_KEY, _AUTOSAVE_EXPORT_SOURCE_SEQUENCE, + } + role = obj.get("role") + if ( + "\n" not in document + and isinstance(role, str) and role in self.allowed_roles + and ("content" in obj or (role == "assistant" and "tool_calls" in obj)) + and obj.keys().isdisjoint(snapshot_fields) + ): + return [obj] return obj if isinstance(obj, list): return obj @@ -601,21 +737,46 @@ def checkpoint_snapshot( if persisted_sequence == sequence > 0: # A peer can own this sequence in either the base or the journal. persisted = self._load_snapshot_unlocked(path, "") + source_sequence = obj.get(_AUTOSAVE_EXPORT_SOURCE_SEQUENCE) + if ( + _AUTOSAVE_EXPORT_SOURCE_SEQUENCE not in persisted + and type(source_sequence) is int + and source_sequence == sequence - 1 + ): + # Older restores left this provenance implicit in their local cursor. + persisted[_AUTOSAVE_EXPORT_SOURCE_SEQUENCE] = source_sequence if not self._checkpoint_states_equal(persisted, obj): source = "journal" if same_sequence_records else "snapshot" raise SnapshotSequenceConflict( "refusing checkpoint sequence " f"{sequence}; it conflicts with persisted {source} state" ) - try: - self._atomic_json_write(path, obj) - except SnapshotCapacityError: - self._atomic_json_write(path, obj, indent=None) - write_regular_bytes_atomic( - self._journal_path(path), - b"", - max_bytes=0, - ) + self._publish_checkpoint_unlocked(path, obj) + + def _publish_checkpoint_unlocked( + self, path: str, snapshot: dict[str, Any], *, defer_journal_reset: bool = False, + ) -> None: + publication = _checkpoint_publication.get() + if publication is not None and (publication.path != path or defer_journal_reset): + publication = None + self._write_snapshot(path, snapshot) + if publication is not None: + publication.synced = True + journal_path = self._journal_path(path) + try: + write_regular_bytes_atomic(journal_path, b"", max_bytes=0) + except OSError as exc: + if not (defer_journal_reset or publication is not None and publication.defer_journal_reset): + raise + # The synced snapshot already supersedes every journal record. + logger.warning("could not compact covered session journal %s: %s", journal_path, exc) + self._remember_autosave_cursor(path, snapshot[_AUTOSAVE_SEQUENCE_KEY]) + + def _write_snapshot(self, path: str, snapshot: dict[str, Any]) -> None: + try: + self._atomic_json_write(path, snapshot) + except SnapshotCapacityError: + self._atomic_json_write(path, snapshot, indent=None) @staticmethod def _journal_path(path: str) -> str: @@ -634,14 +795,18 @@ def _encode_journal_record(record: dict[str, Any]) -> str: def _append_journal_record(self, path: str, record: dict[str, Any]) -> None: with _journal_operation_lock(path): - self._append_journal_record_unlocked(path, record) + try: + self._append_journal_record_unlocked(path, record) + except SnapshotCapacityError: + snapshot = self._load_snapshot_unlocked(path, None, pending_record=record) + self._publish_checkpoint_unlocked(path, snapshot, defer_journal_reset=True) def _append_journal_record_unlocked(self, path: str, record: dict[str, Any]) -> None: journal_path = self._journal_path(path) payload = self._encode_journal_record(record) payload_size = len(payload.encode("utf-8")) if payload_size > MAX_SESSION_SNAPSHOT_BYTES: - raise ValueError( + raise SnapshotCapacityError( "autosave journal record exceeds " f"{MAX_SESSION_SNAPSHOT_BYTES} UTF-8 bytes while writing: " f"{journal_path}" @@ -649,7 +814,8 @@ def _append_journal_record_unlocked(self, path: str, record: dict[str, Any]) -> append_start: int | None = None try: with open_regular_text_append(journal_path, readable=True) as handle: - current_size = os.fstat(handle.fileno()).st_size + before_append = os.fstat(handle.fileno()) + current_size = before_append.st_size complete_size = self._complete_journal_size( handle.fileno(), current_size, @@ -658,7 +824,7 @@ def _append_journal_record_unlocked(self, path: str, record: dict[str, Any]) -> os.ftruncate(handle.fileno(), complete_size) current_size = complete_size if current_size + payload_size > MAX_SESSION_SNAPSHOT_BYTES: - raise ValueError( + raise SnapshotCapacityError( "autosave journal exceeds " f"{MAX_SESSION_SNAPSHOT_BYTES} UTF-8 bytes while writing: " f"{journal_path}" @@ -667,6 +833,7 @@ def _append_journal_record_unlocked(self, path: str, record: dict[str, Any]) -> write_locked_text(handle, payload) handle.flush() os.fsync(handle.fileno()) + self._advance_autosave_cursor(path, handle.fileno(), before_append, record["sequence"]) except BaseException as append_error: if append_start is not None: try: @@ -679,6 +846,26 @@ def _append_journal_record_unlocked(self, path: str, record: dict[str, Any]) -> raise append_error from rollback_error raise + def _advance_autosave_cursor( + self, path: str, fd: int, before_append: os.stat_result, sequence: int, + ) -> None: + cursor = self._autosave_cursor + if cursor is None or cursor.path != os.path.abspath(path): + return + snapshot_revision, journal_revision = cursor.revisions + if journal_revision != _file_revision(before_append) and not ( + journal_revision is None and before_append.st_size == 0 + ): + return + try: + journal_revision = _file_revision(os.fstat(fd)) + except OSError: + return + # A late append can leave an older record after the current cursor. + self._autosave_cursor = _AutosaveCursor( + cursor.path, (snapshot_revision, journal_revision), max(cursor.sequence, sequence), + ) + @staticmethod def _complete_journal_size(fd: int, size: int) -> int: """Find the end of the last complete line using bounded tail reads.""" @@ -731,16 +918,18 @@ def _read_journal_records(self, path: str) -> list[dict[str, Any]]: records.append(record) return records - def _newest_persisted_sequence(self, path: str) -> int: - newest = 0 + def _persisted_base_sequence(self, path: str) -> int | None: try: text = self._read_snapshot_text(path) except FileNotFoundError: - pass - else: - parsed = self._parse_document(text) - if isinstance(parsed, dict): - newest = self._snapshot_sequence(parsed) + return None + parsed = self._parse_document(text) + if isinstance(parsed, dict) and _AUTOSAVE_SEQUENCE_KEY in parsed: + return self._snapshot_sequence(parsed) + return None + + def _newest_persisted_sequence(self, path: str) -> int: + newest = self._persisted_base_sequence(path) or 0 for record in self._read_journal_records(path): newest = max( newest, @@ -824,6 +1013,12 @@ def _read_snapshot_text(path: str) -> str: @staticmethod def _atomic_json_write(path: str, value: Any, *, indent: int | None = 2) -> None: """Durably replace one JSON file without exposing a partial snapshot.""" + publication = _checkpoint_publication.get() + + def mark_replaced() -> None: + if publication is not None and publication.path == path: + publication.visible = True + def serialize(handle: BinaryIO) -> None: writer = _BoundedUTF8Writer(handle, path=path) if indent is None: @@ -836,4 +1031,5 @@ def serialize(handle: BinaryIO) -> None: serialize, max_bytes=MAX_SESSION_SNAPSHOT_BYTES, context="session snapshot", + on_replace=mark_replaced if publication is not None else None, ) diff --git a/opencollab/adapters/tools/fs.py b/opencollab/adapters/tools/fs.py index 0d309823..d6115952 100644 --- a/opencollab/adapters/tools/fs.py +++ b/opencollab/adapters/tools/fs.py @@ -144,6 +144,8 @@ async def execute_with_runtime( total_description = "total not scanned" else: total_description = f"{window.total_lines} lines total" + if not numbered: + return f"File: {params['path']} ({total_description}, no lines at or after offset {window.start_line})" header = ( f"File: {params['path']} ({total_description}, " f"showing {start + 1}-{end})" @@ -156,9 +158,13 @@ async def execute_with_runtime( "numbered line requires a larger max_read_chars setting. Use grep " "to locate relevant text." ) + if window.total_lines is not None: + has_more = end < window.total_lines + elif has_more: + return body + f"\n... Continue with offset={end + 1} to read any later lines." # Loud footer when lines remain below the shown range — otherwise a # default read silently stops at the limit and the tail is lost. - if has_more and not single_line_truncated: + if has_more: if window.total_lines is None: remaining = "more lines below (total not scanned)" else: diff --git a/opencollab/adapters/vm_isolation.py b/opencollab/adapters/vm_isolation.py index 7ba48cbd..988a854e 100644 --- a/opencollab/adapters/vm_isolation.py +++ b/opencollab/adapters/vm_isolation.py @@ -275,15 +275,21 @@ async def release_env(self, env: Environment) -> None: await await_owned_operation(self._export(env, owner), propagate_cancellation=True) assert owner.pool is not None await await_owned_operation(owner.pool.release_env(env), propagate_cancellation=True) + if owner is not self._group and not any( + value is owner and environment is not env for environment, value in self._leases.items() + ): + await await_owned_operation(self._cleanup_owner(owner), propagate_cancellation=True) + return self._leases.pop(env) self._exports.pop(env) self._exported.discard(env) - if owner is not self._group and owner not in self._leases.values(): - await await_owned_operation(self._cleanup_owner(owner), propagate_cancellation=True) - async def release(self) -> None: + def stop_acquiring(self) -> None: self._closed = True self._closing.set() + + async def release(self) -> None: + self.stop_acquiring() await await_owned_operation(self._release_owned(), propagate_cancellation=True) async def _release_owned(self) -> None: diff --git a/opencollab/application/_anthropic_history.py b/opencollab/application/_anthropic_history.py index 1c6f9980..ce1c3a2e 100644 --- a/opencollab/application/_anthropic_history.py +++ b/opencollab/application/_anthropic_history.py @@ -20,6 +20,7 @@ from opencollab.domain.session import SessionState, same_snapshot_value _THINKING_TYPES = frozenset({"thinking", "redacted_thinking"}) +_RUN_FINAL_PROMPT_FIELD = "_opencollab_run_final_prompt" def _strip_anthropic_thinking(messages: list[dict[str, Any]], start: int = 0) -> list[dict[str, Any]]: """Remove a suffix of native thinking while retaining text and tool blocks.""" @@ -35,13 +36,28 @@ def _strip_anthropic_thinking(messages: list[dict[str, Any]], start: int = 0) -> result[index] = {**message, "provider_state": {**state, "anthropic_content": kept}} return result +def _is_run_final_prompt(message: dict) -> bool: + return ( + message.get(_RUN_FINAL_PROMPT_FIELD) is True + and message.get("role") == "system" + and not message.get("compacted") + ) + +def _anthropic_system_instructions(messages: list[dict]) -> list[dict]: + return [ + message for message in messages + if message.get("role") in {"system", "developer"} and not message.get("compacted") + ] + def _edited_anthropic_history(before: list[dict], after: list[dict]) -> list[dict]: """Drop thinking bound to a changed prefix, keeping the valid older run.""" - before_system = [message for message in before if message.get("role") == "system" and not message.get("compacted")] - after_system = [message for message in after if message.get("role") == "system" and not message.get("compacted")] - if not same_snapshot_value(before_system, after_system): + if not same_snapshot_value(_anthropic_system_instructions(before), _anthropic_system_instructions(after)): return _strip_anthropic_thinking(after) - for index, (old, new) in enumerate(zip(before, after)): + # The provider hoists global instructions. Renewing the same final prompt can move + # its row past new tool results while leaving the native prefix intact. + old_prefix = (message for message in before if not _is_run_final_prompt(message)) + new_prefix = ((index, message) for index, message in enumerate(after) if not _is_run_final_prompt(message)) + for old, (index, new) in zip(old_prefix, new_prefix): if not same_snapshot_value(old, new): return _strip_anthropic_thinking(after, index) return after @@ -625,13 +641,26 @@ def projected_groups() -> Iterator[tuple[int, int, list[list[dict]]]]: rebased.extend(chain.from_iterable(current[taken:])) return _edited_anthropic_history(view, rebased), retained -def _anthropic_history_input(state: SessionState) -> list[dict]: +def _anthropic_history_input(state: SessionState, *, include_final_prompt: bool = True) -> list[dict]: history = state.anthropic_history if history is None: return state.messages if _anthropic_source_changed(state): - return copy.deepcopy(_rebase_anthropic_history(state)[0]) - return copy.deepcopy([*history["messages"], *state.messages[history["source_count"]:]]) + messages, _snips = _rebase_anthropic_history(state) + else: + messages = [*history["messages"], *state.messages[history["source_count"]:]] + if not include_final_prompt: + # Retain the previous sent prompt for native prefix comparison only. + messages = [message for message in messages if message.get(_RUN_FINAL_PROMPT_FIELD) is not True] + return copy.deepcopy(messages) + +def _anthropic_completion_messages(messages: list[dict]) -> list[dict]: + """Project the kept history into model-port messages.""" + return [ + {key: value for key, value in message.items() if key != _RUN_FINAL_PROMPT_FIELD} + if _RUN_FINAL_PROMPT_FIELD in message else message + for message in messages + ] def _remember_anthropic_history( state: SessionState, messages: list[dict], tools: list[dict] | None, diff --git a/opencollab/application/_scheduler_cleanup.py b/opencollab/application/_scheduler_cleanup.py index 29063672..f5bfc186 100644 --- a/opencollab/application/_scheduler_cleanup.py +++ b/opencollab/application/_scheduler_cleanup.py @@ -16,8 +16,10 @@ ) from opencollab.application.session_lifecycle import close_session_resources from opencollab.domain.pending import PendingRowError, RowStatus +from opencollab.domain.session import SessionPhase logger = logging.getLogger(__name__) +_CLEANUP_CANCELLED_WORK = "Error: scheduler cleanup cancelled delegated work" class _CleanupTimeout(Enum): @@ -34,6 +36,9 @@ def _unique_task_owners(*groups: Any) -> list[tuple[int, asyncio.Task[Any]]]: return owners class SchedulerCleanupMixin: + def request_shutdown(self) -> None: + self._shutting_down = True + async def cleanup( self, *, @@ -71,11 +76,21 @@ def _validate_cleanup_timeout(value: object) -> float: return timeout async def _cleanup_impl(self, *, timeout: float) -> None: - self._shutting_down = True + self.request_shutdown() failures: list[str] = [] persistence_sessions = tuple(self._sessions.values()) startup_aids = set(self._startup_tasks) origins = {**self._startup_origin, **self._spawn_origin} + # A cancelled recovery waiter can mark its suspended turn stopped before teardown. + suspended_aids = { + aid for aid, scb in self.table.entries.items() + if scb.state.phase is SessionPhase.AWAITING_EVENTS + or ( + scb.state.phase is SessionPhase.STOPPED + and scb.state.terminal_reason == _CLEANUP_CANCELLED_WORK + and not scb.state.pending_events.is_empty() + ) + } interrupted_deliveries = set(self._message_delivery_tasks) public_run_tasks = _unique_task_owners( ((aid, task) for task, aid in self._active_run_tasks.items()), @@ -95,7 +110,8 @@ async def _cleanup_impl(self, *, timeout: float) -> None: running_public_turns = { (aid, task) for aid, task in public_run_tasks if not task.done() } - all_tasks = {task for _aid, task in tracked_tasks} + # Cleanup retries still own tasks that outlived the previous cancellation wait. + all_tasks = {task for _aid, task in tracked_tasks} | self._pending_shutdown_tasks pending = await cancel_tasks_and_wait(all_tasks, timeout=timeout) for task in all_tasks - pending: consume_task_result(task) @@ -108,6 +124,7 @@ async def _cleanup_impl(self, *, timeout: float) -> None: timeout=timeout, ) pending = {task for task in pending if not task.done()} + self._pending_shutdown_tasks = pending if pending: failures.append("execution tasks did not quiesce") if interrupted_deliveries: @@ -128,6 +145,31 @@ async def _cleanup_impl(self, *, timeout: float) -> None: self._run_locks.pop(aid, None) self._message_inbox.pop(aid, None) + # Suspended turns have no running driver for cleanup to cancel. + # Settle them before saving so restore cannot resume a stopped turn. + suspended = [ + (aid, scb) for aid, scb in self.table.entries.items() + if scb.state.phase is SessionPhase.AWAITING_EVENTS + or (aid in suspended_aids and not scb.state.pending_events.is_empty()) + ] + for aid, _scb in suspended: + self._finalize_cleanup_failure(aid, origin_override=origins.get(aid)) + for _aid, scb in suspended: + state = scb.state + pending_events = state.pending_events + for tool_call_id, row in tuple(pending_events.rows.items()): + if row.status is RowStatus.PENDING: + pending_events.fill( + tool_call_id, result=_CLEANUP_CANCELLED_WORK, + status=RowStatus.FAILED, error=_CLEANUP_CANCELLED_WORK, + ) + if state.submitted_summary is not None: + for message in pending_events.ordered_results(): + state.append_message(message) + pending_events.clear() + state.append_message({"role": "assistant", "content": state.submitted_summary}) + state.clear_active_turn() + self._startup_tasks.clear() self._startup_envs.clear() self._startup_origin.clear() @@ -159,10 +201,18 @@ async def _cleanup_impl(self, *, timeout: float) -> None: if persistence_errors: failures.append("session persistence failed") - session_resources_closed = await close_session_resources( - self._persistence_sessions(persistence_sessions), - timeout=timeout, - ) + close_task = self._session_close_task + if close_task is None or ( + close_task.done() + and (close_task.cancelled() or close_task.exception() is not None or not close_task.result()) + ): + close_task = asyncio.create_task(close_session_resources( + self._persistence_sessions(persistence_sessions), timeout=None, + )) + self._session_close_task = close_task + close_task.add_done_callback(consume_task_result) + closed, _ = await asyncio.wait({close_task}, timeout=timeout) + session_resources_closed = bool(closed) and close_task.result() if not session_resources_closed: failures.append("session resource close failed or timed out") @@ -177,13 +227,10 @@ async def _cleanup_impl(self, *, timeout: float) -> None: if isinstance(error, BaseException): lifecycle_errors.append(error) - release_safe = ( - not pending - and environments_aborted - and persistence_quiesced - and session_resources_closed - and lifecycle_quiesced - ) + execution_settled = not pending and environments_aborted and persistence_quiesced + if execution_settled and not closed: + self._continue_worktree_release(close_task, persistence_sessions, timeout=timeout) + release_safe = execution_settled and session_resources_closed and lifecycle_quiesced worktrees_released = release_safe and await self._release_worktree_pool_bounded(timeout=timeout) if not worktrees_released: failures.append( @@ -192,6 +239,8 @@ async def _cleanup_impl(self, *, timeout: float) -> None: else "worktree pool release skipped because owned work did not quiesce" ) if failures: + if environments_aborted and any(task in pending for _aid, task in running_public_turns): + self._continue_cleanup_after_turns(pending, timeout=timeout) failure = RuntimeError("technical scheduler cleanup failed: " + "; ".join(failures)) if persistence_errors: raise failure from persistence_errors[0] @@ -199,6 +248,27 @@ async def _cleanup_impl(self, *, timeout: float) -> None: raise failure from lifecycle_errors[0] raise failure + def _continue_cleanup_after_turns(self, pending: set[asyncio.Future[object]], *, timeout: float) -> None: + owner = self._deferred_turn_cleanup + if owner is not None and not owner.done(): + return + first_attempt = self._cleanup_task + + async def finish_cleanup() -> None: + await asyncio.wait(pending) + if first_attempt is not None: + await asyncio.wait({first_attempt}) + if self._cleanup_task is first_attempt: + self._cleanup_task = None + try: + await self.cleanup(cleanup_timeout=timeout) + except Exception: + logger.exception("deferred scheduler cleanup failed") + + owner = asyncio.create_task(finish_cleanup()) + self._deferred_turn_cleanup = owner + owner.add_done_callback(consume_task_result) + def _persistence_sessions(self, initial: tuple[Any, ...]) -> tuple[Any, ...]: sessions: list[Any] = [] seen: set[int] = set() @@ -208,6 +278,25 @@ def _persistence_sessions(self, initial: tuple[Any, ...]) -> tuple[Any, ...]: sessions.append(session) return tuple(sessions) + def _continue_worktree_release( + self, close_task: asyncio.Task[bool], sessions: tuple[Any, ...], *, timeout: float, + ) -> None: + owner = self._deferred_worktree_release + if owner is not None and not owner.done(): + return + + async def release_after_close() -> None: + if not await asyncio.shield(close_task): + return + while tasks := self._pending_session_persistence_tasks(sessions): + await asyncio.wait(tasks) + if all(getattr(resource, "cleanup_quiesced", False) is True for _, resource in self._lifecycle_resources): + await self._release_worktree_pool_bounded(timeout=timeout) + + owner = asyncio.create_task(release_after_close()) + self._deferred_worktree_release = owner + owner.add_done_callback(consume_task_result) + def _pending_session_persistence_tasks( self, sessions: tuple[Any, ...], @@ -270,7 +359,7 @@ def _finalize_cleanup_failure( *, origin_override: tuple[int, str] | None = None, ) -> None: - reason = "Error: scheduler cleanup cancelled delegated work" + reason = _CLEANUP_CANCELLED_WORK self._release_leases(aid) if aid in self._delivery_committed: return @@ -290,8 +379,7 @@ def _finalize_cleanup_failure( logger.debug("cleanup could not fail pending row %s on aid %s", tool_call_id, parent_aid) scb = self.table.get(aid) if scb is not None: - scb.state.cancel(reason) - scb.result = reason + self._record_agent_cancellation(scb, reason, reason=reason) async def _abort_session_environments(self, aids: set[int], *, timeout: float) -> bool: environments: list[tuple[int, Any]] = [] @@ -348,11 +436,16 @@ async def _abort_session_environments(self, aids: set[int], *, timeout: float) - return succeeded async def _release_worktree_pool_bounded(self, *, timeout: float) -> bool: - try: + async def release_pool() -> None: result = self._worktree_pool.release() - if not inspect.isawaitable(result): - return True - task = asyncio.ensure_future(result) + if inspect.isawaitable(result): + await result + + task = self._worktree_release_task + if task is None or (task.done() and (task.cancelled() or task.exception() is not None)): + task = asyncio.create_task(release_pool()) + self._worktree_release_task = task + try: done, pending = await asyncio.wait({task}, timeout=timeout) if pending: task.cancel() diff --git a/opencollab/application/_scheduler_run.py b/opencollab/application/_scheduler_run.py index 847fc3b3..826c1cec 100644 --- a/opencollab/application/_scheduler_run.py +++ b/opencollab/application/_scheduler_run.py @@ -5,19 +5,30 @@ import asyncio import logging -from opencollab.application._session_run_shared import _FILTERED_OUTPUT_REASON, _last_assistant_answer +from opencollab.application._session_run_shared import ( + _FILTERED_OUTPUT_REASON, + _TRUNCATED_OUTPUT_REASON, + _last_assistant_answer, +) +from opencollab.application.async_timeout import consume_task_result +from opencollab.application.exception_notes import add_exception_note from opencollab.application.scheduler_types import SchedulerStalledError, SchedulerTurnError from opencollab.domain.pending import RowStatus from opencollab.domain.session import SessionPhase, SessionState logger = logging.getLogger(__name__) -def _turn_answer(state: SessionState, turn_start: int, *, completed_answer: str = "") -> str: - if state.phase is SessionPhase.STOPPED and state.terminal_reason == _FILTERED_OUTPUT_REASON: +def _turn_answer(state: SessionState, turn_start: int, *, completed_answer: str | None = None) -> str: + if state.phase is SessionPhase.ERROR and completed_answer is not None: + return completed_answer + if state.phase is SessionPhase.STOPPED and ( + state.terminal_reason == _FILTERED_OUTPUT_REASON + or (completed_answer and state.terminal_reason == _TRUNCATED_OUTPUT_REASON) + ): reply_start = state.completed_turn_start_message_index if reply_start is None: - return completed_answer - return _last_assistant_answer(state.messages, max(turn_start, reply_start)) or completed_answer + return completed_answer or "" + return _last_assistant_answer(state.messages, max(turn_start, reply_start)) or completed_answer or "" return _last_assistant_answer(state.messages, turn_start) class SchedulerRunMixin: @@ -29,6 +40,24 @@ async def run( """Compatibility entry point for an external turn addressed to Lead.""" return await self.run_turn(0, user_message, cancel_event=cancel_event) + def accepted_public_turn_answer(self, aid: int) -> str | None: + if aid not in self._completed_public_turn_answers: + return None + answer = self._completed_public_turn_answers[aid] + state = self._sessions[aid].state + if state.submitted_summary: + return state.submitted_summary + if state.phase is SessionPhase.DONE or ( + state.phase is SessionPhase.STOPPED + and state.terminal_reason in {_FILTERED_OUTPUT_REASON, _TRUNCATED_OUTPUT_REASON} + ): + finished = _last_assistant_answer( + state.messages, state.completed_turn_start_message_index, include_tool_call_text=False, + ) + if finished: + return finished + return answer or None + async def run_turn( self, aid: int, @@ -64,14 +93,17 @@ async def run_turn( self._completed_public_turn_answers.pop(aid, None) if self._turn_cancel_events.get(aid) is cancel_event: self._turn_cancel_events.pop(aid, None) - except asyncio.CancelledError: + except asyncio.CancelledError as cancellation: # Acquiring the run lock gives this caller ownership of the team # turn. A cancelled waiter only withdraws its queued request. if owns_turn and not self._shutting_down: if current_task is not None: if self._active_run_tasks.get(current_task) == aid: self._active_run_tasks.pop(current_task, None) - await self.cleanup() + try: + await self.cleanup() + except Exception as exc: + add_exception_note(cancellation, f"scheduler cleanup also failed: {type(exc).__name__}: {exc}") raise finally: if current_task is not None: @@ -116,12 +148,13 @@ async def _run_turn_exclusive(self, aid: int, user_message: str) -> str: self._start_agent_task(aid, session) await self._wait_for_restored_turn(aid, turn_start) - # A snapshot can capture the durable gap after an external user message - # was accepted but before its driver task began. Finish that queued turn - # before accepting another external message, so restore never fuses two - # unrelated user requests into one provider prompt. + # A reopened IDLE session can still own a queued or interrupted turn. + turn_start = None if getattr(session.state, "pending_external_user_turn", None) is not None: turn_start = len(session.state.messages) + elif session.state.phase is SessionPhase.IDLE: + turn_start = session.state.active_turn_start_message_index + if turn_start is not None: self._reserve_turn_lease(aid) self._start_agent_task(aid, session) await self._wait_for_restored_turn(aid, turn_start) @@ -159,7 +192,7 @@ async def _run_turn_exclusive(self, aid: int, user_message: str) -> str: if self._shutting_down: self._release_turn_lease(aid) raise RuntimeError("Cannot run scheduler: scheduler is shutting down.") - self._completed_public_turn_answers[aid] = "" + self._completed_public_turn_answers[aid] = None self._start_agent_task(aid, session) cancel_event = self._turn_cancel_events.get(aid) @@ -197,6 +230,9 @@ async def _run_turn_exclusive(self, aid: int, user_message: str) -> str: await self._settle_cancelled_suspended_turn(aid) pending = self._active_scheduler_tasks() if not pending: + # A terminal driver can exit before delivering its notice. + if any(self._unanswered.values()) and self._quiescent(): + await self._drain_ready_message_inboxes() if self._quiescent(): break await self._wait_for_scheduler_progress(aid) @@ -340,8 +376,30 @@ async def _settle_cancelled_suspended_turn(self, aid: int) -> None: for task in owned_tasks: task.cancel() if owned_tasks: - await asyncio.gather(*owned_tasks, return_exceptions=True) + try: + done, _ = await asyncio.wait(owned_tasks) + except asyncio.CancelledError as cancellation: + # The CLI can exit while children are still unwinding. Record + # the stopped turn before bounded scheduler cleanup takes over. + try: + self._record_cancelled_turn_subtree(aid, descendants, reason) + except Exception as exc: + add_exception_note( + cancellation, f"interrupted turn settlement also failed: {type(exc).__name__}: {exc}", + ) + raise + for task in done: + consume_task_result(task) + self._record_cancelled_turn_subtree(aid, descendants, reason) + await self.notify_unanswered_senders(aid, reason) + await self._safe_emit_scheduler_event( + self._events.agent_cancelled(aid, target.agent.name) + ) + self._write_manifest() + + def _record_cancelled_turn_subtree(self, aid: int, descendants: set[int], reason: str) -> None: + failure = f"Error: {reason}" for child_aid in (*descendants, aid): scb = self.table.get(child_aid) if scb is None: @@ -357,6 +415,8 @@ async def _settle_cancelled_suspended_turn(self, aid: int) -> None: ) for message in table.ordered_results(): scb.state.append_message(message) + if not table.is_empty() and scb.state.submitted_summary is not None: + scb.state.append_message({"role": "assistant", "content": scb.state.submitted_summary}) table.clear() scb.state.consume_queued_external_user_turn() scb.state.clear_active_turn() @@ -378,12 +438,6 @@ async def _settle_cancelled_suspended_turn(self, aid: int) -> None: self._turn_started_at.pop(child_aid, None) self._autosave_session(child_aid) - await self.notify_unanswered_senders(aid, reason) - await self._safe_emit_scheduler_event( - self._events.agent_cancelled(aid, target.agent.name) - ) - self._write_manifest() - def _message_budget_cleanup_tasks(self) -> set[asyncio.Task]: if not any( inbox and aid not in self._cancelled_turn_inbox_holds diff --git a/opencollab/application/_session_run_completion.py b/opencollab/application/_session_run_completion.py index ee77c83c..f4fccbb7 100644 --- a/opencollab/application/_session_run_completion.py +++ b/opencollab/application/_session_run_completion.py @@ -11,6 +11,8 @@ from typing import Any, Awaitable, Callable from opencollab.application._anthropic_history import ( + _RUN_FINAL_PROMPT_FIELD, + _anthropic_completion_messages, _anthropic_history_input, _capture_anthropic_snips, _edited_anthropic_history, @@ -19,12 +21,16 @@ _strip_anthropic_thinking, ) from opencollab.application._session_run_shared import ( + _CONTEXT_WINDOW_LIMIT_REASON, _INCOMPLETE_RESPONSE_REASONS, + _OUTPUT_LIMIT_REASONS, _STRUCTURED_OUTPUT_TOOL, _WRITE_TOOLS, GenerationTimeoutError, _ContextOverflowStop, + _recorded_tool_call, _request_tool_names, + _RequestBudgetRecovery, _submit_tool_choice, _TeamBudgetStop, _TokenBudgetStop, @@ -36,7 +42,8 @@ _normalize_completion_usage, ) from opencollab.application._tool_loop_execution import _apply_completed_prefix_progress -from opencollab.application.async_timeout import CallerTimeoutError, abandon_on_timeout +from opencollab.application.async_timeout import CallerTimeoutError, abandon_on_timeout, await_owned_operation +from opencollab.application.exception_notes import add_exception_note from opencollab.application.ports import ( _NATIVE_COMPLETION_CAPABILITY, _NATIVE_REQUEST_ADMISSION, @@ -48,6 +55,7 @@ _native_completion_controls, _NativeCompletionControls, ) +from opencollab.application.provider_failure import provider_rejected_output_limit from opencollab.application.shaping import ShaperPipeline from opencollab.application.shaping.pipeline import context_token_estimator from opencollab.application.steering import ( @@ -557,7 +565,7 @@ async def call_llm(self, tools: list[dict] | None) -> CompletionResponse: elif steering is not None and self._requires_thinking_prefix(): self.state.append_message(steering) preserve_history = self._requires_thinking_prefix() - history = _anthropic_history_input(self.state) + history = _anthropic_history_input(self.state, include_final_prompt=False) with _capture_anthropic_snips(self.state if preserve_history else None) as adopted_snips: messages = await self._shape_and_trace(history) snipped = adopted_snips(history, messages) @@ -585,7 +593,7 @@ async def call_llm(self, tools: list[dict] | None) -> CompletionResponse: context_token_estimator(self._context_pressure), _capture_anthropic_snips(self.state if preserve_history else None) as adopted_snips, ): - history = _anthropic_history_input(self.state) + history = _anthropic_history_input(self.state, include_final_prompt=False) forced = ( await ShaperPipeline((self.shaper,)).ashape(history, force=True) if self.shaper is not None else history @@ -681,11 +689,15 @@ async def _complete_with_choice( extra.update(thinking=thinking, thinking_params=params) else: params = None - await self._prepare_request_budget(messages, tools, thinking=thinking, thinking_params=params) - if self._requires_thinking_prefix(): + preserve_history = self._requires_thinking_prefix() + messages = await self._prepare_request_budget( + messages, tools, thinking=thinking, thinking_params=params, mark_final_prompt=preserve_history, + ) + if preserve_history: messages = _remember_anthropic_history(self.state, messages, tools, snipped_exchanges) + request = _anthropic_completion_messages(messages) if preserve_history and self._run_control else messages max_output_tokens = self._request_output_limit( - messages, tools, thinking=thinking, thinking_params=params, + request, tools, thinking=thinking, thinking_params=params, ) reasoning_effort = getattr(self.agent, "reasoning_effort", None) if reasoning_effort is not None: @@ -693,8 +705,8 @@ async def _complete_with_choice( if getattr(self.llm, "supports_response_session_identity", False): extra["response_session_id"] = self._response_session_id try: - return await self._invoke_llm( - messages=messages, + return await self._invoke_with_budget_recovery( + messages=request, tools=tools, temperature=self.agent.temperature, max_output_tokens=max_output_tokens, @@ -703,16 +715,19 @@ async def _complete_with_choice( except Exception as exc: recovery = ( _recover_anthropic_history(self.state, messages, tools, exc) - if self._requires_thinking_prefix() else None + if preserve_history else None ) if recovery is None: raise rejected_by = type(exc).__name__ messages, removed = recovery - await self._prepare_request_budget(messages, tools, thinking=thinking, thinking_params=params) + messages = await self._prepare_request_budget( + messages, tools, thinking=thinking, thinking_params=params, mark_final_prompt=True, + ) messages = _remember_anthropic_history(self.state, messages, tools) + request = _anthropic_completion_messages(messages) if self._run_control else messages max_output_tokens = self._request_output_limit( - messages, tools, thinking=thinking, thinking_params=params, + request, tools, thinking=thinking, thinking_params=params, ) payload = { "reason": "prefix_binding_mismatch", "removed_blocks": removed, "retry": 1, @@ -728,8 +743,8 @@ async def _complete_with_choice( step_type="thinking_prefix_recovery", payload={"aid": self.state.aid, "session_step": self.state.step_count, **payload}, ) - return await self._invoke_llm( - messages=messages, + return await self._invoke_with_budget_recovery( + messages=request, tools=tools, temperature=self.agent.temperature, max_output_tokens=max_output_tokens, @@ -772,10 +787,12 @@ def _estimate_context_message(self, message: dict[str, Any]) -> int: async def _prepare_request_budget( self, messages: list[dict], tools: list[dict] | None, *, thinking: bool, - thinking_params: dict[str, Any] | None = None, - ) -> None: + thinking_params: dict[str, Any] | None = None, mark_final_prompt: bool = False, + ) -> list[dict]: if self._run_control is None: - return + return messages + if any(message.get(_RUN_FINAL_PROMPT_FIELD) is True for message in messages): + messages = [message for message in messages if message.get(_RUN_FINAL_PROMPT_FIELD) is not True] _configured, minimum, reserved = self._request_budget_requirements( messages, tools, thinking=thinking, thinking_params=thinking_params, ) @@ -786,11 +803,16 @@ async def _prepare_request_budget( if self._run_final_prompt is not None: prompt = {"role": "system", "content": self._run_final_prompt} if prompt not in messages: - messages.append(prompt) + if mark_final_prompt: + prompt[_RUN_FINAL_PROMPT_FIELD] = True + return [*messages, prompt] + return messages def _request_output_limit( self, messages: list[dict], tools: list[dict] | None, *, thinking: bool, thinking_params: dict[str, Any] | None = None, + required_output_tokens: int = 0, + allow_budget_recovery: bool = True, ) -> int: if self._team_budget_exhausted is not None and self._team_budget_exhausted(): raise _TeamBudgetStop @@ -800,9 +822,16 @@ def _request_output_limit( self._run_control is not None and self.hard_budget_tokens is not None ), ) - remaining_budget = self.remaining_budget_tokens + minimum_output_tokens = max(minimum_output_tokens, required_output_tokens) + remaining_budget = self._remaining_request_budget() if remaining_budget is not None: output_budget = remaining_budget - reserved_input_tokens + if allow_budget_recovery and self._request_budget_recovery is not None and self._reclaim_output_budget( + output_budget, minimum_output_tokens, max_output_tokens, + ): + remaining_budget = self._remaining_request_budget() + assert remaining_budget is not None + output_budget = remaining_budget - reserved_input_tokens if output_budget < minimum_output_tokens: raise _TokenBudgetStop( reserved_input_tokens=reserved_input_tokens, remaining_budget=remaining_budget, @@ -811,6 +840,124 @@ def _request_output_limit( max_output_tokens = min(max_output_tokens, output_budget) return max_output_tokens + def _remaining_request_budget(self) -> int | None: + remaining = self.remaining_budget_tokens + if remaining is not None and self._preserve_submit_reserve and not self.state.wind_down_done: + return remaining - self._commit_reserve + return remaining + + def _budget_recovery_authority(self) -> _RequestBudgetRecovery | None: + control = self._run_control + if self.max_budget_tokens != self.hard_budget_tokens: + return None + if control is not None and ( + control.initial_soft_budget_tokens is not None or control.decide_budget is not None + ): + return None + return self._request_budget_recovery + + def _reclaim_output_budget(self, output: int, minimum_output: int, configured_output: int) -> bool: + recovery = self._budget_recovery_authority() + if recovery is None: + return False + if not recovery.observed: + recovery.available() + recovery.observed = True + if output >= minimum_output: + return False + return self._claim_request_budget( + minimum_output - output, max(configured_output, minimum_output) - output, + ) + + def _claim_request_budget(self, minimum: int, preferred: int) -> bool: + recovery = self._budget_recovery_authority() + if recovery is None: + return False + self._raise_if_run_cancelled() + grant = recovery.claim(minimum, preferred) + if grant is None: + return False + self.max_budget_tokens = grant + self.hard_budget_tokens = grant + return True + + async def _invoke_with_budget_recovery( + self, *, messages: list[dict], tools: list[dict] | None, max_output_tokens: int, **kwargs: Any, + ) -> CompletionResponse: + start = time.monotonic() + response = await self._invoke_llm( + messages=messages, tools=tools, max_output_tokens=max_output_tokens, **kwargs, + ) + first_reply_at = time.monotonic() + recovery = self._budget_recovery_authority() + if response.finish_reason not in _OUTPUT_LIMIT_REASONS or recovery is None: + return response + configured, minimum, reserved = self._request_budget_requirements( + messages, tools, thinking=kwargs.get("thinking", False), thinking_params=kwargs.get("thinking_params"), + ) + remaining = self._remaining_request_budget() + if remaining is None or max_output_tokens >= configured: + return response + original_text = response.content.strip() if isinstance(response.content, str) else "" + visible_partial = bool(original_text) and not getattr(response, "content_from_reasoning", False) + # Keep shared capacity available for later roles once this one has text to deliver. + replay_room = remaining if visible_partial else remaining + recovery.available() + retry_limit = min(configured, replay_room - reserved) + if retry_limit <= max_output_tokens or retry_limit < minimum: + return response + missing = reserved + retry_limit - remaining + if missing > 0 and not self._claim_request_budget(missing, missing): + return response + retry_started = time.monotonic() + if visible_partial: + self._budget_replay_partial = (first_reply_at, response.content) + try: + self._raise_if_run_cancelled() + replacement = await self._invoke_llm( + messages=messages, tools=tools, max_output_tokens=retry_limit, + required_output_tokens=retry_limit, allow_budget_recovery=not visible_partial, **kwargs, + ) + except BaseException as exc: + if not isinstance(exc, asyncio.CancelledError): + self._budget_replay_partial = None + if isinstance(exc, (_TokenBudgetStop, _TeamBudgetStop)): + return response + recoverable = isinstance(exc, Exception) and ( + isinstance(exc, GenerationTimeoutError) + or self._is_context_overflow(exc) + or self._is_retryable_provider_error(exc) + or provider_rejected_output_limit(exc, retry_limit=retry_limit) + ) + if recoverable and not self._run_cancellation_requested(): + logger.warning("completion budget retry failed on aid=%s (%s)", self.state.aid, type(exc).__name__) + return response + try: + self.record_llm_trace(response, retry_started - start, purpose="budget_recovery") + except Exception as trace_error: + add_exception_note(exc, f"completion trace failed: {type(trace_error).__name__}") + if recoverable: + self._raise_if_run_cancelled() + raise + self._budget_replay_partial = None + replacement_text = replacement.content.strip() if isinstance(replacement.content, str) else "" + replacement_has_text = bool(replacement_text) + if visible_partial: + replacement_has_text = replacement_has_text and not getattr(replacement, "content_from_reasoning", False) + if replacement.finish_reason == _CONTEXT_WINDOW_LIMIT_REASON: + replacement_has_text = replacement_has_text and ( + len(replacement_text) > len(original_text) and replacement_text.startswith(original_text) + ) + elif replacement.finish_reason in _OUTPUT_LIMIT_REASONS: + replacement_has_text = replacement_has_text and len(replacement_text) >= len(original_text) + replacement_has_action = ( + replacement.tool_calls and replacement.finish_reason not in _INCOMPLETE_RESPONSE_REASONS + ) + if replacement.finish_reason != "content_filter" and not (replacement_has_text or replacement_has_action): + self.record_llm_trace(replacement, time.monotonic() - retry_started, purpose="budget_recovery") + return response + self.record_llm_trace(response, retry_started - start, purpose="budget_recovery") + return replacement + @property def remaining_budget_tokens(self) -> int | None: ceilings = [self.max_budget_tokens] @@ -896,10 +1043,13 @@ def revalidate_budget() -> int: def _revalidate_request( self, messages: list[dict], tools: list[dict] | None, *, thinking: bool = False, thinking_params: dict[str, Any] | None = None, + required_output_tokens: int = 0, + allow_budget_recovery: bool = True, ) -> int: self._raise_if_run_cancelled() return self._request_output_limit( messages, tools, thinking=thinking, thinking_params=thinking_params, + required_output_tokens=required_output_tokens, allow_budget_recovery=allow_budget_recovery, ) async def _invoke_summary( @@ -911,7 +1061,9 @@ async def _invoke_summary( messages = _strip_anthropic_thinking(messages) thinking = kwargs.get("thinking", False) thinking_params = kwargs.get("thinking_params") - await self._prepare_request_budget(messages, None, thinking=thinking, thinking_params=thinking_params) + messages = await self._prepare_request_budget( + messages, None, thinking=thinking, thinking_params=thinking_params, + ) max_output_tokens = self._request_output_limit( messages, None, thinking=thinking, thinking_params=thinking_params, ) @@ -942,14 +1094,14 @@ def revalidate() -> int: }) def account_response(response: CompletionResponse) -> None: - input_tokens, _total_tokens = _normalize_completion_usage(response.usage) usage_accounting.finish( response.usage, purpose="summary", late=abandoned, response=response, ) self.state.add_markup_recovered(getattr(response.usage, "markup_recovered", 0)) - self.state.set_context_tokens(input_tokens) - self.record_llm_trace(response, time.monotonic() - start, purpose="summary", thinking=thinking) + self.record_llm_trace( + response, time.monotonic() - start, purpose="summary", thinking=thinking, late=abandoned, + ) async def complete_owned() -> CompletionResponse: try: @@ -968,16 +1120,18 @@ async def complete_owned() -> CompletionResponse: operation = _with_native_completion_controls(operation, scope) owner = asyncio.create_task(operation) self._track_provider_task(owner) + summary_error: Exception | None = None try: if self._per_call_timeout is None: await asyncio.wait({owner}) - return owner.result() - return await abandon_on_timeout( - owner, self._per_call_timeout, - late_task_tracker=self._mark_provider_task_draining, - late_result_handler=self._provider_task_done, - start_event=admitted, - ) + response = owner.result() + else: + response = await abandon_on_timeout( + owner, self._per_call_timeout, + late_task_tracker=self._mark_provider_task_draining, + late_result_handler=self._provider_task_done, + start_event=admitted, + ) except CallerTimeoutError as exc: abandoned = True raise GenerationTimeoutError( @@ -990,8 +1144,29 @@ async def complete_owned() -> CompletionResponse: owner.cancel() self._mark_provider_task_draining(owner) raise + except Exception as exc: + summary_error = exc + raise + else: + input_tokens, _total_tokens = _normalize_completion_usage(response.usage) + self.state.set_context_tokens(input_tokens) + finally: + # A failed summary can also be followed by a paid answer request. + if not abandoned and usage_accounting.tokens and self.provider_usage_checkpoint is not None: + try: + checkpoint = self.provider_usage_checkpoint() + if checkpoint is not None: + await await_owned_operation(checkpoint, propagate_cancellation=True) + except Exception as checkpoint_error: + if summary_error is None: + raise + add_exception_note(summary_error, f"summary usage checkpoint failed: {checkpoint_error}") + return response - async def _invoke_llm(self, *, max_output_tokens: int, **kwargs: Any) -> CompletionResponse: + async def _invoke_llm( + self, *, max_output_tokens: int, required_output_tokens: int = 0, + allow_budget_recovery: bool = True, **kwargs: Any, + ) -> CompletionResponse: """Bound one provider generation by ``_per_call_timeout``. ``None`` disables the ceiling. Expiry raises ``GenerationTimeoutError`` @@ -1003,21 +1178,29 @@ async def _invoke_llm(self, *, max_output_tokens: int, **kwargs: Any) -> Complet protected_call = self.state.wind_down_done usage_accounting = _CompletionUsageAccounting(self, protected_call=protected_call) complete = self.llm.complete + + def revalidate() -> int: + return self._revalidate_request( + kwargs["messages"], kwargs.get("tools"), thinking=kwargs.get("thinking", False), + thinking_params=kwargs.get("thinking_params"), required_output_tokens=required_output_tokens, + allow_budget_recovery=allow_budget_recovery, + ) + admitted, scope = self._add_completion_controls( complete, kwargs, max_output_tokens=max_output_tokens, - usage_accounting=usage_accounting, - revalidate=lambda: self._revalidate_request( - kwargs["messages"], kwargs.get("tools"), thinking=kwargs.get("thinking", False), - thinking_params=kwargs.get("thinking_params"), - ), + usage_accounting=usage_accounting, revalidate=revalidate, ) if scope is not None: kwargs["messages"] = scope.prepare_messages(kwargs["messages"]) late_accounted = False + started = time.monotonic() + request_fields = self._llm_trace_request_fields() if self.tracer else None async def complete_owned() -> CompletionResponse: nonlocal late_accounted try: + if required_output_tokens: + revalidate() response = await _complete_with_error_usage( self, complete, usage_accounting=usage_accounting, **kwargs, ) @@ -1036,12 +1219,21 @@ def record_abandoned(task: asyncio.Task[Any]) -> None: self._provider_task_done(task) else: self._record_late_provider_result(task, accounting=usage_accounting) + if self.tracer and not task.cancelled() and task.exception() is None: + try: + self.record_llm_trace( + task.result(), time.monotonic() - started, + purpose="completion", thinking=kwargs.get("thinking"), + late=True, request_fields=request_fields, + ) + except Exception: + logger.exception("late completion trace failed for aid=%s", self.state.aid) operation = complete_owned() if scope is not None or _native_completion_controls.get() is not None: operation = _with_native_completion_controls(operation, scope) try: - response = await operation if self._per_call_timeout is None else await abandon_on_timeout( + response = await abandon_on_timeout( operation, self._per_call_timeout, task_tracker=self._track_provider_task, @@ -1122,7 +1314,7 @@ def append_assistant_message(self, response: CompletionResponse) -> None: if has_content: assistant_msg["content"] = response.content if response.tool_calls: - assistant_msg["tool_calls"] = response.tool_calls + assistant_msg["tool_calls"] = [_recorded_tool_call(call) for call in response.tool_calls] provider_items = getattr(response, "provider_items", None) if provider_items: assistant_msg["response_items"] = provider_items diff --git a/opencollab/application/_session_run_shared.py b/opencollab/application/_session_run_shared.py index 9392b633..6a2456d9 100644 --- a/opencollab/application/_session_run_shared.py +++ b/opencollab/application/_session_run_shared.py @@ -3,6 +3,8 @@ from __future__ import annotations import asyncio +import json +from collections.abc import Callable from dataclasses import dataclass from typing import Any @@ -10,6 +12,18 @@ DEFAULT_DEFERRABLE_TOOLS = frozenset({"spawn_agent"}) +def _recorded_tool_call(call: dict[str, Any]) -> dict[str, Any]: + function = call.get("function", {}) + arguments = function.get("arguments") + if not isinstance(arguments, dict): + return call + # Argument text is recorded even when execution rejects its contents. + try: + text = json.dumps(arguments, ensure_ascii=False) + except (TypeError, ValueError, OverflowError, RecursionError): + text = repr(arguments) + return {**call, "function": {**function, "arguments": text}} + class GenerationTimeoutError(asyncio.TimeoutError): """A single provider generation exceeded its per-call ceiling.""" @@ -24,6 +38,12 @@ class _ContextOverflowStop(Exception): class _TeamBudgetStop(Exception): """Internal signal that shared team allowance ran out before a request.""" +@dataclass(slots=True) +class _RequestBudgetRecovery: + available: Callable[[], int] + claim: Callable[[int, int], int | None] + observed: bool = False + class _TokenBudgetStop(Exception): """Internal signal that a request has insufficient legal output headroom.""" @@ -57,10 +77,13 @@ class PendingStep: # Separate consecutive user messages for Anthropic. _EMPTY_STOP_PLACEHOLDER = "[no output produced this turn]" -_INCOMPLETE_RESPONSE_REASONS = frozenset({ - "length", "max_tokens", "model_context_window_exceeded", "content_filter", -}) +_OUTPUT_LIMIT_REASONS = frozenset({"length", "max_tokens"}) +_CONTEXT_WINDOW_LIMIT_REASON = "model_context_window_exceeded" +_INCOMPLETE_RESPONSE_REASONS = _OUTPUT_LIMIT_REASONS | {_CONTEXT_WINDOW_LIMIT_REASON, "content_filter"} _FILTERED_OUTPUT_REASON = "provider filtered the output" +_TRUNCATED_OUTPUT_REASON = "output truncated: provider reached its generation limit" +_BUDGET_EXCEEDED_PREFIX = "budget exceeded:" +_REQUEST_BUDGET_REFUSAL_PREFIX = "budget exhausted before model call:" def _last_assistant_answer( messages: list[dict[str, Any]], turn_start: int | None, *, include_tool_call_text: bool = True, diff --git a/opencollab/application/_session_run_trace.py b/opencollab/application/_session_run_trace.py index 0b794a44..8b48682c 100644 --- a/opencollab/application/_session_run_trace.py +++ b/opencollab/application/_session_run_trace.py @@ -4,6 +4,7 @@ from typing import Any +from opencollab.application._session_run_shared import _recorded_tool_call from opencollab.application.ports import CompletionResponse from opencollab.application.shaping import ShaperPipeline from opencollab.application.shaping.pipeline import context_token_estimator @@ -81,9 +82,19 @@ def _maybe_trace_steering(self, level: str | None) -> None: ) self._last_steering_level = level # update high-water mark even with no tracer + def _llm_trace_request_fields(self) -> dict[str, Any]: + return { + "session_step": self.state.step_count, + "response_session_id": self._response_session_id, + "request_tool_names": list(self._last_request_tool_names), + "request_tool_choice": self._last_request_tool_choice, + "request_observation_stage": "application", + } + def record_llm_trace( self, response: CompletionResponse | None, latency: float, *, purpose: str | None = None, thinking: bool | None = None, error: BaseException | None = None, late: bool = False, + request_fields: dict[str, Any] | None = None, ) -> None: if self.tracer: result = error if error is not None else response @@ -96,7 +107,7 @@ def record_llm_trace( "name": tc.get("function", {}).get("name"), "arguments": tc.get("function", {}).get("arguments", ""), } - for tc in tool_calls + for tc in map(_recorded_tool_call, tool_calls) ] usage = getattr(result, "usage", None) input_tokens = getattr(usage, "input_tokens", 0) @@ -111,11 +122,7 @@ def record_llm_trace( "role": getattr(self.agent, "role", None) or getattr(self.agent, "label", None) or self.agent.model, - "session_step": self.state.step_count, - "response_session_id": self._response_session_id, - "request_tool_names": list(self._last_request_tool_names), - "request_tool_choice": self._last_request_tool_choice, - "request_observation_stage": "application", + **(self._llm_trace_request_fields() if request_fields is None else request_fields), } if purpose is not None: payload["purpose"] = purpose diff --git a/opencollab/application/_session_run_usage.py b/opencollab/application/_session_run_usage.py index 55119af4..be28c5b2 100644 --- a/opencollab/application/_session_run_usage.py +++ b/opencollab/application/_session_run_usage.py @@ -10,7 +10,7 @@ from dataclasses import dataclass from typing import Any, Awaitable, Callable -_native_usage_owner: ContextVar[object | None] = ContextVar("native_usage_owner", default=None) +_native_usage_owner: ContextVar[_UsageOrigin | None] = ContextVar("native_usage_owner", default=None) _native_usage_observer: ContextVar[Callable[[Any, BaseException | None, object | None], None] | None] = ContextVar( "native_usage_observer", default=None, ) @@ -23,9 +23,21 @@ def _own_native_usage() -> Iterator[_UsageOrigin | None]: try: yield origin if _native_usage_observer.get() is not None else None finally: + origin.retry_usage_save = None _native_usage_owner.reset(token) +async def _save_native_retry_usage() -> None: + owner = _native_usage_owner.get() + if owner is None or owner.retry_usage_save is None: + return + save = owner.retry_usage_save + owner.retry_usage_save = None + checkpoint = save() + if checkpoint is not None: + await asyncio.shield(checkpoint) + + def _observe_native_usage(usage: Any, error: BaseException | None, response: Any) -> None: observer = _native_usage_observer.get() if observer is not None: @@ -67,7 +79,10 @@ def _same_token_counts(first: Any, second: Any) -> bool: class _UsageOrigin: - __slots__ = () + __slots__ = ("retry_usage_save",) + + def __init__(self) -> None: + self.retry_usage_save: Callable[[], asyncio.Task[None] | None] | None = None def __deepcopy__(self, _memo: dict[int, Any]) -> _UsageOrigin: return self @@ -163,6 +178,8 @@ def record_attempt(self, usage: Any) -> None: tokens = _normalize_completion_usage(usage)[1] self._charge(tokens) self._attempt_tokens[owner] = self._attempt_tokens.get(owner, 0) + tokens + if owner is not None and tokens: + owner.retry_usage_save = self.runner.provider_usage_checkpoint def mark_request_revalidated(self) -> None: owner = _native_usage_owner.get() @@ -369,8 +386,8 @@ def finish( def record_late(self) -> None: if self._settlements: self.runner._late_provider_usage += (self.tokens,) - if self.runner.late_provider_usage_checkpoint is not None: - self.runner.late_provider_usage_checkpoint() + if self.runner.provider_usage_checkpoint is not None: + self.runner.provider_usage_checkpoint() def _charge(self, tokens: int) -> None: self.runner._charge_completion_tokens(tokens) diff --git a/opencollab/application/async_timeout.py b/opencollab/application/async_timeout.py index 9dacdf93..b3575708 100644 --- a/opencollab/application/async_timeout.py +++ b/opencollab/application/async_timeout.py @@ -126,23 +126,26 @@ async def abandon_on_timeout( immediately raises TimeoutError to the caller. Caller cancellation retains the same background ownership and delayed-result handling. - ``start_event`` defers the deadline until request admission finishes. + ``None`` disables the deadline while retaining caller cancellation handling. + ``start_event`` defers an enabled deadline until request admission finishes. """ - if timeout is None: - return await awaitable - if isinstance(timeout, bool): - raise ValueError("timeout must be a finite positive number or None") - try: - normalized_timeout = float(timeout) - except (TypeError, ValueError) as exc: - raise ValueError("timeout must be a finite positive number or None") from exc - if not math.isfinite(normalized_timeout) or normalized_timeout <= 0: - raise ValueError("timeout must be a finite positive number or None") + normalized_timeout = None + if timeout is not None: + if isinstance(timeout, bool): + raise ValueError("timeout must be a finite positive number or None") + try: + normalized_timeout = float(timeout) + except (TypeError, ValueError) as exc: + raise ValueError("timeout must be a finite positive number or None") from exc + if not math.isfinite(normalized_timeout) or normalized_timeout <= 0: + raise ValueError("timeout must be a finite positive number or None") task = asyncio.ensure_future(awaitable) if task_tracker is not None and isinstance(task, asyncio.Task): task_tracker(task) - admission = asyncio.create_task(start_event.wait()) if start_event is not None else None + admission = None + if normalized_timeout is not None and start_event is not None: + admission = asyncio.create_task(start_event.wait()) try: if admission is not None: await asyncio.wait({task, admission}, return_when=asyncio.FIRST_COMPLETED) @@ -150,9 +153,10 @@ async def abandon_on_timeout( return task.result() done, _ = await asyncio.wait({task}, timeout=normalized_timeout) except asyncio.CancelledError: - if late_task_tracker is not None and isinstance(task, asyncio.Task): - late_task_tracker(task) - task.cancel() + if not task.done(): + if late_task_tracker is not None and isinstance(task, asyncio.Task): + late_task_tracker(task) + task.cancel() task.add_done_callback(late_result_handler or consume_task_result) raise finally: @@ -200,12 +204,17 @@ def run_with_bounded_shutdown( result: T | None = None run_error: BaseException | None = None try: + owner = asyncio.ensure_future(awaitable, loop=loop) try: - result = loop.run_until_complete(awaitable) + result = loop.run_until_complete(owner) except BaseException as exc: run_error = exc deadline = loop.time() + timeout - observed: set[asyncio.Task[object]] = set() + observed: set[asyncio.Future[object]] = {owner} + if isinstance(run_error, KeyboardInterrupt) and not owner.done(): + # Let the top-level run cancel and settle its own children first. + owner.cancel() + loop.run_until_complete(asyncio.wait({owner}, timeout=max(0, deadline - loop.time()))) saw_empty = False while True: pending = {task for task in asyncio.all_tasks(loop) if not task.done()} diff --git a/opencollab/application/autosave.py b/opencollab/application/autosave.py index 18a994a3..b8ae0479 100644 --- a/opencollab/application/autosave.py +++ b/opencollab/application/autosave.py @@ -4,6 +4,7 @@ import asyncio import logging +from contextvars import copy_context from typing import Callable from opencollab.application.ports import EventPublisherPort @@ -33,7 +34,7 @@ class AutoSaveSubscriber(EventPublisherPort): """Persist consistent snapshots through one owned background worker. ``prepare_fn`` freezes mutable state on the event loop, then the worker - runs file I/O via ``asyncio.to_thread``. Production saves append journal + runs file I/O in the default executor. Production saves append journal records and periodically compact them into an atomic base snapshot. Pending generations coalesce to the latest state while a write is active. @@ -115,7 +116,9 @@ async def _drain_latest(self) -> None: self._pending = False operation = self._prepare_operation() if operation is not None: - write = asyncio.create_task(asyncio.to_thread(_run_save, operation)) + # Submit before a short-lived loop can cancel its remaining tasks. + loop = asyncio.get_running_loop() + write = loop.run_in_executor(None, copy_context().run, _run_save, operation) cancelled = await self._wait_owned(write) or cancelled error = write.result() if error is not None: @@ -124,7 +127,7 @@ async def _drain_latest(self) -> None: raise asyncio.CancelledError @staticmethod - async def _wait_owned(owner: asyncio.Task[object]) -> bool: + async def _wait_owned(owner: asyncio.Future[object]) -> bool: """Finish one submitted save while preserving caller cancellation.""" cancelled = False while not owner.done(): diff --git a/opencollab/application/ports.py b/opencollab/application/ports.py index c26fa56d..98efaf53 100644 --- a/opencollab/application/ports.py +++ b/opencollab/application/ports.py @@ -302,12 +302,15 @@ class WorkflowSessionFactoryPort(Protocol): ``state.messages`` — no inheritance contract beyond those names. """ + def resolve_tool_preset(self, name: str) -> Sequence[ToolPort]: + ... + def build_workflow_session( self, *, prompt: str, budget: int | None, - tools: Sequence[Any] | None = None, + tools: str | Sequence[Any] | None = None, isolation: bool = False, label: str | None = None, tool_choice: Any = None, @@ -604,6 +607,21 @@ def minimum_output_tokens( """ ... +@dataclass +class _CheckpointPublication: + path: str + defer_journal_reset: bool = False + visible: bool = False + synced: bool = False + + +_checkpoint_publication: ContextVar[_CheckpointPublication | None] = ContextVar( + "checkpoint_publication", default=None, +) + +_AUTOSAVE_EXPORT_SOURCE_SEQUENCE = "_autosave_export_source_sequence" + + class SessionStorePort(Protocol): """Message persistence surface (structured JSON per agent).""" @@ -637,6 +655,17 @@ def load_snapshot( ) -> dict[str, Any]: ... +@runtime_checkable +class AutosaveOwnershipStorePort(Protocol): + def try_autosave_lock( + self, path: str, *, expected_sequence: int | None = None, + ) -> Callable[[], None] | None: + """Return a release callback, or None if busy. + + Raise SnapshotSequenceConflict if durable state exceeds expected_sequence. + """ + ... + @runtime_checkable class JournalSnapshotStorePort(Protocol): """Optional incremental autosave writer with atomic compaction.""" diff --git a/opencollab/application/provider_failure.py b/opencollab/application/provider_failure.py new file mode 100644 index 00000000..94fe7f62 --- /dev/null +++ b/opencollab/application/provider_failure.py @@ -0,0 +1,55 @@ +import re + +from opencollab.application.ports import ProviderTerminalEventError + +_OUTPUT_UPPER_BOUND = re.compile( + r"\b(?:at most|less than or equal to|maximum allowed value is)\s+([0-9]{1,10})\b(?![.,][0-9])", + re.IGNORECASE, +) + + +def _provider_error_body(exc: Exception) -> dict: + body = getattr(exc, "body", None) + if not isinstance(body, dict): + return {} + error = body.get("error") + return error if isinstance(error, dict) else body + + +def provider_http_failure_metadata(exc: Exception) -> tuple[int | None, str | None]: + status_code = getattr(exc, "status_code", None) + if isinstance(status_code, bool) or not isinstance(status_code, int): + status_code = getattr(getattr(exc, "response", None), "status_code", None) + if isinstance(status_code, bool) or not isinstance(status_code, int): + status_code = None + + error_type = _provider_error_body(exc).get("type") + if ( + isinstance(error_type, str) + and 0 < len(error_type) <= 128 + and all(char.isalnum() or char in "._-" for char in error_type) + ): + return status_code, error_type + return status_code, None + + +def provider_rejected_output_limit(exc: Exception, *, retry_limit: int) -> bool: + status_code, _ = provider_http_failure_metadata(exc) + if status_code != 400 or isinstance(exc, ProviderTerminalEventError): + return False + body = _provider_error_body(exc) + param = getattr(exc, "param", None) + if not isinstance(param, str): + param = body.get("param") + if param not in ("max_tokens", "max_completion_tokens", "max_output_tokens"): + return False + code = getattr(exc, "code", None) + if code is None: + code = body.get("code") + if code == "integer_above_max_value": + return True + if code not in (None, "invalid_value"): + return False + message = body.get("message") + bound = _OUTPUT_UPPER_BOUND.search(message) if isinstance(message, str) else None + return bound is not None and 0 < int(bound[1]) < retry_limit diff --git a/opencollab/application/scheduler.py b/opencollab/application/scheduler.py index fbdeaef5..8d11edb4 100644 --- a/opencollab/application/scheduler.py +++ b/opencollab/application/scheduler.py @@ -179,7 +179,8 @@ def __init__( # cancelling a child turn must never terminalize the Lead by default. self._active_run_tasks: dict[asyncio.Task[Any], int] = {} # An inbox follow-up can replace the addressed session's terminal state. - self._completed_public_turn_answers: dict[int, str] = {} + # None leaves transcript lookup available. An empty string records an answerless checkpoint failure. + self._completed_public_turn_answers: dict[int, str | None] = {} self._lead_session: Any | None = None # child aid -> (parent aid, tool_call_id) for deferred spawns: lets a # child's completion fill the exact pending row that suspended its @@ -238,6 +239,11 @@ def __init__( self._manifest_subscriber: AutoSaveSubscriber | None = None self._shutting_down = False self._cleanup_task: asyncio.Task[None] | None = None + self._pending_shutdown_tasks: set[asyncio.Future[object]] = set() + self._deferred_turn_cleanup: asyncio.Task[None] | None = None + self._session_close_task: asyncio.Task[bool] | None = None + self._worktree_release_task: asyncio.Task[None] | None = None + self._deferred_worktree_release: asyncio.Task[None] | None = None self._fallback_autosavers: dict[int, AutoSaveSubscriber] = {} self._scheduler_persistence_errors: list[Exception] = [] # Bootstrap-owned resources whose process/persistence state must be diff --git a/opencollab/application/scheduler_lifecycle.py b/opencollab/application/scheduler_lifecycle.py index bb3590cb..df85e603 100644 --- a/opencollab/application/scheduler_lifecycle.py +++ b/opencollab/application/scheduler_lifecycle.py @@ -13,8 +13,13 @@ import time from typing import Any -from opencollab.application._session_run_shared import _FILTERED_OUTPUT_REASON, _last_assistant_answer +from opencollab.application._session_run_shared import ( + _FILTERED_OUTPUT_REASON, + _TRUNCATED_OUTPUT_REASON, + _last_assistant_answer, +) from opencollab.application.ports import ProviderTerminalEventError +from opencollab.application.provider_failure import provider_http_failure_metadata from opencollab.application.scheduler_types import LaunchSpec from opencollab.domain.identity import role_collision_key, validate_role_identity from opencollab.domain.pending import PendingRowError, RowStatus @@ -388,6 +393,17 @@ async def _suspend_review_turn(self, parent_aid: int): finally: self._turn_waiters.discard(parent_aid) + def _remember_completed_public_turn_answer( + self, scb: SessionControlBlock, *, checkpoint_failed: bool = False, + ) -> None: + if scb.aid not in self._completed_public_turn_answers: + return + answer = _last_assistant_answer( + scb.state.messages, scb.state.completed_turn_start_message_index, include_tool_call_text=False, + ) + if answer or (checkpoint_failed and self._completed_public_turn_answers[scb.aid] is None): + self._completed_public_turn_answers[scb.aid] = answer + async def _drive_agent(self, aid: int, session: Any, *, resumed: bool = False) -> None: """Run a session's loop once and finalize. @@ -436,9 +452,8 @@ async def _drive_agent(self, aid: int, session: Any, *, resumed: bool = False) - self._turn_waiters.discard(aid) except asyncio.CancelledError: self._release_leases(aid) - scb.state.cancel() reason = "Error: agent cancelled before completing delegated work" - scb.result = reason + self._record_agent_cancellation(scb, reason) try: await self.emit_scheduler_event( self._events.agent_cancelled(aid, scb.agent.name) @@ -462,7 +477,18 @@ async def _drive_agent(self, aid: int, session: Any, *, resumed: bool = False) - status_code = getattr(exc, "status_code", None) if type(status_code) is int: scb.provider_status_code = status_code - terminal_reason = scb.state.terminal_reason or f"{type(exc).__name__}: {exc}" + else: + scb.provider_status_code, scb.provider_error_code = provider_http_failure_metadata(exc) + terminal_reason = f"{type(exc).__name__}: {exc}" + phase = scb.state.phase + checkpoint_failed = any(exc is error for error in getattr(session, "persistence_errors", ())) + if phase is SessionPhase.DONE or ( + phase is SessionPhase.STOPPED + and scb.state.terminal_reason in {_FILTERED_OUTPUT_REASON, _TRUNCATED_OUTPUT_REASON} + ): + self._remember_completed_public_turn_answer(scb, checkpoint_failed=checkpoint_failed) + if phase is not SessionPhase.DONE and not checkpoint_failed: + terminal_reason = scb.state.terminal_reason or terminal_reason scb.state.fail(terminal_reason) reason = f"Error: {terminal_reason}" result = await self._append_partial_worktree_diff(aid, scb, session, reason) @@ -502,9 +528,16 @@ async def _drive_agent(self, aid: int, session: Any, *, resumed: bool = False) - terminal_failure = self._terminal_failure_result(scb, result) if terminal_failure is not None: + partial_response = "" + if scb.state.terminal_reason == _FILTERED_OUTPUT_REASON: + partial_response = result + elif scb.state.terminal_reason == _TRUNCATED_OUTPUT_REASON: + partial_response = _last_assistant_answer( + scb.state.messages, scb.state.completed_turn_start_message_index, + ) failure_result = terminal_failure - if scb.state.terminal_reason == _FILTERED_OUTPUT_REASON and result: - failure_result = f"{terminal_failure}\n\n[Partial response]\n{result}" + if partial_response: + failure_result = f"{terminal_failure}\n\n[Partial response]\n{partial_response}" result = await self._append_partial_worktree_diff(aid, scb, session, failure_result) scb.result = result await self._safe_emit_scheduler_event( @@ -524,6 +557,7 @@ async def _drive_agent(self, aid: int, session: Any, *, resumed: bool = False) - if scb.state.phase is SessionPhase.DONE: scb.answer = result + self._remember_completed_public_turn_answer(scb) # A completed coding task still needs its patch evidence. Tracing and # event delivery are observational, but a missing diff is a technical @@ -551,13 +585,6 @@ async def _drive_agent(self, aid: int, session: Any, *, resumed: bool = False) - self._finalize_cleanup_failure(aid) return - if scb.answer and aid in self._completed_public_turn_answers: - answer = _last_assistant_answer( - scb.state.messages, scb.state.completed_turn_start_message_index, include_tool_call_text=False, - ) - if answer: - self._completed_public_turn_answers[aid] = answer - # Store the same post-diff artifact that is delivered to the parent so # spawn_with_review gives the reviewer the actual implementation diff. scb.result = result @@ -772,8 +799,7 @@ async def _wake( status = RowStatus.FAILED fill_error = result if child_scb is not None: - child_scb.state.cancel(result) - child_scb.result = result + self._record_agent_cancellation(child_scb, result, reason=result) table.fill( tool_call_id, result=result, @@ -792,6 +818,14 @@ async def _wake( self._events.agent_resumed(parent_aid, self._role_of(parent_aid)) ) + def _record_agent_cancellation( + self, scb: SessionControlBlock, result: str, *, reason: str | None = None, + ) -> None: + if scb.state.phase is SessionPhase.STOPPED and scb.aid in self._cancelled_turn_inbox_holds: + return + scb.state.cancel(reason) + scb.result = result + def _resume_completed_parent_locked( self, parent_aid: int, diff --git a/opencollab/application/scheduler_messaging.py b/opencollab/application/scheduler_messaging.py index a3cdde03..3836a06c 100644 --- a/opencollab/application/scheduler_messaging.py +++ b/opencollab/application/scheduler_messaging.py @@ -29,7 +29,7 @@ ) from opencollab.application.scheduler_types import QueuedTeammateMessage from opencollab.domain.identity import role_collision_key -from opencollab.domain.session import SessionPhase +from opencollab.domain.session import SessionPhase, is_pending_user_message logger = logging.getLogger(__name__) @@ -357,9 +357,7 @@ def _restore_message_inbox(self, aid: int, state: object) -> None: committed_ids = self._message_ids_in_history(state) restored: list[QueuedTeammateMessage] = [] for item in list(pending): - if not isinstance(item, dict) or not item.get("content"): - continue - if item.get("delivery_status") == "rejected": + if not is_pending_user_message(item): continue xml = str(item["content"]) message_id = str(item.get("message_id") or self._message_id_from_xml(xml) or "") @@ -517,9 +515,14 @@ async def _drain_ready_message_inboxes(self) -> None: await asyncio.gather( *(self._drain_message_inbox(aid) for aid in ready_aids) ) + current = asyncio.current_task() for aid in tuple(self._unanswered): stopped = self.table.get(aid) if stopped is not None and stopped.state.phase in {SessionPhase.STOPPED, SessionPhase.ERROR}: + driver = self._tasks.get(aid) + # The driver sends the terminal reply after collecting its evidence. + if driver is not None and driver is not current and not driver.done(): + continue await self.notify_unanswered_senders(aid, stopped.state.terminal_reason or stopped.state.phase.value) async def _drain_message_inbox_locked( diff --git a/opencollab/application/session.py b/opencollab/application/session.py index 7ccdabc1..121b51d7 100644 --- a/opencollab/application/session.py +++ b/opencollab/application/session.py @@ -3,18 +3,24 @@ import asyncio import copy import inspect +import logging import os import threading +import time +from collections.abc import AsyncIterator, Iterator +from contextlib import asynccontextmanager, contextmanager from dataclasses import dataclass, replace from enum import Enum from typing import TYPE_CHECKING, Any, Awaitable, Callable -from opencollab.application._session_run_shared import _FILTERED_OUTPUT_REASON +from opencollab.application._session_run_shared import _FILTERED_OUTPUT_REASON, _TRUNCATED_OUTPUT_REASON from opencollab.application.async_timeout import await_owned_operation from opencollab.application.autosave import AutoSaveSubscriber from opencollab.application.event_bus import EventBus from opencollab.application.exception_notes import add_exception_note from opencollab.application.ports import ( + _AUTOSAVE_EXPORT_SOURCE_SEQUENCE, + AutosaveOwnershipStorePort, EnvironmentPort, JournalSnapshotStorePort, LLMPort, @@ -26,6 +32,8 @@ SnapshotSequenceConflict, SnapshotStorePort, TracePort, + _checkpoint_publication, + _CheckpointPublication, ) from opencollab.application.session_run import SessionRunUseCase from opencollab.application.session_snapshot import ( @@ -44,12 +52,14 @@ from opencollab.domain.agent import Agent from opencollab.domain.events import SessionRuntimeEvent as SessionEvent from opencollab.domain.pending import PendingRow, RowKind, RowStatus -from opencollab.domain.session import SessionPhase, SessionState, same_snapshot_value +from opencollab.domain.session import SessionPhase, SessionState, is_pending_user_message, same_snapshot_value from opencollab.domain.tool_loops import LoopState if TYPE_CHECKING: from opencollab.application.scheduler import LaunchSpec +logger = logging.getLogger(__name__) + class SessionBusyError(RuntimeError): """Raised when a public operation would interleave an active session turn.""" @@ -144,20 +154,28 @@ def __init__( # runtime was built with. self.tracer = self._tracer self._auto_save_subscriber = runtime.auto_save_subscriber - self.runner.late_provider_usage_checkpoint = self.enqueue_auto_save + self.runner.provider_usage_checkpoint = self.enqueue_auto_save self._owns_llm = runtime.owns_llm self._shared_llm_ownership: _SharedLLMOwnership | None = None self._llm_closed = False + self._llm_close_lock = asyncio.Lock() self._llm_close_error: BaseException | None = None self._terminal_checkpoint_error: Exception | None = None + self._completed_turn_output: tuple[float, str] | None = None self._auto_save_sequence = 0 self._auto_save_reserved_sequence = 0 + self._auto_save_visible_sequence = 0 + self._auto_save_export_source_sequence: int | None = None self._auto_save_conflict: str | None = None self._auto_save_message_count = 0 self._auto_save_messages: list[dict] | None = None self._auto_save_rewrite_from: int | None = 0 self._auto_save_rewrite_revision = 0 self._auto_save_lock = threading.Lock() + self._autosave_writer: Callable[[], None] | None = None + self._autosave_writer_references = 0 + self._autosave_acquisition: asyncio.Task[None] | None = None + self._run_cleanup_loop: asyncio.AbstractEventLoop | None = None self._auto_save_checkpoint_lock = threading.RLock() self._auto_save_pending_checkpoints: set[int] = set() self._auto_save_seen_result_hashes: set[str] = set() @@ -251,6 +269,8 @@ def pending_execution_tasks(self) -> tuple[asyncio.Task[Any], ...]: def pending_cleanup_tasks(self) -> tuple[asyncio.Task[Any], ...]: """Execution and subscriber work that must finish before teardown.""" owned = {*self.pending_execution_tasks, *self.event_bus.pending_tasks} + if self._autosave_acquisition is not None: + owned.add(self._autosave_acquisition) return tuple(task for task in owned if not task.done()) @property @@ -271,29 +291,38 @@ def persistence_errors(self) -> tuple[Exception, ...]: async def aclose(self) -> None: """Release the owned model transport after its last session snapshot closes.""" await self._close_owned_runtimes() - if self._llm_close_error is not None: - raise self._llm_close_error - if not self._owns_llm or self._llm_closed: - self.runner.finish_run_control(lambda: self.pending_cleanup_tasks) - return - self._llm_closed = True - if self._shared_llm_ownership is not None: - self._shared_llm_ownership.owners -= 1 - if self._shared_llm_ownership.owners: - self.runner.finish_run_control(lambda: self.pending_cleanup_tasks) + async with self._llm_close_lock: + if self._llm_close_error is not None: + raise self._llm_close_error + if not self._owns_llm or self._llm_closed: + self._finish_run_control() + return + self._llm_closed = True + if self._shared_llm_ownership is not None: + self._shared_llm_ownership.owners -= 1 + if self._shared_llm_ownership.owners: + self._finish_run_control() + return + close = getattr(self._llm, "close", None) + if not callable(close): + close = getattr(self._llm, "aclose", None) + if callable(close): + try: + outcome = close() + if inspect.isawaitable(outcome): + await outcome + except BaseException as exc: + self._llm_close_error = exc + self.runner._emit_run_event("error", error_type=type(exc).__name__, message=str(exc)) + raise + self._finish_run_control() + + def _finish_run_control(self) -> None: + with self._auto_save_lock: + if self._autosave_writer is not None: + # Cleanup observers can reopen the autosave as soon as they are notified. + self._run_cleanup_loop = asyncio.get_running_loop() return - close = getattr(self._llm, "close", None) - if not callable(close): - close = getattr(self._llm, "aclose", None) - if callable(close): - try: - outcome = close() - if inspect.isawaitable(outcome): - await outcome - except BaseException as exc: - self._llm_close_error = exc - self.runner._emit_run_event("error", error_type=type(exc).__name__, message=str(exc)) - raise self.runner.finish_run_control(lambda: self.pending_cleanup_tasks) def _share_llm_ownership(self, snapshot: Session) -> None: @@ -373,65 +402,154 @@ def phase(self) -> SessionPhase: def phase(self, value: SessionPhase) -> None: self.state.set_phase(value) + @contextmanager + def _autosave_access( + self, path: str | None, *, settle: bool = False, require_current: bool = False, + ) -> Iterator[None]: + store = self.store + if not path or not isinstance(store, AutosaveOwnershipStorePort): + yield + return + + if _same_snapshot_path(path, self._auto_save_path): + with self._auto_save_lock: + if self._autosave_writer is None: + expected = ( + max(self._auto_save_sequence, self._auto_save_visible_sequence) + if require_current else None + ) + self._autosave_writer = _acquire_autosave_writer(store, path, expected) + self._autosave_writer_references += 1 + release = self._release_autosave_writer + else: + release = _acquire_autosave_writer(store, path) + + try: + yield + finally: + if settle: + self._release_after_autosave_settles(release) + else: + release() + + def _release_autosave_writer(self) -> None: + with self._auto_save_lock: + self._autosave_writer_references -= 1 + if self._autosave_writer_references: + return + assert self._autosave_writer is not None + self._autosave_writer() + self._autosave_writer = None + cleanup_loop = self._run_cleanup_loop + self._run_cleanup_loop = None + if cleanup_loop is not None and not cleanup_loop.is_closed(): + cleanup_loop.call_soon_threadsafe(self._finish_run_control) + + def _release_after_autosave_settles(self, release: Callable[[], None]) -> None: + pending = self.pending_cleanup_tasks + if pending: + # Recheck after existing completion callbacks can queue the late usage write. + pending[0].add_done_callback(lambda _: self._release_after_autosave_settles(release)) + else: + release() + + @asynccontextmanager + async def _turn_autosave_access(self) -> AsyncIterator[None]: + path = self._auto_save_path + if not path or not isinstance(self.store, AutosaveOwnershipStorePort): + yield + return + + access = self._autosave_access(path, settle=True, require_current=True) + + async def acquire() -> None: + # The journal lock can be held by another reader or writer. + await await_owned_operation(asyncio.to_thread(access.__enter__)) + + owner = asyncio.create_task(acquire()) + self._autosave_acquisition = owner + try: + await await_owned_operation(owner, propagate_cancellation=True) + yield + finally: + self._autosave_acquisition = None + if not owner.cancelled() and owner.exception() is None: + access.__exit__(None, None, None) + async def run_loop(self, cancel_event: asyncio.Event | None = None) -> str: if self._turn_lock.locked() or self.runner.pending_cleanup_tasks: raise SessionBusyError("session already has an active turn") async with self._turn_lock: - primary_error: BaseException | None = None + async with self._turn_autosave_access(): + return await self._run_turn(cancel_event) + + async def _run_turn(self, cancel_event: asyncio.Event | None) -> str: + primary_error: BaseException | None = None + self._completed_turn_output = None + try: + output = await self.runner.run_loop(cancel_event) + truncated_answer = ( + self.state.phase is SessionPhase.STOPPED + and self.state.terminal_reason == _TRUNCATED_OUTPUT_REASON + and self.state.completed_turn_start_message_index is not None + ) + if output and (self.state.phase is SessionPhase.DONE or truncated_answer): + self._completed_turn_output = (time.monotonic(), output) + return output + except asyncio.CancelledError as exc: + # Direct task cancellation must terminalize the FSM before propagating, + # otherwise the facade rejects the next user turn as permanently busy. + primary_error = exc + if not self.state.phase.is_terminal(): + self.state.cancel() + self._append_restore_results_for_open_tool_calls( + content=( + "Tool execution interrupted by session cancellation. " + "The execution outcome is unknown." + ), + exclude_ids=set(self.state.pending_events.rows), + completed_results=self._completed_tool_results(), + ) + raise + except BaseException as exc: + primary_error = exc + # Cancellation closes this exchange itself. Any other failure leaves + # the assistant tool call in history, so the next request is invalid + # unless those ids are answered before the exception propagates. try: - return await self.runner.run_loop(cancel_event) - except asyncio.CancelledError as exc: - # Direct task cancellation must terminalize the FSM before propagating, - # otherwise the facade rejects the next user turn as permanently busy. - primary_error = exc - if not self.state.phase.is_terminal(): - self.state.cancel() - self._append_restore_results_for_open_tool_calls( - content=( - "Tool execution interrupted by session cancellation. " - "The execution outcome is unknown." - ), - exclude_ids=set(self.state.pending_events.rows), - completed_results=self._completed_tool_results(), + self._close_failed_tool_exchange() + except Exception as close_error: + add_exception_note( + exc, + "open tool calls could not be closed: " + f"{type(close_error).__name__}: {close_error}", ) - raise - except BaseException as exc: - primary_error = exc - # Cancellation closes this exchange itself. Any other failure leaves - # the assistant tool call in history, so the next request is invalid - # unless those ids are answered before the exception propagates. - try: - self._close_failed_tool_exchange() - except Exception as close_error: - add_exception_note( - exc, - "open tool calls could not be closed: " - f"{type(close_error).__name__}: {close_error}", - ) - raise - finally: - if self.state.phase.is_terminal() or primary_error is not None: - try: - await self._close_owned_runtimes() - except BaseException as cleanup_error: - if primary_error is None: - raise - add_exception_note(primary_error, f"owned runtime cleanup also failed: {cleanup_error}") - self.runner._record_run_terminal() + raise + finally: + if self.state.phase.is_terminal() or primary_error is not None: try: - await self._checkpoint_terminal_snapshot() - except Exception as checkpoint_error: + await self._close_owned_runtimes() + except BaseException as cleanup_error: if primary_error is None: raise - add_exception_note( - primary_error, - "terminal checkpoint also failed: " - f"{type(checkpoint_error).__name__}: {checkpoint_error}", - ) + add_exception_note(primary_error, f"owned runtime cleanup also failed: {cleanup_error}") + self.runner._record_run_terminal() + try: + await self._checkpoint_terminal_snapshot(defer_journal_reset=primary_error is None) + except Exception as checkpoint_error: + if primary_error is None: + raise + add_exception_note( + primary_error, + "terminal checkpoint also failed: " + f"{type(checkpoint_error).__name__}: {checkpoint_error}", + ) - async def _checkpoint_terminal_snapshot(self) -> None: + async def _checkpoint_terminal_snapshot(self, *, defer_journal_reset: bool = False) -> None: if not self.state.phase.is_terminal() and self.state.phase is not SessionPhase.AWAITING_EVENTS: return + subscriber = self._auto_save_subscriber + failures = subscriber.failure_count if subscriber is not None else 0 owner = self.enqueue_auto_save() if owner is not None: await await_owned_operation( @@ -450,18 +568,22 @@ async def _checkpoint_terminal_snapshot(self) -> None: # must also publish a self-contained base snapshot: callers and crash # recovery may read the base file directly, without replaying its # sidecar journal. - if ( - not self._auto_save_path - or not isinstance(self.store, JournalSnapshotStorePort) - ): + path = self._auto_save_path + if not path or not isinstance(self.store, JournalSnapshotStorePort): return + if subscriber is not None and subscriber.failure_count != failures: + defer_journal_reset = False + async def checkpoint() -> None: + token = _checkpoint_publication.set(_CheckpointPublication(path, defer_journal_reset)) try: - await asyncio.to_thread(self.save, self._auto_save_path) + await asyncio.to_thread(self.save, path) except Exception as exc: self._terminal_checkpoint_error = exc raise + finally: + _checkpoint_publication.reset(token) await await_owned_operation( checkpoint(), @@ -477,12 +599,14 @@ async def add_user_message(self, content: str) -> None: ): raise SessionBusyError("session already has an active turn") async with self._turn_lock: - self.state.append_queued_external_user_turn( - content, defer=not self.state.pending_events.is_empty() - ) - self.state.reset_for_user_turn() - self.runner.reset_runtime_for_user_turn() - await self.event_bus.emit(SessionEvent(type="user_message_appended")) + async with self._turn_autosave_access(): + self.state.append_queued_external_user_turn( + content, defer=not self.state.pending_events.is_empty() + ) + self.state.reset_for_user_turn() + self.runner.reset_runtime_for_user_turn() + self._completed_turn_output = None + await self.event_bus.emit(SessionEvent(type="user_message_appended")) def apply_launch(self, launch: "LaunchSpec") -> None: """Apply launch-time persistence as a one-shot lifecycle step. @@ -529,13 +653,11 @@ def restore(self, path: str, *, aid: int | None = None) -> None: """Restore a snapshot or legacy transcript, with an optional agent ID override.""" if self._turn_lock.locked() or self.pending_cleanup_tasks: raise SessionBusyError("session cannot be restored while runtime work is active") - if isinstance(self.store, SnapshotStorePort): - snapshot = self.store.load_snapshot(path, self.agent.system_prompt) - else: - snapshot = { - "messages": self.store.load_messages(path, self.agent.system_prompt) - } + with self._autosave_access(self._auto_save_path): + snapshot = _read_session_snapshot(self.store, path, self.agent.system_prompt) + self._restore_snapshot(path, snapshot, aid=aid) + def _restore_snapshot(self, path: str, snapshot: dict[str, Any], *, aid: int | None) -> None: messages = list(snapshot.get("messages", [])) raw_state = snapshot.get("session_state") restored = SessionState( @@ -651,9 +773,10 @@ def _normalize_interrupted_snapshot_state( restored_turn_start: int | None, ) -> None: phase = _restore_phase(raw_state.get("phase", SessionPhase.IDLE.value)) + saved_message_count = len(restored.messages) if phase is SessionPhase.AWAITING_EVENTS: self._complete_missing_pending_rows(restored) - if restored_turn_start is None: + if restored_turn_start is None and not restored.pending_events.is_empty(): # Legacy and malformed snapshots may not carry a valid answer # cursor. Future messages begin at the restored transcript end, # which excludes prior answers while retaining the resumed one. @@ -706,13 +829,46 @@ def _normalize_interrupted_snapshot_state( and raw_state.get("terminal_reason") is not None else None ) - if phase in {SessionPhase.EXECUTING_TOOLS, SessionPhase.AUTOSAVING} and isinstance(submitted_summary, str): - # Accepted submissions survive interruption during their tool_end or autosave events. + if phase in { + SessionPhase.EXECUTING_TOOLS, SessionPhase.AUTOSAVING, SessionPhase.STOPPED, + } and isinstance(submitted_summary, str): + # Cancellation may save a stopped turn before its accepted summary enters the transcript. answer = {"role": "assistant", "content": submitted_summary} if not restored.messages or restored.messages[-1] != answer: restored.append_message(answer) - restored.mark_done() - restored.terminal_reason = "submitted" + if phase is not SessionPhase.STOPPED: + restored.mark_done() + restored.terminal_reason = "submitted" + if restored.phase is SessionPhase.IDLE: + # A saved step can precede its first response. Restored teammate + # messages keep their existing recovery order in that case. + started_user_call = ( + raw_state.get("phase") in (SessionPhase.CALLING_LLM.value, SessionPhase.IDLE.value) + and restored.step_count > 0 + and saved_message_count > 0 + and restored_turn_start == saved_message_count + and restored.messages[saved_message_count - 1].get("role") == "user" + and not any(is_pending_user_message(message) for message in restored.pending_user_messages) + ) + # Wind-down records its token mark before the protected model call. + wind_down_pending = ( + phase in {SessionPhase.IDLE, SessionPhase.PRECHECK, SessionPhase.AUTOSAVING, SessionPhase.CALLING_LLM} + and restored.wind_down_done + and restored.used_tokens == restored.wind_down_token_mark + ) + restored.active_turn_start_message_index = ( + restored_turn_start + if restored.pending_external_user_turn is None + and restored_turn_start is not None + and ( + started_user_call + or _snapshot_turn_needs_continuation( + restored.messages[restored_turn_start:saved_message_count], + wind_down_pending=wind_down_pending, + ) + ) + else None + ) if restored.phase is SessionPhase.DONE or ( restored.phase is SessionPhase.STOPPED and restored.terminal_reason == _FILTERED_OUTPUT_REASON ): @@ -722,6 +878,13 @@ def _normalize_interrupted_snapshot_state( restored.completed_turn_start_message_index = ( completed_turn_start if completed_turn_start is not None else restored_turn_start ) + elif ( + (restored.phase is SessionPhase.STOPPED and restored.terminal_reason == _TRUNCATED_OUTPUT_REASON) + or (restored.phase is SessionPhase.IDLE and restored.pending_external_user_turn is not None) + ): + restored.completed_turn_start_message_index = _restore_active_turn_start( + raw_state.get("completed_turn_start_message_index"), restored.messages, + ) def _normalize_forked_state(self, state: SessionState, raw_state: dict[str, Any]) -> None: state.pending_events.clear() @@ -760,6 +923,11 @@ def _restore_auto_save_tracking(self, snapshot: dict[str, Any]) -> None: sequence = _snapshot_nonnegative_int(snapshot.get("_autosave_sequence")) self._auto_save_sequence = sequence self._auto_save_reserved_sequence = sequence + self._auto_save_visible_sequence = 0 + export_source = snapshot.get(_AUTOSAVE_EXPORT_SOURCE_SEQUENCE) + self._auto_save_export_source_sequence = ( + None if export_source is None else _snapshot_nonnegative_int(export_source) + ) self._auto_save_conflict = None stored_messages = snapshot.get("messages") self._auto_save_message_count = min( @@ -788,32 +956,67 @@ def _checkpoint_restored_auto_save_target( return snapshot with self._auto_save_lock: messages, meta = self._snapshot_for_save(state=restored) - sequence = _snapshot_nonnegative_int(snapshot.get("_autosave_sequence")) + source_sequence = _snapshot_nonnegative_int( + snapshot.get(_AUTOSAVE_EXPORT_SOURCE_SEQUENCE, snapshot.get("_autosave_sequence")), + ) + sequence = source_sequence if isinstance(self.store, JournalSnapshotStorePort): + # Opening a writable copy advances its local cursor without advancing its source. + meta[_AUTOSAVE_EXPORT_SOURCE_SEQUENCE] = source_sequence sequence += 1 + + def checkpoint() -> None: + token = _checkpoint_publication.set(_CheckpointPublication(target_path, defer_journal_reset=True)) + try: + self.store.checkpoint_snapshot(target_path, messages, meta=meta, sequence=sequence) + finally: + _checkpoint_publication.reset(token) + try: - self.store.checkpoint_snapshot(target_path, messages, meta=meta, sequence=sequence) + checkpoint() except SnapshotSequenceConflict: - saved_message_count = len(snapshot.get("messages", ())) - if saved_message_count >= len(messages) or not isinstance(self.store, SnapshotStorePort): + if not isinstance(self.store, SnapshotStorePort): raise previous = self.store.load_snapshot(target_path, self.agent.system_prompt) - previous_messages = previous["messages"] - if previous.get("_autosave_sequence") != sequence or len(previous_messages) != len(messages): + previous_sequence = _snapshot_nonnegative_int(previous.get("_autosave_sequence")) + previous_source_sequence = previous.get(_AUTOSAVE_EXPORT_SOURCE_SEQUENCE) + saved_message_count = len(snapshot.get("messages", ())) + recovered_rows = saved_message_count < len(messages) + extends_transcript = _snapshot_extends_completed_transcript(previous, messages, meta) + if extends_transcript: + sequence = previous_sequence + 1 + elif ( + type(previous_source_sequence) is int + and previous_source_sequence == source_sequence + and previous_sequence >= sequence + ): + # Publication at the same sequence requires an equivalent snapshot. + sequence = previous_sequence + elif not recovered_rows or previous_sequence != sequence: raise - # A retry regenerates recovery rows with a new wall-clock time. - # The checkpoint still compares their content and every source row. - timestamps = [message.get("timestamp") for message in previous_messages[saved_message_count:]] - if not all(isinstance(timestamp, str) for timestamp in timestamps): + previous_messages = previous["messages"] + if not extends_transcript and len(previous_messages) != len(messages): raise - for message, timestamp in zip(messages[saved_message_count:], timestamps): - message["timestamp"] = timestamp - self.store.checkpoint_snapshot(target_path, messages, meta=meta, sequence=sequence) - restored.message_timestamps[saved_message_count:] = timestamps + timestamps = [] + if recovered_rows and not extends_transcript: + # A retry regenerates recovery rows with a new wall-clock time. + # The checkpoint still compares their content and every source row. + timestamps = [message.get("timestamp") for message in previous_messages[saved_message_count:]] + if not all(isinstance(timestamp, str) for timestamp in timestamps): + raise + for message, timestamp in zip(messages[saved_message_count:], timestamps): + message["timestamp"] = timestamp + checkpoint() + if timestamps: + restored.message_timestamps[saved_message_count:] = timestamps else: meta["_autosave_sequence"] = sequence self.store.save(target_path, messages, meta=meta) - return {**snapshot, "_autosave_sequence": sequence, "messages": messages} + recovered = {**snapshot, "_autosave_sequence": sequence, "messages": messages} + recovered.pop(_AUTOSAVE_EXPORT_SOURCE_SEQUENCE, None) + if _AUTOSAVE_EXPORT_SOURCE_SEQUENCE in meta: + recovered[_AUTOSAVE_EXPORT_SOURCE_SEQUENCE] = meta[_AUTOSAVE_EXPORT_SOURCE_SEQUENCE] + return recovered def _publish_restored_state( self, restored: SessionState, snapshot: dict[str, Any], source_path: str, @@ -823,6 +1026,7 @@ def _publish_restored_state( snapshot = self._checkpoint_restored_auto_save_target(source_path, restored, snapshot) with self._auto_save_lock: self.runner.reset_for_restore() + self._completed_turn_output = None self.state.__dict__.clear() self.state.__dict__.update(restored.__dict__) self._loop_checkpoint_results = [] @@ -963,15 +1167,21 @@ def _append_restore_results_for_open_tool_calls( ) def save(self, path: str) -> None: - if ( - _same_snapshot_path(path, self._auto_save_path) - and isinstance(self.store, JournalSnapshotStorePort) - ): + saving_autosave = _same_snapshot_path(path, self._auto_save_path) + if not saving_autosave and self.state.phase.is_terminal() and self.runner.pending_cleanup_tasks: + raise SessionBusyError("cannot export a terminal session while provider requests are still draining") + with self._autosave_access(path, require_current=saving_autosave): + self._save_snapshot(path, saving_autosave=saving_autosave) + + def _save_snapshot(self, path: str, *, saving_autosave: bool) -> None: + if saving_autosave and isinstance(self.store, JournalSnapshotStorePort): # Freeze and publish after every operation already submitted by # this session. An older append may finish later, but replay will # skip its sequence and its completion cannot rewind our cursor. with self._auto_save_lock: messages, meta = self._snapshot_for_save() + if self._auto_save_export_source_sequence is not None: + meta[_AUTOSAVE_EXPORT_SOURCE_SEQUENCE] = self._auto_save_export_source_sequence track_messages = self._auto_save_messages is not None or self.state.anthropic_history is not None tracked_messages = messages if track_messages else None sequence = self._reserve_auto_save_sequence() @@ -982,25 +1192,43 @@ def save(self, path: str) -> None: with self._auto_save_lock: if sequence < self._auto_save_sequence: return - self.store.checkpoint_snapshot(path, messages, meta=meta, sequence=sequence) - with self._auto_save_lock: - self._auto_save_sequence = sequence - self._auto_save_message_count = len(messages) - self._auto_save_messages = tracked_messages - self._auto_save_conflict = None - if self._auto_save_rewrite_revision == rewrite_revision: - self._auto_save_rewrite_from = None - self._auto_save_seen_result_hashes = set(meta["session_state"]["seen_result_hashes"]) - self._next_auto_save_checkpoint = 1 << sequence.bit_length() + active = _checkpoint_publication.get() + publication = _CheckpointPublication( + path, active is not None and active.path == path and active.defer_journal_reset, + ) + token = _checkpoint_publication.set(publication) + try: + self.store.checkpoint_snapshot(path, messages, meta=meta, sequence=sequence) + publication.synced = True + finally: + _checkpoint_publication.reset(token) + with self._auto_save_lock: + if publication.synced: + self._auto_save_sequence = sequence + self._auto_save_visible_sequence = 0 + self._auto_save_message_count = len(messages) + self._auto_save_messages = tracked_messages + self._auto_save_conflict = None + if self._auto_save_rewrite_revision == rewrite_revision: + self._auto_save_rewrite_from = None + self._auto_save_seen_result_hashes = set(meta["session_state"]["seen_result_hashes"]) + self._next_auto_save_checkpoint = 1 << sequence.bit_length() + elif publication.visible: + # The rename is ours. A later delta must still cover the unsynced base. + self._auto_save_visible_sequence = sequence finally: with self._auto_save_lock: self._auto_save_pending_checkpoints.discard(sequence) return with self._auto_save_lock: messages, meta = self._snapshot_for_save() - # An exported snapshot may resume this session's autosave target. - # Keep its ordering cursor when saving to another filename. - meta["_autosave_sequence"] = self._auto_save_reserved_sequence + # Keep the source's fork point across writes to the local working copy. + export_source = self._auto_save_export_source_sequence + if export_source is None: + export_source = self._auto_save_reserved_sequence + meta["_autosave_sequence"] = export_source + if self._auto_save_path is not None or self._auto_save_export_source_sequence is not None: + meta[_AUTOSAVE_EXPORT_SOURCE_SEQUENCE] = export_source self.store.save(path, messages, meta=meta) def _snapshot_for_save( @@ -1127,6 +1355,8 @@ def _prepare_journal_auto_save(self, path: str) -> Callable[[], None]: ): replacement_store = self.store messages, meta = self._snapshot_for_save(replace_from) + if self._auto_save_export_source_sequence is not None: + meta[_AUTOSAVE_EXPORT_SOURCE_SEQUENCE] = self._auto_save_export_source_sequence tracked_messages = [*stored_messages[:replace_from], *messages] if track_messages else None current_seen_hashes = set(self.state.turn.seen_result_hashes) seen_hashes_reset = preceding_write_pending or not self._auto_save_seen_result_hashes.issubset( @@ -1156,7 +1386,8 @@ def write_checkpoint(full_messages: list[dict]) -> bool: self.store.checkpoint_snapshot(path, full_messages, meta=meta, sequence=sequence) except (OSError, SnapshotCapacityError) as checkpoint_error: if replacement_store is None: - raise + logger.warning("session checkpoint deferred after durable autosave: %s", checkpoint_error) + return False try: saved = replacement_store.append_snapshot_replacement( path, @@ -1228,7 +1459,8 @@ def persist_incrementally() -> None: def enqueue_auto_save(self) -> asyncio.Task[None] | None: if self._auto_save_subscriber is None: return None - return self._auto_save_subscriber.enqueue() + with self._autosave_access(self._auto_save_path, settle=True, require_current=True): + return self._auto_save_subscriber.enqueue() def _track_tool_results(self, completed_results: list[dict]) -> None: pending = [ @@ -1261,6 +1493,62 @@ def _auto_save(self) -> None: if self._auto_save_path: self.save(self._auto_save_path) +def _acquire_autosave_writer( + store: AutosaveOwnershipStorePort, path: str, expected_sequence: int | None = None, +) -> Callable[[], None]: + release = store.try_autosave_lock(path, expected_sequence=expected_sequence) + if release is None: + raise SessionBusyError(f"autosave has an active writer: {path}") + return release + +def _read_session_snapshot( + store: SessionStorePort, path: str, system_prompt: str, +) -> dict[str, Any]: + if isinstance(store, SnapshotStorePort): + return store.load_snapshot(path, system_prompt) + return {"messages": store.load_messages(path, system_prompt)} + +def _snapshot_turn_needs_continuation( + messages: list[dict[str, Any]], *, wind_down_pending: bool, +) -> bool: + has_later_input = False + for message in reversed(messages): + role = message.get("role") + if role == "tool": + return True + if role == "assistant": + # A text-only answer can be saved by its observer before the phase reaches DONE. + return has_later_input or bool(message.get("tool_calls")) + if role == "user" or (role == "system" and wind_down_pending): + has_later_input = True + return False + +def _snapshot_extends_completed_transcript( + previous: dict[str, Any], messages: list[dict[str, Any]], meta: dict[str, Any], +) -> bool: + previous_messages = previous["messages"] + previous_state = previous.get("session_state") + if not isinstance(previous_state, dict) or previous_state.get("phase") != SessionPhase.DONE.value: + return False + # Accepted work may only exist in persisted runtime state until delivery. + if ( + previous.get("pending_messages") + or previous_state.get("pending_external_user_turn") + or previous_state.get("pending_events") + or previous_state.get("loop_checkpoint_results") + or previous_state.get("submitted_summary") is not None + ): + return False + state = meta["session_state"] + return ( + len(previous_messages) < len(messages) + and same_snapshot_value(previous_messages, messages[:len(previous_messages)]) + and all( + _snapshot_nonnegative_int(previous_state.get(key)) <= state[key] + for key in ("step_count", "used_tokens") + ) + ) + def _same_snapshot_path(left: str | None, right: str | None) -> bool: if left is None or right is None: return False diff --git a/opencollab/application/session_lifecycle.py b/opencollab/application/session_lifecycle.py index 955107b7..b727c4c9 100644 --- a/opencollab/application/session_lifecycle.py +++ b/opencollab/application/session_lifecycle.py @@ -13,14 +13,31 @@ ) +def _completed_session_output_before(session: Any, deadline: float | None) -> str | None: + completed = getattr(session, "_completed_turn_output", None) + if deadline is None or completed is None: + return None + finished_at, output = completed + return output if finished_at < deadline else None + + +def _budget_replay_output_before(session: Any, deadline: float | None) -> str | None: + partial = getattr(getattr(session, "runner", None), "_budget_replay_partial", None) + if deadline is None or partial is None: + return None + finished_at, output = partial + return output if finished_at < deadline else None + + async def close_session_resources( sessions: Iterable[Any], *, - timeout: float, + timeout: float | None, + errors: list[BaseException] | None = None, ) -> bool: """Close each unique session and report whether every close succeeded.""" close_tasks: set[asyncio.Task[Any]] = set() - succeeded = True + failures: list[BaseException] = [] seen: set[int] = set() for session in sessions: if id(session) in seen: @@ -31,24 +48,26 @@ async def close_session_resources( continue try: outcome = close() - except BaseException: - succeeded = False + except BaseException as exc: + failures.append(exc) continue if inspect.isawaitable(outcome): close_tasks.add(asyncio.ensure_future(outcome)) - if not close_tasks: - return succeeded - _done, pending = await asyncio.wait(close_tasks, timeout=timeout) - if pending: + pending: set[asyncio.Task[Any]] = set() + if close_tasks: + _done, pending = await asyncio.wait(close_tasks, timeout=timeout) + if pending and timeout is not None: pending = await cancel_tasks_and_wait(pending, timeout=timeout) for task in close_tasks - pending: try: task.result() - except BaseException: - succeeded = False + except BaseException as exc: + failures.append(exc) for task in pending: task.add_done_callback(consume_task_result) - return succeeded and not pending + if errors is not None: + errors.extend(failures) + return not failures and not pending __all__ = ["close_session_resources"] diff --git a/opencollab/application/session_run.py b/opencollab/application/session_run.py index 1f27ee6c..8138231a 100644 --- a/opencollab/application/session_run.py +++ b/opencollab/application/session_run.py @@ -10,10 +10,14 @@ from opencollab.application._session_run_completion import _SessionRunCompletionMixin from opencollab.application._session_run_shared import ( + _BUDGET_EXCEEDED_PREFIX, _EMPTY_STOP_NUDGE, _EMPTY_STOP_PLACEHOLDER, _FILTERED_OUTPUT_REASON, _INCOMPLETE_RESPONSE_REASONS, + _OUTPUT_LIMIT_REASONS, + _REQUEST_BUDGET_REFUSAL_PREFIX, + _TRUNCATED_OUTPUT_REASON, _WIND_DOWN_NUDGE, _WIND_DOWN_RETRY, DEFAULT_COMMIT_RESERVE, @@ -28,6 +32,7 @@ PendingStep, _ContextOverflowStop, _last_assistant_answer, + _RequestBudgetRecovery, _submit_tool_choice, _TeamBudgetStop, _TokenBudgetStop, @@ -95,6 +100,7 @@ def __init__( shaper: ShaperPort | None = None, team_budget_exhausted: Callable[[], bool] | None = None, is_context_overflow: Callable[[Exception], bool] | None = None, + is_retryable_provider_error: Callable[[Exception], bool] | None = None, per_call_timeout: float | None = None, enforcement_strength: str = ENFORCEMENT_OFF, commit_reserve: int = DEFAULT_COMMIT_RESERVE, @@ -121,6 +127,8 @@ def __init__( self.tracer = tracer self.max_budget_tokens = max_budget_tokens self.budget_reservations: list[Callable[[], int]] = [] + self._request_budget_recovery: _RequestBudgetRecovery | None = None + self._budget_replay_partial: tuple[float, str] | None = None self._initialize_run_control(run_control, run_id) self.max_steps = max_steps self.deferrable_tool_names = deferrable_tool_names @@ -131,6 +139,7 @@ def __init__( # The adapter classifies provider context overflow without provider imports # in this layer. An unwired classifier leaves exceptions on the ERROR path. self._is_context_overflow = is_context_overflow or (lambda _exc: False) + self._is_retryable_provider_error = is_retryable_provider_error or (lambda _exc: False) # Bound each generation because an HTTP timeout may not bound a slow # streaming or thinking response within the run's wall-clock budget. if per_call_timeout is None: @@ -161,6 +170,7 @@ def __init__( # Wind-down runs only when enforcement is enabled. self._enforcement_strength = enforcement_strength self._commit_reserve = commit_reserve + self._preserve_submit_reserve = False self._submit_tool_name = submit_tool_name # No-progress and low-yield limits share the budget wind-down actuator. self._watchdog_k = watchdog_k @@ -183,7 +193,7 @@ def __init__( # They count against the budget but never enter a later turn's history. self._late_provider_usage: tuple[int, ...] = () # The session supplies its owned persistence queue after adopting this runner. - self.late_provider_usage_checkpoint: Callable[[], object] | None = None + self.provider_usage_checkpoint: Callable[[], asyncio.Task[None] | None] | None = None self._on_completion_tokens: Callable[[int], None] | None = None def reset_runtime_for_user_turn(self) -> None: @@ -192,7 +202,10 @@ def reset_runtime_for_user_turn(self) -> None: self.agent.tool_choice = copy.deepcopy(self._initial_agent_tool_choice) self._pending_tool_allowlist = None self._pending_tool_gate_label = None + self._preserve_submit_reserve = False self._required_tool_retried = False + self._budget_replay_partial = None + self._run_final_prompt = None def reset_for_restore(self) -> None: """Discard process-local turn state before publishing a snapshot.""" @@ -311,7 +324,8 @@ def _prepare_turn(self) -> None: self.state.resume_to_idle() self.state.set_phase(SessionPhase.AWAITING_EVENTS) entry_phase = SessionPhase.AWAITING_EVENTS - if self.state.pending_external_user_turn is not None and entry_phase.is_terminal(): + queued_turn = self.state.pending_external_user_turn + if queued_turn is not None and entry_phase.is_terminal(): self.state.resume_to_idle() entry_phase = SessionPhase.IDLE if entry_phase is SessionPhase.IDLE: @@ -328,8 +342,11 @@ def _prepare_turn(self) -> None: if self._turn_start_message_index is None and entry_phase is SessionPhase.DONE: self._turn_start_message_index = 0 else: - self._turn_start_message_index = len(self.state.messages) - self.state.start_active_turn(self._turn_start_message_index) + turn_start = self.state.active_turn_start_message_index + if entry_phase is not SessionPhase.IDLE or queued_turn is not None or turn_start is None: + turn_start = len(self.state.messages) + self._turn_start_message_index = turn_start + self.state.start_active_turn(turn_start) if entry_phase is SessionPhase.AWAITING_EVENTS: self._resume_from_awaiting() @@ -454,7 +471,9 @@ def configure_enforcement( and self.max_budget_tokens is not None and effective_reserve > self.max_budget_tokens ): - raise ValueError("commit_reserve cannot exceed max_budget_tokens") + missing = effective_reserve - self.max_budget_tokens + if not self._claim_request_budget(missing, missing): + raise ValueError("commit_reserve cannot exceed max_budget_tokens") self._enforcement_strength = enforcement_strength if commit_reserve is not None: @@ -479,8 +498,11 @@ def _enter_wind_down(self) -> None: is absent, retain the current tools and apply the nudge and turn limit. """ self.state.wind_down_done = True - self.state.wind_down_attempts += 1 self.state.wind_down_token_mark = self.state.used_tokens + self._restrict_to_submit_tool() + self.state.append_message({"role": "system", "content": _WIND_DOWN_NUDGE}) + + def _restrict_to_submit_tool(self) -> None: finder = getattr(self.agent, "find_tool", None) submit = finder(self._submit_tool_name) if callable(finder) else None if submit is not None: @@ -489,7 +511,6 @@ def _enter_wind_down(self) -> None: # for the retry turn too; ``_complete`` degrades it once to "auto" on a # 400, after which the retry's text instruction is the guarantee. self.agent.tool_choice = _submit_tool_choice(self._submit_tool_name) - self.state.append_message({"role": "system", "content": _WIND_DOWN_NUDGE}) def _trace_brake_trip( self, @@ -543,7 +564,7 @@ async def _stop_precheck( await self.event_publisher.emit(self.event_factory.error(reason)) self.state.transition_to(SessionPhase.STOPPED, reason=reason) - async def _apply_enforcement_gate(self) -> bool: + async def _apply_enforcement_gate(self, *, step_limit_reached: bool) -> bool: """Choose the next phase when an enforcement brake fires. With enforcement enabled and pending results consumed, budget reserve, @@ -555,8 +576,10 @@ async def _apply_enforcement_gate(self) -> bool: return False if self.state.wind_down_done: if self.state.wind_down_attempts < 2: + self._restrict_to_submit_tool() + if self.state.wind_down_attempts: + self.state.append_message({"role": "system", "content": _WIND_DOWN_RETRY}) self.state.wind_down_attempts += 1 - self.state.append_message({"role": "system", "content": _WIND_DOWN_RETRY}) self.state.transition_to(SessionPhase.CALLING_LLM) return True await self._stop_precheck("wind-down complete: forced commit within reserve") @@ -577,6 +600,19 @@ async def _apply_enforcement_gate(self) -> bool: await self._decide_run_budget(reason="wind_down") budget_spent = (self.max_budget_tokens is not None and self.state.used_tokens >= self.max_budget_tokens - self._commit_reserve) + if ( + budget_spent + and not step_limit_reached + and not self.state.budget_reserve_consumed + and self.state.pending_events.is_empty() + and self.max_budget_tokens is not None + ): + missing = self.state.used_tokens + self._commit_reserve + 1 - self.max_budget_tokens + if self._claim_request_budget(missing, missing): + self._preserve_submit_reserve = True + return False + if self._preserve_submit_reserve and step_limit_reached: + budget_spent = True brake = budget_spent or watchdog_tripped or low_yield_tripped if not brake or not self.state.pending_events.is_empty(): return False @@ -586,6 +622,14 @@ async def _apply_enforcement_gate(self) -> bool: ) return True + await self._begin_wind_down(budget_spent, watchdog_tripped, low_yield_tripped) + self.state.transition_to(SessionPhase.CALLING_LLM) + return True + + async def _begin_wind_down( + self, budget_spent: bool, watchdog_tripped: bool, low_yield_tripped: bool, *, + defer_first_attempt: bool = False, + ) -> None: self._trace_brake_trip(budget_spent, watchdog_tripped, low_yield_tripped) if budget_spent: self.state.budget_reserve_consumed = True @@ -600,8 +644,16 @@ async def _apply_enforcement_gate(self) -> bool: ) ) self._enter_wind_down() - self.state.transition_to(SessionPhase.CALLING_LLM) - return True + if not defer_first_attempt: + self.state.wind_down_attempts += 1 + + def _can_use_preserved_submit_budget(self) -> bool: + return ( + self._preserve_submit_reserve + and not self.state.wind_down_done + and not self.state.budget_reserve_consumed + and self.state.pending_events.is_empty() + ) def _ensure_tool_environment_active(self) -> None: if getattr(self.tool_execution, "environment_revoked", False): @@ -638,9 +690,11 @@ async def precheck(self, cancel_event: asyncio.Event | None) -> None: self.max_budget_tokens is not None and self.state.used_tokens >= self.max_budget_tokens ): - reason = f"budget exceeded: {self.state.used_tokens} tokens used" - await self._stop_precheck(reason) - return + recovery = self._budget_recovery_authority() + if self.state.used_tokens > self.max_budget_tokens or recovery is None or recovery.available() <= 0: + reason = f"{_BUDGET_EXCEEDED_PREFIX} {self.state.used_tokens} tokens used" + await self._stop_precheck(reason) + return # Stop at the aggregate team ceiling even if this session has allowance left, # since an overshooting generation can consume the shared pool. @@ -649,10 +703,11 @@ async def precheck(self, cancel_event: asyncio.Event | None) -> None: await self._stop_precheck(reason) return - if await self._apply_enforcement_gate(): + step_limit_reached = self.max_steps is not None and self.state.step_count >= self.max_steps + if await self._apply_enforcement_gate(step_limit_reached=step_limit_reached): return - if self.max_steps is not None and self.state.step_count >= self.max_steps: + if step_limit_reached: reason = f"step limit reached: {self.state.step_count} steps" await self._stop_precheck(reason) return @@ -671,7 +726,14 @@ async def run_llm_call(self) -> None: tools = self.build_tool_schemas() try: - response = await self.call_llm(tools) + try: + response = await self.call_llm(tools) + except _TokenBudgetStop: + if not self._can_use_preserved_submit_budget(): + raise + self._raise_if_run_cancelled() + await self._begin_wind_down(budget_spent=True, watchdog_tripped=False, low_yield_tripped=False) + response = await self.call_llm(self.build_tool_schemas()) except _RunCancelled: await self._stop_for_run_cancellation() return @@ -689,7 +751,7 @@ async def run_llm_call(self) -> None: if exc.minimum_output_tokens > 1 else "leaving no output headroom" ) reason = ( - "budget exhausted before model call: conservative input reservation " + f"{_REQUEST_BUDGET_REFUSAL_PREFIX} conservative input reservation " f"requires {exc.reserved_input_tokens} of {exc.remaining_budget} " f"remaining tokens, {output_shortfall}" ) @@ -761,9 +823,9 @@ async def handle_pending_response(self) -> None: isinstance(response.content, str) and bool(response.content.strip()) ) + reply_start = len(self.state.messages) - int(has_content) if response.finish_reason == "content_filter": # Settle the filtered reply before observers can suspend the turn. - reply_start = len(self.state.messages) - int(has_content) self.state.append_message({ "role": "system", "content": "[Output filtered by the provider. Session stopped.]", }) @@ -782,7 +844,14 @@ async def handle_pending_response(self) -> None: await self.event_publisher.emit(self.event_factory.text_delta(response.content)) if response.finish_reason in _INCOMPLETE_RESPONSE_REASONS: - reason = "output truncated: provider reached its generation limit" + if response.finish_reason in _OUTPUT_LIMIT_REASONS and self._can_use_preserved_submit_budget(): + await self._begin_wind_down( + budget_spent=True, watchdog_tripped=False, low_yield_tripped=False, + defer_first_attempt=True, + ) + self.state.transition_to(SessionPhase.AUTOSAVING) + return + reason = _TRUNCATED_OUTPUT_REASON self.state.append_message({ "role": "system", "content": "[Output truncated by the provider. Partial response preserved; session stopped.]", @@ -790,6 +859,10 @@ async def handle_pending_response(self) -> None: await self.event_publisher.emit(self.event_factory.error(reason)) self.clear_pending_step() self.state.transition_to(SessionPhase.STOPPED, reason=reason) + if has_content and not getattr(response, "content_from_reasoning", False): + # Team failure delivery reads this reply while the public turn keeps its answer lookup. + self.state.start_active_turn(reply_start) + self.state.clear_active_turn(retain_answer=True) await self.finish_step(pending.latency) return diff --git a/opencollab/application/tool_execution.py b/opencollab/application/tool_execution.py index c0362b6f..15418d0d 100644 --- a/opencollab/application/tool_execution.py +++ b/opencollab/application/tool_execution.py @@ -38,6 +38,7 @@ from opencollab.application.tool_execution_runtime import ( ToolRuntime as ToolRuntime, ) +from opencollab.domain.json_data import loads_finite_json from opencollab.domain.session import SessionState from opencollab.domain.tool_facts import ToolFactsCollector from opencollab.domain.tools import MAX_CALL_HASH_WINDOW as MAX_CALL_HASH_WINDOW @@ -717,10 +718,14 @@ def preflight_rejection_result( def parse_tool_args(self, func: dict) -> dict: args_str = func.get("arguments", "") if isinstance(args_str, dict): + try: + json.dumps(args_str, allow_nan=False) + except (TypeError, ValueError, OverflowError, RecursionError) as exc: + raise json.JSONDecodeError("tool arguments are not JSON-serializable", "", 0) from exc return dict(args_str) if not isinstance(args_str, str): raise ValueError("tool arguments must be a JSON object") - args = json.loads(args_str) if args_str else {} + args = loads_finite_json(args_str) if args_str else {} if not isinstance(args, dict): raise ValueError("tool arguments must be a JSON object") return args diff --git a/opencollab/application/tool_execution_runtime.py b/opencollab/application/tool_execution_runtime.py index 2f124463..4f7145d9 100644 --- a/opencollab/application/tool_execution_runtime.py +++ b/opencollab/application/tool_execution_runtime.py @@ -269,6 +269,7 @@ async def execute_tool( if execution_task is None: result = timeout_result else: + self._track_pending_cleanup(execution_task) cleanup_task = asyncio.create_task(self._cleanup_timed_out_execution(execution_task)) try: quiesced, revoke_error, abort_error = await asyncio.shield(cleanup_task) @@ -289,6 +290,7 @@ async def execute_tool( result = timeout_result + " " + "; ".join(details) + "." except asyncio.CancelledError: if execution_task is not None and not execution_task.done(): + self._track_pending_cleanup(execution_task) cleanup_task = asyncio.create_task(self._cleanup_caller_cancelled_execution(execution_task)) await self._await_owned_cleanup_despite_cancellation(cleanup_task) # The tool can finish before this waiter resumes, including during cleanup. @@ -325,6 +327,9 @@ async def _cleanup_caller_cancelled_execution(self, task: asyncio.Task[Any]) -> await self._cleanup_timed_out_execution(task) async def _cleanup_timed_out_execution(self, task: asyncio.Task[Any]) -> tuple[bool, str | None, str | None]: + owner = asyncio.current_task() + assert owner is not None + self._track_pending_cleanup(owner) task.cancel() cleanup_error = None if await self._wait_task(task, self._cancellation_cleanup_timeout): @@ -335,8 +340,6 @@ async def _cleanup_timed_out_execution(self, task: asyncio.Task[Any]) -> tuple[b cleanup_error = self._task_failure(task, label="tool cancellation cleanup") if cleanup_error is None: return True, None, None - else: - self._track_pending_cleanup(task) revoke_error = self._revoke_environment() abort_error = await self._abort_environment_bounded() if cleanup_error: @@ -350,10 +353,19 @@ async def _await_owned_cleanup_despite_cancellation(self, cleanup_task: asyncio. consume_task_result(cleanup_task) async def _wait_task(self, task: asyncio.Task[Any], timeout: float) -> bool: - done, _pending = await asyncio.wait({task}, timeout=timeout) - if done: - consume_task_result(task) - return bool(done) + loop = asyncio.get_running_loop() + deadline = loop.time() + timeout + while not task.done(): + remaining = deadline - loop.time() + if remaining <= 0: + return False + try: + await asyncio.wait({task}, timeout=remaining) + except asyncio.CancelledError: + # The outer runtime can stop waiting before this cleanup deadline. + pass + consume_task_result(task) + return True def _track_pending_cleanup(self, task: asyncio.Task[Any]) -> None: if task.done() or task in self._pending_cleanup_tasks: diff --git a/opencollab/application/workflow.py b/opencollab/application/workflow.py index 92ec681b..a94947a0 100644 --- a/opencollab/application/workflow.py +++ b/opencollab/application/workflow.py @@ -35,7 +35,7 @@ from copy import deepcopy from typing import Any -from opencollab.application._session_run_shared import _FILTERED_OUTPUT_REASON +from opencollab.application._session_run_shared import _FILTERED_OUTPUT_REASON, _RequestBudgetRecovery from opencollab.application.async_timeout import ( CallerTimeoutError, ) @@ -51,6 +51,8 @@ WorkflowSessionFactoryPort, WorkingTreeProbe, ) +from opencollab.application.provider_failure import provider_http_failure_metadata +from opencollab.application.session_lifecycle import _budget_replay_output_before from opencollab.application.session_run import DEFAULT_COMMIT_RESERVE as DEFAULT_COMMIT_RESERVE from opencollab.application.session_run import ENFORCEMENT_OFF from opencollab.application.structured_output import TOOL_NAME as STRUCTURED_OUTPUT_TOOL_NAME @@ -74,6 +76,7 @@ ) from opencollab.application.workflow_collections import ( WorkflowCollectionsMixin, + _CollectionBudget, _TaskConcurrencyPermit, ) from opencollab.application.workflow_collections import ( @@ -193,6 +196,10 @@ def __init__( self._semaphore = asyncio.Semaphore(max_concurrency) self._task_semaphore = asyncio.Semaphore(task_concurrency) self._sessions: list[Any] = [] + self._candidate_owned_session_ids: set[int] = set() + self._candidate_session_close_failed = False + self._candidate_cleanup_timeout: float | None = None + self._deferred_candidate_cleanups: set[asyncio.Task[None]] = set() # Attribute later agents to the most recently declared workflow phase. self._phase_title: str | None = None self.budget = WorkflowBudget(budget_total, self._sessions) @@ -204,7 +211,7 @@ def __init__( self._active_budget_lease: contextvars.ContextVar[_BudgetLease | None] = ( contextvars.ContextVar("workflow_budget_lease", default=None) ) - self._active_collection_budget: contextvars.ContextVar[int | None] = ( + self._active_collection_budget: contextvars.ContextVar[_CollectionBudget | None] = ( contextvars.ContextVar("workflow_collection_budget", default=None) ) self._active_concurrency_permit: contextvars.ContextVar[ @@ -214,9 +221,12 @@ def __init__( _TaskConcurrencyPermit | None ] = contextvars.ContextVar("workflow_task_concurrency_permit", default=None) self._pending_cleanup_tasks: set[asyncio.Task[Any]] = set() + self._workspace_release_lock = asyncio.Lock() self._workflow_imports: ExitStack | None = None + self._workflow_body_task: asyncio.Task[Any] | None = None self._active_call_tasks: set[asyncio.Task[Any]] = set() self._active_session_tasks: set[asyncio.Task[Any]] = set() + self._environment_acquisitions: set[asyncio.Future[Any]] = set() self._agent_failures: list[dict[str, Any]] = [] self._trace_failures: list[dict[str, str]] = [] self._tree_probe = tree_probe @@ -239,7 +249,8 @@ async def execute_verification( raise TypeError("tool must satisfy the verification tool contract") if not isinstance(params, Mapping): raise TypeError("verification params must be a mapping") - return await self._factory.execute_verification(tool, dict(params)) + with self._own_workflow_call(): + return await self._factory.execute_verification(tool, dict(params)) async def tree_changed(self) -> bool | None: """Whether the working tree has uncommitted changes. @@ -340,8 +351,9 @@ async def _build_workflow_session( *, label: str | None, budget: int | None, - tools: Sequence[Any] | None = None, + tools: str | Sequence[Any] | None = None, isolation: bool | str | None = None, + startup_deadline: float | None = None, **kwargs: Any, ) -> Any: """Build one one-shot session and record that this agent existed. @@ -365,12 +377,20 @@ async def _build_workflow_session( explicit_strategy = isinstance(isolation, str) or default_isolation != "shared" strategy = isolation_name(isolation, default=default_isolation) acquire = getattr(self._factory, "acquire_environment", None) - if callable(acquire): - env = await acquire(isolation=strategy, label=label) - elif strategy in {"shared", "worktree"}: - env = await self._factory.acquire_isolated_env(label=label) if strategy == "worktree" else None + if strategy == "shared": + env = await acquire(isolation=strategy, label=label) if callable(acquire) else None else: - raise ValueError(f"session factory does not support isolation strategy {strategy!r}") + remaining = self._remaining_timeout(startup_deadline) + if callable(acquire): + acquisition = acquire(isolation=strategy, label=label) + elif strategy == "worktree": + acquisition = self._factory.acquire_isolated_env(label=label) + else: + raise ValueError(f"session factory does not support isolation strategy {strategy!r}") + owner = asyncio.ensure_future(acquisition) + self._environment_acquisitions.add(owner) + owner.add_done_callback(self._environment_acquisitions.discard) + env = await self._run_with_timeout(owner, remaining) isolation = strategy != "shared" session = self._factory.build_workflow_session( label=label, @@ -381,6 +401,8 @@ async def _build_workflow_session( **kwargs, ) state = getattr(session, "state", None) + if isinstance(tools, str): + tools = getattr(getattr(session, "agent", None), "tools", ()) self._trace_step( "workflow_agent_started", { @@ -401,6 +423,11 @@ async def _build_workflow_session( ) return session + def _tools_for_capture(self, tools: str | Sequence[Any] | None) -> Sequence[Any]: + if isinstance(tools, str): + return self._factory.resolve_tool_preset(tools) + return tools or () + async def release_isolated_workspaces(self) -> None: """Give back every workspace the factory lent to an isolated agent. @@ -411,24 +438,13 @@ async def release_isolated_workspaces(self) -> None: """ release = getattr(self._factory, "release_isolated_envs", None) if callable(release): - await release() + async with self._workspace_release_lock: + await release() def _record_agent_failure(self, label: str | None, exc: Exception) -> None: - status_code = getattr(exc, "status_code", None) - if isinstance(status_code, bool) or not isinstance(status_code, int): - response = getattr(exc, "response", None) - status_code = getattr(response, "status_code", None) - if isinstance(status_code, bool) or not isinstance(status_code, int): - status_code = None - body = getattr(exc, "body", None) - error = body.get("error") if isinstance(body, dict) else None - if not isinstance(error, dict): - error = body if isinstance(body, dict) else {} - error_type = "content_filter" if self._agent_failure_filtered(exc) else error.get("type") - if not isinstance(error_type, str) or not error_type or len(error_type) > 128: - error_type = None - elif any(not (char.isalnum() or char in "._-") for char in error_type): - error_type = None + status_code, error_type = provider_http_failure_metadata(exc) + if self._agent_failure_filtered(exc): + error_type = "content_filter" record = { "label": str(label or "agent")[:240], "exception_type": type(exc).__name__[:128], @@ -469,7 +485,7 @@ async def wait_for_pending_cleanup(self) -> None: await asyncio.sleep(0) continue saw_empty = False - await asyncio.gather(*pending, return_exceptions=True) + await asyncio.wait(pending) await asyncio.sleep(0) @property @@ -481,6 +497,8 @@ def pending_cleanup_tasks(self) -> tuple[asyncio.Task[Any], ...]: current = None subscriber_tasks: set[asyncio.Task[Any]] = set() for session in self._sessions: + if id(session) in self._candidate_owned_session_ids: + continue for task in getattr(session, "pending_cleanup_tasks", ()): if isinstance(task, asyncio.Task): subscriber_tasks.add(task) @@ -488,6 +506,7 @@ def pending_cleanup_tasks(self) -> tuple[asyncio.Task[Any], ...]: self._pending_cleanup_tasks | self._active_call_tasks | self._active_session_tasks + | self._deferred_candidate_cleanups | subscriber_tasks ) return tuple( @@ -523,7 +542,7 @@ async def agent( *, schema: dict[str, Any] | None = None, label: str | None = None, - tools: Sequence[Any] | None = None, + tools: str | Sequence[Any] | None = None, isolation: bool | str | None = None, tool_choice: Any = None, thinking: bool | None = None, @@ -539,7 +558,10 @@ async def agent( ``budget`` requests a per-call allowance from the remaining shared pool. None shares the available pool. An exhausted pool raises WorkflowBudgetExceeded before session creation unless ``over_budget_ok`` permits the call. + Independent worker tasks can wait for outstanding reservations. + ``tools`` accepts a preset name or a sequence of tools. Structured output + and enforcement add their capture tool to that selection. ``schema`` requires structured_output and returns its validated dictionary. An unsatisfied capture gets one corrective retry carrying gathered history. ``tool_choice`` applies to free-text sessions. Schema sessions instead explore @@ -589,6 +611,7 @@ async def agent( budget, over_budget_ok=over_budget_ok, label=label, + wait_for_release=True, ) permit = self._active_concurrency_permit.get() if permit is None or permit.owner is not call_task: @@ -655,7 +678,7 @@ async def _run_agent( prompt: str, *, label: str | None, - tools: Sequence[Any] | None, + tools: str | Sequence[Any] | None, isolation: bool | str | None, tool_choice: Any = None, thinking: bool | None = None, @@ -673,7 +696,11 @@ async def _run_agent( label=label, tool_choice=tool_choice, thinking=thinking, + startup_deadline=deadline, ) + except CallerTimeoutError: + await self.log(f"agent timed out during workspace setup ({label or 'agent'})") + return None except Exception as exc: # noqa: BLE001 — factory failure must not abort the fleet self._record_agent_failure(label, exc) await self.log(f"agent build failed ({label or 'agent'}): {exc}") @@ -691,7 +718,7 @@ async def _run_agent( return await self._run_session_turn(session, prompt, deadline=deadline, label=label) except CallerTimeoutError: await self.log(f"agent timed out ({label or 'agent'}) after {timeout}s") - return None + return _budget_replay_output_before(session, deadline) except Exception as exc: # noqa: BLE001 — one dead agent never kills the fleet self._record_agent_failure(label, exc) await self.log(f"agent failed ({label or 'agent'}): {exc}") @@ -735,15 +762,30 @@ def _internal_commit_deadline(self) -> float: timeout = min(timeout, remaining) return time.monotonic() + timeout - def _track_session(self, session: Any) -> None: + def _track_session(self, session: Any, *, continue_budget: bool = False) -> None: self.budget._track_session(session) lease = self._active_budget_lease.get() if lease is not None: + previous_spend = lease.spent() lease.sessions.append(session) runner = getattr(session, "runner", None) if lease.reserved and runner is not None: # Other leases keep their allocation when a sibling overspends. runner.budget_reservations.append(lambda: max(0, -int(self.budget.remaining()))) + if ( + (lease.recovery_limit is not None or self.budget._parent_allocation is not None) + and (len(lease.sessions) == 1 or continue_budget) + and lease.total is not None + and previous_spend <= lease.total + and getattr(runner, "hard_budget_tokens", None) == lease.total - previous_spend + and hasattr(runner, "_request_budget_recovery") + ): + runner._request_budget_recovery = _RequestBudgetRecovery( + available=lambda: self.budget._recovery_room(lease), + claim=lambda minimum, preferred: self.budget._claim_recovered_budget( + lease, minimum, preferred, previous_spend=previous_spend, + ), + ) def _active_call_has_pending_cleanup(self) -> bool: lease = self._active_budget_lease.get() diff --git a/opencollab/application/workflow_agent_run.py b/opencollab/application/workflow_agent_run.py index 8b39ba58..4acc106c 100644 --- a/opencollab/application/workflow_agent_run.py +++ b/opencollab/application/workflow_agent_run.py @@ -9,7 +9,8 @@ from dataclasses import dataclass from typing import Any -from opencollab.application.async_timeout import CallerTimeoutError +from opencollab.application.async_timeout import CallerTimeoutError, await_owned_operation +from opencollab.application.session_lifecycle import _budget_replay_output_before, _completed_session_output_before from opencollab.application.workflow_budget import _positive_budget from opencollab.domain.tools import validate_unique_tool_names @@ -100,7 +101,9 @@ async def agent_run( budget_token = None released = False try: - lease = await self._acquire_budget_lease(budget, over_budget_ok=False, label=label) + lease = await self._acquire_budget_lease( + budget, over_budget_ok=False, label=label, wait_for_release=True, + ) async def execute() -> WorkflowAgentResult: nonlocal budget_token, lease, released @@ -114,6 +117,7 @@ async def execute() -> WorkflowAgentResult: lease, cap=budget, over_budget_ok=False, label=label, ) budget_token = self._active_budget_lease.set(lease) + deadline = self._timeout_deadline(timeout) try: options: dict[str, Any] = {} if max_steps is not None: @@ -124,7 +128,14 @@ async def execute() -> WorkflowAgentResult: options["run_control"] = run_control session = await self._build_workflow_session( prompt=prompt, budget=lease.total, tools=tools, - isolation=isolation, label=label, **options, + isolation=isolation, label=label, startup_deadline=deadline, **options, + ) + except CallerTimeoutError: + quiet = await self._settle_agent_run(lease, cleanup_timeout) + return WorkflowAgentResult( + None, "stopped", "timeout", 0, 0, None, lease.total, None, + quiet, quiet and not self._agent_run_environment_unsafe + and not bool(getattr(self._factory, "environment_revoked", False)), ) except Exception as exc: self._record_agent_failure(label, exc) @@ -137,7 +148,7 @@ async def execute() -> WorkflowAgentResult: self._track_session(session) try: output = await self._run_session_turn( - session, prompt, deadline=self._timeout_deadline(timeout), label=label, + session, prompt, deadline=deadline, label=label, ) except CallerTimeoutError: status, reason = "stopped", "timeout" @@ -148,7 +159,7 @@ async def execute() -> WorkflowAgentResult: close = getattr(session, "aclose", None) if quiet and callable(close): try: - await self._run_with_timeout(close(), cleanup_timeout) + await self._run_with_timeout(await_owned_operation(close()), cleanup_timeout) quiet = await self._settle_agent_run(lease, cleanup_timeout) except (CallerTimeoutError, Exception) as exc: self._record_agent_failure(label, exc) @@ -158,6 +169,11 @@ async def execute() -> WorkflowAgentResult: status, reason = "failed", "cleanup incomplete" if getattr(session, "persistence_errors", ()): status, reason = "failed", "session persistence failed" + runner = getattr(session, "runner", None) + if status == "stopped" and reason == "timeout": + output = _completed_session_output_before(session, deadline) + if output is None: + output = _budget_replay_output_before(session, deadline) state = getattr(session, "state", None) phase = getattr(getattr(state, "phase", None), "value", None) terminal_reason = getattr(state, "terminal_reason", None) @@ -166,7 +182,6 @@ async def execute() -> WorkflowAgentResult: reason = terminal_reason elif status == "completed" and phase not in {None, "done"}: status, reason = "stopped", terminal_reason or f"session phase: {phase}" - runner = getattr(session, "runner", None) return WorkflowAgentResult( output, status, reason, int(getattr(session, "used_tokens", 0)), int(getattr(session, "step_count", 0)), @@ -182,7 +197,7 @@ async def execute() -> WorkflowAgentResult: quiet = await self._settle_agent_run(lease, cleanup_timeout) close = getattr(session, "aclose", None) if quiet and callable(close): - await self._run_with_timeout(close(), cleanup_timeout) + await self._run_with_timeout(await_owned_operation(close()), cleanup_timeout) quiet = await self._settle_agent_run(lease, cleanup_timeout) except BaseException: quiet = False diff --git a/opencollab/application/workflow_agents.py b/opencollab/application/workflow_agents.py index 84d9e8a0..a11386fe 100644 --- a/opencollab/application/workflow_agents.py +++ b/opencollab/application/workflow_agents.py @@ -14,10 +14,12 @@ from __future__ import annotations import asyncio +import time from collections.abc import Sequence from typing import Any from opencollab.application.async_timeout import CallerTimeoutError +from opencollab.application.session_lifecycle import _budget_replay_output_before from opencollab.application.session_run import DEFAULT_COMMIT_RESERVE from opencollab.application.submit_findings import ( SUBMIT_TOOL_NAME, @@ -38,7 +40,7 @@ async def _run_enforced_agent( prompt: str, *, label: str | None, - tools: Sequence[Any] | None, + tools: str | Sequence[Any] | None, isolation: bool | str | None, tool_choice: Any, thinking: bool | None, @@ -61,17 +63,20 @@ async def _run_enforced_agent( commit_reserve = max(1, session_budget // 4) capture_done = asyncio.Event() submit_tool = SubmitFindingsTool(on_capture=capture_done.set) - combined_tools = [*(tools or []), submit_tool] try: session = await self._build_workflow_session( prompt=prompt, budget=session_budget, - tools=combined_tools, + tools=[*self._tools_for_capture(tools), submit_tool], isolation=isolation, label=label, tool_choice=tool_choice, thinking=thinking, + startup_deadline=deadline, ) + except CallerTimeoutError: + await self.log(f"agent timed out during workspace setup ({label or 'agent'})") + return harvest_fallback or None except Exception as exc: # noqa: BLE001 — factory failure must not abort the fleet self._record_agent_failure(label, exc) await self.log(f"agent build failed ({label or 'agent'}): {exc}") @@ -92,6 +97,7 @@ async def _run_enforced_agent( cancel_event=capture_done, ) except CallerTimeoutError: + text = _budget_replay_output_before(session, deadline) await self.log(f"agent timed out ({label or 'agent'}) after {timeout}s") except Exception as exc: # noqa: BLE001 — one dead agent never kills the fleet filtered_failure = self._agent_failure_filtered(exc) @@ -150,7 +156,14 @@ async def _synthesize_dead_scout( max_chars=prompt_chars, ) capture_done = asyncio.Event() - submit_tool = SubmitFindingsTool(on_capture=capture_done.set) + accepted_at: float | None = None + + def record_capture() -> None: + nonlocal accepted_at + accepted_at = time.monotonic() + capture_done.set() + + submit_tool = SubmitFindingsTool(on_capture=record_capture) synth_label = f"{label}:synth" if label else "synth" session_budget = self._capped_session_budget(commit_reserve) try: @@ -169,6 +182,7 @@ async def _synthesize_dead_scout( return None self._track_session(session) + deadline = None try: deadline = self._internal_commit_deadline() if caller_deadline is not None: @@ -183,9 +197,12 @@ async def _synthesize_dead_scout( except Exception as exc: # noqa: BLE001 — one dead salvage never kills the fleet self._record_agent_failure(synth_label, exc) await self.log(f"dead-scout synth failed ({synth_label}): {exc}") - return None + if not isinstance(exc, CallerTimeoutError) or accepted_at is None: + return None captured = submit_tool.captured + if accepted_at is not None and (deadline is None or accepted_at >= deadline): + captured = None report = format_findings_report(captured) if captured is not None else "" self._emit_dead_scout_synthesis(synth_label, ledger, captured, bool(report.strip())) return report if report.strip() else None @@ -207,11 +224,13 @@ async def draft_findings( already_owned = call_task in self._active_call_tasks if call_task is not None: self._active_call_tasks.add(call_task) + lease = None async def run_with_lease() -> dict[str, Any] | None: + nonlocal lease try: - lease = await self._acquire_budget_lease( - budget, over_budget_ok=False, label=label + lease = await self._refresh_budget_lease( + lease, cap=budget, over_budget_ok=False, label=label, ) except WorkflowBudgetExceeded: return None @@ -228,10 +247,19 @@ async def run_with_lease() -> dict[str, Any] | None: lease, release_slot=False, ) + lease = None try: + try: + lease = await self._acquire_budget_lease( + budget, over_budget_ok=False, label=label, wait_for_release=True, + ) + except WorkflowBudgetExceeded: + return None return await self._run_with_concurrency_permit(run_with_lease) finally: + if lease is not None: + self.budget.release(lease) if call_task is not None and not already_owned: self._active_call_tasks.discard(call_task) diff --git a/opencollab/application/workflow_budget.py b/opencollab/application/workflow_budget.py index a5912a1d..359e281c 100644 --- a/opencollab/application/workflow_budget.py +++ b/opencollab/application/workflow_budget.py @@ -9,7 +9,7 @@ from dataclasses import dataclass from typing import Any -from opencollab.application.workflow_collections import WorkflowBudgetExceeded +from opencollab.application.workflow_collections import WorkflowBudgetExceeded, _CollectionBudget logger = logging.getLogger(__name__) @@ -45,10 +45,13 @@ def __init__(self, total: int | None, sessions: list[Any]) -> None: self._total = total self._sessions = sessions self._leases: list[_BudgetLease] = [] + self._release_event: asyncio.Event | None = None self._parent_allocation: tuple[WorkflowBudget, _BudgetLease] | None = None @property def total(self) -> int | None: + if self._total is not None and self._parent_allocation is not None: + return self._parent_allocation[1].total return self._total def spent(self) -> int: @@ -62,9 +65,9 @@ def _track_session(self, session: Any) -> None: parent._track_session(session) def remaining(self) -> float: - if self._total is None: + total = self.total + if total is None: return float("inf") - total = self._total spent = self.spent() if self._parent_allocation is not None: parent, allocation = self._parent_allocation @@ -80,7 +83,71 @@ def release(self, lease: _BudgetLease) -> None: try: self._leases.remove(lease) except ValueError: - pass + return + if self._release_event is not None: + self._release_event.set() + self._release_event = None + + def _watch_release(self) -> asyncio.Event: + if self._release_event is None: + self._release_event = asyncio.Event() + return self._release_event + + def _parent_recovery_room(self) -> int: + if self._parent_allocation is None: + return 0 + parent, allocation = self._parent_allocation + return parent._recovery_room(allocation) + + def _collection_recovery_share(self, collection: _CollectionBudget, free: int) -> int: + # Reservations held by this collection already count toward its share. + reserved = sum( + lease.remaining() for lease in self._leases if collection.includes(lease.collection) + ) + balance = max(collection.entry_balance, free + int(reserved)) + if collection.parent is not None: + balance = min(balance, self._collection_recovery_share(collection.parent, free)) + collection.recovered_share = max(collection.recovered_share, balance // collection.size) + return collection.recovered_share + + def _recovery_room(self, lease: _BudgetLease) -> int: + if lease.total is None or lease not in self._leases: + return 0 + limit = lease.recovery_limit + if limit is None and self._parent_allocation is None: + return 0 + free = int(self.remaining()) + self._parent_recovery_room() + if free <= 0: + return 0 + if limit is None: + return free + if isinstance(limit, _CollectionBudget): + limit = self._collection_recovery_share(limit, free) + return max(0, min(limit - lease.total, free)) + + def _claim_parent_capacity(self, tokens: int) -> None: + if self._parent_allocation is None: + return + missing = tokens - int(self.remaining()) + if missing > 0: + parent, allocation = self._parent_allocation + parent._extend_lease(allocation, missing) + + def _extend_lease(self, lease: _BudgetLease, tokens: int) -> None: + self._claim_parent_capacity(tokens) + assert lease.total is not None + lease.total += tokens + lease.reserved = lease.total + + def _claim_recovered_budget( + self, lease: _BudgetLease, minimum: int, preferred: int, *, previous_spend: int, + ) -> int | None: + growth = min(preferred, self._recovery_room(lease)) + if growth < minimum: + return None + self._extend_lease(lease, growth) + assert lease.total is not None + return lease.total - previous_spend @dataclass class _BudgetEscapeState: @@ -88,6 +155,7 @@ class _BudgetEscapeState: lock: asyncio.Lock used: bool = False + allowed: bool = True @dataclass(eq=False) class _BudgetLease: @@ -97,12 +165,16 @@ class _BudgetLease: reserved: int sessions: list[Any] pending_tasks: list[asyncio.Task[Any]] | None = None + recovery_limit: int | _CollectionBudget | None = None + collection: _CollectionBudget | None = None + + def spent(self) -> int: + return sum(max(0, int(getattr(session, "used_tokens", 0))) for session in self.sessions) def remaining(self) -> float: if self.total is None: return float("inf") - spent = sum(max(0, int(getattr(s, "used_tokens", 0))) for s in self.sessions) - return max(0, self.total - spent) + return max(0, self.total - self.spent()) @dataclass class _ConcurrencyPermit: @@ -131,7 +203,8 @@ async def _refresh_budget_lease( return await self._acquire_budget_lease( cap, over_budget_ok=over_budget_ok, label=label, ) - lease.total = min(lease.total, available) + # An explicitly capped call can use tokens returned while it was queued. + lease.total = min(lease.total if cap is None else cap, available) lease.reserved = lease.total return lease @@ -205,79 +278,106 @@ async def _acquire_budget_lease( *, over_budget_ok: bool, label: str | None = None, + wait_for_release: bool = False, ) -> _BudgetLease: - """Atomically reserve one agent call's maximum token allocation. - - ``label`` is carried for the trace record only — it names the caller in - ``budget_refusal`` / ``budget_escape`` and changes no allocation. - """ + """Reserve call capacity before agent admission.""" cap = _positive_budget(cap) if getattr(self, "_limit_mode", "environment") == "environment" and _unbounded_limits_enabled(): return _BudgetLease(total=None, reserved=0, sessions=[]) + # The workflow body can be responsible for letting its workers finish. + can_wait = ( + wait_for_release + and self._workflow_body_task is not asyncio.current_task() + and self._active_budget_lease.get() is None + and self._active_concurrency_permit.get() is None + ) self._budget_waiters += 1 try: - # Let sibling tasks launched by one gather register as contenders - # before the first uncapped caller chooses its share. + # Register sibling calls before the first uncapped allowance is chosen. await asyncio.sleep(0) - async with self._budget_lock: - remaining = self.budget.remaining() - if remaining == float("inf"): - total = max(0, cap) if cap is not None else None - return _BudgetLease(total=total, reserved=0, sessions=[]) - - available = max(0, int(remaining)) - if available <= 0 and not over_budget_ok: + while True: + async with self._budget_lock: + remaining = self.budget.remaining() + if remaining == float("inf"): + return _BudgetLease(total=cap, reserved=0, sessions=[]) + + available = max(0, int(remaining)) + recoverable = max(0, int(remaining) + self.budget._parent_recovery_room()) + initial = available or min(1, recoverable) + total = self.budget.total + if ( + can_wait and initial == 0 and total is not None + and self.budget.spent() < total + and any(lease.remaining() > 0 for lease in self.budget._leases) + ): + released = self.budget._watch_release() + else: + return await self._reserve_available_budget( + cap, available, initial, remaining, over_budget_ok=over_budget_ok, label=label, + ) + await released.wait() + finally: + self._budget_waiters -= 1 + + async def _reserve_available_budget( + self, cap: int | None, available: int, initial: int, remaining: float, + *, over_budget_ok: bool, label: str | None, + ) -> _BudgetLease: + if initial <= 0 and not (over_budget_ok and self._budget_escape_state.allowed): + self._trace_budget_decision( + "budget_refusal", + cap=cap, + remaining=remaining, + label=label, + over_budget_ok=over_budget_ok, + ) + raise WorkflowBudgetExceeded( + f"workflow budget exhausted: spent {self.budget.spent()} " + f"of {self.budget.total}" + ) + if over_budget_ok and initial <= 0: + async with self._budget_escape_state.lock: + if self._budget_escape_state.used: self._trace_budget_decision( "budget_refusal", cap=cap, remaining=remaining, label=label, + over_budget_ok=True, ) raise WorkflowBudgetExceeded( f"workflow budget exhausted: spent {self.budget.spent()} " - f"of {self.budget.total}" - ) - if over_budget_ok and available <= 0: - async with self._budget_escape_state.lock: - if self._budget_escape_state.used: - self._trace_budget_decision( - "budget_refusal", - cap=cap, - remaining=remaining, - label=label, - over_budget_ok=True, - ) - raise WorkflowBudgetExceeded( - f"workflow budget exhausted: spent {self.budget.spent()} " - f"of {self.budget.total}; the one over-budget escape " - "has already been used" - ) - # Claim before tracing/building so failures cannot turn the - # one-shot escape into a retry loop. - self._budget_escape_state.used = True - self._trace_budget_decision( - "budget_escape", - cap=cap, - remaining=remaining, - label=label, - over_budget_ok=True, + f"of {self.budget.total}; the one over-budget escape " + "has already been used" ) - total = max(0, cap) if cap is not None else UNBOUNDED_SESSION_BUDGET - return _BudgetLease(total=total, reserved=0, sessions=[]) - - if cap is None: - collection_share = self._active_collection_budget.get() - if collection_share is not None: - total = min(collection_share, available) - else: - total = max( - 1, - available // max(1, self._budget_waiters), - ) - else: - total = min(max(0, cap), available) - lease = _BudgetLease(total=total, reserved=total, sessions=[]) - self.budget.reserve(lease) - return lease - finally: - self._budget_waiters -= 1 + # Claim before tracing/building so failures cannot turn the + # one-shot escape into a retry loop. + self._budget_escape_state.used = True + self._trace_budget_decision( + "budget_escape", + cap=cap, + remaining=remaining, + label=label, + over_budget_ok=True, + ) + total = max(0, cap) if cap is not None else UNBOUNDED_SESSION_BUDGET + return _BudgetLease(total=total, reserved=0, sessions=[]) + + collection = self._active_collection_budget.get() + recovery_limit = None + if cap is not None: + total = min(cap, initial) + if self.budget._parent_allocation is not None: + recovery_limit = cap + elif collection is not None: + total = min(collection.entry_share, initial) + recovery_limit = collection + else: + total = max(1, initial // max(1, self._budget_waiters)) + lease = _BudgetLease( + total=total, reserved=total, sessions=[], recovery_limit=recovery_limit, collection=collection, + ) + if total > available: + self.budget._claim_parent_capacity(total) + self.budget.reserve(lease) + return lease diff --git a/opencollab/application/workflow_candidates.py b/opencollab/application/workflow_candidates.py index e6d0774d..b407d142 100644 --- a/opencollab/application/workflow_candidates.py +++ b/opencollab/application/workflow_candidates.py @@ -10,9 +10,12 @@ from dataclasses import dataclass, replace from typing import Any -from opencollab.application.async_timeout import CallerTimeoutError, await_owned_operation +from opencollab.application._session_run_shared import _BUDGET_EXCEEDED_PREFIX, _REQUEST_BUDGET_REFUSAL_PREFIX +from opencollab.application.async_timeout import CallerTimeoutError, await_owned_operation, consume_task_result from opencollab.application.exception_notes import add_exception_note +from opencollab.application.session_lifecycle import _budget_replay_output_before, close_session_resources from opencollab.application.workflow_budget import _BudgetLease +from opencollab.domain.session import SessionPhase def _candidate_budget_total(budget: int | None, limit_mode: str = "environment") -> int | None: @@ -62,6 +65,7 @@ class CandidateRun: delivery_diff: str | None = None delivery_paths: tuple[str, ...] = () delivery_source_diff: str | None = None + initial_budget_refusal: str | None = None @property def effective_diff(self) -> str: @@ -69,6 +73,19 @@ def effective_diff(self) -> str: return self.diff return self.delivery_diff +def _initial_budget_refusal(session: Any) -> str | None: + state = getattr(session, "state", None) + reason = getattr(state, "terminal_reason", None) + if ( + getattr(state, "phase", None) is SessionPhase.STOPPED + and getattr(state, "step_count", None) == 0 + and getattr(state, "used_tokens", None) == 0 + and isinstance(reason, str) + and reason.startswith((_BUDGET_EXCEEDED_PREFIX, _REQUEST_BUDGET_REFUSAL_PREFIX)) + ): + return reason + return None + class CandidateCaptureError(RuntimeError): """A candidate worktree survived but its diff could not be captured.""" @@ -123,7 +140,6 @@ def __init__(self, factory: Any, environment: Any) -> None: self._factory = factory self._environment = environment self._isolated_environments: list[tuple[Any, Any]] = [] - self._isolated_sessions: list[Any] = [] def model_request_window(self) -> tuple[float | None, float] | None: read = getattr(self._factory, "model_request_window", None) @@ -141,6 +157,9 @@ def has_pending_isolated_cleanup(self) -> bool: def default_isolation(self): return getattr(self._factory, "default_isolation", "shared") + def resolve_tool_preset(self, name: str) -> Sequence[Any]: + return self._factory.resolve_tool_preset(name) + async def acquire_environment(self, *, isolation, label=None, environment=None): owner = self._environment if environment is None else environment if isolation == "shared": @@ -175,52 +194,17 @@ def build_workflow_session(self, **kwargs: Any) -> Any: environment = kwargs.get("env") if environment is None: environment = self._environment - session = self._factory.build_workflow_session(**{**kwargs, "env": environment}) - if any( - owner is self._environment and environment is isolated - for owner, isolated in self._isolated_environments - ): - self._isolated_sessions.append(session) - return session + return self._factory.build_workflow_session(**{**kwargs, "env": environment}) async def release_isolated_envs(self, *, environment: Any | None = None) -> None: owner = self._environment if environment is None else environment if not any(source is owner for source, _isolated in self._isolated_environments): return - errors: list[Exception] = [] - sessions = self._isolated_sessions if owner is self._environment else [] - for session in sessions: - close = getattr(session, "aclose", None) - if callable(close): - try: - await close() - except Exception as exc: - errors.append(exc) - active = any( - not task.done() - for session in sessions - for task in getattr(session, "pending_cleanup_tasks", ()) - if isinstance(task, asyncio.Future) - ) - if active: - errors.append(RuntimeError("isolated session retains active cleanup")) - else: - release = getattr(self._factory, "release_isolated_envs", None) - try: - if not callable(release) or not _accepts_environment(release): - raise TypeError("candidate isolation requires environment-scoped release") - await release(environment=owner) - except Exception as exc: - errors.append(exc) - else: - self._isolated_environments = [ - pair for pair in self._isolated_environments if pair[0] is not owner - ] - if owner is self._environment: - self._isolated_sessions.clear() - if errors: - detail = "; ".join(f"{type(error).__name__}: {error}" for error in errors) - raise RuntimeError(f"candidate isolation cleanup failed: {detail}") from errors[0] + release = getattr(self._factory, "release_isolated_envs", None) + if not callable(release) or not _accepts_environment(release): + raise TypeError("candidate isolation requires environment-scoped release") + await release(environment=owner) + self._isolated_environments = [pair for pair in self._isolated_environments if pair[0] is not owner] async def execute_verification( self, @@ -258,20 +242,6 @@ def _candidate_verification_tools(tools: Sequence[Any]) -> list[Any]: class WorkflowCandidatesMixin: """Runs agent sessions in candidate leases and adopts a selected diff.""" - async def _run_owned_candidate_call( - self, operation: Callable[[], Awaitable[CandidateRun]], - ) -> CandidateRun: - """Own acquisition, execution, capture, and cleanup as one call.""" - current = asyncio.current_task() - already_owned = current in self._active_call_tasks - if current is not None: - self._active_call_tasks.add(current) - try: - return await operation() - finally: - if current is not None and not already_owned: - self._active_call_tasks.discard(current) - async def _candidate_source_state(self) -> tuple[str | None, str, str | None]: read_revision = getattr(self._candidate_workspace, "source_revision", None) revision = await read_revision() if callable(read_revision) else None @@ -379,15 +349,16 @@ async def run_candidate() -> CandidateRun: env=lease.environment, ) self._track_session(session) + deadline = self._timeout_deadline(timeout) try: output = await self._run_session_turn( session, prompt, - deadline=self._timeout_deadline(timeout), + deadline=deadline, label=label, ) except CallerTimeoutError: - output = None + output = _budget_replay_output_before(session, deadline) await self.log( f"candidate agent timed out ({label}) after {timeout}s" ) @@ -440,6 +411,7 @@ async def run_candidate() -> CandidateRun: delivery_diff=getattr(lease, "delivery_diff", None), delivery_paths=getattr(lease, "delivery_paths", ()), delivery_source_diff=diff if getattr(lease, "delivery_diff", None) is not None else None, + initial_budget_refusal=_initial_budget_refusal(session), ) except BaseException as exc: failure = exc @@ -473,13 +445,16 @@ async def run() -> CandidateRun: return_exceptions=True, ) # Register with gather siblings before candidate setup takes a session slot. - budget_lease = await self._acquire_budget_lease(budget, over_budget_ok=False, label=label) + budget_lease = await self._acquire_budget_lease( + budget, over_budget_ok=False, label=label, wait_for_release=True, + ) try: return await self._run_with_concurrency_permit(run_candidate) finally: self.budget.release(budget_lease) - return await self._run_owned_candidate_call(run) + with self._own_workflow_call(): + return await run() async def candidate_workflow( self, @@ -500,10 +475,17 @@ async def candidate_workflow( async def run() -> CandidateRun: self._raise_if_environment_revoked() - source_before = await self._candidate_source_state() - self._raise_if_environment_revoked() - lease = await self._candidate_workspace.acquire(label) - budget_lease = None + budget_lease = await self._acquire_budget_lease( + budget, over_budget_ok=False, label=label, wait_for_release=True, + ) + try: + self._raise_if_environment_revoked() + source_before = await self._candidate_source_state() + self._raise_if_environment_revoked() + lease = await self._candidate_workspace.acquire(label) + except BaseException: + self.budget.release(budget_lease) + raise child = None imports = ExitStack() candidate: CandidateRun | None = None @@ -511,9 +493,8 @@ async def run() -> CandidateRun: preserve_lease = False try: self._raise_if_environment_revoked() - budget_lease = await self._acquire_budget_lease( - budget, - over_budget_ok=False, + budget_lease = await self._refresh_budget_lease( + budget_lease, cap=budget, over_budget_ok=False, label=label, ) self._raise_if_environment_revoked() workspace = getattr(lease.environment, "workspace", None) @@ -543,12 +524,15 @@ async def run() -> CandidateRun: child._budget_escape_state = self._budget_escape_state child.budget._parent_allocation = (self.budget, budget_lease) child._workflow_imports = imports + budget_token = self._active_budget_lease.set(budget_lease) try: - output = await workflow_fn(child, dict(args)) + output = await child._run_workflow_body(workflow_fn, dict(args)) except Exception as exc: # noqa: BLE001 - preserve candidate edits output = None self._record_agent_failure(label, exc) await self.log(f"candidate workflow failed ({label}): {exc}") + finally: + self._active_budget_lease.reset(budget_token) await child.wait_for_pending_cleanup() try: capture = inspect.getattr_static(lease, "capture_changes", None) @@ -598,8 +582,62 @@ async def run() -> CandidateRun: failure = exc finally: cleanup_quiesced = child is None + deferred = False + + def release_child_scope() -> None: + if child is not None: + child._workflow_imports = None + imports.close() + self.budget.release(budget_lease) + + async def wait_owned(owner: Awaitable[Any]) -> None: + nonlocal failure + try: + await await_owned_operation(owner, propagate_cancellation=True) + except asyncio.CancelledError as exc: + if failure is None: + failure = exc + try: if child is not None: + recovery_required = preserve_lease + + async def finish_child() -> None: + errors: list[BaseException] = [] + try: + closed = await close_session_resources(sessions, timeout=None, errors=errors) + await child.wait_for_pending_cleanup() + for session in sessions: + enqueue = getattr(session, "enqueue_auto_save", None) + if callable(enqueue): + try: + enqueue() + except Exception as exc: + errors.append(exc) + self._candidate_session_close_failed |= not closed or bool(errors) + await child.wait_for_pending_cleanup() + await _wait_for_candidate_cleanup(budget_lease) + try: + await child.release_isolated_workspaces() + except Exception as exc: + errors.append(exc) + if errors: + detail = "; ".join(f"{type(error).__name__}: {error}" for error in errors) + raise RuntimeError(f"candidate workflow cleanup failed: {detail}") from errors[0] + finally: + if deferred: + try: + if ( + not child.pending_cleanup_tasks + and not child._factory.has_pending_isolated_cleanup + ): + if not recovery_required: + await lease.cleanup() + elif callable(inspect.getattr_static(lease, "close_execution", None)): + await lease.close_execution() + finally: + release_child_scope() + try: if isinstance(failure, asyncio.CancelledError): child._agent_run_environment_unsafe = True @@ -607,8 +645,23 @@ async def run() -> CandidateRun: for active in tuple(child._active_call_tasks): if active is not current: active.cancel() - await child.wait_for_pending_cleanup() - await child.release_isolated_workspaces() + await wait_owned(child.wait_for_pending_cleanup()) + sessions = child.sessions + self._candidate_owned_session_ids.update(map(id, sessions)) + cleanup = asyncio.create_task(finish_child()) + timeout = self._candidate_cleanup_timeout + if timeout is not None: + await wait_owned(asyncio.wait({cleanup}, timeout=timeout)) + deferred = not cleanup.done() + if deferred: + preserve_lease = True + self._deferred_candidate_cleanups.add(cleanup) + cleanup.add_done_callback(consume_task_result) + raise TimeoutError("candidate workflow cleanup exceeded its deadline") + await wait_owned(cleanup) + if cleanup.cancelled(): + raise RuntimeError("candidate workflow cleanup was cancelled") + cleanup.result() cleanup_quiesced = True except Exception as exc: detail = f"{type(exc).__name__}: {exc}" @@ -630,7 +683,7 @@ async def run() -> CandidateRun: **agent_failure, "label": f"{label}/{agent_failure.get('label', 'agent')}"[:240], }) - if budget_lease is not None: + if not deferred: pending = [task for task in budget_lease.pending_tasks or () if not task.done()] if pending: await asyncio.gather(*pending, return_exceptions=True) @@ -639,17 +692,15 @@ async def run() -> CandidateRun: getattr(child._factory, "has_pending_isolated_cleanup", False) ) finally: - if child is not None: - child._workflow_imports = None - imports.close() - if budget_lease is not None: - self.budget.release(budget_lease) + if not deferred: + release_child_scope() return await self._finish_candidate_run( lease, candidate, failure, label=label, preserve_lease=preserve_lease, cleanup_quiesced=cleanup_quiesced, ) - return await self._run_owned_candidate_call(run) + with self._own_workflow_call(): + return await run() async def adopt_candidate( self, @@ -662,24 +713,24 @@ async def adopt_candidate( raise RuntimeError("candidate workspaces are not available") if not isinstance(candidate, CandidateRun): raise TypeError("candidate must be a CandidateRun") - read_revision = getattr(self._candidate_workspace, "source_revision", None) - if ( - candidate.source_revision is not None - and callable(read_revision) - and await read_revision() != candidate.source_revision - ): - raise CandidateWorkspaceTrackingError( - f"source worktree changed before candidate adoption {candidate.label}" - ) - self._raise_if_environment_revoked() - adopt_run = getattr(self._candidate_workspace, "adopt_run", None) - if callable(adopt_run): - # Full-environment backends must retain the chosen candidate's - # identity even when two candidates have identical file diffs. - operation = adopt_run(candidate, preserve_paths) - else: - operation = self._candidate_workspace.adopt(candidate.diff, preserve_paths) - await await_owned_operation(operation, propagate_cancellation=True) + with self._own_workflow_call(): + read_revision = getattr(self._candidate_workspace, "source_revision", None) + if ( + candidate.source_revision is not None + and callable(read_revision) + and await read_revision() != candidate.source_revision + ): + raise CandidateWorkspaceTrackingError( + f"source worktree changed before candidate adoption {candidate.label}" + ) + self._raise_if_environment_revoked() + adopt_run = getattr(self._candidate_workspace, "adopt_run", None) + if callable(adopt_run): + # Full-environment backends need the chosen identity even for identical diffs. + operation = adopt_run(candidate, preserve_paths) + else: + operation = self._candidate_workspace.adopt(candidate.diff, preserve_paths) + await await_owned_operation(operation, propagate_cancellation=True) __all__ = [ "CandidateCaptureError", diff --git a/opencollab/application/workflow_collections.py b/opencollab/application/workflow_collections.py index d11c746c..9ced33e1 100644 --- a/opencollab/application/workflow_collections.py +++ b/opencollab/application/workflow_collections.py @@ -20,6 +20,27 @@ class WorkflowBudgetExceeded(Exception): class WorkflowEnvironmentRevoked(RuntimeError): """The shared workflow environment can no longer execute agent work.""" +@dataclass(eq=False) +class _CollectionBudget: + size: int + entry_balance: int + parent: _CollectionBudget | None + recovered_share: int = 0 + + @property + def entry_share(self) -> int: + balance = self.entry_balance + if self.parent is not None: + balance = min(balance, self.parent.entry_share) + return max(1, balance // self.size) + + def includes(self, member: _CollectionBudget | None) -> bool: + while member is not None: + if member is self: + return True + member = member.parent + return False + @dataclass class _TaskPermitState: """Shared state for one context-wide task-concurrency slot.""" @@ -33,7 +54,7 @@ class _TaskConcurrencyPermit: owner: asyncio.Task[Any] | None state: _TaskPermitState - child_lock: asyncio.Lock + child_slot: asyncio.Semaphore closed: bool = False class WorkflowCollectionsMixin: @@ -46,6 +67,41 @@ async def _release_task_slot_after_borrowers( await state.borrowers_done.wait() self._task_semaphore.release() + async def _acquire_child_task_slot(self, inherited: asyncio.Semaphore) -> asyncio.Semaphore: + shared = self._task_semaphore + if self._task_concurrency == 1 or not inherited.locked(): + await inherited.acquire() + return inherited + if not shared.locked(): + await shared.acquire() + return shared + + requests = {asyncio.create_task(slot.acquire()): slot for slot in (inherited, shared)} + selected = None + + async def release_unused() -> None: + unused = [task for task in requests if task is not selected] + for task in unused: + task.cancel() + await asyncio.gather(*unused, return_exceptions=True) + for task in unused: + if not task.cancelled() and task.exception() is None: + requests[task].release() + + try: + done, _ = await asyncio.wait(requests, return_when=asyncio.FIRST_COMPLETED) + winner = next(task for task in requests if task in done) + winner.result() + selected = winner + return requests[winner] + finally: + # Both reservations can succeed before the waiting task is scheduled. + try: + await await_owned_operation(release_unused(), propagate_cancellation=True) + except BaseException: + if selected is not None: + requests[selected].release() + raise async def _run_with_task_concurrency_permit( self, operation: Callable[[], Awaitable[Any]], @@ -57,10 +113,13 @@ async def _run_with_task_concurrency_permit( if active.owner is current: return await operation() - # ContextVars are copied into child Tasks. Let one child at a time - # borrow the parent's live slot, which keeps nested gather() - # compositions deadlock-free at task_concurrency=1. - async with active.child_lock: + # Child tasks may borrow a parent's slot or use spare global capacity. + slot = await self._acquire_child_task_slot(active.child_slot) + if slot is self._task_semaphore: + # Shared-slot work can outlive the parent that launched it. + with self._own_workflow_call(): + return await self._run_with_acquired_task_slot(operation) + try: if not active.closed: state = active.state state.borrowers += 1 @@ -68,7 +127,7 @@ async def _run_with_task_concurrency_permit( borrowed = _TaskConcurrencyPermit( owner=current, state=state, - child_lock=asyncio.Lock(), + child_slot=asyncio.Semaphore(1), ) token = self._active_task_concurrency_permit.set(borrowed) try: @@ -79,6 +138,8 @@ async def _run_with_task_concurrency_permit( state.borrowers -= 1 if state.borrowers == 0: state.borrowers_done.set() + finally: + slot.release() await self._task_semaphore.acquire() return await self._run_with_acquired_task_slot(operation) @@ -98,7 +159,7 @@ async def _run_with_acquired_task_slot( permit = _TaskConcurrencyPermit( owner=current, state=state, - child_lock=asyncio.Lock(), + child_slot=asyncio.Semaphore(1), ) token = self._active_task_concurrency_permit.set(permit) try: @@ -124,7 +185,8 @@ def _start_acquired_task_worker( async def run() -> Any: nonlocal started started = True - return await self._run_with_acquired_task_slot(operation) + with self._own_workflow_call(): + return await self._run_with_acquired_task_slot(operation) def release_unstarted(_task: asyncio.Task[Any]) -> None: if not started: @@ -143,21 +205,16 @@ async def _bounded_collection( if size == 0: return [] - remaining = self.budget.remaining() - if remaining == float("inf"): - planned_budget = None - else: - available = max(0, int(remaining)) - parent_budget = self._active_collection_budget.get() - if parent_budget is not None: - available = min(available, parent_budget) - planned_budget = max(1, available // size) if available else 0 + starting_balance = self.budget.remaining() + available_at_entry = int(starting_balance) if 0 < starting_balance < float("inf") else 0 + collection_budget = _CollectionBudget(size, available_at_entry, self._active_collection_budget.get()) + results: list[Any] = [None] * size next_index = iter(range(size)) errors: dict[int, BaseException] = {} async def execute(index: int) -> None: - budget_token = self._active_collection_budget.set(planned_budget) + budget_token = self._active_collection_budget.set(collection_budget) try: results[index] = await self._run_with_task_concurrency_permit( lambda: run_unit(index) diff --git a/opencollab/application/workflow_runtime.py b/opencollab/application/workflow_runtime.py index 5706f3c1..c3ce7b20 100644 --- a/opencollab/application/workflow_runtime.py +++ b/opencollab/application/workflow_runtime.py @@ -13,7 +13,8 @@ import asyncio import math import time -from collections.abc import Awaitable, Callable +from collections.abc import Awaitable, Callable, Iterator +from contextlib import contextmanager from typing import Any from opencollab.application.async_timeout import ( @@ -27,6 +28,27 @@ class WorkflowRuntimeMixin: """Call cleanup, concurrency permits, and timeout helpers.""" + async def _run_workflow_body( + self, workflow_fn: Callable[[Any, dict[str, Any]], Awaitable[Any]], args: dict[str, Any], + ) -> Any: + self._workflow_body_task = asyncio.current_task() + try: + return await workflow_fn(self, args) + finally: + self._workflow_body_task = None + + @contextmanager + def _own_workflow_call(self) -> Iterator[None]: + current = asyncio.current_task() + already_owned = current in self._active_call_tasks + if current is not None: + self._active_call_tasks.add(current) + try: + yield + finally: + if current is not None and not already_owned: + self._active_call_tasks.discard(current) + @staticmethod def _lease_cleanup_tasks( lease: Any, diff --git a/opencollab/application/workflow_structured.py b/opencollab/application/workflow_structured.py index 7f2dec7d..7f9ad97d 100644 --- a/opencollab/application/workflow_structured.py +++ b/opencollab/application/workflow_structured.py @@ -73,7 +73,7 @@ async def _run_structured_agent( *, schema: dict[str, Any], label: str | None, - tools: Sequence[Any] | None, + tools: str | Sequence[Any] | None, isolation: bool | str | None, timeout: float | None = None, budget: int | None = None, @@ -90,15 +90,15 @@ async def _run_structured_agent( capture_done = asyncio.Event() capture_tool = StructuredOutputTool(schema, on_capture=capture_done.set) seeded_prompt = prompt + _STRUCTURED_INSTRUCTION - combined_tools = [capture_tool, *(tools or [])] session_budget = self._capped_session_budget(budget) try: session = await self._build_workflow_session( prompt=seeded_prompt, budget=session_budget, - tools=combined_tools, + tools=[capture_tool, *self._tools_for_capture(tools)], isolation=isolation, label=label, + startup_deadline=deadline, # Inherit the run-wide reasoning setting rather than forcing it # off. Hard-coding it off here exempted every schema-bound agent # from a setting the run had declared, which reads back from the @@ -107,6 +107,9 @@ async def _run_structured_agent( # on is trying to hold equal. thinking=None, ) + except CallerTimeoutError: + await self.log(f"structured agent timed out during workspace setup ({label or 'agent'})") + return None except Exception as exc: # noqa: BLE001 — factory failure must not abort the fleet self._record_agent_failure(label, exc) await self.log(f"structured agent build failed ({label or 'agent'}): {exc}") @@ -131,8 +134,10 @@ async def _run_structured_agent( await self.log(f"structured agent input exceeded provider limits ({label or 'agent'})") return None except CallerTimeoutError: + # The deadline can expire during persistence after the tool captured a result. + captured = None if self._agent_output_filtered(session) else capture_tool.captured await self.log(f"structured agent timed out ({label or 'agent'}) after {timeout}s") - return None + return captured if _schema_satisfied(captured, schema) else None except Exception as exc: # noqa: BLE001 — one dead agent never kills the fleet self._record_agent_failure(label, exc) await self.log(f"structured agent failed ({label or 'agent'}): {exc}") @@ -202,6 +207,7 @@ async def _forced_structured_commit( isolation=isolation, label=label, tool_choice=_named_tool_choice(capture_tool.name), + startup_deadline=deadline, # Inherit here too, for the same reason as the first pass. The # original rationale for forcing it off -- that reasoning makes # the model answer in free text instead of calling the capture @@ -211,12 +217,16 @@ async def _forced_structured_commit( # the caller's own timeout already bounds. thinking=None, ) + except CallerTimeoutError: + await self.log(f"structured retry timed out during workspace setup ({label or 'agent'})") + captured = capture_tool.captured + return captured if _schema_satisfied(captured, schema) else None except Exception as exc: # noqa: BLE001 — factory failure must not abort the fleet self._record_agent_failure(label, exc) await self.log(f"structured retry build failed ({label or 'agent'}): {exc}") return None - self._track_session(session) + self._track_session(session, continue_budget=True) try: if not self._carry_exploration(prior_session, session): await self.log( @@ -231,8 +241,9 @@ async def _forced_structured_commit( cancel_event=capture_done, ) except CallerTimeoutError: + captured = None if self._agent_output_filtered(session) else capture_tool.captured await self.log(f"structured retry timed out ({label or 'agent'}) after {timeout}s") - return None + return captured if _schema_satisfied(captured, schema) else None except Exception as exc: # noqa: BLE001 — one dead agent never kills the fleet self._record_agent_failure(label, exc) await self.log(f"structured retry failed ({label or 'agent'}): {exc}") diff --git a/opencollab/bootstrap/_workflow_runtime_cleanup.py b/opencollab/bootstrap/_workflow_runtime_cleanup.py index aa4b4513..05be2d09 100644 --- a/opencollab/bootstrap/_workflow_runtime_cleanup.py +++ b/opencollab/bootstrap/_workflow_runtime_cleanup.py @@ -3,9 +3,12 @@ from __future__ import annotations import asyncio +import logging import math +from collections.abc import Iterator from typing import Any, Literal, TypeVar +from opencollab.application.async_timeout import consume_task_result from opencollab.application.exception_notes import add_exception_note from opencollab.application.ports import TracePort from opencollab.application.session_lifecycle import close_session_resources @@ -14,9 +17,10 @@ _workflow_manifest_payload, _write_workflow_manifest, ) -from opencollab.bootstrap.agent_runtime import revoke_and_abort_environment +from opencollab.bootstrap.agent_runtime import revoke_and_abort_environment, run_environment_hook T = TypeVar("T") +logger = logging.getLogger(__name__) def _add_failure_note(error: BaseException, note: str) -> None: add_exception_note(error, note) @@ -84,7 +88,8 @@ async def _wait_for_context_cleanup(ctx: WorkflowContext, *, timeout: float) -> deadline = loop.time() + timeout saw_empty = False while True: - pending = set(ctx.pending_cleanup_tasks) + # Candidate finalizers keep their own worktrees until the close phase. + pending = set(ctx.pending_cleanup_tasks) - ctx._deferred_candidate_cleanups if pending: saw_empty = False remaining = deadline - loop.time() @@ -102,7 +107,7 @@ async def _wait_for_context_cleanup(ctx: WorkflowContext, *, timeout: float) -> def _session_environments(ctx: WorkflowContext) -> tuple[Any, ...]: environments: list[Any] = [] seen: set[int] = set() - for session in ctx.sessions: + for session in _workflow_owned_sessions(ctx): environment = getattr(session, "env", None) if environment is None: environment = getattr(getattr(session, "tool_execution", None), "environment", None) @@ -115,11 +120,15 @@ def _session_persistence_succeeded(ctx: WorkflowContext) -> bool: return all(not getattr(session, "persistence_errors", ()) for session in ctx.sessions) async def _abort_session_environments(ctx: WorkflowContext, *, timeout: float) -> bool: - for task in ctx.pending_cleanup_tasks: + for task in set(ctx.pending_cleanup_tasks) - ctx._deferred_candidate_cleanups: task.cancel() if not getattr(ctx, "_cleanup_environment", True): return True environments = _session_environments(ctx) + if ctx._environment_acquisitions: + # A checkout can still need to read from its shared source. + source = getattr(ctx._factory, "_env", None) + environments = tuple(environment for environment in environments if environment is not source) if not environments: return True results = await asyncio.gather( @@ -132,16 +141,23 @@ async def _quiesce_workflow_context( ctx: WorkflowContext, *, timeout: float, -) -> tuple[bool, bool, tuple[asyncio.Future[Any], ...]]: +) -> tuple[bool, bool]: if await _wait_for_context_cleanup(ctx, timeout=timeout): - return True, _session_persistence_succeeded(ctx), () + return True, _session_persistence_succeeded(ctx) abort_succeeded = await _abort_session_environments(ctx, timeout=timeout) quiesced = await _wait_for_context_cleanup(ctx, timeout=timeout) - lingering = tuple(ctx.pending_cleanup_tasks) + return quiesced, abort_succeeded and quiesced and _session_persistence_succeeded(ctx) + +def _workflow_owned_sessions(ctx: WorkflowContext) -> Iterator[Any]: + # Candidate sessions remain in the run's evidence after their owner closes them. + return (session for session in ctx.sessions if id(session) not in ctx._candidate_owned_session_ids) + +async def _close_workflow_sessions(ctx: WorkflowContext) -> bool: + closed = await close_session_resources(_workflow_owned_sessions(ctx), timeout=None) + deferred = await asyncio.gather(*ctx._deferred_candidate_cleanups, return_exceptions=True) return ( - quiesced, - abort_succeeded and quiesced and _session_persistence_succeeded(ctx), - lingering, + closed and not ctx._candidate_session_close_failed + and all(result is None for result in deferred) and _session_persistence_succeeded(ctx) ) async def _quiesce_and_finalize_workflow_context( @@ -149,11 +165,11 @@ async def _quiesce_and_finalize_workflow_context( *, timeout: float, ) -> tuple[bool, bool, tuple[asyncio.Future[Any], ...]]: - quiesced, succeeded, lingering = await _quiesce_workflow_context(ctx, timeout=timeout) + quiesced, succeeded = await _quiesce_workflow_context(ctx, timeout=timeout) if not quiesced: - return quiesced, succeeded, lingering + return False, False, (_defer_workspace_release(ctx),) enqueued = True - for session in ctx.sessions: + for session in _workflow_owned_sessions(ctx): enqueue = getattr(session, "enqueue_auto_save", None) if not callable(enqueue): continue @@ -161,36 +177,80 @@ async def _quiesce_and_finalize_workflow_context( enqueue() except Exception: enqueued = False - final_quiesced, final_succeeded, final_lingering = await _quiesce_workflow_context( - ctx, - timeout=timeout, - ) - resources_closed = await close_session_resources(ctx.sessions, timeout=timeout) + # Execution has already quiesced. A slow final save can finish without aborting its workspace. + if not await _wait_for_context_cleanup(ctx, timeout=timeout): + return False, False, (_defer_workspace_release(ctx),) + final_succeeded = _session_persistence_succeeded(ctx) + # After the sessions are closed, never before: removing a worktree an agent # still holds would take the tree out from under a live tool call. - workspaces_released = await _release_isolated_workspaces(ctx, timeout=timeout) + close_owner = asyncio.create_task(_close_workflow_sessions(ctx)) + try: + done, _ = await asyncio.wait({close_owner}, timeout=timeout) + except BaseException: + close_owner.add_done_callback(consume_task_result) + raise + if close_owner not in done or ctx.pending_cleanup_tasks: + return False, False, (_defer_workspace_release(ctx, close_owner=close_owner),) + + workspaces_released, pending_workspaces = await _release_isolated_workspaces(ctx, timeout=timeout) return ( - final_quiesced, + not pending_workspaces, succeeded and enqueued and final_succeeded - and resources_closed + and close_owner.result() and workspaces_released, - (*lingering, *final_lingering), + pending_workspaces, ) -async def _release_isolated_workspaces(ctx: WorkflowContext, *, timeout: float) -> bool: - """Remove the worktrees lent to isolated agents; report whether it worked. +def _defer_workspace_release( + ctx: WorkflowContext, *, close_owner: asyncio.Task[bool] | None = None, +) -> asyncio.Task[None]: + async def release_after_close() -> None: + if close_owner is None: + await ctx.wait_for_pending_cleanup() + await _close_workflow_sessions(ctx) + else: + await close_owner + await ctx.wait_for_pending_cleanup() + await ctx.release_isolated_workspaces() + + owner = asyncio.create_task(release_after_close()) + owner.add_done_callback(consume_task_result) + return owner - A failure here leaves directories behind but must not fail the run: the work - the agents produced is already committed or already read back out. Bounded - by the same cleanup timeout as the rest, so a wedged git call cannot hang - the run's exit. - """ +async def _release_isolated_workspaces( + ctx: WorkflowContext, *, timeout: float, +) -> tuple[bool, tuple[asyncio.Future[Any], ...]]: + owner = asyncio.create_task(ctx.release_isolated_workspaces()) + try: + done, _ = await asyncio.wait({owner}, timeout=timeout) + except BaseException: + owner.add_done_callback(consume_task_result) + raise + if owner not in done: + owner.add_done_callback(consume_task_result) + return False, (owner,) try: - await asyncio.wait_for(ctx.release_isolated_workspaces(), timeout) - except (Exception, asyncio.TimeoutError): + owner.result() + except Exception: + return False, () + return True, () + +def _defer_owned_environment_cleanup( + env: Any, pending: tuple[asyncio.Future[Any], ...], *, timeout: float, +) -> bool: + if env is None or not pending: return False + + async def close_after_pending() -> None: + await asyncio.wait(pending) + if not await run_environment_hook(env, "cleanup", timeout): + logger.warning("Deferred workflow environment cleanup failed") + + owner = asyncio.create_task(close_after_pending()) + owner.add_done_callback(consume_task_result) return True async def _await_owned_with_cancellation( diff --git a/opencollab/bootstrap/_workflow_runtime_discovery.py b/opencollab/bootstrap/_workflow_runtime_discovery.py index bf12bf29..a9d29f3d 100644 --- a/opencollab/bootstrap/_workflow_runtime_discovery.py +++ b/opencollab/bootstrap/_workflow_runtime_discovery.py @@ -41,6 +41,14 @@ def exec_module(self, module: ModuleType) -> None: def get_resource_reader(self, fullname: str): return importlib.machinery.SourceFileLoader(fullname, self._path).get_resource_reader(fullname) +def _workflow_package_spec(package_name: str, directory: str) -> importlib.machinery.ModuleSpec: + # The synthetic package exposes adjacent resources without running __init__.py. + return importlib.machinery.ModuleSpec( + package_name, + loader=_WorkflowSourceLoader(os.path.join(directory, "__init__.py"), b""), + is_package=True, + ) + class _WorkflowImportFinder(importlib.abc.MetaPathFinder): """Resolve local workflow imports through the bounded source loader.""" @@ -288,14 +296,7 @@ def _load_workflow_specs(path: str) -> list[WorkflowSpec]: if "." in module_basename: module_basename = package_name module_name = f"{package_name}.{module_basename}" - package_spec = importlib.machinery.ModuleSpec( - package_name, - # Empty source preserves the synthetic package while locating its resources. - loader=_WorkflowSourceLoader(os.path.join(os.path.dirname(path), "__init__.py"), b""), - is_package=True, - ) - package_spec.submodule_search_locations = [] - package = importlib.util.module_from_spec(package_spec) + package = importlib.util.module_from_spec(_workflow_package_spec(package_name, os.path.dirname(path))) loader = _WorkflowSourceLoader(path, source) module_spec = importlib.util.spec_from_loader( module_name, diff --git a/opencollab/bootstrap/_workflow_runtime_execution.py b/opencollab/bootstrap/_workflow_runtime_execution.py index 7e91c5e1..6267c65e 100644 --- a/opencollab/bootstrap/_workflow_runtime_execution.py +++ b/opencollab/bootstrap/_workflow_runtime_execution.py @@ -16,6 +16,7 @@ _add_failure_note, _await_owned_with_cancellation, _close_tracer_capture, + _defer_owned_environment_cleanup, _inspect_tracer, _merge_failure, _persist_workflow_manifest, @@ -23,6 +24,7 @@ _quiesce_and_finalize_workflow_context, _sticky_tracer_failure, ) +from opencollab.bootstrap._workflow_runtime_manifest import _snapshot_workflow_args from opencollab.bootstrap._workflow_runtime_session import _resolve_spec_fn, build_workflow_context from opencollab.bootstrap._workflow_runtime_state import ( DEFAULT_WORKFLOW_CLEANUP_TIMEOUT_SECONDS, @@ -43,12 +45,16 @@ def _runtime_result( name: str, stop_reason: Literal["budget_exceeded"] | None, evidence_complete: bool, + body_returned_before_deadline: bool, + environment_cleanup_deferred: bool, + startup_cleanup_deferred: bool, ) -> WorkflowRuntimeResult: sessions = tuple(ctx.sessions) + tokens = ctx.budget.spent() return WorkflowRuntimeResult( output=output, name=name, - tokens=ctx.budget.spent(), + tokens=tokens, sessions=len(sessions), steps=sum(int(getattr(session, "step_count", 0)) for session in sessions), markup_recovered=sum( @@ -58,6 +64,9 @@ def _runtime_result( agent_failures=ctx.agent_failures, stop_reason=stop_reason, evidence_complete=evidence_complete, + body_returned_before_deadline=body_returned_before_deadline, + environment_cleanup_deferred=environment_cleanup_deferred, + startup_cleanup_deferred=startup_cleanup_deferred, ) def _attach_runtime_result( @@ -76,12 +85,14 @@ async def run_workflow( tracer: TracePort | None = None, event_sink: EventPublisherPort | None = None, budget: int | None = None, + allow_budget_escape: bool = True, max_concurrency: int = 4, task_concurrency: int | None = None, max_steps: int | None = None, system_prompt: str = WORKFLOW_AGENT_PROMPT, agent_profile: Any | None = None, save_dir: str | None = None, + manifest_args: dict[str, Any] | None = None, trace: bool = True, cleanup_timeout: float = DEFAULT_WORKFLOW_CLEANUP_TIMEOUT_SECONDS, env: Any | None = None, @@ -89,6 +100,7 @@ async def run_workflow( deadline_monotonic: float | None = None, deadline_margin_seconds: float = 120.0, return_details: bool = False, + format_output: Callable[[Any], Any] | None = None, cleanup_environment: bool = True, defer_manifest_completion: bool = False, candidate_workspace: Any | None = None, @@ -101,6 +113,8 @@ async def run_workflow( ) -> Any: """Run one workflow and return only after cleanup and evidence persistence.""" cleanup_timeout = _positive_cleanup_timeout(cleanup_timeout) + if save_dir is not None and manifest_args is None: + manifest_args = _snapshot_workflow_args(args) fn = _resolve_spec_fn(spec_or_fn) metadata = ( spec_or_fn @@ -147,25 +161,30 @@ async def run_workflow( deadline_margin_seconds=deadline_margin_seconds, ) ctx._cleanup_environment = cleanup_environment + ctx._candidate_cleanup_timeout = cleanup_timeout + ctx._budget_escape_state.allowed = allow_budget_escape except BaseException as exc: close_failure = _close_tracer_capture(tracer) if owns_tracer else None _note_failure(exc, "owned workflow tracer close also failed", close_failure) raise result: Any = None + body_returned_before_deadline = False stop_reason: Literal["budget_exceeded"] | None = None workflow_failure: BaseException | None = None cancellation: asyncio.CancelledError | None = None imports = ExitStack() ctx._workflow_imports = imports try: - result = await fn(ctx, args) + result = await ctx._run_workflow_body(fn, args) + body_returned_before_deadline = ( + deadline_monotonic is None or asyncio.get_running_loop().time() < deadline_monotonic + ) except WorkflowBudgetExceeded as exc: stop_reason = "budget_exceeded" result = { "status": "budget_exceeded", "error": str(exc), - "tokens_spent": ctx.budget.spent(), "budget_total": ctx.budget.total, } except BaseException as exc: @@ -175,12 +194,14 @@ async def run_workflow( cleanup_failure: BaseException | None = None cleanup_succeeded = False + startup_pending = not ctx.sessions and bool(ctx._environment_acquisitions) + lingering: tuple[asyncio.Future[Any], ...] = () cleanup_task = asyncio.create_task( _quiesce_and_finalize_workflow_context(ctx, timeout=cleanup_timeout) ) try: cleanup_result, cleanup_cancellation = await _await_owned_with_cancellation(cleanup_task) - _cleanup_quiesced, cleanup_succeeded, _lingering = cleanup_result + _cleanup_quiesced, cleanup_succeeded, lingering = cleanup_result cancellation = cancellation or cleanup_cancellation except BaseException as exc: cleanup_failure = exc @@ -188,6 +209,10 @@ async def run_workflow( ctx._workflow_imports = None imports.close() + environment_cleanup_deferred = cleanup_environment and _defer_owned_environment_cleanup( + env, lingering, timeout=cleanup_timeout, + ) + startup_cleanup_deferred = startup_pending and bool(lingering) tracer_failure = _close_tracer_capture(tracer) if owns_tracer else None tracer_write_error, tracer_dropped_steps, inspection_failure = _inspect_tracer(tracer) tracer_failure = _merge_failure( @@ -198,18 +223,35 @@ async def run_workflow( note_prefix="workflow trace also failed", ) + if stop_reason == "budget_exceeded": + result["tokens_spent"] = ctx.budget.spent() + output_format_failed = False + if ( + format_output is not None and workflow_failure is None and cancellation is None + and cleanup_failure is None and cleanup_succeeded and tracer_failure is None + ): + try: + result = format_output(result) + except Exception as exc: + workflow_failure = exc + output_format_failed = True + if cancellation is not None: terminal_status: Literal["completed", "stopped", "failed"] = "stopped" terminal_reason = "cancelled" failure_type = type(cancellation).__name__ elif workflow_failure is not None: terminal_status = "failed" - terminal_reason = "workflow_exception" + terminal_reason = "output_format_failed" if output_format_failed else "workflow_exception" failure_type = type(workflow_failure).__name__ elif stop_reason is not None: terminal_status = "stopped" terminal_reason = stop_reason failure_type = None + elif startup_cleanup_deferred: + terminal_status = "failed" + terminal_reason = "environment_setup_incomplete" + failure_type = None else: terminal_status = "completed" terminal_reason = None @@ -224,13 +266,13 @@ async def run_workflow( if ( requested_manifest and cleanup_failure is None - and cleanup_succeeded + and (cleanup_succeeded or startup_cleanup_deferred) ): manifest_error = _persist_workflow_manifest( save_dir, run_id=run_id, name=name, - args=args, + args=manifest_args if manifest_args is not None else args, ctx=ctx, tracer=tracer, tracer_failure=tracer_failure, @@ -255,28 +297,37 @@ async def run_workflow( name=name, stop_reason=stop_reason, evidence_complete=evidence_complete, + body_returned_before_deadline=body_returned_before_deadline, + environment_cleanup_deferred=environment_cleanup_deferred, + startup_cleanup_deferred=startup_cleanup_deferred, ) _attach_runtime_result(cancellation, runtime_result) _attach_runtime_result(workflow_failure, runtime_result) + cleanup_detail = ( + "session or workspace teardown exceeded its cleanup deadline" + if lingering else "final snapshot or environment abort failed" + ) if cancellation is not None: _note_failure(cancellation, "workflow cleanup also failed", cleanup_failure) - if cleanup_failure is None and not cleanup_succeeded: + if cleanup_failure is None and not cleanup_succeeded and not startup_cleanup_deferred: _add_failure_note( cancellation, - "workflow cleanup also failed: final snapshot or environment abort failed", + f"workflow cleanup also failed: {cleanup_detail}", ) _note_failure(cancellation, "workflow manifest persistence also failed", manifest_error) _note_failure(cancellation, "workflow trace also failed", tracer_failure) raise cancellation if cleanup_failure is not None: failure = RuntimeError("technical workflow cleanup failed") + _attach_runtime_result(failure, runtime_result) _note_failure(failure, "workflow execution also failed", workflow_failure) _note_failure(failure, "workflow manifest persistence also failed", manifest_error) _note_failure(failure, "workflow trace also failed", tracer_failure) raise failure from cleanup_failure if not cleanup_succeeded: - failure = RuntimeError("technical workflow cleanup failed: final snapshot or environment abort failed") + failure = RuntimeError(f"technical workflow cleanup failed: {cleanup_detail}") + _attach_runtime_result(failure, runtime_result) _note_failure(failure, "workflow manifest persistence also failed", manifest_error) _note_failure(failure, "workflow trace also failed", tracer_failure) raise failure from workflow_failure diff --git a/opencollab/bootstrap/_workflow_runtime_manifest.py b/opencollab/bootstrap/_workflow_runtime_manifest.py index 83f3fd4c..bf48d1cc 100644 --- a/opencollab/bootstrap/_workflow_runtime_manifest.py +++ b/opencollab/bootstrap/_workflow_runtime_manifest.py @@ -2,7 +2,7 @@ from __future__ import annotations -import copy +import json import os from typing import Any, Literal @@ -12,6 +12,15 @@ from opencollab.bootstrap.session_factory import WORKFLOW_MANIFEST_FILENAME +def _snapshot_workflow_args(args: dict[str, Any]) -> dict[str, Any]: + try: + return json.loads(json.dumps(args, allow_nan=False)) + except (TypeError, ValueError, OverflowError, RecursionError) as exc: + raise ValueError( + "workflow inputs must be JSON-serializable when artifacts are enabled" + ) from exc + + def _workflow_manifest_payload( *, name: str, @@ -27,28 +36,26 @@ def _workflow_manifest_payload( evidence_complete: bool, run_id: str | None = None, ) -> dict[str, Any]: - """Freeze all event-loop-owned values used by the workflow manifest.""" - return copy.deepcopy( - { - "workflow": name, - # Runtime identity survives when optional trajectory output is off. - "run_id": run_id if run_id is not None else getattr(tracer, "run_id", None), - "args": args, - "sessions": len(ctx.sessions), - "tokens_spent": ctx.budget.spent(), - "budget_total": ctx.budget.total, - "status": status, - "reason": reason, - "failure_type": failure_type, - "evidence_complete": evidence_complete, - "trace_enabled": tracer is not None, - "tracer_write_error": tracer_write_error, - "tracer_dropped_steps": tracer_dropped_steps, - "tracer_failure": ( - f"{type(tracer_failure).__name__}: {tracer_failure}" if tracer_failure is not None else None - ), - } - ) + """Combine the detached input snapshot with terminal execution evidence.""" + return { + "workflow": name, + # Runtime identity survives when optional trajectory output is off. + "run_id": run_id if run_id is not None else getattr(tracer, "run_id", None), + "args": args, + "sessions": len(ctx.sessions), + "tokens_spent": ctx.budget.spent(), + "budget_total": ctx.budget.total, + "status": status, + "reason": reason, + "failure_type": failure_type, + "evidence_complete": evidence_complete, + "trace_enabled": tracer is not None, + "tracer_write_error": tracer_write_error, + "tracer_dropped_steps": tracer_dropped_steps, + "tracer_failure": ( + f"{type(tracer_failure).__name__}: {tracer_failure}" if tracer_failure is not None else None + ), + } def _write_workflow_manifest( save_dir: str, diff --git a/opencollab/bootstrap/_workflow_runtime_session.py b/opencollab/bootstrap/_workflow_runtime_session.py index 81e430df..66781b88 100644 --- a/opencollab/bootstrap/_workflow_runtime_session.py +++ b/opencollab/bootstrap/_workflow_runtime_session.py @@ -324,12 +324,19 @@ async def release_isolated_envs(self, *, environment: Any | None = None) -> None detail = "; ".join(f"{type(error).__name__}: {error}" for error in errors) raise OSError(f"isolated environment cleanup failed: {detail}") from errors[0] + def resolve_tool_preset(self, name: str) -> Sequence[Any]: + if self._agent_profile is not None: + return self._agent_profile.resolve_tools(name) + from opencollab.bootstrap.programmatic import resolve_tools + + return resolve_tools(name) + def build_workflow_session( self, *, prompt: str, budget: int | None, - tools: Sequence[Any] | None = None, + tools: str | Sequence[Any] | None = None, isolation: bool = False, label: str | None = None, tool_choice: Any = None, @@ -366,10 +373,8 @@ def build_workflow_session( system_prompt = system_prompt.replace(self._workspace, environment_workspace) # The workflow owns role permissions and verification-tool instances. # Profile resolution keeps explicit tools, including evidence wrappers. - if self._agent_profile is None and isinstance(tools, str): - from opencollab.bootstrap.programmatic import resolve_tools - - resolved_tools = list(resolve_tools(tools)) + if isinstance(tools, str): + resolved_tools = list(self.resolve_tool_preset(tools)) else: resolved_tools = list( (tools or []) if self._agent_profile is None else self._agent_profile.resolve_tools(tools) diff --git a/opencollab/bootstrap/_workflow_runtime_state.py b/opencollab/bootstrap/_workflow_runtime_state.py index 1a31dba9..8a562a0d 100644 --- a/opencollab/bootstrap/_workflow_runtime_state.py +++ b/opencollab/bootstrap/_workflow_runtime_state.py @@ -28,3 +28,6 @@ class WorkflowRuntimeResult: agent_failures: tuple[dict[str, Any], ...] stop_reason: Literal["budget_exceeded"] | None = None evidence_complete: bool = True + body_returned_before_deadline: bool = False + environment_cleanup_deferred: bool = False + startup_cleanup_deferred: bool = False diff --git a/opencollab/bootstrap/agent_runtime.py b/opencollab/bootstrap/agent_runtime.py index 35205d49..32de6957 100644 --- a/opencollab/bootstrap/agent_runtime.py +++ b/opencollab/bootstrap/agent_runtime.py @@ -4,6 +4,8 @@ import asyncio import inspect +import logging +import time from dataclasses import dataclass from typing import Any, Literal @@ -17,11 +19,13 @@ from opencollab.application.exception_notes import add_exception_note from opencollab.application.ports import LLMPort, TracePort from opencollab.application.run_control import RunControl -from opencollab.application.session_lifecycle import close_session_resources +from opencollab.application.session_lifecycle import _completed_session_output_before, close_session_resources from opencollab.bootstrap.container import build_workspace_safety_policy from opencollab.bootstrap.session_factory import build_session from opencollab.domain.agent import Agent +logger = logging.getLogger(__name__) + class AgentRuntimeLifecycleError(RuntimeError): """Agent-owned work could not reach a proven terminal state.""" @@ -46,40 +50,49 @@ async def _run_session(session: Any, prompt: str) -> str: await session.add_user_message(prompt) return await session.run_loop() -async def run_environment_hook(environment: Any, name: str, timeout: float) -> bool: - """Run one environment hook with bounded cancellation and honest failure.""" +async def _environment_hook_failure(environment: Any, name: str, timeout: float) -> BaseException | None: hook = getattr(environment, name, None) if not callable(hook): - return False + return RuntimeError(f"environment has no {name} hook") try: outcome = hook() - except Exception: - return False + except Exception as exc: + return exc if not inspect.isawaitable(outcome): - return True + return None owner = asyncio.ensure_future(outcome) - done, pending = await asyncio.wait({owner}, timeout=timeout) + _done, pending = await asyncio.wait({owner}, timeout=timeout) if pending: terminal = await force_task_terminal(owner, timeout=timeout) if not terminal: owner.add_done_callback(consume_task_result) - return False + return asyncio.TimeoutError(f"environment {name} hook exceeded its cleanup deadline") try: owner.result() - except BaseException: - return False - return True + except BaseException as exc: + return exc + return None -async def revoke_and_abort_environment(environment: Any, timeout: float) -> bool: +async def run_environment_hook(environment: Any, name: str, timeout: float) -> bool: + return await _environment_hook_failure(environment, name, timeout) is None + +async def _environment_abort_failure(environment: Any, timeout: float) -> BaseException | None: revoke = getattr(environment, "revoke", None) - revoked = True + revoke_failure: Exception | None = None if callable(revoke): try: revoke() - except Exception: - revoked = False - aborted = await run_environment_hook(environment, "abort", timeout) - return revoked and aborted + except Exception as exc: + revoke_failure = exc + abort_failure = await _environment_hook_failure(environment, "abort", timeout) + if revoke_failure is not None and abort_failure is not None: + add_exception_note( + abort_failure, f"environment revocation also failed: {type(revoke_failure).__name__}: {revoke_failure}", + ) + return abort_failure or revoke_failure + +async def revoke_and_abort_environment(environment: Any, timeout: float) -> bool: + return await _environment_abort_failure(environment, timeout) is None async def _wait_session_tasks(session: Any, timeout: float) -> bool: pending = { @@ -115,6 +128,8 @@ async def _finalize_session( cleanup_environment: bool, ) -> bool: quiesced = await _wait_session_tasks(session, timeout) + if not quiesced and getattr(session, "_autosave_acquisition", None) is not None: + return False persistence_ready = False try: save_owner = session.enqueue_auto_save() @@ -130,8 +145,10 @@ async def _finalize_session( ) llm_quiesced = await close_session_resources((session,), timeout=timeout) if quiesced and persistence_quiesced and cleanup_quiesced and llm_quiesced: - runner = getattr(session, "runner", None) - if runner is not None: + finish = getattr(session, "_finish_run_control", None) + if finish is not None: + finish() + elif (runner := getattr(session, "runner", None)) is not None: runner.finish_run_control() return ( quiesced @@ -217,6 +234,7 @@ async def run_agent( finalization_attempts = 0 max_finalization_attempts = 2 stop_task: asyncio.Task[tuple[bool, bool, bool]] | None = None + deferred_close: asyncio.Task[None] | None = None def record_finalization_result(task: asyncio.Task[bool]) -> bool: nonlocal finalization_task, finalization_succeeded @@ -260,6 +278,8 @@ async def finalize_attempt() -> bool: return record_finalization_result(task) async def finalize_with_retry() -> bool: + if deferred_close is not None: + return False if finalization_succeeded: return True while not finalization_succeeded: @@ -275,15 +295,34 @@ async def finalize_with_retry() -> bool: return False async def stop_owned() -> tuple[bool, bool, bool]: - aborted = True - if cleanup_environment: - aborted = await revoke_and_abort_environment( - environment, - cleanup_timeout_seconds, - ) + nonlocal deferred_close + abort_failure = ( + await _environment_abort_failure(environment, cleanup_timeout_seconds) + if cleanup_environment else None + ) terminal = await force_task_terminal(owner, timeout=cleanup_timeout_seconds) + if not terminal and getattr(session, "_autosave_acquisition", None) is not None: + async def finish_stopped_startup() -> None: + await asyncio.wait({owner}) + while tasks := session.pending_cleanup_tasks: + await asyncio.wait(tasks) + closed = await close_session_resources((session,), timeout=None) + if closed and cleanup_environment: + closed = await run_environment_hook(environment, "cleanup", cleanup_timeout_seconds) + if not closed: + logger.warning("Agent cleanup after deferred autosave admission failed") + + owner.add_done_callback(consume_task_result) + deferred_close = asyncio.create_task(finish_stopped_startup()) + deferred_close.add_done_callback(consume_task_result) finalized = await finalize_with_retry() - return aborted, terminal, finalized + if ( + terminal and finalized and isinstance(abort_failure, OSError) + and not isinstance(abort_failure, (TimeoutError, asyncio.TimeoutError)) + ): + # A failed unlink can be repaired by finalization. Confirm abort on the settled owner. + abort_failure = await _environment_abort_failure(environment, cleanup_timeout_seconds) + return abort_failure is None, terminal, finalized async def stop_once(*, propagate_cancellation: bool) -> tuple[bool, bool, bool]: nonlocal stop_task @@ -295,6 +334,7 @@ async def stop_once(*, propagate_cancellation: bool) -> tuple[bool, bool, bool]: ) try: + deadline = None if timeout_seconds is None else time.monotonic() + timeout_seconds done, pending = await asyncio.wait({owner}, timeout=timeout_seconds) if pending: aborted, terminated, finalized = await stop_once( @@ -306,7 +346,7 @@ async def stop_once(*, propagate_cancellation: bool) -> tuple[bool, bool, bool]: ) return _result( session, - output=None, + output=_completed_session_output_before(session, deadline), outcome="timed_out", error=TimeoutError(f"agent exceeded {timeout_seconds:g} seconds"), cleanup_quiesced=True, diff --git a/opencollab/bootstrap/authored_workflow.py b/opencollab/bootstrap/authored_workflow.py index 730c6a07..b91e2aa4 100644 --- a/opencollab/bootstrap/authored_workflow.py +++ b/opencollab/bootstrap/authored_workflow.py @@ -12,7 +12,7 @@ import uuid from collections.abc import Callable from copy import deepcopy -from dataclasses import dataclass +from dataclasses import dataclass, replace from pathlib import Path from typing import TYPE_CHECKING, Any, get_args @@ -57,6 +57,7 @@ class _Child: status: str = "running" tokens: int = 0 reported_tokens: int = 0 + accounting_settled: bool = False result: dict[str, Any] | None = None cleanup_error: Exception | None = None bridge: AuthoredWorkflowBridge | None = None @@ -217,7 +218,7 @@ def _reserved_tokens(self) -> int: # Retain native spend while the child's usage file catches up. return sum(max(0, (item.budget or 0) - item.tokens, (item.bridge.tokens if item.bridge is not None else item.tokens) - item.tokens) - for item in self._children.values() if item.status == "running") + for item in self._children.values() if item.status == "running" and not item.accounting_settled) def _remaining_child_budget(self, child: _Child) -> int | None: remaining = self._get_session().runner.remaining_budget_tokens @@ -353,6 +354,8 @@ async def run() -> ExecResult: execution = None logs: dict[str, Any] = {} status = "running" + result: dict[str, Any] | None = None + saved_artifacts: str | None = None try: execution = asyncio.create_task(run()) child.execution = execution @@ -374,15 +377,15 @@ async def run() -> ExecResult: await _copy_artifact_to_host( child.environment, posixpath.join(child.artifacts, "result.json"), result_path, ) - child.result = json.loads(result_path.read_text(encoding="utf-8")) - self._account_usage(child, child.result["tokens"]) - status = child.result["status"] + result = json.loads(result_path.read_text(encoding="utf-8")) + self._account_usage(child, result["tokens"]) + status = result["status"] except asyncio.CancelledError: status = "stopped" - child.result = {"status": "stopped", "output": None, "reason": "cancelled"} + result = {"status": "stopped", "output": None, "reason": "cancelled"} except Exception as exc: status = "failed" - child.result = {"status": "failed", "output": None, "reason": f"{type(exc).__name__}: {exc}"} + result = {"status": "failed", "output": None, "reason": f"{type(exc).__name__}: {exc}"} finally: if execution is not None: cancelling = not execution.done() @@ -392,8 +395,8 @@ async def run() -> ExecResult: if isinstance(settled[0], ProcessCleanupError) or (cancelling and isinstance(settled[0], Exception)): status = "failed" child.cleanup_error = settled[0] - child.result = {"status": "failed", "output": None, - "reason": f"child process cleanup failed: {settled[0]}"} + result = {"status": "failed", "output": None, + "reason": f"child process cleanup failed: {settled[0]}"} try: assert child.bridge is not None await await_owned_operation(child.bridge.aclose(), propagate_cancellation=False) @@ -402,15 +405,17 @@ async def run() -> ExecResult: except Exception as exc: status = "failed" child.cleanup_error = exc - child.result = {"status": "failed", "output": None, - "reason": f"{(child.result or {}).get('reason', '')}; child accounting failed: {exc}"} - if child.result is not None: - child.result["tokens"] = child.tokens - child.status = status + result = {"status": "failed", "output": None, + "reason": f"{(result or {}).get('reason', '')}; child accounting failed: {exc}"} + if result is not None: + result["tokens"] = child.tokens + # Artifact export can outlast the token reservation. + child.accounting_settled = True if self._save_dir is not None: try: directory = Path(tempfile.mkdtemp(prefix=f"{child.id}-", dir=self._save_dir)) - native_files = (child.result or {}).get("artifact_files") + native_files = (result or {}).get("artifact_files") + final_inventory = native_files is not None if native_files is None: try: native_files = json.loads(await child.environment.read_file( @@ -428,16 +433,25 @@ async def run() -> ExecResult: child.environment, posixpath.join(child.artifacts, name), directory / name, ) except FileNotFoundError: - continue - child.saved_artifacts = str(directory) - (directory / "result.json").write_text(json.dumps(self._snapshot(child, include_result=True)), - encoding="utf-8") + # The provisional list can name files the child never created. + if final_inventory: + raise + saved_artifacts = str(directory) + terminal = replace(child, status=status, result=result, saved_artifacts=saved_artifacts) (directory / "process.json").write_text(json.dumps(logs), encoding="utf-8") + (directory / "result.json").write_text(json.dumps(self._snapshot(terminal, include_result=True)), + encoding="utf-8") except Exception as exc: - child.status = "failed" + status = "failed" child.cleanup_error = exc - child.result = {"status": "failed", "output": None, - "reason": f"child result persistence failed: {exc}", "tokens": child.tokens} + reason = f"child result persistence failed: {exc}" + if result and result.get("reason"): + reason = f"{result['reason']}. {reason}" + result = {"status": "failed", "output": None, + "reason": reason, "tokens": child.tokens} + child.saved_artifacts = saved_artifacts + child.result = result + child.status = status async def _stop(self, child: _Child) -> None: if child.task is None or child.task.done(): diff --git a/opencollab/bootstrap/authored_workflow_runner.py b/opencollab/bootstrap/authored_workflow_runner.py index 9335af89..450f6b14 100644 --- a/opencollab/bootstrap/authored_workflow_runner.py +++ b/opencollab/bootstrap/authored_workflow_runner.py @@ -8,18 +8,77 @@ import re import signal import sys +import sysconfig from dataclasses import replace from functools import partial +from importlib.machinery import ModuleSpec, PathFinder, SourceFileLoader from pathlib import Path +from types import CodeType from typing import Any from opencollab.adapters.env import LocalEnvironment from opencollab.application.run_control import RunControl, RunEvent from opencollab.application.structured_output import StructuredOutputTool from opencollab.application.submit_findings import SubmitFindingsTool +from opencollab.bootstrap._workflow_runtime_discovery import _workflow_package_spec from opencollab.bootstrap.authored_workflow_bridge import BridgeClient, BridgeLLM from opencollab.bootstrap.session_factory import build_session -from opencollab.bootstrap.workflow_runtime import run_workflow +from opencollab.bootstrap.workflow_runtime import WorkflowRuntimeResult, run_workflow + + +class _WorkflowOutputError(ValueError): + runtime_result: WorkflowRuntimeResult + + +class _CurrentSourceLoader(SourceFileLoader): + def get_code(self, fullname: str) -> CodeType: + # A same-size edit in the same second can still match the existing pyc. + path = self.get_filename(fullname) + return self.source_to_code(self.get_data(path), path) + + +class _WorkflowPathFinder: + _PACKAGE_INSTALL_DIRS = {"site-packages", "dist-packages"} + + def __init__(self, workspace: Path) -> None: + self.workspace = workspace + paths = sysconfig.get_paths() + self.install_roots = { + Path(paths[name]).resolve() for name in ("stdlib", "platstdlib", "purelib", "platlib") + } + + @staticmethod + def invalidate_caches() -> None: + PathFinder.invalidate_caches() + + def _uses_current_source(self, path: str) -> bool: + origin = Path(path) + if self._PACKAGE_INSTALL_DIRS.intersection(origin.parent.parts): + return False + try: + resolved = origin.resolve() + except (OSError, RuntimeError): + return False + return ( + resolved.is_relative_to(self.workspace) + and self._PACKAGE_INSTALL_DIRS.isdisjoint(resolved.parent.parts) + and not any(resolved.is_relative_to(root) for root in self.install_roots) + ) + + def find_spec(self, fullname: str, path=None, target=None) -> ModuleSpec | None: + spec = PathFinder.find_spec(fullname, path, target) + if spec is not None and type(spec.loader) is SourceFileLoader and self._uses_current_source(spec.loader.path): + spec.loader = _CurrentSourceLoader(spec.name, spec.loader.path) + return spec + + +def _format_workflow_output(output: Any) -> Any: + try: + # Validate the output inside the UTF-8 envelope written to result.json. + payload = json.dumps({"output": output}, ensure_ascii=False, allow_nan=False) + return json.loads(payload.encode("utf-8"))["output"] + except (TypeError, ValueError, OverflowError, RecursionError) as exc: + raise _WorkflowOutputError(f"workflow output is not JSON serializable: {exc}") from exc def _write_json(path: Path, value: Any) -> None: @@ -80,18 +139,29 @@ async def execute() -> Any: if source.suffix != ".py": raise ValueError("workflow source must be a Python file") sys.dont_write_bytecode = True - spec = importlib.util.spec_from_file_location(f"_oc_child_{request['id']}", source) + package_name = f"_oc_child_{request['id'].replace('-', '_')}" + source_directory = str(source.parent) + package_spec = _workflow_package_spec(package_name, source_directory) + package_spec.submodule_search_locations = [source_directory] + sys.modules[package_name] = importlib.util.module_from_spec(package_spec) + entry_name = source.stem if source.stem.isidentifier() else "_entry" + module_name = f"{package_name}.{entry_name}" + loader = _CurrentSourceLoader(module_name, str(source)) + spec = importlib.util.spec_from_file_location(module_name, source, loader=loader) if spec is None or spec.loader is None: raise ValueError("workflow source cannot be loaded") module = importlib.util.module_from_spec(spec) sys.modules[spec.name] = module - sys.path.insert(0, str(source.parent)) + sys.path.insert(0, source_directory) + local_finder = _WorkflowPathFinder(workspace) + sys.meta_path[:] = [local_finder if finder is PathFinder else finder for finder in sys.meta_path] spec.loader.exec_module(module) flow = getattr(module, request["entry"]) if not callable(flow) and not callable(getattr(flow, "fn", None)): raise TypeError("workflow entry must be callable") environment = LocalEnvironment(str(workspace)) environment.process_isolated = request["process_isolated"] + environment_deferred = False try: return await run_workflow( flow, request["args"], cfg=request["config"], workspace=str(workspace), @@ -99,14 +169,20 @@ async def execute() -> Any: max_steps=request["max_steps"], max_concurrency=request["concurrency"], save_dir=str(artifacts), trace=False, run_id=request["id"], session_builder=build_child, return_details=True, limit_mode="explicit", + format_output=_format_workflow_output, cleanup_timeout=request.get("cleanup_timeout", 2.0), **({"isolation": request["bridge"]["isolation"], "environment_providers": {name: partial(bridge.provider, name) for name in request["bridge"]["strategies"]}} if bridge is not None else {}), ) + except BaseException as failure: + result = getattr(failure, "runtime_result", None) + environment_deferred = getattr(result, "environment_cleanup_deferred", False) + raise finally: - await environment.cleanup() + if not environment_deferred: + await environment.cleanup() owner = asyncio.create_task(execute()) loop = asyncio.get_running_loop() @@ -133,6 +209,8 @@ async def watch_stop() -> None: notes = tuple(getattr(exc, "__notes__", ())) result.update(status="failed" if notes else "stopped", output=None, reason="cancelled", cleanup_errors=notes) + except _WorkflowOutputError as exc: + result.update(status="failed", output=None, reason=str(exc), agent_failures=exc.runtime_result.agent_failures) except Exception as exc: result.update(status="failed", output=None, reason=f"{type(exc).__name__}: {exc}") finally: diff --git a/opencollab/bootstrap/config.py b/opencollab/bootstrap/config.py index b6e7eccf..60f43895 100644 --- a/opencollab/bootstrap/config.py +++ b/opencollab/bootstrap/config.py @@ -375,7 +375,7 @@ def load_dotenv(path: str | None = None) -> dict[str, str]: f"config env file encoding error: expected UTF-8: {env_path} " f"(byte {exc.start}: {exc.reason})" ) from exc - for line in text.splitlines(): + for line in text.removeprefix("\ufeff").splitlines(): line = line.strip() if not line or line.startswith("#"): continue @@ -496,8 +496,9 @@ def resolve_ordered(*keys: str, default: str | None = None) -> str | None: for key, value in (overrides or {}).items(): if key in {"api_key", "auth_token", "base_url"}: value = _optional_string(value) - if value is not None: - selected_overrides[key] = value + if value is None and key in OpenCollabConfig.model_fields and key != "top_p": + continue + selected_overrides[key] = value provider_value = selected_overrides.get("provider") or resolve( "OPENCOLLAB_PROVIDER", default="openai" ) diff --git a/opencollab/bootstrap/container.py b/opencollab/bootstrap/container.py index 1e5ea104..f7ad26e8 100644 --- a/opencollab/bootstrap/container.py +++ b/opencollab/bootstrap/container.py @@ -18,7 +18,7 @@ from opencollab.adapters.llm import LLMClient, is_context_overflow_error from opencollab.adapters.llm.anthropic_provider import _anthropic_thinking_is_always_on from opencollab.adapters.llm.providers import is_anthropic -from opencollab.adapters.llm.retry import RetryTimeBudget +from opencollab.adapters.llm.retry import RetryTimeBudget, is_retryable_error from opencollab.adapters.skills.file_skill_store import FileSkillStore from opencollab.adapters.skills.null_skill_store import NullSkillStore from opencollab.adapters.storage import SessionStore @@ -231,6 +231,7 @@ def _summary_output_limit(request: list[dict[str, Any]]) -> int: return output_limit( request, None, thinking=summary_extra.get("thinking", False), thinking_params=summary_extra.get("thinking_params"), + allow_budget_recovery=False, ) context_window = getattr(resolved_llm, "context_window", lambda: None)() @@ -530,6 +531,7 @@ def build_session_runtime( # boundary pattern as the team-budget predicate). Enables the # force-compact-and-retry + graceful-stop safety net in ``call_llm``. is_context_overflow=is_context_overflow_error, + is_retryable_provider_error=is_retryable_error, # Cooperative per-generation ceiling: bound a single model call to the # configured provider timeout so one slow (thinking) generation cannot # eat the whole run wall (P7). diff --git a/opencollab/bootstrap/isolation.py b/opencollab/bootstrap/isolation.py index 23a91b26..1cf36dde 100644 --- a/opencollab/bootstrap/isolation.py +++ b/opencollab/bootstrap/isolation.py @@ -1,15 +1,21 @@ from __future__ import annotations +import asyncio from typing import Any from opencollab.adapters.session_environments import SessionEnvironmentPool +from opencollab.application.async_timeout import await_owned_operation +from opencollab.application.exception_notes import add_exception_note from opencollab.application.isolation import isolation_name from opencollab.bootstrap.environment_profiles import configured_environment_providers from opencollab.bootstrap.team_config import load_team_config async def prepare_scheduler(ctx: Any, *, builder: Any, isolation=None, - environment_providers=None, **kwargs: Any) -> Any: + environment_providers=None, stop_requested: asyncio.Event | None = None, + **kwargs: Any) -> Any: + if stop_requested is not None and stop_requested.is_set(): + raise asyncio.CancelledError team = kwargs.get("resolved_team_config") or load_team_config( ctx.workspace, path=kwargs.get("team_config_path"), ) @@ -29,11 +35,18 @@ async def prepare_scheduler(ctx: Any, *, builder: Any, isolation=None, # An unset strategy keeps the historical entry workspace even when a child overrides it. entry_isolation = roles.get(team.entry) or selected or "shared" entry = await pool.acquire(team.entry, isolation=entry_isolation) + if stop_requested is not None and stop_requested.is_set(): + raise asyncio.CancelledError pool.set_source(entry, isolation=entry_isolation) scheduler = builder(ctx, **{**kwargs, "environment": entry, "worktree_pool": pool, "resolved_team_config": team}) scheduler.preserve_entry_changes = entry_isolation != "shared" return scheduler - except BaseException: - await pool.release() + except BaseException as exc: + try: + await await_owned_operation(pool.release()) + except (Exception, asyncio.CancelledError) as cleanup_error: + add_exception_note( + exc, f"Team preparation cleanup also failed: {type(cleanup_error).__name__}: {cleanup_error}", + ) raise diff --git a/opencollab/bootstrap/programmatic.py b/opencollab/bootstrap/programmatic.py index 60346e4e..ba45d0cc 100644 --- a/opencollab/bootstrap/programmatic.py +++ b/opencollab/bootstrap/programmatic.py @@ -39,11 +39,12 @@ from opencollab.application.ports import EnvironmentPort from opencollab.application.run_control import RunControl from opencollab.bootstrap._workflow_runtime_cleanup import _sticky_tracer_failure +from opencollab.bootstrap._workflow_runtime_manifest import _snapshot_workflow_args from opencollab.bootstrap.agent_profiles import SingleAgentProfile, resolve_agent_profile from opencollab.bootstrap.agent_runtime import ( AgentRuntimeLifecycleError, AgentRuntimeResult, - run_environment_hook, + _environment_hook_failure, ) from opencollab.bootstrap.agent_runtime import ( run_agent as _run_agent, @@ -218,15 +219,6 @@ def _verify_artifact_claim(path: Path | None) -> None: f"run artifact claim changed during execution: {claim_path}" ) -def _require_json_workflow_inputs(inputs: Mapping[str, Any]) -> None: - """Reject inputs that the workflow artifact manifest could not persist.""" - try: - json.dumps(inputs) - except (TypeError, ValueError, OverflowError, RecursionError) as exc: - raise ValueError( - "workflow inputs must be JSON-serializable when artifacts are enabled" - ) from exc - def _require_json_object(path: Path, description: str) -> dict[str, Any]: try: value = json.loads(read_regular_text(path, max_bytes=64 * 1024 * 1024)) @@ -247,13 +239,11 @@ def _settle_programmatic_workflow_manifest( path = artifacts / "workflow.json" try: manifest = _require_json_object(path, "workflow manifest") - if cleanup_succeeded: - manifest["evidence_complete"] = True - else: + if not cleanup_succeeded and manifest.get("status") not in {"failed", "stopped"}: manifest["status"] = "failed" manifest["reason"] = "environment_cleanup_failed" manifest["failure_type"] = "ProgrammaticLifecycleError" - manifest["evidence_complete"] = False + manifest["evidence_complete"] = cleanup_succeeded SessionStore().save_manifest(path, manifest) except BaseException as exc: return exc @@ -485,7 +475,7 @@ def _workflow_metrics( } metrics.update( _quiescence_metrics( - session_quiesced=details is not None, + session_quiesced=details is not None and not details.startup_cleanup_deferred, environment_owned=environment_owned, environment_cleanup_quiesced=environment_cleanup_quiesced, environment_quiesced=environment_quiesced, @@ -523,8 +513,7 @@ async def run_workflow( environment_providers = configured_environment_providers(config, environment_providers, isolation=isolation) run_id = run_id if run_id is not None else f"workflow-{uuid.uuid4().hex}" workflow_inputs = dict(inputs) - if artifacts is not None: - _require_json_workflow_inputs(workflow_inputs) + manifest_args = _snapshot_workflow_args(workflow_inputs) if artifacts is not None else None _claim_artifacts(artifacts) owned_environment = environment is None resolved_environment = ( @@ -537,27 +526,33 @@ async def run_workflow( else asyncio.get_running_loop().time() + timeout ) details: WorkflowRuntimeResult | None = None - stopped_error: BaseException | None = None + stopped_error: WorkflowDeadlineExceeded | None = None failed_error: BaseException | None = None bootstrap_stopped_environment = False environment_cleanup_quiesced: bool | None = None environment_quiesced: bool | None = None async def cleanup_owned_environment() -> None: - cleaned = await run_environment_hook(resolved_environment, "cleanup", timeout=cleanup_timeout) - if cleaned: + cleanup_failure = await _environment_hook_failure(resolved_environment, "cleanup", timeout=cleanup_timeout) + if cleanup_failure is None: if details is not None and details.evidence_complete: _finalize_programmatic_workflow_manifest(artifacts) return manifest_failure = _settle_programmatic_workflow_manifest(artifacts, cleanup_succeeded=False) failure = ProgrammaticLifecycleError("workflow-owned environment cleanup failed") + if failed_error is not None: + failure.__context__ = failed_error + add_exception_note( + failure, + f"workflow execution also failed: {type(failed_error).__name__}: {failed_error}", + ) if manifest_failure is not None: add_exception_note( failure, "workflow manifest downgrade also failed: " f"{type(manifest_failure).__name__}: {manifest_failure}", ) - raise failure from manifest_failure + raise failure from cleanup_failure try: try: @@ -570,6 +565,7 @@ async def cleanup_owned_environment() -> None: max_concurrency=max_concurrency, task_concurrency=task_concurrency, save_dir=None if artifacts is None else str(artifacts), + manifest_args=manifest_args, trace=trace, env=resolved_environment, cleanup_timeout=cleanup_timeout, @@ -593,6 +589,8 @@ async def cleanup_owned_environment() -> None: bootstrap_stopped_environment = True stopped_error = exc except WorkflowLifecycleError as exc: + failed_error = exc + details = exc.runtime_result raise ProgrammaticLifecycleError(str(exc)) from exc except asyncio.CancelledError as cancellation: bootstrap_stopped_environment = True @@ -607,38 +605,44 @@ async def cleanup_owned_environment() -> None: ) raise except Exception as exc: + failed_error = exc details = getattr(exc, "runtime_result", None) if details is None or not details.evidence_complete: raise ProgrammaticLifecycleError( "workflow runtime failed without finalized execution evidence" ) from exc - failed_error = exc finally: - if owned_environment and not bootstrap_stopped_environment: + environment_deferred = details is not None and details.environment_cleanup_deferred + if owned_environment and not bootstrap_stopped_environment and not environment_deferred: await await_owned_operation(cleanup_owned_environment(), propagate_cancellation=True) environment_cleanup_quiesced = True environment_quiesced = True - if not owned_environment: - _verify_artifact_claim(artifacts) if stopped_error is not None: - if owned_environment: - _finalize_programmatic_workflow_manifest(artifacts) details = stopped_error.result + environment_deferred = details is not None and details.environment_cleanup_deferred + if owned_environment and not environment_deferred: + _finalize_programmatic_workflow_manifest(artifacts) + else: + _verify_artifact_claim(artifacts) metrics = _workflow_metrics( details, agent_profile=agent_profile, run_id=run_id, environment_owned=owned_environment, environment_cleanup_quiesced=( - True if owned_environment else environment_cleanup_quiesced + not environment_deferred if owned_environment else environment_cleanup_quiesced ), environment_quiesced=( - True if owned_environment else environment_quiesced + not environment_deferred if owned_environment else environment_quiesced ), ) return ProgrammaticResult( - output=None, + output=( + details.output + if details is not None and details.evidence_complete and details.body_returned_before_deadline + else None + ), status="stopped", reason="timeout", tokens=0 if details is None else details.tokens, @@ -647,6 +651,8 @@ async def cleanup_owned_environment() -> None: metrics=metrics, agent_failures=() if details is None else details.agent_failures, ) + if not owned_environment: + _verify_artifact_claim(artifacts) if failed_error is not None: return ProgrammaticResult( output=None, diff --git a/opencollab/bootstrap/programmatic_team.py b/opencollab/bootstrap/programmatic_team.py index 5303eaa2..8e149b74 100644 --- a/opencollab/bootstrap/programmatic_team.py +++ b/opencollab/bootstrap/programmatic_team.py @@ -3,15 +3,18 @@ from __future__ import annotations import asyncio +import logging import os import uuid -from collections.abc import Mapping +from collections.abc import Awaitable, Callable, Mapping from pathlib import Path from typing import Any, Literal from opencollab.adapters.env import Environment from opencollab.adapters.trace import Tracer +from opencollab.application.async_timeout import CallerTimeoutError, await_owned_operation, consume_task_result from opencollab.application.exception_notes import add_exception_note +from opencollab.application.scheduler import Scheduler from opencollab.application.scheduler_types import SchedulerTurnError from opencollab.bootstrap import programmatic as _programmatic from opencollab.bootstrap.environment_profiles import environment_cleanup_timeout @@ -25,6 +28,148 @@ from opencollab.bootstrap.team_config import load_team_config from opencollab.domain.session import SessionPhase +logger = logging.getLogger(__name__) + + +class _TeamDeadlineExceeded(CallerTimeoutError): + def __init__(self, output: str | None = None) -> None: + super().__init__() + self.output = output + + +class _TeamPreparationDeadlineExceeded(CallerTimeoutError): + def __init__(self, *, quiesced: bool = False) -> None: + super().__init__("team wall-clock deadline expired during preparation") + self.quiesced = quiesced + + +async def _prepare_team_scheduler( + prepare: Callable[[asyncio.Event], Awaitable[Scheduler]], deadline: float | None, *, cleanup_timeout: float, +) -> Scheduler: + remaining = None if deadline is None else deadline - asyncio.get_running_loop().time() + if remaining is not None and remaining <= 0: + raise _TeamPreparationDeadlineExceeded(quiesced=True) + + stop_requested = asyncio.Event() + + async def prepare_owned() -> tuple[Scheduler | None, BaseException | None]: + try: + return await prepare(stop_requested), None + except (Exception, asyncio.CancelledError) as exc: + return None, exc + + owner = asyncio.create_task(prepare_owned()) + + async def stop(primary: BaseException, *, propagate_cancellation: bool) -> bool: + stop_requested.set() + if isinstance(primary, asyncio.CancelledError): + owner.cancel(*primary.args) + else: + owner.cancel() + + async def release_unstarted() -> bool: + try: + scheduler, failure = await asyncio.shield(owner) + except asyncio.CancelledError: + if owner.cancelled(): + return True + raise + if scheduler is not None: + try: + await scheduler.cleanup(cleanup_timeout=cleanup_timeout) + except (Exception, asyncio.CancelledError) as exc: + note = f"stopped Team cleanup also failed: {type(exc).__name__}: {exc}" + add_exception_note(primary, note) + logger.warning("%s", note) + return False + if failure is None: + return True + notes = getattr(failure, "__notes__", ()) + for note in notes: + add_exception_note(primary, note) + logger.warning("%s", note) + if isinstance(failure, asyncio.CancelledError): + return not notes + note = f"stopped Team preparation also failed: {type(failure).__name__}: {failure}" + add_exception_note(primary, note) + logger.warning("%s", note) + return False + + cleanup = asyncio.create_task(release_unstarted()) + cleanup.add_done_callback(consume_task_result) + done, _ = await await_owned_operation( + asyncio.wait({cleanup}, timeout=cleanup_timeout), propagate_cancellation=propagate_cancellation, + ) + return bool(done) and cleanup.result() + + try: + done, _ = await asyncio.wait({owner}, timeout=remaining) + except asyncio.CancelledError as exc: + await stop(exc, propagate_cancellation=False) + raise + if done: + scheduler, failure = owner.result() + if failure is not None: + raise failure + assert scheduler is not None + return scheduler + timeout = _TeamPreparationDeadlineExceeded() + timeout.quiesced = await stop(timeout, propagate_cancellation=True) + raise timeout + + +async def _stop_team_turn( + scheduler: Scheduler, owner: asyncio.Task[str], cancellation: asyncio.CancelledError, + *, cleanup_timeout: float, propagate_cancellation: bool, +) -> None: + scheduler.request_shutdown() + owner.cancel(*cancellation.args) + owner.add_done_callback(consume_task_result) + try: + await await_owned_operation( + scheduler.cleanup(cleanup_timeout=cleanup_timeout), propagate_cancellation=propagate_cancellation, + ) + except Exception as exc: + add_exception_note(cancellation, f"scheduler cleanup also failed: {type(exc).__name__}: {exc}") + + +async def _run_team_turn( + scheduler: Scheduler, prompt: str, timeout: float | None, *, cleanup_timeout: float, +) -> str: + if timeout is not None and timeout <= 0: + raise _TeamDeadlineExceeded + + turn_cancellation: asyncio.CancelledError | None = None + + async def run_turn() -> str: + nonlocal turn_cancellation + try: + return await scheduler.run(prompt) + except asyncio.CancelledError as exc: + # Python 3.10 may reconstruct the exception at the Task boundary. + turn_cancellation = exc + raise + + owner = asyncio.create_task(run_turn()) + try: + done, _ = await asyncio.wait({owner}, timeout=timeout) + except asyncio.CancelledError as cancellation: + await _stop_team_turn( + scheduler, owner, cancellation, cleanup_timeout=cleanup_timeout, propagate_cancellation=False, + ) + raise + if done: + if turn_cancellation is not None: + raise turn_cancellation + return owner.result() + + output = scheduler.accepted_public_turn_answer(0) + cancellation = asyncio.CancelledError("team wall-clock deadline expired") + await _stop_team_turn( + scheduler, owner, cancellation, cleanup_timeout=cleanup_timeout, propagate_cancellation=True, + ) + raise _TeamDeadlineExceeded(output) from cancellation + async def run_team( *, @@ -58,6 +203,8 @@ async def run_team( ``environment`` supplies the agents' execution workspace. ``workspace`` anchors local configuration, skills, the repository map and session storage. """ + loop = asyncio.get_running_loop() + deadline = None if timeout is None else loop.time() + timeout workflow_cleanup_timeout = environment_cleanup_timeout(config, cleanup_timeout, default=2.0) cleanup_timeout = environment_cleanup_timeout(config, cleanup_timeout, default=DEFAULT_TEAM_CLEANUP_TIMEOUT_SECONDS) team_config = load_team_config(workspace, path=team_config_path) @@ -80,10 +227,11 @@ async def run_team( output_dir=str(artifacts), filename="trajectory.jsonl", ) - try: - scheduler = await prepare_scheduler( + async def prepare(stop_requested: asyncio.Event) -> Scheduler: + return await prepare_scheduler( context, builder=_programmatic.build_scheduler, isolation=isolation, environment_providers=environment_providers, + stop_requested=stop_requested, workflow_cleanup_timeout=workflow_cleanup_timeout, cleanup_timeout=cleanup_timeout, use_worktrees=use_worktrees, @@ -102,6 +250,9 @@ async def run_team( record_delivery_tree=record_delivery_tree, run_id=run_id, ) + + try: + scheduler = await _prepare_team_scheduler(prepare, deadline, cleanup_timeout=cleanup_timeout) except BaseException as exc: tracer_failure = _programmatic._close_tracer(context.tracer) if tracer_failure is not None: @@ -110,6 +261,17 @@ async def run_team( "team tracer close also failed: " f"{type(tracer_failure).__name__}: {tracer_failure}", ) + if isinstance(exc, _TeamPreparationDeadlineExceeded): + _programmatic._verify_artifact_claim(artifacts) + quiesced = exc.quiesced and tracer_failure is None + return ProgrammaticResult( + output=None, status="stopped", reason="timeout", tokens=0, artifacts=artifacts, error=exc, + metrics={"run_id": run_id, "steps": 0, "sessions": 0, **_programmatic._quiescence_metrics( + session_quiesced=quiesced, environment_owned=environment is None, + environment_cleanup_quiesced=quiesced if environment is None else None, + environment_quiesced=quiesced if environment is None else None, + )}, + ) raise output: str | None = None status: Literal["completed", "stopped", "failed"] = "completed" @@ -119,11 +281,11 @@ async def run_team( wind_down_failure: BaseException | None = None try: try: - if timeout is None: - output = await scheduler.run(prompt) - else: - output = await asyncio.wait_for(scheduler.run(prompt), timeout=timeout) + remaining = None if deadline is None else deadline - loop.time() + output = await _run_team_turn(scheduler, prompt, remaining, cleanup_timeout=cleanup_timeout) except asyncio.TimeoutError as exc: + if isinstance(exc, _TeamDeadlineExceeded): + output = exc.output status = "stopped" reason = "timeout" failure = exc diff --git a/opencollab/bootstrap/session_factory.py b/opencollab/bootstrap/session_factory.py index 20d2c199..9496e7d0 100644 --- a/opencollab/bootstrap/session_factory.py +++ b/opencollab/bootstrap/session_factory.py @@ -12,6 +12,7 @@ import os import re import uuid +from contextlib import ExitStack from dataclasses import replace from datetime import datetime from pathlib import Path @@ -33,6 +34,7 @@ from opencollab.application.exception_notes import add_exception_note from opencollab.application.ports import ( AskUserPort, + AutosaveOwnershipStorePort, EventPublisherPort, LLMPort, PermissionPort, @@ -40,11 +42,10 @@ SchedulerPort, SessionStorePort, ShaperPort, - SnapshotStorePort, ) from opencollab.application.run_control import RunControl from opencollab.application.scheduler import LaunchSpec -from opencollab.application.session import Session +from opencollab.application.session import Session, _acquire_autosave_writer, _read_session_snapshot from opencollab.bootstrap.agent_profiles import ( SingleAgentProfile, resolve_agent_profile, @@ -275,29 +276,50 @@ def load_session( Omitted ``aid`` and ``run_id`` values come from the snapshot, so records written during construction and later turns retain the saved identity. """ - explicit_aid = kwargs.get("aid") - if "aid" not in kwargs or "run_id" not in kwargs: - kwargs = {**_snapshot_identity(path, agent, kwargs.get("store")), **kwargs} - session = build_session(agent=agent, **kwargs) - session.restore(path, aid=explicit_aid) - return session - -def _snapshot_identity(path: str, agent: Agent, store: SessionStorePort | None) -> dict[str, Any]: - """The saved identity fields available before constructing the session. + store = kwargs.get("store") + if store is None: + store = SessionStore() + target = kwargs.get("auto_save_path") + session = None + try: + with ExitStack() as ownership: + if target and isinstance(store, AutosaveOwnershipStorePort): + ownership.callback(_acquire_autosave_writer(store, target)) + snapshot = _read_session_snapshot(store, path, agent.system_prompt) + options = {**_snapshot_identity(snapshot), **kwargs, "store": store} + session = build_session(agent=agent, **options) + session._restore_snapshot(path, snapshot, aid=kwargs.get("aid")) + return session + except BaseException as error: + if session is not None: + restore_error = error + + async def rollback() -> None: + operations = [("session", session.aclose)] + if kwargs.get("env") is None and session.env is not None: + operations.append(("environment", session.env.cleanup)) + for label, close in operations: + try: + await close() + except BaseException as failure: + add_exception_note( + restore_error, f"restore {label} cleanup also failed: {type(failure).__name__}: {failure}", + ) + + try: + run_coro_blocking(rollback) + except BaseException as failure: + add_exception_note(error, f"restore rollback also failed: {type(failure).__name__}: {failure}") + raise - Anything unreadable is left for ``restore`` to report. - """ +def _snapshot_identity(snapshot: dict[str, Any]) -> dict[str, Any]: identity: dict[str, Any] = {} - resolved = store if store is not None else SessionStore() - if not isinstance(resolved, SnapshotStorePort): - return identity + run_id = snapshot.get("run_id") + if isinstance(run_id, str) and run_id.strip() and "\x00" not in run_id: + identity["run_id"] = run_id try: - snapshot = resolved.load_snapshot(path, agent.system_prompt) - run_id = snapshot.get("run_id") - if isinstance(run_id, str) and run_id.strip() and "\x00" not in run_id: - identity["run_id"] = run_id identity["aid"] = int(snapshot["aid"]) - except Exception: # noqa: BLE001 - restore raises the real error + except (KeyError, TypeError, ValueError, OverflowError): pass return identity diff --git a/opencollab/bootstrap/team_workflow.py b/opencollab/bootstrap/team_workflow.py index 4988f620..ffe9fedb 100644 --- a/opencollab/bootstrap/team_workflow.py +++ b/opencollab/bootstrap/team_workflow.py @@ -23,6 +23,14 @@ from opencollab.bootstrap.context_builder import SpawnConfig +def _format_workflow_output(output: Any) -> Any: + try: + payload = json.dumps(output, ensure_ascii=False, allow_nan=False, default=str) + return json.loads(payload.encode("utf-8")) + except (TypeError, ValueError, OverflowError, RecursionError) as exc: + raise ValueError(f"Workflow output is not JSON serializable: {exc}") from exc + + class TeamWorkflowTool(Tool): name = "run_workflow" description = ( @@ -110,12 +118,13 @@ def on_event(event: RunEvent) -> None: spec, params["args"], cfg=config, workspace=runtime.environment.workspace if runtime.environment is not None else None, env=runtime.environment, cleanup_environment=False, - budget=budget, limit_mode="explicit", + budget=budget, allow_budget_escape=False, limit_mode="explicit", max_concurrency=params.get("concurrency", 4), max_steps=parent.max_steps, llm=parent._llm, session_builder=build_child, save_dir=save_dir, trace=self._config.tracer is not None, return_details=True, + format_output=_format_workflow_output, )) async def cancel_workflow() -> None: @@ -142,4 +151,4 @@ async def cancel_workflow() -> None: "stop_reason": result.stop_reason, "agent_failures": result.agent_failures, "artifacts": save_dir, - }, ensure_ascii=False, default=str) + }, ensure_ascii=False, allow_nan=False, default=str) diff --git a/opencollab/bootstrap/workflow_runtime.py b/opencollab/bootstrap/workflow_runtime.py index 2c52f012..bff60a92 100644 --- a/opencollab/bootstrap/workflow_runtime.py +++ b/opencollab/bootstrap/workflow_runtime.py @@ -20,6 +20,7 @@ from opencollab.bootstrap._workflow_runtime_execution import ( run_workflow as _run_workflow_with_integrity, ) +from opencollab.bootstrap._workflow_runtime_manifest import _snapshot_workflow_args from opencollab.bootstrap._workflow_runtime_session import ( _WORKFLOW_ENV_OVERRIDE, WorkflowSessionFactory, @@ -34,16 +35,12 @@ _PROFILE_TOOL_LIMITS, resolve_agent_profile, ) -from opencollab.bootstrap.agent_runtime import revoke_and_abort_environment +from opencollab.bootstrap.agent_runtime import _environment_abort_failure from opencollab.bootstrap.environment_profiles import environment_cleanup_timeout from opencollab.bootstrap.session_factory import build_session -# The integrity runtime's own bounded cleanup can legitimately span several -# cleanup_timeout phases (session quiesce runs two passes, each bounded by its -# persistence and environment-abort sub-phases). Give the owner that full -# envelope to self-finish before escalating to the injected-environment fallback -# and force-termination, so a slow-but-legitimate teardown is not force-cancelled -# into a spurious WorkflowLifecycleError. +# Allow the owner to finish its bounded quiescence, save, and teardown +# before falling back to environment abort and forced termination. _OWNER_CLEANUP_GRACE_PHASES = 4 class WorkflowDeadlineExceeded(TimeoutError): @@ -61,6 +58,10 @@ def __init__( class WorkflowLifecycleError(RuntimeError): """Workflow-owned work failed to reach a terminal state.""" + def __init__(self, message: str, *, runtime_result: WorkflowRuntimeResult | None = None) -> None: + super().__init__(message) + self.runtime_result = runtime_result + async def _wait_for_owner( owner: asyncio.Task[Any], *, @@ -78,12 +79,14 @@ async def run_workflow( tracer: TracePort | None = None, event_sink: EventPublisherPort | None = None, budget: int | None = None, + allow_budget_escape: bool = True, max_concurrency: int = 4, task_concurrency: int | None = None, max_steps: int | None = None, system_prompt: str = WORKFLOW_AGENT_PROMPT, agent_profile: Any | None = None, save_dir: str | None = None, + manifest_args: dict[str, Any] | None = None, trace: bool = True, env: Any | None = None, cleanup_timeout: float | None = None, @@ -91,6 +94,7 @@ async def run_workflow( deadline_monotonic: float | None = None, deadline_margin_seconds: float = 120.0, return_details: bool = False, + format_output: Callable[[Any], Any] | None = None, cleanup_environment: bool | None = None, defer_manifest_completion: bool = False, candidate_workspace: Any | None = None, @@ -109,12 +113,14 @@ async def run_workflow( agent_profile = resolve_agent_profile(agent_profile) if cleanup_environment is None: cleanup_environment = env is None + if save_dir is not None and manifest_args is None: + manifest_args = _snapshot_workflow_args(args) token = _WORKFLOW_ENV_OVERRIDE.set(env) - cancelled_result: WorkflowRuntimeResult | None = None + terminal_result: WorkflowRuntimeResult | None = None cancelled_notes: tuple[str, ...] = () async def run_owner() -> Any: - nonlocal cancelled_result, cancelled_notes + nonlocal terminal_result, cancelled_notes tools_token = _PROFILE_TOOL_LIMITS.set( None if agent_profile is None else agent_profile.tool_limits ) @@ -127,6 +133,7 @@ async def run_owner() -> Any: tracer=tracer, event_sink=event_sink, budget=budget, + allow_budget_escape=allow_budget_escape, max_concurrency=max_concurrency, task_concurrency=task_concurrency, max_steps=max_steps, @@ -139,6 +146,7 @@ async def run_owner() -> Any: candidate_workspace=candidate_workspace, run_id=run_id, save_dir=save_dir, + manifest_args=manifest_args, trace=trace, cleanup_timeout=cleanup_timeout, env=env, @@ -146,22 +154,24 @@ async def run_owner() -> Any: deadline_monotonic=deadline_monotonic, deadline_margin_seconds=deadline_margin_seconds, return_details=return_details, + format_output=format_output, cleanup_environment=cleanup_environment, defer_manifest_completion=defer_manifest_completion, ) - except asyncio.CancelledError as cancellation: - attached = getattr(cancellation, "runtime_result", None) + except BaseException as failure: + attached = getattr(failure, "runtime_result", None) if isinstance(attached, WorkflowRuntimeResult): - cancelled_result = attached - cancelled_notes = tuple(getattr(cancellation, "__notes__", ())) + terminal_result = attached + if isinstance(failure, asyncio.CancelledError): + cancelled_notes = tuple(getattr(failure, "__notes__", ())) raise finally: _PROFILE_TOOL_LIMITS.reset(tools_token) owner = asyncio.create_task(run_owner()) - stop_task: asyncio.Task[tuple[bool, bool]] | None = None + stop_task: asyncio.Task[tuple[BaseException | None, bool]] | None = None - async def stop_owned(cancellation: asyncio.CancelledError) -> tuple[bool, bool]: + async def stop_owned(cancellation: asyncio.CancelledError) -> tuple[BaseException | None, bool]: if not owner.done(): owner.cancel(*cancellation.args) @@ -172,21 +182,18 @@ async def stop_owned(cancellation: asyncio.CancelledError) -> tuple[bool, bool]: done, _pending = await asyncio.wait( {owner}, timeout=cleanup_timeout * _OWNER_CLEANUP_GRACE_PHASES ) - aborted = True - if cleanup_environment: - aborted = env is None or bool(getattr(env, "revoked", False)) - if not aborted: - aborted = await revoke_and_abort_environment(env, cleanup_timeout) - if done: - return aborted, True - terminal = await force_task_terminal(owner, timeout=cleanup_timeout) - return aborted, terminal + abort_failure = None + environment_deferred = terminal_result is not None and terminal_result.environment_cleanup_deferred + if cleanup_environment and env is not None and not environment_deferred and not getattr(env, "revoked", False): + abort_failure = await _environment_abort_failure(env, cleanup_timeout) + terminal = bool(done) or await force_task_terminal(owner, timeout=cleanup_timeout) + return abort_failure, terminal async def stop_once( cancellation: asyncio.CancelledError, *, propagate_cancellation: bool, - ) -> tuple[bool, bool]: + ) -> tuple[BaseException | None, bool]: nonlocal stop_task if stop_task is None: stop_task = asyncio.create_task(stop_owned(cancellation)) @@ -205,13 +212,18 @@ async def stop_once( deadline_cancellation = asyncio.CancelledError( "workflow wall-clock deadline expired" ) - aborted, terminated = await stop_once( + abort_failure, terminated = await stop_once( deadline_cancellation, propagate_cancellation=True, ) - if not aborted or not terminated: - raise WorkflowLifecycleError("timed-out workflow did not reach a quiescent terminal state") - deadline_result = cancelled_result + if abort_failure is not None or not terminated: + failure = WorkflowLifecycleError( + "timed-out workflow did not reach a quiescent terminal state", runtime_result=terminal_result, + ) + deadline_error = WorkflowDeadlineExceeded(str(deadline_cancellation), result=terminal_result) + failure.__context__ = deadline_error + raise failure from (abort_failure if abort_failure is not None else deadline_error) + deadline_result = terminal_result try: late_result = owner.result() if isinstance(late_result, WorkflowRuntimeResult): @@ -223,46 +235,52 @@ async def stop_once( notes = cancelled_notes or tuple(getattr(inner, "__notes__", ())) if notes: failure = WorkflowLifecycleError( - "timed-out workflow reported a cleanup or persistence failure" + "timed-out workflow reported a cleanup or persistence failure", + runtime_result=deadline_result, ) for note in notes: add_exception_note(failure, note) raise failure from inner except BaseException as inner: raise WorkflowLifecycleError( - "timed-out workflow failed while reaching its terminal state" + "timed-out workflow failed while reaching its terminal state", runtime_result=terminal_result, ) from inner raise WorkflowDeadlineExceeded( "workflow wall-clock deadline expired", result=deadline_result, ) except asyncio.CancelledError as cancellation: - aborted, terminated = await stop_once( + abort_failure, terminated = await stop_once( cancellation, propagate_cancellation=False ) - if not aborted or not terminated: - raise WorkflowLifecycleError( - "cancelled workflow did not reach a quiescent terminal state" - ) from cancellation + if abort_failure is not None or not terminated: + failure = WorkflowLifecycleError( + "cancelled workflow did not reach a quiescent terminal state", runtime_result=terminal_result, + ) + if abort_failure is not None: + add_exception_note( + failure, f"environment abort also failed: {type(abort_failure).__name__}: {abort_failure}", + ) + raise failure from cancellation if owner.done(): try: late_result = owner.result() if isinstance(late_result, WorkflowRuntimeResult): - cancelled_result = late_result + terminal_result = late_result except asyncio.CancelledError as inner: for note in cancelled_notes or getattr(inner, "__notes__", ()): add_exception_note(cancellation, note) except BaseException as inner: attached = getattr(inner, "runtime_result", None) if isinstance(attached, WorkflowRuntimeResult): - cancelled_result = attached + terminal_result = attached add_exception_note( cancellation, "workflow owner also failed during cancellation: " f"{type(inner).__name__}: {inner}" ) - if cancelled_result is not None: - cancellation.runtime_result = cancelled_result # type: ignore[attr-defined] + if terminal_result is not None: + cancellation.runtime_result = terminal_result # type: ignore[attr-defined] raise cancellation finally: _WORKFLOW_ENV_OVERRIDE.reset(token) diff --git a/opencollab/builtin_workflows/duo/_candidate_records.py b/opencollab/builtin_workflows/duo/_candidate_records.py index bf7d0903..e4573193 100644 --- a/opencollab/builtin_workflows/duo/_candidate_records.py +++ b/opencollab/builtin_workflows/duo/_candidate_records.py @@ -60,6 +60,12 @@ def _record_state(record: dict[str, Any]) -> str | None: return "red" return None +def _verified_for_budget_fallback(candidate: CandidateRun) -> bool: + if not candidate.effective_diff.strip() or candidate.lifecycle_errors: + return False + states = {_record_state(record) for record in _candidate_records(candidate)} + return "green" in states and "red" not in states + def _public_red_winner( candidate_a: CandidateRun, candidate_b: CandidateRun, @@ -93,8 +99,8 @@ async def _adopt( order = [winner, *(label for label in ("A", "B") if label != winner)] attempts: list[str] = [] for label in order: - candidate = candidates[label] - if not candidate.effective_diff.strip(): + candidate = candidates.get(label) + if candidate is None or not candidate.effective_diff.strip(): continue attempts.append(label) try: diff --git a/opencollab/builtin_workflows/duo/_dual_coder.py b/opencollab/builtin_workflows/duo/_dual_coder.py index e7c673cf..20e05cfc 100644 --- a/opencollab/builtin_workflows/duo/_dual_coder.py +++ b/opencollab/builtin_workflows/duo/_dual_coder.py @@ -8,6 +8,7 @@ from dataclasses import replace from typing import Any +from opencollab.application.workflow_collections import WorkflowBudgetExceeded from opencollab.patches import patch_paths from opencollab.tools import evidence_tools from opencollab.workflows import CandidateRun @@ -67,6 +68,27 @@ async def _coder_candidate( }, ) +def _candidate_summary(candidate: CandidateRun | None, kind: str) -> dict[str, Any]: + if candidate is None: + return { + "kind": kind, + "status": "skipped", + "reason": "budget_exceeded", + "nonempty": False, + "diff_bytes": 0, + "changed_paths": [], + "public_command": "", + "public_test_records": [], + } + return { + "kind": kind, + "nonempty": bool(candidate.effective_diff.strip()), + "diff_bytes": len(candidate.diff.encode("utf-8")), + "changed_paths": patch_paths(candidate.effective_diff), + "public_command": dual._candidate_command(candidate), + "public_test_records": dual._candidate_records(candidate), + } + async def _contract_adjudicate( ctx: Any, *, @@ -176,20 +198,29 @@ async def run_dual_coder( shared_command = dual._candidate_command(candidate_a) await ctx.phase("dual-coder-b") - candidate_b = await _coder_candidate( - ctx, - label="dual-coder-contract-b", - prompt=prompts[1], - goal=goal, - shared_command=shared_command, - rules=role_rules, - ) + budget_refusal = None + try: + candidate_b = await _coder_candidate( + ctx, + label="dual-coder-contract-b", + prompt=prompts[1], + goal=goal, + shared_command=shared_command, + rules=role_rules, + ) + if candidate_b.initial_budget_refusal is not None: + raise WorkflowBudgetExceeded(candidate_b.initial_budget_refusal) + except WorkflowBudgetExceeded as exc: + if not dual._verified_for_budget_fallback(candidate_a): + raise + budget_refusal = exc + candidate_b = None await ctx.phase("dual-coder-mechanical-selection") - winner, reason, needs_judge = contract._mechanical_choice( - candidate_a, - candidate_b, - ) + if candidate_b is None: + winner, reason, needs_judge = "A", "candidate-b-budget-exhausted", False + else: + winner, reason, needs_judge = contract._mechanical_choice(candidate_a, candidate_b) judge_result: Any = None if needs_judge: await ctx.phase("dual-coder-contract-adjudication") @@ -212,7 +243,9 @@ async def run_dual_coder( if source_changed: raise RuntimeError("candidate_workspace_tracking_failure: source worktree changed before candidate adoption") - candidates = {"A": candidate_a, "B": candidate_b} + candidates = {"A": candidate_a} + if candidate_b is not None: + candidates["B"] = candidate_b preserve_paths = [str(path) for path in args.get("injected_test_paths") or [] if str(path)] adopted, adoption_attempts = await dual._adopt( ctx, @@ -220,6 +253,8 @@ async def run_dual_coder( candidates=candidates, preserve_paths=preserve_paths, ) + if adopted is None and budget_refusal is not None: + raise budget_refusal return { "status": "done" if adopted is not None else "incomplete", "submission_mode": submission_mode, @@ -231,22 +266,8 @@ async def run_dual_coder( "adoption_attempts": adoption_attempts, "shared_public_command": shared_command, "candidates": { - "A": { - "kind": "minimal-root-cause-coder", - "nonempty": bool(candidate_a.effective_diff.strip()), - "diff_bytes": len(candidate_a.diff.encode("utf-8")), - "changed_paths": patch_paths(candidate_a.effective_diff), - "public_command": dual._candidate_command(candidate_a), - "public_test_records": dual._candidate_records(candidate_a), - }, - "B": { - "kind": "cross-component-contract-coder", - "nonempty": bool(candidate_b.effective_diff.strip()), - "diff_bytes": len(candidate_b.diff.encode("utf-8")), - "changed_paths": patch_paths(candidate_b.effective_diff), - "public_command": dual._candidate_command(candidate_b), - "public_test_records": dual._candidate_records(candidate_b), - }, + "A": _candidate_summary(candidate_a, "minimal-root-cause-coder"), + "B": _candidate_summary(candidate_b, "cross-component-contract-coder"), }, "tokens_spent": ctx.tokens_spent(), } diff --git a/opencollab/builtin_workflows/reconstruct/__init__.py b/opencollab/builtin_workflows/reconstruct/__init__.py index 56fee1c8..2b58eff6 100644 --- a/opencollab/builtin_workflows/reconstruct/__init__.py +++ b/opencollab/builtin_workflows/reconstruct/__init__.py @@ -14,15 +14,22 @@ from __future__ import annotations +import errno import importlib import json +import os import shutil +import tokenize import uuid +from collections.abc import Iterator +from contextlib import contextmanager from copy import deepcopy from dataclasses import dataclass from pathlib import Path +from tempfile import mkdtemp from typing import Any, Awaitable, Callable, Sequence +from opencollab.application.exception_notes import add_exception_note from opencollab.workflows import workflow from ._coverage import describe @@ -122,12 +129,14 @@ class ReconstructionTask: ``oracle`` returns the hidden program's output for an input (raise for an invalid input). ``evaluate`` runs a candidate file on inputs and returns one ``{"ok": True, "output": ...}`` or ``{"ok": False, "error": ...}`` - per input; it should execute the candidate where the agent's own code - runs, never in the harness process. ``tools`` are handed to every coding - session. ``random_inputs(k, exclude)`` draws fresh inputs from a source + per input. The evaluator receives a temporary copy in a staged workspace + with links to the candidate's sibling files and packages. + Execute the copy in the agent's environment, never in the harness process. + ``tools`` are handed to every coding session. + ``random_inputs(k, exclude)`` draws fresh inputs from a source independent of the agent (the benchmark's generator); it is required - when ``random_share`` is positive. ``on_example`` is told about every - observed example and its source (``agent`` or ``random``). ``kind``, + when ``random_share`` is positive. ``on_example`` receives detached input + and output values for every observed example and its source. ``kind``, ``lo``, ``hi`` and ``is_float`` describe the input for the coverage gate and the domain check (kinds: list, two_lists, int, pair, string, points). """ @@ -219,6 +228,135 @@ def _input_key(value: Any) -> str: return repr(value) +def _remove_candidate_file(path: Path, kind: str, error: BaseException | None = None) -> None: + try: + path.unlink(missing_ok=True) + except OSError as cleanup_error: + if error is None: + raise + add_exception_note(error, f"candidate {kind} cleanup failed for {path.name} ({cleanup_error})") + + +def _archive_candidate(program: Path, candidates_dir: Path, iteration: int) -> Path: + stem = f"iter_{iteration:03d}" + path = candidates_dir / f"{stem}.py" + suffix = 2 + while True: + try: + destination = path.open("xb") + except FileExistsError: + path = candidates_dir / f"{stem}_{suffix}.py" + suffix += 1 + continue + try: + with destination, program.open("rb") as source: + shutil.copyfileobj(source, destination) + shutil.copymode(program, path) + except BaseException as error: + _remove_candidate_file(path, "archive", error) + raise + return path + + +def _read_candidate_source(path: Path) -> str: + try: + with tokenize.open(path) as source: + return source.read() + except (LookupError, SyntaxError, UnicodeError): + # The evaluator supplies decoding errors as candidate feedback. + return "" + + +def _stage_relative_gitfile(source: Path, staged: Path) -> bool: + prefix = b"gitdir: " + try: + contents = source.read_bytes() + if not contents.startswith(prefix): + return False + pointer = os.fsdecode(contents[len(prefix):].rstrip(b"\r\n")) + if not pointer or os.path.isabs(pointer): + return False + # Git resolves a gitdir pointer from the directory containing the marker. + gitdir = (source.parent / pointer).resolve() + relative = os.path.relpath(gitdir, start=staged.resolve()) + except (OSError, RuntimeError, ValueError): + return False + (staged / source.name).write_bytes(prefix + os.fsencode(relative) + b"\n") + return True + + +@contextmanager +def _evaluation_directory(archive: Path, program: Path, workspace: Path) -> Iterator[Path]: + prefix = "_oc_evaluate_" + original = Path(os.path.abspath(program)) + source = Path(os.path.abspath(workspace)) + if original.is_relative_to(source): + relative = original.relative_to(source) + else: + source = original.parent + relative = Path(original.name) + locations = [workspace, archive.parent] + if len(relative.parts) > 1: + locations.insert(1, workspace / relative.parent) + for parent in locations: + try: + directory = Path(os.path.abspath(mkdtemp(dir=parent, prefix=prefix))) + except OSError as exc: + if parent == archive.parent or exc.errno not in {errno.EACCES, errno.EPERM, errno.EROFS}: + raise + else: + break + error = None + try: + # Keep the outer namespace free of __init__.py so package discovery skips it. + staged = directory / "workspace.copy" + # Match the nested module path that -m derives from the dotted filesystem name. + module_path = directory / "workspace" / "copy" + module_path.parent.mkdir() + try: + module_path.symlink_to(Path("..") / staged.name, target_is_directory=True) + except OSError as exc: + if exc.errno not in {errno.EACCES, errno.EPERM, errno.ENOSYS, errno.ENOTSUP, errno.EOPNOTSUPP}: + raise + staged = module_path.parent + else: + staged.mkdir() + archive_dir = Path(os.path.abspath(archive.parent)) + for part in relative.parts: + target = source / part + try: + siblings = list(source.iterdir()) + except PermissionError: + siblings = [] + for sibling in siblings: + if sibling in (target, directory, archive_dir) or sibling.name == "__pycache__": + continue + is_directory = sibling.is_dir() + if is_directory or sibling.is_file(): + if sibling.name == ".git" and not is_directory and _stage_relative_gitfile(sibling, staged): + continue + (staged / sibling.name).symlink_to( + os.path.relpath(sibling, start=staged), target_is_directory=is_directory, + ) + source = target + staged /= part + if source != original: + staged.mkdir() + shutil.copy(archive, staged) + directory.chmod((parent.stat().st_mode & 0o777) | 0o700) + yield parent / staged.relative_to(directory.parent) + except BaseException as exc: + error = exc + raise + finally: + try: + shutil.rmtree(directory) + except OSError as exc: + if error is None: + raise + add_exception_note(error, f"candidate evaluation directory cleanup failed for {directory.name} ({exc})") + + @workflow( name="reconstruct", description="Reconstruct a hidden program from input/output observations with batched active exploration", @@ -294,23 +432,24 @@ def accept(batch: list[tuple[Any, Any]], source: str) -> None: examples.append((inp, out)) sources.append(source) if task.on_example is not None: - task.on_example(inp, out, source) + task.on_example(deepcopy(inp), deepcopy(out), source) - async def failures(path: Path) -> list[str]: - if not path.is_file(): + async def failures(path: Path | None) -> list[str]: + if path is None or not path.is_file(): return [f"{task.candidate_file} is missing"] - results = await task.evaluate(path, [i for i, _ in examples]) - if len(results) != len(examples): - raise RuntimeError( - f"candidate evaluator returned {len(results)} results for {len(examples)} inputs" - ) - out = [] - for (inp, expected), res in zip(examples, results): - if not res.get("ok"): - out.append(f"{inp!r}: expected {expected!r}, got {res.get('error')}") - elif not task.outputs_match(res.get("output"), jsonable(expected)): - out.append(f"{inp!r}: expected {expected!r}, got {res.get('output')!r}") - return out + with _evaluation_directory(path, program, workspace) as evaluation_path: + results = await task.evaluate(evaluation_path, deepcopy([inp for inp, _ in examples])) + if len(results) != len(examples): + raise RuntimeError( + f"candidate evaluator returned {len(results)} results for {len(examples)} inputs" + ) + out = [] + for (inp, expected), res in zip(examples, results): + if not res.get("ok"): + out.append(f"{inp!r}: expected {expected!r}, got {res.get('error')}") + elif not task.outputs_match(res.get("output"), jsonable(expected)): + out.append(f"{inp!r}: expected {expected!r}, got {res.get('output')!r}") + return out async def request_examples(n: int, round_no: int) -> bool: """Fill a batch of n new inputs: a random share first, the rest proposed by the agent.""" @@ -426,15 +565,19 @@ async def request_examples(n: int, round_no: int) -> bool: await call_agent(prompt=prompt, label=f"code:{iteration}", tools=list(task.tools)) if stop_reason: break - fails = await failures(program) - candidate_exists = program.is_file() - passed = len(examples) - len(fails) if candidate_exists else 0 + archive = _archive_candidate(program, candidates_dir, iteration) if program.is_file() else None + try: + fails = await failures(archive) + except BaseException as error: + if archive is not None: + _remove_candidate_file(archive, "archive", error) + raise + passed = len(examples) - len(fails) if archive is not None else 0 score = None source = "" - if candidate_exists: - archived.append(candidates_dir / f"iter_{iteration:03d}.py") - shutil.copy(program, archived[-1]) - source = program.read_text(encoding="utf-8") + if archive is not None: + archived.append(archive) + source = _read_candidate_source(archive) score = round(stage_score(source, passed / len(examples) if examples else 0.0, examples), 4) promoted = not fails miss = uncovered() if promoted else set() @@ -490,7 +633,7 @@ async def request_examples(n: int, round_no: int) -> bool: stop_reason = stop_reason or "proposer_failed" break next_batch += batch_step - new_fails = await failures(program) + new_fails = await failures(archive) if new_fails: feedback += "\nYour candidate fails these new examples:\n" + "\n".join(new_fails[:10]) continue @@ -512,7 +655,7 @@ async def request_examples(n: int, round_no: int) -> bool: stop_reason = stop_reason or "proposer_failed" break next_batch += batch_step - new_fails = await failures(program) + new_fails = await failures(archive) feedback = ( "Your current candidate fails these known examples:\n" + "\n".join(new_fails[:10]) if new_fails @@ -531,7 +674,7 @@ async def request_examples(n: int, round_no: int) -> bool: for path in archived: fails = await failures(path) if examples else [] acc = (len(examples) - len(fails)) / len(examples) if examples else 0.0 - score = stage_score(path.read_text(encoding="utf-8"), acc, examples) + score = stage_score(_read_candidate_source(path), acc, examples) if score >= best_score: best_path, best_score = path, score if best_path is not None: diff --git a/opencollab/builtin_workflows/reconstruct/_verification.py b/opencollab/builtin_workflows/reconstruct/_verification.py index 9790b1df..662e5d80 100644 --- a/opencollab/builtin_workflows/reconstruct/_verification.py +++ b/opencollab/builtin_workflows/reconstruct/_verification.py @@ -7,6 +7,8 @@ import ast import json +import math +from fractions import Fraction from typing import Any MEMORISED_INPUTS_THRESHOLD = 3 # distinct non-trivial observed inputs embedded as literals @@ -54,6 +56,8 @@ def outputs_match(actual: Any, expected: Any) -> bool: if _is_real_number(expected) and _is_real_number(actual): if isinstance(expected, int): return actual == expected + if isinstance(actual, int): + return math.isfinite(expected) and abs(Fraction(expected) - actual) < 1e-6 return abs(actual - expected) < 1e-6 return actual == expected diff --git a/opencollab/builtin_workflows/weave/__init__.py b/opencollab/builtin_workflows/weave/__init__.py index 9c947fde..e3d1bd26 100644 --- a/opencollab/builtin_workflows/weave/__init__.py +++ b/opencollab/builtin_workflows/weave/__init__.py @@ -9,10 +9,10 @@ import time import uuid from collections.abc import Mapping, Sequence -from contextlib import suppress from dataclasses import asdict, dataclass, field from typing import Any +from opencollab.application.exception_notes import add_exception_note from opencollab.sdk import BudgetDecision, BudgetSnapshot, RunControl, RunEvent from opencollab.tools import Tool from opencollab.workflows import WorkflowContext, workflow @@ -72,6 +72,18 @@ def __post_init__(self) -> None: def passed(self) -> bool: return self.ok and self.executed + @property + def _completed(self) -> bool: + return self.executed and not any( + self.report.get(field) is True for field in ("timed_out", "evidence_incomplete") + ) + + @property + def _can_finish_repair(self) -> bool: + return self._completed or ( + self.executed and self.report.get("timed_out") is not True and bool(self.repair_targets) + ) + @dataclass class WeaveConfig: """Optional resource limits and scheduling ratios for a concrete invocation.""" @@ -231,9 +243,11 @@ async def verify(self, ctx: WorkflowContext, targets: tuple[str, ...] | None, rows = report["checks"] return WeaveCheck( report["ok"], report["executed"], report, - tuple(row["command"] for row in rows if row["executed"] and not row["ok"] and ( - row.get("exit_code") not in {0, 5} or (row.get("matched") is False and ( - row.get("exit_code") != 5 or not row.get("test_records") + tuple(row["command"] for row in rows if row["executed"] and not row["ok"] and not row.get("timed_out") and ( + row.get("exit_code") not in {0, 5} + or (row.get("matched") is False and ( + (row["exit_code"] == 0 and not row.get("output_truncated")) + or (row["exit_code"] == 5 and not row.get("test_records")) )) )), tuple(row["command"] for row in rows if row["ok"]), @@ -454,6 +468,7 @@ def decide(snapshot: BudgetSnapshot) -> BudgetDecision: return BudgetDecision(cap, final_prompt=prompt) heartbeat = asyncio.create_task(self.heartbeat(label)) + primary_error: BaseException | None = None try: result = await self.ctx.agent_run( prompt, tools=adapter.tools(label), budget=hard, timeout=seconds, max_steps=steps, @@ -462,10 +477,16 @@ def decide(snapshot: BudgetSnapshot) -> BudgetDecision: history_trigger_tokens=config.history_trigger_tokens, tool_cancellation_cleanup_timeout=config.tool_cleanup_seconds), ) + except BaseException as error: + primary_error = error + raise finally: heartbeat.cancel() - with suppress(asyncio.CancelledError): - await heartbeat + heartbeat_result, = await asyncio.gather(heartbeat, return_exceptions=True) + if isinstance(heartbeat_result, Exception): + if primary_error is None: + raise heartbeat_result + add_exception_note(primary_error, f"Weave heartbeat failed: {heartbeat_result}") if result.session_id: state.observe(label, result.session_id, result.tokens, result.steps) if not result.cleanup_complete or not result.workspace_ready: @@ -486,16 +507,44 @@ async def check(self, targets: tuple[str, ...] | None, seconds: float | None) -> async def full_check(self) -> WeaveCheck: seconds = max(0, min(self.seconds_left() - self.config.final_check_time_reserve, _minimum(self.config.final_check_timeout))) - check = await self.check(None, _optional(seconds)) + return await self.check(None, _optional(seconds)) + + def record_full_check(self, check: WeaveCheck) -> None: self.state.data["verification"] = asdict(check) self.persist("check_finished", number=len(self.state.data["repair_rounds"]), check=check) - return check + + async def finish_repair( + self, row: dict[str, Any], before: WeaveCheck, stagnant: int, + ) -> tuple[WeaveCheck, int]: + report = await self.full_check() + if "before_verification" not in row: + row["before_verification"] = asdict(before) + self.record_full_check(report) + if not report._can_finish_repair: + return report, stagnant + advanced = self.adapter.improved(before, report) + stagnant = 0 if advanced else stagnant + 1 + row.update(row.pop("result"), observable_progress=advanced, stagnant_rounds=stagnant) + row.pop("before_verification", None) + self.persist("repair_finished", number=row["round"], result=row, check=report) + return report, stagnant async def repair(self) -> tuple[WeaveCheck, str]: await self.ctx.phase("Full delivery verification") - report = await self.full_check() rounds, config = self.state.data["repair_rounds"], self.config - stagnant = int(rounds[-1].get("stagnant_rounds", 0)) if rounds else 0 + for row in rounds: + if row.get("status") == "running" and "result" not in row: + row["status"] = "interrupted" + stagnant = next((int(row["stagnant_rounds"]) for row in reversed(rounds) if "stagnant_rounds" in row), 0) + if rounds and rounds[-1].get("status") == "running": + pending = rounds[-1] + before = WeaveCheck(**pending.get("before_verification", self.state.data["verification"])) + report, stagnant = await self.finish_repair(pending, before, stagnant) + if not report._can_finish_repair: + return report, "environment_or_unverified" + else: + report = await self.full_check() + self.record_full_check(report) stop = "passed" if report.passed else "round_limit" if not report.passed and stagnant >= config.stagnant_round_limit: return report, "rounds_without_observable_progress" @@ -520,13 +569,14 @@ async def repair(self) -> tuple[WeaveCheck, str]: await self.ctx.phase(f"Repair round {number}") timeout = min(_minimum(config.repair_timeout), max(config.minimum_session_seconds, seconds - config.repair_agent_time_reserve)) - info = await self.solve(self.adapter.repair_prompt(report, self.state), soft=budget, hard=budget, - steps=config.repair_steps, seconds=_optional(timeout), label=f"repair-{number}") - before, report = report, await self.full_check() - advanced = self.adapter.improved(before, report) - stagnant = 0 if advanced else stagnant + 1 - row.update(info, observable_progress=advanced, stagnant_rounds=stagnant) - self.persist("repair_finished", number=number, result=row, check=report) + row["result"] = await self.solve( + self.adapter.repair_prompt(report, self.state), soft=budget, hard=budget, + steps=config.repair_steps, seconds=_optional(timeout), label=f"repair-{number}", + ) + self.persist() + report, stagnant = await self.finish_repair(row, report, stagnant) + if not report._can_finish_repair: + return report, "environment_or_unverified" if report.passed: stop = "passed" elif stagnant >= config.stagnant_round_limit: @@ -606,7 +656,8 @@ async def run(self) -> dict[str, Any]: changed_files=saved["changed_files"], result=saved["result"]) completed.append((group, saved["changed_files"])) report, repair_stop = await self.repair() - status = "completed" if report.passed else "failed" if report.executed else "unverified" + status = "completed" if report.passed else "failed" if report._completed else "unverified" + state.data.pop("error_type", None) state.data.update(status=status, delivery_ok=report.passed) result = {"run_id": state.data["run_id"], "status": status, "delivery_ok": report.passed, "total_tokens": state.tokens, "elapsed_seconds": state.elapsed, @@ -633,7 +684,10 @@ async def run_weave(ctx: WorkflowContext, groups: Sequence[WeaveGroup], *, except BaseException as error: state.data.update(status="cancelled" if isinstance(error, asyncio.CancelledError) else "failed", delivery_ok=False, error_type=type(error).__name__) - runner.persist("finished", error_type=type(error).__name__, status=state.data["status"]) + try: + runner.persist("finished", error_type=type(error).__name__, status=state.data["status"]) + except Exception as persistence_error: + add_exception_note(error, f"could not persist Weave failure: {persistence_error}") raise @workflow( diff --git a/opencollab/builtin_workflows/weave/_execution.py b/opencollab/builtin_workflows/weave/_execution.py index 87d234f7..eeecf18a 100644 --- a/opencollab/builtin_workflows/weave/_execution.py +++ b/opencollab/builtin_workflows/weave/_execution.py @@ -330,7 +330,8 @@ async def _verify_commands(ctx: Any, commands: Sequence[Any], seconds: float | N truncated = any(getattr(result, key, False) for key in ( "stdout_truncated", "stderr_truncated", "stdout_dropped_bytes", "stderr_dropped_bytes", )) - completed = result.returncode == 0 and not truncated and not getattr(result, "timed_out", False) + timed_out = getattr(result, "timed_out", False) + completed = result.returncode == 0 and not truncated and not timed_out if records: row["ok"] = completed and all(record.get("verified") is True for record in records) requires_test_evidence = tool.requires_test_evidence(command) @@ -346,9 +347,17 @@ async def _verify_commands(ctx: Any, commands: Sequence[Any], seconds: float | N if row["ok"] and not records and _static_printer_supplies(command, expected): row["ok"] = False row["reason"] = "expected output is supplied by a static printer" + if truncated: + row["output_truncated"] = True + row["reason"] = "verification command output was truncated" + if timed_out: + row["timed_out"] = True + row["reason"] = "verification command timed out" checks.append(row) return { "ok": bool(checks) and all(row["ok"] for row in checks), "executed": bool(checks) and all(row["executed"] for row in checks), + "timed_out": any(row.get("timed_out") for row in checks), + "evidence_incomplete": any(row.get("output_truncated") and row.get("exit_code") == 0 for row in checks), "checks": checks, } diff --git a/opencollab/domain/json_data.py b/opencollab/domain/json_data.py new file mode 100644 index 00000000..8813f750 --- /dev/null +++ b/opencollab/domain/json_data.py @@ -0,0 +1,14 @@ +import json +import math +from typing import Any + + +def _finite_float(token: str) -> float: + number = float(token) + if not math.isfinite(number): + raise json.JSONDecodeError("JSON numbers must be finite", token, 0) + return number + + +def loads_finite_json(text: str) -> Any: + return json.loads(text, parse_float=_finite_float, parse_constant=_finite_float) diff --git a/opencollab/domain/session.py b/opencollab/domain/session.py index e97aa739..dd40b8bc 100644 --- a/opencollab/domain/session.py +++ b/opencollab/domain/session.py @@ -6,7 +6,7 @@ from dataclasses import dataclass, field from datetime import datetime, timezone from enum import Enum -from typing import Any +from typing import Any, TypeGuard from opencollab.domain.pending import PendingEventTable from opencollab.domain.tool_loops import LoopState @@ -36,6 +36,14 @@ def same_snapshot_value(left: Any, right: Any) -> bool: return type(left) is type(right) and left == right +def is_pending_user_message(message: object) -> TypeGuard[dict[str, Any]]: + return ( + isinstance(message, dict) + and bool(message.get("content")) + and message.get("delivery_status") != "rejected" + ) + + def _now_iso() -> str: return datetime.now(timezone.utc).isoformat() @@ -217,9 +225,8 @@ class SessionState: # it yet. Unlike scheduler-owned ``pending_user_messages``, this records # the crash window between accepting a public turn and starting its driver. pending_external_user_turn: dict[str, Any] | None = None - # First message position *after* the history visible when the active turn - # began. It is retained only while a deferred turn is suspended so a - # restored runner can keep answer lookup within that turn. + # First message position after the initial turn context. Retained across + # suspension and restore to keep answer lookup within the same turn. active_turn_start_message_index: int | None = None # None retains whole-history answer lookup for legacy completed snapshots. completed_turn_start_message_index: int | None = field(default=None, kw_only=True) diff --git a/opencollab/sdk/client.py b/opencollab/sdk/client.py index 565573a5..c1d3a594 100644 --- a/opencollab/sdk/client.py +++ b/opencollab/sdk/client.py @@ -352,6 +352,9 @@ async def team( team configuration instead defines independent allowances and their total. Combining those allowances with an explicit budget raises ValueError. + ``timeout`` covers workspace preparation and the team turn. Cleanup has + its own ``cleanup_timeout``. + ``record_delivery_tree`` adds ``metrics["tree_snapshots"]`` for agent 0's tree before turns and at accepted messages. Serialized boundaries support seat attribution. It defaults to False, omitting the metric and probe cost. diff --git a/tests/agents/test_agent_runtime.py b/tests/agents/test_agent_runtime.py index 6966f128..b4215397 100644 --- a/tests/agents/test_agent_runtime.py +++ b/tests/agents/test_agent_runtime.py @@ -192,6 +192,58 @@ async def test_agent_runtime_timeout_still_aborts_when_revoke_fails(monkeypatch) await _run_agent(environment, timeout_seconds=0.01, cleanup_environment=True) assert environment.abort_calls == 1 +@pytest.mark.parametrize("interrupt", ["deadline", "caller"]) +async def test_agent_runtime_rechecks_a_transient_abort_io_error_after_finalization(monkeypatch, interrupt): + class TransientAbortEnvironment(Environment): + async def abort(self) -> None: + await super().abort() + if self.abort_calls == 1: + raise OSError("temporary file cleanup failed") + assert self.cleanup_done.is_set() + + session = Session(outcome="block") + _patch_session(monkeypatch, session) + environment = TransientAbortEnvironment() + if interrupt == "deadline": + result = await _run_agent(environment, timeout_seconds=0.01, cleanup_environment=True) + assert result.outcome == "timed_out" + assert result.environment_quiesced is True + assert result.tokens_spent == session.used_tokens + else: + messages = [] + + async def run(): + try: + await _run_agent(environment, cleanup_environment=True) + except asyncio.CancelledError as cancellation: + messages.append(str(cancellation)) + raise + + owner = asyncio.create_task(run()) + await session.started.wait() + owner.cancel("caller interrupted the run") + with pytest.raises(asyncio.CancelledError): + await owner + assert messages == ["caller interrupted the run"] + assert owner.cancelled() + assert environment.abort_calls == 2 + assert environment.cleanup_calls == 1 + assert session.close_calls == 1 + +async def test_agent_runtime_keeps_an_abort_io_error_when_recheck_also_fails(monkeypatch): + class FailingAbortEnvironment(Environment): + async def abort(self) -> None: + await super().abort() + raise OSError("temporary file cleanup failed") + + session = Session(outcome="block") + _patch_session(monkeypatch, session) + environment = FailingAbortEnvironment() + with pytest.raises(AgentRuntimeLifecycleError, match="quiescent"): + await _run_agent(environment, timeout_seconds=0.01, cleanup_environment=True) + assert environment.cleanup_done.is_set() + assert environment.abort_calls == 2 + async def test_agent_runtime_caller_cancellation_leaves_caller_environment_active(monkeypatch) -> None: session = Session(outcome="block") _patch_session(monkeypatch, session) diff --git a/tests/agents/test_session_completed_answer.py b/tests/agents/test_session_completed_answer.py index 0c6b6ac0..738b3f7e 100644 --- a/tests/agents/test_session_completed_answer.py +++ b/tests/agents/test_session_completed_answer.py @@ -17,6 +17,42 @@ from tests.support.session_characterization_test_support import FakeLLMClient, llm_response, tool_call +@pytest.mark.parametrize("text", [None, "Visible subtotal. The next"]) +async def test_truncated_standalone_answer_still_allows_generation_after_restore(tmp_path, text): + (tmp_path / "inventory.txt").write_text("apples: 42\n", encoding="utf-8") + agent = Agent(name="assistant", system_prompt="Count the inventory.", tools=[FileReadTool()]) + planning = "I will read the inventory." + model = FakeLLMClient([ + llm_response(content=planning, tool_calls=[tool_call("read", "file_read", '{"path":"inventory.txt"}')]), + llm_response(content=text, finish_reason="length"), + ]) + env = LocalEnvironment(str(tmp_path)) + source = build_session(agent=agent, llm=model, env=env) + restored = None + try: + await source.add_user_message("What is the subtotal?") + assert await source.run_loop() == (text or planning) + assert source.phase is SessionPhase.STOPPED + path = tmp_path / "stopped.json" + source.save(str(path)) + + resume_model = FakeLLMClient([llm_response(content="The inventory contains 42 apples.")]) + restored = load_session(str(path), agent=agent, llm=resume_model, env=env) + assert restored.phase is SessionPhase.STOPPED + assert await restored.run_loop() == "The inventory contains 42 apples." + assert restored.phase is SessionPhase.DONE + assert len(resume_model.calls) == 1 + history = resume_model.calls[0]["messages"] + assert [message["content"] for message in history if message["role"] == "assistant"] == ( + [planning] + ([text] if text else []) + ) + finally: + if restored is not None: + await restored.aclose() + await source.aclose() + await env.cleanup() + + @pytest.mark.parametrize("expected", ["pear", ""]) async def test_final_step_autosave_restores_the_completed_answer(tmp_path, expected): path = tmp_path / "automatic.json" diff --git a/tests/agents/test_session_snapshot_model_lifetime.py b/tests/agents/test_session_snapshot_model_lifetime.py index 9d0fea57..0384bf16 100644 --- a/tests/agents/test_session_snapshot_model_lifetime.py +++ b/tests/agents/test_session_snapshot_model_lifetime.py @@ -15,6 +15,7 @@ import openai import pytest +from opencollab import RunControl from opencollab.adapters.env import LocalEnvironment from opencollab.adapters.llm.client import LLMClient from opencollab.application.event_bus import EventBus @@ -190,13 +191,14 @@ async def close(self): raise self.error -def _owned_source(tmp_path, monkeypatch, model): +def _owned_source(tmp_path, monkeypatch, model, *, run_control=None): monkeypatch.setattr(container, "LLMClient", lambda **_kwargs: model) workspace = tmp_path / "source" workspace.mkdir() return build_session( agent=Agent(name="worker", system_prompt="Return the marker."), env=_ForkableEnvironment(workspace), + run_control=run_control, ) @@ -234,6 +236,44 @@ async def test_concurrent_snapshot_closes_release_each_owner_once(tmp_path, monk await _cleanup(descendant, branch, source) +@pytest.mark.parametrize("close_fails", [False, True]) +async def test_concurrent_close_reports_the_final_transport_outcome(tmp_path, monkeypatch, close_fails): + closing, release_close, second_started = asyncio.Event(), asyncio.Event(), asyncio.Event() + events = [] + error = OSError("close failed") if close_fails else None + + class HeldCloseModel(_Model): + async def close(self): + closing.set() + await release_close.wait() + await super().close() + + model = HeldCloseModel(error=error) + session = _owned_source(tmp_path, monkeypatch, model, run_control=RunControl(on_event=events.append)) + await _turn(session, "BEFORE_CLOSE") + + async def close_again(): + second_started.set() + await session.aclose() + + first = asyncio.create_task(session.aclose()) + second = None + try: + await asyncio.wait_for(closing.wait(), 2) + second = asyncio.create_task(close_again()) + await asyncio.wait_for(second_started.wait(), 2) + assert not second.done() + assert all(event.type != "cleanup_completed" for event in events) + finally: + release_close.set() + results = await asyncio.gather(first, *(() if second is None else (second,)), return_exceptions=True) + await session.env.cleanup() + + assert model.close_calls == 1 + assert len(results) == 2 and all(result is error for result in results) + assert sum(event.type == "cleanup_completed" for event in events) == (0 if close_fails else 1) + + @pytest.mark.parametrize("failure", ["fork", "context"]) async def test_failed_snapshot_leaves_no_model_owner(tmp_path, monkeypatch, failure): model = _Model() diff --git a/tests/agents/test_session_wind_down.py b/tests/agents/test_session_wind_down.py index f4ba1a60..2a60d605 100644 --- a/tests/agents/test_session_wind_down.py +++ b/tests/agents/test_session_wind_down.py @@ -325,6 +325,33 @@ def test_restored_wind_down_does_not_regrant_an_already_allocated_retry(local_en assert restored_llm.calls == [] assert restored.state.phase is SessionPhase.STOPPED +@pytest.mark.parametrize("attempts", [0, 1]) +async def test_restored_wind_down_offers_only_the_submit_tool(local_environment_factory, tmp_path, attempts): + path = tmp_path / "pending-commit.json" + source = Session(env=local_environment_factory(), agent=_agent_with_submit(), llm=FakeLLM()) + try: + await source.add_user_message("Submit the existing findings.") + source.state.wind_down_done = True + source.state.wind_down_attempts = attempts + source.save(str(path)) + finally: + await source.aclose() + await source.env.cleanup() + + llm = FakeLLM([llm_response(content="Recovered report.")]) + restored = load_session(path, env=local_environment_factory(), agent=_agent_with_submit(), llm=llm) + try: + restored.runner.configure_enforcement(enforcement_strength=ENFORCEMENT_ON, commit_reserve=25_000) + assert await restored.run_loop() == "Recovered report." + request, = llm.calls + assert [tool["function"]["name"] for tool in request["tools"]] == [SUBMIT_TOOL_NAME] + assert request["tool_choice"] == _FORCED_SUBMIT_CHOICE + assert restored.state.wind_down_attempts == attempts + 1 + assert restored.state.phase is SessionPhase.DONE + finally: + await restored.aclose() + await restored.env.cleanup() + def test_legacy_wind_down_snapshot_without_attempts_stops_conservatively(local_environment_factory, tmp_path): session = Session(env=local_environment_factory(), agent=_agent_with_submit(), llm=FakeLLM()) session.state.wind_down_done = True diff --git a/tests/interfaces/test_authored_workflow_artifact_publication.py b/tests/interfaces/test_authored_workflow_artifact_publication.py new file mode 100644 index 00000000..786c3ddd --- /dev/null +++ b/tests/interfaces/test_authored_workflow_artifact_publication.py @@ -0,0 +1,179 @@ +from __future__ import annotations + +import asyncio +import errno +import json +import sys +from pathlib import Path + +import pytest + +from opencollab.adapters.llm.types import LLMResponse, Usage +from opencollab.bootstrap import authored_workflow, container +from opencollab.sdk import OpenCollab + + +def call(name, arguments): + return {"id": f"call-{name}-{arguments.get('action', 'write')}", "type": "function", + "function": {"name": name, "arguments": json.dumps(arguments)}} + + +@pytest.mark.parametrize("scene", [ + "settled", "wait", "result-budget", "parent-cancel", "export-fails", "manifest-missing", + "failed-workflow-manifest-missing", +]) +async def test_authored_terminal_acknowledgement_references_persistent_artifacts(tmp_path, monkeypatch, scene): + workspace = tmp_path / "workspace" + workspace.mkdir() + team = tmp_path / "team.yaml" + team.write_text( + "entry: writer\nroles:\n writer:\n prompt: Writer\n" + " tools: [file_write, bash, manage_workflow]\n" + ) + workflow_fails = scene == "failed-workflow-manifest-missing" + missing_manifest = scene == "manifest-missing" or workflow_fails + terminal = ( + "raise ValueError('Invalid authored report row')" if workflow_fails + else "return {'status': 'ready', 'bytes': len(text)}" + ) + source = ( + "from pathlib import Path\n\n" + "async def main(ctx, args):\n" + " text = 'ready for review\\n'\n" + " Path('report.txt').write_text(text)\n" + f" {terminal}\n" + ) + copying, release, cancelled, parent_admitted = [asyncio.Event() for _ in range(4)] + seen = {} + copy_artifact = authored_workflow._copy_artifact_to_host + + async def copy(environment, source, target): + if source.endswith("/workflow.json"): + copying.set() + await release.wait() + if scene == "export-fails": + raise OSError(errno.EIO, "child manifest transfer failed") + if missing_manifest: + Path(source).unlink() + await copy_artifact(environment, source, target) + + monkeypatch.setattr(authored_workflow, "_copy_artifact_to_host", copy) + + class Parent: + def __init__(self, **kwargs): + pass + + def context_window(self): + return 200_000 + + async def close(self): + pass + + def estimate_request_tokens(self, messages, tools, **kwargs): + replies = sum(message["role"] == "tool" for message in messages) + return 9_500 if scene == "result-budget" and replies == 3 else 100 + + async def complete(self, messages, **kwargs): + replies = [message for message in messages if message["role"] == "tool"] + match len(replies): + case 0: + action = call("file_write", {"path": "authored.py", "mode": "create", "content": source}) + case 1: + action = call("manage_workflow", {"action": "launch", "source": "authored.py", + "python": sys.executable, "budget": 1_000}) + case 2: + launched = json.loads(replies[-1]["content"]) + seen["id"] = launched["id"] + await asyncio.wait_for(copying.wait(), 5) + if scene == "parent-cancel": + try: + await asyncio.Future() + except asyncio.CancelledError: + cancelled.set() + raise + if scene == "settled": + release.set() + wait = {"action": "wait", "id": seen["id"]} + if scene == "result-budget": + wait["action"] = "result" + elif scene != "settled": + wait["timeout"] = 0.01 + action = call("manage_workflow", wait) + case 3: + seen["first"] = json.loads(replies[-1]["content"]) + parent_admitted.set() + release.set() + action = call("manage_workflow", {"action": "wait", "id": seen["id"], "timeout": 5}) + case _: + seen["settled"] = json.loads(replies[-1]["content"]) + return LLMResponse(content="Collected the authored report.", usage=Usage(3, 2)) + return LLMResponse(tool_calls=[action], usage=Usage(3, 2), finish_reason="tool_calls") + + monkeypatch.setattr(container, "LLMClient", Parent) + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", "") + monkeypatch.delenv("OPENCOLLAB_UNBOUNDED_LIMITS", raising=False) + + async def run_team(): + try: + return await OpenCollab(workspace, model="offline-model", config={"budget": 10_000}).team( + "Create and collect a local report.", config=team, artifacts=tmp_path / "artifacts", + trace=False, use_worktrees=False, allow_unisolated_shell=True, timeout=15, + ) + except asyncio.CancelledError as error: + return error + + job = asyncio.create_task(run_team()) + try: + if scene == "parent-cancel": + await asyncio.wait_for(copying.wait(), 5) + job.cancel("stop parent during child export") + await asyncio.wait_for(cancelled.wait(), 5) + assert not job.done() + release.set() + elif scene == "result-budget": + await asyncio.wait_for(parent_admitted.wait(), 5) + result = await job + finally: + release.set() + if not job.done(): + job.cancel() + await asyncio.gather(job, return_exceptions=True) + + transient = workspace / ".opencollab" / "child-runs" / seen["id"] + assert (workspace / "report.txt").read_text() == "ready for review\n" + if scene == "parent-cancel": + assert isinstance(result, asyncio.CancelledError) + assert str(result) == "stop parent during child export" + retained, = (tmp_path / "artifacts").glob("child-*/result.json") + saved = json.loads(retained.read_text()) + assert saved["status"] == "completed" + assert saved["result"]["output"] == {"status": "ready", "bytes": 17} + assert saved["artifacts"] == str(retained.parent) + assert not transient.exists() + return + + first, settled = seen["first"], seen["settled"] + assert first["id"] == settled["id"] + if scene == "export-fails" or missing_manifest: + assert first["status"] == "running" and first["result"] is None + assert settled["status"] == "failed" and settled["result"]["output"] is None + problem = "child manifest transfer failed" if scene == "export-fails" else "workflow.json" + assert problem in settled["result"]["reason"] + if workflow_fails: + assert "ValueError: Invalid authored report row" in settled["result"]["reason"] + assert result.status == "failed" and result.tokens == 25 + assert transient.exists() + return + + assert result.ok, (result.reason, result.error) + assert result.output == "Collected the authored report." + assert result.tokens == 25 + assert settled["status"] == "completed" + assert settled["result"]["output"] == {"status": "ready", "bytes": 17} + assert Path(settled["artifacts"], "workflow.json").is_file() + assert json.loads(Path(settled["artifacts"], "result.json").read_text()) == settled + assert not transient.exists() + if scene in {"wait", "result-budget"}: + assert first["status"] == "running" and first["result"] is None + else: + assert first == settled diff --git a/tests/interfaces/test_authored_workflow_execution.py b/tests/interfaces/test_authored_workflow_execution.py index d4b1faf9..260b103c 100644 --- a/tests/interfaces/test_authored_workflow_execution.py +++ b/tests/interfaces/test_authored_workflow_execution.py @@ -72,6 +72,66 @@ async def test_authored_result_and_native_artifacts_cross_file_read_limit(tmp_pa await environment.cleanup() +@pytest.mark.parametrize(("kind", "error"), [ + ("normal", None), + ("nonfinite", "Out of range float values"), + ("circular", "Circular reference detected"), + ("invalid_unicode", "surrogates not allowed"), +]) +async def test_authored_result_and_manifest_agree_on_output_format(tmp_path, kind, error): + (tmp_path / "authored.py").write_text(''' +from pathlib import Path + +async def main(ctx, args): + kind = args["kind"] + Path("measurement.txt").write_text(kind) + if kind == "nonfinite": + return {"mean": float("nan")} + if kind == "circular": + output = [] + output.append(output) + return output + if kind == "invalid_unicode": + return {"label": chr(0xD800)} + return {"mean": 21.0, "unit": "µg"} +''', encoding="utf-8") + environment = LocalEnvironment(str(tmp_path)) + parent, tool, runtime = _manager(environment) + saved = tmp_path / "saved" + saved.mkdir() + tool._save_dir = str(saved) + try: + child = await _launch(tool, runtime, args={"kind": kind}) + collected = await tool.execute_with_runtime({"action": "wait", "id": child["id"]}, runtime) + result = json.loads(collected) + assert (tmp_path / "measurement.txt").read_text() == kind + native = Path(child["artifacts"]) + persisted = Path(result["artifacts"]) + assert json.loads((persisted / "process.json").read_text())["returncode"] == 0 + assert json.loads((persisted / "result.json").read_text(encoding="utf-8")) == result + assert json.loads((native / "result.json").read_text(encoding="utf-8")) == result["result"] + manifest = json.loads((persisted / "workflow.json").read_text()) + assert json.loads((native / "workflow.json").read_text()) == manifest + assert manifest["args"] == {"kind": kind} + assert manifest["tokens_spent"] == result["tokens"] == 0 + assert manifest["evidence_complete"] is True + if error is None: + assert manifest["status"] == result["status"] == result["result"]["status"] == "completed" + assert manifest["reason"] is None + assert result["result"]["output"] == {"mean": 21.0, "unit": "µg"} + else: + assert result["status"] == result["result"]["status"] == "failed" + assert result["result"]["output"] is None + assert "workflow output is not JSON serializable" in result["result"]["reason"] + assert error in result["result"]["reason"] + assert (manifest["status"], manifest["reason"]) == ("failed", "output_format_failed") + finally: + try: + await parent.aclose() + finally: + await environment.cleanup() + + @pytest.mark.parametrize("failure", ["signature", "async-start"]) async def test_executor_start_failure_finishes_child_and_releases_budget(tmp_path, monkeypatch, failure): (tmp_path / "authored.py").write_text("async def main(ctx, args):\n return 1\n") diff --git a/tests/interfaces/test_cli_main_lifecycle.py b/tests/interfaces/test_cli_main_lifecycle.py index 5c37b636..4f8388e7 100644 --- a/tests/interfaces/test_cli_main_lifecycle.py +++ b/tests/interfaces/test_cli_main_lifecycle.py @@ -299,6 +299,7 @@ async def test_cli_run_passes_team_config_path_to_scheduler(monkeypatch, tmp_pat tracer = FakeTracer() install_cli_fakes(monkeypatch, object(), tracer) team_config = tmp_path / "custom-team.yaml" + team_config.write_text("roles:\n custom:\n prompt: Do work.\n", encoding="utf-8") def capture_build_scheduler(*args, **kwargs): captured.update(kwargs) @@ -320,6 +321,7 @@ def capture_build_scheduler(*args, **kwargs): ) assert captured["team_config_path"] == str(team_config) + assert captured["resolved_team_config"].entry == "custom" assert captured["allow_unisolated_child_shell"] is allow_child_shell assert captured["run_id"] == tracer.run_id assert tracer.closed is True diff --git a/tests/interfaces/test_cli_resume_interrupted_turn.py b/tests/interfaces/test_cli_resume_interrupted_turn.py new file mode 100644 index 00000000..2d21e830 --- /dev/null +++ b/tests/interfaces/test_cli_resume_interrupted_turn.py @@ -0,0 +1,127 @@ +import asyncio +import json + +from typer.testing import CliRunner + +from opencollab import OpenCollab +from opencollab.adapters.cli.main import app as cli +from opencollab.adapters.tools.fs import FileReadTool +from opencollab.bootstrap import build_session +from opencollab.domain.agent import Agent +from opencollab.environments import local_environment +from opencollab.tools import builtin_tools +from tests.support.provider_sdk_http import completion_http_response, install_sdk_transport +from tests.support.session_run_test_support import llm_response, tool_call + + +def test_cli_finishes_interrupted_tool_turn_before_accepting_follow_up(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(tmp_path / "usage.jsonl")) + monkeypatch.setenv("OPENCOLLAB_WIRE_PROTOCOL", "chat_completions") + monkeypatch.setenv("OPENCOLLAB_LLM_STREAM_CHAT", "false") + monkeypatch.setenv("OPENCOLLAB_LLM_MAX_RETRIES", "0") + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + system = "Review the project." + interrupted_prompt = "Read note.txt and report the inventory count." + follow_up = "What is the project title?" + recovered_answer = "The inventory count is 17." + follow_up_answer = "The project title is Orchard." + (tmp_path / "note.txt").write_text("inventory count 17\n") + team = tmp_path / "team.yaml" + team.write_text(f"entry: lead\nroles:\n lead:\n prompt: {system}\n tools: [file_read]\n") + + reads = [] + execute_read = FileReadTool.execute_with_runtime + + async def count_read(tool, params, runtime): + reads.append(params["path"]) + return await execute_read(tool, params, runtime) + + monkeypatch.setattr(FileReadTool, "execute_with_runtime", count_read) + source = tmp_path / "source.json" + interrupted = tmp_path / "interrupted.json" + journal = interrupted.with_suffix(".json.journal") + + async def record_interrupted_turn(): + next_request = asyncio.Event() + responses = iter([ + llm_response(content="Project title saved.", total_tokens=7), + llm_response( + tool_calls=[tool_call("read-note", "file_read", '{"path":"note.txt"}')], + finish_reason="tool_calls", total_tokens=11, + ), + ]) + + class OriginalModel: + async def complete(self, messages, **kwargs): + response = next(responses, None) + if response is not None: + return response + next_request.set() + await asyncio.Future() + + env = local_environment(tmp_path) + session = build_session( + agent=Agent(name="lead", system_prompt=system, model="original-model", tools=builtin_tools("file_read")), + env=env, llm=OriginalModel(), auto_save_path=str(source), + ) + turn = None + try: + await session.add_user_message("Record Orchard as the project title.") + assert await session.run_loop() == "Project title saved." + await session.add_user_message(interrupted_prompt) + await asyncio.wait_for(asyncio.gather(*session.event_bus.pending_tasks), timeout=5) + turn = asyncio.create_task(session.run_loop()) + await asyncio.wait_for(next_request.wait(), timeout=5) + await asyncio.wait_for(asyncio.gather(*session.event_bus.pending_tasks), timeout=5) + interrupted.write_bytes(source.read_bytes()) + journal.write_bytes(source.with_suffix(".json.journal").read_bytes()) + finally: + if turn is not None: + turn.cancel() + await asyncio.gather(turn, return_exceptions=True) + await session.aclose() + await env.cleanup() + + asyncio.run(record_interrupted_turn()) + snapshot = OpenCollab.read_session_snapshot(interrupted) + assert snapshot["session_state"]["phase"] in {"autosaving", "precheck", "calling_llm"} + assert snapshot["session_state"]["pending_external_user_turn"] is None + assert snapshot["session_state"]["active_turn_start_message_index"] == 4 + assert snapshot["messages"][-1]["tool_call_id"] == "read-note" + saved_bytes = interrupted.read_bytes(), journal.read_bytes() + requests = [] + + def respond(request): + body = json.loads(request.content) + requests.append(body) + answer = recovered_answer if body["messages"][-1]["role"] == "tool" else follow_up_answer + return completion_http_response(request, text=answer, output_tokens=5) + + install_sdk_transport(monkeypatch, "openai", respond) + result = CliRunner().invoke(cli, [ + "--workspace", str(tmp_path), "--team-config", str(team), "--no-worktrees", + "--provider", "openai", "--model", "reopen-model", "--base-url", "https://fixture.invalid/v1", + "--api-key", tmp_path.name, "--session", str(interrupted), "--prompt", follow_up, + ]) + assert result.exit_code == 0, (result.output, result.exception) + assert [request["model"] for request in requests] == ["reopen-model", "reopen-model"] + first, second = [request["messages"] for request in requests] + assert first[-1]["tool_call_id"] == "read-note" + assert "inventory count 17" in first[-1]["content"] + assert first[-3] == {"role": "user", "content": interrupted_prompt} + assert second == [ + *first, {"role": "assistant", "content": recovered_answer}, {"role": "user", "content": follow_up}, + ] + assert recovered_answer in result.output and follow_up_answer in result.output + assert reads == ["note.txt"] + assert (interrupted.read_bytes(), journal.read_bytes()) == saved_bytes + + persisted, = (tmp_path / ".opencollab" / "sessions").glob("*/agent_0_*.json") + finished = OpenCollab.read_session_snapshot(persisted) + assert finished["session_state"]["used_tokens"] == 32 + assert finished["session_state"]["active_turn_start_message_index"] is None + assert [message["content"] for message in finished["messages"][-3:]] == [ + recovered_answer, follow_up, follow_up_answer, + ] diff --git a/tests/interfaces/test_cli_resume_legacy_jsonl.py b/tests/interfaces/test_cli_resume_legacy_jsonl.py new file mode 100644 index 00000000..7a9de8ed --- /dev/null +++ b/tests/interfaces/test_cli_resume_legacy_jsonl.py @@ -0,0 +1,119 @@ +"""Exercise documented CLI and snapshot API support for one-row legacy JSONL.""" + +from __future__ import annotations + +import json + +import pytest +from typer.testing import CliRunner + +from opencollab import OpenCollab +from opencollab.adapters.cli.main import app as cli +from tests.support.provider_sdk_http import completion_http_response, install_sdk_transport + +SOURCE = "The previously verified shipment identifier is 731." +PROMPT = "State the previously verified shipment identifier." +ANSWER = "The shipment identifier is 731." + + +@pytest.mark.parametrize("scene", [ + "single-user", "single-assistant", "single-no-newline", "two-record", "legacy-array", "native", + "legacy-empty-awaiting", "invalid-native", "invalid-unversioned", "invalid-native-messages", "invalid-legacy", +]) +def test_cli_restores_legacy_jsonl_with_any_valid_record_count(tmp_path, monkeypatch, scene): + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(tmp_path / "usage.jsonl")) + monkeypatch.setenv("OPENCOLLAB_WIRE_PROTOCOL", "chat_completions") + monkeypatch.setenv("OPENCOLLAB_LLM_STREAM_CHAT", "false") + monkeypatch.setenv("OPENCOLLAB_LLM_MAX_RETRIES", "0") + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + workspace = tmp_path / "workspace" + workspace.mkdir() + team = tmp_path / "team.yaml" + team.write_text("entry: lead\nroles:\n lead:\n prompt: Report the recorded shipment.\n tools: []\n") + source_role = "assistant" if scene == "single-assistant" else "user" + row = {"role": source_role, "content": SOURCE} + legacy = scene.startswith("single-") or scene in {"two-record", "invalid-legacy"} + restored_path = tmp_path / ("saved.jsonl" if legacy else "saved.json") + if scene == "two-record": + serialized = json.dumps({"role": "system", "content": "Keep the shipment record."}) + "\n" + json.dumps(row) + elif scene == "invalid-legacy": + serialized = json.dumps({**row, "content": 17}) + elif legacy: + serialized = json.dumps(row) + elif scene == "legacy-array": + serialized = json.dumps([row]) + elif scene == "native": + serialized = json.dumps({"snapshot_version": 1, "messages": [row]}) + elif scene == "legacy-empty-awaiting": + serialized = json.dumps({ + "snapshot_version": 1, "messages": [row], "session_state": {"phase": "awaiting_events"}, + }) + elif scene == "invalid-unversioned": + serialized = json.dumps({"session_state": {"used_tokens": 0}, **row}) + elif scene == "invalid-native-messages": + serialized = json.dumps({"snapshot_version": 1, "messages": SOURCE, **row}) + else: + serialized = json.dumps({"snapshot_version": 1, **row}) + restored_path.write_text(serialized if scene == "single-no-newline" else serialized + "\n", encoding="utf-8") + source_bytes = restored_path.read_bytes() + before, read_error = None, None + try: + before = OpenCollab.read_session_snapshot(restored_path) + except ValueError as error: + read_error = str(error) + + calls = [] + + def handler(request): + assert request.url.path.endswith("/chat/completions") + messages = json.loads(request.content)["messages"] + calls.append(messages) + match = [m for m in messages if m.get("role") == source_role and m.get("content") == SOURCE] + if len(match) == 1 and messages[-1] == {"role": "user", "content": PROMPT}: + return completion_http_response(request, text=ANSWER, output_tokens=5) + return completion_http_response(request, text="No shipment record was loaded.", output_tokens=5) + + install_sdk_transport(monkeypatch, "openai", handler) + result = CliRunner().invoke(cli, [ + "--workspace", str(workspace), "--team-config", str(team), "--no-worktrees", + "--provider", "openai", "--model", "gpt-4o", "--base-url", "https://fixture.invalid/v1", + "--api-key", tmp_path.name, "--session", str(restored_path), "--prompt", PROMPT, + ]) + output_seen = ANSWER in result.output + native_calls = len(calls) + assert restored_path.read_bytes() == source_bytes + if scene.startswith("invalid-"): + expected = { + "invalid-native": "missing required 'messages'", + "invalid-unversioned": "missing required 'messages'", + "invalid-native-messages": "'messages' must be a list", + "invalid-legacy": "'content' must be text", + }[scene] + assert result.exit_code == 1 and native_calls == 0 + assert expected in read_error and expected in str(result.exception) + return + + assert result.exit_code == 0, (result.output, result.exception) + assert read_error is None and row in before["messages"] + assert native_calls == 1 and output_seen + assert [m.get("content") for m in calls[0]].count(SOURCE) == 1 + assert calls[0][-1] == {"role": "user", "content": PROMPT} + transcript, = list((workspace / ".opencollab" / "sessions").glob("*/agent_0_*.json")) + snapshot = OpenCollab.read_session_snapshot(transcript) + assert snapshot["messages"][-1]["content"] == ANSWER + assert snapshot["session_state"]["used_tokens"] == 7 + + +@pytest.mark.parametrize("row", [ + {"role": "user", "content": [{"type": "text", "text": SOURCE}], "timestamp": "2026-11-26T15:00:00Z"}, + {"role": "assistant", "tool_calls": [{ + "id": "call-1", "type": "function", "function": {"name": "read_report", "arguments": "{}"}, + }]}, +]) +def test_reader_preserves_legitimate_single_message_fields(tmp_path, row): + path = tmp_path / "record.jsonl" + path.write_text(json.dumps(row) + "\n", encoding="utf-8") + + assert OpenCollab.read_session_snapshot(path)["messages"] == [row] diff --git a/tests/interfaces/test_cli_resume_visible_answer.py b/tests/interfaces/test_cli_resume_visible_answer.py new file mode 100644 index 00000000..f67b0ad2 --- /dev/null +++ b/tests/interfaces/test_cli_resume_visible_answer.py @@ -0,0 +1,122 @@ +import asyncio +import json + +from typer.testing import CliRunner + +from opencollab import OpenCollab +from opencollab.adapters.cli.main import app as cli +from opencollab.adapters.tools.fs import FileReadTool +from opencollab.bootstrap import build_session, load_session +from opencollab.domain.agent import Agent +from opencollab.environments import local_environment +from tests.support.provider_sdk_http import completion_http_response, install_sdk_transport +from tests.support.session_run_test_support import FakeLLM, llm_response, tool_call + + +def test_cli_reopen_recovers_started_turn_and_preserves_visible_final_answer(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + for key, value in { + "OPENCOLLAB_API_USAGE_LOG": str(tmp_path / "usage.jsonl"), + "OPENCOLLAB_WIRE_PROTOCOL": "chat_completions", + "OPENCOLLAB_LLM_STREAM_CHAT": "false", + "OPENCOLLAB_LLM_MAX_RETRIES": "0", + "OPENCOLLAB_BUDGET_NUDGE_MODE": "off", + "OPENCOLLAB_WRITE_NUDGE_MODE": "off", + }.items(): + monkeypatch.setenv(key, value) + + system = "Report inventory readings." + old_request = "Read note.txt and report the count." + new_request = "What is the report title?" + tool_text = "I will read the note." + old_answer = "The inventory count is 42." + resumed_answer = "I picked up the saved inventory request." + new_answer = "The report is called Orchard." + (tmp_path / "note.txt").write_text("inventory count 42\n", encoding="utf-8") + team = tmp_path / "team.yaml" + team.write_text(f"entry: lead\nroles:\n lead:\n prompt: {system}\n tools: [file_read]\n", encoding="utf-8") + before_first_call = tmp_path / "step-start.json" + restored_copy = tmp_path / "reopened-step-start.json" + before_tool = tmp_path / "before-tool.json" + visible_final = tmp_path / "visible-final.json" + agent = Agent(name="lead", system_prompt=system, tools=[FileReadTool()]) + + async def export_from_observer(): + model = FakeLLM([ + llm_response(content=tool_text, tool_calls=[tool_call("read", "file_read", '{"path":"note.txt"}')]), + llm_response(content=old_answer, total_tokens=11), + ]) + environment = local_environment(tmp_path) + session = build_session(agent=agent, llm=model, env=environment) + + def observe(event): + if event.type == "step_start" and event.data["step"] == 1: + session.save(str(before_first_call)) + elif event.type == "text_delta": + session.save(str(before_tool if event.data["content"] == tool_text else visible_final)) + + session.event_bus.subscribe(observe) + try: + await session.add_user_message(old_request) + assert await session.run_loop() == old_answer + reopened = load_session( + str(before_first_call), agent, llm=FakeLLM(), env=environment, auto_save_path=str(restored_copy), + ) + await reopened.aclose() + finally: + await session.aclose() + await environment.cleanup() + + asyncio.run(export_from_observer()) + started = OpenCollab.read_session_snapshot(before_first_call) + assert started["session_state"]["phase"] == "calling_llm" + assert started["session_state"]["step_count"] == 1 + assert started["session_state"]["pending_external_user_turn"] is None + assert started["session_state"]["active_turn_start_message_index"] == len(started["messages"]) == 2 + assert started["messages"][-1]["role"] == "user" + final = OpenCollab.read_session_snapshot(visible_final) + assert final["session_state"]["phase"] == "handling_response" + assert final["session_state"]["active_turn_start_message_index"] == 2 + assert [row["tool_call_id"] for row in final["messages"] if row["role"] == "tool"] == ["read"] + assert final["messages"][-1]["content"] == old_answer + + for path, expected_requests, assistant_history, expected_tokens in ( + (before_first_call, [old_request, new_request], [resumed_answer, new_answer], 14), + (restored_copy, [old_request, new_request], [resumed_answer, new_answer], 14), + (visible_final, [new_request], [tool_text, old_answer, new_answer], 23), + (before_tool, [old_request, new_request], [tool_text, resumed_answer, new_answer], 19), + ): + calls = [] + + def respond(request): + messages = json.loads(request.content)["messages"] + latest = next(row["content"] for row in reversed(messages) if row["role"] == "user") + calls.append((latest, messages)) + answer = new_answer if latest == new_request else resumed_answer + return completion_http_response(request, text=answer, output_tokens=5) + + saved_bytes = path.read_bytes() + sessions = tmp_path / ".opencollab" / "sessions" + before = set(sessions.glob("*/agent_0_*.json")) + with monkeypatch.context() as provider: + install_sdk_transport(provider, "openai", respond) + result = CliRunner().invoke(cli, [ + "--workspace", str(tmp_path), "--team-config", str(team), "--no-worktrees", + "--provider", "openai", "--model", "reopen-model", "--base-url", "https://fixture.invalid/v1", + "--api-key", tmp_path.name, "--session", str(path), "--prompt", new_request, + ]) + assert result.exit_code == 0, (result.output, result.exception) + assert [prompt for prompt, _ in calls] == expected_requests + if path in (before_first_call, restored_copy): + assert [row["content"] for row in calls[0][1] if row["role"] == "user"] == [old_request] + if path == before_tool: + tool_results = [row for row in calls[0][1] if row["role"] == "tool"] + assert len(tool_results) == 1 + assert tool_results[0]["tool_call_id"] == "read" + assert "interrupted by session restore" in tool_results[0]["content"] + persisted, = set(sessions.glob("*/agent_0_*.json")) - before + snapshot = OpenCollab.read_session_snapshot(persisted) + assert [row["content"] for row in snapshot["messages"] if row["role"] == "assistant"] == assistant_history + assert snapshot["session_state"]["used_tokens"] == expected_tokens + assert new_answer in result.output + assert path.read_bytes() == saved_bytes diff --git a/tests/interfaces/test_cli_submit_answer.py b/tests/interfaces/test_cli_submit_answer.py index aa927023..e2f2086c 100644 --- a/tests/interfaces/test_cli_submit_answer.py +++ b/tests/interfaces/test_cli_submit_answer.py @@ -17,8 +17,12 @@ ANSWER = "The verified total is 1499." PREFACE = "I have checked the supplied totals." -@pytest.mark.parametrize("mode", ["submit", "same_text", "same_text_whitespace", "preface", "plain"]) -def test_explicit_submit_team_prints_its_answer_once(tmp_path, mode): +@pytest.mark.parametrize( + ("mode", "role_model"), + [("submit", None), ("same_text", None), ("same_text_whitespace", None), + ("preface", None), ("plain", None), ("plain", "local-lead")], +) +def test_explicit_submit_team_prints_its_answer_once(tmp_path, mode, role_model): requests = [] class Handler(BaseHTTPRequestHandler): @@ -51,15 +55,16 @@ def log_message(self, *args): pass team = tmp_path / "team.yaml" + model_line = f" model: {role_model}\n" if role_model else "" team.write_text( "entry: lead\nroles:\n lead:\n prompt: Return the verified total.\n" - " tools: [submit]\ntopology:\n lead: []\n", + f" tools: [submit]\n{model_line}topology:\n lead: []\n", encoding="utf-8", ) env = {key: value for key, value in os.environ.items() if not key.startswith(("OPENCOLLAB_", "OPENAI_", "ANTHROPIC_", "DASHSCOPE_"))} env.update(PYTHONPATH=str(REPO_ROOT), PYTHONDONTWRITEBYTECODE="1", NO_PROXY="127.0.0.1,localhost", - OPENCOLLAB_API_USAGE_LOG=str(tmp_path / "usage.jsonl")) + OPENCOLLAB_API_USAGE_LOG=str(tmp_path / "usage.jsonl"), COLUMNS="160") server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) thread = threading.Thread(target=server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True) thread.start() @@ -69,7 +74,7 @@ def log_message(self, *args): "--team-config", str(team), "--no-worktrees", "--provider", "openai", "--model", "local-submit", "--api-key", "local-test", "--base-url", f"http://127.0.0.1:{server.server_port}/v1", "--budget", "100000", - "--prompt", "Return the verified total."], + "--prompt", "Return the verified total.", "--trace"], cwd=tmp_path, env=env, capture_output=True, text=True, timeout=30, ) finally: @@ -79,6 +84,12 @@ def log_message(self, *args): assert result.returncode == 0, result.stdout + result.stderr assert len(requests) == 1 + expected_model = role_model or "local-submit" + assert requests[0]["model"] == expected_model + assert f"openai:{expected_model}" in result.stdout + trajectory, = (tmp_path / "trajectories").glob("*.jsonl") + events = [json.loads(line) for line in trajectory.read_text(encoding="utf-8").splitlines()] + assert [event["payload"]["model"] for event in events if event["type"] == "llm_call"] == [expected_model] assert [tool["function"]["name"] for tool in requests[0]["tools"]] == ["submit"] snapshots = list((tmp_path / ".opencollab" / "sessions").rglob("agent_0_*.json")) assert len(snapshots) == 1 diff --git a/tests/interfaces/test_cli_vm_shutdown.py b/tests/interfaces/test_cli_vm_shutdown.py index f0abfea3..9fd73d5a 100644 --- a/tests/interfaces/test_cli_vm_shutdown.py +++ b/tests/interfaces/test_cli_vm_shutdown.py @@ -69,11 +69,7 @@ def test_cli_sigint_finishes_cleanup_with_the_selected_grace(tmp_path, entry, pr "3" if profile else "0.2"], env=environment, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, ) try: - deadline = time.monotonic() + 15 - while not (tmp_path / "entered").exists(): - if process.poll() is not None or time.monotonic() > deadline: - pytest.fail("CLI failed to enter the run") - time.sleep(0.02) + _wait_for_entry(process, tmp_path / "entered") process.send_signal(signal.SIGINT) stdout, stderr = process.communicate(timeout=15) assert process.returncode == 0, (stdout, stderr) @@ -84,3 +80,53 @@ def test_cli_sigint_finishes_cleanup_with_the_selected_grace(tmp_path, entry, pr if process.poll() is None: process.kill() process.communicate() + + +def _wait_for_entry(process, marker): + deadline = time.monotonic() + 15 + while not marker.exists(): + if process.poll() is not None or time.monotonic() > deadline: + pytest.fail("CLI failed to enter the run") + time.sleep(0.02) + + +def test_workflow_sigint_settles_async_cleanup(tmp_path): + workflows = tmp_path / "workflows" + workflows.mkdir() + (workflows / "settle.py").write_text( + "import asyncio\n" + "from pathlib import Path\n" + "from opencollab import workflow\n" + "@workflow\n" + "async def settle(ctx, args):\n" + " try:\n" + " asyncio.get_running_loop().call_soon(Path('entered').touch)\n" + " await asyncio.Event().wait()\n" + " finally:\n" + " await asyncio.sleep(0.1)\n" + " Path('settled').write_text('cleanup complete')\n", + encoding="utf-8", + ) + environment = {key: value for key, value in os.environ.items() if not key.startswith("OPENCOLLAB_")} + environment.update(PYTHONPATH=str(REPO_ROOT), PYTHONDONTWRITEBYTECODE="1") + process = subprocess.Popen( + [sys.executable, "-m", "opencollab", "workflow", "run", "settle", "--provider", "openai", + "--api-key", "offline-cli-test"], # pragma: allowlist secret + cwd=tmp_path, env=environment, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + ) + try: + _wait_for_entry(process, tmp_path / "entered") + process.send_signal(signal.SIGINT) + stdout, stderr = process.communicate(timeout=15) + finally: + if process.poll() is None: + process.kill() + process.communicate() + + assert process.returncode == 130, (stdout, stderr) + assert (tmp_path / "settled").read_text(encoding="utf-8") == "cleanup complete" + path, = (tmp_path / ".opencollab" / "sessions").glob("*/workflow.json") + manifest = json.loads(path.read_text(encoding="utf-8")) + assert manifest["status"] == "stopped" + assert manifest["reason"] == "cancelled" + assert manifest["evidence_complete"] is True diff --git a/tests/interfaces/test_sdk_agent_deadline_output.py b/tests/interfaces/test_sdk_agent_deadline_output.py new file mode 100644 index 00000000..2084a1ff --- /dev/null +++ b/tests/interfaces/test_sdk_agent_deadline_output.py @@ -0,0 +1,119 @@ +from __future__ import annotations + +import asyncio +import json +import threading + +import pytest + +from opencollab import OpenCollab +from opencollab.adapters.llm.client import LLMClient +from opencollab.application.session import Session +from tests.support.provider_sdk_http import completion_http_response, http_response, install_sdk_transport + + +@pytest.mark.parametrize("entry", ["agent", "workflow-agent"]) +@pytest.mark.parametrize("scene", [ + "completed", "checkpoint", "truncated_checkpoint", "reasoning_checkpoint", "unfinished", "late", +]) +async def test_agent_retains_only_accepted_output_when_the_checkpoint_crosses_deadline( + tmp_path, monkeypatch, entry, scene, +): + answer = "Verified intake recorded as 42." + reasoning = "I should check the remaining intake rows." + truncated = scene in {"truncated_checkpoint", "reasoning_checkpoint"} + held_checkpoint = scene == "checkpoint" or truncated + checkpoint, released = threading.Event(), threading.Event() + original_save = Session.save + calls = [] + + def hold_checkpoint(session, path): + phase = "stopped" if truncated else "done" + if held_checkpoint and not checkpoint.is_set() and session.phase.value == phase: + [recorded] = [row["content"] for row in session.messages if row["role"] == "assistant"] + assert recorded == (reasoning if scene == "reasoning_checkpoint" else answer) + checkpoint.set() + assert released.wait(6) + return original_save(session, path) + + async def respond(request): + calls.append(json.loads(request.content)["model"]) + if scene in {"unfinished", "late"}: + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + if scene == "unfinished": + raise + return completion_http_response(request, output_tokens=5, text="Late response.") + response = completion_http_response(request, output_tokens=5, text=answer) + if not truncated: + return response + body = response.json() + body["choices"][0]["finish_reason"] = "length" + if scene == "reasoning_checkpoint": + body["choices"][0]["message"].update(content=None, reasoning_content=reasoning) + return http_response(request, 200, json=body) + + async def release_after_deadline(): + assert await asyncio.to_thread(checkpoint.wait, 5) + await asyncio.sleep(1.1) + released.set() + + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(tmp_path / "usage.jsonl")) + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + monkeypatch.setattr(Session, "save", hold_checkpoint) + install_sdk_transport(monkeypatch, "openai", respond) + timeout = 4 if scene == "completed" else 1 + artifacts = tmp_path / "artifacts" + app = OpenCollab(tmp_path, model="gpt-4o", config={"max_output_tokens": 128}) + + async def workflow(ctx, _): + stage = await ctx.agent_run("Record the intake.", tools=[], timeout=timeout, cleanup_timeout=3) + assert stage.cleanup_complete and stage.workspace_ready + return {"output": stage.output, "status": stage.status, "reason": stage.reason, "tokens": stage.tokens} + + release_task = asyncio.create_task(release_after_deadline()) if held_checkpoint else None + try: + async with LLMClient( + model="gpt-4o", api_key=tmp_path.name, base_url="https://offline.invalid/v1", + max_retries=0, stream_chat=False, + ) as model: + if entry == "agent": + result = await app.agent( + "Record the intake.", llm=model, tools=[], budget=20_000, + artifacts=artifacts, trace=False, timeout=timeout, cleanup_timeout=3, + ) + assert result.metrics["execution_quiesced"] is True + public = {"output": result.output, "status": result.status, "reason": result.reason, + "tokens": result.tokens} + else: + result = await app.workflow( + workflow, llm=model, budget=20_000, concurrency=1, limit_mode="explicit", + artifacts=artifacts, trace=False, timeout=14, + ) + assert result.ok + public = result.output + if release_task is not None: + await release_task + finally: + released.set() + if release_task is not None and not release_task.done(): + release_task.cancel() + await asyncio.gather(release_task, return_exceptions=True) + + saved, = (path for path in artifacts.glob("*.json") if path.name != "workflow.json") + snapshot = app.read_session_snapshot(saved) + recorded = [row["content"] for row in snapshot["messages"] if row["role"] == "assistant"] + accepted = scene in {"completed", "checkpoint", "truncated_checkpoint"} + assert calls == ["gpt-4o"] + assert result.tokens == public["tokens"] == snapshot["session_state"]["used_tokens"] + assert public["tokens"] == (0 if scene == "unfinished" else 7) + expected_transcript = [answer] if accepted else [] + if scene == "reasoning_checkpoint": + expected_transcript = [reasoning] + assert recorded == expected_transcript + assert public["output"] == (answer if accepted else None) + assert (public["status"], public["reason"]) == ( + ("completed", None) if scene == "completed" else ("stopped", "timeout") + ) diff --git a/tests/interfaces/test_sdk_agent_startup_autosave.py b/tests/interfaces/test_sdk_agent_startup_autosave.py new file mode 100644 index 00000000..d9a244f2 --- /dev/null +++ b/tests/interfaces/test_sdk_agent_startup_autosave.py @@ -0,0 +1,126 @@ +from __future__ import annotations + +import asyncio +import fcntl +import threading + +import pytest + +from opencollab import OpenCollab, RunError +from opencollab.adapters.env import LocalEnvironment +from opencollab.adapters.llm.types import LLMResponse, Usage +from opencollab.adapters.storage import SessionStore +from opencollab.bootstrap import container, programmatic + + +@pytest.mark.parametrize("stop", ["none", "deadline", "caller", "late"]) +async def test_agent_startup_waits_for_the_autosave_journal_off_the_event_loop(tmp_path, monkeypatch, stop): + artifacts = tmp_path / "artifacts" + transcript = artifacts / "agent.json" + locked = asyncio.Event() + release_requested, released = threading.Event(), threading.Event() + lock_threads = [] + requests = [] + model_closed = asyncio.Event() + cancellations = [] + + class ContendedLocalEnvironment(LocalEnvironment): + def __init__(self, workspace): + super().__init__(workspace) + reader = (artifacts / "agent.json.journal.lock").open("a+") + fcntl.flock(reader, fcntl.LOCK_EX) + + def finish_read(): + release_requested.wait(3) + reader.close() + released.set() + + thread = threading.Thread(target=finish_read) + lock_threads.append(thread) + thread.start() + locked.set() + + class InventoryModel: + def __init__(self, **kwargs): + pass + + async def close(self): + model_closed.set() + + def context_window(self): + return 100_000 + + async def complete(self, messages, **kwargs): + requests.append(messages) + return LLMResponse(content="Inventory verified.", usage=Usage(3, 2), finish_reason="stop") + + monkeypatch.setattr(programmatic, "LocalEnvironment", ContendedLocalEnvironment) + monkeypatch.setattr(container, "LLMClient", InventoryModel) + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(tmp_path / "usage.jsonl")) + app = OpenCollab(tmp_path, model="gpt-4o") + async def run(): + try: + return await app.agent( + "Check the inventory.", llm=None if stop == "late" else InventoryModel(), tools=[], + artifacts=artifacts, trace=False, timeout=.15 if stop in {"deadline", "late"} else 5, + cleanup_timeout=.05 if stop == "late" else 1, + ) + except asyncio.CancelledError as exc: + cancellations.append(exc.args) + raise + + operation = asyncio.create_task(run()) + try: + await asyncio.wait_for(locked.wait(), 2) + await asyncio.sleep(.03) + assert not released.is_set() + assert not requests + if stop == "caller": + operation.cancel("stop before the first request") + if stop == "late": + with pytest.raises(RunError, match="timed-out agent did not reach a quiescent terminal state"): + await asyncio.wait_for(asyncio.shield(operation), 2) + assert not released.is_set() + assert not requests + assert SessionStore().try_autosave_lock(str(transcript)) is None + release_requested.set() + + async def reacquire(): + while True: + unlock = SessionStore().try_autosave_lock(str(transcript)) + if unlock is not None: + unlock() + return + await asyncio.sleep(.01) + + await asyncio.wait_for(reacquire(), 1) + await asyncio.wait_for(model_closed.wait(), 1) + return + if stop == "deadline": + await asyncio.sleep(.20) + release_requested.set() + if stop == "caller": + with pytest.raises(asyncio.CancelledError): + await operation + assert cancellations == [("stop before the first request",)] + else: + result = await operation + if stop == "none": + assert (result.status, result.output, result.tokens) == ("completed", "Inventory verified.", 5) + assert len(requests) == 1 + else: + assert (result.status, result.reason, result.output, result.tokens) == ("stopped", "timeout", None, 0) + snapshot = app.read_session_snapshot(transcript) + if stop == "none": + assert snapshot["messages"][-1]["content"] == "Inventory verified." + else: + assert not requests + assert all(row["role"] == "system" for row in snapshot["messages"]) + unlock = SessionStore().try_autosave_lock(str(transcript)) + assert unlock is not None + unlock() + finally: + release_requested.set() + await asyncio.gather(operation, return_exceptions=True) + for thread in lock_threads: + thread.join() diff --git a/tests/interfaces/test_sdk_authored_workflow_imports.py b/tests/interfaces/test_sdk_authored_workflow_imports.py new file mode 100644 index 00000000..db9d0d3f --- /dev/null +++ b/tests/interfaces/test_sdk_authored_workflow_imports.py @@ -0,0 +1,180 @@ +from __future__ import annotations + +import json +import os +import py_compile +import sys +from pathlib import Path + +import pytest + +from opencollab import OpenCollab +from tests.support.paths import REPO_ROOT +from tests.support.provider_sdk_http import completion_http_response, http_response, install_sdk_transport + + +def _write_inventory_workflow(workspace, import_style, units): + directory = workspace / "workflows" + reports = directory / "_inventory" / "reports" + reports.mkdir(parents=True) + (reports.parent / "__init__.py").touch() + (reports / "totals.py").write_text( + "from ..measure import UNITS_PER_BOX\n\n" + "def total(count):\n return count * UNITS_PER_BOX\n", + ) + (directory / "label.txt").write_text(workspace.name) + project_setup = ( + "from project_measure import UNITS_PER_BOX\n\n" + "def total(count):\n return count * UNITS_PER_BOX" + ) + setup = { + "relative": "from ._inventory.reports.totals import total", + "absolute": "from _inventory.reports.totals import total", + "missing": "from _inventory.reports.missing import total", + "entry": "def total(count):\n return count * UNITS_PER_BOX", + "workspace": project_setup, + "src": project_setup, + "added-path": ( + "import sys\n" + "sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'plans' / 'utilities'))\n" + + project_setup + ), + }[import_style] + label = ( + "files(__package__).joinpath('label.txt').read_text()" + if import_style == "relative" else repr(workspace.name) + ) + entry = directory / "report.py" + entry_source = ( + "from importlib.resources import files\n" + "from pathlib import Path\n" + "from opencollab import workflow\n" + f"{setup}\n\n" + '@workflow(name="inventory-report")\n' + "async def make_report(ctx, args):\n" + " count = total(args['count'])\n" + " Path(ctx.workspace_root, 'report.txt').write_text(f'Inventory total {count}.\\n')\n" + " summary = await ctx.agent('Summarize the inventory.', tools=[])\n" + f" return {{'summary': summary, 'total': count, 'label': {label}}}\n" + ) + target = reports.parent / "measure.py" + if import_style in {"workspace", "src", "added-path"}: + import_root = {"workspace": ".", "src": "src", "added-path": "plans/utilities"}[import_style] + target = workspace / import_root / "project_measure.py" + target.parent.mkdir(parents=True, exist_ok=True) + elif import_style == "entry": + target = entry + suffix = entry_source if target == entry else "" + if target != entry: + entry.write_text(entry_source) + target.write_text(f"UNITS_PER_BOX = {units + 1}\n" + suffix) + return target, suffix + + +def _edit_source_in_cache_second(source, suffix, stats, units): + source.write_text(f"UNITS_PER_BOX = {units}\n" + suffix) + os.utime(source, ns=(stats.st_atime_ns, stats.st_mtime_ns // 1_000_000_000 * 1_000_000_000 + 999_000_000)) + edited = source.stat() + assert edited.st_size == stats.st_size + assert int(edited.st_mtime) == int(stats.st_mtime) + + +@pytest.mark.parametrize("import_style", ["relative", "absolute", "missing", "entry", "workspace", "src", "added-path"]) +async def test_team_can_launch_workflow_with_sibling_module(tmp_path, monkeypatch, import_style): + team = tmp_path / "team.yaml" + team.write_text( + "entry: reporter\nroles:\n reporter:\n prompt: Collect the inventory report.\n" + " tools: [bash, manage_workflow]\n", + ) + monkeypatch.delenv("OPENCOLLAB_WORKFLOWS_DIR", raising=False) + monkeypatch.delenv("OPENCOLLAB_UNBOUNDED_LIMITS", raising=False) + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", "") + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + monkeypatch.setenv("PYTHONPATH", str(REPO_ROOT)) + summaries = [] + results = [] + + def respond(request): + messages = json.loads(request.content)["messages"] + if any( + "Summarize the inventory." in json.dumps(message["content"]) + for message in messages if message["role"] == "user" + ): + summaries.append("Inventory confirmed.") + return completion_http_response(request, text=summaries[-1]) + replies = [message for message in messages if message["role"] == "tool"] + if len(replies) == 2: + results.append(json.loads(replies[-1]["content"])) + return completion_http_response(request, text="Collected the workflow outcome.") + if not replies: + arguments = { + "action": "launch", "source": "workflows/report.py", "entry": "make_report", + "args": {"count": 6}, "python": sys.executable, "budget": 10_000, + } + else: + child = json.loads(replies[-1]["content"]) + arguments = {"action": "wait", "id": child["id"]} + response = completion_http_response(request).json() + response["choices"][0]["finish_reason"] = "tool_calls" + response["choices"][0]["message"].update(content=None, tool_calls=[{ + "id": f"workflow-{arguments['action']}", "type": "function", "function": { + "name": "manage_workflow", "arguments": json.dumps(arguments), + }, + }]) + return http_response(request, 200, json=response) + + install_sdk_transport(monkeypatch, "openai", respond) + roots = [("north", 7), ("south", 11)] if import_style == "relative" else [("local", 7)] + for name, units in roots: + workspace = tmp_path / name + source, suffix = _write_inventory_workflow(workspace, import_style, units) + if import_style == "src": + monkeypatch.setenv("PYTHONPATH", os.pathsep.join((str(REPO_ROOT), str(source.parent)))) + stats = source.stat() + cache = Path(py_compile.compile( + str(source), doraise=True, invalidation_mode=py_compile.PycInvalidationMode.TIMESTAMP, + )) + cache_bytes = cache.read_bytes() + app = OpenCollab( + workspace, model="offline-inventory", provider="openai", + api_key=__name__, base_url="https://offline.invalid/v1", + config={"llm_max_retries": 0, "max_output_tokens": 128}, + ) + report = workspace / "report.txt" + revisions = [units] if import_style == "missing" else [units, units + 2] + for revision, current_units in enumerate(revisions): + _edit_source_in_cache_second(source, suffix, stats, current_units) + expected = {"summary": "Inventory confirmed.", "total": current_units * 6, "label": name} + if import_style == "relative" and revision == 0: + direct = await app.workflow("inventory-report", {"count": 6}, trace=False, timeout=10) + assert direct.output == expected and direct.tokens == 4, (direct, direct.agent_failures) + report.unlink() + summaries.clear() + + result = await app.team( + "Collect the inventory report.", config=team, artifacts=tmp_path / f"{name}-artifacts-{revision}", + trace=False, use_worktrees=False, allow_unisolated_shell=True, timeout=15, + ) + assert result.ok and result.output == "Collected the workflow outcome." + record = results.pop() + saved = Path(record["artifacts"]) + assert json.loads((saved / "result.json").read_text()) == record + assert cache.read_bytes() == cache_bytes + if import_style == "missing": + assert record["status"] == "failed" + reason = "ModuleNotFoundError: No module named '_inventory.reports.missing'" + assert record["result"]["reason"] == reason + assert not report.exists() and not summaries + assert result.tokens == 12 + continue + + assert record["status"] == "completed", record + assert record["result"]["output"] == expected + assert report.read_text() == f"Inventory total {current_units * 6}.\n" + assert summaries == ["Inventory confirmed."] + summaries.clear() + assert result.tokens == 16 + manifest = json.loads((saved / "workflow.json").read_text()) + assert manifest["status"] == "completed" + assert manifest["tokens_spent"] == 4 diff --git a/tests/interfaces/test_sdk_candidate_adoption_ownership.py b/tests/interfaces/test_sdk_candidate_adoption_ownership.py new file mode 100644 index 00000000..6482f572 --- /dev/null +++ b/tests/interfaces/test_sdk_candidate_adoption_ownership.py @@ -0,0 +1,112 @@ +from __future__ import annotations + +import asyncio +import json +import shlex +import subprocess +import sys + +import pytest + +from opencollab.adapters.candidate_workspace import EnvCandidateWorkspace +from opencollab.adapters.env import LocalEnvironment +from opencollab.sdk import OpenCollab +from opencollab.tools import builtin_tools + + +@pytest.mark.parametrize("join", [False, True], ids=["plain-gather", "explicit-join"]) +@pytest.mark.parametrize("paused_phase", ["revision", "publication"]) +async def test_sdk_failure_waits_for_in_flight_candidate_publication(tmp_path, join, paused_phase): + workspace = tmp_path / "repo" + workspace.mkdir() + source = workspace / "app.py" + original = "def subtotal(price, count):\n return 0\n" + proposed = "def subtotal(price, count):\n return price * count\n" + source.write_text(original) + (workspace / "test_app.py").write_text( + "from app import subtotal\n\n" + "def test_invoice():\n" + " assert subtotal(5, 4) == 20\n" + ) + for args in ( + ("init", "-q"), ("add", "app.py", "test_app.py"), + ("-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", + "-c", "commit.gpgsign=false", "commit", "-qm", "Prepare invoice fixture"), + ): + subprocess.run(["git", *args], cwd=workspace, check=True, capture_output=True) + starting, publishing, failed = asyncio.Event(), asyncio.Event(), asyncio.Event() + sibling_failure = ValueError("Optional notes are unavailable") + owner = LocalEnvironment(str(workspace)) + adoption_tasks = [] + verified = [] + candidate_ready = False + + class SlowPublication(EnvCandidateWorkspace): + async def pause(self): + starting.set() + await publishing.wait() + + async def source_revision(self): + if candidate_ready and paused_phase == "revision" and not starting.is_set(): + await self.pause() + return await super().source_revision() + + async def adopt_run(self, candidate, preserve_paths=()): + if paused_phase == "publication": + await self.pause() + await super().adopt_run(candidate, preserve_paths) + + async def candidate_work(child, _args): + write, bash = builtin_tools("file_write", "bash", headless=False) + await child.execute_verification(write, {"path": "app.py", "mode": "create", "content": proposed}) + output = await child.execute_verification(bash, { + "command": f"{shlex.quote(sys.executable)} -B -m pytest -q -rA -p no:cacheprovider test_app.py", + }) + assert "1 passed" in output and "test_app.py::test_invoice" in output + verified.append(output) + return "candidate ready" + + async def workflow(ctx, inputs): + nonlocal candidate_ready + candidate = await ctx.candidate_workflow(candidate_work, inputs, label="invoice", budget=4000) + assert candidate.output == "candidate ready" + assert "+ return price * count" in candidate.diff + candidate_ready = True + + async def check_notes(): + await starting.wait() + failed.set() + raise sibling_failure + + adopting = asyncio.create_task(ctx.adopt_candidate(candidate)) + adoption_tasks.append(adopting) + if join: + _published, error = await asyncio.gather(adopting, check_notes(), return_exceptions=True) + raise error + await asyncio.gather(adopting, check_notes()) + + artifacts = tmp_path / "artifacts" + client = OpenCollab(workspace, model="offline", environment=owner) + job = asyncio.create_task(client.workflow( + workflow, budget=10_000, limit_mode="explicit", timeout=15, cleanup_timeout=2, + trace=False, artifacts=artifacts, candidate_workspace=SlowPublication(owner), + )) + try: + await asyncio.wait_for(failed.wait(), 10) + await asyncio.wait({job}, timeout=0.2) + assert not job.done() + assert not (artifacts / "workflow.json").exists() + assert source.read_text() == original + publishing.set() + result = await asyncio.wait_for(job, 10) + assert adoption_tasks[0].done() + assert adoption_tasks[0].result() is None + assert result.status == "failed" and result.error is sibling_failure + assert len(verified) == 1 and source.read_text() == proposed + manifest = json.loads((artifacts / "workflow.json").read_text()) + assert manifest["status"] == "failed" and manifest["evidence_complete"] is True + assert not owner.revoked + finally: + publishing.set() + await asyncio.gather(job, *adoption_tasks, return_exceptions=True) + await owner.cleanup() diff --git a/tests/interfaces/test_sdk_candidate_cancellation_during_cleanup.py b/tests/interfaces/test_sdk_candidate_cancellation_during_cleanup.py new file mode 100644 index 00000000..6fcc69b2 --- /dev/null +++ b/tests/interfaces/test_sdk_candidate_cancellation_during_cleanup.py @@ -0,0 +1,116 @@ +from __future__ import annotations + +import asyncio +from pathlib import Path + +import pytest + +from opencollab import OpenCollab +from opencollab.adapters.candidate_workspace import EnvCandidateWorkspace +from opencollab.adapters.env import LocalEnvironment +from opencollab.adapters.llm.types import LLMResponse, Usage +from tests.workflows.test_workflow_candidate_workspace import _git, _repository + + +@pytest.mark.parametrize("cancel", [False, True]) +@pytest.mark.parametrize("phase", ["pending_cleanup", "isolated_release"]) +async def test_candidate_releases_outer_worktree_when_cancelled_during_cleanup( + tmp_path, monkeypatch, cancel, phase, +): + repository = _repository(tmp_path) + entered, release = asyncio.Event(), asyncio.Event() + candidates, isolated = [], [] + + class Model: + async def complete(self, messages, **kwargs): + return LLMResponse(content="checked", usage=Usage(5, 10)) + + class CandidateWorkspace(EnvCandidateWorkspace): + async def acquire(self, label): + lease = await super().acquire(label) + candidates.append(lease) + return lease + + async def edit(child, _inputs): + (Path(child.workspace_root) / "report.txt").write_text("prepared report\n") + assert await child.agent("review report", isolation="worktree", tools=[]) == "checked" + environment = child.sessions[-1].env + isolated.append(Path(environment.workspace)) + + async def pause_cleanup(): + entered.set() + await release.wait() + + if phase == "pending_cleanup": + waits = 0 + wait = child.wait_for_pending_cleanup + + async def wait_for_cleanup(): + nonlocal waits + waits += 1 + if waits == 2: + child._track_pending_cleanup(asyncio.create_task(pause_cleanup())) + await wait() + + monkeypatch.setattr(child, "wait_for_pending_cleanup", wait_for_cleanup) + else: + cleanup = environment.cleanup + + async def finish(): + await pause_cleanup() + await cleanup() + + monkeypatch.setattr(environment, "cleanup", finish) + return "ready" + + async def flow(ctx, inputs): + task = asyncio.create_task(ctx.candidate_workflow(edit, inputs, label="report", budget=10000)) + try: + await asyncio.wait_for(entered.wait(), 5) + assert "+prepared report" in (candidates[0].delivery_diff or "") + assert Path(candidates[0].candidate_workspace, "report.txt").read_text() == "prepared report\n" + assert isolated[0].is_dir() + if cancel: + task.cancel() + await asyncio.sleep(0) + release.set() + if cancel: + with pytest.raises(asyncio.CancelledError): + await task + outcome = "cancelled" + else: + candidate = await task + assert candidate.output == "ready" + assert "+prepared report" in candidate.diff + outcome = "finished" + assert ctx.tokens_spent() == 15 + assert ctx.tokens_remaining() == 19985 + return outcome + finally: + release.set() + await asyncio.gather(task, return_exceptions=True) + + environment = LocalEnvironment(str(repository)) + workspace = CandidateWorkspace(environment) + try: + result = await OpenCollab(repository, environment=environment, model="test-model").workflow( + flow, llm=Model(), candidate_workspace=workspace, trace=False, + limit_mode="explicit", budget=20000, timeout=10, + ) + assert result.ok, result.reason + assert result.output == ("cancelled" if cancel else "finished") + assert result.tokens == 15 + candidate, = candidates + assert not isolated[0].exists() + worktree_list = _git(repository, "worktree", "list", "--porcelain") + assert ( + Path(candidate.candidate_workspace).exists(), + candidate.candidate_workspace in worktree_list, + candidate.environment.revoked, + ) == (False, False, True) + assert candidate.cleaned + assert _git(repository, "status", "--porcelain") == "" + finally: + for lease in reversed(candidates): + await lease.cleanup() + await environment.cleanup() diff --git a/tests/interfaces/test_sdk_candidate_late_usage.py b/tests/interfaces/test_sdk_candidate_late_usage.py new file mode 100644 index 00000000..b64793e5 --- /dev/null +++ b/tests/interfaces/test_sdk_candidate_late_usage.py @@ -0,0 +1,110 @@ +from __future__ import annotations + +import asyncio +import json + +import pytest + +from opencollab import OpenCollab +from opencollab.adapters.llm.client import LLMClient +from opencollab.adapters.storage import SessionStore +from tests.support.provider_sdk_http import completion_http_response, http_response, install_sdk_transport +from tests.workflows.test_workflow_candidate_workspace import _git, _repository + + +async def test_cancelled_candidate_traces_late_provider_usage(tmp_path, monkeypatch): + repo = _repository(tmp_path) + worktrees = _git(repo, "worktree", "list", "--porcelain") + artifacts = tmp_path / "artifacts" + usage_log = tmp_path / "usage.jsonl" + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(usage_log)) + correcting, cancelled, release, sibling_started = (asyncio.Event() for _ in range(4)) + + async def handler(request): + body = json.loads(request.content) + prompt = next(row["content"] for row in reversed(body["messages"]) if row["role"] == "user") + if "read sibling" in prompt: + sibling_started.set() + return completion_http_response(request, text="sibling answer", output_tokens=5) + if "You MUST call" not in prompt: + return completion_http_response(request, text="Measured 42", output_tokens=6) + + assert any(row.get("content") == "Measured 42" for row in body["messages"]) + correcting.set() + try: + await asyncio.Future() + except asyncio.CancelledError: + cancelled.set() + await release.wait() + payload = completion_http_response(request, text=None, output_tokens=17).json() + payload["choices"][0]["finish_reason"] = "tool_calls" + payload["choices"][0]["message"]["tool_calls"] = [{ + "id": "late-measurement", "type": "function", + "function": {"name": "structured_output", "arguments": '{"measurement":42}'}, + }] + return http_response(request, 200, json=payload) + + async def candidate_flow(ctx, _args): + return await ctx.agent("Record the measurement.", tools=[], schema={ + "type": "object", "properties": {"measurement": {"type": "integer"}}, + "required": ["measurement"], + }) + + async def flow(ctx, args): + candidate = asyncio.create_task(ctx.candidate_workflow(candidate_flow, args, label="measure", budget=10000)) + sibling = None + try: + await asyncio.wait_for(correcting.wait(), 5) + sibling = asyncio.create_task(ctx.agent_run("read sibling", tools=[], budget=5000)) + candidate.cancel() + await asyncio.wait_for(cancelled.wait(), 5) + assert not candidate.done() + assert not sibling_started.is_set() + release.set() + with pytest.raises(asyncio.CancelledError): + await candidate + result = await sibling + return result.output + finally: + release.set() + tasks = [candidate] if sibling is None else [candidate, sibling] + await asyncio.gather(*tasks, return_exceptions=True) + + install_sdk_transport(monkeypatch, "openai", handler) + async with LLMClient( + model="gpt-4o", api_key=tmp_path.name, base_url="https://offline.invalid/v1", max_retries=0, + ) as llm: + result = await OpenCollab(repo, model="gpt-4o", config={"max_output_tokens": 128}).workflow( + flow, llm=llm, artifacts=artifacts, trace=True, budget=20000, concurrency=1, + timeout=25, limit_mode="explicit", + ) + + assert result.status == "completed", result.reason + assert result.output == "sibling answer" + assert result.metrics["execution_quiesced"] is True + assert _git(repo, "worktree", "list", "--porcelain") == worktrees + manifest = json.loads((artifacts / "workflow.json").read_text()) + assert manifest["evidence_complete"] is True + assert result.tokens == manifest["tokens_spent"] == 34 + provider_records = [json.loads(line) for line in usage_log.read_text().splitlines()] + assert [row["usage"]["total_tokens"] for row in provider_records] == [8, 19, 7] + + trace = [json.loads(line) for line in (artifacts / "orchestration.jsonl").read_text().splitlines()] + completions = [row for row in trace if row["type"] == "llm_call"] + assert [row["metrics"]["tokens"] for row in completions] == [8, 19, 7] + late, = (row for row in completions if row["payload"].get("late")) + stopped, = (row for row in trace if row["type"] == "llm_call_cancelled") + for key in ("response_session_id", "session_step"): + assert late["payload"][key] == stopped["payload"][key] + assert stopped["step"] < late["step"] + assert late["payload"]["usage"]["total_tokens"] == 19 + assert late["payload"]["request_tool_names"] == ["structured_output"] + assert all(row["type"] != "tool_exec" for row in trace) + + correction_path, = artifacts.glob("001*.json") + correction = SessionStore().load_snapshot(str(correction_path), "") + assert correction["session_state"]["used_tokens"] == 19 + assert correction["session_state"]["phase"] == "stopped" + assert all(not row.get("tool_calls") for row in correction["messages"]) diff --git a/tests/interfaces/test_sdk_candidate_session_close.py b/tests/interfaces/test_sdk_candidate_session_close.py new file mode 100644 index 00000000..7c909a0e --- /dev/null +++ b/tests/interfaces/test_sdk_candidate_session_close.py @@ -0,0 +1,224 @@ +from __future__ import annotations + +import asyncio +import json +import threading +from pathlib import Path + +import pytest + +from opencollab import OpenCollab, RunError +from opencollab.bootstrap import container +from opencollab.tools import builtin_tools +from tests.interfaces.test_sdk_candidate_runtime_artifacts import EditingModel +from tests.workflows.test_workflow_candidate_workspace import _git, _repository + + +async def _wait_for_worktree_release(checkout): + async def released(): + while checkout.exists(): + await asyncio.sleep(0.01) + + await asyncio.wait_for(released(), 5) + + +@pytest.mark.parametrize("close_outcome", ["complete", "failure", "deadline"]) +async def test_candidate_workflow_closes_sessions_before_releasing_their_checkout( + tmp_path, monkeypatch, close_outcome, +): + repo = _repository(tmp_path) + source = repo / "source.py" + worktrees = _git(repo, "worktree", "list", "--porcelain") + close_started, release_close = asyncio.Event(), asyncio.Event() + sessions, models, closed, candidates = [], [], [], [] + artifacts = tmp_path / "artifacts" + receipt = tmp_path / "close-receipt.txt" + + class Model(EditingModel): + def __init__(self, **_kwargs): + super().__init__() + models.append(self) + + def context_window(self): + return 100_000 + + async def close(self): + session, = sessions + closed.append(await session.env.read_file("source.py")) + if close_outcome == "failure": + raise OSError("provider close failed") + + monkeypatch.setattr(container, "LLMClient", Model) + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(tmp_path / "usage.jsonl")) + + async def edit(child, _inputs): + output = await child.agent("edit source.py", tools=builtin_tools("file_write")) + session, = child.sessions + sessions.append(session) + + async def write_receipt(): + close_started.set() + await release_close.wait() + with receipt.open("a", encoding="utf-8") as stream: + stream.write(await session.env.read_file("source.py")) + + session.own_runtime(write_receipt) + return output + + async def flow(ctx, inputs): + candidate = await ctx.candidate_workflow(edit, inputs, label="edit") + candidates.append(candidate) + await ctx.adopt_candidate(candidate) + return candidate.output + + running = asyncio.create_task(OpenCollab( + repo, model="gpt-4o", provider="openai", api_key=tmp_path.name, + ).workflow( + flow, artifacts=artifacts, trace=False, limit_mode="explicit", budget=10_000, + cleanup_timeout=0.15 if close_outcome == "deadline" else 5, + )) + checkout = None + try: + await asyncio.wait_for(close_started.wait(), 5) + session, = sessions + checkout = Path(session.env.workspace) + assert checkout != repo + assert (checkout / "source.py").read_text() == "value = 2\n" + assert source.read_text() == "value = 1\n" + assert not running.done() + if close_outcome != "deadline": + release_close.set() + + if close_outcome != "complete": + with pytest.raises(RunError): + await asyncio.wait_for(asyncio.shield(running), 5) + else: + result = await asyncio.wait_for(running, 5) + assert result.ok and result.output == "done" + assert result.metrics["sessions"] == 1 + assert result.metrics["execution_quiesced"] is True + manifest = json.loads((artifacts / "workflow.json").read_text()) + assert result.tokens == manifest["tokens_spent"] == 12 + assert manifest["evidence_complete"] is True + candidate, = candidates + assert "+value = 2" in candidate.diff + if close_outcome == "complete": + assert not candidate.lifecycle_errors + elif close_outcome == "failure": + assert "provider close failed" in candidate.lifecycle_errors[0] + else: + assert "candidate workflow cleanup exceeded its deadline" in candidate.lifecycle_errors[0] + assert not receipt.exists() + assert await session.env.read_file("source.py") == "value = 2\n" + release_close.set() + + await _wait_for_worktree_release(checkout) + assert receipt.read_text() == "value = 2\n" + assert closed == ["value = 2\n"] + assert models[0].calls == 2 + assert source.read_text() == "value = 2\n" + assert _git(repo, "worktree", "list", "--porcelain") == worktrees + finally: + release_close.set() + if not running.done(): + running.cancel() + await asyncio.gather(running, return_exceptions=True) + + +async def test_candidate_workflow_accepts_close_that_finishes_after_adoption(tmp_path, monkeypatch): + repo = _repository(tmp_path) + adopted = asyncio.Event() + closed = [] + worktrees = _git(repo, "worktree", "list", "--porcelain") + + class Model(EditingModel): + def __init__(self, **_kwargs): + super().__init__() + + def context_window(self): + return 100_000 + + async def close(self): + await asyncio.wait_for(adopted.wait(), 3) + closed.append(True) + + monkeypatch.setattr(container, "LLMClient", Model) + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(tmp_path / "usage.jsonl")) + + async def edit(child, _inputs): + return await child.agent("edit source.py", tools=builtin_tools("file_write")) + + async def flow(ctx, inputs): + candidate = await ctx.candidate_workflow(edit, inputs, label="edit") + await ctx.adopt_candidate(candidate) + adopted.set() + return candidate.output + + result = await OpenCollab( + repo, model="gpt-4o", provider="openai", api_key=tmp_path.name, + ).workflow(flow, trace=False, limit_mode="explicit", budget=10_000, cleanup_timeout=0.5) + assert result.ok and result.output == "done" + assert result.metrics["execution_quiesced"] is True + assert (repo / "source.py").read_text() == "value = 2\n" + assert closed == [True] + assert _git(repo, "worktree", "list", "--porcelain") == worktrees + + +async def test_candidate_workflow_cleanup_deadline_includes_close_side_autosave(tmp_path, monkeypatch): + repo = _repository(tmp_path) + writing, close_returned = asyncio.Event(), asyncio.Event() + release_save = threading.Event() + loop = asyncio.get_running_loop() + sessions = [] + contexts = [] + + async def edit(child, _inputs): + output = await child.agent("edit source.py", tools=builtin_tools("file_write")) + session, = child.sessions + sessions.append(session) + await child.wait_for_pending_cleanup() + append = session.store.append_snapshot_delta + + def hold_save(path, **kwargs): + loop.call_soon_threadsafe(writing.set) + if not release_save.wait(5): + raise TimeoutError("test did not release the journal writer") + return append(path, **kwargs) + + monkeypatch.setattr(session.store, "append_snapshot_delta", hold_save) + + async def save_on_close(): + assert session.enqueue_auto_save() is not None + await asyncio.wait_for(writing.wait(), 2) + close_returned.set() + + session.own_runtime(save_on_close) + return output + + async def flow(ctx, inputs): + contexts.append(ctx) + candidate = await ctx.candidate_workflow(edit, inputs, label="edit") + assert "+value = 2" in candidate.diff + await ctx.adopt_candidate(candidate) + return candidate.output + + running = asyncio.create_task(OpenCollab(repo, model="controlled").workflow( + flow, llm=EditingModel(), trace=False, limit_mode="explicit", budget=10_000, + artifacts=tmp_path / "artifacts", cleanup_timeout=0.15, + )) + try: + await asyncio.wait_for(close_returned.wait(), 5) + session, = sessions + checkout = Path(session.env.workspace) + with pytest.raises(RunError, match="without finalized execution evidence"): + await asyncio.wait_for(asyncio.shield(running), 2) + context, = contexts + assert context.pending_cleanup_tasks + assert session.pending_cleanup_tasks + assert await session.env.read_file("source.py") == "value = 2\n" + assert (repo / "source.py").read_text() == "value = 2\n" + finally: + release_save.set() + await asyncio.gather(running, return_exceptions=True) + + await _wait_for_worktree_release(checkout) diff --git a/tests/interfaces/test_sdk_native_retry_scope.py b/tests/interfaces/test_sdk_native_retry_scope.py index 5d470816..bd17cc46 100644 --- a/tests/interfaces/test_sdk_native_retry_scope.py +++ b/tests/interfaces/test_sdk_native_retry_scope.py @@ -7,11 +7,13 @@ import re import subprocess from dataclasses import dataclass, field +from types import SimpleNamespace import openai import pytest from opencollab import OpenCollab, RunControl +from opencollab.adapters.llm import retry from opencollab.adapters.llm.client import LLMClient from opencollab.adapters.llm.retry import RetryTimeBudget from opencollab.adapters.llm.types import LLMResponse, Usage @@ -45,8 +47,6 @@ def __call__(self, request): @pytest.fixture def rate_limits(monkeypatch): - from opencollab.adapters.llm import retry - monkeypatch.setattr(retry.random, "uniform", lambda *_args: 0.0) for name in ("OPENCOLLAB_UNBOUNDED_LIMITS", "OPENCOLLAB_API_USAGE_LOG", "OPENCOLLAB_EXTERNAL_PROVIDER_ISOLATION"): @@ -204,6 +204,126 @@ async def flow(ctx, _inputs): finally: await model.close() +@pytest.mark.parametrize("mode", ["chat", "responses", "anthropic"]) +@pytest.mark.parametrize("first_waited", [False, True], ids=["declined-delay", "spent-time"]) +async def test_denied_backoff_keeps_unused_workflow_retry_time( + tmp_path, monkeypatch, rate_limits, mode, first_waited, +): + allowance = 1.0 + + async def handle(request): + first = b"scope-task-first-0" in request.content + response = rate_limits(request) + if response.status_code == 429: + if first and first_waited: + await asyncio.sleep(allowance + 0.1) + response.headers["retry-after"] = "120" if first and not first_waited else "0" + return response + + install_sdk_transport(monkeypatch, "anthropic" if mode == "anthropic" else "openai", handle) + oc = client(tmp_path, mode=mode, allowance=allowance) + model = await prepare(oc.create_model_client()) + + async def flow(ctx, _inputs): + first = await ctx.agent_run("scope-task-first-0", tools=()) + second = await ctx.agent_run("scope-task-second-0", tools=()) + return first, second + + try: + result = await oc.workflow(flow, llm=model, trace=False, timeout=10) + assert result.ok + first, second = result.output + assert (first.status, first.tokens) == ("failed", 0) + if first_waited: + assert (second.status, second.tokens) == ("failed", 0) + assert result.tokens == 0 + else: + assert (second.status, second.output, second.tokens) == ("completed", "done", 4) + assert result.tokens == 4 + assert rate_limits.counts == {"scope-task-first-0": 1, "scope-task-second-0": 1 if first_waited else 2} + assert model.provider_retry_budget.remaining_seconds == allowance + finally: + await model.close() + +@pytest.mark.parametrize("mode", ["chat", "responses", "anthropic"]) +@pytest.mark.parametrize("cancel", [True, False], ids=["cancel-wait", "finish-wait"]) +async def test_competing_roles_keep_spent_retry_time_after_wait_settlement( + tmp_path, monkeypatch, rate_limits, mode, cancel, +): + waiting = asyncio.Event() + release = asyncio.Event() + clock = SimpleNamespace(now=0.0) + delays = [] + retry_after = { + "scope-task-first-0": "8", + "scope-task-competing-0": "0", + "scope-task-long-0": "3", + "scope-task-exact-0": "2", + } + + async def sleep(delay): + delays.append(delay) + if delay == 8: + waiting.set() + await release.wait() + else: + clock.now += delay + + def handle(request): + response = rate_limits(request) + if response.status_code == 429: + label = re.search(rb"scope-task-[a-z]+-\d+", request.content).group().decode() + if label == "scope-task-competing-0": + clock.now += 4 + response.headers["retry-after"] = retry_after[label] + return response + + monkeypatch.setattr(retry, "time", SimpleNamespace(monotonic=lambda: clock.now)) + monkeypatch.setattr(retry, "asyncio", SimpleNamespace(sleep=sleep)) + install_sdk_transport(monkeypatch, "anthropic" if mode == "anthropic" else "openai", handle) + oc = client(tmp_path, mode=mode, allowance=10) + model = await prepare(oc.create_model_client()) + + async def flow(ctx, _inputs): + first = asyncio.create_task(ctx.agent_run("scope-task-first-0", budget=10_000, tools=())) + try: + await asyncio.wait_for(waiting.wait(), 5) + competing = await ctx.agent_run("scope-task-competing-0", tools=()) + assert competing.status == "failed" + if cancel: + first.cancel() + with pytest.raises(asyncio.CancelledError): + await first + else: + clock.now = 8.0 + release.set() + assert (await first).status == "completed" + finally: + if not first.done(): + first.cancel() + await asyncio.gather(first, return_exceptions=True) + larger = await ctx.agent_run("scope-task-long-0", tools=()) + exact = await ctx.agent_run("scope-task-exact-0", tools=()) + return larger, exact + + try: + result = await oc.workflow(flow, llm=model, trace=False, timeout=15) + assert result.ok + larger, exact = result.output + assert larger.status == "failed" + assert exact.status == ("completed" if cancel else "failed") + assert result.tokens == 4 + assert delays == ([8, 2] if cancel else [8]) + assert rate_limits.counts == { + "scope-task-first-0": 1 if cancel else 2, + "scope-task-competing-0": 1, + "scope-task-long-0": 1, + "scope-task-exact-0": 2 if cancel else 1, + } + assert model.provider_retry_budget.remaining_seconds == 10 + finally: + await model.close() + async def test_nested_public_run_is_independent_and_restores_the_outer_allowance(tmp_path, monkeypatch, rate_limits): install_sdk_transport(monkeypatch, "openai", rate_limits) oc = client(tmp_path) @@ -227,6 +347,7 @@ async def flow(ctx, _inputs): await model.close() async def test_direct_native_calls_keep_their_existing_lifetime_budget(tmp_path, monkeypatch, rate_limits): + monkeypatch.setattr(retry, "time", SimpleNamespace(monotonic=lambda: 0.0)) install_sdk_transport(monkeypatch, "openai", rate_limits) oc = client(tmp_path) model = await prepare(oc.create_model_client()) @@ -234,7 +355,7 @@ async def test_direct_native_calls_keep_their_existing_lifetime_budget(tmp_path, assert (await model.complete([{"role": "user", "content": "scope-task-direct-0"}])).content == "done" with pytest.raises(openai.RateLimitError): await model.complete([{"role": "user", "content": "scope-task-direct-1"}]) - assert model.provider_retry_budget.remaining_seconds == 0 + assert model.provider_retry_budget.remaining_seconds == 0.5 assert (await run(oc, model, "scope-task-agent-0", "agent")).ok with pytest.raises(openai.RateLimitError): await model.complete([{"role": "user", "content": "scope-task-direct-2"}]) @@ -245,6 +366,7 @@ async def test_direct_native_calls_keep_their_existing_lifetime_budget(tmp_path, @pytest.mark.parametrize("concurrent", [False, True]) async def test_explicit_shared_budget_preserves_its_cross_run_limit(tmp_path, monkeypatch, rate_limits, concurrent): + monkeypatch.setattr(retry, "time", SimpleNamespace(monotonic=lambda: 0.0)) install_sdk_transport(monkeypatch, "openai", rate_limits) shared = RetryTimeBudget(1.5) model = await prepare(LLMClient( @@ -263,7 +385,7 @@ async def test_explicit_shared_budget_preserves_its_cross_run_limit(tmp_path, mo await run(oc, model, "scope-task-shared-1", "workflow")] assert [result.status for result in results] == ["completed", "failed"] assert model.provider_retry_budget is shared - assert shared.remaining_seconds == 0 + assert shared.remaining_seconds == 0.5 assert rate_limits.counts == {"scope-task-shared-0": 2, "scope-task-shared-1": 1} finally: await model.close() diff --git a/tests/interfaces/test_sdk_run_control_cleanup.py b/tests/interfaces/test_sdk_run_control_cleanup.py index 874b904e..75eafce3 100644 --- a/tests/interfaces/test_sdk_run_control_cleanup.py +++ b/tests/interfaces/test_sdk_run_control_cleanup.py @@ -8,8 +8,9 @@ import pytest from opencollab import OpenCollab, RunControl, RunError +from opencollab.adapters.env import LocalEnvironment from opencollab.adapters.storage import SessionStore -from opencollab.bootstrap import agent_runtime, build_session, container +from opencollab.bootstrap import agent_runtime, build_session, container, load_session from opencollab.domain.agent import Agent from tests.support.environment_test_support import local_environment_factory as local_environment_factory from tests.support.session_characterization_test_support import ( @@ -63,7 +64,9 @@ def observe(event): owner = asyncio.create_task(OpenCollab(tmp_path, model="fixture").agent2( "run the tool", system_prompt="sys", tools=[Tool("cleanup_tool")], llm=model, trace=False, timeout=0.1, cleanup_timeout=0.01, - run_control=RunControl(on_event=observe, tool_cancellation_cleanup_timeout=0.01), + run_control=RunControl( + on_event=observe, tool_cancellation_cleanup_timeout=0.25 if delayed_cleanup else 0.01, + ), )) try: await asyncio.wait_for(started.wait(), 1) @@ -95,6 +98,63 @@ def observe(event): assert len([event for event, *_ in events if event.type == "cleanup_completed"]) == 1 +async def test_cleanup_event_follows_environment_abort(tmp_path): + tool_started, tool_release, tool_finished = asyncio.Event(), asyncio.Event(), asyncio.Event() + abort_started, abort_release, abort_finished = asyncio.Event(), asyncio.Event(), asyncio.Event() + cleanup_reported = asyncio.Event() + observed = [] + + class Environment(LocalEnvironment): + async def abort(self): + abort_started.set() + await abort_release.wait() + await super().abort() + abort_finished.set() + + class Tool(FakeTool): + async def execute_with_runtime(self, args, runtime): + tool_started.set() + try: + await asyncio.Event().wait() + finally: + while not tool_release.is_set(): + try: + await tool_release.wait() + except asyncio.CancelledError: + continue + tool_finished.set() + + def observe(event): + if event.type == "cleanup_completed": + observed.append((tool_finished.is_set(), abort_finished.is_set())) + cleanup_reported.set() + + environment = Environment(str(tmp_path)) + model = Model([llm_response(tool_calls=[tool_call(name="cleanup_tool", arguments="{}")])]) + owner = asyncio.create_task(OpenCollab(tmp_path, model="fixture", environment=environment).agent2( + "run the tool", system_prompt="sys", tools=[Tool("cleanup_tool")], llm=model, + trace=False, timeout=0.15, cleanup_timeout=0.01, + run_control=RunControl(on_event=observe, tool_cancellation_cleanup_timeout=0.01), + )) + try: + await asyncio.wait_for(tool_started.wait(), 1) + await asyncio.wait_for(abort_started.wait(), 1) + with pytest.raises(RunError, match="quiescent terminal state"): + await asyncio.wait_for(asyncio.shield(owner), 1) + tool_release.set() + await asyncio.wait_for(tool_finished.wait(), 1) + assert not cleanup_reported.is_set() + finally: + tool_release.set() + abort_release.set() + await asyncio.gather(owner, return_exceptions=True) + await asyncio.wait_for(abort_finished.wait(), 1) + await environment.cleanup() + + await asyncio.wait_for(cleanup_reported.wait(), 1) + assert observed == [(True, True)] + + async def test_failed_owned_provider_close_retains_error_without_cleanup_event(tmp_path, monkeypatch): events, models = [], [] @@ -126,6 +186,7 @@ async def test_late_provider_usage_keeps_receiver_through_new_subscriber_work( started, release = asyncio.Event(), asyncio.Event() save_started, save_release = threading.Event(), threading.Event() events = [] + resumed = [] path = tmp_path / "session.json" class LateModel(Model): @@ -138,9 +199,17 @@ async def complete(self, messages, tools=None, **kwargs): continue return llm_response(content="late answer", input_tokens=13, output_tokens=24) + def observe(event): + events.append(event) + if event.type == "cleanup_completed": + resumed.append(load_session( + str(path), agent=session.agent, env=session.env, llm=Model(), + auto_save_path=str(path), + )) + session = build_session( env=local_environment_factory(), agent=Agent(name="late-provider", system_prompt="sys"), llm=LateModel(), - auto_save_path=str(path), run_control=RunControl(on_event=events.append), + auto_save_path=str(path), run_control=RunControl(on_event=observe), ) await session.add_user_message("finish") owner = asyncio.create_task(session.run_loop()) @@ -188,4 +257,7 @@ def save(): snapshot = SessionStore().load_snapshot(str(path), session.agent.system_prompt) assert snapshot["session_state"]["used_tokens"] == 37 assert events[-1].type == "cleanup_completed" + recovered, = resumed + assert recovered.used_tokens == 37 + await recovered.aclose() assert len([event for event in events if event.type == "cleanup_completed"]) == 1 diff --git a/tests/interfaces/test_sdk_run_id.py b/tests/interfaces/test_sdk_run_id.py index cdd58431..78d258d6 100644 --- a/tests/interfaces/test_sdk_run_id.py +++ b/tests/interfaces/test_sdk_run_id.py @@ -2,15 +2,19 @@ from __future__ import annotations +import asyncio import json import re +import threading +from contextlib import AsyncExitStack from pathlib import Path import pytest from opencollab import OpenCollab, RunControl, workflow from opencollab.adapters.llm.types import LLMResponse, Usage -from opencollab.bootstrap import build_runtime_context, build_scheduler, load_session +from opencollab.adapters.storage import SessionStore +from opencollab.bootstrap import build_runtime_context, build_scheduler, build_session, load_session from opencollab.domain.agent import Agent from tests.support.environment_test_support import local_environment_factory as local_environment_factory from tests.support.prebuilt_team_test_support import CONFIG @@ -133,6 +137,66 @@ async def test_loading_an_sdk_snapshot_keeps_the_selected_run_identity(local_env finally: await restored.aclose() +@pytest.mark.parametrize("autosave", [False, True]) +async def test_replacing_an_export_during_resume_keeps_its_run_identity( + tmp_path, local_environment_factory, monkeypatch, autosave, +): + env = local_environment_factory(str(tmp_path)) + agent = Agent(name="saved-agent", system_prompt="Answer briefly.") + source = str(tmp_path / "shared.json") + target = str(tmp_path / "continued.json") + store = SessionStore() + load_snapshot = store.load_snapshot + read_first = threading.Event() + replaced = threading.Event() + events = [] + + def read_with_concurrent_export(path, system_prompt): + snapshot = load_snapshot(path, system_prompt) + if path == source and not read_first.is_set(): + read_first.set() + assert replaced.wait(5) + return snapshot + + monkeypatch.setattr(store, "load_snapshot", read_with_concurrent_export) + async with AsyncExitStack() as sessions: + original, replacement = ( + build_session(agent=agent, env=env, llm=ReplyLLM(), aid=aid, run_id=run_id) + for aid, run_id in ((3, "review-a"), (7, "review-b")) + ) + for writer, prompt in ((original, "Review A."), (replacement, "Review B.")): + sessions.push_async_callback(writer.aclose) + await writer.add_user_message(prompt) + assert await writer.run_loop() == "finished" + original.save(source) + + reader = asyncio.create_task(asyncio.to_thread( + load_session, source, agent, env=env, llm=ReplyLLM(), store=store, + auto_save_path=target if autosave else None, + run_control=RunControl(on_event=events.append), + )) + try: + assert await asyncio.to_thread(read_first.wait, 5) + replacement.save(source) + assert OpenCollab.read_session_snapshot(source)["run_id"] == "review-b" + finally: + replaced.set() + restored = await reader + sessions.push_async_callback(restored.aclose) + assert restored.state.aid == 3 + assert restored.run_id == "review-a" + assert restored.messages == original.messages + await restored.add_user_message("Summarize the review.") + assert await restored.run_loop() == "finished" + if not autosave: + restored.save(target) + continued = OpenCollab.read_session_snapshot(target) + assert continued["run_id"] == "review-a" + assert continued["aid"] == 3 + assert continued["session_state"]["used_tokens"] == 12 + assert [event.run_id for event in events if event.type == "usage"] == ["review-a"] + assert OpenCollab.read_session_snapshot(source)["run_id"] == "review-b" + @pytest.mark.parametrize("saved_id", [None, "", " ", 7, "invalid\x00id"]) def test_loading_an_unusable_saved_run_id_preserves_agent_identity(local_environment_factory, tmp_path, saved_id): path = tmp_path / "snapshot.json" diff --git a/tests/interfaces/test_sdk_runtime.py b/tests/interfaces/test_sdk_runtime.py index 261314ee..3fff6eed 100644 --- a/tests/interfaces/test_sdk_runtime.py +++ b/tests/interfaces/test_sdk_runtime.py @@ -544,8 +544,14 @@ async def plain(_ctx, _inputs): assert manifest["reason"] == "environment_cleanup_failed" assert manifest["evidence_complete"] is False +@pytest.mark.parametrize("inputs", [ + {"path": Path("not-json-serializable")}, + {"report": {"samples": [float("nan")]}}, + {"report": {"samples": [float("inf")]}}, + {"report": {"samples": [float("-inf")]}}, +]) async def test_workflow_rejects_non_json_inputs_before_claiming_artifacts( - tmp_path: Path, + tmp_path: Path, inputs, ) -> None: invoked = False @@ -554,7 +560,6 @@ async def plain(_ctx, _inputs): invoked = True return "completed before the old late manifest failure" - inputs = {"path": Path("not-json-serializable")} result = await OpenCollab(tmp_path).workflow(plain, inputs, trace=False) assert result.output == "completed before the old late manifest failure" assert invoked is True diff --git a/tests/interfaces/test_sdk_team_deadline_cancellation.py b/tests/interfaces/test_sdk_team_deadline_cancellation.py new file mode 100644 index 00000000..efe7b12a --- /dev/null +++ b/tests/interfaces/test_sdk_team_deadline_cancellation.py @@ -0,0 +1,71 @@ +import asyncio +import json + +import pytest + +from opencollab import OpenCollab +from opencollab.application.scheduler import Scheduler +from tests.support.provider_sdk_http import completion_http_response, install_sdk_transport + + +@pytest.mark.parametrize("timeout", [5.0, None], ids=["deadline", "unbounded"]) +async def test_team_propagates_cancellation_after_scheduler_completion(tmp_path, monkeypatch, timeout): + ledger = tmp_path / "usage.jsonl" + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(ledger)) + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + config = tmp_path / "team.yaml" + config.write_text( + "entry: lead\nroles:\n lead:\n model: gpt-4o\n" + " prompt: Report the verified total.\n tools: []\n", + encoding="utf-8", + ) + answer = "The verified total is 17." + + async def model_response(request): + return completion_http_response(request, text=answer) + + install_sdk_transport(monkeypatch, "openai", model_response) + app = OpenCollab( + tmp_path, model="gpt-4o", provider="openai", api_key=tmp_path.name, + base_url="https://fixture.invalid/v1", + config={"wire_protocol": "chat_completions", "llm_stream_chat": False, "llm_max_retries": 0}, + ) + original_run = Scheduler.run + cancelled = [] + + def cancel_caller(_owner=None): + cancelled.append(caller.cancel("caller stopped before delivery")) + + async def cancel_after_completion(self, prompt): + output = await original_run(self, prompt) + owner = asyncio.current_task() + owner.add_done_callback(cancel_caller) + return output + + monkeypatch.setattr(Scheduler, "run", cancel_after_completion) + artifacts = tmp_path / "artifacts" + cancellation = [] + + async def run_team(): + try: + return await app.team( + "Report the total.", config=config, timeout=timeout, artifacts=artifacts, + budget=20_000, use_worktrees=False, + ) + except asyncio.CancelledError as exc: + cancellation.append(exc.args) + raise + + caller = asyncio.create_task(run_team()) + with pytest.raises(asyncio.CancelledError): + await caller + + assert cancelled == [True] + assert cancellation == [("caller stopped before delivery",)] + snapshot = app.read_session_snapshot(next(artifacts.glob("agent_0_*.json"))) + assert snapshot["messages"][-1]["content"] == answer + assert snapshot["session_state"]["phase"] == "done" + assert snapshot["session_state"]["used_tokens"] == 4 + records = [json.loads(line) for line in ledger.read_text(encoding="utf-8").splitlines()] + assert [record["usage"]["total_tokens"] for record in records] == [4] diff --git a/tests/interfaces/test_sdk_team_deadline_result.py b/tests/interfaces/test_sdk_team_deadline_result.py new file mode 100644 index 00000000..9ac60024 --- /dev/null +++ b/tests/interfaces/test_sdk_team_deadline_result.py @@ -0,0 +1,198 @@ +import asyncio +import json +import threading + +import pytest + +from opencollab import OpenCollab +from opencollab.adapters.env import LocalEnvironment +from opencollab.application.session import Session +from tests.support.provider_sdk_http import completion_http_response, http_response, install_sdk_transport + + +@pytest.mark.parametrize("outcome", ["submit", "working", "complete"]) +@pytest.mark.parametrize("persist", [False, True], ids=["live", "artifacts"]) +async def test_team_deadline_returns_only_an_accepted_answer(tmp_path, monkeypatch, outcome, persist): + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(tmp_path / "usage.jsonl")) + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + team = tmp_path / "team.yaml" + team.write_text( + "entry: lead\nroles:\n" + " lead:\n model: lead-fixture\n prompt: Report the figures.\n tools: [spawn_agent, submit]\n" + " reader:\n model: reader-fixture\n prompt: Check the figures.\n tools: []\n" + "topology:\n lead: [reader]\n reader: []\n", + encoding="utf-8", + ) + requests = [] + reader_cancelled = asyncio.Event() + answer = "The first table has eight observations." + + async def model_request(request): + body = json.loads(request.content) + model = body["model"] + requests.append(model) + if model == "reader-fixture": + if outcome != "complete": + try: + await asyncio.Event().wait() + finally: + reader_cancelled.set() + return completion_http_response(request, text="Checked. The first table has eight observations.") + assert model == "lead-fixture" + tool_calls = [{ + "id": "reader-call", "type": "function", "function": { + "name": "spawn_agent", "arguments": json.dumps({"role": "reader", "task": "Check the table."}), + }, + }] + if outcome != "working": + tool_calls.append({ + "id": "submit-call", "type": "function", "function": { + "name": "submit", "arguments": json.dumps({"summary": answer}), + }, + }) + return http_response(request, 200, json={ + "id": "team-submission", "object": "chat.completion", "created": 1, "model": model, + "choices": [{"index": 0, "finish_reason": "tool_calls", "message": { + "role": "assistant", "content": "I am checking the first table.", "tool_calls": tool_calls, + }}], + "usage": {"prompt_tokens": 2, "completion_tokens": 2, "total_tokens": 4}, + }) + + install_sdk_transport(monkeypatch, "openai", model_request) + client = OpenCollab( + tmp_path, provider="openai", model="lead-fixture", api_key=tmp_path.name, + base_url="https://fixture.invalid/v1", + config={"llm_max_retries": 0, "wire_protocol": "chat_completions", "llm_stream_chat": False}, + ) + artifacts = tmp_path / "artifacts" if persist else None + result = await client.team( + "Report the table count.", config=team, artifacts=artifacts, trace=False, use_worktrees=False, + budget=100_000, timeout=2.0, cleanup_timeout=1.0, + ) + assert requests == ["lead-fixture", "reader-fixture"] + assert result.metrics["execution_quiesced"] is True + if outcome == "complete": + assert (result.status, result.reason, result.tokens) == ("completed", None, 8) + else: + assert (result.status, result.reason, result.tokens) == ("stopped", "timeout", 4) + assert isinstance(result.error, asyncio.TimeoutError) + assert isinstance(result.error.__cause__, asyncio.CancelledError) + assert reader_cancelled.is_set() + + assert result.output == (None if outcome == "working" else answer) + + +async def test_team_deadline_preserves_final_answer_during_diff_capture(tmp_path, monkeypatch): + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(tmp_path / "usage.jsonl")) + team = tmp_path / "team.yaml" + team.write_text("entry: lead\nroles:\n lead:\n prompt: State the total.\n tools: []\n", encoding="utf-8") + answer = "The total is twelve." + diff_started = asyncio.Event() + diff_cancelled = asyncio.Event() + requests = [] + + class SlowDiffEnvironment(LocalEnvironment): + async def get_diff(self): + diff_started.set() + try: + await asyncio.Event().wait() + finally: + diff_cancelled.set() + return "" + + def respond(request): + requests.append(request) + return completion_http_response(request, text=answer) + + install_sdk_transport(monkeypatch, "openai", respond) + environment = SlowDiffEnvironment(str(tmp_path)) + client = OpenCollab( + tmp_path, provider="openai", model="fixture-model", api_key=tmp_path.name, + base_url="https://fixture.invalid/v1", environment=environment, + config={"llm_max_retries": 0, "wire_protocol": "chat_completions", "llm_stream_chat": False}, + ) + artifacts = tmp_path / "artifacts" + try: + result = await client.team( + "Read the total.", config=team, artifacts=artifacts, budget=20000, + trace=False, use_worktrees=False, timeout=2.0, cleanup_timeout=1.0, + ) + assert len(requests) == 1 + assert diff_started.is_set() and diff_cancelled.is_set() + assert (result.status, result.reason, result.tokens) == ("stopped", "timeout", 4) + assert result.metrics["session_quiesced"] is True + snapshot = client.read_session_snapshot(next(artifacts.glob("agent_0_*.json"))) + assert snapshot["messages"][-1]["content"] == answer + assert result.output == answer + finally: + await environment.cleanup() + + +@pytest.mark.parametrize(("finish_reason", "visible"), [ + ("stop", True), ("length", True), ("content_filter", True), ("length", False), +], ids=["complete", "truncated", "filtered", "reasoning-only"]) +async def test_team_deadline_preserves_visible_reply_during_checkpoint(tmp_path, monkeypatch, finish_reason, visible): + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(tmp_path / "usage.jsonl")) + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + team = tmp_path / "team.yaml" + team.write_text("entry: lead\nroles:\n lead:\n prompt: State the total.\n tools: []\n", encoding="utf-8") + timeout = 1.5 + answer = "The verified inventory contains 42 units." + checkpoint_started = threading.Event() + release_checkpoint = threading.Event() + terminal_phase = "done" if finish_reason == "stop" else "stopped" + save = Session.save + requests = [] + + def hold_checkpoint(session, path): + if (session.phase.value == terminal_phase and threading.current_thread() is not threading.main_thread() + and not checkpoint_started.is_set()): + checkpoint_started.set() + assert release_checkpoint.wait(5) + return save(session, path) + + def respond(request): + requests.append(request) + reply = completion_http_response(request, text=answer, output_tokens=5).json() + choice, = reply["choices"] + choice["finish_reason"] = finish_reason + if not visible: + choice["message"].update(content=None, reasoning_content="I should check the inventory.") + return http_response(request, 200, json=reply) + + async def release_after_deadline(): + assert await asyncio.to_thread(checkpoint_started.wait, 4) + await asyncio.sleep(timeout + 0.1) + release_checkpoint.set() + + monkeypatch.setattr(Session, "save", hold_checkpoint) + install_sdk_transport(monkeypatch, "openai", respond) + client = OpenCollab( + tmp_path, provider="openai", model="fixture-model", api_key=tmp_path.name, + base_url="https://fixture.invalid/v1", + config={"llm_max_retries": 0, "wire_protocol": "chat_completions", "llm_stream_chat": False}, + ) + artifacts = tmp_path / "artifacts" + release = asyncio.create_task(release_after_deadline()) + try: + result = await client.team( + "Report the verified inventory.", config=team, artifacts=artifacts, trace=False, + use_worktrees=False, budget=30_000, timeout=timeout, cleanup_timeout=3, + ) + await release + finally: + release_checkpoint.set() + if not release.done(): + release.cancel() + await asyncio.gather(release, return_exceptions=True) + + assert len(requests) == 1 + assert checkpoint_started.is_set() + assert (result.status, result.reason, result.tokens) == ("stopped", "timeout", 7) + assert result.output == (answer if visible else None) + saved, = artifacts.glob("agent_0_*.json") + if visible: + snapshot = client.read_session_snapshot(saved) + assert [row.get("content") for row in snapshot["messages"] if row["role"] == "assistant"] == [answer] diff --git a/tests/interfaces/test_sdk_team_environment_lifetime.py b/tests/interfaces/test_sdk_team_environment_lifetime.py index 4fb1f110..63771e33 100644 --- a/tests/interfaces/test_sdk_team_environment_lifetime.py +++ b/tests/interfaces/test_sdk_team_environment_lifetime.py @@ -222,3 +222,77 @@ async def fail_first_cleanup(env): finally: await schedulers[0].cleanup() assert _anchors(workspace) == baseline + + +@pytest.mark.parametrize("interruption", ["caller", "timeout"]) +@pytest.mark.parametrize("cleanup_fails", [False, True]) +async def test_interrupted_team_keeps_its_outcome_when_cleanup_retries( + monkeypatch, team_workspace, interruption, cleanup_fails, +): + from opencollab.adapters.env import LocalEnvironment + + workspace, team = team_workspace + entered = asyncio.Event() + cancelled = asyncio.Event() + cleanup_calls = 0 + real_cleanup = LocalEnvironment._cleanup_files + + async def respond(_request): + entered.set() + try: + await asyncio.Event().wait() + finally: + cancelled.set() + + async def cleanup(environment): + nonlocal cleanup_calls + cleanup_calls += 1 + if cleanup_calls == 1 and cleanup_fails: + raise OSError("temporary workspace cleanup failure") + await real_cleanup(environment) + + install_sdk_transport(monkeypatch, "openai", respond) + monkeypatch.setattr(LocalEnvironment, "_cleanup_files", cleanup) + app = OpenCollab( + workspace, model="offline", provider="openai", + api_key="offline-unused", # pragma: allowlist secret + base_url="https://offline.invalid/v1", + config={"llm_max_retries": 0, "wire_protocol": "chat_completions", "llm_stream_chat": False}, + ) + baseline = _anchors(workspace) + running = asyncio.create_task(app.team( + "Reply once.", config=team, trace=False, use_worktrees=False, + timeout=2 if interruption == "timeout" else None, cleanup_timeout=1, + )) + try: + await asyncio.wait_for(entered.wait(), 5) + if interruption == "caller": + running.cancel("caller ended team") + with pytest.raises(asyncio.CancelledError) as caught: + await running + cancellation = caught.value + else: + result = await running + assert (result.status, result.reason) == ("stopped", "timeout") + assert isinstance(result.error, asyncio.TimeoutError) + assert result.metrics["execution_quiesced"] is True + cancellation = result.error.__cause__ + assert isinstance(cancellation, asyncio.CancelledError) + # Python 3.10 can wrap the original exception at a cancelled task boundary. + exceptions = [] + while cancellation is not None and cancellation not in exceptions: + exceptions.append(cancellation) + cancellation = cancellation.__cause__ or cancellation.__context__ + if interruption == "caller": + assert any(error.args == ("caller ended team",) for error in exceptions) + assert any( + "scheduler cleanup also failed" in note + for error in exceptions for note in getattr(error, "__notes__", ()) + ) is cleanup_fails + assert cancelled.is_set() + assert cleanup_calls == (2 if cleanup_fails else 1) + assert _anchors(workspace) == baseline + finally: + if not running.done(): + running.cancel() + await asyncio.gather(running, return_exceptions=True) diff --git a/tests/interfaces/test_sdk_team_filtered_reply.py b/tests/interfaces/test_sdk_team_filtered_reply.py index e38bba04..3d5b0c07 100644 --- a/tests/interfaces/test_sdk_team_filtered_reply.py +++ b/tests/interfaces/test_sdk_team_filtered_reply.py @@ -1,6 +1,10 @@ from __future__ import annotations +import asyncio +import errno import json +import os +from pathlib import Path import pytest @@ -14,9 +18,12 @@ _INTERIM = "I will inspect the inventory before reporting a subtotal." _VISIBLE = "Verified inventory subtotal is 42." +_UPDATED = "Verified inventory subtotal is 43." +_PARTIAL = _VISIBLE + " The next section" _REFUSAL = "I can share the verified subtotal of 42." +_REASONING = "I should check whether the inventory is complete." _FILTER_REASON = "provider filtered the output" -_FILTER_ERROR = f"Error: agent stopped: {_FILTER_REASON}" +_TRUNCATED_REASON = "output truncated: provider reached its generation limit" def _chat_reply(request, model, step, reason, message): @@ -34,14 +41,18 @@ def _inventory_read(): }]} -@pytest.mark.parametrize(("finish_reason", "content", "refusal", "visible"), [ - pytest.param("stop", _VISIBLE, None, _VISIBLE, id="completed"), - pytest.param("content_filter", _VISIBLE, None, _VISIBLE, id="partial"), - pytest.param("content_filter", None, _REFUSAL, _REFUSAL, id="refusal"), - pytest.param("content_filter", None, None, "", id="empty-after-tool"), +@pytest.mark.parametrize(("finish_reason", "terminal_reply", "visible"), [ + pytest.param("stop", {"content": _VISIBLE}, _VISIBLE, id="completed"), + pytest.param("content_filter", {"content": _VISIBLE}, _VISIBLE, id="partial"), + pytest.param("content_filter", {"content": None, "refusal": _REFUSAL}, _REFUSAL, id="refusal"), + pytest.param("content_filter", {"content": None}, "", id="empty-after-tool"), + pytest.param("length", {"content": _PARTIAL}, _PARTIAL, id="truncated"), + pytest.param("length", {"content": None}, "", id="truncated-empty-after-tool"), + pytest.param("length", {"content": None, "reasoning_content": _REASONING}, "", id="truncated-reasoning-only"), + pytest.param("model_context_window_exceeded", {"content": _PARTIAL}, _PARTIAL, id="context-limited"), ]) -async def test_team_passes_filtered_reply_text_to_the_delegating_agent( - tmp_path, monkeypatch, finish_reason, content, refusal, visible, +async def test_team_delivers_member_reply_text_to_the_delegating_agent( + tmp_path, monkeypatch, finish_reason, terminal_reply, visible, ): monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(tmp_path / "usage.jsonl")) monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") @@ -76,7 +87,7 @@ def handler(request): else: assert "verified inventory: 42" in tool_results[-1] reason = finish_reason - message = {"content": content, "refusal": refusal} + message = terminal_reply return _chat_reply(request, model, len(requests), reason, message) install_sdk_transport(monkeypatch, "openai", handler) @@ -91,9 +102,13 @@ def handler(request): artifacts=artifacts, use_worktrees=False, budget=100_000, timeout=5, ) - filtered = finish_reason == "content_filter" - expected_delivery = _FILTER_ERROR if filtered else visible - if filtered and visible: + stop_reason = { + "content_filter": _FILTER_REASON, + "length": _TRUNCATED_REASON, + "model_context_window_exceeded": _TRUNCATED_REASON, + }.get(finish_reason) + expected_delivery = f"Error: agent stopped: {stop_reason}" if stop_reason else visible + if stop_reason and visible: expected_delivery += f"\n\n[Partial response]\n{visible}" assert [row["model"] for row in requests] == [ "fixture-lead", "fixture-reviewer", "fixture-reviewer", "fixture-lead", @@ -102,32 +117,146 @@ def handler(request): assert result.status == "completed" assert result.output == f"Lead received: {expected_delivery}" assert result.tokens == 16 - assert [row["exception_type"] for row in result.agent_failures] == (["AgentStopped"] if filtered else []) + assert [row["exception_type"] for row in result.agent_failures] == (["AgentStopped"] if stop_reason else []) path = next(artifacts.glob("agent_1_*.json")) snapshot = app.read_session_snapshot(path) - assert snapshot["session_state"]["phase"] == ("stopped" if filtered else "done") - assert snapshot["session_state"]["terminal_reason"] == (_FILTER_REASON if filtered else "completed") + assert snapshot["session_state"]["phase"] == ("stopped" if stop_reason else "done") + assert snapshot["session_state"]["terminal_reason"] == (stop_reason or "completed") + recorded_text = terminal_reply.get("reasoning_content", visible) assert [row["content"] for row in snapshot["messages"] if row["role"] == "assistant"] == ( - [_INTERIM, visible] if visible else [_INTERIM] + [_INTERIM, recorded_text] if recorded_text else [_INTERIM] ) model = FakeLLMClient() env = LocalEnvironment(str(tmp_path)) restored = load_session(str(path), agent=Agent(name="reviewer", system_prompt="Read the inventory."), llm=model, env=env) try: - assert await restored.run_loop() == visible + if stop_reason == _TRUNCATED_REASON: + cursor = restored.state.completed_turn_start_message_index + terminal_text = snapshot["messages"][cursor]["content"] if cursor is not None else "" + assert terminal_text == visible + else: + assert await restored.run_loop() == visible assert model.calls == [] finally: await restored.aclose() await env.cleanup() +@pytest.mark.parametrize("capture_cancelled", [False, True], ids=["io-error", "cancelled"]) +async def test_team_delivers_stop_notice_after_borrowed_environment_capture_fails( + tmp_path, monkeypatch, capture_cancelled, +): + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(tmp_path / "usage.jsonl")) + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + workspace = tmp_path / "workspace" + workspace.mkdir() + (workspace / "inventory.txt").write_text("verified inventory: 42\n", encoding="utf-8") + team = tmp_path / "team.yaml" + team.write_text( + "entry: lead\nroles:\n" + " lead:\n model: fixture-lead\n prompt: Ask for the subtotal.\n" + " tools: [message_agent]\n budget: {tokens: 16000}\n" + " reviewer:\n model: fixture-reviewer\n prompt: Total the inventory.\n" + " tools: [file_read, message_agent]\n budget: {tokens: 8000}\n" + " checker:\n model: fixture-checker\n prompt: Confirm the units.\n" + " tools: [message_agent]\n budget: {tokens: 8000}\n" + "topology:\n lead: [reviewer, checker]\n reviewer: [lead]\n checker: [lead]\n", + encoding="utf-8", + ) + initial_capture = asyncio.Event() + reviewer_capture = asyncio.Event() + checker_capture = asyncio.Event() + checker_driver = None + captures = 0 + + class BorrowedEnvironment(LocalEnvironment): + async def capture_changes(self): + nonlocal captures, checker_driver + captures += 1 + if captures == 1: + initial_capture.set() + elif captures == 2: + reviewer_capture.set() + await checker_capture.wait() + assert checker_driver is not None + await asyncio.wait({checker_driver}) + if not capture_cancelled: + raise OSError("Capture I/O failed.") + worker = asyncio.create_task(asyncio.Event().wait()) + worker.cancel() + await worker + elif captures == 3: + checker_driver = asyncio.current_task() + checker_capture.set() + return "" + + calls = [] + notices = [] + + async def handler(request): + body = json.loads(request.content) + model = body["model"] + calls.append(model) + count = calls.count(model) + if model == "fixture-lead": + if count == 1: + questions = [{ + "id": role, "type": "function", "function": { + "name": "message_agent", "arguments": json.dumps({ + "to_role": role, "summary": "Inventory", "content": "Check the inventory.", + }), + }, + } for role in ("reviewer", "checker")] + return _chat_reply(request, model, len(calls), "tool_calls", {"tool_calls": questions}) + if count == 2: + return completion_http_response(request, text="Waiting for the subtotal.") + assert count == 3 + notices.append(body["messages"][-1]["content"]) + return completion_http_response(request, text="The Reviewer stopped.") + if model == "fixture-checker": + assert count == 1 + await reviewer_capture.wait() + return completion_http_response(request, text="The inventory uses unit counts.") + assert model == "fixture-reviewer" + if count == 1: + return _chat_reply(request, model, len(calls), "tool_calls", _inventory_read()) + assert count == 2 + assert "verified inventory: 42" in body["messages"][-1]["content"] + await initial_capture.wait() + return _chat_reply(request, model, len(calls), "length", {"content": _PARTIAL}) + + install_sdk_transport(monkeypatch, "openai", handler) + env = BorrowedEnvironment(str(workspace)) + app = OpenCollab( + workspace, environment=env, model="fixture-lead", provider="openai", + api_key="controlled-test", # pragma: allowlist secret + base_url="https://fixture.invalid/v1", + config={"llm_max_retries": 0, "wire_protocol": "chat_completions", "llm_stream_chat": False}, + ) + try: + result = await app.team( + "Check the inventory.", config=team, artifacts=tmp_path / "artifacts", + use_worktrees=False, prebuild_team=True, serialize_turns=False, timeout=5, + ) + assert await env.read_file("inventory.txt") == "verified inventory: 42\n" + finally: + await env.cleanup() + + assert (result.status, result.output, result.tokens) == ("completed", "The Reviewer stopped.", 24) + assert [row["exception_type"] for row in result.agent_failures] == ["AgentStopped"] + notice, = notices + assert " sequence: + sequence = record["sequence"] + phase = record["meta"]["session_state"]["phase"] + if phase == terminal_phase and sequence < candidate["_autosave_sequence"]: + checkpoint_failed = True + raise OSError(errno.EIO, "terminal checkpoint rename failed") + return replace(source, destination, **kwargs) + + if checkpoint_error: + monkeypatch.setattr(os, "replace", fail_terminal_checkpoint) + try: + result = await app.team( + "Report the verified inventory subtotal.", config=team, artifacts=artifacts, trace=True, + use_worktrees=False, prebuild_team=True, serialize_turns=True, budget=100_000, timeout=timeout, + ) + finally: + if environment is not None: + await environment.cleanup() + assert len(lead_requests) == 3 + int(initial_answer is None) + int(reads_inventory) assert len(worker_requests) == 2 rows = [json.loads(line) for line in (artifacts / "trajectory.jsonl").read_text(encoding="utf-8").splitlines()] lead_completed = next( @@ -242,10 +502,33 @@ def handler(request): row["step"] for row in rows if row["type"] == "message_sent" and row["payload"]["from_aid"] == 1 ) assert lead_completed < worker_sent - filtered = finish_reason == "content_filter" - assert (result.output, result.status, result.reason) == ( - output, "stopped" if filtered else "completed", _FILTER_REASON if filtered else None, - ) + assert result.output == output + snapshots = [app.read_session_snapshot(path) for path in sorted(artifacts.glob("agent_*.json"))] + assert len(snapshots) == 2 + lead = snapshots[0] + usage = [json.loads(line) for line in (tmp_path / "usage.jsonl").read_text(encoding="utf-8").splitlines()] + assert result.tokens == sum(row["usage"]["total_tokens"] for row in usage) + assert result.tokens == sum(snapshot["session_state"]["used_tokens"] for snapshot in snapshots) + assert capture_failed == (finish_reason == "diff-error") + assert checkpoint_failed == checkpoint_error + if finish_reason == "provider-error": + assert result.status == "failed" and provider_message in result.reason + assert lead["messages"][-2]["content"] == _INTERIM + assert lead["messages"][-2]["tool_calls"][0]["id"] == "read-inventory" + elif finish_reason == "diff-error" or checkpoint_error: + assert result.status == "failed" + assert lead["session_state"]["phase"] == "error" + cursor = lead["session_state"]["completed_turn_start_message_index"] + if expected_reply := message.get("content"): + assert cursor is not None + assert [row["content"] for row in lead["messages"][cursor:] if row["role"] == "assistant" + and not row.get("tool_calls")] == [expected_reply] + if checkpoint_error: + assert "terminal checkpoint rename failed" in result.reason + assert lead["session_state"]["terminal_reason"] == result.reason + else: + reason = {"content_filter": _FILTER_REASON, "length": _TRUNCATED_REASON}.get(finish_reason) + assert (result.status, result.reason) == ("stopped" if reason else "completed", reason) @pytest.mark.parametrize( @@ -254,9 +537,10 @@ def handler(request): ("content_filter", "ResponsesTerminalEventError", None), ("invalid_prompt", "ResponsesTerminalEventError", None), ("rate_limit_exceeded", "ResponsesTransientEventError", 429), + ("rate_limit_error", "RateLimitError", 429), ], ) -async def test_team_keeps_typed_responses_failure_metadata(tmp_path, monkeypatch, code, exception_type, status_code): +async def test_team_keeps_responses_failure_metadata(tmp_path, monkeypatch, code, exception_type, status_code): monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(tmp_path / "usage.jsonl")) team = tmp_path / "team.yaml" team.write_text( @@ -285,6 +569,10 @@ def handler(request): items = [function_item("delegate", "spawn_agent", '{"role":"reviewer","task":"Review the subtotal."}')] else: assert len(requests) == 2 and model == "gpt-4o-mini" + if code == "rate_limit_error": + return http_response(request, 429, json={ + "error": {"type": code, "message": "The inventory provider reported an error."}, + }) if code == "content_filter": status = "incomplete" incomplete = {"reason": code} @@ -316,7 +604,10 @@ def handler(request): ) assert len(requests) == 3 - assert (result.status, result.output, result.tokens) == ("completed", "Recorded the reviewer's outcome.", 12) + expected_tokens = 8 if code == "rate_limit_error" else 12 + assert (result.status, result.output, result.tokens) == ( + "completed", "Recorded the reviewer's outcome.", expected_tokens, + ) assert result.agent_failures == ({ "label": "reviewer", "exception_type": exception_type, diff --git a/tests/interfaces/test_sdk_team_initial_checkout_deadline.py b/tests/interfaces/test_sdk_team_initial_checkout_deadline.py new file mode 100644 index 00000000..c63ca7f5 --- /dev/null +++ b/tests/interfaces/test_sdk_team_initial_checkout_deadline.py @@ -0,0 +1,157 @@ +from __future__ import annotations + +import asyncio +from pathlib import Path + +import pytest + +from opencollab import OpenCollab +from opencollab.adapters.env import LocalEnvironment +from opencollab.adapters.llm.types import LLMResponse, Usage +from opencollab.adapters.worktree_pool import WorktreePool +from opencollab.application.async_timeout import await_owned_operation +from opencollab.bootstrap import container, programmatic +from tests.interfaces.test_session_isolation import _repo + + +@pytest.mark.parametrize("mode", ["success", "deadline", "caller", "caller-settles", "shared-budget", "failure"]) +async def test_team_initial_checkout_respects_deadline_and_cancellation(tmp_path, monkeypatch, mode): + workspace = tmp_path / "source" + workspace.mkdir() + _repo(workspace, dirty=False) + entered, finish_setup, setup_done, released = (asyncio.Event() for _ in range(4)) + built = [] + requests = [] + objects = {} + cancellations = [] + preparation_failure = OSError("checkout preparation failed") + + class Model: + def __init__(self, **kwargs): + pass + + def context_window(self): + return 100_000 + + async def complete(self, messages, **kwargs): + requests.append(messages) + if mode == "shared-budget": + await asyncio.Event().wait() + return LLMResponse(content="Inventory approved.", usage=Usage(3, 2), finish_reason="stop") + + async def close(self): + pass + + class DelayedCheckout(WorktreePool): + async def acquire(self, role, *, source=None): + async def configure(): + env = await super(DelayedCheckout, self).acquire(role, source=source) + objects["checkout"] = Path(env.workspace) + entered.set() + await finish_setup.wait() + objects["seed"] = await env.read_file("seed.txt") + setup_done.set() + if mode == "failure": + raise preparation_failure + return env + + if mode != "caller-settles": + return await await_owned_operation(configure(), propagate_cancellation=True) + owner = asyncio.create_task(configure()) + while True: + try: + return await asyncio.shield(owner) + except asyncio.CancelledError: + finish_setup.set() + + async def release(self): + await super().release() + released.set() + if mode == "failure": + raise OSError("checkout release receipt failed") + + def provider(**options): + pool = DelayedCheckout(use_worktrees=True, **options) + objects["pool"] = pool + return pool + + original = programmatic.build_scheduler + + def build(*args, **kwargs): + scheduler = original(*args, **kwargs) + built.append(scheduler) + return scheduler + + monkeypatch.setattr(container, "LLMClient", Model) + monkeypatch.setattr(programmatic, "build_scheduler", build) + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(tmp_path / "usage.jsonl")) + config = tmp_path / "team.yaml" + config.write_text("entry: lead\nroles:\n lead:\n prompt: Verify inventory.\n tools: []\n") + artifacts = tmp_path / "artifacts" + source = LocalEnvironment(str(workspace)) + app = OpenCollab(workspace, environment=source, environment_providers={"reports": provider}) + timeout = {"deadline": 1.2, "shared-budget": 3.4}.get(mode) + + async def run(): + try: + return await app.team( + "Verify the inventory.", config=config, budget=50_000, use_worktrees=False, + isolation="reports", timeout=timeout, + cleanup_timeout=.1, artifacts=artifacts, trace=True, + ) + except asyncio.CancelledError as exc: + cancellations.append(exc.args) + raise + + if mode in {"success", "failure"}: + finish_setup.set() + running = asyncio.create_task(run()) + try: + await asyncio.wait_for(entered.wait(), 5) + if mode.startswith("caller"): + running.cancel("caller interrupted Lead checkout") + if mode == "shared-budget": + await asyncio.sleep(1.8) + finish_setup.set() + done, _ = await asyncio.wait({running}, timeout=2.45 if mode == "shared-budget" else 2.8) + before_finish = bool(done) + print(f"mode={mode!r} returned_before_release={before_finish} models_at_return={len(requests)}") + if mode == "caller" or mode == "deadline": + assert objects["checkout"].is_dir() and not setup_done.is_set() and not released.is_set() + finish_setup.set() + result, = await asyncio.gather(running, return_exceptions=True) + print(f"outcome={getattr(result, 'status', type(result).__name__)!r} model_requests={len(requests)}") + assert before_finish + if mode.startswith("caller"): + assert isinstance(result, asyncio.CancelledError) + assert cancellations == [("caller interrupted Lead checkout",)] + elif mode == "failure": + assert result is preparation_failure + assert any("checkout release receipt failed" in note for note in result.__notes__) + elif mode == "deadline": + assert (result.status, result.reason, result.tokens, result.output) == ("stopped", "timeout", 0, None) + assert result.metrics["sessions"] == 0 and result.metrics["execution_quiesced"] is False + elif mode == "shared-budget": + assert (result.status, result.reason, result.tokens, result.output) == ("stopped", "timeout", 0, None) + assert result.metrics["sessions"] == 1 + else: + assert (result.status, result.tokens, result.output) == ("completed", 5, "Inventory approved.") + + await asyncio.wait_for(setup_done.wait(), 5) + await asyncio.wait_for(released.wait(), 5) + assert objects["seed"] == "initial" + assert not objects["checkout"].exists() + assert await source.read_file("seed.txt") == "initial" + initialized = mode in {"success", "shared-budget"} + assert len(requests) == len(built) == int(initialized) + assert (artifacts / "team.json").exists() is initialized + finally: + finish_setup.set() + await asyncio.gather(running, return_exceptions=True) + if entered.is_set(): + await asyncio.wait_for(setup_done.wait(), 5) + if built: + await built[0].cleanup() + elif "pool" in objects and not released.is_set(): + await objects["pool"].release() + await source.cleanup() diff --git a/tests/interfaces/test_sdk_team_late_close.py b/tests/interfaces/test_sdk_team_late_close.py new file mode 100644 index 00000000..12d5bdec --- /dev/null +++ b/tests/interfaces/test_sdk_team_late_close.py @@ -0,0 +1,135 @@ +from __future__ import annotations + +import asyncio +from pathlib import Path + +import pytest + +from opencollab import OpenCollab +from opencollab.adapters.env import LocalEnvironment +from opencollab.adapters.llm.types import LLMResponse, Usage +from opencollab.adapters.worktree_pool import WorktreePool +from opencollab.bootstrap import container, programmatic +from tests.interfaces.test_session_isolation import _repo + + +@pytest.mark.parametrize("source_owner", ["sdk", "caller"]) +@pytest.mark.parametrize("close_mode", ["immediate", "late", "retry", "attached-runtime"]) +async def test_team_returns_worktree_after_provider_close_settles(tmp_path, monkeypatch, source_owner, close_mode): + workspace = tmp_path / "source" + workspace.mkdir() + _repo(workspace, dirty=False) + entered, finish, closed, removed = (asyncio.Event() for _ in range(4)) + objects = {} + + class LocalModel: + def __init__(self, **kwargs): + pass + + def context_window(self): + return 100_000 + + async def complete(self, messages, **kwargs): + return LLMResponse(content="Inventory sent.", usage=Usage(3, 2), finish_reason="stop") + + async def close(self): + entered.set() + while not finish.is_set(): + try: + await finish.wait() + except asyncio.CancelledError: + pass + try: + objects["report"] = await objects["entry"].read_file("seed.txt") + finally: + closed.set() + + class RecordingPool(WorktreePool): + async def acquire(self, role, *, source=None): + environment = await super().acquire(role, source=source) + objects["entry"] = environment + return environment + + async def release_env(self, environment): + await super().release_env(environment) + removed.set() + + def provider(**options): + pool = RecordingPool(use_worktrees=True, **options) + objects["pool"] = pool + return pool + + build_scheduler = programmatic.build_scheduler + + def remember_scheduler(*args, **kwargs): + scheduler = build_scheduler(*args, **kwargs) + objects["scheduler"] = scheduler + if close_mode == "attached-runtime": + run = scheduler.run + objects["runtime_reads"] = [] + + async def close_report(): + entered.set() + await finish.wait() + objects["runtime_reads"].append(await objects["entry"].read_file("seed.txt")) + + async def run_with_report(prompt): + output = await run(prompt) + scheduler.lead_session.own_runtime(close_report) + return output + + monkeypatch.setattr(scheduler, "run", run_with_report) + return scheduler + + monkeypatch.setattr(programmatic, "build_scheduler", remember_scheduler) + monkeypatch.setattr(container, "LLMClient", LocalModel) + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(tmp_path / "usage.jsonl")) + team = tmp_path / "team.yaml" + team.write_text("entry: lead\nroles:\n lead:\n tools: []\n prompt: Report the inventory.\n") + caller_env = LocalEnvironment(str(workspace)) if source_owner == "caller" else None + if close_mode == "immediate": + finish.set() + app = OpenCollab(workspace, environment=caller_env, environment_providers={"reports": provider}) + operation = asyncio.create_task(app.team("Report the inventory.", config=team, + isolation="reports", trace=False, cleanup_timeout=.1)) + try: + await asyncio.wait_for(entered.wait(), 5) + done, _ = await asyncio.wait({operation}, timeout=2) + assert operation in done + result = await operation + checkout = Path(objects["entry"].workspace) + print(f"source={source_owner} mode={close_mode} status={result.status!r} output={result.output!r} " + f"tokens={result.tokens} checkout_at_return={checkout.exists()}") + assert result.output == "Inventory sent." and result.tokens == 5 + assert result.status == ("completed" if close_mode == "immediate" else "failed") + if close_mode != "immediate": + assert checkout.is_dir() and not closed.is_set() and not removed.is_set() + if close_mode == "retry": + try: + with pytest.raises(RuntimeError, match="session resource close failed or timed out"): + await asyncio.wait_for(objects["scheduler"].cleanup(cleanup_timeout=.1), 2) + finally: + print(f"checkout during retry={checkout.is_dir()} released={removed.is_set()}") + assert checkout.is_dir() and not removed.is_set() + finish.set() + await asyncio.wait_for(closed.wait(), 5) + assert objects["report"] == "initial" + try: + await asyncio.wait_for(removed.wait(), 3) + except asyncio.TimeoutError: + pytest.fail("Team retained the Git worktree after its provider close settled") + assert not checkout.exists() + if close_mode == "attached-runtime": + await objects["scheduler"].cleanup() + assert objects["runtime_reads"] == ["initial"] + if caller_env is not None: + assert await caller_env.read_file("seed.txt") == "initial" + finally: + finish.set() + await asyncio.gather(operation, return_exceptions=True) + if entered.is_set(): + await asyncio.wait_for(closed.wait(), 5) + if "scheduler" in objects: + await objects["scheduler"].cleanup() + if caller_env is not None: + await caller_env.cleanup() diff --git a/tests/interfaces/test_sdk_team_parent_handoff.py b/tests/interfaces/test_sdk_team_parent_handoff.py index 6cb8dfd3..10bc544e 100644 --- a/tests/interfaces/test_sdk_team_parent_handoff.py +++ b/tests/interfaces/test_sdk_team_parent_handoff.py @@ -49,11 +49,11 @@ def capture_scheduler(self, *args, **kwargs): original_init(self, *args, **kwargs) schedulers.append(self) - async def save_after_child_delivery(self): + async def save_after_child_delivery(self, **kwargs): if checkpoint_tail and self.agent.name == "lead" and self.state.phase is SessionPhase.AWAITING_EVENTS: checkpoint_entered.set() await children_delivered.wait() - await original_checkpoint(self) + await original_checkpoint(self, **kwargs) async def capture_delivery(self, *args, **kwargs): nonlocal deliveries diff --git a/tests/interfaces/test_sdk_team_prebuild_deadline.py b/tests/interfaces/test_sdk_team_prebuild_deadline.py new file mode 100644 index 00000000..bca77568 --- /dev/null +++ b/tests/interfaces/test_sdk_team_prebuild_deadline.py @@ -0,0 +1,163 @@ +from __future__ import annotations + +import asyncio +from pathlib import Path + +import pytest + +from opencollab import OpenCollab +from opencollab.adapters.env import LocalEnvironment +from opencollab.adapters.llm.types import LLMResponse, Usage +from opencollab.adapters.worktree_pool import WorktreePool +from opencollab.application.async_timeout import await_owned_operation +from opencollab.bootstrap import container, programmatic +from tests.interfaces.test_session_isolation import _repo + + +@pytest.mark.parametrize("stop", [ + "none", "deadline", "caller", "retry", "deadline-settles", "caller-settles", + "caller-unbounded", "caller-unbounded-settles", +]) +async def test_team_deadline_during_owned_prebuild_releases_after_startup_stops(tmp_path, monkeypatch, stop): + workspace = tmp_path / "source" + workspace.mkdir() + _repo(workspace, dirty=False) + entered, continue_setup, setup_done, pool_released = (asyncio.Event() for _ in range(4)) + objects = {} + requests = [] + caller_stops = stop.startswith("caller") + deadline_stops = stop in {"deadline", "retry", "deadline-settles"} + finishes_on_cancel = stop.endswith("-settles") + deadline = 1.5 if deadline_stops else None if stop.startswith("caller-unbounded") else 8 + + class LocalModel: + def __init__(self, **kwargs): + pass + + def context_window(self): + return 100_000 + + async def complete(self, messages, **kwargs): + requests.append(messages) + return LLMResponse(content="Inventory approved.", usage=Usage(3, 2), finish_reason="stop") + + async def close(self): + pass + + class DelayedWorktreePool(WorktreePool): + async def acquire(self, role, *, source=None): + async def configure_checkout(): + env = await super(DelayedWorktreePool, self).acquire(role, source=source) + objects["worker"] = env + entered.set() + await continue_setup.wait() + objects["read"] = await env.read_file("seed.txt") + setup_done.set() + return env + + if not finishes_on_cancel: + return await await_owned_operation(configure_checkout(), propagate_cancellation=True) + owner = asyncio.create_task(configure_checkout()) + while True: + try: + return await asyncio.shield(owner) + except asyncio.CancelledError: + continue_setup.set() + + async def release(self): + await super().release() + pool_released.set() + + def provider(**options): + return DelayedWorktreePool(use_worktrees=True, **options) + + original = programmatic.build_scheduler + + def build(*args, **kwargs): + scheduler = original(*args, **kwargs) + objects["scheduler"] = scheduler + return scheduler + + monkeypatch.setattr(container, "LLMClient", LocalModel) + monkeypatch.setattr(programmatic, "build_scheduler", build) + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(tmp_path / "usage.jsonl")) + config = tmp_path / "team.yaml" + config.write_text("""entry: lead +roles: + lead: + prompt: Report the inventory. + tools: [message_agent] + worker: + prompt: Verify the inventory. + tools: [] + isolation: reports +topology: + lead: [worker] + worker: [] +""") + source = LocalEnvironment(str(workspace)) + app = OpenCollab(workspace, environment=source, environment_providers={"reports": provider}) + cancellation = [] + + async def run(): + try: + return await app.team( + "Report the inventory.", config=config, budget=50_000, prebuild_team=True, use_worktrees=False, + timeout=deadline, cleanup_timeout=.1, + artifacts=tmp_path / "artifacts", trace=False, + ) + except asyncio.CancelledError as exc: + cancellation.append(exc.args) + raise + + if stop == "none": + continue_setup.set() + operation = asyncio.create_task(run()) + try: + try: + await asyncio.wait_for(entered.wait(), 5) + except asyncio.TimeoutError: + if operation.done(): + pytest.fail(f"Team stopped before worker setup: {operation.result()!r}") + raise + checkout = Path(objects["worker"].workspace) + if caller_stops: + operation.cancel("caller interrupted team preparation") + done, _ = await asyncio.wait({operation}, timeout=3) + print(f"stop={stop!r} returned_while_held={operation in done} checkout_present={checkout.exists()} " + f"requests={len(requests)}") + assert operation in done + if caller_stops: + with pytest.raises(asyncio.CancelledError): + await operation + assert cancellation == [("caller interrupted team preparation",)] + else: + result = await operation + if deadline_stops: + assert (result.status, result.reason, result.tokens, result.output) == ("stopped", "timeout", 0, None) + if not finishes_on_cancel: + assert result.metrics["execution_quiesced"] is False + else: + assert (result.status, result.output, result.tokens) == ("completed", "Inventory approved.", 5) + if stop != "none" and not finishes_on_cancel: + assert not setup_done.is_set() and not pool_released.is_set() + assert checkout.is_dir() and not requests + if stop == "retry": + with pytest.raises(RuntimeError, match="execution tasks did not quiesce"): + await asyncio.wait_for(objects["scheduler"].cleanup(cleanup_timeout=.1), 2) + assert checkout.is_dir() and not pool_released.is_set() + continue_setup.set() + await asyncio.wait_for(setup_done.wait(), 5) + assert objects["read"] == "initial" + await asyncio.wait_for(pool_released.wait(), 5) + assert not checkout.exists() + assert await source.read_file("seed.txt") == "initial" + assert len(requests) == (1 if stop == "none" else 0) + finally: + continue_setup.set() + await asyncio.gather(operation, return_exceptions=True) + if entered.is_set(): + await asyncio.wait_for(setup_done.wait(), 5) + if "scheduler" in objects: + await objects["scheduler"].cleanup() + await source.cleanup() diff --git a/tests/interfaces/test_sdk_team_recovery_interruption.py b/tests/interfaces/test_sdk_team_recovery_interruption.py new file mode 100644 index 00000000..e499fd2d --- /dev/null +++ b/tests/interfaces/test_sdk_team_recovery_interruption.py @@ -0,0 +1,419 @@ +from __future__ import annotations + +import asyncio +import json +from types import SimpleNamespace + +import pytest +from typer.testing import CliRunner + +from opencollab import OpenCollab +from opencollab.adapters.cli import main as cli_main +from opencollab.adapters.cli.turn_queue import TurnQueue +from opencollab.application.scheduler_types import SchedulerTurnError +from opencollab.bootstrap import build_scheduler +from opencollab.bootstrap.config import build_config +from opencollab.bootstrap.runtime_context import build_runtime_context +from opencollab.domain.session import SessionPhase +from tests.support.provider_sdk_http import completion_http_response, http_response, install_sdk_transport + + +def _tool_reply(request, *calls): + return http_response(request, 200, json={ + "id": "chat-team-recovery", "object": "chat.completion", "created": 1, + "model": json.loads(request.content)["model"], + "choices": [{"index": 0, "finish_reason": "tool_calls", "message": { + "role": "assistant", "content": None, + "tool_calls": [ + {"id": call_id, "type": "function", "function": { + "name": name, "arguments": json.dumps(args), + }} + for call_id, name, args in calls + ], + }}], + "usage": {"prompt_tokens": 2, "completion_tokens": 2, "total_tokens": 4}, + }) + + +@pytest.mark.parametrize( + ("interruption", "submit"), + [("cancel", True), ("timeout", True), ("cooperative", True), ("cooperative", False)], +) +async def test_interrupted_team_recovery_keeps_accepted_submission(tmp_path, monkeypatch, interruption, submit): + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(tmp_path / "usage.jsonl")) + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_LLM_MAX_RETRIES", "0") + team = tmp_path / "team.yaml" + team.write_text( + "entry: lead\nroles:\n" + " lead:\n model: lead-fixture\n prompt: Report the verified table count.\n" + " tools: [spawn_agent, submit]\n" + " reviewer:\n model: reviewer-fixture\n prompt: Review the table.\n" + " tools: []\ntopology:\n lead: [reviewer]\n reviewer: []\n", + encoding="utf-8", + ) + + original_prompt = "Review the table." + queued_prompt = "Follow up on the table review." + final_prompt = "Recall the previously submitted count." + summary = "The verified table contains 17 rows." + restored_reply = "The previous submission reported 17 rows." + original_review_started = asyncio.Event() + original_review_release = asyncio.Event() + recovery_review_started = asyncio.Event() + recovery_review_cancelled = asyncio.Event() + late_review_returned = asyncio.Event() + final_requests = [] + stage = "original" + + async def handler(request): + body = json.loads(request.content) + messages = body["messages"] + if stage == "final": + final_requests.append((body["model"], messages)) + return completion_http_response(request, text=restored_reply) + if body["model"] == "reviewer-fixture": + if stage == "original": + original_review_started.set() + await original_review_release.wait() + return completion_http_response(request, text="Original table reviewed.") + recovery_review_started.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + recovery_review_cancelled.set() + if interruption != "cooperative": + raise + await asyncio.sleep(0) + late_review_returned.set() + return completion_http_response(request, text="Late reviewer result.") + tool_rows = [row for row in messages if row["role"] == "tool"] + if stage == "original": + if tool_rows: + return completion_http_response(request, text="Original answer.") + return _tool_reply(request, ("original-review", "spawn_agent", { + "role": "reviewer", "task": "Review the original table.", + })) + assert messages[-1]["role"] == "tool" + assert messages[-1]["tool_call_id"] == "original-review" + assert messages[-1]["content"] == "deferred child interrupted by session restore" + calls = [("recovery-review", "spawn_agent", {"role": "reviewer", "task": "Check the next table."})] + if submit: + calls.append(("submit-count", "submit", {"summary": summary})) + return _tool_reply(request, *calls) + + install_sdk_transport(monkeypatch, "openai", handler) + provider = { + "provider": "openai", "model": "lead-fixture", "api_key": "team-test-token", # pragma: allowlist secret + "base_url": "https://fixture.invalid/v1", + } + transport = {"wire_protocol": "chat_completions", "llm_stream_chat": False, "llm_max_retries": 0} + app = OpenCollab(tmp_path, config=transport, **provider) + + async def await_suspension(directory, *, submitted_summary=None, pending_call=None): + while True: + for path in directory.glob("agent_0_*.json"): + snapshot = app.read_session_snapshot(path) + state = snapshot["session_state"] + if ( + state["phase"] == "awaiting_events" + and state["submitted_summary"] == submitted_summary + and (pending_call is None or any( + row["tool_call_id"] == pending_call and row["status"] == "pending" + for row in state["pending_events"] + )) + ): + return path, snapshot + await asyncio.sleep(0.005) + + original_dir = tmp_path / "original" + original = asyncio.create_task(app.team( + original_prompt, config=team, artifacts=original_dir, + use_worktrees=False, trace=False, budget=100_000, timeout=10, + )) + try: + await asyncio.wait_for(original_review_started.wait(), 5) + _, original_snapshot = await asyncio.wait_for(await_suspension(original_dir), 5) + checkpoint = tmp_path / "checkpoint.json" + checkpoint.write_text(json.dumps(original_snapshot), encoding="utf-8") + finally: + original_review_release.set() + first_result = await asyncio.wait_for(original, 5) + assert first_result.status == "completed" + + stage = "recovery" + cfg = build_config(str(tmp_path), overrides={**provider, **transport, "budget": 100_000}) + context = build_runtime_context(str(tmp_path), cfg.model_dump(), trace=False) + recovery_dir = tmp_path / "recovery" + scheduler = build_scheduler( + context, use_worktrees=False, interactive=True, team_config_path=team, + session_file=str(checkpoint), save_dir=recovery_dir, + ) + async def run_queued(prompt, aid, cancel_event): + await scheduler.run_turn(aid, prompt, cancel_event=cancel_event) + + queue = TurnQueue(run_queued) + if interruption == "cooperative": + active = asyncio.create_task(queue.run()) + queue.submit(queued_prompt, 0) + else: + active = asyncio.create_task(scheduler.run(queued_prompt)) + try: + await asyncio.wait_for(recovery_review_started.wait(), 5) + recovery_path, accepted = await asyncio.wait_for( + await_suspension( + recovery_dir, submitted_summary=summary if submit else None, pending_call="recovery-review", + ), 5, + ) + pending_rows = [("recovery-review", "pending")] + if submit: + pending_rows.append(("submit-count", "done")) + accepted_rows = accepted["session_state"]["pending_events"] + assert [(row["tool_call_id"], row["status"]) for row in accepted_rows] == pending_rows + if interruption == "cooperative": + assert queue.interrupt() + with pytest.raises(SchedulerTurnError) as stopped: + await asyncio.wait_for(active, 5) + assert stopped.value.terminal_reason == "interrupted by user" + assert stopped.value.partial_answer == (summary if submit else None) + await asyncio.wait_for(late_review_returned.wait(), 5) + elif interruption == "cancel": + active.cancel() + with pytest.raises(asyncio.CancelledError): + await active + else: + with pytest.raises(asyncio.TimeoutError): + await asyncio.wait_for(active, 0) + assert recovery_review_cancelled.is_set() + finally: + if not active.done(): + active.cancel() + await asyncio.gather(active, return_exceptions=True) + await scheduler.cleanup() + + settled = app.read_session_snapshot(recovery_path) + stage = "final" + resumed = await asyncio.to_thread(CliRunner().invoke, cli_main.app, [ + "--workspace", str(tmp_path), "--team-config", str(team), "--no-worktrees", + "--provider", provider["provider"], "--model", provider["model"], "--api-key", provider["api_key"], + "--base-url", provider["base_url"], "--budget", "100000", "--session", str(recovery_path), + "--prompt", final_prompt, + ]) + assert resumed.exit_code == 0, (resumed.output, resumed.exception) + assert restored_reply in resumed.output + assert [model for model, _ in final_requests] == ["lead-fixture"] + messages = final_requests[0][1] + assert messages[-1] == {"role": "user", "content": final_prompt} + summary_message = {"role": "assistant", "content": summary} + assert messages.count(summary_message) == int(submit) + if submit: + assert messages[-2] == summary_message + assert [row["content"] for row in messages if row["role"] == "user"] == [original_prompt, final_prompt] + review_result = ( + "Error: agent cancelled before completing delegated work" if interruption == "cooperative" + else "Error: scheduler cleanup cancelled delegated work" + ) + tools = [ + ("original-review", "deferred child interrupted by session restore"), + ("recovery-review", review_result), + ] + if submit: + tools.append(("submit-count", "Submitted. Your turn ends here.")) + assert [(row["tool_call_id"], row["content"]) for row in messages if row["role"] == "tool"] == tools + assert settled["session_state"]["phase"] == "stopped" + assert settled["session_state"]["pending_events"] == [] + assert settled["session_state"]["submitted_summary"] is None + assert sum(row.get("content") == summary for row in settled["messages"]) == int(submit) + if submit: + assert settled["messages"][-1]["content"] == summary + + +@pytest.mark.parametrize( + ("exit_input", "submit"), + [("interrupt", True), ("eof", True), ("eof", False), ("after_drain", True)], +) +async def test_fresh_team_interrupt_then_exit_keeps_accepted_submission(tmp_path, monkeypatch, exit_input, submit): + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(tmp_path / "usage.jsonl")) + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + team = tmp_path / "team.yaml" + team.write_text( + "entry: lead\nroles:\n" + " lead:\n model: lead-fixture\n prompt: Report the verified table count.\n" + " tools: [spawn_agent, submit]\n" + " reviewer:\n model: reviewer-fixture\n prompt: Review the table.\n" + " tools: []\ntopology:\n lead: [reviewer]\n reviewer: []\n", + encoding="utf-8", + ) + + original = "Check the table and report its size." + followup = "Recall the previously submitted count." + summary = "The verified count is 17 rows." + late_review = "Late reviewer result." + started = asyncio.Event() + abandoned = asyncio.Event() + release = asyncio.Event() + returned = asyncio.Event() + final_requests = [] + restoring = False + + async def handler(request): + body = json.loads(request.content) + if restoring: + final_requests.append(body) + return completion_http_response(request, text="Follow-up complete.") + if body["model"] == "reviewer-fixture": + started.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + abandoned.set() + await release.wait() + returned.set() + return completion_http_response(request, text=late_review) + assert body["messages"][-1]["content"] == original + calls = [("review", "spawn_agent", {"role": "reviewer", "task": "Review the appendix."})] + if submit: + calls.append(("submit-count", "submit", {"summary": summary})) + return _tool_reply(request, *calls) + + install_sdk_transport(monkeypatch, "openai", handler) + provider = { + "provider": "openai", "model": "lead-fixture", "api_key": "team-test-token", # pragma: allowlist secret + "base_url": "https://fixture.invalid/v1", + } + transport = {"wire_protocol": "chat_completions", "llm_stream_chat": False, "llm_max_retries": 0} + cfg = build_config(str(tmp_path), overrides={**provider, **transport, "budget": 100_000}) + context = build_runtime_context(str(tmp_path), cfg.model_dump(), trace=False) + artifacts = tmp_path / "fresh" + scheduler = build_scheduler( + context, use_worktrees=False, interactive=True, team_config_path=team, + save_dir=artifacts, cleanup_timeout=2, + ) + lead = scheduler.lead_session + checkpoint = lead._checkpoint_terminal_snapshot + checkpoint_published = asyncio.Event() + driver_cancelled = asyncio.Event() + + async def checkpoint_then_hold(**kwargs): + suspended = lead.state.phase is SessionPhase.AWAITING_EVENTS + await checkpoint(**kwargs) + if suspended: + checkpoint_published.set() + try: + await asyncio.Event().wait() + finally: + driver_cancelled.set() + + if exit_input != "after_drain": + monkeypatch.setattr(lead, "_checkpoint_terminal_snapshot", checkpoint_then_hold) + + completed_interrupts = [] + hard_cancellations = [] + + async def run_queued(prompt, aid, event): + try: + await scheduler.run_turn(aid, prompt, cancel_event=event) + except SchedulerTurnError as exc: + completed_interrupts.append((exc.terminal_reason, exc.partial_answer)) + except asyncio.CancelledError as exc: + hard_cancellations.append(exc) + raise + + queue = TurnQueue(run_queued) + + async def wait_for_submitted_turn(): + await started.wait() + if exit_input != "after_drain": + await checkpoint_published.wait() + while True: + for path in artifacts.glob("agent_0_*.json"): + snapshot = OpenCollab.read_session_snapshot(path) + state = snapshot["session_state"] + if state["phase"] != "awaiting_events": + continue + assert state["submitted_summary"] == (summary if submit else None) + pending = [("review", "pending"), ("submit-count", "done")] if submit else [("review", "pending")] + assert [(row["tool_call_id"], row["status"]) for row in state["pending_events"]] == pending + return + await asyncio.sleep(0.005) + + async def return_late_response(): + await abandoned.wait() + if exit_input != "after_drain": + while not scheduler._shutting_down: + await asyncio.sleep(0.001) + release.set() + + class Prompt: + reads = 0 + + async def read(self): + self.reads += 1 + if self.reads == 1: + return original + if self.reads == 2: + await wait_for_submitted_turn() + raise KeyboardInterrupt + await abandoned.wait() + assert queue.busy + if exit_input == "after_drain": + await queue.drain() + if exit_input == "interrupt": + raise KeyboardInterrupt + raise EOFError + + def deliver(self, _line): + return False + + def decline_pending(self): + return False + + prompt = Prompt() + late_response_task = asyncio.create_task(return_late_response()) + try: + await asyncio.wait_for(cli_main._drive( + queue, reader=cli_main._read_loop(prompt, queue, SimpleNamespace(selected_aid=0), scheduler.lead_session), + until_drained=False, + ), 6) + finally: + release.set() + late_response_task.cancel() + await asyncio.gather(late_response_task, return_exceptions=True) + await cli_main._await_scheduler_cleanup(scheduler, cleanup_timeout=2) + assert returned.is_set() + assert prompt.reads == 3 + if exit_input == "after_drain": + assert completed_interrupts == [("interrupted by user", summary)] + assert not hard_cancellations + else: + assert not completed_interrupts + assert len(hard_cancellations) == 1 + assert driver_cancelled.is_set() + + path = next(artifacts.glob("agent_0_*.json")) + saved = OpenCollab.read_session_snapshot(path) + state = saved["session_state"] + assert (state["phase"], state["terminal_reason"]) == ("stopped", "interrupted by user") + restoring = True + resumed = await asyncio.to_thread(CliRunner().invoke, cli_main.app, [ + "--workspace", str(tmp_path), "--team-config", str(team), "--no-worktrees", + "--provider", provider["provider"], "--model", provider["model"], "--api-key", provider["api_key"], + "--base-url", provider["base_url"], "--budget", "100000", "--session", str(path), "--prompt", followup, + ]) + assert resumed.exit_code == 0, (resumed.output, resumed.exception) + assert [body["model"] for body in final_requests] == ["lead-fixture"] + messages = final_requests[0]["messages"] + assert [row["content"] for row in messages if row["role"] == "user"] == [original, followup] + assert messages.count({"role": "assistant", "content": summary}) == int(submit) + tool_rows = [row for row in messages if row["role"] == "tool"] + assert [row["tool_call_id"] for row in tool_rows] == (["review", "submit-count"] if submit else ["review"]) + assert tool_rows[0]["content"].startswith("Error:") + if submit: + assert tool_rows[1]["content"] == "Submitted. Your turn ends here." + assert all(row.get("content") != late_review for row in messages) + assert state["pending_events"] == [] + assert state["submitted_summary"] is None diff --git a/tests/interfaces/test_sdk_team_registered_workflow_budget.py b/tests/interfaces/test_sdk_team_registered_workflow_budget.py new file mode 100644 index 00000000..219b84d6 --- /dev/null +++ b/tests/interfaces/test_sdk_team_registered_workflow_budget.py @@ -0,0 +1,131 @@ +from __future__ import annotations + +import json +import subprocess + +import pytest + +from opencollab.adapters.llm.types import LLMResponse, Usage +from opencollab.bootstrap import container +from opencollab.sdk import OpenCollab + +SOURCE = '''from pathlib import Path + +from opencollab import workflow + +async def write_report(ctx, args): + Path(ctx.workspace_root, "report.txt").write_text("prepared report\\n") + first = await ctx.agent("Prepare report summary.", tools=[]) + final = await ctx.agent("Write final title.", tools=[], over_budget_ok=args["one_more"]) + return {"summary": first, "title": final, "budget": ctx.budget.total} + +@workflow(name="local-report") +async def main(ctx, args): + if not args.get("candidate"): + return await write_report(ctx, args) + candidate = await ctx.candidate_workflow(write_report, args, label="report", budget=1000) + await ctx.adopt_candidate(candidate) + return {"candidate_output": candidate.output} +''' + + +@pytest.mark.parametrize( + "scene", ["ordinary", "escape", "candidate", "inherited", "default-team-budget", "top-level", "unbounded"], +) +async def test_registered_team_workflow_budget_and_top_level_escape(tmp_path, monkeypatch, scene): + workspace = tmp_path / "workspace" + workflows = workspace / "workflows" + workflows.mkdir(parents=True) + monkeypatch.delenv("OPENCOLLAB_WORKFLOWS_DIR", raising=False) + monkeypatch.delenv("OPENCOLLAB_UNBOUNDED_LIMITS", raising=False) + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", "") + (workflows / "local_report.py").write_text(SOURCE) + if scene == "candidate": + for command in ( + ("init", "-q"), ("add", "workflows/local_report.py"), + ("-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", + "-c", "commit.gpgsign=false", "commit", "-qm", "Prepare workflow fixture"), + ): + subprocess.run(["git", *command], cwd=workspace, check=True, capture_output=True) + config = tmp_path / "team.yaml" + config.write_text( + "entry: writer\nroles:\n writer:\n prompt: Writer\n" + " tools: [run_workflow]\n" + ) + seen = {} + calls = [] + inputs = {"one_more": scene != "ordinary", "candidate": scene == "candidate"} + direct = scene in {"top-level", "unbounded"} + + class Model: + def __init__(self, **kwargs): + pass + + def context_window(self): + return 200_000 + + def estimate_request_tokens(self, messages, tools=None, **kwargs): + return 10 + + async def close(self): + pass + + async def complete(self, messages, **kwargs): + prompt = next(message["content"] for message in messages if message["role"] == "user") + if prompt == "Prepare report summary.": + calls.append("summary") + return LLMResponse(content="Report summary", usage=Usage(978, 22), finish_reason="stop") + if prompt == "Write final title.": + calls.append("title") + return LLMResponse(content="Final title", usage=Usage(40, 10), finish_reason="stop") + replies = [message for message in messages if message["role"] == "tool"] + if not replies: + arguments = {"name": "local-report", "args": inputs} + if scene not in {"inherited", "default-team-budget"}: + arguments["budget"] = 1000 + call = { + "id": "local-report", "type": "function", "function": { + "name": "run_workflow", "arguments": json.dumps(arguments), + }, + } + return LLMResponse(tool_calls=[call], finish_reason="tool_calls", usage=Usage(3, 2)) + seen.update(json.loads(replies[-1]["content"])) + return LLMResponse(content="Report reviewed.", usage=Usage(3, 2), finish_reason="stop") + + if scene == "unbounded": + monkeypatch.setenv("OPENCOLLAB_UNBOUNDED_LIMITS", "true") + client = OpenCollab(workspace, model="offline-model", config={"max_output_tokens": 128}) + if direct: + result = await client.workflow( + "local-report", inputs, llm=Model(), budget=None if scene == "unbounded" else 1000, + limit_mode="environment" if scene == "unbounded" else "explicit", + trace=False, artifacts=tmp_path / "artifacts", timeout=12, + ) + seen.update(output=result.output, stop_reason=None, tokens=result.tokens) + else: + monkeypatch.setattr(container, "LLMClient", Model) + result = await client.team( + "Complete a local report.", config=config, budget=None if scene == "default-team-budget" else 6000, + trace=False, artifacts=tmp_path / "artifacts", use_worktrees=False, timeout=12, + ) + assert result.ok, (result.status, result.reason, result.error) + assert (workspace / "report.txt").read_text() == "prepared report\n" + allowed = direct or scene in {"inherited", "default-team-budget"} + assert calls == (["summary", "title"] if allowed else ["summary"]) + expected_child_tokens = 1050 if allowed else 1000 + assert seen["tokens"] == expected_child_tokens + assert result.tokens == expected_child_tokens + (0 if direct else 10) + if scene == "candidate": + assert seen["output"] == {"candidate_output": None} + assert seen["agent_failures"][0]["exception_type"] == "WorkflowBudgetExceeded" + elif allowed: + assert seen["output"]["title"] == "Final title" + assert seen["stop_reason"] is None + if scene in {"inherited", "default-team-budget"}: + assert seen["output"]["budget"] > seen["tokens"] + elif scene == "unbounded": + assert seen["output"]["budget"] is None + else: + assert seen["stop_reason"] == "budget_exceeded" diff --git a/tests/interfaces/test_sdk_team_start_hook.py b/tests/interfaces/test_sdk_team_start_hook.py index 1efed583..8cdf8f21 100644 --- a/tests/interfaces/test_sdk_team_start_hook.py +++ b/tests/interfaces/test_sdk_team_start_hook.py @@ -48,9 +48,7 @@ def _team(tmp_path, *, start_ending="success", child=False): first = record if start_ending == "error": first += "\nexit 3" - elif start_ending == "timeout": - first += "\nsleep 60" - start_timeout = 0.02 if start_ending == "timeout" else 2 + timed_hook = " - command: sleep 60\n timeout: 0.02\n" if start_ending == "timeout" else "" child_role = " worker:\n prompt: Worker role.\n tools: []\n" if child else "" lead_tools = "[file_read, spawn_agent]" if child else "[file_read]" topology = " lead: [worker]\n worker: []\n" if child else " lead: []\n" @@ -58,7 +56,8 @@ def _team(tmp_path, *, start_ending="success", child=False): path.write_text( "entry: lead\nroles:\n lead:\n prompt: Read the startup marker.\n" f" tools: {lead_tools}\n{child_role}topology:\n{topology}hooks:\n" - f" SessionStart:\n - command: {json.dumps(first)}\n timeout: {start_timeout}\n" + f" SessionStart:\n - command: {json.dumps(first)}\n timeout: 2\n" + f"{timed_hook}" " - command: 'printf INITIALIZED > startup.txt'\n" f" Stop:\n - command: {json.dumps(record)}\n" f" SubagentStop:\n - command: {json.dumps(record)}\n", @@ -66,7 +65,7 @@ def _team(tmp_path, *, start_ending="success", child=False): return path @pytest.mark.parametrize("start_ending", ["success", "error", "timeout"]) -async def test_public_team_start_initializes_before_file_read(tmp_path, monkeypatch, start_ending): +async def test_public_team_start_initializes_before_file_read(tmp_path, monkeypatch, caplog, start_ending): monkeypatch.setattr(container, "LLMClient", _Model) _Model.requests = [] team = _team(tmp_path, start_ending=start_ending) @@ -78,6 +77,10 @@ async def test_public_team_start_initializes_before_file_read(tmp_path, monkeypa assert result.output == "startup marker available" assert (tmp_path / "startup.txt").read_text() == "INITIALIZED" assert (tmp_path / "lifecycle.txt").read_text().splitlines() == ["SessionStart 0", "Stop 0"] + if start_ending == "error": + assert "hook command exited 3" in caplog.text + elif start_ending == "timeout": + assert "hook command timed out after 0.02s: sleep 60" in caplog.text assert any("INITIALIZED" in message.get("content", "") for message in _Model.requests[-1] if message["role"] == "tool") diff --git a/tests/interfaces/test_sdk_team_timeout_restore.py b/tests/interfaces/test_sdk_team_timeout_restore.py new file mode 100644 index 00000000..4f868754 --- /dev/null +++ b/tests/interfaces/test_sdk_team_timeout_restore.py @@ -0,0 +1,132 @@ +"""Restore a settled Team snapshot through the public CLI.""" + +import asyncio +import json + +import pytest +from typer.testing import CliRunner + +from opencollab import OpenCollab +from opencollab.adapters.cli import main as cli_main +from tests.support.provider_sdk_http import completion_http_response, http_response, install_sdk_transport + + +@pytest.mark.parametrize("outcome", ["completed", "timeout"]) +@pytest.mark.parametrize("submit_summary", [False, True]) +async def test_team_nested_turn_does_not_restart_after_settlement(tmp_path, monkeypatch, outcome, submit_summary): + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(tmp_path / "usage.jsonl")) + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_LLM_MAX_RETRIES", "0") + monkeypatch.chdir(tmp_path) + team = tmp_path / "team.yaml" + team.write_text( + "entry: lead\nroles:\n" + " lead:\n model: lead-fixture\n prompt: Assemble both results.\n tools: [spawn_agent, submit]\n" + " reviewer:\n model: reviewer-fixture\n prompt: Check the figures.\n tools: [spawn_agent]\n" + " reader:\n model: reader-fixture\n prompt: Return the measured value.\n tools: []\n" + "topology:\n lead: [reviewer]\n reviewer: [reader]\n reader: []\n", + encoding="utf-8", + ) + requests = [] + leaf_cancelled = asyncio.Event() + restoring = False + summary = "The first table contains eight observations." + + async def handler(request): + body = json.loads(request.content) + model = body["model"] + messages = body["messages"] + requests.append((model, messages)) + if restoring: + return completion_http_response(request, text="Restored answer.") + if model == "reader-fixture": + if outcome == "timeout": + try: + await asyncio.Event().wait() + finally: + leaf_cancelled.set() + return completion_http_response(request, text="Measured value is 42.") + tool_result = next((row["content"] for row in messages if row["role"] == "tool"), None) + if tool_result is not None: + return completion_http_response(request, text=tool_result) + role = "reviewer" if model == "lead-fixture" else "reader" + tool_calls = [{ + "id": f"{role}-call", "type": "function", "function": { + "name": "spawn_agent", "arguments": json.dumps({"role": role, "task": f"Run {role}."}), + }, + }] + if submit_summary and model == "lead-fixture": + tool_calls.append({ + "id": "submit-call", "type": "function", "function": { + "name": "submit", "arguments": json.dumps({"summary": summary}), + }, + }) + return http_response(request, 200, json={ + "id": f"delegate-{role}", "object": "chat.completion", "created": 1, "model": model, + "choices": [{"index": 0, "finish_reason": "tool_calls", "message": { + "role": "assistant", "content": None, "tool_calls": tool_calls, + }}], + "usage": {"prompt_tokens": 2, "completion_tokens": 2, "total_tokens": 4}, + }) + + install_sdk_transport(monkeypatch, "openai", handler) + app = OpenCollab( + tmp_path, provider="openai", model="lead-fixture", + api_key="team-test-token", # pragma: allowlist secret + base_url="https://fixture.invalid/v1", + config={"llm_max_retries": 0, "wire_protocol": "chat_completions", "llm_stream_chat": False}, + ) + artifacts = tmp_path / "artifacts" + result = await app.team( + "Check the figures.", config=team, artifacts=artifacts, trace=False, use_worktrees=False, + budget=100_000, timeout=2 if outcome == "timeout" else 5, cleanup_timeout=1, + ) + assert result.metrics["execution_quiesced"] is True + assert [model for model, _ in requests][:3] == ["lead-fixture", "reviewer-fixture", "reader-fixture"] + if outcome == "timeout": + assert (result.status, result.reason, result.tokens) == ("stopped", "timeout", 8) + assert leaf_cancelled.is_set() + assert len(requests) == 3 + else: + expected_answer = summary if submit_summary else "Measured value is 42." + expected_tokens = 16 if submit_summary else 20 + assert (result.status, result.output, result.tokens) == ("completed", expected_answer, expected_tokens) + assert len(requests) == (4 if submit_summary else 5) + + snapshots = [app.read_session_snapshot(next(artifacts.glob(f"agent_{aid}_*.json"))) for aid in range(3)] + phases = [snapshot["session_state"]["phase"] for snapshot in snapshots] + rows = [[(r["tool_call_id"], r["status"]) for r in snapshot["session_state"]["pending_events"]] + for snapshot in snapshots] + manifest = json.loads((artifacts / "team.json").read_text()) + checkpoint = tmp_path / "checkpoint.json" + checkpoint.write_text(json.dumps(snapshots[0]), encoding="utf-8") + before_resume = len(requests) + restoring = True + resumed = await asyncio.to_thread(CliRunner().invoke, cli_main.app, [ + "--workspace", str(tmp_path), "--team-config", str(team), "--no-worktrees", + "--provider", "openai", "--model", "lead-fixture", "--api-key", "team-test-token", + "--base-url", "https://fixture.invalid/v1", "--budget", "100000", + "--session", str(checkpoint), "--prompt", "Review the follow-up figures.", + ]) + assert resumed.exit_code == 0, (resumed.output, resumed.exception) + restored_requests = requests[before_resume:] + assert [model for model, _ in restored_requests] == ["lead-fixture"] + restored_messages = restored_requests[0][1] + assert restored_messages[-1]["content"] == "Review the follow-up figures." + tool_rows = [row for row in restored_messages if row["role"] == "tool"] + expected_result = ( + "Error: scheduler cleanup cancelled delegated work" if outcome == "timeout" else "Measured value is 42." + ) + expected_tools = [("reviewer-call", expected_result)] + if submit_summary: + expected_tools.append(("submit-call", "Submitted. Your turn ends here.")) + assert snapshots[0]["messages"][-1]["content"] == summary + assert restored_messages[-2] == {"role": "assistant", "content": summary} + assert [(row["tool_call_id"], row["content"]) for row in tool_rows] == expected_tools + expected_phase = "stopped" if outcome == "timeout" else "done" + assert phases == [expected_phase] * 3 + assert [agent["phase"] for agent in manifest["agents"]] == phases + assert all(agent["busy"] is False for agent in manifest["agents"]) + expected_rows = [[] if submit_summary else [("reviewer-call", "failed")], [("reader-call", "failed")], []] + assert rows == (expected_rows if outcome == "timeout" else [[], [], []]) diff --git a/tests/interfaces/test_sdk_workflow_agent_run.py b/tests/interfaces/test_sdk_workflow_agent_run.py index ccd2513b..dd727503 100644 --- a/tests/interfaces/test_sdk_workflow_agent_run.py +++ b/tests/interfaces/test_sdk_workflow_agent_run.py @@ -9,10 +9,11 @@ import pytest -from opencollab import OpenCollab +from opencollab import OpenCollab, RunError from opencollab.adapters.llm.types import LLMResponse, Usage from opencollab.application.workflow import WorkflowBudgetExceeded from opencollab.bootstrap import _workflow_runtime_session as wiring +from opencollab.bootstrap import container from opencollab.bootstrap.single2_prompt import SINGLE2_SYSTEM_PROMPT from opencollab.sdk import BudgetDecision, RunControl from opencollab.tools import builtin_tools @@ -305,6 +306,69 @@ async def flow(ctx, _args): assert received.count("cleanup_completed") == 1 assert llm.closed == 0 +@pytest.mark.asyncio +@pytest.mark.parametrize("wait_boundary", ["stage", "observer", "workflow"]) +async def test_cleanup_wait_deadline_leaves_owned_model_close_pending(tmp_path, monkeypatch, wait_boundary): + started = asyncio.Event() + release = asyncio.Event() + completed = asyncio.Event() + receipt = tmp_path / "close-receipt.txt" + events = [] + + class LateClose(ReplyLLM): + async def close(self): + started.set() + await release.wait() + receipt.write_text("closed", encoding="utf-8") + super().close() + + llm = LateClose() + monkeypatch.setattr(container, "LLMClient", lambda **_kwargs: llm) + + def observe(event): + events.append(event.type) + if event.type == "cleanup_completed": + completed.set() + + control = RunControl(on_event=observe) + + async def flow(ctx, _args): + try: + stage = await ctx.agent_run("finish", tools=[], run_control=control, cleanup_timeout=0.03) + assert started.is_set() + assert not stage.cleanup_complete and not stage.workspace_ready + assert ctx.pending_cleanup_tasks + assert not receipt.exists() and "cleanup_completed" not in events + if wait_boundary == "observer": + with pytest.raises(asyncio.TimeoutError): + await asyncio.wait_for(ctx.wait_for_pending_cleanup(), 0.03) + if wait_boundary == "workflow": + return stage + finally: + if wait_boundary != "workflow": + release.set() + await ctx.wait_for_pending_cleanup() + return stage + + workflow = client(tmp_path).workflow( + flow, budget=10_000, trace=False, cleanup_timeout=0.04 if wait_boundary == "workflow" else 2, + ) + try: + if wait_boundary == "workflow": + with pytest.raises(RunError, match="without finalized execution evidence"): + await asyncio.wait_for(workflow, 5) + assert not completed.is_set() + else: + result = await asyncio.wait_for(workflow, 5) + assert result.ok and result.tokens == 6 + assert result.output.output == "finished" + assert result.output.status == "failed" and result.output.reason == "cleanup incomplete" + finally: + release.set() + await asyncio.wait_for(completed.wait(), 2) + assert receipt.read_text(encoding="utf-8") == "closed" + assert llm.closed == len(llm.calls) == events.count("cleanup_completed") == 1 + @pytest.mark.asyncio async def test_named_tools_work_without_a_workflow_profile(tmp_path): llm = ReplyLLM() diff --git a/tests/interfaces/test_sdk_workflow_budget_admission.py b/tests/interfaces/test_sdk_workflow_budget_admission.py new file mode 100644 index 00000000..e1d66991 --- /dev/null +++ b/tests/interfaces/test_sdk_workflow_budget_admission.py @@ -0,0 +1,549 @@ +from __future__ import annotations + +import asyncio +import json + +import pytest + +from opencollab import OpenCollab, RunControl +from opencollab.adapters.llm.client import LLMClient +from opencollab.adapters.llm.types import LLMResponse, Usage +from opencollab.adapters.tools.fs import FileReadTool +from opencollab.application.session_run import ENFORCEMENT_ON +from opencollab.sdk import BudgetDecision +from tests.support.provider_sdk_http import completion_http_response, http_response, install_sdk_transport + + +@pytest.fixture(autouse=True) +def offline(monkeypatch): + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", "") + + +def user_label(messages): + return next(row["content"] for row in reversed(messages) if row["role"] == "user") + + +async def wait(event): + await asyncio.wait_for(event.wait(), 4) + + +def brief(row): + return row.status, row.output, row.hard_budget_tokens, row.reason + + +@pytest.mark.parametrize("first_cost,overlap", [(100, False), (650, True), (100, True)]) +async def test_later_review_can_spend_immediately_free_tokens(tmp_path, first_cost, overlap): + preparing, release_prepare = asyncio.Event(), asyncio.Event() + entered, start_first, first_done = asyncio.Event(), asyncio.Event(), asyncio.Event() + outsider_active, release_outsider, start_review = (asyncio.Event() for _ in range(3)) + estimates = {"prepare": 590, "intro": first_cost, "outside": 90, "review": 3000} + calls, rows, views = [], {}, {} + + class Model: + def estimate_request_tokens(self, messages, tools=None, **kwargs): + return estimates[user_label(messages)] + + async def complete(self, messages, *, max_output_tokens, **kwargs): + name = user_label(messages) + calls.append((name, max_output_tokens)) + if name == "prepare": + preparing.set() + await wait(release_prepare) + elif name == "outside": + outsider_active.set() + await wait(release_outsider) + return LLMResponse(content=name, usage=Usage(estimates[name], 10), finish_reason="stop") + + async def flow(ctx, _inputs): + async def intro(): + entered.set() + await wait(start_first) + views["first_entry"] = ctx.tokens_remaining() + row = await ctx.agent_run("intro", tools=[]) + rows["intro"] = brief(row) + first_done.set() + return row.output + + async def review(): + await wait(start_review) + views["review_entry"] = ctx.tokens_remaining() + row = await ctx.agent_run("review", tools=[]) + rows["review"] = brief(row) + return row.output + + outs = None + collection = None + preparer = asyncio.create_task(ctx.agent_run("prepare", budget=19000, tools=[])) + try: + await wait(preparing) + views["collection_entry"] = ctx.tokens_remaining() + collection = asyncio.create_task(ctx.parallel([intro, review])) + await wait(entered) + release_prepare.set() + await preparer + start_first.set() + await wait(first_done) + if overlap: + outs = asyncio.create_task(ctx.agent_run("outside", budget=15000, tools=[])) + await wait(outsider_active) + start_review.set() + output = await collection + if outs is not None: + release_outsider.set() + await outs + views["lease_count"] = len(ctx.budget._leases) + views["remaining"] = ctx.tokens_remaining() + return output + finally: + for event in (release_prepare, start_first, start_review, release_outsider): + event.set() + await asyncio.gather(*[t for t in (preparer, collection, outs) if t], return_exceptions=True) + + result = await OpenCollab(tmp_path, model="offline", config={"max_output_tokens": 128}).workflow( + flow, llm=Model(), budget=20000, concurrency=3, task_concurrency=2, + limit_mode="explicit", timeout=10, trace=False, + ) + assert result.status == "completed", result.reason + assert views["collection_entry"] == 1000 + assert views["first_entry"] == 19400 + assert views["review_entry"] >= estimates["review"] + 128 + assert views["lease_count"] == 0 + assert views["remaining"] == 20000 - result.tokens + assert result.output == ["intro", "review"] + assert calls[-1] == ("review", 128) + + +@pytest.mark.parametrize( + "review_input,prepare_tokens,configured_output,first_text,expected_output,expected_limits,review_tokens", + [ + (5750, 3000, 128, "", "Review complete", [128], 5774), + (5990, 3000, 128, "", "Review complete", [10, 128], 12014), + (5990, 3000, 8192, "", "Review complete", [10, 1510], 12014), + (5990, 10000, 128, "", "", [10], 6000), + (5990, 3000, 128, "Partial review", "Partial review", [10], 6000), + ], +) +async def test_truncated_request_replays_only_with_full_budget( + tmp_path, review_input, prepare_tokens, configured_output, first_text, expected_output, expected_limits, + review_tokens, +): + preparing, release_prepare = asyncio.Event(), asyncio.Event() + entered, start = asyncio.Event(), asyncio.Event() + calls = [] + + class Model: + def estimate_request_tokens(self, messages, tools=None, **kwargs): + return 2990 if user_label(messages) == "prepare" else review_input + + async def complete(self, messages, *, max_output_tokens, **kwargs): + name = user_label(messages) + calls.append((name, max_output_tokens)) + if name == "prepare": + preparing.set() + await wait(release_prepare) + return LLMResponse(content="prepared", usage=Usage(prepare_tokens - 10, 10), finish_reason="stop") + if max_output_tokens < 24: + return LLMResponse( + content=first_text, usage=Usage(review_input, max_output_tokens), finish_reason="length", + ) + return LLMResponse(content="Review complete", usage=Usage(review_input, 24), finish_reason="stop") + + async def flow(ctx, _inputs): + async def review(): + entered.set() + await wait(start) + return brief(await ctx.agent_run("review", tools=[])) + + async def record(): + return "recorded" + + prep = asyncio.create_task(ctx.agent_run("prepare", budget=18000, tools=[])) + group = None + try: + await wait(preparing) + assert ctx.tokens_remaining() == 12000 + group = asyncio.create_task(ctx.parallel([review, record])) + await wait(entered) + release_prepare.set() + await prep + assert ctx.tokens_remaining() == 30000 - prepare_tokens + start.set() + return await group + finally: + release_prepare.set() + start.set() + await asyncio.gather(*[t for t in (prep, group) if t], return_exceptions=True) + + result = await OpenCollab(tmp_path, model="offline", config={"max_output_tokens": configured_output}).workflow( + flow, llm=Model(), budget=30000, concurrency=2, task_concurrency=2, + limit_mode="explicit", timeout=10, trace=False, + ) + assert result.status == "completed", result.reason + row_status, output = result.output[0][:2] + assert output == expected_output + if len(expected_limits) == 1 and expected_limits[0] == 10: + assert row_status == "stopped" + assert "output truncated" in result.output[0][3] + else: + assert row_status == "completed" + assert calls == [("prepare", configured_output), *(("review", limit) for limit in expected_limits)] + assert result.tokens == prepare_tokens + review_tokens + + +@pytest.mark.parametrize("kind", ["parallel", "pipeline"]) +@pytest.mark.parametrize("visible", [True, False], ids=["keep-partial", "recover-empty"]) +async def test_budget_replay_preserves_the_inventory_verification(tmp_path, monkeypatch, kind, visible): + ledger = tmp_path / "usage.jsonl" + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(ledger)) + preparing, release_preparation, preparation_finished = (asyncio.Event() for _ in range(3)) + requests = [] + rows = {} + workflow_budget = 20_000 if visible else 24_000 + inventory_total = "Reported total is 42." + verification = "Verified against the recorded rows. Total is 42." + estimates = {"Load inventory": 90, "Summarize inventory": 2990, "Verify totals": 15_000} + + def prompt_for(messages): + return next((row["content"].splitlines()[0] for row in reversed(messages) if row["role"] == "user"), "") + + def estimate(_client, messages, tools=None, **kwargs): + return estimates.get(prompt_for(messages), 50) + + async def reply(request): + body = json.loads(request.content) + prompt = prompt_for(body["messages"]) + limit = body["max_tokens"] + requests.append((prompt, limit)) + finish = "stop" + if prompt == "Load inventory": + preparing.set() + await wait(release_preparation) + answer, output = "Inventory loaded.", 10 + elif prompt == "Summarize inventory": + if limit == 10: + release_preparation.set() + await wait(preparation_finished) + answer, output, finish = (inventory_total if visible else ""), limit, "length" + elif visible: + answer, output, finish = "", limit, "length" + else: + answer, output = inventory_total, 24 + else: + assert prompt == "Verify totals" + assert inventory_total in user_label(body["messages"]) + answer, output = verification, 12 + payload = completion_http_response(request, text=answer, output_tokens=output).json() + payload["choices"][0]["finish_reason"] = finish + inputs = estimates[prompt] + payload["usage"].update(prompt_tokens=inputs, total_tokens=inputs + output) + return http_response(request, 200, json=payload) + + async def flow(ctx, _inputs): + async def load(): + row = await ctx.agent_run("Load inventory", tools=[], budget=workflow_budget - 6000) + assert row.output == "Inventory loaded." + preparation_finished.set() + + async def summarize(): + row = await ctx.agent_run("Summarize inventory\n" + " inventory" * 2980, tools=[]) + rows["summary"] = row + return row.output + + async def record_date(): + return "2026-11-29" + + async def stage(_previous, item, _index): + return await item() + + preparation = asyncio.create_task(load()) + try: + await wait(preparing) + assert ctx.tokens_remaining() == 6000 + operations = [summarize, record_date] + if kind == "pipeline": + summary, date = await ctx.pipeline(operations, stage) + else: + summary, date = await ctx.parallel(operations) + if summary: + prompt = "Verify totals\n" + summary + "\n" + " ledger" * 14_900 + rows["verification"] = await ctx.agent_run(prompt, tools=[]) + return {"date": date, "verification": rows["verification"].output if "verification" in rows else None} + finally: + release_preparation.set() + await preparation + + monkeypatch.setattr(LLMClient, "estimate_request_tokens", estimate) + install_sdk_transport(monkeypatch, "openai", reply) + artifacts = tmp_path / "artifacts" + client = OpenCollab( + tmp_path, model="gpt-4o", provider="openai", api_key=tmp_path.name, base_url="https://fixture.invalid/v1", + config={"wire_protocol": "chat_completions", "llm_stream_chat": False, + "llm_max_retries": 0, "max_output_tokens": 128}, + ) + result = await client.workflow( + flow, budget=workflow_budget, concurrency=2, task_concurrency=2, limit_mode="explicit", + artifacts=artifacts, trace=False, timeout=10, + ) + + attempts = [("Load inventory", 128), ("Summarize inventory", 10)] + if not visible: + attempts.append(("Summarize inventory", 128)) + assert requests == [*attempts, ("Verify totals", 128)] + assert (result.status, result.output) == ("completed", {"date": "2026-11-29", "verification": verification}) + assert rows["summary"].output == inventory_total + assert rows["summary"].hard_budget_tokens == (3000 if visible else 6118) + assert rows["summary"].status == ("stopped" if visible else "completed") + assert (rows["verification"].status, rows["verification"].tokens) == ("completed", 15_012) + billed = [json.loads(line)["usage"]["total_tokens"] for line in ledger.read_text().splitlines()] + manifest = json.loads((artifacts / "workflow.json").read_text()) + assert sorted(billed) == ([100, 3000, 15_012] if visible else [100, 3000, 3014, 15_012]) + assert result.tokens == manifest["tokens_spent"] == sum(billed) + assert manifest["status"] == "completed" and manifest["evidence_complete"] + + +@pytest.mark.parametrize( + "control_kind,budget,expected", + [ + ("none", None, "completed"), + ("observer", None, "completed"), + ("soft", None, "stopped"), + ("policy", None, "stopped"), + ("none", 750, "stopped"), + ], +) +async def test_recovery_respects_session_authority(tmp_path, control_kind, budget, expected): + preparing, release_prepare, collection_entered, start = [asyncio.Event() for _ in range(4)] + events, snapshots, calls = [], [], [] + + def decide(snapshot): + snapshots.append(snapshot) + return BudgetDecision(snapshot.soft_budget_tokens) + + control = { + "none": None, + "observer": RunControl(on_event=events.append), + "soft": RunControl(initial_soft_budget_tokens=400, on_event=events.append), + "policy": RunControl(decide_budget=decide, on_event=events.append), + }[control_kind] + + class Model: + def estimate_request_tokens(self, messages, tools=None, **kwargs): + return {"prepare": 590, "review": 800}[user_label(messages)] + + async def complete(self, messages, *, max_output_tokens, **kwargs): + name = user_label(messages) + calls.append((name, max_output_tokens)) + if name == "prepare": + preparing.set() + await wait(release_prepare) + return LLMResponse(content=name, usage=Usage(590, 10), finish_reason="stop") + return LLMResponse(content=name, usage=Usage(800, 10), finish_reason="stop") + + async def flow(ctx, _inputs): + async def review(): + collection_entered.set() + await wait(start) + return await ctx.agent_run("review", budget=budget, tools=[], run_control=control) + + async def note(): + return "noted" + + prep = asyncio.create_task(ctx.agent_run("prepare", budget=19000, tools=[])) + group = None + try: + await wait(preparing) + group = asyncio.create_task(ctx.parallel([review, note])) + await wait(collection_entered) + release_prepare.set() + await prep + start.set() + return await group + finally: + release_prepare.set() + start.set() + await asyncio.gather(*[t for t in (prep, group) if t], return_exceptions=True) + + result = await OpenCollab(tmp_path, model="offline", config={"max_output_tokens": 128}).workflow( + flow, llm=Model(), budget=20000, concurrency=2, task_concurrency=2, + limit_mode="explicit", timeout=10, trace=False, + ) + row = result.output[0] + assert result.status == "completed", result.reason + assert row.status == expected + if expected == "completed": + assert row.output == "review" + assert row.hard_budget_tokens == row.soft_budget_tokens == 928 + assert calls[-1] == ("review", 128) + else: + assert calls == [("prepare", 128)] + assert row.hard_budget_tokens == (budget or 500) + assert row.soft_budget_tokens == (400 if control_kind == "soft" else row.hard_budget_tokens) + if control_kind == "observer": + assert sum(event.type == "usage" for event in events) == 1 + assert sum(event.type == "cleanup_completed" for event in events) == 1 + if control_kind == "policy": + assert snapshots + assert {snap.hard_budget_tokens for snap in snapshots} == {500} + + +@pytest.mark.parametrize( + "prepare_cap,commit_reserve,room,max_steps,appendix_finish_reason", + [ + (18_000, 256, None, 100, "tool_calls"), + (19_800, 256, None, 100, "tool_calls"), + (19_800, 100, None, 100, "tool_calls"), + (16_000, 1_000, 0, 100, "tool_calls"), + (16_000, 1_000, 100, 100, "tool_calls"), + (16_000, 1_000, 700, 100, "tool_calls"), + (16_000, 1_000, 1800, 100, "tool_calls"), + (16_000, 1_000, 100, 1, "tool_calls"), + (16_000, 1_000, 1800, 2, "tool_calls"), + (16_000, 1_000, 1800, 100, "length"), + (16_000, 1_000, 1800, 100, "max_tokens"), + (16_000, 1_000, 1800, 100, "content_filter"), + ], +) +async def test_released_budget_reaches_enforced_scout_before_wind_down( + tmp_path, prepare_cap, commit_reserve, room, max_steps, appendix_finish_reason, +): + (tmp_path / "notes.txt").write_text("Observed measurement is 42 ms.\n") + (tmp_path / "appendix.txt").write_text("Secondary check corroborates the result.\n") + preparing, release = asyncio.Event(), asyncio.Event() + entered, start = asyncio.Event(), asyncio.Event() + reading, other_started, release_other = (asyncio.Event() for _ in range(3)) + actions, offered_tools = [], [] + partial = "I was about to check the appendix." + + async def wait(event): + await asyncio.wait_for(event.wait(), 5) + + def call(name, arguments): + return {"id": name, "type": "function", "function": {"name": name, "arguments": json.dumps(arguments)}} + + def has_evidence(messages): + return any( + row["role"] == "tool" and "Observed measurement is 42 ms." in row["content"] for row in messages + ) + + class Model: + def estimate_request_tokens(self, messages, tools=None, **kwargs): + if room is None or user_label(messages) in {"prepare", "other"}: + return 80 + if not has_evidence(messages): + return 900 + return 1_400 if any(tool["function"]["name"] == "file_read" for tool in tools) else 850 + + async def complete(self, messages, *, tools, max_output_tokens, **kwargs): + user = user_label(messages) + if user == "prepare": + preparing.set() + await wait(release) + return LLMResponse(content="prepared", usage=Usage(590, 10), finish_reason="stop") + if user == "other": + other_started.set() + await wait(release_other) + return LLMResponse(content="other finished", usage=Usage(80, 10), finish_reason="stop") + tool_names = [tool["function"]["name"] for tool in tools] + evidence = has_evidence(messages) + offered_tools.append(tool_names) + if "file_read" in tool_names and not evidence: + actions.append("read") + response = call("file_read", {"path": "notes.txt"}) + if room is not None: + reading.set() + await wait(other_started) + return LLMResponse(tool_calls=[response], usage=Usage(911, 89), finish_reason="tool_calls") + elif evidence: + appendix_read = any( + row["role"] == "tool" and "Secondary check corroborates" in row["content"] for row in messages + ) + if room in (700, 1800) and "file_read" in tool_names and not appendix_read: + actions.append("appendix") + response = call("file_read", {"path": "appendix.txt"}) + response["id"] = "read_appendix" + if appendix_finish_reason != "tool_calls": + return LLMResponse( + content=partial, tool_calls=[response], usage=Usage(1_400, max_output_tokens), + finish_reason=appendix_finish_reason, + ) + return LLMResponse(tool_calls=[response], usage=Usage(1_400, 100), finish_reason="tool_calls") + actions.append("submit") + if appendix_finish_reason in ("length", "max_tokens"): + assert not appendix_read + assert any(row["role"] == "assistant" and row.get("content") == partial for row in messages) + response = call("submit_findings", { + "summary": "Measured time was 42 ms.", + "findings": [{ + "aspect": "runtime", "claim": "Time was 42 ms", "evidence_anchor": "notes.txt:1", + "verified": True, "confidence": "high", + }], + "insufficient_evidence": False, + }) + else: + actions.append("premature-submit") + response = call("submit_findings", { + "summary": "No evidence was collected.", "findings": [], "insufficient_evidence": True, + }) + usage = Usage(self.estimate_request_tokens(messages, tools), 15) + return LLMResponse(tool_calls=[response], usage=usage, finish_reason="tool_calls") + + async def flow(ctx, _inputs): + async def scout(): + entered.set() + await wait(start) + return await ctx.agent( + "Measure the saved time.", tools=[FileReadTool()], label="scout", + enforcement_strength=ENFORCEMENT_ON, commit_reserve=commit_reserve, + ) + + async def note(): + return "recorded" + + prep = asyncio.create_task(ctx.agent_run("prepare", budget=prepare_cap, tools=[])) + group = other = None + try: + await wait(preparing) + assert ctx.tokens_remaining() == 20_000 - prepare_cap + group = asyncio.create_task(ctx.parallel([scout, note])) + await wait(entered) + release.set() + await prep + assert ctx.tokens_remaining() == 19_400 + start.set() + if room is not None: + await wait(reading) + remaining = ctx.tokens_remaining() + other = asyncio.create_task(ctx.agent_run("other", budget=int(remaining) - room, tools=[])) + await wait(other_started) + assert ctx.tokens_remaining() == room + return await group + finally: + for event in (release, start, other_started, release_other): + event.set() + await asyncio.gather(*[t for t in (prep, group, other) if t], return_exceptions=True) + + artifacts = tmp_path / "artifacts" if appendix_finish_reason in ("length", "max_tokens") else None + result = await OpenCollab(tmp_path, model="offline", config={"max_output_tokens": 128}).workflow( + flow, llm=Model(), budget=20000, concurrency=2, task_concurrency=2, + limit_mode="explicit", timeout=10, max_steps=max_steps, + artifacts=artifacts, trace=artifacts is not None, + ) + + assert result.status == "completed", result.reason + if appendix_finish_reason == "content_filter": + assert actions == ["read", "appendix"] + assert result.output[0] == partial + return + expected = ["read", "appendix", "submit"] if room == 1800 else ["read", "submit"] + assert actions == expected + assert "Measured time was 42 ms." in result.output[0] + if artifacts is not None: + assert result.tokens == 4_083 + rows = [json.loads(line) for line in (artifacts / "orchestration.jsonl").read_text().splitlines()] + calls = [row for row in rows if row["type"] == "llm_call"] + assert sum(row["metrics"]["tokens"] for row in calls) == result.tokens + assert any(row["payload"]["finish_reason"] == appendix_finish_reason for row in calls) + if room is not None: + assert offered_tools[-1] == ["submit_findings"] diff --git a/tests/interfaces/test_sdk_workflow_budget_reclamation.py b/tests/interfaces/test_sdk_workflow_budget_reclamation.py new file mode 100644 index 00000000..5f872170 --- /dev/null +++ b/tests/interfaces/test_sdk_workflow_budget_reclamation.py @@ -0,0 +1,735 @@ +from __future__ import annotations + +import asyncio +import json +import subprocess + +import pytest + +from opencollab import OpenCollab +from opencollab.adapters.candidate_workspace import EnvCandidateWorkspace +from opencollab.adapters.env import LocalEnvironment +from opencollab.adapters.llm.types import LLMResponse, Usage +from opencollab.adapters.tools.fs import FileReadTool +from opencollab.bootstrap import _workflow_runtime_session + + +@pytest.fixture +def repository(tmp_path): + for command in [ + ["init", "-q"], + ["-c", "user.name=Test User", "-c", "user.email=test@example.invalid", + "-c", "commit.gpgsign=false", "commit", "--allow-empty", "-qm", "Initialize"], + ]: + subprocess.run(["git", "-C", str(tmp_path), *command], check=True) + return tmp_path + + +@pytest.mark.parametrize("kind", ["parallel", "pipeline"]) +@pytest.mark.parametrize("method", ["agent", "agent_run", "candidate_agent"]) +@pytest.mark.parametrize( + "input_cost,output_limit,expected_grant", + [(2800, 128, 4000), (3900, 128, 4000), (4300, 128, 4428), (2800, 8192, 4000), (2800, 65536, 4000)], +) +async def test_mixed_collection_claims_only_necessary_budget( + repository, monkeypatch, kind, method, input_cost, output_limit, expected_grant, +): + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", "") + started, settle, collection_entered, collection_can_start = [asyncio.Event() for _ in range(4)] + implicit_started, finish_implicit, explicit_done = [asyncio.Event() for _ in range(3)] + calls, grants = [], {} + + def user_label(messages): + return [row["content"] for row in messages if row["role"] == "user"][-1].splitlines()[0] + + class Model: + def estimate_request_tokens(self, messages, tools=None, **kwargs): + return {"Prepare": 2990, "Summarize": input_cost, "Review": 20490, "Footer": 55}[user_label(messages)] + + def minimum_output_tokens(self, **kwargs): + return 10 + + async def complete(self, messages, *, max_output_tokens, **kwargs): + label = user_label(messages) + calls.append((label, max_output_tokens)) + if label == "Prepare": + started.set() + await asyncio.wait_for(settle.wait(), 5) + elif label == "Summarize": + implicit_started.set() + await asyncio.wait_for(finish_implicit.wait(), 5) + return LLMResponse( + content=label, + usage=Usage(self.estimate_request_tokens(messages), 10), + finish_reason="stop", + ) + + async def flow(ctx, _args): + async def implicit(): + collection_entered.set() + await asyncio.wait_for(collection_can_start.wait(), 5) + row = await getattr(ctx, method)("Summarize", label="summary", tools=[]) + return row if method == "agent" else row.output + + async def review(): + await asyncio.wait_for(implicit_started.wait(), 5) + try: + grants["summary"] = ctx.sessions[-1].max_budget_tokens + grants["available_for_review"] = ctx.tokens_remaining() + row = await ctx.agent_run("Review", tools=[], budget=22000) + grants["review"] = row.hard_budget_tokens + return row.output + finally: + explicit_done.set() + + async def footer(): + await asyncio.wait_for(finish_implicit.wait(), 5) + row = await ctx.agent_run("Footer", tools=[], budget=2500) + return row.output + + async def stage(_previous, call, _index): + return await call() + + preparer = asyncio.create_task(ctx.agent_run("Prepare", tools=[], budget=18000)) + collection = None + try: + await asyncio.wait_for(started.wait(), 5) + assert ctx.tokens_remaining() == 12000 + items = [implicit, review, footer] + collection = asyncio.create_task( + ctx.parallel(items) if kind == "parallel" else ctx.pipeline(items, stage) + ) + await asyncio.wait_for(collection_entered.wait(), 5) + settle.set() + assert (await preparer).output == "Prepare" + assert ctx.tokens_remaining() == 27000 + collection_can_start.set() + await asyncio.wait_for(explicit_done.wait(), 5) + finish_implicit.set() + results = await collection + assert ctx.budget._leases == [] + return results + finally: + settle.set() + collection_can_start.set() + finish_implicit.set() + await asyncio.gather(preparer, *([collection] if collection else []), return_exceptions=True) + + environment = LocalEnvironment(str(repository)) + try: + result = await OpenCollab( + repository, environment=environment, model="offline", config={"max_output_tokens": output_limit}, + ).workflow( + flow, llm=Model(), candidate_workspace=EnvCandidateWorkspace(environment), + budget=30000, concurrency=3, task_concurrency=3, limit_mode="explicit", + timeout=15, trace=False, system_prompt="Summarize the requested information.", + ) + finally: + await environment.cleanup() + assert result.status == "completed", result.reason + assert result.output == ["Summarize", "Review", "Footer"] + assert grants == { + "summary": expected_grant, + "available_for_review": 27000 - expected_grant, + "review": 22000, + } + assert calls == [ + ("Prepare", min(output_limit, 18000 - 2990)), + ("Summarize", min(output_limit, expected_grant - input_cost)), + ("Review", min(output_limit, 22000 - 20490)), + ("Footer", min(output_limit, 2500 - 55)), + ] + assert result.tokens == 23575 + input_cost + + +@pytest.mark.parametrize("needs_recovery", [False, True], ids=["discarded-size-probe", "executed-summary"]) +async def test_summary_sizing_does_not_claim_sibling_budget(repository, monkeypatch, needs_recovery): + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", "") + preparing, release_prepare, collection_entered, begin_summary = (asyncio.Event() for _ in range(4)) + summary_started, release_summary, blocker_started, release_blocker = (asyncio.Event() for _ in range(4)) + calls, grant = [], {} + system_prompt = "Compact earlier records." + + def request_name(messages): + prompt = messages[-1]["content"] + return "summary" if "Your task is to create a detailed summary" in prompt else prompt + + def earlier_records(messages): + return sum((row.get("content") or "").startswith("Earlier record ") for row in messages) + + class Model: + def context_window(self): + return 5000 + + def minimum_output_tokens(self, **kwargs): + return 100 + + def estimate_request_tokens(self, messages, tools=None, **kwargs): + name = request_name(messages) + records = earlier_records(messages) + if name == "summary": + if records > 2: + return 4600 + return 4200 if needs_recovery else 800 + 950 * records + if name == "compact": + return 4500 if records > 2 else 900 + return {"prepare": 2600, "blocker": 200, "review": 3900}.get(name, 20) + + async def complete(self, messages, *, max_output_tokens, **kwargs): + name = request_name(messages) + estimated_input = self.estimate_request_tokens(messages) + calls.append((name, estimated_input, max_output_tokens)) + if name == "prepare": + preparing.set() + await release_prepare.wait() + elif name == "summary": + assert estimated_input + max_output_tokens <= self.context_window() + summary_started.set() + await release_summary.wait() + return LLMResponse( + content="Earlier records extracted.", + usage=Usage(300, 20), finish_reason="stop", + ) + elif name == "blocker": + blocker_started.set() + await release_blocker.wait() + return LLMResponse( + content=name, usage=Usage(2980, 20) if name == "prepare" else Usage(150, 20), finish_reason="stop", + ) + + build_session = _workflow_runtime_session.build_session + + def seed_history(**kwargs): + session = build_session(**kwargs) + if kwargs["agent"].system_prompt == system_prompt: + history = session.messages[:] + for index in range(6): + history.extend([ + {"role": "user", "content": f"Earlier record {index}\n" + "item detail " * 500}, + {"role": "assistant", "content": f"Recorded {index}."}, + ]) + session.messages = history + return session + + monkeypatch.setattr(_workflow_runtime_session, "build_session", seed_history) + + async def flow(ctx, _inputs): + async def compact(): + collection_entered.set() + await begin_summary.wait() + row = await ctx.agent_run("compact", tools=[], system_prompt=system_prompt) + return row.output + + async def review(): + blocker = None + try: + await asyncio.wait_for(summary_started.wait(), 5) + grant["summary"] = ctx.sessions[-1].max_budget_tokens + blocker_budget = 7500 if needs_recovery else 8000 + blocker = asyncio.create_task(ctx.agent_run("blocker", tools=[], budget=blocker_budget)) + await asyncio.wait_for(blocker_started.wait(), 5) + row = await ctx.agent_run("review", tools=[], budget=4600) + grant["review"] = row.hard_budget_tokens + return row.output + finally: + release_summary.set() + release_blocker.set() + if blocker is not None: + await blocker + + prepare = asyncio.create_task(ctx.agent_run("prepare", tools=[], budget=12000)) + collection = None + try: + await asyncio.wait_for(preparing.wait(), 5) + assert ctx.tokens_remaining() == 8000 + collection = asyncio.create_task(ctx.parallel([compact, review])) + await asyncio.wait_for(collection_entered.wait(), 5) + release_prepare.set() + assert (await prepare).output == "prepare" + assert ctx.tokens_remaining() == 17000 + begin_summary.set() + return await collection + finally: + release_prepare.set() + begin_summary.set() + release_summary.set() + release_blocker.set() + await asyncio.gather(prepare, *([collection] if collection is not None else []), return_exceptions=True) + + environment = LocalEnvironment(str(repository)) + try: + result = await OpenCollab( + repository, environment=environment, model="offline", config={"max_output_tokens": 1000}, + ).workflow( + flow, llm=Model(), candidate_workspace=EnvCandidateWorkspace(environment), budget=20000, + concurrency=4, task_concurrency=4, limit_mode="explicit", timeout=12, trace=False, + ) + finally: + await environment.cleanup() + assert result.status == "completed" + assert result.output == ["compact", "review"] + if needs_recovery: + assert grant == {"summary": 5200, "review": 4300} + assert calls[1] == ("summary", 4200, 800) + assert result.tokens == 4150 + else: + assert grant == {"summary": 4000, "review": 4600} + assert [estimated for name, estimated, _ in calls if name == "summary"] == [2700, 2700, 2700] + assert result.tokens == 4470 + assert sum(name == "review" for name, _, _ in calls) == 1 + + +@pytest.mark.parametrize("explicit_child", [False, True]) +async def test_candidate_run_reclaims_for_concurrent_child_requests(repository, monkeypatch, explicit_child): + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", "") + prepare_started, release_prepare = asyncio.Event(), asyncio.Event() + collection_started, release_collection = asyncio.Event(), asyncio.Event() + children = {name: asyncio.Event() for name in ("first", "second")} + release_children = asyncio.Event() + grants = {} + + class Model: + def estimate_request_tokens(self, messages, tools=None, **kwargs): + prompt = next(row["content"] for row in reversed(messages) if row["role"] == "user") + return 3000 if prompt in children else 256 + + async def complete(self, messages, **kwargs): + prompt = next(row["content"] for row in reversed(messages) if row["role"] == "user") + if prompt == "prepare": + prepare_started.set() + await release_prepare.wait() + return LLMResponse(content=prompt, usage=Usage(3990, 10), finish_reason="stop") + if prompt in children: + children[prompt].set() + await release_children.wait() + return LLMResponse(content=prompt, usage=Usage(5, 10), finish_reason="stop") + + async def flow(ctx, _args): + async def candidate(): + collection_started.set() + await release_collection.wait() + + async def child_work(child, _inputs): + async def run(name): + row = await child.agent_run(name, tools=[], budget=3500 if explicit_child else None) + grants[name] = (row.status, row.hard_budget_tokens) + return row.output + + return await child.parallel([lambda: run("first"), lambda: run("second")]) + + return (await ctx.candidate_workflow(child_work, {}, label="candidate")).output + + async def peer(): + try: + for event in children.values(): + await asyncio.wait_for(event.wait(), 5) + assert ctx.tokens_remaining() == 16000 - 2 * 3128 + row = await ctx.agent_run("peer", budget=8000, tools=[]) + grants["peer"] = (row.status, row.hard_budget_tokens) + return row.output + finally: + release_children.set() + + prepare = asyncio.create_task(ctx.agent_run("prepare", budget=16000, tools=[])) + collection = None + try: + await asyncio.wait_for(prepare_started.wait(), 5) + collection = asyncio.create_task(ctx.parallel([candidate, peer])) + await asyncio.wait_for(collection_started.wait(), 5) + release_prepare.set() + assert (await prepare).output == "prepare" + assert ctx.tokens_remaining() == 16000 + release_collection.set() + results = await collection + assert ctx.tokens_remaining() == 15955 + return results + finally: + release_prepare.set() + release_collection.set() + release_children.set() + await asyncio.gather(prepare, *([collection] if collection else []), return_exceptions=True) + + environment = LocalEnvironment(str(repository)) + try: + result = await OpenCollab( + repository, environment=environment, model="offline", config={"max_output_tokens": 128}, + ).workflow( + flow, llm=Model(), candidate_workspace=EnvCandidateWorkspace(environment), + budget=20000, concurrency=3, task_concurrency=3, limit_mode="explicit", timeout=15, trace=False, + ) + finally: + await environment.cleanup() + assert result.status == "completed", result.reason + assert result.output == [["first", "second"], "peer"] + assert grants == {"first": ("completed", 3128), "second": ("completed", 3128), "peer": ("completed", 8000)} + assert result.tokens == 4045 + + +@pytest.mark.parametrize("queued", [False, True]) +async def test_preparer_releases_before_queued_provider_admission(tmp_path, monkeypatch, queued): + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", "") + preparing, release_prepare, finish_prepare = [asyncio.Event() for _ in range(3)] + collection_entered = asyncio.Event() + calls, budgets = [], {} + + class Model: + def estimate_request_tokens(self, messages, tools=None, **kwargs): + return 4000 if messages[-1]["content"] == "prepare" else 7700 + + async def complete(self, messages, *, max_output_tokens, **kwargs): + name = messages[-1]["content"] + calls.append((name, max_output_tokens)) + if name == "prepare": + preparing.set() + await release_prepare.wait() + usage = Usage(3990, 10) + else: + usage = Usage(7700, 10) + return LLMResponse(content=name, usage=usage, finish_reason="stop") + + async def flow(ctx, _inputs): + async def item(name): + collection_entered.set() + if not queued: + await finish_prepare.wait() + row = await ctx.agent_run(name, tools=[]) + budgets[name] = (row.status, row.hard_budget_tokens, row.reason) + return row.output + + async def wait_for_reservations(): + while ctx.tokens_remaining() != 0: + await asyncio.sleep(0) + + prepare = asyncio.create_task(ctx.agent_run("prepare", budget=19000, tools=[])) + collection = None + try: + await asyncio.wait_for(preparing.wait(), 3) + assert ctx.tokens_remaining() == 1000 + collection = asyncio.create_task(ctx.parallel([lambda: item("first"), lambda: item("second")])) + await asyncio.wait_for(collection_entered.wait(), 3) + if queued: + await asyncio.wait_for(wait_for_reservations(), 3) + release_prepare.set() + assert (await prepare).output == "prepare" + finish_prepare.set() + output = await collection + assert ctx.budget._leases == [] + return output + finally: + release_prepare.set() + finish_prepare.set() + await asyncio.gather(prepare, *([collection] if collection else []), return_exceptions=True) + + result = await OpenCollab( + tmp_path, model="offline", config={"max_output_tokens": 128}, + ).workflow(flow, llm=Model(), budget=20000, concurrency=1, task_concurrency=2, limit_mode="explicit") + assert result.status == "completed", result.reason + assert result.output == ["first", "second"] + assert calls == [("prepare", 128), ("first", 128), ("second", 128)] + assert budgets == {"first": ("completed", 7828, None), "second": ("completed", 7828, None)} + assert result.tokens == 19420 + + +@pytest.mark.parametrize("exact", [False, True]) +async def test_recovery_after_spending_entire_entry_share(tmp_path, monkeypatch, exact): + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", "") + (tmp_path / "notes.txt").write_text("Evidence for the review.\n") + preparing, release_prepare = asyncio.Event(), asyncio.Event() + collection_entered, release_collection = asyncio.Event(), asyncio.Event() + calls = [] + + class Model: + def estimate_request_tokens(self, messages, tools=None, **kwargs): + if messages[-1]["role"] == "tool": + return 2000 + return {"prepare": 2990, "review": 5872}[messages[-1]["content"]] + + async def complete(self, messages, *, max_output_tokens, **kwargs): + last = messages[-1] + if last["role"] == "tool": + calls.append(("answer", max_output_tokens)) + assert "Evidence for the review." in last["content"] + return LLMResponse(content="Review complete", usage=Usage(2000, 10), finish_reason="stop") + if last["content"] == "prepare": + calls.append(("prepare", max_output_tokens)) + preparing.set() + await release_prepare.wait() + return LLMResponse(content="prepared", usage=Usage(2990, 10), finish_reason="stop") + calls.append(("read", max_output_tokens)) + return LLMResponse( + tool_calls=[{ + "id": "read-notes", + "type": "function", + "function": {"name": "file_read", "arguments": '{"path":"notes.txt"}'}, + }], + usage=Usage(5872, 128 if exact else 127), + finish_reason="tool_calls", + ) + + async def flow(ctx, _inputs): + async def review(): + collection_entered.set() + await release_collection.wait() + row = await ctx.agent_run("review", tools=[FileReadTool()]) + return row.status, row.output, row.reason, row.hard_budget_tokens + + async def record(): + return "logged" + + prepare = asyncio.create_task(ctx.agent_run("prepare", budget=18000, tools=[])) + collection = None + try: + await asyncio.wait_for(preparing.wait(), 4) + collection = asyncio.create_task(ctx.parallel([review, record])) + await asyncio.wait_for(collection_entered.wait(), 4) + assert ctx.tokens_remaining() == 12000 + release_prepare.set() + assert (await prepare).output == "prepared" + release_collection.set() + return await collection + finally: + release_prepare.set() + release_collection.set() + await asyncio.gather(prepare, *([collection] if collection else []), return_exceptions=True) + + result = await OpenCollab(tmp_path, model="offline", config={"max_output_tokens": 128}).workflow( + flow, llm=Model(), budget=30000, concurrency=2, task_concurrency=2, limit_mode="explicit", timeout=15 + ) + assert result.status == "completed", result.reason + assert result.output == [("completed", "Review complete", None, 8128 if exact else 8127), "logged"] + assert calls == [("prepare", 128), ("read", 128), ("answer", 128)] + assert result.tokens == (11010 if exact else 11009) + + +@pytest.mark.parametrize( + "mode,expected", + [ + ("direct-after", "completed"), + ("inner-collection", "completed"), + ("explicit-child", "completed"), + ("capped-child", "stopped"), + ("capped-outer", "stopped"), + ("direct-queued", "completed"), + ], +) +async def test_queued_candidate_child_rechecks_parent_allocation(repository, monkeypatch, mode, expected): + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", "") + repo = repository + + def label(messages): + return next(row["content"] for row in reversed(messages) if row["role"] == "user") + + async def wait(event): + await asyncio.wait_for(event.wait(), 5) + + preparing, release_prepare, prepare_done = (asyncio.Event() for _ in range(3)) + child_setup = asyncio.Event() + calls, children, views = [], [], {} + + class Model: + def estimate_request_tokens(self, messages, tools=None, **kwargs): + return {"prepare": 590, "review": 3000}[label(messages)] + + async def complete(self, messages, *, max_output_tokens, **kwargs): + name = label(messages) + calls.append((name, max_output_tokens)) + if name == "prepare": + preparing.set() + await wait(release_prepare) + return LLMResponse(content=name, usage=Usage(590, 10), finish_reason="stop") + return LLMResponse(content=name, usage=Usage(3000, 10), finish_reason="stop") + + async def child_work(child, _inputs): + children.append(child) + child_setup.set() + if mode == "direct-after": + await wait(prepare_done) + + async def review(): + cap = {"explicit-child": 4000, "capped-child": 2000}.get(mode) + row = await child.agent_run("review", budget=cap, tools=[]) + return row.status, row.output, row.hard_budget_tokens, row.reason + + if mode == "inner-collection": + row, = await child.parallel([review]) + else: + row = await review() + views["child_total"] = child.budget.total + return row + + async def flow(ctx, _inputs): + async def run_candidate(): + cap = 1000 if mode == "capped-outer" else None + return (await ctx.candidate_workflow(child_work, {}, label="draft", budget=cap)).output + + async def note(): + return "noted" + + async def wait_for_child_reservation(child): + while not child.budget._leases: + await asyncio.sleep(0) + + prep = asyncio.create_task(ctx.agent_run("prepare", budget=19000, tools=[])) + group = None + try: + await wait(preparing) + assert ctx.tokens_remaining() == 1000 + group = asyncio.create_task(ctx.parallel([run_candidate, note])) + await wait(child_setup) + if mode != "direct-after": + await asyncio.wait_for(wait_for_child_reservation(children[0]), 5) + views["queued_grant"] = children[0].budget._leases[0].total + views["before_release"] = ctx.tokens_remaining() + release_prepare.set() + await prep + prepare_done.set() + output = await group + views["remaining"] = ctx.tokens_remaining() + views["leases"] = [len(ctx.budget._leases), len(children[0].budget._leases)] + return output + finally: + release_prepare.set() + prepare_done.set() + await asyncio.gather(*[t for t in (prep, group) if t], return_exceptions=True) + + environment = LocalEnvironment(str(repo)) + try: + result = await OpenCollab( + repo, environment=environment, model="offline", config={"max_output_tokens": 128}, + ).workflow( + flow, llm=Model(), candidate_workspace=EnvCandidateWorkspace(environment), + budget=20000, concurrency=1, task_concurrency=2, limit_mode="explicit", timeout=15, trace=False, + ) + finally: + await environment.cleanup() + + assert result.status == "completed", result.reason + assert views["leases"] == [0, 0] + assert views["remaining"] == 20000 - result.tokens + assert result.output[0][0] == expected + if expected == "completed": + assert result.output[0][1] == "review" + assert calls == [("prepare", 128), ("review", 128)] + assert result.tokens == 3610 + else: + assert calls == [("prepare", 128)] + assert result.tokens == 600 + assert result.output[0][2] <= (1000 if mode == "capped-outer" else 2000) + + +@pytest.mark.parametrize("kind", ["parallel", "pipeline"]) +@pytest.mark.parametrize( + "role_cap,exploration_tokens,correction_budget", + [(None, 5000, 5128), (None, 6000, 5128), (None, 6100, None), (6000, 5000, None), (11000, 5000, 6000)], +) +async def test_structured_correction_uses_available_collection_budget( + tmp_path, monkeypatch, kind, role_cap, exploration_tokens, correction_budget, +): + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + prepare_started, release_preparation, group_entered, start_review = (asyncio.Event() for _ in range(4)) + calls, grants = [], [] + evidence = "The observed measurement was 42 milliseconds." + + def stage(messages): + prompt = next(row["content"] for row in reversed(messages) if row["role"] == "user") + if prompt == "prepare": + return "prepare" + return "correct" if "You MUST call" in prompt else "explore" + + class Model: + def estimate_request_tokens(self, messages, tools=None, **kwargs): + return {"prepare": 2990, "explore": 4950, "correct": 5000}[stage(messages)] + + async def complete(self, messages, *, tools=None, max_output_tokens, **kwargs): + action = stage(messages) + calls.append((action, max_output_tokens)) + if action == "prepare": + prepare_started.set() + await asyncio.wait_for(release_preparation.wait(), 5) + return LLMResponse(content="prepared", usage=Usage(2990, 10), finish_reason="stop") + if action == "explore": + return LLMResponse( + content=evidence, usage=Usage(exploration_tokens - 50, 50), finish_reason="stop", + ) + assert any(row.get("content") == evidence for row in messages) + assert [tool["function"]["name"] for tool in tools] == ["structured_output"] + return LLMResponse( + tool_calls=[{ + "id": "structured-42", "type": "function", + "function": { + "name": "structured_output", + "arguments": json.dumps({"measurement": 42}), + }, + }], + usage=Usage(5000, 20), finish_reason="tool_calls", + ) + + schema = { + "type": "object", "properties": {"measurement": {"type": "integer"}}, + "required": ["measurement"], + } + + async def workflow(ctx, _inputs): + async def review(): + group_entered.set() + await asyncio.wait_for(start_review.wait(), 5) + return await ctx.agent("Record the measurement.", schema=schema, tools=[], budget=role_cap) + + async def note(): + return "recorded" + + async def run_stage(_previous, thunk, _index): + return await thunk() + + preparer = asyncio.create_task(ctx.agent_run("prepare", tools=[], budget=18000)) + group = None + try: + await asyncio.wait_for(prepare_started.wait(), 5) + assert ctx.tokens_remaining() == 12000 + thunks = [review, note] + collection = ctx.parallel(thunks) if kind == "parallel" else ctx.pipeline(thunks, run_stage) + group = asyncio.create_task(collection) + await asyncio.wait_for(group_entered.wait(), 5) + release_preparation.set() + assert (await preparer).output == "prepared" + assert ctx.tokens_remaining() == 27000 + start_review.set() + results = await group + grants.extend((session.used_tokens, session.max_budget_tokens) for session in ctx.sessions) + assert not ctx.budget._leases + return results + finally: + release_preparation.set() + start_review.set() + await asyncio.gather(*[task for task in (preparer, group) if task is not None], return_exceptions=True) + + result = await OpenCollab(tmp_path, model="offline", config={"max_output_tokens": 128}).workflow( + workflow, llm=Model(), budget=30000, concurrency=2, task_concurrency=2, + limit_mode="explicit", timeout=15, trace=False, + ) + assert result.status == "completed", result.reason + assert calls[:2] == [("prepare", 128), ("explore", 128)] + assert grants[1][0] == exploration_tokens + if correction_budget is not None: + assert result.output == [{"measurement": 42}, "recorded"] + assert calls[2:] == [("correct", 128)] + assert grants[2] == (5020, correction_budget) + assert result.tokens == 3000 + exploration_tokens + 5020 + else: + assert result.output == [None, "recorded"] + assert len(calls) == 2 + assert grants[2][0] == 0 + assert result.tokens == 3000 + exploration_tokens diff --git a/tests/interfaces/test_sdk_workflow_budget_replay.py b/tests/interfaces/test_sdk_workflow_budget_replay.py new file mode 100644 index 00000000..041b3831 --- /dev/null +++ b/tests/interfaces/test_sdk_workflow_budget_replay.py @@ -0,0 +1,359 @@ +from __future__ import annotations + +import asyncio +import json +from functools import wraps + +import pytest + +from opencollab import OpenCollab, RunControl +from opencollab.adapters.llm.client import LLMClient +from tests.support.provider_sdk_http import completion_http_response, http_response, install_sdk_transport +from tests.support.responses_provider_test_support import message_item +from tests.support.workflow_context_test_support import reserve_request_tokens_until + +REASONING = "I will inspect the import and export paths, then design a test." + + +def _prompt(messages): + content = next(message["content"] for message in reversed(messages) if message["role"] == "user") + return content if isinstance(content, str) else "".join(part["text"] for part in content) + + +def _completion(request, body, protocol, content, reasoning, finish_reason, inputs, outputs): + total = inputs + outputs + if protocol == "anthropic": + blocks = [{"type": "text", "text": content}] if content else [] + if reasoning: + blocks.append({"type": "thinking", "thinking": reasoning, "signature": "fixture-signature"}) + return http_response(request, 200, json={ + "id": "msg_replay", "type": "message", "role": "assistant", "model": body["model"], "content": blocks, + "stop_reason": {"length": "max_tokens", "stop": "end_turn"}.get(finish_reason, finish_reason), + "stop_sequence": None, + "usage": {"input_tokens": inputs, "output_tokens": outputs}, + }) + if protocol == "responses": + assert body["stream"] + items = [message_item(content)] if content else [] + if reasoning: + items.append({"type": "reasoning", "id": "rs_replay", "summary": [ + {"type": "summary_text", "text": reasoning}, + ]}) + status = "incomplete" if finish_reason == "length" else "completed" + terminal = { + "id": "resp_replay", "object": "response", "created_at": 1, "model": body["model"], + "instructions": body.get("instructions"), "status": status, "output": items, "error": None, + "incomplete_details": {"reason": "max_output_tokens"} if status == "incomplete" else None, + "usage": {"input_tokens": inputs, "output_tokens": outputs, "total_tokens": total}, + } + events = [{"type": "response.output_item.done", "output_index": index, "item": item} + for index, item in enumerate(items)] + events.append({"type": f"response.{status}", "response": terminal}) + payload = "".join(f"data: {json.dumps(event)}\n\n" for event in events) + return http_response(request, 200, headers={"content-type": "text/event-stream"}, text=payload) + usage = {"prompt_tokens": inputs, "completion_tokens": outputs, "total_tokens": total} + if body.get("stream"): + fields = {"id": "chat_replay", "object": "chat.completion.chunk", "created": 1, "model": body["model"]} + delta = {"role": "assistant", "content": content} + if reasoning: + delta["reasoning_content"] = reasoning + events = [ + {**fields, "choices": [{"index": 0, "delta": delta, "finish_reason": None}]}, + {**fields, "choices": [{"index": 0, "delta": {}, "finish_reason": finish_reason}]}, + {**fields, "choices": [], "usage": usage}, + ] + payload = "".join(f"data: {json.dumps(event)}\n\n" for event in events) + "data: [DONE]\n\n" + return http_response(request, 200, headers={"content-type": "text/event-stream"}, text=payload) + response = completion_http_response(request, text=content, output_tokens=outputs).json() + response["choices"][0]["finish_reason"] = finish_reason + response["usage"] = usage + return http_response(request, 200, json=response) + + +async def _wait(event): + await asyncio.wait_for(event.wait(), 5) + + +@pytest.mark.parametrize( + "protocol,outcome,sibling_tokens,review_limits,status,output,usage", + [ + ("chat", "complete", 100, [10, 128], "completed", "Review complete", [6000, 6014]), + ("chat", "shortfall", 34950, [10], "stopped", "Useful partial", [6000]), + ("chat", "exhausted", 35050, [10], "stopped", "Useful partial", [6000]), + ("chat", "estimate_changed", 100, [10], "stopped", "Useful partial", [6000]), + ("chat", "busy", 100, [10, 128], "stopped", "Useful partial", [6000]), + ("chat", "context", 100, [10, 128], "stopped", "Useful partial", [6000]), + ("chat", "empty", 100, [10, 128], "stopped", "Useful partial", [6000, 6118]), + ("chat", "output_limit_rejected", 100, [10, 128], "stopped", "Useful partial", [6000]), + ("chat", "uncoded_unsupported_value", 100, [10, 128], "failed", None, [6000]), + ("chat", "generic_output_limit", 100, [10, 128], "stopped", "Useful partial", [6000]), + ("chat", "nonpositive_cap", 100, [10, 128], "failed", None, [6000]), + ("chat", "cap_allows_retry", 100, [10, 128], "failed", None, [6000]), + ("chat_reasoning", "integer_above_max_value", 100, [10, 128], "stopped", "Useful partial", [6000]), + ("responses", "integer_above_max_value", 100, [32, 128], "stopped", "Useful partial", [6000]), + ("anthropic", "integer_above_max_value", 100, [32, 128], "stopped", "Useful partial", [6000]), + ("chat", "unsupported_value", 100, [10, 128], "failed", None, [6000]), + ("chat", "invalid_type", 100, [10, 128], "failed", None, [6000]), + ("chat", "invalid", 100, [10, 128], "failed", None, [6000]), + ("chat", "expired", 100, [10, 128], "failed", None, [6000]), + ("chat", "filtered", 100, [10, 128], "stopped", "", [6000, 5994]), + ("chat_sse", "reasoning", 100, [32, 128], "stopped", "Useful partial", [6000, 6096]), + ("responses", "reasoning", 100, [32, 128], "stopped", "Useful partial", [6000, 6096]), + ("anthropic", "reasoning", 100, [32, 128], "stopped", "Useful partial", [6000, 6096]), + ("anthropic", "decoded_context", 100, [32, 128], "stopped", "Useful partial", [6000, 5980]), + ("anthropic", "decoded_context_extension", 100, [32, 128], "stopped", "Useful partial with counts", + [6000, 5980]), + ("anthropic", "decoded_context_padded_extension", 100, [32, 128], "stopped", + "\nUseful partial with counts ", [6000, 5980]), + ("anthropic", "decoded_context_after_empty", 100, [32, 128], "stopped", "Review findings", [6000, 5980]), + ("anthropic", "decoded_context_after_reasoning", 100, [32, 128], "stopped", "Review findings", [6000, 5980]), + ("anthropic", "clipped_prefix", 100, [32, 128], "stopped", "Useful partial", [6000, 6096]), + ("anthropic", "clipped_padded_prefix", 100, [32, 128], "stopped", "Useful partial", [6000, 6096]), + ("anthropic", "completed_prefix", 100, [32, 128], "completed", "Useful", [6000, 5992]), + ("chat_sse", "reasoning_complete", 100, [32, 128], "stopped", "Useful partial", [6000, 5992]), + ("chat_sse", "partial", 100, [32, 128], "stopped", "More useful partial", [6000, 6096]), + ("chat_sse", "shorter_divergent", 100, [32, 128], "stopped", "Useful partial", [6000, 6096]), + ("chat_sse", "longer_divergent", 100, [32, 128], "stopped", + "Report issues in the contribution guide.", [6000, 6096]), + ], +) +async def test_budget_replay_preserves_first_partial_when_it_cannot_improve( + tmp_path, monkeypatch, protocol, outcome, sibling_tokens, review_limits, status, output, usage, +): + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + ledger = tmp_path / "usage.jsonl" + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(ledger)) + preparing, finish_prepare, collection_entered, start_review = (asyncio.Event() for _ in range(4)) + reviewing, sibling_admitted, finish_sibling, replay_pending, admit_replay = (asyncio.Event() for _ in range(5)) + release_first_reservation = asyncio.Event() + workflow_budget, review_grant = 44000, 13000 + reserve_request_tokens_until(monkeypatch, "review", review_grant - 6000, release_first_reservation) + events, review_payloads, assistant_history = [], [], [] + model = { + "chat_sse": "deepseek-reasoner", "chat_reasoning": "gpt-5", + "responses": "o3", "anthropic": "claude-opus-5-5", + }.get(protocol, "gpt-4o") + provider = "anthropic" if protocol == "anthropic" else "openai" + wire = "responses" if protocol == "responses" else "chat_completions" + output_field = {"chat_reasoning": "max_completion_tokens", "responses": "max_output_tokens"}.get( + protocol, "max_tokens", + ) + review_inputs = 5990 if protocol in {"chat", "chat_reasoning"} else 5968 + output_parameter_errors = { + "output_limit_rejected": (None, "This route supports at most 64 output tokens."), + "uncoded_unsupported_value": (None, "This output parameter is unsupported for the requested model."), + "generic_output_limit": ("invalid_value", f"{output_field} must be less than or equal to 64."), + "nonpositive_cap": (None, f"{output_field} must be less than or equal to 0."), + "cap_allows_retry": ("invalid_value", f"{output_field} must be less than or equal to 128."), + "integer_above_max_value": ("integer_above_max_value", "The maximum allowed value is 64."), + "unsupported_value": ("unsupported_value", "This output parameter is unsupported for the requested model."), + "invalid_type": ("invalid_type", "The output parameter must be an integer."), + } + + class Client(LLMClient): + def estimate_context_tokens(self, messages, **kwargs): + return 10 * len(messages) + + def estimate_request_tokens(self, messages, tools=None, **kwargs): + prompt = _prompt(messages) + if prompt == "review" and outcome == "estimate_changed" and admit_replay.is_set(): + return 6990 + return {"prepare": 2990, "review": review_inputs, "sibling": 90}[prompt] + + @wraps(LLMClient.complete) + async def complete(self, messages, **kwargs): + if _prompt(messages) == "review" and review_payloads: + replay_pending.set() + await _wait(admit_replay) + return await super().complete(messages, **kwargs) + + async def handler(request): + body = json.loads(request.content) + label = _prompt(body.get("messages", body.get("input"))) + limit = body[output_field] + finish_reason = "stop" + reasoning = None + if label == "prepare": + preparing.set() + await _wait(finish_prepare) + content, inputs, outputs = "prepared", 2990, 10 + elif label == "sibling": + sibling_admitted.set() + await _wait(finish_sibling) + content, inputs, outputs = "sibling finished", sibling_tokens - 10, 10 + else: + review_payloads.append(body) + if len(review_payloads) == 1: + reviewing.set() + await _wait(sibling_admitted) + release_first_reservation.set() + finish_reason = "length" + content, inputs, outputs = "Useful partial", review_inputs, limit + if outcome in {"decoded_context_after_empty", "decoded_context_after_reasoning"}: + content = None + if outcome == "decoded_context_after_reasoning": + reasoning = REASONING + elif outcome in {"busy", "invalid"}: + code = 503 if outcome == "busy" else 400 + return http_response(request, code, json={"error": {"message": f"Offline replay {outcome}"}}) + elif outcome in output_parameter_errors: + code, message = output_parameter_errors[outcome] + error = { + "message": message, + "type": "invalid_request_error", + "param": output_field, + } + if code is not None: + error["code"] = code + return http_response(request, 400, json={"error": error}) + elif outcome == "expired": + return http_response(request, 401, json={ + "error": {"message": "Authentication session expired after its idle timeout."}, + }) + elif outcome == "context": + return http_response(request, 400, json={ + "error": {"message": "Maximum context length exceeded", "code": "context_length_exceeded"}, + }) + elif outcome.startswith("decoded_context"): + finish_reason = "model_context_window_exceeded" + content = { + "decoded_context": "Review introduction", + "decoded_context_extension": "Useful partial with counts", + "decoded_context_padded_extension": "\nUseful partial with counts ", + }.get(outcome, "Review findings") + inputs, outputs = review_inputs, 12 + elif outcome.endswith("prefix"): + is_clipped = outcome != "completed_prefix" + finish_reason = "length" if is_clipped else "stop" + content, inputs, outputs = "Useful", review_inputs, limit if is_clipped else 24 + if outcome == "clipped_padded_prefix": + content = "\nUseful " + elif outcome == "empty" or limit < 128: + finish_reason = "length" + content, inputs, outputs = "", 5990, limit + elif outcome == "filtered": + finish_reason = "content_filter" + content, inputs, outputs = "", 5990, 4 + elif outcome.startswith("reasoning"): + finish_reason = "length" if outcome == "reasoning" else "stop" + content, inputs, outputs = None, review_inputs, limit if outcome == "reasoning" else 24 + reasoning = REASONING + elif outcome == "partial": + finish_reason = "length" + content, inputs, outputs = "More useful partial", review_inputs, limit + reasoning = content + elif outcome in {"shorter_divergent", "longer_divergent"}: + finish_reason = "length" + content = "The" if outcome == "shorter_divergent" else "Report issues in the contribution guide." + inputs, outputs = review_inputs, limit + reasoning = "I will review the materials before reporting the remaining issues." + else: + content, inputs, outputs = "Review complete", 5990, 24 + return _completion(request, body, protocol, content, reasoning, finish_reason, inputs, outputs) + + async def workflow(ctx, _inputs): + async def review(): + collection_entered.set() + await _wait(start_review) + return await ctx.agent_run("review", tools=[], run_control=RunControl(on_event=events.append)) + + async def record(): + return "recorded" + + preparation = asyncio.create_task(ctx.agent_run("prepare", budget=18000, tools=[])) + group = sibling = None + try: + await _wait(preparing) + group = asyncio.create_task(ctx.parallel([review, record])) + await _wait(collection_entered) + finish_prepare.set() + assert (await preparation).output == "prepared" + start_review.set() + await _wait(reviewing) + sibling = asyncio.create_task(ctx.agent_run("sibling", budget=10000, tools=[])) + await _wait(replay_pending) + finish_sibling.set() + await sibling + admit_replay.set() + result, note = await group + assert note == "recorded" + assert ctx.tokens_remaining() == workflow_budget - ctx.budget.spent() + review_session = ctx.budget._sessions[1] + assistant_history.extend( + message["content"] for message in review_session.messages if message["role"] == "assistant" + ) + return result + finally: + for event in (finish_prepare, start_review, sibling_admitted, finish_sibling, admit_replay): + event.set() + await asyncio.gather(*(task for task in (preparation, group, sibling) if task), return_exceptions=True) + + install_sdk_transport(monkeypatch, provider, handler) + pool = tmp_path / "pool" + pool.mkdir() + async with Client( + model=model, provider=provider, wire_protocol=wire, api_key=tmp_path.name, + base_url="https://offline.invalid/v1", request_pool=str(pool), request_capacity=2, max_retries=0, + stream_chat=protocol == "chat_sse", + ) as client: + config = {"max_output_tokens": 128, "wire_protocol": wire} + if protocol == "anthropic": + config.update(thinking=True, thinking_params={"thinking": {"type": "adaptive"}}) + result = await OpenCollab(tmp_path, model=model, provider=provider, config=config).workflow( + workflow, llm=client, budget=workflow_budget, concurrency=3, task_concurrency=2, limit_mode="explicit", + artifacts=tmp_path / "artifacts", trace=True, timeout=15, + ) + + assert result.status == "completed", result.reason + row = result.output + assert (row.status, row.output, row.steps) == (status, output, 1) + assert row.hard_budget_tokens == review_grant + assert row.tokens == sum(usage) + assert result.tokens == 3000 + sibling_tokens + row.tokens + trace_path = tmp_path / "artifacts" / "orchestration.jsonl" + rows = [json.loads(line) for line in trace_path.read_text().splitlines()] + completions = [row for row in rows if row["type"] == "llm_call"] + assert sum(row["metrics"]["tokens"] for row in completions) == result.tokens + assert [event.data["total_tokens"] for event in events if event.type == "usage"] == usage + assert [body[output_field] for body in review_payloads] == review_limits + if len(review_limits) > 1: + input_key = "input" if wire == "responses" else "messages" + assert review_payloads[0][input_key] == review_payloads[1][input_key] + if ( + outcome in output_parameter_errors + or outcome.startswith(("reasoning", "decoded_context")) + or outcome.endswith("prefix") + or outcome in {"complete", "shorter_divergent", "longer_divergent"} + ): + assert assistant_history == ([output] if output is not None else []) + ledger_rows = [json.loads(line) for line in ledger.read_text().splitlines()] + ledger_usage = [entry["usage"]["total_tokens"] for entry in ledger_rows] + expected_ledger_usage = [3000, sibling_tokens, *usage] + if outcome in output_parameter_errors: + expected_ledger_usage.append(0) + [error] = [entry for entry in ledger_rows if entry["status"] == "error"] + assert error["error"]["type"] == "BadRequestError" + assert error["usage"]["total_tokens"] == 0 + if status == "failed": + assert row.reason == "run failed: BadRequestError" + assert sorted(ledger_usage) == sorted(expected_ledger_usage) + if outcome.startswith("reasoning"): + discarded = [row for row in completions if row["payload"].get("reasoning") == REASONING] + assert len(discarded) == 1 + assert discarded[0]["payload"]["purpose"] == "budget_recovery" + if outcome in { + "decoded_context", "clipped_prefix", "clipped_padded_prefix", "shorter_divergent", "longer_divergent", + }: + [discarded] = [row for row in completions if row["payload"].get("purpose") == "budget_recovery"] + assert (discarded["payload"]["finish_reason"], discarded["payload"]["content"]) == { + "decoded_context": ("model_context_window_exceeded", "Review introduction"), + "clipped_prefix": ("max_tokens", "Useful"), + "clipped_padded_prefix": ("max_tokens", "\nUseful "), + "shorter_divergent": ("length", "The"), + "longer_divergent": ("length", "Useful partial"), + }[outcome] + if outcome == "filtered": + assert row.reason == "provider filtered the output" + if outcome == "expired": + assert "AuthenticationError" in row.reason diff --git a/tests/interfaces/test_sdk_workflow_budget_replay_timeout.py b/tests/interfaces/test_sdk_workflow_budget_replay_timeout.py new file mode 100644 index 00000000..5a03c10d --- /dev/null +++ b/tests/interfaces/test_sdk_workflow_budget_replay_timeout.py @@ -0,0 +1,156 @@ +from __future__ import annotations + +import asyncio +import json + +import pytest + +from opencollab import OpenCollab +from opencollab.adapters.llm.client import LLMClient +from tests.support.provider_sdk_http import completion_http_response, http_response, install_sdk_transport +from tests.support.workflow_context_test_support import reserve_request_tokens_until + + +@pytest.mark.parametrize("scene", ["role_timeout", "reasoning_timeout", "workflow_cancel", "completed_replay"]) +async def test_optional_budget_replay_at_a_workflow_role_deadline(tmp_path, monkeypatch, scene): + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + ledger_path = tmp_path / "usage.jsonl" + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(ledger_path)) + preparation_started, release_preparation, preparation_finished = (asyncio.Event() for _ in range(3)) + replay_started, replay_cancelled = asyncio.Event(), asyncio.Event() + requests = [] + calls = [] + partial = "Checked items 1 through 42." + complete = "Checked all 87 items. Inventory reconciled." + hidden = "I should check the remaining rows." + prepare_prompt = "Load the local inventory." + review_prompt = "Review the inventory." + workflow_budget = 45_000 + if scene != "reasoning_timeout": + workflow_budget = 59_000 + reserve_request_tokens_until(monkeypatch, review_prompt, 7000, preparation_finished) + + def prompt_for(messages): + return next((row["content"] for row in reversed(messages) if row["role"] == "user"), "") + + def estimate(_client, messages, tools=None, **kwargs): + return {prepare_prompt: 2990, review_prompt: 5990}.get(prompt_for(messages), 100) + + async def reply(request): + payload = json.loads(request.content) + prompt = prompt_for(payload["messages"]) + requests.append((prompt, payload["max_tokens"])) + if prompt == prepare_prompt: + preparation_started.set() + await release_preparation.wait() + answer, input_tokens, output_tokens, finish = "Inventory loaded.", 2990, 10, "stop" + else: + assert prompt == review_prompt + calls.append(payload["messages"]) + if len(calls) == 1: + release_preparation.set() + await preparation_finished.wait() + answer, input_tokens, output_tokens, finish = partial, 5990, 10, "length" + else: + replay_started.set() + if scene != "completed_replay": + try: + await asyncio.Future() + except asyncio.CancelledError: + replay_cancelled.set() + raise + answer, input_tokens, output_tokens, finish = complete, 5990, 24, "stop" + response = completion_http_response(request, text=answer, output_tokens=output_tokens).json() + choice = response["choices"][0] + choice["finish_reason"] = finish + if scene == "reasoning_timeout" and finish == "length": + choice["message"].update(content=None, reasoning_content=hidden) + response["usage"].update(prompt_tokens=input_tokens, total_tokens=input_tokens + output_tokens) + return http_response(request, 200, json=response) + + monkeypatch.setattr(LLMClient, "estimate_request_tokens", estimate) + install_sdk_transport(monkeypatch, "openai", reply) + + async def flow(ctx, _inputs): + async def prepare(): + result = await ctx.agent_run(prepare_prompt, tools=[], budget=33_000) + assert result.output == "Inventory loaded." + preparation_finished.set() + + async def review(): + return await ctx.agent_run(review_prompt, label="review", tools=[], timeout=2) + + async def record(): + return "Inventory date recorded." + + pending = asyncio.create_task(prepare()) + try: + await asyncio.wait_for(preparation_started.wait(), 5) + result, note = await ctx.parallel([review, record]) + assert note == "Inventory date recorded." + return result + finally: + release_preparation.set() + await pending + + artifacts = tmp_path / "artifacts" + client = OpenCollab( + tmp_path, model="gpt-4o", provider="openai", api_key=tmp_path.name, base_url="https://fixture.invalid/v1", + config={"wire_protocol": "chat_completions", "llm_stream_chat": False, + "llm_max_retries": 0, "max_output_tokens": 128}, + ) + cancellations = [] + + async def run(): + try: + return await client.workflow( + flow, budget=workflow_budget, concurrency=2, task_concurrency=2, limit_mode="explicit", + artifacts=artifacts, trace=True, timeout=12, cleanup_timeout=2, + ) + except asyncio.CancelledError as error: + cancellations.append(error) + raise + + operation = asyncio.create_task(run()) + if scene == "workflow_cancel": + try: + await asyncio.wait_for(replay_started.wait(), 5) + operation.cancel("caller cancelled the workflow") + with pytest.raises(asyncio.CancelledError): + await operation + [cancelled] = cancellations + assert str(cancelled) == "caller cancelled the workflow" + details = cancelled.runtime_result + assert details.output is None and details.tokens == 9000 + finally: + if not operation.done(): + operation.cancel() + await asyncio.gather(operation, return_exceptions=True) + else: + result = await operation + assert result.ok and result.metrics["execution_quiesced"] + row = result.output + assert row.cleanup_complete and row.workspace_ready + if scene == "completed_replay": + assert (row.status, row.reason, row.output, row.tokens) == ("completed", None, complete, 12_014) + else: + expected = partial if scene == "role_timeout" else None + assert (row.status, row.reason, row.output, row.tokens) == ("stopped", "timeout", expected, 6000) + + assert requests == [(prepare_prompt, 128), (review_prompt, 10), (review_prompt, 128)] + assert calls[0] == calls[1] + assert replay_cancelled.is_set() is (scene != "completed_replay") + manifest = json.loads((artifacts / "workflow.json").read_text()) + ledger = [json.loads(line) for line in ledger_path.read_text().splitlines()] + tokens = 15_014 if scene == "completed_replay" else 9000 + assert manifest["tokens_spent"] == sum(row["usage"]["total_tokens"] for row in ledger) == tokens + assert manifest["evidence_complete"] + assert manifest["status"] == ("stopped" if scene == "workflow_cancel" else "completed") + if scene != "workflow_cancel": + assert result.tokens == tokens and not result.agent_failures + + transcript, = artifacts.glob("*_review.json") + snapshot = client.read_session_snapshot(transcript) + assistant = [row["content"] for row in snapshot["messages"] if row["role"] == "assistant"] + assert assistant == ([complete] if scene == "completed_replay" else []) diff --git a/tests/interfaces/test_sdk_workflow_cleanup_failure.py b/tests/interfaces/test_sdk_workflow_cleanup_failure.py new file mode 100644 index 00000000..b38fa068 --- /dev/null +++ b/tests/interfaces/test_sdk_workflow_cleanup_failure.py @@ -0,0 +1,148 @@ +"""SDK workflow evidence retains its original outcome when owned cleanup fails.""" + +from __future__ import annotations + +import asyncio +import errno +import json +from pathlib import Path + +import pytest + +from opencollab import OpenCollab, RunError +from opencollab.adapters import _env_local +from opencollab.bootstrap.workflow_runtime import WorkflowDeadlineExceeded +from tests.support.provider_sdk_http import completion_http_response, http_response, install_sdk_transport + + +def _causes(error): + found = [] + pending = [error] + while pending: + candidate = pending.pop() + if candidate is None or any(candidate is seen for seen in found): + continue + found.append(candidate) + pending.extend((candidate.__cause__, candidate.__context__)) + return found + + +@pytest.mark.parametrize("cleanup_fails", [False, True]) +@pytest.mark.parametrize("outcome", ["completed", "workflow_exception", "deadline"]) +async def test_workflow_cleanup_preserves_outcome_and_errors(tmp_path, monkeypatch, outcome, cleanup_fails): + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(tmp_path / "usage.jsonl")) + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + workspace = tmp_path / "workspace" + workspace.mkdir() + (workspace / "inventory.txt").write_text("Inventory subtotal 42\n", encoding="utf-8") + invalid = "missing-column-value" + (workspace / "calibration.txt").write_text( + invalid if outcome == "workflow_exception" else "3", encoding="utf-8", + ) + + requests = [] + + def respond(request): + body = json.loads(request.content) + requests.append(body) + tool_results = [row["content"] for row in body["messages"] if row["role"] == "tool"] + if tool_results: + assert "Inventory subtotal 42" in tool_results[-1] + return completion_http_response(request, text="Verified subtotal 42.", output_tokens=3) + return http_response(request, 200, json={ + "id": "inventory-completion", "object": "chat.completion", "created": 1, "model": body["model"], + "choices": [{"index": 0, "finish_reason": "tool_calls", "message": { + "role": "assistant", "content": None, "tool_calls": [{ + "id": "inventory-read", "type": "function", "function": { + "name": "file_read", "arguments": json.dumps({"path": "inventory.txt"}), + }, + }], + }}], + "usage": {"prompt_tokens": 2, "completion_tokens": 3, "total_tokens": 5}, + }) + + install_sdk_transport(monkeypatch, "openai", respond) + artifacts = tmp_path / "artifacts" + path = artifacts / "workflow.json" + owned_files = [] + before_cleanup = [] + cleanup_error = OSError(errno.EIO, "verifier scratch cleanup I/O error") + fault_armed = cleanup_fails + unlink_file = _env_local.unlink_regular_file_durable_at + + def unlink(root_fd, base, relative_path, **kwargs): + if fault_armed and str(relative_path).startswith("verification-"): + before_cleanup.append(json.loads(path.read_text())) + raise cleanup_error + return unlink_file(root_fd, base, relative_path, **kwargs) + + monkeypatch.setattr(_env_local, "unlink_regular_file_durable_at", unlink) + + async def flow(ctx, _inputs): + report = await ctx.agent("Read the inventory subtotal.", tools="read", label="verifier") + assert report == "Verified subtotal 42." + environment = ctx.sessions[0].env + scratch = Path(await environment.write_temp_file(report, prefix="verification-")) + owned_files.append((environment, scratch)) + assert scratch.read_text() == report + if outcome == "deadline": + await asyncio.Future() + return {"report": report, "calibration": int((workspace / "calibration.txt").read_text())} + + app = OpenCollab( + workspace, model="offline-verifier", provider="openai", + api_key="fixture-unused", # pragma: allowlist secret + base_url="https://fixture.invalid/v1", + config={"wire_protocol": "chat_completions", "llm_stream_chat": False, "llm_max_retries": 0}, + ) + expected = { + "workflow_exception": ("failed", "workflow_exception", "ValueError"), + "deadline": ("stopped", "cancelled", "CancelledError"), + "completed": ("completed", None, None), + }[outcome] + operation = app.workflow( + flow, artifacts=artifacts, trace=False, budget=80_000, cleanup_timeout=1, + timeout=2 if outcome == "deadline" else None, run_id="inventory-audit", + ) + try: + if cleanup_fails: + with pytest.raises(RunError) as caught: + await operation + causes = _causes(caught.value) + assert cleanup_error in causes + assert all(not item["evidence_complete"] for item in before_cleanup) + assert before_cleanup + if outcome == "workflow_exception": + assert any(isinstance(exc, ValueError) and invalid in str(exc) for exc in causes) + elif outcome == "deadline": + deadline, = [exc for exc in causes if isinstance(exc, WorkflowDeadlineExceeded)] + assert str(deadline) == "workflow wall-clock deadline expired" + assert deadline.result is not None and deadline.result.tokens == 10 + else: + expected = ("failed", "environment_cleanup_failed", "ProgrammaticLifecycleError") + assert owned_files[0][1].is_file() + else: + result = await operation + assert result.tokens == 10 and result.metrics["execution_quiesced"] is True + if outcome == "workflow_exception": + assert result.status == "failed" and invalid in result.reason + assert isinstance(result.error, ValueError) + elif outcome == "deadline": + assert result.status == "stopped" and result.reason == "timeout" + assert isinstance(result.error, WorkflowDeadlineExceeded) + else: + assert result.ok and result.output == {"report": "Verified subtotal 42.", "calibration": 3} + assert not owned_files[0][1].exists() + + assert len(requests) == 2 + manifest = json.loads(path.read_text()) + assert manifest["run_id"] == "inventory-audit" + assert manifest["tokens_spent"] == 10 + assert (manifest["status"], manifest["reason"], manifest["failure_type"]) == expected + assert manifest["evidence_complete"] is (not cleanup_fails) + finally: + fault_armed = False + for environment, scratch in owned_files: + if scratch.exists(): + await environment.cleanup() diff --git a/tests/interfaces/test_sdk_workflow_deadline_result.py b/tests/interfaces/test_sdk_workflow_deadline_result.py new file mode 100644 index 00000000..21ec9cc2 --- /dev/null +++ b/tests/interfaces/test_sdk_workflow_deadline_result.py @@ -0,0 +1,81 @@ +from __future__ import annotations + +import asyncio +import json + +import pytest + +from opencollab import OpenCollab +from opencollab.adapters.llm.client import LLMClient +from opencollab.application.workflow import WorkflowBudgetExceeded +from tests.support.provider_sdk_http import completion_http_response, install_sdk_transport + + +@pytest.mark.parametrize("scene", ["normal", "during-close", "during-body", "return-on-cancel", "budget-stop"]) +async def test_workflow_deadline_keeps_only_output_returned_before_timeout(tmp_path, monkeypatch, scene): + closing = asyncio.Event() + closed = asyncio.Event() + release = asyncio.Event() + body_returns = [] + original_close = LLMClient.close + timeout = 1.0 + + async def close(client): + closing.set() + await release.wait() + await original_close(client) + closed.set() + + async def measure(ctx, _inputs): + answer = await ctx.agent("Measure the subtotal.", tools=[]) + assert answer == "Verified subtotal" + if scene == "budget-stop": + raise WorkflowBudgetExceeded("No budget for another measurement.") + if scene in {"during-body", "return-on-cancel"}: + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + if scene == "during-body": + raise + answer = "Only returned on cancellation" + body_returns.append(answer) + return {"measurement": answer} + + monkeypatch.setattr(LLMClient, "close", close) + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(tmp_path / "usage.jsonl")) + install_sdk_transport(monkeypatch, "openai", lambda request: completion_http_response( + request, text="Verified subtotal", output_tokens=5, + )) + client = OpenCollab( + tmp_path, model="offline-checker", provider="openai", api_key=tmp_path.name, + base_url="https://fixture.invalid/v1", config={"wire_protocol": "chat_completions", "llm_stream_chat": False}, + ) + artifacts = tmp_path / "artifacts" + task = asyncio.create_task(client.workflow( + measure, artifacts=artifacts, trace=False, budget=80_000, timeout=timeout, cleanup_timeout=2, + )) + try: + if scene in {"normal", "during-close", "budget-stop"}: + await asyncio.wait_for(closing.wait(), timeout=2) + assert body_returns == ([] if scene == "budget-stop" else ["Verified subtotal"]) + if scene in {"during-close", "budget-stop"}: + await asyncio.sleep(timeout + 0.05) + release.set() + result = await asyncio.wait_for(task, timeout=3) + finally: + release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + assert closed.is_set() + manifest = json.loads((artifacts / "workflow.json").read_text()) + assert manifest["evidence_complete"] is True + assert result.tokens == manifest["tokens_spent"] == 7 + assert result.status == ("completed" if scene == "normal" else "stopped") + assert result.reason == (None if scene == "normal" else "timeout") + if scene in {"normal", "during-close"}: + assert result.output == {"measurement": "Verified subtotal"} + else: + assert body_returns == (["Only returned on cancellation"] if scene == "return-on-cancel" else []) + assert result.output is None diff --git a/tests/interfaces/test_sdk_workflow_deferred_collection_budget.py b/tests/interfaces/test_sdk_workflow_deferred_collection_budget.py new file mode 100644 index 00000000..98288c3b --- /dev/null +++ b/tests/interfaces/test_sdk_workflow_deferred_collection_budget.py @@ -0,0 +1,338 @@ +from __future__ import annotations + +import asyncio + +import pytest + +from opencollab import OpenCollab +from opencollab.adapters.llm.types import LLMResponse, Usage + + +@pytest.mark.parametrize("kind", ["parallel", "pipeline", "nested"]) +@pytest.mark.parametrize("start", ["overlap", "after", "explicit"]) +@pytest.mark.parametrize("first_reservation", [20000, 19999]) +async def test_collection_can_spend_budget_released_during_preparation(tmp_path, kind, start, first_reservation): + first_started, release_first = asyncio.Event(), asyncio.Event() + prepared, budget_released = asyncio.Event(), asyncio.Event() + calls, rows = [], [] + input_tokens, output_limit = 256, 128 + + class Model: + def estimate_request_tokens(self, messages, tools, **kwargs): + return input_tokens + + async def complete(self, messages, **kwargs): + prompt = messages[-1]["content"].splitlines()[0] + calls.append(prompt) + if prompt == "prepare source": + first_started.set() + await release_first.wait() + return LLMResponse(content="prepared", usage=Usage(4990, 10)) + assert kwargs["max_output_tokens"] == output_limit + return LLMResponse(content=f"summary of {prompt}", usage=Usage(5, 10)) + + async def flow(ctx, _inputs): + async def summarize(name): + prepared.set() + await budget_released.wait() + row = await ctx.agent_run(name, tools=[], budget=7500 if start == "explicit" else None) + rows.append(row) + return row.output + + async def stage(_previous, name, _index): + return await summarize(name) + + async def collect(): + if kind == "pipeline": + return await ctx.pipeline(["first.txt", "second.txt"], stage) + if kind == "nested": + async def group(): + return await ctx.pipeline(["first.txt", "second.txt"], stage) + + return (await ctx.parallel([group]))[0] + return await ctx.parallel([ + lambda: summarize("first.txt"), + lambda: summarize("second.txt"), + ]) + + first = asyncio.create_task(ctx.agent_run("prepare source", tools=[], budget=first_reservation)) + collection = None + try: + await first_started.wait() + assert ctx.tokens_remaining() == 20000 - first_reservation + if start != "after": + collection = asyncio.create_task(collect()) + await prepared.wait() + release_first.set() + assert (await first).output == "prepared" + assert ctx.tokens_remaining() == 15000 + budget_released.set() + return await (collection if collection is not None else collect()) + finally: + release_first.set() + budget_released.set() + await asyncio.gather(first, *([collection] if collection else []), return_exceptions=True) + + result = await OpenCollab( + tmp_path, model="test-model", config={"max_output_tokens": output_limit}, + ).workflow( + flow, llm=Model(), budget=20000, concurrency=2, + task_concurrency=2, trace=False, limit_mode="explicit", timeout=10, + ) + + assert result.status == "completed", result.reason + grant = input_tokens + output_limit if start == "overlap" else 7500 + assert [(row.status, row.hard_budget_tokens, row.reason) for row in rows] == [ + ("completed", grant, None), + ("completed", grant, None), + ] + assert result.output == ["summary of first.txt", "summary of second.txt"] + assert sorted(calls) == ["first.txt", "prepare source", "second.txt"] + assert result.tokens == 5030 + +@pytest.mark.parametrize("kind", ["parallel", "pipeline", "nested"]) +@pytest.mark.parametrize("explicit_first", [False, True]) +async def test_explicit_peer_preserves_collection_share(tmp_path, monkeypatch, kind, explicit_first): + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + started, release = asyncio.Event(), asyncio.Event() + calls, rows = [], {} + prepare, review = "Preparation", "Read the following notes." + first_prompt = prepare if explicit_first else review + notes = review + "\n" + " report" * 2800 + + class Model: + async def complete(self, messages, **kwargs): + prompt = messages[-1]["content"].splitlines()[0] + calls.append(prompt) + if prompt == first_prompt: + started.set() + await release.wait() + return LLMResponse(content=prompt, usage=Usage(8, 7)) + + async def flow(ctx, _inputs): + async def run_item(item): + explicit = item == prepare + first = explicit == explicit_first + if not first: + await asyncio.wait_for(started.wait(), 5) + assert ctx.tokens_remaining() == (8000 if explicit_first else 10000) + try: + row = await ctx.agent_run(item, tools=[], budget=12000 if explicit else None) + rows["prepare" if explicit else "review"] = row + return row.output + finally: + if not first: + release.set() + + async def stage(_previous, item, _index): + return await run_item(item) + + async def pipeline(): + return await ctx.pipeline([prepare, notes], stage) + + if kind == "nested": + return (await ctx.parallel([pipeline]))[0] + if kind == "pipeline": + return await pipeline() + return await ctx.parallel([lambda: run_item(prepare), lambda: run_item(notes)]) + + result = await OpenCollab( + tmp_path, model="test-model", config={"max_output_tokens": 128}, + ).workflow( + flow, llm=Model(), budget=20000, concurrency=2, task_concurrency=2, + timeout=10, trace=False, limit_mode="explicit", system_prompt="Summarize one detail.", + ) + + grants = [12000, 8000] if explicit_first else [10000, 10000] + results = [rows["prepare"], rows["review"]] + assert result.status == "completed", result.reason + assert [row.status for row in results] == ["completed", "completed"] + assert [row.hard_budget_tokens for row in results] == grants + assert result.output == [prepare, review] + assert sorted(calls) == sorted([prepare, review]) + assert result.tokens == 30 + +@pytest.mark.parametrize("hold_external", [False, True], ids=["already-released", "still-reserved"]) +async def test_collection_keeps_live_available_budget_during_later_temporary_reservation( + tmp_path, monkeypatch, hold_external, +): + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + preparing, admit_collection = asyncio.Event(), asyncio.Event() + external_started, release_external, external_finished = asyncio.Event(), asyncio.Event(), asyncio.Event() + first_finished = asyncio.Event() + prompt = "Summarize the detailed report.\n" + " report" * 2800 + grants = {} + + class Model: + async def complete(self, messages, **kwargs): + request = [row["content"] for row in messages if row["role"] == "user"][-1].splitlines()[0] + if request == "Annotate the other document.": + external_started.set() + await release_external.wait() + return LLMResponse(content=request, usage=Usage(8, 7)) + + async def flow(ctx, _inputs): + async def first(): + preparing.set() + await admit_collection.wait() + try: + row = await ctx.agent_run(prompt, tools=[]) + grants["first"] = row + return row.output + finally: + first_finished.set() + + async def second(): + await external_finished.wait() + row = await ctx.agent_run("Summarize the short report.", tools=[]) + grants["second"] = row + return row.output + + async def outside_collection(): + row = await ctx.agent_run("Annotate the other document.", tools=[], budget=12000) + grants["external"] = row + external_finished.set() + return row.output + + collection = asyncio.create_task(ctx.parallel([first, second])) + outside = None + try: + await asyncio.wait_for(preparing.wait(), 4) + assert ctx.tokens_remaining() == 20000 + outside = asyncio.create_task(outside_collection()) + await asyncio.wait_for(external_started.wait(), 4) + assert ctx.tokens_remaining() == 8000 + if not hold_external: + release_external.set() + await outside + admit_collection.set() + await asyncio.wait_for(first_finished.wait(), 4) + release_external.set() + await outside + return await collection + finally: + admit_collection.set() + release_external.set() + external_finished.set() + await asyncio.gather(collection, *([outside] if outside is not None else []), return_exceptions=True) + + result = await OpenCollab( + tmp_path, model="offline", config={"max_output_tokens": 128}, + ).workflow( + flow, llm=Model(), budget=20000, concurrency=2, task_concurrency=2, timeout=10, + trace=False, limit_mode="explicit", system_prompt="Summarize one detail.", + ) + assert result.status == "completed", result.reason + assert result.output == ["Summarize the detailed report.", "Summarize the short report."] + assert result.tokens == 45 + assert all(row.status == "completed" for row in grants.values()) + if hold_external: + assert grants["first"].hard_budget_tokens == 8000 + else: + assert 9900 <= grants["first"].hard_budget_tokens <= 10000 + +@pytest.mark.parametrize("nested", [False, True], ids=["direct", "nested"]) +async def test_parent_balance_uses_its_own_entry_and_live_admission(tmp_path, monkeypatch, nested): + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + + preparation_started, settle_preparation = asyncio.Event(), asyncio.Event() + parent_preparing, start_first_group = asyncio.Event(), asyncio.Event() + first_group_entered, admit_first = asyncio.Event(), asyncio.Event() + outside_started, settle_outside = asyncio.Event(), asyncio.Event() + first_started, finish_first = asyncio.Event(), asyncio.Event() + second_attempted = asyncio.Event() + grants = {} + + class Model: + def estimate_request_tokens(self, messages, tools, **kwargs): + prompt = [row["content"] for row in messages if row["role"] == "user"][-1] + return 3999 if prompt.startswith("Summarize the") else 256 + + async def complete(self, messages, **kwargs): + prompt = [row["content"] for row in messages if row["role"] == "user"][-1] + if prompt == "Prepare a set of notes.": + preparation_started.set() + await settle_preparation.wait() + return LLMResponse(content=prompt, usage=Usage(3990, 10)) + if prompt == "Annotate the unrelated document.": + outside_started.set() + await settle_outside.wait() + elif prompt == "Summarize the first report.": + first_started.set() + await finish_first.wait() + return LLMResponse(content=prompt, usage=Usage(8, 7)) + + async def flow(ctx, _inputs): + async def first_item(): + assert ctx.tokens_remaining() == 16000 + first_group_entered.set() + await admit_first.wait() + row = await ctx.agent_run("Summarize the first report.", tools=[]) + grants["first"] = row.hard_budget_tokens + return row.output + + async def stage(_previous, _item, _index): + return await first_item() + + async def first_group(): + assert ctx.tokens_remaining() == 4000 + parent_preparing.set() + await start_first_group.wait() + if nested: + return (await ctx.pipeline(["first"], stage))[0] + return await first_item() + + async def second_group(): + await first_started.wait() + assert ctx.tokens_remaining() == 4000 + try: + row = await ctx.agent_run("Summarize the second report.", tools=[]) + grants["second"] = row.hard_budget_tokens + return row.output + finally: + second_attempted.set() + + first = asyncio.create_task(ctx.agent_run("Prepare a set of notes.", tools=[], budget=16000)) + tasks = [first] + try: + await asyncio.wait_for(preparation_started.wait(), 4) + assert ctx.tokens_remaining() == 4000 + collection = asyncio.create_task(ctx.parallel([first_group, second_group])) + tasks.append(collection) + await asyncio.wait_for(parent_preparing.wait(), 4) + settle_preparation.set() + assert (await first).output == "Prepare a set of notes." + assert ctx.tokens_remaining() == 16000 + start_first_group.set() + await asyncio.wait_for(first_group_entered.wait(), 4) + other = asyncio.create_task(ctx.agent_run("Annotate the unrelated document.", tools=[], budget=8000)) + tasks.append(other) + await asyncio.wait_for(outside_started.wait(), 4) + assert ctx.tokens_remaining() == 8000 + admit_first.set() + await asyncio.wait_for(second_attempted.wait(), 4) + finish_first.set() + settle_outside.set() + await other + return await collection + finally: + settle_preparation.set() + start_first_group.set() + admit_first.set() + finish_first.set() + settle_outside.set() + await asyncio.gather(*tasks, return_exceptions=True) + + result = await OpenCollab( + tmp_path, model="offline", config={"max_output_tokens": 128}, + ).workflow( + flow, llm=Model(), budget=20000, concurrency=3, task_concurrency=3, timeout=10, + trace=False, limit_mode="explicit", system_prompt="Summarize one detail.", + ) + assert result.status == "completed", result.reason + assert result.output == ["Summarize the first report.", "Summarize the second report."] + assert result.tokens == 4045 + assert grants == {"first": 4000, "second": 4000} diff --git a/tests/interfaces/test_sdk_workflow_finite_json.py b/tests/interfaces/test_sdk_workflow_finite_json.py new file mode 100644 index 00000000..3b234589 --- /dev/null +++ b/tests/interfaces/test_sdk_workflow_finite_json.py @@ -0,0 +1,156 @@ +"""Structured workflow results and their traces can be consumed as JSON.""" + +import asyncio +import json + +import pytest + +from opencollab import OpenCollab +from opencollab.adapters.llm.types import LLMResponse, Usage +from tests.support.provider_sdk_http import ( + completion_http_response, + http_response, + install_sdk_transport, +) + + +def _reject_constant(value): + raise ValueError(f"non-JSON number {value}") + + +def _assert_json_artifacts(artifacts): + for path in artifacts.glob("*.json"): + json.loads(path.read_text(), parse_constant=_reject_constant) + for path in artifacts.glob("*.jsonl"): + for line in path.read_text().splitlines(): + json.loads(line, parse_constant=_reject_constant) + + +@pytest.mark.parametrize(("provider", "number"), [ + ("openai", "2.5"), ("openai", "NaN"), ("openai", "1e309"), + ("anthropic", "2.5"), ("anthropic", "1e309"), +]) +async def test_workflow_repairs_unrepresentable_nested_tool_numbers(tmp_path, monkeypatch, provider, number): + requests = [] + + def reply(request): + requests.append(json.loads(request.content)) + assert len(requests) <= 2 + value = number if len(requests) == 1 else "null" + response = completion_http_response(request).json() + if provider == "anthropic": + response["stop_reason"] = "tool_use" + response["content"] = [{ + "id": f"capture-{len(requests)}", + "type": "tool_use", + "name": "structured_output", + "input": {"samples": [{"mean": "__fixture_mean__"}]}, + }] + raw = json.dumps(response).replace('"__fixture_mean__"', value) + return http_response(request, 200, headers={"content-type": "application/json"}, content=raw) + choice = response["choices"][0] + choice["finish_reason"] = "tool_calls" + choice["message"].update(content=None, tool_calls=[{ + "id": f"capture-{len(requests)}", + "type": "function", + "function": { + "name": "structured_output", + "arguments": '{"samples":[{"mean":' + value + '}]}', + }, + }]) + return http_response(request, 200, json=response) + + install_sdk_transport(monkeypatch, provider, reply) + artifacts = tmp_path / "artifacts" + output = tmp_path / "report.json" + schema = {"type": "object", "properties": {"samples": {"type": "array"}}, "required": ["samples"]} + + async def flow(ctx, _inputs): + report = await ctx.agent("Report the measurements.", tools=[], schema=schema) + output.write_text(json.dumps(report, allow_nan=False)) + return report + + result = await OpenCollab( + tmp_path, provider=provider, model="offline-measurement", + api_key=__name__, base_url="https://offline.invalid/v1", + ).workflow(flow, artifacts=artifacts, trace=True, timeout=10) + + assert result.status == "completed" + repaired = number != "2.5" + expected = {"samples": [{"mean": None if repaired else 2.5}]} + assert result.output == json.loads(output.read_text(), parse_constant=_reject_constant) == expected + assert len(requests) == (2 if repaired else 1) + assert result.tokens == 4 * len(requests) + if repaired: + assert "Error: invalid JSON arguments" in json.dumps(requests[1]["messages"]) + _assert_json_artifacts(artifacts) + + +@pytest.mark.parametrize("finite", [False, True]) +async def test_workflow_records_preparsed_arguments_as_text(tmp_path, finite): + calls = 0 + + class Model: + async def complete(self, messages, **kwargs): + nonlocal calls + calls += 1 + mean = 2.5 if finite else (float("nan") if calls == 1 else None) + return LLMResponse( + finish_reason="tool_calls", usage=Usage(2, 2), + tool_calls=[{ + "id": f"capture-{calls}", + "type": "function", + "function": { + "name": "structured_output", + "arguments": {"samples": [{"mean": mean}]}, + }, + }], + ) + + schema = {"type": "object", "properties": {"samples": {"type": "array"}}, "required": ["samples"]} + artifacts = tmp_path / "artifacts" + + async def flow(ctx, _inputs): + return await ctx.agent("Report the samples.", schema=schema, tools=[]) + + result = await OpenCollab(tmp_path, model="offline").workflow( + flow, llm=Model(), artifacts=artifacts, trace=True, timeout=10, + ) + + assert result.status == "completed" + assert result.output == {"samples": [{"mean": 2.5 if finite else None}]} + assert calls == (1 if finite else 2) + assert result.tokens == 4 * calls + _assert_json_artifacts(artifacts) + + +@pytest.mark.parametrize("external_change", [False, True]) +@pytest.mark.parametrize("depth", [0, 520], ids=["shallow", "deep"]) +async def test_workflow_manifest_snapshots_args_before_execution(tmp_path, external_change, depth): + samples = [2.5] + for _ in range(depth): + samples = [samples] + inputs = {"samples": samples} + artifacts = tmp_path / "artifacts" + + async def flow(_ctx, args): + if not external_change: + args["samples"].append(float("-inf")) + return len(args["samples"]) + + pending = asyncio.create_task(OpenCollab(tmp_path).workflow( + flow, inputs, artifacts=artifacts, trace=False, + )) + if external_change: + await asyncio.sleep(0) + assert (artifacts / ".opencollab-run").exists() + inputs["samples"].append(float("-inf")) + + result = await pending + assert result.ok and result.output == 2 + manifest = json.loads((artifacts / "workflow.json").read_text(), parse_constant=_reject_constant) + recorded = manifest["args"]["samples"] + for _ in range(depth): + recorded, = recorded + assert recorded == [2.5] + assert manifest["evidence_complete"] is True diff --git a/tests/interfaces/test_sdk_workflow_nested_collections.py b/tests/interfaces/test_sdk_workflow_nested_collections.py index 7bbec734..d9a647da 100644 --- a/tests/interfaces/test_sdk_workflow_nested_collections.py +++ b/tests/interfaces/test_sdk_workflow_nested_collections.py @@ -1,6 +1,7 @@ from __future__ import annotations import asyncio +import json import pytest @@ -60,3 +61,142 @@ async def group(): assert events == ["producer-start", "first-put", "consumer-start", "second-put"] assert result.metrics["execution_quiesced"] is True assert contexts[0]._task_semaphore._value == capacity + + +@pytest.mark.asyncio +@pytest.mark.parametrize("release_slot_later", [False, True]) +async def test_independent_nested_collections_use_the_second_slot(tmp_path, release_slot_later): + queue = asyncio.Queue(maxsize=1) + filled = asyncio.Event() + other_started = asyncio.Event() + consumer_waiting = asyncio.Event() + + async def flow(ctx, _inputs): + async def produce(): + if release_slot_later: + await other_started.wait() + await queue.put("first") + filled.set() + await queue.put("second") + return "produced" + + async def consume(_previous, _item, _index): + values = [await queue.get(), await queue.get()] + (tmp_path / "delivered.txt").write_text("\n".join(values)) + return values + + async def receive(): + await filled.wait() + consumer_waiting.set() + return (await ctx.pipeline(["stream"], consume))[0] + + async def combined(): + written, read = await asyncio.gather(ctx.parallel([produce]), receive()) + return [written[0], read] + + async def other(): + other_started.set() + await consumer_waiting.wait() + return "finished" + + result = await ctx.parallel([combined, other] if release_slot_later else [combined]) + assert await ctx.parallel([lambda: asyncio.sleep(0, result="next")] * 2) == ["next", "next"] + return result + + result = await OpenCollab(tmp_path, model="offline").workflow( + flow, concurrency=2, task_concurrency=2, timeout=5, trace=False, + ) + expected = [["produced", ["first", "second"]]] + if release_slot_later: + expected.append("finished") + assert result.status == "completed" + assert result.output == expected + assert (tmp_path / "delivered.txt").read_text() == "first\nsecond" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("valid", [False, True]) +@pytest.mark.parametrize("layout", ["separate-collections", "allocated-worker"]) +async def test_nested_collection_writer_finishes_before_result_delivery(tmp_path, valid, layout): + required = tmp_path / "metadata.txt" + summary = tmp_path / "summary.txt" + artifacts = tmp_path / "artifacts" + if valid: + required.write_text("approved") + check_started = asyncio.Event() + validation_finished = asyncio.Event() + writer_started = asyncio.Event() + writer_waiting = asyncio.Event() + release_writer = asyncio.Event() + children = [] + + async def check(): + check_started.set() + await validation_finished.wait() + return "checked" + + async def write_summary(_previous, content, _index): + writer_started.set() + if not validation_finished.is_set(): + writer_waiting.set() + await release_writer.wait() + summary.write_text(content) + return "saved" + + async def validate(): + await check_started.wait() + try: + await asyncio.wait_for(writer_started.wait(), 0.15) + except asyncio.TimeoutError: + pass + try: + return required.read_text() + finally: + validation_finished.set() + + async def flow(ctx, _inputs): + async def combined(): + if layout == "allocated-worker": + async def stage(previous, item, index): + if item == "check": + return await check() + return await write_summary(previous, item, index) + + children.append(asyncio.create_task(ctx.pipeline(["check", "summary"], stage))) + return await asyncio.gather(*children, validate()) + children.extend(( + asyncio.create_task(ctx.parallel([check])), + asyncio.create_task(ctx.pipeline(["summary"], write_summary)), + )) + return await asyncio.gather(*children, validate()) + + return await ctx.parallel([combined]) + + running = asyncio.create_task(OpenCollab(tmp_path, model="offline").workflow( + flow, task_concurrency=2, timeout=5, cleanup_timeout=2, trace=False, artifacts=artifacts, + )) + try: + await asyncio.wait_for(validation_finished.wait(), 3) + if writer_waiting.is_set(): + done, _ = await asyncio.wait({running}, timeout=0.1) + assert not done + assert not summary.exists() + release_writer.set() + result = await asyncio.wait_for(running, 3) + assert result.status == "completed" + if not valid: + expected = [None] + elif layout == "allocated-worker": + expected = [[["checked", "saved"], "approved"]] + else: + expected = [[["checked"], ["saved"], "approved"]] + assert result.output == expected + assert summary.read_text() == "summary" + assert result.metrics["execution_quiesced"] is True + manifest = json.loads((artifacts / "workflow.json").read_text()) + assert manifest["evidence_complete"] is True + finally: + release_writer.set() + if not running.done(): + running.cancel() + await asyncio.gather(running, *children, return_exceptions=True) diff --git a/tests/interfaces/test_sdk_workflow_scout_recovery.py b/tests/interfaces/test_sdk_workflow_scout_recovery.py new file mode 100644 index 00000000..391072c4 --- /dev/null +++ b/tests/interfaces/test_sdk_workflow_scout_recovery.py @@ -0,0 +1,165 @@ +from __future__ import annotations + +import asyncio +import json +import threading +import time + +import pytest + +from opencollab import OpenCollab +from opencollab.application.session import Session +from opencollab.application.session_run import ENFORCEMENT_ON +from opencollab.application.submit_findings import SubmitFindingsTool +from opencollab.tools import builtin_tools +from tests.support.provider_sdk_http import completion_http_response, http_response, install_sdk_transport + +SCOUT_DRAFT = "I read the inventory and have no formatted findings yet." +ACCEPTED_SUMMARY = "Verified inventory subtotal of 42 units." +SUBMISSION = { + "summary": ACCEPTED_SUMMARY, + "findings": [{ + "aspect": "inventory", + "claim": "The subtotal is 42 units.", + "evidence_anchor": "Inventory subtotal 42 units", + "verified": True, + "confidence": "high", + }], + "insufficient_evidence": False, +} + + +@pytest.mark.parametrize("scenario", ["normal", "delayed-checkpoint", "late-submission", "rejected-submission"]) +async def test_pipeline_publishes_findings_accepted_before_deadline(tmp_path, monkeypatch, scenario): + source = tmp_path / "inventory.txt" + source.write_text("Inventory subtotal 42 units\n") + report_file = tmp_path / "report.txt" + artifacts = tmp_path / "artifacts" + requests, tool_results = [], [] + collect_started = 0.0 + timeout = 2.0 + checkpoint_entered = threading.Event() + release_checkpoint = threading.Event() + original_save = Session.save + original_submit = SubmitFindingsTool.execute_with_runtime + + async def submit(tool, params, runtime): + if scenario == "late-submission": + # Keep the loop busy past the deadline so tool acceptance races the timeout waiter. + time.sleep(max(0, collect_started + timeout + 0.05 - time.monotonic())) + result = await original_submit(tool, params, runtime) + tool_results.append((tool.terminal_capture_accepted, time.monotonic())) + return result + + def save(session, target): + if scenario == "delayed-checkpoint" and not checkpoint_entered.is_set() and any( + row.get("tool_call_id") == "submit-inventory" and "Findings accepted" in row["content"] + for row in session.messages + ): + checkpoint_entered.set() + assert release_checkpoint.wait(10) + return original_save(session, target) + + def tool_response(request, name, call_id, arguments): + response = completion_http_response(request, text="").json() + response["choices"][0] = { + "index": 0, + "finish_reason": "tool_calls", + "message": {"role": "assistant", "content": None, "tool_calls": [{ + "id": call_id, + "type": "function", + "function": {"name": name, "arguments": json.dumps(arguments)}, + }]}, + } + return http_response(request, 200, json=response) + + def respond(request): + body = json.loads(request.content) + tools = {row["function"]["name"] for row in body.get("tools", [])} + if tools == {"submit_findings"}: + if any(row.get("tool_call_id") == "submit-inventory" for row in body["messages"]): + requests.append("recovery-followup") + return completion_http_response(request, text="The submission needs a citation.") + requests.append("recovery-submission") + assert "Inventory subtotal 42 units" in json.dumps(body["messages"]) + payload = SUBMISSION + if scenario == "rejected-submission": + payload = {**SUBMISSION, "findings": [{**SUBMISSION["findings"][0], "evidence_anchor": ""}]} + return tool_response(request, "submit_findings", "submit-inventory", payload) + if "file_read" in tools: + if any(row.get("tool_call_id") == "read-inventory" for row in body["messages"]): + requests.append("scout-draft") + return completion_http_response(request, text=SCOUT_DRAFT) + requests.append("scout-read") + return tool_response(request, "file_read", "read-inventory", {"path": source.name}) + requests.append("publication-review") + return completion_http_response(request, text="Publication review completed.") + + async def flow(ctx, _inputs): + async def collect(_previous, item, _index): + nonlocal collect_started + collect_started = time.monotonic() + return await ctx.agent( + f"Read item {item} and verify the subtotal.", label="inventory-scout", + tools=builtin_tools("file_read", headless=False), timeout=timeout, budget=20_000, + enforcement_strength=ENFORCEMENT_ON, commit_reserve=5000, + ) + + async def publish(previous, _item, _index): + if scenario == "delayed-checkpoint": + assert checkpoint_entered.is_set() + assert ctx.tokens_remaining() == 10_000 + reviewing = asyncio.create_task(ctx.agent_run( + f"Review the inventory report for publication.\n{previous}", tools=[], budget=6000, + )) + try: + if scenario == "delayed-checkpoint": + done, _ = await asyncio.wait({reviewing}, timeout=0.03) + assert not done and "publication-review" not in requests + finally: + release_checkpoint.set() + review = await reviewing + report_file.write_text(previous) + return {"review": review.status, "report": previous} + + return await ctx.pipeline(["inventory"], collect, publish) + + monkeypatch.setattr(Session, "save", save) + monkeypatch.setattr(SubmitFindingsTool, "execute_with_runtime", submit) + install_sdk_transport(monkeypatch, "openai", respond) + for name in ("OPENCOLLAB_BUDGET_NUDGE_MODE", "OPENCOLLAB_WRITE_NUDGE_MODE"): + monkeypatch.setenv(name, "off") + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", "") + + app = OpenCollab(tmp_path, model="gpt-4o", provider="openai", api_key=tmp_path.name, + base_url="https://offline.invalid/v1", config={ + "wire_protocol": "chat_completions", "llm_stream_chat": False, + "llm_max_retries": 0, "max_output_tokens": 128, + }) + try: + result = await app.workflow(flow, concurrency=1, timeout=10, + artifacts=artifacts, trace=False, budget=30_000, limit_mode="explicit") + finally: + release_checkpoint.set() + + manifest = json.loads((artifacts / "workflow.json").read_text()) + assert result.status == "completed", result.reason + assert requests[:3] == ["scout-read", "scout-draft", "recovery-submission"] + assert requests[3:] == (["recovery-followup", "publication-review"] if scenario == "rejected-submission" + else ["publication-review"]) + ((accepted, submitted_at),) = tool_results + assert accepted is (scenario != "rejected-submission") + assert (submitted_at >= collect_started + timeout) is (scenario == "late-submission") + assert result.tokens == manifest["tokens_spent"] == 4 * len(requests) + assert manifest["evidence_complete"] is True + assert result.output[0]["review"] == "completed" + report = report_file.read_text() + assert report == result.output[0]["report"] + if scenario in {"normal", "delayed-checkpoint"}: + assert ACCEPTED_SUMMARY in report + else: + assert report == SCOUT_DRAFT + if scenario == "delayed-checkpoint": + failure, = result.agent_failures + assert failure["label"] == "inventory-scout:synth" + assert failure["exception_type"] == "CallerTimeoutError" diff --git a/tests/interfaces/test_sdk_workflow_startup_ownership.py b/tests/interfaces/test_sdk_workflow_startup_ownership.py new file mode 100644 index 00000000..65dd3737 --- /dev/null +++ b/tests/interfaces/test_sdk_workflow_startup_ownership.py @@ -0,0 +1,169 @@ +from __future__ import annotations + +import asyncio +import json +from pathlib import Path + +import pytest + +from opencollab import OpenCollab +from opencollab.adapters.env import LocalEnvironment +from opencollab.adapters.llm.types import LLMResponse, Usage +from opencollab.adapters.worktree_pool import WorktreePool +from opencollab.application.async_timeout import await_owned_operation +from tests.interfaces.test_session_isolation import _repo + + +@pytest.mark.parametrize("stop,borrow_source,entry", [ + ("none", False, "managed"), + ("stage", False, "managed"), + ("deadline", False, "managed"), + ("caller", False, "managed"), + ("caller", True, "managed"), + ("stage", False, "plain"), + ("stage", False, "enforced"), + ("stage", False, "schema"), +]) +async def test_workflow_retains_ownership_while_an_isolated_agent_is_starting( + tmp_path, monkeypatch, stop, borrow_source, entry, +): + workspace = tmp_path / "source" + workspace.mkdir() + _repo(workspace, dirty=False) + entered, continue_setup, setup_finished, pool_released, stage_finished, return_stage = ( + asyncio.Event() for _ in range(6) + ) + setup_state = {} + requests = [] + stages = [] + cancellations = [] + + class InventoryModel: + def context_window(self): + return 100_000 + + async def complete(self, messages, **kwargs): + requests.append(messages) + return LLMResponse(content="Inventory verified.", usage=Usage(3, 2), finish_reason="stop") + + class DelayedWorktreePool(WorktreePool): + async def acquire(self, role, *, source=None): + async def configure_checkout(): + env = await super(DelayedWorktreePool, self).acquire(role, source=source) + setup_state.update(env=env, source=source) + entered.set() + await continue_setup.wait() + try: + setup_state["source_text"] = await source.read_file("seed.txt") + setup_state["checkout_text"] = await env.read_file("seed.txt") + finally: + setup_finished.set() + return env + + return await await_owned_operation(configure_checkout(), propagate_cancellation=not borrow_source) + + async def release(self): + await super().release() + pool_released.set() + + def provider(**options): + return DelayedWorktreePool(use_worktrees=True, **options) + + async def flow(ctx, _): + options = dict(label="verifier", tools=[], isolation="inventory", budget=15_000, + timeout=.9 if stop == "stage" else 5) + if entry == "managed": + stage = await ctx.agent_run("Check the inventory.", cleanup_timeout=.06, **options) + else: + if entry == "enforced": + options["enforcement_strength"] = "needs-enforcement" + if entry == "schema": + options["schema"] = {"type": "object", "properties": {"verified": {"type": "boolean"}}} + stage = await ctx.agent("Check the inventory.", **options) + stages.append(stage) + stage_finished.set() + await return_stage.wait() + return stage.output if entry == "managed" else stage + + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(tmp_path / "usage.jsonl")) + borrowed = LocalEnvironment(str(workspace)) if borrow_source else None + client = OpenCollab( + workspace, model="gpt-4o", environment=borrowed, environment_providers={"inventory": provider}, + ) + artifacts = tmp_path / "artifacts" + if stop == "none": + continue_setup.set() + return_stage.set() + async def run(): + try: + return await client.workflow( + flow, llm=InventoryModel(), budget=30_000, limit_mode="explicit", artifacts=artifacts, + trace=False, timeout=1.6 if stop == "deadline" else None, cleanup_timeout=.08, + ) + except asyncio.CancelledError as exc: + cancellations.append(exc.args) + raise + + operation = asyncio.create_task(run()) + try: + await asyncio.wait_for(entered.wait(), 5) + checkout = Path(setup_state["env"].workspace) + source = setup_state["source"] + if stop == "stage": + await asyncio.wait_for(stage_finished.wait(), 3) + stage, = stages + if entry == "managed": + assert (stage.status, stage.reason, stage.output, stage.tokens) == ("stopped", "timeout", None, 0) + assert not stage.cleanup_complete and not stage.workspace_ready + else: + assert stage is None + elif stop == "caller": + operation.cancel("caller stopped worktree preparation") + done, _ = await asyncio.wait({operation}, timeout=3) + assert operation in done + with pytest.raises(asyncio.CancelledError): + await operation + assert cancellations == [("caller stopped worktree preparation",)] + else: + result = await asyncio.wait_for(asyncio.shield(operation), 3) + if stop == "deadline": + assert (result.status, result.reason, result.output, result.tokens) == ("stopped", "timeout", None, 0) + assert result.metrics["execution_quiesced"] is False + else: + assert (result.status, result.output, result.tokens) == ("completed", "Inventory verified.", 5) + + manifest = artifacts / "workflow.json" + if stop != "none": + assert not setup_finished.is_set() and not pool_released.is_set() + assert checkout.is_dir() and not source.revoked + assert not requests + if stop in {"deadline", "caller"}: + snapshot = json.loads(manifest.read_text()) + assert (snapshot["status"], snapshot["reason"]) == ("stopped", "cancelled") + assert snapshot["sessions"] == snapshot["tokens_spent"] == 0 + assert snapshot["evidence_complete"] is False + continue_setup.set() + await asyncio.wait_for(setup_finished.wait(), 3) + assert setup_state["source_text"] == setup_state["checkout_text"] == "initial" + if stop == "stage": + return_stage.set() + result = await asyncio.wait_for(operation, 3) + assert (result.status, result.output, result.tokens) == ("completed", None, 0) + await asyncio.wait_for(pool_released.wait(), 3) + assert not checkout.exists() + if borrowed is not None: + assert source is borrowed and await borrowed.read_file("seed.txt") == "initial" + if stop in {"none", "stage"}: + saved = json.loads(manifest.read_text()) + assert saved["evidence_complete"] is True + assert saved["status"] == "completed" + assert saved["sessions"] == (1 if stop == "none" else 0) + assert len(requests) == (1 if stop == "none" else 0) + finally: + continue_setup.set() + return_stage.set() + await asyncio.gather(operation, return_exceptions=True) + if entered.is_set(): + await asyncio.wait_for(pool_released.wait(), 5) + if borrowed is not None: + await borrowed.cleanup() diff --git a/tests/interfaces/test_sdk_workflow_structured_capture_timeout.py b/tests/interfaces/test_sdk_workflow_structured_capture_timeout.py new file mode 100644 index 00000000..7bc4de42 --- /dev/null +++ b/tests/interfaces/test_sdk_workflow_structured_capture_timeout.py @@ -0,0 +1,86 @@ +"""Preserve an accepted structured result across its terminal checkpoint deadline.""" + +from __future__ import annotations + +import json +import threading + +import pytest + +from opencollab import OpenCollab +from opencollab.adapters.llm.client import LLMClient +from opencollab.application.session import Session +from tests.support.provider_sdk_http import completion_http_response, http_response, install_sdk_transport + + +@pytest.mark.parametrize("capture_stage", ["initial", "correction", "neither"]) +async def test_validated_capture_survives_the_caller_deadline_during_checkpoint(tmp_path, monkeypatch, capture_stage): + requests = [] + checkpoint_entered = threading.Event() + release_checkpoint = threading.Event() + original_save = Session.save + expected = {"measurement": 42} + held_stage = "correction" if capture_stage == "neither" else capture_stage + + def stage(messages): + user_texts = [row.get("content") for row in messages if row.get("role") == "user"] + if any(isinstance(text, str) and "You MUST call" in text for text in user_texts): + return "correction" + return "initial" + + def save_after_release(session, target): + if not checkpoint_entered.is_set() and stage(session.messages) == held_stage: + if capture_stage != "neither": + assert any(row.get("tool_call_id") == "verified-meter" for row in session.messages) + checkpoint_entered.set() + assert release_checkpoint.wait(10) + return original_save(session, target) + + async def handler(request): + action = stage(json.loads(request.content)["messages"]) + requests.append(action) + if action != capture_stage: + response = completion_http_response(request, text="The observed measurement was 42 milliseconds.").json() + else: + response = completion_http_response(request, text="").json() + choice = response["choices"][0] + choice["finish_reason"] = "tool_calls" + choice["message"] = { + "role": "assistant", "content": None, + "tool_calls": [{ + "id": "verified-meter", "type": "function", + "function": {"name": "structured_output", "arguments": json.dumps(expected)}, + }], + } + response["usage"] = {"prompt_tokens": 801, "completion_tokens": 19, "total_tokens": 820} + return http_response(request, 200, json=response) + + schema = {"type": "object", "properties": {"measurement": {"type": "integer"}}, "required": ["measurement"]} + monkeypatch.setattr(Session, "save", save_after_release) + install_sdk_transport(monkeypatch, "openai", handler) + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + + async def workflow(ctx, _inputs): + try: + result = await ctx.agent("Record the measurement.", schema=schema, tools=[], timeout=2) + assert checkpoint_entered.is_set() + return result + finally: + release_checkpoint.set() + + artifacts = tmp_path / "artifacts" + async with LLMClient( + model="gpt-4o", api_key=tmp_path.name, base_url="https://offline.invalid/v1", max_retries=0, + ) as model: + result = await OpenCollab(tmp_path, model="gpt-4o", config={"max_output_tokens": 128}).workflow( + workflow, llm=model, budget=20_000, concurrency=1, limit_mode="explicit", + artifacts=artifacts, trace=True, timeout=15, + ) + assert result.status == "completed", result.reason + assert requests == (["initial"] if capture_stage == "initial" else ["initial", "correction"]) + assert result.tokens == 820 * len(requests) + assert result.output == (None if capture_stage == "neither" else expected) + manifest = json.loads((artifacts / "workflow.json").read_text()) + assert manifest["tokens_spent"] == result.tokens + assert manifest["evidence_complete"] is True diff --git a/tests/interfaces/test_sdk_workflow_text_replay_settlement.py b/tests/interfaces/test_sdk_workflow_text_replay_settlement.py new file mode 100644 index 00000000..04b40eb9 --- /dev/null +++ b/tests/interfaces/test_sdk_workflow_text_replay_settlement.py @@ -0,0 +1,179 @@ +from __future__ import annotations + +import asyncio +import json + +import pytest + +from opencollab import OpenCollab +from opencollab.adapters.llm.client import LLMClient +from tests.support.provider_sdk_http import completion_http_response, http_response, install_sdk_transport +from tests.support.workflow_context_test_support import reserve_request_tokens_until +from tests.support.worktree_delivery_support import make_repo + +PREPARE = "Load the local inventory." +REVIEW = "Review the inventory." +PARTIAL = "Checked items 1 through 42." +COMPLETE = "Checked all 87 items. Inventory reconciled." + + +@pytest.mark.parametrize(("entry", "scene"), [ + ("agent", "replay_timeout"), + ("agent", "replay_complete"), + ("agent", "single_complete"), + ("agent", "initial_timeout"), + ("agent", "initial_cancel"), + ("agent", "workflow_cancel"), + ("enforced", "replay_timeout"), + ("candidate", "replay_timeout"), +]) +async def test_workflow_agent_retains_settled_text_when_budget_replay_times_out(tmp_path, monkeypatch, entry, scene): + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + ledger_path = tmp_path / "provider.jsonl" + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(ledger_path)) + prep_started, prep_release, prep_finished = (asyncio.Event() for _ in range(3)) + initial_started, replay_started, request_cancelled = (asyncio.Event() for _ in range(3)) + reserve_request_tokens_until(monkeypatch, REVIEW, 7000, prep_finished) + requests = [] + review_messages = [] + + def prompt_for(messages): + return next((row["content"] for row in reversed(messages) if row["role"] == "user"), "") + + def estimate(_client, messages, tools=None, **kwargs): + return {PREPARE: 2990, REVIEW: 5990}.get(prompt_for(messages), 100) + + async def handler(request): + body = json.loads(request.content) + prompt = prompt_for(body["messages"]) + limit = body["max_tokens"] + requests.append((prompt, limit)) + finish = "stop" + if prompt == PREPARE: + prep_started.set() + await prep_release.wait() + text, inputs, outputs = "Inventory loaded.", 2990, 10 + else: + assert prompt == REVIEW + review_messages.append(body["messages"]) + if len(review_messages) == 1: + prep_release.set() + await prep_finished.wait() + if scene in {"initial_timeout", "initial_cancel"}: + initial_started.set() + try: + await asyncio.Future() + except asyncio.CancelledError: + request_cancelled.set() + raise + text = COMPLETE if scene == "single_complete" else PARTIAL + finish = "stop" if scene == "single_complete" else "length" + inputs, outputs = 5990, limit + else: + replay_started.set() + if scene in {"replay_timeout", "workflow_cancel"}: + try: + await asyncio.Future() + except asyncio.CancelledError: + request_cancelled.set() + raise + text, inputs, outputs = COMPLETE, 5990, 24 + response = completion_http_response(request, text=text, output_tokens=outputs).json() + response["choices"][0]["finish_reason"] = finish + response["usage"].update(prompt_tokens=inputs, total_tokens=inputs + outputs) + return http_response(request, 200, json=response) + + monkeypatch.setattr(LLMClient, "estimate_request_tokens", estimate) + install_sdk_transport(monkeypatch, "openai", handler) + + async def workflow(ctx, _inputs): + async def prepare(): + result = await ctx.agent(PREPARE, tools=[], budget=33_000) + assert result == "Inventory loaded." + prep_finished.set() + + async def review(): + if entry == "candidate": + candidate = await ctx.candidate_agent(REVIEW, label="review", tools=[], timeout=2) + assert not candidate.diff + return candidate.output + if entry == "enforced": + return await ctx.agent( + REVIEW, label="review", tools=[], timeout=2, + enforcement_strength="needs-enforcement", commit_reserve=100, + ) + return await ctx.agent(REVIEW, label="review", tools=[], timeout=2) + + async def record(): + return "Inventory date recorded." + + pending = asyncio.create_task(prepare()) + try: + await asyncio.wait_for(prep_started.wait(), 5) + result, note = await ctx.parallel([review, record]) + assert note == "Inventory date recorded." + return result + finally: + prep_release.set() + await pending + + artifacts = tmp_path / "artifacts" + workspace = make_repo(tmp_path / "workspace") if entry == "candidate" else tmp_path + client = OpenCollab( + workspace, model="gpt-4o", provider="openai", api_key=tmp_path.name, + base_url="https://fixture.invalid/v1", + config={"wire_protocol": "chat_completions", "llm_stream_chat": False, + "llm_max_retries": 0, "max_output_tokens": 128}, + ) + cancellations = [] + + async def run_workflow(): + try: + return await client.workflow( + workflow, budget=59_000, concurrency=2, task_concurrency=2, limit_mode="explicit", + artifacts=artifacts, trace=True, timeout=12, cleanup_timeout=2, + ) + except asyncio.CancelledError as exc: + # Python 3.10 drops metadata when another task awaits this cancellation. + cancellations.append(exc) + raise + + operation = asyncio.create_task(run_workflow()) + cancelled = scene in {"initial_cancel", "workflow_cancel"} + if cancelled: + try: + event = initial_started if scene == "initial_cancel" else replay_started + await asyncio.wait_for(event.wait(), 5) + operation.cancel("caller cancelled inventory workflow") + with pytest.raises(asyncio.CancelledError): + await operation + error, = cancellations + assert error.args == ("caller cancelled inventory workflow",) + result = error.runtime_result + assert result.evidence_complete and not result.environment_cleanup_deferred + finally: + if not operation.done(): + operation.cancel() + await asyncio.gather(operation, return_exceptions=True) + else: + result = await operation + assert result.ok and result.metrics["execution_quiesced"] + ledger = [json.loads(line) for line in ledger_path.read_text().splitlines()] + billed_tokens = [row["usage"]["total_tokens"] for row in ledger if row.get("usage")] + manifest = json.loads((artifacts / "workflow.json").read_text()) + limits, expected_tokens, expected_output = { + "replay_timeout": ([10, 128], 9000, PARTIAL), + "replay_complete": ([10, 128], 15_014, COMPLETE), + "single_complete": ([10], 9000, COMPLETE), + "initial_timeout": ([10], 3000, None), + "initial_cancel": ([10], 3000, None), + "workflow_cancel": ([10, 128], 9000, None), + }[scene] + assert requests == [(PREPARE, 128), *((REVIEW, limit) for limit in limits)] + assert manifest["status"] == ("stopped" if cancelled else "completed") + assert result.tokens == manifest["tokens_spent"] == sum(billed_tokens) == expected_tokens + assert request_cancelled.is_set() is (cancelled or scene in {"initial_timeout", "replay_timeout"}) + if len(review_messages) == 2: + assert review_messages[0] == review_messages[1] + assert result.output == expected_output diff --git a/tests/interfaces/test_sdk_workflow_tool_presets.py b/tests/interfaces/test_sdk_workflow_tool_presets.py new file mode 100644 index 00000000..1d22e44f --- /dev/null +++ b/tests/interfaces/test_sdk_workflow_tool_presets.py @@ -0,0 +1,117 @@ +"""Combine a public read preset with each Workflow agent's output mode.""" + +from __future__ import annotations + +import json +import subprocess + +import pytest + +from opencollab import OpenCollab +from opencollab.application.session_run import ENFORCEMENT_ON +from tests.support.provider_sdk_http import completion_http_response, http_response, install_sdk_transport + +READ_TOOLS = ["file_read", "grep", "git_diff"] +INVENTORY = "Inventory subtotal 42" +RESULT_SCHEMA = { + "type": "object", + "properties": {"subtotal": {"type": "integer"}}, + "required": ["subtotal"], +} + + +@pytest.mark.parametrize("profile", [None, "base"]) +@pytest.mark.parametrize("mode", ["text", "schema", "enforced"]) +@pytest.mark.parametrize("nested", [False, True]) +async def test_workflow_read_preset_with_output_mode(tmp_path, monkeypatch, mode, profile, nested): + workspace = tmp_path / "workspace" + workspace.mkdir() + (workspace / "inventory.txt").write_text(INVENTORY + "\n", encoding="utf-8") + if nested: + for args in ( + ("init", "-q"), + ("add", "inventory.txt"), + ("-c", "user.name=Test User", "-c", "user.email=test@example.invalid", + "-c", "commit.gpgsign=false", "commit", "-qm", "Initialize inventory"), + ): + subprocess.run(["git", *args], cwd=workspace, check=True, capture_output=True) + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(tmp_path / "usage.jsonl")) + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + requests = [] + + def respond(request): + body = json.loads(request.content) + requests.append(body) + history = [message["content"] for message in body["messages"] if message["role"] == "tool"] + if not any(INVENTORY in output for output in history): + if not any(tool["function"]["name"] == "file_read" for tool in body.get("tools", [])): + return completion_http_response(request, text="The inventory is unavailable.", output_tokens=3) + name, arguments = "file_read", {"path": "inventory.txt"} + else: + if mode == "text": + return completion_http_response(request, text=INVENTORY, output_tokens=3) + if mode == "schema": + name, arguments = "structured_output", {"subtotal": 42} + else: + name, arguments = "submit_findings", { + "findings": [{ + "aspect": "subtotal", "claim": INVENTORY, "evidence_anchor": "inventory.txt:1", + "verified": True, "confidence": "high", + }], + "summary": INVENTORY, + "insufficient_evidence": False, + } + return http_response(request, 200, json={ + "id": f"inventory-{len(requests)}", "object": "chat.completion", "created": 1, "model": body["model"], + "choices": [{"index": 0, "finish_reason": "tool_calls", "message": { + "role": "assistant", "content": None, "tool_calls": [{ + "id": f"inventory-tool-{len(requests)}", "type": "function", "function": { + "name": name, "arguments": json.dumps(arguments), + }, + }], + }}], + "usage": {"prompt_tokens": 2, "completion_tokens": 3, "total_tokens": 5}, + }) + + install_sdk_transport(monkeypatch, "openai", respond) + + async def read_inventory(ctx, _inputs): + options = {} + if mode == "schema": + options["schema"] = RESULT_SCHEMA + elif mode == "enforced": + options.update(enforcement_strength=ENFORCEMENT_ON, commit_reserve=2048) + return await ctx.agent("Read inventory.txt and report the subtotal.", tools="read", **options) + + async def flow(ctx, inputs): + if not nested: + return await read_inventory(ctx, inputs) + candidate = await ctx.candidate_workflow(read_inventory, inputs, label="inventory-reader") + return candidate.output + + app = OpenCollab( + workspace, model="offline-inventory", provider="openai", + api_key="fixture-unused", # pragma: allowlist secret + base_url="https://fixture.invalid/v1", + config={"wire_protocol": "chat_completions", "llm_stream_chat": False, + "max_output_tokens": 128, "llm_max_retries": 0}, + ) + artifacts = tmp_path / "artifacts" + result = await app.workflow(flow, budget=50_000, agent_profile=profile, artifacts=artifacts, limit_mode="explicit") + assert result.ok and result.agent_failures == () + assert len(requests) == 2 and result.tokens == 10 + expected_tools = { + "text": READ_TOOLS, + "schema": ["structured_output", *READ_TOOLS], + "enforced": [*READ_TOOLS, "submit_findings"], + }[mode] + assert [tool["function"]["name"] for tool in requests[0]["tools"]] == expected_tools + trace = (artifacts / "orchestration.jsonl").read_text().splitlines() + started = [row["payload"] for line in trace if (row := json.loads(line))["type"] == "workflow_agent_started"] + assert [row["tools"] for row in started] == [expected_tools] + if mode == "schema": + assert result.output == {"subtotal": 42} + elif mode == "enforced": + assert INVENTORY in result.output and "inventory.txt:1" in result.output + else: + assert result.output == INVENTORY diff --git a/tests/interfaces/test_sdk_workflow_verification_ownership.py b/tests/interfaces/test_sdk_workflow_verification_ownership.py new file mode 100644 index 00000000..ca935c52 --- /dev/null +++ b/tests/interfaces/test_sdk_workflow_verification_ownership.py @@ -0,0 +1,124 @@ +from __future__ import annotations + +import asyncio +import json +import shlex +import sys + +import pytest + +from opencollab.adapters.env import LocalEnvironment +from opencollab.sdk import OpenCollab +from opencollab.tools import builtin_tools + + +@pytest.mark.parametrize("scene", ["success", "sibling", "joined", "cancel"]) +async def test_local_verification_settles_before_workflow_returns(tmp_path, scene): + workspace = tmp_path / "workspace" + workspace.mkdir() + started = workspace / "verifier.started" + proceed = workspace / "continue.check" + verified = workspace / "verified.txt" + (workspace / "verify_report.py").write_text( + "import time\n" + "from pathlib import Path\n" + "Path('verifier.started').write_text('started')\n" + "while not Path('continue.check').exists():\n" + " time.sleep(.02)\n" + "Path('verified.txt').write_text('report verified\\n')\n" + "print('VERIFIED')\n" + ) + (workspace / "verify_reuse.py").write_text("print('REUSABLE')\n") + python = shlex.quote(sys.executable) + sibling_failed = asyncio.Event() + subject_error = ValueError("Required deployment date is missing") + verification_tasks = [] + + async def wait_started(): + while not started.is_file(): + await asyncio.sleep(0.005) + + async def run_verification(ctx, source): + bash, = builtin_tools("bash", headless=False) + return await ctx.execute_verification(bash, {"command": f"{python} -B {source}"}) + + async def child(ctx, _args): + async def check_inputs(): + await wait_started() + sibling_failed.set() + raise subject_error + + if scene == "success": + return await run_verification(ctx, "verify_report.py") + verifier = asyncio.create_task(run_verification(ctx, "verify_report.py")) + verification_tasks.append(verifier) + if scene == "cancel": + await asyncio.Future() + elif scene == "joined": + _report, failure = await asyncio.gather(verifier, check_inputs(), return_exceptions=True) + raise failure + else: + await asyncio.gather(verifier, check_inputs()) + + async def parent(ctx, args): + return await child(ctx, args) + + async def reuse(ctx, _args): + return await run_verification(ctx, "verify_reuse.py") + + environment = LocalEnvironment(str(workspace)) + client = OpenCollab(workspace, model="offline-model", environment=environment) + artifacts = tmp_path / "artifacts" + + async def run_workflow(): + try: + return await client.workflow( + parent, budget=10_000, limit_mode="explicit", timeout=10, cleanup_timeout=1, + trace=False, artifacts=artifacts, + ) + except asyncio.CancelledError as error: + return error + + running = asyncio.create_task(run_workflow()) + try: + await asyncio.wait_for(wait_started(), 5) + if scene in {"sibling", "joined"}: + await asyncio.wait_for(sibling_failed.wait(), 5) + if scene == "cancel": + running.cancel("cancel parent while verifying") + result = await asyncio.wait_for(running, 5) + assert isinstance(result, asyncio.CancelledError) + assert str(result) == "cancel parent while verifying" + verifier, = verification_tasks + assert verifier.cancelled() + assert not verified.exists() + proceed.write_text("proceed") + else: + await asyncio.wait({running}, timeout=0.2) + assert not running.done() + assert not (artifacts / "workflow.json").exists() + assert not verified.exists() + proceed.write_text("proceed") + result = await asyncio.wait_for(running, 5) + if scene == "success": + assert result.ok and "VERIFIED" in result.output + else: + assert result.status == "failed" and result.error is subject_error + verifier, = verification_tasks + assert verifier.done() and "VERIFIED" in verifier.result() + assert verified.read_text() == "report verified\n" + + manifest = json.loads((artifacts / "workflow.json").read_text()) + expected = {"success": "completed", "cancel": "stopped", "sibling": "failed", "joined": "failed"} + assert manifest["status"] == expected[scene] + assert manifest["evidence_complete"] is True + assert not environment.revoked + reused = await client.workflow(reuse, trace=False, timeout=5) + assert reused.ok and "REUSABLE" in reused.output + assert verified.exists() is (scene != "cancel") + finally: + proceed.touch() + if not running.done(): + running.cancel() + await asyncio.gather(running, *verification_tasks, return_exceptions=True) + await environment.cleanup() diff --git a/tests/interfaces/test_session_isolation.py b/tests/interfaces/test_session_isolation.py index 826854a4..172965c4 100644 --- a/tests/interfaces/test_session_isolation.py +++ b/tests/interfaces/test_session_isolation.py @@ -1,13 +1,17 @@ from __future__ import annotations +import asyncio import json import subprocess +import threading from pathlib import Path import pytest -from opencollab import OpenCollab +from opencollab import OpenCollab, RunError +from opencollab.adapters.env import LocalEnvironment from opencollab.adapters.llm.types import LLMResponse, Usage +from opencollab.adapters.session_environments import SessionEnvironmentPool from opencollab.adapters.worktree_pool import WorktreePool from opencollab.bootstrap import _workflow_runtime_session as wiring from opencollab.bootstrap import container @@ -106,6 +110,477 @@ async def flow(ctx, args): assert not (tmp_path / "marker.txt").exists() +async def test_workflow_workspace_release_is_safe_for_concurrent_callers(tmp_path): + _repo(tmp_path, dirty=False) + removed = [] + + class ObservedPool(WorktreePool): + async def release_env(self, env): + assert await env.read_file("marker.txt") == "marker" + removed.append(Path(env.workspace)) + await super().release_env(env) + + def provider(**kwargs): + return ObservedPool(use_worktrees=True, **kwargs) + + async def flow(ctx, _args): + output = await ctx.agent("Write one note.", tools=list(builtin_tools("file_write"))) + for session in ctx.sessions: + await session.aclose() + await asyncio.gather( + ctx.release_isolated_workspaces(), + ctx.release_isolated_workspaces(), + ) + return output + + client = OpenCollab(tmp_path, environment_providers={"custom": provider}) + result = await client.workflow(flow, isolation="custom", llm=Writer(), trace=False) + assert result.ok and result.output == "finished" + checkout, = removed + assert not checkout.exists() + assert (tmp_path / "seed.txt").read_text() == "initial" + + +async def test_concurrent_session_pool_shutdown_releases_each_backend_once(tmp_path): + _repo(tmp_path, dirty=False) + entered, finish = asyncio.Event(), asyncio.Event() + calls = [] + + class ObservedPool(WorktreePool): + async def release(self): + calls.append("release") + entered.set() + await finish.wait() + await super().release() + + def provider(**kwargs): + return ObservedPool(use_worktrees=True, **kwargs) + + pool = SessionEnvironmentPool(str(tmp_path), isolation="custom", providers={"custom": provider}) + workspace = await pool.acquire("worker") + first = asyncio.create_task(pool.release()) + try: + await asyncio.wait_for(entered.wait(), 5) + second = asyncio.create_task(pool.release()) + await asyncio.sleep(0) + finally: + finish.set() + await asyncio.gather(first, second) + assert calls == ["release"] + assert not Path(workspace.workspace).exists() + + +@pytest.mark.parametrize("shutdown", [False, True]) +async def test_concurrent_release_waits_for_the_same_workspace_owner(tmp_path, shutdown): + _repo(tmp_path, dirty=False) + entered, finish = asyncio.Event(), asyncio.Event() + calls = [] + + class ObservedPool(WorktreePool): + async def release_env(self, env): + calls.append(env) + entered.set() + await finish.wait() + await super().release_env(env) + + def provider(**kwargs): + return ObservedPool(use_worktrees=True, **kwargs) + + pool = SessionEnvironmentPool(str(tmp_path), isolation="custom", providers={"custom": provider}) + workspace = await pool.acquire("worker") + first = asyncio.create_task(pool.release_env(workspace)) + try: + await asyncio.wait_for(entered.wait(), 5) + second = asyncio.create_task(pool.release() if shutdown else pool.release_env(workspace)) + await asyncio.sleep(0) + await asyncio.sleep(0) + finally: + finish.set() + await asyncio.gather(first, second) + await pool.release() + assert calls == [workspace] and not Path(workspace.workspace).exists() + + +@pytest.mark.parametrize("release_fault", [False, True]) +async def test_final_scoped_release_stops_new_shared_borrowers(tmp_path, release_fault): + _repo(tmp_path, dirty=False) + entered, finish = asyncio.Event(), asyncio.Event() + calls = [] + + class ObservedPool(WorktreePool): + def __init__(self, **options): + super().__init__(use_worktrees=True, **options) + + async def release_env(self, env): + calls.append(env) + if len(calls) == 1: + entered.set() + await finish.wait() + if release_fault: + raise OSError("temporary checkout cleanup error") + await super().release_env(env) + + pool = SessionEnvironmentPool(str(tmp_path), isolation="observed", providers={"observed": ObservedPool}) + workspace = await pool.acquire("owner") + borrower = await pool.acquire("healthy", isolation="shared", source=workspace) + assert borrower is workspace + await pool.release_env(borrower) + assert not calls + assert await workspace.read_file("seed.txt") == "initial" + + closing = asyncio.create_task(pool.release_env(workspace)) + try: + await asyncio.wait_for(entered.wait(), 5) + with pytest.raises(RuntimeError, match="environment is unavailable"): + await pool.acquire("during", isolation="shared", source=workspace) + finish.set() + if release_fault: + with pytest.raises(OSError, match="temporary checkout cleanup error"): + await closing + assert await workspace.read_file("seed.txt") == "initial" + with pytest.raises(RuntimeError, match="environment is unavailable"): + await pool.acquire("before-retry", isolation="shared", source=workspace) + await pool.release_env(workspace) + else: + await closing + assert not Path(workspace.workspace).exists() + with pytest.raises(RuntimeError, match="environment is unavailable"): + await pool.acquire("after", isolation="shared", source=workspace) + replacement = await pool.acquire("replacement") + assert await replacement.read_file("seed.txt") == "initial" + await pool.release_env(replacement) + finally: + finish.set() + await asyncio.gather(closing, return_exceptions=True) + await pool.release() + + +@pytest.mark.parametrize("release_completed", [False, True]) +async def test_acquisition_rejects_provider_alias_after_yielding(tmp_path, release_completed): + _repo(tmp_path, dirty=False) + release_entered, finish_release = asyncio.Event(), asyncio.Event() + acquire_entered, finish_acquire = asyncio.Event(), asyncio.Event() + + class ReusingPool(WorktreePool): + def __init__(self, **options): + super().__init__(use_worktrees=True, **options) + self.environment = None + + async def acquire(self, role, *, source=None): + if self.environment is None: + self.environment = await super().acquire(role, source=source) + else: + acquire_entered.set() + await finish_acquire.wait() + return self.environment + + async def release_env(self, env): + release_entered.set() + await finish_release.wait() + await super().release_env(env) + + pool = SessionEnvironmentPool(str(tmp_path), isolation="reusing", providers={"reusing": ReusingPool}) + workspace = await pool.acquire("owner") + acquiring = asyncio.create_task(pool.acquire("alias")) + closing = None + try: + await asyncio.wait_for(acquire_entered.wait(), 5) + closing = asyncio.create_task(pool.release_env(workspace)) + await asyncio.wait_for(release_entered.wait(), 5) + if release_completed: + finish_release.set() + await closing + finish_acquire.set() + with pytest.raises(RuntimeError, match="environment is unavailable"): + await acquiring + finish_release.set() + await closing + assert not Path(workspace.workspace).exists() + finally: + finish_release.set() + finish_acquire.set() + await asyncio.gather(acquiring, *(task for task in (closing,) if task is not None), return_exceptions=True) + await pool.release() + + +async def test_pool_keeps_failed_child_source_and_releases_independent_worktree(tmp_path, monkeypatch): + _repo(tmp_path, dirty=False) + + def provider(**options): + return WorktreePool(use_worktrees=True, **options) + + pool = SessionEnvironmentPool(str(tmp_path), providers={"report": provider}) + ready = False + try: + parent = await pool.acquire("parent") + independent = await pool.acquire("independent") + child = await pool.acquire("child", isolation="report", source=parent) + cleanup = child.cleanup + + async def delayed_cleanup(): + if not ready: + raise OSError("report not copied") + await cleanup() + + monkeypatch.setattr(child, "cleanup", delayed_cleanup) + checkout = Path(parent.workspace) + with pytest.raises(OSError, match="report not copied"): + await pool.release() + assert await parent.read_file("seed.txt") == "initial" + assert checkout.is_dir() and Path(child.workspace).is_dir() + assert not Path(independent.workspace).exists() + finally: + ready = True + await pool.release() + assert not checkout.exists() + + +@pytest.mark.parametrize("late_source", [False, True]) +@pytest.mark.parametrize("export_fault", [False, True]) +async def test_pool_retains_sources_of_a_reused_environment(tmp_path, late_source, export_fault): + _repo(tmp_path, dirty=False) + report = tmp_path / "report.txt" + release_attempts = 0 + export_enabled = True + + class ReportPool(WorktreePool): + def __init__(self, **options): + super().__init__(use_worktrees=True, **options) + self.environment = None + self.sources = [] + + async def acquire(self, role, *, source=None): + self.sources.append(source) + if self.environment is None: + self.environment = await super().acquire(role, source=source) + return self.environment + + async def release_env(self, env): + nonlocal release_attempts + release_attempts += 1 + if export_enabled: + if export_fault and release_attempts == 1: + raise OSError("temporary report destination error") + details = [await source.read_file("detail.txt") for source in self.sources] + report.write_text(" / ".join(details)) + await super().release_env(env) + + pool = SessionEnvironmentPool(str(tmp_path), providers={"report": ReportPool}) + try: + first = await pool.acquire("first") + if not late_source: + second = await pool.acquire("second") + view = await pool.acquire("combine-first", source=first, isolation="report") + if late_source: + second = await pool.acquire("second") + again = await pool.acquire("combine-second", source=second, isolation="report") + independent = await pool.acquire("independent") + assert view is again + await first.write_file("detail.txt", "first") + await second.write_file("detail.txt", "second") + await pool.release_env(again) + assert release_attempts == 0 + + if export_fault: + with pytest.raises(OSError, match="temporary report destination error"): + await pool.release() + assert not Path(independent.workspace).exists() + assert await first.read_file("detail.txt") == "first" + assert await second.read_file("detail.txt") == "second" + assert Path(view.workspace).is_dir() + + await pool.release() + assert report.read_text() == "first / second" + assert release_attempts == (2 if export_fault else 1) + assert all(not Path(env.workspace).exists() for env in (first, second, view, independent)) + finally: + export_enabled = False + await pool.release() + + +@pytest.mark.parametrize("phase", ["session-close", "workspace-release"]) +@pytest.mark.parametrize("mode", ["cleanup-timeout", "caller-cancelled", "workflow-timeout"]) +async def test_workflow_preserves_workspace_until_owned_cleanup_settles(tmp_path, monkeypatch, phase, mode): + workspace = tmp_path / "source" + workspace.mkdir() + _repo(workspace, dirty=False) + entered, finish, flushed, source_closed = (asyncio.Event() for _ in range(4)) + observed = {} + loop = asyncio.get_running_loop() + started = loop.time() + workflow_timeout = 4 if mode == "workflow-timeout" else None + + class ReportPool(WorktreePool): + async def acquire(self, role, *, source=None): + environment = await super().acquire(role, source=source) + observed["environment"] = environment + if phase == "workspace-release": + cleanup = environment.cleanup + + async def release_report(): + entered.set() + await finish.wait() + observed["report"] = await observed["source"].read_file("seed.txt") + await cleanup() + flushed.set() + + monkeypatch.setattr(environment, "cleanup", release_report) + return environment + + def provider(**options): + source = options["base_environment"] + observed["source"] = source + cleanup = source.cleanup + + async def close_source(): + await cleanup() + source_closed.set() + + monkeypatch.setattr(source, "cleanup", close_source) + pool = ReportPool(use_worktrees=True, **options) + observed["pool"] = pool + return pool + + async def flow(ctx, _args): + output = await ctx.agent("Write one report.", tools=list(builtin_tools("file_write"))) + if phase == "session-close": + session, = ctx.sessions + + async def copy_report(): + entered.set() + await finish.wait() + try: + observed["report"] = await observed["environment"].read_file("marker.txt") + finally: + flushed.set() + + session.own_runtime(copy_report) + if workflow_timeout is not None: + await asyncio.sleep(max(0, started + workflow_timeout - .25 - loop.time())) + return output + + client = OpenCollab(workspace, environment_providers={"report": provider}) + + async def run(): + try: + return await client.workflow( + flow, llm=Writer(), trace=False, isolation="report", timeout=workflow_timeout, + cleanup_timeout=.6 if workflow_timeout is not None else .1, + ) + except asyncio.CancelledError as exc: + observed["cancellation"] = exc.args + raise + + operation = asyncio.create_task(run()) + try: + await asyncio.wait_for(entered.wait(), 8) + if mode == "caller-cancelled": + operation.cancel("caller stopped") + done, _ = await asyncio.wait({operation}, timeout=2) + assert operation in done + expected_error = asyncio.CancelledError if mode == "caller-cancelled" else RunError + with pytest.raises(expected_error): + await operation + assert Path(observed["environment"].workspace).is_dir() + assert not source_closed.is_set() + assert await observed["source"].read_file("seed.txt") == "initial" + if mode == "caller-cancelled": + assert observed["cancellation"] == ("caller stopped",) + finally: + finish.set() + await asyncio.gather(operation, return_exceptions=True) + try: + if entered.is_set(): + await asyncio.wait_for(flushed.wait(), 5) + await asyncio.wait_for(source_closed.wait(), 5) + assert not Path(observed["environment"].workspace).exists() + finally: + if "pool" in observed: + await observed["pool"].release() + assert observed["report"] == ("marker" if phase == "session-close" else "initial") + + +@pytest.mark.parametrize("caller_owns_source", [False, True]) +async def test_workflow_removes_worktree_after_final_save_settles(tmp_path, monkeypatch, caller_owns_source): + repository = tmp_path / "source" + repository.mkdir() + _repo(repository, dirty=False) + saving, removed, source_closed = (asyncio.Event() for _ in range(3)) + finish_save = threading.Event() + loop = asyncio.get_running_loop() + observed = {} + + class ReportPool(WorktreePool): + async def acquire(self, role, *, source=None): + workspace = await super().acquire(role, source=source) + observed["workspace"] = workspace + return workspace + + async def release_env(self, env): + await super().release_env(env) + removed.set() + + def provider(**options): + source = options["base_environment"] + cleanup = source.cleanup + + async def close_source(): + await cleanup() + source_closed.set() + + monkeypatch.setattr(source, "cleanup", close_source) + pool = ReportPool(use_worktrees=True, **options) + observed["pool"] = pool + return pool + + async def flow(ctx, _args): + answer = await ctx.agent("Write a report.", tools=list(builtin_tools("file_write"))) + await ctx.wait_for_pending_cleanup() + session, = ctx.sessions + append = session.store.append_snapshot_delta + + def finish_delayed_save(path, **kwargs): + loop.call_soon_threadsafe(saving.set) + if not finish_save.wait(10): + raise TimeoutError("Test did not release the final save") + append(path, **kwargs) + observed["saved"] = True + + monkeypatch.setattr(session.store, "append_snapshot_delta", finish_delayed_save) + return answer + + source = LocalEnvironment(str(repository)) if caller_owns_source else None + client = OpenCollab(repository, environment=source, environment_providers={"report": provider}) + operation = asyncio.create_task(client.workflow( + flow, llm=Writer(), trace=False, isolation="report", cleanup_timeout=.1, artifacts=tmp_path / "artifacts", + )) + try: + await asyncio.wait_for(saving.wait(), 8) + done, _ = await asyncio.wait({operation}, timeout=2) + assert operation in done + with pytest.raises(RunError): + await operation + checkout = Path(observed["workspace"].workspace) + assert (checkout / "marker.txt").read_text() == "marker" + assert not removed.is_set() and not source_closed.is_set() + + finish_save.set() + await asyncio.wait_for(removed.wait(), 5) + assert observed["saved"] and not checkout.exists() + if source is None: + await asyncio.wait_for(source_closed.wait(), 5) + else: + assert not source_closed.is_set() + assert await source.read_file("seed.txt") == "initial" + finally: + finish_save.set() + await asyncio.gather(operation, return_exceptions=True) + if "pool" in observed: + await observed["pool"].release() + if source is not None: + await source.cleanup() + + @pytest.mark.parametrize("entry_isolation", ["shared", "worktree"]) async def test_team_role_override_and_isolated_entry_patch(tmp_path, monkeypatch, entry_isolation): _repo(tmp_path) diff --git a/tests/interfaces/test_team_workflow.py b/tests/interfaces/test_team_workflow.py index 3f6ab537..d4c97021 100644 --- a/tests/interfaces/test_team_workflow.py +++ b/tests/interfaces/test_team_workflow.py @@ -12,6 +12,7 @@ from opencollab.bootstrap.tool_registry import build_tools_for_role from opencollab.sdk import OpenCollab from tests.support.environment_test_support import local_environment_factory as local_environment_factory +from tests.support.provider_sdk_http import completion_http_response, http_response, install_sdk_transport def _call(name, args): @@ -127,6 +128,93 @@ async def complete(self, messages, **kwargs): assert manifest["status"] == "completed" +@pytest.mark.parametrize("kind", ["finite", "none", "path", "nan", "cycle", "invalid_text", "raises"]) +async def test_registered_workflow_records_output_format_failures(tmp_path, monkeypatch, kind): + workflows = tmp_path / "workflows" + workflows.mkdir() + (workflows / "measurement.py").write_text(""" +from pathlib import Path + +from opencollab import workflow + +@workflow +async def measurement(ctx, args): + summary = await ctx.agent("Summarize calibration measurements.", tools=[]) + Path(ctx.workspace_root, "measurement.txt").write_text(summary, encoding="utf-8") + case = args["kind"] + if case == "nan": + return {"mean": float("nan")} + if case == "cycle": + values = [] + values.append(values) + return values + if case == "invalid_text": + return bytes([255]).decode("utf-8", "surrogateescape") + if case == "none": + return None + if case == "path": + return Path("measurement.txt") + if case == "raises": + raise ValueError("No sample was available.") + return {"mean": 21.0, "unit": "µg"} +""", encoding="utf-8") + config = tmp_path / "team.yaml" + config.write_text( + "entry: analyst\nroles:\n analyst:\n prompt: Run the registered measurement.\n" + " tools: [run_workflow]\n", + encoding="utf-8", + ) + received = [] + + async def respond(request): + messages = json.loads(request.content)["messages"] + if any(message.get("content") == "Summarize calibration measurements." + for message in messages if message["role"] == "user"): + return completion_http_response(request, text="Calibration summary ready.") + replies = [message for message in messages if message["role"] == "tool"] + if replies: + received.append(replies[-1]["content"]) + return completion_http_response(request, text="Observed the workflow outcome.") + response = completion_http_response(request).json() + choice = response["choices"][0] + choice["finish_reason"] = "tool_calls" + choice["message"].update(content=None, tool_calls=[ + _call("run_workflow", {"name": "measurement", "args": {"kind": kind}, "budget": 4000}), + ]) + return http_response(request, 200, json=response) + + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", "") + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + install_sdk_transport(monkeypatch, "openai", respond) + artifacts = tmp_path / "run" + result = await OpenCollab( + tmp_path, model="measurement-fixture", provider="openai", + api_key=__name__, base_url="https://controlled.invalid/v1", + config={"llm_max_retries": 0, "max_output_tokens": 128}, + ).team( + "Run the local measurement.", config=config, budget=15000, + artifacts=artifacts, trace=False, use_worktrees=False, timeout=12, + ) + assert result.ok and result.output == "Observed the workflow outcome." + assert result.tokens == 12 + assert (tmp_path / "measurement.txt").read_text(encoding="utf-8") == "Calibration summary ready." + manifest_path, = artifacts.rglob("workflow.json") + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + assert manifest["tokens_spent"] == 4 + reply, = received + if kind in {"nan", "cycle", "invalid_text"}: + assert "Workflow output is not JSON serializable:" in reply + assert (manifest["status"], manifest["reason"]) == ("failed", "output_format_failed") + elif kind == "raises": + assert "No sample was available." in reply + assert (manifest["status"], manifest["reason"]) == ("failed", "workflow_exception") + else: + outputs = {"finite": {"mean": 21.0, "unit": "µg"}, "none": None, "path": "measurement.txt"} + assert json.loads(reply)["output"] == outputs[kind] + assert manifest["status"] == "completed" + + def test_workflow_dispatch_requires_explicit_team_permission(): assert all("run_workflow" not in r.tools for r in default_team_config().roles.values()) with pytest.raises(ValueError, match="requires a Team session"): diff --git a/tests/interfaces/test_workflow_budget_result.py b/tests/interfaces/test_workflow_budget_result.py new file mode 100644 index 00000000..a2b0f013 --- /dev/null +++ b/tests/interfaces/test_workflow_budget_result.py @@ -0,0 +1,89 @@ +from __future__ import annotations + +import asyncio +import json + +import pytest +from typer.testing import CliRunner + +from opencollab import OpenCollab +from opencollab.adapters.cli import workflow as workflow_cli +from opencollab.application.workflow_registry import Registry, WorkflowSpec +from tests.support.provider_sdk_http import completion_http_response, install_sdk_transport + + +@pytest.mark.parametrize("surface", ["cli", "sdk"]) +@pytest.mark.parametrize("settle_first", [False, True]) +def test_budget_stop_reports_spend_after_owned_cleanup(tmp_path, monkeypatch, surface, settle_first): + usage_path = tmp_path / "usage.jsonl" + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(usage_path)) + monkeypatch.setenv("OPENCOLLAB_WIRE_PROTOCOL", "chat_completions") + monkeypatch.setenv("OPENCOLLAB_LLM_STREAM_CHAT", "false") + monkeypatch.setenv("OPENCOLLAB_LLM_MAX_RETRIES", "0") + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + started = asyncio.Event() + release = asyncio.Event() + calls = [] + + async def measure(ctx, _inputs): + first = asyncio.create_task(ctx.agent("First measurement", budget=80_000, tools=[])) + await asyncio.wait_for(started.wait(), timeout=2) + try: + if settle_first: + release.set() + initial = await first + followup = await ctx.agent("Review measurement", tools=[]) + return [initial, followup] + return await ctx.agent("Review measurement", tools=[]) + finally: + release.set() + + async def respond(request): + messages = json.loads(request.content)["messages"] + prompt = next(message["content"] for message in reversed(messages) if message["role"] == "user") + calls.append(prompt) + if prompt == "First measurement": + started.set() + await release.wait() + return completion_http_response(request, text="Verified subtotal", output_tokens=5) + + install_sdk_transport(monkeypatch, "openai", respond) + base_url = "https://fixture.invalid/v1" + if surface == "cli": + registry = Registry() + registry.register(WorkflowSpec("measure", "Measure the subtotal.", measure)) + monkeypatch.setattr(workflow_cli, "load_registry", lambda _workspace: registry) + run = CliRunner().invoke(workflow_cli.app, [ + "run", "measure", "--workspace", str(tmp_path), "--model", "offline-checker", "--provider", "openai", + "--api-key", tmp_path.name, "--base-url", base_url, "--budget", "80000", "--no-trace", + ]) + assert run.exit_code == (0 if settle_first else 1), run.output + start = run.output.rindex("[\n" if settle_first else "{\n") + output = json.loads(run.output[start:]) + manifest_path, = (tmp_path / ".opencollab" / "sessions").glob("*/workflow.json") + else: + app = OpenCollab(tmp_path, model="offline-checker", provider="openai", api_key=tmp_path.name, base_url=base_url) + artifacts = tmp_path / "artifacts" + result = asyncio.run(app.workflow(measure, artifacts=artifacts, budget=80_000, trace=False)) + assert result.status == ("completed" if settle_first else "stopped") + assert result.reason == (None if settle_first else "budget_exceeded") + assert result.tokens == (14 if settle_first else 7) + output = result.output + manifest_path = artifacts / "workflow.json" + + manifest = json.loads(manifest_path.read_text()) + ledger = [json.loads(row) for row in usage_path.read_text().splitlines()] + paid = sum(row["usage"]["total_tokens"] for row in ledger) + assert len(calls) == len(ledger) == (2 if settle_first else 1) + assert manifest["evidence_complete"] is True + assert manifest["tokens_spent"] == paid == (14 if settle_first else 7) + if settle_first: + assert output == ["Verified subtotal", "Verified subtotal"] + else: + assert output == { + "status": "budget_exceeded", + "error": "workflow budget exhausted: spent 0 of 80000", + "tokens_spent": paid, + "budget_total": 80_000, + } diff --git a/tests/runtime/test_anthropic_preserved_history.py b/tests/runtime/test_anthropic_preserved_history.py index f510ede3..ea6a5e19 100644 --- a/tests/runtime/test_anthropic_preserved_history.py +++ b/tests/runtime/test_anthropic_preserved_history.py @@ -16,6 +16,7 @@ from opencollab.adapters.llm.client import LLMClient from opencollab.adapters.tools.fs import FileReadTool, FileWriteTool from opencollab.application._anthropic_history import _anthropic_history_input, _remember_anthropic_history +from opencollab.application.session import SessionBusyError from opencollab.application.session_snapshot import _restore_anthropic_history from opencollab.application.shaping import AutoCompactShaper, PerToolResultBudgetShaper, ToolOutputClearShaper from opencollab.application.steering import READS_NUDGE_HARD @@ -1059,7 +1060,15 @@ def pause_fallback(*args, **kwargs): assert await asyncio.to_thread(fallback_started.wait, 10) writer.messages = [*writer.messages, {"role": "user", "content": "peer checkpoint evidence"}] - writer.save(str(path)) + before = OpenCollab.read_session_snapshot(path) + with pytest.raises(SessionBusyError): + writer.save(str(path)) + assert OpenCollab.read_session_snapshot(path) == before + + # Simulate a legacy writer to exercise the stale checkpoint and fallback checks. + with monkeypatch.context() as legacy_writer: + legacy_writer.setattr(writer.store, "try_autosave_lock", lambda *args, **kwargs: lambda: None) + writer.save(str(path)) published = OpenCollab.read_session_snapshot(path) release_fallback.set() reply_to_first.set() @@ -1188,7 +1197,7 @@ async def provider(request): ids=["between-checkpoints", "periodic-checkpoint", "checkpoint-error", "append-error"], ) async def test_legacy_journal_persists_native_rewrites_before_checkpoint( - monkeypatch, tmp_path, base_sequence, failed_write, expected_writes, + monkeypatch, tmp_path, caplog, base_sequence, failed_write, expected_writes, ): monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") path = str(tmp_path / "session.json") @@ -1257,7 +1266,9 @@ async def provider(request): assert restored.messages == session.messages assert sum(row["role"] == "tool" for row in restored.messages) == 1 assert writes == expected_writes - assert session.persistence_errors == ((write_error,) if failed_write in expected_writes else ()) + if failed_write == "checkpoint" and "checkpoint" in expected_writes: + assert "session checkpoint deferred after durable autosave" in caplog.text + assert session.persistence_errors == ((write_error,) if failed_write == "append" else ()) resume.set() assert await running == "done" diff --git a/tests/runtime/test_anthropic_thinking_top_p_http.py b/tests/runtime/test_anthropic_thinking_top_p_http.py index 1e85915e..edcb3a86 100644 --- a/tests/runtime/test_anthropic_thinking_top_p_http.py +++ b/tests/runtime/test_anthropic_thinking_top_p_http.py @@ -63,6 +63,7 @@ async def handler(request): async def test_claude_4_6_thinking_sends_supported_top_p( monkeypatch, tmp_path, top_p, public_agent, model, thinking_params, ): + monkeypatch.setenv("OPENCOLLAB_TOP_P", "0.81") requests = [] async def handler(request): @@ -77,6 +78,7 @@ async def handler(request): config={"llm_max_retries": 0, "thinking": True, "thinking_params": thinking_params, "top_p": top_p, "max_output_tokens": 2048}, ) + assert app.configuration["top_p"] == top_p if public_agent: result = await app.agent("Return ok", tools=(), trace=False, budget=10000, max_steps=1) assert result.status == "completed" diff --git a/tests/runtime/test_autosave_journal_capacity.py b/tests/runtime/test_autosave_journal_capacity.py new file mode 100644 index 00000000..9dcc661f --- /dev/null +++ b/tests/runtime/test_autosave_journal_capacity.py @@ -0,0 +1,211 @@ +from __future__ import annotations + +import asyncio +import errno +import json +import multiprocessing +import os +from pathlib import Path +from unittest.mock import patch + +import pytest + +from opencollab import OpenCollab +from opencollab.adapters import storage as storage_module +from opencollab.adapters.env import LocalEnvironment +from opencollab.adapters.storage import SessionStore +from opencollab.application.ports import SnapshotCapacityError, SnapshotSequenceConflict +from opencollab.bootstrap import build_session +from opencollab.domain.agent import Agent +from opencollab.tools import builtin_tools +from tests.support.session_run_test_support import llm_response, tool_call + + +@pytest.mark.parametrize("length", [2000, 8000]) +async def test_current_tool_results_survive_autosave_capacity(tmp_path, monkeypatch, length): + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + monkeypatch.setattr(storage_module, "MAX_SESSION_SNAPSHOT_BYTES", 32 * 1024) + path = tmp_path / "review.json" + for step in range(1, 4): + (tmp_path / f"report-{step}.txt").write_text(f"Section {step}\n" + str(step) * length) + + reply_started = asyncio.Event() + allow_completion = asyncio.Event() + + class RecordingModel: + def __init__(self): + self.calls = 0 + + async def complete(self, messages, **kwargs): + self.calls += 1 + await asyncio.gather(*session._auto_save_subscriber.pending_tasks) + if self.calls == 4: + reply_started.set() + await allow_completion.wait() + return llm_response(content="Review complete") + call = tool_call( + f"read-{self.calls}", "file_read", + json.dumps({"path": f"report-{self.calls}.txt"}), + ) + return llm_response(tool_calls=[call], finish_reason="tool_calls") + + environment = LocalEnvironment(str(tmp_path)) + session = build_session( + agent=Agent(name="reviewer", system_prompt="Read and review the three local reports.", + tools=builtin_tools("file_read")), + env=environment, llm=RecordingModel(), auto_save_path=str(path), max_steps=7, + ) + running = None + try: + await session.add_user_message("Read each report and summarize the findings.") + running = asyncio.create_task(session.run_loop()) + await asyncio.wait_for(reply_started.wait(), 5) + snapshot = OpenCollab.read_session_snapshot(path) + tool_ids = [row["tool_call_id"] for row in snapshot["messages"] if row["role"] == "tool"] + live_ids = [row["tool_call_id"] for row in session.messages if row["role"] == "tool"] + assert live_ids == tool_ids == ["read-1", "read-2", "read-3"] + assert not session.persistence_errors + allow_completion.set() + assert await running == "Review complete" + finally: + allow_completion.set() + if running is not None: + if not reply_started.is_set(): + running.cancel() + await asyncio.gather(running, return_exceptions=True) + await session.aclose() + await environment.cleanup() + + +@pytest.mark.parametrize("rejected", ["capacity", "stale"]) +def test_capacity_recovery_preserves_last_durable_state(tmp_path, monkeypatch, rejected): + monkeypatch.setattr(storage_module, "MAX_SESSION_SNAPSHOT_BYTES", 16 * 1024) + path = tmp_path / "review.json" + journal = path.with_suffix(".json.journal") + store = SessionStore() + base = [{"role": "system", "content": "Summarize the findings."}] + first = {"role": "assistant", "content": "First note. " * 900} + second = {"role": "assistant", "content": "Second note. " * 900} + store.checkpoint_snapshot(str(path), base, meta={}, sequence=1) + store.append_snapshot_delta(str(path), sequence=2, replace_from=1, messages=[first], meta={}) + before = path.read_bytes(), journal.read_bytes() + if rejected == "capacity": + error, sequence = SnapshotCapacityError, 3 + else: + error, sequence = SnapshotSequenceConflict, 2 + with pytest.raises(error): + store.append_snapshot_delta( + str(path), sequence=sequence, replace_from=2, messages=[second], meta={}, + ) + assert (path.read_bytes(), journal.read_bytes()) == before + assert store.load_snapshot(str(path), "")["messages"] == [*base, first] + + +_ROLLOVER_LIMIT = 16 * 1024 +_SYSTEM_MESSAGE = {"role": "system", "content": "Keep the latest review draft."} + + +def _draft(number: int) -> dict[str, str]: + return {"role": "user", "content": f"Draft {number} " + "text " * 1200} + + +def _append_draft(path: str, sequence: int, number: int) -> None: + SessionStore().append_snapshot_delta( + path, sequence=sequence, replace_from=1, messages=[_draft(number)], + meta={"session_state": {"draft": number}}, + seen_result_hashes_reset=True, seen_result_hashes_added=[f"draft-{number}"], + ) + + +@pytest.fixture +def near_capacity_journal(tmp_path, monkeypatch): + monkeypatch.setattr(storage_module, "MAX_SESSION_SNAPSHOT_BYTES", _ROLLOVER_LIMIT) + path = tmp_path / "rolling-snapshot.json" + SessionStore().checkpoint_snapshot(str(path), [_SYSTEM_MESSAGE], meta={}, sequence=1) + _append_draft(str(path), 2, 1) + _append_draft(str(path), 3, 2) + return path, path.with_suffix(".json.journal") + + +def test_automatic_rollover_preserves_failure_before_base_publish(near_capacity_journal, monkeypatch): + path, journal = near_capacity_journal + real_replace = os.replace + + def fail_base_rename(src, dst): + if Path(dst) == path: + raise OSError(errno.EIO, "Could not replace base") + return real_replace(src, dst) + + before = path.read_bytes(), journal.read_bytes() + with monkeypatch.context() as fail: + fail.setattr(os, "replace", fail_base_rename) + with pytest.raises(OSError, match="Could not replace base"): + _append_draft(str(path), 4, 3) + + assert (path.read_bytes(), journal.read_bytes()) == before + _append_draft(str(path), 4, 3) + assert OpenCollab.read_session_snapshot(path)["messages"] == [_SYSTEM_MESSAGE, _draft(3)] + + +def _interrupt_before_journal_reset(path: Path, journal: Path) -> None: + storage_module.MAX_SESSION_SNAPSHOT_BYTES = _ROLLOVER_LIMIT + real_replace = os.replace + + def interrupt_journal_rename(src, dst): + if Path(dst) == journal: + os._exit(73) + return real_replace(src, dst) + + with patch.object(os, "replace", interrupt_journal_rename): + _append_draft(str(path), 4, 3) + + +@pytest.mark.parametrize("failure", ["rename-eio", "process-exit"]) +def test_automatic_rollover_with_covered_journal_can_be_retried( + near_capacity_journal, monkeypatch, caplog, failure, +): + path, journal = near_capacity_journal + prior_journal = journal.read_bytes() + if failure == "process-exit": + context = multiprocessing.get_context("spawn") + worker = context.Process(target=_interrupt_before_journal_reset, args=(path, journal)) + worker.start() + try: + worker.join(timeout=10) + assert worker.exitcode == 73 + finally: + if worker.is_alive(): + worker.kill() + worker.join(timeout=10) + else: + real_replace = os.replace + + def fail_journal_rename(src, dst): + if Path(dst) == journal: + raise OSError(errno.EIO, "Could not reset journal") + return real_replace(src, dst) + + with monkeypatch.context() as fail: + fail.setattr(os, "replace", fail_journal_rename) + _append_draft(str(path), 4, 3) + assert "Could not reset journal" in caplog.text + + base = json.loads(path.read_bytes()) + assert base["_autosave_sequence"] == 4 + assert journal.read_bytes() == prior_journal + assert OpenCollab.read_session_snapshot(path)["messages"] == [_SYSTEM_MESSAGE, _draft(3)] + + with pytest.raises(SnapshotSequenceConflict, match="conflicting autosave sequence 4"): + _append_draft(str(path), 4, 9) + with pytest.raises(SnapshotSequenceConflict, match="stale autosave sequence 3"): + _append_draft(str(path), 3, 2) + assert journal.read_bytes() == prior_journal + + _append_draft(str(path), 4, 3) + assert journal.read_bytes() == b"" + _append_draft(str(path), 5, 4) + restored = OpenCollab.read_session_snapshot(path) + assert restored["_autosave_sequence"] == 5 + assert restored["messages"] == [_SYSTEM_MESSAGE, _draft(4)] + assert restored["session_state"] == {"draft": 4, "seen_result_hashes": ["draft-4"]} diff --git a/tests/runtime/test_autosave_ownership_store.py b/tests/runtime/test_autosave_ownership_store.py new file mode 100644 index 00000000..4a75ef30 --- /dev/null +++ b/tests/runtime/test_autosave_ownership_store.py @@ -0,0 +1,229 @@ +from __future__ import annotations + +import errno +import multiprocessing +import os +import signal +from multiprocessing.synchronize import Event +from pathlib import Path + +import pytest + +from opencollab.adapters import storage +from opencollab.adapters.storage import SessionStore +from opencollab.application.ports import AutosaveOwnershipStorePort, SnapshotSequenceConflict + + +def _hold_autosave_lock(path: str, ready: Event, stop: Event) -> None: + release = SessionStore().try_autosave_lock(path) + assert release is not None + try: + ready.set() + assert stop.wait(timeout=15) + finally: + release() + + +def test_autosave_lock_coordinates_processes_and_recovers_after_kill(tmp_path: Path) -> None: + path = str(tmp_path / "nested" / "session.json") + lock_path = Path(f"{path}.autosave.lock") + store = SessionStore() + assert isinstance(store, AutosaveOwnershipStorePort) + release = store.try_autosave_lock(path) + assert release is not None + release() + inode = lock_path.stat().st_ino + messages = [{"role": "user", "content": "saved"}] + store.append_snapshot_delta(path, sequence=1, replace_from=0, messages=messages, meta={}) + + context = multiprocessing.get_context("spawn") + ready = context.Event() + stop = context.Event() + holder = context.Process(target=_hold_autosave_lock, args=(path, ready, stop)) + holder.start() + try: + assert ready.wait(timeout=10) + assert store.try_autosave_lock(path, expected_sequence=0) is None + assert store.load_snapshot(path, "system")["messages"] == messages + finally: + holder.kill() + holder.join(timeout=10) + assert holder.exitcode == -signal.SIGKILL + + release = store.try_autosave_lock(path) + assert release is not None + release() + assert lock_path.stat().st_ino == inode + + +@pytest.mark.parametrize("publisher", ["checkpoint", "journal"]) +def test_autosave_lock_checks_the_newest_durable_sequence( + tmp_path: Path, publisher: str, +) -> None: + path = str(tmp_path / "session.json") + store = SessionStore() + messages = [{"role": "user", "content": "saved"}] + if publisher == "checkpoint": + store.checkpoint_snapshot(path, messages, meta={}, sequence=5) + else: + store.append_snapshot_delta(path, sequence=5, replace_from=0, messages=messages, meta={}) + store.append_snapshot_delta(path, sequence=3, replace_from=0, messages=messages, meta={}) + with Path(f"{path}.journal").open("ab") as journal: + journal.write(b'{"journal_version":1,"sequence":9}') + + store = SessionStore() + with pytest.raises(SnapshotSequenceConflict, match="sequence 4; persisted sequence 5"): + store.try_autosave_lock(path, expected_sequence=4) + + for expected_sequence in (None, 5, 6): + release = store.try_autosave_lock(path, expected_sequence=expected_sequence) + assert release is not None + release() + + +def test_autosave_lock_releases_after_validation_failure( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + path = str(tmp_path / "session.json") + store = SessionStore() + + def fail_read(_path: str) -> int: + raise PermissionError(errno.EACCES, "could not read persisted sequence") + + monkeypatch.setattr(store, "_newest_persisted_sequence", fail_read) + with pytest.raises(PermissionError, match="could not read persisted sequence"): + store.try_autosave_lock(path, expected_sequence=0) + + release = store.try_autosave_lock(path) + assert release is not None + release() + + +@pytest.mark.parametrize("publisher", ["checkpoint", "journal"]) +def test_autosave_lock_reuses_native_appends_and_detects_peer_writes( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, publisher: str, +) -> None: + path = str(tmp_path / "session.json") + store = SessionStore() + messages = [{"role": "user", "content": "saved"}] + release = store.try_autosave_lock(path, expected_sequence=0) + assert release is not None + release() + + def unexpected_read(_path: str) -> int: + pytest.fail("unchanged files or a tracked append should reuse the durable cursor") + + with monkeypatch.context() as cached: + cached.setattr(store, "_newest_persisted_sequence", unexpected_read) + store.append_snapshot_delta(path, sequence=5, replace_from=0, messages=messages, meta={}) + store.append_snapshot_delta(path, sequence=3, replace_from=0, messages=messages, meta={}) + + with pytest.raises(SnapshotSequenceConflict, match="sequence 4; persisted sequence 5"): + store.try_autosave_lock(path, expected_sequence=4) + release = store.try_autosave_lock(path, expected_sequence=5) + assert release is not None + release() + + peer = SessionStore() + if publisher == "checkpoint": + peer.checkpoint_snapshot(path, messages, meta={}, sequence=6) + else: + peer.append_snapshot_delta(path, sequence=6, replace_from=0, messages=messages, meta={}) + with pytest.raises(SnapshotSequenceConflict, match="sequence 5; persisted sequence 6"): + store.try_autosave_lock(path, expected_sequence=5) + + +@pytest.mark.parametrize("operation", ["checkpoint", "load"]) +def test_autosave_lock_reuses_cursor_from_locked_storage_operations( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, operation: str, +) -> None: + path = str(tmp_path / "session.json") + store = SessionStore() + messages = [{"role": "user", "content": "saved"}] + if operation == "checkpoint": + store.checkpoint_snapshot(path, messages, meta={}, sequence=4) + else: + SessionStore().checkpoint_snapshot(path, messages, meta={}, sequence=4) + assert store.load_snapshot(path, "")["messages"] == messages + + def unexpected_read(_path: str) -> int: + pytest.fail("checkpoint or load should remember the durable cursor") + + monkeypatch.setattr(store, "_newest_persisted_sequence", unexpected_read) + with pytest.raises(SnapshotSequenceConflict, match="sequence 3; persisted sequence 4"): + store.try_autosave_lock(path, expected_sequence=3) + + +def test_autosave_ownership_and_checkpoint_survive_cache_refresh_failure( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + path = str(tmp_path / "session.json") + store = SessionStore() + messages = [{"role": "user", "content": "saved"}] + + release = store.try_autosave_lock(path, expected_sequence=0) + assert release is not None + release() + + def fail_stat(_path: str) -> None: + raise OSError(errno.EIO, "could not check file revisions") + + monkeypatch.setattr(store, "_autosave_file_revisions", fail_stat) + store.checkpoint_snapshot(path, messages, meta={}, sequence=4) + with pytest.raises(SnapshotSequenceConflict, match="sequence 3; persisted sequence 4"): + store.try_autosave_lock(path, expected_sequence=3) + assert SessionStore().load_snapshot(path, "")["messages"] == messages + + +def test_autosave_ownership_observes_an_explicit_overwrite( + tmp_path: Path, +) -> None: + path = str(tmp_path / "session.json") + store = SessionStore() + peer = SessionStore() + messages = [{"role": "user", "content": "saved"}] + store.checkpoint_snapshot(path, messages, meta={}, sequence=5) + + release = peer.try_autosave_lock(path) + assert release is not None + try: + peer.save(path, messages) + finally: + release() + + release = store.try_autosave_lock(path, expected_sequence=0) + assert release is not None + release() + + +def test_autosave_lock_propagates_io_failure_and_closes_handle( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + path = str(tmp_path / "session.json") + Path(f"{path}.autosave.lock").touch() + opened: list[int] = [] + + def fail_lock(fd: int, operation: int) -> None: + assert operation == storage.fcntl.LOCK_EX | storage.fcntl.LOCK_NB + opened.append(fd) + raise OSError(errno.EIO, "flock failed") + + monkeypatch.setattr(storage.fcntl, "flock", fail_lock) + with pytest.raises(OSError) as error: + SessionStore().try_autosave_lock(path) + assert error.value.errno == errno.EIO + + (fd,) = opened + with pytest.raises(OSError) as closed: + os.fstat(fd) + assert closed.value.errno == errno.EBADF + + +def test_autosave_lock_rejects_dangling_sidecar_symlink(tmp_path: Path) -> None: + path = str(tmp_path / "session.json") + target = tmp_path / "missing" + Path(f"{path}.autosave.lock").symlink_to(target) + + with pytest.raises(OSError): + SessionStore().try_autosave_lock(path) + assert not target.exists() diff --git a/tests/runtime/test_autosave_subscriber.py b/tests/runtime/test_autosave_subscriber.py index ecbc562f..fb3ccc15 100644 --- a/tests/runtime/test_autosave_subscriber.py +++ b/tests/runtime/test_autosave_subscriber.py @@ -3,16 +3,22 @@ from __future__ import annotations import asyncio +import errno import json import logging +import os import threading import time +from pathlib import Path +from unittest.mock import patch import pytest +from opencollab.adapters import safe_files from opencollab.adapters.storage import SessionStore -from opencollab.application.autosave import SAVE_TRIGGERS, AutoSaveSubscriber +from opencollab.application.autosave import SAVE_TRIGGERS, AutoSaveSubscriber, _run_save from opencollab.application.event_bus import EventBus +from opencollab.application.ports import SnapshotCapacityError, SnapshotSequenceConflict from opencollab.bootstrap import build_session as Session from opencollab.bootstrap import load_session from opencollab.domain.events import SessionRuntimeEvent as SessionEvent @@ -338,7 +344,19 @@ async def scenario(): assert seen == [] -def test_session_with_auto_save_path_writes_on_user_message(local_environment_factory, tmp_path): +@pytest.mark.parametrize("delay_save_task", [False, True]) +def test_session_with_auto_save_path_writes_on_user_message( + local_environment_factory, tmp_path, monkeypatch, delay_save_task, +): + if delay_save_task: + original = asyncio.to_thread + + async def delayed_submission(function, *args, **kwargs): + if function is _run_save: + await asyncio.sleep(.05) + return await original(function, *args, **kwargs) + + monkeypatch.setattr(asyncio, "to_thread", delayed_submission) path = tmp_path / "auto.jsonl" session = Session( env=local_environment_factory(), @@ -426,6 +444,40 @@ async def scenario(): assert session.persistence_errors == (injected_error,) assert journal_path.read_bytes() == b"" +@pytest.mark.parametrize("error_type", [OSError, SnapshotCapacityError, SnapshotSequenceConflict]) +async def test_scheduled_checkpoint_failure_after_durable_append( + local_environment_factory, tmp_path, caplog, error_type, +): + path = tmp_path / "scheduled.json" + error = error_type("scheduled checkpoint failed") + store = _SwitchableCheckpointStore(error) + store.fail_checkpoint = True + session = Session( + env=local_environment_factory(), + agent=FakeAgent(), + llm=_CompletingLLM(), + auto_save_path=str(path), + store=store, + ) + + await session.add_user_message("go") + await asyncio.gather(*session.pending_cleanup_tasks) + + assert not path.exists() + saved = store.load_snapshot(str(path), session.agent.system_prompt) + assert saved["messages"][-1]["content"] == "go" + if error_type is SnapshotSequenceConflict: + assert session.persistence_errors == (error,) + else: + assert session.persistence_errors == () + assert "session checkpoint deferred after durable autosave: scheduled checkpoint failed" in caplog.text + + store.fail_checkpoint = False + await session.enqueue_auto_save() + assert json.loads(path.read_bytes())["_autosave_sequence"] == saved["_autosave_sequence"] + 1 + assert path.with_suffix(".json.journal").read_bytes() == b"" + assert await session.run_loop() == "done" + @pytest.mark.parametrize( ("mode", "expected_phase"), [("done", "done"), ("stopped", "stopped"), ("error", "error")], @@ -560,6 +612,70 @@ async def scenario(): asyncio.run(scenario()) +@pytest.mark.parametrize("failure_stage", ["base_rename", "directory_sync", "journal_reset", "append_then_reset"]) +async def test_terminal_result_requires_a_durable_base_but_can_leave_covered_journal( + local_environment_factory, tmp_path, monkeypatch, caplog, failure_stage, +): + path = tmp_path / "completed.json" + journal = path.with_suffix(".json.journal") + session = Session( + env=local_environment_factory(), agent=FakeAgent(), llm=_CompletingLLM(), + auto_save_path=str(path), + ) + error = OSError(errno.EIO, f"checkpoint {failure_stage}") + append_error = OSError(errno.EIO, "terminal append") + append = session.store.append_snapshot_delta + save = session.save + replace_file = os.replace + + def fail_rename(source, destination): + failing_path = path if failure_stage == "base_rename" else journal + if Path(destination) == failing_path: + raise error + return replace_file(source, destination) + + def save_with_failure(target): + if failure_stage == "directory_sync": + with patch.object(safe_files, "_fsync_directory", side_effect=error): + save(target) + else: + with patch.object(os, "replace", fail_rename): + save(target) + + def fail_terminal_append(*args, **kwargs): + if kwargs["meta"]["session_state"]["phase"] == "done": + raise append_error + return append(*args, **kwargs) + + try: + await session.add_user_message("initial turn") + assert await session.run_loop() == "done" + if failure_stage == "append_then_reset": + monkeypatch.setattr(session.store, "append_snapshot_delta", fail_terminal_append) + monkeypatch.setattr(session, "save", save_with_failure) + await session.add_user_message("go") + if failure_stage == "journal_reset": + assert await session.run_loop() == "done" + base = json.loads(path.read_bytes()) + assert base["session_state"]["phase"] == "done" + assert base["messages"][-1]["content"] == "done" + assert journal.stat().st_size > 0 + assert session.persistence_errors == () + assert "could not compact covered session journal" in caplog.text + + with pytest.raises(OSError) as manual: + session.save(str(path)) + assert manual.value is error + else: + with pytest.raises(OSError) as terminal: + await session.run_loop() + assert terminal.value is error + expected = (append_error, error) if failure_stage == "append_then_reset" else (error,) + assert session.persistence_errors == expected + finally: + await session.aclose() + await session.env.cleanup() + def test_cancelling_terminal_checkpoint_waits_for_owned_write(local_environment_factory, tmp_path): class BlockingCheckpointStore(SessionStore): def __init__(self): diff --git a/tests/runtime/test_cancelled_provider_usage.py b/tests/runtime/test_cancelled_provider_usage.py index 47d760e5..07d06cbc 100644 --- a/tests/runtime/test_cancelled_provider_usage.py +++ b/tests/runtime/test_cancelled_provider_usage.py @@ -3,12 +3,15 @@ from __future__ import annotations import asyncio +import json import pytest from opencollab.adapters.storage import SessionStore from opencollab.adapters.tools.spawn import SpawnAgentTool +from opencollab.adapters.trace import Tracer from opencollab.application.event_bus import EventBus +from opencollab.application.run_control import RunControl, RunEvent from opencollab.application.scheduler import Scheduler, SchedulerTurnError from opencollab.application.session import SessionBusyError from opencollab.application.session_run import GenerationTimeoutError @@ -217,12 +220,14 @@ def append_snapshot_delta(self, *args, **kwargs): async def test_late_summary_usage_is_automatically_saved(local_environment_factory, trigger, tmp_path): provider = _DelayedProvider() path = tmp_path / "summary.json" + tracer = Tracer(run_id="late-summary", output_dir=str(tmp_path)) session = build_session( env=local_environment_factory(), agent=FakeAgent(), llm=provider, llm_timeout=0.01 if trigger == "timeout" else None, - auto_save_path=str(path), + auto_save_path=str(path), tracer=tracer, ) session.messages = history() + session.state.set_context_tokens(23) try: await _abandon_call(session, provider, trigger) assert session.used_tokens == 0 @@ -231,19 +236,57 @@ async def test_late_summary_usage_is_automatically_saved(local_environment_facto await asyncio.wait_for(_drain(session), 1) assert session.used_tokens == 37 assert session.runner.late_provider_usage == (37,) + assert session.state.context_tokens == 23 assert session.step_count == 0 assert session.messages == original_messages snapshot = SessionStore().load_snapshot(str(path), session.agent.system_prompt) assert snapshot["session_state"]["used_tokens"] == 37 + assert snapshot["session_state"]["context_tokens"] == 23 assert _message_payloads(snapshot["messages"]) == original_messages restored = load_session(str(path), env=local_environment_factory(), agent=FakeAgent(), llm=provider) assert restored.used_tokens == 37 + assert restored.state.context_tokens == 23 assert restored.messages == original_messages assert restored.step_count == 0 assert session.persistence_errors == () + tracer.flush() + with open(tracer.path, encoding="utf-8") as handle: + calls = [row for line in handle if (row := json.loads(line))["type"] == "llm_call"] + call, = calls + assert call["metrics"]["tokens"] == 37 + assert call["payload"]["purpose"] == "summary" + assert call["payload"]["late"] is True finally: provider.release.set() await _drain(session) + tracer.close() + +async def test_summary_usage_cancellation_keeps_session_reusable(local_environment_factory): + provider = _DelayedProvider() + provider.release.set() + summary_usage = [] + + def cancel_on_first_summary(event: RunEvent) -> None: + if event.type == "usage" and event.data.get("purpose") == "summary": + summary_usage.append(event.used_tokens) + if len(summary_usage) == 1: + turn.cancel() + + session = build_session( + env=local_environment_factory(), agent=FakeAgent(), llm=provider, llm_timeout=600, + run_control=RunControl(history_trigger_tokens=512, on_event=cancel_on_first_summary), + ) + session.messages = history() + turn = asyncio.create_task(session.run_loop()) + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(turn, 5) + + assert summary_usage == [37] + assert session.used_tokens == 37 + assert session.phase is SessionPhase.STOPPED + assert session.runner.pending_cleanup_tasks == () + await session.add_user_message("next turn") + assert await asyncio.wait_for(session.run_loop(), 5) == "provider response" async def test_session_accounts_provider_success_when_cancellation_races_with_completion(local_environment_factory): class Provider: diff --git a/tests/runtime/test_chat_stream_cancellation.py b/tests/runtime/test_chat_stream_cancellation.py new file mode 100644 index 00000000..c576399c --- /dev/null +++ b/tests/runtime/test_chat_stream_cancellation.py @@ -0,0 +1,194 @@ +"""Cancellation and paid usage across timed Chat stream reads.""" + +from __future__ import annotations + +import asyncio +import json + +import pytest + +from opencollab import OpenCollab +from opencollab.adapters.llm.client import LLMClient +from tests.support.provider_sdk_http import install_sdk_transport, provider_http + + +@pytest.mark.parametrize(("mode", "cancel_during_close"), [ + ("timer-cancel", False), + ("header-cancel", False), + ("late-frame-cancel", False), + ("direct-cancel", False), + ("timeout-cancel", False), + ("no-cancel", False), + ("timer-cancel", True), + ("header-cancel", True), +]) +async def test_chat_usage_frame_cancel_preserves_allowance_for_another_call( + tmp_path, monkeypatch, mode, cancel_during_close, +): + mode_requests = [] + accepted_cancellations = [] + caller_errors = [] + reports = {"first": [], "second": []} + stream_closures = [] + usage_path = tmp_path / "usage.jsonl" + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(usage_path)) + monkeypatch.delenv("OPENCOLLAB_EXTERNAL_PROVIDER_ISOLATION", raising=False) + http = provider_http("openai") + loop = asyncio.get_running_loop() + caller = None + waiting_for_late_frame = asyncio.Event() + read_timed_out = asyncio.Event() + closing = asyncio.Event() + release_close = asyncio.Event() + + def cancel_first(_done=None): + accepted_cancellations.append(caller.cancel("withdraw first answer")) + + class ChatStream(http.AsyncByteStream): + def __init__(self, actor, attempt): + self.actor = actor + self.attempt = attempt + self.disconnect = attempt == 1 + self.total = (27 if actor == "first" else 23) if self.disconnect else (41 if actor == "first" else 19) + + async def __aiter__(self): + if self.actor == "first" and self.attempt == 1 and mode == "header-cancel": + await asyncio.sleep(0) + common = {"id": "chatcmpl-usage-timing", "object": "chat.completion.chunk", "created": 1, "model": "gpt-4o"} + status = "partial" if self.disconnect else "finished" + answer = {"role": "assistant", "content": f"{self.actor} {status}"} + for delta, finish in [(answer, None), ({}, "stop")]: + choice = {"index": 0, "delta": delta, "finish_reason": finish} + yield f"data: {json.dumps({**common, 'choices': [choice]})}\n\n".encode() + + direct_iteration = False + if self.actor == "first" and self.attempt == 1 and mode in {"timer-cancel", "direct-cancel"}: + chunk_owner = asyncio.current_task() + direct_iteration = chunk_owner is caller + if direct_iteration: + loop.call_soon(cancel_first) + else: + # The SDK has decoded the usage frame before __anext__ completes. + chunk_owner.add_done_callback(cancel_first) + if self.actor == "first" and self.attempt == 1 and mode == "late-frame-cancel": + waiting_for_late_frame.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + # The local transport can finish this frame while unwinding. + pass + if self.actor == "first" and self.attempt == 1 and mode == "timeout-cancel": + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + read_timed_out.set() + await asyncio.Event().wait() + usage = {"prompt_tokens": self.total - 7, "completion_tokens": 7, "total_tokens": self.total} + yield f"data: {json.dumps({**common, 'choices': [], 'usage': usage})}\n\n".encode() + + if self.disconnect: + if direct_iteration: + # Let the queued user cancellation arrive after the paid frame. + await asyncio.sleep(0) + raise http.ReadError("peer reset after the usage frame") + yield b"data: [DONE]\n\n" + + async def aclose(self): + if cancel_during_close and self.actor == "first" and self.attempt == 1: + closing.set() + await release_close.wait() + stream_closures.append((self.actor, self.attempt)) + + async def handler(request): + body = json.loads(request.content) + actor = body["messages"][-1]["content"] + attempt = mode_requests.count(actor) + 1 + mode_requests.append(actor) + if mode == "header-cancel" and actor == "first" and attempt == 1: + opening = asyncio.current_task() + if opening is caller: + loop.call_soon(cancel_first) + else: + opening.add_done_callback(cancel_first) + assert body["stream"] and body["stream_options"] == {"include_usage": True} + return http.Response(200, headers={"content-type": "text/event-stream"}, stream=ChatStream(actor, attempt)) + + install_sdk_transport(monkeypatch, "openai", handler) + + if mode == "direct-cancel": + client = LLMClient( + model="gpt-4o", api_key=tmp_path.name, base_url="https://fixture.invalid/v1", + stream_chat=True, first_event_timeout=3, stream_idle_timeout=None, + max_retries=1, provider_error_time_budget=1.6, + ) + else: + client = OpenCollab( + tmp_path, model="gpt-4o", provider="openai", api_key=tmp_path.name, + base_url="https://fixture.invalid/v1", + config={"llm_stream_chat": True, "llm_first_event_timeout": 3, + "llm_stream_idle_timeout": 0.25 if mode == "timeout-cancel" else 3, + "llm_max_retries": 1, "provider_error_time_budget": 1.6}, + ).create_model_client() + + async with client: + async def complete(actor): + try: + reply = await client.complete( + [{"role": "user", "content": actor}], + on_usage=lambda usage: reports[actor].append(usage.total_tokens), + ) + except BaseException as exc: + if actor == "first": + caller_errors.append(exc) + raise + return (type(reply).__name__, reply.content) + + caller = asyncio.create_task(complete("first")) + if mode == "late-frame-cancel": + await asyncio.wait_for(waiting_for_late_frame.wait(), 2) + cancel_first() + if mode == "timeout-cancel": + await asyncio.wait_for(read_timed_out.wait(), 2) + cancel_first() + if cancel_during_close: + try: + await asyncio.wait_for(closing.wait(), 2) + assert caller.cancel("withdraw again during HTTP close") + await asyncio.sleep(0) + finally: + release_close.set() + done, _ = await asyncio.wait({caller}, timeout=4) + assert caller in done + try: + first = await caller + except BaseException: + exc, = caller_errors + first = (type(exc).__name__, str(exc)) + after_first = client.provider_retry_budget.remaining_seconds + try: + second = await complete("second") + except Exception as exc: + second = (type(exc).__name__, str(exc)) + + ledger = [json.loads(line) for line in usage_path.read_text().splitlines()] + ledger_history = [ + (record["status"], record["usage"]["total_tokens"], (record.get("error") or {}).get("type")) + for record in ledger + ] + assert len(ledger) == 2 + assert len(stream_closures) == len(mode_requests) + if mode == "no-cancel": + assert first == ("LLMResponse", "first finished") + assert mode_requests == ["first", "first", "second"] + assert reports == {"first": [68], "second": [23]} + assert second[0] == "ReadError" + return + + assert accepted_cancellations == [True] + assert after_first == 1.6 + assert first == ("CancelledError", "withdraw first answer") + assert mode_requests == ["first", "second", "second"] + expected_first = 0 if mode in {"header-cancel", "timeout-cancel"} else 27 + assert reports == {"first": [expected_first] if expected_first else [], "second": [42]} + assert second == ("LLMResponse", "second finished") + assert ledger_history == [("error", expected_first, "CancelledError"), ("success", 42, None)] diff --git a/tests/runtime/test_compaction_accounting.py b/tests/runtime/test_compaction_accounting.py index 04708d30..1bcce6bd 100644 --- a/tests/runtime/test_compaction_accounting.py +++ b/tests/runtime/test_compaction_accounting.py @@ -8,6 +8,7 @@ import pytest +from opencollab import OpenCollab from opencollab.adapters.llm.types import LLMResponse, Usage from opencollab.adapters.trace import Tracer from opencollab.bootstrap import build_session @@ -70,6 +71,7 @@ def test_summary_usage_and_native_trace_fields_are_recorded(local_environment_fa assert len(calls) == 2 summary = next(row for row in calls if row["payload"].get("purpose") == "summary") assert summary["metrics"]["tokens"] == 7_600 + assert not summary["payload"].get("late") assert summary["payload"]["usage"]["input_tokens"] == 7_598 assert summary["payload"]["usage"]["cache_read_tokens"] == 20 assert summary["payload"]["usage"]["raw_usage"] == {"provider_input": 7_598} @@ -123,12 +125,48 @@ async def scenario(): second = await session.runner._shape_and_trace(session.messages) assert first == second assert session.used_tokens == 7_600 + assert session.state.context_tokens == 7_598 assert await session.run_loop() == "answer" asyncio.run(scenario()) assert [call["summary"] for call in model.calls] == [True, False] assert session.used_tokens == 7_610 +async def test_autosave_keeps_settled_summary_usage_before_answer_starts(local_environment_factory, tmp_path): + started = asyncio.Event() + release = asyncio.Event() + + class HeldAnswer(AccountingModel): + async def complete(self, messages, tools=None, **kwargs): + response = await super().complete(messages, tools, **kwargs) + if not self.calls[-1]["summary"]: + started.set() + await release.wait() + return response + + path = tmp_path / "summary.json" + model = HeldAnswer() + session = build_session( + env=local_environment_factory(), agent=Agent(name="inventory", system_prompt="Count the inventory."), + llm=model, auto_save_path=str(path), max_budget_tokens=20_000, + ) + session.messages = history() + session.save(str(path)) + task = asyncio.create_task(session.run_loop()) + try: + await asyncio.wait_for(started.wait(), 5) + assert session.used_tokens == 7_600 + saved = OpenCollab.read_session_snapshot(path)["session_state"] + assert (saved["used_tokens"], saved["context_tokens"]) == (7_600, 7_598) + finally: + release.set() + answer = await asyncio.wait_for(task, 5) + await session.aclose() + + assert answer == "answer" + assert [call["summary"] for call in model.calls] == [True, False] + assert OpenCollab.read_session_snapshot(path)["session_state"]["used_tokens"] == 7_610 + def test_summary_overspend_stops_before_an_answer_request(local_environment_factory): model = AccountingModel(summary_tokens=40_000) session = build_session( @@ -156,12 +194,18 @@ def test_disabled_history_compaction_has_only_answer_usage(local_environment_fac def test_late_summary_response_is_owned_and_charged_once(local_environment_factory, deadline): from opencollab.application.session_run import GenerationTimeoutError + request_started = asyncio.Event() + cancellation_received = asyncio.Event() + release_response = asyncio.Event() + class LateModel(AccountingModel): async def complete(self, messages, tools=None, **kwargs): + request_started.set() try: - await asyncio.sleep(0.15) + await asyncio.Future() except asyncio.CancelledError: - await asyncio.sleep(0.02) + cancellation_received.set() + await release_response.wait() return await super().complete(messages, tools, **kwargs) model = LateModel() @@ -172,16 +216,19 @@ async def complete(self, messages, tools=None, **kwargs): async def scenario(): task = asyncio.create_task(session.run_loop()) - if deadline is None: - await asyncio.sleep(0.01) - task.cancel() - with pytest.raises(asyncio.CancelledError): - await asyncio.wait_for(task, 0.1) - else: - with pytest.raises(GenerationTimeoutError): - await asyncio.wait_for(task, 0.1) - assert session.pending_cleanup_tasks - await asyncio.wait_for(asyncio.gather(*session.pending_cleanup_tasks), 0.1) + try: + await asyncio.wait_for(request_started.wait(), 5) + if deadline is None: + task.cancel() + error = asyncio.CancelledError if deadline is None else GenerationTimeoutError + with pytest.raises(error): + await asyncio.wait_for(task, 5) + await asyncio.wait_for(cancellation_received.wait(), 5) + assert session.pending_cleanup_tasks + assert session.used_tokens == 0 + finally: + release_response.set() + await asyncio.wait_for(asyncio.gather(*session.pending_cleanup_tasks), 5) asyncio.run(scenario()) assert [call["summary"] for call in model.calls] == [True] diff --git a/tests/runtime/test_config.py b/tests/runtime/test_config.py index 87076ac3..a2e62210 100644 --- a/tests/runtime/test_config.py +++ b/tests/runtime/test_config.py @@ -324,9 +324,10 @@ def test_empty_high_priority_file_value_does_not_hide_lower_value( assert build_config(str(tmp_path)).model == "lower-priority-model" -def test_unknown_override_key_fails_fast(): +@pytest.mark.parametrize("value", ["gpt-4o-mini", None]) +def test_unknown_override_key_fails_fast(value): with pytest.raises(Exception, match="modle"): - build_config(overrides={"modle": "gpt-4o-mini"}) + build_config(overrides={"modle": value}) def test_api_key_env_precedence_is_provider_and_endpoint_specific(): assert api_key_env_precedence("openai") == ( diff --git a/tests/runtime/test_config_inline_comments.py b/tests/runtime/test_config_inline_comments.py index 3b78349b..e818af17 100644 --- a/tests/runtime/test_config_inline_comments.py +++ b/tests/runtime/test_config_inline_comments.py @@ -10,7 +10,8 @@ @pytest.mark.parametrize("quote", ["", '"', "'"]) @pytest.mark.parametrize("comment", ["", " # run setting", "\t# run setting"]) -def test_public_sdk_reads_commented_settings(tmp_path, monkeypatch, quote, comment): +@pytest.mark.parametrize("encoding", ["utf-8", "utf-8-sig"]) +def test_public_sdk_reads_commented_settings(tmp_path, monkeypatch, quote, comment, encoding): for name in tuple(os.environ): if name.startswith("OPENCOLLAB_") or name in { "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "DASHSCOPE_API_KEY", @@ -23,7 +24,7 @@ def test_public_sdk_reads_commented_settings(tmp_path, monkeypatch, quote, comme f"OPENCOLLAB_TEMPERATURE={quote}0.7{quote}{comment}\n" f"OPENCOLLAB_THINKING={quote}true{quote}{comment}\n" f"OPENCOLLAB_MODEL={quote}gpt-4o{quote}{comment}\n", - encoding="utf-8", + encoding=encoding, ) config = OpenCollab(tmp_path).configuration diff --git a/tests/runtime/test_env_process_groups.py b/tests/runtime/test_env_process_groups.py index 36833cca..1c68fb37 100644 --- a/tests/runtime/test_env_process_groups.py +++ b/tests/runtime/test_env_process_groups.py @@ -1,4 +1,4 @@ -"""Linux process-group exit detection and its conservative proc fallbacks.""" +"""Process-group exit detection and cleanup.""" from __future__ import annotations @@ -223,6 +223,66 @@ def test_non_linux_group_uses_existing_signal_probe(monkeypatch) -> None: assert process_module._group_exists(101) is True +@pytest.mark.parametrize("denied_signal", [signal.SIGTERM, signal.SIGKILL]) +async def test_darwin_cleanup_confirms_disappearance_after_signal_denial(monkeypatch, denied_signal) -> None: + calls = [] + reaped = False + denied_probe = False + + def killpg(group_id, sig): + nonlocal denied_probe + assert group_id == 101 + if sig: + calls.append(sig) + if sig == denied_signal: + raise PermissionError("Darwin group has no signalable members") + return + if reaped: + if denied_probe: + raise ProcessLookupError + denied_probe = True + raise PermissionError("Darwin group is still exiting") + + async def wait(): + nonlocal reaped + reaped = True + + monkeypatch.setattr(process_module, "sys", SimpleNamespace(platform="darwin")) + monkeypatch.setattr(process_module, "os", SimpleNamespace(name="posix", killpg=killpg)) + process = SimpleNamespace(pid=101, wait=wait) + + assert await process_module.terminate_process(process, term_grace=0, kill_grace=1) + assert reaped and denied_probe + assert calls == ([signal.SIGTERM, signal.SIGKILL] if denied_signal == signal.SIGKILL else [signal.SIGTERM]) + +@pytest.mark.parametrize(("platform", "wait_stalls"), [("darwin", False), ("darwin", True), ("linux", False)]) +async def test_cleanup_preserves_signal_permission_error_without_confirmed_exit(monkeypatch, platform, wait_stalls): + signals = [] + waited = False + error = PermissionError("permission denied for live group") + + def killpg(group_id, sig): + assert group_id == 101 + if sig: + signals.append(sig) + raise error + + async def wait(): + nonlocal waited + waited = True + if wait_stalls: + await asyncio.Event().wait() + + monkeypatch.setattr(process_module, "sys", SimpleNamespace(platform=platform)) + monkeypatch.setattr(process_module, "os", SimpleNamespace(name="posix", killpg=killpg)) + process = SimpleNamespace(pid=101, wait=wait) + + with pytest.raises(PermissionError) as exc: + await process_module.terminate_process(process, term_grace=0, kill_grace=0.02) + assert exc.value is error + assert waited is (platform == "darwin") + assert signals == [signal.SIGTERM] + _GROUP_SUPERVISOR = textwrap.dedent("""\ import ctypes import os diff --git a/tests/runtime/test_exported_session_resume.py b/tests/runtime/test_exported_session_resume.py index 23ac8dd3..c4617e45 100644 --- a/tests/runtime/test_exported_session_resume.py +++ b/tests/runtime/test_exported_session_resume.py @@ -2,20 +2,28 @@ from __future__ import annotations +import asyncio import copy +import errno import json +import threading +from contextlib import AsyncExitStack import pytest from opencollab import OpenCollab +from opencollab.adapters import storage from opencollab.adapters.env import LocalEnvironment from opencollab.adapters.llm.client import LLMClient from opencollab.adapters.storage import SessionStore -from opencollab.application.ports import SnapshotSequenceConflict +from opencollab.application.ports import SnapshotCapacityError, SnapshotSequenceConflict from opencollab.bootstrap import build_session, load_session from opencollab.domain import session as session_module from opencollab.domain.agent import Agent +from opencollab.domain.pending import PendingRow, RowKind +from opencollab.domain.session import SessionPhase from opencollab.tools import builtin_tools +from tests.support.environment_test_support import local_environment_factory as local_environment_factory from tests.support.provider_sdk_http import completion_http_response, http_response, install_sdk_transport from tests.support.session_run_test_support import FakeLLM, llm_response, tool_call @@ -35,6 +43,232 @@ def transcript(snapshot): return [{key: value for key, value in row.items() if key != "timestamp"} for row in snapshot["messages"]] + +@pytest.mark.parametrize(("borrow_env", "borrow_llm", "close_fails"), [ + (False, False, False), (False, True, False), + (True, False, False), (True, True, False), + (False, False, True), +]) +async def test_failed_load_releases_only_owned_resources(tmp_path, monkeypatch, borrow_env, borrow_llm, close_fails): + monkeypatch.chdir(tmp_path) + source = str(tmp_path / "export.json") + target = str(tmp_path / "autosave.json") + store = SessionStore() + store.checkpoint_snapshot(source, [{"role": "user", "content": "old request"}], meta={}, sequence=2) + store.checkpoint_snapshot(target, [{"role": "user", "content": "new request"}], meta={}, sequence=9) + (tmp_path / "sample.txt").write_text("17") + env = LocalEnvironment(str(tmp_path)) if borrow_env else None + llm = LLMClient(model="offline", provider="openai", api_key=__name__) if borrow_llm else None + agent = Agent(name="reader", system_prompt="Read the sample.", model="offline", + provider="openai", api_key=__name__) + original_cleanup = LocalEnvironment.cleanup + original_close = LLMClient.close + cleaned, closed = [], [] + + async def cleanup(environment): + await original_cleanup(environment) + cleaned.append(environment) + + async def close(client): + release = store.try_autosave_lock(target) + assert release is not None + release() + await original_close(client) + closed.append(client) + if close_fails: + raise OSError("model close failed") + + monkeypatch.setattr(LocalEnvironment, "cleanup", cleanup) + monkeypatch.setattr(LLMClient, "close", close) + try: + with pytest.raises(SnapshotSequenceConflict, match="refusing stale checkpoint sequence") as caught: + load_session(source, agent, env=env, llm=llm, store=store, auto_save_path=target) + assert len(cleaned) == int(not borrow_env) + assert len(closed) == int(not borrow_llm) + assert store.load_snapshot(target, agent.system_prompt)["messages"][-1]["content"] == "new request" + if env is not None: + assert await env.read_file("sample.txt") == "17" + if close_fails: + assert any("model close failed" in note for note in caught.value.__notes__) + finally: + if env is not None: + await original_cleanup(env) + if llm is not None: + await original_close(llm) + + +@pytest.mark.parametrize("entry", ["load_session", "restore"]) +@pytest.mark.parametrize("failure_stage", ["base", "journal"]) +async def test_restore_only_requires_the_new_checkpoint_to_be_durable( + tmp_path, local_environment_factory, monkeypatch, entry, failure_stage, +): + exported, target = tmp_path / "backup.json", tmp_path / "target.json" + journal = tmp_path / "target.json.journal" + agent = Agent(name="reviewer", system_prompt="Remember the requests.") + store = SessionStore() + options = {"agent": agent, "env": local_environment_factory(str(tmp_path)), "store": store} + async with AsyncExitStack() as sessions: + original = build_session(**options, llm=model(), auto_save_path=str(tmp_path / "source.json")) + sessions.push_async_callback(original.aclose) + await converse(original, 1) + original.save(str(exported)) + + store.checkpoint_snapshot(str(target), [{"role": "user", "content": "Earlier note."}], meta={}, sequence=1) + store.append_snapshot_delta( + str(target), sequence=2, replace_from=1, + messages=[{"role": "assistant", "content": "Earlier answer."}], meta={}, + ) + before = target.read_bytes(), journal.read_bytes() + continuation = model() + existing = None + if entry == "restore": + existing = build_session(**options, llm=continuation, auto_save_path=str(target)) + sessions.push_async_callback(existing.aclose) + existing.restore(str(target)) + fault = OSError(errno.EIO, "checkpoint persistence failed") + failed = False + save_base = storage.SessionStore._atomic_json_write + save_bytes = storage.write_regular_bytes_atomic + + def save_snapshot(path, value, **kwargs): + if failure_stage == "base" and path == str(target): + raise fault + return save_base(path, value, **kwargs) + + def reset_journal(path, payload, **kwargs): + nonlocal failed + if failure_stage == "journal" and path == str(journal) and payload == b"" and not failed: + failed = True + assert json.loads(target.read_text())["messages"][-1]["content"] == "Completed request 0." + raise fault + return save_bytes(path, payload, **kwargs) + + monkeypatch.setattr(storage.SessionStore, "_atomic_json_write", staticmethod(save_snapshot)) + monkeypatch.setattr(storage, "write_regular_bytes_atomic", reset_journal) + + def resume(): + if existing is not None: + existing.restore(str(exported)) + return existing + session = load_session(str(exported), **options, llm=continuation, auto_save_path=str(target)) + sessions.push_async_callback(session.aclose) + return session + + if failure_stage == "base": + with pytest.raises(OSError) as caught: + resume() + assert caught.value is fault + assert (target.read_bytes(), journal.read_bytes()) == before + if existing is not None: + assert existing.messages[-1]["content"] == "Earlier answer." + return + + resumed = resume() + assert failed and journal.read_bytes() == before[1] + assert resumed.messages == original.messages + await resumed.add_user_message("Remember the new deadline.") + await resumed.run_loop() + persisted = store.load_snapshot(str(target), agent.system_prompt) + assert transcript(persisted) == resumed.messages + assert persisted["session_state"]["used_tokens"] == 14 + + +@pytest.mark.parametrize("fits", [True, False]) +async def test_manual_export_uses_compact_snapshot_at_capacity(tmp_path, local_environment_factory, monkeypatch, fits): + agent = Agent(name="reviewer", system_prompt="Keep the review digest.") + env = local_environment_factory(str(tmp_path)) + destination = tmp_path / "backup.json" + async with AsyncExitStack() as sessions: + original = build_session(agent=agent, env=env, llm=model()) + sessions.push_async_callback(original.aclose) + original.messages = [{"role": "system", "content": agent.system_prompt}] + [ + {"role": role, "content": f"Verified inventory entry {number}."} + for number in range(40) for role in ("user", "assistant") + ] + await converse(original, 1) + measured = tmp_path / "complete.json" + original.save(str(measured)) + snapshot = OpenCollab.read_session_snapshot(measured) + compact_size = len(json.dumps(snapshot, ensure_ascii=False, separators=(",", ":")).encode("utf-8")) + assert measured.stat().st_size > compact_size + SessionStore().save(str(destination), [{"role": "system", "content": "Previous digest."}]) + previous = destination.read_bytes() + limit = compact_size if fits else compact_size - 1 + monkeypatch.setattr(storage, "MAX_SESSION_SNAPSHOT_BYTES", limit) + + if not fits: + with pytest.raises(SnapshotCapacityError): + original.save(str(destination)) + assert destination.read_bytes() == previous + return + + original.save(str(destination)) + assert destination.stat().st_size <= limit + assert OpenCollab.read_session_snapshot(destination) == snapshot + resumed = load_session( + str(destination), agent=agent, env=env, + llm=FakeLLM([llm_response(content="Digest resumed.")]), + ) + sessions.push_async_callback(resumed.aclose) + assert resumed.messages == original.messages + await resumed.add_user_message("Review this digest.") + assert await resumed.run_loop() == "Digest resumed." + + +@pytest.mark.parametrize("failure_stage", ["base", "journal"]) +async def test_manual_export_reports_durable_replacement( + tmp_path, local_environment_factory, monkeypatch, failure_stage, +): + target = tmp_path / "target.json" + journal = target.with_suffix(".json.journal") + store = SessionStore() + store.checkpoint_snapshot(str(target), [{"role": "system", "content": "Earlier note."}], meta={}, sequence=1) + store.append_snapshot_delta( + str(target), sequence=2, replace_from=1, + messages=[{"role": "assistant", "content": "Earlier answer."}], meta={}, + ) + before = target.read_bytes(), journal.read_bytes() + failure = OSError(errno.EIO, "replacement failed") + write_base = storage.SessionStore._atomic_json_write + write_journal = storage.write_regular_bytes_atomic + cleanup_attempted = False + + def publish(path, snapshot, **kwargs): + if failure_stage == "base" and path == str(target): + raise failure + return write_base(path, snapshot, **kwargs) + + def reset_journal(path, payload, **kwargs): + nonlocal cleanup_attempted + if path == str(journal) and payload == b"": + cleanup_attempted = True + raise failure + return write_journal(path, payload, **kwargs) + + monkeypatch.setattr(storage.SessionStore, "_atomic_json_write", staticmethod(publish)) + monkeypatch.setattr(storage, "write_regular_bytes_atomic", reset_journal) + agent = Agent(name="reviewer", system_prompt="Remember the requests.") + async with AsyncExitStack() as sessions: + original = build_session(agent=agent, env=local_environment_factory(str(tmp_path)), llm=model()) + sessions.push_async_callback(original.aclose) + await converse(original, 1) + + if failure_stage == "base": + with pytest.raises(OSError) as caught: + original.save(str(target)) + assert caught.value is failure + assert (target.read_bytes(), journal.read_bytes()) == before + assert not cleanup_attempted + return + + original.save(str(target)) + assert cleanup_attempted + assert journal.read_bytes() == before[1] + snapshot = OpenCollab.read_session_snapshot(target) + assert transcript(snapshot) == original.messages + assert snapshot["_autosave_sequence"] == 3 + + @pytest.mark.parametrize("turns", [1, 4]) @pytest.mark.parametrize("entry", ["restore", "load_session"]) @pytest.mark.parametrize("save_twice", [False, True]) @@ -84,6 +318,401 @@ async def test_manual_export_resumes_original_autosave_and_continues( await restored.aclose() await restored.env.cleanup() +async def test_export_preserves_source_cursor_when_overwriting_an_old_autosave(tmp_path): + automatic = str(tmp_path / "automatic.json") + exported = str(tmp_path / "exported.json") + agent = Agent(name="reviewer", system_prompt="Remember each request.") + store = SessionStore() + older_messages = [{"role": "user", "content": "Earlier unrelated draft."}] + store.checkpoint_snapshot(exported, older_messages, meta={}, sequence=1) + store.append_snapshot_delta( + exported, sequence=2, replace_from=1, messages=[{"role": "assistant", "content": "Draft saved."}], + meta={}, + ) + + original = build_session(agent=agent, llm=model(4), auto_save_path=automatic, store=store) + try: + await converse(original, 4) + source = store.load_snapshot(automatic, agent.system_prompt) + assert source["_autosave_sequence"] > 3 + original.save(exported) + assert store.load_snapshot(exported, agent.system_prompt) == { + **source, "_autosave_export_source_sequence": source["_autosave_sequence"], + } + finally: + await original.aclose() + await original.env.cleanup() + + restored = load_session(exported, agent=agent, llm=model(), auto_save_path=automatic, store=store) + try: + assert restored.messages == transcript(source) + await restored.add_user_message("Continue using the remembered requirements.") + await restored.run_loop() + resumed = store.load_snapshot(automatic, agent.system_prompt) + assert resumed["_autosave_sequence"] > source["_autosave_sequence"] + assert transcript(resumed) == restored.messages + assert restored.persistence_errors == () + finally: + await restored.aclose() + await restored.env.cleanup() + + +@pytest.mark.parametrize("copy_mode", ["fresh", "reopened", "legacy", "read-answer"]) +@pytest.mark.parametrize("source_advances", [False, True]) +async def test_writable_restore_copy_reexports_the_original_source_order( + tmp_path, local_environment_factory, copy_mode, source_advances, +): + original_path, first_export, copy_path, backup_path = ( + str(tmp_path / f"{name}.json") for name in ("original", "first", "copy", "backup") + ) + agent = Agent(name="reviewer", system_prompt="Remember the requests.") + store = SessionStore() + options = {"agent": agent, "env": local_environment_factory(str(tmp_path)), "store": store} + + def inspect(path): + return store.load_snapshot(path, agent.system_prompt) + + async with AsyncExitStack() as sessions: + original = build_session(**options, llm=model(), auto_save_path=original_path) + sessions.push_async_callback(original.aclose) + await converse(original, 1) + original.save(first_export) + source = inspect(first_export) + + copied = load_session(first_export, **options, llm=model(), auto_save_path=copy_path) + sessions.push_async_callback(copied.aclose) + if copy_mode == "legacy": + legacy = inspect(copy_path) + del legacy["_autosave_export_source_sequence"] + (tmp_path / "copy.json").write_text(json.dumps(legacy), encoding="utf-8") + copied = load_session(first_export, **options, llm=model(), auto_save_path=copy_path) + sessions.push_async_callback(copied.aclose) + elif copy_mode == "reopened": + copied = load_session(copy_path, **options, llm=model(), auto_save_path=copy_path) + sessions.push_async_callback(copied.aclose) + elif copy_mode == "read-answer": + assert await copied.run_loop() == "Completed request 0." + copied = load_session(copy_path, **options, llm=model(), auto_save_path=copy_path) + sessions.push_async_callback(copied.aclose) + copied.save(backup_path) + assert inspect(backup_path)["_autosave_sequence"] == source["_autosave_sequence"] + + if source_advances: + await original.add_user_message("Remember the new requirement.") + while original.pending_cleanup_tasks: + await asyncio.gather(*original.pending_cleanup_tasks) + newer = inspect(original_path) + assert newer["_autosave_sequence"] == source["_autosave_sequence"] + 1 + assert newer["messages"][-1]["content"] == "Remember the new requirement." + with pytest.raises(SnapshotSequenceConflict): + load_session(backup_path, **options, llm=model(), auto_save_path=original_path) + assert inspect(original_path) == newer + else: + restored = load_session(backup_path, **options, llm=model(), auto_save_path=original_path) + sessions.push_async_callback(restored.aclose) + assert restored.messages == transcript(source) + assert restored.used_tokens == 7 + + +@pytest.mark.parametrize("already_queued", [False, True]) +async def test_writable_restore_copy_can_publish_new_work(tmp_path, local_environment_factory, already_queued): + original_path, first_export, copy_path, backup_path = ( + str(tmp_path / f"{name}.json") for name in ("original", "first", "copy", "backup") + ) + agent = Agent(name="reviewer", system_prompt="Remember the requests.") + store = SessionStore() + options = {"agent": agent, "env": local_environment_factory(str(tmp_path)), "store": store} + async with AsyncExitStack() as sessions: + original = build_session(**options, llm=model(), auto_save_path=original_path) + sessions.push_async_callback(original.aclose) + await converse(original, 1) + request = "Remember the new requirement." + if already_queued: + await original.add_user_message(request) + original.save(first_export) + while original.pending_cleanup_tasks: + await asyncio.gather(*original.pending_cleanup_tasks) + + reply = "New requirement recorded." + continuation = FakeLLM([llm_response(content=reply, total_tokens=7, input_tokens=5)]) + copied = load_session(first_export, **options, llm=continuation, auto_save_path=copy_path) + sessions.push_async_callback(copied.aclose) + if not already_queued: + await copied.add_user_message(request) + assert await copied.run_loop() == reply + assert len(continuation.calls) == 1 + copied.save(backup_path) + + readback = model() + restored = load_session(backup_path, **options, llm=readback, auto_save_path=original_path) + sessions.push_async_callback(restored.aclose) + assert restored.messages == copied.messages + assert restored.used_tokens == 14 + assert await restored.run_loop() == reply + assert readback.calls == [] + +@pytest.mark.parametrize( + ("exports", "original_turns", "offline_turns"), + [(6, 2, 1), (1, 1, 4), (6, 0, 3)], +) +async def test_continued_backup_preserves_newer_divergent_autosave( + tmp_path, local_environment_factory, exports, original_turns, offline_turns, +): + original_path, backup_path, export_path = ( + str(tmp_path / name) for name in ("original.json", "backup.json", "continued.json") + ) + agent = Agent(name="reviewer", system_prompt="Remember each requirement.") + store = SessionStore() + options = {"agent": agent, "store": store, "env": local_environment_factory(str(tmp_path))} + + async def run_turns(session, branch, turns): + for index in range(turns): + await session.add_user_message(f"{branch} requirement {index}.") + await session.run_loop() + + def source_bytes(): + return [ + (tmp_path / name).read_bytes() for name in ("original.json", "original.json.journal") + ] + + async with AsyncExitStack() as sessions: + original = build_session(**options, llm=model(1 + original_turns), auto_save_path=original_path) + sessions.push_async_callback(original.aclose) + await run_turns(original, "Shared", 1) + for _ in range(exports): + original.save(backup_path) + await run_turns(original, "Original", original_turns) + await original.aclose() + before = source_bytes() + state = store.load_snapshot(original_path, agent.system_prompt) + + offline = load_session(backup_path, **options, llm=model(offline_turns), auto_save_path=backup_path) + sessions.push_async_callback(offline.aclose) + await run_turns(offline, "Offline", offline_turns) + await offline.aclose() + # Reopening the working copy must retain the originating sequence. + reopened = load_session(backup_path, **options, llm=model(), auto_save_path=backup_path) + sessions.push_async_callback(reopened.aclose) + reopened.save(export_path) + + if original_turns: + with pytest.raises(SnapshotSequenceConflict): + load_session(export_path, **options, llm=model(), auto_save_path=original_path) + assert source_bytes() == before + assert store.load_snapshot(original_path, agent.system_prompt) == state + return + + restored = load_session(export_path, **options, llm=model(), auto_save_path=original_path) + sessions.push_async_callback(restored.aclose) + assert source_bytes() != before + assert restored.messages == offline.messages + assert restored.used_tokens == (1 + offline_turns) * 7 + requests = [m["content"].splitlines()[0] for m in restored.messages if m["role"] == "user"] + assert requests == ["Shared requirement 0."] + [f"Offline requirement {i}." for i in range(offline_turns)] + await restored.aclose() + + # The originating cursor stays fixed, so a subsequent restore uses the + # earlier transcript to recognize a continuation. + await run_turns(reopened, "Follow-up", 1) + reopened.save(export_path) + later = load_session(export_path, **options, llm=model(), auto_save_path=original_path) + sessions.push_async_callback(later.aclose) + assert later.messages == reopened.messages + assert later.used_tokens == (2 + offline_turns) * 7 + +@pytest.mark.parametrize("pending", ["inbox", "deferred-user", "settled-child"]) +async def test_continued_backup_preserves_pending_autosave_state( + tmp_path, local_environment_factory, pending, +): + source, exported, working, backup = ( + str(tmp_path / f"{name}.json") for name in ("source", "exported", "working", "backup") + ) + agent = Agent(name="reviewer", system_prompt="Retain each accepted requirement.") + store = SessionStore() + options = {"agent": agent, "env": local_environment_factory(str(tmp_path)), "store": store} + source_paths = (tmp_path / "source.json", tmp_path / "source.json.journal") + + async with AsyncExitStack() as sessions: + original = build_session(**options, auto_save_path=source, llm=model()) + sessions.push_async_callback(original.aclose) + await converse(original, 1) + if pending != "inbox": + original.state.append_message({ + "role": "assistant", "tool_calls": [tool_call("check", "read_receipt", "{}")], + }) + original.state.set_phase(SessionPhase.AWAITING_EVENTS) + original.state.pending_events.add(PendingRow("check", RowKind.CHILD_AGENT, 0, ref=1)) + original.save(source) + original.save(exported) + if pending == "inbox": + original.state.queue_pending_user_message({ + "role": "user", "content": "Record the accepted correction.", "message_id": "inbox-correction", + }) + elif pending == "deferred-user": + original.state.append_queued_external_user_turn("Record the accepted correction.", defer=True) + else: + original.state.pending_events.fill("check", result="The signed record confirms the correction.") + original.save(source) + before = store.load_snapshot(source, agent.system_prompt) + source_bytes = [path.read_bytes() for path in source_paths] + await original.aclose() + + offline = load_session(exported, **options, auto_save_path=working, llm=model(2)) + sessions.push_async_callback(offline.aclose) + if pending != "inbox": + await offline.run_loop() + await offline.add_user_message("Review an independent proposal.") + await offline.run_loop() + offline.save(backup) + continued = store.load_snapshot(backup, agent.system_prompt) + assert continued["messages"][:len(before["messages"])] == before["messages"] + assert len(continued["messages"]) > len(before["messages"]) + assert continued["session_state"]["step_count"] > before["session_state"]["step_count"] + assert continued["session_state"]["used_tokens"] > before["session_state"]["used_tokens"] + + with pytest.raises(SnapshotSequenceConflict): + load_session(backup, **options, auto_save_path=source, llm=model()) + assert [path.read_bytes() for path in source_paths] == source_bytes + assert store.load_snapshot(source, agent.system_prompt) == before + + +@pytest.mark.parametrize("change", ["inbox", "stop"]) +async def test_equal_transcript_does_not_replace_newer_runtime_state( + tmp_path, local_environment_factory, change, +): + seed, exported, target = (str(tmp_path / f"{name}.json") for name in ("seed", "exported", "target")) + agent = Agent(name="reviewer", system_prompt="Retain each accepted requirement.") + store = SessionStore() + options = {"agent": agent, "env": local_environment_factory(str(tmp_path)), "store": store} + target_paths = (tmp_path / "target.json", tmp_path / "target.json.journal") + + async with AsyncExitStack() as sessions: + original = build_session(**options, auto_save_path=seed, llm=model()) + sessions.push_async_callback(original.aclose) + await converse(original, 1) + original.save(exported) + restored = load_session(exported, **options, auto_save_path=target, llm=model()) + sessions.push_async_callback(restored.aclose) + if change == "inbox": + restored.state.queue_pending_user_message({ + "role": "user", "content": "Record the accepted correction.", "message_id": "inbox-correction", + }) + else: + restored.state.cancel("interrupted by user") + restored.save(target) + before = store.load_snapshot(target, agent.system_prompt) + exported_state = store.load_snapshot(exported, agent.system_prompt) + assert before["messages"] == exported_state["messages"] + assert before["_autosave_export_source_sequence"] == exported_state["_autosave_sequence"] + target_bytes = [path.read_bytes() for path in target_paths] + + with pytest.raises(SnapshotSequenceConflict): + load_session(exported, **options, auto_save_path=target, llm=model()) + assert [path.read_bytes() for path in target_paths] == target_bytes + assert store.load_snapshot(target, agent.system_prompt) == before + + +@pytest.mark.parametrize( + "publication", ["before-prepare", "pending", "settled", "failed", "checkpointed", "overlapping"], +) +async def test_exported_working_copy_preserves_a_new_queued_turn( + tmp_path, local_environment_factory, monkeypatch, publication, +): + source, export, working, backup = ( + str(tmp_path / f"{name}.json") for name in ("source", "export", "working", "backup") + ) + store = SessionStore() + options = { + "agent": Agent(name="reviewer", system_prompt="Remember each request."), + "env": local_environment_factory(str(tmp_path)), + "store": store, + } + + async def settle(session): + while session.pending_cleanup_tasks: + await asyncio.gather(*session.pending_cleanup_tasks) + + async with AsyncExitStack() as sessions: + original = build_session(**options, llm=model(), auto_save_path=source) + sessions.push_async_callback(original.aclose) + await converse(original, 1) + original.save(export) + + copy_session = load_session(export, **options, llm=model(), auto_save_path=working) + sessions.push_async_callback(copy_session.aclose) + previous = OpenCollab.read_session_snapshot(working) + next_request = "Remember the new requirement." + + def fail_append(*args, **kwargs): + raise OSError(errno.EIO, "queued autosave failed") + + earlier_started, earlier_release = threading.Event(), threading.Event() + queued_started, queued_release = threading.Event(), threading.Event() + pauses = iter(((earlier_started, earlier_release), (queued_started, queued_release))) + append = store.append_snapshot_delta + + def pause_append(path, **kwargs): + signals = next(pauses, None) + if signals is not None: + started, release = signals + started.set() + assert release.wait(timeout=3) + return append(path, **kwargs) + + with monkeypatch.context() as patch: + try: + if publication == "failed": + patch.setattr(store, "append_snapshot_delta", fail_append) + elif publication in {"before-prepare", "overlapping"}: + patch.setattr(store, "append_snapshot_delta", pause_append) + copy_session.enqueue_auto_save() + assert await asyncio.to_thread(earlier_started.wait, 3) + await copy_session.add_user_message(next_request) + assert copy_session.pending_cleanup_tasks + if publication == "settled": + await settle(copy_session) + elif publication == "checkpointed": + copy_session.save(working) + elif publication == "overlapping": + earlier_release.set() + assert await asyncio.to_thread(queued_started.wait, 3) + copy_session.save(backup) + finally: + earlier_release.set() + queued_release.set() + await settle(copy_session) + + saved = OpenCollab.read_session_snapshot(backup) + automatic = OpenCollab.read_session_snapshot(working) + queued = saved["session_state"]["pending_external_user_turn"] + assert queued["content"] == next_request + if publication == "failed": + assert automatic == previous + assert str(copy_session.persistence_errors[0]).endswith("queued autosave failed") + else: + assert automatic["messages"] == saved["messages"] + assert automatic["session_state"] == saved["session_state"] + + continuation = FakeLLM([llm_response(content="New requirement recorded.", total_tokens=7, input_tokens=5)]) + resumed = load_session(backup, **options, llm=continuation, auto_save_path=working) + sessions.push_async_callback(resumed.aclose) + assert continuation.calls == [] + assert await resumed.run_loop() == "New requirement recorded." + assert await resumed.run_loop() == "New requirement recorded." + assert len(continuation.calls) == 1 + user_requests = [ + row["content"].splitlines()[0] for row in continuation.calls[0]["messages"] if row["role"] == "user" + ] + assert user_requests == ["Remember requirement 0.", next_request] + + finished = OpenCollab.read_session_snapshot(working) + assert finished["session_state"]["used_tokens"] == 14 + for outdated in (export, backup): + with pytest.raises(SnapshotSequenceConflict, match="refusing stale checkpoint"): + load_session(outdated, **options, llm=model(), auto_save_path=working) + assert OpenCollab.read_session_snapshot(working) == finished + + async def test_export_keeps_original_autosave_bytes_unchanged(tmp_path): automatic = tmp_path / "automatic.json" exported = tmp_path / "exported.json" @@ -104,6 +733,139 @@ async def test_export_keeps_original_autosave_bytes_unchanged(tmp_path): await original.aclose() await original.env.cleanup() +@pytest.mark.parametrize("copy_mode", ["direct", "read-only", "writable"]) +@pytest.mark.parametrize("source_advances", [False, True]) +async def test_reusing_export_path_does_not_promote_source_history( + tmp_path, local_environment_factory, copy_mode, source_advances, +): + source, backup, copy_path = (tmp_path / name for name in ("source.json", "backup.json", "copy.json")) + store = SessionStore() + store.checkpoint_snapshot( + str(backup), [{"role": "user", "content": "Previous task."}], meta={}, sequence=20, + ) + store.append_snapshot_delta( + str(backup), sequence=21, replace_from=1, + messages=[{"role": "assistant", "content": "Saved the previous task."}], meta={}, + ) + agent = Agent(name="reviewer", system_prompt="Remember the original requirements.") + options = {"agent": agent, "store": store, "env": local_environment_factory(str(tmp_path))} + original = build_session(**options, llm=model(3), auto_save_path=str(source)) + reader = restored = None + try: + await converse(original, 1) + first = store.load_snapshot(str(source), agent.system_prompt) + original.save(str(backup)) + exported = store.load_snapshot(str(backup), agent.system_prompt) + assert exported["_autosave_sequence"] > first["_autosave_sequence"] + if copy_mode != "direct": + reader = load_session( + str(backup), **options, llm=model(), + auto_save_path=str(backup) if copy_mode == "writable" else None, + ) + if copy_mode == "writable": + reader.save(str(backup)) + assert store.load_snapshot(str(backup), agent.system_prompt)["_autosave_sequence"] > ( + exported["_autosave_sequence"] + ) + reader.save(str(copy_path)) + backup = copy_path + if source_advances: + await converse(original, 2) + before = store.load_snapshot(str(source), agent.system_prompt) + files = [source, source.with_suffix(".json.journal")] + original_bytes = [path.read_bytes() for path in files] + with pytest.raises(SnapshotSequenceConflict, match="refusing stale checkpoint"): + load_session(str(backup), **options, llm=model(), auto_save_path=str(source)) + assert store.load_snapshot(str(source), agent.system_prompt) == before + assert [path.read_bytes() for path in files] == original_bytes + else: + restored = load_session(str(backup), **options, llm=model(), auto_save_path=str(source)) + resumed = store.load_snapshot(str(source), agent.system_prompt) + assert resumed["_autosave_sequence"] == first["_autosave_sequence"] + 1 + assert resumed["messages"] == first["messages"] + await converse(restored, 1) + assert store.load_snapshot(str(source), agent.system_prompt)["session_state"]["used_tokens"] == 14 + finally: + for session in (original, reader, restored): + if session is not None: + await session.aclose() + + +@pytest.mark.parametrize("target_update", ["unchanged", "checkpoint", "accounting", "concurrent"]) +async def test_reexport_restores_its_immediate_autosave_only_if_equivalent( + tmp_path, local_environment_factory, monkeypatch, target_update, +): + original_path, working_path, backup_path = ( + str(tmp_path / name) for name in ("original.json", "working.json", "backup.json") + ) + agent = Agent(name="reviewer", system_prompt="Remember the current draft.") + store = SessionStore() + options = {"agent": agent, "store": store, "env": local_environment_factory(str(tmp_path))} + + def inspect(path): + return store.load_snapshot(path, agent.system_prompt) + + async with AsyncExitStack() as sessions: + for path, message in ((original_path, "Current draft."), (working_path, "Earlier draft.")): + session = build_session(**options, llm=model(), auto_save_path=path) + sessions.push_async_callback(session.aclose) + await session.add_user_message(message) + await session.run_loop() + await session.aclose() + original = inspect(original_path) + exporter = load_session(original_path, **options, llm=model(), auto_save_path=original_path) + sessions.push_async_callback(exporter.aclose) + exporter.save(working_path) + working = load_session(working_path, **options, llm=model(), auto_save_path=working_path) + sessions.push_async_callback(working.aclose) + if target_update in {"checkpoint", "concurrent"}: + working.save(working_path) + working.save(backup_path) + + if target_update == "accounting": + working.used_tokens += 9 + working.save(working_path) + current = inspect(working_path) + if target_update == "concurrent": + checkpoint = store.checkpoint_snapshot + peer = SessionStore() + local_sequence = current["_autosave_sequence"] + + def publish_before_retry(path, messages, *, meta, sequence): + if sequence == local_sequence: + peer_meta = {**meta, "session_state": {**meta["session_state"], "used_tokens": 31}} + peer.checkpoint_snapshot(path, messages, meta=peer_meta, sequence=local_sequence + 1) + return checkpoint(path, messages, meta=meta, sequence=sequence) + + monkeypatch.setattr(store, "checkpoint_snapshot", publish_before_retry) + + continuation = model() + if target_update in {"accounting", "concurrent"}: + with pytest.raises(SnapshotSequenceConflict): + load_session(backup_path, **options, llm=continuation, auto_save_path=working_path) + expected = copy.deepcopy(current) + if target_update == "concurrent": + expected["_autosave_sequence"] += 1 + expected["session_state"]["used_tokens"] = 31 + assert inspect(working_path) == expected + assert continuation.calls == [] + return + + restored = load_session(backup_path, **options, llm=continuation, auto_save_path=working_path) + sessions.push_async_callback(restored.aclose) + assert inspect(working_path) == current + assert restored.messages == transcript(original) + assert restored.used_tokens == 7 + restored.save(backup_path) + restored_original = load_session(backup_path, **options, llm=model(), auto_save_path=original_path) + sessions.push_async_callback(restored_original.aclose) + assert inspect(original_path)["_autosave_sequence"] == original["_autosave_sequence"] + 1 + await restored.add_user_message("Continue the review.") + await restored.run_loop() + assert continuation.calls[0]["messages"][:len(original["messages"])] == transcript(original) + assert inspect(working_path)["session_state"]["used_tokens"] == 14 + + async def test_older_export_still_cannot_replace_a_newer_autosave(tmp_path): automatic = tmp_path / "automatic.json" exported = tmp_path / "older.json" diff --git a/tests/runtime/test_late_provider_session_export.py b/tests/runtime/test_late_provider_session_export.py new file mode 100644 index 00000000..96acbc02 --- /dev/null +++ b/tests/runtime/test_late_provider_session_export.py @@ -0,0 +1,160 @@ +"""Terminal session exports require settled native usage after cancellation.""" + +from __future__ import annotations + +import asyncio +import json + +import pytest + +from opencollab import OpenCollab +from opencollab.application.session import SessionBusyError +from opencollab.bootstrap import build_session, load_session +from opencollab.bootstrap.agent_profiles import resolve_agent_profile +from opencollab.domain.agent import Agent +from opencollab.environments import local_environment +from tests.support.provider_sdk_http import completion_http_response, http_response, install_sdk_transport +from tests.support.responses_provider_test_support import function_item + + +def _tool_response(request, provider, call_id, output_tokens): + body = json.loads(request.content) + arguments = {"path": "notes.txt"} + usage = {"input_tokens": 2, "output_tokens": output_tokens} + if provider == "anthropic": + return http_response(request, 200, json={ + "id": f"msg_{call_id}", "type": "message", "role": "assistant", "model": body["model"], + "content": [{"type": "tool_use", "id": call_id, "name": "file_read", "input": arguments}], + "stop_reason": "tool_use", "stop_sequence": None, "usage": usage, + }) + + item = function_item(call_id, "file_read", json.dumps(arguments)) + response = { + "id": f"resp_{call_id}", "object": "response", "status": "completed", "model": body["model"], + "output": [item], "error": None, "incomplete_details": None, + "usage": {**usage, "total_tokens": 2 + output_tokens}, + } + events = [ + {"type": "response.output_item.done", "output_index": 0, "item": item}, + {"type": "response.completed", "response": response}, + ] + stream = "".join(f"event: {event['type']}\ndata: {json.dumps(event)}\n\n" for event in events) + return http_response(request, 200, headers={"content-type": "text/event-stream"}, text=stream) + + +def _tool_results(request_body, provider): + if provider == "anthropic": + return { + item["tool_use_id"]: item["content"] + for message in request_body["messages"] if isinstance(message["content"], list) + for item in message["content"] if item["type"] == "tool_result" + } + return { + item["call_id"]: item["output"] + for item in request_body["input"] if item.get("type") == "function_call_output" + } + + +async def _drain(session): + while tasks := session.pending_cleanup_tasks: + await asyncio.gather(*tasks, return_exceptions=True) + + +@pytest.mark.parametrize("provider", ["openai", "anthropic"]) +@pytest.mark.parametrize("llm_timeout", [None, 600]) +async def test_terminal_export_requires_settled_native_usage(tmp_path, monkeypatch, provider, llm_timeout): + usage_log = tmp_path / "usage.jsonl" + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(usage_log)) + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + (tmp_path / "notes.txt").write_text("The event is on April 18.\n", encoding="utf-8") + automatic, exported = tmp_path / "automatic.json", tmp_path / "exported.json" + admitted, release = asyncio.Event(), asyncio.Event() + requests = [] + environment = local_environment(tmp_path) + options = { + "env": environment, + "auto_save_path": str(automatic), + "max_budget_tokens": 60_000, + "llm_timeout": llm_timeout, + } + profile = resolve_agent_profile("base") + + def agent(): + return Agent( + name="reader", system_prompt="Read and remember the date.", tools=list(profile.resolve_tools("read")), + model="gpt-4o" if provider == "openai" else "claude-sonnet-4-6", + provider=provider, wire_protocol="responses" if provider == "openai" else "chat_completions", + api_key=tmp_path.name, base_url="https://provider.invalid/v1", + llm_max_retries=0, + ) + + async def peer(request): + requests.append(json.loads(request.content)) + match len(requests): + case 1: + return _tool_response(request, provider, "call_first", 9) + case 2: + return completion_http_response(request, output_tokens=11, text="Recorded April 18.") + case 3: + return _tool_response(request, provider, "call_second", 15) + case 4: + admitted.set() + while not release.is_set(): + try: + await release.wait() + except asyncio.CancelledError: + continue + return completion_http_response(request, output_tokens=21, text="Late unused answer.") + case 5: + return completion_http_response(request, output_tokens=27, text="I still remember April 18.") + case _: + pytest.fail("unexpected extra provider request") + + install_sdk_transport(monkeypatch, provider, peer) + original = build_session(agent=agent(), agent_profile=profile, **options) + turn = resumed = None + try: + await original.add_user_message("Read notes.txt and remember the date.") + assert await original.run_loop() == "Recorded April 18." + await original.add_user_message("Read the file again to verify the date.") + turn = asyncio.create_task(original.run_loop()) + await asyncio.wait_for(admitted.wait(), 2) + turn.cancel() + done, _ = await asyncio.wait({turn}, timeout=2) + assert turn in done + with pytest.raises(asyncio.CancelledError): + await turn + + stopped = OpenCollab.read_session_snapshot(automatic) + assert stopped["session_state"]["phase"] == "stopped" + assert stopped["session_state"]["used_tokens"] == 41 + with pytest.raises(SessionBusyError, match="provider requests are still draining"): + original.save(str(exported)) + assert not exported.exists() + + release.set() + await asyncio.wait_for(_drain(original), 2) + original.save(str(exported)) + await original.aclose() + resumed = load_session(str(exported), agent=agent(), agent_profile=profile, **options) + assert resumed.used_tokens == 64 + await resumed.add_user_message("Tell me the date you remember.") + assert await resumed.run_loop() == "I still remember April 18." + assert len(requests) == 5 + results = _tool_results(requests[-1], provider) + assert set(results) == {"call_first", "call_second"} + assert all("April 18" in json.dumps(value) for value in results.values()) + assert "Late unused answer." not in json.dumps(requests[-1]) + assert OpenCollab.read_session_snapshot(automatic)["session_state"]["used_tokens"] == 93 + usage = [json.loads(line)["usage"]["total_tokens"] for line in usage_log.read_text().splitlines()] + assert usage == [11, 13, 17, 23, 29] + finally: + release.set() + if turn is not None: + await asyncio.gather(turn, return_exceptions=True) + await _drain(original) + await original.aclose() + if resumed is not None: + await resumed.aclose() + await environment.cleanup() diff --git a/tests/runtime/test_llm_retry.py b/tests/runtime/test_llm_retry.py index 1a00a05e..bd3973b8 100644 --- a/tests/runtime/test_llm_retry.py +++ b/tests/runtime/test_llm_retry.py @@ -10,6 +10,7 @@ from openai import APIError, OpenAIError from opencollab.adapters.llm import retry +from opencollab.adapters.llm.responses_errors import ResponsesTerminalEventError from opencollab.adapters.llm.retry import is_retryable_error, with_retry @@ -67,8 +68,9 @@ def test_statusless_provider_base_error_is_retryable(error_class): @pytest.mark.parametrize("status", [400, 401, 404]) @pytest.mark.parametrize("status_location", ["direct", "response", "wrapper", "cause"]) -def test_gateway_wording_keeps_explicit_client_errors_non_retryable(status, status_location): - error = _sdk_error("Concurrency limit exceeded for user, please retry later") +@pytest.mark.parametrize("message", ["Concurrency limit exceeded", "Session expired after idle timeout"]) +def test_gateway_wording_keeps_explicit_client_errors_non_retryable(status, status_location, message): + error = _sdk_error(message) if status_location == "direct": error.status_code = status elif status_location == "response": @@ -85,6 +87,11 @@ def test_gateway_wording_keeps_explicit_client_errors_non_retryable(status, stat assert is_retryable_error(error) is False +def test_responses_terminal_error_keeps_explicit_failure(): + error = ResponsesTerminalEventError("Authentication timed out", code="invalid_api_key") + + assert is_retryable_error(error) is False + @pytest.mark.parametrize("status", [429, 503, 529]) def test_gateway_refusal_keeps_retryable_statuses(status): error = _sdk_error("Concurrency limit exceeded for user") diff --git a/tests/runtime/test_native_chat_terminal_close.py b/tests/runtime/test_native_chat_terminal_close.py new file mode 100644 index 00000000..0ad07fd9 --- /dev/null +++ b/tests/runtime/test_native_chat_terminal_close.py @@ -0,0 +1,132 @@ +from __future__ import annotations + +import asyncio +import json + +import pytest + +from opencollab import OpenCollab +from opencollab.adapters.llm import retry +from tests.support.provider_sdk_http import install_sdk_transport, provider_http + + +@pytest.mark.parametrize("scene", [ + "healthy", "close-reset", "paid-read-reset", "read-and-close-reset", "no-finish", "no-usage", "cancel-close", + "cancel-close-again", "close-idle", "read-and-close-idle", "no-usage-close-idle", +]) +async def test_native_chat_close_error_is_distinct_from_an_unfinished_read(tmp_path, monkeypatch, scene): + usage_path = tmp_path / "usage.jsonl" + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(usage_path)) + monkeypatch.setattr(retry, "extract_retry_after_seconds", lambda _error: 0.0) + monkeypatch.setattr(retry, "RETRY_JITTER_MAX_SECONDS", 0.0) + close_started = asyncio.Event() + close_cancelled = asyncio.Event() + close_release = asyncio.Event() + close_finished = asyncio.Event() + caller_cancels = scene in {"cancel-close", "cancel-close-again"} + requests, closes, observed_usage, cancellations = [], [], [], [] + http = provider_http("openai") + + def chunk(**data): + common = {"id": "reply", "object": "chat.completion.chunk", "model": "gpt-4o", "created": 1} + return f"data: {json.dumps({**common, **data})}\n\n".encode() + + class Reply(http.AsyncByteStream): + def __init__(self, attempt): + self.attempt = attempt + self.mode = scene if attempt == 1 else "healthy" + + async def __aiter__(self): + answer = "First answer" if self.attempt == 1 else "Retried answer" + read_fails = self.mode in {"read-and-close-reset", "read-and-close-idle"} + finish_reason = None if read_fails or self.mode == "no-finish" else "stop" + yield chunk(choices=[{"index": 0, "delta": {"content": answer}, "finish_reason": finish_reason}]) + if read_fails: + raise http.ReadError("read reset") + if self.mode not in {"no-usage", "no-usage-close-idle"}: + yield chunk(choices=[], usage={"prompt_tokens": 24, "completion_tokens": 7, "total_tokens": 31}) + if self.mode == "paid-read-reset": + raise http.ReadError("read reset after usage") + yield b"data: [DONE]\n\n" + + async def aclose(self): + closes.append(self.attempt) + if self.mode in {"cancel-close", "cancel-close-again", "close-idle", "read-and-close-idle", + "no-usage-close-idle"}: + close_started.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + close_cancelled.set() + if self.mode == "cancel-close-again": + await close_release.wait() + close_finished.set() + raise + if self.mode in {"close-reset", "read-and-close-reset", "no-finish", "no-usage"}: + raise http.ReadError("close reset") + + def respond(request): + body = json.loads(request.content) + assert body["stream_options"] == {"include_usage": True} + requests.append(request.url.path) + return http.Response(200, headers={"content-type": "text/event-stream"}, stream=Reply(len(requests))) + + install_sdk_transport(monkeypatch, "openai", respond) + app = OpenCollab( + tmp_path, provider="openai", model="gpt-4o", api_key=tmp_path.name, base_url="https://fixture.invalid/v1", + config={"wire_protocol": "chat_completions", "llm_stream_chat": True, + "llm_stream_idle_timeout": 3 if caller_cancels else 0.15, + "llm_max_retries": int(scene in {"close-reset", "close-idle", "paid-read-reset"})}, + ) + async with app.create_model_client() as client: + messages = [{"role": "user", "content": "Report the result."}] + + async def complete(): + try: + return await client.complete(messages, on_usage=lambda usage: observed_usage.append(usage.total_tokens)) + except asyncio.CancelledError as exc: + cancellations.append(exc.args) + raise + + if caller_cancels: + task = asyncio.create_task(complete()) + try: + await asyncio.wait_for(close_started.wait(), timeout=2) + task.cancel("withdraw reply") + await asyncio.wait_for(close_cancelled.wait(), timeout=1) + if scene == "cancel-close-again": + assert task.cancel("withdraw again") + await asyncio.sleep(0) + close_release.set() + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(task, timeout=2) + finally: + close_release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + assert close_cancelled.is_set() + assert close_finished.is_set() + assert cancellations == [("withdraw reply",)] + elif scene in {"read-and-close-reset", "read-and-close-idle", "no-finish", "no-usage"}: + message = "read reset" if scene.startswith("read-and-close") else "close reset" + with pytest.raises(http.ReadError, match=f"^{message}$"): + await complete() + elif scene == "no-usage-close-idle": + with pytest.raises(asyncio.TimeoutError): + await complete() + else: + response = await complete() + assert response.content == ("Retried answer" if scene == "paid-read-reset" else "First answer") + + zero_usage = {"read-and-close-reset", "read-and-close-idle", "no-usage", "no-usage-close-idle"} + expected_usage = 0 if scene in zero_usage else 62 if scene == "paid-read-reset" else 31 + assert observed_usage == ([expected_usage] if expected_usage else []) + assert closes == ([1, 2] if scene == "paid-read-reset" else [1]) + cancelled_closes = {"cancel-close", "cancel-close-again", "close-idle", "read-and-close-idle", + "no-usage-close-idle"} + assert close_cancelled.is_set() is (scene in cancelled_closes) + ledger, = map(json.loads, usage_path.read_text().splitlines()) + assert ledger["usage"]["total_tokens"] == expected_usage + successes = {"healthy", "close-reset", "close-idle", "paid-read-reset"} + assert ledger["status"] == ("success" if scene in successes else "error") diff --git a/tests/runtime/test_provider_retry_after_http.py b/tests/runtime/test_provider_retry_after_http.py new file mode 100644 index 00000000..f5a46401 --- /dev/null +++ b/tests/runtime/test_provider_retry_after_http.py @@ -0,0 +1,117 @@ +"""Retry timing from provider headers through the real SDK transport.""" + +from __future__ import annotations + +import json +from types import SimpleNamespace + +import anthropic +import openai +import pytest + +from opencollab.adapters.llm import retry +from opencollab.adapters.llm.client import LLMClient +from tests.support.provider_sdk_http import completion_http_response, http_response, install_sdk_transport + + +@pytest.mark.parametrize("protocol", ["chat", "responses", "anthropic"]) +@pytest.mark.parametrize("headers", [ + {"Retry-After": "0.125"}, + {"Retry-After-Ms": "125"}, + {"Retry-After-Ms": "125", "Retry-After": "3"}, + {"Retry-After-Ms": "NaN", "Retry-After": "0.125"}, +], ids=["seconds", "milliseconds", "milliseconds-preferred", "invalid-milliseconds-uses-seconds"]) +async def test_provider_retry_delay_fits_budget(monkeypatch, tmp_path, protocol, headers): + log_path = tmp_path / "usage.jsonl" + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(log_path)) + monkeypatch.delenv("OPENCOLLAB_EXTERNAL_PROVIDER_ISOLATION", raising=False) + monkeypatch.delenv("OPENCOLLAB_REQUIRE_INSTRUCTIONS_ECHO", raising=False) + requests, delays = [], [] + + def handle(request): + requests.append(request.url.path) + if len(requests) == 1: + return http_response(request, 429, headers=headers, json={ + "type": "error", + "error": {"type": "rate_limit_error", "message": "Request rate limited"}, + }) + return completion_http_response(request, output_tokens=7) + + async def record_delay(seconds): + delays.append(seconds) + + monkeypatch.setattr(retry, "asyncio", SimpleNamespace(sleep=record_delay)) + monkeypatch.setattr(retry, "time", SimpleNamespace(monotonic=lambda: 0.0)) + monkeypatch.setattr(retry, "RETRY_JITTER_MAX_SECONDS", 0) + provider = "anthropic" if protocol == "anthropic" else "openai" + install_sdk_transport(monkeypatch, provider, handle) + async with LLMClient( + provider=provider, model="claude-sonnet-4-6" if provider == "anthropic" else "gpt-4o", + wire_protocol="responses" if protocol == "responses" else "chat_completions", + api_key="controlled-test", base_url="https://controlled.invalid/v1", # pragma: allowlist secret + max_retries=1, provider_error_time_budget=0.75, + ) as client: + response = await client.complete([{"role": "user", "content": "Reply ok."}]) + + assert len(requests) == 2 + assert delays == [0.125] + assert response.content == "ok" + assert response.usage.total_tokens == 9 + record, = map(json.loads, log_path.read_text().splitlines()) + assert record["status"] == "success" + assert record["transport_timing"]["attempts"] == 2 + assert record["usage"]["total_tokens"] == 9 + + +@pytest.mark.parametrize("protocol", ["chat", "responses", "anthropic"]) +@pytest.mark.parametrize(("status", "error_text", "retryable"), [ + (524, "A Timeout Occurred", True), + (520, "Upstream temporarily unavailable", True), + (521, "Origin temporarily unavailable", True), + (521, "Origin rejected the configured connection", False), + (522, "Connection timed out", True), + (523, "Origin unreachable. Check the routing configuration.", False), + (501, "The timeout option is not implemented for this endpoint", False), + (400, "Invalid timeout parameter", False), +]) +async def test_gateway_status_and_error_text_control_retry( + monkeypatch, tmp_path, protocol, status, error_text, retryable, +): + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(tmp_path / "usage.jsonl")) + monkeypatch.delenv("OPENCOLLAB_EXTERNAL_PROVIDER_ISOLATION", raising=False) + requests, delays = [], [] + + def handle(request): + requests.append(request) + if len(requests) == 1: + return http_response( + request, status, headers={"Content-Type": "text/html", "Retry-After": "0.125"}, + text=f"{status} {error_text}", + ) + return completion_http_response(request) + + async def record_delay(seconds): + delays.append(seconds) + + monkeypatch.setattr(retry, "asyncio", SimpleNamespace(sleep=record_delay)) + monkeypatch.setattr(retry, "RETRY_JITTER_MAX_SECONDS", 0) + provider = "anthropic" if protocol == "anthropic" else "openai" + install_sdk_transport(monkeypatch, provider, handle) + async with LLMClient( + provider=provider, model="claude-sonnet-4-6" if provider == "anthropic" else "gpt-4o", + wire_protocol="responses" if protocol == "responses" else "chat_completions", + api_key=tmp_path.name, base_url="https://controlled.invalid", + max_retries=1, + ) as client: + messages = [{"role": "user", "content": "Reply ok."}] + if retryable: + result = await client.complete(messages) + assert result.content == "ok" + assert result.usage.total_tokens == 4 + else: + with pytest.raises((openai.APIStatusError, anthropic.APIStatusError)) as captured: + await client.complete(messages) + assert captured.value.status_code == status + + assert len(requests) == (2 if retryable else 1) + assert delays == ([0.125] if retryable else []) diff --git a/tests/runtime/test_responses_error_usage_http.py b/tests/runtime/test_responses_error_usage_http.py index 308609c1..13c274b2 100644 --- a/tests/runtime/test_responses_error_usage_http.py +++ b/tests/runtime/test_responses_error_usage_http.py @@ -16,7 +16,12 @@ from opencollab.adapters.llm import client as client_module from opencollab.adapters.llm import retry from opencollab.adapters.llm.client import LLMClient -from opencollab.adapters.llm.responses_errors import ResponsesProtocolError +from opencollab.adapters.llm.responses_errors import ( + ResponsesProtocolError, + ResponsesTerminalEventError, + ResponsesTransientEventError, +) +from opencollab.adapters.llm.responses_provider import _wait_for_transport from opencollab.adapters.storage import SessionStore from opencollab.adapters.trace import Tracer from opencollab.application.session_run import GenerationTimeoutError @@ -26,7 +31,7 @@ from opencollab.domain.session import SessionPhase from tests.runtime.test_async_compaction import history from tests.support.environment_test_support import local_environment_factory as local_environment_factory -from tests.support.provider_sdk_http import install_sdk_transport +from tests.support.provider_sdk_http import http_response, install_sdk_transport, provider_http from tests.support.responses_provider_test_support import function_item, message_item KNOWN_USAGE = { @@ -45,12 +50,12 @@ def _response(body, spec): if "function_arguments" in spec: items = [function_item("call_usage", "structured_output", spec["function_arguments"])] return { - "id": "resp_usage_test", "object": "response", "created_at": 1, "model": body["model"], + "id": "resp_usage_test", "object": "response", "created_at": 1, + "model": spec.get("provider_model", body["model"]), "instructions": body.get("instructions"), "status": "incomplete" if kind == "filter" else "failed" if kind == "failed" else "completed", - "error": ( - {"code": "server_error", "message": "An internal server error occurred."} if kind == "failed" else None - ), + "error": spec.get("error", {"code": "server_error", "message": "An internal server error occurred."}) + if kind == "failed" else None, "incomplete_details": {"reason": "content_filter"} if kind == "filter" else None, "output": items, "usage": spec.get("usage", KNOWN_USAGE), } @@ -164,7 +169,8 @@ async def test_reported_terminal_error_usage_reaches_session_and_ledger( **KNOWN_USAGE, "input_tokens_details": {"cached_tokens": 5}, "output_tokens_details": {"reasoning_tokens": 2}, } - base_url, requests = local_responses_server([{"kind": kind, "usage": reported}]) + provider_model = f"{model}-provider-revision" + base_url, requests = local_responses_server([{"kind": kind, "usage": reported, "provider_model": provider_model}]) async with _client(model, base_url) as client: session = build_session( env=local_environment_factory(), @@ -180,6 +186,7 @@ async def test_reported_terminal_error_usage_reaches_session_and_ledger( assert captured.value.code == "server_error" else: assert "content_filter" in str(captured.value) + assert getattr(captured.value, "provider_model", None) == provider_model assert captured.value.usage.raw_usage == reported records = _records(usage_log) assert len(records) == 1 @@ -193,6 +200,7 @@ async def test_reported_terminal_error_usage_reaches_session_and_ledger( assert payload["error"] == {"type": type(captured.value).__name__, "message": str(captured.value)} assert payload["purpose"] == "completion" assert (payload["aid"], payload["session_step"], payload["model"]) == (7, 1, model) + assert payload["provider_model"] == provider_model assert payload["wire_protocol"] == "responses" assert payload["usage"] == { "input_tokens": 30, "output_tokens": 7, "total_tokens": 37, @@ -201,6 +209,19 @@ async def test_reported_terminal_error_usage_reaches_session_and_ledger( } assert calls[0]["metrics"]["tokens"] == 37 +@pytest.mark.parametrize("kind", ["filter", "failed"]) +async def test_terminal_error_without_model_keeps_provider_identity_unknown(monkeypatch, usage_log, kind): + def respond(request): + content_type, body = _payload(json.loads(request.content), {"kind": kind, "provider_model": None}) + return http_response(request, 200, headers={"content-type": content_type}, content=body) + + install_sdk_transport(monkeypatch, "openai", respond) + async with _client("gpt-4o", "https://fixture.invalid/v1") as client: + with pytest.raises(ResponsesProtocolError) as captured: + await client.complete([{"role": "user", "content": "Report the measurement."}]) + assert getattr(captured.value, "provider_model", None) is None + assert captured.value.usage.total_tokens == 37 + @pytest.mark.parametrize("model", ["gpt-4o", "o1-pro"]) async def test_invalid_function_json_retains_terminal_usage(model, local_responses_server, usage_log): base_url, requests = local_responses_server([{"function_arguments": '{"answer":4'}]) @@ -298,6 +319,41 @@ async def test_retry_usage_is_charged_once_with_final_request_context( assert records[0]["usage"]["total_tokens"] == 74 assert records[0]["usage"]["raw_usage"]["attempts"] == [KNOWN_USAGE, KNOWN_USAGE] +@pytest.mark.parametrize(("code", "message", "retries", "attempts", "error_status"), [ + ("upstream_timeout", "Upstream inference request timeout", 1, 2, None), + ("upstream_timeout", "Upstream inference request timeout", 0, 1, 504), + ("stream_interrupted", "upstream stream was interrupted before it finished", 1, 2, None), + ("stream_truncated", "upstream stream ended before the response was complete", 1, 2, None), + ("server_is_overloaded", "backend is overloaded or unavailable; retry shortly", 1, 2, None), + ("invalid_prompt", "The prompt's timeout option is not supported", 1, 1, None), + ("unknown_failure", "Unrecognized provider failure", 1, 1, None), +]) +async def test_responses_stream_retries_transient_gateway_events( + local_environment_factory, local_responses_server, usage_log, code, message, retries, attempts, error_status, +): + base_url, requests = local_responses_server([ + {"kind": "failed", "error": {"code": code, "message": message}}, + {"text": "The result is 42."}, + ]) + recovers = attempts > 1 + async with _client("gpt-4o", base_url, retries=retries) as client: + session = build_session(env=local_environment_factory(), agent=_agent(), llm=client) + await session.add_user_message("Give a short answer") + if recovers: + assert await session.run_loop() == "The result is 42." + else: + with pytest.raises(ResponsesTerminalEventError) as captured: + await session.run_loop() + assert captured.value.code == code + assert captured.value.status_code == error_status + assert all(request["stream"] for request in requests) + assert len(requests) == attempts + assert session.phase is (SessionPhase.DONE if recovers else SessionPhase.ERROR) + assert session.used_tokens == 37 * attempts + record, = _records(usage_log) + assert record["status"] == ("success" if recovers else "error") + assert record["usage"]["total_tokens"] == session.used_tokens + async def test_retry_cost_can_exhaust_session_budget(local_environment_factory, local_responses_server, usage_log): usage = {**KNOWN_USAGE, "input_tokens": 600, "output_tokens": 300, "total_tokens": 900} base_url, requests = local_responses_server([{"kind": "empty", "usage": usage}, {"usage": usage}]) @@ -385,18 +441,265 @@ async def test_summary_attempts_and_answer_are_each_charged_once( assert calls[0]["payload"]["request_tool_choice"] is None assert calls[0]["payload"].get("status") == ("error" if failed_summary else None) +@pytest.mark.parametrize(("model", "summary_specs", "charged"), [ + ("gpt-4o", [{"kind": "filter"}], 37), + ("gpt-4o", [{"kind": "failed"}, {"kind": "filter"}], 74), + ("o1-pro", [{"kind": "filter"}], 37), + ("gpt-4o", [{"kind": "filter", "usage": None}], 0), +], ids=["stream", "stream-after-retry", "non-stream", "missing-usage"]) +async def test_paid_summary_failure_is_saved_before_fallback_answer( + monkeypatch, tmp_path, usage_log, local_environment_factory, model, summary_specs, charged, +): + started, release = asyncio.Event(), asyncio.Event() + requests = [] + + async def handler(request): + index = len(requests) + body = json.loads(request.content) + requests.append(body) + if index < len(summary_specs): + spec = summary_specs[index] + else: + spec = {"text": "answer"} + started.set() + await release.wait() + content_type, content = _payload(body, spec) + return http_response(request, 200, headers={"content-type": content_type}, content=content) + + install_sdk_transport(monkeypatch, "openai", handler) + path = tmp_path / "session.json" + async with _client(model, "https://offline.invalid/v1", retries=1) as client: + session = build_session( + env=local_environment_factory(), agent=_agent(model), llm=client, + auto_save_path=str(path), max_budget_tokens=26_000, + ) + session.messages = history() + session.used_tokens = 250 + session.save(str(path)) + initial_sequence = OpenCollab.read_session_snapshot(path)["_autosave_sequence"] + turn = asyncio.create_task(session.run_loop()) + try: + await asyncio.wait_for(started.wait(), 10) + receipt = OpenCollab.read_session_snapshot(path) + assert session.used_tokens == receipt["session_state"]["used_tokens"] == 250 + charged + assert receipt["_autosave_sequence"] == initial_sequence + (len(summary_specs) if charged else 0) + finally: + release.set() + answer = await turn + await session.aclose() + + assert answer == "answer" + assert all("Your task is to create a detailed summary" in request["input"][-1]["content"] + for request in requests[:-1]) + assert len(requests) == len(summary_specs) + 1 + assert [record["usage"]["total_tokens"] for record in _records(usage_log)] == [charged, 37] + assert OpenCollab.read_session_snapshot(path)["session_state"]["used_tokens"] == 287 + charged + async def _drain(session): while session.pending_cleanup_tasks: await asyncio.gather(*session.pending_cleanup_tasks, return_exceptions=True) await asyncio.sleep(0) +@pytest.mark.parametrize(("summary", "retry_budget", "known_usage"), [ + (False, 0.0, True), + (False, 30.0, True), + (True, 0.0, True), + (True, 30.0, True), + (False, 0.0, False), +], ids=["answer", "answer-shared-time", "summary", "summary-shared-time", "unreported"]) +async def test_settled_attempt_usage_is_saved_before_retry( + monkeypatch, tmp_path, usage_log, local_environment_factory, summary, retry_budget, known_usage, +): + sleeping, release = asyncio.Event(), asyncio.Event() + requests = [] + + async def sleep(delay): + assert delay == 1.0 + sleeping.set() + await release.wait() + + monkeypatch.setattr(retry, "asyncio", SimpleNamespace(sleep=sleep)) + monkeypatch.setattr(retry, "extract_retry_after_seconds", lambda _error: 1.0) + + async def handler(request): + body = json.loads(request.content) + is_summary = "Your task is to create a detailed summary" in body["input"][-1]["content"] + requests.append("summary" if is_summary else "answer") + if len(requests) == 1: + spec = {"kind": "failed"} + if not known_usage: + spec["usage"] = None + else: + spec = {"text": "Earlier context." if is_summary else "answer"} + content_type, content = _payload(body, spec) + return http_response(request, 200, headers={"content-type": content_type}, content=content) + + install_sdk_transport(monkeypatch, "openai", handler) + path = tmp_path / "session.json" + async with LLMClient( + model="gpt-4o", wire_protocol="responses", api_key=tmp_path.name, + base_url="https://offline.invalid/v1", max_retries=1, context_window=40_000, + provider_error_time_budget=retry_budget, first_event_timeout=None, request_timeout=None, + ) as client: + session = build_session( + agent=_agent(), env=local_environment_factory(), llm=client, + auto_save_path=str(path), max_budget_tokens=26_000, + ) + session.messages = history(summary) + session.used_tokens = 250 + session.save(str(path)) + initial_sequence = OpenCollab.read_session_snapshot(path)["_autosave_sequence"] + turn = asyncio.create_task(session.run_loop()) + try: + await asyncio.wait_for(sleeping.wait(), 10) + snapshot = OpenCollab.read_session_snapshot(path) + assert requests == (["summary"] if summary else ["answer"]) + assert session.used_tokens == snapshot["session_state"]["used_tokens"] == (287 if known_usage else 250) + assert snapshot["_autosave_sequence"] == initial_sequence + (1 if known_usage else 0) + finally: + release.set() + answer = await turn + await session.aclose() + + assert answer == "answer" + assert requests == (["summary", "summary", "answer"] if summary else ["answer", "answer"]) + expected = 250 + 37 * (len(requests) if known_usage else len(requests) - 1) + assert OpenCollab.read_session_snapshot(path)["session_state"]["used_tokens"] == expected + +@pytest.mark.parametrize("cancel", [False, True]) +@pytest.mark.parametrize("retry_budget", [0.0, 15.0]) +async def test_direct_responses_completion_cancellation_keeps_reported_usage( + monkeypatch, tmp_path, usage_log, cancel, retry_budget, +): + started = asyncio.Event() + interrupted = asyncio.Event() + release = asyncio.Event() + requests, reported = [], [] + cancellations = [] + + async def handler(request): + requests.append(request.url.path) + started.set() + while not release.is_set(): + try: + await release.wait() + except asyncio.CancelledError: + interrupted.set() + content_type, payload = _payload(json.loads(request.content), {"text": "completed response"}) + return http_response(request, 200, headers={"content-type": content_type}, content=payload) + + install_sdk_transport(monkeypatch, "openai", handler) + oc = OpenCollab( + tmp_path, model="gpt-4o", provider="openai", api_key=tmp_path.name, base_url="https://offline.invalid/v1", + config={ + "wire_protocol": "responses", + "llm_timeout": 8.0, + "llm_max_retries": 0, + "provider_error_time_budget": retry_budget, + }, + ) + async with oc.create_model_client() as client: + messages = [{"role": "user", "content": "Reply briefly"}] + + async def invoke(): + try: + return await client.complete(messages, on_usage=reported.append) + except asyncio.CancelledError as exc: + cancellations.append((exc.args, exc.usage.total_tokens)) + raise + + call = asyncio.create_task(invoke()) + try: + await asyncio.wait_for(started.wait(), 5) + if cancel: + call.cancel("caller moved on") + await asyncio.wait_for(interrupted.wait(), 5) + release.set() + done, _ = await asyncio.wait({call}, timeout=5) + assert call in done + if cancel: + with pytest.raises(asyncio.CancelledError): + await call + else: + assert (await call).content == "completed response" + finally: + release.set() + await asyncio.gather(call, return_exceptions=True) + + assert requests == ["/v1/responses"] + assert cancellations == ([(("caller moved on",), 37)] if cancel else []) + assert [usage.total_tokens for usage in reported] == [37] + record, = _records(usage_log) + assert record["status"] == "success" + assert record["usage"]["total_tokens"] == 37 + +async def test_completed_transport_reports_simultaneous_caller_cancellation(): + interruptions = [] + + async def transport(): + call.cancel("caller moved on") + return "completed" + + call = asyncio.create_task(_wait_for_transport(transport(), None, on_interrupt=interruptions.append)) + assert await call == "completed" + interruption, = interruptions + assert isinstance(interruption, asyncio.CancelledError) + assert interruption.args == ("caller moved on",) + +@pytest.mark.parametrize("kind", ["answer", "failed"]) +async def test_direct_responses_cancellation_races_with_terminal_result(monkeypatch, tmp_path, usage_log, kind): + requests, reported, cancellations = [], [], [] + + def cancel_after_terminal(_task): + cancellations.append(caller.cancel("caller moved on")) + + async def handler(request): + requests.append(request.url.path) + assert asyncio.current_task() is not caller + asyncio.current_task().add_done_callback(cancel_after_terminal) + content_type, payload = _payload(json.loads(request.content), {"kind": kind}) + return http_response(request, 200, headers={"content-type": content_type}, content=payload) + + install_sdk_transport(monkeypatch, "openai", handler) + async with LLMClient( + model="gpt-4o", wire_protocol="responses", api_key=tmp_path.name, + base_url="https://offline.invalid/v1", max_retries=0, request_timeout=8.0, + first_event_timeout=None, stream_idle_timeout=None, + ) as client: + async def invoke(): + try: + return await client.complete([{"role": "user", "content": "Reply briefly"}], on_usage=reported.append) + except asyncio.CancelledError as exc: + assert exc.args == ("caller moved on",) + assert exc.usage.total_tokens == 37 + if kind == "failed": + assert isinstance(exc.__cause__, ResponsesTransientEventError) + raise + + caller = asyncio.create_task(invoke()) + with pytest.raises(asyncio.CancelledError): + await caller + + assert cancellations == [True] + assert requests == ["/v1/responses"] + assert [usage.total_tokens for usage in reported] == [37] + record, = _records(usage_log) + assert record["usage"]["total_tokens"] == 37 + assert record["status"] == ("error" if kind == "failed" else "success") + if kind == "failed": + assert record["error"]["type"] == "ResponsesTransientEventError" + @pytest.mark.parametrize("summary", [False, True]) -@pytest.mark.parametrize("trigger", ["cancel", "timeout"]) +@pytest.mark.parametrize(("trigger", "session_timeout"), [ + pytest.param("cancel", 600, id="cancel-with-deadline"), + pytest.param("cancel", None, id="cancel-without-deadline"), + pytest.param("timeout", 0.01, id="timeout"), +]) @pytest.mark.parametrize("kind", ["filter", "answer"]) @pytest.mark.parametrize("repeat_cancel", [False, True]) async def test_late_sdk_terminal_usage_is_saved_once( local_environment_factory, - monkeypatch, tmp_path, usage_log, summary, trigger, kind, repeat_cancel, trajectory, + monkeypatch, tmp_path, usage_log, summary, trigger, session_timeout, kind, repeat_cancel, trajectory, ): started = asyncio.Event() cancelled = asyncio.Event() @@ -417,7 +720,7 @@ async def handler(request): async with _client("gpt-4o", "http://controlled.invalid/v1") as client: session = build_session( env=local_environment_factory(), - agent=_agent(), llm=client, llm_timeout=0.01 if trigger == "timeout" else 600, + agent=_agent(), llm=client, llm_timeout=session_timeout, auto_save_path=str(snapshot_path), tracer=trajectory, ) if summary: @@ -434,8 +737,10 @@ async def handler(request): expected_error = asyncio.CancelledError else: expected_error = GenerationTimeoutError + done, _ = await asyncio.wait({turn}, timeout=1) + assert turn in done with pytest.raises(expected_error): - await asyncio.wait_for(turn, 1) + await turn await asyncio.wait_for(cancelled.wait(), 1) assert session.used_tokens == 0 if repeat_cancel: @@ -543,6 +848,182 @@ def retry_after(_error): assert records[0]["error"]["type"] == "CancelledError" assert records[0]["usage"]["total_tokens"] == 37 +@pytest.mark.parametrize("trigger", ["cancel", "deadline"]) +@pytest.mark.parametrize("retry_time_budget", [0.0, 30.0]) +@pytest.mark.parametrize(("stage", "late_kind"), [ + ("headers", "answer"), ("first_event", "answer"), ("close", "answer"), ("close", "failed"), +]) +async def test_round_timeout_retains_late_usage_after_retries( + local_environment_factory, monkeypatch, tmp_path, usage_log, trigger, retry_time_budget, stage, late_kind, +): + blocked = asyncio.Event() + sdk_cancelled = asyncio.Event() + release = asyncio.Event() + prior_spend = [] + reported_usage = [(21, 10), (28, 13), (42, 11), (47, 15)] + http = provider_http("openai") + + async def wait_for_release(): + blocked.set() + while not release.is_set(): + try: + await release.wait() + except asyncio.CancelledError: + sdk_cancelled.set() + + async def handler(request): + index = len(prior_spend) + prior_spend.append(session.used_tokens) + input_tokens, output_tokens = reported_usage[index] + kind = "failed" if index < 2 else late_kind if index == 2 else "answer" + content_type, payload = _payload(json.loads(request.content), { + "kind": kind, + "usage": { + "input_tokens": input_tokens, "output_tokens": output_tokens, + "total_tokens": input_tokens + output_tokens, + }, + }) + if index != 2: + return http_response(request, 200, headers={"content-type": content_type}, content=payload) + if stage == "headers": + await wait_for_release() + return http_response(request, 200, headers={"content-type": content_type}, content=payload) + + class LateStream(http.AsyncByteStream): + async def __aiter__(self): + if stage == "first_event": + await wait_for_release() + yield payload + + async def aclose(self): + if stage == "close": + await wait_for_release() + + return http_response(request, 200, headers={"content-type": content_type}, stream=LateStream()) + + install_sdk_transport(monkeypatch, "openai", handler) + snapshot_path = tmp_path / "late-round.json" + async with LLMClient( + model="gpt-4o", wire_protocol="responses", api_key="controlled-local", # pragma: allowlist secret + base_url="http://controlled.invalid/v1", max_retries=3, request_timeout=10.0, + provider_error_time_budget=retry_time_budget, context_window=40000, + ) as client: + session = build_session( + env=local_environment_factory(), agent=_agent(), llm=client, + llm_timeout=0.75 if trigger == "deadline" else 10.0, auto_save_path=str(snapshot_path), + ) + await session.add_user_message("Give a short answer") + turn = asyncio.create_task(session.run_loop()) + try: + await asyncio.wait_for(blocked.wait(), 5) + if trigger == "cancel": + turn.cancel() + expected_error = asyncio.CancelledError if trigger == "cancel" else GenerationTimeoutError + with pytest.raises(expected_error): + await asyncio.wait_for(turn, 5) + await asyncio.wait_for(sdk_cancelled.wait(), 5) + assert session.used_tokens == 72 + stopped_messages = session.messages.copy() + owner, = session.runner.pending_cleanup_tasks + owner.cancel() + await asyncio.sleep(0) + assert not owner.done() + release.set() + await asyncio.wait_for(_drain(session), 5) + finally: + release.set() + await asyncio.gather(turn, return_exceptions=True) + await _drain(session) + + assert prior_spend == [0, 31, 72] + assert session.messages == stopped_messages + assert session.phase is (SessionPhase.STOPPED if trigger == "cancel" else SessionPhase.ERROR) + assert session.used_tokens == 125 + assert session.runner.late_provider_usage == (125,) + snapshot = SessionStore().load_snapshot(str(snapshot_path), session.agent.system_prompt) + assert snapshot["session_state"]["used_tokens"] == 125 + record, = _records(usage_log) + assert record["status"] == ("success" if late_kind == "answer" else "error") + if late_kind == "failed": + assert record["error"]["type"] == "CancelledError" + assert record["transport_timing"]["attempts"] == 3 + assert record["usage"]["total_tokens"] == 125 + assert [attempt["total_tokens"] for attempt in record["usage"]["raw_usage"]["attempts"]] == [31, 41, 53] + +@pytest.mark.parametrize("trigger", ["idle", "request", "cancel"]) +@pytest.mark.parametrize("retry_time_budget", [0.0, 3.0]) +async def test_completed_responses_survives_interrupted_http_close( + monkeypatch, usage_log, trigger, retry_time_budget, +): + http = provider_http("openai") + close_started = asyncio.Event() + interrupted = [] + caller_cancellations = [] + calls = [] + + class SlowClose(http.AsyncByteStream): + def __init__(self, payload): + self.payload = payload + + async def __aiter__(self): + yield self.payload + + async def aclose(self): + close_started.set() + try: + await asyncio.Future() + except asyncio.CancelledError: + interrupted.append(True) + raise + + async def respond(request): + calls.append(request.url.path) + spec = {"text": "inventory count 42" if len(calls) == 1 else "replacement answer"} + content_type, payload = _payload(json.loads(request.content), spec) + headers = {"content-type": content_type} + if len(calls) == 1: + return http.Response(200, headers=headers, stream=SlowClose(payload)) + return http_response(request, 200, headers=headers, content=payload) + + install_sdk_transport(monkeypatch, "openai", respond) + async with LLMClient( + model="gpt-4o", wire_protocol="responses", api_key="controlled-local", # pragma: allowlist secret + base_url="https://fixture.invalid/v1", max_retries=1, + request_timeout=0.4 if trigger == "request" else 5, + stream_idle_timeout=0.15 if trigger == "idle" else 5, + provider_error_time_budget=retry_time_budget, + ) as client: + async def invoke(): + try: + return await client.complete([{"role": "user", "content": "Count the inventory"}]) + except asyncio.CancelledError as exc: + caller_cancellations.append((exc.args, exc.usage.total_tokens)) + raise + + call = asyncio.create_task(invoke()) + try: + await asyncio.wait_for(close_started.wait(), 5) + if trigger == "cancel": + call.cancel("caller stopped") + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(call, 5) + assert caller_cancellations == [(("caller stopped",), 37)] + else: + reply = await asyncio.wait_for(call, 5) + assert reply.content == "inventory count 42" + assert reply.usage.total_tokens == 37 + finally: + if not call.done(): + call.cancel() + await asyncio.gather(call, return_exceptions=True) + + assert calls == ["/v1/responses"] + assert interrupted == [True] + record, = _records(usage_log) + assert record["status"] == "success" + assert record["usage"]["total_tokens"] == 37 + + @pytest.mark.parametrize("kind", ["filter", "answer"]) async def test_cancellation_during_ledger_write_does_not_duplicate_usage( local_environment_factory, diff --git a/tests/runtime/test_responses_http_contract.py b/tests/runtime/test_responses_http_contract.py index 143bbd0a..1763ed08 100644 --- a/tests/runtime/test_responses_http_contract.py +++ b/tests/runtime/test_responses_http_contract.py @@ -10,8 +10,11 @@ import pytest +from opencollab import OpenCollab from opencollab.adapters.llm.client import LLMClient -from opencollab.domain.token_estimation import estimate_messages_tokens +from opencollab.adapters.llm.responses_messages import messages_to_input +from opencollab.domain.token_estimation import estimate_messages_tokens, estimate_tokens +from tests.support.responses_provider_test_support import message_item def _response(response_id: str, *, include_usage: bool = True) -> dict[str, Any]: @@ -77,13 +80,15 @@ def _completed_event( @contextmanager def fake_responses_server( scripts: list[list[dict[str, Any]]], + *, + bearer_value: str = "fake-key", ) -> Iterator[tuple[str, list[dict[str, Any]]]]: requests: list[dict[str, Any]] = [] lock = threading.Lock() class Handler(BaseHTTPRequestHandler): def do_POST(self): - if self.path != "/v1/responses" or self.headers.get("Authorization") != "Bearer fake-key": + if self.path != "/v1/responses" or self.headers.get("Authorization") != f"Bearer {bearer_value}": self.send_error(404) return body = self.rfile.read(int(self.headers.get("Content-Length", "0"))) @@ -118,7 +123,8 @@ def log_message(self, format, *args): thread.join(timeout=2) @pytest.mark.asyncio -async def test_real_http_stream_replays_reasoning_function_call_and_output(monkeypatch): +@pytest.mark.parametrize("phased", [False, True], ids=["unphased", "phased"]) +async def test_real_http_stream_replays_reasoning_function_call_and_output(monkeypatch, phased): monkeypatch.setenv("OPENCOLLAB_LLM_USER_AGENT", "codex_cli_rs/test") reasoning = { "id": "rs_1", @@ -141,12 +147,13 @@ async def test_real_http_stream_replays_reasoning_function_call_and_output(monke "status": "completed", "content": [{"type": "output_text", "text": "42", "annotations": []}], } + commentary = {**message_item("I'll look up the number."), "id": "msg_lookup", "phase": "commentary"} + first_items = [reasoning, commentary, call] if phased else [reasoning, call] scripts = [ [ {"type": "response.created", "sequence_number": 0, "response": _response("resp_1")}, - _item_event(reasoning, 0), - _item_event(call, 1), - _completed_event("resp_1", 3, [reasoning, call]), + *(_item_event(item, index) for index, item in enumerate(first_items)), + _completed_event("resp_1", len(first_items) + 1, first_items), ], [ {"type": "response.created", "sequence_number": 0, "response": _response("resp_2")}, @@ -199,6 +206,7 @@ async def test_real_http_stream_replays_reasoning_function_call_and_output(monke await client.close() + assert first.content is None assert first.tool_calls[0]["id"] == "call_exact" assert second.content == "42" assert requests[0]["include"] == ["reasoning.encrypted_content"] @@ -208,8 +216,7 @@ async def test_real_http_stream_replays_reasoning_function_call_and_output(monke assert requests[0]["_user_agent"] == "codex_cli_rs/test" assert requests[0]["prompt_cache_key"] == requests[1]["prompt_cache_key"] replay = requests[1]["input"] - assert reasoning in replay - assert call in replay + assert replay[1:-1] == first_items assert replay[-1] == { "type": "function_call_output", "call_id": "call_exact", @@ -310,8 +317,49 @@ async def test_real_http_missing_usage_estimates_encrypted_replay_and_registered prefer_response_items=True, ) +@pytest.mark.parametrize("phased", [False, True], ids=["unphased", "phased"]) +async def test_public_agent_uses_final_answer_and_replays_native_phases(tmp_path, monkeypatch, phased): + log = tmp_path / "usage.jsonl" + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(log)) + final = message_item("391") + items = [final] + if phased: + final["phase"] = "final_answer" + items.insert(0, { + **message_item("I'll check the multiplication."), + "id": "msg_progress", + "phase": "commentary", + }) + scripts = [[ + *(_item_event(item, index) for index, item in enumerate(items)), + _completed_event("resp_phases", len(items) + 1, items), + ]] + artifacts = tmp_path / "artifacts" + with fake_responses_server(scripts, bearer_value=tmp_path.name) as (base_url, requests): + app = OpenCollab( + tmp_path, model="gpt-5.3-codex", api_key=tmp_path.name, base_url=base_url, + config={"wire_protocol": "responses", "llm_max_retries": 0}, + ) + result = await app.agent( + "What is 17 times 23?", tools=[], budget=10_000, max_steps=2, + timeout=HANG_GUARD_SECONDS, artifacts=artifacts, trace=False, + ) + + assert (result.status, result.output, result.tokens) == ("completed", "391", 25) + assert len(requests) == 1 + assistant = app.read_session_snapshot(artifacts / "agent.json")["messages"][-1] + assert assistant["content"] == "391" + assert assistant["response_items"] == items + assert messages_to_input([assistant])[1] == items + record, = [json.loads(line) for line in log.read_text().splitlines()] + assert record["status"] == "success" + assert record["usage"]["total_tokens"] == 25 + assert record["usage"]["estimated"] is False + @pytest.mark.asyncio -async def test_real_http_deepseek_named_tool_uses_json_schema_text_binding(): +@pytest.mark.parametrize("phased", [False, True], ids=["unphased", "phased"]) +@pytest.mark.parametrize("include_usage", [False, True], ids=["estimated-usage", "reported-usage"]) +async def test_real_http_deepseek_named_tool_uses_json_schema_text_binding(phased, include_usage): schema = { "type": "object", "required": ["findings"], @@ -342,10 +390,19 @@ async def test_real_http_deepseek_named_tool_uses_json_schema_text_binding(): } ], } + commentary = { + **message_item("I'll gather the findings."), + "id": "msg_progress", + "phase": "commentary", + } + items = [message] + if phased: + message["phase"] = "final_answer" + items.insert(0, commentary) scripts = [[ {"type": "response.created", "sequence_number": 0, "response": _response("resp_schema")}, - _item_event(message, 0), - _completed_event("resp_schema", 2, [message]), + *(_item_event(item, index) for index, item in enumerate(items)), + _completed_event("resp_schema", len(items) + 1, items, include_usage=include_usage), ]] with fake_responses_server(scripts) as (base_url, requests): client = LLMClient( @@ -384,4 +441,16 @@ async def test_real_http_deepseek_named_tool_uses_json_schema_text_binding(): assert request["reasoning"] == {"effort": "none"} assert result.content is None assert result.tool_calls[0]["function"]["name"] == "structured_output" + assert json.loads(result.tool_calls[0]["function"]["arguments"]) == { + "findings": [{"path": "a.py", "summary": "ok"}], + } assert result.provider_items[-1]["type"] == "function_call" + assert result.provider_items[:-1] == ([commentary] if phased else []) + if include_usage: + assert result.usage.total_tokens == 25 + assert result.usage.estimated is False + else: + function = result.tool_calls[0]["function"] + prefix = commentary["content"][0]["text"] if phased else "" + assert result.usage.output_tokens == estimate_tokens(prefix + function["name"] + function["arguments"]) + assert result.usage.estimated is True diff --git a/tests/runtime/test_responses_schema_output_limit.py b/tests/runtime/test_responses_schema_output_limit.py index 417f8f31..f46558f0 100644 --- a/tests/runtime/test_responses_schema_output_limit.py +++ b/tests/runtime/test_responses_schema_output_limit.py @@ -21,8 +21,16 @@ @pytest.mark.parametrize("streamed", [False, True]) @pytest.mark.parametrize("text", [None, '{"result":', '{"result":"ok"}']) -async def test_schema_limit_preserves_reported_usage_and_skips_projection(streamed, text): - items = [] if text is None else [{**message_item(text), "status": "incomplete"}] +@pytest.mark.parametrize("phased", [False, True], ids=["unphased", "phased"]) +async def test_schema_limit_preserves_reported_usage_and_skips_projection(streamed, text, phased): + items = [] + if phased: + items.append({**message_item("Collecting the result."), "id": "msg_progress", "phase": "commentary"}) + if text is not None: + partial = {**message_item(text), "status": "incomplete"} + if phased: + partial["phase"] = "final_answer" + items.append(partial) terminal = completed_response( status="incomplete", incomplete_details={"reason": "max_output_tokens"}, output=items, ) diff --git a/tests/runtime/test_run_control_turn_handoff.py b/tests/runtime/test_run_control_turn_handoff.py new file mode 100644 index 00000000..a602d6a2 --- /dev/null +++ b/tests/runtime/test_run_control_turn_handoff.py @@ -0,0 +1,231 @@ +"""Exercise per-turn final prompts on a reusable controlled session.""" + +from __future__ import annotations + +import copy +import json + +import pytest + +from opencollab import BudgetDecision, RunControl +from opencollab.adapters.env import LocalEnvironment +from opencollab.adapters.llm.types import LLMResponse, Usage +from opencollab.application._anthropic_history import _RUN_FINAL_PROMPT_FIELD, _edited_anthropic_history +from opencollab.bootstrap import build_session, load_session +from opencollab.domain.agent import Agent +from tests.runtime.test_anthropic_preserved_history import _agent, _client +from tests.support.provider_sdk_http import completion_http_response, http_response, install_sdk_transport + + +@pytest.mark.parametrize("first_outcome", ["completed", "provider_error", "budget_refused"]) +@pytest.mark.parametrize("shaping", [True, False], ids=["default-shaper", "no-shaper"]) +async def test_new_user_turn_discards_previous_final_prompt(tmp_path, monkeypatch, first_outcome, shaping): + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + old_prompt = "Close the first branch and do not continue its review." + if first_outcome == "budget_refused": + old_prompt += " Review only the previous item." * 120 + finishing = True + requests = [] + + class Model: + async def complete(self, messages, tools=None, **kwargs): + assert all("_opencollab_run_final_prompt" not in row for row in messages) + requests.append(copy.deepcopy(messages)) + if finishing and first_outcome == "provider_error": + raise ConnectionError("local fixture provider unavailable") + text = "First result." if finishing else "Second result." + if not finishing and any(row.get("content") == old_prompt for row in messages): + text = "The older instruction is still active." + return LLMResponse(content=text, finish_reason="stop", usage=Usage(input_tokens=8, output_tokens=2)) + + def decide(snapshot): + return BudgetDecision(snapshot.soft_budget_tokens, final_prompt=old_prompt if finishing else None) + + environment = LocalEnvironment(str(tmp_path)) + session = build_session( + env=environment, agent=Agent(name="inventory", system_prompt="Check the requested inventory."), + llm=Model(), max_budget_tokens=500, run_control=RunControl(decide_budget=decide), + ) + if not shaping: + session.runner.shaper = None + try: + await session.add_user_message("Check the first inventory.") + if first_outcome == "provider_error": + with pytest.raises(ConnectionError, match="local fixture provider unavailable"): + await session.run_loop() + else: + expected = "First result." if first_outcome == "completed" else "" + assert await session.run_loop() == expected + if first_outcome == "budget_refused": + assert requests == [] and "budget exhausted before model call" in session.state.terminal_reason + else: + assert [row for row in requests[-1] if row.get("content") == old_prompt] + assert all(row.get("content") != old_prompt for row in session.messages) + + finishing = False + await session.add_user_message("Check the second inventory.") + completed = await session.run_loop() + expected_calls = 1 if first_outcome == "budget_refused" else 2 + assert len(requests) == expected_calls + assert all(row.get("content") != old_prompt for row in requests[-1]) + assert completed == "Second result." + finally: + await session.aclose() + await environment.cleanup() + + +@pytest.mark.parametrize("restored", [False, True], ids=["same-session", "restore"]) +async def test_anthropic_final_prompt_applies_to_only_one_request(tmp_path, monkeypatch, restored): + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(tmp_path / "usage.jsonl")) + old_prompt = "Close the first branch and do not continue its review." + requests = [] + + def respond(request): + body = json.loads(request.content) + requests.append(body) + if len(requests) > 1: + prompt_active = old_prompt in json.dumps(body["system"]) + text = "Older instruction still active." if prompt_active else "Second result." + return completion_http_response(request, text=text) + return http_response(request, 200, json={ + "id": "msg_first", "type": "message", "role": "assistant", "model": body["model"], + "content": [ + {"type": "thinking", "thinking": "Read the first inventory.", "signature": "first-test-signature"}, + {"type": "text", "text": "First result."}, + ], "stop_reason": "end_turn", "stop_sequence": None, + "usage": {"input_tokens": 60, "output_tokens": 10}, + }) + + install_sdk_transport(monkeypatch, "anthropic", respond) + environment = LocalEnvironment(str(tmp_path)) + control = RunControl(decide_budget=lambda snapshot: BudgetDecision( + snapshot.soft_budget_tokens, final_prompt=old_prompt if not requests else None, + )) + async with _client() as model: + options = dict(agent=_agent(), llm=model, env=environment, max_budget_tokens=10_000, run_control=control) + session = build_session(**options) + try: + await session.add_user_message("Check the first inventory.") + assert await session.run_loop() == "First result." + assert old_prompt in json.dumps(requests[0]["system"]) + if restored: + snapshot = tmp_path / "session.json" + session.save(str(snapshot)) + await session.aclose() + session = load_session(str(snapshot), **{**options, "run_control": None}) + + await session.add_user_message("Check the second inventory.") + output = await session.run_loop() + assert len(requests) == 2 and old_prompt not in json.dumps(requests[1]["system"]) + assert "first-test-signature" not in json.dumps(requests[1]["messages"]) + assert "first-test-signature" in json.dumps(session.messages) + assert output == "Second result." + finally: + await session.aclose() + await environment.cleanup() + + +@pytest.mark.parametrize("renewed", [True, False], ids=["same-prompt", "changed-prompt"]) +async def test_anthropic_tool_continuation_with_final_prompt(tmp_path, monkeypatch, renewed): + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(tmp_path / "usage.jsonl")) + (tmp_path / "source.txt").write_text("There are 27 items.\n") + first_prompt = "Finish by reporting the inventory total." + second_prompt = first_prompt if renewed else "Report the regional breakdown as well." + requests = [] + thinking = {"type": "thinking", "thinking": "", "signature": "tool-turn-signature"} + tool_use = {"type": "tool_use", "id": "read-inventory", "name": "file_read", "input": {"path": "source.txt"}} + + def respond(request): + body = json.loads(request.content) + requests.append(body) + if len(requests) == 1: + return http_response(request, 200, json={ + "id": "msg_read", "type": "message", "role": "assistant", "model": body["model"], + "content": [thinking, tool_use], "stop_reason": "tool_use", "stop_sequence": None, + "usage": {"input_tokens": 60, "output_tokens": 10}, + }) + assistant, tool_result = body["messages"][-2:] + assert assistant["content"] == ([thinking, tool_use] if renewed else [tool_use]) + result, = tool_result["content"] + assert result["tool_use_id"] == "read-inventory" + assert "There are 27 items." in result["content"] + return completion_http_response(request, text="27 items.") + + def decide(snapshot): + prompt = second_prompt if requests else first_prompt + return BudgetDecision( + snapshot.soft_budget_tokens, final_prompt=prompt if snapshot.reason == "request" else None, + ) + + install_sdk_transport(monkeypatch, "anthropic", respond) + control = RunControl(decide_budget=decide) + environment = LocalEnvironment(str(tmp_path)) + async with _client() as model: + session = build_session( + agent=_agent(), llm=model, env=environment, run_control=control, max_budget_tokens=10_000, + ) + try: + await session.add_user_message("Read the inventory.") + assert await session.run_loop() == "27 items." + assert session.used_tokens == 74 + finally: + await session.aclose() + await environment.cleanup() + initial, followup = requests + assert initial["system"].endswith(first_prompt) + assert followup["system"].endswith(second_prompt) + assert initial["tools"] == followup["tools"] + + +@pytest.mark.parametrize("reordered", [False, True], ids=["same-system", "developer-reordered"]) +async def test_anthropic_final_prompt_renewal_checks_wire_system_order(tmp_path, monkeypatch, reordered): + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(tmp_path / "usage.jsonl")) + requests = [] + thinking = {"type": "thinking", "thinking": "", "signature": "system-order-signature"} + tool_use = {"type": "tool_use", "id": "read-total", "name": "file_read", "input": {"path": "source.txt"}} + + def respond(request): + body = json.loads(request.content) + requests.append(body) + if len(requests) == 1: + return http_response(request, 200, json={ + "id": "msg_system_order", "type": "message", "role": "assistant", "model": body["model"], + "content": [thinking, tool_use], "stop_reason": "tool_use", "stop_sequence": None, + "usage": {"input_tokens": 60, "output_tokens": 10}, + }) + return completion_http_response(request, text="The total is 27.") + + system = {"role": "system", "content": "Report the total."} + user = {"role": "user", "content": "Read the inventory."} + developer = {"role": "developer", "content": "Include the units."} + prompt = {"role": "system", "content": "Finish the inventory report.", _RUN_FINAL_PROMPT_FIELD: True} + initial_messages = [system, user, prompt, developer] if reordered else [system, user, developer, prompt] + options = {"tools": _agent().tool_schemas(), "thinking": True, + "thinking_params": {"thinking": {"type": "adaptive"}}} + install_sdk_transport(monkeypatch, "anthropic", respond) + async with _client() as model: + first = await model.complete(initial_messages, **options) + assistant = {"role": "assistant", "content": first.content, "tool_calls": first.tool_calls, + "provider_state": first.provider_state} + tool_result = {"role": "tool", "tool_call_id": "read-total", "content": "27 items."} + continuation = _edited_anthropic_history( + [*initial_messages, assistant, tool_result], + [system, user, developer, assistant, tool_result, prompt], + ) + assert (await model.complete(continuation, **options)).content == "The total is 27." + + initial, followup = requests + assert followup["system"] == "\n\n".join(row["content"] for row in (system, developer, prompt)) + if reordered: + assert initial["system"] == "\n\n".join(row["content"] for row in (system, prompt, developer)) + else: + assert initial["system"] == followup["system"] + assert followup["messages"][1]["content"] == ([tool_use] if reordered else [thinking, tool_use]) + assert followup["messages"][2]["content"] == [ + {"type": "tool_result", "tool_use_id": "read-total", "content": "27 items."}, + ] diff --git a/tests/runtime/test_session_autosave_handoff.py b/tests/runtime/test_session_autosave_handoff.py new file mode 100644 index 00000000..90a086dd --- /dev/null +++ b/tests/runtime/test_session_autosave_handoff.py @@ -0,0 +1,231 @@ +from __future__ import annotations + +import asyncio +import sys +from contextlib import suppress +from pathlib import Path + +import pytest + +from opencollab import OpenCollab +from opencollab.application.session import Session, SessionBusyError +from opencollab.bootstrap import build_session, load_session +from opencollab.domain.agent import Agent +from opencollab.environments import local_environment +from tests.support.paths import REPO_ROOT +from tests.support.session_run_test_support import FakeLLM, llm_response + +_AUTOSAVE = "autosave.json" +_TIMEOUT = 10 +_WORKER_MODULE = "tests.runtime.test_session_autosave_handoff" + + +class _LateProvider(FakeLLM): + def __init__(self) -> None: + super().__init__([ + llm_response(content="Initial review recorded.", total_tokens=10), + llm_response(content="Late review response.", total_tokens=20), + ]) + self.admitted = asyncio.Event() + self.release = asyncio.Event() + + async def complete(self, *args, **kwargs): + if self.calls: + self.admitted.set() + # The provider reports usage after the caller has cancelled the turn. + while not self.release.is_set(): + try: + await self.release.wait() + except asyncio.CancelledError: + continue + return await super().complete(*args, **kwargs) + + +def _session_options(root: Path, llm: FakeLLM): + return { + "agent": Agent(name="reviewer", system_prompt="Continue the review."), + "llm": llm, + "env": local_environment(root), + "auto_save_path": str(root / _AUTOSAVE), + "llm_timeout": 600, + } + + +def _saved_state(root: Path) -> tuple[str, int]: + state = OpenCollab.read_session_snapshot(root / _AUTOSAVE)["session_state"] + return state["phase"], state["used_tokens"] + + +async def _drain(session: Session) -> None: + while tasks := session.pending_cleanup_tasks: + await asyncio.gather(*tasks, return_exceptions=True) + + +async def _hold_autosave(root: Path) -> None: + provider = _LateProvider() + session = build_session(**_session_options(root, provider)) + await session.add_user_message("Record the initial review.") + assert await session.run_loop() == "Initial review recorded." + await session.add_user_message("Review the next section.") + turn = asyncio.create_task(session.run_loop()) + await asyncio.wait_for(provider.admitted.wait(), _TIMEOUT) + turn.cancel() + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(turn, _TIMEOUT) + await session.aclose() + assert session.pending_execution_tasks + print("waiting for provider", flush=True) + + await asyncio.to_thread(sys.stdin.readline) + provider.release.set() + await asyncio.wait_for(_drain(session), _TIMEOUT) + assert session.used_tokens == 30 + print("settled", flush=True) + await asyncio.to_thread(sys.stdin.readline) + await session.env.cleanup() + + +async def _resume_autosave(root: Path) -> None: + llm = FakeLLM([llm_response(content="Follow-up recorded.", total_tokens=5)]) + options = _session_options(root, llm) + try: + session = load_session(str(root / _AUTOSAVE), **options) + except SessionBusyError: + print("busy", flush=True) + return + inherited_tokens = session.used_tokens + try: + await session.add_user_message("Continue from the saved review.") + assert await session.run_loop() == "Follow-up recorded." + finally: + await session.aclose() + await session.env.cleanup() + print(f"resumed from {inherited_tokens} tokens", flush=True) + + +async def _start_worker(role: str, root: Path) -> asyncio.subprocess.Process: + return await asyncio.create_subprocess_exec( + sys.executable, "-m", _WORKER_MODULE, role, str(root), + cwd=REPO_ROOT, + stdin=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + + +async def _kill_worker(process: asyncio.subprocess.Process) -> None: + if process.returncode is None: + with suppress(ProcessLookupError): + process.kill() + await asyncio.wait_for(process.communicate(), _TIMEOUT) + + +async def _finish_worker(process: asyncio.subprocess.Process, command: bytes | None = None) -> str: + try: + output, errors = await asyncio.wait_for(process.communicate(command), _TIMEOUT) + finally: + await _kill_worker(process) + assert process.returncode == 0, errors.decode(errors="replace") + return output.decode().strip() + + +async def _expect_worker_line(process: asyncio.subprocess.Process, expected: bytes) -> None: + assert process.stdout is not None + line = await asyncio.wait_for(process.stdout.readline(), _TIMEOUT) + if not line: + await _finish_worker(process) + assert line == expected + + +@pytest.mark.parametrize("crash_owner", [False, True], ids=["settled", "killed"]) +async def test_autosave_handoff_between_processes(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, crash_owner: bool): + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + owner = await _start_worker("hold", tmp_path) + try: + await _expect_worker_line(owner, b"waiting for provider\n") + assert _saved_state(tmp_path) == ("stopped", 10) + for destination in (None, str(tmp_path / "copy.json")): + options = _session_options(tmp_path, FakeLLM()) + options["auto_save_path"] = destination + observer = load_session(str(tmp_path / _AUTOSAVE), **options) + try: + assert observer.used_tokens == 10 + if destination is not None: + assert OpenCollab.read_session_snapshot(destination)["session_state"]["used_tokens"] == 10 + finally: + await observer.aclose() + await observer.env.cleanup() + contender = await _start_worker("resume", tmp_path) + assert await _finish_worker(contender) == "busy" + assert _saved_state(tmp_path) == ("stopped", 10) + + if crash_owner: + await _kill_worker(owner) + assert owner.returncode != 0 + inherited_tokens = 10 + else: + assert owner.stdin is not None + owner.stdin.write(b"release\n") + await owner.stdin.drain() + await _expect_worker_line(owner, b"settled\n") + assert _saved_state(tmp_path) == ("stopped", 30) + inherited_tokens = 30 + + successor = await _start_worker("resume", tmp_path) + assert await _finish_worker(successor) == f"resumed from {inherited_tokens} tokens" + assert _saved_state(tmp_path) == ("done", inherited_tokens + 5) + if not crash_owner: + assert owner.returncode is None + await _finish_worker(owner, command=b"exit\n") + finally: + await _kill_worker(owner) + +async def test_queued_autosave_cannot_replace_a_live_turn(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + path = tmp_path / _AUTOSAVE + admitted, release = asyncio.Event(), asyncio.Event() + + class WaitingProvider(FakeLLM): + async def complete(self, *args, **kwargs): + admitted.set() + await release.wait() + return await super().complete(*args, **kwargs) + + older = build_session(**_session_options( + tmp_path, FakeLLM([llm_response(content="Recorded one task.", total_tokens=10)]), + )) + newer = turn = None + try: + await older.add_user_message("Review the first section.") + assert await older.run_loop() == "Recorded one task." + newer = load_session(str(path), **_session_options( + tmp_path, WaitingProvider([llm_response(content="Recorded the second task.", total_tokens=20)]), + )) + await newer.add_user_message("Review the second section.") + turn = asyncio.create_task(newer.run_loop()) + await asyncio.wait_for(admitted.wait(), _TIMEOUT) + await asyncio.gather(*newer.event_bus.pending_tasks) + before = OpenCollab.read_session_snapshot(path) + assert any(row["content"] == "Review the second section." for row in before["messages"]) + with pytest.raises(SessionBusyError, match="active writer"): + older.enqueue_auto_save() + assert OpenCollab.read_session_snapshot(path) == before + release.set() + assert await asyncio.wait_for(turn, _TIMEOUT) == "Recorded the second task." + assert _saved_state(tmp_path) == ("done", 30) + finally: + release.set() + if turn is not None: + await asyncio.gather(turn, return_exceptions=True) + if newer is not None: + await newer.aclose() + await newer.env.cleanup() + await older.aclose() + await older.env.cleanup() + + +if __name__ == "__main__": + workers = {"hold": _hold_autosave, "resume": _resume_autosave} + asyncio.run(workers[sys.argv[1]](Path(sys.argv[2]))) diff --git a/tests/runtime/test_stale_writable_session.py b/tests/runtime/test_stale_writable_session.py new file mode 100644 index 00000000..49af1f30 --- /dev/null +++ b/tests/runtime/test_stale_writable_session.py @@ -0,0 +1,315 @@ +from __future__ import annotations + +import asyncio +import errno +import os +from contextlib import AsyncExitStack +from copy import deepcopy +from pathlib import Path + +import pytest + +from opencollab import OpenCollab +from opencollab.adapters import safe_files +from opencollab.application.ports import SnapshotSequenceConflict +from opencollab.application.session import Session +from opencollab.bootstrap import build_session, load_session +from opencollab.domain.agent import Agent +from opencollab.environments import local_environment +from tests.support.session_run_test_support import FakeLLM, llm_response + + +async def _settle_autosave(session: Session) -> None: + while tasks := session.pending_cleanup_tasks: + await asyncio.gather(*tasks) + + +@pytest.mark.parametrize("entry", ["new-prompt", "queued-prompt", "enqueue-autosave"]) +async def test_stale_writable_session_rejects_turn_until_restored( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, entry: str, +) -> None: + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + autosave_path = tmp_path / "autosave.json" + journal_path = tmp_path / "autosave.json.journal" + autosave = str(autosave_path) + queued_prompt = entry == "queued-prompt" + initial_prompt = "Review the first section." + second_prompt = "Review the second section." + follow_up = "Summarize the complete review." + original_llm = FakeLLM([ + llm_response(content="First section reviewed.", total_tokens=10), + llm_response(content="Second section reviewed.", total_tokens=20), + ]) + resumed_llm = FakeLLM([ + llm_response(content="Review summarized.", total_tokens=5), + ]) + + async with AsyncExitStack() as cleanup: + original_env = local_environment(tmp_path) + cleanup.push_async_callback(original_env.cleanup) + original = build_session( + agent=Agent(name="reviewer", system_prompt="Review the report."), + llm=original_llm, + env=original_env, + auto_save_path=autosave, + ) + cleanup.push_async_callback(original.aclose) + cleanup.push_async_callback(_settle_autosave, original) + await original.add_user_message(initial_prompt) + assert await original.run_loop() == "First section reviewed." + + if queued_prompt: + await original.add_user_message(second_prompt) + await _settle_autosave(original) + snapshot = OpenCollab.read_session_snapshot(autosave) + assert snapshot["session_state"]["pending_external_user_turn"]["content"] == second_prompt + + resumed_env = local_environment(tmp_path) + cleanup.push_async_callback(resumed_env.cleanup) + resumed = load_session( + autosave, + agent=Agent(name="reviewer", system_prompt="Review the report."), + llm=resumed_llm, + env=resumed_env, + auto_save_path=autosave, + ) + cleanup.push_async_callback(resumed.aclose) + cleanup.push_async_callback(_settle_autosave, resumed) + assert resumed.used_tokens == 10 + if queued_prompt: + assert resumed.state.pending_external_user_turn["content"] == second_prompt + + if not queued_prompt: + await original.add_user_message(second_prompt) + assert await original.run_loop() == "Second section reviewed." + before = OpenCollab.read_session_snapshot(autosave) + assert before["session_state"]["used_tokens"] == 30 + saved_bytes = autosave_path.read_bytes(), journal_path.read_bytes() + stale_messages = deepcopy(resumed.messages) + stale_turn = resumed.state.checkpoint_user_turn() + stale_steps = resumed.step_count + + with pytest.raises(SnapshotSequenceConflict): + if entry == "new-prompt": + await resumed.add_user_message(follow_up) + elif queued_prompt: + await resumed.run_loop() + else: + resumed.enqueue_auto_save() + + await _settle_autosave(resumed) + assert resumed_llm.calls == [] + assert resumed.messages == stale_messages + assert resumed.state.checkpoint_user_turn() == stale_turn + assert resumed.used_tokens == 10 + assert resumed.step_count == stale_steps + assert OpenCollab.read_session_snapshot(autosave) == before + assert (autosave_path.read_bytes(), journal_path.read_bytes()) == saved_bytes + + resumed.restore(autosave) + assert resumed.used_tokens == 30 + await resumed.add_user_message(follow_up) + assert await resumed.run_loop() == "Review summarized." + assert len(resumed_llm.calls) == 1 + after = OpenCollab.read_session_snapshot(autosave) + assert after["session_state"]["used_tokens"] == 35 + assert [message["content"] for message in after["messages"]] == [ + "Review the report.", + initial_prompt, + "First section reviewed.", + second_prompt, + "Second section reviewed.", + follow_up, + "Review summarized.", + ] + + +@pytest.mark.parametrize( + ("failure_stage", "peer_write", "retry_save"), + [ + ("base_rename", False, True), + ("base_sync", False, True), + ("base_sync_read", False, True), + ("journal_reset", False, True), + ("base_sync", False, False), + ("journal_reset", False, False), + ("base_rename", True, True), + ("base_sync", True, True), + ("journal_reset", True, True), + ], +) +async def test_manual_checkpoint_can_retry_its_own_failed_publication( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, failure_stage: str, peer_write: bool, retry_save: bool, +) -> None: + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + path = tmp_path / "autosave.json" + journal = tmp_path / "autosave.json.journal" + exported = tmp_path / "export.json" + autosave = str(path) + agent = Agent(name="reviewer", system_prompt="Review the chapter.") + llm = FakeLLM([ + llm_response(content="First section reviewed.", total_tokens=11), + llm_response(content="Second section reviewed.", total_tokens=13), + ]) + + async with AsyncExitStack() as cleanup: + env = local_environment(tmp_path) + cleanup.push_async_callback(env.cleanup) + session = build_session(agent=agent, llm=llm, env=env, auto_save_path=autosave) + cleanup.push_async_callback(session.aclose) + cleanup.push_async_callback(_settle_autosave, session) + await session.add_user_message("Review the first section.") + assert await session.run_loop() == "First section reviewed." + await session.add_user_message("Review the second section.") + await _settle_autosave(session) + if not journal.stat().st_size: + await session.enqueue_auto_save() + original = OpenCollab.read_session_snapshot(path) + sequence = original["_autosave_sequence"] + original_base = path.read_bytes() + original_journal = journal.read_bytes() + assert original_journal + + error = OSError(errno.EIO, f"checkpoint {failure_stage} failed") + replace_file = os.replace + sync_directory = safe_files._fsync_directory + read_snapshot_text = session.store._read_snapshot_text + sync_failed = False + + def fail_rename(source, destination): + failing_path = path if failure_stage == "base_rename" else journal + if Path(destination) == failing_path: + raise error + return replace_file(source, destination) + + def fail_base_sync(directory): + nonlocal sync_failed + if directory == path.parent: + sync_failed = True + raise error + return sync_directory(directory) + + def read_during_fault(name): + if sync_failed and name == autosave: + raise OSError(errno.EIO, "snapshot temporarily unavailable") + return read_snapshot_text(name) + + with monkeypatch.context() as fault: + if failure_stage in {"base_sync", "base_sync_read"}: + fault.setattr(safe_files, "_fsync_directory", fail_base_sync) + if failure_stage == "base_sync_read": + fault.setattr(session.store, "_read_snapshot_text", read_during_fault) + else: + fault.setattr(os, "replace", fail_rename) + with pytest.raises(OSError) as failure: + session.save(autosave) + assert failure.value is error + + published = failure_stage != "base_rename" + expected = {**original, "_autosave_sequence": sequence + int(published)} + assert OpenCollab.read_session_snapshot(path) == expected + assert (path.read_bytes() != original_base) == published + assert journal.read_bytes() == original_journal + source_bytes = path.read_bytes(), journal.read_bytes() + session.save(str(exported)) + assert OpenCollab.read_session_snapshot(exported) == { + **original, + "_autosave_sequence": sequence + 1, + "_autosave_export_source_sequence": sequence + 1, + } + assert (path.read_bytes(), journal.read_bytes()) == source_bytes + + if peer_write: + peer = load_session(autosave, agent=agent, llm=FakeLLM([]), env=env, auto_save_path=autosave, aid=42) + cleanup.push_async_callback(peer.aclose) + peer.save(autosave) + peer_snapshot = OpenCollab.read_session_snapshot(path) + assert peer_snapshot["aid"] == 42 + assert peer_snapshot["_autosave_sequence"] == expected["_autosave_sequence"] + 1 + peer_bytes = path.read_bytes(), journal.read_bytes() + with pytest.raises(SnapshotSequenceConflict): + session.save(autosave) + with pytest.raises(SnapshotSequenceConflict): + await session.run_loop() + assert len(llm.calls) == 1 + assert OpenCollab.read_session_snapshot(path) == peer_snapshot + assert (path.read_bytes(), journal.read_bytes()) == peer_bytes + return + + if retry_save: + session.save(autosave) + saved = OpenCollab.read_session_snapshot(path) + assert saved == {**original, "_autosave_sequence": saved["_autosave_sequence"]} + assert saved["_autosave_sequence"] > sequence + assert journal.read_bytes() == b"" + assert await session.run_loop() == "Second section reviewed." + assert len(llm.calls) == 2 + final = OpenCollab.read_session_snapshot(path) + assert final["session_state"]["used_tokens"] == 24 + assert final["session_state"]["pending_external_user_turn"] is None + assert [message["content"] for message in final["messages"]] == [ + "Review the chapter.", + "Review the first section.", + "First section reviewed.", + "Review the second section.", + "Second section reviewed.", + ] + + +@pytest.mark.parametrize("destination_turns", [1, 2]) +async def test_export_over_compacted_autosave_invalidates_loaded_session( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, destination_turns: int, +) -> None: + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + target, source = tmp_path / "target.json", tmp_path / "source.json" + target_journal = target.with_suffix(".json.journal") + agent = Agent(name="editor", system_prompt="Review the draft.") + target_llm = FakeLLM( + [llm_response(content="Draft A reviewed.", total_tokens=11)] * destination_turns + + [llm_response(content="Current draft summarized.", total_tokens=5)] + ) + async with AsyncExitStack() as cleanup: + env = local_environment(tmp_path) + cleanup.push_async_callback(env.cleanup) + destination = build_session(agent=agent, llm=target_llm, env=env, auto_save_path=str(target)) + exporting = build_session( + agent=agent, env=env, auto_save_path=str(source), + llm=FakeLLM([llm_response(content="Draft B reviewed.", total_tokens=17)]), + ) + cleanup.push_async_callback(destination.aclose) + cleanup.push_async_callback(exporting.aclose) + for index in range(destination_turns): + await destination.add_user_message(f"Review draft A, section {index + 1}.") + assert await destination.run_loop() == "Draft A reviewed." + await exporting.add_user_message("Review draft B.") + assert await exporting.run_loop() == "Draft B reviewed." + + target_before = OpenCollab.read_session_snapshot(target) + source_before = OpenCollab.read_session_snapshot(source) + source_bytes = source.read_bytes() + assert target_journal.read_bytes() == b"" + assert target_before["_autosave_sequence"] >= source_before["_autosave_sequence"] + + exporting.save(str(target)) + replacement = OpenCollab.read_session_snapshot(target) + assert replacement["_autosave_sequence"] > target_before["_autosave_sequence"] + assert replacement["_autosave_export_source_sequence"] == source_before["_autosave_sequence"] + assert replacement["messages"] == source_before["messages"] + assert source.read_bytes() == source_bytes + replacement_bytes = target.read_bytes() + + with pytest.raises(SnapshotSequenceConflict): + await destination.add_user_message("Summarize the current draft.") + assert len(target_llm.calls) == destination_turns + assert target.read_bytes() == replacement_bytes + assert target_journal.read_bytes() == b"" + + destination.restore(str(target)) + assert destination.used_tokens == 17 + await destination.add_user_message("Summarize the current draft.") + assert await destination.run_loop() == "Current draft summarized." + assert destination.used_tokens == 22 + assert len(target_llm.calls) == destination_turns + 1 diff --git a/tests/runtime/test_submitted_session_resume.py b/tests/runtime/test_submitted_session_resume.py new file mode 100644 index 00000000..b6e7dfd0 --- /dev/null +++ b/tests/runtime/test_submitted_session_resume.py @@ -0,0 +1,159 @@ +"""Restore the assistant answer accepted before a submission event was interrupted.""" + +from __future__ import annotations + +import asyncio +import json +import os + +import pytest + +from opencollab import OpenCollab +from opencollab.adapters.tools.submit import SubmitTool +from opencollab.application.event_bus import EventBus +from opencollab.bootstrap import build_session, load_session +from opencollab.domain.agent import Agent +from opencollab.environments import local_environment +from tests.support.provider_sdk_http import completion_http_response, http_response, install_sdk_transport + + +@pytest.mark.parametrize("scene", ["cancel", "deadline", "completed", "before_submit"]) +async def test_reopen_accepted_submission_once(tmp_path, monkeypatch, scene): + monkeypatch.chdir(tmp_path) + for key in tuple(os.environ): + if key.startswith(("OPENCOLLAB_", "OPENAI_", "ANTHROPIC_", "DASHSCOPE_")): + monkeypatch.delenv(key) + usage_path = tmp_path / "usage.jsonl" + monkeypatch.setenv("OPENCOLLAB_API_USAGE_LOG", str(usage_path)) + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + summary = "The intake audit verified 42 complete records." + answer = {"role": "assistant", "content": summary} + requests = [] + entered, release = asyncio.Event(), asyncio.Event() + held_event = "tool_start" if scene == "before_submit" else "tool_end" + + async def observe(event): + if scene != "completed" and event.type == held_event and event.data.get("tool") == "submit": + entered.set() + await release.wait() + + def respond(request): + body = json.loads(request.content) + requests.append(body["messages"]) + if len(requests) > 1: + return completion_http_response(request, output_tokens=13, text="Follow-up complete.") + return http_response(request, 200, json={ + "id": "submit-intake", "object": "chat.completion", "created": 1, "model": body["model"], + "choices": [{"index": 0, "finish_reason": "tool_calls", "message": { + "role": "assistant", "content": None, + "tool_calls": [{"id": "submission", "type": "function", "function": { + "name": "submit", "arguments": json.dumps({"summary": summary}), + }}], + }}], + "usage": {"prompt_tokens": 2, "completion_tokens": 3, "total_tokens": 5}, + }) + + install_sdk_transport(monkeypatch, "openai", respond) + provider = { + "provider": "openai", "model": "fixture-model", + "api_key": tmp_path.name, "base_url": "https://fixture.invalid/v1", + } + transport = {"wire_protocol": "chat_completions", "llm_max_retries": 0} + + def agent(): + return Agent(name="auditor", system_prompt="Report the intake audit.", tools=[SubmitTool()], + **provider, **transport) + + path = tmp_path / "session.json" + recovered_path = tmp_path / "recovered.json" + environment = local_environment(tmp_path) + turn = original = restored = None + try: + if scene == "deadline": + emit = EventBus.emit + + async def emit_with_observer(bus, event): + await observe(event) + await emit(bus, event) + + monkeypatch.setattr(EventBus, "emit", emit_with_observer) + config = tmp_path / "team.yaml" + config.write_text( + "entry: auditor\nroles:\n auditor:\n" + " prompt: Report the intake audit.\n tools: [submit]\n", + encoding="utf-8", + ) + app = OpenCollab(tmp_path, config=transport, **provider) + artifacts = tmp_path / "artifacts" + turn = asyncio.create_task(app.team( + "Audit intake records.", config=config, artifacts=artifacts, + trace=False, use_worktrees=False, budget=50_000, timeout=2, cleanup_timeout=2, + )) + await asyncio.wait_for(entered.wait(), 2) + result = await asyncio.wait_for(turn, 4) + assert (result.status, result.reason, result.output, result.tokens) == ( + "stopped", "timeout", summary, 5, + ) + path, = artifacts.glob("agent_0_*.json") + else: + original = build_session( + agent=agent(), env=environment, event_sink=EventBus(observe), + auto_save_path=str(path), max_budget_tokens=50_000, + ) + await original.add_user_message("Audit intake records.") + turn = asyncio.create_task(original.run_loop()) + if scene == "completed": + assert await asyncio.wait_for(turn, 3) == summary + else: + await asyncio.wait_for(entered.wait(), 10) + assert original.state.submitted_summary == (summary if scene == "cancel" else None) + turn.cancel() + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(turn, 3) + await original.aclose() + + saved = OpenCollab.read_session_snapshot(path) + saved_state = saved["session_state"] + expected_count = int(scene != "before_submit") + assert saved_state["used_tokens"] == 5 + assert saved_state["phase"] == ("done" if scene == "completed" else "stopped") + for source in (path, path, recovered_path): + restored = load_session( + str(source), agent=agent(), env=environment, + auto_save_path=str(recovered_path), max_budget_tokens=50_000, + ) + assert restored.used_tokens == 5 + assert restored.phase.value == saved_state["phase"] + assert restored.state.terminal_reason == saved_state["terminal_reason"] + assert restored.messages.count(answer) == expected_count + await restored.aclose() + + restored = load_session( + str(recovered_path), agent=agent(), env=environment, + auto_save_path=str(recovered_path), max_budget_tokens=50_000, + ) + await restored.add_user_message("Recall the intake audit.") + assert await restored.run_loop() == "Follow-up complete." + assert restored.used_tokens == 20 + assert len(requests) == 2 + assert requests[-1].count(answer) == expected_count + results = [row for row in requests[-1] if row["role"] == "tool"] + assert [row["tool_call_id"] for row in results] == ["submission"] + if expected_count: + assert results[0]["content"] == "Submitted. Your turn ends here." + assert requests[-1][-3:-1] == [results[0], answer] + else: + assert "interrupted by session cancellation" in results[0]["content"] + ledger = [json.loads(line)["usage"]["total_tokens"] for line in usage_path.read_text().splitlines()] + assert ledger == [5, 15] + finally: + release.set() + if turn is not None and not turn.done(): + turn.cancel() + await asyncio.gather(turn, return_exceptions=True) + if original is not None: + await original.aclose() + if restored is not None: + await restored.aclose() + await environment.cleanup() diff --git a/tests/runtime/test_summary_client_close_accounting.py b/tests/runtime/test_summary_client_close_accounting.py index f5d23e0f..dd61bb43 100644 --- a/tests/runtime/test_summary_client_close_accounting.py +++ b/tests/runtime/test_summary_client_close_accounting.py @@ -40,6 +40,7 @@ async def close(self): session = build_session(agent=Agent(name="close-window", system_prompt="system"), llm_timeout=deadline, tracer=tracer) session.messages = history() + session.state.set_context_tokens(23) async def scenario(): owner = asyncio.create_task(session.run_loop()) @@ -67,6 +68,7 @@ async def wait_for_summary_client(): asyncio.run(scenario()) assert session.used_tokens == 7_600 + assert session.state.context_tokens == 23 assert session.runner.late_provider_usage == () assert session.pending_cleanup_tasks == () assert clients[1].close_exited is True @@ -75,6 +77,7 @@ async def wait_for_summary_client(): assert len(calls) == 1 assert calls[0]["tokens"] == 7_600 assert calls[0]["payload"]["purpose"] == "summary" + assert not calls[0]["payload"].get("late") def test_returned_summary_usage_survives_owned_client_close_failure(monkeypatch): clients = [] diff --git a/tests/runtime/test_vm_isolation.py b/tests/runtime/test_vm_isolation.py index 488e3658..32a4ea06 100644 --- a/tests/runtime/test_vm_isolation.py +++ b/tests/runtime/test_vm_isolation.py @@ -293,6 +293,83 @@ async def test_reset_failure_retains_lease_and_restores_guest_before_next_claim( assert await _VMLeases(database, [resource], 0).acquire("next") == resource +async def test_scoped_session_release_retries_failed_reset_and_returns_capacity(tmp_path, local_vm): + source = tmp_path / "source" + _repository(source) + marker, ready = tmp_path / "guest-marker", tmp_path / "reset-ready" + marker.write_text("dirty") + resource = _resource(tmp_path / "guest", reset_command=f"test -f '{ready}' && rm -f '{marker}'") + database = str(tmp_path / "leases.sqlite") + provider = vm_isolation_provider([resource], lease_database=database, scope="session") + pool = SessionEnvironmentPool( + str(source), isolation="vm-session", providers={"vm-session": provider}, + owned_save_dir=str(tmp_path / "results"), + ) + + def lease_count(): + with sqlite3.connect(database) as connection: + return connection.execute("SELECT count(*) FROM vm_leases").fetchone()[0] + + try: + environment = await pool.acquire("worker") + await environment.exec_cmd("printf recorded > answer.txt") + export = Path(environment.export_directory) + with pytest.raises(RuntimeError, match="VM guest reset"): + await pool.release_env(environment) + assert marker.exists() and lease_count() == 1 + with pytest.raises(VMCapacityError, match="capacity exhausted"): + await pool.acquire("too-early") + + ready.touch() + await pool.release_env(environment) + assert not marker.exists() and lease_count() == 0 + replacement = await pool.acquire("next-role") + assert replacement.resource_id == resource.resource_id + await pool.release_env(replacement) + assert lease_count() == 0 + assert (export / "answer.txt").read_text() == "recorded" + finally: + ready.touch() + await pool.release() + + +async def test_failed_vm_reset_still_returns_an_independent_guest(tmp_path, local_vm): + source = tmp_path / "source" + _repository(source) + ready = tmp_path / "reset-ready" + resources = [ + _resource(tmp_path / "healthy", "healthy"), + _resource(tmp_path / "recovering", "recovering", reset_command=f"test -f '{ready}'"), + ] + database = str(tmp_path / "leases.sqlite") + provider = vm_isolation_provider(resources, lease_database=database, scope="session") + pool = SessionEnvironmentPool( + str(source), isolation="vm-session", providers={"vm-session": provider}, + owned_save_dir=str(tmp_path / "results"), + ) + registry = _VMLeases(database, resources, 0) + try: + first = await pool.acquire("report-first") + second = await pool.acquire("report-second") + assert (await first.exec_cmd("printf first > answer.txt")).returncode == 0 + assert (await second.exec_cmd("printf second > answer.txt")).returncode == 0 + + with pytest.raises(RuntimeError, match="VM guest reset"): + await pool.release() + with sqlite3.connect(database) as connection: + assert connection.execute("SELECT resource_id FROM vm_leases").fetchall() == [("recovering",)] + for environment, text in ((first, "first"), (second, "second")): + assert (Path(environment.export_directory) / "answer.txt").read_text() == text + replacement = await registry.acquire("new-run") + assert replacement == resources[0] + registry.release(replacement, "new-run") + finally: + ready.touch() + await pool.release() + with sqlite3.connect(database) as connection: + assert not connection.execute("SELECT 1 FROM vm_leases").fetchall() + + async def test_release_interrupts_configured_capacity_wait(tmp_path, local_vm): resource = _resource(tmp_path / "guest") database = str(tmp_path / "leases.sqlite") @@ -307,6 +384,61 @@ async def test_release_interrupts_configured_capacity_wait(tmp_path, local_vm): registry.release(resource, "outer") +@pytest.mark.parametrize("owns_vm", [False, True], ids=["another-controller", "same-pool"]) +async def test_session_pool_release_interrupts_capacity_wait(tmp_path, local_vm, monkeypatch, owns_vm): + source = tmp_path / "source" + _repository(source) + resource = _resource(tmp_path / "guest") + database = str(tmp_path / "leases.sqlite") + registry = _VMLeases(database, [resource], 0) + provider = vm_isolation_provider([resource], lease_database=database, scope="session", wait_timeout=None) + pool = SessionEnvironmentPool( + str(source), isolation="vm-session", providers={"vm-session": provider}, + owned_save_dir=str(tmp_path / "results"), + ) + if owns_vm: + active = await pool.acquire("first") + await active.exec_cmd("printf recorded > answer.txt") + else: + await registry.acquire("other-controller") + + attempted = asyncio.Event() + real_acquire = _VMLeases._try_acquire + + def observe_acquire(leases, owner): + result = real_acquire(leases, owner) + assert result is None + attempted.set() + return result + + monkeypatch.setattr(_VMLeases, "_try_acquire", observe_acquire) + waiting = asyncio.create_task(pool.acquire("waiting")) + closing = None + try: + await asyncio.wait_for(attempted.wait(), 5) + closing = asyncio.create_task(pool.release()) + done, _ = await asyncio.wait({closing}, timeout=5) + assert closing in done + await closing + with pytest.raises(RuntimeError, match="closed"): + await waiting + expected = [] if owns_vm else [("other-controller",)] + with sqlite3.connect(database) as connection: + assert connection.execute("SELECT owner FROM vm_leases").fetchall() == expected + if owns_vm: + assert (Path(active.export_directory) / "answer.txt").read_text() == "recorded" + finally: + if not waiting.done(): + waiting.cancel() + await asyncio.gather(waiting, return_exceptions=True) + if closing is not None: + await closing + else: + await pool.release() + if not owns_vm: + registry.release(resource, "other-controller") + + async def test_sessions_prepare_independently_and_release_capacity_to_waiters(tmp_path, local_vm, monkeypatch): source = tmp_path / "source" _repository(source) diff --git a/tests/support/workflow_context_test_support.py b/tests/support/workflow_context_test_support.py index 78b2122d..7bad9c2c 100644 --- a/tests/support/workflow_context_test_support.py +++ b/tests/support/workflow_context_test_support.py @@ -6,9 +6,22 @@ from collections.abc import Awaitable, Callable, Sequence from typing import Any +from opencollab.application.session import Session from opencollab.domain.session import TurnEnforcementState +def reserve_request_tokens_until(monkeypatch, prompt: str, tokens: int, released: asyncio.Event) -> None: + """Temporarily reduce request capacity inside an already granted session allowance.""" + add_user_message = Session.add_user_message + + async def add_with_reservation(session: Session, content: str) -> None: + if content == prompt: + session.runner.budget_reservations.append(lambda: 0 if released.is_set() else tokens) + await add_user_message(session, content) + + monkeypatch.setattr(Session, "add_user_message", add_with_reservation) + + class FakeState: def __init__(self, aid: int = -1) -> None: self.messages: list[dict[str, Any]] = [] diff --git a/tests/tools/test_docker_text_encoding.py b/tests/tools/test_docker_text_encoding.py index cbf6ad7a..1fbe0ea9 100644 --- a/tests/tools/test_docker_text_encoding.py +++ b/tests/tools/test_docker_text_encoding.py @@ -265,6 +265,25 @@ async def test_docker_partial_later_line_is_read_again_before_character_truncati assert "offset=3" not in second assert "�" not in first + second +async def test_docker_character_cut_links_to_rows_beyond_the_captured_prefix(tmp_path, docker_runtime): + runtime, calls = docker_runtime + target = tmp_path / "long-page.txt" + content = ("😀" * 500 + "\r\n\u6458\u8981\r\n\u7ed3\u8bba").encode("utf-8") + target.write_bytes(content) + tool = FileReadTool(max_read_chars=100) + + first = await tool.execute_with_runtime({"path": str(target), "limit": 1}, runtime) + continuation = re.search(r"Continue with offset=(\d+)", first) + assert "line 1 was character-truncated" in first + assert continuation is not None + second = await tool.execute_with_runtime( + {"path": str(target), "offset": int(continuation.group(1)), "limit": 2}, runtime, + ) + + assert second.split("\n")[1:] == ["2\t\u6458\u8981", "3\t\u7ed3\u8bba"] + assert sum("head -c" in call["command"] for call in calls) == 2 + assert target.read_bytes() == content + async def test_docker_file_read_rejects_incomplete_utf8_at_file_end( tmp_path, docker_runtime, ): diff --git a/tests/tools/test_file_read_continuation.py b/tests/tools/test_file_read_continuation.py index 20167cc1..01e1e473 100644 --- a/tests/tools/test_file_read_continuation.py +++ b/tests/tools/test_file_read_continuation.py @@ -59,8 +59,9 @@ def _displayed_body(result): footer = re.search(r"\n\.\.\. (?:line \d+ was|(?:\d+ )?more lines below)", body) return body[:footer.start()] if footer else body -def test_long_single_line_read_explains_character_cut_without_next_line(tmp_path): - (tmp_path / "minified.js").write_text("x" * 200, encoding="utf-8") +@pytest.mark.parametrize("ending", ["", "\r\n"]) +def test_long_single_line_read_explains_character_cut_without_next_line(tmp_path, ending): + (tmp_path / "minified.js").write_bytes(("x" * 200 + ending).encode("utf-8")) runtime = ToolRuntime(environment=LocalEnvironment(str(tmp_path)), safety_policy=None, permission_policy=None) result = asyncio.run(FileReadTool(max_read_chars=100).execute_with_runtime({"path": "minified.js"}, runtime)) @@ -70,6 +71,49 @@ def test_long_single_line_read_explains_character_cut_without_next_line(tmp_path assert "more lines below" not in result assert "offset=2" not in result +@pytest.mark.parametrize("backend", ["local", "default_range", "read_file_only"]) +async def test_truncated_line_still_links_to_later_rows(tmp_path, backend): + lines = ["résumé" * 5_100, "\u7ed3\u679c \u2028\u6b63\u6587", "\u7ed3\u8bba"] + runtime = _runtime(tmp_path, "\r\n".join(lines), backend) + tool = FileReadTool() + received = [] + offset = 1 + try: + for _ in range(3): + page = await tool.execute_with_runtime( + {"path": "source.txt", "offset": offset, "limit": 1}, runtime, + ) + if offset == 1: + assert "line 1 was character-truncated" in page + assert len(_displayed_body(page)) <= tool.max_read_chars + else: + assert "character-truncated" not in page + received.append(page.split("\n")[1]) + continuation = re.search(r"Continue with offset=(\d+)", page) + if continuation is None: + break + offset = int(continuation.group(1)) + assert continuation is None + assert received == ["2\t\u7ed3\u679c \u2028\u6b63\u6587", "3\t\u7ed3\u8bba"] + finally: + await _cleanup(runtime) + +@pytest.mark.parametrize("ending", ["", "\n"]) +async def test_conditional_offset_at_eof_reports_no_rows(tmp_path, ending): + runtime = _runtime(tmp_path, "x" * 150_000 + ending, "local") + tool = FileReadTool(max_read_chars=80) + try: + first = await tool.execute_with_runtime({"path": "source.txt", "limit": 1}, runtime) + assert "character-truncated" in first + continuation = re.search(r"Continue with offset=(\d+)", first) + assert continuation is not None + follow = await tool.execute_with_runtime( + {"path": "source.txt", "offset": int(continuation.group(1)), "limit": 1}, runtime, + ) + assert follow == "File: source.txt (1 lines total, no lines at or after offset 2)" + finally: + await _cleanup(runtime) + def test_complete_line_window_keeps_working_line_pagination(tmp_path): (tmp_path / "lines.txt").write_text("first\nsecond\nthird\n", encoding="utf-8") runtime = ToolRuntime(environment=LocalEnvironment(str(tmp_path)), safety_policy=None, permission_policy=None) diff --git a/tests/tools/test_tool_execution_use_case.py b/tests/tools/test_tool_execution_use_case.py index a33ace3f..33658bf1 100644 --- a/tests/tools/test_tool_execution_use_case.py +++ b/tests/tools/test_tool_execution_use_case.py @@ -291,11 +291,13 @@ def test_tool_execution_use_case_handles_non_string_and_preparsed_arguments(): use_case, _ = build_use_case(agent=FakeAgent(tools=[tool])) invalid = run(use_case.process([tool_call(arguments=7)])) + nonfinite = run(use_case.process([tool_call(arguments={"sample": [float("nan")]})])) valid = run(use_case.process([tool_call(arguments={"value": 1})])) assert "must be a JSON object" in invalid.messages_to_append[0]["content"] + assert "invalid JSON arguments" in nonfinite.messages_to_append[0]["content"] assert valid.messages_to_append[0]["content"] == "runtime result" - assert tool.runtime_calls[0][0] == {"value": 1} + assert [call[0] for call in tool.runtime_calls] == [{"value": 1}] def test_terminal_structured_output_skips_later_side_effect_and_answers_every_call(): terminal = StructuredOutputTool( diff --git a/tests/workflows/test_builtin_workflow_discovery.py b/tests/workflows/test_builtin_workflow_discovery.py index 70678b97..c3ae1182 100644 --- a/tests/workflows/test_builtin_workflow_discovery.py +++ b/tests/workflows/test_builtin_workflow_discovery.py @@ -78,7 +78,7 @@ def test_cli_runs_installed_workflow_and_forwards_agent_profile(tmp_path, monkey async def run(spec, args, **kwargs): captured.update(spec=spec, args=args, **kwargs) - return SimpleNamespace(output={"status": "done"}, stop_reason=None) + return SimpleNamespace(output=kwargs["format_output"]({"status": "done"}), stop_reason=None) monkeypatch.setattr(workflow_cli, "run_workflow", run) result = CliRunner().invoke( diff --git a/tests/workflows/test_candidate_adoption_revision.py b/tests/workflows/test_candidate_adoption_revision.py new file mode 100644 index 00000000..8632ac23 --- /dev/null +++ b/tests/workflows/test_candidate_adoption_revision.py @@ -0,0 +1,139 @@ +from __future__ import annotations + +import asyncio +import shlex +import subprocess +import sys +from pathlib import Path + +import pytest + +from opencollab import OpenCollab +from opencollab.adapters.env import LocalEnvironment +from opencollab.application.workflow_candidates import CandidateAdoptionRecoveryError, CandidateWorkspaceTrackingError +from opencollab.tools import builtin_tools +from tests.workflows.test_workflow_candidate_workspace import _git + + +def _inventory(repo): + return int(subprocess.run( + [sys.executable, "-B", "inventory.py"], cwd=repo, capture_output=True, text=True, check=True, + ).stdout) + + +def _worktrees(repo): + return [line for line in _git(repo, "worktree", "list", "--porcelain").splitlines() if line.startswith("worktree ")] + + +class _PausedPublication(LocalEnvironment): + def __init__(self, workspace, command, *, no_hardlinks=False): + super().__init__(str(workspace)) + self.command = command + self.paused = asyncio.Event() + self.resume = asyncio.Event() + self.applied = False + self.no_hardlinks = no_hardlinks + self.activation_needed = False + + async def exec_cmd(self, command, timeout=120.0, **kwargs): + if self.no_hardlinks and "hold_original() {" in command: + command = "ln() { return 1; }; " + command + result = await super().exec_cmd(command, timeout, **kwargs) + self.activation_needed |= "activate-originals" in result.stdout.splitlines() + if " apply --binary " in command: + self.applied = True + if self.command in command and not self.paused.is_set(): + assert result.returncode == 0 + self.paused.set() + await self.resume.wait() + return result + + +@pytest.mark.parametrize("event", [ + "nonconflicting-edit", "after-check", "after-check-no-links", "after-apply", "overlapping-edit", +]) +async def test_candidate_adoption_checks_source_revision_around_git_apply(tmp_path, event): + repo = tmp_path / "source" + repo.mkdir() + source = repo / "inventory.py" + original = "from pathlib import Path\nprice = int(Path('price.txt').read_text())\nprint(price * 1)\n" + proposed = original.replace("* 1", "* 6") + source.write_text(original) + (repo / "price.txt").write_text("7\n") + (repo / "notes.txt").write_text("Original notes\n") + _git(repo, "init", "-qb", "main") + _git(repo, "add", ".") + _git(repo, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "-c", + "commit.gpgsign=false", "commit", "-qm", "Prepare inventory") + _git(repo, "switch", "-qc", "other-market") + (repo / "price.txt").write_text("11\n") + _git(repo, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "-c", + "commit.gpgsign=false", "commit", "-qam", "Change market price") + _git(repo, "switch", "-q", "main") + worktrees = _worktrees(repo) + write, bash = builtin_tools("file_write", "bash", headless=False) + before_apply = event.startswith("after-check") + owner = _PausedPublication( + repo, " apply --check --binary " if before_apply else " apply --binary ", + no_hardlinks=event == "after-check-no-links", + ) + caller_index = None + caller_inode = None + + async def edit(child, _inputs): + await child.execute_verification(write, {"path": source.name, "mode": "create", "content": proposed}) + command = shlex.join((sys.executable, "-B", source.name)) + output = await child.execute_verification(bash, {"command": command}) + assert "42" in output + assert _inventory(Path(child.workspace_root)) == 42 + return "inventory verified" + + async def run(ctx, inputs): + nonlocal caller_index, caller_inode + candidate = await ctx.candidate_workflow(edit, inputs, label="inventory") + assert candidate.output == "inventory verified" + assert "+print(price * 6)" in candidate.diff + adoption = asyncio.create_task(ctx.adopt_candidate(candidate)) + try: + await asyncio.wait_for(owner.paused.wait(), 10) + if event != "nonconflicting-edit": + _git(repo, "switch", "-q", "other-market") + if event == "overlapping-edit": + source.write_text(original.replace("* 1", "* 8")) + (repo / "notes.txt").write_text("User notes\n") + _git(repo, "add", "notes.txt") + caller_index = (repo / ".git/index").read_bytes() + caller_inode = source.stat().st_ino + finally: + owner.resume.set() + await adoption + return candidate.output + + try: + result = await OpenCollab(repo, model="offline", environment=owner).workflow( + run, trace=False, limit_mode="explicit", budget=10_000, timeout=60, + ) + assert caller_index is not None + assert (repo / ".git/index").read_bytes() == caller_index + assert _git(repo, "show", ":notes.txt") == "User notes\n" + assert _worktrees(repo) == worktrees + if event == "nonconflicting-edit": + assert result.ok and result.output == "inventory verified" + assert _git(repo, "branch", "--show-current").strip() == "main" + assert _inventory(repo) == 42 + else: + assert result.status == "failed" + assert _git(repo, "branch", "--show-current").strip() == "other-market" + if event == "overlapping-edit": + assert isinstance(result.error, CandidateAdoptionRecoveryError) + assert "original files retained" in str(result.error) + assert _inventory(repo) == 88 + else: + assert isinstance(result.error, CandidateWorkspaceTrackingError) + assert _inventory(repo) == 11 + assert owner.applied != before_apply + if event == "after-check-no-links": + assert owner.activation_needed + assert source.stat().st_ino == caller_inode + finally: + await owner.cleanup() diff --git a/tests/workflows/test_candidate_case_spelling.py b/tests/workflows/test_candidate_case_spelling.py new file mode 100644 index 00000000..8b671b54 --- /dev/null +++ b/tests/workflows/test_candidate_case_spelling.py @@ -0,0 +1,485 @@ +from __future__ import annotations + +import asyncio +import json +import shlex +import subprocess +import sys +from pathlib import Path +from unicodedata import normalize + +import pytest + +from opencollab import OpenCollab +from opencollab.adapters.env import LocalEnvironment, WorktreeEnvironment +from opencollab.adapters.worktree_pool import WorktreePool +from opencollab.application.scheduler import Scheduler +from opencollab.application.workflow_candidates import CandidateAdoptionRecoveryError, CandidateWorkspaceTrackingError +from opencollab.patches import patch_paths +from tests.support.provider_sdk_http import completion_http_response, http_response, install_sdk_transport +from tests.workflows.test_workflow_candidate_workspace import _git + +_TEXT = "original value\n" + "".join(f"unchanged line {index}\n" for index in range(10)) + "original tail\n" + + +def _exact(repo: Path, path: str) -> bool: + for part in Path(path).parts: + if not repo.is_dir() or part not in {entry.name for entry in repo.iterdir()}: + return False + repo /= part + return True + + +def _repository( + tmp_path: Path, name: str, content: bytes, *, ignored: str = "", symlink: bool = False, crlf: bool = False, +) -> Path: + repo = tmp_path / "repo" + repo.mkdir() + _git(repo, "init", "-qb", "main") + _git(repo, "config", "user.name", "Fixture") + _git(repo, "config", "user.email", "fixture@example.invalid") + source = repo / name + source.parent.mkdir(exist_ok=True, parents=True) + if symlink: + source.symlink_to("missing.txt") + else: + source.write_bytes(content) + (repo / ".gitignore").write_text(f"/{ignored}\n" if ignored else "") + if crlf: + (repo / ".gitattributes").write_text("*.data text eol=crlf\n") + (repo / "inventory.txt").write_text("7\n") + (repo / "notes.txt").write_text("original notes\n") + _git(repo, "add", ".") + _git(repo, "add", "--force", "--", name) + _git(repo, "-c", "commit.gpgsign=false", "commit", "-qm", "Prepare case spelling fixture") + return repo + + +@pytest.mark.parametrize("old,new,form", [ + ("Record.txt", "record.txt", "pure"), + ("record.txt", "Record.txt", "pure"), + ("Record.txt", "record.txt", "edited"), + ("record.txt", "Record.txt", "edited"), + ("Record.txt", "record.txt", "ignored"), + ("record.txt", "Record.txt", "binary"), + ("Record.txt", "record.txt", "symlink"), + ("Inventory/Inner/Record.txt", "inventory/inner/RECORD.txt", "directory"), + ("Inventory/Inner/Record.txt", "inventory/inner/RECORD.txt", "preserved"), + ("Inventory.data", "inventory.data", "crlf"), + ("État.txt", "état.txt", "unicode"), + ("E\u0301tat.txt", "e\u0301tat.txt", "decomposed"), + ("Record.txt", "record.txt", "ignorecase-disabled"), +]) +async def test_candidate_adopts_exact_case_spelling(tmp_path, old, new, form): + original = bytes(range(256)) if form == "binary" else _TEXT.encode() + if form == "crlf": + original = original.replace(b"\n", b"\r\n") + repo = _repository(tmp_path, old, original, ignored=new if form == "ignored" else "", + symlink=form == "symlink", crlf=form == "crlf") + case_insensitive = (repo / new).exists() + if form == "ignorecase-disabled": + _git(repo, "config", "core.ignorecase", "false") + original_worktrees = _git(repo, "worktree", "list", "--porcelain") + (repo / "notes.txt").write_text("staged notes\n") + _git(repo, "add", "notes.txt") + (repo / "notes.txt").write_text("unstaged notes\n") + index = (repo / ".git/index").read_bytes() + nested = form in {"directory", "preserved"} + late_directory_file = str(Path(old).with_name("user draft.txt")) if nested else None + expected = ( + original.replace(b"original value", b"candidate value") if nested or form in {"edited", "crlf"} + else original[::-1] if form == "binary" else original + ) + + async def edit(child, _inputs): + workspace = Path(child.workspace_root) + if nested: + (workspace / "Inventory").rename(workspace / "inventory") + (workspace / "inventory/Inner").rename(workspace / "inventory/inner") + (workspace / "inventory/inner/Record.txt").rename(workspace / new) + elif form in {"unicode", "decomposed", "ignorecase-disabled"} or (form == "ignored" and case_insensitive): + (workspace / old).rename(workspace / new) + else: + _git(workspace, "mv", "--", old, new) + if form != "symlink": + (workspace / new).write_bytes(expected) + (workspace / "inventory.txt").write_text("42\n") + return "candidate verified" + + async def run(ctx, inputs): + candidate = await ctx.candidate_workflow(edit, inputs, label="case spelling") + assert candidate.output == "candidate verified", candidate.lifecycle_errors + paths = set(patch_paths(candidate.effective_diff)) + if form == "decomposed": + assert {normalize("NFC", old), normalize("NFC", new)} <= {normalize("NFC", path) for path in paths} + else: + assert {old, new} <= paths + if form == "edited": + (repo / old).write_text(_TEXT.replace("original tail", "user tail")) + if late_directory_file: + (repo / late_directory_file).write_text("late user file\n") + await ctx.adopt_candidate(candidate, preserve_paths=[late_directory_file] if form == "preserved" else ()) + return candidate.output + + result = await OpenCollab(repo, model="offline").workflow( + run, trace=False, limit_mode="explicit", budget=10_000, timeout=120, + ) + if form == "preserved" and case_insensitive: + assert isinstance(result.error, ValueError) + assert "overlaps a preserved path" in str(result.error) + assert _exact(repo, old) and not _exact(repo, new) + assert (repo / old).read_bytes() == original + assert (repo / "inventory.txt").read_text() == "7\n" + assert (repo / late_directory_file).read_text() == "late user file\n" + assert (repo / ".git/index").read_bytes() == index + assert _git(repo, "worktree", "list", "--porcelain") == original_worktrees + return + assert result.ok, (result.error, getattr(result.error, "__cause__", None)) + if form == "decomposed" and not case_insensitive: + names = {normalize("NFC", path.name) for path in repo.iterdir()} + assert normalize("NFC", new) in names and normalize("NFC", old) not in names + else: + assert _exact(repo, new) and not _exact(repo, old) + assert (repo / "inventory.txt").read_text() == "42\n" + assert (repo / "notes.txt").read_text() == "unstaged notes\n" + assert _git(repo, "show", ":notes.txt") == "staged notes\n" + assert (repo / ".git/index").read_bytes() == index + assert _git(repo, "worktree", "list", "--porcelain") == original_worktrees + if form == "symlink": + assert (repo / new).readlink() == Path("missing.txt") + elif form == "edited": + assert (repo / new).read_bytes() == expected.replace(b"original tail", b"user tail") + else: + assert (repo / new).read_bytes() == expected + if late_directory_file: + user_file = (repo / new).with_name("user draft.txt") if case_insensitive else repo / late_directory_file + assert user_file.read_text() == "late user file\n" + + +class _SwitchAfterRename(LocalEnvironment): + def __init__(self, repo: Path, destination: str, edit: bool): + super().__init__(str(repo)) + self.repo = repo + self.destination = destination + self.edit = edit + self.switched = False + self.caller_index: bytes | None = None + + async def exec_cmd(self, command, timeout=120.0, **kwargs): + read_revision = f"git -C {shlex.quote(str(self.repo))} rev-parse --verify HEAD" + if command == read_revision and not self.switched and _exact(self.repo, self.destination): + _git(self.repo, "switch", "-q", "other") + (self.repo / "independent.txt").write_text("keep user work\n") + if self.edit: + (self.repo / self.destination).write_text("late independent edit\n") + self.switched = True + self.caller_index = (self.repo / ".git/index").read_bytes() + return await super().exec_cmd(command, timeout, **kwargs) + + +@pytest.mark.parametrize("old,new,edit", [ + ("Record.txt", "record.txt", False), + ("record.txt", "Record.txt", False), + ("Inventory/Record.txt", "inventory/RECORD.txt", False), + ("Record.txt", "record.txt", True), + ("E\u0301tat.txt", "e\u0301tat.txt", False), +]) +async def test_case_rename_recovery_after_source_revision_change(tmp_path, old, new, edit): + repo = _repository(tmp_path, old, _TEXT.encode()) + if not (repo / new).exists(): + pytest.skip("case-insensitive directory entries are required") + _git(repo, "switch", "-qc", "other") + (repo / "market.txt").write_text("11\n") + _git(repo, "add", "market.txt") + _git(repo, "-c", "commit.gpgsign=false", "commit", "-qm", "Change market") + _git(repo, "switch", "-q", "main") + owner = _SwitchAfterRename(repo, new, edit) + worktrees = _git(repo, "worktree", "list", "--porcelain") + inode = (repo / old).stat().st_ino + + async def modify(child, _inputs): + worktree = Path(child.workspace_root) + if "/" in old: + (worktree / "Inventory").rename(worktree / "inventory") + (worktree / "inventory/Record.txt").rename(worktree / new) + elif not old.isascii(): + (worktree / old).rename(worktree / new) + else: + _git(worktree, "mv", "--", old, new) + (worktree / "inventory.txt").write_text("42\n") + return "candidate verified" + + async def run(ctx, inputs): + candidate = await ctx.candidate_workflow(modify, inputs, label="case spelling") + assert candidate.output == "candidate verified", candidate.lifecycle_errors + await ctx.adopt_candidate(candidate) + + try: + with (repo / old).open("a") as original_handle: + result = await OpenCollab(repo, model="offline", environment=owner).workflow( + run, trace=False, limit_mode="explicit", budget=10_000, timeout=120, + ) + assert owner.switched + assert _git(repo, "worktree", "list", "--porcelain").splitlines()[0] == worktrees.splitlines()[0] + assert _git(repo, "worktree", "list", "--porcelain").count("worktree ") == 1 + assert (repo / ".git/index").read_bytes() == owner.caller_index + assert (repo / "inventory.txt").read_text() == "7\n" + assert (repo / "independent.txt").read_text() == "keep user work\n" + assert _git(repo, "branch", "--show-current").strip() == "other" + if edit: + assert isinstance(result.error, CandidateAdoptionRecoveryError) + assert (repo / new).read_text() == "late independent edit\n" + else: + assert isinstance(result.error, CandidateWorkspaceTrackingError), result.error + assert _exact(repo, old) and not _exact(repo, new) + assert (repo / old).stat().st_ino == inode + original_handle.write("write after rollback\n") + original_handle.flush() + assert (repo / old).read_text() == _TEXT + "write after rollback\n" + finally: + await owner.cleanup() + + +class _LostCaseResult(LocalEnvironment): + def __init__(self, repo: Path, destination: str, operation: str): + super().__init__(str(repo)) + self.repo = repo + self.destination = destination + self.operation = operation + self.lost_result = False + + async def exec_cmd(self, command, timeout=120.0, **kwargs): + result = await super().exec_cmd(command, timeout, **kwargs) + if self.operation == "rename": + matches = 'mv -f -- "$source" "$target"' in command + else: + matches = command.startswith("rm -rf -- ") and ".candidate-case-publication-" in command + if ( + matches and result.returncode == 0 and not self.lost_result and _exact(self.repo, self.destination) + ): + self.lost_result = True + raise RuntimeError(f"{self.operation} response lost") + return result + + +@pytest.mark.parametrize("operation", ["rename", "cleanup"]) +async def test_case_rename_reports_actual_result_when_a_response_is_lost(tmp_path, operation): + old, new = "Record.txt", "record.txt" + repo = _repository(tmp_path, old, _TEXT.encode()) + if not (repo / new).exists(): + pytest.skip("case-insensitive directory entries are required") + owner = _LostCaseResult(repo, new, operation) + index = (repo / ".git/index").read_bytes() + original_worktrees = _git(repo, "worktree", "list", "--porcelain") + inode = (repo / old).stat().st_ino + + async def edit(child, _inputs): + worktree = Path(child.workspace_root) + _git(worktree, "mv", "--", old, new) + (worktree / "inventory.txt").write_text("42\n") + return "candidate verified" + + async def run(ctx, inputs): + candidate = await ctx.candidate_workflow(edit, inputs, label="case spelling") + assert candidate.output == "candidate verified", candidate.lifecycle_errors + await ctx.adopt_candidate(candidate) + + try: + result = await OpenCollab(repo, model="offline", environment=owner).workflow( + run, trace=False, limit_mode="explicit", budget=10_000, timeout=120, + ) + assert owner.lost_result + if operation == "rename": + assert (result.status, str(result.error)) == ("failed", "rename response lost") + expected, removed, inventory = old, new, "7\n" + else: + assert result.ok, result.error + expected, removed, inventory = new, old, "42\n" + assert _exact(repo, expected) and not _exact(repo, removed) + assert (repo / expected).stat().st_ino == inode + assert (repo / expected).read_text() == _TEXT + assert (repo / "inventory.txt").read_text() == inventory + assert (repo / ".git/index").read_bytes() == index + assert _git(repo, "worktree", "list", "--porcelain") == original_worktrees + finally: + await owner.cleanup() + + +async def test_worktree_captures_physical_case_rename(tmp_path): + old, new = "Record.data", "record.data" + original = _TEXT.encode().replace(b"\n", b"\r\n") + repo = _repository(tmp_path, old, original, crlf=True) + index = (repo / ".git/index").read_bytes() + environment = WorktreeEnvironment(str(repo), branch_name="case-spelling-capture") + await environment.setup() + try: + worktree = Path(environment.workspace) + _git(worktree, "mv", "--", old, new) + (worktree / new).write_bytes(original.replace(b"original value", b"candidate value")) + patch = await environment.get_diff() + assert {old, new} <= set(patch_paths(patch)) + assert "+candidate value\r\n" in patch + assert _exact(worktree, new) and not _exact(worktree, old) + assert _exact(repo, old) and (repo / old).read_bytes() == original + assert (repo / ".git/index").read_bytes() == index + finally: + await environment.cleanup() + assert not worktree.exists() + + +async def test_directory_copy_delivers_case_rename(tmp_path): + source = tmp_path / "plain" + source.mkdir() + old, new = "Record.txt", "record.txt" + (source / old).write_text(_TEXT) + (source / "inventory.txt").write_text("7\n") + pool = WorktreePool(str(source), use_worktrees=True, enable_adoption=True) + candidate = await pool.acquire("coder") + try: + worktree = Path(candidate.workspace) + (worktree / old).rename(worktree / new) + candidate_text = _TEXT.replace("original value", "candidate value") + (worktree / new).write_text(candidate_text) + (worktree / "inventory.txt").write_text("42\n") + patch = await candidate.get_diff() + assert {old, new} <= set(patch_paths(patch)) + await pool.adopt(patch) + assert _exact(source, new) and not _exact(source, old) + assert (source / new).read_text() == candidate_text + assert (source / "inventory.txt").read_text() == "42\n" + assert not (source / ".git").exists() + finally: + await pool.release() + assert not worktree.exists() + + +@pytest.mark.parametrize(("change", "old", "new"), [ + ("unstaged", "Report.sh", "report.sh"), + ("staged", "Report.sh", "report.sh"), + ("staged-addition", "Report.sh", "report.sh"), + ("staged-directory", "Reports/Report.sh", "reports/Report.sh"), +]) +async def test_team_adopts_exact_candidate_spelling(tmp_path, monkeypatch, change, old, new): + addition = change.startswith("staged-") + script = b"#!/bin/sh\nprintf '%s\\n' 42\n" + source = _repository(tmp_path, old, script) + if addition: + _git(source, "rm", old) + else: + (source / old).chmod(0o755) + _git(source, "add", old) + _git(source, "-c", "commit.gpgsign=false", "commit", "-qm", "Prepare the report fixture") + (source / "notes.txt").write_text("staged notes\n") + _git(source, "add", "notes.txt") + (source / "notes.txt").write_text("unstaged notes\n") + index = (source / ".git/index").read_bytes() + worktrees = _git(source, "worktree", "list", "--porcelain") + config = tmp_path / "team.yaml" + config.write_text("""entry: analyst +roles: + analyst: + model: fixture-analyst + prompt: Delegate and adopt the completed report. + tools: [message_agent, adopt_agent] + coder: + model: fixture-coder + prompt: Rename and execute the report. + tools: [bash] +topology: + analyst: [coder] +""") + schedulers = [] + initialize = Scheduler.__init__ + + def remember_scheduler(self, *args, **kwargs): + initialize(self, *args, **kwargs) + schedulers.append(self) + + monkeypatch.setattr(Scheduler, "__init__", remember_scheduler) + calls = {"fixture-analyst": 0, "fixture-coder": 0} + captured = [] + inspected = [] + + async def handler(request): + body = json.loads(request.content) + model = body["model"] + calls[model] += 1 + turn = calls[model] + latest = next((m["content"] for m in reversed(body["messages"]) if m["role"] == "tool"), "") + if model == "fixture-coder": + if turn == 2: + assert "REPORT_PASS" in latest, latest + workspace = Path(schedulers[0]._sessions[1].env.workspace) + index_path = Path(_git(workspace, "rev-parse", "--absolute-git-dir").rstrip("\n")) / "index" + if addition: + assert f"H {old}" in _git(workspace, "ls-files", "-v").splitlines() + assert (workspace / new).read_bytes() == script + inspected.append((index_path, index_path.read_bytes())) + return completion_http_response(request, text="Renamed and executed the report.") + rename = ( + f"subprocess.run(['git', 'mv', {old!r}, {new!r}], check=True); " + if change == "staged" else f"Path({old!r}).rename({new!r}); " + ) + if addition: + if change == "staged-directory": + rename = "Path('Reports').rename('reports'); " + rename = ( + f"Path({old!r}).parent.mkdir(exist_ok=True); " + f"Path({old!r}).write_bytes({script!r}); Path({old!r}).chmod(0o755); " + f"subprocess.run(['git', 'add', {old!r}], check=True); " + + rename + ) + probe = ( + "import subprocess; from pathlib import Path; " + rename + + "names = {path.as_posix() for path in Path('.').rglob('*')}; " + + f"assert {new!r} in names; " + + f"assert {old!r} not in names; " + + f"assert subprocess.check_output(['./{new}']).strip() == b'42'; print('REPORT_PASS')" + ) + name, args = "bash", {"command": shlex.join((sys.executable, "-B", "-c", probe))} + elif turn == 1: + name, args = "message_agent", { + "to_role": "coder", "summary": "Prepare report", "content": "Rename and execute the report.", + } + elif turn == 2: + assert "Message queued" in latest, latest + scheduler = schedulers[0] + driver = scheduler._tasks.get(1) + if driver is not None: + await asyncio.shield(driver) + index_path, original_index = inspected[0] + assert index_path.read_bytes() == original_index + captured.append(scheduler._completed_coder_diffs[1].patch) + name, args = "adopt_agent", {"aid": 1} + else: + assert "Adopted coder" in latest, latest + return completion_http_response(request, text="Delivered the report.") + return http_response(request, 200, json={ + "id": f"{model}-{turn}", "object": "chat.completion", "created": 1, "model": model, + "choices": [{"index": 0, "finish_reason": "tool_calls", "message": { + "role": "assistant", "content": None, "tool_calls": [{ + "id": f"{model}-{turn}", "type": "function", + "function": {"name": name, "arguments": json.dumps(args)}, + }], + }}], "usage": {"prompt_tokens": 2, "completion_tokens": 3, "total_tokens": 5}, + }) + + install_sdk_transport(monkeypatch, "openai", handler) + result = await OpenCollab( + source, model="fixture-analyst", base_url="https://controlled.invalid/v1", + api_key="controlled-test", config={"llm_max_retries": 0}, # pragma: allowlist secret + ).team( + "Deliver the renamed report.", config=config, prebuild_team=True, allow_unisolated_shell=True, + trace=False, timeout=30, budget=20_000, + ) + assert result.ok, (result.reason, result.error) + assert result.output == "Delivered the report." + assert calls == {"fixture-analyst": 3, "fixture-coder": 2} + expected_paths = {new} if addition else {old, new} + assert len(captured) == 1 and expected_paths == set(patch_paths(captured[0])) + assert _exact(source, new) and not _exact(source, old) + assert (source / new).read_bytes() == script + assert subprocess.check_output([f"./{new}"], cwd=source) == b"42\n" + assert (source / "notes.txt").read_text() == "unstaged notes\n" + assert (source / ".git/index").read_bytes() == index + assert _git(source, "worktree", "list", "--porcelain") == worktrees diff --git a/tests/workflows/test_candidate_source_casepaths.py b/tests/workflows/test_candidate_source_casepaths.py new file mode 100644 index 00000000..d87da108 --- /dev/null +++ b/tests/workflows/test_candidate_source_casepaths.py @@ -0,0 +1,224 @@ +"""Verify exact source path spelling through public candidate worktree creation.""" + +from pathlib import Path +from types import SimpleNamespace +from unicodedata import normalize + +import pytest + +from opencollab import OpenCollab +from opencollab.adapters.worktree_pool import WorktreePool +from opencollab.application.workflow_candidates import CandidateWorkspaceTrackingError +from opencollab.patches import patch_entries +from opencollab.tools import builtin_tools +from tests.workflows.test_candidate_workspace_submodules import _partly_initialized_source +from tests.workflows.test_workflow_candidate_workspace import _git, _repository + + +@pytest.mark.parametrize( + "staged,directory,upper,checkout", + [ + (True, False, False, "ordinary"), + (True, False, True, "ordinary"), + (False, False, False, "ordinary"), + (False, False, True, "ordinary"), + (True, True, False, "ordinary"), + (True, True, True, "ordinary"), + (False, True, False, "ordinary"), + (False, True, True, "ordinary"), + (False, False, False, "ignored"), + (True, False, False, "converted"), + (False, False, False, "converted-target"), + (True, True, False, "team"), + (False, False, True, "team"), + (True, False, False, "submodules"), + (False, False, True, "sparse-index"), + (True, False, False, "unicode"), + (False, False, False, "unicode"), + (False, False, False, "decomposed"), + (True, False, False, "ignorecase-disabled"), + (False, False, False, "ignorecase-disabled"), + (False, False, False, "staged-addition"), + (False, True, False, "staged-addition"), + (False, False, False, "team-staged-addition"), + (False, True, False, "team-staged-addition"), + ], +) +async def test_candidate_starts_with_exact_source_spelling(tmp_path, staged, directory, upper, checkout): + repo = _partly_initialized_source(tmp_path) if checkout == "submodules" else _repository(tmp_path) + old_name, new_name = ("NOTES", "notes") if upper else ("notes", "NOTES") + if checkout == "unicode": + old_name, new_name = "État.txt", "état.txt" + if checkout == "decomposed": + old_name, new_name = "E\u0301tat.txt", "e\u0301tat.txt" + old = repo / old_name + new = repo / new_name + if directory: + old.mkdir() + (old / "nested").mkdir() + original = old / "nested" / "document.txt" + renamed = new / "nested" / "document.txt" + (old / "tracked-sibling.txt").write_text("tracked sibling\n") + else: + original, renamed = old, new + original.write_bytes(b"source notes\n" * 4) + if checkout == "converted": + (repo / ".gitattributes").write_text(f"{old_name} text eol=crlf\n{new_name} text eol=crlf\n") + if checkout == "converted-target": + (repo / ".gitattributes").write_text(f"{new_name} text eol=crlf\n") + if checkout == "ignored": + (repo / ".gitignore").write_text(f"/{new_name}\n") + _git(repo, "add", "--force", "--", old_name) + if checkout == "sparse-index": + (repo / "archive").mkdir() + (repo / "archive" / "untouched.txt").write_text("out of cone\n") + _git(repo, "add", ".") + if not checkout.endswith("staged-addition"): + _git(repo, "commit", "-m", "test: add inventory source") + else: + _git(repo, "update-index", "--assume-unchanged", "--", original.relative_to(repo).as_posix()) + if checkout == "sparse-index": + _git(repo, "sparse-checkout", "set", "--cone", "--sparse-index", "other") + assert not (repo / "archive" / "untouched.txt").exists() + # A distinct ignored destination needs a staged move on case-sensitive volumes. + if staged or (checkout == "ignored" and not new.exists()): + # Git treats an existing directory destination as a container. + if (directory and new.exists()) or checkout == "unicode": + _git(repo, "mv", old_name, "intermediate") + _git(repo, "mv", "intermediate", new_name) + else: + _git(repo, "mv", old_name, new_name) + else: + old.rename(new) + if checkout == "ignorecase-disabled": + _git(repo, "config", "core.ignorecase", "false") + assert new.name in {entry.name for entry in repo.iterdir()} + source_bytes = b"unstaged notes\nsource notes\nsource notes\nsource notes\n" + renamed.write_bytes(source_bytes) + if directory: + (new / "draft.txt").write_text("user untracked draft\n") + (repo / "source.py").write_text("value = 2\n") + _git(repo, "add", "source.py") + (repo / "source.py").write_text("value = 3\n") + index_file = repo / ".git/index" + index_before = index_file.read_bytes() + index_entries = _git(repo, "ls-files", "-v") + worktrees_before = _git(repo, "worktree", "list", "--porcelain") + observed = [] + + async def examine(child, _inputs): + candidate_repo = Path(child.workspace_root) + observed.append(candidate_repo) + names = {entry.name for entry in candidate_repo.iterdir()} + if checkout == "decomposed": + names = {normalize("NFC", name) for name in names} + assert normalize("NFC", new_name) in names and normalize("NFC", old_name) not in names + else: + assert new_name in names and old_name not in names + assert (candidate_repo / renamed.relative_to(repo)).read_bytes() == source_bytes + if checkout.endswith("staged-addition"): + old_path = original.relative_to(repo).as_posix() + new_path = renamed.relative_to(repo).as_posix() + assert f"h {old_path}" in index_entries.splitlines() + candidate_entries = _git(candidate_repo, "ls-files", "-v").splitlines() + assert f"H {new_path}" in candidate_entries + assert all(entry[2:] != old_path for entry in candidate_entries) + if directory: + assert (candidate_repo / new_name / "tracked-sibling.txt").read_text() == "tracked sibling\n" + assert (candidate_repo / new_name / "draft.txt").read_text() == "user untracked draft\n" + if checkout == "submodules": + assert (candidate_repo / "vendor/required/source.py").read_text() == "value = 1\n" + assert not list((candidate_repo / "vendor/optional").iterdir()) + assert (candidate_repo / "source.py").read_text() == "value = 3\n" + (candidate_repo / "source.py").write_text("value = 42\n") + return "checked source spelling" + + async def flow(ctx, inputs): + run = await ctx.candidate_workflow(examine, inputs, label="inventory candidate") + assert run.output == "checked source spelling" + assert patch_entries(run.diff) == [("source.py", "source.py")] + await ctx.adopt_candidate(run) + return run.output + + if checkout in {"team", "team-staged-addition"}: + pool = WorktreePool(str(repo), use_worktrees=True, enable_adoption=True) + try: + environment = await pool.acquire("coder") + await examine(SimpleNamespace(workspace_root=environment.workspace), {}) + patch = await environment.get_diff() + assert patch_entries(patch) == [("source.py", "source.py")] + await pool.adopt(patch) + finally: + await pool.release() + else: + result = await OpenCollab(repo, model="offline").workflow(flow, trace=False) + assert result.ok, result.reason + assert (repo / "source.py").read_text() == "value = 42\n" + assert renamed.read_bytes() == source_bytes + assert index_file.read_bytes() == index_before + assert _git(repo, "ls-files", "-v") == index_entries + assert _git(repo, "show", ":source.py").strip() == "value = 2" + assert observed and all(not path.exists() for path in observed) + assert _git(repo, "worktree", "list", "--porcelain") == worktrees_before + + +async def test_source_spelling_change_preserves_candidate_for_recovery(tmp_path): + repo = _repository(tmp_path) + (repo / "notes").write_text("source notes\n") + _git(repo, "add", "notes") + _git(repo, "commit", "-m", "test: add source notes") + index_before = (repo / ".git/index").read_bytes() + candidate_paths = [] + + async def change_source(child, _inputs): + path = Path(child.workspace_root) + candidate_paths.append(path) + (path / "source.py").write_text("value = 42\n") + (repo / "notes").rename(repo / "NOTES") + return "source changed" + + async def flow(ctx, inputs): + return (await ctx.candidate_workflow(change_source, inputs, label="source spelling drift")).output + + try: + result = await OpenCollab(repo, model="offline").workflow(flow, trace=False) + assert isinstance(result.error, CandidateWorkspaceTrackingError) + assert candidate_paths and (candidate_paths[0] / "source.py").read_text() == "value = 42\n" + assert {path.name for path in repo.iterdir() if path.name.lower() == "notes"} == {"NOTES"} + assert (repo / "source.py").read_text() == "value = 1\n" + assert (repo / ".git/index").read_bytes() == index_before + finally: + for path in candidate_paths: + if path.exists(): + _git(repo, "worktree", "remove", "--force", "--", str(path)) + + +async def test_candidate_file_tool_uses_the_recased_source_directory(tmp_path): + repo = _repository(tmp_path) + old = repo / "inventory" + old.mkdir() + (old / "notes.txt").write_text("retained\n") + _git(repo, "add", "inventory") + _git(repo, "commit", "-m", "test: prepare source subdirectory") + current = repo / "Inventory" + old.rename(current) + (current / "draft.txt").write_text("user draft\n") + index_before = (repo / ".git/index").read_bytes() + write, = builtin_tools("file_write", headless=False) + + async def examine(child, _inputs): + assert Path(child.workspace_root).name == "Inventory" + assert Path(child.workspace_root, "draft.txt").read_text() == "user draft\n" + return await child.execute_verification(write, { + "path": "notes.txt", "mode": "create", "content": "updated\n", + }) + + async def flow(ctx, inputs): + run = await ctx.candidate_workflow(examine, inputs, label="source subdirectory") + assert patch_entries(run.diff) == [("Inventory/notes.txt", "Inventory/notes.txt")] + await ctx.adopt_candidate(run) + + result = await OpenCollab(current, model="offline").workflow(flow, trace=False) + assert result.ok, result.reason + assert (current / "notes.txt").read_text() == "updated\n" + assert (repo / ".git/index").read_bytes() == index_before diff --git a/tests/workflows/test_candidate_workflow_budget_inheritance.py b/tests/workflows/test_candidate_workflow_budget_inheritance.py index eee15c93..90c86636 100644 --- a/tests/workflows/test_candidate_workflow_budget_inheritance.py +++ b/tests/workflows/test_candidate_workflow_budget_inheritance.py @@ -16,7 +16,7 @@ from opencollab.application.workflow import WorkflowBudgetExceeded, WorkflowContext from opencollab.bootstrap._workflow_runtime_session import WorkflowSessionFactory from tests.support.provider_sdk_http import completion_http_response, install_sdk_transport -from tests.support.workflow_context_test_support import FakeFactory, FakeSession +from tests.support.workflow_context_test_support import FakeFactory, FakeSession, _DeferredTokenSession @pytest.fixture @@ -43,6 +43,128 @@ def _context(repository, factory, total): candidate_workspace=EnvCandidateWorkspace(LocalEnvironment(str(repository))), ) +@pytest.mark.parametrize(("method", "slots", "first_spend", "escape"), [ + ("agent", 1, 15, False), + ("agent", 2, 15, True), + ("agent", 1, 100, False), + ("agent_run", 1, 15, False), + ("candidate_agent", 1, 15, False), + ("candidate_workflow", 1, 15, False), + ("draft_findings", 2, 15, False), +]) +async def test_full_reservation_waits_for_actual_budget_spend(repository, method, slots, first_spend, escape): + ready, release = asyncio.Event(), asyncio.Event() + + async def mark_ready(): + ready.set() + await release.wait() + + first = _DeferredTokenSession(tokens=first_spend, on_enter=mark_ready) + first.reply = "prepared" + factory = FakeFactory([ + first, + FakeSession(reply="reviewed", tokens=7), + ]) + ctx = WorkflowContext( + factory, budget_total=100, max_concurrency=slots, + candidate_workspace=EnvCandidateWorkspace(LocalEnvironment(str(repository))), + ) + + async def review(): + if method == "candidate_workflow": + async def child_review(child, _args): + return await child.agent("review") + + return (await ctx.candidate_workflow(child_review, {}, label="review", budget=100)).output + if method in {"agent_run", "candidate_agent"}: + return (await getattr(ctx, method)("review", label="review", budget=100)).output + if method == "draft_findings": + return await ctx.draft_findings("review", budget=100) + return await ctx.agent("review", budget=100, over_budget_ok=escape) + + tasks = [asyncio.create_task(ctx.agent("prepare", budget=100))] + try: + await asyncio.wait_for(ready.wait(), 10) + reviewer = asyncio.create_task(review()) + tasks.append(reviewer) + for _ in range(10): + await asyncio.sleep(0) + assert not reviewer.done() + assert ctx.tokens_spent() == 0 and ctx.tokens_remaining() == 0 + assert len(factory.builds) == 1 + first.land_spend() + release.set() + prepared, reviewed = await asyncio.wait_for( + asyncio.gather(*tasks, return_exceptions=True), 10, + ) + assert prepared == "prepared" + if first_spend == 100: + assert isinstance(reviewed, WorkflowBudgetExceeded) + assert "spent 100 of 100" in str(reviewed) + assert len(factory.builds) == 1 + else: + assert reviewed == (None if method == "draft_findings" else "reviewed") + assert [build["budget"] for build in factory.builds] == [100, 85] + assert ctx.tokens_remaining() == 78 + assert not ctx._budget_escape_state.used + assert ctx._semaphore._value == slots + assert not ctx.budget._leases + finally: + release.set() + for task in tasks: + if not task.done(): + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + await ctx.wait_for_pending_cleanup() + +async def test_cancelled_call_waiting_for_reserved_budget_keeps_capacity(repository): + ready, release = asyncio.Event(), asyncio.Event() + + async def hold_session(): + ready.set() + await release.wait() + + first = _DeferredTokenSession(tokens=15, on_enter=hold_session) + factory = FakeFactory([first, FakeSession(reply="reviewed", tokens=7)]) + ctx = _context(repository, factory, 100) + preparer = asyncio.create_task(ctx.agent("prepare", budget=100)) + reviewer = None + try: + await asyncio.wait_for(ready.wait(), 10) + reviewer = asyncio.create_task(ctx.agent("cancelled review", budget=100)) + for _ in range(10): + await asyncio.sleep(0) + assert not reviewer.done() + reviewer.cancel() + with pytest.raises(asyncio.CancelledError): + await reviewer + first.land_spend() + finally: + release.set() + if reviewer is not None: + if not reviewer.done(): + reviewer.cancel() + await asyncio.gather(reviewer, return_exceptions=True) + await asyncio.wait_for(preparer, 10) + + assert await ctx.agent("new review", budget=100) == "reviewed" + assert [build["budget"] for build in factory.builds] == [100, 85] + assert ctx.tokens_remaining() == 78 + +async def test_candidate_callback_cannot_wait_for_its_own_reservation(repository): + parent = _context(repository, FakeFactory([FakeSession(tokens=15)]), 100) + + async def nested(child, _args): + with pytest.raises(WorkflowBudgetExceeded): + await asyncio.create_task(parent.agent("needs parent budget", budget=100)) + return await child.agent("uses the candidate allowance") + + candidate = await asyncio.wait_for( + parent.candidate_workflow(nested, {}, label="candidate", budget=100), 10, + ) + assert candidate.output == "done" + assert parent.tokens_remaining() == 85 + @pytest.mark.parametrize( "total,spent,requested,approved", [ diff --git a/tests/workflows/test_candidate_workspace_raw_diff.py b/tests/workflows/test_candidate_workspace_raw_diff.py index 3b54f9e6..11b5dbaa 100644 --- a/tests/workflows/test_candidate_workspace_raw_diff.py +++ b/tests/workflows/test_candidate_workspace_raw_diff.py @@ -1,6 +1,7 @@ from __future__ import annotations import shlex +import sys from pathlib import Path import pytest @@ -8,7 +9,7 @@ from opencollab.adapters._env_base import ExecResult from opencollab.adapters._env_local import LocalEnvironment from opencollab.adapters.candidate_workspace import EnvCandidateWorkspace, _raw_diff_at -from tests.workflows.test_workflow_candidate_workspace import _repository +from tests.workflows.test_workflow_candidate_workspace import _git, _repository @pytest.mark.parametrize("index_file", [None, "/tmp/candidate-index"]) @@ -67,3 +68,32 @@ async def display_conversion(command, **kwargs): if lease is not None: await lease.cleanup() await base.cleanup() + + +async def test_candidate_delivers_with_large_tracked_path_list(tmp_path): + repo = _repository(tmp_path) + book = repo / "book" + book.mkdir() + for chapter in range(6200): + (book / f"{chapter:08}-{'outline-' * 12}.txt").write_text("chapter\n") + _git(repo, "add", "book") + _git(repo, "-c", "commit.gpgsign=false", "commit", "-qm", "Add book chapters") + (repo / "draft.txt").write_text("user draft\n") + index = (repo / ".git/index").read_bytes() + worktrees = _git(repo, "worktree", "list", "--porcelain") + environment = LocalEnvironment(str(repo)) + workspace = EnvCandidateWorkspace(environment) + lease = None + try: + lease = await workspace.acquire("book-chapters") + assert await lease.environment.read_file("draft.txt") == "user draft\n" + await lease.environment.write_file("source.py", "print(42)\n") + await workspace.adopt(await lease.diff()) + result = await environment.exec_cmd(shlex.join((sys.executable, "-B", "source.py"))) + assert result.returncode == 0 and result.stdout == "42\n" + assert (repo / ".git/index").read_bytes() == index + finally: + if lease is not None: + await lease.cleanup() + await environment.cleanup() + assert _git(repo, "worktree", "list", "--porcelain") == worktrees diff --git a/tests/workflows/test_duo_runtime.py b/tests/workflows/test_duo_runtime.py index 712c01c5..e8b23d27 100644 --- a/tests/workflows/test_duo_runtime.py +++ b/tests/workflows/test_duo_runtime.py @@ -2,6 +2,7 @@ from __future__ import annotations +import asyncio import copy import json import logging @@ -22,6 +23,7 @@ from opencollab.bootstrap import _workflow_runtime_session as workflow_session from opencollab.bootstrap.single2_prompt import SINGLE2_SYSTEM_PROMPT from opencollab.bootstrap.workflow_runtime import run_workflow +from opencollab.builtin_workflows import duo from opencollab.builtin_workflows.duo import _dual_coder, _file_selection from opencollab.environments import DockerOptions, docker_isolation_provider from opencollab.sdk.result import RunError @@ -513,3 +515,294 @@ def build(**kwargs): assert calls == ["A", "B"] assert (repo / filename).read_text() == desired assert _git(repo, "diff", "--name-only").strip() == filename + +@pytest.mark.parametrize(("submission", "evidence", "budget"), [ + ("task", "green", 20_000), + ("working_tree", "green", 20_000), + ("task", "red", 20_000), + ("task", "stale", 20_000), + ("task", "empty", 20_000), + ("task", "green", 20_050), + ("working_tree", "green", 20_050), + ("task", "red", 20_050), + ("task", "stale", 20_050), + ("task", "empty", 20_050), + ("task", "green", 22_000), +]) +async def test_duo_delivers_current_verified_a_when_budget_refuses_b( + tmp_path, monkeypatch, submission, evidence, budget, +): + simulate_candidate_sandbox(monkeypatch) + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + repo = _repository(tmp_path / "repo", both_pass=False) + if evidence == "empty": + (repo / "test_public.py").write_text( + "from source import value\n\ndef test_public():\n assert value() == 1\n" + ) + _git(repo, "add", "test_public.py") + _git(repo, "commit", "-qm", "Test the baseline") + command = f"{shlex.quote(sys.executable)} -m pytest -q -rA -p no:cacheprovider test_public.py" + initial_worktrees = _git(repo, "worktree", "list", "--porcelain") + preparing, finish_preparation = asyncio.Event(), asyncio.Event() + prepare_prompt = "Summarize the release notes." + calls = [] + + def request(messages): + prompt = next(row["content"] for row in messages if row["role"] == "user") + if prepare_prompt in prompt: + return "prepare", 0 + role = "A" if "You are candidate A" in prompt else "B" + return role, sum(row["role"] == "tool" for row in messages) + + class Model: + def estimate_request_tokens(self, messages, tools, **kwargs): + role, step = request(messages) + if role == "prepare": + return 80 + if role == "B": + return 100 + if step < 2: + return 3_800 + if evidence == "stale" and step == 2: + return 500 + # Account for the preparation and two tool requests, leaving 21 output tokens at 20,000. + return 11_639 if evidence == "stale" else 12_199 + + async def complete(self, messages, tools=None, *, max_output_tokens, **kwargs): + role, step = request(messages) + calls.append((role, step)) + inputs = self.estimate_request_tokens(messages, tools) + if role == "prepare": + preparing.set() + await finish_preparation.wait() + return LLMResponse(content="Release notes prepared.", usage=Usage(inputs, 20)) + if step == 0 or (role == "A" and evidence == "stale" and step == 2): + if role == "A" and evidence == "empty": + response = _tool_response("file_read", {"path": "source.py"}, step) + else: + value = 3 if role == "A" and step == 0 and evidence != "red" else 2 + response = _tool_response("file_write", { + "path": "source.py", "mode": "create", "content": f"def value():\n return {value}\n", + }, step) + response.usage = Usage(inputs, 60 if step == 2 else 40) + return response + if step == 1: + response = _tool_response("bash", {"command": command}, step) + response.usage = Usage(inputs, 40) + return response + outputs = 21 if role == "A" else max_output_tokens + return LLMResponse(content="I ran the public test.", usage=Usage(inputs, outputs)) + + async def flow(ctx, args): + preparation = asyncio.create_task(ctx.agent_run(prepare_prompt, budget=12_000, tools=[])) + + async def run_after_preparation(): + finish_preparation.set() + assert (await preparation).output == "Release notes prepared." + return await duo(ctx, args) + + try: + await asyncio.wait_for(preparing.wait(), 5) + assert ctx.tokens_remaining() == budget - 12_000 + return (await ctx.parallel([run_after_preparation]))[0] + finally: + finish_preparation.set() + await preparation + + artifacts = tmp_path / "artifacts" + result = await OpenCollab(repo, model="scripted-local-model", config={"max_output_tokens": 128}).workflow( + flow, {"goal": "Make value() return 3", "submission_mode": submission}, + llm=Model(), budget=budget, max_steps=5, concurrency=2, timeout=20, trace=True, + artifacts=artifacts, limit_mode="explicit", + ) + runs_b = budget >= 22_000 + output = result.output + if evidence == "green": + assert result.status == "completed" + assert output["status"] == "done" and output["submission_mode"] == submission + assert output["adopted"] == output["winner"] == "A" + assert output["adoption_attempts"] == ["A"] + assert output["judge_used"] is False and output["judge_result"] is None + record, = output["candidates"]["A"]["public_test_records"] + assert record["verified"] is True and record["applicability"] == "current" + b = output["candidates"]["B"] + if runs_b: + assert output["selection_reason"] == "same-command-public-red" + assert "status" not in b + assert b["nonempty"] is True + assert b["public_test_records"][0]["exit_code"] == 1 + else: + assert output["selection_reason"] == "candidate-b-budget-exhausted" + assert (b["status"], b["reason"], b["nonempty"]) == ("skipped", "budget_exceeded", False) + assert b["changed_paths"] == b["public_test_records"] == [] + assert b["diff_bytes"] == 0 and b["public_command"] == "" + else: + assert (result.status, result.reason, output["status"]) == ("stopped", "budget_exceeded", "budget_exceeded") + + assert any(role == "B" for role, _step in calls) is runs_b + assert _git(repo, "worktree", "list", "--porcelain") == initial_worktrees + source = (repo / "source.py").read_text() + assert source == ("def value():\n return 3\n" if evidence == "green" else "def value():\n return 1\n") + verified = subprocess.run(shlex.split(command), cwd=repo, capture_output=True, text=True) + assert verified.returncode == (0 if evidence in {"green", "empty"} else 1), verified.stdout + verified.stderr + + manifest = json.loads((artifacts / "workflow.json").read_text()) + assert manifest["evidence_complete"] is True + assert manifest["tokens_spent"] == result.tokens + if not runs_b: + assert result.tokens == 20_000 + traces = [json.loads(line) for line in (artifacts / "orchestration.jsonl").read_text().splitlines()] + refusals = [row["payload"]["label"] for row in traces if row["type"] == "budget_refusal"] + assert refusals == (["dual-coder-contract-b"] if budget == 20_000 else []) + executed = [row["payload"]["result"] for row in traces if row["type"] == "tool_exec" + and row["payload"]["tool"] == "bash"] + assert [line.splitlines()[0] for line in executed] == ( + ["Exit code: 0", "Exit code: 1"] if runs_b else [f"Exit code: {int(evidence == 'red')}"] + ) + + +async def test_duo_can_start_b_after_a_budget_refusal_and_reservation_release(tmp_path, monkeypatch): + simulate_candidate_sandbox(monkeypatch) + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + repo = _repository(tmp_path / "repo", both_pass=False) + command = f"{shlex.quote(sys.executable)} -m pytest -q -rA -p no:cacheprovider test_public.py" + initial_worktrees = _git(repo, "worktree", "list", "--porcelain") + preparing, release = asyncio.Event(), asyncio.Event() + prepare_prompt = "Prepare release notes." + calls = [] + + class Model: + def estimate_request_tokens(self, messages, tools, **kwargs): + return 100 + + async def complete(self, messages, tools=None, **kwargs): + prompt = next(row["content"] for row in messages if row["role"] == "user") + if prompt == prepare_prompt: + calls.append(("prepare", 0)) + preparing.set() + await release.wait() + return LLMResponse(content="Notes completed.", usage=Usage(90, 10)) + assert "You are candidate B" in prompt + step = sum(row["role"] == "tool" for row in messages) + calls.append(("B", step)) + if step == 0: + response = _tool_response("file_write", { + "path": "source.py", "mode": "create", "content": "def value():\n return 3\n", + }, step) + elif step == 1: + response = _tool_response("bash", {"command": command}, step) + else: + response = LLMResponse(content="Verified three.", usage=Usage(90, 10)) + response.usage = Usage(90, 10) + return response + + async def flow(ctx, args): + preparation = asyncio.create_task(ctx.agent_run(prepare_prompt, tools=[], budget=19_950)) + phase = ctx.phase + + async def release_before_b(label): + await phase(label) + if label == "dual-coder-b": + release.set() + assert (await preparation).output == "Notes completed." + assert ctx.tokens_remaining() == 19_900 + + monkeypatch.setattr(ctx, "phase", release_before_b) + try: + await asyncio.wait_for(preparing.wait(), 5) + assert ctx.tokens_remaining() == 50 + return await duo(ctx, args) + finally: + release.set() + await preparation + + result = await OpenCollab(repo, model="scripted-local-model", config={"max_output_tokens": 128}).workflow( + flow, {"goal": "Make value() return 3"}, + llm=Model(), budget=20_000, concurrency=2, max_steps=5, timeout=20, + trace=False, limit_mode="explicit", + ) + assert result.ok and result.output["status"] == "done" + assert calls == [("prepare", 0), ("B", 0), ("B", 1), ("B", 2)] + assert result.tokens == 400 + assert result.output["adopted"] == "B" and result.output["selection_reason"] == "only-b-nonempty" + assert result.output["candidates"]["B"]["public_test_records"][0]["verified"] + assert (repo / "source.py").read_text() == "def value():\n return 3\n" + assert _git(repo, "worktree", "list", "--porcelain") == initial_worktrees + + +async def test_duo_stops_when_verified_budget_fallback_cannot_be_adopted(tmp_path, monkeypatch): + simulate_candidate_sandbox(monkeypatch) + monkeypatch.setenv("OPENCOLLAB_BUDGET_NUDGE_MODE", "off") + monkeypatch.setenv("OPENCOLLAB_WRITE_NUDGE_MODE", "off") + repo = _repository(tmp_path / "repo", both_pass=False) + package = repo / "catalog" + package.mkdir() + (package / "__init__.py").touch() + (repo / "test_public.py").write_text( + "def test_catalog_entry():\n" + " from catalog.labels import entry\n" + " assert entry() == 'ready'\n", + encoding="utf-8", + ) + _git(repo, "add", ".") + _git(repo, "commit", "-qm", "Set up catalog") + worktrees_before = _git(repo, "worktree", "list", "--porcelain") + command = [sys.executable, "-B", "-m", "pytest", "-q", "-rA", "-p", "no:cacheprovider", "test_public.py"] + calls = [] + + class Model: + def estimate_request_tokens(self, messages, tools, **kwargs): + # The final reply uses the rest of the 20,000-token budget. + return (3_800, 3_800, 12_299)[sum(row["role"] == "tool" for row in messages)] + + async def complete(self, messages, tools=None, **kwargs): + prompt = next(row["content"] for row in messages if row["role"] == "user") + assert "You are candidate A" in prompt + step = sum(row["role"] == "tool" for row in messages) + calls.append(step) + inputs = self.estimate_request_tokens(messages, tools) + if step == 0: + response = _tool_response("file_write", { + "path": "catalog/labels.py", "mode": "create", + "content": "def entry():\n return 'ready'\n", + }, step) + elif step == 1: + response = _tool_response("bash", {"command": shlex.join(command)}, step) + else: + return LLMResponse(content="Catalog test passed.", usage=Usage(inputs, 21)) + response.usage = Usage(inputs, 40) + return response + + artifacts = tmp_path / "artifacts" + package.chmod(0o555) + try: + if os.access(package, os.W_OK): + pytest.skip("source directory remains writable with read-only permissions") + result = await OpenCollab(repo, model="scripted-local-model", config={"max_output_tokens": 128}).workflow( + "duo", {"goal": "Add the catalog entry 'ready'."}, + llm=Model(), budget=20_000, max_steps=5, timeout=20, trace=True, + artifacts=artifacts, limit_mode="explicit", + ) + finally: + package.chmod(0o755) + + assert calls == [0, 1, 2] + traces = [json.loads(line) for line in (artifacts / "orchestration.jsonl").read_text().splitlines()] + test_results = [row["payload"]["result"] for row in traces if row["type"] == "tool_exec" + and row["payload"]["tool"] == "bash"] + assert [line.splitlines()[0] for line in test_results] == ["Exit code: 0"] + assert any(row["type"] == "workflow_log" and "Duo adoption failed (A)" in row["payload"]["message"] + for row in traces) + assert not (package / "labels.py").exists() + failed_check = subprocess.run(command, cwd=repo, capture_output=True, text=True) + assert failed_check.returncode == 1 and "No module named 'catalog.labels'" in failed_check.stdout + assert _git(repo, "status", "--short") == "" + assert _git(repo, "worktree", "list", "--porcelain") == worktrees_before + assert (result.status, result.reason, result.tokens) == ("stopped", "budget_exceeded", 20_000) + assert result.output["status"] == "budget_exceeded" + manifest = json.loads((artifacts / "workflow.json").read_text()) + assert (manifest["status"], manifest["reason"], manifest["tokens_spent"]) == ( + "stopped", "budget_exceeded", 20_000, + ) diff --git a/tests/workflows/test_reconstruct_observation_delivery.py b/tests/workflows/test_reconstruct_observation_delivery.py new file mode 100644 index 00000000..f388b16b --- /dev/null +++ b/tests/workflows/test_reconstruct_observation_delivery.py @@ -0,0 +1,459 @@ +"""Exercise Reconstruct with a subprocess adapter that consumes JSON request fields.""" + +import asyncio +import errno +import importlib +import json +import os +import py_compile +import subprocess +import sys +from pathlib import Path + +import pytest + +from opencollab import OpenCollab +from opencollab.adapters.llm.types import LLMResponse, Usage +from opencollab.builtin_workflows import ReconstructionTask, register_task +from opencollab.tools import builtin_tools +from tests.support.worktree_delivery_support import git, make_repo + +SOURCE = """import json +import sys + +def solve(items): + return sum(items) + +if __name__ == "__main__": + print(json.dumps([solve(items) for items in json.loads(sys.argv[1])])) +""" + + +class Model: + def __init__(self, filename="candidate.py", sources=(SOURCE,)): + self.filename = filename + self.sources = iter(sources) + + async def complete(self, messages, **kwargs): + program = None if any(message["role"] == "tool" for message in messages) else next(self.sources) + if program is None: + return LLMResponse(content="Candidate ready.", usage=Usage(4, 2), finish_reason="stop") + return LLMResponse( + tool_calls=[{ + "id": "write-candidate", + "type": "function", + "function": { + "name": "file_write", + "arguments": json.dumps({ + "path": self.filename, "mode": "create", "overwrite": True, "content": program, + }), + }, + }], + usage=Usage(4, 2), + finish_reason="tool_calls", + ) + + +async def execute(candidate, samples, workspace, *, as_module=False): + relative = candidate.relative_to(workspace) + entry = ["-m", ".".join(relative.with_suffix("").parts)] if as_module else [str(relative)] + process = await asyncio.create_subprocess_exec( + sys.executable, "-B", *entry, json.dumps(samples), + cwd=workspace, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, + ) + stdout, stderr = await process.communicate() + assert process.returncode == 0, stderr.decode() + return json.loads(stdout) + + +@pytest.mark.parametrize("consumer", ["none", "evaluator", "observer"]) +async def test_reconstruct_callbacks_cannot_rewrite_observed_examples(tmp_path: Path, consumer: str) -> None: + workspace = tmp_path / "workspace" + workspace.mkdir() + subprocess.run(["git", "init", "-q", str(workspace)], check=True) + observed = [] + analytics = [] + original = [{"items": [1, 3]}, {"items": [3, 5]}] + + def on_example(row, output, source): + items = row.pop("items") if consumer == "observer" else row["items"] + total = output.pop("total") if consumer == "observer" else output["total"] + analytics.append({"items": items, "total": total, "source": source}) + + async def evaluate(candidate, inputs): + # The subprocess takes positional item lists. Consume the input field to + # separate it from request metadata while building batch arguments. + samples = [ + row.pop("items", []) if consumer == "evaluator" else row.get("items", []) + for row in inputs + ] + outputs = await execute(candidate, samples, workspace) + observed.append(outputs) + return [{"ok": True, "output": {"total": output}} for output in outputs] + + task = ReconstructionTask( + input_type="object", input_constraints="The items field is a list of integers.", + function_name="solve", workspace=workspace, oracle=lambda row: {"total": sum(row["items"])}, + evaluate=evaluate, random_inputs=lambda count, exclude: original, on_example=on_example, + tools=builtin_tools("file_write"), + ) + result = await OpenCollab(workspace, model="scripted-local-model").workflow( + "reconstruct", {"task": register_task(task), "random_share": 1, "early_stop": 1}, + llm=Model(), budget=60_000, limit_mode="explicit", trace=False, + ) + assert result.ok, result.reason + delivered = workspace / "candidate.py" + assert delivered.read_text(encoding="utf-8") == SOURCE + held_out = await execute(delivered, [[7, 11]], workspace) + print(json.dumps({ + "consumer": consumer, + "status": result.status, + "examples": result.output["examples"], + "analytics": analytics, + "promotions": result.output["promotions"], + "score": result.output["final_score"], + "evaluations": observed, + "held_out": held_out, + })) + assert held_out == [18] + assert observed == [[4, 8], [4, 8]] + assert analytics == [ + {"items": [1, 3], "total": 4, "source": "random"}, + {"items": [3, 5], "total": 8, "source": "random"}, + ] + assert result.output["examples"] == [ + [original[0], {"total": 4}, "random"], + [original[1], {"total": 8}, "random"], + ] + assert result.output["promotions"] == 1 + assert result.output["final_score"] == 0.997 + + +@pytest.mark.parametrize( + "case", ["large_int", "rounded_int", "declared_encoding", "invalid_encoding", "non_text_codec"], +) +async def test_reconstruct_scores_python_candidate_and_recovers(tmp_path: Path, case: str) -> None: + subprocess.run(["git", "init", "-q", str(tmp_path)], check=True) + candidate = tmp_path / "candidate.py" + latin1_program = SOURCE.replace('return sum(items)', 'return f"café {sum(items)}"') + precise_program = SOURCE.replace('return sum(items)', 'return sum(items) / 2') + original_bytes = None + + if case == "large_int": + programs = (SOURCE.replace('return sum(items)', 'return 10**400'), precise_program) + + def oracle(items): + return sum(items) / 2 + elif case == "rounded_int": + programs = ( + SOURCE.replace("return sum(items)", "return sum(items) * 10**16 + 1"), + SOURCE.replace("return sum(items)", "return float(sum(items) * 10**16)"), + ) + + def oracle(items): + return float(sum(items) * 10**16) + elif case == "declared_encoding": + original_bytes = ("# coding: latin-1\n" + latin1_program).encode("latin-1") + candidate.write_bytes(original_bytes) + programs = (None,) + + def oracle(items): + return f"café {sum(items)}" + else: + invalid_source = (latin1_program.encode("latin-1") if case == "invalid_encoding" + else b"# coding: base64\n" + SOURCE.encode("ascii")) + candidate.write_bytes(invalid_source) + programs = (None, SOURCE) + oracle = sum + + async def evaluate(staged, samples): + try: + outputs = await execute(staged, samples, tmp_path) + except AssertionError as error: + assert case in {"invalid_encoding", "non_text_codec"} and "SyntaxError" in str(error) + return [{"ok": False, "error": str(error)} for _ in samples] + return [{"ok": True, "output": value} for value in outputs] + + task = ReconstructionTask( + input_type="list of integers", input_constraints="Any list of integers.", + function_name="solve", workspace=tmp_path, oracle=oracle, evaluate=evaluate, + random_inputs=lambda count, exclude: [[1, 3], [3, 5]], tools=builtin_tools("file_write"), + ) + result = await OpenCollab(tmp_path, model="scripted-local-model").workflow( + "reconstruct", + {"task": register_task(task), "random_share": 1, "early_stop": 1, "max_iterations": 2}, + llm=Model(sources=programs), budget=60_000, limit_mode="explicit", trace=False, + ) + assert result.ok, result.reason + accepted_round = 1 if case == "declared_encoding" else 2 + assert result.output["iterations"] == accepted_round + assert result.output["promotions"] == 1 + assert result.output["final_program"] == f"iter_{accepted_round:03d}.py" + assert [event["passed"] for event in result.output["events"] if "passed" in event] == ( + [2] if accepted_round == 1 else [0, 2] + ) + assert await execute(candidate, [[7, 11]], tmp_path) == [oracle([7, 11])] + if original_bytes is not None: + assert candidate.read_bytes() == original_bytes + + +async def test_reconstruct_evaluation_preserves_plugin_discovery(tmp_path: Path) -> None: + subprocess.run(["git", "init", "-q", str(tmp_path)], check=True) + plugins = tmp_path / "plugins" + plugins.mkdir() + (plugins / "__init__.py").write_text( + """from importlib import import_module +from pkgutil import iter_modules + +def apply_plugins(value): + for plugin in iter_modules(__path__, prefix=__name__ + "."): + value = import_module(plugin.name).adjust(value) + return value +""", encoding="utf-8", + ) + entry = """ +if __name__ == "__main__": + import json, sys + print(json.dumps([solve(value) for value in json.loads(sys.argv[1])])) +""" + correct = """from . import apply_plugins + +def adjust(value): + return value + 1 + +def solve(value): + return apply_plugins(value) +""" + entry + fallback = """def adjust(value): + return value + 1 if value >= 0 else value + +solve = adjust +""" + entry + filename = "plugins/greeting.py" + + async def evaluate(candidate, inputs): + outputs = await execute(candidate, inputs, tmp_path, as_module=True) + return [{"ok": True, "output": output} for output in outputs] + + task = ReconstructionTask( + input_type="integer", input_constraints="Any integer.", function_name="solve", + workspace=tmp_path, candidate_file=filename, oracle=lambda value: value + 1, + evaluate=evaluate, random_inputs=lambda count, exclude: [1, 2], + tools=builtin_tools("file_write"), + ) + result = await OpenCollab(tmp_path, model="scripted-local-model").workflow( + "reconstruct", + {"task": register_task(task), "random_share": 1, "early_stop": 1, "max_iterations": 2}, + llm=Model(filename, [correct, fallback]), budget=60_000, limit_mode="explicit", trace=False, + ) + assert result.ok, result.reason + assert await execute(tmp_path / filename, [-5, 12], tmp_path, as_module=True) == [-4, 13] + assert result.output["iterations"] == 1 and result.output["promotions"] == 1 + assert (tmp_path / filename).read_text(encoding="utf-8") == correct + assert not list(tmp_path.glob("_oc_evaluate_*")) + + +@pytest.mark.parametrize("layout", ["repository", "worktree", "submodule", "nested-submodule"]) +async def test_reconstruct_evaluation_resolves_linked_git_metadata(tmp_path: Path, layout: str) -> None: + repository = make_repo(tmp_path / "repository") + git(repository, "-c", "tag.gpgsign=false", "tag", "v1.2.3") + workspace = checkout = repository + if layout == "worktree": + workspace = checkout = tmp_path / "linked" + git(repository, "worktree", "add", "--detach", str(workspace)) + elif layout in {"submodule", "nested-submodule"}: + parent = make_repo(tmp_path / "parent") + git(parent, "-c", "tag.gpgsign=false", "tag", "v9.0.0") + git(parent, "-c", "protocol.file.allow=always", "submodule", "add", str(repository), "inventory") + checkout = parent / "inventory" + workspace = parent if layout == "nested-submodule" else checkout + assert (checkout / ".git").read_text(encoding="utf-8").startswith("gitdir: ../") + marker = checkout / ".git" + original = marker.read_bytes() if marker.is_file() else None + filename = (checkout / "version_report.py").relative_to(workspace).as_posix() + git_source = """ +import json +import subprocess +import sys +from pathlib import Path + +def report(value): + version = subprocess.check_output( + ["git", "describe", "--tags", "--exact-match"], cwd=Path(__file__).absolute().parent, text=True + ).strip() + return f"{value} [{version}]" + +if __name__ == "__main__": + print(json.dumps([report(value) for value in json.loads(sys.argv[1])])) +""" + observed = [] + + async def evaluate(candidate, inputs): + output = await execute(candidate, inputs, workspace) + observed.append(output) + return [{"ok": True, "output": value} for value in output] + + task = ReconstructionTask( + input_type="text", input_constraints="Any label.", function_name="report", + candidate_file=filename, workspace=workspace, oracle=lambda label: f"{label} [v1.2.3]", + evaluate=evaluate, random_inputs=lambda *_: ["apple", "pear"], tools=builtin_tools("file_write"), + ) + result = await OpenCollab(workspace, model="scripted-local-model").workflow( + "reconstruct", {"task": register_task(task), "random_share": 1, "early_stop": 1, "max_iterations": 1}, + llm=Model(filename, [git_source]), budget=60_000, limit_mode="explicit", trace=False, + ) + assert result.ok, result.reason + assert result.tokens == 12 and result.output["promotions"] == 1 + assert result.output["final_program"] == "iter_001.py" + assert observed == [["apple [v1.2.3]", "pear [v1.2.3]"]] * 2 + assert await execute(workspace / filename, ["plum"], workspace) == ["plum [v1.2.3]"] + assert (marker.read_bytes() if marker.is_file() else None) == original + assert not list(workspace.rglob("_oc_evaluate_*")) + + +@pytest.mark.parametrize("archive_fallback", [False, True], ids=["workspace", "archive"]) +@pytest.mark.parametrize("auto_launch", [False, True], ids=["canonical", "automatic"]) +async def test_reconstruct_evaluates_archived_source_with_canonical_imports( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, archive_fallback: bool, auto_launch: bool, +) -> None: + subprocess.run(["git", "init", "-q", str(tmp_path)], check=True) + source_directory = tmp_path if auto_launch else tmp_path / "src" + package = source_directory / "catalog" / "pricing" + package.mkdir(parents=True) + (package.parent / "__init__.py").touch() + (package / "__init__.py").write_text( + """from dataclasses import dataclass +from importlib.resources import files + +RATE = int(files(__name__).joinpath("rate.txt").read_text(encoding="utf-8")) + +@dataclass(frozen=True) +class Offer: + units: int +""", encoding="utf-8", + ) + (package / "validator.py").write_text( + """from . import Offer, RATE + +def value_with_rate(offer): + assert isinstance(offer, Offer) + return offer.units + RATE +""", encoding="utf-8", + ) + (package / "rate.txt").write_text("3\n", encoding="utf-8") + entry = """ +if __name__ == "__main__": + import json, sys + print(json.dumps([solve(value) for value in json.loads(sys.argv[1])])) +""" + correct = """from . import Offer +from catalog.pricing.validator import value_with_rate + +def solve(value): + return value_with_rate(Offer(value)) +""" + entry + wrong = "def solve(value):\n return value - 3\n" + entry + delivered = package / "offer.py" + filename = delivered.relative_to(tmp_path).as_posix() + module_path = delivered.relative_to(source_directory) + if archive_fallback: + reconstruct_module = importlib.import_module("opencollab.builtin_workflows.reconstruct") + mkdtemp = reconstruct_module.mkdtemp + + def make_evaluation_directory(*, dir, prefix): + if dir in {tmp_path, package}: + raise PermissionError(errno.EACCES, "staging directory creation denied") + return mkdtemp(dir=dir, prefix=prefix) + + monkeypatch.setattr(reconstruct_module, "mkdtemp", make_evaluation_directory) + reevaluated = [] + + async def evaluate(candidate, inputs): + if archive_fallback: + assert candidate.is_relative_to(tmp_path / ".oc_candidates") + import_root = candidate.parents[len(module_path.parts) - 1] + if auto_launch and all( + part.isidentifier() for part in candidate.relative_to(tmp_path).with_suffix("").parts + ): + import_root = tmp_path + outputs = await execute(candidate, inputs, import_root, as_module=True) + if candidate.read_text(encoding="utf-8") == correct and delivered.read_text(encoding="utf-8") == wrong: + reevaluated.append(outputs) + return [{"ok": True, "output": output} for output in outputs] + + task = ReconstructionTask( + input_type="integer", input_constraints="Any integer.", function_name="solve", + workspace=tmp_path, candidate_file=filename, oracle=lambda value: value + 3, + evaluate=evaluate, random_inputs=lambda count, exclude: [1, 2] if not exclude else [3, 4, 5], + tools=builtin_tools("file_write"), + ) + result = await OpenCollab(tmp_path, model="scripted-local-model").workflow( + "reconstruct", + {"task": register_task(task), "random_share": 1, "batch_step": 1, "early_stop": 2, "max_iterations": 2}, + llm=Model(filename, [correct, wrong]), budget=60_000, limit_mode="explicit", trace=False, + ) + assert result.ok, result.reason + assert result.output["iterations"] == 2 and result.output["promotions"] == 1 + assert reevaluated == [[4, 5, 6, 7, 8]] + assert delivered.read_text(encoding="utf-8") == correct + assert await execute(delivered, [-5, 12], source_directory, as_module=True) == [-2, 15] + assert not list(tmp_path.rglob("_oc_evaluate_*")) + + +@pytest.mark.parametrize("stale_seconds", [0, 2], ids=["matching-header", "invalid-header"]) +async def test_reconstruct_evaluation_uses_its_own_bytecode_cache(tmp_path: Path, stale_seconds: int) -> None: + workspace = tmp_path / "workspace" + package = workspace / "plugins" + package.mkdir(parents=True) + (package / "__init__.py").touch() + subprocess.run(["git", "init", "-q", str(workspace)], check=True) + filename = "plugins/candidate.py" + source = "def solve(value):\n return value + 3\n" + stale_source = tmp_path / "previous.py" + stale_source.write_text("def solve(value):\n return value + 7\n", encoding="utf-8") + cache_name = f"candidate.{sys.implementation.cache_tag}.pyc" + source_cache = package / "__pycache__" / cache_name + source_cache.parent.mkdir() + observations = [] + script = ( + "import importlib, json, sys;" + "module = importlib.import_module(sys.argv[1]);" + "print(json.dumps([module.solve(value) for value in json.loads(sys.argv[2])]))" + ) + + async def evaluate(candidate, inputs): + timestamp = candidate.stat().st_mtime_ns - stale_seconds * 1_000_000_000 + os.utime(stale_source, ns=(timestamp, timestamp)) + py_compile.compile( + str(stale_source), cfile=str(source_cache), dfile=str(workspace / filename), doraise=True, + invalidation_mode=py_compile.PycInvalidationMode.TIMESTAMP, + ) + before = source_cache.read_bytes() + module = ".".join(candidate.relative_to(workspace).with_suffix("").parts) + process = await asyncio.create_subprocess_exec( + sys.executable, "-E", "-c", script, module, json.dumps(inputs), + cwd=workspace, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, + ) + stdout, stderr = await process.communicate() + assert process.returncode == 0, stderr.decode() + outputs = json.loads(stdout) + stage_cache = candidate.parent / "__pycache__" / cache_name + observations.append((outputs, stage_cache, stage_cache.read_bytes() != before)) + assert source_cache.read_bytes() == before + return [{"ok": True, "output": output} for output in outputs] + + task = ReconstructionTask( + input_type="integer", input_constraints="Any integer.", function_name="solve", + workspace=workspace, candidate_file=filename, oracle=lambda value: value + 3, + evaluate=evaluate, random_inputs=lambda count, exclude: [1, 2], + tools=builtin_tools("file_write"), + ) + result = await OpenCollab(workspace, model="scripted-local-model").workflow( + "reconstruct", + {"task": register_task(task), "random_share": 1, "early_stop": 1, "max_iterations": 1}, + llm=Model(filename, [source]), budget=60_000, limit_mode="explicit", trace=False, + ) + assert result.ok, result.reason + assert [outputs for outputs, _, _ in observations] == [[4, 5], [4, 5]] + assert all(distinct and not cache.exists() for _, cache, distinct in observations) + assert result.output["promotions"] == 1 diff --git a/tests/workflows/test_reconstruct_workflow.py b/tests/workflows/test_reconstruct_workflow.py index 8788f780..52feddb0 100644 --- a/tests/workflows/test_reconstruct_workflow.py +++ b/tests/workflows/test_reconstruct_workflow.py @@ -3,9 +3,14 @@ from __future__ import annotations import asyncio +import errno +import importlib import json +import shutil +import stat +import sys from pathlib import Path -from typing import Any +from typing import Any, Callable import pytest @@ -61,7 +66,7 @@ def __call__(self, k: int, exclude: set[str]) -> list[Any]: async def _evaluate(program: Path, inputs: list[Any]) -> list[dict[str, Any]]: - namespace: dict[str, Any] = {} + namespace: dict[str, Any] = {"__file__": str(program)} exec(program.read_text(encoding="utf-8"), namespace) # noqa: S102 - test-authored candidates only results = [] for inp in inputs: @@ -86,6 +91,7 @@ async def incomplete_evaluation(_program: Path, inputs: list[Any]) -> list[dict[ _run(task, ctx, max_iterations=1, early_stop=1) assert (tmp_path / task.candidate_file).is_file() + assert not list((tmp_path / ".oc_candidates").iterdir()) def test_missing_candidate_reports_no_examples_passed(tmp_path: Path) -> None: @@ -103,6 +109,23 @@ async def agent(self, prompt: str, *, schema=None, **kwargs): assert result["final_score"] is None +@pytest.mark.parametrize("error_number", sorted({errno.ENOTSUP, errno.EOPNOTSUPP})) +def test_reconstruct_evaluates_a_standalone_script_without_symlinks( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, error_number: int, +) -> None: + def unsupported_symlink(*args, **kwargs): + raise OSError(error_number, "filesystem does not support symlinks") + + monkeypatch.setattr(Path, "symlink_to", unsupported_symlink) + task = make_task(tmp_path) + result = _run(task, ScriptedContext(tmp_path, programs=[CORRECT]), max_iterations=1, early_stop=1) + + assert result["promotions"] == 1 + assert (tmp_path / task.candidate_file).read_text(encoding="utf-8") == CORRECT + assert (tmp_path / ".oc_candidates" / result["final_program"]).read_text(encoding="utf-8") == CORRECT + assert not list(tmp_path.glob("_oc_evaluate_*")) + + @pytest.mark.parametrize("random_value", [(2, -3), [2, -3]]) def test_random_tuple_and_agent_json_list_count_as_one_input( tmp_path: Path, random_value: tuple[int, int] | list[int] @@ -221,8 +244,16 @@ def make_task(workspace: Path, **overrides: Any) -> ReconstructionTask: class ScriptedContext: """Plays the agent: writes the scripted candidate, proposes fresh inputs, spends no tokens.""" - def __init__(self, workspace: Path, programs: list[str] | None = None, repeat_first_proposal: bool = False): + def __init__( + self, + workspace: Path, + programs: list[str] | None = None, + repeat_first_proposal: bool = False, + *, + candidate_file: str = "candidate.py", + ): self.workspace = workspace + self.candidate_file = candidate_file self.programs = list(programs or [CORRECT]) self.repeat_first_proposal = repeat_first_proposal self.labels: list[str] = [] @@ -254,7 +285,7 @@ async def agent(self, prompt: str, *, label: str, tools: list[Any], schema: dict batch.append([self._next, -3]) return {"inputs": batch} program = self.programs.pop(0) if len(self.programs) > 1 else self.programs[0] - (self.workspace / "candidate.py").write_text(program, encoding="utf-8") + (self.workspace / self.candidate_file).write_text(program, encoding="utf-8") return "done" @@ -505,6 +536,367 @@ def test_selection_ignores_candidates_left_by_an_earlier_run(tmp_path: Path) -> assert (stale_dir / "iter_050.py").read_text(encoding="utf-8") == stale # left untouched +async def test_evaluated_candidate_survives_edit_to_live_program(tmp_path: Path) -> None: + candidate_file = "src/candidate.py" + program = tmp_path / candidate_file + program.parent.mkdir() + (program.parent / "offset.txt").write_text("5\n", encoding="utf-8") + source = ( + "from pathlib import Path\n" + "def solve(xs):\n" + " offset = int(Path(__file__).with_name('offset.txt').read_text())\n" + " return sum(abs(x) for x in xs) + offset\n" + ) + evaluated, edited = asyncio.Event(), asyncio.Event() + evaluated_paths = [] + + class ExecutableCandidate(ScriptedContext): + async def agent(self, *args, **kwargs): + value = await super().agent(*args, **kwargs) + if program.is_file(): + program.chmod(0o750) + return value + + async def evaluate(path: Path, inputs: list[Any]) -> list[dict[str, Any]]: + assert path.parent != program.parent + assert path.name == program.name + assert stat.S_IMODE(path.stat().st_mode) == 0o750 + assert path.read_text(encoding="utf-8") == source + results = await _evaluate(path, inputs) + evaluated_paths.append(path) + if len(evaluated_paths) == 1: + evaluated.set() + await edited.wait() + return results + + async def edit_program() -> None: + await evaluated.wait() + program.write_text("def solve(xs):\n return 0\n", encoding="utf-8") + edited.set() + + task = make_task( + tmp_path, candidate_file=candidate_file, evaluate=evaluate, oracle=lambda value: _oracle(value) + 5, + ) + context = ExecutableCandidate(tmp_path, programs=[source], candidate_file=candidate_file) + result, _ = await asyncio.wait_for(asyncio.gather( + reconstruct(context, {"task": register_task(task), "early_stop": 1}), + edit_program(), + ), timeout=5) + archived = tmp_path / ".oc_candidates" / result["final_program"] + assert result["promotions"] == 1 + assert result["stop_reason"] == "early_stop" + assert result["final_score"] == 1.0 + assert len(set(evaluated_paths)) == 2 + assert all(not path.exists() for path in evaluated_paths) + assert set(program.parent.iterdir()) == {program, program.parent / "offset.txt"} + assert archived.read_text(encoding="utf-8") == program.read_text(encoding="utf-8") == source + assert stat.S_IMODE(archived.stat().st_mode) == stat.S_IMODE(program.stat().st_mode) == 0o750 + + +@pytest.mark.parametrize("relative", [False, True], ids=["absolute-workspace", "relative-workspace"]) +@pytest.mark.parametrize("writable", [True, False], ids=["writable-root", "read-only-root"]) +@pytest.mark.parametrize( + "sidecar", [None, ".json", ".resources"], ids=["plain-module", "resource-file", "resource-directory"], +) +async def test_reconstruct_evaluator_can_run_the_candidate_as_a_module( + tmp_path, monkeypatch, relative, writable, sidecar, +): + monkeypatch.chdir(tmp_path.parent) + workspace = Path(tmp_path.name) if relative else tmp_path + candidate_file = "src/solver/candidate.py" + package = workspace / "src" / "solver" + package.mkdir(parents=True) + (package / "__init__.py").touch() + (package.parent / "__init__.py").touch() + helper_package = package.parent / "_oc_evaluate_helpers" + helper_package.mkdir() + (helper_package / "__init__.py").write_text("def measure(xs):\n return sum(abs(x) for x in xs)\n") + source = ( + "from pkgutil import resolve_name\n" + "from .._oc_evaluate_helpers import measure\n" + "assert resolve_name(f\"{__package__.rsplit('.', 1)[0]}._oc_evaluate_helpers:measure\") is measure\n" + ) + module = importlib.import_module("opencollab.builtin_workflows.reconstruct") + make_temporary = module.mkdtemp + + def deny_workspace_creation(*, dir, **kwargs): + if dir == workspace: + raise PermissionError(errno.EACCES, "workspace forbids new directories") + return make_temporary(dir=dir, **kwargs) + + if not writable: + monkeypatch.setattr(module, "mkdtemp", deny_workspace_creation) + if sidecar: + resource_path = package / f"candidate{sidecar}" + lookup = f"Path(__file__).with_suffix({sidecar!r})" + if sidecar == ".resources": + resource_path.mkdir() + resource_path /= "offset.json" + lookup += " / 'offset.json'" + resource_path.write_text('{"offset": 5}', encoding="utf-8") + source += ( + "from pathlib import Path\n" + "import json\n" + "def solve(value):\n" + f" offset = json.loads(({lookup}).read_text())['offset']\n" + " return measure(value) + offset\n" + ) + else: + source += "solve = measure\n" + source += ( + "if __name__ == '__main__':\n" + " import json, sys\n" + " from pathlib import Path\n" + " assert Path(__file__).samefile(sys.argv[2])\n" + " print(json.dumps([solve(value) for value in json.loads(sys.argv[1])]))\n" + ) + evaluated = [] + + async def evaluate(path, inputs): + evaluated.append(path) + parts = path.relative_to(workspace).with_suffix("").parts + original_parts = Path(candidate_file).with_suffix("").parts + assert parts[-len(original_parts):] == original_parts + assert path.name == "candidate.py" + assert parts[0 if writable else 2].startswith("_oc_evaluate_") + module = ".".join(parts) + process = await asyncio.create_subprocess_exec( + sys.executable, "-B", "-m", module, json.dumps(inputs), str(path.absolute()), + cwd=workspace, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, + ) + stdout, stderr = await process.communicate() + assert process.returncode == 0, stderr.decode() + return [{"ok": True, "output": value} for value in json.loads(stdout)] + + task = make_task( + workspace, candidate_file=candidate_file, evaluate=evaluate, + oracle=lambda value: _oracle(value) + (5 if sidecar else 0), + ) + result = await reconstruct( + ScriptedContext(workspace, programs=[source], candidate_file=candidate_file), + {"task": register_task(task), "early_stop": 1}, + ) + assert result["promotions"] == 1 and result["stop_reason"] == "early_stop" + assert result["final_score"] == result["events"][-1]["score"] + assert len(evaluated) == 2 + assert all(not path.exists() for path in evaluated) + if sidecar: + aliases = [path.with_suffix(sidecar) for path in evaluated] + assert all(not path.exists() and not path.is_symlink() for path in aliases) + assert resource_path.read_text(encoding="utf-8") == '{"offset": 5}' + assert (workspace / candidate_file).read_text(encoding="utf-8") == source + assert (workspace / ".oc_candidates" / result["final_program"]).read_text(encoding="utf-8") == source + + +@pytest.mark.parametrize("relative", [False, True], ids=["absolute-workspace", "relative-workspace"]) +@pytest.mark.parametrize( + ("neighbor", "evaluation_fails"), + [("import", False), ("package", False), ("resource", False), ("resource", True)], + ids=["sibling-import", "sibling-package", "sibling-resource", "evaluator-error"], +) +async def test_reconstruct_evaluates_a_writable_file_in_a_read_only_workspace( + tmp_path, monkeypatch, relative, neighbor, evaluation_fails, +): + monkeypatch.chdir(tmp_path.parent) + workspace = Path(tmp_path.name) if relative else tmp_path + candidate_file = "src/solver/candidate.py" + program = workspace / candidate_file + program.parent.mkdir(parents=True) + program.write_text("# Existing editable candidate.\n", encoding="utf-8") + helper = program.with_name("sibling.py") + helper.write_text("MULTIPLIER = 3\n", encoding="utf-8") + package = program.with_name("sibling_package") + package.mkdir() + (package / "__init__.py").write_text("from .arithmetic import MULTIPLIER\n", encoding="utf-8") + arithmetic = package / "arithmetic.py" + arithmetic.write_text("MULTIPLIER = 3\n", encoding="utf-8") + resource = program.with_name("multiplier.txt") + resource.write_text("3", encoding="utf-8") + dependency = { + "import": "from sibling import MULTIPLIER\n", + "package": "from sibling_package import MULTIPLIER\n", + "resource": "from pathlib import Path\n" + "MULTIPLIER = int(Path(__file__).with_name('multiplier.txt').read_text())\n", + }[neighbor] + source = dependency + ( + "import json, sys\n" + "def solve(xs):\n return MULTIPLIER * sum(abs(x) for x in xs)\n" + "print(json.dumps([solve(value) for value in json.loads(sys.argv[1])]))\n" + ) + module = importlib.import_module("opencollab.builtin_workflows.reconstruct") + make_temporary = module.mkdtemp + evaluated = [] + + def deny_workspace_creation(*, dir, **kwargs): + if dir in (workspace, program.parent): + raise PermissionError(errno.EACCES, "directory forbids creating staging directories") + return make_temporary(dir=dir, **kwargs) + + async def evaluate(path, inputs): + relative_path = path.relative_to(workspace / ".oc_candidates") + assert relative_path.parts[0].startswith("_oc_evaluate_") + assert Path(*relative_path.parts[2:]) == Path(candidate_file) + assert path.name == program.name and not path.is_symlink() + assert path.read_text(encoding="utf-8") == source + for sibling in (helper, resource): + link = path.with_name(sibling.name) + assert not link.readlink().is_absolute() + assert link.read_bytes() == sibling.read_bytes() + package_link = path.with_name(package.name) + assert not package_link.readlink().is_absolute() + assert (package_link / arithmetic.name).read_bytes() == arithmetic.read_bytes() + evaluated.append(path) + process = await asyncio.create_subprocess_exec( + sys.executable, "-B", str(path.relative_to(workspace)), json.dumps(inputs), + cwd=workspace, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, + ) + stdout, stderr = await process.communicate() + assert process.returncode == 0, stderr.decode() + path.write_text("# Evaluator changes its own copy.\n", encoding="utf-8") + if evaluation_fails: + raise ValueError("evaluator returned invalid measurements") + return [{"ok": True, "output": value} for value in json.loads(stdout)] + + monkeypatch.setattr(module, "mkdtemp", deny_workspace_creation) + task = make_task(workspace, candidate_file=candidate_file, evaluate=evaluate, oracle=lambda xs: 3 * _oracle(xs)) + run = reconstruct( + ScriptedContext(workspace, programs=[source], candidate_file=candidate_file), + {"task": register_task(task), "early_stop": 1}, + ) + archives = workspace / ".oc_candidates" + if evaluation_fails: + with pytest.raises(ValueError, match="invalid measurements"): + await run + assert len(evaluated) == 1 and not list(archives.iterdir()) + else: + result = await run + archive = archives / result["final_program"] + assert result["stop_reason"] == "early_stop" + assert result["promotions"] == 1 and result["final_score"] > 0.95 + assert len(set(evaluated)) == 2 + assert set(archives.iterdir()) == {archive} + assert archive.read_text(encoding="utf-8") == source + assert all(not path.parent.exists() for path in evaluated) + assert set(program.parent.iterdir()) == {program, resource, helper, package} + assert set(package.iterdir()) == {package / "__init__.py", arithmetic} + assert program.read_text(encoding="utf-8") == source + + +@pytest.mark.parametrize("cancel", [False, True], ids=["failure", "cancel"]) +@pytest.mark.parametrize("kind", ["archive", "evaluation directory"]) +async def test_failed_archive_cleanup_preserves_evaluator_exit(tmp_path, monkeypatch, cancel, kind): + archive = tmp_path / ".oc_candidates" / "iter_001.py" + started = asyncio.Event() + evaluator_failure = RuntimeError("candidate evaluator lost its output stream") + unlink = Path.unlink + rmtree = shutil.rmtree + evaluated_paths = [] + sidecar = tmp_path / "candidate.json" + sidecar.write_text('{"offset": 0}', encoding="utf-8") + + def fail_unlink(path, *args, **kwargs): + if kind == "archive" and path == archive: + raise OSError(errno.EIO, "candidate cleanup failed") + return unlink(path, *args, **kwargs) + + def fail_rmtree(path, *args, **kwargs): + if kind == "evaluation directory" and Path(path).name.startswith("_oc_evaluate_"): + raise OSError(errno.EIO, "candidate cleanup failed") + return rmtree(path, *args, **kwargs) + + monkeypatch.setattr(Path, "unlink", fail_unlink) + monkeypatch.setattr(shutil, "rmtree", fail_rmtree) + + async def evaluate(path, inputs): + assert path.parent != tmp_path + assert path.read_text(encoding="utf-8") == archive.read_text(encoding="utf-8") + assert path.with_suffix(".json").read_bytes() == sidecar.read_bytes() + evaluated_paths.append(path) + assert all(row["ok"] for row in await _evaluate(path, inputs)) + started.set() + if cancel: + await asyncio.Event().wait() + raise evaluator_failure + + task = make_task(tmp_path, evaluate=evaluate) + + async def run(): + try: + await reconstruct(ScriptedContext(tmp_path), {"task": register_task(task)}) + except (RuntimeError, asyncio.CancelledError) as error: + return error + + job = asyncio.create_task(run()) + try: + if cancel: + await asyncio.wait_for(started.wait(), timeout=5) + job.cancel("cancel candidate evaluation") + error = await job + if cancel: + assert isinstance(error, asyncio.CancelledError) + assert str(error) == "cancel candidate evaluation" + else: + assert error is evaluator_failure + finally: + if not job.done(): + job.cancel() + await asyncio.gather(job, return_exceptions=True) + + note, = error.__notes__ + evaluation_path, = evaluated_paths + assert sidecar.read_text(encoding="utf-8") == '{"offset": 0}' + blocked = archive if kind == "archive" else evaluation_path + cleanup_name = archive.name if kind == "archive" else evaluation_path.parent.parent.name + assert f"candidate {kind} cleanup failed for {cleanup_name}" in note + assert "candidate cleanup failed" in note + assert blocked.read_text(encoding="utf-8") == CORRECT + if kind == "archive": + assert not evaluation_path.parent.parent.exists() + else: + assert not archive.exists() + assert (tmp_path / "candidate.py").read_text(encoding="utf-8") == CORRECT + + +@pytest.mark.parametrize("overlap", [False, True], ids=["sequential", "parallel"]) +async def test_shared_workspace_runs_keep_their_archived_candidates(tmp_path: Path, overlap: bool) -> None: + first_selecting = asyncio.Event() + second_finished = asyncio.Event() + doubled = "def solve(xs):\n return 2 * sum(abs(x) for x in xs)\n" + + class FirstContext(ScriptedContext): + async def phase(self, name: str) -> None: + await super().phase(name) + if overlap and name == "select": + first_selecting.set() + await asyncio.wait_for(second_finished.wait(), timeout=5) + + async def run(ctx: ScriptedContext, oracle: Callable[[list[int]], int]) -> dict[str, Any]: + task = make_task(tmp_path, candidate_file=ctx.candidate_file, oracle=oracle) + return await reconstruct(ctx, {"task": register_task(task), "max_iterations": 1, "early_stop": 1}) + + async def run_second() -> dict[str, Any]: + if overlap: + await asyncio.wait_for(first_selecting.wait(), timeout=5) + ctx = ScriptedContext(tmp_path, [doubled], candidate_file="doubled.py") + second = await run(ctx, lambda xs: 2 * _oracle(xs)) + second_finished.set() + return second + + first_run = run(FirstContext(tmp_path, candidate_file="absolute.py"), _oracle) + if overlap: + first, second = await asyncio.gather(first_run, run_second()) + else: + first, second = await first_run, await run_second() + + for outcome, filename, source in [(first, "absolute.py", CORRECT), (second, "doubled.py", doubled)]: + assert outcome["promotions"] == 1 + assert outcome["final_score"] == 1.0 + assert (tmp_path / filename).read_text(encoding="utf-8") == source + assert (tmp_path / ".oc_candidates" / outcome["final_program"]).read_text(encoding="utf-8") == source + assert first["final_program"] == "iter_001.py" + assert second["final_program"] != first["final_program"] + + def test_task_resolution_from_import_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: module = tmp_path / "fake_bench.py" module.write_text( diff --git a/tests/workflows/test_scheduler_cross_agent_budget_cleanup.py b/tests/workflows/test_scheduler_cross_agent_budget_cleanup.py index 3f090161..69d20f80 100644 --- a/tests/workflows/test_scheduler_cross_agent_budget_cleanup.py +++ b/tests/workflows/test_scheduler_cross_agent_budget_cleanup.py @@ -82,7 +82,7 @@ async def handler(request): ) lead = build_session( agent=Agent(name="lead", system_prompt="lead"), llm=client, - max_budget_tokens=total, llm_timeout=timeout, + max_budget_tokens=total, llm_timeout=1.0, ) scheduler.register_lead(lead) if owner_aid: diff --git a/tests/workflows/test_scheduler_late_provider_budget.py b/tests/workflows/test_scheduler_late_provider_budget.py index ee9eb102..d35e707b 100644 --- a/tests/workflows/test_scheduler_late_provider_budget.py +++ b/tests/workflows/test_scheduler_late_provider_budget.py @@ -31,6 +31,8 @@ async def release(self) -> None: return None class _LateProvider: + supports_request_admission = True + def __init__(self, *, late_error: bool = False, block: bool = False) -> None: self.cancel_seen = asyncio.Event() self.release_late = asyncio.Event() @@ -38,8 +40,9 @@ def __init__(self, *, late_error: bool = False, block: bool = False) -> None: self.late_error = late_error self.block = block - async def complete(self, messages, tools=None, temperature=0.0, **kwargs): + async def complete(self, messages, tools=None, temperature=0.0, *, on_admitted, **kwargs): del messages, tools, temperature, kwargs + on_admitted() self.started.set() if self.block: await asyncio.Event().wait() @@ -89,7 +92,7 @@ async def test_late_provider_usage_stays_reserved_after_child_terminal(): provider = factory.providers[first] try: - await asyncio.wait_for(provider.cancel_seen.wait(), timeout=0.5) + await asyncio.wait_for(provider.cancel_seen.wait(), timeout=2) await asyncio.wait_for(first_task, timeout=0.5) assert scheduler.table.get(first).state.phase is SessionPhase.ERROR assert scheduler._turn_lease.get(first) is None @@ -136,7 +139,7 @@ async def test_late_provider_failure_releases_unused_budget_reservation(): provider.late_error = True try: - await asyncio.wait_for(provider.cancel_seen.wait(), timeout=0.5) + await asyncio.wait_for(provider.cancel_seen.wait(), timeout=2) await asyncio.wait_for(first_task, timeout=0.5) assert scheduler.allocated_tokens == 200_000 diff --git a/tests/workflows/test_scheduler_queued_restore.py b/tests/workflows/test_scheduler_queued_restore.py index ec00c82c..e42b0275 100644 --- a/tests/workflows/test_scheduler_queued_restore.py +++ b/tests/workflows/test_scheduler_queued_restore.py @@ -5,11 +5,16 @@ import asyncio import copy import json +import threading +from contextlib import AsyncExitStack import pytest +from opencollab import OpenCollab from opencollab.adapters.env import LocalEnvironment +from opencollab.adapters.storage import SessionStore from opencollab.application.event_bus import EventBus +from opencollab.application.ports import SnapshotSequenceConflict from opencollab.application.scheduler import Scheduler from opencollab.bootstrap import build_session, load_session from opencollab.domain.agent import Agent @@ -117,6 +122,102 @@ async def wait_for_queue(): await resumed.cleanup() +@pytest.mark.parametrize("publication", ["before", "in-flight", "published"]) +async def test_cancelled_turn_admission_preserves_restored_export_order(tmp_path, monkeypatch, publication): + source, exported, working_path, backup, early_backup = ( + str(tmp_path / f"{name}.json") for name in ("source", "export", "working", "backup", "early") + ) + store = SessionStore() + options = {"agent": Agent(name="lead", system_prompt="Keep each accepted request."), "store": store} + + async def settle(session): + while session.pending_cleanup_tasks: + await asyncio.gather(*session.pending_cleanup_tasks) + + observed = asyncio.Event() + + async def hold_admission(event): + if event.type == "user_message_appended": + observed.set() + await asyncio.Future() + + async with AsyncExitStack() as resources: + environment = LocalEnvironment(str(tmp_path)) + resources.push_async_callback(environment.cleanup) + original = build_session(**options, env=environment, llm=_Provider(), auto_save_path=source, aid=0) + resources.push_async_callback(original.aclose) + await original.add_user_message("Earlier accepted request.") + assert await original.run_loop() == "answer-1" + original.save(exported) + + provider = _Provider() + working = load_session( + exported, **options, env=environment, llm=provider, auto_save_path=working_path, + event_sink=hold_admission if publication == "before" else None, + ) + resources.push_async_callback(working.aclose) + if publication != "before": + working.event_bus.subscribe(hold_admission) + scheduler = Scheduler(session_factory=object(), worktree_pool=fake_worktree_pool(), event_sink=EventBus()) + scheduler.register_lead(working) + resources.push_async_callback(scheduler.cleanup) + + await original.add_user_message("Newer request on the source.") + await settle(original) + latest_source = OpenCollab.read_session_snapshot(source) + + started, release = threading.Event(), threading.Event() + append = store.append_snapshot_delta + + def hold_first_working_write(path, **kwargs): + if path == working_path and not started.is_set(): + started.set() + assert release.wait(3) + return append(path, **kwargs) + + if publication == "in-flight": + monkeypatch.setattr(store, "append_snapshot_delta", hold_first_working_write) + + async def wait_for_rollback(): + while working.state.pending_external_user_turn is not None: + await asyncio.sleep(0) + + turn = asyncio.create_task(scheduler.run("Cancelled request on the copy.")) + try: + await asyncio.wait_for(observed.wait(), 3) + if publication == "in-flight": + assert await asyncio.to_thread(started.wait, 3) + elif publication == "published": + await working.enqueue_auto_save() + provisional = OpenCollab.read_session_snapshot(working_path) + assert provisional["session_state"]["pending_external_user_turn"]["content"] == ( + "Cancelled request on the copy." + ) + turn.cancel() + if publication == "in-flight": + await asyncio.wait_for(wait_for_rollback(), 3) + working.save(early_backup) + release.set() + with pytest.raises(asyncio.CancelledError): + await turn + finally: + release.set() + if not turn.done(): + turn.cancel() + await asyncio.gather(turn, return_exceptions=True) + + await settle(working) + assert working.state.pending_external_user_turn is None + assert working.messages[-1]["content"] == "answer-1" + assert provider.calls == [] + working.save(backup) + copies = (early_backup, backup) if publication == "in-flight" else (backup,) + for copy_path in copies: + with pytest.raises(SnapshotSequenceConflict): + load_session(copy_path, **options, env=environment, llm=_Provider(), auto_save_path=source) + assert OpenCollab.read_session_snapshot(source) == latest_source + + @pytest.mark.parametrize("restore_sender", [False, True]) @pytest.mark.parametrize("completed_driver", [False, True]) async def test_active_restore_rejects_missing_sender_without_blocking_new_turn( @@ -174,6 +275,13 @@ async def test_active_restore_rejects_missing_sender_without_blocking_new_turn( assert await asyncio.wait_for(first, 2) == f"answer-{expected_calls}" assert len(continuation.calls) == expected_calls assert continuation.calls[-1][-1]["content"].startswith("new request") + second_snapshot = tmp_path / "second-step.json" + + def save_second_step(event): + if event.type == "step_start": + restored.save(str(second_snapshot)) + + restored.event_bus.subscribe(save_second_step) assert await resumed.run("second request") == f"answer-{expected_calls + 1}" deliveries = [message for message in restored.messages if message["role"] == "user" and "QUEUED_WORK" in message["content"]] @@ -192,6 +300,28 @@ async def test_active_restore_rejects_missing_sender_without_blocking_new_turn( assert restored.phase is SessionPhase.DONE assert restored.state.pending_external_user_turn is None assert not resumed._message_inbox.get(0) + + second_state = OpenCollab.read_session_snapshot(second_snapshot) + assert second_state["session_state"]["phase"] == "calling_llm" + assert [item["delivery_status"] for item in second_state.get("pending_messages", [])] == ( + [] if restore_sender else ["rejected"] + ) + next_provider = _Provider() + reopened_lead = load_session( + str(second_snapshot), agent=Agent(name="lead", system_prompt="lead"), llm=next_provider, + env=LocalEnvironment(str(tmp_path)), + ) + reopened = Scheduler( + session_factory=_Factory(_Provider()), worktree_pool=fake_worktree_pool(), event_sink=EventBus(), + ) + reopened.register_lead(reopened_lead) + try: + assert await asyncio.wait_for(reopened.run("third request"), 2) == "answer-2" + assert len(next_provider.calls) == 2 + assert next_provider.calls[0][-1]["content"].startswith("second request") + assert next_provider.calls[1][-1]["content"].startswith("third request") + finally: + await reopened.cleanup() finally: continuation.release.set() await resumed.cleanup() diff --git a/tests/workflows/test_stop_notice_lifecycle.py b/tests/workflows/test_stop_notice_lifecycle.py index 4d902381..2a4e2ce2 100644 --- a/tests/workflows/test_stop_notice_lifecycle.py +++ b/tests/workflows/test_stop_notice_lifecycle.py @@ -19,6 +19,45 @@ def _seat(scheduler, session, aid): ) scheduler._sessions[aid] = session + +@pytest.mark.parametrize("driver_delivers", [False, True]) +async def test_fallback_notice_waits_for_terminal_driver(driver_delivers): + lead = ScriptedSession("lead", []) + stopped = ScriptedSession("coder", []) + scheduler, _ = build_scheduler(lead, []) + _seat(scheduler, stopped, 1) + stopped.state.cancel("output limit") + scheduler._unanswered[1] = {0: "request"} + release_driver = asyncio.Event() + partial = "[Partial response]\nVerified subtotal is 42." + + async def finish(): + await release_driver.wait() + if driver_delivers: + await scheduler.notify_unanswered_senders(1, "output limit", partial_result=partial) + + driver = asyncio.create_task(finish()) + delivery_blocker = asyncio.create_task(asyncio.Event().wait()) + scheduler._tasks.update({0: delivery_blocker, 1: driver}) + try: + await scheduler._drain_ready_message_inboxes() + assert scheduler._unanswered[1] == {0: "request"} + assert not lead.state.pending_user_messages + + release_driver.set() + await driver + await scheduler._drain_ready_message_inboxes() + + notice, = lead.state.pending_user_messages + assert "output limit" in notice["content"] + assert (partial in notice["content"]) is driver_delivers + assert not scheduler._unanswered.get(1) + finally: + release_driver.set() + delivery_blocker.cancel() + await asyncio.gather(driver, delivery_blocker, return_exceptions=True) + + @pytest.mark.parametrize("locked_aid", [0, 2]) async def test_cancelling_notice_lock_wait_retains_each_uncommitted_sender(locked_aid): lead = ScriptedSession("lead", []) diff --git a/tests/workflows/test_weave_execution.py b/tests/workflows/test_weave_execution.py index e0080558..1bec5e32 100644 --- a/tests/workflows/test_weave_execution.py +++ b/tests/workflows/test_weave_execution.py @@ -7,6 +7,7 @@ import json import shlex import sys +from types import SimpleNamespace import pytest @@ -21,6 +22,7 @@ plan_weave_groups, run_weave, ) +from opencollab.builtin_workflows.weave import _execution as weave_execution from opencollab.tools import builtin_tools, has_pass_evidence from tests.support.installed_weave_smoke import exercise_weave @@ -791,7 +793,10 @@ async def first(ctx, _args): assert settled.is_set() assert (tmp_path / "result.txt").read_text() == "correct\n" assert len(model.calls) == 2 - state = WeaveState(interrupted.saved[-1]) + cancelled_checkpoint = interrupted.saved[-1] + assert cancelled_checkpoint["status"] == "cancelled" + assert cancelled_checkpoint["error_type"] == "CancelledError" + state = WeaveState(cancelled_checkpoint) original_tokens = state.tokens resumed = FileChecks(tmp_path) @@ -807,6 +812,522 @@ async def second(ctx, _args): assert result.tokens == 0 assert state.tokens == original_tokens == 12 assert resumed.checks and all(check.executed and check.ok for check in resumed.checks) + assert result.output["state"]["status"] == resumed.saved[-1]["status"] == "completed" + assert "error_type" not in result.output["state"] + assert "error_type" not in resumed.saved[-1] + assert cancelled_checkpoint["error_type"] == "CancelledError" + +@pytest.mark.parametrize("repair_passes", [True, False]) +@pytest.mark.parametrize("legacy", [False, True]) +async def test_cancelled_repair_resumes_at_verification(tmp_path, repair_passes, legacy): + entering_check = asyncio.Event() + previous_checks = 2 if repair_passes else 3 + + class Interrupted(FileChecks): + async def verify(self, ctx, targets, seconds): + if len(self.checks) == previous_checks: + entering_check.set() + await asyncio.Event().wait() + return await super().verify(ctx, targets, seconds) + + model = FileModel(repaired="correct\n" if repair_passes else "wrong\n") + config = _config(max_repair_rounds=5, stagnant_round_limit=2) + adapter = Interrupted(tmp_path) + state = None + + async def flow(ctx, _args): + return await run_weave(ctx, [WeaveGroup("result", "write-stage")], + config=config, adapter=adapter, state=state) + + options = dict(llm=model, budget=20_000, limit_mode="explicit", trace=False, + run_id="resume-repair", agent_profile="single2") + running = asyncio.create_task(_client(tmp_path).workflow(flow, **options)) + try: + await asyncio.wait_for(entering_check.wait(), 5) + finally: + running.cancel() + with pytest.raises(asyncio.CancelledError): + await running + + saved = json.loads(json.dumps(adapter.saved[-1])) + pending = saved["repair_rounds"][-1] + assert pending["status"] == "running" + original_result = pending["result"] + if legacy: + pending.pop("result") + state = WeaveState(saved) + tokens_before = state.tokens + calls_before = len(model.calls) + adapter = FileChecks(tmp_path) + result = await _client(tmp_path).workflow(flow, **options) + + extra_calls = 2 if legacy and not repair_passes else 0 + assert result.ok and result.output["delivery_ok"] is repair_passes + assert len(model.calls) == calls_before + extra_calls + assert result.output["total_tokens"] == tokens_before + 6 * extra_calls + assert result.tokens == 6 * extra_calls + assert len(adapter.checks) == 1 + extra_calls // 2 + assert all(check.executed for check in adapter.checks) + rounds = result.output["repair_rounds"] + assert len(rounds) == len(saved["repair_rounds"]) + extra_calls // 2 + restored = rounds[pending["round"] - 1] + assert restored["status"] == ("interrupted" if legacy else "completed") + if not legacy: + assert restored["session_id"] == original_result["session_id"] + assert restored["tokens"] == 12 and restored["steps"] == 2 + assert result.output["repair_stop_reason"] == ( + "passed" if repair_passes else "rounds_without_observable_progress" + ) + if not repair_passes: + assert rounds[-1]["stagnant_rounds"] == 2 + +@pytest.mark.parametrize("partial", [False, True]) +async def test_skipped_verification_keeps_the_completed_repair_pending(tmp_path, monkeypatch, partial): + entering_check = asyncio.Event() + config = _config(max_repair_rounds=3, stagnant_round_limit=1, final_check_time_reserve=5) + format_runs = tmp_path / "format-ran.txt" + value_runs = tmp_path / "checks-ran.txt" + (tmp_path / "check_format.py").write_text( + "from pathlib import Path\n" + "with Path('format-ran.txt').open('a') as stream: stream.write('executed\\n')\n" + "assert Path('result.txt').read_text().endswith('\\n')\n" + "print('FORMAT_OK')\n", + encoding="utf-8", + ) + + class Checks(FileChecks): + def __init__(self, mode=None): + super().__init__(tmp_path) + self.mode = mode + self.check_commands = ({ + "command": f"{shlex.quote(sys.executable)} check_format.py", "expected_output": "FORMAT_OK", + }, *self.check_commands) + + async def verify(self, ctx, targets, seconds): + if self.mode == "interrupt" and targets is None and len(self.checks) == 2: + first = WeaveAdapter(check_commands=self.check_commands[:1]) + assert (await first.verify(ctx, targets, seconds)).passed + entering_check.set() + await asyncio.Event().wait() + if self.mode == "partial" and targets is None: + previous = format_runs.read_bytes() + + def clock(): + return 0 if format_runs.read_bytes() == previous else 11 + + with monkeypatch.context() as scoped: + scoped.setattr(weave_execution, "time", SimpleNamespace(monotonic=clock)) + return await super().verify(ctx, targets, 10) + return await super().verify(ctx, targets, seconds) + + adapter = Checks("interrupt") + model = FileModel(initial="wrong", repaired="wrong\n") + options = dict(llm=model, budget=20_000, limit_mode="explicit", trace=False, + run_id="resume-after-skipped-check", agent_profile="single2") + + async def flow(ctx, args): + return await run_weave( + ctx, [WeaveGroup("result", "write-stage")], config=config, adapter=adapter, + state=WeaveState(args["state"]) if "state" in args else None, + ) + + running = asyncio.create_task(_client(tmp_path).workflow(flow, **options)) + try: + await asyncio.wait_for(entering_check.wait(), 5) + finally: + running.cancel() + with pytest.raises(asyncio.CancelledError): + await running + + interrupted = json.loads(json.dumps(adapter.saved[-1])) + previous_verification = interrupted["verification"] + assert previous_verification["executed"] and previous_verification["progress_markers"] == [] + pending, = interrupted["repair_rounds"] + assert pending["result"]["status"] == "completed" + assert len(model.calls) == 4 + + format_before, value_before = format_runs.read_bytes(), value_runs.read_bytes() + adapter = Checks("partial" if partial else None) + short = await _client(tmp_path).workflow( + flow, {"state": interrupted}, timeout=None if partial else 2, **options, + ) + assert short.ok and short.output["status"] == "unverified" + assert short.output["repair_stop_reason"] == "environment_or_unverified" + assert short.tokens == 0 and short.output["total_tokens"] == 24 and len(model.calls) == 4 + assert value_runs.read_bytes() == value_before + assert format_runs.read_bytes() == format_before + (b"executed\n" if partial else b"") + saved = json.loads(json.dumps(adapter.saved[-1])) + assert saved["verification"] == json.loads(json.dumps(short.output["verification"])) + assert [row["executed"] for row in saved["verification"]["report"]["checks"]] == [partial, False] + pending_after, = saved["repair_rounds"] + assert pending_after["status"] == "running" and pending_after["result"] == pending["result"] + assert "stagnant_rounds" not in pending_after + + adapter = Checks() + model.repaired = "correct\n" + resumed = await _client(tmp_path).workflow(flow, {"state": saved}, **options) + assert resumed.ok and resumed.output["delivery_ok"] is True + assert resumed.tokens == 12 and resumed.output["total_tokens"] == 36 and len(model.calls) == 6 + assert (tmp_path / "result.txt").read_text() == "correct\n" + assert len(adapter.checks) == 2 and all(check.executed for check in adapter.checks) + first, second = resumed.output["repair_rounds"] + assert first["session_id"] == pending["result"]["session_id"] + assert first["status"] == second["status"] == "completed" + assert first["observable_progress"] is True and first["stagnant_rounds"] == 0 + +async def test_repair_check_timeout_resumes_from_disk(tmp_path): + checkpoint = tmp_path / "state.json" + started = tmp_path / "check-started" + finished = tmp_path / "check-finished" + script = r""" +from pathlib import Path +from time import sleep + +assert Path("result.txt").read_text() == "correct\n" +started = Path("check-started") +if not started.exists(): + started.touch() + sleep(30) +Path("check-finished").touch() +print("RESULT_OK") +""" + + class DiskChecks(FileChecks): + def __init__(self): + super().__init__(tmp_path) + (tmp_path / "check_result.py").write_text(script, encoding="utf-8") + + def save_state(self, data): + temporary = checkpoint.with_suffix(".tmp") + temporary.write_text(json.dumps(data), encoding="utf-8") + temporary.replace(checkpoint) + + adapter = DiskChecks() + model = FileModel() + config = _config(max_repair_rounds=1, stagnant_round_limit=1, final_check_timeout=1) + options = dict(llm=model, budget=20_000, limit_mode="explicit", trace=False, run_id="resume-timed-out-check") + + async def flow(ctx, args): + return await run_weave( + ctx, [WeaveGroup("result", "write-stage")], config=config, adapter=adapter, + state=WeaveState(args["state"]) if "state" in args else None, + ) + + first = await _client(tmp_path).workflow(flow, **options) + assert first.ok and first.output["status"] == "unverified" + assert first.output["repair_stop_reason"] == "environment_or_unverified" + assert started.is_file() and not finished.exists() + assert (tmp_path / "result.txt").read_text() == "correct\n" + assert first.tokens == 24 and len(model.calls) == 4 + assert adapter.checks[1].executed and adapter.checks[1].repair_targets + assert adapter.checks[-1].executed and not adapter.checks[-1].repair_targets + assert first.output["verification"]["executed"] is True + row, = first.output["verification"]["report"]["checks"] + assert row["executed"] and row["timed_out"] and row["reason"] == "verification command timed out" + + saved = json.loads(checkpoint.read_text(encoding="utf-8")) + pending, = saved["repair_rounds"] + assert pending["status"] == "running" and pending["result"]["tokens"] == 12 + assert "stagnant_rounds" not in pending + assert not any(kind == "repair_finished" for kind, _ in adapter.updates) + + adapter = DiskChecks() + config.final_check_timeout = 3 + resumed = await _client(tmp_path).workflow(flow, {"state": saved}, **options) + assert resumed.ok and resumed.output["delivery_ok"] and finished.is_file() + assert resumed.tokens == 0 and resumed.output["total_tokens"] == 24 and len(model.calls) == 4 + assert len(adapter.checks) == 1 and adapter.checks[0].passed + repaired, = json.loads(checkpoint.read_text(encoding="utf-8"))["repair_rounds"] + assert repaired["status"] == "completed" and repaired["session_id"] == pending["result"]["session_id"] + assert repaired["observable_progress"] and repaired["stagnant_rounds"] == 0 + assert [kind for kind, _ in adapter.updates].count("repair_finished") == 1 + + +@pytest.mark.parametrize("noisy_failure", [False, True], ids=["concise-failure", "truncated-failure"]) +async def test_repair_stays_pending_after_truncated_pytest_output(tmp_path, noisy_failure): + test_file = tmp_path / "test_delivery.py" + test_file.write_text( + "from pathlib import Path\n" + "def test_delivery():\n" + " correct = Path('result.txt').read_text() == 'correct\\n'\n" + f" if not Path('quiet-logs').exists() and (correct or {noisy_failure!r}):\n" + " for index in range(12000):\n" + " print(f'Processed example {index:05d}: ' + 'sample ' * 14)\n" + " assert correct\n", + encoding="utf-8", + ) + command = f"{shlex.quote(sys.executable)} -m pytest -q -s -p no:cacheprovider {test_file.name}" + + class PytestChecks(FileChecks): + def __init__(self): + super().__init__(tmp_path) + self.check_commands = (command,) + + adapter = PytestChecks() + model = FileModel() + config = _config(max_repair_rounds=1, stagnant_round_limit=1) + + async def flow(ctx, args): + return await run_weave( + ctx, [WeaveGroup("result", "write-stage")], config=config, adapter=adapter, + state=WeaveState(args["state"]) if "state" in args else None, + ) + + options = dict(llm=model, budget=20_000, limit_mode="explicit", trace=False, run_id="resume-truncated-pytest") + first = await _client(tmp_path).workflow(flow, **options) + assert first.ok and first.output["status"] == "unverified" + assert first.output["repair_stop_reason"] == "environment_or_unverified" + assert (tmp_path / "result.txt").read_text(encoding="utf-8") == "correct\n" + assert first.tokens == 24 and len(model.calls) == 4 + failed, = adapter.checks[1].report["checks"] + assert failed["exit_code"] == 1 and failed["ok"] is False + assert failed.get("output_truncated", False) is noisy_failure + assert adapter.checks[1].report["evidence_incomplete"] is False + assert adapter.checks[1].repair_targets == (command,) + report = first.output["verification"]["report"] + assert report["evidence_incomplete"] is True + truncated, = report["checks"] + assert truncated["executed"] and truncated["exit_code"] == 0 + assert truncated["output_truncated"] and truncated["reason"] == "verification command output was truncated" + assert truncated["test_records"][0]["verified"] is False + assert adapter.checks[-1].repair_targets == () + + saved = json.loads(json.dumps(adapter.saved[-1])) + pending, = saved["repair_rounds"] + assert pending["status"] == "running" and pending["result"]["status"] == "completed" + assert "stagnant_rounds" not in pending + assert not any(kind == "repair_finished" for kind, _ in adapter.updates) + + (tmp_path / "quiet-logs").touch() + adapter = PytestChecks() + resumed = await _client(tmp_path).workflow(flow, {"state": saved}, **options) + assert resumed.ok and resumed.output["delivery_ok"] is True + assert resumed.tokens == 0 and resumed.output["total_tokens"] == 24 and len(model.calls) == 4 + verified, = adapter.checks + assert verified.passed and verified.report["checks"][0]["test_records"][0]["verified"] is True + repaired, = resumed.output["repair_rounds"] + assert repaired["status"] == "completed" and repaired["session_id"] == pending["result"]["session_id"] + assert repaired["observable_progress"] and repaired["stagnant_rounds"] == 0 + assert [kind for kind, _ in adapter.updates].count("repair_finished") == 1 + + +async def test_truncated_pytest_output_keeps_other_failures_repairable(tmp_path): + test_file = tmp_path / "test_verbose.py" + test_file.write_text( + "from pathlib import Path\n" + "def test_delivery():\n" + " if not Path('quiet-logs').exists():\n" + " for index in range(12000):\n" + " print(f'Processed example {index:05d}: ' + 'sample ' * 14)\n" + " assert 6 * 7 == 42\n", + encoding="utf-8", + ) + verbose = f"{shlex.quote(sys.executable)} -m pytest -q -s -p no:cacheprovider {test_file.name}" + model = FileModel() + + class MixedChecks(FileChecks): + def __init__(self): + super().__init__(tmp_path) + self.check_commands = (*self.check_commands, verbose) + + def repair_prompt(self, check, state): + model.repaired = "partially corrected\n" if len(state.data["repair_rounds"]) == 1 else "correct\n" + return super().repair_prompt(check, state) + + adapter = MixedChecks() + config = _config(max_repair_rounds=2, stagnant_round_limit=2) + + async def flow(ctx, args): + return await run_weave( + ctx, [WeaveGroup("result", "write-stage")], config=config, adapter=adapter, + state=WeaveState(args["state"]) if "state" in args else None, + ) + + options = dict(llm=model, budget=20_000, limit_mode="explicit", trace=False, run_id="mixed-truncated-pytest") + first = await _client(tmp_path).workflow(flow, **options) + assert first.ok and first.output["status"] == "unverified" + assert (tmp_path / "result.txt").read_text(encoding="utf-8") == "correct\n" + assert first.tokens == 36 and len(model.calls) == 6 + first_repair, second_repair = first.output["repair_rounds"] + assert first_repair["status"] == "completed" and first_repair["stagnant_rounds"] == 1 + assert second_repair["status"] == "running" and second_repair["result"]["status"] == "completed" + remaining_failure = adapter.checks[-2] + assert remaining_failure.repair_targets == (adapter.check_commands[0]["command"],) + assert remaining_failure.report["evidence_incomplete"] is True + fixed, truncated = first.output["verification"]["report"]["checks"] + assert fixed["ok"] is True and truncated["output_truncated"] and truncated["ok"] is False + + saved = json.loads(json.dumps(adapter.saved[-1])) + (tmp_path / "quiet-logs").touch() + adapter = MixedChecks() + resumed = await _client(tmp_path).workflow(flow, {"state": saved}, **options) + assert resumed.ok and resumed.output["delivery_ok"] is True + assert resumed.tokens == 0 and len(model.calls) == 6 + original, verified = resumed.output["repair_rounds"] + assert original == first_repair + assert verified["status"] == "completed" and verified["session_id"] == second_repair["result"]["session_id"] + assert verified["observable_progress"] and verified["stagnant_rounds"] == 0 + + +async def test_truncated_nonpytest_exit_five_is_repairable(tmp_path): + adapter = FileChecks(tmp_path) + (tmp_path / "check_result.py").write_text( + "from pathlib import Path\n" + "if Path('result.txt').read_text() != 'correct\\n':\n" + " for index in range(12000):\n" + " print(f'Analyzed record {index:05d}: ' + 'unmatched ' * 12)\n" + " raise SystemExit(5)\n" + "print('RESULT_OK')\n", + encoding="utf-8", + ) + model = FileModel() + + async def flow(ctx, _args): + return await run_weave( + ctx, [WeaveGroup("result", "write-stage")], config=_config(max_repair_rounds=1), adapter=adapter, + ) + + result = await _client(tmp_path).workflow(flow, llm=model, budget=20_000, limit_mode="explicit", trace=False) + assert result.ok and result.output["delivery_ok"] is True + assert (tmp_path / "result.txt").read_text(encoding="utf-8") == "correct\n" + assert result.tokens == 24 and len(model.calls) == 4 + failed, = adapter.checks[1].report["checks"] + assert failed["exit_code"] == 5 and failed["output_truncated"] and failed["ok"] is False + assert adapter.checks[1].repair_targets == (failed["command"],) + repaired, = result.output["repair_rounds"] + assert repaired["status"] == "completed" + + +async def test_repair_progress_error_preserves_the_latest_check(tmp_path): + progress_file = tmp_path / "progress.json" + progress_file.mkdir() + + class ProgressReport(FileChecks): + def improved(self, before, after): + advanced = super().improved(before, after) + progress_file.write_text(json.dumps(advanced), encoding="utf-8") + return advanced + + adapter = ProgressReport(tmp_path) + model = FileModel() + + async def flow(ctx, args): + state = WeaveState(args["state"]) if "state" in args else None + return await run_weave(ctx, [WeaveGroup("result", "write-stage")], + config=_config(max_repair_rounds=1), adapter=adapter, state=state) + + options = dict(llm=model, budget=20_000, limit_mode="explicit", trace=False, run_id="resume-progress") + failed = await _client(tmp_path).workflow(flow, **options) + assert failed.status == "failed" and isinstance(failed.error, IsADirectoryError) + assert failed.tokens == 24 and len(model.calls) == 4 + assert [check.passed for check in adapter.checks] == [False, False, True] + assert (tmp_path / "result.txt").read_text(encoding="utf-8") == "correct\n" + saved = json.loads(json.dumps(adapter.saved[-1])) + assert saved["status"] == "failed" and saved["delivery_ok"] is False + assert saved["verification"]["ok"] is True + pending, = saved["repair_rounds"] + assert pending["status"] == "running" + assert pending["before_verification"]["ok"] is False + events = [(kind, data["number"]) for kind, data in adapter.updates + if kind in {"check_finished", "repair_finished"}] + assert events == [("check_finished", 0), ("check_finished", 1)] + + progress_file.rmdir() + adapter = ProgressReport(tmp_path) + resumed = await _client(tmp_path).workflow(flow, {"state": saved}, **options) + assert resumed.ok and resumed.output["delivery_ok"] is True + assert resumed.tokens == 0 and resumed.output["total_tokens"] == 24 and len(model.calls) == 4 + assert len(adapter.checks) == 1 and adapter.checks[0].passed + repair, = resumed.output["repair_rounds"] + assert repair["status"] == "completed" and repair["session_id"] == pending["result"]["session_id"] + assert repair["observable_progress"] is True and repair["stagnant_rounds"] == 0 + +async def test_error_checkpoint_preserves_the_verifier_error(tmp_path): + class Failing(FileChecks): + async def verify(self, ctx, targets, seconds): + await super().verify(ctx, targets, seconds) + raise ValueError("cannot read the verifier report") + + def save_state(self, data): + if data["status"] == "failed": + raise OSError("cannot write the stopped snapshot") + super().save_state(data) + + adapter = Failing(tmp_path) + + async def flow(ctx, _args): + return await run_weave(ctx, [WeaveGroup("result", "write-stage")], + config=_config(), adapter=adapter) + + result = await _client(tmp_path).workflow( + flow, llm=FileModel(initial="correct\n"), budget=20_000, trace=False, + ) + assert adapter.checks[0].executed + assert result.status == "failed" and isinstance(result.error, ValueError) + assert str(result.error) == "cannot read the verifier report" + assert any("cannot write the stopped snapshot" in note for note in result.error.__notes__) + +@pytest.mark.parametrize("cancelled", [False, True]) +async def test_failed_repair_heartbeat_preserves_the_solver_exit(tmp_path, cancelled): + heartbeat_failed, awaiting_cancel = asyncio.Event(), asyncio.Event() + errors = [] + + class BrokenHeartbeat(FileChecks): + fail_snapshot = False + + def on_update(self, kind, state, data): + if kind == "heartbeat" and data["phase"] == "repair-1": + self.fail_snapshot = True + super().on_update(kind, state, data) + + def save_state(self, data): + if self.fail_snapshot: + self.fail_snapshot = False + heartbeat_failed.set() + raise OSError("heartbeat checkpoint unavailable") + super().save_state(data) + + class WaitingSolver(FileModel): + async def complete(self, messages, tools=None, **kwargs): + response = await super().complete(messages, tools, **kwargs) + prompt = next(message["content"] for message in messages if message["role"] == "user") + if response.finish_reason == "stop" and prompt.startswith("repair-stage"): + await asyncio.wait_for(heartbeat_failed.wait(), 5) + if cancelled: + awaiting_cancel.set() + await asyncio.Event().wait() + return response + + adapter, model = BrokenHeartbeat(tmp_path), WaitingSolver() + + async def flow(ctx, _args): + try: + return await run_weave(ctx, [WeaveGroup("result", "write-stage")], + config=_config(), adapter=adapter) + except BaseException as error: + errors.append(error) + raise + + running = asyncio.create_task(_client(tmp_path).workflow( + flow, llm=model, budget=20_000, trace=False, + )) + if cancelled: + try: + await asyncio.wait_for(awaiting_cancel.wait(), 5) + finally: + running.cancel() + with pytest.raises(asyncio.CancelledError): + await running + error, = errors + assert isinstance(error, asyncio.CancelledError) + assert any("heartbeat checkpoint unavailable" in note for note in error.__notes__) + assert adapter.saved[-1]["status"] == "cancelled" + else: + result = await running + assert result.status == "failed" and isinstance(result.error, OSError) + assert str(result.error) == "heartbeat checkpoint unavailable" + assert adapter.saved[-1]["status"] == "failed" + assert (tmp_path / "result.txt").read_text() == "correct\n" async def test_cancelled_writer_settles_before_return_without_later_group_or_check(tmp_path): writing, release, cancelled = asyncio.Event(), asyncio.Event(), asyncio.Event() diff --git a/tests/workflows/test_workflow_candidate_workspace.py b/tests/workflows/test_workflow_candidate_workspace.py index a94a405b..27c466ac 100644 --- a/tests/workflows/test_workflow_candidate_workspace.py +++ b/tests/workflows/test_workflow_candidate_workspace.py @@ -210,6 +210,7 @@ def __init__(self, environment): super().__init__(tokens=3) self.environment = environment self.closes = 0 + self.source_at_close = None async def run_loop(self, cancel_event=None): if self.prompt == "edit candidate": @@ -223,6 +224,7 @@ async def run_loop(self, cancel_event=None): async def aclose(self): self.closes += 1 + self.source_at_close = await self.environment.read_file("source.py") def build(**kwargs): session = ReadingSession(kwargs["env"]) @@ -248,15 +250,17 @@ async def nested(child, _args): candidate = await parent.candidate_workflow(nested, {}, label="candidate") assert candidate.output == "value = 2\ncandidate content\n" + assert not candidate.lifecycle_errors assert parent.tokens_spent() == 6 assert len(parent.sessions) == 2 assert built[1].environment.workspace != built[0].environment.workspace - assert built[1].closes == 1 - assert built[0].closes == 0 + assert [session.source_at_close for session in built] == ["value = 2\n", "value = 9\n"] + assert [session.closes for session in built] == [1, 1] assert base.revoked is False assert (repo / "source.py").read_text() == "value = 1\n" assert len(_git(repo, "worktree", "list", "--porcelain").split("worktree ")) == 2 await factory.release_isolated_envs() + assert [session.closes for session in built] == [1, 1] assert base.revoked is False @pytest.mark.parametrize("source_edit", [False, True]) diff --git a/tests/workflows/test_workflow_cli.py b/tests/workflows/test_workflow_cli.py index 43b885be..d231cdb7 100644 --- a/tests/workflows/test_workflow_cli.py +++ b/tests/workflows/test_workflow_cli.py @@ -11,6 +11,7 @@ from types import SimpleNamespace from typing import Any +import pytest from typer.testing import CliRunner from opencollab.adapters.cli import workflow as workflow_cli @@ -52,7 +53,7 @@ async def fake_run_workflow(spec_or_fn, args, **kwargs): captured["spec_or_fn"] = spec_or_fn captured["args"] = args captured["kwargs"] = kwargs - return SimpleNamespace(output=await spec_or_fn.fn(object(), args), stop_reason=None) + return SimpleNamespace(output=kwargs["format_output"](await spec_or_fn.fn(object(), args)), stop_reason=None) monkeypatch.setattr(workflow_cli, "run_workflow", fake_run_workflow) @@ -128,7 +129,9 @@ async def fake_run_workflow(_spec, _args, **kwargs): await kwargs["event_sink"].emit( SimpleNamespace(kind="log", message="[x] [link=unterminated") ) - return SimpleNamespace(output={"values": ["[bold]literal[/bold]", "[x]"]}, stop_reason=None) + return SimpleNamespace( + output=kwargs["format_output"]({"values": ["[bold]literal[/bold]", "[x]"]}), stop_reason=None, + ) monkeypatch.setattr(workflow_cli, "run_workflow", fake_run_workflow) @@ -189,7 +192,7 @@ async def echo(ctx, args): async def fake_run_workflow(spec_or_fn, args, *, cfg, budget=None, **kwargs): captured["cfg_budget"] = cfg["budget"] captured["budget_arg"] = budget - return SimpleNamespace(output=await spec_or_fn.fn(object(), args), stop_reason=None) + return SimpleNamespace(output=kwargs["format_output"](await spec_or_fn.fn(object(), args)), stop_reason=None) monkeypatch.setattr(workflow_cli, "run_workflow", fake_run_workflow) @@ -217,7 +220,7 @@ async def echo(ctx, args): async def fake_run_workflow(spec_or_fn, args, *, cfg, budget=None, **kwargs): captured["cfg_budget"] = cfg["budget"] captured["budget_arg"] = budget - return SimpleNamespace(output=await spec_or_fn.fn(object(), args), stop_reason=None) + return SimpleNamespace(output=kwargs["format_output"](await spec_or_fn.fn(object(), args)), stop_reason=None) monkeypatch.setattr(workflow_cli, "run_workflow", fake_run_workflow) @@ -235,12 +238,78 @@ def test_workflow_run_unknown_name_exits_nonzero(monkeypatch): assert result.exit_code != 0 -def test_workflow_run_invalid_json_args_exits_nonzero(monkeypatch): +@pytest.mark.parametrize("args", ["{not-json", '{"samples":[NaN]}', '{"samples":[1e309]}']) +def test_workflow_run_invalid_json_args_exits_nonzero(monkeypatch, args): monkeypatch.setattr(workflow_cli, "load_registry", lambda _workspace=".": _stub_registry()) - result = runner.invoke(workflow_cli.app, ["run", "alpha", "--args", "{not-json"]) + result = runner.invoke(workflow_cli.app, ["run", "alpha", "--args", args]) - assert result.exit_code != 0 + assert result.exit_code == 1 + assert "Invalid --args JSON" in result.output + +@pytest.mark.parametrize("save", [False, True], ids=["no-save", "save"]) +def test_workflow_run_reports_nonfinite_output(tmp_path, monkeypatch, save): + completed = tmp_path / "completed.txt" + + @workflow(name="report", description="returns a measurement") + async def report(_ctx, _args): + completed.write_text("finished") + return {"samples": [float("nan")]} + + registry = Registry() + registry.register(report.__workflow_spec__) + monkeypatch.setattr(workflow_cli, "load_registry", lambda _workspace=".": registry) + monkeypatch.setattr(workflow_cli, "missing_api_key_for", lambda *a, **k: False) + + result = runner.invoke(workflow_cli.app, [ + "run", "report", "--workspace", str(tmp_path), "--save" if save else "--no-save", "--no-trace", + ]) + + assert completed.read_text() == "finished" + assert result.exit_code == 1 + assert "Could not serialize workflow result as JSON" in result.stderr + assert '"samples"' not in result.stdout + manifests = list((tmp_path / ".opencollab/sessions").glob("*/workflow.json")) + assert len(manifests) == int(save) + if save: + manifest = json.loads(manifests[0].read_text()) + assert manifest["status"] == "failed" + assert manifest["reason"] == "output_format_failed" + assert manifest["evidence_complete"] is True + +def test_workflow_run_saves_deep_json_inputs(tmp_path): + workflows = tmp_path / "workflows" + workflows.mkdir() + (workflows / "summarize.py").write_text( + "from opencollab import workflow\n\n" + "@workflow\n" + "async def summarize(ctx, args):\n" + " current = args.pop('tree')\n" + " depth = 0\n" + " while isinstance(current, list):\n" + " current, = current\n" + " depth += 1\n" + " return {'depth': depth, 'leaf': current}\n", + encoding="utf-8", + ) + depth = 520 + arguments = '{"tree":' + "[" * depth + '"shipment"' + "]" * depth + "}" + + result = runner.invoke(workflow_cli.app, [ + "run", "summarize", "--workspace", str(tmp_path), "--args", arguments, + "--provider", "openai", "--api-key", "offline-unused", "--save", "--no-trace", + ]) + + assert result.exit_code == 0, (result.stdout, result.exception) + assert json.loads(_last_json_block(result.stdout)) == {"depth": depth, "leaf": "shipment"} + path, = (tmp_path / ".opencollab/sessions").glob("*/workflow.json") + manifest = json.loads(path.read_text(encoding="utf-8")) + assert manifest["status"] == "completed" + assert manifest["evidence_complete"] is True + recorded = manifest["args"]["tree"] + for _ in range(depth): + recorded, = recorded + assert recorded == "shipment" def _last_json_block(text: str) -> str: """Extract the trailing JSON object/array printed by the run command. diff --git a/tests/workflows/test_workflow_cli_budget_exit.py b/tests/workflows/test_workflow_cli_budget_exit.py index e00d4392..11b1c083 100644 --- a/tests/workflows/test_workflow_cli_budget_exit.py +++ b/tests/workflows/test_workflow_cli_budget_exit.py @@ -53,7 +53,7 @@ def do_POST(self): server.server_close() thread.join(timeout=5) -def _cli(project, name, base_url, *arguments): +def _cli(project, name, base_url, *arguments, unbounded=False): return subprocess.run( [sys.executable, "-m", "opencollab", "workflow", "run", name, "--workspace", str(project), "--provider", "openai", "--model", "fixture-model", @@ -67,6 +67,7 @@ def _cli(project, name, base_url, *arguments): "TERM": "dumb", "COLUMNS": "240", "TERMINAL_WIDTH": "240", + "OPENCOLLAB_UNBOUNDED_LIMITS": str(unbounded).lower(), }, capture_output=True, text=True, @@ -77,11 +78,8 @@ def _payload(result): start = result.stdout.rfind("\n{") + 1 return json.loads(result.stdout[start:]) -@pytest.mark.parametrize("budget", [10_000, 500], ids=["completed", "budget-stop"]) -@pytest.mark.parametrize("save", [True, False], ids=["save", "no-save"]) -@pytest.mark.parametrize("trace", [True, False], ids=["trace", "no-trace"]) -def test_cli_budget_exit_preserves_json_and_artifacts(tmp_path, completion_server, budget, save, trace): - directory = tmp_path / "workflows" +def _write_two_reply_workflow(project): + directory = project / "workflows" directory.mkdir() (directory / "two_replies.py").write_text( "from opencollab import workflow\n" @@ -92,6 +90,13 @@ def test_cli_budget_exit_preserves_json_and_artifacts(tmp_path, completion_serve " return {'first': first, 'second': second}\n", encoding="utf-8", ) + + +@pytest.mark.parametrize("budget", [10_000, 500], ids=["completed", "budget-stop"]) +@pytest.mark.parametrize("save", [True, False], ids=["save", "no-save"]) +@pytest.mark.parametrize("trace", [True, False], ids=["trace", "no-trace"]) +def test_cli_budget_exit_preserves_json_and_artifacts(tmp_path, completion_server, budget, save, trace): + _write_two_reply_workflow(tmp_path) base_url, requests = completion_server result = _cli( tmp_path, "two-replies", base_url, "--budget", str(budget), @@ -122,6 +127,29 @@ def test_cli_budget_exit_preserves_json_and_artifacts(tmp_path, completion_serve else: assert not sessions.exists() + +@pytest.mark.parametrize("budget", [None, 500], ids=["environment-default", "explicit-limit"]) +def test_cli_honors_explicit_budget_in_an_unbounded_environment(tmp_path, completion_server, budget): + _write_two_reply_workflow(tmp_path) + base_url, requests = completion_server + args = [] if budget is None else ["--budget", str(budget)] + result = _cli(tmp_path, "two-replies", base_url, "--no-trace", *args, unbounded=True) + + stopped = budget is not None + assert result.returncode == int(stopped), result.stdout + result.stderr + assert len(requests) == (1 if stopped else 2) + manifest, = (tmp_path / ".opencollab" / "sessions").glob("*/workflow.json") + saved = json.loads(manifest.read_text(encoding="utf-8")) + assert saved["budget_total"] == budget + assert saved["status"] == ("stopped" if stopped else "completed") + assert saved["tokens_spent"] == 500 * len(requests) + if stopped: + assert _payload(result)["status"] == "budget_exceeded" + assert _payload(result)["tokens_spent"] == 500 + else: + assert _payload(result) == {"first": "local reply", "second": "local reply"} + + @pytest.mark.parametrize("status", ["budget_exceeded", "stopped", "failed"]) def test_cli_completed_callback_keeps_arbitrary_status_output(tmp_path, completion_server, status): directory = tmp_path / "workflows" diff --git a/tests/workflows/test_workflow_context_budget.py b/tests/workflows/test_workflow_context_budget.py index 38c4b716..92362d1e 100644 --- a/tests/workflows/test_workflow_context_budget.py +++ b/tests/workflows/test_workflow_context_budget.py @@ -115,6 +115,42 @@ async def wait_for_reservations(count): await asyncio.gather(*tasks, return_exceptions=True) await ctx.wait_for_pending_cleanup() +@pytest.mark.asyncio +@pytest.mark.parametrize("method", ["agent", "agent_run"]) +@pytest.mark.parametrize(("first_spend", "review_grant"), [(12, 6000), (9000, 1000)]) +async def test_queued_explicit_cap_uses_released_workflow_budget(method, first_spend, review_grant): + started, release = asyncio.Event(), asyncio.Event() + + async def enter_first(): + started.set() + await release.wait() + + first = _DeferredTokenSession(tokens=first_spend, on_enter=enter_first) + factory = FakeFactory([first, FakeSession(tokens=5)]) + ctx = WorkflowContext(factory, budget_total=10_000, max_concurrency=1) + run = getattr(ctx, method) + tasks = [asyncio.create_task(run("prepare", budget=9000))] + + async def wait_for_review_reservation(): + while ctx.tokens_remaining() != 0: + await asyncio.sleep(0) + + try: + await asyncio.wait_for(started.wait(), MUST_SETTLE_SECONDS) + tasks.append(asyncio.create_task(run("review", budget=6000))) + await asyncio.wait_for(wait_for_review_reservation(), MUST_SETTLE_SECONDS) + assert len(factory.builds) == 1 + first.land_spend() + release.set() + await asyncio.wait_for(asyncio.gather(*tasks), MUST_SETTLE_SECONDS) + assert [build["budget"] for build in factory.builds] == [9000, review_grant] + assert ctx.tokens_spent() == first_spend + 5 + assert not ctx.budget._leases + finally: + release.set() + await asyncio.gather(*tasks, return_exceptions=True) + + @pytest.mark.asyncio async def test_queued_over_budget_call_claims_the_single_escape(): started, release = asyncio.Event(), asyncio.Event() diff --git a/tests/workflows/test_workflow_context_nested_parallel.py b/tests/workflows/test_workflow_context_nested_parallel.py index 61fc746a..174729b2 100644 --- a/tests/workflows/test_workflow_context_nested_parallel.py +++ b/tests/workflows/test_workflow_context_nested_parallel.py @@ -250,3 +250,27 @@ async def test_extra_task_slot_released_when_worker_cancelled_before_start(): assert await asyncio.wait_for(ctx.parallel([lambda: asyncio.sleep(0, result="next")]), 2.0) == ["next"] assert ctx._task_semaphore._value == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("cancel", [False, True]) +async def test_ready_inherited_and_shared_slots_are_released_once(cancel): + ctx = WorkflowContext(FakeFactory([]), task_concurrency=2) + inherited = asyncio.Semaphore(0) + shared = ctx._task_semaphore + await shared.acquire() + await shared.acquire() + waiting = asyncio.create_task(ctx._acquire_child_task_slot(inherited)) + await asyncio.sleep(0) + await asyncio.sleep(0) + inherited.release() + shared.release() + await asyncio.sleep(0) + if cancel: + waiting.cancel() + with pytest.raises(asyncio.CancelledError): + await waiting + else: + selected = await waiting + selected.release() + assert inherited._value == shared._value == 1 diff --git a/tests/workflows/test_workflow_runtime_cleanup.py b/tests/workflows/test_workflow_runtime_cleanup.py index 93a08adf..9ce6b370 100644 --- a/tests/workflows/test_workflow_runtime_cleanup.py +++ b/tests/workflows/test_workflow_runtime_cleanup.py @@ -59,14 +59,13 @@ def __init__(self, environment, cleanup_task) -> None: ctx._cleanup_environment = False ctx._track_session(Session(environment, cleanup_task)) - quiesced, succeeded, lingering = await workflow_cleanup._quiesce_workflow_context( + quiesced, succeeded = await workflow_cleanup._quiesce_workflow_context( ctx, timeout=0.01, ) assert quiesced assert succeeded - assert not lingering assert not environment.revoked assert environment.abort_calls == 0 @@ -302,7 +301,7 @@ def build_workflow_session(self, **kwargs): try: release_first.set() assert await asyncio.to_thread(second_started.wait, MUST_SETTLE_SECONDS) - quiesced, succeeded, _lingering = await cleanup + quiesced, succeeded = await cleanup assert quiesced is False assert succeeded is False assert calls == ["start-1", "end-1", "start-2"] @@ -341,7 +340,7 @@ def build_workflow_session(self, **kwargs): ctx._track_session(SessionWithFailedAutosave()) await event_bus.emit(SessionRuntimeEvent(type="step_end")) - quiesced, succeeded, _lingering = await workflow_cleanup._quiesce_workflow_context( + quiesced, succeeded = await workflow_cleanup._quiesce_workflow_context( ctx, timeout=MUST_SETTLE_SECONDS, ) @@ -390,7 +389,7 @@ def build_workflow_session(self, **kwargs): assert llm.cancel_seen.is_set() assert session.pending_cleanup_tasks - quiesced, succeeded, _lingering = await workflow_cleanup._quiesce_workflow_context( + quiesced, succeeded = await workflow_cleanup._quiesce_workflow_context( ctx, timeout=0.01, ) @@ -419,7 +418,7 @@ def close(self) -> None: closed.append(True) async def failed_abort(ctx, *, timeout): - return True, False, () + return True, False monkeypatch.setattr(workflow_execution, "Tracer", RecordingTracer) monkeypatch.setattr(workflow_cleanup, "_quiesce_workflow_context", failed_abort) diff --git a/tests/workflows/test_workflow_runtime_deadline.py b/tests/workflows/test_workflow_runtime_deadline.py index 614848e9..d1ad1ca2 100644 --- a/tests/workflows/test_workflow_runtime_deadline.py +++ b/tests/workflows/test_workflow_runtime_deadline.py @@ -6,6 +6,7 @@ import pytest +from opencollab.bootstrap import _workflow_runtime_execution as workflow_execution from opencollab.bootstrap import ( _workflow_runtime_session as workflow_session, ) @@ -19,6 +20,28 @@ ) +@pytest.mark.parametrize("entry", ["execution", "bootstrap"]) +async def test_completed_runtime_retains_output_after_the_deadline(tmp_path, monkeypatch, entry): + output = {"measurement": 42} + + async def measure(_ctx, _args): + return output + + async def report_completed_owner(owner, *, timeout): + assert timeout == 0 + await owner + return {owner}, set() + + monkeypatch.setattr(workflow_runtime, "_wait_for_owner", report_completed_owner) + runner = workflow_execution if entry == "execution" else workflow_runtime + details = await runner.run_workflow( + measure, {}, cfg=_cfg(), workspace=str(tmp_path), + deadline_monotonic=asyncio.get_running_loop().time() - 1, return_details=True, + ) + assert details.output is output + assert details.body_returned_before_deadline is False + + @pytest.mark.asyncio async def test_bootstrap_deadline_cancels_owner_without_aborting_injected_environment(monkeypatch): cancelled = asyncio.Event() diff --git a/tests/workflows/test_workflow_task_input.py b/tests/workflows/test_workflow_task_input.py index 698f8f34..bab3eb0d 100644 --- a/tests/workflows/test_workflow_task_input.py +++ b/tests/workflows/test_workflow_task_input.py @@ -81,7 +81,7 @@ def test_duo_task_forwards_goal_and_explicit_shell_choice(tmp_path, monkeypatch) async def run(spec, args, **kwargs): captured.update(name=spec.name, args=args) - return SimpleNamespace(output=args, stop_reason=None) + return SimpleNamespace(output=kwargs["format_output"](args), stop_reason=None) monkeypatch.delenv("OPENCOLLAB_WORKFLOWS_DIR", raising=False) monkeypatch.setattr(workflow_cli, "run_workflow", run)