@v587d/capital-generation 2.31.7 → 2.32.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/CHANGELOG.md +60 -0
- package/README.md +14 -5
- package/automation/package.json +1 -1
- package/chart-ui/package.json +1 -1
- package/config/package.json +1 -1
- package/lib/analysis/artifact.d.ts +35 -0
- package/lib/analysis/artifact.js +250 -0
- package/lib/analysis/registry.d.ts +16 -2
- package/lib/analysis/registry.js +133 -23
- package/lib/analysis/runtime.d.ts +46 -19
- package/lib/analysis/runtime.js +485 -116
- package/lib/analysis/schemas.d.ts +46 -0
- package/lib/analysis/schemas.js +260 -7
- package/lib/analysis/snapshot.d.ts +10 -3
- package/lib/analysis/snapshot.js +298 -46
- package/lib/analysis/storage.d.ts +29 -1
- package/lib/analysis/storage.js +39 -6
- package/lib/analysis/tools.js +270 -29
- package/lib/analysis/types.d.ts +257 -3
- package/lib/analysis/types.js +31 -1
- package/lib/analysis/validation.d.ts +37 -1
- package/lib/analysis/validation.js +315 -1
- package/lib/chart/tool.js +1 -0
- package/lib/data-collector/store.d.ts +7 -1
- package/lib/data-collector/store.js +14 -0
- package/lib/python-runtime/child-env.d.ts +4 -2
- package/lib/python-runtime/child-env.js +21 -14
- package/lib/python-runtime/manager.d.ts +8 -0
- package/lib/python-runtime/manager.js +30 -14
- package/lib/sources/tencent-http.js +9 -3
- package/lib/web-retriever/local-fetch.d.ts +1 -1
- package/lib/web-retriever/local-fetch.js +1 -1
- package/lib/web-retriever/wind-client.d.ts +1 -1
- package/lib/web-retriever/wind-client.js +1 -1
- package/package.json +2 -1
- package/plugin-page/README.en.md +1 -1
- package/plugin-page/README.zh.md +1 -1
- package/preset/capital-generation/agent.patch.yml +1 -1
- package/preset/capital-generation/skills/capital-analysis-evidence/SKILL.md +15 -2
- package/preset/capital-generation/skills/capital-analysis-synthesis/SKILL.md +54 -9
- package/preset/capital-generation/skills/capital-analysis-validation/SKILL.md +41 -7
- package/preset/capital-generation/skills/capital-equity-research/SKILL.md +1 -1
- package/preset/capital-generation/skills/capital-event-impact/SKILL.md +20 -1
- package/preset/capital-generation/skills/capital-orchestration/SKILL.md +1 -1
- package/preset/capital-generation/skills/capital-senior-analysis/SKILL.md +38 -8
- package/python/analysis/lib/__init__.py +9 -0
- package/python/analysis/lib/errors.py +12 -0
- package/python/analysis/lib/eventstudy.py +164 -0
- package/python/analysis/lib/frames.py +95 -0
- package/python/analysis/lib/gaps.py +54 -0
- package/python/analysis/lib/jsonio.py +61 -0
- package/python/analysis/lib/metrics.py +147 -0
- package/python/analysis/lib/pit.py +84 -0
- package/python/analysis/lib/prices.py +140 -0
- package/python/analysis/lib/timeaxis.py +142 -0
- package/python/analysis/lib/version.py +3 -0
- package/python/analysis/modules/comps_valuation/module.py +26 -59
- package/python/analysis/modules/earnings_bridge/module.py +20 -77
- package/python/analysis/modules/event_study/LICENSE +21 -0
- package/python/analysis/modules/event_study/module.json +217 -0
- package/python/analysis/modules/event_study/module.py +979 -0
- package/python/analysis/modules/financial_quality/module.py +25 -88
- package/python/analysis/modules/hello/module.py +4 -0
- package/python/analysis/modules/kline_quality/module.py +26 -132
- package/python/analysis/modules/portfolio_stress/module.py +27 -112
- package/python/analysis/modules/returns_risk/module.json +108 -25
- package/python/analysis/modules/returns_risk/module.py +68 -227
- package/python/analysis/modules/scenario_sensitivity/module.py +11 -44
- package/python/analysis/modules/simple_backtest/module.json +244 -36
- package/python/analysis/modules/simple_backtest/module.py +1146 -459
- package/python/analysis/modules/statement_integrity/module.py +35 -87
- package/python/analysis/modules/technical_indicators/module.py +33 -152
- package/python/analysis/modules/valuation_sensitivity/module.py +30 -61
- package/python/worker.py +5 -0
- package/watchlist/package.json +1 -1
package/lib/analysis/runtime.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { moduleCodeFacts } from './registry.js';
|
|
2
|
+
import { ANALYSIS_QUEUE_WAIT_MS, MODULE_DEFAULT_LIMITS } from './schemas.js';
|
|
3
|
+
import { REQUEST_FILE, RESULT_FILE, RUN_FILE, analysisContractV2Enabled, analysisDir, moduleRunDir, newModuleRunId, readJsonFile, runRef, writeFiles, } from './storage.js';
|
|
4
|
+
import { ANALYSIS_ERROR_CODES, ANALYSIS_PROTOCOL, AnalysisError, WORKER_PROTOCOL_VERSION, } from './types.js';
|
|
4
5
|
import { validateAgainstSchema, validateModuleResult } from './validation.js';
|
|
5
6
|
import { createHash } from 'node:crypto';
|
|
6
7
|
import { dirname } from 'node:path';
|
|
@@ -11,44 +12,134 @@ import { stableStringify } from './snapshot.js';
|
|
|
11
12
|
* the same install hint as the data capabilities.
|
|
12
13
|
*/
|
|
13
14
|
export function analysisRuntimeFrom(ctx) {
|
|
15
|
+
const managerOf = () => {
|
|
16
|
+
const manager = ctx.get('pythonRuntime');
|
|
17
|
+
return manager !== undefined && typeof manager.runAnalysisModule === 'function' ? manager : undefined;
|
|
18
|
+
};
|
|
19
|
+
const notReady = () => {
|
|
20
|
+
throw new AnalysisError('analysis_runtime_not_ready', '私有 Python 运行时未加载(python-runtime 行未启用或尚未装配);请在插件设置 → 分析环境里安装 base pack');
|
|
21
|
+
};
|
|
14
22
|
return {
|
|
15
23
|
async runAnalysisModule(options) {
|
|
16
|
-
const manager =
|
|
17
|
-
if (manager === undefined || typeof manager.runAnalysisModule !== 'function') {
|
|
18
|
-
throw new AnalysisError('analysis_runtime_not_ready', '私有 Python 运行时未加载(python-runtime 行未启用或尚未装配);请在插件设置 → 分析环境里安装 base pack');
|
|
19
|
-
}
|
|
24
|
+
const manager = managerOf() ?? notReady();
|
|
20
25
|
return await manager.runAnalysisModule(options);
|
|
21
26
|
},
|
|
27
|
+
async analysisRuntimeIdentity() {
|
|
28
|
+
const manager = managerOf() ?? notReady();
|
|
29
|
+
if (typeof manager.analysisRuntimeIdentity !== 'function')
|
|
30
|
+
return { python_version: 'unknown' };
|
|
31
|
+
return await manager.analysisRuntimeIdentity();
|
|
32
|
+
},
|
|
22
33
|
};
|
|
23
34
|
}
|
|
24
35
|
/** Global cap: the private interpreter is heavy and the machine is shared with the DSH host. */
|
|
25
36
|
const MAX_CONCURRENT_ANALYSES = 2;
|
|
26
37
|
let activeAnalyses = 0;
|
|
27
38
|
const waiting = [];
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
39
|
+
const cancelledError = () => new AnalysisError('analysis_cancelled', '调用已被取消,未启动分析进程');
|
|
40
|
+
const queueTimeoutError = () => new AnalysisError('analysis_queue_timeout', '排队超时:执行槽位被占满,等待超过上限;稍后重试或缩小分析范围');
|
|
41
|
+
function throwIfAborted(signal) {
|
|
42
|
+
if (signal?.aborted === true)
|
|
43
|
+
throw cancelledError();
|
|
44
|
+
}
|
|
45
|
+
function acquireAnalysisSlot(deadline, signal) {
|
|
46
|
+
throwIfAborted(signal);
|
|
47
|
+
if (activeAnalyses < MAX_CONCURRENT_ANALYSES && waiting.length === 0) {
|
|
48
|
+
activeAnalyses += 1;
|
|
49
|
+
return Promise.resolve(releaseAnalysisSlot);
|
|
35
50
|
}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
51
|
+
const remaining = deadline - Date.now();
|
|
52
|
+
if (remaining <= 0)
|
|
53
|
+
return Promise.reject(queueTimeoutError());
|
|
54
|
+
return new Promise((resolve, reject) => {
|
|
55
|
+
let settled = false;
|
|
56
|
+
const cleanup = () => {
|
|
57
|
+
clearTimeout(timer);
|
|
58
|
+
signal?.removeEventListener('abort', onAbort);
|
|
59
|
+
};
|
|
60
|
+
const removeWaiter = () => {
|
|
61
|
+
const index = waiting.indexOf(waiter);
|
|
62
|
+
if (index >= 0)
|
|
63
|
+
waiting.splice(index, 1);
|
|
64
|
+
};
|
|
65
|
+
const settle = (error) => {
|
|
66
|
+
if (settled)
|
|
67
|
+
return;
|
|
68
|
+
settled = true;
|
|
69
|
+
cleanup();
|
|
70
|
+
if (error === undefined)
|
|
71
|
+
resolve(releaseAnalysisSlot);
|
|
72
|
+
else
|
|
73
|
+
reject(error);
|
|
74
|
+
};
|
|
75
|
+
const waiter = {
|
|
76
|
+
// The release path reserves the slot before granting it, so two releases cannot oversubscribe.
|
|
77
|
+
grant: () => settle(),
|
|
78
|
+
reject: (error) => { removeWaiter(); settle(error); },
|
|
79
|
+
};
|
|
80
|
+
const timer = setTimeout(() => { removeWaiter(); settle(queueTimeoutError()); }, remaining);
|
|
81
|
+
const onAbort = () => { removeWaiter(); settle(cancelledError()); };
|
|
82
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
83
|
+
waiting.push(waiter);
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
function releaseAnalysisSlot() {
|
|
87
|
+
activeAnalyses -= 1;
|
|
88
|
+
const next = waiting.shift();
|
|
89
|
+
if (next !== undefined) {
|
|
90
|
+
activeAnalyses += 1;
|
|
91
|
+
next.grant();
|
|
39
92
|
}
|
|
40
93
|
}
|
|
41
94
|
/** One run per snapshot at a time; the tail is kept so later runs queue instead of interleaving. */
|
|
42
95
|
const snapshotTails = new Map();
|
|
43
|
-
async function
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
|
|
96
|
+
async function withSnapshotLock(analysisId, deadline, signal, run) {
|
|
97
|
+
const tail = snapshotTails.get(analysisId) ?? Promise.resolve();
|
|
98
|
+
let releaseQueue;
|
|
99
|
+
const mine = new Promise((resolve) => { releaseQueue = resolve; });
|
|
100
|
+
const chained = tail.then(() => mine);
|
|
101
|
+
snapshotTails.set(analysisId, chained);
|
|
47
102
|
try {
|
|
48
|
-
|
|
103
|
+
throwIfAborted(signal);
|
|
104
|
+
const remaining = deadline - Date.now();
|
|
105
|
+
if (remaining <= 0)
|
|
106
|
+
throw queueTimeoutError();
|
|
107
|
+
await new Promise((resolve, reject) => {
|
|
108
|
+
let settled = false;
|
|
109
|
+
const cleanup = () => {
|
|
110
|
+
clearTimeout(timer);
|
|
111
|
+
signal?.removeEventListener('abort', onAbort);
|
|
112
|
+
};
|
|
113
|
+
const timer = setTimeout(() => {
|
|
114
|
+
if (settled)
|
|
115
|
+
return;
|
|
116
|
+
settled = true;
|
|
117
|
+
cleanup();
|
|
118
|
+
reject(queueTimeoutError());
|
|
119
|
+
}, remaining);
|
|
120
|
+
const onAbort = () => {
|
|
121
|
+
if (settled)
|
|
122
|
+
return;
|
|
123
|
+
settled = true;
|
|
124
|
+
cleanup();
|
|
125
|
+
reject(cancelledError());
|
|
126
|
+
};
|
|
127
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
128
|
+
tail.then(() => { if (!settled) {
|
|
129
|
+
settled = true;
|
|
130
|
+
cleanup();
|
|
131
|
+
resolve();
|
|
132
|
+
} }, () => { if (!settled) {
|
|
133
|
+
settled = true;
|
|
134
|
+
cleanup();
|
|
135
|
+
resolve();
|
|
136
|
+
} });
|
|
137
|
+
});
|
|
138
|
+
return await run();
|
|
49
139
|
}
|
|
50
140
|
finally {
|
|
51
|
-
|
|
141
|
+
releaseQueue();
|
|
142
|
+
if (snapshotTails.get(analysisId) === chained)
|
|
52
143
|
snapshotTails.delete(analysisId);
|
|
53
144
|
}
|
|
54
145
|
}
|
|
@@ -67,130 +158,396 @@ function requireString(value, field) {
|
|
|
67
158
|
}
|
|
68
159
|
return value;
|
|
69
160
|
}
|
|
161
|
+
function runtimeIdentityKey(identity) {
|
|
162
|
+
if (identity === undefined)
|
|
163
|
+
return 'unknown';
|
|
164
|
+
const packs = Object.entries(identity.packs ?? {}).sort(([left], [right]) => left.localeCompare(right));
|
|
165
|
+
return `${identity.python_version}|${packs.map(([name, version]) => `${name}@${version}`).join(',')}`;
|
|
166
|
+
}
|
|
167
|
+
function runtimeFacts(identity, pythonVersion) {
|
|
168
|
+
return {
|
|
169
|
+
python: pythonVersion ?? identity?.python_version ?? null,
|
|
170
|
+
pack_base: identity?.packs?.base ?? null,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
/** `required_fields` names a request path; a manifest can require one, the host checks it pre-run. */
|
|
174
|
+
function missingRequiredFields(fields, request) {
|
|
175
|
+
const valueOf = (field) => {
|
|
176
|
+
if (field === 'task_id')
|
|
177
|
+
return request.task_id;
|
|
178
|
+
if (field === 'as_of')
|
|
179
|
+
return request.as_of;
|
|
180
|
+
if (field.startsWith('inputs.'))
|
|
181
|
+
return request.inputs[field.slice('inputs.'.length)];
|
|
182
|
+
return request.params[field.slice('params.'.length)];
|
|
183
|
+
};
|
|
184
|
+
const missing = [];
|
|
185
|
+
for (const field of fields) {
|
|
186
|
+
const value = valueOf(field);
|
|
187
|
+
const empty = value === undefined || value === null || (typeof value === 'string' && value.trim() === '')
|
|
188
|
+
|| (Array.isArray(value) && value.length === 0);
|
|
189
|
+
if (empty)
|
|
190
|
+
missing.push(field);
|
|
191
|
+
}
|
|
192
|
+
return missing;
|
|
193
|
+
}
|
|
194
|
+
/** `run.json` is rewritten whole by the store seam; rows are matched by `module_run_id`. */
|
|
195
|
+
function upsertRun(index, record) {
|
|
196
|
+
const runs = index.runs.filter((item) => item.module_run_id !== record.module_run_id);
|
|
197
|
+
return { schema_version: 2, analysis_id: index.analysis_id, input_fingerprint: index.input_fingerprint, runs: [...runs, record] };
|
|
198
|
+
}
|
|
199
|
+
function statusForFlowError(code) {
|
|
200
|
+
if (code === 'analysis_timeout' || code === 'analysis_queue_timeout')
|
|
201
|
+
return 'timed_out';
|
|
202
|
+
if (code === 'analysis_cancelled')
|
|
203
|
+
return 'cancelled';
|
|
204
|
+
return 'failed';
|
|
205
|
+
}
|
|
206
|
+
function stripCode(message, code) {
|
|
207
|
+
return message.startsWith(`${code}: `) ? message.slice(code.length + 2) : message;
|
|
208
|
+
}
|
|
209
|
+
/** The error a caller sees must name the run, so its terminal row can be found after the fact. */
|
|
210
|
+
function withRunRef(error, ref) {
|
|
211
|
+
return new AnalysisError(error.code, `${stripCode(error.message, error.code)}(run ${ref})`);
|
|
212
|
+
}
|
|
70
213
|
/** Run one registered module against a loaded snapshot, with reuse keyed by `run_fingerprint`. */
|
|
71
214
|
export async function runModuleOnSnapshot(options) {
|
|
72
215
|
const { writer, runtime, session, snapshot, module } = options;
|
|
73
|
-
const
|
|
216
|
+
const clock = options.clock ?? Date.now;
|
|
74
217
|
const manifest = module.manifest;
|
|
218
|
+
if (snapshot.legacy === true && analysisContractV2Enabled()) {
|
|
219
|
+
throw new AnalysisError('analysis_snapshot_legacy', '这是 V1 快照:只读兼容,不能再运行;请用同一批输入重建 V2 快照');
|
|
220
|
+
}
|
|
221
|
+
const inputsDir = snapshot.paths.inputs_dir;
|
|
222
|
+
if (typeof inputsDir !== 'string' || inputsDir === '') {
|
|
223
|
+
throw new AnalysisError('analysis_snapshot_invalid', `快照 ${snapshot.analysis_id} 的暂存输入目录无法定位;重建快照后再跑`);
|
|
224
|
+
}
|
|
75
225
|
if (!manifest.roles.includes('senior_analyst')) {
|
|
76
226
|
throw new AnalysisError('analysis_module_not_applicable', `模块 ${manifest.id} 未声明 senior_analyst 角色`);
|
|
77
227
|
}
|
|
228
|
+
// Row-level PIT filtering is the module's job, so only a module that declares it may run on an
|
|
229
|
+
// as_known_then snapshot; otherwise the host would be claiming a guarantee it cannot enforce.
|
|
230
|
+
const temporalMode = snapshot.temporal_mode ?? 'ex_post';
|
|
231
|
+
if (temporalMode === 'as_known_then' && manifest.temporal_aware !== true) {
|
|
232
|
+
throw new AnalysisError('analysis_point_in_time_conflict', `快照是 as_known_then,但模块 ${manifest.id} 未声明 temporal_aware:不能用事后数据跑时点分析`);
|
|
233
|
+
}
|
|
234
|
+
const analysisId = requireString(snapshot.analysis_id, 'analysis_id');
|
|
235
|
+
const taskId = requireString(snapshot.task_id, 'task_id');
|
|
236
|
+
const asOf = requireString(snapshot.as_of, 'as_of');
|
|
237
|
+
// Validate the raw object first: normalizing an array or a string into `{}` would make a bad request
|
|
238
|
+
// look like an empty one (X-02).
|
|
78
239
|
const params = options.params ?? {};
|
|
79
240
|
const paramIssues = validateAgainstSchema(params, manifest.input_schema, 'params');
|
|
80
241
|
if (paramIssues.length > 0) {
|
|
81
242
|
throw new AnalysisError('analysis_input_invalid', `参数不符合 ${manifest.id} 的输入契约:${paramIssues.slice(0, 4).join(';')}`);
|
|
82
243
|
}
|
|
83
|
-
const
|
|
244
|
+
const inputs = {
|
|
245
|
+
datasets: snapshot.dataset_refs.map((item) => ({ dataset_id: item.dataset_id })),
|
|
246
|
+
profiles: snapshot.profile_refs.map((item) => ({ profile_id: item.profile_id })),
|
|
247
|
+
evidence: snapshot.evidence,
|
|
248
|
+
};
|
|
249
|
+
const missingFields = missingRequiredFields(manifest.required_fields, { task_id: taskId, as_of: asOf, inputs, params });
|
|
250
|
+
if (missingFields.length > 0) {
|
|
251
|
+
throw new AnalysisError('analysis_input_invalid', `模块 ${manifest.id} 需要这些输入字段:${missingFields.join('、')}(本次为空)`);
|
|
252
|
+
}
|
|
253
|
+
const codeFacts = moduleCodeFacts(module);
|
|
254
|
+
const moduleRunId = newModuleRunId();
|
|
255
|
+
const ref = runRef(analysisId, moduleRunId);
|
|
256
|
+
const queuedAt = clock();
|
|
257
|
+
const queueWaitMs = options.queueWaitMs ?? ANALYSIS_QUEUE_WAIT_MS;
|
|
258
|
+
const deadline = queuedAt + queueWaitMs;
|
|
84
259
|
const paramsDigest = digest(params);
|
|
260
|
+
let identity;
|
|
261
|
+
try {
|
|
262
|
+
identity = await runtime.analysisRuntimeIdentity?.();
|
|
263
|
+
}
|
|
264
|
+
catch (error) {
|
|
265
|
+
// Reading the runtime facts is the first thing that can fail; nothing has started yet, so no
|
|
266
|
+
// terminal row would describe a run that never existed.
|
|
267
|
+
throw asRuntimeError(error, manifest.id);
|
|
268
|
+
}
|
|
269
|
+
const runtimeKey = runtimeIdentityKey(identity);
|
|
85
270
|
const runFingerprint = digest({
|
|
86
271
|
input_fingerprint: snapshot.input_fingerprint,
|
|
87
272
|
module_id: manifest.id,
|
|
88
273
|
module_version: manifest.version,
|
|
274
|
+
module_code_hash: codeFacts.module_code_hash,
|
|
275
|
+
worker_protocol_version: WORKER_PROTOCOL_VERSION,
|
|
276
|
+
runtime: runtimeKey,
|
|
89
277
|
params_digest: paramsDigest,
|
|
90
278
|
});
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
as_of: requireString(snapshot.as_of, 'as_of'),
|
|
108
|
-
inputs: {
|
|
109
|
-
datasets: snapshot.dataset_refs.map((item) => ({ dataset_id: item.dataset_id })),
|
|
110
|
-
profiles: snapshot.profile_refs.map((item) => ({ profile_id: item.profile_id })),
|
|
111
|
-
evidence: snapshot.evidence,
|
|
112
|
-
},
|
|
113
|
-
params,
|
|
114
|
-
};
|
|
115
|
-
const [requestFile] = await writeFiles(writer, session, dir, [{ name: REQUEST_FILE, content: JSON.stringify(request) }], {
|
|
116
|
-
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
117
|
-
what: '写入模块请求失败',
|
|
118
|
-
});
|
|
119
|
-
const runDirAbsolute = dirname(requestFile.absolutePath);
|
|
120
|
-
const limits = { ...MODULE_DEFAULT_LIMITS, ...manifest.limits };
|
|
121
|
-
let executed;
|
|
279
|
+
const base = {
|
|
280
|
+
module_run_id: moduleRunId,
|
|
281
|
+
analysis_id: analysisId,
|
|
282
|
+
snapshot_id: analysisId,
|
|
283
|
+
module_id: manifest.id,
|
|
284
|
+
module_version: manifest.version,
|
|
285
|
+
module_code_hash: codeFacts.module_code_hash,
|
|
286
|
+
worker_protocol_version: WORKER_PROTOCOL_VERSION,
|
|
287
|
+
params_digest: paramsDigest,
|
|
288
|
+
run_fingerprint: runFingerprint,
|
|
289
|
+
};
|
|
290
|
+
const runDir = moduleRunDir(analysisId, moduleRunId);
|
|
291
|
+
// Workspace-relative to the analysis directory, as the plan records it.
|
|
292
|
+
const resultRef = `modules/${moduleRunId}/${RESULT_FILE}`;
|
|
293
|
+
/** Best effort: a terminal row is mandatory, intermediate rows are only useful if they land. */
|
|
294
|
+
const writeRecord = async (record, required) => {
|
|
122
295
|
try {
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
inputsDir: snapshot.paths.inputs_dir,
|
|
128
|
-
capabilities: manifest.capabilities,
|
|
129
|
-
limits: {
|
|
130
|
-
max_input_rows: limits.max_input_rows,
|
|
131
|
-
max_output_bytes: limits.max_output_bytes,
|
|
132
|
-
max_log_bytes: limits.max_log_bytes,
|
|
133
|
-
},
|
|
134
|
-
timeoutMs: limits.timeout_ms,
|
|
135
|
-
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
136
|
-
}));
|
|
296
|
+
const index = await readRunIndex(writer, session, analysisId, options.signal);
|
|
297
|
+
const next = upsertRun({ ...index, input_fingerprint: snapshot.input_fingerprint }, record);
|
|
298
|
+
await writeRunIndex(writer, session, analysisId, next, options.signal);
|
|
299
|
+
return next;
|
|
137
300
|
}
|
|
138
301
|
catch (error) {
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
const result = validated.result;
|
|
143
|
-
if (result === undefined || !validated.ok) {
|
|
144
|
-
await writeFiles(writer, session, dir, [{
|
|
145
|
-
name: RESULT_FILE,
|
|
146
|
-
content: JSON.stringify({ ok: false, issues: validated.issues, raw: executed.result ?? null }),
|
|
147
|
-
}], { ...(options.signal === undefined ? {} : { signal: options.signal }), overwrite: true, what: '写入失败结果失败' });
|
|
148
|
-
throw new AnalysisError('analysis_output_invalid', `模块 ${manifest.id} 的结果不满足契约:${validated.issues.slice(0, 4).map((issue) => issue.detail).join(';')}`);
|
|
302
|
+
if (required)
|
|
303
|
+
throw error;
|
|
304
|
+
return { schema_version: 2, analysis_id: analysisId, input_fingerprint: snapshot.input_fingerprint, runs: [] };
|
|
149
305
|
}
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
}
|
|
169
|
-
const nextIndex = {
|
|
170
|
-
analysis_id: analysisId,
|
|
171
|
-
input_fingerprint: snapshot.input_fingerprint,
|
|
172
|
-
runs: [...index.runs, record],
|
|
173
|
-
};
|
|
174
|
-
await writeFiles(writer, session, analysisDir(analysisId), [{ name: RUN_FILE, content: JSON.stringify(nextIndex) }], {
|
|
175
|
-
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
176
|
-
overwrite: true,
|
|
177
|
-
what: '写入 run.json 失败',
|
|
178
|
-
});
|
|
179
|
-
return toOutcome(analysisId, moduleRunId, manifest.id, manifest.version, moduleResult, false);
|
|
306
|
+
};
|
|
307
|
+
let terminalRecorded = false;
|
|
308
|
+
const recordTerminal = async (patch) => {
|
|
309
|
+
terminalRecorded = true;
|
|
310
|
+
await writeRecord(terminalRecord(patch), true);
|
|
311
|
+
};
|
|
312
|
+
const terminalRecord = (patch) => ({
|
|
313
|
+
...base,
|
|
314
|
+
runtime: runtimeFacts(identity, patch.pythonVersion),
|
|
315
|
+
status: patch.status,
|
|
316
|
+
queued_at: queuedAt,
|
|
317
|
+
...(patch.startedAt === undefined ? {} : { started_at: patch.startedAt }),
|
|
318
|
+
...(patch.finishedAt === undefined ? {} : { finished_at: patch.finishedAt }),
|
|
319
|
+
...(patch.queueMs === undefined ? {} : { queue_ms: patch.queueMs }),
|
|
320
|
+
...(patch.execMs === undefined ? {} : { exec_ms: patch.execMs }),
|
|
321
|
+
...(patch.error === undefined ? {} : { error: patch.error }),
|
|
322
|
+
...(patch.resultRef === undefined ? {} : { result_ref: patch.resultRef }),
|
|
323
|
+
output_refs: [...(patch.outputRefs ?? [])],
|
|
324
|
+
...(patch.reusedFrom === undefined ? {} : { reused_from: patch.reusedFrom }),
|
|
180
325
|
});
|
|
326
|
+
try {
|
|
327
|
+
return await withSnapshotLock(analysisId, deadline, options.signal, async () => {
|
|
328
|
+
const index = await readRunIndex(writer, session, analysisId, options.signal);
|
|
329
|
+
const reusable = findReusable(index, runFingerprint, manifest);
|
|
330
|
+
if (reusable !== undefined) {
|
|
331
|
+
const stored = await readRunResult(writer, session, analysisId, reusable, options.signal);
|
|
332
|
+
if (stored !== undefined) {
|
|
333
|
+
const reuseRecord = terminalRecord({
|
|
334
|
+
status: reusable.status,
|
|
335
|
+
startedAt: clock(),
|
|
336
|
+
finishedAt: clock(),
|
|
337
|
+
queueMs: 0,
|
|
338
|
+
execMs: 0,
|
|
339
|
+
resultRef: reusable.result_ref,
|
|
340
|
+
outputRefs: reusable.output_refs ?? [],
|
|
341
|
+
reusedFrom: reusable.module_run_id,
|
|
342
|
+
});
|
|
343
|
+
await writeRunIndex(writer, session, analysisId, upsertRun({ ...index, input_fingerprint: snapshot.input_fingerprint }, reuseRecord), options.signal);
|
|
344
|
+
return toOutcome(base, module, stored, reusable.output_refs ?? [], true);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
try {
|
|
348
|
+
throwIfAborted(options.signal);
|
|
349
|
+
}
|
|
350
|
+
catch (error) {
|
|
351
|
+
const analysisError = asRuntimeError(error, manifest.id);
|
|
352
|
+
await recordTerminal({
|
|
353
|
+
status: statusForFlowError(analysisError.code),
|
|
354
|
+
finishedAt: clock(),
|
|
355
|
+
error: { code: analysisError.code, message: analysisError.message },
|
|
356
|
+
});
|
|
357
|
+
throw withRunRef(analysisError, ref);
|
|
358
|
+
}
|
|
359
|
+
let release;
|
|
360
|
+
try {
|
|
361
|
+
release = await acquireAnalysisSlot(deadline, options.signal);
|
|
362
|
+
}
|
|
363
|
+
catch (error) {
|
|
364
|
+
const analysisError = asRuntimeError(error, manifest.id);
|
|
365
|
+
await recordTerminal({
|
|
366
|
+
status: statusForFlowError(analysisError.code),
|
|
367
|
+
finishedAt: clock(),
|
|
368
|
+
error: { code: analysisError.code, message: analysisError.message },
|
|
369
|
+
});
|
|
370
|
+
throw withRunRef(analysisError, ref);
|
|
371
|
+
}
|
|
372
|
+
try {
|
|
373
|
+
const startedAt = clock();
|
|
374
|
+
const request = {
|
|
375
|
+
protocol: ANALYSIS_PROTOCOL,
|
|
376
|
+
task_id: taskId,
|
|
377
|
+
analysis_id: analysisId,
|
|
378
|
+
module_run_id: moduleRunId,
|
|
379
|
+
snapshot_id: analysisId,
|
|
380
|
+
as_of: asOf,
|
|
381
|
+
temporal: {
|
|
382
|
+
mode: temporalMode,
|
|
383
|
+
as_of: asOf,
|
|
384
|
+
...(snapshot.data_cutoff === undefined ? {} : { data_cutoff: snapshot.data_cutoff }),
|
|
385
|
+
},
|
|
386
|
+
inputs,
|
|
387
|
+
params,
|
|
388
|
+
};
|
|
389
|
+
const [requestFile] = await writeFiles(writer, session, runDir, [{ name: REQUEST_FILE, content: JSON.stringify(request) }], {
|
|
390
|
+
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
391
|
+
what: '写入模块请求失败',
|
|
392
|
+
});
|
|
393
|
+
const runDirAbsolute = dirname(requestFile.absolutePath);
|
|
394
|
+
await writeRecord(terminalRecord({
|
|
395
|
+
status: 'running',
|
|
396
|
+
startedAt,
|
|
397
|
+
queueMs: startedAt - queuedAt,
|
|
398
|
+
}), false);
|
|
399
|
+
const limits = { ...MODULE_DEFAULT_LIMITS, ...manifest.limits };
|
|
400
|
+
let executed;
|
|
401
|
+
try {
|
|
402
|
+
executed = await runtime.runAnalysisModule({
|
|
403
|
+
moduleDir: module.dir,
|
|
404
|
+
entrypoint: module.entrypoint,
|
|
405
|
+
runDir: runDirAbsolute,
|
|
406
|
+
inputsDir,
|
|
407
|
+
capabilities: manifest.capabilities,
|
|
408
|
+
limits: {
|
|
409
|
+
max_input_rows: limits.max_input_rows,
|
|
410
|
+
max_output_bytes: limits.max_output_bytes,
|
|
411
|
+
max_log_bytes: limits.max_log_bytes,
|
|
412
|
+
},
|
|
413
|
+
timeoutMs: limits.timeout_ms,
|
|
414
|
+
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
catch (error) {
|
|
418
|
+
const analysisError = asRuntimeError(error, manifest.id);
|
|
419
|
+
await recordTerminal({
|
|
420
|
+
status: statusForFlowError(analysisError.code),
|
|
421
|
+
startedAt,
|
|
422
|
+
finishedAt: clock(),
|
|
423
|
+
queueMs: startedAt - queuedAt,
|
|
424
|
+
execMs: clock() - startedAt,
|
|
425
|
+
error: { code: analysisError.code, message: analysisError.message },
|
|
426
|
+
});
|
|
427
|
+
throw withRunRef(analysisError, ref);
|
|
428
|
+
}
|
|
429
|
+
const validated = validateModuleResult(executed.result, manifest);
|
|
430
|
+
const result = validated.result;
|
|
431
|
+
if (result === undefined || !validated.ok) {
|
|
432
|
+
await writeFiles(writer, session, runDir, [{
|
|
433
|
+
name: RESULT_FILE,
|
|
434
|
+
content: JSON.stringify({ ok: false, issues: validated.issues, raw: executed.result ?? null }),
|
|
435
|
+
}], { ...(options.signal === undefined ? {} : { signal: options.signal }), overwrite: true, what: '写入失败结果失败' }).catch(() => undefined);
|
|
436
|
+
const details = validated.issues.slice(0, 4).map((issue) => issue.detail).join(';');
|
|
437
|
+
const analysisError = new AnalysisError('analysis_output_invalid', `模块 ${manifest.id} 的结果不满足契约:${details}`);
|
|
438
|
+
await recordTerminal({
|
|
439
|
+
status: 'failed',
|
|
440
|
+
startedAt,
|
|
441
|
+
finishedAt: clock(),
|
|
442
|
+
queueMs: startedAt - queuedAt,
|
|
443
|
+
execMs: clock() - startedAt,
|
|
444
|
+
pythonVersion: executed.pythonVersion,
|
|
445
|
+
error: { code: analysisError.code, message: analysisError.message },
|
|
446
|
+
});
|
|
447
|
+
throw withRunRef(analysisError, ref);
|
|
448
|
+
}
|
|
449
|
+
const moduleResult = result;
|
|
450
|
+
await writeFiles(writer, session, runDir, [{
|
|
451
|
+
name: RESULT_FILE,
|
|
452
|
+
content: JSON.stringify({
|
|
453
|
+
ok: true,
|
|
454
|
+
python: executed.pythonVersion,
|
|
455
|
+
duration_ms: executed.durationMs,
|
|
456
|
+
result: moduleResult,
|
|
457
|
+
}),
|
|
458
|
+
}], { ...(options.signal === undefined ? {} : { signal: options.signal }), overwrite: true, what: '写入模块结果失败' });
|
|
459
|
+
const outputRefs = outputRefsOf(moduleResult, analysisId, moduleRunId);
|
|
460
|
+
const finishedAt = clock();
|
|
461
|
+
await writeRunIndex(writer, session, analysisId, upsertRun({ ...index, input_fingerprint: snapshot.input_fingerprint }, terminalRecord({
|
|
462
|
+
status: moduleResult.status,
|
|
463
|
+
startedAt,
|
|
464
|
+
finishedAt,
|
|
465
|
+
queueMs: startedAt - queuedAt,
|
|
466
|
+
execMs: finishedAt - startedAt,
|
|
467
|
+
pythonVersion: executed.pythonVersion,
|
|
468
|
+
resultRef,
|
|
469
|
+
outputRefs,
|
|
470
|
+
})), options.signal);
|
|
471
|
+
return toOutcome(base, module, moduleResult, outputRefs, false);
|
|
472
|
+
}
|
|
473
|
+
finally {
|
|
474
|
+
release();
|
|
475
|
+
}
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
catch (error) {
|
|
479
|
+
if (terminalRecorded)
|
|
480
|
+
throw error;
|
|
481
|
+
// The lock itself can fail before the callback runs (pre-abort, queue timeout on the snapshot
|
|
482
|
+
// tail); that run still owes the index a terminal row.
|
|
483
|
+
const analysisError = asRuntimeError(error, manifest.id);
|
|
484
|
+
await recordTerminal({
|
|
485
|
+
status: statusForFlowError(analysisError.code),
|
|
486
|
+
finishedAt: clock(),
|
|
487
|
+
error: { code: analysisError.code, message: analysisError.message },
|
|
488
|
+
});
|
|
489
|
+
throw withRunRef(analysisError, ref);
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
function workspaceRelative(analysisId, moduleRunId) {
|
|
493
|
+
return moduleRunDir(analysisId, moduleRunId);
|
|
181
494
|
}
|
|
182
|
-
|
|
495
|
+
/** Reuse is opt-in per status: a failed run is never reused, partial/blocked only when declared. */
|
|
496
|
+
function findReusable(index, runFingerprint, manifest) {
|
|
497
|
+
const allowed = new Set([
|
|
498
|
+
'completed',
|
|
499
|
+
...(manifest.reuse.allow_partial ? ['partial'] : []),
|
|
500
|
+
...(manifest.reuse.allow_blocked ? ['blocked'] : []),
|
|
501
|
+
]);
|
|
502
|
+
for (let position = index.runs.length - 1; position >= 0; position -= 1) {
|
|
503
|
+
const record = index.runs[position];
|
|
504
|
+
if (record.run_fingerprint !== runFingerprint)
|
|
505
|
+
continue;
|
|
506
|
+
if (!allowed.has(record.status))
|
|
507
|
+
continue;
|
|
508
|
+
if (record.result_ref === undefined)
|
|
509
|
+
continue;
|
|
510
|
+
return record;
|
|
511
|
+
}
|
|
512
|
+
return undefined;
|
|
513
|
+
}
|
|
514
|
+
async function readRunResult(writer, session, analysisId, record, signal) {
|
|
515
|
+
const path = record.result_ref === undefined
|
|
516
|
+
? `${workspaceRelative(analysisId, record.module_run_id)}/${RESULT_FILE}`
|
|
517
|
+
: `${analysisDir(analysisId)}/${record.result_ref}`;
|
|
518
|
+
const stored = await readJsonFile(writer, session, path, signal);
|
|
519
|
+
if (stored?.result === undefined)
|
|
520
|
+
return undefined;
|
|
521
|
+
return stored.result;
|
|
522
|
+
}
|
|
523
|
+
function outputRefsOf(result, analysisId, moduleRunId) {
|
|
524
|
+
const outputs = Array.isArray(result.outputs) ? result.outputs : [];
|
|
525
|
+
return outputs
|
|
526
|
+
.map((output) => (typeof output?.name === 'string' && output.name !== '' ? `analysis_output:${analysisId}/${moduleRunId}/${output.name}` : undefined))
|
|
527
|
+
.filter((item) => item !== undefined);
|
|
528
|
+
}
|
|
529
|
+
function boundedMethodology(result) {
|
|
530
|
+
const lines = Array.isArray(result.methodology_log) ? result.methodology_log.filter((line) => typeof line === 'string') : [];
|
|
531
|
+
return lines.slice(0, 4).map((line) => (line.length > 240 ? `${line.slice(0, 239)}…` : line));
|
|
532
|
+
}
|
|
533
|
+
function toOutcome(base, module, result, outputRefs, reused) {
|
|
183
534
|
const issues = result.status === 'failed' ? [{ code: 'analysis_module_failed', detail: result.summary }] : [];
|
|
184
535
|
return {
|
|
185
|
-
analysis_run_ref: runRef(
|
|
186
|
-
module_id:
|
|
187
|
-
module_version:
|
|
536
|
+
analysis_run_ref: runRef(base.analysis_id, base.module_run_id),
|
|
537
|
+
module_id: module.manifest.id,
|
|
538
|
+
module_version: module.manifest.version,
|
|
539
|
+
module_code_hash: base.module_code_hash,
|
|
188
540
|
status: result.status,
|
|
189
541
|
summary: typeof result.summary === 'string' ? result.summary : '',
|
|
190
542
|
metrics: (result.metrics ?? {}),
|
|
191
543
|
assumptions: result.assumptions ?? [],
|
|
544
|
+
methodology: boundedMethodology(result),
|
|
192
545
|
limitations: result.limitations ?? [],
|
|
193
546
|
data_gaps: result.data_gaps ?? [],
|
|
547
|
+
output_refs: [...outputRefs],
|
|
548
|
+
sensitivity: (result.sensitivity ?? {}),
|
|
549
|
+
...(result.simulation === undefined ? {} : { simulation: result.simulation }),
|
|
550
|
+
...(result.event_study === undefined ? {} : { event_study: result.event_study }),
|
|
194
551
|
validation: { status: issues.length === 0 ? 'pass' : 'warning', issues },
|
|
195
552
|
reused,
|
|
196
553
|
};
|
|
@@ -217,9 +574,21 @@ function asRuntimeError(error, moduleId) {
|
|
|
217
574
|
}
|
|
218
575
|
return new AnalysisError('analysis_output_invalid', `模块 ${moduleId} 执行失败:${message}`);
|
|
219
576
|
}
|
|
220
|
-
async function readRunIndex(writer, session, analysisId, signal) {
|
|
577
|
+
export async function readRunIndex(writer, session, analysisId, signal) {
|
|
221
578
|
const stored = await readJsonFile(writer, session, `${analysisDir(analysisId)}/${RUN_FILE}`, signal);
|
|
222
579
|
if (stored === undefined)
|
|
223
580
|
return { analysis_id: analysisId, input_fingerprint: '', runs: [] };
|
|
224
|
-
return {
|
|
581
|
+
return {
|
|
582
|
+
...(stored.schema_version === 2 ? { schema_version: 2 } : {}),
|
|
583
|
+
analysis_id: analysisId,
|
|
584
|
+
input_fingerprint: stored.input_fingerprint ?? '',
|
|
585
|
+
runs: Array.isArray(stored.runs) ? stored.runs : [],
|
|
586
|
+
};
|
|
587
|
+
}
|
|
588
|
+
export async function writeRunIndex(writer, session, analysisId, index, signal) {
|
|
589
|
+
await writeFiles(writer, session, analysisDir(analysisId), [{ name: RUN_FILE, content: JSON.stringify(index) }], {
|
|
590
|
+
...(signal === undefined ? {} : { signal }),
|
|
591
|
+
overwrite: true,
|
|
592
|
+
what: '写入 run.json 失败',
|
|
593
|
+
});
|
|
225
594
|
}
|