agentenv-framework 0.9.1254__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agent_env/__init__.py +0 -0
- agent_env/a2a_agent/__init__.py +23 -0
- agent_env/a2a_agent/a2a_agent.py +600 -0
- agent_env/a2a_agent/conversation_store.py +356 -0
- agent_env/a2a_agent/object_transfer.py +609 -0
- agent_env/a2a_agent/protocol.py +238 -0
- agent_env/a2a_agent/store.py +201 -0
- agent_env/a2a_agent/validator.py +901 -0
- agent_env/artifact/__init__.py +48 -0
- agent_env/artifact/artifact.py +74 -0
- agent_env/artifact/artifacts/__init__.py +0 -0
- agent_env/artifact/artifacts/cli.py +83 -0
- agent_env/artifact/artifacts/docker_image.py +457 -0
- agent_env/artifact/artifacts/environment.py +89 -0
- agent_env/artifact/artifacts/environment_universe.py +156 -0
- agent_env/artifact/artifacts/file.py +214 -0
- agent_env/artifact/artifacts/file_artifact_universe.py +206 -0
- agent_env/artifact/artifacts/skill.py +206 -0
- agent_env/artifact/artifacts/vm_image.py +95 -0
- agent_env/artifact/ref.py +15 -0
- agent_env/artifact/registry.py +251 -0
- agent_env/artifact/store.py +295 -0
- agent_env/artifact/universe.py +38 -0
- agent_env/attribution.py +41 -0
- agent_env/bundle/__init__.py +4 -0
- agent_env/bundle/_fs.py +128 -0
- agent_env/bundle/authoring.py +239 -0
- agent_env/bundle/installed.py +175 -0
- agent_env/bundle/ledger.py +269 -0
- agent_env/bundle/materialize.py +204 -0
- agent_env/bundle/parse.py +594 -0
- agent_env/bundle/plan.py +414 -0
- agent_env/bundle/resolve.py +404 -0
- agent_env/bundle/run.py +361 -0
- agent_env/cli/__init__.py +69 -0
- agent_env/cli/__main__.py +10 -0
- agent_env/cli/_installers.py +576 -0
- agent_env/cli/_plugin_changes.py +947 -0
- agent_env/cli/a2a_agent/__init__.py +22 -0
- agent_env/cli/a2a_agent/add_skill.py +97 -0
- agent_env/cli/a2a_agent/deploy.py +60 -0
- agent_env/cli/a2a_agent/get.py +15 -0
- agent_env/cli/a2a_agent/get_instance.py +26 -0
- agent_env/cli/a2a_agent/put.py +78 -0
- agent_env/cli/a2a_agent/validate.py +56 -0
- agent_env/cli/artifact/__init__.py +20 -0
- agent_env/cli/artifact/cli.py +83 -0
- agent_env/cli/artifact/environment.py +44 -0
- agent_env/cli/artifact/environment_universe.py +163 -0
- agent_env/cli/artifact/file_artifact_universe.py +281 -0
- agent_env/cli/artifact/skill.py +128 -0
- agent_env/cli/banner.py +25 -0
- agent_env/cli/config.py +263 -0
- agent_env/cli/env/__init__.py +31 -0
- agent_env/cli/env/deploy.py +112 -0
- agent_env/cli/env/gateway.py +57 -0
- agent_env/cli/env/get_instance.py +40 -0
- agent_env/cli/env/mcp_server.py +410 -0
- agent_env/cli/env/multi.py +282 -0
- agent_env/cli/env/service_db.py +99 -0
- agent_env/cli/env/snapshot.py +35 -0
- agent_env/cli/env/state/__init__.py +6 -0
- agent_env/cli/env/state/init.py +108 -0
- agent_env/cli/env/state/teardown.py +44 -0
- agent_env/cli/env/website.py +216 -0
- agent_env/cli/env/website_browser.py +67 -0
- agent_env/cli/eval/__init__.py +16 -0
- agent_env/cli/eval/add_tasks.py +63 -0
- agent_env/cli/eval/create.py +49 -0
- agent_env/cli/eval/run.py +194 -0
- agent_env/cli/identity/__init__.py +5 -0
- agent_env/cli/identity/client_identity.py +37 -0
- agent_env/cli/plugin.py +438 -0
- agent_env/cli/run.py +285 -0
- agent_env/cli/task/__init__.py +21 -0
- agent_env/cli/task/create.py +109 -0
- agent_env/cli/task/get.py +17 -0
- agent_env/cli/task/get_instance.py +34 -0
- agent_env/cli/task/run.py +615 -0
- agent_env/cli/task/validate.py +31 -0
- agent_env/cli/up.py +123 -0
- agent_env/cli/utils.py +183 -0
- agent_env/config/__init__.py +50 -0
- agent_env/config/describe.py +1067 -0
- agent_env/config/errors.py +13 -0
- agent_env/config/loader.py +245 -0
- agent_env/config/model.py +154 -0
- agent_env/config/paths.py +25 -0
- agent_env/config/plugin_tables.py +101 -0
- agent_env/config/provenance.py +134 -0
- agent_env/config/runtime.py +1064 -0
- agent_env/config/snapshot.py +81 -0
- agent_env/entity_refs.py +186 -0
- agent_env/env/__init__.py +49 -0
- agent_env/env/env.py +433 -0
- agent_env/env/env_artifact_store.py +87 -0
- agent_env/env/envs/__init__.py +7 -0
- agent_env/env/envs/_deployment.py +281 -0
- agent_env/env/envs/gateway_server.py +32 -0
- agent_env/env/envs/mcp_server.py +387 -0
- agent_env/env/envs/multi_env.py +780 -0
- agent_env/env/envs/service_db/Dockerfile +20 -0
- agent_env/env/envs/service_db/Dockerfile.db-mcp +42 -0
- agent_env/env/envs/service_db/Dockerfile.db-web +8 -0
- agent_env/env/envs/service_db.py +92 -0
- agent_env/env/envs/website.py +294 -0
- agent_env/env/envs/website_browser/Dockerfile +40 -0
- agent_env/env/envs/website_browser/__init__.py +17 -0
- agent_env/env/envs/website_browser/entrypoint.sh +13 -0
- agent_env/env/gateway/Dockerfile +14 -0
- agent_env/env/gateway/__init__.py +37 -0
- agent_env/env/gateway/clock.py +184 -0
- agent_env/env/gateway/constants.py +190 -0
- agent_env/env/gateway/entrypoint.py +156 -0
- agent_env/env/gateway/gateway.py +1095 -0
- agent_env/env/gateway/get_time.py +60 -0
- agent_env/env/gateway/requirements.txt +4 -0
- agent_env/env/gateway/triggers.py +1193 -0
- agent_env/env/legacy_protocol.py +146 -0
- agent_env/env/registry.py +93 -0
- agent_env/env/snapshot_store.py +372 -0
- agent_env/env/store.py +411 -0
- agent_env/eval/__init__.py +14 -0
- agent_env/eval/eval.py +68 -0
- agent_env/eval/store.py +116 -0
- agent_env/examples/hello/README.md +9 -0
- agent_env/examples/hello/artifacts/greeting/check.sh +1 -0
- agent_env/examples/hello/artifacts/greeting/hello.txt +1 -0
- agent_env/examples/hello/tasks/hello.json +10 -0
- agent_env/explorer/__init__.py +12 -0
- agent_env/explorer/app.py +277 -0
- agent_env/explorer/openapi_docs.py +242 -0
- agent_env/explorer/plugin.py +95 -0
- agent_env/explorer/routers/__init__.py +1 -0
- agent_env/explorer/routers/common.py +174 -0
- agent_env/explorer/routers/conversations.py +25 -0
- agent_env/explorer/routers/objects.py +112 -0
- agent_env/explorer/routers/runs.py +475 -0
- agent_env/plugins/__init__.py +59 -0
- agent_env/plugins/_cli.py +244 -0
- agent_env/plugins/_discovery.py +97 -0
- agent_env/plugins/_inventory.py +262 -0
- agent_env/plugins/_registration.py +268 -0
- agent_env/plugins/_report.py +47 -0
- agent_env/plugins/_requirements.py +55 -0
- agent_env/providers/__init__.py +37 -0
- agent_env/providers/env_providers/__init__.py +12 -0
- agent_env/providers/env_providers/constants.py +13 -0
- agent_env/providers/env_providers/env_gateway_provider.py +1354 -0
- agent_env/providers/env_providers/env_provider.py +237 -0
- agent_env/providers/env_providers/env_server_provider.py +133 -0
- agent_env/providers/env_state/__init__.py +49 -0
- agent_env/providers/env_state/env_state_provider.py +554 -0
- agent_env/providers/env_state/local_postgres.py +390 -0
- agent_env/providers/env_state/store.py +112 -0
- agent_env/providers/sandbox_providers/__init__.py +29 -0
- agent_env/providers/sandbox_providers/chained_sandbox_provider.py +93 -0
- agent_env/providers/sandbox_providers/e2b/__init__.py +6 -0
- agent_env/providers/sandbox_providers/e2b/provider.py +376 -0
- agent_env/providers/sandbox_providers/e2b/sandbox.py +342 -0
- agent_env/providers/sandbox_providers/e2b/template.py +158 -0
- agent_env/providers/sandbox_providers/local_sandbox.py +408 -0
- agent_env/providers/sandbox_providers/modal_sandbox.py +500 -0
- agent_env/providers/sandbox_providers/modal_vm_sandbox.py +466 -0
- agent_env/providers/sandbox_providers/sandbox.py +387 -0
- agent_env/providers/sandbox_providers/sandbox_provider.py +614 -0
- agent_env/py.typed +0 -0
- agent_env/runner/__init__.py +16 -0
- agent_env/runner/local_runner.py +190 -0
- agent_env/runner/runner.py +127 -0
- agent_env/runner/store.py +94 -0
- agent_env/store/__init__.py +126 -0
- agent_env/store/_google.py +68 -0
- agent_env/store/base.py +33 -0
- agent_env/store/document_store/__init__.py +60 -0
- agent_env/store/document_store/document_store.py +519 -0
- agent_env/store/document_store/dynamodb_document_store.py +306 -0
- agent_env/store/document_store/evaluation.py +199 -0
- agent_env/store/document_store/firestore_mongo_document_store.py +242 -0
- agent_env/store/document_store/mongo_document_store.py +259 -0
- agent_env/store/document_store/sqlite_document_store.py +314 -0
- agent_env/store/ids.py +123 -0
- agent_env/store/image_store/__init__.py +34 -0
- agent_env/store/image_store/ecr_image_store.py +131 -0
- agent_env/store/image_store/google_credentials.py +113 -0
- agent_env/store/image_store/image_store.py +113 -0
- agent_env/store/image_store/local_registry_image_store.py +106 -0
- agent_env/store/image_store/oci_registry_credentials.py +196 -0
- agent_env/store/local_state.py +27 -0
- agent_env/store/object_store/__init__.py +24 -0
- agent_env/store/object_store/gcs_object_store.py +415 -0
- agent_env/store/object_store/local_object_store.py +143 -0
- agent_env/store/object_store/object_store.py +198 -0
- agent_env/store/object_store/s3_object_store.py +354 -0
- agent_env/store/query.py +112 -0
- agent_env/store/routing.py +609 -0
- agent_env/store/secret_store/__init__.py +19 -0
- agent_env/store/secret_store/aws_secrets_manager_secret_store.py +293 -0
- agent_env/store/secret_store/gcp_secret_manager_secret_store.py +319 -0
- agent_env/store/secret_store/local_secret_store.py +47 -0
- agent_env/store/secret_store/secret_store.py +19 -0
- agent_env/task/__init__.py +27 -0
- agent_env/task/interrupts.py +109 -0
- agent_env/task/registry.py +27 -0
- agent_env/task/step_journal.py +99 -0
- agent_env/task/store.py +940 -0
- agent_env/task/task.py +815 -0
- agent_env/task/teardown.py +142 -0
- agent_env/task_step/__init__.py +47 -0
- agent_env/task_step/context.py +195 -0
- agent_env/task_step/context_ops.py +224 -0
- agent_env/task_step/registry.py +182 -0
- agent_env/task_step/review_store.py +118 -0
- agent_env/task_step/snapshot_utils/__init__.py +2 -0
- agent_env/task_step/snapshot_utils/agent_state_capture.py +261 -0
- agent_env/task_step/snapshot_utils/snapshot_series.py +631 -0
- agent_env/task_step/store.py +129 -0
- agent_env/task_step/task_step.py +173 -0
- agent_env/task_step/task_steps/__init__.py +27 -0
- agent_env/task_step/task_steps/a2a_agent_validator/__init__.py +31 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/README.md +158 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.m4a +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.mp3 +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.mp4 +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.ogg +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.wav +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/document.pdf +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/red.gif +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/red.jpg +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/red.png +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_agent_card.py +103 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_agent_config_identity.py +69 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_agent_mcp.py +178 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_core_protocol.py +67 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_install.py +115 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_litellm_attribution.py +124 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_litellm_attribution_runtime.py +173 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_modalities.py +270 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_peer_agents.py +102 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_role.py +151 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_skill_config.py +194 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_snapshot.py +111 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_system_prompt.py +215 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_trajectory.py +164 -0
- agent_env/task_step/task_steps/add_skills.py +240 -0
- agent_env/task_step/task_steps/apply_server_config.py +288 -0
- agent_env/task_step/task_steps/collect_artifacts.py +940 -0
- agent_env/task_step/task_steps/deploy_agent.py +626 -0
- agent_env/task_step/task_steps/deploy_env.py +197 -0
- agent_env/task_step/task_steps/deploy_human_agent.py +100 -0
- agent_env/task_step/task_steps/deploy_sandbox.py +170 -0
- agent_env/task_step/task_steps/env_card_validator/__init__.py +4 -0
- agent_env/task_step/task_steps/env_card_validator/verify_env_card.py +109 -0
- agent_env/task_step/task_steps/env_card_validator/verify_env_core_protocol.py +108 -0
- agent_env/task_step/task_steps/install_agent.py +376 -0
- agent_env/task_step/task_steps/load_artifact.py +775 -0
- agent_env/task_step/task_steps/mcp_cli_builder/__init__.py +4 -0
- agent_env/task_step/task_steps/mcp_cli_builder/build_mcp_cli.py +201 -0
- agent_env/task_step/task_steps/mcp_cli_builder/codegen.py +627 -0
- agent_env/task_step/task_steps/mcp_env_validator/__init__.py +44 -0
- agent_env/task_step/task_steps/mcp_env_validator/validation_gate_aggregator.py +102 -0
- agent_env/task_step/task_steps/mcp_env_validator/verify_mcp_env_assessment.py +78 -0
- agent_env/task_step/task_steps/mcp_env_validator/verify_mcp_tool_schema.py +152 -0
- agent_env/task_step/task_steps/mcp_env_validator/verify_spec_conformance.py +486 -0
- agent_env/task_step/task_steps/modify_env_tool_access.py +80 -0
- agent_env/task_step/task_steps/multienv_validator/__init__.py +3 -0
- agent_env/task_step/task_steps/multienv_validator/combine_universe_verdicts.py +107 -0
- agent_env/task_step/task_steps/multienv_validator/universe_comparison.py +253 -0
- agent_env/task_step/task_steps/multienv_validator/verify_universe_agent_judge.py +180 -0
- agent_env/task_step/task_steps/multienv_validator/verify_universe_roundtrip.py +241 -0
- agent_env/task_step/task_steps/peer_agents.py +92 -0
- agent_env/task_step/task_steps/prompt_agent.py +900 -0
- agent_env/task_step/task_steps/register_agent_triggers.py +113 -0
- agent_env/task_step/task_steps/register_env_triggers.py +97 -0
- agent_env/task_step/task_steps/reset_env.py +71 -0
- agent_env/task_step/task_steps/review.py +152 -0
- agent_env/task_step/task_steps/run_code.py +461 -0
- agent_env/task_step/task_steps/run_code_runner.py +52 -0
- agent_env/task_step/task_steps/run_docker_container.py +380 -0
- agent_env/task_step/task_steps/sandbox_utils/__init__.py +0 -0
- agent_env/task_step/task_steps/sandbox_utils/sandbox_utils.py +79 -0
- agent_env/task_step/task_steps/snapshot_agent_state.py +205 -0
- agent_env/task_step/task_steps/snapshot_env.py +637 -0
- agent_env/task_step/task_steps/sync_env_clock.py +132 -0
- agent_env/task_step/task_steps/teardown_sandboxes.py +170 -0
- agent_env/task_step/task_steps/verifiers/__init__.py +23 -0
- agent_env/task_step/task_steps/verifiers/agent_prompt_response_verifier.py +166 -0
- agent_env/task_step/task_steps/verifiers/aggregate_verifiers.py +90 -0
- agent_env/task_step/task_steps/verifiers/env_outcome_verifier.py +127 -0
- agent_env/task_step/task_steps/verifiers/judge_utils/__init__.py +2 -0
- agent_env/task_step/task_steps/verifiers/judge_utils/frame_selection.py +377 -0
- agent_env/task_step/task_steps/verifiers/judge_utils/judge_output_format.py +1293 -0
- agent_env/task_step/task_steps/verifiers/judge_utils/trajectory_filter.py +514 -0
- agent_env/task_step/task_steps/verifiers/rubrics_verifier.py +1318 -0
- agent_env/task_step/task_steps/verifiers/run_container_unit_tests_verifier.py +434 -0
- agent_env/task_step/task_steps/verifiers/scoring.py +40 -0
- agent_env/task_step/task_steps/verifiers/verify_sandbox.py +308 -0
- agent_env/task_step/thread_work.py +61 -0
- agent_env/utils/__init__.py +0 -0
- agent_env/utils/card_naming.py +108 -0
- agent_env/utils/deprecation.py +109 -0
- agent_env/utils/docker_build.py +29 -0
- agent_env/utils/exec_retry.py +77 -0
- agent_env/utils/litellm_attribution.py +59 -0
- agent_env/utils/paths.py +20 -0
- agentenv_framework-0.9.1254.dist-info/METADATA +394 -0
- agentenv_framework-0.9.1254.dist-info/RECORD +312 -0
- agentenv_framework-0.9.1254.dist-info/WHEEL +4 -0
- agentenv_framework-0.9.1254.dist-info/entry_points.txt +5 -0
- agentenv_framework-0.9.1254.dist-info/licenses/LICENSE +202 -0
- agentenv_framework-0.9.1254.dist-info/licenses/NOTICE +4 -0
- agentenv_framework-0.9.1254.dist-info/licenses/THIRD_PARTY_NOTICES.md +7665 -0
agent_env/task/store.py
ADDED
|
@@ -0,0 +1,940 @@
|
|
|
1
|
+
"""Task store for MongoDB persistence."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import copy
|
|
7
|
+
import dataclasses
|
|
8
|
+
import logging
|
|
9
|
+
import random
|
|
10
|
+
import string
|
|
11
|
+
import time
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from datetime import datetime, timezone
|
|
14
|
+
from enum import StrEnum
|
|
15
|
+
from typing import TYPE_CHECKING, Callable, Optional, Self
|
|
16
|
+
|
|
17
|
+
from agent_env.store.base import NotFoundError
|
|
18
|
+
from agent_env.config import get_config
|
|
19
|
+
from agent_env.store.document_store import DocumentStore, DuplicateKeyError, Filter, Lte, Ne, Sort, UpdateSpec, VersionedEntityStore, VersionedEntityStoreCache, compare_and_swap
|
|
20
|
+
from agent_env.store.query import QueryBuilder, to_document_query
|
|
21
|
+
from agent_env.task.step_journal import (
|
|
22
|
+
_RESERVED_STEP_IDS,
|
|
23
|
+
_SCHEDULER_STEP_ID,
|
|
24
|
+
_SEED_STEP_ID,
|
|
25
|
+
_apply_forward,
|
|
26
|
+
_get_path,
|
|
27
|
+
_union,
|
|
28
|
+
commit_ordered,
|
|
29
|
+
replay_context,
|
|
30
|
+
)
|
|
31
|
+
from agent_env.task_step.context import TaskStepContext
|
|
32
|
+
|
|
33
|
+
if TYPE_CHECKING:
|
|
34
|
+
from agent_env.task.task import Task
|
|
35
|
+
from agent_env.task_step.context_ops import ContextUpdateOps
|
|
36
|
+
|
|
37
|
+
logger = logging.getLogger(__name__)
|
|
38
|
+
|
|
39
|
+
TASKS_COLLECTION = "tasks"
|
|
40
|
+
TASK_INSTANCES_COLLECTION = "task_instances"
|
|
41
|
+
TASK_STEP_JOURNAL_COLLECTION = "task_step_journal"
|
|
42
|
+
_REV = "rev"
|
|
43
|
+
_JOURNAL_SEQ = "journal_seq"
|
|
44
|
+
# Steps whose latest completion was a re-record, decided inside the CAS so never a stale read.
|
|
45
|
+
_RERECORDED = "rerecorded_steps"
|
|
46
|
+
# Which run the journal entries belong to; a re-register bumps it, retiring them without a delete.
|
|
47
|
+
_GENERATION = "run_generation"
|
|
48
|
+
class TaskQuery(QueryBuilder["Task"]):
|
|
49
|
+
def __init__(self, store: Optional["TaskStore"] = None) -> None:
|
|
50
|
+
super().__init__()
|
|
51
|
+
self._store = store
|
|
52
|
+
|
|
53
|
+
def _clone(self) -> Self:
|
|
54
|
+
clone = TaskQuery(self._store)
|
|
55
|
+
clone._filters = self._filters.copy()
|
|
56
|
+
clone._sort_field = self._sort_field
|
|
57
|
+
clone._sort_desc = self._sort_desc
|
|
58
|
+
clone._limit_value = self._limit_value
|
|
59
|
+
clone._offset_value = self._offset_value
|
|
60
|
+
return clone
|
|
61
|
+
|
|
62
|
+
def type(self, task_type: str) -> Self:
|
|
63
|
+
return self._add_filter("type", task_type)
|
|
64
|
+
|
|
65
|
+
def execute(self) -> list[Task]:
|
|
66
|
+
if self._store is None:
|
|
67
|
+
self._store = get_task_store()
|
|
68
|
+
return self._store.execute_query(self)
|
|
69
|
+
|
|
70
|
+
def _execute_count(self) -> int:
|
|
71
|
+
if self._store is None:
|
|
72
|
+
self._store = get_task_store()
|
|
73
|
+
return self._store.execute_count(self)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class TaskStore:
|
|
77
|
+
def __init__(self) -> None:
|
|
78
|
+
self._versioned_cache: VersionedEntityStoreCache[Task] = VersionedEntityStoreCache(
|
|
79
|
+
TASKS_COLLECTION, self._serialize, self._deserialize, secondary_indexes=[["type"]],
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def _doc_store(self):
|
|
84
|
+
return get_config().get_document_store()
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def _versioned(self) -> VersionedEntityStore[Task]:
|
|
88
|
+
return self._versioned_cache.for_store(self._doc_store)
|
|
89
|
+
|
|
90
|
+
def _serialize(self, task: Task) -> dict:
|
|
91
|
+
doc = task.to_dict()
|
|
92
|
+
doc["created_at_utc"] = datetime.now(timezone.utc)
|
|
93
|
+
return doc
|
|
94
|
+
|
|
95
|
+
def get(self, id: str, version: Optional[int] = None) -> Task:
|
|
96
|
+
task = self._versioned.get(id, version)
|
|
97
|
+
if task is None:
|
|
98
|
+
version_str = f" version={version}" if version is not None else ""
|
|
99
|
+
raise NotFoundError(f"Task {id}{version_str} not found")
|
|
100
|
+
return task
|
|
101
|
+
|
|
102
|
+
def next_version(self, id: str) -> int:
|
|
103
|
+
return self._versioned.next_version(id)
|
|
104
|
+
|
|
105
|
+
def put_document(self, task: Task) -> Task:
|
|
106
|
+
task.version = self._versioned.put(task)
|
|
107
|
+
return task
|
|
108
|
+
|
|
109
|
+
def _deserialize(self, doc: dict) -> Task:
|
|
110
|
+
from agent_env.task.registry import get_task_registry
|
|
111
|
+
|
|
112
|
+
doc.pop("_id", None)
|
|
113
|
+
doc.pop("created_at_utc", None)
|
|
114
|
+
task_type = doc["type"]
|
|
115
|
+
registry = get_task_registry()
|
|
116
|
+
cls = registry.get(task_type)
|
|
117
|
+
if cls is None:
|
|
118
|
+
raise ValueError(f"Unknown task type: {task_type}")
|
|
119
|
+
return cls.from_dict(doc)
|
|
120
|
+
|
|
121
|
+
def execute_query(self, query: TaskQuery) -> list[Task]:
|
|
122
|
+
filt, sort = to_document_query(query)
|
|
123
|
+
return self._versioned.query(filt, sort, query._limit_value, query._offset_value)
|
|
124
|
+
|
|
125
|
+
def execute_count(self, query: TaskQuery) -> int:
|
|
126
|
+
filt, _ = to_document_query(query)
|
|
127
|
+
return self._versioned.count(filt)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
_task_store: Optional[TaskStore] = None
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def get_task_store() -> TaskStore:
|
|
134
|
+
global _task_store
|
|
135
|
+
if _task_store is None:
|
|
136
|
+
_task_store = TaskStore()
|
|
137
|
+
return _task_store
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def set_task_store(store: TaskStore) -> None:
|
|
141
|
+
global _task_store
|
|
142
|
+
_task_store = store
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def reset_task_store() -> None:
|
|
146
|
+
global _task_store
|
|
147
|
+
_task_store = None
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
# --- TaskInstance store (non-versioned, tracks task run instances) ---
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class TaskStepStatus(StrEnum):
|
|
154
|
+
SUCCESS = "success"
|
|
155
|
+
FAILURE = "failure"
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
@dataclass
|
|
159
|
+
class TaskStepResult:
|
|
160
|
+
step_id: str
|
|
161
|
+
status: TaskStepStatus
|
|
162
|
+
|
|
163
|
+
@classmethod
|
|
164
|
+
def from_dict(cls, data: dict) -> TaskStepResult:
|
|
165
|
+
return cls(step_id=data["step_id"], status=TaskStepStatus(data["status"]))
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
@dataclass
|
|
169
|
+
class TaskInstance:
|
|
170
|
+
instance_id: str
|
|
171
|
+
task_id: str
|
|
172
|
+
task_version: int
|
|
173
|
+
status: str
|
|
174
|
+
current_step: int
|
|
175
|
+
total_steps: int
|
|
176
|
+
context: dict | None = None
|
|
177
|
+
error: str | None = None
|
|
178
|
+
created_at_utc: str | None = None
|
|
179
|
+
completed_at_utc: str | None = None
|
|
180
|
+
rev: int = 0
|
|
181
|
+
completed_steps: list[TaskStepResult] = field(default_factory=list)
|
|
182
|
+
step_attempt_failures: list[dict] = field(default_factory=list)
|
|
183
|
+
# Bumped by ``undo_steps_sync(bump_epoch=True)`` on each retry. A completion write
|
|
184
|
+
# carries the epoch it was dispatched under and no-ops when older than the stored one,
|
|
185
|
+
# fencing a writer from a rolled-back attempt. Missing (pre-field docs) reads as 0.
|
|
186
|
+
attempt_epoch: int = 0
|
|
187
|
+
|
|
188
|
+
@classmethod
|
|
189
|
+
def from_dict(cls, data: dict) -> TaskInstance:
|
|
190
|
+
return cls(
|
|
191
|
+
instance_id=data["instance_id"],
|
|
192
|
+
task_id=data["task_id"],
|
|
193
|
+
task_version=data["task_version"],
|
|
194
|
+
status=data["status"],
|
|
195
|
+
current_step=data["current_step"],
|
|
196
|
+
total_steps=data["total_steps"],
|
|
197
|
+
context=data.get("context"),
|
|
198
|
+
error=data.get("error"),
|
|
199
|
+
created_at_utc=data.get("created_at_utc"),
|
|
200
|
+
completed_at_utc=data.get("completed_at_utc"),
|
|
201
|
+
rev=data.get("rev", 0),
|
|
202
|
+
completed_steps=[TaskStepResult.from_dict(e) for e in data.get("completed_steps", [])],
|
|
203
|
+
step_attempt_failures=data.get("step_attempt_failures", []),
|
|
204
|
+
attempt_epoch=data.get("attempt_epoch", 0),
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
@dataclass
|
|
209
|
+
class StepAttemptFailure:
|
|
210
|
+
"""Recorded once per failed step attempt, so a later retry can't clobber the earlier,
|
|
211
|
+
more useful failure messages."""
|
|
212
|
+
|
|
213
|
+
attempt: int
|
|
214
|
+
step_id: str | None = None
|
|
215
|
+
step_type: str | None = None
|
|
216
|
+
error_class: str | None = None
|
|
217
|
+
error_message: str | None = None
|
|
218
|
+
duration_s: float | None = None
|
|
219
|
+
occurred_at_utc: str | None = None
|
|
220
|
+
|
|
221
|
+
def to_dict(self) -> dict:
|
|
222
|
+
return dataclasses.asdict(self)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _fresh_run_state(start_step: int, completed_step_docs: list[dict]) -> dict:
|
|
226
|
+
"""The fields a run owns. A re-register resets exactly these, so both registration paths
|
|
227
|
+
have to agree on them; ``rev`` and the generation are bumped there instead and live in
|
|
228
|
+
``_new_instance_doc``."""
|
|
229
|
+
return {
|
|
230
|
+
"context": dataclasses.asdict(TaskStepContext()),
|
|
231
|
+
"completed_steps": completed_step_docs,
|
|
232
|
+
"status": "running",
|
|
233
|
+
"error": None,
|
|
234
|
+
"completed_at_utc": None,
|
|
235
|
+
"current_step": start_step,
|
|
236
|
+
# Present from birth: undo reads this as the authoritative record, so *absent* has to
|
|
237
|
+
# mean "predates the journal", not "no re-records yet".
|
|
238
|
+
_RERECORDED: [],
|
|
239
|
+
"attempt_epoch": 0,
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _new_instance_doc(
|
|
244
|
+
instance_id: str, task_id: str, task_version: int, total_steps: int,
|
|
245
|
+
created_at_utc: str, run_state: dict,
|
|
246
|
+
) -> dict:
|
|
247
|
+
"""A brand-new instance document: identity, the counters a re-register bumps, run state."""
|
|
248
|
+
return {
|
|
249
|
+
"instance_id": instance_id,
|
|
250
|
+
"task_id": task_id,
|
|
251
|
+
"task_version": task_version,
|
|
252
|
+
"total_steps": total_steps,
|
|
253
|
+
"created_at_utc": created_at_utc,
|
|
254
|
+
"rev": 0,
|
|
255
|
+
_GENERATION: 0,
|
|
256
|
+
**run_state,
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
class TaskInstanceStore:
|
|
261
|
+
def __init__(self) -> None:
|
|
262
|
+
self._indexed = None
|
|
263
|
+
|
|
264
|
+
@property
|
|
265
|
+
def _doc_store(self):
|
|
266
|
+
# Resolved per call: a cached store outlives reset_config(), so a process that
|
|
267
|
+
# re-pointed would read the new config and write the old backend. An operation that
|
|
268
|
+
# writes more than once resolves here once and passes ``store`` down, so a reset
|
|
269
|
+
# between its writes cannot leave half of it in each backend.
|
|
270
|
+
store = get_config().get_document_store()
|
|
271
|
+
if self._indexed is not store:
|
|
272
|
+
store.ensure_index(TASK_INSTANCES_COLLECTION, ["instance_id"], unique=True)
|
|
273
|
+
store.ensure_index(TASK_INSTANCES_COLLECTION, ["task_id"])
|
|
274
|
+
store.ensure_index(TASK_INSTANCES_COLLECTION, ["task_id", "created_at_utc"])
|
|
275
|
+
store.ensure_index(TASK_INSTANCES_COLLECTION, ["task_id", "task_version", "created_at_utc"])
|
|
276
|
+
store.ensure_index(TASK_STEP_JOURNAL_COLLECTION, ["instance_id", "step_id"], unique=True)
|
|
277
|
+
store.ensure_index(TASK_STEP_JOURNAL_COLLECTION, ["instance_id", "seq"])
|
|
278
|
+
self._indexed = store
|
|
279
|
+
return store
|
|
280
|
+
|
|
281
|
+
def create_instance(
|
|
282
|
+
self,
|
|
283
|
+
task_id: str,
|
|
284
|
+
task_version: int,
|
|
285
|
+
total_steps: int,
|
|
286
|
+
start_step: int = 0,
|
|
287
|
+
completed_steps: list[TaskStepResult] | None = None,
|
|
288
|
+
) -> TaskInstance:
|
|
289
|
+
completed_step_docs = [
|
|
290
|
+
dataclasses.asdict(e) for e in completed_steps or []
|
|
291
|
+
]
|
|
292
|
+
suffix = "".join(random.choices(string.ascii_lowercase + string.digits, k=8))
|
|
293
|
+
instance_id = f"{task_id}-{suffix}"
|
|
294
|
+
created_at_utc = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
|
|
295
|
+
doc = _new_instance_doc(
|
|
296
|
+
instance_id, task_id, task_version, total_steps, created_at_utc,
|
|
297
|
+
_fresh_run_state(start_step, completed_step_docs),
|
|
298
|
+
)
|
|
299
|
+
store = self._doc_store
|
|
300
|
+
store.insert(TASK_INSTANCES_COLLECTION, doc)
|
|
301
|
+
self._journal_seeded_completions(store, instance_id, completed_step_docs)
|
|
302
|
+
return TaskInstance.from_dict(doc)
|
|
303
|
+
|
|
304
|
+
def upsert_instance(
|
|
305
|
+
self,
|
|
306
|
+
instance_id: str,
|
|
307
|
+
task_id: str,
|
|
308
|
+
task_version: int,
|
|
309
|
+
total_steps: int,
|
|
310
|
+
start_step: int = 0,
|
|
311
|
+
completed_steps: list[TaskStepResult] | None = None,
|
|
312
|
+
) -> TaskInstance | None:
|
|
313
|
+
"""Idempotent register on a caller-supplied ``instance_id``."""
|
|
314
|
+
current_time_str = datetime.now(timezone.utc).strftime(
|
|
315
|
+
"%Y-%m-%d %H:%M UTC"
|
|
316
|
+
)
|
|
317
|
+
completed_step_docs = [
|
|
318
|
+
dataclasses.asdict(e) for e in completed_steps or []
|
|
319
|
+
]
|
|
320
|
+
run_state = _fresh_run_state(start_step, completed_step_docs)
|
|
321
|
+
fresh_doc = _new_instance_doc(
|
|
322
|
+
instance_id, task_id, task_version, total_steps, current_time_str, run_state,
|
|
323
|
+
)
|
|
324
|
+
store = self._doc_store
|
|
325
|
+
try:
|
|
326
|
+
store.insert(TASK_INSTANCES_COLLECTION, fresh_doc)
|
|
327
|
+
self._journal_seeded_completions(store, instance_id, completed_step_docs)
|
|
328
|
+
return TaskInstance.from_dict(fresh_doc)
|
|
329
|
+
except DuplicateKeyError:
|
|
330
|
+
# atomic inc (not read-then-set rev): stays monotonic under concurrent re-registers + racing step CAS.
|
|
331
|
+
# The same write bumps the generation, retiring the old journal without a delete that
|
|
332
|
+
# could race a completion still landing.
|
|
333
|
+
updated = store.update_one_and_get(
|
|
334
|
+
TASK_INSTANCES_COLLECTION,
|
|
335
|
+
Filter.of(instance_id=instance_id),
|
|
336
|
+
UpdateSpec(set=dict(run_state), inc={_REV: 1, _GENERATION: 1}),
|
|
337
|
+
return_after=True,
|
|
338
|
+
)
|
|
339
|
+
if updated is None:
|
|
340
|
+
raise RuntimeError(
|
|
341
|
+
f"register_task_instance: instance {instance_id!r} "
|
|
342
|
+
"disappeared during re-register"
|
|
343
|
+
)
|
|
344
|
+
self._journal_seeded_completions(store, instance_id, completed_step_docs)
|
|
345
|
+
return TaskInstance.from_dict(updated)
|
|
346
|
+
|
|
347
|
+
def file_artifact_universe_ids_for_batch(self, batch_id: str) -> list[str]:
|
|
348
|
+
"""Return FileArtifactUniverse ids produced by task instances in a batch.
|
|
349
|
+
|
|
350
|
+
``batch_id`` is a batch-runner concept stored on the task instance
|
|
351
|
+
(``context.metadata.batch_id``). The ``collect_artifacts`` step writes
|
|
352
|
+
a forward pointer (``context.metadata.file_artifact_universe.id``) on
|
|
353
|
+
the instance, so aggregating those ids over every instance matching
|
|
354
|
+
the batch gives the set of universes that batch produced.
|
|
355
|
+
|
|
356
|
+
De-duplicates while preserving first-appearance order: instances by creation time (to the
|
|
357
|
+
minute), then by instance id. The order is imposed here, since a document store returns a
|
|
358
|
+
query's matches in no particular order.
|
|
359
|
+
"""
|
|
360
|
+
docs = self._doc_store.query(
|
|
361
|
+
TASK_INSTANCES_COLLECTION, Filter.of(**{"context.metadata.batch_id": batch_id})
|
|
362
|
+
)
|
|
363
|
+
seen: set[str] = set()
|
|
364
|
+
ids: list[str] = []
|
|
365
|
+
for doc in sorted(docs, key=lambda d: (d.get("created_at_utc") or "", d.get("instance_id") or "")):
|
|
366
|
+
uid = _get_path(doc, "context.metadata.file_artifact_universe.id")
|
|
367
|
+
if uid and uid not in seen:
|
|
368
|
+
seen.add(uid)
|
|
369
|
+
ids.append(uid)
|
|
370
|
+
return ids
|
|
371
|
+
|
|
372
|
+
def get(self, instance_id: str) -> TaskInstance:
|
|
373
|
+
doc = self._doc_store.find_one(TASK_INSTANCES_COLLECTION, Filter.of(instance_id=instance_id))
|
|
374
|
+
if not doc:
|
|
375
|
+
raise NotFoundError(f"TaskInstance '{instance_id}' not found")
|
|
376
|
+
return TaskInstance.from_dict(doc)
|
|
377
|
+
|
|
378
|
+
def seed_context(self, instance_id: str, ops: "ContextUpdateOps") -> None:
|
|
379
|
+
"""Apply the run's initial context, then journal it as the replay base (even when empty)."""
|
|
380
|
+
store = self._doc_store
|
|
381
|
+
# One entry per deployment, as completions and the replay of this seed write them.
|
|
382
|
+
ops = dataclasses.replace(ops, add_to_sets={p: _union([], items, path=p) for p, items in ops.add_to_sets.items()})
|
|
383
|
+
if not ops.is_empty():
|
|
384
|
+
store.update(
|
|
385
|
+
TASK_INSTANCES_COLLECTION, Filter.of(instance_id=instance_id), ops.to_update_spec()
|
|
386
|
+
)
|
|
387
|
+
# Doc first: a failed journal write (logged by the caller) must not cost the run its seed.
|
|
388
|
+
self._journal_step(store, instance_id, _SEED_STEP_ID, ops, "seed")
|
|
389
|
+
|
|
390
|
+
def _bump_journal_seq(self, store: DocumentStore, instance_id: str) -> dict | None:
|
|
391
|
+
"""Atomically bump the instance's journal sequence; the post-update doc, or None if the
|
|
392
|
+
instance is missing."""
|
|
393
|
+
return store.update_one_and_get(
|
|
394
|
+
TASK_INSTANCES_COLLECTION, Filter.of(instance_id=instance_id),
|
|
395
|
+
UpdateSpec(inc={_JOURNAL_SEQ: 1}),
|
|
396
|
+
)
|
|
397
|
+
|
|
398
|
+
def _journal_step(
|
|
399
|
+
self, store: DocumentStore, instance_id: str, step_id: str, ops: "ContextUpdateOps", status: str,
|
|
400
|
+
attempt_epoch: int | None = None,
|
|
401
|
+
) -> tuple[int, int] | None:
|
|
402
|
+
"""Record a step's diff, replacing any earlier entry for it under a fresh ``seq``.
|
|
403
|
+
Returns ``(seq, generation)``, or None if the instance is missing, the write is
|
|
404
|
+
already fenced by ``attempt_epoch``, or a later attempt already owns the row: a
|
|
405
|
+
completion that will not land must not displace the entry the re-run committed."""
|
|
406
|
+
doc = self._bump_journal_seq(store, instance_id)
|
|
407
|
+
if doc is None:
|
|
408
|
+
return None
|
|
409
|
+
if attempt_epoch is not None and doc.get("attempt_epoch", 0) > attempt_epoch:
|
|
410
|
+
return None
|
|
411
|
+
seq = doc[_JOURNAL_SEQ]
|
|
412
|
+
generation = doc.get(_GENERATION, 0)
|
|
413
|
+
row = {
|
|
414
|
+
"instance_id": instance_id,
|
|
415
|
+
"step_id": step_id,
|
|
416
|
+
"seq": seq,
|
|
417
|
+
"generation": generation,
|
|
418
|
+
"status": status,
|
|
419
|
+
"recorded_at": datetime.now(timezone.utc), # a real datetime, so a retention index could key on it later
|
|
420
|
+
"ops": ops.to_journal_dict(),
|
|
421
|
+
}
|
|
422
|
+
if not self._write_journal_row(store, instance_id, step_id, row):
|
|
423
|
+
return None
|
|
424
|
+
return seq, generation
|
|
425
|
+
|
|
426
|
+
def _write_journal_row(self, store: DocumentStore, instance_id: str, step_id: str, row: dict) -> bool:
|
|
427
|
+
"""Land ``row`` for the step unless a row with a higher ``seq`` already exists.
|
|
428
|
+
|
|
429
|
+
The seq is taken before the epoch fence and the completion CAS, so a writer that
|
|
430
|
+
passed the fence and then paused always carries a lower seq than any writer that
|
|
431
|
+
started after the undo. Never going backwards in seq is what keeps that writer from
|
|
432
|
+
displacing the re-run's entry between the fence and its own (declined) CAS; the fence
|
|
433
|
+
and this write cannot be one atomic operation across two collections. Returns
|
|
434
|
+
whether the row landed."""
|
|
435
|
+
key = Filter.of(instance_id=instance_id, step_id=step_id)
|
|
436
|
+
older = key.where("seq", Lte(row["seq"] - 1))
|
|
437
|
+
for _ in range(5):
|
|
438
|
+
if store.replace(TASK_STEP_JOURNAL_COLLECTION, older, row):
|
|
439
|
+
return True
|
|
440
|
+
existing = store.find_one(TASK_STEP_JOURNAL_COLLECTION, key)
|
|
441
|
+
if existing is None:
|
|
442
|
+
try:
|
|
443
|
+
store.insert(TASK_STEP_JOURNAL_COLLECTION, row)
|
|
444
|
+
return True
|
|
445
|
+
except DuplicateKeyError:
|
|
446
|
+
continue # lost the first-insert race; compare seqs on the next pass
|
|
447
|
+
if existing.get("seq", 0) >= row["seq"]:
|
|
448
|
+
return False # a later attempt owns the row
|
|
449
|
+
# An older row landed between the replace and the read; replace it on the next pass.
|
|
450
|
+
raise RuntimeError(
|
|
451
|
+
f"journal row for step {step_id!r} on instance {instance_id!r} kept changing under us"
|
|
452
|
+
)
|
|
453
|
+
|
|
454
|
+
def journal_step_sync(self, instance_id: str, step_id: str, ops: "ContextUpdateOps", status: str) -> int | None:
|
|
455
|
+
"""``_journal_step`` on the current backend, for callers that only need the seq."""
|
|
456
|
+
journaled = self._journal_step(self._doc_store, instance_id, step_id, ops, status)
|
|
457
|
+
return None if journaled is None else journaled[0]
|
|
458
|
+
|
|
459
|
+
def _journal_seeded_completions(
|
|
460
|
+
self, store: DocumentStore, instance_id: str, completed_step_docs: list[dict],
|
|
461
|
+
) -> None:
|
|
462
|
+
"""Journal an empty entry per completion carried in from a previous attempt, so a
|
|
463
|
+
completion with no entry means exactly one thing: its journal write failed. Empty is
|
|
464
|
+
the truthful diff — the seed already holds whatever those steps wrote."""
|
|
465
|
+
from agent_env.task_step.context_ops import ContextUpdateOps
|
|
466
|
+
|
|
467
|
+
for c in completed_step_docs:
|
|
468
|
+
try:
|
|
469
|
+
self._journal_step(store, instance_id, c["step_id"], ContextUpdateOps(), c["status"])
|
|
470
|
+
except Exception:
|
|
471
|
+
logger.warning("Failed to journal seeded step %s for instance_id=%s",
|
|
472
|
+
c["step_id"], instance_id, exc_info=True)
|
|
473
|
+
|
|
474
|
+
def journal_entries_sync(self, instance_id: str, generation: int | None = None) -> list[dict]:
|
|
475
|
+
"""The instance's entries for one run generation, in seq order; a previous run's are
|
|
476
|
+
retired and not returned. ``generation`` defaults to the instance's current one."""
|
|
477
|
+
return self._journal_entries(self._doc_store, instance_id, generation)
|
|
478
|
+
|
|
479
|
+
def _journal_entries(
|
|
480
|
+
self, store: DocumentStore, instance_id: str, generation: int | None,
|
|
481
|
+
) -> list[dict]:
|
|
482
|
+
if generation is None:
|
|
483
|
+
instance = store.find_one(TASK_INSTANCES_COLLECTION, Filter.of(instance_id=instance_id))
|
|
484
|
+
generation = 0 if instance is None else instance.get(_GENERATION, 0)
|
|
485
|
+
entries = store.query(
|
|
486
|
+
TASK_STEP_JOURNAL_COLLECTION, Filter.of(instance_id=instance_id),
|
|
487
|
+
sort=Sort.by("seq", descending=False),
|
|
488
|
+
)
|
|
489
|
+
return [e for e in entries if e.get("generation", 0) == generation]
|
|
490
|
+
|
|
491
|
+
def clear_journal_sync(self, instance_id: str) -> None:
|
|
492
|
+
"""Drop every journal entry for an instance, whatever its generation. Not on the
|
|
493
|
+
re-register path — a delete racing a live completion is exactly what generations
|
|
494
|
+
exist to avoid — this is for an explicit teardown."""
|
|
495
|
+
store = self._doc_store
|
|
496
|
+
entries = store.query(
|
|
497
|
+
TASK_STEP_JOURNAL_COLLECTION, Filter.of(instance_id=instance_id),
|
|
498
|
+
)
|
|
499
|
+
for e in entries:
|
|
500
|
+
store.delete(
|
|
501
|
+
TASK_STEP_JOURNAL_COLLECTION, Filter.of(instance_id=instance_id, step_id=e["step_id"]),
|
|
502
|
+
)
|
|
503
|
+
|
|
504
|
+
def undo_steps_sync(
|
|
505
|
+
self,
|
|
506
|
+
instance_id: str,
|
|
507
|
+
step_ids: set[str],
|
|
508
|
+
*,
|
|
509
|
+
extra_ops: "Callable[[dict, dict], ContextUpdateOps] | None" = None,
|
|
510
|
+
bump_epoch: bool = False,
|
|
511
|
+
) -> dict | None:
|
|
512
|
+
"""Roll the named steps out by replaying the surviving committed entries over the seed,
|
|
513
|
+
in one CAS on ``rev``, then delete those entries at the seq it read. None if the
|
|
514
|
+
instance is missing. Refuses a missing seed or an unjournaled survivor; callers
|
|
515
|
+
regraft secrets into the returned doc.
|
|
516
|
+
|
|
517
|
+
``extra_ops(before_context, after_context)`` lets the caller write its own record in
|
|
518
|
+
the same CAS (the scheduler's retry audit): it sees the context as stored and as
|
|
519
|
+
replayed, returns forward ops, and those are applied on top of the replay and then
|
|
520
|
+
journaled under ``__scheduler__``, which replays right after the seed and is never
|
|
521
|
+
undone. ``bump_epoch`` advances ``attempt_epoch`` in the same write, so a completion
|
|
522
|
+
still in flight from the undone attempt is fenced (``record_step_complete_sync``).
|
|
523
|
+
"""
|
|
524
|
+
step_ids = set(step_ids) - _RESERVED_STEP_IDS
|
|
525
|
+
undone_seqs: dict[str, int] = {}
|
|
526
|
+
applied_extra: list["ContextUpdateOps"] = []
|
|
527
|
+
store = self._doc_store
|
|
528
|
+
|
|
529
|
+
def _mutate(doc: dict) -> UpdateSpec:
|
|
530
|
+
entries = self._journal_entries(store, instance_id, doc.get(_GENERATION, 0))
|
|
531
|
+
# The seq this attempt read, so the trim can't delete a row a re-completion wrote after the CAS.
|
|
532
|
+
undone_seqs.clear()
|
|
533
|
+
undone_seqs.update({e["step_id"]: e["seq"] for e in entries if e["step_id"] in step_ids})
|
|
534
|
+
before = doc.get("completed_steps", [])
|
|
535
|
+
completed_ids = {c.get("step_id") for c in before}
|
|
536
|
+
if not any(e["step_id"] == _SEED_STEP_ID for e in entries):
|
|
537
|
+
raise ValueError(f"instance {instance_id!r} has no journal seed (pre-journal or unseeded); cannot undo")
|
|
538
|
+
journaled = {e["step_id"] for e in entries}
|
|
539
|
+
unreplayable = sorted(
|
|
540
|
+
c["step_id"] for c in before
|
|
541
|
+
if c.get("status") != TaskStepStatus.FAILURE
|
|
542
|
+
and c["step_id"] not in journaled and c["step_id"] not in step_ids
|
|
543
|
+
)
|
|
544
|
+
if unreplayable:
|
|
545
|
+
raise ValueError(
|
|
546
|
+
f"steps {unreplayable} completed without a journal entry; their writes cannot be "
|
|
547
|
+
f"replayed, refusing to undo {sorted(step_ids)} on instance {instance_id!r}"
|
|
548
|
+
)
|
|
549
|
+
completed = [c for c in before if c.get("step_id") not in step_ids]
|
|
550
|
+
keep = commit_ordered([e for e in entries if e["step_id"] not in step_ids], completed)
|
|
551
|
+
# The instance's own flags, not the entries' pre-CAS ones (see ``replay_context``).
|
|
552
|
+
# Every instance this code creates carries the field, so absent means the run
|
|
553
|
+
# predates the journal: its entries' flags are pre-CAS guesses that a losing
|
|
554
|
+
# writer can have left stale, and the winning CAS's verdict is unrecoverable.
|
|
555
|
+
flags = doc.get(_RERECORDED)
|
|
556
|
+
if flags is None:
|
|
557
|
+
raise ValueError(
|
|
558
|
+
f"instance {instance_id!r} predates {_RERECORDED} (pre-journal run); its "
|
|
559
|
+
"entries carry only pre-CAS re-record flags, so replay order cannot be "
|
|
560
|
+
f"reconstructed — refusing to undo {sorted(step_ids)}"
|
|
561
|
+
)
|
|
562
|
+
rerecords = [s for s in flags if s not in step_ids]
|
|
563
|
+
replayed = {"context": replay_context(keep, rerecords)}
|
|
564
|
+
applied_extra.clear()
|
|
565
|
+
if extra_ops is not None:
|
|
566
|
+
# Copies: the callback must not be able to edit the CAS's working state.
|
|
567
|
+
ops = extra_ops(copy.deepcopy(doc.get("context") or {}), copy.deepcopy(replayed["context"]))
|
|
568
|
+
_apply_forward(replayed, ops)
|
|
569
|
+
applied_extra.append(ops)
|
|
570
|
+
fields: dict = {
|
|
571
|
+
"context": replayed["context"],
|
|
572
|
+
"completed_steps": completed,
|
|
573
|
+
"current_step": len(completed),
|
|
574
|
+
_RERECORDED: rerecords,
|
|
575
|
+
}
|
|
576
|
+
if bump_epoch:
|
|
577
|
+
fields["attempt_epoch"] = doc.get("attempt_epoch", 0) + 1
|
|
578
|
+
if len(completed) < len(before):
|
|
579
|
+
undone_the_failure = any(
|
|
580
|
+
c.get("status") == TaskStepStatus.FAILURE
|
|
581
|
+
for c in before if c.get("step_id") in step_ids
|
|
582
|
+
)
|
|
583
|
+
if doc.get("status") != "failed" or undone_the_failure:
|
|
584
|
+
# A completion came off a finished run: it is running again until re-recorded.
|
|
585
|
+
fields.update(status="running", error=None, completed_at_utc=None)
|
|
586
|
+
# Otherwise the step that failed the run is still recorded — undoing a
|
|
587
|
+
# *different* step does not make the run healthy, so its error stands.
|
|
588
|
+
return UpdateSpec(set=fields)
|
|
589
|
+
|
|
590
|
+
result = compare_and_swap(
|
|
591
|
+
store, TASK_INSTANCES_COLLECTION, Filter.of(instance_id=instance_id),
|
|
592
|
+
_mutate, counter_field=_REV,
|
|
593
|
+
)
|
|
594
|
+
if result is None:
|
|
595
|
+
return None
|
|
596
|
+
for sid, seq in undone_seqs.items():
|
|
597
|
+
store.delete(
|
|
598
|
+
TASK_STEP_JOURNAL_COLLECTION,
|
|
599
|
+
Filter.of(instance_id=instance_id, step_id=sid, seq=seq),
|
|
600
|
+
)
|
|
601
|
+
if applied_extra:
|
|
602
|
+
# Doc first, like the seed: the record is in the context already; a failed journal
|
|
603
|
+
# write only means replay lacks it until the next undo rewrites this row.
|
|
604
|
+
try:
|
|
605
|
+
self._journal_step(store, instance_id, _SCHEDULER_STEP_ID, applied_extra[0], "scheduler")
|
|
606
|
+
except Exception:
|
|
607
|
+
logger.warning("Failed to journal the scheduler record for instance_id=%s", instance_id, exc_info=True)
|
|
608
|
+
return result
|
|
609
|
+
|
|
610
|
+
def record_step_complete_sync(
|
|
611
|
+
self,
|
|
612
|
+
instance_id: str,
|
|
613
|
+
entry: dict,
|
|
614
|
+
ops: "ContextUpdateOps",
|
|
615
|
+
total_steps: int,
|
|
616
|
+
completed_at_utc: str,
|
|
617
|
+
attempt_epoch: int = 0,
|
|
618
|
+
) -> None:
|
|
619
|
+
"""Journal the step's diff, then upsert the step into ``completed_steps`` (moved to the
|
|
620
|
+
end) and derive ``current_step``/``status`` under an optimistic compare-and-swap on
|
|
621
|
+
``rev`` (retried).
|
|
622
|
+
|
|
623
|
+
Journal first but fail open: a failed journal write is logged and the completion still
|
|
624
|
+
lands, leaving a completion with no entry, which is what undo refuses to replay over.
|
|
625
|
+
The CAS is bound to the generation captured while journaling, so a completion from a run
|
|
626
|
+
a re-register superseded is declined rather than joining the fresh one.
|
|
627
|
+
|
|
628
|
+
``attempt_epoch`` is the epoch the step was dispatched under. A write older than the
|
|
629
|
+
stored epoch is from an attempt a retry already rolled back; it neither journals nor
|
|
630
|
+
lands, so it cannot resurrect rolled-back state. Cancellation does not interrupt an
|
|
631
|
+
in-flight ``to_thread`` call, so this fence, not the cancel, stops the drained
|
|
632
|
+
step's write.
|
|
633
|
+
|
|
634
|
+
Replaces the old aggregation-pipeline update: the dedupe and the
|
|
635
|
+
``$size``/``$cond`` derivations run in Python, so any backend can implement it
|
|
636
|
+
with a plain conditional update.
|
|
637
|
+
"""
|
|
638
|
+
step_id = entry["step_id"]
|
|
639
|
+
store = self._doc_store
|
|
640
|
+
try:
|
|
641
|
+
journaled = self._journal_step(
|
|
642
|
+
store, instance_id, step_id, ops, entry["status"], attempt_epoch=attempt_epoch
|
|
643
|
+
)
|
|
644
|
+
except Exception:
|
|
645
|
+
logger.warning(
|
|
646
|
+
"Failed to journal step %s for instance_id=%s; completing without an undo record",
|
|
647
|
+
step_id, instance_id, exc_info=True,
|
|
648
|
+
)
|
|
649
|
+
journaled = None
|
|
650
|
+
seq, journaled_generation = journaled if journaled is not None else (None, None)
|
|
651
|
+
|
|
652
|
+
def _mutate(doc: dict) -> UpdateSpec | None:
|
|
653
|
+
if journaled_generation is not None and doc.get(_GENERATION, 0) != journaled_generation:
|
|
654
|
+
logger.warning(
|
|
655
|
+
"Declining completion of step %s for instance_id=%s: the run was "
|
|
656
|
+
"re-registered (generation %s -> %s) after the step journaled",
|
|
657
|
+
step_id, instance_id, journaled_generation, doc.get(_GENERATION, 0),
|
|
658
|
+
)
|
|
659
|
+
return None
|
|
660
|
+
if doc.get("attempt_epoch", 0) > attempt_epoch:
|
|
661
|
+
return None
|
|
662
|
+
# Position is the replay order, so a re-record moves to the end, items included.
|
|
663
|
+
rerecorded = any(c.get("step_id") == step_id for c in doc.get("completed_steps", []))
|
|
664
|
+
set_fields: dict = dict(ops.sets)
|
|
665
|
+
for path, items in ops.add_to_sets.items():
|
|
666
|
+
set_fields[path] = _union(_get_path(doc, path) or [], items, move_to_end=rerecorded, path=path)
|
|
667
|
+
completed = [c for c in doc.get("completed_steps", []) if c.get("step_id") != step_id] + [entry]
|
|
668
|
+
set_fields["completed_steps"] = completed
|
|
669
|
+
set_fields["current_step"] = len(completed)
|
|
670
|
+
# Computed from the doc this attempt won on, and recorded with the write it
|
|
671
|
+
# describes: the only record of a re-record, and the one replay reads.
|
|
672
|
+
rerecords = [s for s in doc.get(_RERECORDED, []) if s != step_id]
|
|
673
|
+
if rerecorded:
|
|
674
|
+
rerecords.append(step_id)
|
|
675
|
+
set_fields[_RERECORDED] = rerecords
|
|
676
|
+
if len(completed) >= total_steps and doc.get("status") != "failed":
|
|
677
|
+
set_fields["status"] = "completed"
|
|
678
|
+
set_fields["completed_at_utc"] = completed_at_utc
|
|
679
|
+
return UpdateSpec(set=set_fields, unset=set(ops.unsets))
|
|
680
|
+
|
|
681
|
+
result = compare_and_swap(
|
|
682
|
+
store,
|
|
683
|
+
TASK_INSTANCES_COLLECTION,
|
|
684
|
+
Filter.of(instance_id=instance_id),
|
|
685
|
+
_mutate,
|
|
686
|
+
counter_field=_REV,
|
|
687
|
+
)
|
|
688
|
+
if result is None and journaled is not None:
|
|
689
|
+
# The completion never landed, so the entry describes nothing in the document.
|
|
690
|
+
# Delete at the exact seq, so a re-record that replaced the row keeps its own.
|
|
691
|
+
store.delete(
|
|
692
|
+
TASK_STEP_JOURNAL_COLLECTION,
|
|
693
|
+
Filter.of(instance_id=instance_id, step_id=step_id, seq=seq),
|
|
694
|
+
)
|
|
695
|
+
|
|
696
|
+
def record_task_failure_sync(
|
|
697
|
+
self,
|
|
698
|
+
instance_id: str,
|
|
699
|
+
failing_step_id: str | None,
|
|
700
|
+
context: "TaskStepContext",
|
|
701
|
+
error: BaseException,
|
|
702
|
+
completed_at_utc: str,
|
|
703
|
+
) -> None:
|
|
704
|
+
"""Terminal failure write — one atomic update guarded on ``status != completed``
|
|
705
|
+
(so a sibling step that finished mid-cancel isn't overwritten)."""
|
|
706
|
+
spec = UpdateSpec(
|
|
707
|
+
set={
|
|
708
|
+
"status": "failed",
|
|
709
|
+
"error": str(error),
|
|
710
|
+
"context": context.to_safe_dict(),
|
|
711
|
+
"completed_at_utc": completed_at_utc,
|
|
712
|
+
},
|
|
713
|
+
inc={"rev": 1},
|
|
714
|
+
)
|
|
715
|
+
if failing_step_id is not None:
|
|
716
|
+
entry = dataclasses.asdict(TaskStepResult(step_id=failing_step_id, status=TaskStepStatus.FAILURE))
|
|
717
|
+
spec.add_to_set = {"completed_steps": [entry]}
|
|
718
|
+
self._doc_store.update(
|
|
719
|
+
TASK_INSTANCES_COLLECTION,
|
|
720
|
+
Filter.of(instance_id=instance_id).where("status", Ne("completed")),
|
|
721
|
+
spec,
|
|
722
|
+
)
|
|
723
|
+
|
|
724
|
+
def record_task_cancelled_sync(self, instance_id: str, reason: str, completed_at_utc: str) -> None:
|
|
725
|
+
"""Mark a run cancelled, over the ``failed`` its unwinding recorded, but never a completed one."""
|
|
726
|
+
self._doc_store.update(
|
|
727
|
+
TASK_INSTANCES_COLLECTION,
|
|
728
|
+
Filter.of(instance_id=instance_id).where("status", Ne("completed")),
|
|
729
|
+
UpdateSpec(
|
|
730
|
+
set={"status": "cancelled", "error": reason, "completed_at_utc": completed_at_utc},
|
|
731
|
+
inc={"rev": 1},
|
|
732
|
+
),
|
|
733
|
+
)
|
|
734
|
+
|
|
735
|
+
def append_step_attempt_failure_sync(self, instance_id: str, failure: "StepAttemptFailure") -> None:
|
|
736
|
+
"""Best-effort append of one attempt's failure, designed not to conflict with the
|
|
737
|
+
``record_task_failure`` write. ``add_to_set`` creates the array on the first append and
|
|
738
|
+
dedupes an identical re-issued write, so it's idempotent."""
|
|
739
|
+
self._doc_store.update(
|
|
740
|
+
TASK_INSTANCES_COLLECTION,
|
|
741
|
+
Filter.of(instance_id=instance_id).where("status", Ne("completed")),
|
|
742
|
+
UpdateSpec(add_to_set={"step_attempt_failures": [failure.to_dict()]}),
|
|
743
|
+
)
|
|
744
|
+
|
|
745
|
+
|
|
746
|
+
_task_instance_store: Optional[TaskInstanceStore] = None
|
|
747
|
+
|
|
748
|
+
|
|
749
|
+
def get_task_instance_store() -> TaskInstanceStore:
|
|
750
|
+
global _task_instance_store
|
|
751
|
+
if _task_instance_store is None:
|
|
752
|
+
_task_instance_store = TaskInstanceStore()
|
|
753
|
+
return _task_instance_store
|
|
754
|
+
|
|
755
|
+
|
|
756
|
+
def set_task_instance_store(store: TaskInstanceStore) -> None:
|
|
757
|
+
global _task_instance_store
|
|
758
|
+
_task_instance_store = store
|
|
759
|
+
|
|
760
|
+
|
|
761
|
+
def reset_task_instance_store() -> None:
|
|
762
|
+
global _task_instance_store
|
|
763
|
+
_task_instance_store = None
|
|
764
|
+
|
|
765
|
+
|
|
766
|
+
def register_task_instance(
|
|
767
|
+
task_id: str,
|
|
768
|
+
task_version: int,
|
|
769
|
+
total_steps: int,
|
|
770
|
+
start_step: int = 0,
|
|
771
|
+
instance_id: str | None = None,
|
|
772
|
+
completed_steps: list[TaskStepResult] | None = None,
|
|
773
|
+
) -> TaskInstance | None:
|
|
774
|
+
"""Register a task_instance row.
|
|
775
|
+
|
|
776
|
+
With ``instance_id``: idempotent upsert. Without: random-id insert.
|
|
777
|
+
"""
|
|
778
|
+
try:
|
|
779
|
+
store = get_task_instance_store()
|
|
780
|
+
if instance_id is None:
|
|
781
|
+
return store.create_instance(
|
|
782
|
+
task_id, task_version, total_steps, start_step, completed_steps,
|
|
783
|
+
)
|
|
784
|
+
return store.upsert_instance(
|
|
785
|
+
instance_id,
|
|
786
|
+
task_id,
|
|
787
|
+
task_version,
|
|
788
|
+
total_steps,
|
|
789
|
+
start_step,
|
|
790
|
+
completed_steps,
|
|
791
|
+
)
|
|
792
|
+
except Exception:
|
|
793
|
+
logger.warning("Failed to create task instance record", exc_info=True)
|
|
794
|
+
return None
|
|
795
|
+
|
|
796
|
+
|
|
797
|
+
def seed_task_instance_context(instance_id: str, context: "TaskStepContext") -> None:
|
|
798
|
+
"""Apply the caller's initial context to an instance row created by
|
|
799
|
+
``register_task_instance``, as path-level Mongo updates.
|
|
800
|
+
|
|
801
|
+
Must be called before any step's ``record_step_complete`` fires (steps
|
|
802
|
+
haven't started yet at this point in ``Task.run()``).
|
|
803
|
+
"""
|
|
804
|
+
from agent_env.task_step.context_ops import build_context_update_ops
|
|
805
|
+
|
|
806
|
+
ops = build_context_update_ops(None, context)
|
|
807
|
+
try:
|
|
808
|
+
get_task_instance_store().seed_context(instance_id, ops)
|
|
809
|
+
except Exception:
|
|
810
|
+
logger.warning("Failed to seed task instance context", exc_info=True)
|
|
811
|
+
|
|
812
|
+
|
|
813
|
+
async def record_step_complete(
|
|
814
|
+
instance_id: str,
|
|
815
|
+
step_id: str,
|
|
816
|
+
ops: "ContextUpdateOps",
|
|
817
|
+
total_steps: int,
|
|
818
|
+
completed_at_utc: str,
|
|
819
|
+
status: TaskStepStatus = TaskStepStatus.SUCCESS,
|
|
820
|
+
attempt_epoch: int = 0,
|
|
821
|
+
) -> None:
|
|
822
|
+
"""Union the step into ``completed_steps`` and derive ``current_step`` /
|
|
823
|
+
``status`` / ``completed_at_utc`` under an optimistic compare-and-swap on
|
|
824
|
+
``rev`` (read -> compute in Python -> conditional write, retried on
|
|
825
|
+
contention). Concurrent finishers converge without losing each other's
|
|
826
|
+
entries; ``completed_steps`` keeps first-appearance order. ``attempt_epoch``
|
|
827
|
+
fences a write from a rolled-back attempt (see ``record_step_complete_sync``).
|
|
828
|
+
"""
|
|
829
|
+
entry = dataclasses.asdict(TaskStepResult(step_id=step_id, status=status))
|
|
830
|
+
try:
|
|
831
|
+
await asyncio.to_thread(
|
|
832
|
+
get_task_instance_store().record_step_complete_sync,
|
|
833
|
+
instance_id, entry, ops, total_steps, completed_at_utc, attempt_epoch,
|
|
834
|
+
)
|
|
835
|
+
except Exception:
|
|
836
|
+
logger.error(
|
|
837
|
+
"Failed to record step complete for instance_id=%s step_id=%s",
|
|
838
|
+
instance_id, step_id, exc_info=True,
|
|
839
|
+
)
|
|
840
|
+
|
|
841
|
+
|
|
842
|
+
async def undo_steps(
|
|
843
|
+
instance_id: str,
|
|
844
|
+
step_ids: set[str],
|
|
845
|
+
*,
|
|
846
|
+
extra_ops: "Callable[[dict, dict], ContextUpdateOps] | None" = None,
|
|
847
|
+
bump_epoch: bool = False,
|
|
848
|
+
) -> dict | None:
|
|
849
|
+
"""Async ``TaskInstanceStore.undo_steps_sync``; None if the instance is missing or the
|
|
850
|
+
write failed (logged). A refusal propagates: the store is saying it cannot rebuild that
|
|
851
|
+
context, and a caller that re-dispatched anyway would run the span on a dirty one."""
|
|
852
|
+
try:
|
|
853
|
+
return await asyncio.to_thread(
|
|
854
|
+
get_task_instance_store().undo_steps_sync, instance_id, set(step_ids),
|
|
855
|
+
extra_ops=extra_ops, bump_epoch=bump_epoch,
|
|
856
|
+
)
|
|
857
|
+
except ValueError:
|
|
858
|
+
raise
|
|
859
|
+
except Exception:
|
|
860
|
+
logger.error("Failed to undo steps %s for instance_id=%s", sorted(step_ids), instance_id, exc_info=True)
|
|
861
|
+
return None
|
|
862
|
+
|
|
863
|
+
|
|
864
|
+
_FAILURE_WRITE_MAX_ATTEMPTS = 3
|
|
865
|
+
_FAILURE_WRITE_BACKOFF_SECONDS = 0.5
|
|
866
|
+
|
|
867
|
+
|
|
868
|
+
async def record_task_failure(
|
|
869
|
+
instance_id: str,
|
|
870
|
+
failing_step_id: str | None,
|
|
871
|
+
context: "TaskStepContext",
|
|
872
|
+
error: BaseException,
|
|
873
|
+
completed_at_utc: str,
|
|
874
|
+
) -> None:
|
|
875
|
+
"""Write terminal failure state.
|
|
876
|
+
|
|
877
|
+
Filter excludes already-completed instances: a sibling step's
|
|
878
|
+
`record_step_complete` may land between the scheduler's cancel and this
|
|
879
|
+
write (cancellation doesn't interrupt an in-flight `asyncio.to_thread`
|
|
880
|
+
call), and its CAS could have stamped `status="completed"`. The filter
|
|
881
|
+
makes this write a no-op in that case rather than flipping a successful run
|
|
882
|
+
to "failed".
|
|
883
|
+
"""
|
|
884
|
+
store = get_task_instance_store()
|
|
885
|
+
last_exc: BaseException | None = None
|
|
886
|
+
for attempt in range(_FAILURE_WRITE_MAX_ATTEMPTS):
|
|
887
|
+
try:
|
|
888
|
+
await asyncio.to_thread(
|
|
889
|
+
store.record_task_failure_sync,
|
|
890
|
+
instance_id, failing_step_id, context, error, completed_at_utc,
|
|
891
|
+
)
|
|
892
|
+
return
|
|
893
|
+
except Exception as exc: # noqa: BLE001
|
|
894
|
+
last_exc = exc
|
|
895
|
+
if attempt + 1 < _FAILURE_WRITE_MAX_ATTEMPTS:
|
|
896
|
+
await asyncio.sleep(_FAILURE_WRITE_BACKOFF_SECONDS * (2**attempt))
|
|
897
|
+
logger.warning(
|
|
898
|
+
"Failed to record task failure after %d attempts; the task instance record "
|
|
899
|
+
"will not show it",
|
|
900
|
+
_FAILURE_WRITE_MAX_ATTEMPTS, exc_info=last_exc,
|
|
901
|
+
)
|
|
902
|
+
|
|
903
|
+
|
|
904
|
+
|
|
905
|
+
|
|
906
|
+
def record_task_cancelled(instance_id: str, reason: str, completed_at_utc: str) -> None:
|
|
907
|
+
"""Write a cancelled run's terminal state, retried like ``record_task_failure``. It logs a write that keeps
|
|
908
|
+
failing rather than raising. Synchronous: ``run_bundle`` calls it once its event loop has closed."""
|
|
909
|
+
store = get_task_instance_store()
|
|
910
|
+
last_exc: BaseException | None = None
|
|
911
|
+
for attempt in range(_FAILURE_WRITE_MAX_ATTEMPTS):
|
|
912
|
+
try:
|
|
913
|
+
store.record_task_cancelled_sync(instance_id, reason, completed_at_utc)
|
|
914
|
+
return
|
|
915
|
+
except Exception as exc: # noqa: BLE001
|
|
916
|
+
last_exc = exc
|
|
917
|
+
if attempt + 1 < _FAILURE_WRITE_MAX_ATTEMPTS:
|
|
918
|
+
time.sleep(_FAILURE_WRITE_BACKOFF_SECONDS * (2**attempt))
|
|
919
|
+
logger.warning(
|
|
920
|
+
"Failed to record the cancellation of instance_id=%s after %d attempts",
|
|
921
|
+
instance_id, _FAILURE_WRITE_MAX_ATTEMPTS, exc_info=last_exc,
|
|
922
|
+
)
|
|
923
|
+
|
|
924
|
+
# Best-effort, diagnostic-only wrapper around ``append_step_attempt_failure_sync``: retries a
|
|
925
|
+
# transient write (like ``record_task_failure``), then logs and swallows — never raises.
|
|
926
|
+
async def append_step_attempt_failure(instance_id: str, failure: "StepAttemptFailure") -> None:
|
|
927
|
+
store = get_task_instance_store()
|
|
928
|
+
last_exc: BaseException | None = None
|
|
929
|
+
for attempt in range(_FAILURE_WRITE_MAX_ATTEMPTS):
|
|
930
|
+
try:
|
|
931
|
+
await asyncio.to_thread(store.append_step_attempt_failure_sync, instance_id, failure)
|
|
932
|
+
return
|
|
933
|
+
except Exception as exc: # noqa: BLE001
|
|
934
|
+
last_exc = exc
|
|
935
|
+
if attempt + 1 < _FAILURE_WRITE_MAX_ATTEMPTS:
|
|
936
|
+
await asyncio.sleep(_FAILURE_WRITE_BACKOFF_SECONDS * (2**attempt))
|
|
937
|
+
logger.warning(
|
|
938
|
+
"Failed to append attempt-failure ledger entry for instance_id=%s after %d attempts",
|
|
939
|
+
instance_id, _FAILURE_WRITE_MAX_ATTEMPTS, exc_info=last_exc,
|
|
940
|
+
)
|