From d77d0bc7d618b1c1f3150273effe9def64835426 Mon Sep 17 00:00:00 2001 From: TangZ-L <345187680+TangZ-L@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:35:47 +0800 Subject: [PATCH 1/8] =?UTF-8?q?feat(m10):=20=E6=96=B0=E5=A2=9E=E6=9C=8D?= =?UTF-8?q?=E5=8A=A1=E4=BB=A4=E7=89=8C=E6=9C=BA=E5=99=A8=E8=BA=AB=E4=BB=BD?= =?UTF-8?q?=E4=B8=8E=E9=89=B4=E6=9D=83=E4=BE=9D=E8=B5=96=20(#429)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../m10-candidate-launch-override.en.md | 4 +- .../m10-candidate-launch-override.i18n.yaml | 4 +- .../issues/m10-candidate-launch-override.md | 4 +- backend/app/api/dependencies.py | 104 ++- backend/app/api/service_tokens.py | 93 +++ backend/app/main.py | 15 +- backend/app/models/__init__.py | 4 + backend/app/models/evaluation.py | 10 + backend/app/models/identity.py | 47 ++ backend/app/services/service_tokens.py | 417 +++++++++++++ .../migrations/versions/0035_service_token.py | 102 +++ tests/backend/test_service_tokens.py | 590 ++++++++++++++++++ 12 files changed, 1385 insertions(+), 9 deletions(-) create mode 100644 backend/app/api/service_tokens.py create mode 100644 backend/app/services/service_tokens.py create mode 100644 backend/migrations/versions/0035_service_token.py create mode 100644 tests/backend/test_service_tokens.py diff --git a/.agents/flow/issues/m10-candidate-launch-override.en.md b/.agents/flow/issues/m10-candidate-launch-override.en.md index 4b39ff37..984f2265 100644 --- a/.agents/flow/issues/m10-candidate-launch-override.en.md +++ b/.agents/flow/issues/m10-candidate-launch-override.en.md @@ -6,7 +6,7 @@ English | [中文](m10-candidate-launch-override.md) kind: issue milestone: m10 priority: P0 -status: ready +status: in-progress scope: - .agents/flow/issues/m10-candidate-launch-override.md - .agents/flow/issues/m10-candidate-launch-override.en.md @@ -18,6 +18,7 @@ scope: - backend/app/api/dependencies.py - backend/app/models/evaluation.py - backend/app/models/identity.py + - backend/app/models/__init__.py - backend/app/services/service_tokens.py - backend/app/api/service_tokens.py - backend/app/main.py @@ -28,6 +29,7 @@ scope: - docs/design/eval-platform-architecture.md - docs/design/eval-platform-architecture.en.md - docs/design/eval-platform-architecture.i18n.yaml + - scripts/doc-budgets.manifest.json adr: [] github: number: 429 diff --git a/.agents/flow/issues/m10-candidate-launch-override.i18n.yaml b/.agents/flow/issues/m10-candidate-launch-override.i18n.yaml index dbf6ec5c..d3f7a5db 100644 --- a/.agents/flow/issues/m10-candidate-launch-override.i18n.yaml +++ b/.agents/flow/issues/m10-candidate-launch-override.i18n.yaml @@ -1,5 +1,5 @@ # 双语配对一致性记录(docs/i18n/README.md):两侧在最后一次确认一致状态下的 # git blob hash。两种语言同等权威;编辑任一侧后带上另一侧,然后重录: # pnpm run record:i18n -- .agents/flow/issues/m10-candidate-launch-override.md -m10-candidate-launch-override.md: 9764f3009c23d705bbecae7081ae01b748b7a7d5 -m10-candidate-launch-override.en.md: 4b39ff374064102e9802e4a7d4be099c7a450975 +m10-candidate-launch-override.md: 9c020b1fed4b19ef8baf1616eaa107bbeda5f28d +m10-candidate-launch-override.en.md: 984f22654df2c29fe3cfc523abcbfa974ddea202 diff --git a/.agents/flow/issues/m10-candidate-launch-override.md b/.agents/flow/issues/m10-candidate-launch-override.md index 9764f300..9c020b1f 100644 --- a/.agents/flow/issues/m10-candidate-launch-override.md +++ b/.agents/flow/issues/m10-candidate-launch-override.md @@ -6,7 +6,7 @@ kind: issue milestone: m10 priority: P0 -status: ready +status: in-progress scope: - .agents/flow/issues/m10-candidate-launch-override.md - .agents/flow/issues/m10-candidate-launch-override.en.md @@ -18,6 +18,7 @@ scope: - backend/app/api/dependencies.py - backend/app/models/evaluation.py - backend/app/models/identity.py + - backend/app/models/__init__.py - backend/app/services/service_tokens.py - backend/app/api/service_tokens.py - backend/app/main.py @@ -28,6 +29,7 @@ scope: - docs/design/eval-platform-architecture.md - docs/design/eval-platform-architecture.en.md - docs/design/eval-platform-architecture.i18n.yaml + - scripts/doc-budgets.manifest.json adr: [] github: number: 429 diff --git a/backend/app/api/dependencies.py b/backend/app/api/dependencies.py index 131698fa..2479c352 100644 --- a/backend/app/api/dependencies.py +++ b/backend/app/api/dependencies.py @@ -1,7 +1,18 @@ -"""FastAPI dependencies for console session and role enforcement.""" +"""FastAPI dependencies for console session and role enforcement. + +M10 (#429) adds the machine-identity path: ``require_session_or_service`` +accepts either the console session cookie or ``Authorization: Bearer hev_...``. +A service token must carry the scope the route declares and, for launches, the +requested template must be inside the token's allowlist. A present but +malformed ``Authorization`` header is always a 401 — it never silently falls +back to the cookie, so a caller cannot mistake a broken machine credential for +a working console session. +""" from __future__ import annotations +from collections.abc import Callable +from dataclasses import dataclass from typing import Annotated from fastapi import Depends, HTTPException, Request @@ -9,12 +20,28 @@ from ..config import Settings, get_settings from ..db import get_session +from ..models import SERVICE_TOKEN_SCOPES, ServiceToken from ..services import identity +from ..services import service_tokens as token_service from .errors import error_detail SessionDep = Annotated[Session, Depends(get_session)] SettingsDep = Annotated[Settings, Depends(get_settings)] +SCOPE_EVAL_LAUNCH = "eval:launch" +SCOPE_EVAL_READ = "eval:read" + + +@dataclass(frozen=True) +class Actor: + """The authenticated principal of a stable execution API call.""" + + label: str + is_admin: bool + is_service: bool + scopes: frozenset[str] = frozenset() + service_token: ServiceToken | None = None + def _unauthenticated(message: str = "登录已失效,请重新登录。") -> HTTPException: return HTTPException( @@ -23,6 +50,13 @@ def _unauthenticated(message: str = "登录已失效,请重新登录。") -> H ) +def _forbidden(message: str) -> HTTPException: + return HTTPException( + status_code=403, + detail=error_detail("forbidden", message), + ) + + def _resolve( request: Request, session: Session, @@ -64,3 +98,71 @@ def require_admin( detail=error_detail("forbidden", "当前账号没有写入权限。"), ) return context + + +def _service_actor( + request: Request, + session: Session, + header: str, + *, + scope: str, +) -> Actor: + parts = header.strip().split(None, 1) + if len(parts) != 2 or parts[0].lower() != "bearer": + raise _unauthenticated("服务令牌格式不正确,请使用 Bearer hev_... 认证。") + raw_token = parts[1].strip() + if not raw_token.startswith(token_service.TOKEN_PREFIX): + raise _unauthenticated("服务令牌格式不正确,请使用 Bearer hev_... 认证。") + token = token_service.authenticate(session, raw_token) + if token is None: + raise _unauthenticated("服务令牌无效、已撤销或已过期。") + scopes = frozenset(str(item) for item in (token.scopes_json or [])) + if scope not in scopes: + raise _forbidden("服务令牌缺少所需权限。") + if scope == SCOPE_EVAL_LAUNCH: + allowlist = [str(item) for item in (token.template_allowlist_json or [])] + if allowlist: + template_id = str(request.path_params.get("template_id") or "") + if template_id not in allowlist: + raise _forbidden("服务令牌无权启动该模板。") + return Actor( + label=token_service.actor_label(token), + is_admin=False, + is_service=True, + scopes=scopes, + service_token=token, + ) + + +def require_session_or_service(scope: str) -> Callable[..., Actor]: + """Build the dependency for a stable execution route. + + ``scope`` is one of ``SERVICE_TOKEN_SCOPES``: ``eval:launch`` additionally + requires the admin role for a console session, while ``eval:read`` accepts + any authenticated role. + """ + + if scope not in SERVICE_TOKEN_SCOPES: + raise ValueError(f"unknown service token scope: {scope}") + + def dependency( + request: Request, + session: SessionDep, + settings: SettingsDep, + ) -> Actor: + header = request.headers.get("Authorization") + if header is not None: + return _service_actor(request, session, header, scope=scope) + context = _resolve(request, session, settings) + if context is None: + raise _unauthenticated() + request.state.auth = context + if scope == SCOPE_EVAL_LAUNCH and context.role != identity.ROLE_ADMIN: + raise _forbidden("当前账号没有写入权限。") + return Actor( + label=context.user.email, + is_admin=context.role == identity.ROLE_ADMIN, + is_service=False, + ) + + return dependency diff --git a/backend/app/api/service_tokens.py b/backend/app/api/service_tokens.py new file mode 100644 index 00000000..12108510 --- /dev/null +++ b/backend/app/api/service_tokens.py @@ -0,0 +1,93 @@ +"""M10 (#429): admin API for service tokens (machine identity). + +Creating, listing and revoking tokens stays a console administrator action, so +every route depends on :func:`require_admin`. The plaintext is returned exactly +once by ``POST``; ``GET`` only exposes metadata and ``DELETE`` revokes (never +deletes) so a revoked token keeps its audit trail. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Literal + +from fastapi import APIRouter, Depends, HTTPException, Response +from pydantic import BaseModel, Field +from sqlalchemy.orm import Session + +from ..db import get_session +from ..services import identity +from ..services import service_tokens as token_service +from .dependencies import require_admin +from .errors import error_detail + +router = APIRouter(tags=["service-tokens"]) + + +class ServiceTokenCreateRequest(BaseModel): + name: str = Field(min_length=1, max_length=100) + scopes: list[Literal["eval:launch", "eval:read"]] = Field(min_length=1) + template_allowlist: list[str] = Field(default_factory=list) + max_concurrent_runs: int | None = Field(default=None, ge=1) + daily_budget_cny: float | None = Field(default=None, ge=0) + expires_at: datetime | None = None + + +def _http_error(error: token_service.ServiceTokenError) -> HTTPException: + details = dict(error.details or {}) + if error.field: + fields = dict(details.get("fields") or {}) + fields[error.field] = "invalid" + details["fields"] = fields + return HTTPException( + status_code=error.status, + detail=error_detail(error.code, str(error), details=details or None), + ) + + +@router.post("/api/v1/service-tokens", status_code=201) +def create_service_token( + payload: ServiceTokenCreateRequest, + session: Session = Depends(get_session), + context: identity.AuthContext = Depends(require_admin), +) -> dict: + """Create a token; the plaintext is returned here and never again.""" + + try: + token, plaintext = token_service.create_token( + session, + payload.model_dump(), + created_by=context.user.email, + ) + except token_service.ServiceTokenError as error: + raise _http_error(error) from error + return { + "status": "ok", + "service_token": token_service.token_view(token), + "token": plaintext, + } + + +@router.get("/api/v1/service-tokens") +def list_service_tokens( + session: Session = Depends(get_session), + _context: identity.AuthContext = Depends(require_admin), +) -> dict: + tokens = token_service.list_tokens(session) + return { + "status": "ok", + "items": [token_service.token_view(token) for token in tokens], + } + + +@router.delete("/api/v1/service-tokens/{token_id}", status_code=204) +def revoke_service_token( + token_id: str, + session: Session = Depends(get_session), + _context: identity.AuthContext = Depends(require_admin), +) -> Response: + try: + token_service.revoke_token(session, token_id) + except token_service.ServiceTokenError as error: + raise _http_error(error) from error + return Response(status_code=204) diff --git a/backend/app/main.py b/backend/app/main.py index f731cd32..d3c98827 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -25,6 +25,7 @@ from .api.runners import router as runners_router from .api.runtimes import router as runtimes_router from .api.self_evolution import router as self_evolution_router +from .api.service_tokens import router as service_tokens_router from .api.traces import router as traces_router from .api.webhooks import router as webhooks_router from .config import get_settings @@ -75,9 +76,13 @@ def create_app() -> FastAPI: app.include_router(overview_router, dependencies=[Depends(require_session)]) app.include_router(runners_router) app.include_router(evaluations_router, dependencies=[Depends(require_session)]) - # M10 (#378): reusable launch presets; launch requires the admin role and - # is enforced inside the router, list/detail stay session-readable. - app.include_router(eval_templates_router, dependencies=[Depends(require_session)]) + # M10 (#378): reusable launch presets. The router declares authentication + # per route: launch requires the admin role (M10 #429: or an eval:launch + # service token), list/detail any console session. + app.include_router(eval_templates_router) + # M10 (#429): service tokens are managed by console administrators only; + # every route declares ``require_admin`` itself. + app.include_router(service_tokens_router) app.include_router(datasets_router, dependencies=[Depends(require_session)]) app.include_router(dataset_image_sources_router, dependencies=[Depends(require_session)]) # M8 (#290): per-preparation tarball readiness/ensure/retry polling. @@ -85,7 +90,9 @@ def create_app() -> FastAPI: dataset_image_artifacts_router, dependencies=[Depends(require_session)] ) app.include_router(agent_assets_router, dependencies=[Depends(require_session)]) - app.include_router(results_router, dependencies=[Depends(require_session)]) + # M10 (#378): stable status/results read models. Authentication is declared + # per route (console session, or an eval:read service token in M10 #429). + app.include_router(results_router) app.include_router(traces_router, dependencies=[Depends(require_session)]) app.include_router(eval_workbench_router, dependencies=[Depends(require_session)]) app.include_router(runtimes_router, dependencies=[Depends(require_session)]) diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index 1ad9e595..5de22e4e 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -39,10 +39,12 @@ EvalTemplate, ) from .identity import ( + SERVICE_TOKEN_SCOPES, AuditLog, AuthSession, Membership, Project, + ServiceToken, Tenant, User, Workspace, @@ -91,6 +93,8 @@ "Membership", "AuthSession", "AuditLog", + "ServiceToken", + "SERVICE_TOKEN_SCOPES", "Outbox", "ServiceHeartbeat", "Deployment", diff --git a/backend/app/models/evaluation.py b/backend/app/models/evaluation.py index 3236fcb3..4228f21f 100644 --- a/backend/app/models/evaluation.py +++ b/backend/app/models/evaluation.py @@ -156,6 +156,16 @@ class EvalRun(Base, TimestampMixin): template_snapshot_json: Mapped[dict] = mapped_column( json_type(), default=dict, nullable=False, server_default="{}" ) + # M10 (#429): machine-triggered launches may pin the run to a candidate + # commit and carry evolution provenance. Both are frozen on the run so a + # later template edit or token rotation cannot rewrite what was measured; + # ``{}`` keeps runs created by the console one-click path unchanged. + asset_override_json: Mapped[dict] = mapped_column( + json_type(), default=dict, nullable=False, server_default="{}" + ) + evolution_lineage_json: Mapped[dict] = mapped_column( + json_type(), default=dict, nullable=False, server_default="{}" + ) # M4-02 cancellation/reconciliation: the dispatched GitHub workflow run and # the client cancellation request are tracked on the run (A2 consumes both). github_run_id: Mapped[str | None] = mapped_column(String(64), nullable=True) diff --git a/backend/app/models/identity.py b/backend/app/models/identity.py index 0e6b8c8e..0f516525 100644 --- a/backend/app/models/identity.py +++ b/backend/app/models/identity.py @@ -1,6 +1,7 @@ from __future__ import annotations from datetime import datetime +from decimal import Decimal from sqlalchemy import ( Boolean, @@ -9,6 +10,8 @@ ForeignKey, ForeignKeyConstraint, Index, + Integer, + Numeric, String, UniqueConstraint, text, @@ -136,6 +139,50 @@ class AuthSession(Base, CreatedAtMixin): ) +SERVICE_TOKEN_SCOPES = ("eval:launch", "eval:read") + + +class ServiceToken(Base, TimestampMixin): + """M10 (#429): machine identity for template launches and result reads. + + Automation (harness-evolution) cannot hold a browser session, so template + launch and the stable status/results reads also accept a bearer service + token. Only the SHA-256 hex of the full plaintext is persisted; the + plaintext is returned exactly once by the creation call. Scopes, an optional + template allowlist and optional concurrency/budget caps are stored per token + so the API can enforce the caller's authority without another lookup table. + """ + + __tablename__ = "service_token" + + id: Mapped[str] = mapped_column(String(36), primary_key=True, default=new_id) + tenant_id: Mapped[str] = tenant_fk() + name: Mapped[str] = mapped_column(String(100), nullable=False) + token_hash: Mapped[str] = mapped_column(String(64), unique=True, nullable=False) + scopes_json: Mapped[list] = mapped_column(json_type(), default=list, nullable=False) + # Empty means every template; otherwise the ids the token may launch. + template_allowlist_json: Mapped[list] = mapped_column( + json_type(), default=list, nullable=False + ) + max_concurrent_runs: Mapped[int | None] = mapped_column(Integer, nullable=True) + daily_budget_cny: Mapped[Decimal | None] = mapped_column(Numeric(12, 6), nullable=True) + expires_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) + revoked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) + last_used_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) + created_by: Mapped[str] = mapped_column(String(128), nullable=False) + + __table_args__ = ( + UniqueConstraint("tenant_id", "name", name="uq_service_token_tenant_name"), + UniqueConstraint("tenant_id", "id", name="uq_service_token_tenant_id_id"), + Index( + "ix_service_token_tenant_revoked_created", + "tenant_id", + "revoked_at", + "created_at", + ), + ) + + class AuditLog(Base, CreatedAtMixin): """Minimal audit trail for identity events (login/logout/password reset).""" diff --git a/backend/app/services/service_tokens.py b/backend/app/services/service_tokens.py new file mode 100644 index 00000000..fd840fc3 --- /dev/null +++ b/backend/app/services/service_tokens.py @@ -0,0 +1,417 @@ +"""M10 (#429): service tokens — machine identity for template launches. + +Harness-evolution and other automation cannot hold a browser session, so the +stable execution APIs also accept a bearer service token. This module owns the +credential lifecycle, the scope/allowlist checks and the launch caps. + +Security contract: + +* the plaintext (``hev_`` + 32 random URL-safe bytes) is returned exactly once, + by :func:`create_token`, and never persisted or logged; +* only the SHA-256 hex of the full plaintext is stored, so a leaked row cannot + be replayed as a credential; +* revoked and expired tokens never authenticate, and the last successful use is + recorded for audit; +* launch caps are enforced before any asset work or run creation, so an + over-limit caller cannot consume capacity. + +Errors carry ``status``/``code``/``field``/``details`` so the API layer can +reuse the console's shared ``{"error": {...}}`` envelope. +""" + +from __future__ import annotations + +import hashlib +import secrets +from datetime import UTC, datetime +from decimal import Decimal, InvalidOperation +from typing import Any + +from sqlalchemy import func, select +from sqlalchemy.exc import IntegrityError +from sqlalchemy.orm import Session + +from ..defaults import DEFAULT_TENANT_ID +from ..models import SERVICE_TOKEN_SCOPES, EvalRun, ServiceToken +from ..money import MoneyError, money_str, money_value +from .evaluations import TERMINAL_RUN_STATUSES + +# The plaintext prefix is part of the contract: the auth dependency rejects a +# bearer value that does not start with it, and support can tell a service +# token apart from a console session at a glance. +TOKEN_PREFIX = "hev_" +TOKEN_BYTES = 32 + +MAX_NAME_LENGTH = 100 +MAX_ALLOWLIST_ITEMS = 100 +MAX_TEMPLATE_ID_LENGTH = 36 +MAX_CREATED_BY_LENGTH = 128 + + +class ServiceTokenError(Exception): + """Base error mapped to the console's ``{"error": {...}}`` envelope.""" + + status = 422 + code = "service_token_invalid" + + def __init__( + self, + message: str, + *, + field: str | None = None, + details: dict | None = None, + code: str | None = None, + ) -> None: + super().__init__(message) + self.field = field + self.details = details or {} + if code: + self.code = code + + +class ServiceTokenInvalid(ServiceTokenError): + status = 422 + code = "service_token_invalid" + + +class ServiceTokenNotFound(ServiceTokenError): + status = 404 + code = "service_token_not_found" + + +class ServiceTokenConflict(ServiceTokenError): + status = 409 + code = "service_token_name_conflict" + + +class ServiceTokenLimit(ServiceTokenError): + status = 429 + code = "service_token_limit_exceeded" + + +def _now(now: datetime | None) -> datetime: + return now or datetime.now(UTC) + + +def _as_utc(value: datetime | None) -> datetime | None: + """SQLite returns naive datetimes for timezone=True columns.""" + + if value is None: + return None + if value.tzinfo is None: + return value.replace(tzinfo=UTC) + return value.astimezone(UTC) + + +def _iso(value: datetime | None) -> str | None: + value = _as_utc(value) + return value.isoformat().replace("+00:00", "Z") if value is not None else None + + +def _hash_token(raw_token: str) -> str: + return hashlib.sha256(raw_token.encode("utf-8")).hexdigest() + + +def _is_active(token: ServiceToken, *, now: datetime | None = None) -> bool: + if token.revoked_at is not None: + return False + expires_at = _as_utc(token.expires_at) + return expires_at is None or expires_at > _now(now) + + +def _invalid(message: str, *, field: str) -> ServiceTokenInvalid: + return ServiceTokenInvalid(message, field=field) + + +def _name(value: Any) -> str: + if not isinstance(value, str): + raise _invalid("服务令牌名称必须是字符串", field="name") + name = value.strip() + if not name: + raise _invalid("服务令牌名称不能为空", field="name") + if len(name) > MAX_NAME_LENGTH: + raise _invalid(f"服务令牌名称不能超过 {MAX_NAME_LENGTH} 个字符", field="name") + return name + + +def _scopes(value: Any) -> list[str]: + if not isinstance(value, (list, tuple)): + raise _invalid("服务令牌 scope 必须是数组", field="scopes") + scopes: list[str] = [] + for item in value: + if not isinstance(item, str) or item not in SERVICE_TOKEN_SCOPES: + allowed = "、".join(SERVICE_TOKEN_SCOPES) + raise _invalid(f"服务令牌 scope 只能是 {allowed}", field="scopes") + if item not in scopes: + scopes.append(item) + if not scopes: + raise _invalid("服务令牌至少需要一个 scope", field="scopes") + return scopes + + +def _template_allowlist(value: Any) -> list[str]: + if value is None: + return [] + if not isinstance(value, (list, tuple)): + raise _invalid("模板白名单必须是数组", field="template_allowlist") + if len(value) > MAX_ALLOWLIST_ITEMS: + raise _invalid( + f"模板白名单不能超过 {MAX_ALLOWLIST_ITEMS} 个模板", + field="template_allowlist", + ) + allowlist: list[str] = [] + for item in value: + if not isinstance(item, str): + raise _invalid("模板白名单只能包含模板 ID 字符串", field="template_allowlist") + template_id = item.strip() + if not template_id: + raise _invalid("模板白名单不能包含空模板 ID", field="template_allowlist") + if len(template_id) > MAX_TEMPLATE_ID_LENGTH: + raise _invalid( + f"模板 ID 不能超过 {MAX_TEMPLATE_ID_LENGTH} 个字符", + field="template_allowlist", + ) + if template_id not in allowlist: + allowlist.append(template_id) + return allowlist + + +def _max_concurrent_runs(value: Any) -> int | None: + if value is None: + return None + if isinstance(value, bool) or not isinstance(value, int): + raise _invalid("并发上限必须是整数", field="max_concurrent_runs") + if value < 1: + raise _invalid("并发上限必须大于等于 1", field="max_concurrent_runs") + return value + + +def _daily_budget(value: Any) -> Decimal | None: + if value is None: + return None + try: + amount = money_value(value) + except (MoneyError, InvalidOperation, TypeError, ValueError) as error: + raise _invalid("当日预算必须是数字", field="daily_budget_cny") from error + if not amount.is_finite(): + raise _invalid("当日预算必须是有限数字", field="daily_budget_cny") + if amount < 0: + raise _invalid("当日预算必须大于等于 0", field="daily_budget_cny") + return amount + + +def _expires_at(value: Any, *, now: datetime) -> datetime | None: + if value is None: + return None + if not isinstance(value, datetime) or value.tzinfo is None: + raise _invalid("过期时间必须是带时区的日期时间", field="expires_at") + expires_at = value.astimezone(UTC) + if expires_at <= now: + raise _invalid("过期时间必须晚于当前时间", field="expires_at") + return expires_at + + +def create_token( + session: Session, + data: dict, + *, + created_by: str, + now: datetime | None = None, +) -> tuple[ServiceToken, str]: + """Create a token and return ``(row, plaintext)``. + + The plaintext is the only copy that will ever exist outside the caller's + hands: it is not stored, not logged and not derivable from ``token_hash``. + """ + + if not isinstance(data, dict): + raise ServiceTokenInvalid("请求体必须是对象") + current = _now(now) + name = _name(data.get("name")) + scopes = _scopes(data.get("scopes")) + allowlist = _template_allowlist(data.get("template_allowlist")) + max_concurrent_runs = _max_concurrent_runs(data.get("max_concurrent_runs")) + daily_budget_cny = _daily_budget(data.get("daily_budget_cny")) + expires_at = _expires_at(data.get("expires_at"), now=current) + + existing = session.scalar( + select(ServiceToken.id).where( + ServiceToken.tenant_id == str(DEFAULT_TENANT_ID), + ServiceToken.name == name, + ) + ) + if existing is not None: + raise ServiceTokenConflict("服务令牌名称已存在", field="name") + + plaintext = TOKEN_PREFIX + secrets.token_urlsafe(TOKEN_BYTES) + token = ServiceToken( + tenant_id=str(DEFAULT_TENANT_ID), + name=name, + token_hash=_hash_token(plaintext), + scopes_json=scopes, + template_allowlist_json=allowlist, + max_concurrent_runs=max_concurrent_runs, + daily_budget_cny=daily_budget_cny, + expires_at=expires_at, + created_by=str(created_by or "")[:MAX_CREATED_BY_LENGTH], + ) + session.add(token) + try: + session.commit() + except IntegrityError as error: + # A concurrent create can win the unique-name race after the pre-check. + session.rollback() + raise ServiceTokenConflict("服务令牌名称已存在", field="name") from error + return token, plaintext + + +def list_tokens(session: Session) -> list[ServiceToken]: + """Tenant tokens, newest first. Never includes secret material.""" + + return list( + session.scalars( + select(ServiceToken) + .where(ServiceToken.tenant_id == str(DEFAULT_TENANT_ID)) + .order_by(ServiceToken.created_at.desc(), ServiceToken.id.desc()) + ) + ) + + +def _get_token(session: Session, token_id: str) -> ServiceToken: + token = session.scalar( + select(ServiceToken).where( + ServiceToken.id == token_id, + ServiceToken.tenant_id == str(DEFAULT_TENANT_ID), + ) + ) + if token is None: + raise ServiceTokenNotFound("服务令牌不存在") + return token + + +def revoke_token( + session: Session, token_id: str, *, now: datetime | None = None +) -> ServiceToken: + """Revoke a token. Revoking an already revoked token is idempotent and keeps + the first timestamp, so the audit trail does not move.""" + + token = _get_token(session, token_id) + if token.revoked_at is None: + token.revoked_at = _now(now) + session.commit() + return token + + +def authenticate( + session: Session, raw_token: str | None, *, now: datetime | None = None +) -> ServiceToken | None: + """Resolve a bearer plaintext to its active row, recording the last use. + + Missing, malformed, unknown, revoked and expired tokens all return ``None`` + so the dependency can answer one generic 401 without leaking which check + failed. + """ + + if not raw_token or not isinstance(raw_token, str): + return None + if not raw_token.startswith(TOKEN_PREFIX): + return None + token = session.scalar( + select(ServiceToken).where( + ServiceToken.token_hash == _hash_token(raw_token), + ServiceToken.tenant_id == str(DEFAULT_TENANT_ID), + ) + ) + if token is None: + return None + current = _now(now) + if not _is_active(token, now=current): + return None + token.last_used_at = current + session.commit() + return token + + +def enforce_launch_caps( + session: Session, token: ServiceToken, *, now: datetime | None = None +) -> None: + """Reject a launch that would exceed the token's concurrency/budget caps. + + Both caps count the runs the token itself created (``created_by`` is the + ``svc:`` actor label), so a console user with the same template is + never charged to the machine identity. + """ + + current = _now(now) + actor = actor_label(token) + tenant_id = str(DEFAULT_TENANT_ID) + + if token.max_concurrent_runs is not None: + active = int( + session.scalar( + select(func.count()) + .select_from(EvalRun) + .where( + EvalRun.tenant_id == tenant_id, + EvalRun.created_by == actor, + EvalRun.status.not_in(TERMINAL_RUN_STATUSES), + ) + ) + or 0 + ) + cap = int(token.max_concurrent_runs) + if active >= cap: + raise ServiceTokenLimit( + f"服务令牌的并发评测数已达上限({active}/{cap})", + details={ + "limit": "max_concurrent_runs", + "cap": cap, + "active": active, + }, + ) + + if token.daily_budget_cny is not None: + day_start = current.replace(hour=0, minute=0, second=0, microsecond=0) + spent = session.scalar( + select(func.coalesce(func.sum(EvalRun.budget_spent_cny), 0)).where( + EvalRun.tenant_id == tenant_id, + EvalRun.created_by == actor, + EvalRun.created_at >= day_start, + ) + ) + spent_amount = money_value(spent) if spent is not None else Decimal("0") + cap_amount = money_value(token.daily_budget_cny) + if spent_amount >= cap_amount: + raise ServiceTokenLimit( + "服务令牌的当日预算已用尽", + details={ + "limit": "daily_budget_cny", + "cap": money_str(cap_amount), + "spent": money_str(spent_amount), + }, + ) + + +def token_view(token: ServiceToken) -> dict: + """Admin-facing view: metadata only, never the hash or the plaintext.""" + + return { + "id": token.id, + "name": token.name, + "scopes": list(token.scopes_json or []), + "template_allowlist": list(token.template_allowlist_json or []), + "max_concurrent_runs": token.max_concurrent_runs, + "daily_budget_cny": money_str(token.daily_budget_cny), + "expires_at": _iso(token.expires_at), + "revoked_at": _iso(token.revoked_at), + "last_used_at": _iso(token.last_used_at), + "created_by": token.created_by, + "created_at": _iso(token.created_at), + "active": _is_active(token), + } + + +def actor_label(token: ServiceToken) -> str: + """The ``created_by``/audit label a machine-triggered run records.""" + + return f"svc:{token.name}" diff --git a/backend/migrations/versions/0035_service_token.py b/backend/migrations/versions/0035_service_token.py new file mode 100644 index 00000000..ff6087ca --- /dev/null +++ b/backend/migrations/versions/0035_service_token.py @@ -0,0 +1,102 @@ +"""service tokens for machine-triggered template launches + +Revision ID: 0035_service_token +Revises: 0034_pool_unique_labels +Create Date: 2026-11-25 + +M10 (#429): harness-evolution cannot hold a browser session, so the platform +gains a machine identity. ``service_token`` stores only the SHA-256 hex of a +``hev_`` bearer token (the plaintext is returned once at creation), together +with its scopes, an optional template allowlist and optional concurrency/budget +caps. The two new ``eval_run`` columns freeze the candidate asset override and +the evolution lineage on the run itself; both default to ``{}`` so every run +created before this revision keeps the console's one-click semantics. +""" + +from __future__ import annotations + +from collections.abc import Sequence + +import sqlalchemy as sa +from alembic import op +from sqlalchemy.dialects import postgresql + +revision: str = "0035_service_token" +down_revision: str | None = "0034_pool_unique_labels" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + +_JSON = sa.JSON().with_variant(postgresql.JSONB(astext_type=sa.Text()), "postgresql") + + +def upgrade() -> None: + op.create_table( + "service_token", + sa.Column("id", sa.String(length=36), nullable=False), + sa.Column("tenant_id", sa.String(length=36), nullable=False), + sa.Column("name", sa.String(length=100), nullable=False), + sa.Column("token_hash", sa.String(length=64), nullable=False), + sa.Column("scopes_json", _JSON, nullable=False), + sa.Column("template_allowlist_json", _JSON, nullable=False), + sa.Column("max_concurrent_runs", sa.Integer(), nullable=True), + sa.Column("daily_budget_cny", sa.Numeric(precision=12, scale=6), nullable=True), + sa.Column("expires_at", sa.DateTime(timezone=True), nullable=True), + sa.Column("revoked_at", sa.DateTime(timezone=True), nullable=True), + sa.Column("last_used_at", sa.DateTime(timezone=True), nullable=True), + sa.Column("created_by", sa.String(length=128), nullable=False), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("CURRENT_TIMESTAMP"), + nullable=False, + ), + sa.Column( + "updated_at", + sa.DateTime(timezone=True), + server_default=sa.text("CURRENT_TIMESTAMP"), + nullable=False, + ), + sa.ForeignKeyConstraint( + ["tenant_id"], + ["tenant.id"], + name="fk_service_token_tenant_id_tenant", + ondelete="RESTRICT", + ), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("tenant_id", "name", name="uq_service_token_tenant_name"), + sa.UniqueConstraint("tenant_id", "id", name="uq_service_token_tenant_id_id"), + sa.UniqueConstraint("token_hash", name="uq_service_token_token_hash"), + ) + op.create_index("ix_service_token_tenant_id", "service_token", ["tenant_id"]) + op.create_index( + "ix_service_token_tenant_revoked_created", + "service_token", + ["tenant_id", "revoked_at", "created_at"], + ) + + op.add_column( + "eval_run", + sa.Column( + "asset_override_json", + _JSON, + server_default=sa.text("'{}'"), + nullable=False, + ), + ) + op.add_column( + "eval_run", + sa.Column( + "evolution_lineage_json", + _JSON, + server_default=sa.text("'{}'"), + nullable=False, + ), + ) + + +def downgrade() -> None: + op.drop_column("eval_run", "evolution_lineage_json") + op.drop_column("eval_run", "asset_override_json") + op.drop_index("ix_service_token_tenant_revoked_created", table_name="service_token") + op.drop_index("ix_service_token_tenant_id", table_name="service_token") + op.drop_table("service_token") diff --git a/tests/backend/test_service_tokens.py b/tests/backend/test_service_tokens.py new file mode 100644 index 00000000..cf6b891e --- /dev/null +++ b/tests/backend/test_service_tokens.py @@ -0,0 +1,590 @@ +"""M10 (#429): service tokens and the session-or-service auth dependency. + +These tests pin the machine-identity contract: the plaintext is returned once +and stored only as SHA-256, the admin management API is session-only, revoked +and expired tokens never authenticate, and ``require_session_or_service`` +enforces scope plus the template allowlist without ever falling back to the +cookie when a Bearer header is malformed. +""" + +from __future__ import annotations + +import hashlib +from datetime import UTC, datetime, timedelta +from decimal import Decimal + +import pytest +from app.api.dependencies import Actor, require_session_or_service +from app.config import get_settings +from app.defaults import DEFAULT_PROJECT_ID, DEFAULT_TENANT_ID +from app.models import ( + SERVICE_TOKEN_SCOPES, + EvalRun, + ServiceToken, + Tenant, + User, + Workspace, +) +from app.services import identity, service_tokens +from conftest import ( + TEST_ADMIN_EMAIL, + TEST_ADMIN_PASSWORD, + TEST_VIEWER_EMAIL, + TEST_VIEWER_PASSWORD, +) +from fastapi import HTTPException +from fastapi.testclient import TestClient +from sqlalchemy import func, select +from sqlalchemy.orm import Session +from starlette.requests import Request + +FUTURE = datetime.now(UTC) + timedelta(days=30) + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _login(client: TestClient, email: str, password: str): + return client.post( + "/api/v1/auth/login", json={"email": email, "password": password} + ) + + +def _add_viewer(session: Session) -> User: + tenant = session.scalar(select(Tenant).where(Tenant.slug == "default")) + workspace = session.scalar(select(Workspace).where(Workspace.tenant_id == tenant.id)) + user = identity.upsert_member( + session, + email=TEST_VIEWER_EMAIL, + password=TEST_VIEWER_PASSWORD, + tenant=tenant, + workspace=workspace, + role=identity.ROLE_VIEWER, + is_default=True, + ) + session.commit() + return user + + +def _make_token(session: Session, **overrides) -> tuple[ServiceToken, str]: + data = {"name": "he-bot", "scopes": ["eval:launch", "eval:read"]} + data.update(overrides) + token, plaintext = service_tokens.create_token( + session, data, created_by=TEST_ADMIN_EMAIL + ) + return token, plaintext + + +def _request( + *, + authorization: str | None = None, + cookie: str | None = None, + path_params: dict | None = None, +) -> Request: + headers: list[tuple[bytes, bytes]] = [] + if authorization is not None: + headers.append((b"authorization", authorization.encode("utf-8"))) + if cookie is not None: + headers.append((b"cookie", cookie.encode("utf-8"))) + return Request( + { + "type": "http", + "method": "POST", + "path": "/api/v1/eval-templates/tmpl/launch", + "headers": headers, + "path_params": path_params or {}, + "query_string": b"", + } + ) + + +def _call_dependency(session: Session, scope: str, request: Request) -> Actor: + dependency = require_session_or_service(scope) + return dependency(request=request, session=session, settings=get_settings()) + + +def _error_code(error: HTTPException) -> str: + return error.detail["error"]["code"] + + +def _session_cookie(session: Session, email: str) -> str: + settings = get_settings() + user = session.scalar(select(User).where(User.email == email)) + membership = identity.get_default_membership(session, user.id) + _auth_session, token, _expires_at = identity.create_session( + session, user=user, membership=membership, settings=settings + ) + session.commit() + return f"{settings.auth_cookie_name}={token}" + + +# --------------------------------------------------------------------------- +# Creation and persistence +# --------------------------------------------------------------------------- + + +def test_create_returns_plaintext_once_and_persists_only_the_hash( + client: TestClient, session: Session +) -> None: + response = client.post( + "/api/v1/service-tokens", + json={ + "name": "harness-evolution", + "scopes": ["eval:launch", "eval:read", "eval:launch"], + "template_allowlist": ["tmpl-a", "tmpl-a", "tmpl-b"], + "max_concurrent_runs": 2, + "daily_budget_cny": 12.5, + "expires_at": FUTURE.isoformat(), + }, + ) + + assert response.status_code == 201, response.text + body = response.json() + assert body["status"] == "ok" + plaintext = body["token"] + assert plaintext.startswith("hev_") and len(plaintext) > 40 + assert response.text.count(plaintext) == 1 + + view = body["service_token"] + assert view["name"] == "harness-evolution" + assert view["scopes"] == ["eval:launch", "eval:read"] + assert view["template_allowlist"] == ["tmpl-a", "tmpl-b"] + assert view["max_concurrent_runs"] == 2 + assert Decimal(str(view["daily_budget_cny"])) == Decimal("12.5") + assert view["active"] is True + assert view["revoked_at"] is None + assert view["last_used_at"] is None + assert view["created_by"] == TEST_ADMIN_EMAIL + assert "token" not in view and "token_hash" not in view + + stored = session.scalar(select(ServiceToken).where(ServiceToken.name == "harness-evolution")) + assert stored is not None + assert stored.token_hash == hashlib.sha256(plaintext.encode("utf-8")).hexdigest() + assert len(stored.token_hash) == 64 + assert plaintext not in stored.token_hash + assert stored.scopes_json == ["eval:launch", "eval:read"] + assert stored.daily_budget_cny == Decimal("12.5") + + # The list endpoint is masked: no plaintext and no hash ever leaves the API. + listed = client.get("/api/v1/service-tokens") + assert listed.status_code == 200, listed.text + items = listed.json()["items"] + assert [item["name"] for item in items] == ["harness-evolution"] + assert plaintext not in listed.text + assert "token_hash" not in listed.text + assert items[0]["id"] == view["id"] + assert "token" not in items[0] + + +def test_duplicate_name_conflicts_without_creating_a_second_row( + client: TestClient, session: Session +) -> None: + payload = {"name": "dup-bot", "scopes": ["eval:read"]} + first = client.post("/api/v1/service-tokens", json=payload) + assert first.status_code == 201, first.text + + second = client.post("/api/v1/service-tokens", json=payload) + assert second.status_code == 409, second.text + error = second.json()["detail"]["error"] + assert error["code"] == "service_token_name_conflict" + assert error["details"]["fields"]["name"] == "invalid" + assert ( + session.scalar(select(func.count()).select_from(ServiceToken)) == 1 + ) + + +def test_payload_validation_rejects_bad_fields( + client: TestClient, session: Session +) -> None: + invalid_http = [ + {"name": "x", "scopes": []}, + {"name": "x", "scopes": ["eval:admin"]}, + {"name": "", "scopes": ["eval:read"]}, + {"name": "x" * 101, "scopes": ["eval:read"]}, + {"name": "x", "scopes": ["eval:read"], "max_concurrent_runs": 0}, + {"name": "x", "scopes": ["eval:read"], "daily_budget_cny": -1}, + ] + for payload in invalid_http: + response = client.post("/api/v1/service-tokens", json=payload) + assert response.status_code == 422, (payload, response.text) + + naive_expiry = client.post( + "/api/v1/service-tokens", + json={ + "name": "naive-bot", + "scopes": ["eval:read"], + "expires_at": "2030-01-01T00:00:00", + }, + ) + assert naive_expiry.status_code == 422 + error = naive_expiry.json()["detail"]["error"] + assert error["code"] == "service_token_invalid" + assert error["details"]["fields"]["expires_at"] == "invalid" + assert session.scalar(select(func.count()).select_from(ServiceToken)) == 0 + + invalid_service = [ + ({"name": "", "scopes": ["eval:read"]}, "name"), + ({"name": "x", "scopes": []}, "scopes"), + ({"name": "x", "scopes": ["eval:write"]}, "scopes"), + ({"name": "x", "scopes": ["eval:read"], "template_allowlist": ["t" * 37]}, + "template_allowlist"), + ({"name": "x", "scopes": ["eval:read"], "template_allowlist": [1]}, + "template_allowlist"), + ({"name": "x", "scopes": ["eval:read"], "max_concurrent_runs": True}, + "max_concurrent_runs"), + ({"name": "x", "scopes": ["eval:read"], "daily_budget_cny": "free"}, + "daily_budget_cny"), + ({"name": "x", "scopes": ["eval:read"], + "expires_at": datetime.now(UTC) - timedelta(minutes=1)}, "expires_at"), + ({"name": "x", "scopes": ["eval:read"], "expires_at": datetime(2030, 1, 1)}, + "expires_at"), + ] + for data, field in invalid_service: + with pytest.raises(service_tokens.ServiceTokenInvalid) as raised: + service_tokens.create_token(session, data, created_by=TEST_ADMIN_EMAIL) + assert raised.value.status == 422 + assert raised.value.code == "service_token_invalid" + assert raised.value.field == field + + +def test_management_requires_an_admin_session( + client: TestClient, session: Session +) -> None: + _add_viewer(session) + client.cookies.clear() + assert _login(client, TEST_VIEWER_EMAIL, TEST_VIEWER_PASSWORD).status_code == 200 + + payload = {"name": "viewer-bot", "scopes": ["eval:read"]} + assert client.post("/api/v1/service-tokens", json=payload).status_code == 403 + assert client.get("/api/v1/service-tokens").status_code == 403 + assert client.delete("/api/v1/service-tokens/missing").status_code == 403 + + client.cookies.clear() + anonymous = client.post("/api/v1/service-tokens", json=payload) + assert anonymous.status_code == 401 + assert anonymous.json()["detail"]["error"]["code"] == "unauthenticated" + + assert _login(client, TEST_ADMIN_EMAIL, TEST_ADMIN_PASSWORD).status_code == 200 + assert client.post("/api/v1/service-tokens", json=payload).status_code == 201 + + +# --------------------------------------------------------------------------- +# Revocation, expiry and last use +# --------------------------------------------------------------------------- + + +def test_revoke_returns_204_and_blocks_authentication( + client: TestClient, session: Session +) -> None: + created = client.post( + "/api/v1/service-tokens", + json={"name": "revoke-bot", "scopes": ["eval:launch"]}, + ) + assert created.status_code == 201, created.text + token_id = created.json()["service_token"]["id"] + plaintext = created.json()["token"] + assert service_tokens.authenticate(session, plaintext) is not None + + revoked = client.delete(f"/api/v1/service-tokens/{token_id}") + assert revoked.status_code == 204 + assert revoked.text == "" + stored = session.get(ServiceToken, token_id) + assert stored.revoked_at is not None + first_revoked_at = stored.revoked_at + assert service_tokens.authenticate(session, plaintext) is None + assert service_tokens.token_view(stored)["active"] is False + + # Idempotent: a second revoke keeps the original audit timestamp. + assert client.delete(f"/api/v1/service-tokens/{token_id}").status_code == 204 + session.refresh(stored) + assert stored.revoked_at == first_revoked_at + + missing = client.delete("/api/v1/service-tokens/does-not-exist") + assert missing.status_code == 404 + assert missing.json()["detail"]["error"]["code"] == "service_token_not_found" + + +def test_authenticate_records_last_use_and_rejects_expiry(session: Session) -> None: + token, plaintext = _make_token(session, name="used-bot") + assert token.last_used_at is None + + resolved = service_tokens.authenticate(session, plaintext) + assert resolved is not None + assert resolved.id == token.id + assert token.last_used_at is not None + + token.expires_at = datetime.now(UTC) - timedelta(seconds=1) + session.commit() + assert service_tokens.authenticate(session, plaintext) is None + + expired, expired_plaintext = _make_token(session, name="expired-bot") + expired.expires_at = datetime.now(UTC) - timedelta(days=1) + session.commit() + assert service_tokens.authenticate(session, expired_plaintext) is None + + assert service_tokens.authenticate(session, "hev_unknown") is None + assert service_tokens.authenticate(session, "plain-token") is None + assert service_tokens.authenticate(session, "") is None + assert service_tokens.authenticate(session, None) is None + + +# --------------------------------------------------------------------------- +# Session-or-service dependency +# --------------------------------------------------------------------------- + + +def test_dependency_accepts_an_in_scope_service_token(session: Session) -> None: + _token, plaintext = _make_token(session, name="launch-bot") + request = _request( + authorization=f"Bearer {plaintext}", path_params={"template_id": "tmpl-a"} + ) + + actor = _call_dependency(session, "eval:launch", request) + + assert isinstance(actor, Actor) + assert actor.label == "svc:launch-bot" + assert actor.is_service is True + assert actor.is_admin is False + assert actor.scopes == frozenset(SERVICE_TOKEN_SCOPES) + assert actor.service_token is not None + assert actor.service_token.name == "launch-bot" + + +def test_dependency_enforces_scope_and_template_allowlist(session: Session) -> None: + _read_token, read_plaintext = _make_token( + session, name="read-bot", scopes=["eval:read"] + ) + with pytest.raises(HTTPException) as raised: + _call_dependency( + session, + "eval:launch", + _request(authorization=f"Bearer {read_plaintext}"), + ) + assert raised.value.status_code == 403 + assert _error_code(raised.value) == "forbidden" + # ``eval:read`` is the same token's scope, so reads pass. + read_actor = _call_dependency( + session, "eval:read", _request(authorization=f"Bearer {read_plaintext}") + ) + assert read_actor.scopes == frozenset({"eval:read"}) + + _scoped, scoped_plaintext = _make_token( + session, + name="allow-bot", + scopes=["eval:launch"], + template_allowlist=["tmpl-a"], + ) + allowed = _call_dependency( + session, + "eval:launch", + _request( + authorization=f"Bearer {scoped_plaintext}", + path_params={"template_id": "tmpl-a"}, + ), + ) + assert allowed.label == "svc:allow-bot" + for path_params in ({"template_id": "tmpl-b"}, {}): + with pytest.raises(HTTPException) as denied: + _call_dependency( + session, + "eval:launch", + _request( + authorization=f"Bearer {scoped_plaintext}", + path_params=path_params, + ), + ) + assert denied.value.status_code == 403 + + # An empty allowlist means every template. + _open, open_plaintext = _make_token(session, name="open-bot", scopes=["eval:launch"]) + open_actor = _call_dependency( + session, + "eval:launch", + _request( + authorization=f"Bearer {open_plaintext}", + path_params={"template_id": "any-template"}, + ), + ) + assert open_actor.is_service is True + + +def test_dependency_rejects_bad_or_dead_bearer_tokens(session: Session) -> None: + _token, plaintext = _make_token(session, name="dead-bot") + service_tokens.revoke_token(session, _token.id) + + cases = [ + "Token " + plaintext, + "Bearer plain-token", + "Bearer " + "x" * 40, + "Bearer", + "Bearer " + plaintext, # revoked + ] + for header in cases: + with pytest.raises(HTTPException) as raised: + _call_dependency( + session, + "eval:launch", + _request(authorization=header, path_params={"template_id": "tmpl"}), + ) + assert raised.value.status_code == 401 + assert _error_code(raised.value) == "unauthenticated" + + with pytest.raises(ValueError): + require_session_or_service("eval:write") + + +def test_malformed_bearer_never_falls_back_to_the_console_cookie( + client: TestClient, session: Session +) -> None: + cookie = _session_cookie(session, TEST_ADMIN_EMAIL) + + # A valid cookie alone passes the admin launch check... + actor = _call_dependency( + session, + "eval:launch", + _request(cookie=cookie, path_params={"template_id": "tmpl-a"}), + ) + assert actor.label == TEST_ADMIN_EMAIL + assert actor.is_admin is True and actor.is_service is False + + # ...but a present Authorization header wins, and a malformed one is a 401 + # instead of silently degrading to the cookie. + with pytest.raises(HTTPException) as raised: + _call_dependency( + session, + "eval:launch", + _request( + authorization="Basic abc", + cookie=cookie, + path_params={"template_id": "tmpl-a"}, + ), + ) + assert raised.value.status_code == 401 + + with pytest.raises(HTTPException) as anonymous: + _call_dependency(session, "eval:read", _request()) + assert anonymous.value.status_code == 401 + + +def test_session_branch_keeps_role_semantics( + client: TestClient, session: Session +) -> None: + viewer = _add_viewer(session) + viewer_cookie = _session_cookie(session, viewer.email) + + with pytest.raises(HTTPException) as denied: + _call_dependency( + session, + "eval:launch", + _request(cookie=viewer_cookie, path_params={"template_id": "tmpl-a"}), + ) + assert denied.value.status_code == 403 + + read_request = _request(cookie=viewer_cookie) + reader = _call_dependency(session, "eval:read", read_request) + assert reader.is_admin is False + assert reader.is_service is False + assert read_request.state.auth.user.email == viewer.email + + admin_request = _request( + cookie=_session_cookie(session, TEST_ADMIN_EMAIL), + path_params={"template_id": "tmpl-a"}, + ) + admin = _call_dependency(session, "eval:launch", admin_request) + assert admin.is_admin is True + assert admin_request.state.auth.role == identity.ROLE_ADMIN + + +# --------------------------------------------------------------------------- +# Launch caps +# --------------------------------------------------------------------------- + + +def _run(session: Session, *, key: str, status: str, **overrides) -> EvalRun: + values = { + "tenant_id": str(DEFAULT_TENANT_ID), + "project_id": str(DEFAULT_PROJECT_ID), + "name": f"run-{key}", + "idempotency_key": key, + "created_by": "svc:capped-bot", + "status": status, + } + values.update(overrides) + run = EvalRun(**values) + session.add(run) + session.commit() + return run + + +def test_eval_run_override_columns_default_to_empty(session: Session) -> None: + run = _run(session, key="override-default", status="queued") + assert run.asset_override_json == {} + assert run.evolution_lineage_json == {} + + +def test_concurrency_cap_blocks_only_non_terminal_runs(session: Session) -> None: + token, _plaintext = _make_token( + session, name="capped-bot", scopes=["eval:launch"], max_concurrent_runs=1 + ) + assert service_tokens.enforce_launch_caps(session, token) is None + + run = _run(session, key="concurrency-1", status="running") + with pytest.raises(service_tokens.ServiceTokenLimit) as raised: + service_tokens.enforce_launch_caps(session, token) + assert raised.value.status == 429 + assert raised.value.code == "service_token_limit_exceeded" + assert raised.value.details["limit"] == "max_concurrent_runs" + assert raised.value.details["active"] == 1 + + run.status = "completed" + session.commit() + assert service_tokens.enforce_launch_caps(session, token) is None + + # Runs created by someone else never count against the machine identity. + _run( + session, + key="concurrency-other", + status="running", + created_by=TEST_ADMIN_EMAIL, + ) + assert service_tokens.enforce_launch_caps(session, token) is None + + +def test_daily_budget_cap_counts_today_spend(session: Session) -> None: + token, _plaintext = _make_token( + session, + name="budget-bot", + scopes=["eval:launch"], + daily_budget_cny=5, + ) + _run( + session, + key="budget-1", + status="completed", + created_by="svc:budget-bot", + budget_spent_cny=Decimal("7.500000"), + ) + with pytest.raises(service_tokens.ServiceTokenLimit) as raised: + service_tokens.enforce_launch_caps(session, token) + assert raised.value.code == "service_token_limit_exceeded" + assert raised.value.details["limit"] == "daily_budget_cny" + assert Decimal(str(raised.value.details["cap"])) == Decimal("5") + assert Decimal(str(raised.value.details["spent"])) == Decimal("7.5") + + # Yesterday's spend is outside the UTC-day window: 7.5 today is under an 8 + # cap, but 7.5 + 3 would not be, so this also proves the window. + yesterday = datetime.now(UTC) - timedelta(days=1) + _run( + session, + key="budget-yesterday", + status="completed", + created_by="svc:budget-bot", + budget_spent_cny=Decimal("3"), + created_at=yesterday, + ) + generous, _ = _make_token( + session, name="budget-ok-bot", scopes=["eval:launch"], daily_budget_cny=8 + ) + assert service_tokens.enforce_launch_caps(session, generous) is None From 67e07d6109cdf0607dca149125d298f94354a3f7 Mon Sep 17 00:00:00 2001 From: TangZ-L <345187680+TangZ-L@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:05:06 +0800 Subject: [PATCH 2/8] =?UTF-8?q?feat(m10):=20=E6=A8=A1=E6=9D=BF=E5=90=AF?= =?UTF-8?q?=E5=8A=A8=E6=94=AF=E6=8C=81=E5=80=99=E9=80=89=20commit=20?= =?UTF-8?q?=E6=B3=A8=E5=85=A5=E4=B8=8E=E6=9C=8D=E5=8A=A1=E4=BB=A4=E7=89=8C?= =?UTF-8?q?=E9=89=B4=E6=9D=83=20(#429)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/api/eval_templates.py | 68 ++- backend/app/api/results.py | 32 +- backend/app/services/eval_templates.py | 387 ++++++++++++- tests/backend/test_eval_templates.py | 748 ++++++++++++++++++++++++- 4 files changed, 1210 insertions(+), 25 deletions(-) diff --git a/backend/app/api/eval_templates.py b/backend/app/api/eval_templates.py index 4f076d34..e69c7866 100644 --- a/backend/app/api/eval_templates.py +++ b/backend/app/api/eval_templates.py @@ -13,7 +13,8 @@ from ..db import get_session from ..services import eval_templates as template_service from ..services import identity -from .dependencies import require_admin, require_session +from ..services import service_tokens as token_service +from .dependencies import Actor, require_admin, require_session, require_session_or_service from .errors import error_detail from .evaluations import CaseSelectionRequest, ExecutionPolicyRequest @@ -86,12 +87,41 @@ class TemplateUpdateRequest(BaseModel): enabled: bool | None = None +class AssetOverrideRequest(BaseModel): + """M10 (#429): optional candidate asset selection for a machine launch. + + Whole-field replacement semantics: a field that is absent inherits the + template; a field that is present replaces the template value entirely (no + merging). ``commit`` is the authoritative identity and ``ref`` is display + and audit only, so a candidate is always pinned by commit. + """ + + repo_url: str | None = Field(default=None, max_length=500) + ref: str | None = Field(default=None, max_length=200) + commit: str | None = Field(default=None, pattern="^[0-9a-f]{40}$") + asset_paths: list[str] | None = None + asset_types: dict[str, str] | None = None + + +class LaunchLineageRequest(BaseModel): + """Caller provenance stored on the run; never part of evaluation semantics.""" + + evolutionRunId: str | None = Field(default=None, max_length=64) + evolutionRoundId: str | None = Field(default=None, max_length=64) + roundSeq: int | None = Field(default=None, ge=1) + parentCommit: str | None = Field(default=None, max_length=40) + + class LaunchTemplateRequest(BaseModel): idempotency_key: str | None = Field(default=None, max_length=128) name: str | None = Field(default=None, max_length=200) + asset_override: AssetOverrideRequest | None = None + lineage: LaunchLineageRequest | None = None -def _http_error(error: template_service.TemplateError) -> HTTPException: +def _http_error( + error: template_service.TemplateError | token_service.ServiceTokenError, +) -> HTTPException: details = dict(error.details or {}) if error.field: fields = dict(details.get("fields") or {}) @@ -238,22 +268,38 @@ def launch_eval_template( payload: LaunchTemplateRequest, idempotency_header: Annotated[str | None, Header(alias="Idempotency-Key")] = None, session: Session = Depends(get_session), - context: identity.AuthContext = Depends(require_admin), + context: Actor = Depends(require_session_or_service("eval:launch")), ) -> dict: key = (idempotency_header or payload.idempotency_key or "").strip() if not key: key = str(uuid.uuid4()) + asset_override = ( + payload.asset_override.model_dump(exclude_unset=True) + if payload.asset_override is not None + else None + ) + lineage = ( + payload.lineage.model_dump(exclude_unset=True) + if payload.lineage is not None + else None + ) try: - run, created = template_service.launch_template( + run, created, launch_meta = template_service.launch_template( session, template_id, idempotency_key=key, - created_by=context.user.email, + created_by=context.label, name=(payload.name or "").strip() or None, + asset_override=asset_override, + lineage=lineage, + service_token=context.service_token, ) - except template_service.TemplateError as error: + except ( + template_service.TemplateError, + token_service.ServiceTokenError, + ) as error: raise _http_error(error) from error - return { + body = { "run_id": run.id, "template_id": template_id, "status": run.status, @@ -261,3 +307,11 @@ def launch_eval_template( "result_url": f"/api/v1/eval-runs/{run.id}/results", "created": created, } + # Console compatibility: the one-click launch never received an override, + # so its 202 body stays byte-for-byte identical to the pre-#429 contract. + if payload.asset_override is not None or run.asset_override_json: + body["asset"] = launch_meta.get("asset") + warnings = launch_meta.get("warnings") or [] + if warnings: + body["warnings"] = warnings + return body diff --git a/backend/app/api/results.py b/backend/app/api/results.py index 461f2104..097713b1 100644 --- a/backend/app/api/results.py +++ b/backend/app/api/results.py @@ -16,9 +16,11 @@ ) from ..scoring.service import case_test_summary from ..seed import ensure_default_scope -from ..services import comparison, token_usage +from ..services import comparison, identity, token_usage from ..services import evaluations as evaluation_service +from ..services.eval_templates import run_asset_identity from ..services.evaluations import TERMINAL_RUN_STATUSES, iso_utc +from .dependencies import Actor, require_session, require_session_or_service router = APIRouter(tags=["results"]) @@ -174,7 +176,9 @@ def _token_metric_items( @router.get("/api/v1/eval-runs/{run_id}/results") def get_eval_results( - run_id: str, session: Session = Depends(get_session) + run_id: str, + session: Session = Depends(get_session), + _actor: Actor = Depends(require_session_or_service("eval:read")), ) -> dict[str, object]: tenant_id = _scope(session) run = _run_or_404(session, tenant_id, run_id) @@ -229,7 +233,7 @@ def get_eval_results( generated_at=iso_utc(run.finished_at or utcnow()), ) ) - return { + response: dict[str, object] = { "run_id": run.id, "template_id": run.template_id, "status": run.status, @@ -239,11 +243,22 @@ def get_eval_results( "items": items, "token_summary": token_summary, } + # M10 (#429): the frozen asset identity and the caller lineage are additive + # fields, present only for runs that actually carry them. + asset = run_asset_identity(session, run) + if asset is not None: + response["asset"] = asset + lineage = run.evolution_lineage_json or {} + if lineage: + response["lineage"] = lineage + return response @router.get("/api/v1/eval-runs/{run_id}/status") def get_eval_status( - run_id: str, session: Session = Depends(get_session) + run_id: str, + session: Session = Depends(get_session), + _actor: Actor = Depends(require_session_or_service("eval:read")), ) -> dict[str, object]: """M10 (#378): the stable poll read model for template-launched runs. @@ -264,7 +279,7 @@ def get_eval_status( else (min(99, round(finished / total * 100)) if total else 0) ) duration = evaluation_service.run_duration_seconds(run) - return { + response: dict[str, object] = { "run_id": run.id, "template_id": run.template_id, "template_version": run.template_version, @@ -290,6 +305,11 @@ def get_eval_status( "status_url": f"/api/v1/eval-runs/{run.id}/status", "result_url": f"/api/v1/eval-runs/{run.id}/results", } + # M10 (#429): additive asset echo, present only when the run froze assets. + asset = run_asset_identity(session, run) + if asset is not None: + response["asset"] = asset + return response @router.get("/api/v1/eval-runs/{run_id}/compare") @@ -297,6 +317,7 @@ def compare_eval_run( run_id: str, baseline_run_id: str | None = Query(default=None, max_length=36), session: Session = Depends(get_session), + _context: identity.AuthContext = Depends(require_session), ) -> dict[str, object]: tenant_id = _scope(session) run = _run_or_404(session, tenant_id, run_id) @@ -316,6 +337,7 @@ def get_case_tests( case_run_id: str, attempt: int | None = Query(default=None, ge=1), session: Session = Depends(get_session), + _context: identity.AuthContext = Depends(require_session), ) -> dict[str, object]: tenant_id = _scope(session) case_run = session.scalar( diff --git a/backend/app/services/eval_templates.py b/backend/app/services/eval_templates.py index 5378466e..b1ac8273 100644 --- a/backend/app/services/eval_templates.py +++ b/backend/app/services/eval_templates.py @@ -22,6 +22,7 @@ from __future__ import annotations +import re from datetime import UTC, datetime from typing import Any @@ -35,6 +36,7 @@ from ..config import Settings, get_settings from ..defaults import DEFAULT_PROJECT_ID, DEFAULT_TENANT_ID from ..models import ( + AgentAssetSnapshot, AgentAssetSource, Dataset, DatasetVersion, @@ -42,15 +44,31 @@ EvalTemplate, ModelConfig, ResourcePool, + ServiceToken, ) from ..money import money_str from . import agent_assets as asset_service from . import evaluations as evaluation_service from . import preparations as preparation_service +from . import service_tokens as token_service +from .git_client import GitClientError TEMPLATE_STATUSES = ("enabled", "disabled") TEMPLATE_SEARCH_LIMIT = 100 +# M10 (#429): the launch override resolves a candidate asset selection. ``commit`` +# is the authoritative identity (40-hex), while ``ref`` is display/audit only. +# The asset domain's own selection errors keep their code so a caller sees the +# same contract as the run-level asset endpoints. +ASSET_OVERRIDE_FIELD = "asset_override" +ASSET_OVERRIDE_PATH_LIMIT = 500 +ASSET_OVERRIDE_MAX_URL_LENGTH = 500 +ASSET_OVERRIDE_MAX_REF_LENGTH = 200 +PASSTHROUGH_ASSET_CODES = frozenset( + {"asset_path_not_found", "asset_selection_empty", "asset_type_invalid"} +) +_COMMIT_PATTERN = re.compile(r"^[0-9a-f]{40}$") + class TemplateError(Exception): """Base error mapped to the console's ``{"error": {...}}`` envelope.""" @@ -112,6 +130,27 @@ def __init__( self.status = status +class AssetSourceUnresolved(TemplateError): + """``asset_override.repo_url`` cannot be matched to a registered source.""" + + status = 422 + code = "asset_source_unresolved" + + +class AssetRefUnresolved(TemplateError): + """The requested commit/ref cannot be resolved in the asset repository.""" + + status = 422 + code = "asset_ref_unresolved" + + +class CandidateCommitMismatch(TemplateError): + """The resolved commit differs from the requested candidate commit.""" + + status = 422 + code = "candidate_commit_mismatch" + + def _now(now: datetime | None) -> datetime: return now or datetime.now(UTC) @@ -973,6 +1012,296 @@ def _self_evolution_launch_payload(template: EvalTemplate) -> dict: } +def _override_text(override: dict, key: str, *, max_length: int) -> str | None: + """Read one optional override string; ``None`` means the field is absent.""" + + value = override.get(key) + if value is None: + return None + if not isinstance(value, str): + raise TemplateInvalid( + f"asset_override.{key} 必须是字符串", field=ASSET_OVERRIDE_FIELD + ) + text = value.strip() + if len(text) > max_length: + raise TemplateInvalid( + f"asset_override.{key} 不能超过 {max_length} 个字符", + field=ASSET_OVERRIDE_FIELD, + ) + return text or None + + +def _override_paths(override: dict) -> list[str] | None: + """Whole-field ``asset_paths``; ``None`` inherits the template value.""" + + value = override.get("asset_paths") + if value is None: + return None + if not isinstance(value, (list, tuple)): + raise TemplateInvalid( + "asset_override.asset_paths 必须是字符串列表", field=ASSET_OVERRIDE_FIELD + ) + paths: list[str] = [] + for path in value: + if ( + not isinstance(path, str) + or not path.strip() + or len(path) > ASSET_OVERRIDE_PATH_LIMIT + ): + raise TemplateInvalid( + "asset_override.asset_paths 每项必须是 " + f"1..{ASSET_OVERRIDE_PATH_LIMIT} 字符的字符串", + field=ASSET_OVERRIDE_FIELD, + ) + paths.append(path) + return paths + + +def _override_types(override: dict) -> dict[str, str] | None: + """Whole-field ``asset_types``; ``None`` inherits the template value.""" + + value = override.get("asset_types") + if value is None: + return None + if not isinstance(value, dict): + raise TemplateInvalid( + "asset_override.asset_types 必须是对象", field=ASSET_OVERRIDE_FIELD + ) + return { + str(key): str(item) + for key, item in value.items() + if isinstance(key, str) and isinstance(item, str) + } + + +def _override_source( + session: Session, template: EvalTemplate, override: dict +) -> AgentAssetSource: + """Resolve the asset source an override pins its commit in. + + ``repo_url`` must exactly match a registered tenant source, because only a + registered source carries the credential and scan paths used to read the + candidate commit. Without ``repo_url`` the template's own source is used. + """ + + repo_url = _override_text( + override, "repo_url", max_length=ASSET_OVERRIDE_MAX_URL_LENGTH + ) + if repo_url: + source = session.scalar( + select(AgentAssetSource) + .where( + AgentAssetSource.tenant_id == str(DEFAULT_TENANT_ID), + AgentAssetSource.repo_url == repo_url, + ) + .order_by(AgentAssetSource.created_at, AgentAssetSource.id) + ) + if source is None: + raise AssetSourceUnresolved( + f"资产覆盖的仓库未登记为资产源:{repo_url}", + field=ASSET_OVERRIDE_FIELD, + details={"field": ASSET_OVERRIDE_FIELD, "repo_url": repo_url}, + ) + return source + if not template.asset_source_id: + raise AssetSourceUnresolved( + "资产覆盖未指定 repo_url,且模板未绑定资产源", + field=ASSET_OVERRIDE_FIELD, + details={"field": ASSET_OVERRIDE_FIELD, "template_id": template.id}, + ) + source = _get_tenant_row( + session, AgentAssetSource, template.asset_source_id, field="asset_source_id" + ) + if source is None: + raise AssetSourceUnresolved( + "模板绑定的资产源不存在或已删除", + field=ASSET_OVERRIDE_FIELD, + details={ + "field": ASSET_OVERRIDE_FIELD, + "template_id": template.id, + "asset_source_id": template.asset_source_id, + }, + ) + return source + + +def launch_asset_identity(effective: dict | None) -> dict | None: + """The 202 ``asset`` block built from a normalized effective identity.""" + + if not effective: + return None + return { + "repo_url": effective.get("repo_url"), + "requested_ref": effective.get("requested_ref"), + "requested_commit": effective.get("requested_commit"), + "resolved_commit": effective.get("resolved_commit"), + "asset_snapshot_id": effective.get("asset_snapshot_id"), + "bundle_digest": effective.get("bundle_digest"), + } + + +def run_asset_identity(session: Session, run: EvalRun) -> dict | None: + """The stable status/results ``asset`` echo for an asset-frozen run. + + Reads the snapshot referenced by ``run.asset_snapshot_id`` so the echo + always reflects the frozen identity, never the live source or template. + Synthetic runs and rows whose snapshot no longer resolves return ``None`` + so both read models keep their previous shape for them. + """ + + snapshot_id = run.asset_snapshot_id + if not snapshot_id: + return None + snapshot = session.get(AgentAssetSnapshot, snapshot_id) + if snapshot is None or snapshot.tenant_id != str(DEFAULT_TENANT_ID): + return None + effective = (run.asset_override_json or {}).get("effective") or {} + return { + "resolved_commit": snapshot.resolved_commit, + "asset_snapshot_id": snapshot.id, + # A stored override echo wins: ``commit`` only launches report the + # commit here, while the snapshot itself recorded the resolution ref. + "requested_ref": effective.get("requested_ref") or snapshot.requested_ref, + } + + +def _resolve_override_assets( + session: Session, + template: EvalTemplate, + override: dict, + *, + created_by: str, + settings: Settings, +) -> tuple[str, dict, dict]: + """Resolve an explicit ``asset_override`` into a frozen snapshot. + + Returns ``(snapshot_id, launch_asset, effective)``. ``commit`` is the + authoritative identity: it is resolved as-is and the resulting commit is + asserted before any preparation exists, so a drifting ref or a replaced + object can never be silently evaluated (``candidate_commit_mismatch``). + ``ref`` only shapes the audit echo. + """ + + source = _override_source(session, template, override) + commit = _override_text(override, "commit", max_length=40) + if commit is not None and _COMMIT_PATTERN.fullmatch(commit) is None: + raise TemplateInvalid( + "asset_override.commit 必须是 40 位小写十六进制 commit", + field=ASSET_OVERRIDE_FIELD, + ) + display_ref = _override_text( + override, "ref", max_length=ASSET_OVERRIDE_MAX_REF_LENGTH + ) + resolution_ref = ( + commit + or display_ref + or (template.asset_ref or source.default_ref or "").strip() + ) + if not resolution_ref: + raise AssetRefUnresolved( + "资产 Ref 未解析:请提供 commit/ref,或为模板/资产源设置 Ref", + field=ASSET_OVERRIDE_FIELD, + details={"field": ASSET_OVERRIDE_FIELD, "requested_ref": None}, + ) + raw_ref = override.get("ref") + if isinstance(raw_ref, str) and raw_ref.strip(): + # Display/audit only: echo the request verbatim, never the resolution. + requested_ref: str | None = raw_ref + elif commit: + requested_ref = commit + else: + requested_ref = resolution_ref + paths = _override_paths(override) + types = _override_types(override) + if paths is None: + paths = list(template.asset_paths_json or []) + if types is None: + types = dict(template.asset_types_json or {}) + try: + snapshot, _assets, _snapshot_created = asset_service.resolve_assets( + session, + source_id=source.id, + requested_ref=resolution_ref, + paths=paths, + types=types, + runtime_key=template.runtime_key, + created_by=created_by, + settings=settings, + ) + except asset_service.AgentAssetError as error: + if error.code in PASSTHROUGH_ASSET_CODES: + raise TemplateInvalid( + str(error), + field=ASSET_OVERRIDE_FIELD, + details=dict(error.details or {}), + code=error.code, + ) from error + raise TemplateInvalid( + f"资产解析失败:{error}", + field=ASSET_OVERRIDE_FIELD, + code="template_reference_invalid", + ) from error + except GitClientError as error: + raise AssetRefUnresolved( + f"资产 Ref 解析失败:{error}", + field=ASSET_OVERRIDE_FIELD, + details={ + "field": ASSET_OVERRIDE_FIELD, + "requested_ref": resolution_ref, + "git_code": error.code, + }, + ) from error + except TemplateError: + raise + except Exception as error: # network or object-store failure after resolve + raise TemplateInvalid( + f"资产解析失败:{error}", + field=ASSET_OVERRIDE_FIELD, + code="template_reference_invalid", + ) from error + if commit and snapshot.resolved_commit != commit: + raise CandidateCommitMismatch( + f"候选 commit 解析不一致:请求 {commit},解析 {snapshot.resolved_commit}", + field=ASSET_OVERRIDE_FIELD, + details={"requested": commit, "resolved": snapshot.resolved_commit}, + ) + effective = { + "repo_url": source.repo_url, + "source_id": source.id, + "requested_ref": requested_ref, + "requested_commit": commit, + "resolved_commit": snapshot.resolved_commit, + "asset_snapshot_id": snapshot.id, + "bundle_digest": snapshot.bundle_digest, + "asset_paths": list(paths), + "asset_types": dict(types), + } + return snapshot.id, launch_asset_identity(effective), effective + + +def _override_warnings(template: EvalTemplate) -> list[str]: + """Non-blocking D5 hint when a candidate launch hits a reporting template.""" + + if not template.self_evolution_enabled: + return [] + return [ + "该模板已开启自进化 bad case 上报;候选 commit 评测会向模板工作区回传" + "失败用例,建议为候选评测使用关闭上报的模板。" + ] + + +def _replay_launch_meta(template: EvalTemplate, run: EvalRun) -> dict: + """Echo a replayed launch from the stored run; no asset work happens.""" + + effective = (run.asset_override_json or {}).get("effective") or {} + if not effective: + return {"asset": None, "warnings": []} + return { + "asset": launch_asset_identity(effective), + "warnings": _override_warnings(template), + } + + def launch_template( session: Session, template_id: str, @@ -980,13 +1309,23 @@ def launch_template( idempotency_key: str, created_by: str, name: str | None = None, + asset_override: dict | None = None, + lineage: dict | None = None, + service_token: ServiceToken | None = None, settings: Settings | None = None, now: datetime | None = None, -) -> tuple[EvalRun, bool]: +) -> tuple[EvalRun, bool, dict]: """Launch a template through the existing prepare/create path. - Returns ``(run, created)``. A replayed idempotency key returns the original - run of the same template; reusing a key for a different template is a 409. + Returns ``(run, created, launch_meta)``. A replayed idempotency key returns + the original run of the same template; reusing a key for a different + template is a 409. + + M10 (#429): a machine caller passes ``service_token`` so its concurrency and + budget caps are enforced before any asset work, and may pin the run to a + candidate commit through ``asset_override``. ``launch_meta`` carries the + 202 ``asset`` block plus non-blocking warnings; the console one-click path + (no override) leaves both empty. """ settings = settings or get_settings() @@ -996,9 +1335,9 @@ def launch_template( raise TemplateInvalid("启动必须提供幂等键", field="idempotency_key") key = key[:128] template = get_template(session, template_id) - # Replay wins over the enabled check: a client that retries the same - # idempotent launch after the template was disabled must still receive the - # original run instead of a conflicting 409. + # Replay wins over every live check: a client that retries the same + # idempotent launch after the template was disabled (or after its caps were + # reached by this very run) must still receive the original run. existing = session.scalar( select(EvalRun).where( EvalRun.tenant_id == str(DEFAULT_TENANT_ID), @@ -1013,16 +1352,31 @@ def launch_template( details={"run_id": existing.id, "template_id": existing.template_id}, code="idempotency_conflict", ) - return existing, False + return existing, False, _replay_launch_meta(template, existing) + if service_token is not None: + token_service.enforce_launch_caps(session, service_token) if not template.enabled: raise TemplateDisabled("模板已停用,不能启动") # Validate/decrypt the reporting target before resolving assets or # preparing: a broken target must never yield a partially launched run. self_evolution = _self_evolution_launch_payload(template) - asset_snapshot_id = _resolve_template_assets( - session, template, created_by=created_by, settings=settings - ) + launch_asset: dict | None = None + warnings: list[str] = [] + effective: dict = {} + if asset_override is None: + asset_snapshot_id = _resolve_template_assets( + session, template, created_by=created_by, settings=settings + ) + else: + asset_snapshot_id, launch_asset, effective = _resolve_override_assets( + session, + template, + asset_override, + created_by=created_by, + settings=settings, + ) + warnings = _override_warnings(template) try: preparation = preparation_service.build_preparation( session, @@ -1076,7 +1430,18 @@ def launch_template( run.template_id = template.id run.template_version = template.version run.template_snapshot_json = template_view(session, template, settings=settings) + if asset_override is not None: + # Freeze both the raw request and the normalized identity so status, + # results and a later replay echo what was actually measured. + run.asset_override_json = { + "requested": dict(asset_override), + "effective": effective, + } + if lineage: + # Caller provenance only: it never participates in evaluation + # semantics, so it is stored verbatim and echoed by results. + run.evolution_lineage_json = dict(lineage) template.launch_count = int(template.launch_count or 0) + 1 template.last_launched_at = now session.commit() - return run, created + return run, created, {"asset": launch_asset, "warnings": warnings} diff --git a/tests/backend/test_eval_templates.py b/tests/backend/test_eval_templates.py index 0fc75852..283084d3 100644 --- a/tests/backend/test_eval_templates.py +++ b/tests/backend/test_eval_templates.py @@ -8,11 +8,16 @@ from __future__ import annotations +import hashlib import json +from dataclasses import dataclass +from decimal import Decimal from uuid import uuid4 +import pytest from app.config import get_settings from app.models import ( + AgentAssetSnapshot, AgentAssetSource, Credential, Dataset, @@ -26,10 +31,13 @@ ) from app.secrets import get_secret_box from app.seed import ensure_default_scope +from app.services import agent_assets, identity from app.services import eval_templates as template_service -from app.services import identity +from app.services.git_client import GitClientError, TreeEntry +from conftest import TEST_ADMIN_EMAIL, TEST_ADMIN_PASSWORD from fastapi.testclient import TestClient -from sqlalchemy import select, text +from object_stub import StubObjectStore +from sqlalchemy import func, select, text from sqlalchemy.orm import Session SELF_EVOLUTION_TOKEN = "whk_" + "a1B2c3D4e5" * 3 @@ -1102,6 +1110,742 @@ def test_launch_from_reporting_template_sets_run_self_evolution( assert SELF_EVOLUTION_TOKEN not in response.text +# --------------------------------------------------------------------------- +# M10 (#429): candidate commit injection + service-token launches +# --------------------------------------------------------------------------- + +SOURCE_REPO = "https://github.com/acme/candidate-skills" +CANDIDATE_REPO = "https://github.com/acme/candidate-repo" +CANDIDATE_COMMIT = "c" * 40 +BASE_COMMIT = "a" * 40 +SKILL_PATH = "skills/candidate" +SKILL_MANIFEST = f"{SKILL_PATH}/SKILL.md" +SKILL_CONTENT = ( + b"---\nname: candidate\ndescription: Candidate skill\n---\n# Candidate\n" +) + + +@dataclass +class FakeRepo: + """A tiny commit tree served by :class:`FakeGitHubClient` (no network).""" + + commit: str = CANDIDATE_COMMIT + files: dict[str, bytes] | None = None + + def __post_init__(self) -> None: + if self.files is None: + self.files = { + SKILL_MANIFEST: SKILL_CONTENT, + f"{SKILL_PATH}/reference.md": b"reference\n", + } + + +class FakeGitHubClient: + """Minimal GitHub surface with failure and commit-drift injection.""" + + def __init__( + self, + repo: FakeRepo, + token: str | None = None, + *, + resolve_error: Exception | None = None, + resolved_commit: str | None = None, + ) -> None: + self.repo = repo + self.token = token + self.resolve_error = resolve_error + self.resolved_commit = resolved_commit + self.blobs = { + hashlib.sha1(path.encode()).hexdigest(): content + for path, content in repo.files.items() + } + + def close(self) -> None: + return None + + def resolve_commit(self, owner: str, repo: str, ref: str) -> str: + if self.resolve_error is not None: + raise self.resolve_error + return self.resolved_commit or self.repo.commit + + def tree(self, owner: str, repo: str, commit: str) -> list[TreeEntry]: + return [ + TreeEntry( + path=path, + entry_type="blob", + sha=hashlib.sha1(path.encode()).hexdigest(), + size=len(content), + ) + for path, content in self.repo.files.items() + ] + + def blob(self, owner: str, repo: str, sha: str) -> bytes: + return self.blobs[sha] + + +def install_fake_github( + monkeypatch: pytest.MonkeyPatch, + repo: FakeRepo | None = None, + **client_kwargs: object, +) -> FakeRepo: + repo = repo or FakeRepo() + monkeypatch.setattr( + agent_assets, + "GitHubClient", + lambda token=None, **_kwargs: FakeGitHubClient(repo, token, **client_kwargs), + ) + return repo + + +@pytest.fixture +def asset_store(configure_settings): + """Local S3-shaped store so ``resolve_assets`` exercises the real path.""" + + with StubObjectStore() as store: + configure_settings( + S3_ENDPOINT=store.endpoint, + S3_BUCKET="eval-artifacts", + S3_ACCESS_KEY="ak", + S3_SECRET_KEY="sk", + S3_ADDRESSING_STYLE="path", + ) + yield store + + +def create_asset_source( + session: Session, + repo_url: str = SOURCE_REPO, + *, + default_ref: str = "main", +) -> AgentAssetSource: + tenant, _workspace, project = ensure_default_scope(session) + source = AgentAssetSource( + tenant_id=tenant.id, + project_id=project.id, + name=f"assets-{uuid4().hex[:8]}", + repo_url=repo_url, + provider="github", + default_ref=default_ref, + scan_paths_json=[], + selection_mode="explicit", + runtime_prerequisites_json={}, + last_scan_json={}, + status="ready", + ) + session.add(source) + session.commit() + return source + + +def seed_candidate_template( + client: TestClient, session: Session, *, repo_url: str = SOURCE_REPO +) -> tuple[dict, AgentAssetSource, dict]: + ids = seed_launch(session) + source = create_asset_source(session, repo_url) + template = create_template( + client, + ids, + asset_source_id=source.id, + asset_ref="main", + asset_paths=[SKILL_PATH], + ) + return ids, source, template + + +def launch_override( + client: TestClient, + template_id: str, + *, + key: str, + override: dict | None = None, + lineage: dict | None = None, + headers: dict | None = None, +): + body: dict = {} + if override is not None: + body["asset_override"] = override + if lineage is not None: + body["lineage"] = lineage + request_headers = {"Idempotency-Key": key} + request_headers.update(headers or {}) + return client.post( + f"/api/v1/eval-templates/{template_id}/launch", + headers=request_headers, + json=body, + ) + + +def _run_count(session: Session, template_id: str) -> int: + return int( + session.scalar( + select(func.count()) + .select_from(EvalRun) + .where(EvalRun.template_id == template_id) + ) + or 0 + ) + + +def _create_service_token(client: TestClient, **overrides: object) -> tuple[dict, str]: + payload = {"name": f"bot-{uuid4().hex[:8]}", "scopes": ["eval:launch"]} + payload.update(overrides) + response = client.post("/api/v1/service-tokens", json=payload) + assert response.status_code == 201, response.text + body = response.json() + return body["service_token"], body["token"] + + +def _record_spend( + session: Session, *, created_by: str, budget_spent_cny: Decimal +) -> None: + tenant, _workspace, project = ensure_default_scope(session) + session.add( + EvalRun( + tenant_id=tenant.id, + project_id=project.id, + name="spend-record", + idempotency_key=f"spend-{uuid4().hex[:8]}", + created_by=created_by, + budget_spent_cny=budget_spent_cny, + status="completed", + ) + ) + session.commit() + + +def test_launch_asset_override_pins_candidate_commit_and_echoes( + client: TestClient, + session: Session, + monkeypatch: pytest.MonkeyPatch, + asset_store: StubObjectStore, +) -> None: + install_fake_github(monkeypatch) + _ids, source, template = seed_candidate_template(client, session) + lineage = { + "evolutionRunId": "evo-1", + "evolutionRoundId": "round-7", + "roundSeq": 7, + "parentCommit": BASE_COMMIT, + } + + response = launch_override( + client, + template["id"], + key="candidate-launch", + override={ + "repo_url": SOURCE_REPO, + "ref": "refs/heads/candidate", + "commit": CANDIDATE_COMMIT, + "asset_paths": [SKILL_PATH], + "asset_types": {SKILL_PATH: "skill"}, + }, + lineage=lineage, + ) + assert response.status_code == 202, response.text + body = response.json() + asset = body["asset"] + assert asset["repo_url"] == SOURCE_REPO + # ``ref`` is display/audit only and must echo verbatim. + assert asset["requested_ref"] == "refs/heads/candidate" + assert asset["requested_commit"] == CANDIDATE_COMMIT + assert asset["resolved_commit"] == CANDIDATE_COMMIT + assert asset["asset_snapshot_id"] + assert asset["bundle_digest"].startswith("sha256:") + assert "warnings" not in body + + run = session.get(EvalRun, body["run_id"]) + assert run is not None + assert run.asset_snapshot_id == asset["asset_snapshot_id"] + assert run.asset_override_json["requested"]["commit"] == CANDIDATE_COMMIT + assert run.asset_override_json["requested"]["ref"] == "refs/heads/candidate" + assert run.asset_override_json["effective"] == { + "repo_url": SOURCE_REPO, + "source_id": source.id, + "requested_ref": "refs/heads/candidate", + "requested_commit": CANDIDATE_COMMIT, + "resolved_commit": CANDIDATE_COMMIT, + "asset_snapshot_id": asset["asset_snapshot_id"], + "bundle_digest": asset["bundle_digest"], + "asset_paths": [SKILL_PATH], + "asset_types": {SKILL_PATH: "skill"}, + } + assert run.evolution_lineage_json == lineage + + status = client.get(f"/api/v1/eval-runs/{body['run_id']}/status").json() + assert status["asset"] == { + "resolved_commit": CANDIDATE_COMMIT, + "asset_snapshot_id": asset["asset_snapshot_id"], + "requested_ref": "refs/heads/candidate", + } + results = client.get(f"/api/v1/eval-runs/{body['run_id']}/results").json() + assert results["asset"] == status["asset"] + assert results["lineage"] == lineage + assert _run_count(session, template["id"]) == 1 + + # The replay echoes the stored identity and never resolves assets again. + replay = launch_override( + client, + template["id"], + key="candidate-launch", + override={"commit": CANDIDATE_COMMIT}, + lineage=lineage, + ) + assert replay.status_code == 202, replay.text + assert replay.json()["created"] is False + assert replay.json()["run_id"] == body["run_id"] + assert replay.json()["asset"] == asset + assert _run_count(session, template["id"]) == 1 + + +def test_launch_without_override_keeps_the_console_response_shape( + client: TestClient, + session: Session, + monkeypatch: pytest.MonkeyPatch, + asset_store: StubObjectStore, +) -> None: + install_fake_github(monkeypatch) + _ids, _source, template = seed_candidate_template(client, session) + + response = client.post( + f"/api/v1/eval-templates/{template['id']}/launch", + headers={"Idempotency-Key": "console-launch"}, + json={"name": "控制台一键启动"}, + ) + assert response.status_code == 202, response.text + body = response.json() + assert "asset" not in body + assert "warnings" not in body + + run = session.get(EvalRun, body["run_id"]) + assert run is not None + assert run.asset_snapshot_id + assert run.asset_override_json == {} + assert run.evolution_lineage_json == {} + + # The read models still echo the frozen legacy asset identity. + status = client.get(f"/api/v1/eval-runs/{body['run_id']}/status").json() + assert status["asset"] == { + "resolved_commit": CANDIDATE_COMMIT, + "asset_snapshot_id": run.asset_snapshot_id, + "requested_ref": "main", + } + + replay = client.post( + f"/api/v1/eval-templates/{template['id']}/launch", + headers={"Idempotency-Key": "console-launch"}, + json={"name": "控制台一键启动"}, + ) + assert replay.status_code == 202 + assert replay.json()["created"] is False + assert "asset" not in replay.json() + + +def test_override_repo_url_must_be_a_registered_source( + client: TestClient, + session: Session, + monkeypatch: pytest.MonkeyPatch, + asset_store: StubObjectStore, +) -> None: + install_fake_github(monkeypatch) + _ids, _source, template = seed_candidate_template(client, session) + override = {"repo_url": CANDIDATE_REPO, "commit": CANDIDATE_COMMIT} + + unregistered = launch_override( + client, template["id"], key="cross-repo", override=override + ) + assert unregistered.status_code == 422, unregistered.text + error = unregistered.json()["detail"]["error"] + assert error["code"] == "asset_source_unresolved" + assert error["details"]["fields"]["asset_override"] == "invalid" + assert error["details"]["repo_url"] == CANDIDATE_REPO + assert _run_count(session, template["id"]) == 0 + + registered = create_asset_source(session, CANDIDATE_REPO) + # The exact same request succeeds once the source is registered: the + # override chooses the source by exact repo_url. + retried = launch_override( + client, template["id"], key="cross-repo", override=override + ) + assert retried.status_code == 202, retried.text + assert retried.json()["asset"]["repo_url"] == CANDIDATE_REPO + run = session.get(EvalRun, retried.json()["run_id"]) + assert run is not None + assert run.asset_override_json["effective"]["source_id"] == registered.id + + +def test_override_unresolvable_commit_is_a_ref_error( + client: TestClient, + session: Session, + monkeypatch: pytest.MonkeyPatch, +) -> None: + install_fake_github( + monkeypatch, + resolve_error=GitClientError("ref_unresolved", "无法解析 Ref"), + ) + _ids, _source, template = seed_candidate_template(client, session) + + response = launch_override( + client, + template["id"], + key="unresolvable-commit", + override={"commit": CANDIDATE_COMMIT}, + ) + assert response.status_code == 422, response.text + error = response.json()["detail"]["error"] + assert error["code"] == "asset_ref_unresolved" + assert error["details"]["fields"]["asset_override"] == "invalid" + assert error["details"]["requested_ref"] == CANDIDATE_COMMIT + assert _run_count(session, template["id"]) == 0 + + +def test_override_selection_errors_keep_the_existing_asset_codes( + client: TestClient, + session: Session, + monkeypatch: pytest.MonkeyPatch, +) -> None: + install_fake_github(monkeypatch) + _ids, _source, template = seed_candidate_template(client, session) + + missing_path = launch_override( + client, + template["id"], + key="missing-path", + override={ + "commit": CANDIDATE_COMMIT, + "asset_paths": ["missing/command.md"], + "asset_types": {"missing/command.md": "command"}, + }, + ) + assert missing_path.status_code == 422, missing_path.text + assert missing_path.json()["detail"]["error"]["code"] == "asset_path_not_found" + + # An explicitly empty list replaces the template selection wholesale. + empty_selection = launch_override( + client, + template["id"], + key="empty-selection", + override={"commit": CANDIDATE_COMMIT, "asset_paths": []}, + ) + assert empty_selection.status_code == 422, empty_selection.text + assert ( + empty_selection.json()["detail"]["error"]["code"] == "asset_selection_empty" + ) + assert _run_count(session, template["id"]) == 0 + + +def test_override_commit_mismatch_never_creates_a_run( + client: TestClient, + session: Session, + monkeypatch: pytest.MonkeyPatch, + asset_store: StubObjectStore, +) -> None: + # The source resolves the requested commit to a different object: the + # authoritative assertion must fail the launch instead of measuring drift. + install_fake_github(monkeypatch, resolved_commit=BASE_COMMIT) + _ids, _source, template = seed_candidate_template(client, session) + + response = launch_override( + client, + template["id"], + key="commit-mismatch", + override={"commit": CANDIDATE_COMMIT}, + ) + assert response.status_code == 422, response.text + error = response.json()["detail"]["error"] + assert error["code"] == "candidate_commit_mismatch" + assert error["details"]["requested"] == CANDIDATE_COMMIT + assert error["details"]["resolved"] == BASE_COMMIT + assert _run_count(session, template["id"]) == 0 + + +def test_override_snapshot_manifest_proves_golden_injection( + client: TestClient, + session: Session, + monkeypatch: pytest.MonkeyPatch, + asset_store: StubObjectStore, +) -> None: + repo = install_fake_github(monkeypatch) + _ids, _source, template = seed_candidate_template(client, session) + + response = launch_override( + client, + template["id"], + key="golden-injection", + override={"ref": "candidate", "commit": CANDIDATE_COMMIT}, + ) + assert response.status_code == 202, response.text + snapshot_id = response.json()["asset"]["asset_snapshot_id"] + snapshot = session.get(AgentAssetSnapshot, snapshot_id) + assert snapshot is not None + assert snapshot.resolved_commit == CANDIDATE_COMMIT + + expected = "sha256:" + hashlib.sha256(SKILL_CONTENT).hexdigest() + manifest = { + item["path"]: item for item in (snapshot.manifest_json or {}).get("files", []) + } + assert manifest[SKILL_MANIFEST]["sha256"] == expected + + # The manifest path is the same blob the pinned commit's tree serves. + reader = FakeGitHubClient(repo) + entries = { + entry.path: entry + for entry in reader.tree("acme", "candidate-skills", CANDIDATE_COMMIT) + } + assert entries[SKILL_MANIFEST].sha == hashlib.sha1( + SKILL_MANIFEST.encode() + ).hexdigest() + assert ( + reader.blob("acme", "candidate-skills", entries[SKILL_MANIFEST].sha) + == SKILL_CONTENT + ) + + +def test_override_on_reporting_template_warns_without_blocking( + client: TestClient, + session: Session, + monkeypatch: pytest.MonkeyPatch, + asset_store: StubObjectStore, +) -> None: + install_fake_github(monkeypatch) + ids = seed_launch(session) + source = create_asset_source(session) + template = create_template( + client, + ids, + asset_source_id=source.id, + asset_ref="main", + asset_paths=[SKILL_PATH], + self_evolution=SELF_EVOLUTION, + ) + + response = launch_override( + client, + template["id"], + key="reporting-override", + override={"commit": CANDIDATE_COMMIT}, + ) + assert response.status_code == 202, response.text + warnings = response.json()["warnings"] + assert len(warnings) == 1 + assert "自进化" in warnings[0] + + # The console one-click launch of the same reporting template stays quiet. + console = client.post( + f"/api/v1/eval-templates/{template['id']}/launch", + headers={"Idempotency-Key": "reporting-console"}, + json={}, + ) + assert console.status_code == 202, console.text + assert "warnings" not in console.json() + + +def test_service_token_launch_records_machine_actor_and_replays( + client: TestClient, session: Session +) -> None: + ids = seed_launch(session) + template = create_template(client, ids) + token, plaintext = _create_service_token( + client, name="launch-bot", scopes=["eval:launch"] + ) + headers = {"Authorization": f"Bearer {plaintext}", "Idempotency-Key": "svc-key"} + + first = client.post( + f"/api/v1/eval-templates/{template['id']}/launch", headers=headers, json={} + ) + assert first.status_code == 202, first.text + run_id = first.json()["run_id"] + run = session.get(EvalRun, run_id) + assert run is not None + assert run.created_by == "svc:launch-bot" + + detail = client.get(f"/api/v1/evaluations/{run_id}") + assert detail.status_code == 200, detail.text + assert detail.json()["created_by"] == "svc:launch-bot" + assert detail.json()["template"]["id"] == template["id"] + + replay = client.post( + f"/api/v1/eval-templates/{template['id']}/launch", headers=headers, json={} + ) + assert replay.status_code == 202, replay.text + assert replay.json()["run_id"] == run_id + assert replay.json()["created"] is False + # The machine identity is isolated from the console actor's idempotency. + assert token["name"] == "launch-bot" + assert _run_count(session, template["id"]) == 1 + + +def test_service_token_scope_and_allowlist_are_enforced( + client: TestClient, session: Session +) -> None: + ids = seed_launch(session) + template = create_template(client, ids) + other = create_template(client, ids, name="另一个模板") + + _read_token, read_plaintext = _create_service_token( + client, name="scope-read-bot", scopes=["eval:read"] + ) + wrong_scope = client.post( + f"/api/v1/eval-templates/{template['id']}/launch", + headers={"Authorization": f"Bearer {read_plaintext}"}, + json={}, + ) + assert wrong_scope.status_code == 403, wrong_scope.text + assert wrong_scope.json()["detail"]["error"]["code"] == "forbidden" + + _scoped, scoped_plaintext = _create_service_token( + client, + name="allowlist-bot", + scopes=["eval:launch"], + template_allowlist=[other["id"]], + ) + allowed = client.post( + f"/api/v1/eval-templates/{other['id']}/launch", + headers={ + "Authorization": f"Bearer {scoped_plaintext}", + "Idempotency-Key": "allowlisted", + }, + json={}, + ) + assert allowed.status_code == 202, allowed.text + denied = client.post( + f"/api/v1/eval-templates/{template['id']}/launch", + headers={"Authorization": f"Bearer {scoped_plaintext}"}, + json={}, + ) + assert denied.status_code == 403, denied.text + assert _run_count(session, template["id"]) == 0 + + +def test_revoked_service_token_cannot_launch( + client: TestClient, session: Session +) -> None: + ids = seed_launch(session) + template = create_template(client, ids) + token, plaintext = _create_service_token( + client, name="revoked-bot", scopes=["eval:launch"] + ) + assert client.delete(f"/api/v1/service-tokens/{token['id']}").status_code == 204 + + response = client.post( + f"/api/v1/eval-templates/{template['id']}/launch", + headers={"Authorization": f"Bearer {plaintext}"}, + json={}, + ) + assert response.status_code == 401, response.text + assert response.json()["detail"]["error"]["code"] == "unauthenticated" + assert _run_count(session, template["id"]) == 0 + + +def test_service_token_concurrency_cap_blocks_launch( + client: TestClient, session: Session +) -> None: + ids = seed_launch(session) + template = create_template(client, ids) + _token, plaintext = _create_service_token( + client, + name="cap-bot", + scopes=["eval:launch"], + max_concurrent_runs=1, + ) + auth = {"Authorization": f"Bearer {plaintext}"} + + first = client.post( + f"/api/v1/eval-templates/{template['id']}/launch", + headers={**auth, "Idempotency-Key": "cap-1"}, + json={}, + ) + assert first.status_code == 202, first.text + + blocked = client.post( + f"/api/v1/eval-templates/{template['id']}/launch", + headers={**auth, "Idempotency-Key": "cap-2"}, + json={}, + ) + assert blocked.status_code == 429, blocked.text + error = blocked.json()["detail"]["error"] + assert error["code"] == "service_token_limit_exceeded" + assert error["details"]["limit"] == "max_concurrent_runs" + assert _run_count(session, template["id"]) == 1 + + +def test_service_token_daily_budget_cap_blocks_launch( + client: TestClient, session: Session +) -> None: + ids = seed_launch(session) + template = create_template(client, ids) + _token, plaintext = _create_service_token( + client, + name="budget-bot", + scopes=["eval:launch"], + daily_budget_cny=5, + ) + _record_spend(session, created_by="svc:budget-bot", budget_spent_cny=Decimal("5")) + + blocked = client.post( + f"/api/v1/eval-templates/{template['id']}/launch", + headers={"Authorization": f"Bearer {plaintext}"}, + json={}, + ) + assert blocked.status_code == 429, blocked.text + error = blocked.json()["detail"]["error"] + assert error["code"] == "service_token_limit_exceeded" + assert error["details"]["limit"] == "daily_budget_cny" + assert Decimal(str(error["details"]["spent"])) == Decimal("5") + assert _run_count(session, template["id"]) == 0 + + +def test_eval_read_token_reads_status_results_and_compare_stays_session_only( + client: TestClient, session: Session +) -> None: + ids = seed_launch(session) + template = create_template(client, ids) + launched = client.post( + f"/api/v1/eval-templates/{template['id']}/launch", + headers={"Idempotency-Key": "read-scope"}, + json={}, + ) + assert launched.status_code == 202, launched.text + run_id = launched.json()["run_id"] + + _read_token, read_plaintext = _create_service_token( + client, name="reader-bot", scopes=["eval:read"] + ) + read_auth = {"Authorization": f"Bearer {read_plaintext}"} + status = client.get(f"/api/v1/eval-runs/{run_id}/status", headers=read_auth) + assert status.status_code == 200, status.text + results = client.get(f"/api/v1/eval-runs/{run_id}/results", headers=read_auth) + assert results.status_code == 200, results.text + + _launch_token, launch_plaintext = _create_service_token( + client, name="launch-only-bot", scopes=["eval:launch"] + ) + launch_auth = {"Authorization": f"Bearer {launch_plaintext}"} + assert ( + client.get(f"/api/v1/eval-runs/{run_id}/status", headers=launch_auth).status_code + == 403 + ) + assert ( + client.get( + f"/api/v1/eval-runs/{run_id}/results", headers=launch_auth + ).status_code + == 403 + ) + + # compare/case-tests kept their session-only dependency: a bearer token + # alone (no cookie) must not reach them, while a console session still can. + client.cookies.clear() + denied = client.get(f"/api/v1/eval-runs/{run_id}/compare", headers=read_auth) + assert denied.status_code == 401, denied.text + assert denied.json()["detail"]["error"]["code"] == "unauthenticated" + login = client.post( + "/api/v1/auth/login", + json={"email": TEST_ADMIN_EMAIL, "password": TEST_ADMIN_PASSWORD}, + ) + assert login.status_code == 200, login.text + assert client.get(f"/api/v1/eval-runs/{run_id}/compare").status_code == 200 + assert client.get(f"/api/v1/eval-runs/{run_id}/status").status_code == 200 + + def test_existing_templates_default_to_self_evolution_disabled( client: TestClient, session: Session ) -> None: From 92bdd453ece9d681009c678d1f336baa2c3ebbd9 Mon Sep 17 00:00:00 2001 From: TangZ-L <345187680+TangZ-L@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:44:37 +0800 Subject: [PATCH 3/8] =?UTF-8?q?docs(m10):=20=E8=AE=B0=E5=BD=95=E6=9C=BA?= =?UTF-8?q?=E5=99=A8=E8=A7=A6=E5=8F=91=E8=A6=86=E7=9B=96=E5=8F=82=E6=95=B0?= =?UTF-8?q?=E4=B8=8E=E6=9C=8D=E5=8A=A1=E4=BB=A4=E7=89=8C=E5=A5=91=E7=BA=A6?= =?UTF-8?q?=20(#429)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/design/eval-platform-architecture.en.md | 11 ++++++----- docs/design/eval-platform-architecture.i18n.yaml | 4 ++-- docs/design/eval-platform-architecture.md | 11 ++++++----- scripts/doc-budgets.manifest.json | 4 ++-- 4 files changed, 16 insertions(+), 14 deletions(-) diff --git a/docs/design/eval-platform-architecture.en.md b/docs/design/eval-platform-architecture.en.md index 5ef4f876..d9310e6f 100644 --- a/docs/design/eval-platform-architecture.en.md +++ b/docs/design/eval-platform-architecture.en.md @@ -182,7 +182,7 @@ Existing adapter code changes only when the upstream data format changes or the An evaluation template (`eval_template`) is a project-level reusable launch preset that stores the dataset version, agent runtime, agent asset source and ref, asset selection, model credential, resource pool, case scope, execution policy, prompt suffix, max turns, agent timeout, and the self-evolution reporting target as one fixed selection. A template fixes the selection, not the execution outcome: on every launch the API service re-resolves the template's asset ref, validates the references, and generates a fresh immutable snapshot, while the evaluation records `template_id`, the template version, and the launch snapshot, so later template edits never change an evaluation that has started. Set the ref to a commit to pin the content; otherwise each launch resolves the branch or tag as it exists at that moment. -The template lifecycle is create, edit, disable, and delete; deletion is offered only from the disabled state, and deleting a template never cascades to started evaluations or traces, so runs keep their template id and version while the provenance entry stops showing a link once the name no longer resolves. Deletion uses `DELETE /api/v1/eval-templates/{template_id}` and requires administrator permission. A template that is disabled or whose references were deleted cannot launch, and the platform validates the dataset version, model credential, resource pool, and asset source before creating a run. A template launch accepts no configuration overrides, preserving the one-click semantics and reproducibility; use a copied and edited template, or the existing custom launch flow, for a different combination. +The template lifecycle is create, edit, disable, and delete; deletion is offered only from the disabled state, and deleting a template never cascades to started evaluations or traces, so runs keep their template id and version while the provenance entry stops showing a link once the name no longer resolves. Deletion uses `DELETE /api/v1/eval-templates/{template_id}` and requires administrator permission. A template that is disabled or whose references were deleted cannot launch, and the platform validates the dataset version, model credential, resource pool, and asset source before creating a run. Console one-click launches accept no configuration overrides, preserving the one-click semantics and reproducibility, so a different combination uses a copied and edited template or the existing custom launch flow; machine triggers (service tokens) may carry an optional `asset_override` (repo_url, ref, commit, asset_paths, asset_types) to pin one evaluation to a chosen repository and candidate commit, fields are replaced as a whole with absent fields inheriting the template, the commit is the authoritative identity, and the platform must assert that the resolved commit equals the requested commit, rejecting with 422 on a mismatch instead of ever evaluating silently, while ref is display and audit only. When a template is created or updated, the deterministic image dependency is validated first: the execution and scoring image digests are resolved in the order launch override → dataset version → platform default, and if all three are empty the request returns 422 with the error attached to `execution.execution_image_digest` and `execution.scoring_image_digest`, stating whether to record the digest on the dataset version or configure the platform default. Checks that depend on live state — asset ref resolution, capacity, model credentials, and online runners — still run at launch. When a launch is blocked, the API returns `template_launch_blocked` with `details.blockers`, and the UI lists each blocker's code, message, field, and remediation guidance instead of only a summary error. @@ -194,7 +194,7 @@ The template list uses the console management read API `GET /api/v1/eval-templat A template's launch history reuses the evaluation list read API instead of adding a dedicated execution API: `GET /api/v1/evaluations` accepts an optional `template_id` filter combined with `status`, `limit`, and `offset`, returning `items`, `total`, `limit`, and `offset` ordered by launch time descending and a 404 when the template is unknown; template history defaults to a limit of 10 and includes a `status_counts` map. The history action on each template row and the launch-history action on the template detail page both read this filtered page, defaulting to 10 rows with 10/20/50 options and filtering by the evaluation status enum with counts (zero included), and items reuse the evaluation summary and link to the evaluation detail; the embedded `recent_runs` preview still keeps only the latest five. The filter is read-only and does not change the execution chain. Each evaluation-list summary also carries the resolved source-template `template` (id, name, version, and enabled state), so the list labels template-launched runs with "from template · template name" linked to the template detail while custom runs show no origin line. -Table 12 lists the three stable APIs. All three reuse console session authentication: launching requires administrator permission, while status and results are read-only for signed-in users; the first release does not provide a separate machine token. +Table 12 lists the three stable APIs. All three reuse "console session or service token" authentication: launching requires administrator permission or a service token with `eval:launch`, while status and results are read-only for signed-in users or a service token with `eval:read`; administrators create, list, and revoke service tokens at `/api/v1/service-tokens`, with scopes, a template allowlist, and concurrency/budget caps, the plaintext is returned exactly once in the creation response and only its hash is stored, and machine launches record `created_by` as `svc:` in the existing audit and idempotency constraints. Table 12 The three execution APIs of an evaluation template @@ -204,11 +204,11 @@ Table 12 The three execution APIs of an evaluation template | Query status | GET /api/v1/eval-runs/{run_id}/status | none | `run_id`, `template_id`, `status`, `terminal`, progress counts, start and finish times, and resolve rate | | Query results | GET /api/v1/eval-runs/{run_id}/results | none | `run_id`, `status`, `is_final`, metric items, and token summary; a running run returns a partial snapshot | -The launch API first verifies that the template exists and is enabled and that its references are still available, then runs the existing prepare/create flow; 404 means the template or evaluation does not exist, 409 means the template is disabled or the idempotency key conflicts, 422 means a reference is invalid or a field is unavailable, and 403 means the current account lacks launch permission. The status API returns `terminal=true` in a terminal state; the results API returns `is_final=false` before the terminal state, so clients can decide whether to keep polling. +The launch API first verifies that the template exists and is enabled and that its references are still available, then runs the existing prepare/create flow; 404 means the template or evaluation does not exist, 409 means the template is disabled or the idempotency key conflicts, 422 means a reference is invalid or a field is unavailable, and 403 means the current account lacks launch permission. The status API returns `terminal=true` in a terminal state; the results API returns `is_final=false` before the terminal state, so clients can decide whether to keep polling. An override launch echoes `asset` (resolved_commit, asset_snapshot_id, bundle_digest) in the 202 response, status and results echo the same identity for caller-side comparison, and new 422 codes `candidate_commit_mismatch`, `asset_source_unresolved`, and `asset_ref_unresolved` join the reused `asset_selection_empty` and `asset_path_not_found`, none of which create an evaluation. A template launch does not change the scheduling or execution chain: the server simply turns the fixed selection into a normal prepare and create call, and the subsequent sharding, runners, scoring, traces, and result aggregation are identical to a custom launch. A template therefore cannot bypass capacity admission, budget, image preflight, or permission checks; failures happen before a run is created and never leave a half-created task. -Before creating a run, a launch decrypts the stored token and passes it with the other reporting fields into the existing prepare/create flow, so an evaluation launched from a template reports bad cases in its terminal state through the M9 #266/#341 outbox; when enabled but the configuration is incomplete or the ciphertext cannot be decrypted, the launch returns 422 before creating a run. +Before creating a run, a launch decrypts the stored token and passes it with the other reporting fields into the existing prepare/create flow, so an evaluation launched from a template reports bad cases in its terminal state through the M9 #266/#341 outbox; when enabled but the configuration is incomplete or the ciphertext cannot be decrypted, the launch returns 422 before creating a run. Machine triggers with `asset_override` inherit the template's reporting semantics with no extra switch and no dedup; self-evolution candidate evaluations should use a template with reporting disabled, and an override launch against a reporting-enabled template surfaces one warning in the response `warnings`. ## 6. Core Data Model @@ -228,8 +228,9 @@ Table 2 Core data model | agent_asset_snapshot / agent_asset | Immutable asset snapshots and assets | Resolved commit, tree digest, OSS address, content hash | | resource_pool / runner | Resource pool registry | Connection ID, provisioning mode, labels, status, last heartbeat | | eval_template | Evaluation templates (reusable launch presets) | Fixed fields and references, execution policy, self-evolution reporting config and encrypted token, enabled state, version, last launch time, creator | -| eval_run / eval_case_run | Evaluations and case executions | State machine, metric snapshots, asset snapshot, template ID and launch snapshot, session ID, timeout | +| eval_run / eval_case_run | Evaluations and case executions | State machine, metric snapshots, asset snapshot, template ID and launch snapshot, session ID, timeout; asset override and lineage (asset_override, evolution lineage) | | session / span | Normalized traces | Parent session, span kind, attribute JSONB, tokens and cost | +| service_token | Machine-trigger identity | hashed token, scopes, template allowlist, concurrency/budget caps, last-used and revocation state | ## 7. Concurrency Capacity diff --git a/docs/design/eval-platform-architecture.i18n.yaml b/docs/design/eval-platform-architecture.i18n.yaml index dbbf911a..70136223 100644 --- a/docs/design/eval-platform-architecture.i18n.yaml +++ b/docs/design/eval-platform-architecture.i18n.yaml @@ -1,5 +1,5 @@ # 双语配对一致性记录(docs/i18n/README.md):两侧在最后一次确认一致状态下的 # git blob hash。两种语言同等权威;编辑任一侧后带上另一侧,然后重录: # pnpm run record:i18n -- docs/design/eval-platform-architecture.md -eval-platform-architecture.md: 74d49e35ec324b8ebc4b7d9acae4409f91d0f8de -eval-platform-architecture.en.md: 5ef4f876621568131315a0410e1f034becc414c2 +eval-platform-architecture.md: b5b6d4ed28aab44b84e3db04b9001722495e6b5f +eval-platform-architecture.en.md: d9310e6f41a693a406911e23a19369750979ba83 diff --git a/docs/design/eval-platform-architecture.md b/docs/design/eval-platform-architecture.md index 74d49e35..b5b6d4ed 100644 --- a/docs/design/eval-platform-architecture.md +++ b/docs/design/eval-platform-architecture.md @@ -182,7 +182,7 @@ Skill、Command 与 Subagent 统一归入可配置的 Agent 资产源。资产 评测模板(eval_template)是项目级的可复用启动预设,把数据集版本、Agent 运行时、Agent 资产源与 Ref、资产选择、模型凭据、资源池、用例范围、执行策略、附加指令、最大轮次、Agent 超时与自进化上报目标保存为一组固定选择。模板只固化选择,不固化执行结果:每次启动都由 API 服务按模板重新解析资产 Ref、校验引用并生成新的不可变快照,评测记录保存 `template_id`、模板版本与启动快照,模板后续编辑不会改变已启动的评测。需要锁定内容时把 Ref 填成 commit;否则每次启动都解析该分支或 tag 的当时提交。 -模板的生命周期是创建、编辑、停用和删除;删除只从停用状态发起,删除模板不会级联删除已启动的评测与轨迹,运行记录保留模板标识与版本,模板名无法解析后来源处不再显示链接;删除接口为 `DELETE /api/v1/eval-templates/{template_id}`,需要管理员权限。停用或删除引用对象的模板不能启动,平台在创建运行前统一校验数据集版本、模型凭据、资源池与资产源是否仍可用。模板启动不接受配置覆盖,保证“一键”语义与结果可复现;需要不同组合时复制模板再编辑,或走现有的自定义发起流程。 +模板的生命周期是创建、编辑、停用和删除;删除只从停用状态发起,删除模板不会级联删除已启动的评测与轨迹,运行记录保留模板标识与版本,模板名无法解析后来源处不再显示链接;删除接口为 `DELETE /api/v1/eval-templates/{template_id}`,需要管理员权限。停用或删除引用对象的模板不能启动,平台在创建运行前统一校验数据集版本、模型凭据、资源池与资产源是否仍可用。控制台一键启动不接受配置覆盖,保证“一键”语义与结果可复现,需要不同组合时复制模板再编辑或走自定义发起流程;机器触发(服务令牌)可在启动请求携带可选 `asset_override`(repo_url、ref、commit、asset_paths、asset_types),把一次评测钉在指定代码仓的指定候选 commit 上,字段整体替换、缺省继承模板,commit 为权威身份且平台必须断言解析出的 `resolved_commit` 与请求 commit 一致,不一致即 422 拒绝、绝不静默评测,`ref` 仅作展示审计。 模板保存/更新时先校验确定性镜像依赖:执行与评分 digest 按「本次覆盖 → 数据集版本 → 平台默认」解析,三处皆空时返回 422,定位到 `execution.execution_image_digest` 与 `execution.scoring_image_digest`,提示补录 digest 或配置平台默认值。资产 Ref、容量与凭据仍在启动时检查。启动被 blocker 阻断时返回 `details.blockers`,界面逐条展示 code、message、字段与修复建议。 @@ -194,7 +194,7 @@ Skill、Command 与 Subagent 统一归入可配置的 Agent 资产源。资产 模板的启动历史复用评测列表读接口,不新增专用执行接口:`GET /api/v1/evaluations` 接受可选 `template_id` 过滤,与 `status`、`limit`、`offset` 组合,按启动时间倒序返回 `items`、`total`、`limit` 与 `offset`;模板不存在时返回 404,模板历史未显式传 `limit` 时默认 10,并附带 `status_counts` 计数映射。模板列表每行的“历史”和模板详情页的“启动历史”都通过该过滤分页读取,默认每页 10 条并支持 10/20/50 切换,状态筛选沿用评测状态枚举并显示计数(0 也保留),条目复用评测摘要并链接到评测详情;模板详情内嵌的 `recent_runs` 仍只保留最近 5 条预览。该过滤只读,不改变执行链路。评测列表的摘要同时返回解析后的来源模板 `template`(id、模板名、版本与启用状态),列表行据此对模板启动的评测显示“来自模板 · 模板名”并链接到模板详情,自定义发起的评测不显示来源行。 -三个稳定接口见表 12。三个接口都复用控制台会话鉴权:启动需要管理员权限,状态与结果对已登录用户只读;首期不提供独立的机器令牌。 +三个稳定接口见表 12。三个接口复用「控制台会话或服务令牌」鉴权:启动需要管理员权限或持 `eval:launch` 的服务令牌,状态与结果对已登录用户或持 `eval:read` 的服务令牌只读;服务令牌由管理员在 `/api/v1/service-tokens` 创建、列表与撤销,支持 scope、模板白名单与并发/预算上限,明文仅在创建响应返回一次,库内只存哈希,机器启动的 `created_by` 落 `svc:<名称>` 并进入既有审计与幂等约束。 表 12 评测模板的三个执行接口 @@ -204,11 +204,11 @@ Skill、Command 与 Subagent 统一归入可配置的 Agent 资产源。资产 | 查询状态 | GET /api/v1/eval-runs/{run_id}/status | 无 | `run_id`、`template_id`、`status`、`terminal`、进度计数、起止时间与解决率 | | 查询结果 | GET /api/v1/eval-runs/{run_id}/results | 无 | `run_id`、`status`、`is_final`、指标项与 token 摘要;运行中返回部分快照 | -启动接口先校验模板存在且启用、引用对象仍可用,再走既有的 prepare/create 流程;返回 404 表示模板或评测不存在,409 表示模板停用或幂等键冲突,422 表示引用对象失效或字段不可用,403 表示当前账号没有启动权限。状态接口在终态返回 `terminal=true`;结果接口在终态前返回 `is_final=false`,客户端据此决定是否继续轮询。 +启动接口先校验模板存在且启用、引用对象仍可用,再走既有的 prepare/create 流程;返回 404 表示模板或评测不存在,409 表示模板停用或幂等键冲突,422 表示引用对象失效或字段不可用,403 表示当前账号没有启动权限。状态接口在终态返回 `terminal=true`;结果接口在终态前返回 `is_final=false`,客户端据此决定是否继续轮询。带覆盖的启动在 202 响应回显 `asset`(resolved_commit、asset_snapshot_id、bundle_digest),status 与 results 同样回显该身份供调用方比对,新增 422 错误码 `candidate_commit_mismatch`、`asset_source_unresolved`、`asset_ref_unresolved`(`asset_selection_empty` 与 `asset_path_not_found` 复用既有码),任一命中即不创建评测。 模板启动不改变调度与执行链路:它只是在服务端把固定选择转换为一次普通的 prepare 与 create 调用,后续分片、Runner、评分、轨迹与结果聚合与自定义发起完全一致。因此模板不会绕过容量准入、预算、镜像预检或权限校验;失败发生在创建运行之前,不会留下半创建的任务。 -启动在创建运行前解密保存的令牌,把它与其他上报字段一并传入既有 prepare/create 链路,从模板启动的评测在终态按 M9 #266/#341 outbox 上报 bad case;启用但配置不完整或密文无法解密时,启动在创建运行前返回 422。 +启动在创建运行前解密保存的令牌,把它与其他上报字段一并传入既有 prepare/create 链路,从模板启动的评测在终态按 M9 #266/#341 outbox 上报 bad case;启用但配置不完整或密文无法解密时,启动在创建运行前返回 422。带 `asset_override` 的机器触发沿用模板的上报语义,不自增开关也不做去重;自进化候选评测应使用未启用上报的模板,模板启用上报时带覆盖启动在响应 `warnings` 中提示一次。 ## 6. 核心数据模型 @@ -228,8 +228,9 @@ Skill、Command 与 Subagent 统一归入可配置的 Agent 资产源。资产 | agent_asset_snapshot / agent_asset | 不可变资产快照与资产 | resolved commit、tree 摘要、OSS 地址、内容哈希 | | resource_pool / runner | 资源池登记 | 连接标识、供给模式、标签、状态、最近心跳 | | eval_template | 评测模板(可复用启动预设) | 固定字段与引用、执行策略、自进化上报配置与密文令牌、启用状态、版本、最近启动时间、创建人 | -| eval_run / eval_case_run | 评测与用例执行 | 状态机、指标快照、资产快照、模板标识与启动快照、会话标识、超时时间 | +| eval_run / eval_case_run | 评测与用例执行 | 状态机、指标快照、资产快照、模板标识与启动快照、会话标识、超时时间、资产覆盖与血缘(asset_override、evolution lineage) | | session / span | 归一化轨迹 | 父会话、span 类型、属性 JSONB、token 与成本 | +| service_token | 机器触发身份 | 哈希令牌、scope、模板白名单、并发/预算上限、最近使用与撤销状态 | ## 7. 并发能力 diff --git a/scripts/doc-budgets.manifest.json b/scripts/doc-budgets.manifest.json index c03cdfb0..7b65892d 100644 --- a/scripts/doc-budgets.manifest.json +++ b/scripts/doc-budgets.manifest.json @@ -1,13 +1,13 @@ { "//": "常驻文档词数上限。超限时先搬层或压缩;提高上限须在 PR 中说明。", - "// docs/design/eval-platform-architecture.md": "M1-02 architecture scope adds resource capability validation plus Git-backed Skill/Command/Subagent asset sources, editable refs, immutable commit snapshots, and runtime materialization; M10 adds the evaluation-template preset, one-click launch and three execution APIs (5.14 plus data model and flow references; 11500 -> 12800); M8 #382 adds the template-level self-evolution reporting contract to 5.14 and the eval_template row (12800 -> 13000); the template launch-history entry adds the evaluation-list template_id filter and paginated history modal to 5.14 (13000 -> 13200); M8 #398 adds save-time image-digest validation and launch-blocker guidance to 5.14 (13200 -> 13350); M10 #416 adds the disabled-only template deletion rule and run-history retention to 5.14 (13350 -> 13500).", + "// docs/design/eval-platform-architecture.md": "M1-02 architecture scope adds resource capability validation plus Git-backed Skill/Command/Subagent asset sources, editable refs, immutable commit snapshots, and runtime materialization; M10 adds the evaluation-template preset, one-click launch and three execution APIs (5.14 plus data model and flow references; 11500 -> 12800); M8 #382 adds the template-level self-evolution reporting contract to 5.14 and the eval_template row (12800 -> 13000); the template launch-history entry adds the evaluation-list template_id filter and paginated history modal to 5.14 (13000 -> 13200); M8 #398 adds save-time image-digest validation and launch-blocker guidance to 5.14 (13200 -> 13350); M10 #416 adds the disabled-only template deletion rule and run-history retention to 5.14 (13350 -> 13500); M10 #429 adds the machine-trigger `asset_override` candidate-pinning contract and the service-token launch/read scopes to 5.14 plus the service_token row in table 2 (13500 -> 13800).", "// docs/architecture.md": "M3-06 adds the administrator operations-status surface to the current component map and a short access/telemetry note; M4-04 adds the Aliyun spot provisioner + ephemeral JIT runner current-fact paragraph (800 -> 950); M5-02 adds the model-credentials console current-fact section (950 -> 1100); M5-01 adds the Agent asset source/snapshot + runtime injection paragraph (1100 -> 1200); M5-08 adds the production runner callback entry, pool-label dispatch and creation-verification provisioning facts (1200 -> 1350); M6-01 adds the native trace capture and multi-file manifest current-fact section (1350 -> 1550); M5-11 adds the permanent runner-tarball proxy fact with private OSS and heartbeat-token auth (1550 -> 1600); M5-12 adds the content-addressed scripts bundle, proxy and checkout fallback (1600 -> 1750); M5-15 adds the upload wizard, bounded validation subprocess, persisted report and commit-only immutable version (1750 -> 1950); M6-03 adds the versioned Claude Code parser evidence chain, deduplicated usage, root fragments and degradation facts (1950 -> 2150); M6-04 adds the attempt-scoped query, pagination and audited raw-content access facts (2150 -> 2250); M8-14 adds the GitHub egress proxy current-fact section with payload/exec env, allowlist maintenance and verification commands (2250 -> 2550; the deploy derives the proxy address from API_BIND_ADDRESS, 2550 -> 2600); the dynamic egress token, the authenticated public 3129 listener and the GitHub-only deny semantics add the token flow and public-path verification commands (2600 -> 3000); M9 #263 adds the self-evolution reporting current-fact section (launch config, outbox reporting, signed session envelope endpoint; 3000 -> 3150); M8 #273 adds the OSS dataset image tarball distribution current-fact paragraph (3150 -> 3300); M9 #277 adds the case-list main Agent session id current-fact section (3300 -> 3400; the old margin was only 4 words, so compression could not absorb the new fact; later additions should move detail to design 06 first); M8 #290 adds the DinD preparation worker, deterministic-key reuse and the profile/data-disk gate (3400 -> 3700). Page-level detail still stays in design 06 and the module docstrings. M8-43 (#304) adds the dispatch TTL > job > case > agent timeout hierarchy, the dispatch-provided execute job timeout and the SIGTERM partial-trace/terminal-callback facts (3700 -> 3800; page-level details stay in design 06); M8-44 adds the contended-pool scheduling reliability paragraph (3800 -> 3900); M8-47 (#312) adds the image/OSS scripts-bundle preload order, 60-second fetch budget and dispatch-pinned digest facts (3900 -> 4050); M8 #348 adds the prebuilt runner image, runtime auto-upgrade hardening, reboot-required guard and systemd-inhibit facts (4050 -> 4300).", "README.md": 420, "AGENTS.md": 520, "docs/AGENTS.md": 500, "docs/README.md": 520, "docs/architecture.md": 4300, - "docs/design/eval-platform-architecture.md": 13500, + "docs/design/eval-platform-architecture.md": 13800, "docs/development.md": 1160, "docs/i18n/README.md": 550, "docs/i18n/terminology.md": 220, From d127276a824b42143c4beebc3384272a8c32c945 Mon Sep 17 00:00:00 2001 From: TangZ-L <345187680+TangZ-L@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:46:50 +0800 Subject: [PATCH 4/8] =?UTF-8?q?fix(m10):=20=E6=94=B6=E7=B4=A7=E7=A9=BA?= =?UTF-8?q?=E8=A6=86=E7=9B=96=E4=B8=8E=E5=87=AD=E6=8D=AE=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E6=98=A0=E5=B0=84=E5=B9=B6=E8=A1=A5=E9=89=B4=E6=9D=83=E5=9B=9E?= =?UTF-8?q?=E5=BD=92=E6=B5=8B=E8=AF=95=20(#429)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/api/eval_templates.py | 7 +- backend/app/services/eval_templates.py | 23 +++++ backend/app/services/service_tokens.py | 20 +++- tests/backend/test_eval_templates.py | 129 ++++++++++++++++++++++++- 4 files changed, 173 insertions(+), 6 deletions(-) diff --git a/backend/app/api/eval_templates.py b/backend/app/api/eval_templates.py index e69c7866..83e52826 100644 --- a/backend/app/api/eval_templates.py +++ b/backend/app/api/eval_templates.py @@ -309,8 +309,11 @@ def launch_eval_template( } # Console compatibility: the one-click launch never received an override, # so its 202 body stays byte-for-byte identical to the pre-#429 contract. - if payload.asset_override is not None or run.asset_override_json: - body["asset"] = launch_meta.get("asset") + # An empty override object carries no intent and is normalized to absent by + # the service, so keying off the resolved identity (not the request field) + # also keeps a mismatched replay from emitting ``"asset": null``. + if launch_meta.get("asset") is not None: + body["asset"] = launch_meta["asset"] warnings = launch_meta.get("warnings") or [] if warnings: body["warnings"] = warnings diff --git a/backend/app/services/eval_templates.py b/backend/app/services/eval_templates.py index b1ac8273..d629f45d 100644 --- a/backend/app/services/eval_templates.py +++ b/backend/app/services/eval_templates.py @@ -67,6 +67,9 @@ PASSTHROUGH_ASSET_CODES = frozenset( {"asset_path_not_found", "asset_selection_empty", "asset_type_invalid"} ) +# Credential problems make the referenced Git objects unresolvable, so the +# launch maps them to ``asset_ref_unresolved`` (issue #429 error table). +UNRESOLVED_REFERENCE_CODES = frozenset({"credential_not_found", "credential_invalid"}) _COMMIT_PATTERN = re.compile(r"^[0-9a-f]{40}$") @@ -1236,6 +1239,19 @@ def _resolve_override_assets( details=dict(error.details or {}), code=error.code, ) from error + if error.code in UNRESOLVED_REFERENCE_CODES: + # A missing/invalid credential makes the repository objects + # unresolvable exactly like an unreachable repository: the issue + # contract maps that to ``asset_ref_unresolved``. + raise AssetRefUnresolved( + f"资产 Ref 解析失败:{error}", + field=ASSET_OVERRIDE_FIELD, + details={ + "field": ASSET_OVERRIDE_FIELD, + "requested_ref": resolution_ref, + "asset_code": error.code, + }, + ) from error raise TemplateInvalid( f"资产解析失败:{error}", field=ASSET_OVERRIDE_FIELD, @@ -1330,6 +1346,13 @@ def launch_template( settings = settings or get_settings() now = _now(now) + # ``asset_override: {}`` (or only explicit nulls) carries no intent: every + # field is absent, so it must behave exactly like a console one-click launch + # instead of failing because an inherited template has no asset source. + if asset_override is not None and not any( + value is not None for value in asset_override.values() + ): + asset_override = None key = (idempotency_key or "").strip() if not key: raise TemplateInvalid("启动必须提供幂等键", field="idempotency_key") diff --git a/backend/app/services/service_tokens.py b/backend/app/services/service_tokens.py index fd840fc3..fa56f948 100644 --- a/backend/app/services/service_tokens.py +++ b/backend/app/services/service_tokens.py @@ -46,6 +46,9 @@ MAX_ALLOWLIST_ITEMS = 100 MAX_TEMPLATE_ID_LENGTH = 36 MAX_CREATED_BY_LENGTH = 128 +# Audit refresh interval for ``last_used_at``: frequent status polls must not +# commit a row update on every read. +LAST_USED_WRITE_INTERVAL_SECONDS = 60.0 class ServiceTokenError(Exception): @@ -327,8 +330,13 @@ def authenticate( current = _now(now) if not _is_active(token, now=current): return None - token.last_used_at = current - session.commit() + # ``last_used_at`` is an audit hint, not a lease: a status poll should not + # turn a read into a write on every request. Refresh it at most once per + # interval; a fresh token records its first use immediately. + previous = _as_utc(token.last_used_at) + if previous is None or (current - previous).total_seconds() >= LAST_USED_WRITE_INTERVAL_SECONDS: + token.last_used_at = current + session.commit() return token @@ -340,6 +348,14 @@ def enforce_launch_caps( Both caps count the runs the token itself created (``created_by`` is the ``svc:`` actor label), so a console user with the same template is never charged to the machine identity. + + The check is an admission guard, not a hard quota: two launches can race + between the count and the run insert. Serializing it would need a token + row lock held across the whole launch transaction, which the prepare/create + path deliberately keeps short; the documented contract is best-effort. + The budget cap compares spend already reconciled on the token's runs, so a + launch that is still running is counted by the concurrency cap, not the + budget cap. """ current = _now(now) diff --git a/tests/backend/test_eval_templates.py b/tests/backend/test_eval_templates.py index 283084d3..3adcae95 100644 --- a/tests/backend/test_eval_templates.py +++ b/tests/backend/test_eval_templates.py @@ -10,7 +10,7 @@ import hashlib import json -from dataclasses import dataclass +from dataclasses import dataclass, field from decimal import Decimal from uuid import uuid4 @@ -1131,6 +1131,9 @@ class FakeRepo: commit: str = CANDIDATE_COMMIT files: dict[str, bytes] | None = None + # Every ref the server asked to resolve, in order. A commit-only launch + # must never ask the provider to resolve the display ref. + resolved_refs: list[str] = field(default_factory=list) def __post_init__(self) -> None: if self.files is None: @@ -1150,11 +1153,13 @@ def __init__( *, resolve_error: Exception | None = None, resolved_commit: str | None = None, + ref_commit: str | None = None, ) -> None: self.repo = repo self.token = token self.resolve_error = resolve_error self.resolved_commit = resolved_commit + self.ref_commit = ref_commit self.blobs = { hashlib.sha1(path.encode()).hexdigest(): content for path, content in repo.files.items() @@ -1166,7 +1171,14 @@ def close(self) -> None: def resolve_commit(self, owner: str, repo: str, ref: str) -> str: if self.resolve_error is not None: raise self.resolve_error - return self.resolved_commit or self.repo.commit + self.repo.resolved_refs.append(ref) + if ref == self.repo.commit: + # A full SHA resolves to itself; ``resolved_commit`` can force a + # drift so the candidate_commit_mismatch assertion is exercised. + return self.resolved_commit or self.repo.commit + # A non-SHA ref resolves to the configured branch commit: a test that + # supplies both ref and commit can prove the ref was never consulted. + return self.ref_commit or self.repo.commit def tree(self, owner: str, repo: str, commit: str) -> list[TreeEntry]: return [ @@ -1440,6 +1452,91 @@ def test_launch_without_override_keeps_the_console_response_shape( assert "asset" not in replay.json() +def test_empty_asset_override_is_the_console_contract( + client: TestClient, session: Session +) -> None: + """``asset_override: {}`` has no intent: it must not demand an asset source.""" + + ids = seed_launch(session) + template = create_template(client, ids) + + response = launch_override( + client, template["id"], key="empty-override", override={} + ) + assert response.status_code == 202, response.text + body = response.json() + assert "asset" not in body + run = session.get(EvalRun, body["run_id"]) + assert run is not None + assert run.asset_override_json == {} + # Still a replayable idempotent launch with the console response shape. + assert body["created"] is True + + +def test_commit_is_authoritative_even_when_ref_is_supplied( + client: TestClient, + session: Session, + monkeypatch: pytest.MonkeyPatch, + asset_store: StubObjectStore, +) -> None: + # ``main`` resolves to the base commit; only the candidate SHA may win. + repo = install_fake_github(monkeypatch, ref_commit=BASE_COMMIT) + _ids, _source, template = seed_candidate_template(client, session) + + response = launch_override( + client, + template["id"], + key="commit-beats-ref", + override={"ref": "main", "commit": CANDIDATE_COMMIT}, + ) + assert response.status_code == 202, response.text + asset = response.json()["asset"] + assert asset["resolved_commit"] == CANDIDATE_COMMIT + assert asset["requested_ref"] == "main" + # The provider was asked to resolve the commit, never the display ref. + assert repo.resolved_refs == [CANDIDATE_COMMIT] + status = client.get(f"/api/v1/eval-runs/{response.json()['run_id']}/status").json() + assert status["asset"]["resolved_commit"] == CANDIDATE_COMMIT + assert status["asset"]["requested_ref"] == "main" + + +def test_routes_that_dropped_router_dependencies_require_auth( + client: TestClient, session: Session, monkeypatch: pytest.MonkeyPatch +) -> None: + """No route lost its guard when the router-level dependencies were removed.""" + + install_fake_github(monkeypatch) + ids = seed_launch(session) + template = create_template(client, ids) + launched = client.post( + f"/api/v1/eval-templates/{template['id']}/launch", + headers={"Idempotency-Key": "anonymous-guard"}, + json={}, + ) + assert launched.status_code == 202, launched.text + run_id = launched.json()["run_id"] + + client.cookies.clear() + protected = [ + ("GET", "/api/v1/eval-templates"), + ("GET", f"/api/v1/eval-templates/{template['id']}"), + ("PATCH", f"/api/v1/eval-templates/{template['id']}"), + ("DELETE", f"/api/v1/eval-templates/{template['id']}"), + ("POST", f"/api/v1/eval-templates/{template['id']}/launch"), + ("GET", f"/api/v1/eval-runs/{run_id}/status"), + ("GET", f"/api/v1/eval-runs/{run_id}/results"), + ("GET", f"/api/v1/eval-runs/{run_id}/compare"), + ("GET", "/api/v1/eval-case-runs/missing/tests"), + ("GET", "/api/v1/service-tokens"), + ("POST", "/api/v1/service-tokens"), + ("DELETE", "/api/v1/service-tokens/missing"), + ] + for method, path in protected: + response = client.request(method, path, json={}) + assert response.status_code == 401, (method, path, response.text) + assert response.json()["detail"]["error"]["code"] == "unauthenticated" + + def test_override_repo_url_must_be_a_registered_source( client: TestClient, session: Session, @@ -1498,6 +1595,34 @@ def test_override_unresolvable_commit_is_a_ref_error( assert _run_count(session, template["id"]) == 0 +def test_override_credential_failure_maps_to_ref_unresolved( + client: TestClient, + session: Session, + monkeypatch: pytest.MonkeyPatch, + asset_store: StubObjectStore, +) -> None: + """A broken source credential is a reference-resolution failure (issue 429).""" + + install_fake_github(monkeypatch) + _ids, _source, template = seed_candidate_template(client, session) + + def fail_resolve(*_args: object, **_kwargs: object): + raise agent_assets.AgentAssetError("credential_invalid", "Git 访问令牌无效") + + monkeypatch.setattr(template_service.asset_service, "resolve_assets", fail_resolve) + response = launch_override( + client, + template["id"], + key="credential-invalid", + override={"commit": CANDIDATE_COMMIT}, + ) + assert response.status_code == 422, response.text + error = response.json()["detail"]["error"] + assert error["code"] == "asset_ref_unresolved" + assert error["details"]["asset_code"] == "credential_invalid" + assert _run_count(session, template["id"]) == 0 + + def test_override_selection_errors_keep_the_existing_asset_codes( client: TestClient, session: Session, From 1e7ae4b1229202d1ae157654e35e2b86f66fb11b Mon Sep 17 00:00:00 2001 From: TangZ-L <345187680+TangZ-L@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:51:49 +0800 Subject: [PATCH 5/8] =?UTF-8?q?fix(m10):=20=E5=AF=B9=E9=BD=90=200035=20?= =?UTF-8?q?=E8=BF=81=E7=A7=BB=E7=89=88=E6=9C=AC=E6=96=AD=E8=A8=80=E5=B9=B6?= =?UTF-8?q?=E8=A1=A5=E5=85=85=20issue=20scope=20(#429)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .agents/flow/issues/m10-candidate-launch-override.en.md | 2 ++ .agents/flow/issues/m10-candidate-launch-override.i18n.yaml | 4 ++-- .agents/flow/issues/m10-candidate-launch-override.md | 2 ++ tests/backend/test_deployment_migration.py | 2 +- tests/backend/test_operations.py | 2 +- 5 files changed, 8 insertions(+), 4 deletions(-) diff --git a/.agents/flow/issues/m10-candidate-launch-override.en.md b/.agents/flow/issues/m10-candidate-launch-override.en.md index 984f2265..0d5cbf76 100644 --- a/.agents/flow/issues/m10-candidate-launch-override.en.md +++ b/.agents/flow/issues/m10-candidate-launch-override.en.md @@ -26,6 +26,8 @@ scope: - tests/backend/test_eval_templates.py - tests/backend/test_results.py - tests/backend/test_service_tokens.py + - tests/backend/test_operations.py + - tests/backend/test_deployment_migration.py - docs/design/eval-platform-architecture.md - docs/design/eval-platform-architecture.en.md - docs/design/eval-platform-architecture.i18n.yaml diff --git a/.agents/flow/issues/m10-candidate-launch-override.i18n.yaml b/.agents/flow/issues/m10-candidate-launch-override.i18n.yaml index d3f7a5db..a7e822b4 100644 --- a/.agents/flow/issues/m10-candidate-launch-override.i18n.yaml +++ b/.agents/flow/issues/m10-candidate-launch-override.i18n.yaml @@ -1,5 +1,5 @@ # 双语配对一致性记录(docs/i18n/README.md):两侧在最后一次确认一致状态下的 # git blob hash。两种语言同等权威;编辑任一侧后带上另一侧,然后重录: # pnpm run record:i18n -- .agents/flow/issues/m10-candidate-launch-override.md -m10-candidate-launch-override.md: 9c020b1fed4b19ef8baf1616eaa107bbeda5f28d -m10-candidate-launch-override.en.md: 984f22654df2c29fe3cfc523abcbfa974ddea202 +m10-candidate-launch-override.md: cf52aa9ceff0fcbea8254179f77b7caadac15ebf +m10-candidate-launch-override.en.md: 0d5cbf761a09a97dc2d245ab64094d2573ea37c7 diff --git a/.agents/flow/issues/m10-candidate-launch-override.md b/.agents/flow/issues/m10-candidate-launch-override.md index 9c020b1f..cf52aa9c 100644 --- a/.agents/flow/issues/m10-candidate-launch-override.md +++ b/.agents/flow/issues/m10-candidate-launch-override.md @@ -26,6 +26,8 @@ scope: - tests/backend/test_eval_templates.py - tests/backend/test_results.py - tests/backend/test_service_tokens.py + - tests/backend/test_operations.py + - tests/backend/test_deployment_migration.py - docs/design/eval-platform-architecture.md - docs/design/eval-platform-architecture.en.md - docs/design/eval-platform-architecture.i18n.yaml diff --git a/tests/backend/test_deployment_migration.py b/tests/backend/test_deployment_migration.py index f92430f7..1eb9fbb9 100644 --- a/tests/backend/test_deployment_migration.py +++ b/tests/backend/test_deployment_migration.py @@ -33,7 +33,7 @@ def test_deployment_table_and_revision(database_url: str) -> None: } <= columns with Session(engine) as session: revision = session.scalar(text("SELECT version_num FROM alembic_version")) - assert revision == "0034_pool_unique_labels" + assert revision == "0035_service_token" finally: engine.dispose() diff --git a/tests/backend/test_operations.py b/tests/backend/test_operations.py index 7e0953c4..00dea830 100644 --- a/tests/backend/test_operations.py +++ b/tests/backend/test_operations.py @@ -100,7 +100,7 @@ def test_operations_status_reports_services_resources_and_database( database = payload["database"] assert database["status"] == "ok" assert database["dialect"] in {"sqlite", "postgresql"} - assert database["revision"] == "0034_pool_unique_labels" + assert database["revision"] == "0035_service_token" assert database["size_bytes"] > 0 capacity = database["capacity"] assert set(capacity) == { From def12d79854085cf1e17f8c47c10bae158f1c58f Mon Sep 17 00:00:00 2001 From: TangZ-L <345187680+TangZ-L@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:15:56 +0800 Subject: [PATCH 6/8] =?UTF-8?q?docs(m10):=20=E8=A1=A5=20PR=20#431=20?= =?UTF-8?q?=E6=A3=80=E8=A7=86=E8=AE=B0=E5=BD=95=20(#429)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pr431-review.md | 727 ++++++++++++++++++ 1 file changed, 727 insertions(+) create mode 100644 plans/2026-11-25-m10-candidate-launch-override/pr431-review.md diff --git a/plans/2026-11-25-m10-candidate-launch-override/pr431-review.md b/plans/2026-11-25-m10-candidate-launch-override/pr431-review.md new file mode 100644 index 00000000..43e735da --- /dev/null +++ b/plans/2026-11-25-m10-candidate-launch-override/pr431-review.md @@ -0,0 +1,727 @@ +# PR #431 检视记录 — 评测模板机器触发:候选 commit 注入与服务令牌 + +- **检视对象**:[PR #431](https://github.com/Shadow-Azure/ai-eval-platform/pull/431) `feat(m10): 评测模板机器触发:候选 commit 注入与服务令牌 (#429)`,base `main`,head `agent/candidate-launch-override-03cd0f5d`。 +- **提交**:`d77d0bc`(服务令牌与鉴权依赖)、`67e07d6`(launch 覆盖 + 令牌鉴权)、`92bdd45`(文档 §5.14)、`d127276`(空覆盖/凭据错误映射收紧 + 鉴权回归)、`1e7ae4b`(0035 迁移版本断言 + issue scope)。 +- **规模**:22 文件,+2784 / −50。 +- **owning Note / issue**:[`.agents/flow/issues/m10-candidate-launch-override.md`](../../.agents/flow/issues/m10-candidate-launch-override.md)(GitHub issue #429,状态 `in-progress`)。 +- **实现计划**:[`openapi-change.md`](openapi-change.md)(schema 级 diff)、[`docs-5-14-revision.md`](docs-5-14-revision.md)(中英替换文案);两份均已在 `main` 上,不在本 PR diff 内。 +- **日期**:2026-11-25。 +- **路径偏离说明**:`pr-review` 技能默认把检视文档落在 `plans/yyyy-mm-dd-pr-review.md`;本 issue 的 `scope` 只允许 `plans/2026-11-25-m10-candidate-launch-override/**`,`plans/2026-11-25-pr431-review.md` 不在白名单内,因此本文件改落当前路径。这样 `verify-flow --diff origin/main` 的 scope 校验仍可通过。 +- **检视口径**:本次仅读取代码与证据,未修改任何实现、测试、常驻文档或流程文件;文中的行号均来自对本工作树文件的实际读取,`plans/` 之外的路径指仓库根相对路径。 + +--- + +## §0 变更文件树与职责 + +共 22 = **新增 A 4 + 修改 M 18**,按架构故事排序;每行一句话职责。 + +```text +# 1) 机器身份:令牌表 + 生命周期服务 + 管理员 API + 鉴权依赖(A3 / M4) +backend/app/models/identity.py M +47 service_token 表模型 + SERVICE_TOKEN_SCOPES 常量 +backend/app/models/__init__.py M +4 导出 ServiceToken / SERVICE_TOKEN_SCOPES +backend/migrations/versions/0035_service_token.py A +102 建 service_token 表 + eval_run 两个 JSON 列 + 索引 +backend/app/services/service_tokens.py A +433 令牌创建/校验/撤销、scope 与白名单、并发/预算上限 +backend/app/api/service_tokens.py A +93 POST/GET/DELETE /api/v1/service-tokens(仅管理员会话) +backend/app/api/dependencies.py M +103 Actor 主体 + require_session_or_service(scope) 依赖 +backend/app/main.py M +11 挂载令牌路由;把三个路由的“路由级鉴权”改为逐路由声明 + +# 2) 候选覆盖:请求模型、解析与冻结、读模型回显(M4) +backend/app/api/eval_templates.py M +64 AssetOverrideRequest / LaunchLineageRequest;launch 接 Actor、回显 asset/warnings +backend/app/services/eval_templates.py M +399 覆盖解析(源、commit 断言、快照)、回显与重放、launch 三元返回 +backend/app/models/evaluation.py M +10 eval_run.asset_override_json / evolution_lineage_json +backend/app/api/results.py M +27 status/results 换“会话或 eval:read 令牌”并要求回显 asset/lineage + +# 3) 契约文档(M5,双语三件套 + 预算登记) +docs/design/eval-platform-architecture.md M +6 §5.14 机器触发/令牌鉴权/回显与错误码 + 表 2 两行 +docs/design/eval-platform-architecture.en.md M +6 英文侧镜像 +docs/design/eval-platform-architecture.i18n.yaml M +2 重录配对 blob +scripts/doc-budgets.manifest.json M +2 预算 13500 → 13800 并登记理由 + +# 4) 流程文件(M3) +.agents/flow/issues/m10-candidate-launch-override.md M +5 status → in-progress;scope 补 5 个实际改动路径 +.agents/flow/issues/m10-candidate-launch-override.en.md M +5 英文侧镜像 +.agents/flow/issues/m10-candidate-launch-override.i18n.yaml M +2 重录配对 blob + +# 5) 测试(A1 / M3) +tests/backend/test_service_tokens.py A +590 令牌 CRUD/哈希/撤销/过期/依赖/上限的单测 +tests/backend/test_eval_templates.py M +871 覆盖启动端到端(含 fake GitHub + StubObjectStore)、鉴权回归 +tests/backend/test_operations.py M +1 数据库 revision 断言 0034 → 0035 +tests/backend/test_deployment_migration.py M +1 部署迁移 revision 断言同步 +``` + +- issue scope 里列的 `tests/backend/test_results.py` 本 PR **未改**:status/results 的鉴权与回显用例写进了 `test_eval_templates.py`(`tests/backend/test_eval_templates.py:1922`),不影响 scope 校验。 +- `plans/2026-11-25-m10-candidate-launch-override/openapi-change.md` 与 `docs-5-14-revision.md` 是本 issue 的设计产物,已在 `main`,本 PR 只读不改。 + +--- + +## §1 一页速览 + +**一句话**:给“模板一键启动”开了一个机器入口——HE(harness-evolution)拿服务令牌调 launch,可选地把本次评测钉在某个仓库的某个候选 commit 上;平台沿用既有资产解析/快照冻结与 prepare/create 链路,把解析出的 commit 冻结进 run 并在 202/status/results 回显,控制台原路径的输入、返回、权限与幂等语义一律不变。 + +**一个比喻**:服务令牌是发给自动化的**门禁卡**(卡上写着能进哪几间房、每天能用多少预算),不是“替人登录”;`asset_override` 是一张**取样单**——写明去哪家仓库、取哪个 commit、取哪几份文件,平台当场取样、封存成不可变样本(快照)并贴封条号(`asset_snapshot_id` + `bundle_digest`),之后仓库分支怎么动都不影响这次检测;`commit` 是取样前必须核对的瓶身编号,对不上就整单退回(422),绝不“差不多就行”。幂等键则是单据号——重打同一张单据,拿回的是同一个 run。 + +### 交付块 + +| 交付块 | 内容 | 关键位置 | +|---|---|---| +| 机器身份 | `service_token` 表 + 迁移 0035;令牌明文只回一次、库内只存 SHA-256;scope、模板白名单、并发/预算上限、过期与撤销 | `backend/app/models/identity.py:142`、`backend/app/services/service_tokens.py:217`、`backend/migrations/versions/0035_service_token.py:32` | +| 鉴权依赖 | `Actor` 主体 + `require_session_or_service(scope)`:管理员会话或 `eval:launch` 令牌;任意会话或 `eval:read` 令牌;带 `Authorization` 头就只看令牌,不回退 Cookie | `backend/app/api/dependencies.py:103`、`:137` | +| 候选注入 | launch 请求可选 `asset_override`(repo_url/ref/commit/asset_paths/asset_types,整字段替换)与 `lineage`;commit 权威并断言 `resolved_commit == commit` | `backend/app/api/eval_templates.py:90`、`backend/app/services/eval_templates.py:1171` | +| 回显 | 202 带 `asset`(有覆盖时)与 `warnings`(覆盖 + 模板开上报时);status/results 带 `asset`,results 另带 `lineage` | `backend/app/services/eval_templates.py:1131`、`:1146`、`backend/app/api/results.py:246` | +| 文档 | `docs/design/eval-platform-architecture.md` §5.14 + 表 2 中英镜像;预算 13500 → 13800 | `docs/design/eval-platform-architecture.md:185`、`:197`、`:207`、`:211`、`:231`、`:233` | + +### 验证基线(本次实测引用) + +| 证据 | 结果 | 来源 | +|---|---|---| +| PR CI | **8/8 全绿**:`backend (pytest + migration)` 8m11s、`backend changes`、`deployment contract`、`docs`、`flow-offline`、`flow-online`、`runner (node contract tests)`、`web (typecheck + build)` | `gh pr checks 431`;runs 45571559222 / 45571559029 / 45571559015 | +| 真实环境冒烟 | 证据 JSON 内 **15 项检查全部 `ok: true`**(交接记录写 14 项,以证据文件为准):202、`resolved_commit == 请求 commit`(`a82a590ade533b9ce8cc46f9be250e1a726da2d3`)、`requested_ref` 回显、快照与 bundle、幂等重放、status/results 回显、`asset_source_unresolved`/`asset_ref_unresolved` 422、错 scope 403、匿名 401、撤销后 401 | `.tmp-t/smoke-429-evidence.json`(仓库外,未入库) | +| 控制台回归 | 模板列表/详情、评测详情渲染与原型比对(6 张截图 + `facts.json`);评测详情显示“创建人 `svc:hev-smoke-1681755553`”,模板详情显示启动历史 1 次 | `reports/2026-11-25/m10-429-machine-trigger/`(仓库外,未入库) | +| PR 描述自述 | `pytest` 四套件 127 passed、迁移/运维/鉴权套件全绿、`verify-flow` 与 `doc-quick`/`doc-sync` 绿 | PR body“本地验证”(本次未复跑) | +| 冒烟与门禁段落 | PR body 仍写“(待补:…)” | PR body(见 §6.3) | + +> 冒烟与截图证据都在仓库外(`.tmp-t/` 与 `reports/` 未跟踪目录),本 PR 不提交这些产物——符合“证据留档但不入库”的约定。 + +--- + +## §2 架构导览 + +### 2.1 身份层:一个 `Actor` 顶替两种主体 + +`backend/app/api/dependencies.py:35` 的 `Actor` 是这次新增的“主体抽象”,四个字段说明一切: + +```python +@dataclass(frozen=True) +class Actor: + label: str # 控制台 = 用户邮箱;机器 = svc:<令牌名> + is_admin: bool + is_service: bool + scopes: frozenset[str] = frozenset() + service_token: ServiceToken | None = None +``` + +`require_session_or_service(scope)`(`dependencies.py:137`)返回一个依赖闭包,内部只有两条路(`:148`): + +- **有 `Authorization` 头 → 只走令牌**(`:153`)。`_service_actor`(`:103`)先拆 `Bearer`、再要求 `hev_` 前缀、再 `authenticate()` 查库、再校验 scope(缺 → 403),最后对 `eval:launch` 校验模板白名单(`:122`,从 `request.path_params["template_id"]` 取,避免依赖路由自己传参)。 +- **无头 → 走会话**(`:156`):`_resolve` 取 Cookie 会话,`eval:launch` 还要求管理员角色(`:160`),`eval:read` 任意已登录角色即可。 + +两个关键纪律写在模块 docstring(`:3`–`:9`):**头存在但格式错误永远是 401,绝不悄悄回退到 Cookie**。这条对自动化特别重要——否则一个拼错的令牌会被“恰好还登录着”的浏览器会话兜住,故障被掩盖。`test_service_tokens.py:438` 用“合法 Cookie + `Basic abc`”把这个边界钉住了。 + +### 2.2 令牌存储:一张只存哈希的表 + +`backend/app/models/identity.py:145` 的 `ServiceToken`:`token_hash`(64 字符 SHA-256 hex,唯一)、`scopes_json`、`template_allowlist_json`(空 = 全部模板)、`max_concurrent_runs`、`daily_budget_cny`(`Numeric(12,6)`,与平台金额列同精度)、`expires_at`、`revoked_at`、`last_used_at`、`created_by`;唯一约束是 `(tenant_id, name)`,另加 `(tenant_id, id)` 与列表索引。 + +迁移 `0035_service_token`(`backend/migrations/versions/0035_service_token.py:32`)与模型一一对应:建表 → `ix_service_token_tenant_id`(对应 `tenant_fk()` 的 `index=True`,`backend/app/models/base.py:54`)→ `(tenant_id, revoked_at, created_at)` 复合索引 → 给 `eval_run` 加两列 `asset_override_json` / `evolution_lineage_json`(`server_default '{}'`,老 run 不受影响)→ `downgrade` 逆序删列删表。 + +比喻:发出去的是**一次性钥匙坯**,锁孔里只留钥匙的齿纹(哈希);别人捡到数据库也配不出钥匙。 + +### 2.3 令牌生命周期:创建、认证、上限、视图 + +`backend/app/services/service_tokens.py` 是纯服务层,错误类自带 `status/code`(`:54`–`:92`),API 层只做转发: + +- **创建**(`:217`):逐字段规范化(`_name`/`_scopes`/`_template_allowlist`/`_max_concurrent_runs`/`_daily_budget`/`_expires_at`),名称先查重再落库,并捕获 `IntegrityError` 兜住并发同名(`:262`)。明文 `hev_` + 32 字节 `token_urlsafe`(`:249`)只在这里返回,不写日志、不进视图。 +- **认证**(`:308`):前缀校验 → 按 `token_hash` 查行 → `_is_active` 判撤销/过期 → 命中后按 60 秒节流刷新 `last_used_at`(`:337`)。节流是为状态轮询设计的:不能让每次 GET 都变成一次写库。 +- **上限**(`:343`):并发按 `created_by == svc:` 且状态非终态计数;预算按当天(UTC 自然日)该主体的 `budget_spent_cny` 求和,`>= cap` 即 429。docstring(`:352`–`:358`)明说这是**准入守卫(best-effort)而非硬配额**,选它而不做强串行化,是因为 prepare/create 链路刻意保持短事务(见 §6.4)。 +- **视图**(`:411`):只回元数据 + `active` 派生位,永不含 `token_hash`;`actor_label`(`:430`)产出 `svc:`,与既有 `created_by` 审计和 `(tenant_id, created_by, idempotency_key)` 幂等约束天然对齐(机器与真人互不串单)。 + +### 2.4 覆盖解析:先定“去哪个仓库”,再定“取哪个 commit” + +`backend/app/services/eval_templates.py` 新增了三个错误类(`:136` `AssetSourceUnresolved`、`:143` `AssetRefUnresolved`、`:150` `CandidateCommitMismatch`,均 422 且 `code` 与 issue 的错误表逐字一致)和一组小函数: + +1. `_override_text` / `_override_paths` / `_override_types`(`:1018`–`:1078`):服务层兜底校验(不信任 Pydantic,因为 service 也被测试/内部直接调用);`None` 一律表示“该字段缺省 → 继承模板”。 +2. `_override_source`(`:1080`):给了 `repo_url` 就在同租户**精确匹配**已登记 `AgentAssetSource`,未命中 → `asset_source_unresolved`;没给就用模板自己的 `asset_source_id`,模板也没绑 → 同样 `asset_source_unresolved`(“覆盖未指定 repo_url 且模板未绑定资产源”)。 +3. `_resolve_override_assets`(`:1171`):`resolution_ref = commit or ref or 模板 asset_ref or 源 default_ref`(`:1198`);`ref` 只用于**回显**(`:1209`–`:1216`,有 ref 就原样回显,没有就回显 commit);随后调用既有 `asset_service.resolve_assets`(`:1224`),把资产域错误分成三档映射(`:1234`–`:1277`): + - `asset_path_not_found / asset_selection_empty / asset_type_invalid` → 原码透传(与 run 级资产接口同一契约); + - `credential_not_found / credential_invalid` → `asset_ref_unresolved`(凭据坏了等价于对象取不到); + - 其余(网络、对象存储)→ `template_reference_invalid`。 +4. **断言**(`:1278`):`commit` 存在且 `snapshot.resolved_commit != commit` → `candidate_commit_mismatch`,details 同时给 `requested` 与 `resolved`。断言发生在 `build_preparation` 之前,所以失败时连 preparation 都不会留下。 +5. 归一化身份写进 `effective`(`:1284`),同时作为 202 的 `asset` 块和 run 的冻结值来源。 + +对照既有路径 `_resolve_template_assets`(`:919`)就能看出设计取向:**老路径一行没改**,新逻辑只是一个分叉(`launch_template:1390`),两条路最终都落到同一个 `build_preparation(asset_snapshot_id=...)`(`:1404`)。也就是说,覆盖只改变“资产从哪来”,不新增任何执行路径。 + +### 2.5 冻结与回显:run 是唯一事实源 + +`launch_template`(`:1321`)现在返回 `(run, created, launch_meta)`,并在三处落库: + +- `run.asset_override_json = {"requested": ..., "effective": ...}`(`:1456`):既留原始请求(审计:调用方到底要了什么),也留归一化结果(回显:实际测了什么); +- `run.evolution_lineage_json = lineage`(`:1463`):纯血缘,不参与评测语义; +- `launch_meta` 只带 `asset` 与 `warnings`,由 API 层决定是否放进 202(`backend/app/api/eval_templates.py:315`)。 + +读侧 `run_asset_identity`(`:1146`)刻意**读快照而不是读模板**:`resolved_commit` 取 `AgentAssetSnapshot.resolved_commit`,`asset_snapshot_id` 取快照 id,`requested_ref` 优先取冻结的 `effective.requested_ref`(覆盖启动)否则取 `snapshot.requested_ref`(控制台启动)。于是 status/results 的回显永远等于“当时测的那一份”,模板改名、分支移动、令牌轮换都改不了它。 + +### 2.6 错误信封与装配 + +- API 层统一 `_http_error`(`backend/app/api/eval_templates.py:122`):把 `field` 折成 `details.fields. = "invalid"`,再交给 `error_detail`(`backend/app/api/errors.py:8`)拼 `{"error": {code, message, request_id, details}}`。模板错误与令牌错误共用这一个函数。 +- `main.py:79`–`:95` 把 `eval_templates` 与 `results` 两个路由的**路由级** `Depends(require_session)` 摘掉,改为逐路由声明:launch 用 `require_session_or_service("eval:launch")`,status/results 用 `eval:read`,compare/case-tests 保留 `require_session`,模板列表/详情保留 `require_session`,写操作保留 `require_admin`。这类“拆路由级依赖”的改动最容易漏鉴权,PR 用 `test_routes_that_dropped_router_dependencies_require_auth`(`tests/backend/test_eval_templates.py:1503`)逐个路径断言 401——这是本次检视里我最认可的一处防御。 + +--- + +## §3 数据流走查 + +下面用一次真实的机器启动(数据取自冒烟证据,模板 `1aac08bc…`,请求 commit `a82a590ade533b9ce8cc46f9be250e1a726da2d3`)走完整条链路,每步给锚点。 + +### 剧本 A:带覆盖的机器启动(成功路径) + +1. **管理员建令牌**(控制台会话)→ `POST /api/v1/service-tokens`(`backend/app/api/service_tokens.py:48`)→ `_admin` 依赖校验管理员 → `create_token` 生成 `hev_…` 并只存哈希(`service_tokens.py:249`)→ 201 响应里 `token` 只出现这一次(响应里 `response.text.count(plaintext) == 1`,`tests/backend/test_service_tokens.py:148`)。 +2. **HE 调 launch**:`Authorization: Bearer hev_…` + `Idempotency-Key` + body(示例): + + ```json + { + "idempotency_key": "round-1-candidate", + "asset_override": { + "repo_url": "https://github.com/Shadow-Azure/ai-eval-platform", + "ref": "main", + "commit": "a82a590ade533b9ce8cc46f9be250e1a726da2d3", + "asset_paths": [".claude/skills/review/SKILL.md"], + "asset_types": {".claude/skills/review/SKILL.md": "skill"} + }, + "lineage": {"evolutionRunId": "evo-smoke-429", "evolutionRoundId": "round-1", "roundSeq": 1} + } + ``` + +3. **鉴权**(`dependencies.py:153` → `_service_actor`):拆头、查令牌、验 `eval:launch`、验模板白名单 → `Actor(label="svc:")`。 +4. **route 归一化请求**(`backend/app/api/eval_templates.py:276`):`model_dump(exclude_unset=True)` 让“没传”和“显式 null”都表现为缺省;`created_by=context.label`(`:291`),因此 run 的 `created_by` 落 `svc:`。 +5. **服务层**(`services/eval_templates.py:1347` 起):空覆盖归一(`:1352`)→ 幂等重放优先(`:1364`–`:1378`)→ 令牌上限准入(`:1379`,先于“模板是否启用”)→ `enabled` 校验(`:1381`)→ 自进化上报目标校验(`:1386`,坏目标不产生 run)→ 覆盖解析并断言 commit(`:1395` → `:1171`)→ `resolve_assets` 冻结快照(可能复用同 digest 的既有快照)。 +6. **prepare/create**(`:1404`、`:1442`):把 `asset_snapshot_id` 交给既有 `build_preparation`,`consume_preparation` 建 run(`backend/app/services/preparations.py:1027` 把快照 id 写到 run)。随后补 `template_id/version/snapshot`、写 `asset_override_json/lineage`、`launch_count += 1`、一次 `commit`(`:1453`–`:1469`)。 +7. **202**(`api/eval_templates.py:302`):`{run_id, template_id, status, status_url, result_url, created, asset:{repo_url, requested_ref, requested_commit, resolved_commit, asset_snapshot_id, bundle_digest}}`;本场景模板未开上报,故无 `warnings`。 +8. **HE 比对**:把 `asset.resolved_commit` 与请求 commit 逐字比较(平台已断言过一次,这里是双保险);不一致就说明请求和响应被中间层改写,HE 不进入轮询。 +9. **轮询 status**(`api/results.py:257`):用 `eval:read` 令牌读;响应除既有进度字段外多一个 `asset{resolved_commit, asset_snapshot_id, requested_ref}`(`:308`–`:311`),取自快照(`services/eval_templates.py:1146`)。 +10. **取 results**(`api/results.py:177`):终态 `is_final=true`,附 `asset` 与 `lineage`(`:246`–`:253`);HE 据此换算目标分/覆盖率/护栏(裁决在 HE,平台不给 verdict)。 + +### 剧本 B:幂等重放 + +HE 超时重发同一 `Idempotency-Key`:`launch_template` 先查 `(tenant, created_by, key)`(`:1364`),命中且模板一致 → `(existing, False, _replay_launch_meta(...))`。`_replay_launch_meta`(`:1309`)从 run 冻结的 `effective` 重建 `asset`,**不重新解析资产、不重新扣上限**(重放先于上限检查)。所以网络重试不会失败、也不会多建 run(冒烟证据 `idempotent_replay created=False` 即此)。注意重放的 `warnings` 是用**当前**模板重算的(见 §6.6)。 + +### 剧本 C:失败路径(都不创建 run) + +| 场景 | 触发点 | 返回 | +|---|---|---| +| 没带令牌 / 令牌无效、撤销、过期 / 头格式错 | `dependencies.py:111`–`:118` | 401 `unauthenticated` | +| 令牌 scope 不足 / 模板不在白名单 | `dependencies.py:120`–`:127` | 403 `forbidden` | +| `repo_url` 未登记 | `services/eval_templates.py:1102` | 422 `asset_source_unresolved`(details 带 repo_url) | +| commit/ref 在仓库取不到、凭据失效/无效 | `:1242`、`:1260` | 422 `asset_ref_unresolved`(details 带 requested_ref + 子码) | +| 解析出的 commit 与请求不一致 | `:1278` | 422 `candidate_commit_mismatch`(details 带 requested/resolved) | +| 覆盖后选择为空 / 路径不存在 | `:1235` | 422 `asset_selection_empty` / `asset_path_not_found`(复用资产域码) | +| 并发/预算到顶 | `dependencies` → `enforce_launch_caps`(`service_tokens.py:379`、`:400`) | 429 `service_token_limit_exceeded`(details 带 cap/active 或 cap/spent) | + +所有失败都发生在 `consume_preparation` 之前或之中,冒烟与单测都用 `_run_count(...) == 0` 反证“没有半创建的 run”(如 `tests/backend/test_eval_templates.py:1683`)。 + +### 剧本 D:控制台一键启动(回归路径) + +无 `Authorization`、无 `asset_override`:会话鉴权 → 管理员角色 → `asset_override=None` → 走**未改动的** `_resolve_template_assets`(`:1391`)→ `launch_meta = {"asset": None, "warnings": []}` → 202 里**没有** `asset`/`warnings`(`api/eval_templates.py:315`,有值才加键)。run 的 `asset_override_json` 保持 `{}`。但 status/results 仍会回显 `asset`(任何冻结过快照的 run 都回显,见 §6.7)——这是**增量字段**,控制台不读它,旧 run 也不因缺失该字段改变其它行为。 + +--- + +## §4 导读地图 + +| 层 | 文件 | 状态 | 说明 | +|---|---|---|---| +| 流程 | `.agents/flow/issues/m10-candidate-launch-override.md` | ✅ | 通读;验收 7 条是 §5 的来源 | +| 流程 | `.agents/flow/issues/m10-candidate-launch-override.en.md` | ✅ | 仅 diff(与中文镜像一致) | +| 流程 | `.agents/flow/issues/m10-candidate-launch-override.i18n.yaml` | ✅ | 仅 diff(两个 blob 重录) | +| 计划 | `plans/…/openapi-change.md`、`docs-5-14-revision.md` | ✅ | 已在 main,作为契约对照 | +| 鉴权 | `backend/app/api/dependencies.py` | ✅ | 全文 | +| 身份 | `backend/app/models/identity.py` | ✅ | 变更区(142–183) | +| 身份 | `backend/app/models/__init__.py` | ✅ | 仅 diff(导出) | +| 身份 | `backend/migrations/versions/0035_service_token.py` | ✅ | 全文 | +| 身份 | `backend/app/services/service_tokens.py` | ✅ | 全文 | +| 身份 | `backend/app/api/service_tokens.py` | ✅ | 全文 | +| 装配 | `backend/app/main.py` | ✅ | 变更区(74–98) | +| 覆盖 | `backend/app/api/eval_templates.py` | ✅ | 变更区 + launch 全函数(90–134、262–320) | +| 覆盖 | `backend/app/services/eval_templates.py` | ✅ | 新增段 1018–1470 逐行读;旧路径 919–948 对照读 | +| 覆盖 | `backend/app/models/evaluation.py` | ✅ | 变更区(155–168) | +| 回显 | `backend/app/api/results.py` | ✅ | 变更区(176–317)+ `_run_or_404` | +| 文档 | `docs/design/eval-platform-architecture.md` | ✅ | diff + 命中段逐行 | +| 文档 | `docs/design/eval-platform-architecture.en.md` | ✅ | diff(逐句对照中文) | +| 文档 | `docs/design/eval-platform-architecture.i18n.yaml` | ✅ | 仅 diff | +| 文档 | `scripts/doc-budgets.manifest.json` | ✅ | 仅 diff | +| 测试 | `tests/backend/test_service_tokens.py` | ✅ | 全文(1–589) | +| 测试 | `tests/backend/test_eval_templates.py` | ✅/◻ | 新增段(1129–1991)与 helper 全读;**既有 1–1128 行未逐行重读**(标 ◻) | +| 测试 | `tests/backend/test_operations.py` | ✅ | 仅 diff(revision 断言) | +| 测试 | `tests/backend/test_deployment_migration.py` | ✅ | 仅 diff(revision 断言) | + +--- + +## §5 人工验收清单 + +来源:issue #429「验收」7 条 + PR 描述「本地验证/冒烟/门禁」。`[x]` 已有本次实测证据;`[ ]` 仍需人工拍板或复跑。 + +- [x] 带覆盖 launch 一个真实候选 commit:202 的 `asset.resolved_commit` 逐字等于请求 commit,status/results 回显一致。证据:冒烟 `resolved_commit_equals_request / status_asset_echo`(commit `a82a590…`);单测 `tests/backend/test_eval_templates.py:1328`。 +- [x] golden 注入证明:候选改一个 `SKILL.md`,快照 manifest 中该文件 digest 与 commit 中对应 blob 一致。证据:单测 `test_eval_templates.py:1686`(`sha256(SKILL_CONTENT)` 对齐 manifest,再与 fake tree/blob 对照)。 +- [x] commit 权威:同时给 ref 与 commit 按 commit 解析、ref 原样回显;仅给不可解析 commit → 422 `asset_ref_unresolved` 且不创建 run。证据:单测 `:1476`(断言 provider 只被问了 commit)、`:1573`;冒烟 `unresolvable_commit_422`。 +- [x] 跨仓注入:未登记的 `repo_url` → 422 `asset_source_unresolved`;登记后同一请求成功。证据:单测 `:1540`;冒烟 `unregistered_repo_422`。 +- [x] 覆盖后选择为空 / 路径不存在 → 422 对应码,不建 run。证据:单测 `:1626`。 +- [x] 不带 `asset_override` 的控制台一键启动行为不变:202 无 `asset` 块,权限/幂等/校验语义不变。证据:单测 `:1412`、`:1455`、`:473`;控制台截图与原型比对(模板列表/详情、评测详情)。 +- [x] 服务令牌:无令牌 → 401(按实现口径,issue 原文写 403,见 §6.2)、错 scope / 模板不在白名单 → 403、`created_by=svc:`、幂等重放同一 run。证据:单测 `:1767`、`:1802`;冒烟 `wrong_scope_403`、`anonymous_read_401`、`revoked_token_401`、`machine_actor_recorded`;`facts.json` 中评测详情“创建人 `svc:hev-smoke-1681755553`”。 +- [x] `npm test`、`verify:flow`、`lint:docs`、`verify:docs` 与 PR CI 通过。证据:CI `docs`、`flow-offline`、`flow-online`、`backend (pytest + migration)` 全绿(`gh pr checks 431`);本地套件按 PR 描述为绿,本次未复跑。 +- [ ] 429(并发/预算上限)在真实环境的返回体与文档一致性:单测覆盖(`test_eval_templates.py:1864`、`:1896`),但冒烟未走 429 分支,且常驻文档尚未记录该码(见 §6.3)。 +- [ ] PR body 的“冒烟测试/门禁”两个「待补」段落回填:证据已存在,但描述未更新(见 §6.3)。 + +--- + +## §6 讨论点 + +> 每条固定五段:**位置 / 现象 / 问题 / 预判 / 结论**。结论栏留空给拍板;预判只是初判,不是定论。 + +### 6.1 `repo_url` 精确匹配在多资产源时可能选错源 + +- **位置**:`backend/app/services/eval_templates.py:1093`–`:1108`;`backend/app/models/agent_asset.py:36`、`:62`。 +- **现象**:覆盖给了 `repo_url` 时,按 `(tenant_id, repo_url)` 查 `AgentAssetSource`,`order_by(created_at, id)` 取**第一条**。而 `AgentAssetSource` 只保证 `name` 唯一,`repo_url` 没有唯一约束——同一仓库可以登记多个源(不同凭据、不同 `scan_paths`、不同 `default_ref`)。 +- **问题**:模板本身明明绑定了某个源(含它的凭据与扫描路径),但覆盖只传了同一个 `repo_url` 时,平台会静默改用“最早登记的那个源”,而不是模板自己的源。对“同一 repo 两个源、凭据权限不同”的现场,解析结果可能不是调用方预期的那个;且没有任何提示。 +- **预判**:不是本 PR 的功能缺陷(issue 只要求“按 repo_url 匹配已登记源”),但属于可低成本收紧的健壮性问题。建议:若 `template.asset_source_id` 对应的源 `repo_url` 与请求相等,**优先用它**;否则再退回“最早登记”。或者退一步,在 `_override_source` 命中多条时把 `source_id` 记进审计(现在 `effective.source_id` 已经有,但调用方看不到)。 +- **结论**:(留空) + +### 6.2 缺凭据返回 401 而非 issue 验收写的 403 + +- **位置**:`backend/app/api/dependencies.py:46`–`:57`、`:117`–`:127`;issue 验收原文 `.agents/flow/issues/m10-candidate-launch-override.md:175`(“无令牌/错 scope/模板不在白名单 → 403”)。 +- **现象**:实现把“没令牌、令牌格式错、无效、撤销、过期”统一映射为 **401 `unauthenticated`**;“scope 不足、模板不在白名单”映射为 **403 `forbidden`**。冒烟证据也是 `anonymous_read_401` + `wrong_scope_403`。 +- **问题**:与 issue 验收文字不一致。若只看验收单,会以为“无令牌 = 403”。好处是 401/403 的语义分工更清晰(认证失败 vs 授权不足),也与平台既有会话语义一致(`require_session` 一直返回 401)。 +- **预判**:**保留 401**(改实现会把“认证 vs 授权”混回一锅),但应当把 issue 验收文字改成与新口径一致,并在常驻文档补一句“401 表示未认证或令牌无效/已撤销/已过期”。这属于“文字对齐”,不是代码修复。 +- **结论**:(留空) + +### 6.3 调用方契约缺口:429 / 401 与 OpenAPI 的 bearer scheme 没进文档 + +- **位置**:`docs/design/eval-platform-architecture.md:197`、`:207`;`backend/app/services/service_tokens.py:90`–`:92`;`plans/2026-11-25-m10-candidate-launch-override/openapi-change.md:169`–`:186`;`backend/app/api/dependencies.py:137`–`:168`。 +- **现象**:三段现象叠加—— + 1. 常驻文档写了“并发/预算上限”,但没写**超限返回 429 `service_token_limit_exceeded`**(grep 全文无 `429`),也没写 launch/status/results 新增的 **401**; + 2. 设计稿 `openapi-change.md` 的 `LaunchErrorCodes` 枚举同样只有 403/404/409/422,没有 429(该稿定稿早于“上限用 429”的实现决定); + 3. 实现用普通 `Depends` 而不是 `Security`/`HTTPBearer`,`securitySchemes.serviceToken`(计划 §1 明确要求)不会出现在运行时生成的 OpenAPI 里。 +- **问题**:HE 是外部集成方,读的是文档与 OpenAPI。429 是它必须处理的**可重试/需退避**信号,401 是它刷新令牌的信号;这两个码没写进文档,会让适配器把“限额”当未知错误。Bearer scheme 缺失则让“生成的 OpenAPI”无法表达机器鉴权。 +- **预判**:429/401 段落在本 PR 或紧跟的一个 `docs:` 小 PR 补(§5.14 加两句即可,预算已到 13800,建议压缩别处或按门禁登记);`openapi-change.md` 是历史设计稿,可不回改,但要接受“archive 与实现有偏差”。OpenAPI securityScheme 属“要不要对外暴露机器鉴权”的产品决定,本 PR 不做也说得过去,建议登记为后续项。**PR body 的“冒烟/门禁待补”也建议一并回填**——证据已在仓库外留档,描述里还是“待补”,会让合并记录与事实脱节。 +- **结论**:(留空) + +### 6.4 上限是 best-effort;令牌名一旦撤销就永久占用 + +- **位置**:`backend/app/services/service_tokens.py:343`–`:408`(上限)、`:240`–`:247`(名称查重不过滤 revoked);`backend/app/services/eval_templates.py:1379`。 +- **现象**:并发/预算在“计数 → 建 run”之间没有锁(docstring `:352` 明说 best-effort);预算只统计已结算到 `budget_spent_cny` 的 run,所以同一毫秒的多个 launch 可以一起越过上限。另一方面,`create_token` 按 `(tenant, name)` 查重时**包含已撤销的行**,撤销 `he-bot` 后不能再建同名令牌,只能换名——换名会让 `created_by` 从 `svc:he-bot` 变成 `svc:he-bot-2`,历史 run 的归属在审计视角下“断代”。 +- **问题**:两个都是“可接受但要知道”的取舍:上限是准入守卫而不是账单;名称是令牌的**永久标识**(好处是 `svc:` 不会被复用冒充,坏处是运维得接受改名)。 +- **预判**:上限语义按 docstring 接受,但建议在常驻文档补一句“上限为 best-effort 准入守卫,不是硬配额;预算按已结算花费统计”。名称永久占用也值得写成运维事实(或提供“允许复用已撤销名称”的显式开关,由管理员确认——但那会削弱审计可读性,不建议首期做)。另外 `enforce_launch_caps` 排在 `template.enabled` 之前(`:1379` vs `:1381`),所以“上限已满 + 模板停用”会先返回 429 而不是 409;无实害,但如果希望错误优先级稳定,可把 enabled 校验提前。 +- **结论**:(留空) + +### 6.5 空覆盖的边界:`{}` 等于“没意图”,`{"asset_paths": []}` 等于“就要空选择” + +- **位置**:`backend/app/services/eval_templates.py:1349`–`:1355`、`:1217`–`:1222`;测试 `tests/backend/test_eval_templates.py:1455`、`:1647`。 +- **现象**:`launch_template` 用 `not any(value is not None ...)` 判断“空覆盖”,所以 `{}`、`{"ref": null}`、`{"commit": null, "repo_url": null}` 都退化为控制台语义(不要求模板绑源、202 无 `asset`);但 `{"asset_paths": []}` 因为值是 `[]`(非 None)被当作**有意图**,整字段替换成空列表,最终 422 `asset_selection_empty`。 +- **问题**:两种“看起来都像空请求”的输入行为完全不同。这是“整字段替换”语义的正确推论(显式空列表就是“什么都不要”),但对 HE 的适配器是个坑:序列化时把 `None` 写成 `[]` 或把 `[]` 写成 `None`,结果一个是“继承模板”一个是“422”。 +- **预判**:实现正确,不建议改语义;建议在文档/接口示例里给一组对照(`{}` = 一键启动、`{"asset_paths": []}` = 选择为空被拒),并在 HE 适配器里对“未设置”统一省略字段而不是发 `null`/`[]`。 +- **结论**:(留空) + +### 6.6 重放的 `warnings` 用“当前模板”重算,不是冻结值 + +- **位置**:`backend/app/services/eval_templates.py:1309`–`:1318`、`:1298`–`:1306`。 +- **现象**:重放时不重新解析资产(正确),但 `warnings` 由 `_override_warnings(template)` 按**此刻**的模板 `self_evolution_enabled` 重新生成。于是:启动时模板未开上报(202 无 warnings)→ 模板后来开启上报 → 同一个幂等键重放,202 突然多出 `warnings`。 +- **问题**:严格幂等通常意味着“同一请求同一响应”。这里多出的只是一条**非阻断提示**,不会改变 run 或执行语义;但确实让“重放响应逐字节一致”不再成立。 +- **预判**:无实害,可接受。若以后要求严格幂等,可把 `warnings` 一并冻结进 `asset_override_json`(或 run 的另一个 JSON 列),重放直接回放。当前不建议为它扩列。 +- **结论**:(留空) + +### 6.7 `asset` 回显范围扩大到“所有冻结过快照的 run”(additive) + +- **位置**:`backend/app/services/eval_templates.py:1146`–`:1168`;`backend/app/api/results.py:246`–`:254`、`:308`–`:311`;测试 `tests/backend/test_eval_templates.py:1437`。 +- **现象**:`run_asset_identity` 只看 `run.asset_snapshot_id`,不区分“覆盖启动 / 控制台模板启动 / run 级资产评测”。因此控制台一键启动的 run、以及既有的 `POST /api/v1/evaluations` 资产评测,status/results 也会多出 `asset`(而它们的 202 没有 `asset`,这是有意的)。 +- **问题**:字段是**纯增量**,控制台不读,旧 run 也不因此改变其它行为。唯一“不一致”是:控制台 run 的 202 没有 `asset`,但 status 有——这不是同一契约内的矛盾(202 只对带覆盖的调用方承诺 `asset`),但对读代码的人是理解成本。 +- **预判**:接受。建议在文档 §5.14 把“回显范围”写成一句话(任何冻结过资产快照的 run 都会回显),省得后人以为只有覆盖启动才有。 +- **结论**:(留空) + +### 6.8 控制台文案仍写“启动请求不能覆盖固定字段”(`web/` 不在 scope) + +- **位置**:`web/src/pages/EvalTemplateDetailPage.tsx:439`、`web/src/components/TemplateApiModal.tsx:111`;`facts.json` 的模板详情文本里能看到同一句在页面上真实渲染。 +- **现象**:机器启动已经可以覆盖资产选择,但控制台“边界”说明还写“启动请求不能覆盖固定字段”。对控制台用户而言这句话仍基本成立(UI 没有覆盖入口),对读文档/API 的机器调用者则是过期信息。 +- **问题**:issue #429 的 scope 明确不含 `web/`,所以本 PR 不改是对的;但这条文案迟早要改,否则“文档说能覆盖、控制台说不能覆盖”会同时存在。 +- **预判**:开一个 `web` 小 PR 改成“控制台一键启动不可覆盖;机器触发(服务令牌)可携带候选覆盖”,并顺带在“接口”弹窗里补 `/api/v1/service-tokens` 的存在。不建议塞进本 PR(会破坏 scope 门禁的一致性)。 +- **结论**:(留空) + +--- + +## §7 分流表 + +| 发现 | 定性 | 去处 | 状态 | +|---|---|---|---| +| 401(未认证/令牌无效)取代 issue 验收写的 403 | 文字对齐,非 bug | 更新 issue #429 验收措辞 + 文档补 401 一句 | ✅ 已决(2026-11-25,PR 描述已按 401 口径声明,issue 文字待同步) | +| 429 `service_token_limit_exceeded` 未进常驻文档与设计稿枚举 | 文档缺口 | 本 PR 或紧跟的 `docs:` 小 PR 补 §5.14 两句 | ◻ 待办(见 §6.3) | +| 上限 best-effort、预算按已结算花费 | 已知取舍(docstring 已写) | 常驻文档补一句语义说明,理由留在本检视文档 | ✅ 已决(2026-11-25,接受) | +| 撤销后令牌名不可复用(`svc:` 标签断代) | 可接受的运维事实 | 文档/运维说明;不建重复 Note | ◻ 待拍板(见 §6.4) | +| `repo_url` 多条匹配时静默取最早源 | 健壮性可收紧 | 讨论后再定是否开 follow-up issue;若改,只动 `_override_source` | ◻ 待拍板(见 §6.1) | +| 重放 `warnings` 按当前模板重算 | 无实害的幂等瑕疵 | 本检视文档留档;将来重构时冻结 | ✅ 已决(2026-11-25,接受) | +| `asset` 回显覆盖所有冻结 run | 纯增量、有意为之 | 文档补“回显范围”一句 | ✅ 已决(2026-11-25,接受) | +| OpenAPI 未声明 `serviceToken` securityScheme | 契约完整性问题 | 后续 issue(若 HE 依赖生成式 schema) | ◻ 待拍板(见 §6.3) | +| 控制台“不能覆盖固定字段”文案过期 | 文档/UI 债 | 单独 `web` 小 PR(`web/` 不在 #429 scope) | ◻ 待办(见 §6.8) | +| 冒烟证据在仓库外、未入库;PR body 仍写“待补” | 过程记录 | 回填 PR 描述;证据不入库 | ◻ 待办(见 §6.3) | + +--- + +## §8 链接 + +- PR:[#431](https://github.com/Shadow-Azure/ai-eval-platform/pull/431) +- Issue / owning 工作文件:[#429](https://github.com/Shadow-Azure/ai-eval-platform/issues/429) → [`.agents/flow/issues/m10-candidate-launch-override.md`](../../.agents/flow/issues/m10-candidate-launch-override.md) +- 实现计划:[`openapi-change.md`](openapi-change.md)(schema diff)、[`docs-5-14-revision.md`](docs-5-14-revision.md)(文档替换稿) +- 常驻文档:[`docs/design/eval-platform-architecture.md`](../../docs/design/eval-platform-architecture.md) §5.14(第 185/197/207/211 行)与表 2(第 231/233 行) +- 既有覆盖管道证据:`backend/app/api/evaluations.py`、`backend/app/services/agent_assets.py:2001` +- 相关 issue:#378(评测模板)、#382(模板级自进化上报)、#410(模板来源展示) +- 冒烟证据(仓库外,未入库):`.tmp-t/smoke-429-evidence.json`;截图与事实:`reports/2026-11-25/m10-429-machine-trigger/`(`01`–`06` PNG、`facts.json`、`smoke-report.html`) +- 后续 PR:控制台文案修正(`web/`,待开) + +--- + +## §9 文件级代码分析 + +### 9.1 `backend/app/models/identity.py`(M +47) + +- **职责**:新增 `service_token` ORM 模型与 scope 常量;变更形态 M(在 `AuthSession` 之后插入)。 +- **关键依赖**:SQLAlchemy 2.x `Mapped`/`mapped_column`——仓库统一的数据层写法;`json_type()`(`backend/app/models/base.py:32`)让 JSON 列在 PostgreSQL 用 JSONB、测试用 SQLite 时用 JSON,这是本仓库“同 schema 双库”的惯用缝。 +- **变更代码块**: + + ```python + # 旧:AuthSession 之后直接是 AuditLog + # 新: + SERVICE_TOKEN_SCOPES = ("eval:launch", "eval:read") + + class ServiceToken(Base, TimestampMixin): + __tablename__ = "service_token" + token_hash: Mapped[str] = mapped_column(String(64), unique=True, nullable=False) + template_allowlist_json: Mapped[list] = mapped_column(json_type(), default=list, ...) + max_concurrent_runs: Mapped[int | None] = mapped_column(Integer, nullable=True) + daily_budget_cny: Mapped[Decimal | None] = mapped_column(Numeric(12, 6), nullable=True) + ... + __table_args__ = ( + UniqueConstraint("tenant_id", "name", name="uq_service_token_tenant_name"), + UniqueConstraint("tenant_id", "id", name="uq_service_token_tenant_id_id"), + Index("ix_service_token_tenant_revoked_created", "tenant_id", "revoked_at", "created_at"), + ) + ``` + + 为什么这么写:`(tenant_id, id)` 复合唯一是仓库里所有租户内实体的既有惯例(供跨表复合外键引用);`(tenant_id, revoked_at, created_at)` 索引服务于“列出租户令牌(按撤销状态与创建时间)”的查询形状;金额用 `Numeric(12,6)` 与 `eval_run.budget_spent_cny` 同精度,避免比较时出现浮点尾差。 +- **实现思路**(≤3 行):令牌只是“带权限范围的主体档案”,密钥材料刻意不在模型里留明文位;上限与白名单作为列而不是独立表,省掉一次 join。 +- **检视发现**:无功能发现。唯一可提的是 `scope` 常量放在 `identity.py` 而不是 `services/service_tokens.py`,导致 `dependencies.py` 与 service 都从 `models` 导入业务常量——分层上略怪,但避免了 models ←→ services 的循环导入,可接受。 + +### 9.2 `backend/app/models/__init__.py`(M +4) + +- **职责**:导出 `ServiceToken`、`SERVICE_TOKEN_SCOPES`(`:42`、`:47`、`:96`–`:97`);变更形态 M,纯增量。 +- **关键依赖**:无第三方;仓库用 `__init__` 做统一模型入口,所有服务层 `from ..models import X`。 +- **变更代码块**:`from .identity import (` 里加两行 + `__all__` 加两行。为什么这么写:保持“模型从包根导入”的既有约定,服务层不用深入子模块。 +- **实现思路**:无逻辑。 +- **检视发现**:无。 + +### 9.3 `backend/migrations/versions/0035_service_token.py`(A +102) + +- **职责**:建 `service_token` 表、加 `eval_run` 两个 JSON 列、同步 downgrade;变更形态 A。 +- **关键依赖**:Alembic + SQLAlchemy core;`sa.JSON().with_variant(postgresql.JSONB, "postgresql")`(`:29`)复刻 `json_type()` 的双库行为——迁移不能 import 应用代码,所以这份 variant 是必要的重复。 +- **变更代码块**: + + ```python + # 新:upgrade() + op.create_table("service_token", ..., + sa.ForeignKeyConstraint(["tenant_id"], ["tenant.id"], name="fk_service_token_tenant_id_tenant", ondelete="RESTRICT"), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("tenant_id", "name", name="uq_service_token_tenant_name"), + sa.UniqueConstraint("tenant_id", "id", name="uq_service_token_tenant_id_id"), + sa.UniqueConstraint("token_hash", name="uq_service_token_token_hash")) + op.create_index("ix_service_token_tenant_id", ...) + op.create_index("ix_service_token_tenant_revoked_created", ...) + op.add_column("eval_run", sa.Column("asset_override_json", _JSON, server_default=sa.text("'{}'"), nullable=False)) + op.add_column("eval_run", sa.Column("evolution_lineage_json", _JSON, server_default=sa.text("'{}'"), nullable=False)) + ``` + + 为什么这么写:`server_default '{}'` 让**存量 run 不需要回填**(老行为 = 未覆盖),这正是“additive”的数据侧保证;`ondelete=RESTRICT` 与其它租户表一致,租户删除先被拦住。 +- **实现思路**:一张表 + 两列 + 四个索引/约束,没有数据迁移脚本——设计上不留历史包袱。 +- **检视发现**:迁移把唯一约束显式命名为 `uq_service_token_token_hash`、`uq_service_token_tenant_name` 等;`token_hash` 在模型侧是 `unique=True`,`Base.metadata` 的命名约定(`backend/app/models/base.py:11`–`:17`)恰好生成同名的 `uq_service_token_token_hash`,`ix_service_token_tenant_id` 也与 `tenant_fk()` 的 `index=True` 自动命名一致——两侧语义与名字都对得上,没有漂移。`downgrade` 只删列删表,不回填数据——符合“0035 之前的 run 本来就没有这两个键”的事实。 + +### 9.4 `backend/app/services/service_tokens.py`(A +433) + +- **职责**:机器身份的唯一业务实现:创建/列出/撤销/认证/上限/视图/主体标签;变更形态 A。 +- **关键依赖**:`hashlib`(SHA-256,标准库)+ `secrets.token_urlsafe`(CSPRNG 生成明文);SQLAlchemy `func.count` / `func.coalesce` 做上限统计。没有引入任何新第三方包——这点值得强调:令牌系统最怕“为了 JWT 引入 PyJWT”,这里用最朴素的高熵随机串 + 哈希,攻击面最小。 +- **变更代码块**: + + ```python + # 创建(:217) + plaintext = TOKEN_PREFIX + secrets.token_urlsafe(TOKEN_BYTES) # 47 字符 + token = ServiceToken(..., token_hash=_hash_token(plaintext), ...) + session.add(token); session.commit() # IntegrityError → 409 + # 认证(:308) + token = session.scalar(select(ServiceToken).where(token_hash == _hash_token(raw), tenant_id == DEFAULT)) + if token is None or not _is_active(token): return None + if previous is None or (current - previous).total_seconds() >= 60: token.last_used_at = current; session.commit() + # 上限(:343) + active = count(EvalRun where created_by == actor and status not in TERMINAL) + spent = coalesce(sum(EvalRun.budget_spent_cny) where created_by == actor and created_at >= 今天) + ``` + + 为什么这么写:①明文只在一处产生、只在一个响应返回,任何持久化路径都拿不到它;②`last_used_at` 60 秒节流是为了“状态轮询不要把读请求变成写请求”;③上限按 `created_by` 而不是另建关联表,是因为 `svc:` 已经是既有审计字段,复用它避免新表与 run 的 FK 迁移。 +- **实现思路**(≤3 行):用高熵 bearer 串做“机器口令”,库内只留哈希;授权信息(scope/白名单/上限)全部挂在令牌行上,鉴权一次查询就能拿到全部判定材料。 +- **检视发现**:见 §6.4(best-effort 上限、名称永久占用)。另:`enforce_launch_caps` 的预算窗口起点用 `current.replace(hour=0,...)`,而 `current` 已经是 UTC(`_now`),与文档“UTC 自然日”一致;但 run 的 `created_at` 若是无时区列(SQLite 返回 naive),比较仍能工作(同库同值),无实害。 + +### 9.5 `backend/app/api/service_tokens.py`(A +93) + +- **职责**:三个管理员端点:`POST` 创建(201,明文一次)、`GET` 列表(掩码)、`DELETE` 撤销(204);变更形态 A。 +- **关键依赖**:FastAPI(`APIRouter`/`Depends`/`HTTPException`)+ Pydantic v2(`Field(min_length=1)`、`Literal["eval:launch","eval:read"]`)。Pydantic 的 `Literal` 让 scope 在**HTTP 层**就被拒(422 通用错误体),而 service 层还有一份同义校验兜内部调用——两层都保留是刻意的(`:29` vs `service_tokens.py:140`)。 +- **变更代码块**: + + ```python + @router.post("/api/v1/service-tokens", status_code=201) + def create_service_token(payload, session, context: AuthContext = Depends(require_admin)): + token, plaintext = token_service.create_token(session, payload.model_dump(), created_by=context.user.email) + return {"status": "ok", "service_token": token_service.token_view(token), "token": plaintext} + ``` + + 为什么这么写:三个路由全部 `require_admin`(管理员会话),不暴露给服务令牌——**令牌不能自己造令牌**,避免权限自我增殖;`DELETE` 返回 `Response(status_code=204)` 而不是带 body,保持“撤销即空响应”的语义。 +- **实现思路**:API 层只做“校验 → 调服务 → 包装错误信封”,无业务判断。 +- **检视发现**:无。`_http_error`(`:36`)与模板路由的同名函数逻辑重复(都做 `details.fields` 折叠),但两处分属不同模块、错误基类不同,抽象收益不大,接受。 + +### 9.6 `backend/app/api/dependencies.py`(M +103) + +- **职责**:新增 `Actor` 与 `require_session_or_service(scope)`;变更形态 M(模块 docstring 扩写 + 追加两个函数与两个错误小工厂)。 +- **关键依赖**:FastAPI `Depends`/`HTTPException`/`Request`;`identity.resolve_session`(会话解析)与 `token_service.authenticate`(令牌解析)是本文件的两个下游。 +- **变更代码块**(旧 vs 新): + + ```python + # 旧:只有三条会话依赖 + require_session / optional_session / require_admin + + # 新:+ Actor + 令牌分支 + def dependency(request, session, settings) -> Actor: + header = request.headers.get("Authorization") + if header is not None: # 有头就只认令牌 + return _service_actor(request, session, header, scope=scope) + context = _resolve(request, session, settings) + if context is None: raise _unauthenticated() + request.state.auth = context # 会话分支保留既有 state 行为 + if scope == SCOPE_EVAL_LAUNCH and context.role != identity.ROLE_ADMIN: + raise _forbidden("当前账号没有写入权限。") + return Actor(label=context.user.email, ...) + ``` + + 为什么这么写:①“有头就只走令牌”避免“坏令牌被 Cookie 兜住”;②`request.state.auth` 只在会话分支设置——全仓 grep `state.auth` 只有本文件的 3 处写入、没有读取方,所以服务分支不设它没有副作用;③闭包工厂让路由端只写 `Depends(require_session_or_service("eval:read"))`,scope 与路由一一对应,不靠路由自己记得校验。 +- **实现思路**(≤3 行):把“谁在调用”收敛成一个不可变 `Actor`,两种凭据各自解析后汇入同一主体;授权判定(scope/白名单/角色)就在依赖里一次做完,业务代码不再关心凭据形态。 +- **检视发现**:见 §6.2(401/403 口径)、§6.3(未声明 OpenAPI securityScheme)。另有一个小观察:`SCOPE_EVAL_LAUNCH/READ` 常量(`:31`–`:32`)与 `SERVICE_TOKEN_SCOPES` 重复定义,serve 的是“依赖层不直接依赖 service 模块常量”的可读性,可接受。 + +### 9.7 `backend/app/main.py`(M +11) + +- **职责**:挂载 `service_tokens_router`;把 `eval_templates` 与 `results` 从“路由级 `require_session`”改为逐路由声明;变更形态 M。 +- **关键依赖**:FastAPI `include_router(dependencies=...)` 的语义——路由级依赖会对该路由**所有**端点生效,因此“某几个端点要放宽/换鉴权”时必须拆掉路由级依赖,逐个声明。 +- **变更代码块**: + + ```python + # 旧 + app.include_router(eval_templates_router, dependencies=[Depends(require_session)]) + app.include_router(results_router, dependencies=[Depends(require_session)]) + # 新 + app.include_router(eval_templates_router) # 每个路由自己声明 + app.include_router(service_tokens_router) # 每路由 require_admin + app.include_router(results_router) # status/results 允 eval:read + ``` + + 为什么这么写:`results` 里 compare/case-tests 必须保持“仅会话”,status/results 要允许 `eval:read` 令牌;`eval_templates` 里 launch 要允许令牌而 CRUD 保持会话/管理员。路由级依赖无法表达这种“同 router 不同鉴权”,只能拆。 +- **实现思路**:把鉴权从“router 级默认值”下沉到“路由显式声明”,并用一条专门的回归测试兜住“拆完没漏”。 +- **检视发现**:无——这是本次最容易出错的一处,但results 的四个路由 + 模板的六个路由的显式依赖都能在文件里逐条对上(`backend/app/api/eval_templates.py:164/197/215/235/256/271`、`backend/app/api/results.py:181/261/320/340`),且 `test_eval_templates.py:1503` 覆盖 12 条路径的匿名 401。 + +### 9.8 `backend/app/api/eval_templates.py`(M +64) + +- **职责**:请求模型加 `asset_override`/`lineage`;launch 换 `Actor` 依赖、把覆盖与血缘透传给服务层、按需回显 `asset`/`warnings`;变更形态 M。 +- **关键依赖**:Pydantic v2 的 `model_dump(exclude_unset=True)`——这是“字段缺省 vs 显式 null”能区分的关键;`Field(pattern="^[0-9a-f]{40}$")` 在 HTTP 层先挡非法 commit。 +- **变更代码块**: + + ```python + # 新:请求模型 + class AssetOverrideRequest(BaseModel): + repo_url: str | None = Field(default=None, max_length=500) + ref: str | None = Field(default=None, max_length=200) + commit: str | None = Field(default=None, pattern="^[0-9a-f]{40}$") + asset_paths: list[str] | None = None + asset_types: dict[str, str] | None = None + + # 新:launch 主体 + asset_override = payload.asset_override.model_dump(exclude_unset=True) if payload.asset_override else None + run, created, launch_meta = template_service.launch_template(..., created_by=context.label, + asset_override=asset_override, lineage=lineage, service_token=context.service_token) + ... + if launch_meta.get("asset") is not None: body["asset"] = launch_meta["asset"] + if launch_meta.get("warnings"): body["warnings"] = launch_meta["warnings"] + ``` + + 为什么这么写:①`exclude_unset=True` 让“只传了 `commit`”和“显式把 `ref` 置 null”在服务层可区分,从而支持“整字段替换 + 缺省继承”;②`created_by=context.label` 把控制台邮箱与 `svc:` 统一成一种主体标签,幂等键自然按主体隔离;③回显靠 `launch_meta` 而不是重新查一次 run,保证 202 与内部冻结值一致。 +- **实现思路**(≤3 行):API 层只做“模型 → dict → 透传 → 包装响应”的搬运营,不写解析逻辑;回显字段“有才加键”,让控制台响应保持逐字节兼容。 +- **检视发现**:`_http_error` 的类型注解扩成 `TemplateError | ServiceTokenError`(`:122`),两者都有 `status/code/details/field`,鸭子类型成立;若将来新增第三种错误基类,记得同步这里(无实害,仅备注)。 + +### 9.9 `backend/app/services/eval_templates.py`(M +399) + +- **职责**:新增覆盖解析/断言/回显/重放;`launch_template` 改成“幂等 → 上限 → 启用 → 上报目标 → 资产解析(分叉)→ prepare/create → 冻结”,返回三元组;变更形态 M。 +- **关键依赖**:`asset_service.resolve_assets`(既有资产解析与快照冻结)、`preparation_service.build_preparation/consume_preparation`(既有 prepare/create)、`GitClientError`(Git 访问错误)。本文件没有新第三方依赖,全部是“复用既有件 + 错误映射”。 +- **变更代码块**(旧 vs 新,择要): + + ```python + # 旧:单一资产来源 + 二元返回 + asset_snapshot_id = _resolve_template_assets(session, template, created_by=..., settings=...) + ... + return run, created + + # 新:分叉 + 三元返回 + if asset_override is None: + asset_snapshot_id = _resolve_template_assets(...) # 老路径一行未改 + else: + asset_snapshot_id, launch_asset, effective = _resolve_override_assets(...) + warnings = _override_warnings(template) + ... + run.asset_override_json = {"requested": dict(asset_override), "effective": effective} + run.evolution_lineage_json = dict(lineage) + return run, created, {"asset": launch_asset, "warnings": warnings} + ``` + + ```python + # 新:commit 断言(:1278) + if commit and snapshot.resolved_commit != commit: + raise CandidateCommitMismatch(..., details={"requested": commit, "resolved": snapshot.resolved_commit}) + ``` + + 为什么这么写:①分叉而不是改写老函数,把“控制台路径零变化”变成代码结构上的事实,而不是测试上的承诺;②断言放在 `build_preparation` 之前,保证“不一致就什么都不留”;③`requested`/`effective` 双份冻结,同时服务“审计”和“回显”两个目的,避免读侧重新推导。 +- **实现思路**(≤3 行):把“覆盖”建模成一次**来源重定向**——先换源、再按 commit/ref 解析出快照、断言 commit、然后把快照交给既有的 prepare/create;平台不新增执行路径,只换输入。 +- **检视发现**:见 §6.1(多源歧义)、§6.5(空覆盖边界)、§6.6(重放 warnings)。另有两处小的一致性观察:①`_override_source`(`:1188`)在 commit 格式校验(`:1189`)之前执行,所以“坏 commit + 未登记 repo”会先报 `asset_source_unresolved`——错误优先级略反直觉但无实害;②`_override_types`(`:1063`)会静默丢弃非字符串键值,而 `_override_paths` 遇到非法项会 422——同样是“服务层兜底”,两者严格程度不一致(HTTP 层 Pydantic 已挡,实际不可达),可不动。 + +### 9.10 `backend/app/models/evaluation.py`(M +10) + +- **职责**:`eval_run` 增加 `asset_override_json`、`evolution_lineage_json` 两个非空 JSON 列(默认 `{}`);变更形态 M。 +- **关键依赖**:`json_type()` 双库 variant;`TimestampMixin` 提供的 `created_at/updated_at`。 +- **变更代码块**:两个 `mapped_column(json_type(), default=dict, nullable=False, server_default="{}")`。为什么这么写:老 run 无需回填;`{}` 是“未覆盖/无血缘”的零值,读侧 `(x or {})` 判空即可。 +- **实现思路**:把“覆盖请求 + 归一化身份 + 血缘”冻结进 run 本身,而不是靠关联表——一次查询即可回显,且天然随 run 生命周期不可变。 +- **检视发现**:无。注意 `asset_override_json` 同时存**原始请求**与 `effective`,字段名说的是 override,实际语义是“覆盖审计包”;命名略窄但注释已说明(`:159`–`:162`)。 + +### 9.11 `backend/app/api/results.py`(M +27) + +- **职责**:status/results 换成 `require_session_or_service("eval:read")`;两个读模型增量回显 `asset`(results 另回显 `lineage`);compare/case-tests 显式保留 `require_session`;变更形态 M。 +- **关键依赖**:`run_asset_identity`(服务层)、`Actor`(依赖层);`_run_or_404` 保证租户内查找。 +- **变更代码块**: + + ```python + # 旧 + def get_eval_results(run_id: str, session: Session = Depends(get_session)): ... + # 新 + def get_eval_results(run_id, session=Depends(get_session), + _actor: Actor = Depends(require_session_or_service("eval:read"))): ... + ... + asset = run_asset_identity(session, run) + if asset is not None: response["asset"] = asset + lineage = run.evolution_lineage_json or {} + if lineage: response["lineage"] = lineage + ``` + + 为什么这么写:①`_actor` 前导下划线表明“这个端点只需要鉴权、不需要主体信息”,可读性上区分于 launch;②“有才加键”保证旧 run 的响应形状不变(严格增量);③compare/case-tests 保留 `require_session` 是刻意的——它们返回完整用例内容,面比 status/results 大,不在 #429 的开放范围内。 +- **实现思路**(≤3 行):读模型的增量字段全部走同一个 `run_asset_identity`,status 与 results 不会出现两种回显口径。 +- **检视发现**:无功能发现。每次轮询多一次 `session.get(AgentAssetSnapshot)`(主键查,代价可忽略);若将来 status 的 QPS 很高,可考虑把 identity 冗余进 run 行,但目前不需要。 + +### 9.12 `docs/design/eval-platform-architecture.md`(M +6/−5) + +- **职责**:§5.14 三处改写(覆盖语义、鉴权句、错误码/回显句)+ 末段补上报提示 + 表 2 两行(eval_run 追加字段、新增 service_token 行);变更形态 M。 +- **关键依赖**:仓库文档门禁(`lint:docs`/`verify:docs` 查双语镜像、围栏、预算);`scripts/doc-budgets.manifest.json` 登记词数上限。 +- **变更代码块**:以第 185 行为例——旧句“模板启动不接受配置覆盖……”改为“控制台一键启动不接受配置覆盖……;机器触发(服务令牌)可携带可选 `asset_override`……commit 为权威身份且必须断言……`ref` 仅作展示审计”。为什么这么写:把“谁能覆盖”说清楚,避免读成“模板彻底不能覆盖”;把 commit 断言与 422 拒绝写成硬约束,和实现一一对应。 +- **实现思路**:只加“现状事实”,不复述设计理由(理由留在 issue/本检视文档),符合 `docs/AGENTS.md` 的“文档写现状”。 +- **检视发现**:见 §6.3(429/401 未写)、§6.7(回显范围未写一句)。另:第 207 行的错误码句沿用“403 表示当前账号没有启动权限”,未区分“令牌 scope/白名单不足也是 403”,读者可能把 403 只当角色问题——可在 429/401 补句时一并润色。 + +### 9.13 `docs/design/eval-platform-architecture.en.md`(M +6/−5) + +- **职责**:英文侧逐句镜像;变更形态 M。 +- **关键依赖**:无;受 `.i18n.yaml` blob 配对与 `verify:docs` 的“围栏/表格/列表镜像”约束。 +- **变更代码块**:`Console one-click launches accept no configuration overrides...`(第 185 行)、`All three reuse "console session or service token" authentication...`(第 197 行)、`An override launch echoes asset...`(第 207 行)、`Machine triggers with asset_override inherit...`(第 211 行)、表 2 的 `service_token` 行(第 233 行)。 +- **实现思路**:与中文同构,长句一行到底(仓库文档风格)。 +- **检视发现**:本次按 diff 逐句对照中文,未发现语义漂移;`verify:docs` 的 CI 绿也说明镜像结构成立。 + +### 9.14 `docs/design/eval-platform-architecture.i18n.yaml`(M +2/−2) + +- **职责**:重录中英两侧 blob hash;变更形态 M。 +- **关键依赖**:`npm run record:i18n -- ` 生成。 +- **变更代码块**:两个 40 位 hash 更新(`b5b6d4e…` / `d9310e6…`)。为什么必须改:配对门禁以 blob 为准,漏录会让 `verify:docs` 判“两侧不一致”。 +- **实现思路**:纯记录。 +- **检视发现**:无;CI `docs` 绿说明重录生效。 + +### 9.15 `scripts/doc-budgets.manifest.json`(M +2/−2) + +- **职责**:架构文档预算 13500 → 13800,并在 `//` 说明里登记理由(M10 #429 的机器触发契约 + 表 2 新行);变更形态 M。 +- **关键依赖**:仓库文档预算门禁读取该文件。 +- **变更代码块**:`"docs/design/eval-platform-architecture.md": 13800` + `//` 串尾追加一段带编号与增量的说明。为什么这么写:仓库规则要求“提高上限须在 PR 中说明”,而说明只写增量事实(13500 → 13800),不重复文档内容。 +- **实现思路**:预算随事实增长,理由串本身就是账本。 +- **检视发现**:无。若 §6.3 决定再补 429/401 两句,需留意是否顶到 13800——届时优先压缩旧句而不是继续提预算。 + +### 9.16 `.agents/flow/issues/m10-candidate-launch-override.md`(M +5/−1) + +- **职责**:`status: ready → in-progress`;`scope` 补 4 个实际改动路径(`models/__init__.py`、两个 revision 断言测试、`doc-budgets.manifest.json`);变更形态 M。 +- **关键依赖**:`verify-flow` 的机读围栏(`yaml flow`)与 scope 校验——PR 改动路径必须落在 scope 内,否则 `verify-flow --diff origin/main` 红。 +- **变更代码块**:scope 列表追加四行 + status 一行。为什么这么写:scope 是“允许改动的白名单”,实现过程中发现需要动 `doc-budgets` 与版本断言,就必须把白名单同步扩进去,而不是绕过门禁。 +- **实现思路**:流程文件与代码同 PR 演进,门禁才是可信的。 +- **检视发现**:scope 扩容属于“事后补白名单”,严格说应在动那些文件之前先改 scope;但本 PR 是同一个提交集内自洽(`1e7ae4b` 专门做这件事),且 CI flow 门禁绿,可接受。另:scope 里 `tests/backend/test_results.py` 最终没改,属“允许但未用”,无影响。 + +### 9.17 `.agents/flow/issues/m10-candidate-launch-override.en.md`(M +5/−1) + +- **职责**:英文镜像(同 status/scope);变更形态 M。 +- **关键依赖**:中英围栏必须逐字节一致(README §机读围栏),scope 列表因此两侧同步。 +- **变更代码块**:与中文同构的 5 行。 +- **实现思路**:镜像维护。 +- **检视发现**:diff 对照无漂移。 + +### 9.18 `.agents/flow/issues/m10-candidate-launch-override.i18n.yaml`(M +2/−2) + +- **职责**:重录 flow 三件套的配对 hash;变更形态 M。 +- **关键依赖**:`record:i18n`。 +- **变更代码块**:两个 hash 更新。为什么:改了 md 必须重录,否则 `verify:flow` 判配对失败。 +- **实现思路**:纯记录。 +- **检视发现**:无。 + +### 9.19 `tests/backend/test_service_tokens.py`(A +590) + +- **职责**:令牌域单测 + 依赖域单测 + 上限单测;变更形态 A。 +- **关键依赖**:`fastapi.testclient.TestClient`(真跑 ASGI,不 mock 路由)、`starlette.requests.Request`(手工构造请求直接调依赖,省掉为每个 scope 组合造路由)、SQLite 会话 fixture。`_request()`(`:80`)用最小 ASGI scope 手工拼请求是这里的巧劲:依赖是纯函数,不必为它铺 HTTP。 +- **变更代码块**(测试即规格,择要): + + ```python + # 哈希与一次性明文(:128) + assert response.text.count(plaintext) == 1 + assert stored.token_hash == hashlib.sha256(plaintext.encode()).hexdigest() + # 依赖的“坏头不回退 Cookie”(:438) + with pytest.raises(HTTPException): _call_dependency(..., _request(authorization="Basic abc", cookie=cookie)) + assert raised.value.status_code == 401 + # 上限(:527、:555) + run.status = "completed"; session.commit(); assert enforce_launch_caps(...) is None + ``` + + 为什么这么写:把“安全契约”直接写成断言(明文只出现一次、库里只有哈希、坏头必 401、过期/撤销即失效、上限只算自己主体),比文档承诺更可靠。 +- **实现思路**(≤3 行):分四组(创建/撤销/依赖/上限),每组用最小 fixture 构造,避免共享状态;对“不该发生”的分支(如匿名管理、坏 scope)逐个反证。 +- **检视发现**:无遗漏感。唯一未覆盖的是“并发创建同名令牌时 `IntegrityError` → 409”的真实竞态(`:262` 的分支没有被并发测试触发),属可接受的测试成本。 + +### 9.20 `tests/backend/test_eval_templates.py`(M +871) + +- **职责**:新增候选覆盖端到端用例(fake GitHub + StubObjectStore 真跑 `resolve_assets`)、鉴权回归、令牌上限、读回显;变更形态 M(追加在既有文件尾部)。 +- **关键依赖**:`monkeypatch.setattr(agent_assets, "GitHubClient", ...)`(`FakeGitHubClient`,`:1146`)把网络替换成内存仓库;`StubObjectStore` fixture(`:1212`)提供 S3 形状的本地对象存储,让快照/清单真的写一遍。`FakeRepo.resolved_refs`(`:1136`)记录“provider 被问了哪个 ref”,用来证明“commit 权威、ref 从未参与解析”。 +- **变更代码块**: + + ```python + # 旧:只有控制台启动用例 + # 新:候选覆盖主用例(:1328)——202 回显 + run 冻结 + status/results + 重放 + assert replay.json()["asset"] == asset # 重放回显同一身份 + # 失败矩阵(:1540/:1573/:1598/:1626/:1661)——每类错误都断言 _run_count == 0 + # 鉴权回归(:1503)——12 条路径匿名必须 401 + for method, path in protected: assert client.request(method, path, json={}).status_code == 401 + ``` + + 为什么这么写:①用 fake GitHub 而不是打真网,测试可在 CI 离线跑且能注入“解析漂移/凭据失效”;②每个失败用例都反证“没有建 run”,把“失败不留半成品”变成可执行断言;③golden 注入用例(`:1686`)同时校验 manifest sha256 与“同一 commit 的 tree/blob”,证明“注入的内容确实来自该 commit”。 +- **实现思路**(≤3 行):以“202 → run 行 → status → results → 重放”为主轴写端到端;失败路径按错误码分文件块,每条都带 details 断言,便于将来定位契约变更。 +- **检视发现**:`test_launch_asset_override_pins_candidate_commit_and_echoes`(`:1328`)里预置了 `warnings` 不在响应中的断言,配合 `:1728` 的上报模板用例,把“只在覆盖 + 开上报时提示”钉住了。未覆盖:`asset_override.repo_url` 命中多个源时的选择(§6.1 的分支),以及 429 与 `enabled=false` 同时成立时的错误优先级(§6.4)——都属边界,可接受。 + +### 9.21 `tests/backend/test_operations.py`(M +1/−1) + +- **职责**:`database["revision"]` 断言从 `0034_pool_unique_labels` 改为 `0035_service_token`;变更形态 M。 +- **关键依赖**:无。 +- **变更代码块**:一行字符串。 +- **实现思路**:迁移 head 变了就同步运维读模型的断言,避免“部署检查拿旧 head 当预期”。 +- **检视发现**:无。这类“head 版本硬编码”会随每次迁移改动一次,属仓库既有约定。 + +### 9.22 `tests/backend/test_deployment_migration.py`(M +1/−1) + +- **职责**:`alembic_version` 断言同步到 `0035_service_token`;变更形态 M。 +- **关键依赖**:`database_url` fixture 真跑迁移链。 +- **变更代码块**:一行字符串。 +- **实现思路**:与 9.21 同源——迁移 head 是部署契约的一部分。 +- **检视发现**:无;与 0035 的 `down_revision`(`:25`)一致,CI `deployment contract` 绿。 + +--- + +## 检视小结(给拍板用) + +- **功能正确性**:主线(令牌鉴权 + 候选注入 + commit 断言 + 回显 + 幂等)在代码、单测、真实冒烟三层自洽;控制台路径零改动的承诺在结构上成立(老函数未改、响应有值才加键)。 +- **最值得先讨论的三点**:①`repo_url` 多源歧义(§6.1,功能性、可低成本收紧);②401/429 的调用方契约缺口(§6.2+§6.3,直接影响 HE 适配器);③令牌名永久占用与上限 best-effort 的运维语义(§6.4,影响长期运维)。 +- **没有发现必须阻断合并的实现缺陷**;上述均为文档/边界/后续项,建议在合并前至少把 §6.3 的文档补句与 PR 描述回填列入同一批。 From 74c4effada5199a7220cf188b3203991b2b5f41e Mon Sep 17 00:00:00 2001 From: TangZ-L <345187680+TangZ-L@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:20:42 +0800 Subject: [PATCH 7/8] =?UTF-8?q?fix(m10):=20=E6=94=B6=E7=B4=A7=E8=A6=86?= =?UTF-8?q?=E7=9B=96=E6=BA=90=E6=AD=A7=E4=B9=89=E5=B9=B6=E8=A1=A5=E9=BD=90?= =?UTF-8?q?=E9=89=B4=E6=9D=83=E4=B8=8E=E4=B8=8A=E9=99=90=E5=A5=91=E7=BA=A6?= =?UTF-8?q?=E6=96=87=E6=A1=A3=20(#429)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../m10-candidate-launch-override.en.md | 2 +- .../m10-candidate-launch-override.i18n.yaml | 4 +- .../issues/m10-candidate-launch-override.md | 2 +- backend/app/services/eval_templates.py | 38 ++++++++++--- backend/app/services/service_tokens.py | 4 ++ docs/design/eval-platform-architecture.en.md | 4 +- .../eval-platform-architecture.i18n.yaml | 4 +- docs/design/eval-platform-architecture.md | 4 +- .../openapi-change.md | 13 +++-- scripts/doc-budgets.manifest.json | 4 +- tests/backend/test_eval_templates.py | 56 +++++++++++++++++++ 11 files changed, 111 insertions(+), 24 deletions(-) diff --git a/.agents/flow/issues/m10-candidate-launch-override.en.md b/.agents/flow/issues/m10-candidate-launch-override.en.md index 0d5cbf76..20064471 100644 --- a/.agents/flow/issues/m10-candidate-launch-override.en.md +++ b/.agents/flow/issues/m10-candidate-launch-override.en.md @@ -172,7 +172,7 @@ GET /api/v1/eval-runs/{run_id}/results - Cross-repository injection: an unregistered `repo_url` answers 422 `asset_source_unresolved`; after registration the same request succeeds. - Empty selection or a missing path after override: 422 `asset_selection_empty / asset_path_not_found`, and no run is created. - Console one-click launches without `asset_override` behave unchanged: no `asset` block in the response, and permission, idempotency, and validation semantics stay the same. -- Service token: no token, wrong scope, or a template outside the allowlist → 403; audit records `created_by=svc:`; an idempotent replay returns the same run; `npm test`, `npm run verify:flow`, `npm run lint:docs`, `npm run verify:docs`, and PR CI pass. +- Service token: no valid credential (no token, invalid, revoked, or expired) → 401 `unauthenticated`; an insufficient scope or a template outside the allowlist → 403 `forbidden`; reaching the concurrency or daily-budget cap → 429 `service_token_limit_exceeded`; audit records `created_by=svc:`; an idempotent replay returns the same run; `npm test`, `npm run verify:flow`, `npm run lint:docs`, `npm run verify:docs`, and PR CI pass. ## Non-goals diff --git a/.agents/flow/issues/m10-candidate-launch-override.i18n.yaml b/.agents/flow/issues/m10-candidate-launch-override.i18n.yaml index a7e822b4..b82f104c 100644 --- a/.agents/flow/issues/m10-candidate-launch-override.i18n.yaml +++ b/.agents/flow/issues/m10-candidate-launch-override.i18n.yaml @@ -1,5 +1,5 @@ # 双语配对一致性记录(docs/i18n/README.md):两侧在最后一次确认一致状态下的 # git blob hash。两种语言同等权威;编辑任一侧后带上另一侧,然后重录: # pnpm run record:i18n -- .agents/flow/issues/m10-candidate-launch-override.md -m10-candidate-launch-override.md: cf52aa9ceff0fcbea8254179f77b7caadac15ebf -m10-candidate-launch-override.en.md: 0d5cbf761a09a97dc2d245ab64094d2573ea37c7 +m10-candidate-launch-override.md: 05a694ce6dfe42d38b60a8fc9a47121d7a1b23d1 +m10-candidate-launch-override.en.md: 20064471002bebb0e0458da82c4c60eca63376bc diff --git a/.agents/flow/issues/m10-candidate-launch-override.md b/.agents/flow/issues/m10-candidate-launch-override.md index cf52aa9c..05a694ce 100644 --- a/.agents/flow/issues/m10-candidate-launch-override.md +++ b/.agents/flow/issues/m10-candidate-launch-override.md @@ -172,7 +172,7 @@ GET /api/v1/eval-runs/{run_id}/results - 跨仓注入:`repo_url` 未登记时 422 `asset_source_unresolved`;登记后同一请求成功。 - 覆盖后选择为空或路径不存在:422 `asset_selection_empty / asset_path_not_found`,不创建 run。 - 不带 `asset_override` 的控制台一键启动行为不变:响应无 `asset` 块,权限、幂等与校验语义不变。 -- 服务令牌:无令牌/错 scope/模板不在白名单 → 403;审计记录 `created_by=svc:`;幂等重放返回同一 run;`npm test`、`npm run verify:flow`、`npm run lint:docs`、`npm run verify:docs` 与 PR CI 通过。 +- 服务令牌:无有效凭据(无令牌/无效/已撤销/已过期)→ 401 `unauthenticated`;scope 不足或模板不在白名单 → 403 `forbidden`;达到并发或当日预算上限 → 429 `service_token_limit_exceeded`;审计记录 `created_by=svc:`;幂等重放返回同一 run;`npm test`、`npm run verify:flow`、`npm run lint:docs`、`npm run verify:docs` 与 PR CI 通过。 ## 非目标 diff --git a/backend/app/services/eval_templates.py b/backend/app/services/eval_templates.py index d629f45d..afcccff3 100644 --- a/backend/app/services/eval_templates.py +++ b/backend/app/services/eval_templates.py @@ -1091,21 +1091,43 @@ def _override_source( override, "repo_url", max_length=ASSET_OVERRIDE_MAX_URL_LENGTH ) if repo_url: - source = session.scalar( - select(AgentAssetSource) - .where( - AgentAssetSource.tenant_id == str(DEFAULT_TENANT_ID), - AgentAssetSource.repo_url == repo_url, + matches = list( + session.scalars( + select(AgentAssetSource) + .where( + AgentAssetSource.tenant_id == str(DEFAULT_TENANT_ID), + AgentAssetSource.repo_url == repo_url, + ) + .order_by(AgentAssetSource.created_at, AgentAssetSource.id) ) - .order_by(AgentAssetSource.created_at, AgentAssetSource.id) ) - if source is None: + if not matches: raise AssetSourceUnresolved( f"资产覆盖的仓库未登记为资产源:{repo_url}", field=ASSET_OVERRIDE_FIELD, details={"field": ASSET_OVERRIDE_FIELD, "repo_url": repo_url}, ) - return source + if len(matches) > 1: + # ``repo_url`` has no uniqueness constraint: the same repository may + # be registered twice with different credentials or scan paths. + # Prefer the template's own source when it is one of the matches; + # otherwise refuse to guess instead of silently using the oldest. + for candidate in matches: + if candidate.id == template.asset_source_id: + return candidate + raise AssetSourceUnresolved( + f"资产覆盖的仓库登记了多个资产源,无法确定使用哪一个:{repo_url}", + field=ASSET_OVERRIDE_FIELD, + details={ + "field": ASSET_OVERRIDE_FIELD, + "repo_url": repo_url, + "candidates": [ + {"id": candidate.id, "name": candidate.name} + for candidate in matches + ], + }, + ) + return matches[0] if not template.asset_source_id: raise AssetSourceUnresolved( "资产覆盖未指定 repo_url,且模板未绑定资产源", diff --git a/backend/app/services/service_tokens.py b/backend/app/services/service_tokens.py index fa56f948..3cda77be 100644 --- a/backend/app/services/service_tokens.py +++ b/backend/app/services/service_tokens.py @@ -225,6 +225,10 @@ def create_token( The plaintext is the only copy that will ever exist outside the caller's hands: it is not stored, not logged and not derivable from ``token_hash``. + + Names are unique per tenant and are not reused after revocation. That keeps + ``svc:`` a stable audit and idempotency identity: rotation creates a + new name, so old and new machine actors never share `created_by`. """ if not isinstance(data, dict): diff --git a/docs/design/eval-platform-architecture.en.md b/docs/design/eval-platform-architecture.en.md index d9310e6f..75616cdb 100644 --- a/docs/design/eval-platform-architecture.en.md +++ b/docs/design/eval-platform-architecture.en.md @@ -194,7 +194,7 @@ The template list uses the console management read API `GET /api/v1/eval-templat A template's launch history reuses the evaluation list read API instead of adding a dedicated execution API: `GET /api/v1/evaluations` accepts an optional `template_id` filter combined with `status`, `limit`, and `offset`, returning `items`, `total`, `limit`, and `offset` ordered by launch time descending and a 404 when the template is unknown; template history defaults to a limit of 10 and includes a `status_counts` map. The history action on each template row and the launch-history action on the template detail page both read this filtered page, defaulting to 10 rows with 10/20/50 options and filtering by the evaluation status enum with counts (zero included), and items reuse the evaluation summary and link to the evaluation detail; the embedded `recent_runs` preview still keeps only the latest five. The filter is read-only and does not change the execution chain. Each evaluation-list summary also carries the resolved source-template `template` (id, name, version, and enabled state), so the list labels template-launched runs with "from template · template name" linked to the template detail while custom runs show no origin line. -Table 12 lists the three stable APIs. All three reuse "console session or service token" authentication: launching requires administrator permission or a service token with `eval:launch`, while status and results are read-only for signed-in users or a service token with `eval:read`; administrators create, list, and revoke service tokens at `/api/v1/service-tokens`, with scopes, a template allowlist, and concurrency/budget caps, the plaintext is returned exactly once in the creation response and only its hash is stored, and machine launches record `created_by` as `svc:` in the existing audit and idempotency constraints. +Table 12 lists the three stable APIs. All three reuse "console session or service token" authentication: launching requires administrator permission or a service token with `eval:launch`, while status and results are read-only for signed-in users or a service token with `eval:read`; administrators create, list, and revoke service tokens at `/api/v1/service-tokens`, with scopes, a template allowlist, and concurrency/budget caps, the plaintext is returned exactly once in the creation response and only its hash is stored, and machine launches record `created_by` as `svc:` in the existing audit and idempotency constraints. A missing or invalid credential answers 401, an insufficient scope or a template outside the allowlist answers 403, and reaching the concurrency or daily-budget cap answers 429; the caps are best-effort admission guards, the budget counts the token's already-settled spend per UTC day, and a token name is unique per tenant and never reused after revocation. Table 12 The three execution APIs of an evaluation template @@ -204,7 +204,7 @@ Table 12 The three execution APIs of an evaluation template | Query status | GET /api/v1/eval-runs/{run_id}/status | none | `run_id`, `template_id`, `status`, `terminal`, progress counts, start and finish times, and resolve rate | | Query results | GET /api/v1/eval-runs/{run_id}/results | none | `run_id`, `status`, `is_final`, metric items, and token summary; a running run returns a partial snapshot | -The launch API first verifies that the template exists and is enabled and that its references are still available, then runs the existing prepare/create flow; 404 means the template or evaluation does not exist, 409 means the template is disabled or the idempotency key conflicts, 422 means a reference is invalid or a field is unavailable, and 403 means the current account lacks launch permission. The status API returns `terminal=true` in a terminal state; the results API returns `is_final=false` before the terminal state, so clients can decide whether to keep polling. An override launch echoes `asset` (resolved_commit, asset_snapshot_id, bundle_digest) in the 202 response, status and results echo the same identity for caller-side comparison, and new 422 codes `candidate_commit_mismatch`, `asset_source_unresolved`, and `asset_ref_unresolved` join the reused `asset_selection_empty` and `asset_path_not_found`, none of which create an evaluation. +The launch API first verifies that the template exists and is enabled and that its references are still available, then runs the existing prepare/create flow; 404 means the template or evaluation does not exist, 409 means the template is disabled or the idempotency key conflicts, 422 means a reference is invalid or a field is unavailable, and 403 means the current account lacks launch permission. The status API returns `terminal=true` in a terminal state; the results API returns `is_final=false` before the terminal state, so clients can decide whether to keep polling. Every run with a frozen asset snapshot echoes `asset` (resolved_commit, asset_snapshot_id, requested_ref) from status and results, while an override launch additionally echoes `asset` (including repo_url, requested_commit, and bundle_digest) in its 202 response, and new 422 codes `candidate_commit_mismatch`, `asset_source_unresolved`, and `asset_ref_unresolved` join the reused `asset_selection_empty` and `asset_path_not_found`, none of which create an evaluation. A template launch does not change the scheduling or execution chain: the server simply turns the fixed selection into a normal prepare and create call, and the subsequent sharding, runners, scoring, traces, and result aggregation are identical to a custom launch. A template therefore cannot bypass capacity admission, budget, image preflight, or permission checks; failures happen before a run is created and never leave a half-created task. diff --git a/docs/design/eval-platform-architecture.i18n.yaml b/docs/design/eval-platform-architecture.i18n.yaml index 70136223..8cceccdc 100644 --- a/docs/design/eval-platform-architecture.i18n.yaml +++ b/docs/design/eval-platform-architecture.i18n.yaml @@ -1,5 +1,5 @@ # 双语配对一致性记录(docs/i18n/README.md):两侧在最后一次确认一致状态下的 # git blob hash。两种语言同等权威;编辑任一侧后带上另一侧,然后重录: # pnpm run record:i18n -- docs/design/eval-platform-architecture.md -eval-platform-architecture.md: b5b6d4ed28aab44b84e3db04b9001722495e6b5f -eval-platform-architecture.en.md: d9310e6f41a693a406911e23a19369750979ba83 +eval-platform-architecture.md: 5dfc5623d28cd5c724616badf1db75a98282f1f1 +eval-platform-architecture.en.md: 75616cdbd5aab043b7c95c89de1858dd473c118d diff --git a/docs/design/eval-platform-architecture.md b/docs/design/eval-platform-architecture.md index b5b6d4ed..5dfc5623 100644 --- a/docs/design/eval-platform-architecture.md +++ b/docs/design/eval-platform-architecture.md @@ -194,7 +194,7 @@ Skill、Command 与 Subagent 统一归入可配置的 Agent 资产源。资产 模板的启动历史复用评测列表读接口,不新增专用执行接口:`GET /api/v1/evaluations` 接受可选 `template_id` 过滤,与 `status`、`limit`、`offset` 组合,按启动时间倒序返回 `items`、`total`、`limit` 与 `offset`;模板不存在时返回 404,模板历史未显式传 `limit` 时默认 10,并附带 `status_counts` 计数映射。模板列表每行的“历史”和模板详情页的“启动历史”都通过该过滤分页读取,默认每页 10 条并支持 10/20/50 切换,状态筛选沿用评测状态枚举并显示计数(0 也保留),条目复用评测摘要并链接到评测详情;模板详情内嵌的 `recent_runs` 仍只保留最近 5 条预览。该过滤只读,不改变执行链路。评测列表的摘要同时返回解析后的来源模板 `template`(id、模板名、版本与启用状态),列表行据此对模板启动的评测显示“来自模板 · 模板名”并链接到模板详情,自定义发起的评测不显示来源行。 -三个稳定接口见表 12。三个接口复用「控制台会话或服务令牌」鉴权:启动需要管理员权限或持 `eval:launch` 的服务令牌,状态与结果对已登录用户或持 `eval:read` 的服务令牌只读;服务令牌由管理员在 `/api/v1/service-tokens` 创建、列表与撤销,支持 scope、模板白名单与并发/预算上限,明文仅在创建响应返回一次,库内只存哈希,机器启动的 `created_by` 落 `svc:<名称>` 并进入既有审计与幂等约束。 +三个稳定接口见表 12。三个接口复用「控制台会话或服务令牌」鉴权:启动需要管理员权限或持 `eval:launch` 的服务令牌,状态与结果对已登录用户或持 `eval:read` 的服务令牌只读;服务令牌由管理员在 `/api/v1/service-tokens` 创建、列表与撤销,支持 scope、模板白名单与并发/预算上限,明文仅在创建响应返回一次,库内只存哈希,机器启动的 `created_by` 落 `svc:<名称>` 并进入既有审计与幂等约束。无有效凭据返回 401,scope 或白名单不足返回 403,达到并发或当日预算上限返回 429;上限是尽力而为的准入守卫,预算按该令牌已结算花费、UTC 自然日计算,令牌名在租户内唯一且撤销后不复用。 表 12 评测模板的三个执行接口 @@ -204,7 +204,7 @@ Skill、Command 与 Subagent 统一归入可配置的 Agent 资产源。资产 | 查询状态 | GET /api/v1/eval-runs/{run_id}/status | 无 | `run_id`、`template_id`、`status`、`terminal`、进度计数、起止时间与解决率 | | 查询结果 | GET /api/v1/eval-runs/{run_id}/results | 无 | `run_id`、`status`、`is_final`、指标项与 token 摘要;运行中返回部分快照 | -启动接口先校验模板存在且启用、引用对象仍可用,再走既有的 prepare/create 流程;返回 404 表示模板或评测不存在,409 表示模板停用或幂等键冲突,422 表示引用对象失效或字段不可用,403 表示当前账号没有启动权限。状态接口在终态返回 `terminal=true`;结果接口在终态前返回 `is_final=false`,客户端据此决定是否继续轮询。带覆盖的启动在 202 响应回显 `asset`(resolved_commit、asset_snapshot_id、bundle_digest),status 与 results 同样回显该身份供调用方比对,新增 422 错误码 `candidate_commit_mismatch`、`asset_source_unresolved`、`asset_ref_unresolved`(`asset_selection_empty` 与 `asset_path_not_found` 复用既有码),任一命中即不创建评测。 +启动接口先校验模板存在且启用、引用对象仍可用,再走既有的 prepare/create 流程;返回 404 表示模板或评测不存在,409 表示模板停用或幂等键冲突,422 表示引用对象失效或字段不可用,403 表示当前账号没有启动权限。状态接口在终态返回 `terminal=true`;结果接口在终态前返回 `is_final=false`,客户端据此决定是否继续轮询。任何冻结过资产快照的 run 都在 status 与 results 回显 `asset`(resolved_commit、asset_snapshot_id、requested_ref);带覆盖的启动在 202 响应也回显 `asset`(另含 repo_url、requested_commit、bundle_digest)供调用方比对,新增 422 错误码 `candidate_commit_mismatch`、`asset_source_unresolved`、`asset_ref_unresolved`(`asset_selection_empty` 与 `asset_path_not_found` 复用既有码),任一命中即不创建评测。 模板启动不改变调度与执行链路:它只是在服务端把固定选择转换为一次普通的 prepare 与 create 调用,后续分片、Runner、评分、轨迹与结果聚合与自定义发起完全一致。因此模板不会绕过容量准入、预算、镜像预检或权限校验;失败发生在创建运行之前,不会留下半创建的任务。 diff --git a/plans/2026-11-25-m10-candidate-launch-override/openapi-change.md b/plans/2026-11-25-m10-candidate-launch-override/openapi-change.md index 2eaa8bd8..2a680b11 100644 --- a/plans/2026-11-25-m10-candidate-launch-override/openapi-change.md +++ b/plans/2026-11-25-m10-candidate-launch-override/openapi-change.md @@ -183,16 +183,20 @@ components: - asset_path_not_found # 422(既有码,launch 场景复用) - image_not_ready # 409(既有) - forbidden # 403(既有;服务令牌 scope/白名单不足) + - unauthenticated # 401(既有;无凭据或令牌无效/撤销/过期) + - service_token_limit_exceeded # 429(新增;并发或当日预算上限) ``` -新增三个码的触发条件: +新增三个 422 码的触发条件: | code | HTTP | 触发条件 | |---|---|---| | `candidate_commit_mismatch` | 422 | 解析到的 `resolved_commit` 与请求 `commit` 不一致(ref 漂移、对象被替换)。绝不静默评测。 | -| `asset_source_unresolved` | 422 | `asset_override.repo_url` 在同租户已登记资产源中无精确 `repo_url` 匹配,凭据不可确定。 | +| `asset_source_unresolved` | 422 | `asset_override.repo_url` 在同租户已登记资产源中无精确 `repo_url` 匹配,或同仓登记了多个源且无法确定用哪一个(模板自身的源优先),凭据不可确定。 | | `asset_ref_unresolved` | 422 | commit/ref 在资产源仓库不可解析(仓库不可达、凭据失效、对象不存在)。 | +鉴权与上限补充:launch 的「管理员会话或服务令牌」统一按 401(无有效凭据)与 403(scope/白名单不足)区分;服务令牌的并发/当日预算上限为尽力而为的准入守卫(预算按该令牌已结算的运行花费、UTC 自然日),达到上限返回 429 `service_token_limit_exceeded`。该 429 码属于服务令牌扩展,不改变无覆盖控制台启动的既有错误面。 + 带 `details`:`{ "field": "asset_override", "requested": ..., "resolved": ... }`,便于 HE 定位。 ## 3. `GET /api/v1/eval-runs/{run_id}/status`(响应扩展) @@ -272,6 +276,7 @@ paths: ## 6. 兼容性说明 - 全部为增量:不删字段、不改既有字段语义、不改既有错误码含义;旧客户端(控制台)零感知。 -- `asset` 块只对「模板启动且解析过资产」的 run 输出;合成评测与旧 run 不输出(字段可空或省略,实现 PR 定稿)。 -- 幂等键唯一约束仍是 `(tenant_id, created_by, idempotency_key)`;服务令牌主体 `svc:` 与真人会话天然隔离。 +- launch 202 的 `asset` 块只在带 `asset_override`(或重放了这样的 run)时输出,控制台一键启动的响应逐字节不变;status/results 的 `asset` 对「解析并冻结过资产快照」的 run 输出(含既有模板启动与 run 级资产评测),属于纯增量回显。 +- 无覆盖控制台启动不经过服务令牌上限检查,不会出现 401/429 的新错误面;401/403 的区分只影响带凭据的机器调用。 +- 幂等键唯一约束仍是 `(tenant_id, created_by, idempotency_key)`;服务令牌主体 `svc:` 与真人会话天然隔离。服务令牌名称在租户内唯一且撤销后不复用,保证 `svc:` 审计标签不会指向另一个主体。 - 平台不给 verdict/策略字段(D4);HE 依据 `results` 的指标项与 `status` 计数自行换算裁决输入。 diff --git a/scripts/doc-budgets.manifest.json b/scripts/doc-budgets.manifest.json index 7b65892d..763643dc 100644 --- a/scripts/doc-budgets.manifest.json +++ b/scripts/doc-budgets.manifest.json @@ -1,13 +1,13 @@ { "//": "常驻文档词数上限。超限时先搬层或压缩;提高上限须在 PR 中说明。", - "// docs/design/eval-platform-architecture.md": "M1-02 architecture scope adds resource capability validation plus Git-backed Skill/Command/Subagent asset sources, editable refs, immutable commit snapshots, and runtime materialization; M10 adds the evaluation-template preset, one-click launch and three execution APIs (5.14 plus data model and flow references; 11500 -> 12800); M8 #382 adds the template-level self-evolution reporting contract to 5.14 and the eval_template row (12800 -> 13000); the template launch-history entry adds the evaluation-list template_id filter and paginated history modal to 5.14 (13000 -> 13200); M8 #398 adds save-time image-digest validation and launch-blocker guidance to 5.14 (13200 -> 13350); M10 #416 adds the disabled-only template deletion rule and run-history retention to 5.14 (13350 -> 13500); M10 #429 adds the machine-trigger `asset_override` candidate-pinning contract and the service-token launch/read scopes to 5.14 plus the service_token row in table 2 (13500 -> 13800).", + "// docs/design/eval-platform-architecture.md": "M1-02 architecture scope adds resource capability validation plus Git-backed Skill/Command/Subagent asset sources, editable refs, immutable commit snapshots, and runtime materialization; M10 adds the evaluation-template preset, one-click launch and three execution APIs (5.14 plus data model and flow references; 11500 -> 12800); M8 #382 adds the template-level self-evolution reporting contract to 5.14 and the eval_template row (12800 -> 13000); the template launch-history entry adds the evaluation-list template_id filter and paginated history modal to 5.14 (13000 -> 13200); M8 #398 adds save-time image-digest validation and launch-blocker guidance to 5.14 (13200 -> 13350); M10 #416 adds the disabled-only template deletion rule and run-history retention to 5.14 (13350 -> 13500); M10 #429 adds the machine-trigger `asset_override` candidate-pinning contract and the service-token launch/read scopes to 5.14 plus the service_token row in table 2 (13500 -> 13800), and the review follow-up records the 401/403/429 response mapping, best-effort caps, asset-echo range, and token-name reuse in 5.14 (13800 -> 13900).", "// docs/architecture.md": "M3-06 adds the administrator operations-status surface to the current component map and a short access/telemetry note; M4-04 adds the Aliyun spot provisioner + ephemeral JIT runner current-fact paragraph (800 -> 950); M5-02 adds the model-credentials console current-fact section (950 -> 1100); M5-01 adds the Agent asset source/snapshot + runtime injection paragraph (1100 -> 1200); M5-08 adds the production runner callback entry, pool-label dispatch and creation-verification provisioning facts (1200 -> 1350); M6-01 adds the native trace capture and multi-file manifest current-fact section (1350 -> 1550); M5-11 adds the permanent runner-tarball proxy fact with private OSS and heartbeat-token auth (1550 -> 1600); M5-12 adds the content-addressed scripts bundle, proxy and checkout fallback (1600 -> 1750); M5-15 adds the upload wizard, bounded validation subprocess, persisted report and commit-only immutable version (1750 -> 1950); M6-03 adds the versioned Claude Code parser evidence chain, deduplicated usage, root fragments and degradation facts (1950 -> 2150); M6-04 adds the attempt-scoped query, pagination and audited raw-content access facts (2150 -> 2250); M8-14 adds the GitHub egress proxy current-fact section with payload/exec env, allowlist maintenance and verification commands (2250 -> 2550; the deploy derives the proxy address from API_BIND_ADDRESS, 2550 -> 2600); the dynamic egress token, the authenticated public 3129 listener and the GitHub-only deny semantics add the token flow and public-path verification commands (2600 -> 3000); M9 #263 adds the self-evolution reporting current-fact section (launch config, outbox reporting, signed session envelope endpoint; 3000 -> 3150); M8 #273 adds the OSS dataset image tarball distribution current-fact paragraph (3150 -> 3300); M9 #277 adds the case-list main Agent session id current-fact section (3300 -> 3400; the old margin was only 4 words, so compression could not absorb the new fact; later additions should move detail to design 06 first); M8 #290 adds the DinD preparation worker, deterministic-key reuse and the profile/data-disk gate (3400 -> 3700). Page-level detail still stays in design 06 and the module docstrings. M8-43 (#304) adds the dispatch TTL > job > case > agent timeout hierarchy, the dispatch-provided execute job timeout and the SIGTERM partial-trace/terminal-callback facts (3700 -> 3800; page-level details stay in design 06); M8-44 adds the contended-pool scheduling reliability paragraph (3800 -> 3900); M8-47 (#312) adds the image/OSS scripts-bundle preload order, 60-second fetch budget and dispatch-pinned digest facts (3900 -> 4050); M8 #348 adds the prebuilt runner image, runtime auto-upgrade hardening, reboot-required guard and systemd-inhibit facts (4050 -> 4300).", "README.md": 420, "AGENTS.md": 520, "docs/AGENTS.md": 500, "docs/README.md": 520, "docs/architecture.md": 4300, - "docs/design/eval-platform-architecture.md": 13800, + "docs/design/eval-platform-architecture.md": 13900, "docs/development.md": 1160, "docs/i18n/README.md": 550, "docs/i18n/terminology.md": 220, diff --git a/tests/backend/test_eval_templates.py b/tests/backend/test_eval_templates.py index 3adcae95..badc326f 100644 --- a/tests/backend/test_eval_templates.py +++ b/tests/backend/test_eval_templates.py @@ -1570,6 +1570,62 @@ def test_override_repo_url_must_be_a_registered_source( assert run.asset_override_json["effective"]["source_id"] == registered.id +def test_override_prefers_the_template_source_when_repo_url_has_candidates( + client: TestClient, + session: Session, + monkeypatch: pytest.MonkeyPatch, + asset_store: StubObjectStore, +) -> None: + """Same repo_url registered twice: the template's own source wins.""" + + install_fake_github(monkeypatch) + ids = seed_launch(session) + create_asset_source(session, SOURCE_REPO) # older, not bound to the template + bound = create_asset_source(session, SOURCE_REPO) + template = create_template( + client, + ids, + asset_source_id=bound.id, + asset_ref="main", + asset_paths=[SKILL_PATH], + ) + + response = launch_override( + client, + template["id"], + key="multi-source-template", + override={"repo_url": SOURCE_REPO, "commit": CANDIDATE_COMMIT}, + ) + assert response.status_code == 202, response.text + run = session.get(EvalRun, response.json()["run_id"]) + assert run is not None + assert run.asset_override_json["effective"]["source_id"] == bound.id + + +def test_override_rejects_ambiguous_repo_url_without_a_template_source( + client: TestClient, session: Session, monkeypatch: pytest.MonkeyPatch +) -> None: + """Two candidates and no bound source: refuse to guess, never pick silently.""" + + install_fake_github(monkeypatch) + ids = seed_launch(session) + create_asset_source(session, SOURCE_REPO) + create_asset_source(session, SOURCE_REPO) + template = create_template(client, ids) + + response = launch_override( + client, + template["id"], + key="ambiguous-source", + override={"repo_url": SOURCE_REPO, "commit": CANDIDATE_COMMIT}, + ) + assert response.status_code == 422, response.text + error = response.json()["detail"]["error"] + assert error["code"] == "asset_source_unresolved" + assert len(error["details"]["candidates"]) == 2 + assert _run_count(session, template["id"]) == 0 + + def test_override_unresolvable_commit_is_a_ref_error( client: TestClient, session: Session, From 46c6f3342c17501f0b5c27dec3ddb694acefa1c6 Mon Sep 17 00:00:00 2001 From: TangZ-L <345187680+TangZ-L@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:21:25 +0800 Subject: [PATCH 8/8] =?UTF-8?q?docs(m10):=20=E5=9B=9E=E5=A1=AB=20PR=20#431?= =?UTF-8?q?=20=E6=A3=80=E8=A7=86=E6=84=8F=E8=A7=81=E5=A4=84=E7=90=86?= =?UTF-8?q?=E7=BB=93=E6=9E=9C=20(#429)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pr431-review.md | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/plans/2026-11-25-m10-candidate-launch-override/pr431-review.md b/plans/2026-11-25-m10-candidate-launch-override/pr431-review.md index 43e735da..0b748248 100644 --- a/plans/2026-11-25-m10-candidate-launch-override/pr431-review.md +++ b/plans/2026-11-25-m10-candidate-launch-override/pr431-review.md @@ -269,7 +269,7 @@ HE 超时重发同一 `Idempotency-Key`:`launch_template` 先查 `(tenant, cre - **现象**:覆盖给了 `repo_url` 时,按 `(tenant_id, repo_url)` 查 `AgentAssetSource`,`order_by(created_at, id)` 取**第一条**。而 `AgentAssetSource` 只保证 `name` 唯一,`repo_url` 没有唯一约束——同一仓库可以登记多个源(不同凭据、不同 `scan_paths`、不同 `default_ref`)。 - **问题**:模板本身明明绑定了某个源(含它的凭据与扫描路径),但覆盖只传了同一个 `repo_url` 时,平台会静默改用“最早登记的那个源”,而不是模板自己的源。对“同一 repo 两个源、凭据权限不同”的现场,解析结果可能不是调用方预期的那个;且没有任何提示。 - **预判**:不是本 PR 的功能缺陷(issue 只要求“按 repo_url 匹配已登记源”),但属于可低成本收紧的健壮性问题。建议:若 `template.asset_source_id` 对应的源 `repo_url` 与请求相等,**优先用它**;否则再退回“最早登记”。或者退一步,在 `_override_source` 命中多条时把 `source_id` 记进审计(现在 `effective.source_id` 已经有,但调用方看不到)。 -- **结论**:(留空) +- **结论**:2026-11-25 已修:`_override_source` 命中多个源时优先模板自身的源;仍有歧义则 422 `asset_source_unresolved` 并在 `details.candidates` 返回候选,不再静默取最早。新增两条用例(`test_override_prefers_the_template_source_when_repo_url_has_candidates`、`test_override_rejects_ambiguous_repo_url_without_a_template_source`),提交 `74c4eff`。 ### 6.2 缺凭据返回 401 而非 issue 验收写的 403 @@ -277,7 +277,7 @@ HE 超时重发同一 `Idempotency-Key`:`launch_template` 先查 `(tenant, cre - **现象**:实现把“没令牌、令牌格式错、无效、撤销、过期”统一映射为 **401 `unauthenticated`**;“scope 不足、模板不在白名单”映射为 **403 `forbidden`**。冒烟证据也是 `anonymous_read_401` + `wrong_scope_403`。 - **问题**:与 issue 验收文字不一致。若只看验收单,会以为“无令牌 = 403”。好处是 401/403 的语义分工更清晰(认证失败 vs 授权不足),也与平台既有会话语义一致(`require_session` 一直返回 401)。 - **预判**:**保留 401**(改实现会把“认证 vs 授权”混回一锅),但应当把 issue 验收文字改成与新口径一致,并在常驻文档补一句“401 表示未认证或令牌无效/已撤销/已过期”。这属于“文字对齐”,不是代码修复。 -- **结论**:(留空) +- **结论**:2026-11-25 保留 401;issue 验收改为“无有效凭据 → 401;scope/白名单不足 → 403;达到并发/预算上限 → 429”,§5.14 与 `openapi-change.md` 同步,提交 `74c4eff`。 ### 6.3 调用方契约缺口:429 / 401 与 OpenAPI 的 bearer scheme 没进文档 @@ -288,7 +288,7 @@ HE 超时重发同一 `Idempotency-Key`:`launch_template` 先查 `(tenant, cre 3. 实现用普通 `Depends` 而不是 `Security`/`HTTPBearer`,`securitySchemes.serviceToken`(计划 §1 明确要求)不会出现在运行时生成的 OpenAPI 里。 - **问题**:HE 是外部集成方,读的是文档与 OpenAPI。429 是它必须处理的**可重试/需退避**信号,401 是它刷新令牌的信号;这两个码没写进文档,会让适配器把“限额”当未知错误。Bearer scheme 缺失则让“生成的 OpenAPI”无法表达机器鉴权。 - **预判**:429/401 段落在本 PR 或紧跟的一个 `docs:` 小 PR 补(§5.14 加两句即可,预算已到 13800,建议压缩别处或按门禁登记);`openapi-change.md` 是历史设计稿,可不回改,但要接受“archive 与实现有偏差”。OpenAPI securityScheme 属“要不要对外暴露机器鉴权”的产品决定,本 PR 不做也说得过去,建议登记为后续项。**PR body 的“冒烟/门禁待补”也建议一并回填**——证据已在仓库外留档,描述里还是“待补”,会让合并记录与事实脱节。 -- **结论**:(留空) +- **结论**:2026-11-25 已补:§5.14 增加 401/403/429、best-effort、回显范围与令牌名复用;`openapi-change.md` 的枚举与触发条件同步 429/401;issue 验收同步;PR body 已回填冒烟与 CI(截图见 release `m10-429-machine-trigger-evidence-20261125`)。提交 `74c4eff`。`securitySchemes` 仍缺,登记为后续 issue(HE 以文档适配,不依赖生成式 schema)。 ### 6.4 上限是 best-effort;令牌名一旦撤销就永久占用 @@ -296,7 +296,7 @@ HE 超时重发同一 `Idempotency-Key`:`launch_template` 先查 `(tenant, cre - **现象**:并发/预算在“计数 → 建 run”之间没有锁(docstring `:352` 明说 best-effort);预算只统计已结算到 `budget_spent_cny` 的 run,所以同一毫秒的多个 launch 可以一起越过上限。另一方面,`create_token` 按 `(tenant, name)` 查重时**包含已撤销的行**,撤销 `he-bot` 后不能再建同名令牌,只能换名——换名会让 `created_by` 从 `svc:he-bot` 变成 `svc:he-bot-2`,历史 run 的归属在审计视角下“断代”。 - **问题**:两个都是“可接受但要知道”的取舍:上限是准入守卫而不是账单;名称是令牌的**永久标识**(好处是 `svc:` 不会被复用冒充,坏处是运维得接受改名)。 - **预判**:上限语义按 docstring 接受,但建议在常驻文档补一句“上限为 best-effort 准入守卫,不是硬配额;预算按已结算花费统计”。名称永久占用也值得写成运维事实(或提供“允许复用已撤销名称”的显式开关,由管理员确认——但那会削弱审计可读性,不建议首期做)。另外 `enforce_launch_caps` 排在 `template.enabled` 之前(`:1379` vs `:1381`),所以“上限已满 + 模板停用”会先返回 429 而不是 409;无实害,但如果希望错误优先级稳定,可把 enabled 校验提前。 -- **结论**:(留空) +- **结论**:2026-11-25 接受:上限维持 best-effort(预算按已结算花费、UTC 自然日),§5.14 已写明;`create_token` docstring 与 `openapi-change.md` 写明“名称租户内唯一且撤销后不复用,保证 `svc:` 审计稳定”;错误优先级不变(429 先于 409,无实害)。提交 `74c4eff`。 ### 6.5 空覆盖的边界:`{}` 等于“没意图”,`{"asset_paths": []}` 等于“就要空选择” @@ -304,7 +304,7 @@ HE 超时重发同一 `Idempotency-Key`:`launch_template` 先查 `(tenant, cre - **现象**:`launch_template` 用 `not any(value is not None ...)` 判断“空覆盖”,所以 `{}`、`{"ref": null}`、`{"commit": null, "repo_url": null}` 都退化为控制台语义(不要求模板绑源、202 无 `asset`);但 `{"asset_paths": []}` 因为值是 `[]`(非 None)被当作**有意图**,整字段替换成空列表,最终 422 `asset_selection_empty`。 - **问题**:两种“看起来都像空请求”的输入行为完全不同。这是“整字段替换”语义的正确推论(显式空列表就是“什么都不要”),但对 HE 的适配器是个坑:序列化时把 `None` 写成 `[]` 或把 `[]` 写成 `None`,结果一个是“继承模板”一个是“422”。 - **预判**:实现正确,不建议改语义;建议在文档/接口示例里给一组对照(`{}` = 一键启动、`{"asset_paths": []}` = 选择为空被拒),并在 HE 适配器里对“未设置”统一省略字段而不是发 `null`/`[]`。 -- **结论**:(留空) +- **结论**:2026-11-25 接受:语义不变(`{}`/全 null 按无覆盖,显式空列表按整字段替换并 422 `asset_selection_empty`);HE 适配器应省略未设置字段。§5.14 未逐例展开,示例留给 OpenAPI 适配稿。 ### 6.6 重放的 `warnings` 用“当前模板”重算,不是冻结值 @@ -312,7 +312,7 @@ HE 超时重发同一 `Idempotency-Key`:`launch_template` 先查 `(tenant, cre - **现象**:重放时不重新解析资产(正确),但 `warnings` 由 `_override_warnings(template)` 按**此刻**的模板 `self_evolution_enabled` 重新生成。于是:启动时模板未开上报(202 无 warnings)→ 模板后来开启上报 → 同一个幂等键重放,202 突然多出 `warnings`。 - **问题**:严格幂等通常意味着“同一请求同一响应”。这里多出的只是一条**非阻断提示**,不会改变 run 或执行语义;但确实让“重放响应逐字节一致”不再成立。 - **预判**:无实害,可接受。若以后要求严格幂等,可把 `warnings` 一并冻结进 `asset_override_json`(或 run 的另一个 JSON 列),重放直接回放。当前不建议为它扩列。 -- **结论**:(留空) +- **结论**:2026-11-25 接受(无实害):重放提示按当前模板重算,不扩冻结列;已在 §7 留档。 ### 6.7 `asset` 回显范围扩大到“所有冻结过快照的 run”(additive) @@ -320,7 +320,7 @@ HE 超时重发同一 `Idempotency-Key`:`launch_template` 先查 `(tenant, cre - **现象**:`run_asset_identity` 只看 `run.asset_snapshot_id`,不区分“覆盖启动 / 控制台模板启动 / run 级资产评测”。因此控制台一键启动的 run、以及既有的 `POST /api/v1/evaluations` 资产评测,status/results 也会多出 `asset`(而它们的 202 没有 `asset`,这是有意的)。 - **问题**:字段是**纯增量**,控制台不读,旧 run 也不因此改变其它行为。唯一“不一致”是:控制台 run 的 202 没有 `asset`,但 status 有——这不是同一契约内的矛盾(202 只对带覆盖的调用方承诺 `asset`),但对读代码的人是理解成本。 - **预判**:接受。建议在文档 §5.14 把“回显范围”写成一句话(任何冻结过资产快照的 run 都会回显),省得后人以为只有覆盖启动才有。 -- **结论**:(留空) +- **结论**:2026-11-25 接受:§5.14 已写明“任何冻结过资产快照的 run 都在 status 与 results 回显 `asset`”,`openapi-change.md` 兼容性段同步。 ### 6.8 控制台文案仍写“启动请求不能覆盖固定字段”(`web/` 不在 scope) @@ -328,7 +328,7 @@ HE 超时重发同一 `Idempotency-Key`:`launch_template` 先查 `(tenant, cre - **现象**:机器启动已经可以覆盖资产选择,但控制台“边界”说明还写“启动请求不能覆盖固定字段”。对控制台用户而言这句话仍基本成立(UI 没有覆盖入口),对读文档/API 的机器调用者则是过期信息。 - **问题**:issue #429 的 scope 明确不含 `web/`,所以本 PR 不改是对的;但这条文案迟早要改,否则“文档说能覆盖、控制台说不能覆盖”会同时存在。 - **预判**:开一个 `web` 小 PR 改成“控制台一键启动不可覆盖;机器触发(服务令牌)可携带候选覆盖”,并顺带在“接口”弹窗里补 `/api/v1/service-tokens` 的存在。不建议塞进本 PR(会破坏 scope 门禁的一致性)。 -- **结论**:(留空) +- **结论**:2026-11-25 记录为后续 `web` 小 PR;本 PR 不改 `web/`。 --- @@ -336,16 +336,16 @@ HE 超时重发同一 `Idempotency-Key`:`launch_template` 先查 `(tenant, cre | 发现 | 定性 | 去处 | 状态 | |---|---|---|---| -| 401(未认证/令牌无效)取代 issue 验收写的 403 | 文字对齐,非 bug | 更新 issue #429 验收措辞 + 文档补 401 一句 | ✅ 已决(2026-11-25,PR 描述已按 401 口径声明,issue 文字待同步) | -| 429 `service_token_limit_exceeded` 未进常驻文档与设计稿枚举 | 文档缺口 | 本 PR 或紧跟的 `docs:` 小 PR 补 §5.14 两句 | ◻ 待办(见 §6.3) | -| 上限 best-effort、预算按已结算花费 | 已知取舍(docstring 已写) | 常驻文档补一句语义说明,理由留在本检视文档 | ✅ 已决(2026-11-25,接受) | -| 撤销后令牌名不可复用(`svc:` 标签断代) | 可接受的运维事实 | 文档/运维说明;不建重复 Note | ◻ 待拍板(见 §6.4) | -| `repo_url` 多条匹配时静默取最早源 | 健壮性可收紧 | 讨论后再定是否开 follow-up issue;若改,只动 `_override_source` | ◻ 待拍板(见 §6.1) | +| 401(未认证/令牌无效)取代 issue 验收写的 403 | 文字对齐,非 bug | 更新 issue #429 验收措辞 + §5.14/openapi 补 401 一句 | ✅ 已决(2026-11-25,issue 与文档已同步,`74c4eff`) | +| 429 `service_token_limit_exceeded` 未进常驻文档与设计稿枚举 | 文档缺口 | §5.14 与 `openapi-change.md` 补 429/401 | ✅ 已决(2026-11-25,`74c4eff`;预算 13800 → 13900) | +| 上限 best-effort、预算按已结算花费 | 已知取舍(docstring 已写) | 常驻文档补一句语义说明,理由留在本检视文档 | ✅ 已决(2026-11-25,§5.14 已写明,`74c4eff`) | +| 撤销后令牌名不可复用(`svc:` 标签断代) | 可接受的运维事实 | 文档与 `create_token` docstring 写明;不建重复 Note | ✅ 已决(2026-11-25,`74c4eff`) | +| `repo_url` 多条匹配时静默取最早源 | 健壮性收紧 | 优先模板源;仍歧义则 422 返回 candidates | ✅ 已修(2026-11-25,两条用例,`74c4eff`) | | 重放 `warnings` 按当前模板重算 | 无实害的幂等瑕疵 | 本检视文档留档;将来重构时冻结 | ✅ 已决(2026-11-25,接受) | -| `asset` 回显覆盖所有冻结 run | 纯增量、有意为之 | 文档补“回显范围”一句 | ✅ 已决(2026-11-25,接受) | -| OpenAPI 未声明 `serviceToken` securityScheme | 契约完整性问题 | 后续 issue(若 HE 依赖生成式 schema) | ◻ 待拍板(见 §6.3) | -| 控制台“不能覆盖固定字段”文案过期 | 文档/UI 债 | 单独 `web` 小 PR(`web/` 不在 #429 scope) | ◻ 待办(见 §6.8) | -| 冒烟证据在仓库外、未入库;PR body 仍写“待补” | 过程记录 | 回填 PR 描述;证据不入库 | ◻ 待办(见 §6.3) | +| `asset` 回显覆盖所有冻结 run | 纯增量、有意为之 | §5.14 与 openapi 兼容性段补“回显范围” | ✅ 已决(2026-11-25,`74c4eff`) | +| OpenAPI 未声明 `serviceToken` securityScheme | 契约完整性问题 | 后续 issue(HE 以文档适配,不依赖生成式 schema) | ◻ 后续 issue(2026-11-25 拍板) | +| 控制台“不能覆盖固定字段”文案过期 | 文档/UI 债 | 单独 `web` 小 PR(`web/` 不在 #429 scope) | ◻ 后续 web issue(2026-11-25 记录) | +| 冒烟证据在仓库外、未入库;PR body 仍写“待补” | 过程记录 | 回填 PR 描述;证据不入库 | ✅ 已办(2026-11-25,PR body 已回填;截图在 release `m10-429-machine-trigger-evidence-20261125`) | ---