@arcticdata/dsh-datarc-skills 0.0.0-stage → 26.39.0
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.
- package/README.md +20 -2
- package/cordis.patch.yml +4 -0
- package/icon.svg +4 -0
- package/index.js +35 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +37 -4
- package/skills/datarc-access-permissions/SKILL.md +30 -0
- package/skills/datarc-access-permissions/references/api.md +31 -0
- package/skills/datarc-access-permissions/references/write-order.md +16 -0
- package/skills/datarc-analysis-report/SKILL.md +125 -0
- package/skills/datarc-analysis-report/agents/openai.yaml +6 -0
- package/skills/datarc-analysis-report/references/analyst-frameworks.md +215 -0
- package/skills/datarc-analysis-report/references/api-contracts.md +478 -0
- package/skills/datarc-analysis-report/references/direct-card-fallback-design.md +66 -0
- package/skills/datarc-analysis-report/references/human-in-the-loop.md +142 -0
- package/skills/datarc-analysis-report/references/loop-personalization-policy.md +138 -0
- package/skills/datarc-analysis-report/references/manifest-example.json +779 -0
- package/skills/datarc-analysis-report/references/narrative-schema.md +160 -0
- package/skills/datarc-analysis-report/references/question-syntax.md +151 -0
- package/skills/datarc-analysis-report/scripts/run_analysis_report.py +2225 -0
- package/skills/datarc-analysis-report/scripts/run_dataseek_cards.py +1914 -0
- package/skills/datarc-analysis-report/scripts/test_run_analysis_report.py +5295 -0
- package/skills/datarc-data-search/SKILL.md +243 -0
- package/skills/datarc-data-search/scripts/calculate.py +116 -0
- package/skills/datarc-data-search/scripts/data-search.mjs +628 -0
- package/skills/datarc-data-search/scripts/datarc-client.mjs +464 -0
- package/skills/datarc-data-search/scripts/search-result.mjs +211 -0
- package/skills/datarc-dataseek-batch-evaluation/SKILL.md +59 -0
- package/skills/datarc-dataseek-batch-evaluation/references/artifacts.md +36 -0
- package/skills/datarc-dataseek-batch-evaluation/references/equivalence.md +30 -0
- package/skills/datarc-dataseek-batch-evaluation/scripts/datarc-client.mjs +464 -0
- package/skills/datarc-dataseek-batch-evaluation/scripts/dataseek-batch-evaluation.mjs +1020 -0
- package/skills/datarc-dataseek-search/SKILL.md +96 -0
- package/skills/datarc-dataseek-search/scripts/datarc-client.mjs +464 -0
- package/skills/datarc-dataseek-search/scripts/dataseek-search.mjs +257 -0
- package/skills/datarc-dataseek-semantic-debugging/SKILL.md +44 -0
- package/skills/datarc-dataseek-semantic-debugging/agents/openai.yaml +4 -0
- package/skills/datarc-dataseek-semantic-debugging/evals/evals.json +165 -0
- package/skills/datarc-dataseek-semantic-debugging/references/dataset.md +77 -0
- package/skills/datarc-dataseek-semantic-debugging/references/input-and-resolution.md +93 -0
- package/skills/datarc-dataseek-semantic-debugging/references/interventions.md +64 -0
- package/skills/datarc-dataseek-semantic-debugging/references/knowledge-and-prompts.md +47 -0
- package/skills/datarc-dataseek-semantic-debugging/references/rollback.md +11 -0
- package/skills/datarc-dataseek-semantic-debugging/references/verification-and-rollback.md +95 -0
- package/skills/datarc-dataseek-semantic-debugging/scripts/semantic-debugging.mjs +29 -0
- package/skills/datarc-dataseek-testset-generation/SKILL.md +47 -0
- package/skills/datarc-dataseek-testset-generation/scripts/datarc-client.mjs +464 -0
- package/skills/datarc-dataseek-testset-generation/scripts/dataseek-testset-generation.mjs +526 -0
- package/skills/datarc-datasource/SKILL.md +97 -0
- package/skills/datarc-oauth/SKILL.md +47 -0
- package/skills/datarc-oauth/scripts/auth.mjs +130 -0
- package/skills/datarc-oauth/scripts/credentials.mjs +237 -0
- package/skills/datarc-report-add-card/SKILL.md +90 -0
- package/skills/datarc-report-add-card/agents/openai.yaml +4 -0
- package/skills/datarc-report-add-card/scripts/datarc-client.mjs +464 -0
- package/skills/datarc-report-add-card/scripts/report-card.mjs +439 -0
- package/skills/datarc-semantic-alias/SKILL.md +20 -0
- package/skills/datarc-semantic-alias/scripts/alias-plan.mjs +422 -0
- package/skills/datarc-semantic-alias/scripts/alias.mjs +11 -0
- package/skills/datarc-semantic-calibration/SKILL.md +20 -0
- package/skills/datarc-semantic-calibration/scripts/calibration-plan.mjs +683 -0
- package/skills/datarc-semantic-calibration/scripts/calibration.mjs +11 -0
- package/skills/datarc-semantic-core/SKILL.md +12 -0
- package/skills/datarc-semantic-core/scripts/artifact-journal.mjs +830 -0
- package/skills/datarc-semantic-core/scripts/canonical.mjs +48 -0
- package/skills/datarc-semantic-core/scripts/case-model.mjs +608 -0
- package/skills/datarc-semantic-core/scripts/cli.mjs +180 -0
- package/skills/datarc-semantic-core/scripts/datarc-client.mjs +180 -0
- package/skills/datarc-semantic-core/scripts/interpretation-pairs.mjs +57 -0
- package/skills/datarc-semantic-core/scripts/interventions.mjs +693 -0
- package/skills/datarc-semantic-core/scripts/live-resolution.mjs +305 -0
- package/skills/datarc-semantic-core/scripts/model-scope.mjs +49 -0
- package/skills/datarc-semantic-core/scripts/reproduction.mjs +330 -0
- package/skills/datarc-semantic-core/scripts/semantic-cli.mjs +740 -0
- package/skills/datarc-semantic-core/scripts/shared.mjs +312 -0
- package/skills/datarc-semantic-core/scripts/verification.mjs +1014 -0
- package/skills/datarc-semantic-dataset/SKILL.md +20 -0
- package/skills/datarc-semantic-dataset/scripts/dataset-plan.mjs +749 -0
- package/skills/datarc-semantic-dataset/scripts/dataset-preflight.mjs +813 -0
- package/skills/datarc-semantic-dataset/scripts/dataset.mjs +11 -0
- package/skills/datarc-semantic-knowledge/SKILL.md +38 -0
- package/skills/datarc-semantic-knowledge/references/knowledge-drafts.md +61 -0
- package/skills/datarc-semantic-knowledge/references/knowledge-generation.json +16 -0
- package/skills/datarc-semantic-knowledge/scripts/knowledge-draft.mjs +347 -0
- package/skills/datarc-semantic-knowledge/scripts/knowledge-plan.mjs +848 -0
- package/skills/datarc-semantic-knowledge/scripts/knowledge.mjs +31 -0
- package/skills/datarc-semantic-prompt/SKILL.md +20 -0
- package/skills/datarc-semantic-prompt/scripts/prompt-plan.mjs +447 -0
- package/skills/datarc-semantic-prompt/scripts/prompt.mjs +15 -0
- package/skills/datarc-semantic-synonym/SKILL.md +20 -0
- package/skills/datarc-semantic-synonym/scripts/synonym-plan.mjs +688 -0
- package/skills/datarc-semantic-synonym/scripts/synonym.mjs +11 -0
- package/skills/datarc-viz-analysis-report/SKILL.md +108 -0
- package/skills/datarc-viz-analysis-report/assets/LICENSE-echarts.md +8 -0
- package/skills/datarc-viz-analysis-report/assets/echarts.min.js +45 -0
- package/skills/datarc-viz-analysis-report/references/api-contracts.md +163 -0
- package/skills/datarc-viz-analysis-report/references/derivation-log.md +157 -0
- package/skills/datarc-viz-analysis-report/references/evidence-framework.md +76 -0
- package/skills/datarc-viz-analysis-report/references/html-template.md +92 -0
- package/skills/datarc-viz-analysis-report/references/provenance-format.md +56 -0
- package/skills/datarc-viz-analysis-report/references/question-syntax.md +151 -0
- package/skills/datarc-viz-analysis-report/scripts/render_viz_report.py +1708 -0
- package/skills/datarc-viz-analysis-report/scripts/test_render_viz_report.py +964 -0
- package/skills/datarc-workspace-configuration/SKILL.md +59 -0
- package/skills/datarc-workspace-configuration/references/artifacts.md +75 -0
- package/skills/datarc-workspace-configuration/references/verification.md +20 -0
- package/skills/datarc-workspace-configuration/scripts/configuration.mjs +662 -0
- package/skills/datarc-workspace-context/SKILL.md +43 -0
- package/skills/datarc-workspace-context/agents/openai.yaml +4 -0
- package/skills/datarc-workspace-context/scripts/datarc-client.mjs +31 -0
- package/skills/datarc-workspace-context/scripts/query-display.mjs +114 -0
- package/skills/datarc-workspace-context/scripts/workspace-context.mjs +58 -0
- package/skills/datarc-workspace-custom-tables/SKILL.md +89 -0
- package/skills/datarc-workspace-custom-tables/scripts/datarc-client.mjs +165 -0
- package/skills/datarc-workspace-custom-tables/scripts/workspace-custom-tables.mjs +601 -0
- package/skills/datarc-workspace-keywords/SKILL.md +197 -0
- package/skills/datarc-workspace-keywords/agents/openai.yaml +4 -0
- package/skills/datarc-workspace-keywords/references/api-fields.md +79 -0
- package/skills/datarc-workspace-keywords/references/derived-measures.md +177 -0
- package/skills/datarc-workspace-keywords/scripts/datarc-client.mjs +145 -0
- package/skills/datarc-workspace-keywords/scripts/workspace-keywords.mjs +2421 -0
- package/skills/datarc-workspace-membership/SKILL.md +29 -0
- package/skills/datarc-workspace-membership/references/api.md +19 -0
- package/skills/datarc-workspace-modeling/SKILL.md +209 -0
- package/skills/datarc-workspace-modeling/agents/openai.yaml +4 -0
- package/skills/datarc-workspace-modeling/references/join-preview.md +38 -0
- package/skills/datarc-workspace-modeling/references/model-plan.md +300 -0
- package/skills/datarc-workspace-modeling/references/model-tags.md +95 -0
- package/skills/datarc-workspace-modeling/references/modeling-contract.json +29 -0
- package/skills/datarc-workspace-modeling/references/modeling-fixtures.json +2423 -0
- package/skills/datarc-workspace-modeling/scripts/datarc-client.mjs +137 -0
- package/skills/datarc-workspace-modeling/scripts/workspace-model-tags.mjs +238 -0
- package/skills/datarc-workspace-modeling/scripts/workspace-modeling.mjs +1261 -0
- package/skills-index.json +194 -0
|
@@ -0,0 +1,1914 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Run one approved analysis round from DataSeek messages to card objects.
|
|
3
|
+
|
|
4
|
+
The runner is intentionally limited to one round (at most eight questions). It
|
|
5
|
+
does not choose a workspace, read SOPs, approve a Plan, start AutoInsights, or
|
|
6
|
+
write a report. Credentials come from environment variables or the session workspace credential file.
|
|
7
|
+
Raw cards are written to a mode-0600 temporary file because they may contain
|
|
8
|
+
qKeys needed by the next in-memory analysis stage.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import argparse
|
|
14
|
+
import contextlib
|
|
15
|
+
import copy
|
|
16
|
+
import importlib
|
|
17
|
+
import importlib.metadata
|
|
18
|
+
import json
|
|
19
|
+
import os
|
|
20
|
+
import re
|
|
21
|
+
import sys
|
|
22
|
+
import tempfile
|
|
23
|
+
import threading
|
|
24
|
+
import time
|
|
25
|
+
import tomllib
|
|
26
|
+
import uuid
|
|
27
|
+
from collections import Counter
|
|
28
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
29
|
+
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor
|
|
30
|
+
from concurrent.futures import wait as wait_futures
|
|
31
|
+
from datetime import UTC, datetime, timedelta
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
from typing import Any
|
|
34
|
+
from urllib.parse import urlsplit
|
|
35
|
+
|
|
36
|
+
from run_analysis_report import (
|
|
37
|
+
DATASEEK_MESSAGE_TIMEOUT_SECONDS,
|
|
38
|
+
MAX_JSON_INPUT_BYTES,
|
|
39
|
+
MAX_MODEL_UID_CHARS,
|
|
40
|
+
MAX_MODELS_PER_QUESTION,
|
|
41
|
+
MAX_QUESTION_CHARS,
|
|
42
|
+
MAX_QUESTIONS_PER_ROUND,
|
|
43
|
+
QUESTION_ID_PATTERN,
|
|
44
|
+
SHA256_PATTERN,
|
|
45
|
+
DataSeekFailed,
|
|
46
|
+
DataSeekTimeout,
|
|
47
|
+
ReportContractError,
|
|
48
|
+
build_card_payload,
|
|
49
|
+
build_dataseek_message_payload,
|
|
50
|
+
build_locale_headers,
|
|
51
|
+
flatten_units,
|
|
52
|
+
normalize_question_tokens,
|
|
53
|
+
plan_digest,
|
|
54
|
+
project_execution_questions,
|
|
55
|
+
validate_execution_plan,
|
|
56
|
+
validate_normalized_tokens_in_scope,
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
SCHEMA_VERSION = 1
|
|
60
|
+
DEFAULT_WORKERS = 3
|
|
61
|
+
MAX_WORKERS = 3
|
|
62
|
+
MAX_QUESTIONS = MAX_QUESTIONS_PER_ROUND
|
|
63
|
+
REQUEST_TIMEOUT_SECONDS = 30.0
|
|
64
|
+
POLL_INTERVAL_SECONDS = 1.0
|
|
65
|
+
HEARTBEAT_INTERVAL_SECONDS = 10.0
|
|
66
|
+
BREAKER_WINDOW_SECONDS = 15.0
|
|
67
|
+
CIRCUIT_OPEN_CLEANUP_SECONDS = 3.0
|
|
68
|
+
_CARD_FALLBACK_BUSINESS_STATUSES = frozenset({10404, 10406})
|
|
69
|
+
_CONTEXTUAL_SECRET_FRAGMENT_CHARS = 16
|
|
70
|
+
_UNLABELED_SECRET_FRAGMENT_CHARS = 64
|
|
71
|
+
_MAX_SAFE_ERROR_CHARS = 200
|
|
72
|
+
_MAX_REDACTION_INPUT_CHARS = _MAX_SAFE_ERROR_CHARS + (_UNLABELED_SECRET_FRAGMENT_CHARS * 12)
|
|
73
|
+
_REDACTION_MARKER = "[REDACTED]"
|
|
74
|
+
_SECRET_CONTEXT_PATTERN = re.compile(r"(?i)(?:authorization|auth(?:data)?|token|jwt|credential)[\"']?\s*[:=]\s*[\"']?$")
|
|
75
|
+
_SECRET_VALUE_DELIMITERS = frozenset("\"',;:&#)]}>,;:")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class RunnerError(RuntimeError):
|
|
79
|
+
"""A safe, structured error that may be shown without leaking credentials."""
|
|
80
|
+
|
|
81
|
+
def __init__(self, code: str, message: str):
|
|
82
|
+
super().__init__(message)
|
|
83
|
+
self.code = code
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class ApiRequestError(RunnerError):
|
|
87
|
+
"""An HTTP, transport, or API-envelope failure."""
|
|
88
|
+
|
|
89
|
+
def __init__(
|
|
90
|
+
self,
|
|
91
|
+
code: str,
|
|
92
|
+
message: str,
|
|
93
|
+
*,
|
|
94
|
+
stage: str,
|
|
95
|
+
status_code: int | None = None,
|
|
96
|
+
business_status: int | None = None,
|
|
97
|
+
) -> None:
|
|
98
|
+
super().__init__(code, message)
|
|
99
|
+
self.stage = stage
|
|
100
|
+
self.status_code = status_code
|
|
101
|
+
self.business_status = business_status
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def is_auth_failure(self) -> bool:
|
|
105
|
+
return self.status_code in {401, 403}
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class _CircuitOpenError(RuntimeError):
|
|
109
|
+
"""Raised at a business-request safety point after the batch opens."""
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class RunProgress:
|
|
113
|
+
"""Publish bounded progress events and an atomic private status snapshot."""
|
|
114
|
+
|
|
115
|
+
_RUN_TRANSITIONS = {
|
|
116
|
+
"VALIDATING": frozenset({"DIRECT_CARD", "FAILED"}),
|
|
117
|
+
"DIRECT_CARD": frozenset({"DATASEEK_FALLBACK", "FINALIZING", "FAILED"}),
|
|
118
|
+
"DATASEEK_FALLBACK": frozenset({"FINALIZING", "FAILED"}),
|
|
119
|
+
"FINALIZING": frozenset({"COMPLETE", "PARTIAL", "FAILED"}),
|
|
120
|
+
"COMPLETE": frozenset(),
|
|
121
|
+
"PARTIAL": frozenset(),
|
|
122
|
+
"FAILED": frozenset(),
|
|
123
|
+
}
|
|
124
|
+
_QUESTION_TRANSITIONS = {
|
|
125
|
+
"QUEUED": frozenset({"DIRECT_CARD", "ABORTED"}),
|
|
126
|
+
"DIRECT_CARD": frozenset({"VALIDATING_CARD_UNITS", "FALLBACK_QUEUED", "FAILED", "ABORTED"}),
|
|
127
|
+
"FALLBACK_QUEUED": frozenset({"CREATING_THREAD", "FAILED", "ABORTED"}),
|
|
128
|
+
"CREATING_THREAD": frozenset({"CREATING_MESSAGE", "CLEANING_THREAD", "FAILED", "ABORTED"}),
|
|
129
|
+
"CREATING_MESSAGE": frozenset({"WAITING_DATASEEK", "CLEANING_THREAD", "FAILED", "ABORTED"}),
|
|
130
|
+
"WAITING_DATASEEK": frozenset({"CLEANING_THREAD", "FAILED", "ABORTED"}),
|
|
131
|
+
"CLEANING_THREAD": frozenset({"VALIDATING_TOKENS", "FAILED", "ABORTED"}),
|
|
132
|
+
"VALIDATING_TOKENS": frozenset({"RETRYING_CARD", "FAILED", "ABORTED"}),
|
|
133
|
+
"RETRYING_CARD": frozenset({"VALIDATING_CARD_UNITS", "FAILED", "ABORTED"}),
|
|
134
|
+
"VALIDATING_CARD_UNITS": frozenset({"SUCCESS", "FAILED", "ABORTED"}),
|
|
135
|
+
"SUCCESS": frozenset(),
|
|
136
|
+
"FAILED": frozenset(),
|
|
137
|
+
"ABORTED": frozenset(),
|
|
138
|
+
}
|
|
139
|
+
_TERMINAL_QUESTION_STAGES = frozenset({"SUCCESS", "FAILED", "ABORTED"})
|
|
140
|
+
_SAFE_QUESTION_FIELDS = frozenset(
|
|
141
|
+
{
|
|
142
|
+
"errorCode",
|
|
143
|
+
"httpStatus",
|
|
144
|
+
"businessStatus",
|
|
145
|
+
"retryable",
|
|
146
|
+
"attempt",
|
|
147
|
+
"deadlineAt",
|
|
148
|
+
"lastProgressAt",
|
|
149
|
+
"pollCount",
|
|
150
|
+
}
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
def __init__(
|
|
154
|
+
self,
|
|
155
|
+
*,
|
|
156
|
+
stream: Any = sys.stdout,
|
|
157
|
+
temp_root: Path | None = None,
|
|
158
|
+
now: Callable[[], datetime] | None = None,
|
|
159
|
+
heartbeat_interval: float = HEARTBEAT_INTERVAL_SECONDS,
|
|
160
|
+
start_heartbeat: bool = True,
|
|
161
|
+
) -> None:
|
|
162
|
+
self._stream = stream
|
|
163
|
+
self._temp_root = (temp_root or Path(tempfile.gettempdir())).resolve()
|
|
164
|
+
self._now = now or (lambda: datetime.now(UTC))
|
|
165
|
+
self._heartbeat_interval = heartbeat_interval
|
|
166
|
+
self._start_heartbeat = start_heartbeat
|
|
167
|
+
self._lock = threading.Lock()
|
|
168
|
+
self._stop_heartbeat = threading.Event()
|
|
169
|
+
self._heartbeat_thread: threading.Thread | None = None
|
|
170
|
+
self._started = False
|
|
171
|
+
self._terminal = False
|
|
172
|
+
self._closed = False
|
|
173
|
+
self._sequence = 0
|
|
174
|
+
self._run_id = uuid.uuid4().hex
|
|
175
|
+
self._run_dir: Path | None = None
|
|
176
|
+
self._state_file: Path | None = None
|
|
177
|
+
self._state: dict[str, Any] = {}
|
|
178
|
+
|
|
179
|
+
@property
|
|
180
|
+
def run_dir(self) -> Path:
|
|
181
|
+
if self._run_dir is None:
|
|
182
|
+
raise RunnerError("PROGRESS_NOT_STARTED", "progress has not started")
|
|
183
|
+
return self._run_dir
|
|
184
|
+
|
|
185
|
+
@property
|
|
186
|
+
def state_file(self) -> Path:
|
|
187
|
+
if self._state_file is None:
|
|
188
|
+
raise RunnerError("PROGRESS_NOT_STARTED", "progress has not started")
|
|
189
|
+
return self._state_file
|
|
190
|
+
|
|
191
|
+
def start(self, question_ids: Sequence[str], workers: int) -> None:
|
|
192
|
+
"""Create the private run directory, publish the snapshot, and flush start."""
|
|
193
|
+
if (
|
|
194
|
+
not isinstance(question_ids, Sequence)
|
|
195
|
+
or isinstance(question_ids, (str, bytes))
|
|
196
|
+
or not 1 <= len(question_ids) <= MAX_QUESTIONS
|
|
197
|
+
or len(question_ids) != len(set(question_ids))
|
|
198
|
+
or not all(isinstance(question_id, str) and QUESTION_ID_PATTERN.fullmatch(question_id) for question_id in question_ids)
|
|
199
|
+
):
|
|
200
|
+
raise RunnerError("INVALID_PROGRESS", "progress question ids must be safe, non-empty, and unique")
|
|
201
|
+
if isinstance(workers, bool) or not isinstance(workers, int) or not 1 <= workers <= MAX_WORKERS:
|
|
202
|
+
raise RunnerError("INVALID_WORKERS", "workers must be between 1 and 3")
|
|
203
|
+
with self._lock:
|
|
204
|
+
if self._started:
|
|
205
|
+
raise RunnerError("PROGRESS_ALREADY_STARTED", "progress has already started")
|
|
206
|
+
if not self._temp_root.is_dir():
|
|
207
|
+
raise RunnerError("INVALID_PROGRESS_DIR", "progress temporary root does not exist")
|
|
208
|
+
raw_dir = tempfile.mkdtemp(prefix="datarc-analysis-run-", dir=self._temp_root)
|
|
209
|
+
self._run_dir = Path(raw_dir).resolve()
|
|
210
|
+
try:
|
|
211
|
+
self._run_dir.chmod(0o700)
|
|
212
|
+
self._state_file = self._run_dir / "status.json"
|
|
213
|
+
timestamp = self._timestamp()
|
|
214
|
+
self._state = {
|
|
215
|
+
"schemaVersion": SCHEMA_VERSION,
|
|
216
|
+
"runId": self._run_id,
|
|
217
|
+
"sequence": 0,
|
|
218
|
+
"runStage": "VALIDATING",
|
|
219
|
+
"startedAt": timestamp,
|
|
220
|
+
"heartbeatAt": timestamp,
|
|
221
|
+
"workers": workers,
|
|
222
|
+
"counts": {},
|
|
223
|
+
"questions": [{"id": question_id, "stage": "QUEUED"} for question_id in question_ids],
|
|
224
|
+
"breaker": {"state": "CLOSED", "source": None, "reasonCode": None},
|
|
225
|
+
}
|
|
226
|
+
self._started = True
|
|
227
|
+
self._publish_locked(
|
|
228
|
+
{
|
|
229
|
+
"event": "run.started",
|
|
230
|
+
"schemaVersion": SCHEMA_VERSION,
|
|
231
|
+
"runId": self._run_id,
|
|
232
|
+
"stateFile": str(self._state_file),
|
|
233
|
+
"workers": workers,
|
|
234
|
+
"questionCount": len(question_ids),
|
|
235
|
+
}
|
|
236
|
+
)
|
|
237
|
+
except Exception:
|
|
238
|
+
self._rollback_unpublished_start_locked()
|
|
239
|
+
raise
|
|
240
|
+
if self._start_heartbeat:
|
|
241
|
+
try:
|
|
242
|
+
self._heartbeat_thread = threading.Thread(
|
|
243
|
+
target=self._heartbeat_loop,
|
|
244
|
+
name="datarc-progress-heartbeat",
|
|
245
|
+
daemon=True,
|
|
246
|
+
)
|
|
247
|
+
self._heartbeat_thread.start()
|
|
248
|
+
except Exception:
|
|
249
|
+
self.fail_run()
|
|
250
|
+
raise
|
|
251
|
+
|
|
252
|
+
def run_stage(self, stage: str) -> None:
|
|
253
|
+
with self._lock:
|
|
254
|
+
self._require_active_locked()
|
|
255
|
+
current = self._state["runStage"]
|
|
256
|
+
if stage == current:
|
|
257
|
+
return
|
|
258
|
+
if stage not in self._RUN_TRANSITIONS.get(current, frozenset()):
|
|
259
|
+
raise RunnerError("INVALID_PROGRESS_TRANSITION", f"invalid run progress transition {current} -> {stage}")
|
|
260
|
+
self._state["runStage"] = stage
|
|
261
|
+
self._publish_locked({"event": "run.stage", "runId": self._run_id, "stage": stage})
|
|
262
|
+
|
|
263
|
+
def question_stage(self, question_id: str, stage: str, **safe_fields: Any) -> None:
|
|
264
|
+
self._validate_safe_fields(safe_fields)
|
|
265
|
+
with self._lock:
|
|
266
|
+
self._require_active_locked()
|
|
267
|
+
question = self._question_locked(question_id)
|
|
268
|
+
current = question["stage"]
|
|
269
|
+
stage_changed = stage != current
|
|
270
|
+
if current in self._TERMINAL_QUESTION_STAGES:
|
|
271
|
+
if not stage_changed and not safe_fields:
|
|
272
|
+
return
|
|
273
|
+
raise RunnerError("INVALID_PROGRESS_TRANSITION", "terminal question progress cannot change")
|
|
274
|
+
if not stage_changed and not safe_fields:
|
|
275
|
+
return
|
|
276
|
+
if stage_changed and stage not in self._QUESTION_TRANSITIONS.get(current, frozenset()):
|
|
277
|
+
raise RunnerError(
|
|
278
|
+
"INVALID_PROGRESS_TRANSITION",
|
|
279
|
+
f"invalid question progress transition {current} -> {stage}",
|
|
280
|
+
)
|
|
281
|
+
question.update(copy.deepcopy(safe_fields))
|
|
282
|
+
question["stage"] = stage
|
|
283
|
+
question["lastProgressAt"] = safe_fields.get("lastProgressAt", self._timestamp())
|
|
284
|
+
event_name = "question.finished" if stage in self._TERMINAL_QUESTION_STAGES else "question.stage"
|
|
285
|
+
event = {
|
|
286
|
+
"event": event_name,
|
|
287
|
+
"runId": self._run_id,
|
|
288
|
+
"questionId": question_id,
|
|
289
|
+
"stage": stage,
|
|
290
|
+
**copy.deepcopy(safe_fields),
|
|
291
|
+
}
|
|
292
|
+
self._publish_locked(event if stage_changed else None)
|
|
293
|
+
|
|
294
|
+
def breaker(self, snapshot: Mapping[str, Any]) -> None:
|
|
295
|
+
if set(snapshot) != {"state", "source", "reasonCode"}:
|
|
296
|
+
raise RunnerError("INVALID_PROGRESS", "breaker progress must use the exact safe contract")
|
|
297
|
+
safe_snapshot = {
|
|
298
|
+
"state": snapshot.get("state"),
|
|
299
|
+
"source": snapshot.get("source"),
|
|
300
|
+
"reasonCode": snapshot.get("reasonCode"),
|
|
301
|
+
}
|
|
302
|
+
if safe_snapshot["state"] != "OPEN" or safe_snapshot["source"] not in {None, "card", "dataseek"}:
|
|
303
|
+
raise RunnerError("INVALID_PROGRESS", "invalid breaker progress snapshot")
|
|
304
|
+
if not isinstance(safe_snapshot["reasonCode"], str) or not safe_snapshot["reasonCode"]:
|
|
305
|
+
raise RunnerError("INVALID_PROGRESS", "invalid breaker progress reason")
|
|
306
|
+
with self._lock:
|
|
307
|
+
self._require_active_locked()
|
|
308
|
+
if self._state["breaker"]["state"] == "OPEN":
|
|
309
|
+
return
|
|
310
|
+
self._state["breaker"] = safe_snapshot
|
|
311
|
+
self._publish_locked(
|
|
312
|
+
{
|
|
313
|
+
"event": "breaker.opened",
|
|
314
|
+
"runId": self._run_id,
|
|
315
|
+
"source": safe_snapshot["source"],
|
|
316
|
+
"reasonCode": safe_snapshot["reasonCode"],
|
|
317
|
+
}
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
def heartbeat(self) -> None:
|
|
321
|
+
"""Publish one local-only heartbeat snapshot for deterministic tests."""
|
|
322
|
+
with self._lock:
|
|
323
|
+
if not self._started or self._terminal or self._closed:
|
|
324
|
+
return
|
|
325
|
+
self._publish_locked(None)
|
|
326
|
+
|
|
327
|
+
def deadline_at(self, seconds: float) -> str:
|
|
328
|
+
value = self._now()
|
|
329
|
+
if value.tzinfo is None:
|
|
330
|
+
value = value.replace(tzinfo=UTC)
|
|
331
|
+
return _format_timestamp(value + timedelta(seconds=seconds))
|
|
332
|
+
|
|
333
|
+
def finish(self, status: str, result_file: Path | None, counts: Mapping[str, int]) -> None:
|
|
334
|
+
"""Stop heartbeats, atomically publish terminal state, and flush finish."""
|
|
335
|
+
self._stop_heartbeat_thread()
|
|
336
|
+
normalized_counts = _validate_progress_counts(counts)
|
|
337
|
+
if status not in {"COMPLETE", "PARTIAL", "FAILED"}:
|
|
338
|
+
raise RunnerError("INVALID_PROGRESS", "invalid terminal run status")
|
|
339
|
+
with self._lock:
|
|
340
|
+
if not self._started or self._terminal:
|
|
341
|
+
return
|
|
342
|
+
derived_counts = self._terminal_counts_locked()
|
|
343
|
+
if normalized_counts != derived_counts:
|
|
344
|
+
raise RunnerError("INVALID_PROGRESS_COUNTS", "terminal counts do not match question progress")
|
|
345
|
+
self._finish_locked(status, result_file, derived_counts)
|
|
346
|
+
|
|
347
|
+
def fail_run(self) -> None:
|
|
348
|
+
"""Safely abort every non-terminal question and publish a failed run."""
|
|
349
|
+
self._stop_heartbeat_thread()
|
|
350
|
+
with self._lock:
|
|
351
|
+
if not self._started or self._terminal:
|
|
352
|
+
return
|
|
353
|
+
for question in self._state["questions"]:
|
|
354
|
+
if question["stage"] in self._TERMINAL_QUESTION_STAGES:
|
|
355
|
+
continue
|
|
356
|
+
question["stage"] = "ABORTED"
|
|
357
|
+
question["errorCode"] = "RUNNER_FAILED"
|
|
358
|
+
question["retryable"] = False
|
|
359
|
+
question["lastProgressAt"] = self._timestamp()
|
|
360
|
+
self._publish_locked(
|
|
361
|
+
{
|
|
362
|
+
"event": "question.finished",
|
|
363
|
+
"runId": self._run_id,
|
|
364
|
+
"questionId": question["id"],
|
|
365
|
+
"stage": "ABORTED",
|
|
366
|
+
"errorCode": "RUNNER_FAILED",
|
|
367
|
+
"retryable": False,
|
|
368
|
+
}
|
|
369
|
+
)
|
|
370
|
+
self._finish_locked("FAILED", None, self._terminal_counts_locked())
|
|
371
|
+
|
|
372
|
+
def _finish_locked(self, status: str, result_file: Path | None, counts: Mapping[str, int]) -> None:
|
|
373
|
+
current = self._state["runStage"]
|
|
374
|
+
if status not in self._RUN_TRANSITIONS.get(current, frozenset()):
|
|
375
|
+
if status != "FAILED":
|
|
376
|
+
raise RunnerError("INVALID_PROGRESS_TRANSITION", f"invalid run progress transition {current} -> {status}")
|
|
377
|
+
self._terminal = True
|
|
378
|
+
self._state["runStage"] = status
|
|
379
|
+
self._state["counts"] = {
|
|
380
|
+
"total": len(self._state["questions"]),
|
|
381
|
+
"queued": 0,
|
|
382
|
+
"running": 0,
|
|
383
|
+
"succeeded": counts["successCount"],
|
|
384
|
+
"failed": counts["failedCount"],
|
|
385
|
+
"aborted": counts["abortedCount"],
|
|
386
|
+
}
|
|
387
|
+
self._state["finishedAt"] = self._timestamp()
|
|
388
|
+
self._state["resultFile"] = str(result_file) if result_file is not None else None
|
|
389
|
+
self._publish_locked(
|
|
390
|
+
{
|
|
391
|
+
"event": "run.finished",
|
|
392
|
+
"runId": self._run_id,
|
|
393
|
+
"status": status,
|
|
394
|
+
**counts,
|
|
395
|
+
"resultFile": str(result_file) if result_file is not None else None,
|
|
396
|
+
},
|
|
397
|
+
refresh_counts=False,
|
|
398
|
+
)
|
|
399
|
+
|
|
400
|
+
def _terminal_counts_locked(self) -> dict[str, int]:
|
|
401
|
+
stages = Counter(question["stage"] for question in self._state["questions"])
|
|
402
|
+
terminal_total = sum(stages[stage] for stage in self._TERMINAL_QUESTION_STAGES)
|
|
403
|
+
if terminal_total != len(self._state["questions"]):
|
|
404
|
+
raise RunnerError("INCOMPLETE_PROGRESS", "all questions must be terminal before normal finish")
|
|
405
|
+
return {
|
|
406
|
+
"successCount": stages["SUCCESS"],
|
|
407
|
+
"failedCount": stages["FAILED"],
|
|
408
|
+
"abortedCount": stages["ABORTED"],
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
def close(self) -> None:
|
|
412
|
+
self._stop_heartbeat_thread()
|
|
413
|
+
with self._lock:
|
|
414
|
+
self._closed = True
|
|
415
|
+
|
|
416
|
+
def _heartbeat_loop(self) -> None:
|
|
417
|
+
while not self._stop_heartbeat.wait(self._heartbeat_interval):
|
|
418
|
+
self.heartbeat()
|
|
419
|
+
|
|
420
|
+
def _stop_heartbeat_thread(self) -> None:
|
|
421
|
+
self._stop_heartbeat.set()
|
|
422
|
+
thread = self._heartbeat_thread
|
|
423
|
+
if thread is not None and thread is not threading.current_thread() and thread.is_alive():
|
|
424
|
+
thread.join()
|
|
425
|
+
self._heartbeat_thread = None
|
|
426
|
+
|
|
427
|
+
def _rollback_unpublished_start_locked(self) -> None:
|
|
428
|
+
state_file = self._state_file
|
|
429
|
+
run_dir = self._run_dir
|
|
430
|
+
if state_file is not None:
|
|
431
|
+
state_file.unlink(missing_ok=True)
|
|
432
|
+
if run_dir is not None:
|
|
433
|
+
run_dir.rmdir()
|
|
434
|
+
self._started = False
|
|
435
|
+
self._terminal = False
|
|
436
|
+
self._closed = False
|
|
437
|
+
self._sequence = 0
|
|
438
|
+
self._run_id = uuid.uuid4().hex
|
|
439
|
+
self._run_dir = None
|
|
440
|
+
self._state_file = None
|
|
441
|
+
self._state = {}
|
|
442
|
+
self._stop_heartbeat.clear()
|
|
443
|
+
self._heartbeat_thread = None
|
|
444
|
+
|
|
445
|
+
def _require_active_locked(self) -> None:
|
|
446
|
+
if not self._started:
|
|
447
|
+
raise RunnerError("PROGRESS_NOT_STARTED", "progress has not started")
|
|
448
|
+
if self._terminal or self._closed:
|
|
449
|
+
raise RunnerError("PROGRESS_FINISHED", "progress has already finished")
|
|
450
|
+
|
|
451
|
+
def _question_locked(self, question_id: str) -> dict[str, Any]:
|
|
452
|
+
for question in self._state["questions"]:
|
|
453
|
+
if question["id"] == question_id:
|
|
454
|
+
return question
|
|
455
|
+
raise RunnerError("INVALID_PROGRESS", "progress question id is not part of this run")
|
|
456
|
+
|
|
457
|
+
def _publish_locked(self, event: dict[str, Any] | None, *, refresh_counts: bool = True) -> None:
|
|
458
|
+
self._sequence += 1
|
|
459
|
+
self._state["sequence"] = self._sequence
|
|
460
|
+
self._state["heartbeatAt"] = self._timestamp()
|
|
461
|
+
if refresh_counts:
|
|
462
|
+
self._state["counts"] = self._snapshot_counts_locked()
|
|
463
|
+
self._write_snapshot_locked()
|
|
464
|
+
if event is not None:
|
|
465
|
+
_write_stream_json(self._stream, {**event, "sequence": self._sequence})
|
|
466
|
+
|
|
467
|
+
def _snapshot_counts_locked(self) -> dict[str, int]:
|
|
468
|
+
stages = Counter(question["stage"] for question in self._state["questions"])
|
|
469
|
+
terminal_count = sum(stages[stage] for stage in self._TERMINAL_QUESTION_STAGES)
|
|
470
|
+
return {
|
|
471
|
+
"total": len(self._state["questions"]),
|
|
472
|
+
"queued": stages["QUEUED"] + stages["FALLBACK_QUEUED"],
|
|
473
|
+
"running": len(self._state["questions"]) - terminal_count - stages["QUEUED"] - stages["FALLBACK_QUEUED"],
|
|
474
|
+
"succeeded": stages["SUCCESS"],
|
|
475
|
+
"failed": stages["FAILED"],
|
|
476
|
+
"aborted": stages["ABORTED"],
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
def _write_snapshot_locked(self) -> None:
|
|
480
|
+
descriptor, raw_path = tempfile.mkstemp(prefix=".status-", suffix=".json", dir=self.run_dir)
|
|
481
|
+
temporary_path = Path(raw_path)
|
|
482
|
+
descriptor_open = True
|
|
483
|
+
try:
|
|
484
|
+
os.fchmod(descriptor, 0o600)
|
|
485
|
+
with os.fdopen(descriptor, "w", encoding="utf-8") as output:
|
|
486
|
+
descriptor_open = False
|
|
487
|
+
json.dump(self._state, output, ensure_ascii=False, separators=(",", ":"))
|
|
488
|
+
output.write("\n")
|
|
489
|
+
output.flush()
|
|
490
|
+
os.fsync(output.fileno())
|
|
491
|
+
temporary_path.replace(self.state_file)
|
|
492
|
+
except Exception:
|
|
493
|
+
if descriptor_open:
|
|
494
|
+
os.close(descriptor)
|
|
495
|
+
temporary_path.unlink(missing_ok=True)
|
|
496
|
+
raise
|
|
497
|
+
|
|
498
|
+
def _timestamp(self) -> str:
|
|
499
|
+
return _format_timestamp(self._now())
|
|
500
|
+
|
|
501
|
+
@classmethod
|
|
502
|
+
def _validate_safe_fields(cls, fields: Mapping[str, Any]) -> None:
|
|
503
|
+
unknown = set(fields) - cls._SAFE_QUESTION_FIELDS
|
|
504
|
+
if unknown:
|
|
505
|
+
raise ValueError(f"unsupported progress fields: {', '.join(sorted(unknown))}")
|
|
506
|
+
error_code = fields.get("errorCode")
|
|
507
|
+
if error_code is not None and (not isinstance(error_code, str) or len(error_code) > 128 or re.fullmatch(r"[A-Z0-9_-]+", error_code) is None):
|
|
508
|
+
raise ValueError("invalid progress errorCode")
|
|
509
|
+
for name in ("httpStatus", "businessStatus", "attempt", "pollCount"):
|
|
510
|
+
value = fields.get(name)
|
|
511
|
+
if value is not None and (isinstance(value, bool) or not isinstance(value, int) or value < 0):
|
|
512
|
+
raise ValueError(f"invalid progress {name}")
|
|
513
|
+
retryable = fields.get("retryable")
|
|
514
|
+
if retryable is not None and not isinstance(retryable, bool):
|
|
515
|
+
raise ValueError("invalid progress retryable")
|
|
516
|
+
for name in ("deadlineAt", "lastProgressAt"):
|
|
517
|
+
value = fields.get(name)
|
|
518
|
+
if value is not None and (not isinstance(value, str) or len(value) > 40):
|
|
519
|
+
raise ValueError(f"invalid progress {name}")
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
class BatchCircuitBreaker:
|
|
523
|
+
"""Thread-safe, batch-local CLOSED-to-OPEN circuit breaker."""
|
|
524
|
+
|
|
525
|
+
_SOURCES = frozenset({"card", "dataseek"})
|
|
526
|
+
|
|
527
|
+
def __init__(
|
|
528
|
+
self,
|
|
529
|
+
*,
|
|
530
|
+
monotonic: Callable[[], float] = time.monotonic,
|
|
531
|
+
on_open: Callable[[dict[str, Any]], None] | None = None,
|
|
532
|
+
) -> None:
|
|
533
|
+
self._monotonic = monotonic
|
|
534
|
+
self._on_open = on_open
|
|
535
|
+
self._lock = threading.Lock()
|
|
536
|
+
self._state = "CLOSED"
|
|
537
|
+
self._source: str | None = None
|
|
538
|
+
self._reason_code: str | None = None
|
|
539
|
+
self._opened_at: float | None = None
|
|
540
|
+
self._failures: dict[str, list[tuple[float, str]]] = {source: [] for source in self._SOURCES}
|
|
541
|
+
self._in_flight = 0
|
|
542
|
+
|
|
543
|
+
def observe_success(self, source: str) -> None:
|
|
544
|
+
"""Clear only the successful source's CLOSED-state failure window."""
|
|
545
|
+
with self._lock:
|
|
546
|
+
self._validate_source(source)
|
|
547
|
+
self._observe_success_locked(source)
|
|
548
|
+
|
|
549
|
+
def observe_failure(self, source: str, question_id: str, error: ApiRequestError) -> None:
|
|
550
|
+
"""Observe one business request failure and open when its threshold is met."""
|
|
551
|
+
with self._lock:
|
|
552
|
+
self._validate_source(source)
|
|
553
|
+
opened_snapshot = self._observe_failure_locked(source, question_id, error)
|
|
554
|
+
self._notify_open(opened_snapshot)
|
|
555
|
+
|
|
556
|
+
def abort_auth(self, source: str | None = None) -> None:
|
|
557
|
+
"""Open immediately after the first confirmed HTTP 401 or 403."""
|
|
558
|
+
with self._lock:
|
|
559
|
+
if source is not None:
|
|
560
|
+
self._validate_source(source)
|
|
561
|
+
opened_snapshot = self._open_locked(source, "AUTH_ABORTED")
|
|
562
|
+
self._notify_open(opened_snapshot)
|
|
563
|
+
|
|
564
|
+
def is_open(self) -> bool:
|
|
565
|
+
with self._lock:
|
|
566
|
+
return self._state == "OPEN"
|
|
567
|
+
|
|
568
|
+
def snapshot(self) -> dict[str, Any]:
|
|
569
|
+
with self._lock:
|
|
570
|
+
return {
|
|
571
|
+
"state": self._state,
|
|
572
|
+
"source": self._source,
|
|
573
|
+
"reasonCode": self._reason_code,
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
def submit_if_closed(self, submitter: Callable[[], Any]) -> Any | None:
|
|
577
|
+
"""Linearize phase submission with opening the breaker."""
|
|
578
|
+
with self._lock:
|
|
579
|
+
if self._state == "OPEN":
|
|
580
|
+
return None
|
|
581
|
+
return submitter()
|
|
582
|
+
|
|
583
|
+
def reserve_cleanup_request(
|
|
584
|
+
self,
|
|
585
|
+
normal_timeout: float = REQUEST_TIMEOUT_SECONDS,
|
|
586
|
+
open_budget: float = CIRCUIT_OPEN_CLEANUP_SECONDS,
|
|
587
|
+
) -> tuple[bool, float | None]:
|
|
588
|
+
"""Atomically permit one cleanup request with its bounded timeout."""
|
|
589
|
+
with self._lock:
|
|
590
|
+
if self._state == "CLOSED":
|
|
591
|
+
return True, normal_timeout
|
|
592
|
+
if self._opened_at is None:
|
|
593
|
+
return False, None
|
|
594
|
+
remaining = self._opened_at + open_budget - self._monotonic()
|
|
595
|
+
if remaining <= 0:
|
|
596
|
+
return False, None
|
|
597
|
+
return True, min(normal_timeout, remaining)
|
|
598
|
+
|
|
599
|
+
def request(
|
|
600
|
+
self,
|
|
601
|
+
source: str,
|
|
602
|
+
question_id: str,
|
|
603
|
+
request: Callable[[], Any],
|
|
604
|
+
) -> Any:
|
|
605
|
+
"""Reserve one in-flight business request at an atomic safety point."""
|
|
606
|
+
with self._lock:
|
|
607
|
+
self._validate_source(source)
|
|
608
|
+
if self._state == "OPEN":
|
|
609
|
+
raise _CircuitOpenError
|
|
610
|
+
self._in_flight += 1
|
|
611
|
+
try:
|
|
612
|
+
result = request()
|
|
613
|
+
except ApiRequestError as exc:
|
|
614
|
+
with self._lock:
|
|
615
|
+
opened_snapshot = self._observe_failure_locked(source, question_id, exc)
|
|
616
|
+
self._in_flight -= 1
|
|
617
|
+
self._notify_open(opened_snapshot)
|
|
618
|
+
raise
|
|
619
|
+
except Exception:
|
|
620
|
+
with self._lock:
|
|
621
|
+
self._in_flight -= 1
|
|
622
|
+
raise
|
|
623
|
+
else:
|
|
624
|
+
with self._lock:
|
|
625
|
+
self._observe_success_locked(source)
|
|
626
|
+
self._in_flight -= 1
|
|
627
|
+
return result
|
|
628
|
+
|
|
629
|
+
def _observe_success_locked(self, source: str) -> None:
|
|
630
|
+
if self._state == "CLOSED":
|
|
631
|
+
self._failures[source].clear()
|
|
632
|
+
|
|
633
|
+
def _observe_failure_locked(self, source: str, question_id: str, error: ApiRequestError) -> dict[str, Any] | None:
|
|
634
|
+
if self._state == "OPEN":
|
|
635
|
+
return None
|
|
636
|
+
if error.is_auth_failure:
|
|
637
|
+
return self._open_locked(source, "AUTH_ABORTED")
|
|
638
|
+
is_server_failure = error.code == "HTTP_ERROR" and error.status_code is not None and 500 <= error.status_code < 600
|
|
639
|
+
if error.code != "NETWORK_ERROR" and not is_server_failure:
|
|
640
|
+
return None
|
|
641
|
+
now = self._monotonic()
|
|
642
|
+
failures = [
|
|
643
|
+
(observed_at, observed_question_id)
|
|
644
|
+
for observed_at, observed_question_id in self._failures[source]
|
|
645
|
+
if now - observed_at <= BREAKER_WINDOW_SECONDS
|
|
646
|
+
]
|
|
647
|
+
failures.append((now, question_id))
|
|
648
|
+
self._failures[source] = failures
|
|
649
|
+
if len(failures) >= 3 and len({observed_question_id for _, observed_question_id in failures}) >= 2:
|
|
650
|
+
return self._open_locked(source, "UPSTREAM_UNAVAILABLE", opened_at=now)
|
|
651
|
+
return None
|
|
652
|
+
|
|
653
|
+
def _open_locked(
|
|
654
|
+
self,
|
|
655
|
+
source: str | None,
|
|
656
|
+
reason_code: str,
|
|
657
|
+
*,
|
|
658
|
+
opened_at: float | None = None,
|
|
659
|
+
) -> dict[str, Any] | None:
|
|
660
|
+
if self._state == "CLOSED":
|
|
661
|
+
self._state = "OPEN"
|
|
662
|
+
self._source = source
|
|
663
|
+
self._reason_code = reason_code
|
|
664
|
+
self._opened_at = self._monotonic() if opened_at is None else opened_at
|
|
665
|
+
return {
|
|
666
|
+
"state": self._state,
|
|
667
|
+
"source": self._source,
|
|
668
|
+
"reasonCode": self._reason_code,
|
|
669
|
+
}
|
|
670
|
+
return None
|
|
671
|
+
|
|
672
|
+
def _notify_open(self, snapshot: dict[str, Any] | None) -> None:
|
|
673
|
+
if snapshot is not None and self._on_open is not None:
|
|
674
|
+
self._on_open(snapshot)
|
|
675
|
+
|
|
676
|
+
@classmethod
|
|
677
|
+
def _validate_source(cls, source: str) -> None:
|
|
678
|
+
if source not in cls._SOURCES:
|
|
679
|
+
raise ValueError(f"unsupported circuit-breaker source: {source}")
|
|
680
|
+
|
|
681
|
+
|
|
682
|
+
class DataSeekTerminalFailed(DataSeekFailed):
|
|
683
|
+
"""A DataSeek failure returned by a confirmed terminal message state."""
|
|
684
|
+
|
|
685
|
+
|
|
686
|
+
class Httpx2Transport:
|
|
687
|
+
"""Small same-origin client with redirects and proxy inheritance disabled."""
|
|
688
|
+
|
|
689
|
+
def __init__(self, httpx2: Any, endpoint: str, token: str, language: str):
|
|
690
|
+
self._token = token
|
|
691
|
+
self._request_error = httpx2.RequestError
|
|
692
|
+
self._client = httpx2.Client(
|
|
693
|
+
base_url=endpoint,
|
|
694
|
+
headers={"Authorization": token, **build_locale_headers(language)},
|
|
695
|
+
follow_redirects=False,
|
|
696
|
+
trust_env=False,
|
|
697
|
+
)
|
|
698
|
+
|
|
699
|
+
def request(
|
|
700
|
+
self,
|
|
701
|
+
method: str,
|
|
702
|
+
path: str,
|
|
703
|
+
*,
|
|
704
|
+
stage: str,
|
|
705
|
+
json_body: dict[str, Any] | None = None,
|
|
706
|
+
timeout: float = REQUEST_TIMEOUT_SECONDS,
|
|
707
|
+
) -> Any:
|
|
708
|
+
kwargs: dict[str, Any] = {"timeout": timeout}
|
|
709
|
+
if json_body is not None:
|
|
710
|
+
kwargs["json"] = json_body
|
|
711
|
+
try:
|
|
712
|
+
response = self._client.request(method, path, **kwargs)
|
|
713
|
+
except self._request_error as exc:
|
|
714
|
+
raise ApiRequestError(
|
|
715
|
+
"NETWORK_ERROR",
|
|
716
|
+
f"{stage} transport failed ({type(exc).__name__})",
|
|
717
|
+
stage=stage,
|
|
718
|
+
) from None
|
|
719
|
+
|
|
720
|
+
if not response.is_success:
|
|
721
|
+
raise ApiRequestError(
|
|
722
|
+
"HTTP_ERROR",
|
|
723
|
+
_safe_http_message(response, stage, self._token),
|
|
724
|
+
stage=stage,
|
|
725
|
+
status_code=response.status_code,
|
|
726
|
+
business_status=_response_business_status(response),
|
|
727
|
+
)
|
|
728
|
+
try:
|
|
729
|
+
payload = response.json()
|
|
730
|
+
except ValueError:
|
|
731
|
+
raise ApiRequestError("INVALID_JSON", f"{stage} returned invalid JSON", stage=stage) from None
|
|
732
|
+
if not isinstance(payload, dict) or payload.get("status") != "SUCCESS" or "data" not in payload:
|
|
733
|
+
raise ApiRequestError(
|
|
734
|
+
"API_ERROR",
|
|
735
|
+
_safe_api_message(payload, stage, self._token),
|
|
736
|
+
stage=stage,
|
|
737
|
+
)
|
|
738
|
+
return payload["data"]
|
|
739
|
+
|
|
740
|
+
def close(self) -> None:
|
|
741
|
+
with contextlib.suppress(Exception):
|
|
742
|
+
self._client.close()
|
|
743
|
+
|
|
744
|
+
|
|
745
|
+
def validate_batch(batch: Any, approved_plan: Any, approved_digest: str) -> dict[str, Any]:
|
|
746
|
+
"""Validate a single-round batch against the exact approved Plan file."""
|
|
747
|
+
required = {
|
|
748
|
+
"schemaVersion",
|
|
749
|
+
"round",
|
|
750
|
+
"questions",
|
|
751
|
+
}
|
|
752
|
+
if not isinstance(batch, dict) or set(batch) != required:
|
|
753
|
+
raise RunnerError("INVALID_BATCH", "batch must use the exact single-round contract")
|
|
754
|
+
if batch["schemaVersion"] != SCHEMA_VERSION:
|
|
755
|
+
raise RunnerError("INVALID_BATCH", f"schemaVersion must be {SCHEMA_VERSION}")
|
|
756
|
+
|
|
757
|
+
execution = _validate_execution_contract(approved_plan)
|
|
758
|
+
|
|
759
|
+
if not isinstance(approved_digest, str) or not SHA256_PATTERN.fullmatch(approved_digest):
|
|
760
|
+
raise RunnerError("PLAN_NOT_APPROVED", "approved Plan digest must be a lowercase SHA-256 digest")
|
|
761
|
+
actual_digest = plan_digest(approved_plan)
|
|
762
|
+
if approved_digest != actual_digest:
|
|
763
|
+
raise RunnerError("PLAN_NOT_APPROVED", "approved Plan file does not match the user-approved digest")
|
|
764
|
+
|
|
765
|
+
round_number = batch["round"]
|
|
766
|
+
if isinstance(round_number, bool) or not isinstance(round_number, int) or not 1 <= round_number <= execution["maxRounds"]:
|
|
767
|
+
raise RunnerError("INVALID_BATCH", "round must be within the approved Plan round budget")
|
|
768
|
+
validated = copy.deepcopy(batch)
|
|
769
|
+
questions = _validate_questions(
|
|
770
|
+
validated["questions"],
|
|
771
|
+
round_number=round_number,
|
|
772
|
+
max_questions=execution["maxQuestionsPerRound"],
|
|
773
|
+
)
|
|
774
|
+
if round_number == 1 and questions != execution["initialQuestions"]:
|
|
775
|
+
raise RunnerError("PLAN_MISMATCH", "round 1 questions do not exactly match the approved Plan")
|
|
776
|
+
validated["questions"] = questions
|
|
777
|
+
validated["projectId"] = execution["projectId"]
|
|
778
|
+
validated["language"] = execution["language"]
|
|
779
|
+
validated["scope"] = copy.deepcopy(execution["scope"])
|
|
780
|
+
validated["planDigest"] = actual_digest
|
|
781
|
+
return validated
|
|
782
|
+
|
|
783
|
+
|
|
784
|
+
def _validate_execution_contract(plan: Any) -> dict[str, Any]:
|
|
785
|
+
try:
|
|
786
|
+
execution = validate_execution_plan(plan)
|
|
787
|
+
except ReportContractError as exc:
|
|
788
|
+
raise RunnerError("INVALID_PLAN", str(exc)) from None
|
|
789
|
+
validated = copy.deepcopy(execution)
|
|
790
|
+
validated["initialQuestions"] = project_execution_questions(execution)
|
|
791
|
+
return validated
|
|
792
|
+
|
|
793
|
+
|
|
794
|
+
def _validate_questions(
|
|
795
|
+
questions: Any,
|
|
796
|
+
*,
|
|
797
|
+
round_number: int,
|
|
798
|
+
max_questions: int,
|
|
799
|
+
) -> list[dict[str, Any]]:
|
|
800
|
+
if not isinstance(questions, list) or not 1 <= len(questions) <= max_questions:
|
|
801
|
+
raise RunnerError("INVALID_BATCH", f"questions must contain one to {max_questions} items")
|
|
802
|
+
validated = copy.deepcopy(questions)
|
|
803
|
+
seen_ids: set[str] = set()
|
|
804
|
+
seen_question_signatures: set[tuple[str, tuple[str, ...]]] = set()
|
|
805
|
+
for item in validated:
|
|
806
|
+
if not isinstance(item, dict) or set(item) != {"id", "question", "requestTuids"}:
|
|
807
|
+
raise RunnerError("INVALID_BATCH", "every question must contain only id, question, and requestTuids")
|
|
808
|
+
question_id = item["id"]
|
|
809
|
+
question = item["question"]
|
|
810
|
+
request_tuids = item["requestTuids"]
|
|
811
|
+
if not isinstance(question_id, str) or not QUESTION_ID_PATTERN.fullmatch(question_id) or question_id in seen_ids:
|
|
812
|
+
raise RunnerError("INVALID_BATCH", "question ids must be safe, non-empty, and unique")
|
|
813
|
+
if not question_id.startswith(f"r{round_number}-"):
|
|
814
|
+
raise RunnerError("INVALID_BATCH", "question ids must start with the current round prefix")
|
|
815
|
+
if not isinstance(question, str):
|
|
816
|
+
raise RunnerError("INVALID_BATCH", "question text must be non-empty and at most 4000 characters")
|
|
817
|
+
normalized_question = question.strip()
|
|
818
|
+
if not normalized_question or len(normalized_question) > MAX_QUESTION_CHARS:
|
|
819
|
+
raise RunnerError("INVALID_BATCH", "question text must be non-empty and at most 4000 characters")
|
|
820
|
+
if request_tuids != []:
|
|
821
|
+
raise RunnerError("INVALID_BATCH", "requestTuids must be an empty list for automatic model matching")
|
|
822
|
+
question_signature = (normalized_question, tuple(request_tuids))
|
|
823
|
+
if question_signature in seen_question_signatures:
|
|
824
|
+
raise RunnerError("INVALID_BATCH", "question and model selections must not repeat within one round")
|
|
825
|
+
seen_ids.add(question_id)
|
|
826
|
+
seen_question_signatures.add(question_signature)
|
|
827
|
+
item["question"] = normalized_question
|
|
828
|
+
return validated
|
|
829
|
+
|
|
830
|
+
|
|
831
|
+
def run_batch(
|
|
832
|
+
batch: dict[str, Any],
|
|
833
|
+
transport_factory: Callable[[], Any],
|
|
834
|
+
*,
|
|
835
|
+
approved_plan: dict[str, Any],
|
|
836
|
+
approved_plan_digest: str,
|
|
837
|
+
workers: int = DEFAULT_WORKERS,
|
|
838
|
+
monotonic: Callable[[], float] = time.monotonic,
|
|
839
|
+
wait: Callable[[float], None] = time.sleep,
|
|
840
|
+
progress: RunProgress | None = None,
|
|
841
|
+
) -> dict[str, Any]:
|
|
842
|
+
"""Execute one approved round with bounded concurrency and stable ordering."""
|
|
843
|
+
validated = validate_batch(batch, approved_plan, approved_plan_digest)
|
|
844
|
+
if isinstance(workers, bool) or not isinstance(workers, int) or not 1 <= workers <= MAX_WORKERS:
|
|
845
|
+
raise RunnerError("INVALID_WORKERS", "workers must be between 1 and 3")
|
|
846
|
+
|
|
847
|
+
questions = validated["questions"]
|
|
848
|
+
breaker = BatchCircuitBreaker(monotonic=monotonic, on_open=progress.breaker if progress is not None else None)
|
|
849
|
+
if progress is not None:
|
|
850
|
+
progress.run_stage("DIRECT_CARD")
|
|
851
|
+
results = _run_phase(
|
|
852
|
+
questions,
|
|
853
|
+
lambda question: _run_direct_question(
|
|
854
|
+
transport_factory,
|
|
855
|
+
validated["projectId"],
|
|
856
|
+
question,
|
|
857
|
+
breaker,
|
|
858
|
+
scope=validated["scope"],
|
|
859
|
+
progress=progress,
|
|
860
|
+
),
|
|
861
|
+
workers,
|
|
862
|
+
phase_name="direct-card",
|
|
863
|
+
breaker=breaker,
|
|
864
|
+
progress=progress,
|
|
865
|
+
)
|
|
866
|
+
fallback_indexes = [index for index, result in enumerate(results) if result["status"] == "FALLBACK"]
|
|
867
|
+
if fallback_indexes:
|
|
868
|
+
if progress is not None:
|
|
869
|
+
progress.run_stage("DATASEEK_FALLBACK")
|
|
870
|
+
fallback_results = _run_phase(
|
|
871
|
+
[questions[index] for index in fallback_indexes],
|
|
872
|
+
lambda question: _run_dataseek_fallback(
|
|
873
|
+
transport_factory,
|
|
874
|
+
validated["projectId"],
|
|
875
|
+
question,
|
|
876
|
+
breaker,
|
|
877
|
+
monotonic,
|
|
878
|
+
wait,
|
|
879
|
+
scope=validated["scope"],
|
|
880
|
+
progress=progress,
|
|
881
|
+
),
|
|
882
|
+
workers,
|
|
883
|
+
phase_name="dataseek-fallback",
|
|
884
|
+
breaker=breaker,
|
|
885
|
+
progress=progress,
|
|
886
|
+
)
|
|
887
|
+
for index, fallback_result in zip(fallback_indexes, fallback_results, strict=True):
|
|
888
|
+
results[index] = fallback_result
|
|
889
|
+
|
|
890
|
+
if progress is not None:
|
|
891
|
+
progress.run_stage("FINALIZING")
|
|
892
|
+
counts = Counter(result["status"] for result in results)
|
|
893
|
+
return {
|
|
894
|
+
"schemaVersion": SCHEMA_VERSION,
|
|
895
|
+
"planDigest": validated["planDigest"],
|
|
896
|
+
"round": validated["round"],
|
|
897
|
+
"projectId": validated["projectId"],
|
|
898
|
+
"language": validated["language"],
|
|
899
|
+
"successCount": counts["SUCCESS"],
|
|
900
|
+
"failedCount": counts["FAILED"],
|
|
901
|
+
"abortedCount": counts["ABORTED"],
|
|
902
|
+
"runStatus": _run_status(counts),
|
|
903
|
+
"breaker": breaker.snapshot(),
|
|
904
|
+
"results": results,
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
|
|
908
|
+
def _run_phase(
|
|
909
|
+
questions: Sequence[dict[str, Any]],
|
|
910
|
+
runner: Callable[[dict[str, Any]], dict[str, Any]],
|
|
911
|
+
workers: int,
|
|
912
|
+
*,
|
|
913
|
+
phase_name: str,
|
|
914
|
+
breaker: BatchCircuitBreaker,
|
|
915
|
+
progress: RunProgress | None = None,
|
|
916
|
+
) -> list[dict[str, Any]]:
|
|
917
|
+
"""Run one finitely submitted phase while preserving input order."""
|
|
918
|
+
results: list[dict[str, Any] | None] = [None] * len(questions)
|
|
919
|
+
with ThreadPoolExecutor(
|
|
920
|
+
max_workers=min(workers, len(questions)),
|
|
921
|
+
thread_name_prefix=f"datarc-{phase_name}",
|
|
922
|
+
) as executor:
|
|
923
|
+
futures: dict[Any, int] = {}
|
|
924
|
+
next_index = 0
|
|
925
|
+
|
|
926
|
+
def submit_one(index: int) -> bool:
|
|
927
|
+
future = breaker.submit_if_closed(lambda: executor.submit(runner, questions[index]))
|
|
928
|
+
if future is None:
|
|
929
|
+
return False
|
|
930
|
+
futures[future] = index
|
|
931
|
+
return True
|
|
932
|
+
|
|
933
|
+
while next_index < len(questions) and len(futures) < workers:
|
|
934
|
+
if not submit_one(next_index):
|
|
935
|
+
break
|
|
936
|
+
next_index += 1
|
|
937
|
+
|
|
938
|
+
while futures:
|
|
939
|
+
completed, _ = wait_futures(futures, return_when=FIRST_COMPLETED)
|
|
940
|
+
for future in completed:
|
|
941
|
+
index = futures.pop(future)
|
|
942
|
+
try:
|
|
943
|
+
results[index] = future.result()
|
|
944
|
+
except Exception as exc:
|
|
945
|
+
results[index] = _failure_result(
|
|
946
|
+
questions[index]["id"],
|
|
947
|
+
"runner",
|
|
948
|
+
"INTERNAL_ERROR",
|
|
949
|
+
f"runner failed ({type(exc).__name__})",
|
|
950
|
+
route=phase_name,
|
|
951
|
+
)
|
|
952
|
+
if progress is not None:
|
|
953
|
+
_sync_progress_result(progress, results[index])
|
|
954
|
+
while next_index < len(questions) and len(futures) < workers:
|
|
955
|
+
if not submit_one(next_index):
|
|
956
|
+
break
|
|
957
|
+
next_index += 1
|
|
958
|
+
|
|
959
|
+
for index, result in enumerate(results):
|
|
960
|
+
if result is None:
|
|
961
|
+
results[index] = _aborted_result(questions[index]["id"], breaker, route="not-started")
|
|
962
|
+
if progress is not None:
|
|
963
|
+
_sync_progress_result(progress, results[index])
|
|
964
|
+
return [result for result in results if result is not None]
|
|
965
|
+
|
|
966
|
+
|
|
967
|
+
def _sync_progress_result(progress: RunProgress, result: Mapping[str, Any]) -> None:
|
|
968
|
+
"""Copy only fixed, safe result metadata into progress state."""
|
|
969
|
+
question_id = result.get("id")
|
|
970
|
+
status = result.get("status")
|
|
971
|
+
if not isinstance(question_id, str) or not isinstance(status, str):
|
|
972
|
+
raise RunnerError("INVALID_PROGRESS", "runner result lacks safe progress identity")
|
|
973
|
+
if status == "FALLBACK":
|
|
974
|
+
reason = result.get("reason")
|
|
975
|
+
fields = {"errorCode": reason} if isinstance(reason, str) else {}
|
|
976
|
+
progress.question_stage(question_id, "FALLBACK_QUEUED", **fields)
|
|
977
|
+
return
|
|
978
|
+
if status == "SUCCESS":
|
|
979
|
+
progress.question_stage(question_id, "SUCCESS")
|
|
980
|
+
return
|
|
981
|
+
if status not in {"FAILED", "ABORTED"}:
|
|
982
|
+
raise RunnerError("INVALID_PROGRESS", "runner result has an unsupported progress status")
|
|
983
|
+
error = result.get("error")
|
|
984
|
+
error_code = error.get("code") if isinstance(error, Mapping) else None
|
|
985
|
+
safe_fields: dict[str, Any] = {}
|
|
986
|
+
if isinstance(error_code, str):
|
|
987
|
+
safe_fields["errorCode"] = error_code
|
|
988
|
+
safe_fields["retryable"] = _is_retryable_error(error_code, result.get("httpStatus"))
|
|
989
|
+
http_status = result.get("httpStatus")
|
|
990
|
+
business_status = result.get("businessStatus")
|
|
991
|
+
if isinstance(http_status, int) and not isinstance(http_status, bool):
|
|
992
|
+
safe_fields["httpStatus"] = http_status
|
|
993
|
+
if isinstance(business_status, int) and not isinstance(business_status, bool):
|
|
994
|
+
safe_fields["businessStatus"] = business_status
|
|
995
|
+
progress.question_stage(question_id, status, **safe_fields)
|
|
996
|
+
|
|
997
|
+
|
|
998
|
+
def _is_retryable_error(error_code: str, http_status: Any) -> bool:
|
|
999
|
+
return error_code in {"NETWORK_ERROR", "DATASEEK_TIMEOUT", "UPSTREAM_UNAVAILABLE"} or (
|
|
1000
|
+
isinstance(http_status, int) and not isinstance(http_status, bool) and (http_status in {408, 429} or 500 <= http_status < 600)
|
|
1001
|
+
)
|
|
1002
|
+
|
|
1003
|
+
|
|
1004
|
+
def write_secure_result(result: dict[str, Any], output_dir: Path | None = None) -> Path:
|
|
1005
|
+
"""Write raw cards to a unique mode-0600 file under the runtime temp root."""
|
|
1006
|
+
temp_root = Path(tempfile.gettempdir()).resolve()
|
|
1007
|
+
target_dir = (output_dir or temp_root).resolve()
|
|
1008
|
+
if target_dir != temp_root and temp_root not in target_dir.parents:
|
|
1009
|
+
raise RunnerError("UNSAFE_OUTPUT_DIR", "raw result files must stay under the runtime temporary directory")
|
|
1010
|
+
if not target_dir.is_dir():
|
|
1011
|
+
raise RunnerError("INVALID_OUTPUT_DIR", "output directory does not exist")
|
|
1012
|
+
descriptor, raw_path = tempfile.mkstemp(prefix="datarc-dataseek-cards-", suffix=".json", dir=target_dir)
|
|
1013
|
+
path = Path(raw_path)
|
|
1014
|
+
descriptor_open = True
|
|
1015
|
+
try:
|
|
1016
|
+
os.fchmod(descriptor, 0o600)
|
|
1017
|
+
with os.fdopen(descriptor, "w", encoding="utf-8") as output:
|
|
1018
|
+
descriptor_open = False
|
|
1019
|
+
json.dump(result, output, ensure_ascii=False, separators=(",", ":"))
|
|
1020
|
+
output.write("\n")
|
|
1021
|
+
except Exception:
|
|
1022
|
+
try:
|
|
1023
|
+
if descriptor_open:
|
|
1024
|
+
os.close(descriptor)
|
|
1025
|
+
path.unlink(missing_ok=True)
|
|
1026
|
+
finally:
|
|
1027
|
+
raise
|
|
1028
|
+
return path
|
|
1029
|
+
|
|
1030
|
+
|
|
1031
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
1032
|
+
parser = argparse.ArgumentParser(description="Run one approved DataSeek-to-card analysis round")
|
|
1033
|
+
parser.add_argument("approved_plan", type=Path, help="exact credential-free Plan JSON approved by the user")
|
|
1034
|
+
parser.add_argument("batch", type=Path, help="credential-free single-round JSON batch")
|
|
1035
|
+
parser.add_argument(
|
|
1036
|
+
"--approved-plan-digest",
|
|
1037
|
+
required=True,
|
|
1038
|
+
help="SHA-256 printed when the user approved this exact Plan",
|
|
1039
|
+
)
|
|
1040
|
+
parser.add_argument("--workers", type=int, choices=range(1, MAX_WORKERS + 1), default=DEFAULT_WORKERS)
|
|
1041
|
+
output_group = parser.add_mutually_exclusive_group()
|
|
1042
|
+
output_group.add_argument("--output-dir", type=Path, help="directory below the runtime temp root for the mode-0600 result")
|
|
1043
|
+
output_group.add_argument("--progress", choices=("ndjson",), help="emit bounded NDJSON progress and a private status file")
|
|
1044
|
+
args = parser.parse_args(argv)
|
|
1045
|
+
|
|
1046
|
+
progress: RunProgress | None = None
|
|
1047
|
+
result: dict[str, Any] | None = None
|
|
1048
|
+
try:
|
|
1049
|
+
approved_plan = _read_batch(args.approved_plan)
|
|
1050
|
+
batch = _read_batch(args.batch)
|
|
1051
|
+
validated_batch = validate_batch(batch, approved_plan, args.approved_plan_digest)
|
|
1052
|
+
if args.progress == "ndjson":
|
|
1053
|
+
progress = RunProgress(stream=sys.stdout)
|
|
1054
|
+
progress.start([question["id"] for question in validated_batch["questions"]], args.workers)
|
|
1055
|
+
endpoint, token = _read_runtime_credentials(os.environ)
|
|
1056
|
+
httpx2 = _load_httpx2()
|
|
1057
|
+
result = run_batch(
|
|
1058
|
+
batch,
|
|
1059
|
+
lambda: Httpx2Transport(httpx2, endpoint, token, validated_batch["language"]),
|
|
1060
|
+
approved_plan=approved_plan,
|
|
1061
|
+
approved_plan_digest=args.approved_plan_digest,
|
|
1062
|
+
workers=args.workers,
|
|
1063
|
+
progress=progress,
|
|
1064
|
+
)
|
|
1065
|
+
result_path = write_secure_result(result, progress.run_dir if progress is not None else args.output_dir)
|
|
1066
|
+
if progress is not None:
|
|
1067
|
+
progress.finish(
|
|
1068
|
+
result["runStatus"],
|
|
1069
|
+
result_path,
|
|
1070
|
+
{key: result[key] for key in ("successCount", "failedCount", "abortedCount")},
|
|
1071
|
+
)
|
|
1072
|
+
except RunnerError as exc:
|
|
1073
|
+
_finish_failed_progress(progress)
|
|
1074
|
+
if progress is not None:
|
|
1075
|
+
progress.close()
|
|
1076
|
+
_write_stream_json(sys.stderr, {"status": "ERROR", "code": exc.code, "message": str(exc)})
|
|
1077
|
+
return 1
|
|
1078
|
+
except Exception as exc:
|
|
1079
|
+
_finish_failed_progress(progress)
|
|
1080
|
+
if progress is not None:
|
|
1081
|
+
progress.close()
|
|
1082
|
+
_write_stream_json(
|
|
1083
|
+
sys.stderr,
|
|
1084
|
+
{"status": "ERROR", "code": "INTERNAL_ERROR", "message": f"runner failed ({type(exc).__name__})"},
|
|
1085
|
+
)
|
|
1086
|
+
return 1
|
|
1087
|
+
|
|
1088
|
+
if progress is not None:
|
|
1089
|
+
progress.close()
|
|
1090
|
+
else:
|
|
1091
|
+
_write_stream_json(
|
|
1092
|
+
sys.stdout,
|
|
1093
|
+
{
|
|
1094
|
+
"status": "COMPLETE",
|
|
1095
|
+
"resultFile": str(result_path),
|
|
1096
|
+
"successCount": result["successCount"],
|
|
1097
|
+
"failedCount": result["failedCount"] + result["abortedCount"],
|
|
1098
|
+
"questions": [
|
|
1099
|
+
{
|
|
1100
|
+
"id": item["id"],
|
|
1101
|
+
"status": "FAILED" if item["status"] == "ABORTED" else item["status"],
|
|
1102
|
+
**({"resolution": item["resolution"]} if item["status"] == "SUCCESS" else {"stage": item["stage"]}),
|
|
1103
|
+
}
|
|
1104
|
+
for item in result["results"]
|
|
1105
|
+
],
|
|
1106
|
+
},
|
|
1107
|
+
)
|
|
1108
|
+
return 0
|
|
1109
|
+
|
|
1110
|
+
|
|
1111
|
+
def _run_direct_question(
|
|
1112
|
+
transport_factory: Callable[[], Any],
|
|
1113
|
+
project_id: int,
|
|
1114
|
+
question: dict[str, Any],
|
|
1115
|
+
breaker: BatchCircuitBreaker,
|
|
1116
|
+
*,
|
|
1117
|
+
scope: dict[str, Any],
|
|
1118
|
+
progress: RunProgress | None = None,
|
|
1119
|
+
) -> dict[str, Any]:
|
|
1120
|
+
question_id = question["id"]
|
|
1121
|
+
if breaker.is_open():
|
|
1122
|
+
return _aborted_result(question_id, breaker, route="not-started")
|
|
1123
|
+
|
|
1124
|
+
if progress is not None:
|
|
1125
|
+
progress.question_stage(question_id, "DIRECT_CARD", attempt=1)
|
|
1126
|
+
transport = transport_factory()
|
|
1127
|
+
try:
|
|
1128
|
+
card = _business_request(
|
|
1129
|
+
transport,
|
|
1130
|
+
breaker,
|
|
1131
|
+
"card",
|
|
1132
|
+
question_id,
|
|
1133
|
+
"POST",
|
|
1134
|
+
_project_path(project_id, "card/"),
|
|
1135
|
+
stage="direct-card",
|
|
1136
|
+
json_body=build_card_payload(question["question"]),
|
|
1137
|
+
)
|
|
1138
|
+
if card is None:
|
|
1139
|
+
return _fallback_candidate(question_id, "EMPTY_CARD")
|
|
1140
|
+
if progress is not None:
|
|
1141
|
+
progress.question_stage(question_id, "VALIDATING_CARD_UNITS")
|
|
1142
|
+
return _finalize_card(question_id, card, scope, "direct-card")
|
|
1143
|
+
except _CircuitOpenError:
|
|
1144
|
+
return _aborted_result(question_id, breaker, route="not-started")
|
|
1145
|
+
except ApiRequestError as exc:
|
|
1146
|
+
if exc.code == "HTTP_ERROR" and exc.status_code == 400 and exc.business_status in _CARD_FALLBACK_BUSINESS_STATUSES:
|
|
1147
|
+
return _fallback_candidate(question_id, f"BUSINESS_STATUS_{exc.business_status}")
|
|
1148
|
+
return _failure_result(
|
|
1149
|
+
question_id,
|
|
1150
|
+
"direct-card",
|
|
1151
|
+
exc.code,
|
|
1152
|
+
str(exc),
|
|
1153
|
+
route="direct-card",
|
|
1154
|
+
http_status=exc.status_code,
|
|
1155
|
+
business_status=exc.business_status,
|
|
1156
|
+
)
|
|
1157
|
+
except RunnerError as exc:
|
|
1158
|
+
return _failure_result(question_id, "direct-card", exc.code, str(exc), route="direct-card")
|
|
1159
|
+
finally:
|
|
1160
|
+
with contextlib.suppress(Exception):
|
|
1161
|
+
transport.close()
|
|
1162
|
+
|
|
1163
|
+
|
|
1164
|
+
def _fallback_candidate(question_id: str, reason: str) -> dict[str, Any]:
|
|
1165
|
+
return {"id": question_id, "status": "FALLBACK", "reason": reason}
|
|
1166
|
+
|
|
1167
|
+
|
|
1168
|
+
def _business_request(
|
|
1169
|
+
transport: Any,
|
|
1170
|
+
breaker: BatchCircuitBreaker,
|
|
1171
|
+
source: str,
|
|
1172
|
+
question_id: str,
|
|
1173
|
+
method: str,
|
|
1174
|
+
path: str,
|
|
1175
|
+
*,
|
|
1176
|
+
stage: str,
|
|
1177
|
+
json_body: dict[str, Any] | None = None,
|
|
1178
|
+
timeout: float | None = None,
|
|
1179
|
+
) -> Any:
|
|
1180
|
+
kwargs: dict[str, Any] = {"stage": stage}
|
|
1181
|
+
if json_body is not None:
|
|
1182
|
+
kwargs["json_body"] = json_body
|
|
1183
|
+
if timeout is not None:
|
|
1184
|
+
kwargs["timeout"] = timeout
|
|
1185
|
+
return breaker.request(
|
|
1186
|
+
source,
|
|
1187
|
+
question_id,
|
|
1188
|
+
lambda: transport.request(method, path, **kwargs),
|
|
1189
|
+
)
|
|
1190
|
+
|
|
1191
|
+
|
|
1192
|
+
def _run_dataseek_fallback(
|
|
1193
|
+
transport_factory: Callable[[], Any],
|
|
1194
|
+
project_id: int,
|
|
1195
|
+
question: dict[str, Any],
|
|
1196
|
+
breaker: BatchCircuitBreaker,
|
|
1197
|
+
monotonic: Callable[[], float],
|
|
1198
|
+
wait: Callable[[float], None],
|
|
1199
|
+
*,
|
|
1200
|
+
scope: dict[str, Any],
|
|
1201
|
+
progress: RunProgress | None = None,
|
|
1202
|
+
) -> dict[str, Any]:
|
|
1203
|
+
question_id = question["id"]
|
|
1204
|
+
if breaker.is_open():
|
|
1205
|
+
return _aborted_result(question_id, breaker, route="not-started")
|
|
1206
|
+
|
|
1207
|
+
transport = transport_factory()
|
|
1208
|
+
thread_uid: str | None = None
|
|
1209
|
+
message_id: int | None = None
|
|
1210
|
+
cleanup_warnings: list[str] = []
|
|
1211
|
+
terminal_confirmed = False
|
|
1212
|
+
tokens: list[dict[str, Any]] | None = None
|
|
1213
|
+
pending_error: Exception | None = None
|
|
1214
|
+
circuit_aborted = False
|
|
1215
|
+
try:
|
|
1216
|
+
if progress is not None:
|
|
1217
|
+
progress.question_stage(question_id, "CREATING_THREAD", attempt=1)
|
|
1218
|
+
thread = _business_request(
|
|
1219
|
+
transport,
|
|
1220
|
+
breaker,
|
|
1221
|
+
"dataseek",
|
|
1222
|
+
question_id,
|
|
1223
|
+
"POST",
|
|
1224
|
+
_project_path(project_id, "threads/"),
|
|
1225
|
+
stage="create-thread",
|
|
1226
|
+
json_body={},
|
|
1227
|
+
)
|
|
1228
|
+
try:
|
|
1229
|
+
thread_uid = _required_string(thread, "uid", "create-thread")
|
|
1230
|
+
except ApiRequestError:
|
|
1231
|
+
cleanup_warnings.append("delete-thread-skipped-missing-uid")
|
|
1232
|
+
raise
|
|
1233
|
+
try:
|
|
1234
|
+
if progress is not None:
|
|
1235
|
+
progress.question_stage(question_id, "CREATING_MESSAGE", attempt=1)
|
|
1236
|
+
message = _business_request(
|
|
1237
|
+
transport,
|
|
1238
|
+
breaker,
|
|
1239
|
+
"dataseek",
|
|
1240
|
+
question_id,
|
|
1241
|
+
"POST",
|
|
1242
|
+
_project_path(project_id, f"threads/{thread_uid}/messages/"),
|
|
1243
|
+
stage="create-message",
|
|
1244
|
+
json_body=build_dataseek_message_payload(project_id, question["question"]),
|
|
1245
|
+
)
|
|
1246
|
+
try:
|
|
1247
|
+
message_id = _required_positive_int(message, "id", "create-message")
|
|
1248
|
+
except ApiRequestError:
|
|
1249
|
+
cleanup_warnings.append("abort-message-skipped-missing-id")
|
|
1250
|
+
raise
|
|
1251
|
+
try:
|
|
1252
|
+
if progress is not None:
|
|
1253
|
+
progress.question_stage(
|
|
1254
|
+
question_id,
|
|
1255
|
+
"WAITING_DATASEEK",
|
|
1256
|
+
attempt=1,
|
|
1257
|
+
deadlineAt=progress.deadline_at(DATASEEK_MESSAGE_TIMEOUT_SECONDS),
|
|
1258
|
+
pollCount=0,
|
|
1259
|
+
)
|
|
1260
|
+
tokens = _poll_message(
|
|
1261
|
+
transport,
|
|
1262
|
+
project_id,
|
|
1263
|
+
thread_uid,
|
|
1264
|
+
message_id,
|
|
1265
|
+
monotonic=monotonic,
|
|
1266
|
+
wait=wait,
|
|
1267
|
+
breaker=breaker,
|
|
1268
|
+
question_id=question_id,
|
|
1269
|
+
progress=progress,
|
|
1270
|
+
)
|
|
1271
|
+
terminal_confirmed = True
|
|
1272
|
+
except DataSeekTerminalFailed as exc:
|
|
1273
|
+
terminal_confirmed = True
|
|
1274
|
+
pending_error = exc
|
|
1275
|
+
except DataSeekTimeout as exc:
|
|
1276
|
+
pending_error = exc
|
|
1277
|
+
except (DataSeekFailed, ApiRequestError) as exc:
|
|
1278
|
+
pending_error = exc
|
|
1279
|
+
except _CircuitOpenError:
|
|
1280
|
+
circuit_aborted = True
|
|
1281
|
+
except ApiRequestError as exc:
|
|
1282
|
+
pending_error = exc
|
|
1283
|
+
except _CircuitOpenError:
|
|
1284
|
+
circuit_aborted = True
|
|
1285
|
+
finally:
|
|
1286
|
+
try:
|
|
1287
|
+
if progress is not None:
|
|
1288
|
+
progress.question_stage(question_id, "CLEANING_THREAD")
|
|
1289
|
+
finally:
|
|
1290
|
+
_cleanup_dataseek(
|
|
1291
|
+
transport,
|
|
1292
|
+
project_id,
|
|
1293
|
+
thread_uid,
|
|
1294
|
+
message_id,
|
|
1295
|
+
terminal_confirmed=terminal_confirmed,
|
|
1296
|
+
breaker=breaker,
|
|
1297
|
+
warnings=cleanup_warnings,
|
|
1298
|
+
)
|
|
1299
|
+
|
|
1300
|
+
if circuit_aborted:
|
|
1301
|
+
return _aborted_result(
|
|
1302
|
+
question_id,
|
|
1303
|
+
breaker,
|
|
1304
|
+
route="dataseek-fallback",
|
|
1305
|
+
cleanup_warnings=cleanup_warnings,
|
|
1306
|
+
)
|
|
1307
|
+
|
|
1308
|
+
if pending_error is not None:
|
|
1309
|
+
return _exception_result(question_id, pending_error, cleanup_warnings, route="dataseek-fallback")
|
|
1310
|
+
|
|
1311
|
+
if progress is not None:
|
|
1312
|
+
progress.question_stage(question_id, "VALIDATING_TOKENS")
|
|
1313
|
+
tokens = _validated_tokens(tokens)
|
|
1314
|
+
|
|
1315
|
+
try:
|
|
1316
|
+
validate_normalized_tokens_in_scope(tokens, scope, f"question {question_id} tokens")
|
|
1317
|
+
except ReportContractError as exc:
|
|
1318
|
+
raise RunnerError("FIELD_SCOPE_MISMATCH", str(exc)) from None
|
|
1319
|
+
|
|
1320
|
+
if progress is not None:
|
|
1321
|
+
progress.question_stage(question_id, "RETRYING_CARD", attempt=2)
|
|
1322
|
+
card = _business_request(
|
|
1323
|
+
transport,
|
|
1324
|
+
breaker,
|
|
1325
|
+
"card",
|
|
1326
|
+
question_id,
|
|
1327
|
+
"POST",
|
|
1328
|
+
_project_path(project_id, "card/"),
|
|
1329
|
+
stage="fallback-card",
|
|
1330
|
+
# 不传模型限制:由服务端按问题自动匹配模型(与前端一致;
|
|
1331
|
+
# 传不全会导致 10406 CARD_NOT_MATCHED_MODEL)。batch requestTuids 仅记录获批请求策略。
|
|
1332
|
+
json_body=build_card_payload(tokens),
|
|
1333
|
+
)
|
|
1334
|
+
if progress is not None:
|
|
1335
|
+
progress.question_stage(question_id, "VALIDATING_CARD_UNITS")
|
|
1336
|
+
result = _finalize_card(question_id, card, scope, "dataseek-fallback")
|
|
1337
|
+
if cleanup_warnings:
|
|
1338
|
+
result["cleanupWarnings"] = cleanup_warnings
|
|
1339
|
+
return result
|
|
1340
|
+
except _CircuitOpenError:
|
|
1341
|
+
return _aborted_result(
|
|
1342
|
+
question_id,
|
|
1343
|
+
breaker,
|
|
1344
|
+
route="dataseek-fallback" if thread_uid is not None else "not-started",
|
|
1345
|
+
cleanup_warnings=cleanup_warnings,
|
|
1346
|
+
)
|
|
1347
|
+
except ApiRequestError as exc:
|
|
1348
|
+
return _exception_result(question_id, exc, cleanup_warnings, route="dataseek-fallback")
|
|
1349
|
+
except (DataSeekFailed, ReportContractError, RunnerError) as exc:
|
|
1350
|
+
if isinstance(exc, RunnerError):
|
|
1351
|
+
code = exc.code
|
|
1352
|
+
stage = "runner"
|
|
1353
|
+
elif isinstance(exc, DataSeekFailed):
|
|
1354
|
+
code = "DATASEEK_FAILED"
|
|
1355
|
+
stage = "dataseek"
|
|
1356
|
+
else:
|
|
1357
|
+
code = "CONTRACT_ERROR"
|
|
1358
|
+
stage = "runner"
|
|
1359
|
+
return _failure_result(question_id, stage, code, str(exc), cleanup_warnings, route="dataseek-fallback")
|
|
1360
|
+
finally:
|
|
1361
|
+
with contextlib.suppress(Exception):
|
|
1362
|
+
transport.close()
|
|
1363
|
+
|
|
1364
|
+
|
|
1365
|
+
def _cleanup_dataseek(
|
|
1366
|
+
transport: Any,
|
|
1367
|
+
project_id: int,
|
|
1368
|
+
thread_uid: str | None,
|
|
1369
|
+
message_id: int | None,
|
|
1370
|
+
*,
|
|
1371
|
+
terminal_confirmed: bool,
|
|
1372
|
+
breaker: BatchCircuitBreaker,
|
|
1373
|
+
warnings: list[str],
|
|
1374
|
+
) -> None:
|
|
1375
|
+
if thread_uid is None:
|
|
1376
|
+
return
|
|
1377
|
+
requests: list[tuple[str, str, str]] = []
|
|
1378
|
+
if message_id is not None and not terminal_confirmed:
|
|
1379
|
+
requests.append(
|
|
1380
|
+
(
|
|
1381
|
+
"POST",
|
|
1382
|
+
_project_path(project_id, f"threads/{thread_uid}/messages/{message_id}/abort/"),
|
|
1383
|
+
"abort-message",
|
|
1384
|
+
)
|
|
1385
|
+
)
|
|
1386
|
+
requests.append(
|
|
1387
|
+
(
|
|
1388
|
+
"DELETE",
|
|
1389
|
+
_project_path(project_id, f"threads/{thread_uid}/"),
|
|
1390
|
+
"delete-thread",
|
|
1391
|
+
)
|
|
1392
|
+
)
|
|
1393
|
+
|
|
1394
|
+
for method, path, stage in requests:
|
|
1395
|
+
allowed, timeout = breaker.reserve_cleanup_request()
|
|
1396
|
+
if not allowed or timeout is None:
|
|
1397
|
+
warnings.append("cleanup-skipped-circuit-open")
|
|
1398
|
+
break
|
|
1399
|
+
_best_effort_request(
|
|
1400
|
+
transport,
|
|
1401
|
+
method,
|
|
1402
|
+
path,
|
|
1403
|
+
stage,
|
|
1404
|
+
warnings,
|
|
1405
|
+
timeout=timeout,
|
|
1406
|
+
)
|
|
1407
|
+
|
|
1408
|
+
|
|
1409
|
+
def _poll_message(
|
|
1410
|
+
transport: Any,
|
|
1411
|
+
project_id: int,
|
|
1412
|
+
thread_uid: str,
|
|
1413
|
+
message_id: int,
|
|
1414
|
+
*,
|
|
1415
|
+
timeout: float = DATASEEK_MESSAGE_TIMEOUT_SECONDS,
|
|
1416
|
+
interval: float = POLL_INTERVAL_SECONDS,
|
|
1417
|
+
monotonic: Callable[[], float],
|
|
1418
|
+
wait: Callable[[float], None],
|
|
1419
|
+
breaker: BatchCircuitBreaker | None = None,
|
|
1420
|
+
question_id: str | None = None,
|
|
1421
|
+
progress: RunProgress | None = None,
|
|
1422
|
+
) -> list[dict[str, Any]]:
|
|
1423
|
+
deadline = monotonic() + timeout
|
|
1424
|
+
path = _project_path(project_id, f"threads/{thread_uid}/messages/{message_id}/")
|
|
1425
|
+
poll_count = 0
|
|
1426
|
+
while True:
|
|
1427
|
+
remaining = deadline - monotonic()
|
|
1428
|
+
if remaining <= 0:
|
|
1429
|
+
raise DataSeekTimeout(f"DataSeek message exceeded {timeout:g} seconds")
|
|
1430
|
+
try:
|
|
1431
|
+
poll_count += 1
|
|
1432
|
+
if progress is not None and question_id is not None:
|
|
1433
|
+
progress.question_stage(question_id, "WAITING_DATASEEK", pollCount=poll_count)
|
|
1434
|
+
if breaker is None:
|
|
1435
|
+
message = transport.request(
|
|
1436
|
+
"GET",
|
|
1437
|
+
path,
|
|
1438
|
+
stage="poll-message",
|
|
1439
|
+
timeout=min(REQUEST_TIMEOUT_SECONDS, remaining),
|
|
1440
|
+
)
|
|
1441
|
+
else:
|
|
1442
|
+
message = _business_request(
|
|
1443
|
+
transport,
|
|
1444
|
+
breaker,
|
|
1445
|
+
"dataseek",
|
|
1446
|
+
question_id or "unknown-question",
|
|
1447
|
+
"GET",
|
|
1448
|
+
path,
|
|
1449
|
+
stage="poll-message",
|
|
1450
|
+
timeout=min(REQUEST_TIMEOUT_SECONDS, remaining),
|
|
1451
|
+
)
|
|
1452
|
+
except ApiRequestError as exc:
|
|
1453
|
+
if not _is_transient_poll_error(exc):
|
|
1454
|
+
raise
|
|
1455
|
+
if breaker is not None and breaker.is_open():
|
|
1456
|
+
raise _CircuitOpenError from None
|
|
1457
|
+
remaining = deadline - monotonic()
|
|
1458
|
+
if remaining <= 0:
|
|
1459
|
+
raise DataSeekTimeout(f"DataSeek message exceeded {timeout:g} seconds") from None
|
|
1460
|
+
wait(min(interval, remaining))
|
|
1461
|
+
continue
|
|
1462
|
+
current = message.get("current") if isinstance(message, dict) else None
|
|
1463
|
+
if not isinstance(current, dict):
|
|
1464
|
+
raise DataSeekFailed("DataSeek returned an invalid message")
|
|
1465
|
+
if current.get("error"):
|
|
1466
|
+
raise DataSeekTerminalFailed("DataSeek returned an explicit error")
|
|
1467
|
+
result = current.get("result")
|
|
1468
|
+
if isinstance(result, list) and result:
|
|
1469
|
+
for item in result:
|
|
1470
|
+
data = item.get("data") if isinstance(item, dict) and item.get("type") == "answer" else None
|
|
1471
|
+
questions = data.get("questions") if isinstance(data, dict) else None
|
|
1472
|
+
if isinstance(questions, list) and questions:
|
|
1473
|
+
return _validated_tokens(questions[0])
|
|
1474
|
+
raise DataSeekTerminalFailed("DataSeek reached a terminal result without answer tokens")
|
|
1475
|
+
if breaker is not None and breaker.is_open():
|
|
1476
|
+
raise _CircuitOpenError
|
|
1477
|
+
remaining = deadline - monotonic()
|
|
1478
|
+
if remaining <= 0:
|
|
1479
|
+
raise DataSeekTimeout(f"DataSeek message exceeded {timeout:g} seconds")
|
|
1480
|
+
wait(min(interval, remaining))
|
|
1481
|
+
|
|
1482
|
+
|
|
1483
|
+
def _is_transient_poll_error(error: ApiRequestError) -> bool:
|
|
1484
|
+
return error.code == "NETWORK_ERROR" or (
|
|
1485
|
+
error.code == "HTTP_ERROR" and error.status_code is not None and (error.status_code in {408, 429} or 500 <= error.status_code < 600)
|
|
1486
|
+
)
|
|
1487
|
+
|
|
1488
|
+
|
|
1489
|
+
def _best_effort_request(
|
|
1490
|
+
transport: Any,
|
|
1491
|
+
method: str,
|
|
1492
|
+
path: str,
|
|
1493
|
+
stage: str,
|
|
1494
|
+
warnings: list[str],
|
|
1495
|
+
*,
|
|
1496
|
+
timeout: float | None = None,
|
|
1497
|
+
) -> None:
|
|
1498
|
+
kwargs: dict[str, Any] = {
|
|
1499
|
+
"stage": stage,
|
|
1500
|
+
"json_body": {} if method == "POST" else None,
|
|
1501
|
+
}
|
|
1502
|
+
if timeout is not None:
|
|
1503
|
+
kwargs["timeout"] = timeout
|
|
1504
|
+
try:
|
|
1505
|
+
transport.request(method, path, **kwargs)
|
|
1506
|
+
except Exception:
|
|
1507
|
+
warnings.append(f"{stage}-failed")
|
|
1508
|
+
|
|
1509
|
+
|
|
1510
|
+
def _validated_tokens(tokens: Any) -> list[dict[str, Any]]:
|
|
1511
|
+
try:
|
|
1512
|
+
return normalize_question_tokens(tokens)
|
|
1513
|
+
except ReportContractError as exc:
|
|
1514
|
+
raise DataSeekFailed(f"DataSeek returned malformed answer tokens ({exc})") from None
|
|
1515
|
+
|
|
1516
|
+
|
|
1517
|
+
def _validate_resolved_tuids(value: Any) -> list[str] | None:
|
|
1518
|
+
"""Validate the model resolution returned by `/card/` without inventing a scope."""
|
|
1519
|
+
if value is None:
|
|
1520
|
+
return None
|
|
1521
|
+
if (
|
|
1522
|
+
not isinstance(value, list)
|
|
1523
|
+
or not 1 <= len(value) <= MAX_MODELS_PER_QUESTION
|
|
1524
|
+
or not all(isinstance(uid, str) and uid and len(uid) <= MAX_MODEL_UID_CHARS for uid in value)
|
|
1525
|
+
or len(value) != len(set(value))
|
|
1526
|
+
):
|
|
1527
|
+
raise RunnerError(
|
|
1528
|
+
"INVALID_CARD_MODELS",
|
|
1529
|
+
f"card tuids must be null or one to {MAX_MODELS_PER_QUESTION} unique model uids",
|
|
1530
|
+
)
|
|
1531
|
+
return list(value)
|
|
1532
|
+
|
|
1533
|
+
|
|
1534
|
+
def _finalize_card(
|
|
1535
|
+
question_id: str,
|
|
1536
|
+
card: Any,
|
|
1537
|
+
scope: dict[str, Any],
|
|
1538
|
+
route: str,
|
|
1539
|
+
) -> dict[str, Any]:
|
|
1540
|
+
"""Validate a server card before exposing it as a successful report result."""
|
|
1541
|
+
if not isinstance(card, dict) or not card:
|
|
1542
|
+
raise ApiRequestError("EMPTY_CARD", "create-card returned no card", stage="create-card")
|
|
1543
|
+
try:
|
|
1544
|
+
tokens = normalize_question_tokens(flatten_units(card.get("units")))
|
|
1545
|
+
validate_normalized_tokens_in_scope(tokens, scope, f"question {question_id} card units")
|
|
1546
|
+
except ReportContractError as exc:
|
|
1547
|
+
raise RunnerError("FIELD_SCOPE_MISMATCH", str(exc)) from None
|
|
1548
|
+
resolved_tuids = _validate_resolved_tuids(card.get("tuids"))
|
|
1549
|
+
return {
|
|
1550
|
+
"id": question_id,
|
|
1551
|
+
"status": "SUCCESS",
|
|
1552
|
+
"route": route,
|
|
1553
|
+
"resolution": route,
|
|
1554
|
+
"tokens": copy.deepcopy(tokens),
|
|
1555
|
+
"resolvedTuids": copy.deepcopy(resolved_tuids),
|
|
1556
|
+
"card": copy.deepcopy(card),
|
|
1557
|
+
}
|
|
1558
|
+
|
|
1559
|
+
|
|
1560
|
+
def _exception_result(
|
|
1561
|
+
question_id: str,
|
|
1562
|
+
exc: Exception,
|
|
1563
|
+
cleanup_warnings: list[str],
|
|
1564
|
+
*,
|
|
1565
|
+
route: str,
|
|
1566
|
+
) -> dict[str, Any]:
|
|
1567
|
+
if isinstance(exc, ApiRequestError):
|
|
1568
|
+
return _failure_result(
|
|
1569
|
+
question_id,
|
|
1570
|
+
exc.stage,
|
|
1571
|
+
exc.code,
|
|
1572
|
+
str(exc),
|
|
1573
|
+
cleanup_warnings,
|
|
1574
|
+
route=route,
|
|
1575
|
+
http_status=exc.status_code,
|
|
1576
|
+
business_status=exc.business_status,
|
|
1577
|
+
)
|
|
1578
|
+
if isinstance(exc, DataSeekTimeout):
|
|
1579
|
+
return _failure_result(question_id, "dataseek", "DATASEEK_TIMEOUT", str(exc), cleanup_warnings, route=route)
|
|
1580
|
+
if isinstance(exc, DataSeekFailed):
|
|
1581
|
+
return _failure_result(question_id, "dataseek", "DATASEEK_FAILED", str(exc), cleanup_warnings, route=route)
|
|
1582
|
+
return _failure_result(
|
|
1583
|
+
question_id,
|
|
1584
|
+
"runner",
|
|
1585
|
+
"INTERNAL_ERROR",
|
|
1586
|
+
f"runner failed ({type(exc).__name__})",
|
|
1587
|
+
cleanup_warnings,
|
|
1588
|
+
route=route,
|
|
1589
|
+
)
|
|
1590
|
+
|
|
1591
|
+
|
|
1592
|
+
def _aborted_result(
|
|
1593
|
+
question_id: str,
|
|
1594
|
+
breaker: BatchCircuitBreaker,
|
|
1595
|
+
*,
|
|
1596
|
+
route: str,
|
|
1597
|
+
cleanup_warnings: list[str] | None = None,
|
|
1598
|
+
) -> dict[str, Any]:
|
|
1599
|
+
reason_code = breaker.snapshot()["reasonCode"] or "UPSTREAM_UNAVAILABLE"
|
|
1600
|
+
message = (
|
|
1601
|
+
"batch stopped after an authentication failure"
|
|
1602
|
+
if reason_code == "AUTH_ABORTED"
|
|
1603
|
+
else "batch stopped because an upstream service became unavailable"
|
|
1604
|
+
)
|
|
1605
|
+
result: dict[str, Any] = {
|
|
1606
|
+
"id": question_id,
|
|
1607
|
+
"status": "ABORTED",
|
|
1608
|
+
"route": route,
|
|
1609
|
+
"stage": "not-started" if route == "not-started" else "circuit-open",
|
|
1610
|
+
"error": {"code": reason_code, "message": message},
|
|
1611
|
+
}
|
|
1612
|
+
if cleanup_warnings:
|
|
1613
|
+
result["cleanupWarnings"] = list(cleanup_warnings)
|
|
1614
|
+
return result
|
|
1615
|
+
|
|
1616
|
+
|
|
1617
|
+
def _run_status(counts: Counter[str]) -> str:
|
|
1618
|
+
if counts["SUCCESS"] == sum(counts.values()):
|
|
1619
|
+
return "COMPLETE"
|
|
1620
|
+
if counts["SUCCESS"]:
|
|
1621
|
+
return "PARTIAL"
|
|
1622
|
+
return "FAILED"
|
|
1623
|
+
|
|
1624
|
+
|
|
1625
|
+
def _failure_result(
|
|
1626
|
+
question_id: str,
|
|
1627
|
+
stage: str,
|
|
1628
|
+
code: str,
|
|
1629
|
+
message: str,
|
|
1630
|
+
cleanup_warnings: list[str] | None = None,
|
|
1631
|
+
*,
|
|
1632
|
+
route: str,
|
|
1633
|
+
http_status: int | None = None,
|
|
1634
|
+
business_status: int | None = None,
|
|
1635
|
+
) -> dict[str, Any]:
|
|
1636
|
+
result: dict[str, Any] = {
|
|
1637
|
+
"id": question_id,
|
|
1638
|
+
"status": "FAILED",
|
|
1639
|
+
"route": route,
|
|
1640
|
+
"stage": stage,
|
|
1641
|
+
"error": {"code": code, "message": message[:300]},
|
|
1642
|
+
}
|
|
1643
|
+
if http_status is not None:
|
|
1644
|
+
result["httpStatus"] = http_status
|
|
1645
|
+
if business_status is not None:
|
|
1646
|
+
result["businessStatus"] = business_status
|
|
1647
|
+
if cleanup_warnings:
|
|
1648
|
+
result["cleanupWarnings"] = list(cleanup_warnings)
|
|
1649
|
+
return result
|
|
1650
|
+
|
|
1651
|
+
|
|
1652
|
+
def _project_path(project_id: int, suffix: str) -> str:
|
|
1653
|
+
return f"/api/v3/account-projects/{project_id}/{suffix}"
|
|
1654
|
+
|
|
1655
|
+
|
|
1656
|
+
def _required_string(data: Any, key: str, stage: str) -> str:
|
|
1657
|
+
value = data.get(key) if isinstance(data, dict) else None
|
|
1658
|
+
if not isinstance(value, str) or not value:
|
|
1659
|
+
raise ApiRequestError("INVALID_RESPONSE", f"{stage} returned no {key}", stage=stage)
|
|
1660
|
+
return value
|
|
1661
|
+
|
|
1662
|
+
|
|
1663
|
+
def _required_positive_int(data: Any, key: str, stage: str) -> int:
|
|
1664
|
+
value = data.get(key) if isinstance(data, dict) else None
|
|
1665
|
+
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
|
|
1666
|
+
raise ApiRequestError("INVALID_RESPONSE", f"{stage} returned no {key}", stage=stage)
|
|
1667
|
+
return value
|
|
1668
|
+
|
|
1669
|
+
|
|
1670
|
+
def _read_batch(path: Path) -> Any:
|
|
1671
|
+
if not path.is_file():
|
|
1672
|
+
raise RunnerError("INVALID_BATCH_FILE", "batch file does not exist")
|
|
1673
|
+
if path.stat().st_size > MAX_JSON_INPUT_BYTES:
|
|
1674
|
+
raise RunnerError("INVALID_BATCH_FILE", "batch file exceeds 4 MiB")
|
|
1675
|
+
try:
|
|
1676
|
+
return json.loads(path.read_text(encoding="utf-8"))
|
|
1677
|
+
except (OSError, UnicodeError, json.JSONDecodeError):
|
|
1678
|
+
raise RunnerError("INVALID_BATCH_FILE", "batch file must contain UTF-8 JSON") from None
|
|
1679
|
+
|
|
1680
|
+
|
|
1681
|
+
def _read_runtime_credentials(environ: Mapping[str, str]) -> tuple[str, str]:
|
|
1682
|
+
try:
|
|
1683
|
+
stored = _read_credentials_file(environ)
|
|
1684
|
+
except RunnerError:
|
|
1685
|
+
if not environ.get("DATARC_ENDPOINT") or not environ.get("DATARC_TOKEN"):
|
|
1686
|
+
raise
|
|
1687
|
+
stored = {}
|
|
1688
|
+
endpoint = environ.get("DATARC_ENDPOINT") or stored.get("endpoint")
|
|
1689
|
+
token = environ.get("DATARC_TOKEN")
|
|
1690
|
+
if not token and endpoint and stored.get("endpoint") and _normalize_endpoint(endpoint) == _normalize_endpoint(stored["endpoint"]):
|
|
1691
|
+
token = stored.get("token")
|
|
1692
|
+
if not endpoint:
|
|
1693
|
+
raise RunnerError("DATARC_ENDPOINT_MISSING", "DATARC_ENDPOINT is required")
|
|
1694
|
+
if not token:
|
|
1695
|
+
raise RunnerError("DATARC_TOKEN_MISSING", "DATARC_TOKEN is required")
|
|
1696
|
+
if "\r" in token or "\n" in token or len(token) > 16_384:
|
|
1697
|
+
raise RunnerError("DATARC_TOKEN_INVALID", "DATARC_TOKEN is invalid")
|
|
1698
|
+
return _normalize_endpoint(endpoint), token
|
|
1699
|
+
|
|
1700
|
+
|
|
1701
|
+
def _read_credentials_file(environ: Mapping[str, str]) -> dict[str, Any]:
|
|
1702
|
+
configured = environ.get("DATARC_CONFIG_FILE")
|
|
1703
|
+
if configured:
|
|
1704
|
+
path = Path(configured)
|
|
1705
|
+
if not path.is_absolute():
|
|
1706
|
+
raise RunnerError("INVALID_CONFIG", "DATARC_CONFIG_FILE 必须为绝对路径;请指定工具允许访问的配置文件")
|
|
1707
|
+
else:
|
|
1708
|
+
workspace = Path(environ.get("DATARC_WORKSPACE_DIR") or Path.cwd())
|
|
1709
|
+
if not workspace.is_absolute():
|
|
1710
|
+
raise RunnerError("INVALID_CONFIG", "DATARC_WORKSPACE_DIR 必须为绝对路径;请使用当前会话工作区的根目录")
|
|
1711
|
+
path = workspace / ".datarc" / "config.toml"
|
|
1712
|
+
try:
|
|
1713
|
+
info = path.lstat()
|
|
1714
|
+
if path.is_symlink() or not path.is_file() or info.st_size > 65536 or (os.name != "nt" and info.st_mode & 0o077):
|
|
1715
|
+
raise ValueError
|
|
1716
|
+
stored = tomllib.loads(path.read_text(encoding="utf-8"))
|
|
1717
|
+
if (
|
|
1718
|
+
not isinstance(stored, dict)
|
|
1719
|
+
or stored.get("version") != 1
|
|
1720
|
+
or not isinstance(stored.get("endpoint"), str)
|
|
1721
|
+
or not isinstance(stored.get("token"), str)
|
|
1722
|
+
):
|
|
1723
|
+
raise ValueError
|
|
1724
|
+
_normalize_endpoint(stored["endpoint"])
|
|
1725
|
+
if not stored["token"].strip() or "\r" in stored["token"] or "\n" in stored["token"]:
|
|
1726
|
+
raise ValueError
|
|
1727
|
+
return stored
|
|
1728
|
+
except FileNotFoundError:
|
|
1729
|
+
return {}
|
|
1730
|
+
except (OSError, ValueError, RunnerError):
|
|
1731
|
+
raise RunnerError("INVALID_CONFIG", "无法读取 datarc 凭据文件;请检查 TOML 格式及权限(macOS/Linux 应为 600)后重试") from None
|
|
1732
|
+
|
|
1733
|
+
|
|
1734
|
+
def _normalize_endpoint(value: str) -> str:
|
|
1735
|
+
candidate = value.split("#", 1)[0].rstrip("/")
|
|
1736
|
+
parts = urlsplit(candidate)
|
|
1737
|
+
if (
|
|
1738
|
+
parts.scheme not in {"http", "https"}
|
|
1739
|
+
or not parts.hostname
|
|
1740
|
+
or parts.username
|
|
1741
|
+
or parts.password
|
|
1742
|
+
or parts.path not in {"", "/"}
|
|
1743
|
+
or parts.query
|
|
1744
|
+
or parts.fragment
|
|
1745
|
+
):
|
|
1746
|
+
raise RunnerError("DATARC_ENDPOINT_INVALID", "DATARC_ENDPOINT must be a credential-free http(s) origin")
|
|
1747
|
+
try:
|
|
1748
|
+
port = parts.port
|
|
1749
|
+
except ValueError:
|
|
1750
|
+
raise RunnerError("DATARC_ENDPOINT_INVALID", "DATARC_ENDPOINT contains an invalid port") from None
|
|
1751
|
+
host = parts.hostname.casefold()
|
|
1752
|
+
if ":" in host:
|
|
1753
|
+
host = f"[{host}]"
|
|
1754
|
+
if port is not None and not ((parts.scheme == "http" and port == 80) or (parts.scheme == "https" and port == 443)):
|
|
1755
|
+
host = f"{host}:{port}"
|
|
1756
|
+
return f"{parts.scheme.casefold()}://{host}"
|
|
1757
|
+
|
|
1758
|
+
|
|
1759
|
+
def _load_httpx2() -> Any:
|
|
1760
|
+
try:
|
|
1761
|
+
version = importlib.metadata.version("httpx2")
|
|
1762
|
+
module = importlib.import_module("httpx2")
|
|
1763
|
+
except (ImportError, importlib.metadata.PackageNotFoundError):
|
|
1764
|
+
raise RunnerError(
|
|
1765
|
+
"DEPENDENCY_MISSING",
|
|
1766
|
+
"httpx2==2.3.0 is unavailable; use the Skill's Agent-managed API fallback",
|
|
1767
|
+
) from None
|
|
1768
|
+
if version != "2.3.0":
|
|
1769
|
+
raise RunnerError(
|
|
1770
|
+
"DEPENDENCY_VERSION_MISMATCH",
|
|
1771
|
+
"httpx2==2.3.0 is required; use the Skill's Agent-managed API fallback",
|
|
1772
|
+
)
|
|
1773
|
+
return module
|
|
1774
|
+
|
|
1775
|
+
|
|
1776
|
+
def _safe_http_message(response: Any, stage: str, token: str) -> str:
|
|
1777
|
+
message = f"{stage} returned HTTP {getattr(response, 'status_code', 'error')}"
|
|
1778
|
+
try:
|
|
1779
|
+
payload = response.json()
|
|
1780
|
+
except (ValueError, AttributeError):
|
|
1781
|
+
return message
|
|
1782
|
+
detail = _payload_message(payload)
|
|
1783
|
+
return f"{message}: {_redact(detail, token)[:_MAX_SAFE_ERROR_CHARS]}" if detail else message
|
|
1784
|
+
|
|
1785
|
+
|
|
1786
|
+
def _response_business_status(response: Any) -> int | None:
|
|
1787
|
+
try:
|
|
1788
|
+
payload = response.json()
|
|
1789
|
+
except (ValueError, AttributeError):
|
|
1790
|
+
return None
|
|
1791
|
+
value = payload.get("status") if isinstance(payload, dict) else None
|
|
1792
|
+
if isinstance(value, int) and not isinstance(value, bool):
|
|
1793
|
+
return value
|
|
1794
|
+
if isinstance(value, str) and value.isascii() and value.isdecimal() and len(value) <= 9:
|
|
1795
|
+
return int(value)
|
|
1796
|
+
return None
|
|
1797
|
+
|
|
1798
|
+
|
|
1799
|
+
def _safe_api_message(payload: Any, stage: str, token: str) -> str:
|
|
1800
|
+
detail = _payload_message(payload)
|
|
1801
|
+
return f"{stage} failed: {_redact(detail, token)[:_MAX_SAFE_ERROR_CHARS]}" if detail else f"{stage} returned an API error"
|
|
1802
|
+
|
|
1803
|
+
|
|
1804
|
+
def _payload_message(payload: Any) -> str:
|
|
1805
|
+
if not isinstance(payload, dict):
|
|
1806
|
+
return ""
|
|
1807
|
+
for key in ("message", "error_message", "error", "detail"):
|
|
1808
|
+
value = payload.get(key)
|
|
1809
|
+
if isinstance(value, str) and value:
|
|
1810
|
+
return value
|
|
1811
|
+
return ""
|
|
1812
|
+
|
|
1813
|
+
|
|
1814
|
+
def _redact(value: str, secret: str) -> str:
|
|
1815
|
+
"""Mask complete or significant secret prefixes in a bounded error detail."""
|
|
1816
|
+
bounded = value[:_MAX_REDACTION_INPUT_CHARS]
|
|
1817
|
+
redacted: list[str] = []
|
|
1818
|
+
cursor = 0
|
|
1819
|
+
visible_limit = min(len(bounded), _MAX_SAFE_ERROR_CHARS)
|
|
1820
|
+
while cursor < visible_limit:
|
|
1821
|
+
matched_chars, consumed_chars = _match_secret_fragment(bounded, cursor, secret)
|
|
1822
|
+
should_redact = matched_chars == len(secret) or matched_chars >= _UNLABELED_SECRET_FRAGMENT_CHARS
|
|
1823
|
+
if matched_chars >= _CONTEXTUAL_SECRET_FRAGMENT_CHARS and _has_secret_context(bounded, cursor):
|
|
1824
|
+
should_redact = True
|
|
1825
|
+
if should_redact and consumed_chars:
|
|
1826
|
+
if matched_chars < len(secret):
|
|
1827
|
+
consumed_chars = _secret_value_end(bounded, cursor + consumed_chars) - cursor
|
|
1828
|
+
redacted.append(_REDACTION_MARKER)
|
|
1829
|
+
cursor += consumed_chars
|
|
1830
|
+
continue
|
|
1831
|
+
redacted.append(bounded[cursor])
|
|
1832
|
+
cursor += 1
|
|
1833
|
+
return "".join(redacted).replace("\r", " ").replace("\n", " ")
|
|
1834
|
+
|
|
1835
|
+
|
|
1836
|
+
def _has_secret_context(value: str, start: int) -> bool:
|
|
1837
|
+
return _SECRET_CONTEXT_PATTERN.search(value[max(0, start - 64) : start]) is not None
|
|
1838
|
+
|
|
1839
|
+
|
|
1840
|
+
def _secret_value_end(value: str, start: int) -> int:
|
|
1841
|
+
cursor = start
|
|
1842
|
+
while cursor < len(value) and not value[cursor].isspace() and value[cursor] not in _SECRET_VALUE_DELIMITERS:
|
|
1843
|
+
cursor += 1
|
|
1844
|
+
return cursor
|
|
1845
|
+
|
|
1846
|
+
|
|
1847
|
+
def _match_secret_fragment(value: str, start: int, secret: str) -> tuple[int, int]:
|
|
1848
|
+
raw_match = _match_raw_secret_fragment(value, start, secret)
|
|
1849
|
+
encoded_match = _match_optionally_encoded_secret_fragment(value, start, secret)
|
|
1850
|
+
return max(raw_match, encoded_match)
|
|
1851
|
+
|
|
1852
|
+
|
|
1853
|
+
def _match_raw_secret_fragment(value: str, start: int, secret: str) -> tuple[int, int]:
|
|
1854
|
+
match_length = 0
|
|
1855
|
+
max_match_length = min(len(secret), len(value) - start)
|
|
1856
|
+
while match_length < max_match_length and value[start + match_length] == secret[match_length]:
|
|
1857
|
+
match_length += 1
|
|
1858
|
+
return match_length, match_length
|
|
1859
|
+
|
|
1860
|
+
|
|
1861
|
+
def _match_optionally_encoded_secret_fragment(value: str, start: int, secret: str) -> tuple[int, int]:
|
|
1862
|
+
matched_chars = 0
|
|
1863
|
+
cursor = start
|
|
1864
|
+
for character in secret:
|
|
1865
|
+
if cursor >= len(value):
|
|
1866
|
+
break
|
|
1867
|
+
encoded = "".join(f"%{byte:02X}" for byte in character.encode("utf-8"))
|
|
1868
|
+
candidate = value[cursor : cursor + len(encoded)]
|
|
1869
|
+
if value[cursor] == "%" and encoded.casefold().startswith(candidate.casefold()):
|
|
1870
|
+
cursor += len(candidate)
|
|
1871
|
+
if len(candidate) < len(encoded):
|
|
1872
|
+
break
|
|
1873
|
+
matched_chars += 1
|
|
1874
|
+
continue
|
|
1875
|
+
if value[cursor] != character:
|
|
1876
|
+
break
|
|
1877
|
+
cursor += 1
|
|
1878
|
+
matched_chars += 1
|
|
1879
|
+
return matched_chars, cursor - start
|
|
1880
|
+
|
|
1881
|
+
|
|
1882
|
+
def _finish_failed_progress(progress: RunProgress | None) -> None:
|
|
1883
|
+
if progress is None:
|
|
1884
|
+
return
|
|
1885
|
+
with contextlib.suppress(Exception):
|
|
1886
|
+
progress.fail_run()
|
|
1887
|
+
|
|
1888
|
+
|
|
1889
|
+
def _validate_progress_counts(counts: Mapping[str, int]) -> dict[str, int]:
|
|
1890
|
+
keys = ("successCount", "failedCount", "abortedCount")
|
|
1891
|
+
if set(counts) != set(keys):
|
|
1892
|
+
raise RunnerError("INVALID_PROGRESS", "progress counts must use the exact terminal contract")
|
|
1893
|
+
normalized = dict(counts)
|
|
1894
|
+
if any(isinstance(normalized[key], bool) or not isinstance(normalized[key], int) or normalized[key] < 0 for key in keys):
|
|
1895
|
+
raise RunnerError("INVALID_PROGRESS", "progress counts must be non-negative integers")
|
|
1896
|
+
return normalized
|
|
1897
|
+
|
|
1898
|
+
|
|
1899
|
+
def _format_timestamp(value: datetime) -> str:
|
|
1900
|
+
if not isinstance(value, datetime):
|
|
1901
|
+
raise RunnerError("INVALID_PROGRESS", "progress clock must return a datetime")
|
|
1902
|
+
if value.tzinfo is None:
|
|
1903
|
+
value = value.replace(tzinfo=UTC)
|
|
1904
|
+
return value.astimezone(UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
|
1905
|
+
|
|
1906
|
+
|
|
1907
|
+
def _write_stream_json(stream: Any, payload: dict[str, Any]) -> None:
|
|
1908
|
+
json.dump(payload, stream, ensure_ascii=False, separators=(",", ":"))
|
|
1909
|
+
stream.write("\n")
|
|
1910
|
+
stream.flush()
|
|
1911
|
+
|
|
1912
|
+
|
|
1913
|
+
if __name__ == "__main__":
|
|
1914
|
+
raise SystemExit(main())
|