Files
crank/_bmad-output/implementation-artifacts/1-5-canonical-request-trace-identity.md
T

37 KiB
Raw Blame History

baseline_commit
baseline_commit
c30461cc92

Story 1.5: Ввести canonical request и trace identity

Status: done

Story

As an оператор поддержки, I want получать Request ID и Trace ID на существующих ingress/runtime paths, so that все последующие capabilities наследуют correlation по готовому contract.

Strategic Intent

Story 1.5 завершает correlation foundation Wave 0. Она отделяет локальную product identity от внешнего telemetry backend: Request ID и Trace ID существуют, возвращаются и сохраняются даже при отключённом OTLP, sampling-off или недоступном exporter. После этой Story синхронный REST → MCP путь диагностируется локально по двум разным идентификаторам, а последующие Tasks, Resources, Prompts и Load Runs получают готовый typed parent-context contract.

Story не заявляет, что trace уже доступен в GlitchTip. Поиск/copy/deep-link в UI, browser spans, GlitchTip performance delivery и durable telemetry spool принадлежат Epic 5.

Requirement: FR-27
Architecture: AD-11; применимые AD-12, AD-19, AD-20, AD-21
Applicable NFR: NFR-O1, NFR-S2, NFR-S4, NFR-S6, NFR-S8, NFR-O4, NFR-O5, NFR-C1; NFR-C4 только при появлении нового пользовательского текста.

Acceptance Criteria

  1. Отдельные canonical identities на каждом ingress

    • Given UI-originated Admin API request, любой Admin API ingress либо MCP Streamable HTTP ingress
    • When отсутствуют IDs, x-request-id/traceparent malformed, oversized либо представлены неоднозначными duplicate values
    • Then локально создаются отдельные typed Request ID и canonical W3C Trace ID
    • And локально созданный Request ID является UUIDv7, Trace ID — 32 lowercase hex, не all-zero, и они никогда не используются вместо друг друга
    • And response headers и safe boundary error возвращают один и тот же локальный x-request-id и x-trace-id, не отражая rejected input.
  2. Совместимый Request ID и строгий W3C parent

    • Given ровно один syntactically valid bounded x-request-id
    • When ingress формирует context
    • Then текущее совместимое opaque значение сохраняется как Request ID; missing/rejected значение заменяется UUIDv7
    • And валидный traceparent продолжает его Trace ID новым local span, а invalid parent создаёт новый local root trace
    • And JSON-RPC id, legacy x-correlation-id, database Execution ID и Request ID остаются разными контрактами.
  3. Независимость от sampling и exporter

    • Given OTLP unset, exporter unavailable либо local sampler не записывает span
    • When Admin/MCP request проходит ingress
    • Then процесс всё равно создаёт валидный local Trace ID до application logic
    • And response, boundary error, runtime context, structured logs и новый Invocation record получают этот ID
    • And отсутствие telemetry export не меняет product response или readiness после успешного startup.
  4. Сквозное synchronous propagation

    • Given validated ingress correlation context
    • When Admin test либо MCP Tool call проходит service → RuntimeExecutionRequest → runtime → REST adapter → upstream
    • Then typed Request ID и TraceContext передаются явно, а spans продолжают одну trace topology
    • And upstream получает system-owned x-request-id и W3C traceparent
    • And static/mapped/user headers и upstream response не могут заменить x-request-id, x-trace-id, legacy x-correlation-id, traceparent, tracestate или baggage.
  5. Bounded trust policy

    • Given incoming traceparent, tracestate или baggage
    • When headers проверяются
    • Then ровно один traceparent строго валидируется по W3C; duplicate, malformed, non-canonical, zero-ID и oversized варианты отклоняются без echo
    • And tracestate ограничен 512 bytes и 32 members, но caller state не пересылается наружу по умолчанию
    • And baggage имеет input budget 8192 bytes/64 members и пустую Community allowlist, поэтому user baggage не извлекается и не пересылается; rejected reason остаётся закрытым low-cardinality enum, а не raw value.
  6. Durable Invocation identity и совместимая migration v3

    • Given новый Admin test или MCP Tool Execution
    • When Invocation History сохраняется
    • Then новый record содержит обязательные для application write Request ID и Trace ID независимо от sampling
    • And fresh/v2 databases переходят через новую append-only checksummed migration v3 под MigrationAuthority; immutable v1/v2 source/digests не меняются
    • And legacy rows остаются читаемыми с честным nullable Trace ID, без fabricated backfill, а schema fingerprint валидируется относительно фактически applied version.
  7. Safe logs, events и errors

    • Given success, auth/validation/rate-limit rejection, upstream failure, runtime error либо history-write loss
    • When формируются logs, audit/error events и boundary payloads
    • Then canonical IDs присутствуют только в bounded validated correlation fields
    • And credentials, cookies, mapped headers, raw trace inputs, payloads, URLs и driver causes не отражаются
    • And Request/Trace/Correlation IDs никогда не используются как Prometheus labels или dynamic event names.
  8. Future durable boundary contract

    • Given будущая Task/worker/process boundary
    • When owning Story проектирует acknowledgement и durable envelope
    • Then она обязана сохранять typed Request ID, Trace ID и validated canonical parent TraceContext до acknowledgement
    • And каждый retry является отдельным child attempt span при сохранении origin Trace ID
    • And фактическая Task persistence/worker propagation и их completion evidence остаются в owning Epic 4 stories.
  9. Correlation evidence

    • Given foundation suite
    • When выполняются missing/valid/malformed/oversized/duplicate, auth, validation, concurrency, sampling-off, success и upstream-failure cases
    • Then 100% проверенных Admin/MCP ingresses и всех новых Invocation records имеют оба ID без cross-request leakage
    • And один real-stack Admin test и MCP Tool call связывают ingress response, captured upstream headers, structured logs и PostgreSQL history
    • And targeted suites, migration gates, explicit Community scope scan и один финальный just verify проходят без dependency/toolchain drift.

Scope Boundary

In Scope

  • Existing Admin HTTP and MCP Streamable HTTP ingress, включая success, auth, validation, rate-limit, unmatched и internal-error responses.
  • UI-originated calls как Admin ingress; браузер должен уметь получить IDs из response/error contract, но не создаёт browser trace в этой Story.
  • Framework-free typed Request ID/Trace ID/TraceContext, runtime propagation и future durable parent envelope.
  • Local trace creation при disabled export/sampling-off; OpenTelemetry остаётся adapter/export mechanism, а не source of truth для persisted identity.
  • Admin test и MCP Tool synchronous execution, REST outbound headers, structured logs/errors и Invocation History.
  • Append-only migration v3 через Story 1.4 authority.

Out of Scope

  • Global correlation search, copy controls, timeline и trace-backend deep links — Story 5.2 / FR-28.
  • Browser navigation/API spans и same-origin telemetry relay — Story 5.3 / FR-30.
  • GlitchTip performance export, Sentry-envelope mapping, spool и Telemetry Loss Record — Stories 5.4–5.6 / FR-29/FR-31.
  • Prometheus exemplars/Grafana — Story 1.6 и Epic 5.
  • Task/worker persistence, process continuation и retries — Epic 4; здесь только typed contract.
  • Fabricated Trace ID backfill для historical Invocation rows.
  • Resources, Prompts, Load Runs или новые пользовательские экраны.

Tasks / Subtasks

  • Task 1 — Зафиксировать typed correlation contract и trust policy (AC: 1–5, 8)

    • Выделить framework-free RequestId, TraceId, TraceContext и serializable future parent envelope в существующем нижнем слое; не дублировать типы между Admin/MCP/runtime.
    • Generated Request ID — UUIDv7; совместимый inbound Request ID — один visible ASCII value ≤128 bytes без whitespace/control/comma/semicolon.
    • Trace ID — canonical lowercase 32-hex non-zero; traceparent — единственный W3C-valid header с non-zero trace/parent IDs.
    • Зафиксировать tracestate budget 512 bytes/32 members, baggage budget 8192 bytes/64 members и пустую Community allowlist для caller state/baggage.
    • Определить response headers x-request-id/x-trace-id, boundary JSON fields request_id/trace_id и единый reserved-correlation-header set.
  • Task 2 — Добавить RED contract/security tests до production wiring (AC: 1–5, 7, 9)

    • Table-driven cases: absent, exact limits, over limits, invalid UTF-8/ASCII, duplicate values, zero IDs, malformed version/flags, hostile canaries.
    • Admin и MCP 2xx/400/401/403/404/429/500 responses возвращают согласованные safe headers; structured errors содержат те же IDs там, где boundary имеет JSON contract.
    • Sampling/export disabled и unavailable exporter не удаляют Trace ID.
    • Concurrent requests не смешивают task-local/request extensions/log correlation.
    • Metric schema/scrape negative test запрещает request_id, trace_id, correlation_id в labels.
  • Task 3 — Сделать local Trace ID независимым от exporter (AC: 1–3, 5)

    • Изменить observability lifecycle так, чтобы локальная trace context generation работала всегда, но disabled export не создавал exporter/background queue/network egress.
    • Строго извлекать или отклонять remote parent до application logic; invalid input не логировать и не возвращать.
    • Получать canonical local context из ingress span и закреплять его typed snapshot в request extension/task-local scope.
    • Не включать Sentry performance tracing или GlitchTip delivery в эту Story.
  • Task 4 — Провести context через Admin и MCP boundaries (AC: 1–3, 7, 9)

    • Middleware выполняется достаточно рано, чтобы IDs получали auth/validation/unmatched/internal failures.
    • Admin ApiError и MCP Tool/JSON-RPC boundary errors получают safe correlation без raw cause; success bodies не меняются без необходимости.
    • Все HTTP responses получают x-request-id и x-trace-id; rejected input никогда не отражается.
    • UI API error object может сохранить response IDs для будущего support UI без добавления global search/deep-link/browser telemetry.
  • Task 5 — Устранить conflated runtime correlation (AC: 2, 4, 8)

    • Заменить внутренний correlation_id=request_id на explicit typed Request ID + TraceContext в RuntimeRequestContext и core adapter context.
    • Legacy outbound x-correlation-id, если сохраняется ради compatibility, является явно документированным alias Request ID и никогда не считается Trace ID.
    • Admin test, MCP Tool и approval continuation передают один canonical context в RuntimeExecutionRequest.
    • Любой existing internal execution fallback, запущенный без transport context, генерирует оба typed ID; silent request_id-only execution запрещён.
    • Future durable envelope имеет bounded deterministic serde roundtrip, но не создаёт Task storage.
  • Task 6 — Закрепить system-owned outbound propagation (AC: 4–5, 7)

    • REST adapter удаляет reserved correlation headers из static/mapped input до валидации values и инжектирует только system context.
    • Outbound client span и traceparent сохраняют ingress Trace ID; каждая attempt/span identity остаётся отдельной.
    • Upstream traceparent/x-request-id/x-trace-id response не меняет local context/history/error identity.
    • User tracestate и baggage не покидают установку по умолчанию.
  • Task 7 — Добавить append-only migration v3 и persistence (AC: 6, 9)

    • Создать новый exact-byte SQL artifact request_trace_identity_v3.sql; не редактировать baseline_v1.rs или consolidation_v2.sql.
    • Добавить descriptor/version/digest/dispatch/machine contract и version-aware schema fingerprint: healthy v2 сообщает migration_required, v3 требует новый shape.
    • Добавить nullable invocation_logs.trace_id с canonical-format constraint для non-null и partial indexes (workspace_id, trace_id) и (workspace_id, request_id) только для non-null values.
    • Новый application write требует оба typed ID; reads сохраняют nullable compatibility historical rows без backfill.
    • Проверить fresh, v2→v3, current/repeat, corrupt checksum, structural drift, rollback и representative row preservation на PostgreSQL 16.
  • Task 8 — Обновить history/log/error contracts (AC: 3, 6–7)

    • Добавить Trace ID в InvocationLog, registry insert/select/map и все Admin/MCP constructors/fixtures.
    • History write loss сохраняет product outcome и логирует оба safe ID без database cause.
    • Logging/Sentry correlation принимает только validated typed scalar; минимальный event budget не должен превращать raw input в output.
    • Не добавлять IDs в metrics labels; не утверждать внешнюю trace delivery.
  • Task 9 — Выполнить focused и final evidence один раз (AC: 9)

    • Сначала targeted pure/ingress/runtime/REST/registry suites, затем PostgreSQL migration matrix.
    • Один real-stack smoke проверяет Admin test и MCP Tool до captured upstream/history/log IDs при exporter disabled.
    • Обновить Capability Inventory и baseline evidence новым version/checksum только по фактически прошедшим результатам; отделить реализованный FR-27 foundation от остающихся planned FR-28…FR-35.
    • После targeted green выполнить UI build/затронутый Playwright только если менялся api.js, затем один just verify.
    • Выполнить git diff --check, Cargo/npm/toolchain audit и explicit Community scan каждого NEW/UPDATE path; skipped/flaky/missing evidence не считать pass.

Review Findings

  • [Review][Patch] [High] Пересобрать Capability Baseline на clean implementation revision: после исправлений создать локальный implementation commit, повторить collector/just verify на его SHA и оформить evidence отдельным локальным commit без push [docs/capability-baseline/results.json:301]
  • [Review][Patch] [High] Missing/malformed ingress должен создавать настоящий local root, а typed TraceContext обязан быть snapshot фактического ingress span; не устанавливать синтетический remote parent и не hardcode sampled flag [crates/crank-core/src/correlation.rs:96]
  • [Review][Patch] [High] Нормализовать RuntimeRequestContext в начале execution и parent-ить runtime/approval-recovery spans от explicit typed context, не от случайного ambient span [crates/crank-runtime/src/executor.rs:241]
  • [Review][Patch] [Medium] Создавать и активировать отдельный outbound attempt span до W3C injection, чтобы upstream parent-id совпадал со span-id попытки [crates/crank-adapter-rest/src/client.rs:103]
  • [Review][Patch] [High] Закрыть serde-bypass: RequestId/TraceId/TraceContext/CorrelationContext должны десериализоваться только через validating constructors и проверять согласованность trace_id с traceparent [crates/crank-core/src/correlation.rs:8]
  • [Review][Patch] [High] Не возвращать и не сохранять raw SQLx/runtime/crypto/URL/payload causes в Admin/MCP boundary payloads и Invocation History; использовать fixed public messages и low-cardinality codes [apps/admin-api/src/error.rs:161]
  • [Review][Patch] [Medium] Добавлять canonical request_id/trace_id в error.data всех MCP JSON-RPC validation/session/catalog/internal branches [crates/crank-community-mcp/src/jsonrpc.rs:47]
  • [Review][Patch] [Medium] Отбрасывать все шесть reserved correlation headers до parsing пользовательского value, включая case variants x-request-id/x-trace-id/x-correlation-id [crates/crank-adapter-rest/src/client.rs:459]
  • [Review][Patch] [Medium] Гарантировать Request ID и Trace ID в structured rejection/internal logs, включая 400/401/403/404/429/500 [apps/admin-api/src/error.rs:137]
  • [Review][Patch] [Medium] Принимать typed RequestId/TraceId в observability correlation API либо валидировать строки до task-local/Sentry tags [crates/crank-observability/src/error_reporting.rs:116]
  • [Review][Patch] [Medium] Резервировать event budget под canonical IDs и не удалять их из bounded JSON logs/Sentry events при допустимой минимальной конфигурации [crates/crank-observability/src/logging.rs:103]
  • [Review][Patch] [High] Schema fingerprint v3 должен проверять точные definitions/таблицы/колонки/predicate/validity constraint и indexes, а не только ожидаемые имена [crates/crank-registry/src/migrations/schema_guard.rs:279]
  • [Review][Patch] [Medium] Healthy v2 fingerprint должен обнаруживать частично вручную добавленные v3 objects до запуска ADD COLUMN/index DDL [crates/crank-registry/src/migrations/schema_guard.rs:262]
  • [Review][Patch] [Medium] Migration v3 должна предсказуемо обработать legacy request_id, превышающий PostgreSQL B-tree key limit, вместо необъяснимого apply failure [crates/crank-registry/src/migrations/request_trace_identity_v3.sql:14]
  • [Review][Patch] [High] Дополнить обязательную AC9 evidence matrix: Admin/MCP 400/401/403/404/429/500, concurrency, true sampling-off/export failure и цельные response→upstream→JSON log→PostgreSQL chains [apps/admin-api/tests/integration/request_context.rs:24]
  • [Review][Patch] [Medium] Добавить фактически изменённый apps/admin-api/src/dto.rs в Story File List и повторить полный explicit scope/evidence audit [apps/admin-api/src/dto.rs:549]

Dev Notes

Current Brownfield State

  • crank_observability::RequestId уже валидирует один x-request-id и генерирует UUIDv7, но тип связан с Axum HeaderMap, а Admin/MCP extensions хранят только String.
  • apps/admin-api/src/request_context.rs и crates/crank-community-mcp/src/request_context.rs создают ingress span, принимают remote parent и возвращают только x-request-id.
  • crates/crank-observability/src/propagation.rs извлекает W3C context через global propagator, но не задаёт явные duplicate/size/tracestate rules.
  • При отсутствующем OTLP lifecycle не устанавливает tracer layer/provider. Поэтому current_trace_id() возвращает None: это главный correctness gap.
  • Runtime/core RuntimeRequestContext содержат request_id и correlation_id; from_request_id() делает их равными. Это legacy compatibility, а не Trace ID.
  • REST adapter уже подавляет mapped traceparent/tracestate/baggage и system headers overwrite mapped request headers, но trace injection зависит от ambient span и reserved set неполон.
  • InvocationLog/invocation_logs хранят nullable request_id и не имеют trace_id.
  • Admin ApiError не содержит correlation fields; MCP ToolErrorContract содержит только Request ID.
  • UI window.CrankApi не создаёт browser trace и не сохраняет response correlation в error object. Browser tracing остаётся Story 5.3.

Frozen Contract Decisions

  • Request ID и Trace ID — разные identities. Request ID поддерживает текущий валидный opaque inbound формат; только локально созданный replacement обязан быть UUIDv7.
  • Trace ID не является x-request-id, x-correlation-id, Execution ID или JSON-RPC ID.
  • x-trace-id — safe response/support header. traceparent предназначен для W3C propagation и не возвращается клиенту как support ID.
  • Invalid/duplicate traceparent создаёт новый root trace. Invalid/oversized tracestate или baggage не уничтожает валидный traceparent, но state/baggage отбрасывается.
  • Caller tracestate/baggage не пересылаются по умолчанию; эта Story не добавляет operator allowlist configuration.
  • Local trace creation обязательна, export — optional. Не создавать network egress, если он не настроен.
  • Исторические rows с trace_id = NULL честно остаются legacy; нельзя генерировать им несвязанный ID.
  • Migration v3 — expand-compatible nullable column. Application N пишет оба ID; schema остаётся читаемой N-1 до закрытия rollback window.

Architecture / Dependency Guardrails

  • Не заставлять crank-core/runtime/registry зависеть от crank-observability или Axum/OpenTelemetry implementation.
  • Framework header parsing остаётся в ingress adapters; shared identity/value types не импортируют Axum.
  • crank-observability продолжает владеть exporter/redaction и не становится доменным source of truth.
  • Не менять dependency direction без явного синхронного обновления Architecture Spine и boundary tests. Использовать уже locked crates; не обновлять версии.
  • Product metrics записываются только через crank-metrics; IDs запрещены в labels.
  • Apps remain composition roots; routes не вызывают runtime напрямую, services не импортируют Axum.
  • Migration DDL принадлежит только crank-registry::MigrationAuthority; app startup read-only.

File Map

Likely NEW

  • crates/crank-registry/src/migrations/request_trace_identity_v3.sql
  • focused correlation contract tests if existing suites cannot hold the matrix.

Likely UPDATE

  • crates/crank-observability/src/{correlation.rs,propagation.rs,lifecycle.rs,logging.rs,error_reporting.rs,lib.rs} and correlation/propagation/logging tests.
  • crates/crank-core/src/{lib.rs,observability.rs,ext/protocol.rs} or another existing pure contract owner selected without reversing dependencies.
  • crates/crank-runtime/src/{request_context.rs,executor.rs,lib.rs} and focused tests.
  • apps/admin-api/src/{request_context.rs,error.rs,routes/operations.rs,service.rs,service/operations.rs} plus request/history integration tests.
  • crates/crank-community-mcp/src/{request_context.rs,app.rs,app/invocation_history.rs,approval_execution.rs,tool_error.rs,jsonrpc.rs} plus focused/integration tests.
  • crates/crank-adapter-rest/src/{lib.rs,client.rs} and integration tests.
  • crates/crank-registry/src/{model.rs,postgres/mod.rs,postgres/observability.rs,migrations/authority.rs,migrations/schema_guard.rs} plus migration/history tests.
  • docs/schemas/migration-sequence.json, docs/migrations.md, docs/en/migrations.md, observability docs/indexes as applicable.
  • docs/capability-inventory.json и versioned docs/capability-baseline/* только для честной привязки нового FR-27 evidence/checksum.
  • apps/ui/js/api.js and focused Playwright only if response correlation is retained in browser error objects.
  • local ignored _bmad-output/project-context.md; do not force-add.

Must Not Change

  • Immutable v1/v2 migration source/digests, Rust 1.96.1/Edition 2024, dependency versions, MCP revision matrix, Admin success DTOs, product status/outcome semantics.
  • No GlitchTip availability claim, direct browser DSN, telemetry spool, Task tables/workers, global correlation search, Grafana or new metric labels.

Testing Commands

cargo test -p crank-observability --test correlation
cargo test -p crank-observability --test propagation
cargo test -p crank-observability --test json_logging
cargo test -p admin-api --test integration request_context -- --test-threads=1
cargo test -p mcp-server --test integration request_context -- --test-threads=1
cargo test -p crank-adapter-rest --test integration -- --test-threads=1
cargo test -p crank-registry --test integration migrations -- --test-threads=1
cargo test -p crank-registry --test integration observability -- --test-threads=1
cargo test -p admin-api --test integration community_access_usage -- --test-threads=1
cargo test -p mcp-server --test integration transport_protocol -- --test-threads=1
cargo run -p admin-api --bin crank-migrate -- plan --check
just capability-inventory-check
cd apps/ui && npm ci && npm run build
# Playwright only if apps/ui/js/api.js changes
PATH="$HOME/.cargo/bin:$PATH" just authenticated-product-smoke http://localhost:3000
PATH="$HOME/.cargo/bin:$PATH" just verify
git diff --check

Previous Story Intelligence

  • Story 1.4 established one append-only checksummed migration authority. Add v3; never extend unconditional current fingerprint so that healthy v2 becomes partial_sequence instead of migration_required.
  • The schema guard must validate the shape for the actual applied ledger version: v2 accepts pre-trace history, v3 requires the new column/constraints/indexes.
  • App startup remains read-only; only crank-migrate apply writes DDL. Preserve the one-shot Compose ordering.
  • Story 1.4 review showed that all RED/edge cases should be frozen before implementation, then targeted suites and one final full gate should run once.
  • Existing worktree contains Stories 1.1–1.4 changes. Preserve them; no reset/checkout or incidental lockfile regeneration.

Latest Technical Notes

  • W3C traceparent carries version, 16-byte Trace ID, 8-byte parent ID and flags; all-zero Trace/Parent IDs are invalid and malformed input must be ignored rather than propagated.
  • W3C tracestate limits a list to 32 members and 512 characters; Community defaults to discarding caller state instead of forwarding vendor/user data.
  • OpenTelemetry propagation is an adapter for extracting/injecting context. Persisted local identity must remain available when recording/export is disabled.

References

  • [Source: _bmad-output/planning-artifacts/epics.md — Epic 1, Story 1.5, FR-27; Epic 5 Stories 5.1–5.4]
  • [Source: _bmad-output/planning-artifacts/prds/prd-crank-2026-08-03/prd.md — FR-27, NFR-O1, NFR-S2/S4/S6/S8, NFR-O4/O5]
  • [Source: _bmad-output/planning-artifacts/prds/prd-crank-2026-08-03/addendum.md — Observability direction]
  • [Source: _bmad-output/planning-artifacts/architecture/architecture-crank-2026-08-03/ARCHITECTURE-SPINE.md — AD-11, AD-12, AD-19, AD-21]
  • [Source: _bmad-output/planning-artifacts/implementation-readiness-report-2026-08-08.md — FR-27/NFR-O1 mapping and story-level evidence requirement]
  • [Source: _bmad-output/implementation-artifacts/1-4-versioned-migration-authority.md — migration authority and review lessons]
  • [Source: _bmad-output/project-context.md — observability, redaction, migration and test rules]
  • W3C Trace Context
  • OpenTelemetry Context and Propagation
  • W3C Baggage

Dev Agent Record

Agent Model Used

GPT-5 Codex

Debug Log References

  • RED: cargo test -p crank-core --test correlation initially failed because the typed correlation contract and UUID dependency did not exist.
  • Targeted GREEN: core correlation (5), observability all-targets, Admin/MCP ingress, runtime, REST propagation, migration matrix (16 after v3 rollback case), history and real execution-stage tests.
  • Final quality gate: just verify passed after updating the migration CLI expectations from v2 to v3.
  • UI evidence: npm run build; npm run e2e -- observability.spec.js — 3 passed, 0 failed, 0 flaky.
  • Real-stack evidence: authenticated product smoke completed Operation create/test/publish, Agent publish, MCP initialize, tools/list and tools/call against the local PostgreSQL 16 stack.
  • Contract evidence: Capability baseline 2026.08.10.1 validates with 31 flows / 19 implemented; explicit Community scan passed for 72 Story paths; git diff --check passed.

Completion Notes List

  • Added one framework-free canonical RequestId / TraceId / TraceContext contract shared by Admin, MCP, runtime and persistence. Request identity is no longer conflated with trace identity.
  • Local trace identity now exists without OTLP export, sampling or a telemetry backend. The implementation creates the product context first and attaches the ingress span to it; OpenTelemetry remains an adapter rather than the source of durable identity.
  • Admin and MCP boundaries return safe x-request-id and x-trace-id; structured boundary/tool errors and UI error objects retain only validated bounded values.
  • REST propagation is system-owned: mapped/static correlation headers, caller tracestate and baggage cannot replace or escape the canonical context.
  • Added append-only migration v3 and version-aware fingerprints. New Invocation writes require both IDs; historical rows remain nullable without fabricated backfill. Transactional v3 rollback and v2 upgrade paths are proven on PostgreSQL 16.
  • Capability Inventory now records FR-27 as implemented, while FR-28–FR-35 remain planned. This Story does not claim GlitchTip trace availability, search/deep links, browser spans, telemetry spool, Grafana or exemplars.
  • Repaired the local Playwright stack to run the controlled migrator before services, use process-scoped configuration and shut down child processes/PostgreSQL cleanly.
  • No open implementation blocker and no user action required. Story is ready for adversarial code review.

File List

  • Cargo.lock
  • crates/crank-core/Cargo.toml
  • crates/crank-core/src/correlation.rs
  • crates/crank-core/src/ext/protocol.rs
  • crates/crank-core/src/lib.rs
  • crates/crank-core/src/observability.rs
  • crates/crank-core/tests/correlation.rs
  • crates/crank-observability/Cargo.toml
  • crates/crank-observability/src/correlation.rs (removed; contract moved to crank-core)
  • crates/crank-observability/src/error_reporting.rs
  • crates/crank-observability/src/lib.rs
  • crates/crank-observability/src/lifecycle.rs
  • crates/crank-observability/src/logging.rs
  • crates/crank-observability/src/otlp.rs
  • crates/crank-observability/src/prometheus.rs
  • crates/crank-observability/tests/json_logging.rs
  • crates/crank-observability/tests/prometheus.rs
  • crates/crank-observability/tests/request_correlation.rs
  • crates/crank-observability/tests/correlation.rs (removed; replaced by core contract tests)
  • crates/crank-runtime/src/executor.rs
  • crates/crank-runtime/src/request_context.rs
  • crates/crank-trace/Cargo.toml
  • crates/crank-trace/src/lib.rs
  • crates/crank-adapter-rest/src/client.rs
  • crates/crank-adapter-rest/src/lib.rs
  • crates/crank-adapter-rest/tests/integration/client.rs
  • apps/admin-api/src/error.rs
  • apps/admin-api/src/dto.rs
  • apps/admin-api/src/request_context.rs
  • apps/admin-api/src/routes/operations.rs
  • apps/admin-api/src/service.rs
  • apps/admin-api/src/service/demo.rs
  • apps/admin-api/src/service/operations.rs
  • apps/admin-api/tests/integration.rs
  • apps/admin-api/tests/integration/common.rs
  • apps/admin-api/tests/integration/operations_agents.rs
  • apps/admin-api/tests/integration/request_context.rs
  • apps/admin-api/tests/migration_command.rs
  • crates/crank-community-mcp/src/app.rs
  • crates/crank-community-mcp/src/app/invocation_history.rs
  • crates/crank-community-mcp/src/app/tool_resolution.rs
  • crates/crank-community-mcp/src/approval_execution.rs
  • crates/crank-community-mcp/src/jsonrpc.rs
  • crates/crank-community-mcp/src/rate_limit.rs
  • crates/crank-community-mcp/src/request_context.rs
  • crates/crank-community-mcp/src/session.rs
  • crates/crank-community-mcp/src/tool_error.rs
  • crates/crank-community-mcp/src/tool_search.rs
  • crates/crank-community-mcp/tests/unit/tool_error.rs
  • apps/mcp-server/tests/integration.rs
  • apps/mcp-server/tests/integration/common.rs
  • apps/mcp-server/tests/integration/execution_stages.rs
  • apps/mcp-server/tests/integration/jsonrpc_correlation.rs
  • apps/mcp-server/tests/integration/request_context.rs
  • apps/mcp-server/tests/integration/transport_protocol.rs
  • crates/crank-registry/src/error.rs
  • crates/crank-registry/src/migrations/authority.rs
  • crates/crank-registry/src/migrations/authority_tests.rs
  • crates/crank-registry/src/migrations/request_trace_identity_v3.sql
  • crates/crank-registry/src/migrations/schema_guard.rs
  • crates/crank-registry/src/postgres/mod.rs
  • crates/crank-registry/src/postgres/observability.rs
  • crates/crank-registry/tests/integration/common.rs
  • crates/crank-registry/tests/integration/migrations.rs
  • apps/ui/js/api.js
  • apps/ui/playwright.config.js
  • apps/ui/scripts/playwright-stack.sh
  • apps/ui/tests/e2e/observability.spec.js
  • docs/mcp-interface.md
  • docs/observability.md
  • docs/migrations.md
  • docs/en/migrations.md
  • docs/schemas/migration-sequence.json
  • docs/capability-inventory.json
  • docs/capability-baseline/manifest.json
  • docs/capability-baseline/manual-checklist.md
  • docs/capability-baseline/outcome-taxonomy.json
  • docs/capability-baseline/required-surfaces.json
  • docs/capability-baseline/results.json
  • scripts/check-community-scope.py
  • tests/unit/test_check_community_scope.py

Change Log

  • 2026-08-10: Story 1.5 created with typed Request/Trace identity, sampling-independent local correlation, synchronous propagation, migration v3 and bounded evidence contract.
  • 2026-08-10: Implemented and verified the canonical identity foundation, persistence migration, browser support-error retention, full correlation test matrix and versioned FR-27 evidence; moved Story to review.
  • 2026-08-14: Closed all adversarial review findings, restored architecture/code-health gates, verified production images, committed implementation as f6fc2e5, rebuilt clean evidence baseline 2026.08.14.1 and committed evidence as 17c8e3a; Story moved to done.