feat(PR-03): execution controller, cancellable process adapter and budgets

- add src/execution/{request,process,controller,events}.rs implementing RFC-0002
  §6.3 request validation, function_id->CLI name resolution, single-job
  lifecycle, dedupe by client_request_id+payload digest, 409 busy/conflict,
  unique terminal states, idempotent cancel and Trace v2 binding against the
  exact pre-run Analysis bytes
- route all Core subprocess spawning through one bounded, cancelable adapter
  with process-group TERM->2s->KILL, spawn hook, 4 MiB output caps and explicit
  --fuel/--max-output/--timeout/trace budgets; CoreClient check/--version reuse it
- add marqdo.view-run-events v1 event log: 128 frame ring, Last-Event-ID replay
  or authoritative snapshot, numeric seq/id, heartbeat constant
- add bounded --run-timeout (default 30s, max 120s
- add ADR-0008 (lifecycle/cancel race/trace-missing semantics) and PR-03
  evidence; execution tests use a real fake-Core executable
- unit 58 + contract 41 + integration 42 pass; clippy clean
This commit is contained in:
cflmy committed 2026-11-22 13:39:17 +08:00
1 parent 5c9a313424
commit e13c1828a4
23 files changed
+3312 -158

No files matched your search

+22 -1
View File
@@ -6,6 +6,27 @@ Protocol axes (Tool v1, Analysis v2, Trace v2) are versioned separately.
## [Unreleased]
### Added (RFC-VIEW-0002 PR-03)
- Execution layer: `src/execution/{request,process,controller,events}.rs`.
- request validation per §6.3 (size/path/target/parameter/mode/fs grants) and
exact `function_id` -> CLI name resolution from Analysis v2;
- one cancellable process adapter (explicit argv, process group,
SIGTERM→2s→SIGKILL, bounded stdout/stderr, spawn hook, wall clock); the
CoreClient now uses the same adapter for `check`/`--version`;
- single active job, `client_request_id` + payload digest idempotency/409,
unique terminal states, cancellation, 128-event ring buffer with
`Last-Event-ID` replay/snapshot, and `marqdo.view-run-events` v1 frames;
- Trace v2 verification against the exact pre-run Analysis bytes with safe
event summaries; missing/invalid trace is reported without faking evidence.
- Explicit budgets on every run/call (`--fuel`, `--max-output`, `--timeout`,
trace limits) plus 4 MiB JSON/Trace bounded reads and `view.output_limit`.
- New `--run-timeout` option clamped to 1..=120 seconds (default 30).
- ADR-0008 records lifecycle/cancel-race/Trace-missing semantics.
- Tests: `tests/integration/execution.rs` with a real fake-Core executable
(accepted/running/terminal SSE-ready events, call argv, dedupe, busy, cancel,
session isolation, stale digest, grants, unavailable trace).
### Changed (RFC-VIEW-0002 PR-02)
- Restructured the crate into the RFC-VIEW-0002 §5.3 layout: `src/protocol/
@@ -115,7 +136,7 @@ Protocol axes (Tool v1, Analysis v2, Trace v2) are versioned separately.
search, settings, 7 viewport widths without horizontal overflow or dock
clipping, no-JS reading, print mode, explicit run + clear.
- Screenshot evidence for the Welcome page (1664×920, 390×844) and a real
Trace run page in `docs/evidence/PR-03/`.
Trace run page in `docs/evidence/0001-pr03/`.
- Meta CSP no longer carries the ignored `frame-ancestors` directive (the HTTP
header still enforces framing).
+1 -1
View File
@@ -48,7 +48,7 @@
| ID | 结果 | 说明 |
|---|---|---|
| U-01 1664×920 视觉 | **PARTIAL** | 截图已采集(`docs/evidence/PR-03/`),几何/颜色令牌/无溢出/无外部资源 PASS;与参考截图的**像素级人工比对未执行(UNVERIFIED)** |
| U-01 1664×920 视觉 | **PARTIAL** | 截图已采集(`docs/evidence/0001-pr03/`),几何/颜色令牌/无溢出/无外部资源 PASS;与参考截图的**像素级人工比对未执行(UNVERIFIED)** |
| U-02 多宽度 | PASS | 390/600/900/1280/1664/1920/2560 真实 Chromium:无横向溢出、Dock 在视口内 |
| U-03 键盘/焦点/屏幕阅读器 | PASS(基础) | Tab 可达命名控件、Esc 关闭、Ctrl/Cmd+K 搜索;完整 screen-reader 手工走查未做 |
| U-04 动态曲线侧注 | **PARTIAL** | 运行事件使用**内联 keyed chip**(无 JS/移动/打印均可读);SVG 曲线侧注未实现,不画错线 |
+10 -10
View File
@@ -59,14 +59,14 @@
| 条款 | 状态 | 计划 |
|---|---|---|
| 7 条最小路由 | **PENDING** | PR-04 |
| POST /api/runs 两阶段确认请求体(document/target/parameters/analysis_digest/mode/grants/client_request_id) | **PENDING** | PR-03/04 |
| 校验顺序(会话→CSRF/Origin/Host→大小/schema→containment→check→digest→函数/参数→模式/grants→并发→202) | **PENDING** | PR-03/04 |
| 同 `client_request_id` 幂等/不同 payload 409 | **PENDING** | PR-04 |
| POST /api/runs 两阶段确认请求体(document/target/parameters/analysis_digest/mode/grants/client_request_id) | PARTIAL | `execution/request.rs` 校验/解析/计划已实现;HTTP 路由 PR-04 |
| 校验顺序(会话→CSRF/Origin/Host→大小/schema→containment→check→digest→函数/参数→模式/grants→并发→202) | PARTIAL | Controller 已实现 schema→dedupe→busy→check→digest→target→202;HTTP 前置校验 PR-04 |
| 同 `client_request_id` 幂等/不同 payload 409 | PASS(Controller) | `tests/integration/execution.rs`;HTTP 映射 PR-04 |
| SSE 帧合同(事件类型/seq/id/schema/心跳) | **PENDING** | PR-04 |
| Last-Event-ID 重放、快照、128 缓冲、TTL、≤2 连接/任务 | **PENDING** | PR-04 |
| 单活动任务、409 run.busy、后台执行不阻塞 SSE | **PENDING** | PR-03/04 |
| 进程组取消(TERM→2s→KILL)、墙钟上限、有界输出 | **PENDING** | PR-03 |
| 显式预算参数 | **PENDING** | PR-03 |
| 单活动任务、409 run.busy、后台执行不阻塞 SSE | PARTIAL | Controller 单任务/后台线程已实现并测试;HTTP/SSE PR-04 |
| 进程组取消(TERM→2s→KILL)、墙钟上限、有界输出 | PASS(模块) | `src/execution/process.rs`、`tests/integration/execution.rs` |
| 显式预算参数 | PASS(模块) | `src/execution/controller.rs`、`--run-timeout` 1..=120 |
| 会话 Cookie(HttpOnly/SameSite=Strict)+ X-View-CSRF + Origin/Host | **PENDING** | PR-04 |
| loopback only、请求体≤64KiB、CSP、路径 containment | PARTIAL | 大部分已有;会话 Cookie 待 PR-04 |
| SSE 按会话隔离、跨站读取拒绝 | **PENDING** | PR-04 |
@@ -78,7 +78,7 @@
| PR-00 取证/基线 | **完成** | 待提交(本提交) |
| PR-01 Tool/打包/scripts/CI/0.2.0 | **完成** | `scripts/package.sh`、`scripts/install-smoke.sh`、`scripts/verify-frozen-cli.sh`、`.github/workflows/ci.yml` |
| PR-02 Reader/Analysis 结构与只读路由 | **完成** | `src/protocol/*`、`src/reader/*`、`src/config.rs`、`/api/documents`、`tests/{contract,integration}`;`docs/evidence/PR-02/` |
| PR-03 执行层/请求/进程/控制器 | PENDING | — |
| PR-03 执行层/请求/进程/控制器 | **完成** | `src/execution/*`、ADR-0008、`docs/evidence/PR-03/` |
| PR-04 SSE/路由/会话/前端闭环 | PENDING | — |
| PR-05 Trace 绑定/标注/浏览器回归 | PENDING | — |
| PR-06 导出/发布/文档闭环 | PENDING | — |
@@ -92,14 +92,14 @@
| E03 Source/Document 切换 | PASS | 浏览器证据 |
| E04 中文/Emoji/表格/公式 span | PASS | `tests/integration/unicode_spans.rs`、golden |
| E05 main 运行 run --json --trace-file | PARTIAL | 同步路径有;SSE 终态待 PR-04 |
| E06 H2 Exec n=5 call | **PENDING** | PR-03/04 |
| E07 文本/列表常量参数 | **PENDING** | PR-03/04 |
| E06 H2 Exec n=5 call | PARTIAL | `build_call_args` + Controller 测试;真实 CLI/UI PR-04/06 |
| E07 文本/列表常量参数 | PARTIAL | `--arg name=expression` argv 已实现;真实 CLI/UI PR-04/06 |
| E08 无 main 不自动运行别的函数 | PARTIAL | 现有 `can_offer_run` 逻辑;PR-04 复核 |
| E09 Trace 事件映射不伪造变量 | PARTIAL | `src/trace.rs`;SSE 后复核 |
| E10 SSE text/event-stream 无 polling | **PENDING** | PR-04 |
| E11 Last-Event-ID 重连 | **PENDING** | PR-04 |
| E12 长任务心跳/GET 不重启 | **PENDING** | PR-04 |
| E13 取消终止进程树 | **PENDING** | PR-03/04 |
| E13 取消终止进程树 | PARTIAL | Controller/process 已测(`second_run_is_busy...`、`process.rs` 单测);HTTP 接线 PR-04 |
| E14 静态导出零联网/相对链接 | PARTIAL | 已实现;PR-06 复核 |
| E15 刷新/重开不自动执行 | PASS | `tests/integration/http_live.rs` |
| E16 运行后改源码 → stale 无高亮 | PARTIAL | 现有 stale;PR-05 复核 |
+11 -8
View File
@@ -23,7 +23,7 @@
| PR-00 基线、旧 View 取证、冻结 CLI 合同 | **完成** | `docs/audits/legacy-view.md`、`docs/audits/protocol-contract-0002.md`、`docs/decisions/0007` |
| PR-01 Tool v1 打包/安装/调度、0.2.0、scripts/、CI | **完成** | `scripts/package.sh`、`scripts/install-smoke.sh`、`scripts/verify-frozen-cli.sh`、`.github/workflows/ci.yml`;冻结 CLI `tool install`/`view --help`/篡改拒绝实测 |
| PR-02 Reader/Analysis 只读面与目标目录结构 | **完成** | `src/protocol/*`、`src/reader/*`、`src/config.rs`、`tests/{contract,integration}/`、`/api/documents`;证据 `docs/evidence/PR-02/` |
| PR-03 执行层:request/process/controller、pure + project grants | 待开始(现有同步 `pure` 执行可迁移) | `src/core_client.rs`、`src/app.rs` |
| PR-03 执行层:request/process/controller、pure + project grants | **完成** | `src/execution/{request,process,controller,events}.rs`、`--run-timeout`、ADR-0008、`tests/integration/execution.rs`;证据 `docs/evidence/PR-03/` |
| PR-04 SSE 任务生命周期、取消、7 路由、会话 Cookie/CSRF | **未实现(MVP 阻塞项)** | — |
| PR-05 Trace 绑定/原文标注/浏览器回归 | 待开始(现有 Trace 校验可迁移) | `src/trace.rs` |
| PR-06 静态导出/发布包/文档闭环 | 待开始(现有导出可迁移) | `src/export.rs` |
@@ -37,7 +37,7 @@
| 原始 Markdown/GFM 阅读、源码态、搜索/设置/打印 | 已实现(单一 `assets/reader.css`/`assets/reader.js`) |
| Analysis v2 严格校验、函数/Unit/签名/诊断/导入/引用/资源投影 | 已实现(无效 span 降级) |
| 单一 `ReaderRenderer`,Live/Export 共用 | 已实现(`src/reader/render.rs`,门禁测试) |
| 显式确认后同步运行 `pure` + Trace v2 校验与展示 | 已实现,但**不是 0002 的异步 SSE 闭环** |
| 显式确认后同步运行 `pure` + Trace v2 校验与展示 | 旧同步路径仍在(过渡);新的异步 Controller/SSE 就绪于 PR-03/04 |
| 静态离线导出(无执行、manifest/哈希、原子发布) | 已实现,待按 0002 重新验收 |
| Tool v1 打包/安装/分发、冻结 CLI SHA 前后一致 | 已实现,待迁移至 `scripts/` 与 0.2.0 |
| HTTP 安全(Host/Origin/CSRF/路径 containment/CSP) | 部分实现;缺**会话 Cookie**模型与 7 路由合同 |
@@ -57,12 +57,15 @@
4. **无 project grants**:0002 要求受控 fs read/write glob(明确二次确认),
其它 net/process/env/plugin 一律拒绝并引导 CLI。
5. **无运行会话 Cookie**:CSRF 目前是进程级 token;0002 要求
`HttpOnly; SameSite=Strict` 随机会话 Cookie + 每会话 CSRF,且 SSE 按会话隔离。
6. **无取消/单任务状态机/重复请求去重**:缺 `cancel_requested`、唯一终态、
`client_request_id` 幂等/409、409 run.busy。
7. **执行预算未按 0002**:默认 30s(最大 120s)、`--fuel 1000000`、
`--max-output 1048576`、`--trace-max-events 10000`、`--trace-max-bytes 4194304`、
JSON/Trace/日志 4 MiB 有界读取与 `view.output_limit` 未实现。
`HttpOnly; SameSite=Strict` 随机会话 Cookie + 每会话 CSRF,且 SSE 按会话隔离
(PR-04)。
6. **HTTP/SSE 传输未接**:Controller 已实现单任务状态机、取消、去重、
`client_request_id` 幂等/409 与 `409 run.busy`(`src/execution/controller.rs`),
但 `POST /api/runs`、`GET .../events`、`POST .../cancel` 与前端尚未切换(PR-04)。
7. **执行预算**:Controller 已显式发送 `--timeout`(默认 30s/最大 120s)、
`--fuel 1000000`、`--max-output 1048576`、`--trace-max-events 10000`、
`--trace-max-bytes 4194304`,并做 4 MiB JSON/Trace 有界读取与
`view.output_limit`;HTTP 层仍需映射为终态事件(PR-04)。
8. **目录/测试/示例仍有缺口**:`src/protocol`/`src/reader`/`src/config.rs`/
`tests/{contract,integration}`/`scripts/`/`.github/workflows/ci.yml` 已就位;
仍缺 `src/execution/*`、`src/server/{mod,routes,security,sse}.rs`、
@@ -0,0 +1,68 @@
# ADR-0008:单任务执行生命周期、取消竞态与 Trace 缺失语义
- 状态:Accepted
- 日期:2026-11-22
- 关联:`docs/architecture/RFC-VIEW-0002.md` §6.3–§6.7;PR-03/PR-04
本 ADR 固定 RFC 留给实现选择的几个边界,避免后续 UI/测试出现两套解释。
## 1. 单活动任务与接受顺序
- 每个 View 服务进程**最多 1 个活动 CLI 任务**;第二个请求返回 `409 run.busy`
(`view.run_busy`),不排队、不并发执行。
- `POST /api/runs` 的接受顺序:schema/大小/路径 → `client_request_id` 去重 →
单任务门禁 → **只读 `check --emit` + Analysis 字节摘要比对** → 目标/参数解析 →
创建 `accepted` 任务 → 后台线程 → `202`。
- 去重键是 `client_request_id` + **原始请求体字节的 SHA-256**:
- 相同 ID + 相同字节 → 返回同一 `run_id`(`reused=true`),**不启动第二次进程**;
- 相同 ID + 不同字节 → `409 Conflict`(`view.run_conflict`);
- ID 对应任务已过 TTL → 明确错误(`view.run_invalid`),不默认重跑。
- 去重/活动任务/任务表由同一个 Controller 锁保护;静态 `check` 在锁内完成,
保证两个并发请求不会同时越过单任务门禁。`check` 不执行目标程序。
## 2. 状态机与终态唯一性
- 状态:`accepted → running → {succeeded, failed, cancelled, timed_out}`,
`cancel_requested` 不是终态,`unavailable` 仅表示进程无法启动/环境不可用。
- `running` 只在内核进程**成功 spawn 之后**发布(进程适配器提供 spawn hook)。
- 终态由 Controller 在线程内、持有 job 锁时发布;发布前检查 `log.terminal()`,
所以任何任务最多一个终态事件。取消/超时/自然退出竞态都走同一路径。
## 3. 取消与退出竞态
- 取消 = 幂等 POST 设置取消标志并发布 `cancel_requested`;执行线程负责终止
进程组(先 SIGTERM,约 2s 后 SIGKILL)与唯一终态。
- 若进程在取消请求后自然退出:
- 退出码为 0 且 `--json.success=true` → 允许 `succeeded`(RFC §6.6 竞态条款);
- 其他情况(被信号终止、非零退出、JSON 缺失/失败)→ `cancelled`。
- 这一判断依赖“取消请求”标志而非仅依赖适配器是否发出了 SIGKILL,因为
SIGTERM 可能在 2s 宽限期内就让进程退出。
- 页面关闭/SSE 断开**不取消**任务;取消只能显式 POST。
## 4. Trace 缺失/无效与运行成功的关系
- 运行成功与否以 CLI `--json.success` + 进程退出状态为准;`trace_status` 独立:
- `verified`:Trace v2 通过 `analysis_digest`/`root_id`/`module_id`/span 校验;
- `unavailable`:CLI 未写 trace(例如失败路径或未请求);
- `invalid`:Trace 存在但 schema/摘要/事件绑定不合法。
- **Trace 缺失或 invalid 不把成功运行改判为失败**,但 UI 必须明确显示
“Trace 不可用/无效”,不得绘制执行侧注、不得伪造事件,也不得宣称完整观测。
- 运行后源码字节变化 → 结果 `stale=true`,Trace 即使曾校验通过也不得锚定当前
正文;前端仍可显示结果,但标注失效。
## 5. 预算与有界性
- 入口固定预算:`--timeout`=View 墙钟(默认 30s,最大 120s,`--run-timeout`
可配置且与 Core 参数一致)、`--fuel 1000000`、`--max-output 1048576`、
`--trace-max-events 10000`、`--trace-max-bytes 4194304`。
- View 侧再限制:stdout/JSON ≤4 MiB、stderr 保留 ≤64 KiB(继续排空管道避免
子进程阻塞)、Trace 文件 ≤4 MiB;超限以 `view.output_limit` 失败终态报告。
- 每次执行使用独立 0700 临时目录,Trace 读出后随临时目录删除;项目目录中不写
`.view-*` 运行产物。
## 6. 事件日志与 SSE
- 每任务事件日志保留最近 128 条 + 终态快照;序号严格递增,SSE `id` 与
`data.seq` 一致;心跳是注释不占序号。
- 快照使用**新的序号**(不重复旧 id),保证客户端去重逻辑不会误丢弃快照。
- 这些决定在 PR-04 的 HTTP/SSE 层消费;Controller 本身不实现 HTTP 轮询。
+23
View File
@@ -0,0 +1,23 @@
# PR-03 浏览器视觉验收证据
- 采集环境:Chromium Headless Shell 131(Playwright 1.49.0),Linux x86_64,
视口见文件名;真实冻结核心 `marqdo 3.0.0-beta.1`
(SHA-256 `062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f`)。
- 采集脚本:`tests/browser/reader.browser.cjs`,入口 `tools/test-browser.sh`。
- 断言范围(全部 PASS):单一 CSS/单一 script、无外部网络请求、无 console 错误、
文档/源码切换、搜索、设置字号与标注显隐、7 个宽度(390/600/900/1280/1664/
1920/2560)无横向溢出且 Dock 在视口内、无 JS 可读、打印隐藏交互栏、显式运行
确认后展示真实 Trace 与内联 chip、清理结果。
| 文件 | 说明 |
|---|---|
| `welcome-1664x920.png` | 显式 `view.json` Welcome 页,1664×920(与基准截图同尺寸),无运行 |
| `welcome-390x844.png` | 同一页面 390×844 单栏布局 |
| `control-flow-run-1664x920.png` | `examples/control-flow` 用户确认运行后的真实 Trace v2 运行面板与内联事件 chip |
## 诚实限制
- 未做与 `docs/design/reference-old-view-reader.png` 的像素差分:本环境无法进行
人工视觉判读,`U-01` 只声明“DOM/几何/字体栈/颜色令牌/无溢出/无外部资源”通过,
像素级视觉相似度标记为 **UNVERIFIED(人工复核待办)**,不以自动化 PASS 代替。
- 截图是证据,不是新的渲染路径:页面仍由唯一 `ReaderRenderer` 生成。
File renamed without changes.

Before

Width:  |  Height:  |  Size: 100 KiB

After

Width:  |  Height:  |  Size: 100 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 174 KiB

After

Width:  |  Height:  |  Size: 174 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 98 KiB

After

Width:  |  Height:  |  Size: 98 KiB

+54 -18
View File
@@ -1,23 +1,59 @@
# PR-03 浏览器视觉验收证据
# PR-03 证据:执行层(request / process / controller / events)
- 采集环境:Chromium Headless Shell 131(Playwright 1.49.0),Linux x86_64,
视口见文件名;真实冻结核心 `marqdo 3.0.0-beta.1`
(SHA-256 `062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f`)。
- 采集脚本:`tests/browser/reader.browser.cjs`,入口 `tools/test-browser.sh`。
- 断言范围(全部 PASS):单一 CSS/单一 script、无外部网络请求、无 console 错误、
文档/源码切换、搜索、设置字号与标注显隐、7 个宽度(390/600/900/1280/1664/
1920/2560)无横向溢出且 Dock 在视口内、无 JS 可读、打印隐藏交互栏、显式运行
确认后展示真实 Trace 与内联 chip、清理结果。
- 日期:2026-11-22
- 范围:`src/execution/{request,process,controller,events}.rs`、`core_client` 单一进程
适配器、`--run-timeout`、`DocumentService::static_document`
- 冻结 CLI:`marqdo 3.0.0-beta.1`(`062cb56e…`);本 PR 只用假核心做确定性进程级
测试,PR-04/06 再用真实冻结 CLI 做端到端验收
- 说明:本 PR **不切换 HTTP 运行路由**;`POST /api/run`(同步旧路径)暂留到
PR-04 被 7 路由 + SSE 替换。
| 文件 | 说明 |
## 1. 实现结构
```
src/execution/
request.rs # §6.3 请求 schema/大小/路径/mode/grants/参数名校验;
# function_id -> CLI 名称(canonical 或唯一 local name)
process.rs # 唯一子进程适配器:argv 数组、独立进程组、SIGTERM→2s→SIGKILL、
# 有界 stdout/stderr(继续排空避免死锁)、spawn hook、墙钟
events.rs # RunState 状态机、run.* 事件、128 环形缓冲、Last-Event-ID 重放/
# 快照、SSE 帧、心跳常量
controller.rs # 单任务门禁、去重、静态 check+digest 比对、后台执行、
# Trace 校验投影、取消、终态唯一性、TTL 清理
```
`core_client` 的 `check`/`--version` 也改为走 `process::run_bounded`,因此
View 只有**一个**子进程实现;`build_run_args`/`build_call_args` 是唯一 argv 构造点。
## 2. 关键测试(`tests/integration/execution.rs`,假核心真实进程)
| 测试 | 断言 |
|---|---|
| `welcome-1664x920.png` | 显式 `view.json` Welcome 页,1664×920(与基准截图同尺寸),无运行 |
| `welcome-390x844.png` | 同一页面 390×844 单栏布局 |
| `control-flow-run-1664x920.png` | `examples/control-flow` 用户确认运行后的真实 Trace v2 运行面板与内联事件 chip |
| `explicit_entry_run_streams_accepted_running_and_succeeded_with_verified_trace` | 事件序号递增;accepted/running/succeeded;Trace `verified`、事件非空、`stale=false`、stdout 来自 CLI JSON |
| `call_target_uses_the_call_subcommand_and_function_name` | argv 为 `call FILE <name>`;FUNCTION 名称由 function_id 精确解析 |
| `same_client_request_id_is_idempotent_and_different_payload_conflicts` | 同 ID 同 body → 同 `run_id`(reused);不同 body → `view.run_conflict` |
| `second_run_is_busy_while_one_is_active_and_cancel_is_idempotent` | 第二任务 `view.run_busy`;取消幂等;终态唯一 `cancelled`;<10s 结束 |
| `cross_session_observation_is_rejected` | 其他会话订阅/取消 → `view.run_not_found` |
| `stale_analysis_digest_is_rejected_before_any_process_starts` | digest 不符 → `view.run_invalid`,假核心无 run 调用 |
| `project_grants_are_mapped_to_explicit_cli_flags_and_pure_grants_are_rejected` | project 请求 argv 有 `--mode project`/`--allow-read`/`--allow-write`;pure+grants 被拒 |
| `run_without_a_trace_file_succeeds_but_reports_unavailable_trace` | 成功 + `trace=null` + `trace_status=unavailable`,不伪造 |
| `event_frames_use_the_view_run_events_schema_and_numeric_ids` | `marqdo.view-run-events` v1、run_id/seq 一致 |
| 单元测试(events/process/request) | 环形缓冲截断→快照、seq/id 一致、取消终止进程组、glob/参数/包络校验 |
## 诚实限制
## 3. 实测命令与结果
- 未做与 `docs/design/reference-old-view-reader.png` 的像素差分:本环境无法进行
人工视觉判读,`U-01` 只声明“DOM/几何/字体栈/颜色令牌/无溢出/无外部资源”通过,
像素级视觉相似度标记为 **UNVERIFIED(人工复核待办)**,不以自动化 PASS 代替。
- 截图是证据,不是新的渲染路径:页面仍由唯一 `ReaderRenderer` 生成。
```bash
cargo fmt --all -- --check
cargo clippy --all-targets --offline -- -D warnings
cargo test --locked --offline
```
结果:unit 58 + contract 41 + integration 42 = **141 passed / 0 failed**。
`--run-timeout` 限制在 1..=120 秒,默认 30 秒(`tests/contract/cli_surface.rs`)。
## 4. 明确未完成
- HTTP 路由/SSE 传输/session Cookie 属于 PR-04;当前 Controller 已提供
`submit/subscribe/cancel/job_state`,但未暴露公共状态轮询路由。
- 前端函数参数表单与运行区仍在 PR-04 切换;旧同步 `/api/run` 在此期间仍是过渡实现。
- 真实冻结 CLI 的 run/call/Trace 端到端证据在 PR-04/PR-06 记录(本 PR 不冒称)。
+21
View File
@@ -41,6 +41,16 @@ pub struct Cli {
#[arg(long, global = true)]
pub no_open: bool,
/// Wall-clock limit for one explicit run, in seconds (RFC-VIEW-0002 §6.7).
/// The frozen Core receives the same value via `--timeout`.
#[arg(
long,
default_value_t = 30,
global = true,
value_parser = clap::value_parser!(u64).range(1..=120)
)]
pub run_timeout: u64,
/// Advanced: allow a non-loopback bind. No execution API is opened by it.
#[arg(long, global = true, hide = true)]
pub unsafe_expose: bool,
@@ -97,6 +107,7 @@ pub struct RuntimeOpts {
pub port: u16,
pub no_open: bool,
pub unsafe_expose: bool,
pub run_timeout_secs: u64,
}
impl Cli {
@@ -108,6 +119,7 @@ impl Cli {
port: self.port,
no_open: self.no_open,
unsafe_expose: self.unsafe_expose,
run_timeout_secs: self.run_timeout,
}
}
}
@@ -141,6 +153,7 @@ mod tests {
assert!(cli.command.is_none());
assert_eq!(cli.host, "127.0.0.1");
assert_eq!(cli.port, 7429);
assert_eq!(cli.run_timeout, 30);
}
#[test]
@@ -187,6 +200,14 @@ mod tests {
}
}
#[test]
fn run_timeout_is_bounded_to_rfc_range() {
assert!(Cli::try_parse_from(["marqdo-view", "--run-timeout", "0"]).is_err());
assert!(Cli::try_parse_from(["marqdo-view", "--run-timeout", "121"]).is_err());
let cli = Cli::parse_from(["marqdo-view", "--run-timeout", "45"]);
assert_eq!(cli.runtime().run_timeout_secs, 45);
}
#[test]
fn bind_policy_is_loopback_by_default() {
assert!(validate_bind("127.0.0.1", false).is_ok());
+67 -114
View File
@@ -10,15 +10,14 @@
//! drop.
use crate::error::{ViewError, ViewResult};
use crate::execution::process::{run_bounded, ProcessBudget};
use crate::protocol::tool_v1::{self, CoreVersion};
use crate::reader::source::{sha256_hex, sha256_prefixed};
use crate::reader::source::{Project, SafeRelativePath};
use serde::{Deserialize, Serialize};
use std::ffi::OsString;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use std::time::Duration;
/// Default View-level wall clock cap for one Core `run`.
pub const DEFAULT_RUN_TIMEOUT: Duration = Duration::from_secs(120);
@@ -433,75 +432,27 @@ impl CoreClient {
})
}
/// Spawn the core with an explicit argv, private cwd and a wall-clock cap.
/// Spawn the core through the single process adapter with an explicit
/// argv, private cwd, bounded capture and a wall-clock cap.
fn execute(&self, args: &[OsString], cwd: &Path, timeout: Duration) -> ViewResult<ExecOutput> {
let mut command = Command::new(&self.bin);
command
.args(args)
.current_dir(cwd)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
// Put the core in its own process group so a View-level timeout kills
// the whole subtree, not just the immediate shell-less child.
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
// SAFETY: `setpgid` is async-signal-safe and only touches the child
// before exec.
unsafe {
command.pre_exec(|| {
if libc::setpgid(0, 0) != 0 {
return Err(std::io::Error::last_os_error());
}
Ok(())
});
}
}
let mut child = command.spawn().map_err(|err| ViewError::CoreSpawn {
detail: format!("spawn {}: {err}", self.bin.display()),
})?;
let stdout = child.stdout.take().expect("piped stdout");
let stderr = child.stderr.take().expect("piped stderr");
let stdout_thread = std::thread::spawn(move || read_all(stdout));
let stderr_thread = std::thread::spawn(move || read_all(stderr));
let deadline = Instant::now() + timeout;
let status = loop {
match child.try_wait() {
Ok(Some(status)) => break status,
Ok(None) => {
if Instant::now() >= deadline {
kill_process_tree(&mut child);
let _ = child.wait();
let _ = stdout_thread.join();
let _ = stderr_thread.join();
return Err(ViewError::CoreTimeout {
detail: format!(
"core did not finish within {}s and was killed",
timeout.as_secs()
),
});
}
std::thread::sleep(Duration::from_millis(10));
}
Err(err) => {
let _ = child.kill();
return Err(ViewError::CoreSpawn {
detail: format!("wait for {}: {err}", self.bin.display()),
});
}
}
let budget = ProcessBudget {
wall_clock: timeout,
..Default::default()
};
let stdout_bytes = stdout_thread.join().unwrap_or_default();
let stderr_bytes = stderr_thread.join().unwrap_or_default();
let stdout = String::from_utf8_lossy(&stdout_bytes).to_string();
let stderr = String::from_utf8_lossy(&stderr_bytes).to_string();
let outcome = run_bounded(&self.bin, args, cwd, &budget, None)?;
if outcome.timed_out {
return Err(ViewError::CoreTimeout {
detail: format!(
"core did not finish within {}s and was killed",
timeout.as_secs()
),
});
}
let stdout = outcome.stdout.text_lossy();
let stderr = outcome.stderr.text_lossy();
Ok(ExecOutput {
exit_code: status.code().unwrap_or(-1),
stdout_bytes,
exit_code: outcome.exit_code.unwrap_or(-1),
stdout_bytes: outcome.stdout.bytes,
stdout,
stderr,
})
@@ -515,86 +466,88 @@ struct ExecOutput {
stderr: String,
}
/// Kill the core and every descendant in its process group (Unix), or just the
/// direct child elsewhere. Never leaves a runaway subprocess behind.
fn kill_process_tree(child: &mut std::process::Child) {
#[cfg(unix)]
{
let pid = child.id() as i32;
if pid > 0 {
// SAFETY: negative pid targets the process group created by
// pre_exec(setpgid); ESRCH is harmless when it already exited.
unsafe {
libc::kill(-pid, libc::SIGKILL);
}
}
}
let _ = child.kill();
}
fn read_all(mut reader: impl Read) -> Vec<u8> {
let mut bytes = Vec::new();
let _ = reader.read_to_end(&mut bytes);
bytes
}
/// Build the base `check` arguments. The caller appends `--emit <path>` and
/// optionally `--refs`; this function exists so the argv shape is unit-testable.
fn build_check_args(entry: &Path) -> Vec<OsString> {
vec![OsString::from("check"), entry.as_os_str().to_os_string()]
}
/// Build `run` arguments from an already user-approved request.
pub fn build_run_args(entry: &Path, trace_path: &Path, options: &RunOptions) -> Vec<OsString> {
let mut args = vec![
OsString::from("run"),
entry.as_os_str().to_os_string(),
OsString::from("--mode"),
OsString::from(options.mode.as_str()),
OsString::from("--json"),
OsString::from("--trace-file"),
trace_path.as_os_str().to_os_string(),
];
/// Common explicit flags shared by `run` and `call`. Budgets are always sent
/// explicitly by the execution controller (RFC-VIEW-0002 §6.7).
fn append_common_args(args: &mut Vec<OsString>, trace_path: &Path, options: &RunOptions) {
fn push_pair(args: &mut Vec<OsString>, flag: &str, value: &str) {
args.push(OsString::from(flag));
args.push(OsString::from(value));
}
args.push(OsString::from("--mode"));
args.push(OsString::from(options.mode.as_str()));
args.push(OsString::from("--json"));
args.push(OsString::from("--trace-file"));
args.push(trace_path.as_os_str().to_os_string());
for glob in &options.grants.allow_read {
push_pair(&mut args, "--allow-read", glob);
push_pair(args, "--allow-read", glob);
}
for glob in &options.grants.allow_write {
push_pair(&mut args, "--allow-write", glob);
push_pair(args, "--allow-write", glob);
}
for host in &options.grants.allow_net {
push_pair(&mut args, "--allow-net", host);
push_pair(args, "--allow-net", host);
}
for name in &options.grants.allow_env {
push_pair(&mut args, "--allow-env", name);
push_pair(args, "--allow-env", name);
}
for program in &options.grants.allow_process {
push_pair(&mut args, "--allow-process", program);
push_pair(args, "--allow-process", program);
}
if options.grants.allow_random {
args.push(OsString::from("--allow-random"));
}
if let Some(fuel) = options.fuel {
push_pair(&mut args, "--fuel", &fuel.to_string());
push_pair(args, "--fuel", &fuel.to_string());
}
if let Some(stack) = options.stack {
push_pair(&mut args, "--stack", &stack.to_string());
push_pair(args, "--stack", &stack.to_string());
}
if let Some(max_output) = options.max_output {
push_pair(&mut args, "--max-output", &max_output.to_string());
push_pair(args, "--max-output", &max_output.to_string());
}
if let Some(timeout) = options.timeout_seconds {
push_pair(&mut args, "--timeout", &timeout.to_string());
push_pair(args, "--timeout", &timeout.to_string());
}
if let Some(max_events) = options.trace_max_events {
push_pair(&mut args, "--trace-max-events", &max_events.to_string());
push_pair(args, "--trace-max-events", &max_events.to_string());
}
if let Some(max_bytes) = options.trace_max_bytes {
push_pair(&mut args, "--trace-max-bytes", &max_bytes.to_string());
push_pair(args, "--trace-max-bytes", &max_bytes.to_string());
}
}
/// Build `run` arguments from an already user-approved request.
pub fn build_run_args(entry: &Path, trace_path: &Path, options: &RunOptions) -> Vec<OsString> {
let mut args = vec![OsString::from("run"), entry.as_os_str().to_os_string()];
append_common_args(&mut args, trace_path, options);
args
}
/// Build `call` arguments: explicit argv, one `--arg name=expression` per
/// parameter, never a shell string and never client-supplied flags.
pub fn build_call_args(
entry: &Path,
function: &str,
arguments: &[(String, String)],
trace_path: &Path,
options: &RunOptions,
) -> Vec<OsString> {
let mut args = vec![
OsString::from("call"),
entry.as_os_str().to_os_string(),
OsString::from(function),
];
for (name, expression) in arguments {
args.push(OsString::from("--arg"));
args.push(OsString::from(format!("{name}={expression}")));
}
append_common_args(&mut args, trace_path, options);
args
}
+49 -1
View File
@@ -42,6 +42,22 @@ pub enum ViewError {
ResourceLimit { detail: String },
/// Core subprocess could not be spawned.
CoreSpawn { detail: String },
/// The submitted run request failed schema/target/parameter validation.
RunInvalid { detail: String },
/// The entry document has no resolvable `main`; View never substitutes one.
NoEntryFunction { detail: String },
/// Another explicit run is already active; View allows one at a time.
RunBusy { detail: String },
/// The same client request id was reused with a different payload.
RunConflict { detail: String },
/// The requested run id is unknown, expired or belongs to another session.
RunNotFound { detail: String },
/// Bounded capture of CLI stdout/stderr/JSON/trace exceeded the budget.
OutputLimit { detail: String },
/// The CLI exited but its `--json` document was missing or invalid.
CoreProtocol { detail: String },
/// More than two concurrent SSE observers for one job.
SseBusy { detail: String },
/// Core subprocess exceeded the View-level timeout and was killed.
CoreTimeout { detail: String },
/// Local file system / HTTP I/O failure.
@@ -67,6 +83,14 @@ impl ViewError {
ViewError::ResourceLimit { .. } => "view.resource_limit",
ViewError::CoreSpawn { .. } => "view.core_spawn",
ViewError::CoreTimeout { .. } => "view.core_timeout",
ViewError::RunInvalid { .. } => "view.run_invalid",
ViewError::NoEntryFunction { .. } => "view.no_entry_function",
ViewError::RunBusy { .. } => "view.run_busy",
ViewError::RunConflict { .. } => "view.run_conflict",
ViewError::RunNotFound { .. } => "view.run_not_found",
ViewError::OutputLimit { .. } => "view.output_limit",
ViewError::CoreProtocol { .. } => "view.core_protocol",
ViewError::SseBusy { .. } => "view.sse_busy",
ViewError::Io { .. } => "view.io",
ViewError::Unsupported { .. } => "view.unsupported",
}
@@ -80,7 +104,15 @@ impl ViewError {
| ViewError::PathForbidden { .. }
| ViewError::BindDenied { .. }
| ViewError::SourceSpanInvalid { .. }
| ViewError::Unsupported { .. } => ExitClass::Argument,
| ViewError::Unsupported { .. }
| ViewError::RunInvalid { .. }
| ViewError::NoEntryFunction { .. }
| ViewError::RunBusy { .. }
| ViewError::RunConflict { .. }
| ViewError::RunNotFound { .. }
| ViewError::OutputLimit { .. }
| ViewError::CoreProtocol { .. }
| ViewError::SseBusy { .. } => ExitClass::Argument,
_ => ExitClass::Runtime,
}
}
@@ -118,6 +150,14 @@ impl ViewError {
"view.resource_limit" => "超过配置的资源上限。",
"view.core_spawn" => "无法启动冻结核心。",
"view.core_timeout" => "冻结核心执行超时,已终止。",
"view.run_invalid" => "运行请求未通过校验(目标、参数、模式或授权不合法)。",
"view.no_entry_function" => "文档没有可调用的 main;请改选一个 H2 Exec 函数。",
"view.run_busy" => "已有一次运行正在进行;本版本每个 View 服务只允许一个任务。",
"view.run_conflict" => "同一客户端请求 ID 携带了不同内容,拒绝执行。",
"view.run_not_found" => "运行任务不存在、已过期或不属于当前会话。",
"view.core_protocol" => "冻结核心退出但未给出合法的 --json 结果。",
"view.sse_busy" => "该运行任务的 SSE 观察连接超过上限,请稍后重试。",
"view.output_limit" => "执行输出超过 View 的接收上限,已停止接收。",
"view.io" => "本地 I/O 失败。",
"view.unsupported" => "当前版本不支持该功能。",
_ => "View 内部错误。",
@@ -162,6 +202,14 @@ impl ViewError {
| ViewError::ResourceLimit { detail }
| ViewError::CoreSpawn { detail }
| ViewError::CoreTimeout { detail }
| ViewError::RunInvalid { detail }
| ViewError::NoEntryFunction { detail }
| ViewError::RunBusy { detail }
| ViewError::RunConflict { detail }
| ViewError::RunNotFound { detail }
| ViewError::OutputLimit { detail }
| ViewError::CoreProtocol { detail }
| ViewError::SseBusy { detail }
| ViewError::Io { detail }
| ViewError::Unsupported { detail } => detail,
ViewError::SourceMismatch { expected, actual } => {
File diff suppressed because it is too large. Load diff
+430
View File
@@ -0,0 +1,430 @@
//! View-owned run event log and SSE frames (`marqdo.view-run-events` v1).
//!
//! This is View's own protocol, not a CLI protocol (RFC-VIEW-0002 §6.4). It
//! only carries four event types and a bounded, sequenced replay buffer; it is
//! not an event bus and never carries token streams or per-instruction values.
use std::collections::VecDeque;
use std::sync::mpsc::{self, Receiver, SyncSender, TrySendError};
/// In-memory replay buffer per job (RFC-VIEW-0002 §6.5).
pub const EVENT_RING_CAPACITY: usize = 128;
/// Heartbeat comment cadence; not an event and does not use a sequence number.
pub const HEARTBEAT_INTERVAL_SECS: u64 = 15;
pub const HEARTBEAT_FRAME: &str = ": heartbeat\n\n";
pub const EVENTS_SCHEMA: &str = "marqdo.view-run-events";
pub const EVENTS_SCHEMA_VERSION: u32 = 1;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RunState {
Accepted,
Running,
CancelRequested,
Succeeded,
Failed,
Cancelled,
TimedOut,
Unavailable,
}
impl RunState {
pub fn data_value(&self) -> &'static str {
match self {
RunState::Accepted => "accepted",
RunState::Running => "running",
RunState::CancelRequested => "cancel_requested",
RunState::Succeeded => "succeeded",
RunState::Failed => "failed",
RunState::Cancelled => "cancelled",
RunState::TimedOut => "timed_out",
RunState::Unavailable => "unavailable",
}
}
pub fn label(&self) -> &'static str {
match self {
RunState::Accepted => "已接受",
RunState::Running => "运行中",
RunState::CancelRequested => "正在取消",
RunState::Succeeded => "成功",
RunState::Failed => "失败",
RunState::Cancelled => "已取消",
RunState::TimedOut => "超时",
RunState::Unavailable => "不可用",
}
}
pub fn is_terminal(&self) -> bool {
matches!(
self,
RunState::Succeeded
| RunState::Failed
| RunState::Cancelled
| RunState::TimedOut
| RunState::Unavailable
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EventKind {
State,
Complete,
Error,
Snapshot,
}
impl EventKind {
pub fn sse_name(&self) -> &'static str {
match self {
EventKind::State => "run.state",
EventKind::Complete => "run.complete",
EventKind::Error => "run.error",
EventKind::Snapshot => "run.snapshot",
}
}
}
#[derive(Debug, Clone)]
pub struct RunEvent {
pub seq: u64,
pub kind: EventKind,
pub state: RunState,
pub at: String,
/// Safe parsed CLI result summary (never raw HTML/innerHTML material).
pub result: Option<serde_json::Value>,
/// Verified Trace v2 summary, only after digest/binding checks.
pub trace: Option<serde_json::Value>,
/// `{code, message}` for terminal failures.
pub error: Option<serde_json::Value>,
}
impl RunEvent {
pub fn data(&self, run_id: &str) -> serde_json::Value {
let mut data = serde_json::json!({
"schema": EVENTS_SCHEMA,
"schema_version": EVENTS_SCHEMA_VERSION,
"run_id": run_id,
"seq": self.seq,
"state": self.state.data_value(),
"at": self.at,
});
if let Some(result) = &self.result {
data["result"] = result.clone();
}
if let Some(trace) = &self.trace {
data["trace"] = trace.clone();
}
if let Some(error) = &self.error {
data["error"] = error.clone();
}
data
}
/// One SSE frame with `event:`, numeric `id` equal to `data.seq`, and JSON
/// data on a single line.
pub fn to_sse(&self, run_id: &str) -> String {
let data = serde_json::to_string(&self.data(run_id))
.unwrap_or_else(|_| "{\"schema\":\"marqdo.view-run-events\"}".to_string());
format!(
"event: {}\nid: {}\ndata: {}\n\n",
self.kind.sse_name(),
self.seq,
data
)
}
}
/// Result of subscribing: the frames to write first, then a bounded receiver.
pub struct Subscription {
pub replay: Vec<RunEvent>,
pub receiver: Receiver<RunEvent>,
/// True when the stream must be closed after writing replay (terminal job).
pub terminal: bool,
}
/// Per-job event log. Callers provide the locking (the controller holds the job
/// lock while publishing and while snapshot+subscribe to avoid races).
pub struct EventLog {
next_seq: u64,
ring: VecDeque<RunEvent>,
subscribers: Vec<SyncSender<RunEvent>>,
last_state: RunState,
terminal_snapshot: Option<RunEvent>,
}
impl Default for EventLog {
fn default() -> Self {
Self::new()
}
}
impl EventLog {
pub fn new() -> Self {
Self {
next_seq: 1,
ring: VecDeque::with_capacity(EVENT_RING_CAPACITY),
subscribers: Vec::new(),
last_state: RunState::Accepted,
terminal_snapshot: None,
}
}
fn next_event(&mut self, kind: EventKind, state: RunState) -> RunEvent {
let event = RunEvent {
seq: self.next_seq,
kind,
state,
at: utc_now(),
result: None,
trace: None,
error: None,
};
self.next_seq += 1;
self.last_state = state;
event
}
fn record(&mut self, mut event: RunEvent) -> RunEvent {
if self.ring.len() == EVENT_RING_CAPACITY {
self.ring.pop_front();
}
// A single terminal event is the only one ever stored as the final
// snapshot; once terminal, later publishes are ignored by the caller.
if event.state.is_terminal() {
event.kind = match event.kind {
EventKind::State => EventKind::State,
other => other,
};
self.terminal_snapshot = Some(event.clone());
}
self.ring.push_back(event.clone());
self.subscribers
.retain(|sender| match sender.try_send(event.clone()) {
Ok(()) => true,
Err(TrySendError::Full(_)) | Err(TrySendError::Disconnected(_)) => false,
});
event
}
pub fn publish_state(&mut self, state: RunState) -> RunEvent {
let event = self.next_event(EventKind::State, state);
self.record(event)
}
pub fn publish_complete(
&mut self,
result: serde_json::Value,
trace: Option<serde_json::Value>,
) -> RunEvent {
let mut event = self.next_event(EventKind::Complete, RunState::Succeeded);
event.result = Some(result);
event.trace = trace;
self.record(event)
}
pub fn publish_error(
&mut self,
state: RunState,
code: &str,
message: &str,
result: Option<serde_json::Value>,
trace: Option<serde_json::Value>,
) -> RunEvent {
let mut event = self.next_event(EventKind::Error, state);
event.error = Some(serde_json::json!({
"code": code,
"message": message,
}));
event.result = result;
event.trace = trace;
self.record(event)
}
pub fn last_state(&self) -> RunState {
self.last_state
}
pub fn terminal(&self) -> bool {
self.terminal_snapshot.is_some() || self.last_state.is_terminal()
}
pub fn oldest_seq(&self) -> Option<u64> {
self.ring.front().map(|event| event.seq)
}
/// Build the current snapshot frame from the latest known state (and the
/// terminal result when present). A snapshot always carries the newest
/// sequence number, never a fake historical one.
pub fn snapshot_event(&mut self) -> RunEvent {
// A snapshot always takes a fresh sequence so a client that already saw
// earlier frames never mistakes it for a duplicate and skips it.
let seq = self.next_seq;
self.next_seq += 1;
if let Some(terminal) = &self.terminal_snapshot {
let mut snapshot = terminal.clone();
snapshot.seq = seq;
snapshot.kind = EventKind::Snapshot;
return snapshot;
}
RunEvent {
seq,
kind: EventKind::Snapshot,
state: self.last_state,
at: utc_now(),
result: None,
trace: None,
error: None,
}
}
/// Atomically build replay and register the subscriber. The caller must
/// hold the job lock (controller's Mutex) across this call.
pub fn subscribe(&mut self, last_event_id: Option<u64>) -> Subscription {
let (sender, receiver) = mpsc::sync_channel(EVENT_RING_CAPACITY);
let terminal = self.terminal();
let mut replay: Vec<RunEvent> = Vec::new();
match last_event_id {
Some(cursor) => {
let oldest = self.oldest_seq().unwrap_or(self.next_seq);
let last = self.next_seq.saturating_sub(1);
if cursor > last || cursor + 1 < oldest {
// Too old (already evicted) or forged: synchronise with one
// authoritative snapshot instead of a discontinuous history.
replay.push(self.snapshot_event());
} else {
replay.extend(self.ring.iter().filter(|event| event.seq > cursor).cloned());
}
}
None => {
replay.push(self.snapshot_event());
}
}
if !terminal {
self.subscribers.push(sender);
}
Subscription {
replay,
receiver,
terminal,
}
}
}
/// Minimal RFC3339 UTC timestamp without a date/time dependency.
pub fn utc_now() -> String {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default();
format_utc(now.as_secs())
}
fn format_utc(epoch_secs: u64) -> String {
let days = (epoch_secs / 86_400) as i64;
let seconds = epoch_secs % 86_400;
let (year, month, day) = civil_from_days(days);
format!(
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
seconds / 3600,
(seconds % 3600) / 60,
seconds % 60
)
}
/// Howard Hinnant's `civil_from_days`, valid for the Unix epoch range.
fn civil_from_days(days: i64) -> (i64, u32, u32) {
let z = days + 719_468;
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
let doe = z - era * 146_097;
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
(if m <= 2 { y + 1 } else { y }, m as u32, d as u32)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn states_have_stable_wire_values_and_terminals() {
assert_eq!(RunState::CancelRequested.data_value(), "cancel_requested");
assert!(!RunState::CancelRequested.is_terminal());
for state in [
RunState::Succeeded,
RunState::Failed,
RunState::Cancelled,
RunState::TimedOut,
RunState::Unavailable,
] {
assert!(state.is_terminal());
}
}
#[test]
fn frames_have_event_id_and_matching_data_seq() {
let mut log = EventLog::new();
let event = log.publish_state(RunState::Running);
let frame = event.to_sse("run-1");
assert!(frame.starts_with("event: run.state\n"));
assert!(frame.contains(&format!("id: {}", event.seq)));
let data_line = frame
.lines()
.find(|line| line.starts_with("data: "))
.expect("data line");
let data: serde_json::Value =
serde_json::from_str(data_line.trim_start_matches("data: ")).expect("json");
assert_eq!(data["seq"], event.seq);
assert_eq!(data["run_id"], "run-1");
assert_eq!(data["state"], "running");
assert_eq!(data["schema"], EVENTS_SCHEMA);
assert_eq!(data["schema_version"], 1);
}
#[test]
fn ring_is_bounded_and_old_cursor_gets_snapshot() {
let mut log = EventLog::new();
for _ in 0..(EVENT_RING_CAPACITY + 40) {
log.publish_state(RunState::Running);
}
assert_eq!(log.ring.len(), EVENT_RING_CAPACITY);
let subscription = log.subscribe(Some(1));
assert_eq!(subscription.replay.len(), 1);
assert_eq!(subscription.replay[0].kind, EventKind::Snapshot);
assert!(!subscription.terminal);
}
#[test]
fn terminal_job_replays_snapshot_and_closes() {
let mut log = EventLog::new();
log.publish_state(RunState::Running);
log.publish_complete(serde_json::json!({"success": true}), None);
let subscription = log.subscribe(None);
assert!(subscription.terminal);
assert_eq!(subscription.replay[0].kind, EventKind::Snapshot);
assert_eq!(subscription.replay[0].state, RunState::Succeeded);
assert!(subscription.replay[0].result.is_some());
}
#[test]
fn utc_formatting_is_stable() {
assert_eq!(format_utc(0), "1970-01-01T00:00:00Z");
assert_eq!(format_utc(1_700_000_000), "2023-11-14T22:13:20Z");
}
#[test]
fn newest_cursor_replays_only_new_events() {
let mut log = EventLog::new();
let first = log.publish_state(RunState::Accepted);
let second = log.publish_state(RunState::Running);
let subscription = log.subscribe(Some(first.seq));
assert_eq!(subscription.replay.len(), 1);
assert_eq!(subscription.replay[0].seq, second.seq);
}
}
+15
View File
@@ -0,0 +1,15 @@
//! Execution layer: the only path from an explicit user request to a Core
//! subprocess.
//!
//! `DocumentService` and the renderer never depend on this module; only the
//! `POST /api/runs` server handler can reach it (RFC-VIEW-0002 §5.1).
//!
//! - `request`: schema/target/parameter/mode/grant validation
//! - `process`: the one cancellable Core process adapter with bounded capture
//! - `events`: bounded, sequenced View-owned run events and SSE frames
//! - `controller`: single-job lifecycle, dedupe, cancel, Trace binding
pub mod controller;
pub mod events;
pub mod process;
pub mod request;
+293
View File
@@ -0,0 +1,293 @@
//! The one cancellable CLI process adapter.
//!
//! Every explicit run/call is spawned here as an explicit argv array (never a
//! shell), in its own process group, with bounded stdout/stderr capture and a
//! View-owned wall-clock cap that does not rely on the Core terminating itself
//! (RFC-VIEW-0002 §6.7).
//!
//! The adapter is also used by `core_client` for read-only `check`/`--version`
//! calls so there is exactly one process-spawning implementation in View.
use crate::error::{ViewError, ViewResult};
use std::ffi::OsString;
use std::io::Read;
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
/// Default stdout/JSON budget (4 MiB, RFC-VIEW-0002 §6.7).
pub const MAX_STDOUT_BYTES: usize = 4 * 1024 * 1024;
/// Default stderr budget retained for display.
pub const MAX_STDERR_BYTES: usize = 64 * 1024;
/// Grace period between SIGTERM and SIGKILL when cancelling.
pub const CANCEL_GRACE: Duration = Duration::from_secs(2);
/// Poll interval for child state/cancel/wall-clock checks.
const POLL: Duration = Duration::from_millis(20);
/// Execution budgets sent to the Core and enforced again by View.
#[derive(Debug, Clone)]
pub struct ProcessBudget {
/// View-owned wall clock. Always <= the Core `--timeout` value.
pub wall_clock: Duration,
pub max_stdout: usize,
pub max_stderr: usize,
}
impl Default for ProcessBudget {
fn default() -> Self {
Self {
wall_clock: Duration::from_secs(30),
max_stdout: MAX_STDOUT_BYTES,
max_stderr: MAX_STDERR_BYTES,
}
}
}
/// One bounded stream capture. Reading continues past the cap (so the child
/// never blocks on a full pipe) but retained bytes stay bounded.
#[derive(Debug, Clone, Default)]
pub struct Captured {
pub bytes: Vec<u8>,
pub total: usize,
pub truncated: bool,
}
impl Captured {
pub fn text_lossy(&self) -> String {
String::from_utf8_lossy(&self.bytes).to_string()
}
}
#[derive(Debug, Clone)]
pub struct ProcessOutcome {
pub exit_code: Option<i32>,
pub stdout: Captured,
pub stderr: Captured,
pub cancelled: bool,
pub timed_out: bool,
pub duration: Duration,
}
impl ProcessOutcome {
pub fn status_ok(&self) -> bool {
self.exit_code == Some(0)
}
}
/// Spawn one Core process and wait for it with bounded capture, optional
/// cancellation and a hard wall-clock cap. Never uses a shell.
pub fn run_bounded(
bin: &Path,
args: &[OsString],
cwd: &Path,
budget: &ProcessBudget,
cancel: Option<Arc<AtomicBool>>,
) -> ViewResult<ProcessOutcome> {
run_bounded_with_hook(bin, args, cwd, budget, cancel, Box::new(|| {}))
}
/// Same as [`run_bounded`], with a hook invoked exactly once **after** the
/// child process was successfully spawned (used to publish `running`).
pub fn run_bounded_with_hook(
bin: &Path,
args: &[OsString],
cwd: &Path,
budget: &ProcessBudget,
cancel: Option<Arc<AtomicBool>>,
on_spawn: Box<dyn FnOnce() + Send>,
) -> ViewResult<ProcessOutcome> {
let started = Instant::now();
let mut command = Command::new(bin);
command
.args(args)
.current_dir(cwd)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
// SAFETY: async-signal-safe child-only setup before exec.
unsafe {
command.pre_exec(|| {
if libc::setpgid(0, 0) != 0 {
return Err(std::io::Error::last_os_error());
}
Ok(())
});
}
}
let mut child = command.spawn().map_err(|err| ViewError::CoreSpawn {
detail: format!("spawn {}: {err}", bin.display()),
})?;
on_spawn();
let stdout = child.stdout.take().expect("piped stdout");
let stderr = child.stderr.take().expect("piped stderr");
let stdout_cap = budget.max_stdout;
let stderr_cap = budget.max_stderr;
let stdout_thread = std::thread::spawn(move || read_bounded(stdout, stdout_cap));
let stderr_thread = std::thread::spawn(move || read_bounded(stderr, stderr_cap));
let deadline = started + budget.wall_clock;
let mut cancelled = false;
let mut timed_out = false;
let mut cancel_sent: Option<Instant> = None;
let status = loop {
match child.try_wait() {
Ok(Some(status)) => break status,
Ok(None) => {}
Err(err) => {
terminate_group(&mut child);
return Err(ViewError::CoreSpawn {
detail: format!("wait for {}: {err}", bin.display()),
});
}
}
if let Some(flag) = cancel.as_deref() {
if flag.load(Ordering::SeqCst) && cancel_sent.is_none() {
cancel_sent = Some(Instant::now());
signal_group(child.id(), libc::SIGTERM);
}
}
if let Some(since) = cancel_sent {
if since.elapsed() >= CANCEL_GRACE {
signal_group(child.id(), libc::SIGKILL);
cancelled = true;
}
}
if Instant::now() >= deadline {
signal_group(child.id(), libc::SIGKILL);
timed_out = true;
}
if cancelled || timed_out {
// Keep polling until the child is reaped; the group may take a
// moment to die after SIGKILL.
std::thread::sleep(POLL);
continue;
}
std::thread::sleep(POLL);
};
// A cancel request that raced with a natural exit must not fabricate a
// cancellation: only a kill initiated by this adapter marks it cancelled.
if cancel_sent.is_some() && !cancelled && !timed_out {
cancelled = false;
}
let stdout = stdout_thread.join().unwrap_or_default();
let stderr = stderr_thread.join().unwrap_or_default();
Ok(ProcessOutcome {
exit_code: status.code(),
stdout,
stderr,
cancelled,
timed_out,
duration: started.elapsed(),
})
}
/// Signal a whole process group (Unix) or only the child elsewhere.
pub fn signal_group(pid: u32, signal: i32) {
#[cfg(unix)]
{
let pgid = pid as i32;
if pgid > 0 {
// SAFETY: negative pid targets the group created by setpgid; ESRCH
// is harmless when the process already exited.
unsafe {
libc::kill(-pgid, signal);
}
}
}
#[cfg(not(unix))]
{
let _ = (pid, signal);
}
}
fn terminate_group(child: &mut Child) {
signal_group(child.id(), kill_signal());
let _ = child.kill();
let _ = child.wait();
}
fn kill_signal() -> i32 {
#[cfg(unix)]
{
libc::SIGKILL
}
#[cfg(not(unix))]
{
9
}
}
fn read_bounded(mut reader: impl Read, cap: usize) -> Captured {
let mut captured = Captured::default();
let mut buffer = [0u8; 16 * 1024];
loop {
match reader.read(&mut buffer) {
Ok(0) => break,
Ok(read) => {
captured.total += read;
let remaining = cap.saturating_sub(captured.bytes.len());
if remaining > 0 {
let take = remaining.min(read);
captured.bytes.extend_from_slice(&buffer[..take]);
}
if captured.total > cap {
captured.truncated = true;
}
}
Err(err) if err.kind() == std::io::ErrorKind::Interrupted => continue,
Err(_) => break,
}
}
captured
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bounded_capture_keeps_limit_and_drains() {
let captured = read_bounded(std::io::Cursor::new(vec![b'x'; 100]), 10);
assert_eq!(captured.bytes.len(), 10);
assert_eq!(captured.total, 100);
assert!(captured.truncated);
}
#[test]
fn default_budget_matches_rfc() {
let budget = ProcessBudget::default();
assert_eq!(budget.wall_clock, Duration::from_secs(30));
assert_eq!(budget.max_stdout, 4 * 1024 * 1024);
}
#[cfg(unix)]
#[test]
fn cancellation_terminates_the_process_group() {
let flag = Arc::new(AtomicBool::new(true));
let start = Instant::now();
let outcome = run_bounded(
Path::new("/bin/sleep"),
&[OsString::from("30")],
Path::new("/"),
&ProcessBudget {
wall_clock: Duration::from_secs(20),
..Default::default()
},
Some(flag),
)
.expect("spawn sleep");
assert_ne!(
outcome.exit_code,
Some(0),
"cancel must not look successful"
);
assert!(start.elapsed() < Duration::from_secs(10));
}
}
+594
View File
@@ -0,0 +1,594 @@
//! Validation of the two-phase explicit run request (RFC-VIEW-0002 §6.3).
//!
//! The browser never sends a command: it sends a document, a target selected
//! from Analysis v2, constant parameter expressions, the exact Analysis digest
//! it rendered, a mode and (for project mode) explicit fs globs. Everything is
//! re-validated here and finally by the Core itself; the client cannot inject
//! cwd, flags, a binary path or shell text.
use crate::core_client::Grants;
use crate::error::{ViewError, ViewResult};
use crate::protocol::analysis_v2::SemanticProjection;
use crate::reader::source::SafeRelativePath;
use serde::Deserialize;
/// Bounded request body size accepted before JSON parsing (RFC §6.8).
pub const MAX_RUN_BODY_BYTES: usize = 64 * 1024;
pub const MAX_PARAMETERS: usize = 32;
pub const MAX_EXPRESSION_CHARS: usize = 4096;
pub const MAX_GRANT_GLOBS: usize = 16;
pub const MAX_GRANT_CHARS: usize = 256;
pub const MAX_CLIENT_REQUEST_ID_CHARS: usize = 128;
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RunRequest {
pub document: String,
pub target: RunTarget,
#[serde(default)]
pub parameters: Vec<ParameterInput>,
pub analysis_digest: String,
#[serde(default = "default_mode")]
pub mode: String,
#[serde(default)]
pub grants: GrantRequest,
pub client_request_id: String,
}
fn default_mode() -> String {
"pure".to_string()
}
#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "kind", deny_unknown_fields)]
pub enum RunTarget {
#[serde(rename = "entry")]
Entry,
#[serde(rename = "function")]
Function { function_id: String },
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ParameterInput {
pub name: String,
pub expression: String,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GrantRequest {
#[serde(default)]
pub read: Vec<String>,
#[serde(default)]
pub write: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RunMode {
Pure,
Project,
}
impl RunMode {
pub fn as_str(&self) -> &'static str {
match self {
RunMode::Pure => "pure",
RunMode::Project => "project",
}
}
}
/// A request that passed schema/size/path/mode/grant validation, before the
/// read-only `check` and Analysis-digest step performed by the controller.
#[derive(Debug, Clone)]
pub struct ValidatedRequest {
pub document: SafeRelativePath,
pub target: RunTarget,
pub parameters: Vec<ParameterInput>,
pub analysis_digest: String,
pub mode: RunMode,
pub grants: Grants,
pub client_request_id: String,
}
/// The target resolved against the entry module's verified Analysis.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExecutionTarget {
/// `marqdo run FILE` (entry `main`).
Entry,
/// `marqdo call FILE NAME --arg ...`.
Function {
/// Canonical or unique local name accepted by the frozen CLI.
cli_name: String,
/// Display label from Analysis (`namespace.local_name` when present).
label: String,
},
}
/// One target/parameter plan for the Core argv builder.
#[derive(Debug, Clone)]
pub struct ExecutionPlan {
pub document: SafeRelativePath,
pub target: ExecutionTarget,
pub arguments: Vec<(String, String)>,
pub mode: RunMode,
pub grants: Grants,
pub analysis_digest: String,
pub client_request_id: String,
}
impl ValidatedRequest {
/// Resolve the target and parameter names against the verified entry-module
/// Analysis. Never accepts a dependency-module function id (RFC §6.3).
pub fn plan_against(self, projection: &SemanticProjection) -> ViewResult<ExecutionPlan> {
let target = match &self.target {
RunTarget::Entry => {
if resolve_main(projection).is_none() {
return Err(ViewError::NoEntryFunction {
detail: format!(
"{} 没有可调用的 main;请从函数面板选择一个 H2 Exec 函数",
self.document
),
});
}
ExecutionTarget::Entry
}
RunTarget::Function { function_id } => {
let function = projection
.functions
.iter()
.find(|function| &function.id == function_id)
.ok_or_else(|| ViewError::RunInvalid {
detail: format!(
"function_id {function_id:?} 不在当前入口模块可调用函数中;依赖模块函数不能作为 call 目标"
),
})?;
let canonical = canonical_name(&function.id, &projection.module_id);
let cli_name = if unique_local_name(projection, &function.local_name, &function.id)
{
function.local_name.clone()
} else {
canonical.clone()
};
let label = canonical;
validate_parameters(&self.parameters, projection, &function.id)?;
ExecutionTarget::Function { cli_name, label }
}
};
Ok(ExecutionPlan {
document: self.document,
target,
arguments: self
.parameters
.into_iter()
.map(|parameter| (parameter.name, parameter.expression))
.collect(),
mode: self.mode,
grants: self.grants,
analysis_digest: self.analysis_digest,
client_request_id: self.client_request_id,
})
}
}
/// Parse and validate the raw request against fixed limits. Does not touch the
/// file system or the Core; the controller performs the read-only check next.
pub fn validate_request(body: &[u8]) -> ViewResult<ValidatedRequest> {
if body.len() > MAX_RUN_BODY_BYTES {
return Err(ViewError::RunInvalid {
detail: format!("运行请求体超过 {MAX_RUN_BODY_BYTES} 字节上限"),
});
}
let request: RunRequest =
serde_json::from_slice(body).map_err(|err| ViewError::RunInvalid {
detail: format!("运行请求不是合法的 marqdo.view-run-request v1 JSON: {err}"),
})?;
validate_client_request_id(&request.client_request_id)?;
validate_digest(&request.analysis_digest)?;
let document = SafeRelativePath::parse(&request.document)?;
if !document.as_str().ends_with(".mq.md") {
return Err(ViewError::RunInvalid {
detail: "运行目标必须是受控项目根内的 .mq.md 文档".to_string(),
});
}
match &request.target {
RunTarget::Entry => {}
RunTarget::Function { function_id } => {
if function_id.is_empty()
|| function_id.len() > 512
|| function_id.chars().any(|ch| ch.is_control() || ch == '\0')
{
return Err(ViewError::RunInvalid {
detail: "function_id 必须来自 Analysis v2 且长度为 1..=512".to_string(),
});
}
}
}
if request.parameters.len() > MAX_PARAMETERS {
return Err(ViewError::RunInvalid {
detail: format!("参数数量超过 {MAX_PARAMETERS} 个上限"),
});
}
for parameter in &request.parameters {
validate_parameter_name(&parameter.name)?;
validate_expression(&parameter.expression)?;
}
let (mode, grants) = validate_mode_and_grants(&request.mode, &request.grants)?;
Ok(ValidatedRequest {
document,
target: request.target,
parameters: request.parameters,
analysis_digest: request.analysis_digest,
mode,
grants,
client_request_id: request.client_request_id,
})
}
fn validate_client_request_id(value: &str) -> ViewResult<()> {
if value.is_empty()
|| value.chars().count() > MAX_CLIENT_REQUEST_ID_CHARS
|| !value
.chars()
.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.' | ':'))
{
return Err(ViewError::RunInvalid {
detail: format!(
"client_request_id 必须是不透明的 ASCII 标识(1..={MAX_CLIENT_REQUEST_ID_CHARS},字母/数字/-_ .:)"
),
});
}
Ok(())
}
fn validate_digest(value: &str) -> ViewResult<()> {
let Some(hex) = value.strip_prefix("sha256:") else {
return Err(ViewError::RunInvalid {
detail: "analysis_digest 必须以 sha256: 开头".to_string(),
});
};
if hex.len() != 64 || !hex.chars().all(|ch| ch.is_ascii_hexdigit()) {
return Err(ViewError::RunInvalid {
detail: "analysis_digest 必须是 sha256:<64 hex>".to_string(),
});
}
Ok(())
}
fn validate_parameter_name(name: &str) -> ViewResult<()> {
if name.is_empty()
|| name.chars().count() > 128
|| name
.chars()
.any(|ch| ch.is_control() || ch.is_whitespace() || ch == '=')
{
return Err(ViewError::RunInvalid {
detail: "参数名必须非空且不包含控制字符、空白或 '='".to_string(),
});
}
Ok(())
}
fn validate_expression(expression: &str) -> ViewResult<()> {
if expression.trim().is_empty() {
return Err(ViewError::RunInvalid {
detail: "参数 expression 不能为空;View 不做隐式裸文本转字符串".to_string(),
});
}
if expression.chars().count() > MAX_EXPRESSION_CHARS {
return Err(ViewError::RunInvalid {
detail: format!("参数 expression 超过 {MAX_EXPRESSION_CHARS} 字符上限"),
});
}
if expression.chars().any(|ch| ch == '\0' || ch.is_control()) {
return Err(ViewError::RunInvalid {
detail: "参数 expression 不能包含 NUL/控制字符".to_string(),
});
}
Ok(())
}
fn validate_mode_and_grants(mode: &str, grants: &GrantRequest) -> ViewResult<(RunMode, Grants)> {
match mode {
"pure" => {
if !grants.read.is_empty() || !grants.write.is_empty() {
return Err(ViewError::RunInvalid {
detail: "pure 模式不能携带 fs grants;需要文件访问时请显式选择 project 模式"
.to_string(),
});
}
Ok((RunMode::Pure, Grants::default()))
}
"project" => {
if grants.read.len() > MAX_GRANT_GLOBS || grants.write.len() > MAX_GRANT_GLOBS {
return Err(ViewError::RunInvalid {
detail: format!("每个 fs grant 列表最多 {MAX_GRANT_GLOBS} 项"),
});
}
let mut seen = std::collections::BTreeSet::new();
let mut validated = Grants::default();
for glob in &grants.read {
validate_glob(glob)?;
if seen.insert(glob.clone()) {
validated.allow_read.push(glob.clone());
}
}
let mut seen_write = std::collections::BTreeSet::new();
for glob in &grants.write {
validate_glob(glob)?;
if seen_write.insert(glob.clone()) {
validated.allow_write.push(glob.clone());
}
}
Ok((RunMode::Project, validated))
}
"strict" => Err(ViewError::RunDenied {
detail: "strict 模式不在 View 首版提供;请改用 pure/project 或直接在终端运行 CLI"
.to_string(),
}),
other => Err(ViewError::RunDenied {
detail: format!(
"模式 {other:?} 不在首版支持范围;仅允许 pure 或受控 project(fs read/write)"
),
}),
}
}
fn validate_glob(glob: &str) -> ViewResult<()> {
if glob.is_empty() || glob.chars().count() > MAX_GRANT_CHARS {
return Err(ViewError::RunInvalid {
detail: format!("fs grant glob 必须为 1..={MAX_GRANT_CHARS} 字符"),
});
}
if glob.starts_with('/')
|| glob.starts_with('\\')
|| glob.starts_with('~')
|| glob.contains('\\')
|| glob.contains('\0')
|| glob.chars().any(|ch| ch.is_control())
|| glob.split('/').any(|segment| segment == "..")
|| glob.contains(':')
{
return Err(ViewError::RunInvalid {
detail: format!(
"fs grant {glob:?} 必须是项目根相对 glob(禁止绝对路径、..、反斜杠、盘符/控制字符)"
),
});
}
Ok(())
}
/// Resolve `main` exactly like the frozen CLI does for `run`: canonical name
/// first, then a unique local name. No fallback to any other function.
fn resolve_main(projection: &SemanticProjection) -> Option<(String, String)> {
if let Some(function) = projection.functions.iter().find(|function| {
canonical_name(&function.id, &projection.module_id) == "main"
|| function.local_name == "main"
}) {
return Some((
canonical_name(&function.id, &projection.module_id),
function.local_name.clone(),
));
}
None
}
fn unique_local_name(projection: &SemanticProjection, local_name: &str, id: &str) -> bool {
let matches = projection
.functions
.iter()
.filter(|function| function.local_name == local_name)
.count();
if matches == 1 {
return true;
}
// If several namespaces define the same local name, only the canonical
// qualified name is unambiguous; the CLI resolver has the same rule.
let canonical = canonical_name(id, &projection.module_id);
canonical == local_name
}
/// Analysis v2 function ids are `<module id>::<canonical name>`.
pub fn canonical_name(function_id: &str, module_id: &str) -> String {
function_id
.strip_prefix(&format!("{module_id}::"))
.unwrap_or(function_id)
.to_string()
}
fn validate_parameters(
parameters: &[ParameterInput],
projection: &SemanticProjection,
function_id: &str,
) -> ViewResult<()> {
let function = projection
.functions
.iter()
.find(|function| function.id == function_id)
.ok_or_else(|| ViewError::RunInvalid {
detail: "函数在选择后消失,请刷新页面重新选择".to_string(),
})?;
let mut seen = std::collections::BTreeSet::new();
for parameter in parameters {
if !function
.signature
.params
.iter()
.any(|param| param.name == parameter.name)
{
return Err(ViewError::RunInvalid {
detail: format!(
"参数 {:?} 不在函数 {} 的签名中",
parameter.name, function.local_name
),
});
}
if !seen.insert(parameter.name.clone()) {
return Err(ViewError::RunInvalid {
detail: format!("参数 {:?} 重复提交", parameter.name),
});
}
}
Ok(())
}
/// Stable digest of the exact request bytes, used for `client_request_id`
/// idempotency (same id + same bytes => same run; different bytes => 409).
pub fn payload_digest(bytes: &[u8]) -> String {
crate::reader::source::sha256_hex(bytes)
}
#[cfg(test)]
mod tests {
use super::*;
fn projection() -> SemanticProjection {
let source = "x".repeat(200);
let digest = crate::reader::source::sha256_hex(source.as_bytes());
let analysis = serde_json::json!({
"schema": "marqdo.analysis",
"schema_version": 2,
"producer": {"name": "marqdo", "version": "3.0.0-beta.1", "markdown_profile": "marqdo.md.v1"},
"project": {"root_id": "root:t@0.1.0", "identity_kind": "manifest", "lock_digest": "", "stdlib": null},
"modules": [{
"id": "root:t@0.1.0::index.mq.md",
"package_instance_id": "root:t@0.1.0",
"relative_path": "index.mq.md",
"source_digest": digest,
"units": [],
"functions": [
{"id": "root:t@0.1.0::index.mq.md::main", "unit_id": "u1", "local_name": "main",
"namespace": null, "span": {"start": 0, "end": 10}, "heading_span": {"start": 0, "end": 10},
"signature": {"kind": "inferred", "params": []}, "body": [], "effects": ["unknown"]},
{"id": "root:t@0.1.0::index.mq.md::N.f", "unit_id": "u2", "local_name": "f",
"namespace": "N", "span": {"start": 20, "end": 30}, "heading_span": {"start": 20, "end": 30},
"signature": {"kind": "explicit", "params": [
{"name": "n", "required": true, "type": "Int", "default": null, "span": null}
]}, "body": [], "effects": ["unknown"]}
],
"imports": [], "references": [], "calls": [], "resources": []
}],
"diagnostics": []
})
.to_string();
let source = "x".repeat(200);
let index = crate::reader::source::SourceIndex::new(&source);
crate::protocol::analysis_v2::verify_analysis(
analysis.to_string().as_bytes(),
&source,
&index,
"index.mq.md",
)
.map(|verified| verified.projection)
.unwrap_or_else(|err| panic!("fixture analysis must verify: {err}"))
}
#[test]
fn rejects_unknown_fields_and_bad_modes() {
let base = serde_json::json!({
"document": "index.mq.md",
"target": {"kind": "entry"},
"analysis_digest": format!("sha256:{}", "a".repeat(64)),
"mode": "pure",
"client_request_id": "req-1"
});
let mut with_unknown = base.clone();
with_unknown["cwd"] = serde_json::json!("/tmp");
assert!(validate_request(with_unknown.to_string().as_bytes()).is_err());
let mut strict = base.clone();
strict["mode"] = serde_json::json!("strict");
assert_eq!(
validate_request(strict.to_string().as_bytes())
.unwrap_err()
.code(),
"view.run_denied"
);
let mut project_without_globs = base;
project_without_globs["mode"] = serde_json::json!("project");
assert!(validate_request(project_without_globs.to_string().as_bytes()).is_ok());
}
#[test]
fn rejects_absolute_and_parent_globs() {
let request = serde_json::json!({
"document": "index.mq.md",
"target": {"kind": "entry"},
"analysis_digest": format!("sha256:{}", "a".repeat(64)),
"mode": "project",
"grants": {"read": ["../secret"], "write": []},
"client_request_id": "req-1"
});
assert!(validate_request(request.to_string().as_bytes()).is_err());
let request = serde_json::json!({
"document": "index.mq.md",
"target": {"kind": "entry"},
"analysis_digest": format!("sha256:{}", "a".repeat(64)),
"mode": "project",
"grants": {"read": ["/etc/passwd"], "write": []},
"client_request_id": "req-1"
});
assert!(validate_request(request.to_string().as_bytes()).is_err());
}
#[test]
fn canonical_names_and_targets_resolve() {
let projection = projection();
let request = serde_json::json!({
"document": "index.mq.md",
"target": {"kind": "function", "function_id": "root:t@0.1.0::index.mq.md::N.f"},
"parameters": [{"name": "n", "expression": "5"}],
"analysis_digest": format!("sha256:{}", projection.analysis_sha256),
"mode": "pure",
"client_request_id": "req-2"
});
let validated = validate_request(request.to_string().as_bytes()).expect("valid");
let plan = validated.plan_against(&projection).expect("plan");
match plan.target {
ExecutionTarget::Function { cli_name, .. } => assert_eq!(cli_name, "f"),
ExecutionTarget::Entry => panic!("expected function"),
}
assert_eq!(plan.arguments, vec![("n".to_string(), "5".to_string())]);
}
#[test]
fn entry_without_main_is_explicitly_rejected() {
let mut projection = projection();
projection
.functions
.retain(|function| function.local_name != "main");
let request = serde_json::json!({
"document": "index.mq.md",
"target": {"kind": "entry"},
"analysis_digest": format!("sha256:{}", projection.analysis_sha256),
"mode": "pure",
"client_request_id": "req-3"
});
let validated = validate_request(request.to_string().as_bytes()).expect("valid");
assert_eq!(
validated.plan_against(&projection).unwrap_err().code(),
"view.no_entry_function"
);
}
#[test]
fn unknown_parameter_names_are_rejected_before_execution() {
let projection = projection();
let request = serde_json::json!({
"document": "index.mq.md",
"target": {"kind": "function", "function_id": "root:t@0.1.0::index.mq.md::N.f"},
"parameters": [{"name": "bogus", "expression": "5"}],
"analysis_digest": format!("sha256:{}", projection.analysis_sha256),
"mode": "pure",
"client_request_id": "req-4"
});
let validated = validate_request(request.to_string().as_bytes()).expect("valid");
assert_eq!(
validated.plan_against(&projection).unwrap_err().code(),
"view.run_invalid"
);
}
}
+1
View File
@@ -10,6 +10,7 @@ pub mod cli;
pub mod config;
pub mod core_client;
pub mod error;
pub mod execution;
pub mod export;
pub mod protocol;
pub mod reader;
+88 -1
View File
@@ -11,7 +11,7 @@ use crate::reader::markdown::{DocumentIdentity, DocumentModel};
use crate::reader::model::{
Navigation, OutlineEntry, OutlineKind, PresentationModel, SourceStatus,
};
use crate::reader::source::{Project, SafeRelativePath};
use crate::reader::source::{sha256_hex, Project, SafeRelativePath};
use crate::core_client::{
CheckOptions, CheckResponse, CoreClient, RawCheckDiagnostic, RunOptions, SandboxMode,
@@ -186,6 +186,10 @@ impl DocumentService {
self.core.as_ref()
}
pub fn core_client(&self) -> Option<&CoreClient> {
self.core.as_ref()
}
pub fn core_version(&self) -> Option<&str> {
self.core_version.as_deref()
}
@@ -430,3 +434,86 @@ fn diagnostic_to_view(
hints: diagnostic.hints.clone(),
}
}
/// One read-only, byte-verified static view of a document, used by explicit
/// run validation and Trace binding. Nothing here executes the document.
#[derive(Debug)]
pub struct StaticDocument {
pub relative: SafeRelativePath,
pub source: String,
pub source_index: crate::reader::source::SourceIndex,
pub source_sha256: String,
/// Exact bytes written by `marqdo check --emit`.
pub analysis_bytes: Vec<u8>,
pub analysis_digest: String,
pub verified: crate::protocol::analysis_v2::VerifiedAnalysis,
}
impl DocumentService {
/// Re-run the read-only `check --emit` and verify Analysis v2 against the
/// current exact source bytes. This is the only static truth used before an
/// explicit run is accepted.
pub fn static_document(&self, relative: &SafeRelativePath) -> ViewResult<StaticDocument> {
let client = self.core.as_ref().ok_or_else(|| ViewError::RunDenied {
detail: "没有可用的冻结核心(MARQDO_BIN);无法验证运行请求".to_string(),
})?;
let source_bytes = self.project.read_source(relative)?;
let source_sha256 = sha256_hex(&source_bytes);
let source = String::from_utf8(source_bytes).map_err(|err| ViewError::Io {
detail: format!("{relative} is not valid UTF-8: {err}"),
})?;
let source_index = crate::reader::source::SourceIndex::new(&source);
let response = client.check(
&self.project,
relative,
&CheckOptions {
refs: false,
timeout: Some(std::time::Duration::from_secs(30)),
},
)?;
let check = match response {
CheckResponse {
success: true,
analysis: Some(check),
..
} => check,
CheckResponse {
success: false,
diagnostics,
exit_code,
..
} => {
let first = diagnostics
.first()
.map(|diagnostic| format!("{}: {}", diagnostic.code, diagnostic.message))
.unwrap_or_else(|| "no diagnostic detail".to_string());
return Err(ViewError::AnalysisFailed {
detail: format!(
"Core 检查失败(exit {exit_code}, {} diagnostic(s));拒绝执行。first: {first}",
diagnostics.len()
),
});
}
CheckResponse { analysis: None, .. } => {
return Err(ViewError::AnalysisFailed {
detail: "Core 声称检查成功但没有产出 Analysis".to_string(),
});
}
};
let verified = crate::protocol::analysis_v2::verify_analysis(
&check.analysis_bytes,
&source,
&source_index,
relative.as_str(),
)?;
Ok(StaticDocument {
relative: relative.clone(),
source,
source_index,
source_sha256,
analysis_digest: check.analysis_digest,
analysis_bytes: check.analysis_bytes,
verified,
})
}
}
+4 -4
View File
@@ -73,9 +73,6 @@ dir="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
printf 'invocation\n'
for arg in "$@"; do printf 'arg=%s\n' "$arg"; done
} >> "$dir/argv.txt"
if [ -f "$dir/sleep" ]; then
sleep "$(cat "$dir/sleep")"
fi
case "$1" in
--version)
if [ -f "$dir/version" ]; then cat "$dir/version"; else printf 'marqdo 3.0.0-beta.1\n'; fi
@@ -94,8 +91,11 @@ case "$1" in
if [ -f "$dir/check_exit" ]; then exit "$(cat "$dir/check_exit")"; fi
exit 0
;;
run)
run|call)
: > "$dir/run-was-called"
if [ -f "$dir/sleep" ]; then
sleep "$(cat "$dir/sleep")"
fi
trace=""
prev=""
for a in "$@"; do
+514
View File
@@ -0,0 +1,514 @@
//! Execution controller tests: one explicit request, one Core subprocess, one
//! unique terminal state, SSE-ready events, dedupe, grants and cancellation.
//!
//! The fake Core is a real executable (never a mocked trait) so argv, process
//! lifecycle and trace files are exercised at the process boundary.
use crate::common::{sha256_hex, FakeCore};
use marqdo_view::execution::controller::{ExecutionConfig, ExecutionController, SseSubscription};
use marqdo_view::execution::events::RunState;
use marqdo_view::reader::assemble::DocumentService;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
fn repo_root() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
}
fn golden(name: &str) -> String {
let path = repo_root().join("tests/golden/analysis-v2").join(name);
std::fs::read_to_string(&path).unwrap_or_else(|err| panic!("read {path:?}: {err}"))
}
fn analysis_digest(analysis: &str) -> String {
format!("sha256:{}", sha256_hex(analysis.as_bytes()))
}
struct Fixture {
core: FakeCore,
controller: Arc<ExecutionController>,
_service: Arc<DocumentService>,
}
fn fixture_with(
name: &str,
project_relative: &str,
analysis: &str,
run_json: &str,
trace: Option<&str>,
config: ExecutionConfig,
) -> Fixture {
let core = FakeCore::new(name);
core.set_analysis(analysis);
core.set_check_json(r#"{"command":"check","diagnostics":[],"errors":0,"success":true}"#);
core.set_run(0, run_json, trace);
let project = repo_root().join(project_relative);
let service = Arc::new(
DocumentService::open(&project, Some(core.script.as_path()))
.expect("open document service"),
);
let controller = Arc::new(ExecutionController::new(Arc::clone(&service), config));
Fixture {
core,
controller,
_service: service,
}
}
fn control_flow(name: &str) -> Fixture {
let analysis = golden("control-flow.json");
let run =
std::fs::read_to_string(repo_root().join("tests/golden/trace-v2/control-flow.run.json"))
.expect("run golden");
let trace =
std::fs::read_to_string(repo_root().join("tests/golden/trace-v2/control-flow.trace.json"))
.expect("trace golden");
fixture_with(
name,
"examples/control-flow",
&analysis,
&run,
Some(&trace),
ExecutionConfig::default().with_timeout(10),
)
}
fn request_body(
analysis: &str,
target: serde_json::Value,
mode: &str,
grants: serde_json::Value,
client_request_id: &str,
) -> Vec<u8> {
serde_json::json!({
"document": "index.mq.md",
"target": target,
"analysis_digest": analysis_digest(analysis),
"mode": mode,
"grants": grants,
"client_request_id": client_request_id,
})
.to_string()
.into_bytes()
}
fn frame_data(frame: &str) -> Option<serde_json::Value> {
frame
.lines()
.find(|line| line.starts_with("data: "))
.and_then(|line| serde_json::from_str(line.trim_start_matches("data: ")).ok())
}
fn is_terminal_data(data: &serde_json::Value) -> bool {
data["state"]
.as_str()
.map(|state| {
matches!(
state,
"succeeded" | "failed" | "cancelled" | "timed_out" | "unavailable"
)
})
.unwrap_or(false)
}
fn terminal_events(subscription: SseSubscription) -> (Vec<serde_json::Value>, serde_json::Value) {
let mut parsed = subscription
.replay
.iter()
.filter_map(|frame| frame_data(frame))
.collect::<Vec<serde_json::Value>>();
let mut terminal = parsed
.iter()
.rev()
.find(|data| is_terminal_data(data))
.cloned();
let deadline = Instant::now() + Duration::from_secs(20);
while terminal.is_none() && Instant::now() < deadline {
match subscription
.receiver
.recv_timeout(Duration::from_millis(250))
{
Ok(event) => {
let data = event.data(&subscription.run_id);
if event.state.is_terminal() {
terminal = Some(data.clone());
}
parsed.push(data);
}
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
if subscription.terminal {
break;
}
}
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
}
}
(parsed, terminal.expect("terminal event"))
}
fn wait_for_file(path: &Path) {
let deadline = Instant::now() + Duration::from_secs(10);
while Instant::now() < deadline {
if path.is_file() {
return;
}
std::thread::sleep(Duration::from_millis(20));
}
panic!("timed out waiting for {path:?}");
}
#[test]
fn explicit_entry_run_streams_accepted_running_and_succeeded_with_verified_trace() {
let fixture = control_flow("ctrl-success");
let analysis = golden("control-flow.json");
let body = request_body(
&analysis,
serde_json::json!({"kind": "entry"}),
"pure",
serde_json::json!({}),
"req-success",
);
let accepted = fixture
.controller
.submit("session-a", &body)
.expect("accepted");
assert!(!accepted.reused);
assert_eq!(accepted.run_id.len(), 32);
assert_eq!(
accepted.events_url,
format!("/api/runs/{}/events", accepted.run_id)
);
let subscription = fixture
.controller
.subscribe("session-a", &accepted.run_id, Some(0))
.expect("subscribe");
let (events, terminal) = terminal_events(subscription);
let seqs: Vec<u64> = events
.iter()
.map(|event| event["seq"].as_u64().unwrap())
.collect();
assert!(
seqs.windows(2).all(|pair| pair[0] < pair[1]),
"seqs: {seqs:?}"
);
let states: Vec<String> = events
.iter()
.map(|event| event["state"].as_str().unwrap().to_string())
.collect();
assert!(
states.contains(&"accepted".to_string()),
"states: {states:?}"
);
assert!(
states.contains(&"running".to_string()),
"states: {states:?}"
);
assert_eq!(terminal["state"], "succeeded");
assert_eq!(terminal["result"]["success"], true);
assert_eq!(terminal["trace"]["status"], "verified");
assert!(!terminal["trace"]["events"].as_array().unwrap().is_empty());
assert_eq!(terminal["trace"]["stale"], false);
// The fake Core's stderr/stdout were read through the adapter, not guessed.
assert_eq!(terminal["result"]["stdout"], "0\n0\n2\n");
}
#[test]
fn call_target_uses_the_call_subcommand_and_function_name() {
let fixture = control_flow("ctrl-call");
let analysis = golden("control-flow.json");
let function_id = "root:control-flow@0.1.0::index.mq.md::演示.main";
let body = request_body(
&analysis,
serde_json::json!({"kind": "function", "function_id": function_id}),
"pure",
serde_json::json!({}),
"req-call",
);
let accepted = fixture
.controller
.submit("session-a", &body)
.expect("accepted");
let subscription = fixture
.controller
.subscribe("session-a", &accepted.run_id, Some(0))
.expect("subscribe");
let (_events, terminal) = terminal_events(subscription);
assert_eq!(terminal["state"], "succeeded");
let argv = std::fs::read_to_string(fixture.core.dir.join("argv.txt")).unwrap_or_default();
assert!(argv.contains("arg=call"), "argv: {argv}");
assert!(argv.contains("arg=main"), "argv: {argv}");
}
#[test]
fn same_client_request_id_is_idempotent_and_different_payload_conflicts() {
let fixture = control_flow("ctrl-dedupe");
let analysis = golden("control-flow.json");
let body = request_body(
&analysis,
serde_json::json!({"kind": "entry"}),
"pure",
serde_json::json!({}),
"req-dedupe",
);
let first = fixture
.controller
.submit("session-a", &body)
.expect("first accepted");
let second = fixture
.controller
.submit("session-a", &body)
.expect("second accepted");
assert_eq!(first.run_id, second.run_id);
assert!(second.reused);
let mut changed: serde_json::Value = serde_json::from_slice(&body).unwrap();
changed["mode"] = serde_json::json!("project");
let err = fixture
.controller
.submit("session-a", changed.to_string().as_bytes())
.expect_err("conflicting payload must be rejected");
assert_eq!(err.code(), "view.run_conflict");
}
#[test]
fn second_run_is_busy_while_one_is_active_and_cancel_is_idempotent() {
let analysis = golden("control-flow.json");
let run = r#"{"command":"run","success":true,"value":{"type":"int","decimal":"1"}}"#;
let fixture = fixture_with(
"ctrl-cancel",
"examples/control-flow",
&analysis,
run,
None,
ExecutionConfig::default().with_timeout(30),
);
fixture.core.set_sleep_seconds(30);
let body = request_body(
&analysis,
serde_json::json!({"kind": "entry"}),
"pure",
serde_json::json!({}),
"req-cancel",
);
let accepted = fixture
.controller
.submit("session-a", &body)
.expect("accepted");
wait_for_file(&fixture.core.dir.join("run-was-called"));
let other_body = request_body(
&analysis,
serde_json::json!({"kind": "entry"}),
"pure",
serde_json::json!({}),
"req-cancel-other",
);
let busy = fixture
.controller
.submit("session-a", &other_body)
.expect_err("second run must be busy");
assert_eq!(busy.code(), "view.run_busy");
let started = Instant::now();
let state = fixture
.controller
.cancel("session-a", &accepted.run_id)
.expect("cancel");
assert!(matches!(
state,
RunState::CancelRequested | RunState::Cancelled
));
// Repeat cancel is idempotent.
let _ = fixture
.controller
.cancel("session-a", &accepted.run_id)
.expect("second cancel");
let subscription = fixture
.controller
.subscribe("session-a", &accepted.run_id, Some(0))
.expect("subscribe");
let (events, terminal) = terminal_events(subscription);
assert_eq!(terminal["state"], "cancelled");
let terminal_count = events
.iter()
.filter(|event| {
event["state"]
.as_str()
.map(|state| {
matches!(
state,
"succeeded" | "failed" | "cancelled" | "timed_out" | "unavailable"
)
})
.unwrap_or(false)
})
.count();
assert_eq!(terminal_count, 1, "exactly one terminal state: {events:?}");
assert!(started.elapsed() < Duration::from_secs(10));
}
#[test]
fn cross_session_observation_is_rejected() {
let fixture = control_flow("ctrl-session");
let analysis = golden("control-flow.json");
let body = request_body(
&analysis,
serde_json::json!({"kind": "entry"}),
"pure",
serde_json::json!({}),
"req-session",
);
let accepted = fixture
.controller
.submit("session-a", &body)
.expect("accepted");
assert_eq!(
fixture
.controller
.subscribe("session-b", &accepted.run_id, None)
.unwrap_err()
.code(),
"view.run_not_found"
);
assert_eq!(
fixture
.controller
.cancel("session-b", &accepted.run_id)
.unwrap_err()
.code(),
"view.run_not_found"
);
}
#[test]
fn stale_analysis_digest_is_rejected_before_any_process_starts() {
let fixture = control_flow("ctrl-stale");
let analysis = golden("control-flow.json");
let mut body: serde_json::Value = serde_json::from_slice(&request_body(
&analysis,
serde_json::json!({"kind": "entry"}),
"pure",
serde_json::json!({}),
"req-stale",
))
.unwrap();
body["analysis_digest"] = serde_json::json!(format!("sha256:{}", "0".repeat(64)));
let err = fixture
.controller
.submit("session-a", body.to_string().as_bytes())
.expect_err("stale digest must be rejected");
assert_eq!(err.code(), "view.run_invalid");
assert!(!fixture.core.dir.join("run-was-called").exists());
}
#[test]
fn project_grants_are_mapped_to_explicit_cli_flags_and_pure_grants_are_rejected() {
let fixture = control_flow("ctrl-grants");
let analysis = golden("control-flow.json");
let body = request_body(
&analysis,
serde_json::json!({"kind": "entry"}),
"project",
serde_json::json!({"read": ["data/**"], "write": ["out/*.txt"]}),
"req-project",
);
let accepted = fixture
.controller
.submit("session-a", &body)
.expect("accepted");
let subscription = fixture
.controller
.subscribe("session-a", &accepted.run_id, Some(0))
.expect("subscribe");
let (_events, terminal) = terminal_events(subscription);
assert_eq!(terminal["state"], "succeeded");
let argv = std::fs::read_to_string(fixture.core.dir.join("argv.txt")).unwrap_or_default();
assert!(argv.contains("arg=--mode\narg=project"), "argv: {argv}");
assert!(
argv.contains("arg=--allow-read\narg=data/**"),
"argv: {argv}"
);
assert!(
argv.contains("arg=--allow-write\narg=out/*.txt"),
"argv: {argv}"
);
assert!(!argv.contains("arg=--mode\narg=pure"));
// pure with grants is rejected by request validation before the Core runs.
let pure_with_grants = request_body(
&analysis,
serde_json::json!({"kind": "entry"}),
"pure",
serde_json::json!({"read": ["data/**"]}),
"req-pure-grants",
);
let err = fixture
.controller
.submit("session-a", &pure_with_grants)
.expect_err("pure grants must be rejected");
assert_eq!(err.code(), "view.run_invalid");
}
#[test]
fn run_without_a_trace_file_succeeds_but_reports_unavailable_trace() {
let analysis = golden("control-flow.json");
let run = r#"{"command":"run","success":true,"value":{"type":"int","decimal":"7"},"stdout":"hi\n","stderr":"","diagnostics":[]}"#;
let fixture = fixture_with(
"ctrl-no-trace",
"examples/control-flow",
&analysis,
run,
None,
ExecutionConfig::default().with_timeout(10),
);
let body = request_body(
&analysis,
serde_json::json!({"kind": "entry"}),
"pure",
serde_json::json!({}),
"req-no-trace",
);
let accepted = fixture
.controller
.submit("session-a", &body)
.expect("accepted");
let subscription = fixture
.controller
.subscribe("session-a", &accepted.run_id, Some(0))
.expect("subscribe");
let (_events, terminal) = terminal_events(subscription);
assert_eq!(terminal["state"], "succeeded");
assert_eq!(terminal["result"]["value_text"], "Int(7)");
assert_eq!(terminal["trace"], serde_json::Value::Null);
assert_eq!(terminal["result"]["trace_status"], "unavailable");
assert!(!fixture.core.dir.join("trace.json").exists() || terminal["trace"].is_null());
}
#[test]
fn event_frames_use_the_view_run_events_schema_and_numeric_ids() {
let fixture = control_flow("ctrl-frames");
let analysis = golden("control-flow.json");
let body = request_body(
&analysis,
serde_json::json!({"kind": "entry"}),
"pure",
serde_json::json!({}),
"req-frames",
);
let accepted = fixture
.controller
.submit("session-a", &body)
.expect("accepted");
let subscription = fixture
.controller
.subscribe("session-a", &accepted.run_id, None)
.expect("subscribe");
let (events, terminal) = terminal_events(subscription);
assert_eq!(terminal["schema"], "marqdo.view-run-events");
assert_eq!(terminal["schema_version"], 1);
assert_eq!(terminal["run_id"], accepted.run_id.as_str());
assert!(!events.is_empty());
}
+1
View File
@@ -4,6 +4,7 @@
#[path = "../common/mod.rs"]
mod common;
mod execution;
mod export;
mod http_live;
mod rendering;