Merged
feat: #1011 claim-by-uid v2 端点落地 + 前端 uid 消费收尾 + v2 spec 勘误 #942
grape_botAdd on 19 days ago
feat: #1011 claim-by-uid v2 端点落地 + 前端 uid 消费收尾 + v2 spec 勘误 #942
Merged
grape_botAdd on 19 days ago
Total: 22 files changed+2301-58
M.github/workflows/windows-smoke.yml+18-0File content is under review, please try again later
M.gitignore+1-0File content is under review, please try again later
@@ -0,0 +1,37 @@
1+# Issue #1011 方案设计(Plan)
2+ 
3+> 需求见 spec.md(基线 = Issue 正文)。本文为技术方案。
4+ 
5+## 总体顺序(实现路径 0→4)
6+ 
7+0. **派生源修正收口(db_setup.py)**
8+ - 新迁移 `202611040001 issue-1011-engine-anchor-columns`(safe):agent_runtimes 加 5 列
9+ anchor 快照(engine_type / provider_id / template_id / provider_uid / template_uid)
10+ —— 注册路径(runtime.py register)持久化锚,使派生源可离线重算。
11+ - 新迁移 `202611040002 issue-101101-backfill-rederive-engine-uids`(backfill):
12+ 按当前 derive_engine_uid 公式全量重派生 agent_runtimes.engine_uid
13+ (uid 锚 → uid 公式;id 锚 → id 公式;无锚 → legacy 公式=原值零变更),
14+ uid 变化行经 rebase_engine_uid_references 改绑全部引用轨道(映射式,旧行 uid 从行内读取),
15+ 对账报告落盘(复用 `_write_uid_migration_report_file`,tag=1011)。
16+ - 报告补写:启动时对 646/868/1011 三个 tag 的迁移报告做「已盖章且报告文件缺失 → 补写空报告
17+ (注明『迁移已于先前版本执行』,幂等:文件已存在不重写)」。
18+1. **v2 端点(runtime.py)**:路由层薄壳 + uid→行解析 helper(`_resolve_runtime_by_uid`),
19+ bound 归属校验 uid 口径(`_require_runtime_owned_uid`),v1 路由与 service.claim/claim_by_tag 零改动。
20+2. **heartbeat-v2**:新 body 模型(HeartbeatBodyV2 = HeartbeatBody + engine_uids)+ 独立端点;
21+ 解析 uids→ids(credential 归属内)与 runtime_ids 合并去重后走与 v1 相同的更新逻辑
22+ (提取 `_apply_heartbeat_runtimes(c, ids, ...)` 公共函数,v1/v2 共用)。
23+3. **autopilot**:db_setup 加列 `engine_runtime_uids`;routes 校验 uid-first + 双非空拒绝 + 写侧升格;
24+ scheduler 入队 uid 模式 → pool_engine_uids 镜像(enqueue_task 已支持参数);
25+ 升格脚本 scripts/upgrade_autopilot_engine_uids.py(幂等 + 悬空报告);
26+ 前端 autopilot.js uid 优先 id 兜底。
27+4. **spec 勘误 + worker**:v2 spec §2.1/2.2 换真实路径;RuntimeClient 增加 v2-first 调用
28+ (uid 从 register 响应持久化到本地 JSON 文件;capabilities.uid_claim 探测;
29+ 空白 404/405 → 记忆切换 v1;UNKNOWN_ENGINE_UID → 回退 v1)。
30+ 
31+## 关键设计决策(照 Issue 正文「四、Technical Approach」)
32+ 
33+- v2 路径形态:路径参数 uid(/runtimes/uid/{uid}/tasks/claim 系)。
34+- 失效语义:4xx fail-fast(404 UNKNOWN_ENGINE_UID)。
35+- heartbeat v2:独立端点 `/heartbeat-v2`。
36+- autopilot 存储:姊妹字段。
37+- 测试先行红→绿;全部纳入 tests/atomic + linux-backend CI。
@@ -0,0 +1,30 @@
1+# Issue #1011 需求文档(Spec)
2+ 
3+> 基线:Issue #1011 正文(完整 spec 已在 Issue 正文,本文为开发侧要点摘录,权威以 Issue 正文「三、Scope / 五、Acceptance Criteria / 七、用例矩阵」为准)。
4+ 
5+## 目标
6+ 
7+在 #868 既有交付之上完成 uid 改造下一阶段代码落地:
8+ 
9+1. **In Scope 0**:engine_uid 派生源修正收口(存量重派生回填 + 已盖章库迁移报告补写)。
10+2. **In Scope 1**:claim-by-uid 协议 v2 端点(claim / claim-by-tag / claim-bound / claim-by-tag-bound / claim-capabilities / heartbeat-v2 / complete-v2 / fail-v2 / progress-v2),双端点并存 + uid 失效语义(回退 id / 双失效 404 UNKNOWN_ENGINE_UID)+ uid_claim 能力位。
11+3. **In Scope 2**:autopilot 前后端 uid 消费收尾(姊妹字段 engine_runtime_uids 方案)+ 存量升格脚本。
12+4. **In Scope 3**:v2 协议 spec(docs/issue-868/claim-by-uid-v2-protocol-spec.md)端点路径勘误。
13+5. **In Scope 4**:worker 侧 v2-first / v1-fallback 消费(404 语义二分)。
14+ 
15+## 关键语义(照 Issue 正文)
16+ 
17+- v2 路由寻址键 = engine_uid(路径参数 str),内部解析为 runtime_id 后**复用与 v1 完全相同的服务层逻辑**(语义零漂移)。
18+- uid 命中 → 认领,payload 双带 id+uid 三键(engine_uid / engine_name_snapshot / pool_engine_uids,#646/#868 已有)。
19+- uid 失效 + body.runtime_id 命中 → 回退 id 认领(并存期兜底)。
20+- 双失效 → 404 + 错误码 UNKNOWN_ENGINE_UID,绝不静默 200 空任务。
21+- heartbeat-v2:engine_uids 优先解析、失效回退 runtime_ids、全失效条目不造行(日志取证)。
22+- 上报 v2(complete/fail/progress):按 uid 校验任务归属(任务行 engine_uid 与上报引擎 uid 不一致 → 403/409)。
23+- 404 语义二分:空白 404(`{"detail":"Not Found"}`)= 旧服务端(worker 记忆切换 v1);body 带 UNKNOWN_ENGINE_UID = uid 失效(回退 v1,v1 再 404 才重注册)。
24+- autopilot 姊妹字段:engine_runtime_uids 与 engine_runtime_ids 并存;读侧 uids 非空优先;写侧升格(写 uids 清空 ids);双非空 400 拒绝;入队 uid 模式 → uid 池路径(pool_engine_uids 镜像)。
25+ 
26+## 测试 seam
27+ 
28+- 服务端:HTTP 端点层(FastAPI TestClient / 直接调用路由函数 + service 层)+ db_setup 迁移函数。
29+- worker 侧:RuntimeClient(封装 v2-first/fallback 决策,可单测)。
30+- 前端:autopilot.js 的 payload 构造/展示降级函数(js 测试沿用 #868 模式)。
@@ -0,0 +1,17 @@
1+# Issue #1011 任务拆解(Task)
2+ 
3+| # | 切片 | 交付 | 状态 |
4+|---|---|---|---|
5+| T0 | anchor 快照列迁移 + 注册路径持久化锚 | db_setup.py / runtime.py register | ✅ |
6+| T1 | 存量重派生回填迁移(幂等 + 对账报告落盘) | db_setup.py | ✅ |
7+| T2 | 已盖章库迁移报告补写(646/868/1011) | db_setup.py | ✅ |
8+| T3 | v2 claim 系端点 ×5(claim/by-tag/bound/by-tag-bound/capabilities)+ uid 归属校验 | routes/runtime.py | ✅ |
9+| T4 | heartbeat-v2(engine_uids 优先 + 回退 ids + 全失效不造行) | routes/runtime.py | ✅ |
10+| T5 | 上报 v2(complete/fail/progress 按 uid 校验归属) | routes/runtime.py | ✅ |
11+| T6 | autopilot 后端姊妹字段 + scheduler uid 池路径 + 升格脚本 | routes/autopilot.py / scheduler.py / scripts/ | ✅ |
12+| T7 | autopilot 前端 uid 优先 id 兜底 | static/js/pages/autopilot.js | ✅ |
13+| T8 | v2 spec §2.1/2.2 勘误 | docs/issue-868/claim-by-uid-v2-protocol-spec.md | ✅ |
14+| T9 | worker v2-first/v1-fallback + 404 二分 + uid 持久化 | runtime/client.py / agent.py | ✅ |
15+| T10 | 原子守卫测试 + linux-backend CI 挂载 | tests/atomic / windows-smoke.yml | ✅ |
16+ 
17+验证:`python3 -m pytest tests/atomic/test_issue_1011_*.py`(详见各测试文件头部)。
@@ -1,7 +1,8 @@
1-# claim-by-uid 协议 v2 设计 Spec(Issue #868 交付,只设计不切实现)1+# claim-by-uid 协议 v2 设计 Spec(Issue #868 设计交付;Issue #1011 实现落地 + 勘误)
2 2 
3-> 状态:设计稿(Design only)。本 Issue 不做协议切换,阶段 5 前完成设计即可(#646 Spec v3.1 排期)。3+> 状态:已实现(Issue #1011:v2 claim 系端点 / heartbeat-v2 / 上报 v2 / capabilities
4-> 背景:worker 认领(claim)链路当前以自增 `runtime_id` 寻址;`runtime_id` 跨刷新/重建会漂移4+> uid_claim 能力位 / worker v2-first 回退,端点形态见 §2.1 勘误后口径)。
5+> 背景:worker 认领(claim)链路 v1 以自增 `runtime_id` 寻址;`runtime_id` 跨刷新/重建会漂移
5> (#646 已为持久层引入 `engine_uid` UUIDv5 稳定键)。v2 的目标:上行寻址从 id 迁移到 uid,6> (#646 已为持久层引入 `engine_uid` UUIDv5 稳定键)。v2 的目标:上行寻址从 id 迁移到 uid,
6> 消除 worker 侧因引擎行重建导致的认领黑洞。7> 消除 worker 侧因引擎行重建导致的认领黑洞。
7 8 
@@ -21,27 +22,46 @@
21 22 
22### 2.1 双端点并存(兼容期核心设计)23### 2.1 双端点并存(兼容期核心设计)
23 24 
25+> **勘误(Issue #1011)**:原表所列 `POST /api/runtime/worker/claim`(既有)为臆造路径,
26+> 代码中不存在。真实既有 v1 端点为 `POST /api/runtime/runtimes/{runtime_id}/tasks/claim`
27+> (src/api/routes/runtime.py,路径参数 `runtime_id: int` = 自增 id 寻址,即 v1 的
28+> 漂移根源)及 claim-by-tag / claim-bound / claim-by-tag-bound / claim-capabilities
29+> 共 5 个变体。v2 已按真实路径形态实现(Issue #1011,与下表一致):
30+ 
24| 端点 | 寻址键 | 状态 | 说明 |31| 端点 | 寻址键 | 状态 | 说明 |
25|---|---|---|---|32|---|---|---|---|
26-| `POST /api/runtime/worker/claim`(既有) | `runtime_id` | 长期保留 | 旧 worker(存量版本)唯一路径 |33+| `POST /api/runtime/runtimes/{runtime_id}/tasks/claim`(既有 v1) | `runtime_id` | 长期保留 | 旧 worker(存量版本)唯一路径 |
27-| `POST /api/runtime/worker/v2/claim`(新增) | `engine_uid`(必填)+ `runtime_id`(可选,兜底锚) | 新增 | v2 worker 首选 |34+| `POST /api/runtime/runtimes/uid/{engine_uid}/tasks/claim`(v2,已实现) | `engine_uid`(路径)+ `runtime_id`(body 可选兜底锚) | 新增 | v2 worker 首选 |
35+| `POST /api/runtime/runtimes/uid/{engine_uid}/tasks/claim-by-tag/{tag}`(v2 变体,已实现) | 同上 | 新增 | tag 匹配 + scope 隔离(服务层与 v1 共用) |
36+| `POST /api/runtime/runtimes/uid/{engine_uid}/tasks/claim-bound`(v2 变体,已实现) | 同上 | 新增 | expected 原子校验;归属校验 uid 口径 |
37+| `POST /api/runtime/runtimes/uid/{engine_uid}/tasks/claim-by-tag-bound/{tag}`(v2 变体,已实现) | 同上 | 新增 | 同上 |
38+| `GET /api/runtime/runtimes/uid/{engine_uid}/tasks/claim-capabilities`(v2 只读,已实现) | 同上 | 新增 | 能力位含 `uid_claim`(worker v2 探测锚点) |
39+| `POST /api/runtime/heartbeat-v2`(已实现) | body `engine_uids[]` + `runtime_ids[]` | 新增 | uid 优先解析、失效回退 ids、全失效不造行 |
40+| `POST /api/runtime/tasks/{task_id}/complete-v2` / `fail-v2` / `progress-v2`(已实现) | body `engine_uid` | 新增 | 按 uid 校验任务归属(不一致 403) |
28 41 
29-- 心跳 / 任务结果上报同样提供 v2 端点(`/heartbeat/v2`、`/tasks/{id}/result/v2`),形态同上。42+- 心跳 / 任务结果上报同样提供 v2 端点(上表),v1 端点原样保留。
30- **不做协议切换**:v2 端点上线后 v1 保持可用,直到阶段 5 显式下线(需先统计 v1 流量归零)。43- **不做协议切换**:v2 端点上线后 v1 保持可用,直到阶段 5 显式下线(需先统计 v1 流量归零)。
44+- lookup / recover-orphans / tags 等其余 runtimes/{id} 路径端点**本 issue 不 v2 化**
45+ (非认领热路径,阶段 5 随 id 读路径清理统一处置,豁免清单)。
46+- **404 语义二分(Issue #1011 补,worker 回退逻辑前提)**:v2 端点 404 须区分
47+ ①端点不存在(`{"detail":"Not Found"}` 空白 404/405 = 旧服务端,worker 切换 v1
48+ 并记忆)②uid 失效(body 错误码 `UNKNOWN_ENGINE_UID` = uid 漂移,回退 v1 id claim)。
31 49 
32### 2.2 请求字段(v2 claim 示例)50### 2.2 请求字段(v2 claim 示例)
33 51 
34```json52```json
35{53{
36- "engine_uid": "82f61f47-13b4-57a2-996b-740510f7bebf",
37 "runtime_id": 3,54 "runtime_id": 3,
38- "capabilities": ["coding", "qa"],55+ "expected_task_id": "",
39- "lease": {"ttl": 60}56+ "expected_event_seq": 0,
57+ "supports_obs_url": true,
58+ "prefer_fallback": false
40}59}
41```60```
42 61 
43-- `engine_uid`:必填,36 位小写连字符 UUID(服务端校验 `is_uid_str`)。62+- `engine_uid`:路径参数,36 位小写连字符 UUID(服务端校验 uid→行解析,限本凭据)。
44-- `runtime_id`:可选,作为 uid 失效时的兜底锚与漂移检测输入。63+- `runtime_id`:body 可选,作为 uid 失效时的兜底锚与漂移检测输入。
64+- `expected_task_id` / `expected_event_seq`:成对可选(bound 语义,与 v1 同)。
45 65 
46### 2.3 服务端解析语义(uid 失效回退 runtime_id)66### 2.3 服务端解析语义(uid 失效回退 runtime_id)
47 67 
@@ -66,7 +86,7 @@ resolve(engine_uid, runtime_id):
66- uid 失效(404 UNKNOWN_ENGINE_UID)→ worker 降级 v1 端点按 `runtime_id` claim;86- uid 失效(404 UNKNOWN_ENGINE_UID)→ worker 降级 v1 端点按 `runtime_id` claim;
67 两者都失效 → 重新注册(register 端点本就幂等,重复注册 uid 不漂移,#646 T4 保证)。87 两者都失效 → 重新注册(register 端点本就幂等,重复注册 uid 不漂移,#646 T4 保证)。
68 88 
69-### 2.5 守卫测试设计(本期交付测试设计,不实现)89+### 2.5 守卫测试(Issue #1011 已实现:tests/atomic/test_issue_1011_claim_v2.py)
70 90 
71- `test_claim_v2_resolves_by_uid`:uid 命中 → 按该引擎认领。91- `test_claim_v2_resolves_by_uid`:uid 命中 → 按该引擎认领。
72- `test_claim_v2_uid_stale_falls_back_to_runtime_id`:uid 失效 + id 命中未迁移行 → 回退成功。92- `test_claim_v2_uid_stale_falls_back_to_runtime_id`:uid 失效 + id 命中未迁移行 → 回退成功。
Ascripts/upgrade_autopilot_engine_uids.py+147-0File content is under review, please try again later
Msrc/api/db_setup.py+157-0File content is under review, please try again later
Msrc/api/routes/autopilot.py+134-6File content is under review, please try again later
@@ -397,6 +397,17 @@ def runtime_register(body: RuntimeRegBody, request: Request, credential_id: int
397 1 if rt.get("healthy", True) else 0, 1, "online",397 1 if rt.get("healthy", True) else 0, 1, "online",
398 datetime.now(timezone.utc).isoformat(), rt.get("cli_path", ""), cred_scope, owner_id, _ls_json, cred_repo_key, body.cli_version, cred_org_id, _role_tags_json))398 datetime.now(timezone.utc).isoformat(), rt.get("cli_path", ""), cred_scope, owner_id, _ls_json, cred_repo_key, body.cli_version, cred_org_id, _role_tags_json))
399 rid = c.lastrowid399 rid = c.lastrowid
400+ # Issue #1011:锚快照持久化(engine_type/provider_id/template_id/
401+ # provider_uid/template_uid 五列,001 迁移加列)——派生源修正后
402+ # 存量行可离线重算(002 重派生迁移消费);未迁移旧库缺列时降级跳过。
403+ try:
404+ c.execute(
405+ "UPDATE agent_runtimes SET engine_type=?, provider_id=?, template_id=?, "
406+ "provider_uid=?, template_uid=? WHERE id=?",
407+ (_anchor[0] or "", _anchor[1] or "", _anchor[2] or "",
408+ _anchor[3] or "", _anchor[4] or "", rid))
409+ except Exception:
410+ pass
400 # 自动写入默认 "all" 标签——新引擎默认可认领任意角色任务。411 # 自动写入默认 "all" 标签——新引擎默认可认领任意角色任务。
401 # 若已有 capabilities 行则跳过(用户手动配置过标签的不覆盖)。412 # 若已有 capabilities 行则跳过(用户手动配置过标签的不覆盖)。
402 # tags_user_set=1 时也跳过(用户已手动清空/设过标签,心跳不再自动补 'all')413 # tags_user_set=1 时也跳过(用户已手动清空/设过标签,心跳不再自动补 'all')
@@ -967,6 +978,257 @@ def runtime_task_lookup(runtime_id: int,
967 return {"task": task}978 return {"task": task}
968 979 
969 980 
981+# ===== Issue #1011:claim-by-uid 协议 v2 端点(双端点并存期)=====
982+# 设计(docs/issue-868/claim-by-uid-v2-protocol-spec.md §2.1 勘误后口径):
983+# - v2 路由只做寻址键转换(uid → runtime_id),随后**直接调用 v1 路由函数**,
984+# 服务层逻辑与 v1 完全共用(语义零漂移);
985+# - uid 命中 → 按该引擎行认领;uid 失效 + body.runtime_id 命中 → 回退 id 认领
986+# (并存期兜底);双失效 → 404 UNKNOWN_ENGINE_UID(绝不静默 200 空任务);
987+# - v1 端点保留不变(旧 worker 唯一路径),v1 流量归零后阶段 5 统一下线。
988+ 
989+class RuntimeClaimBodyV2(RuntimeClaimBody):
990+ """v2 claim body:v1 字段 + runtime_id 兜底锚(uid 失效时回退 id 认领)。"""
991+ runtime_id: int = 0
992+ 
993+ 
994+class HeartbeatBodyV2(HeartbeatBody):
995+ """v2 心跳 body:v1 字段 + engine_uids 数组(uid 优先解析,失效回退 runtime_ids)。"""
996+ engine_uids: list[str] = []
997+ 
998+ 
999+class CompleteBodyV2(CompleteBody):
1000+ engine_uid: str = ""
1001+ 
1002+ 
1003+class FailBodyV2(FailBody):
1004+ engine_uid: str = ""
1005+ 
1006+ 
1007+class ProgressBodyV2(ProgressBody):
1008+ engine_uid: str = ""
1009+ 
1010+ 
1011+def _resolve_runtime_by_uid(engine_uid: str, fallback_runtime_id: int,
1012+ credential_id: int) -> int:
1013+ """v2 寻址解析:uid → runtime_id(限本 rta_ 凭据),双失效 404 UNKNOWN_ENGINE_UID。
1014+ 
1015+ - uid 命中(agent_runtimes.engine_uid 且 credential_id 匹配)→ 返回该行 id;
1016+ - uid 未命中(失效:引擎删除/合流重派生窗口/未迁移 NULL uid)且
1017+ fallback_runtime_id 非 0 且命中本凭据 → 回退该行 id(并存期兜底);
1018+ - 双失效 → 404(fail-fast,不静默造行;message 含 NULL uid 引擎的重注册提示)。
1019+ """
1020+ uid = (engine_uid or "").strip().lower()
1021+ if uid:
1022+ with db_lock:
1023+ c = db.cursor()
1024+ row = c.execute(
1025+ "SELECT id FROM agent_runtimes WHERE engine_uid=? AND credential_id=? LIMIT 1",
1026+ (uid, credential_id)).fetchone()
1027+ if row:
1028+ return row[0]
1029+ log.warning(f"v2 resolve: engine_uid not found (stale?): uid={uid} "
1030+ f"credential={credential_id} fallback_runtime_id={fallback_runtime_id}")
1031+ if fallback_runtime_id:
1032+ with db_lock:
1033+ c = db.cursor()
1034+ row = c.execute(
1035+ "SELECT id FROM agent_runtimes WHERE id=? AND credential_id=? LIMIT 1",
1036+ (fallback_runtime_id, credential_id)).fetchone()
1037+ if row:
1038+ return row[0]
1039+ raise HTTPException(status_code=404, detail={
1040+ "code": "UNKNOWN_ENGINE_UID",
1041+ "message": f"engine_uid '{uid or '(empty)'}' not found"
1042+ f"{' and runtime_id fallback missed' if fallback_runtime_id else ''}"
1043+ " (engine deleted or uid pending backfill; re-register to obtain a fresh uid)"})
1044+ 
1045+ 
1046+def _require_runtime_owned_uid(engine_uid: str, credential_id: int) -> int:
1047+ """v2 归属校验(claim-bound 系):上报 engine_uid 必须属于该 rta_ 凭据,否则 403。
1048+ 
1049+ 对应 v1 的 _require_runtime_owned(runtime_id 口径);返回解析出的 runtime_id。
1050+ """
1051+ uid = (engine_uid or "").strip().lower()
1052+ with db_lock:
1053+ c = db.cursor()
1054+ row = c.execute(
1055+ "SELECT id FROM agent_runtimes WHERE engine_uid=? AND credential_id=? LIMIT 1",
1056+ (uid, credential_id)).fetchone()
1057+ if not row:
1058+ raise HTTPException(status_code=403, detail={
1059+ "code": 403,
1060+ "message": "engine_uid not owned by this credential"})
1061+ return row[0]
1062+ 
1063+ 
1064+def _claim_body_v1(body: RuntimeClaimBodyV2 | None) -> RuntimeClaimBody | None:
1065+ """v2 claim body → v1 body(剥离 runtime_id 兜底锚,其余字段逐字段透传)。"""
1066+ if body is None:
1067+ return None
1068+ return RuntimeClaimBody(
1069+ supports_obs_url=body.supports_obs_url,
1070+ prefer_fallback=body.prefer_fallback,
1071+ expected_task_id=body.expected_task_id,
1072+ expected_event_seq=body.expected_event_seq)
1073+ 
1074+ 
1075+@router.post("/runtimes/uid/{engine_uid}/tasks/claim")
1076+def runtime_claim_v2(engine_uid: str, body: RuntimeClaimBodyV2 | None = None,
1077+ credential_id: int = Depends(_require_credential)):
1078+ """Issue #1011 v2 claim:按 engine_uid 认领(uid 失效回退 body.runtime_id)。
1079+ 
1080+ 寻址键转换后直接调 v1 runtime_claim(服务层语义零漂移);
1081+ payload 与 v1 一致双带 id+uid 三键(engine_uid/engine_name_snapshot/pool_engine_uids)。
1082+ """
1083+ rid = _resolve_runtime_by_uid(engine_uid, body.runtime_id if body else 0, credential_id)
1084+ return runtime_claim(rid, _claim_body_v1(body), credential_id)
1085+ 
1086+ 
1087+@router.post("/runtimes/uid/{engine_uid}/tasks/claim-by-tag/{tag}")
1088+def runtime_claim_by_tag_v2(engine_uid: str, tag: str,
1089+ body: RuntimeClaimBodyV2 | None = None,
1090+ credential_id: int = Depends(_require_credential)):
1091+ """Issue #1011 v2 claim-by-tag:uid 寻址 + v1 服务层(tag 匹配/scope 隔离零漂移)。"""
1092+ rid = _resolve_runtime_by_uid(engine_uid, body.runtime_id if body else 0, credential_id)
1093+ return runtime_claim_by_tag(rid, tag, _claim_body_v1(body), credential_id)
1094+ 
1095+ 
1096+@router.post("/runtimes/uid/{engine_uid}/tasks/claim-bound")
1097+def runtime_claim_bound_v2(engine_uid: str, body: RuntimeClaimBodyV2,
1098+ credential_id: int = Depends(_require_credential)):
1099+ """Issue #1011 v2 claim-bound:归属校验改 uid 口径(他人 uid → 403),其余同 v1。"""
1100+ rid = _require_runtime_owned_uid(engine_uid, credential_id)
1101+ return runtime_claim_bound(rid, _claim_body_v1(body), credential_id)
1102+ 
1103+ 
1104+@router.post("/runtimes/uid/{engine_uid}/tasks/claim-by-tag-bound/{tag}")
1105+def runtime_claim_by_tag_bound_v2(engine_uid: str, tag: str,
1106+ body: RuntimeClaimBodyV2,
1107+ credential_id: int = Depends(_require_credential)):
1108+ """Issue #1011 v2 claim-by-tag-bound:归属校验 uid 口径,其余同 v1。"""
1109+ rid = _require_runtime_owned_uid(engine_uid, credential_id)
1110+ return runtime_claim_by_tag_bound(rid, tag, _claim_body_v1(body), credential_id)
1111+ 
1112+ 
1113+@router.get("/runtimes/uid/{engine_uid}/tasks/claim-capabilities")
1114+def runtime_claim_capabilities_v2(engine_uid: str,
1115+ credential_id: int = Depends(_require_credential)):
1116+ """Issue #1011 v2 能力协商(只读):uid 形态 + uid_claim 能力位。
1117+ 
1118+ uid_claim=True 是 worker v2-first 的探测锚点(旧服务端该路径 404 空白 →
1119+ worker 判定对端不支持 v2 切换 v1 端点并记忆);旧客户端 GET v1 路径行为不变。
1120+ """
1121+ rid = _require_runtime_owned_uid(engine_uid, credential_id)
1122+ return {
1123+ "runtime_id": rid,
1124+ "engine_uid": (engine_uid or "").strip().lower(),
1125+ "capabilities": {
1126+ "bound_claim": True,
1127+ "task_lookup": True,
1128+ "uid_claim": True,
1129+ },
1130+ }
1131+ 
1132+ 
1133+@router.post("/heartbeat-v2")
1134+def runtime_heartbeat_v2(body: HeartbeatBodyV2, request: Request,
1135+ credential_id: int = Depends(_require_credential)):
1136+ """Issue #1011 v2 心跳:engine_uids 优先解析、失效回退 runtime_ids、全失效不造行。
1137+ 
1138+ 解析后委托 v1 runtime_heartbeat(心跳全逻辑共用,语义零漂移);
1139+ uid 失效条目仅日志取证(不造行,防 -cred0 孤儿),回退语义见 v2 spec §2.3。
1140+ """
1141+ resolved_ids: list[int] = []
1142+ stale_uids: list[str] = []
1143+ with db_lock:
1144+ c = db.cursor()
1145+ for _uid in (body.engine_uids or []):
1146+ uid = str(_uid or "").strip().lower()
1147+ if not uid:
1148+ continue
1149+ row = c.execute(
1150+ "SELECT id FROM agent_runtimes WHERE engine_uid=? AND credential_id=? LIMIT 1",
1151+ (uid, credential_id)).fetchone()
1152+ if row:
1153+ resolved_ids.append(row[0])
1154+ else:
1155+ stale_uids.append(uid)
1156+ for uid in stale_uids:
1157+ log.warning(f"heartbeat-v2: engine_uid not found (stale, no row created): "
1158+ f"uid={uid} credential={credential_id}")
1159+ merged = list(resolved_ids)
1160+ for rid in (body.runtime_ids or []):
1161+ if rid not in merged:
1162+ merged.append(rid)
1163+ v1_body = HeartbeatBody(
1164+ runtime_ids=merged,
1165+ cpu_percent=body.cpu_percent,
1166+ memory_percent=body.memory_percent,
1167+ disk_percent=body.disk_percent,
1168+ tmp_percent=body.tmp_percent,
1169+ bandwidth_percent=body.bandwidth_percent,
1170+ bandwidth_mbps=body.bandwidth_mbps,
1171+ load_avg=body.load_avg,
1172+ spec=body.spec,
1173+ log_lines=body.log_lines,
1174+ probe_results=body.probe_results)
1175+ resp = runtime_heartbeat(v1_body, request, credential_id)
1176+ resp["engine_uids_resolved"] = len(resolved_ids)
1177+ resp["engine_uids_stale"] = len(stale_uids)
1178+ return resp
1179+ 
1180+ 
1181+def _validate_task_engine_uid(task_id: str, engine_uid: str) -> None:
1182+ """Issue #1011 上报 v2:按 uid 校验任务归属(任务行 engine_uid 快照 vs 上报引擎 uid)。
1183+ 
1184+ - 上报 uid 与任务行快照不一致 → 403 TASK_ENGINE_UID_MISMATCH(明确拒绝,
1185+ 替代 v1 仅按 runtime_id 归属的口径);
1186+ - 任务行 uid 为空(legacy 任务/未迁移)→ 放行走 v1 语义(兼容期)。
1187+ """
1188+ uid = (engine_uid or "").strip().lower()
1189+ if not uid:
1190+ return
1191+ with db_lock:
1192+ c = db.cursor()
1193+ row = c.execute("SELECT engine_uid FROM agent_tasks WHERE id=?", (task_id,)).fetchone()
1194+ task_uid = (row[0] or "").strip().lower() if row else ""
1195+ if task_uid and task_uid != uid:
1196+ raise HTTPException(status_code=403, detail={
1197+ "code": "TASK_ENGINE_UID_MISMATCH",
1198+ "message": f"task '{task_id}' belongs to engine_uid '{task_uid}', "
1199+ f"reported by '{uid}'"})
1200+ 
1201+ 
1202+@router.post("/tasks/{task_id}/complete-v2")
1203+def runtime_task_complete_v2(task_id: str, body: CompleteBodyV2,
1204+ credential_id: int = Depends(_require_credential)):
1205+ """Issue #1011 v2 完成(幂等):按 uid 校验任务归属后委托 v1 逻辑。"""
1206+ _validate_task_engine_uid(task_id, body.engine_uid)
1207+ v1_body = CompleteBody(result_text=body.result_text, exit_code=body.exit_code,
1208+ session_id=body.session_id, work_dir=body.work_dir,
1209+ engine=body.engine, run_token=body.run_token)
1210+ return runtime_task_complete(task_id, v1_body, credential_id)
1211+ 
1212+ 
1213+@router.post("/tasks/{task_id}/fail-v2")
1214+def runtime_task_fail_v2(task_id: str, body: FailBodyV2,
1215+ credential_id: int = Depends(_require_credential)):
1216+ """Issue #1011 v2 失败:按 uid 校验任务归属后委托 v1 逻辑。"""
1217+ _validate_task_engine_uid(task_id, body.engine_uid)
1218+ v1_body = FailBody(error=body.error, failure_reason=body.failure_reason,
1219+ exit_code=body.exit_code, run_token=body.run_token)
1220+ return runtime_task_fail(task_id, v1_body, credential_id)
1221+ 
1222+ 
1223+@router.post("/tasks/{task_id}/progress-v2")
1224+def runtime_task_progress_v2(task_id: str, body: ProgressBodyV2,
1225+ credential_id: int = Depends(_require_credential)):
1226+ """Issue #1011 v2 进度:按 uid 校验任务归属后委托 v1 逻辑。"""
1227+ _validate_task_engine_uid(task_id, body.engine_uid)
1228+ v1_body = ProgressBody(summary=body.summary, step=body.step, total=body.total)
1229+ return runtime_task_progress(task_id, v1_body, credential_id)
1230+ 
1231+ 
970@router.post("/tasks/{task_id}/skill-zip")1232@router.post("/tasks/{task_id}/skill-zip")
971def runtime_task_skill_zip(task_id: str, credential_id: int = Depends(_require_credential)):1233def runtime_task_skill_zip(task_id: str, credential_id: int = Depends(_require_credential)):
972 """v3.0 服务端代拉(降级链 ②):worker URL 直连失败的兜底。1234 """v3.0 服务端代拉(降级链 ②):worker URL 直连失败的兜底。
Msrc/api/static/js/pages/autopilot.js+56-14File content is under review, please try again later
Msrc/runtime/agent.py+8-3File content is under review, please try again later
Msrc/runtime/client.py+245-4File content is under review, please try again later
@@ -556,6 +556,45 @@ def _engines_by_ids(engine_ids: list[int], repo: str, cfg: dict) -> list[dict]:
556 return members556 return members
557 557 
558 558 
559+def _engines_by_uids(engine_uids: list, repo: str) -> list[dict]:
560+ """Issue #1011:按 engine_uid 列表查引擎详情(uid 池路径,字段同 _engines_by_ids)。
561+ 
562+ uid 无效/未迁移(NULL uid)行不命中即排除——语义与 id 池一致;
563+ 未迁移旧库(缺 engine_uid 列)返回空列表(调用方按全灭处理)。
564+ """
565+ if not engine_uids:
566+ return []
567+ norm = [str(u or "").strip().lower() for u in engine_uids if str(u or "").strip()]
568+ if not norm:
569+ return []
570+ db, lock = _db()
571+ members = []
572+ with lock:
573+ c = db.cursor()
574+ try:
575+ placeholders = ",".join("?" * len(norm))
576+ c.execute(
577+ "SELECT r.id, r.name, r.status, r.healthy, r.installed, r.credential_id, r.last_seen_at, "
578+ " r.scope, r.owner_id, LOWER(r.engine_uid), "
579+ " COALESCE(rc.device_name, ''), COALESCE(rc.owner_name, ''), COALESCE(r.role_tags, '') "
580+ "FROM agent_runtimes r LEFT JOIN runtime_credentials rc ON rc.id = r.credential_id "
581+ f"WHERE LOWER(r.engine_uid) IN ({placeholders})",
582+ tuple(norm))
583+ rows = c.fetchall()
584+ except Exception as e:
585+ log.warning(f"_engines_by_uids failed: {e}")
586+ return []
587+ for r in rows:
588+ members.append({
589+ "runtime_id": r[0], "name": r[1] or "", "status": r[2] or "offline", "healthy": bool(r[3]),
590+ "installed": bool(r[4]), "credential_id": r[5] or 0, "last_seen_at": r[6] or "",
591+ "scope": r[7] or "global", "owner_id": r[8] or "", "engine_uid": r[9] or "",
592+ "device_name": r[10] or "",
593+ "owner_name": r[11] or "", "priority": 0, "role_tags": r[12] or "",
594+ })
595+ return members
596+ 
597+ 
559def _filter_by_tags(members: list[dict], agent_type: str) -> list[dict]:598def _filter_by_tags(members: list[dict], agent_type: str) -> list[dict]:
560 """过滤绑定集合,只保留标签匹配 agent_type 的引擎。"""599 """过滤绑定集合,只保留标签匹配 agent_type 的引擎。"""
561 if not agent_type or not members:600 if not agent_type or not members:
Msrc/runtime/scheduler.py+42-17File content is under review, please try again later
@@ -464,6 +464,31 @@ def _log_pool_skip_once(task_id, runtime_id: int, allowed):
464 f"of task {task_id}, skip (Issue #605)")464 f"of task {task_id}, skip (Issue #605)")
465 465 
466 466 
467+def _pool_filter_allows_uid(c, task_id: str, runtime_id: int) -> bool:
468+ """Issue #1011 UC-C1:pool 名单 uid 轨等价守卫。
469+ 
470+ 任务行 pool_engine_uids 非空时,认领引擎(runtime_id 解析出的 engine_uid)
471+ 在 uid 池内 → 放行(即使 pool_engine_ids 镜像缺失/未同步)。uid 池为空
472+ (selector 模式 / legacy 任务)→ False(不干预,走既有 id 轨判定)。
473+ Lock contract:调用方已持有 db_lock。
474+ """
475+ try:
476+ row = c.execute(
477+ "SELECT pool_engine_uids FROM agent_tasks WHERE id=?", (task_id,)).fetchone()
478+ uids_raw = (row[0] or "") if row else ""
479+ if not uids_raw:
480+ return False
481+ allowed_uids = json.loads(uids_raw)
482+ if not isinstance(allowed_uids, list) or not allowed_uids:
483+ return False
484+ urow = c.execute(
485+ "SELECT engine_uid FROM agent_runtimes WHERE id=?", (runtime_id,)).fetchone()
486+ uid = (urow[0] or "").strip().lower() if urow else ""
487+ return bool(uid) and uid in [str(u or "").strip().lower() for u in allowed_uids]
488+ except Exception:
489+ return False
490+ 
491+ 
467def _table_columns(table: str) -> set:492def _table_columns(table: str) -> set:
468 """表实际存在的列(PRAGMA,进程内缓存)。493 """表实际存在的列(PRAGMA,进程内缓存)。
469 494 
@@ -1338,6 +1363,11 @@ def claim(runtime_id, expected_task_id=None, expected_event_seq=None) -> dict |
1338 if _pe_row and _pe_row[0]:1363 if _pe_row and _pe_row[0]:
1339 try:1364 try:
1340 _allowed = json.loads(_pe_row[0])1365 _allowed = json.loads(_pe_row[0])
1366+ if _allowed and runtime_id not in _allowed:
1367+ # Issue #1011 UC-C1:uid 池轨等价守卫(uid 在 pool_engine_uids
1368+ # 名单内 → 放行;ids 镜像缺失/不同步时不误杀 uid 池任务)
1369+ if _pool_filter_allows_uid(c, row[0], runtime_id):
1370+ _allowed = None
1341 if _allowed and runtime_id not in _allowed:1371 if _allowed and runtime_id not in _allowed:
1342 db.commit()1372 db.commit()
1343 return None1373 return None
@@ -1409,6 +1439,11 @@ def claim(runtime_id, expected_task_id=None, expected_event_seq=None) -> dict |
1409 import json as _json1439 import json as _json
1410 try:1440 try:
1411 _allowed = _json.loads(_pe_row[0])1441 _allowed = _json.loads(_pe_row[0])
1442+ if _allowed and runtime_id not in _allowed:
1443+ # Issue #1011 UC-C1:uid 池轨等价守卫(uid 在 pool_engine_uids
1444+ # 名单内 → 放行,ids 镜像缺失/不同步不误杀 uid 池任务)
1445+ if _pool_filter_allows_uid(c, task_id, runtime_id):
1446+ _allowed = None
1412 if _allowed and runtime_id not in _allowed:1447 if _allowed and runtime_id not in _allowed:
1413 # 兜底:检查 pool_engine_ids 中的引擎是否全部不可达1448 # 兜底:检查 pool_engine_ids 中的引擎是否全部不可达
1414 # 不可达 = 离线 / 无对应 tag 能力 / scope 不匹配1449 # 不可达 = 离线 / 无对应 tag 能力 / scope 不匹配
@@ -1752,6 +1787,10 @@ def claim_by_tag(tag: str, runtime_id: int,
1752 if _pe_row and _pe_row[0]:1787 if _pe_row and _pe_row[0]:
1753 try:1788 try:
1754 _allowed = json.loads(_pe_row[0])1789 _allowed = json.loads(_pe_row[0])
1790+ if _allowed and runtime_id not in _allowed:
1791+ # Issue #1011 UC-C1:uid 池轨等价守卫(同 claim 处)
1792+ if _pool_filter_allows_uid(c, task_id, runtime_id):
1793+ _allowed = None
1755 if _allowed and runtime_id not in _allowed:1794 if _allowed and runtime_id not in _allowed:
1756 return None1795 return None
1757 except Exception:1796 except Exception:
@@ -1814,6 +1853,10 @@ def claim_by_tag(tag: str, runtime_id: int,
1814 import json as _json1853 import json as _json
1815 try:1854 try:
1816 _allowed = _json.loads(_pe_row[0])1855 _allowed = _json.loads(_pe_row[0])
1856+ if _allowed and runtime_id not in _allowed:
1857+ # Issue #1011 UC-C1:uid 池轨等价守卫(同 claim 处)
1858+ if _pool_filter_allows_uid(c, task_id, runtime_id):
1859+ _allowed = None
1817 if _allowed and runtime_id not in _allowed:1860 if _allowed and runtime_id not in _allowed:
1818 # 兜底:检查 pool_engine_ids 中的引擎是否全部不可达1861 # 兜底:检查 pool_engine_ids 中的引擎是否全部不可达
1819 # 不可达 = 离线 / 无对应 tag 能力 / scope 不匹配1862 # 不可达 = 离线 / 无对应 tag 能力 / scope 不匹配
Msrc/runtime/worker_report_queue.py+4-2File content is under review, please try again later
Atests/atomic/test_issue_1011_autopilot_uid.py+263-0File content is under review, please try again later
Atests/atomic/test_issue_1011_claim_v2.py+273-0File content is under review, please try again later
Atests/atomic/test_issue_1011_migrations.py+219-0File content is under review, please try again later
Atests/atomic/test_issue_1011_worker_v2.py+243-0File content is under review, please try again later
Atests/js/test_issue_1011_autopilot_uid.js+31-0File content is under review, please try again later