fix: collapse the evidence-key gate and resolver into one decision

Three fix rounds each rebuilt the gate as a separate expression that merely
agreed with the resolver on the inputs that round's tests used. Different
expressions cannot agree in general, so the defect class stayed open while
each reported instance closed.

`findResolvableAsset(assets, key)` is now the single place that decides which
Asset an evidence key resolves to. Every gate is
`Boolean(findResolvableAsset(...)) || legacyKey(key)` via one shared
composition, and every resolver returns what it returns:

- validate-working-copy: the key gate and the decorative lookup (a last-wins
  Map against the resolver's first-wins find, so alt could be judged against a
  different Asset than the one rendered)
- adapters/mock/project-public-render-model: gate and resolver
- instant-preview: gate and descriptor resolver
- createAssetCatalogResolver: the pixels, a fourth expression nobody had
  listed -- one Asset's caption could sit over another Asset's image

Duplicate assetKeys are a contract violation but reachable through a paged
list, so the choice is total and order-independent: newest updatedAt wins,
tie-broken by id.

InstantPreview's gate is no longer looser than the others. The un-loaded-asset
case it was loosened for blanks either way; all the looseness bought was
catalog-only keys rendering an empty gap with no message while validation said
EVIDENCE_UNSUPPORTED. The test that pinned that divergence now asserts the
consistent behaviour, and the false comment claiming a fix that did not exist
is gone.

idempotent() now maps a deterministic content failure to VALIDATION_STALE/409
instead of offering a retry that fails identically, and no longer caches
uncharacterized internal failures -- reporting one as retryable while freezing
it in the ledger meant the retry could never re-run.

Adds tests/features/tech-log/evidence-key-agreement.test.ts: 144 adversarial
(asset list, key) combinations asserting the agreement itself rather than
examples. It reported 53 disagreements against the previous code.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-08-18 06:55:06 +09:00
co-authored by Claude Opus 5
parent 783e9b2cf1
commit 073fda87eb
9 changed files with 754 additions and 275 deletions
@@ -2,6 +2,7 @@ import { StudioGatewayError } from "../../application/ports/studio-gateway-error
import type { IdempotentOptions, RequestOptions, StudioGateway } from "../../application/ports/studio-gateway.ts";
import type { components } from "../../contracts/studio/generated.ts";
import type { Asset, CatalogPage, DocumentPage, PreviewDetail, ProblemDetails, PublicationAggregate, PublicationEvent, PublicationListItem, PublicationPage, PublicPreview, PublishResult, StudioDashboard, WorkingCopy, WorkingCopyDetail, WorkingCopyInput } from "../../contracts/studio/contract.ts";
import { ContentFormatError } from "../../domain/content-format/parse-case-content.ts";
import { deriveDocumentState, derivePreviewState } from "../../domain/studio/document-state.ts";
import { cursorBinding, decodeCursor, encodeCursor } from "./cursor.ts";
import { createMockStudioState, MockStudioState } from "./mock-state.ts";
@@ -63,6 +64,34 @@ function uuid(value: unknown, path: string): asserts value is string {
if (typeof value !== "string" || !UUID.test(value)) throw requestError([{ path, message: "Must be a UUID." }]);
}
/**
* Classifies whatever escaped a handler into the problem this port reports,
* and whether that outcome may be replayed from the idempotency ledger.
*
* A `ContentFormatError` is deterministic: the document no longer projects
* against the dependencies as they stand (an Asset deleted between validate
* and preview is the live case). Reporting that as `STUDIO_UNAVAILABLE`/500
* `retryable: true` invites a retry that fails identically -- the honest
* signal is `VALIDATION_STALE`/409, "re-validate, then try again", which is
* not a retry of this request at all. Anything else is an uncharacterized
* internal defect: we cannot claim it is deterministic, so it is reported as
* retryable and deliberately left out of the ledger.
*/
function failureOf(error: unknown): { problem: ProblemDetails; replayable: boolean } {
if (error instanceof StudioGatewayError) return { problem: error.problem, replayable: true };
if (error instanceof ContentFormatError) {
const detail = error.issues.map((issue) => `${issue.line}:${issue.column} ${issue.detail}`).join("; ");
return {
problem: gatewayProblem(409, "VALIDATION_STALE", `The document no longer renders against current dependencies: ${detail}`).problem,
replayable: true,
};
}
return {
problem: gatewayProblem(500, "STUDIO_UNAVAILABLE", error instanceof Error ? error.message : "Studio가 요청을 처리하지 못했습니다.", { retryable: true }).problem,
replayable: false,
};
}
function exactSet(left: string[], right: string[]) {
return new Set(left).size === left.length && new Set(right).size === right.length && [...left].sort().join("\0") === [...right].sort().join("\0");
}
@@ -87,25 +116,18 @@ export function createMockStudioGateway(supplied: Partial<MockStudioDependencies
}
try { const value = work(); state.idempotency.set(key, { fingerprint, outcome: { kind: "success", value: clone(value) } }); return clone(value); }
catch (error) {
// Fix round 3. This port's contract is `StudioGatewayError` only --
// nothing else may cross it. Round 2 fixed one way a raw `Error`
// reached here (`createPreview`'s resolver); the class recurred a
// third time via a different Asset shape, and each time the actual
// symptom at the port boundary was the same: an unwrapped exception
// escaping `work()`. Rather than keep chasing individual internal
// causes, anything that isn't already a `StudioGatewayError` is
// normalized into one here, so a future internal defect degrades to a
// proper problem response instead of a bare `Error`.
const studioError = error instanceof StudioGatewayError
? error
: gatewayProblem(
500,
"STUDIO_UNAVAILABLE",
error instanceof Error ? error.message : "Studio가 요청을 처리하지 못했습니다.",
{ retryable: true },
);
state.idempotency.set(key, { fingerprint, outcome: { kind: "problem", problem: clone(studioError.problem) } });
throw new StudioGatewayError(clone(studioError.problem));
// This port's contract is `StudioGatewayError` only -- nothing else may
// cross it -- so anything `work()` throws is normalized here.
const { problem, replayable } = failureOf(error);
// Only outcomes we know are deterministic go in the ledger. Replaying a
// cached result is the ledger's whole point when re-running would
// produce the same answer, and it is exactly wrong when it would not:
// an uncharacterized internal failure is reported as retryable, so the
// retry has to actually re-run rather than replay a frozen 500. (No
// handler here mutates state before throwing an uncharacterized error,
// so re-running cannot double-apply an effect.)
if (replayable) state.idempotency.set(key, { fingerprint, outcome: { kind: "problem", problem: clone(problem) } });
throw new StudioGatewayError(clone(problem));
}
}
@@ -2,7 +2,8 @@ import type { components } from "../../contracts/studio/generated.ts";
import type { Asset } from "../../contracts/studio/contract.ts";
import {
evidenceCatalogEntriesFromAssets,
supportsEvidenceKeyFromReadyAssets,
findResolvableAsset,
supportsResolvableEvidenceKey,
} from "../../domain/content-format/asset-evidence-catalog.ts";
import {
projectWorkingCopy as projectWorkingCopyWithEvidence,
@@ -17,67 +18,41 @@ type ResolvedAsset = components["schemas"]["ResolvedAsset"];
type ProjectArguments = Parameters<typeof projectWorkingCopyWithEvidence>;
// The domain projection has no asset catalog access, so a CASE projection's
// EVIDENCE_FIGURE blocks come back without a resolved `asset`. This adapter owns
// the asset catalog (`adapters/static/evidence-assets.ts`, plus -- fix round 1
// (I2) -- whatever `Asset`s the caller passes, merged via
// `evidenceCatalogEntriesFromAssets`, the same function `validate-working-copy.ts`
// and Instant Preview use, so this mock's own `createPreview` agrees with
// `validateDocument` about which evidence keys exist), so it resolves the
// EVIDENCE_FIGURE blocks come back without a resolved `asset`. This adapter
// owns the asset catalog (`adapters/static/evidence-assets.ts` for the one
// legacy key, plus whatever `Asset`s the caller passes), so it resolves the
// descriptor here to produce a genuine, fully-resolved `PublicRenderModel`.
//
// Fix round 3 (I2 regression, third instance). Gate 1 (`supportsEvidenceKey`
// below) is built from `supportsEvidenceKeyFromReadyAssets` -- the exact
// predicate the resolver below uses (`assetKey === key && READY &&
// publicPath truthy`) -- not a catalog lookup. Round 1 gated on "is there
// any EVIDENCE catalog row for it" (too loose: rows that exist for
// something other than media, e.g. a QUESTION resolution target, passed).
// Round 2 narrowed to a catalog synthesized *from* Assets, but that catalog
// lookup (`evidenceCatalogEntryFor`, matching `id || label || publicPath`)
// is still a different expression than the resolver's own condition: a
// `READY` Asset with `publicPath: null`/`""`, or one whose `publicPath`
// happens to satisfy the legacy `/media/${someOtherKey}.svg` convention for
// a key that is not its own `assetKey`, passed that gate while the resolver
// below could not produce real pixels for it -- the same
// `validateDocument`-says-VALID / `createPreview`-throws disagreement, twice.
// Gate 2 (`evidenceCatalogEntryFor` below) keeps reading the merged catalog.
// The key gate and the resolver below are the same expression over the same
// inputs: both ask `findResolvableAsset(assets, key)` first and fall back to
// the same `isSupportedEvidenceKey` legacy check. Nothing else decides which
// Asset a key resolves to.
export function projectWorkingCopy(
input: ProjectArguments[0],
catalog: ProjectArguments[1],
context: ProjectArguments[2],
assets: readonly Asset[] = [],
) {
const evidenceCatalog = [...catalog, ...evidenceCatalogEntriesFromAssets(assets)];
const supportsEvidenceKey = (key: string) =>
isSupportedEvidenceKey(key) || supportsEvidenceKeyFromReadyAssets(assets)(key);
const model = projectWorkingCopyWithEvidence(
input,
evidenceCatalog,
[...catalog, ...evidenceCatalogEntriesFromAssets(assets)],
context,
supportsEvidenceKey,
supportsResolvableEvidenceKey(assets, isSupportedEvidenceKey),
);
return resolveCaseEvidenceAssets(model, resolveAssetDescriptor(assets));
}
/**
* Fix round 3. Total -- never throws -- the same discipline
* `instant-preview.tsx`'s resolver already followed. This class of bug has
* now recurred twice as "gate 1 passes a key the resolver then cannot
* resolve, and the resolver throws a raw, unwrapped `Error`". With gate 1
* above built from this function's exact condition, that specific
* disagreement cannot happen through `projectWorkingCopy`'s own interface
* any more -- but a resolver that structurally cannot throw is worth more
* than a resolver plus a comment asserting it never will (round 2's comment
* here made exactly that claim, and was wrong). Kept as defence in depth:
* if a future change reintroduces a mismatch, this degrades to a
* placeholder instead of putting a bare `Error` through the gateway port.
* Total -- never throws. Tries the same two sources the key gate above tries,
* in the same order, over the same `assets`; the final placeholder is what a
* key neither source can supply degrades to, rather than a bare `Error` put
* through the gateway port.
*/
function resolveAssetDescriptor(assets: readonly Asset[]) {
return (key: string): ResolvedAsset => {
const asset = assets.find(
(candidate) => candidate.assetKey === key && candidate.managementStatus === "READY",
);
if (asset?.publicPath) {
const asset = findResolvableAsset(assets, key);
if (asset) {
return {
assetId: asset.id,
assetKey: asset.assetKey,
@@ -2,7 +2,8 @@ import type { components } from "../../contracts/studio/generated.ts";
import type { Asset, ValidationReport, WorkingCopy } from "../../contracts/studio/contract.ts";
import {
evidenceCatalogEntriesFromAssets,
supportsEvidenceKeyFromReadyAssets,
findResolvableAsset,
supportsResolvableEvidenceKey,
} from "../../domain/content-format/asset-evidence-catalog.ts";
import { parseCaseContent } from "../../domain/content-format/parse-case-content.ts";
import { evidenceCatalogEntryFor } from "../../domain/content-format/project-public-render-model.ts";
@@ -17,23 +18,16 @@ export type ValidationDependencies = {
now: Date; validationId: string; dependencyRevision: string;
catalog: ReadonlyArray<CatalogEntry>; documents: ReadonlyArray<WorkingCopy>;
/**
* Fix round 1 (I2). Without this, the mock's validate step only ever
* recognized the one hardcoded legacy evidence key -- disconnected from
* the Asset system (Tasks 6/7) the Picker (Task 10) actually inserts keys
* from -- so every Picker-inserted directive previewed live and then
* failed validation. Merged into `catalog` via
* `evidenceCatalogEntriesFromAssets`, the same function Instant Preview
* uses, so both paths agree on which keys a document may reference.
* The Assets the session has loaded. Without them the mock's validate step
* would only recognize the one hardcoded legacy evidence key, disconnected
* from the Asset system the Picker inserts keys from, and every
* Picker-inserted directive would preview live and then fail validation.
*
* Fix round 2: only used for gate 2 (the merged-catalog lookup) and the
* `EVIDENCE_ALT_REQUIRED` decorative check. Gate 1 (`supportsEvidenceKey`
* below) intentionally does NOT read the merged catalog -- see that
* variable's comment.
*
* Fix round 3: gate 1 also stopped reading a catalog derived from these
* assets at all -- it now calls `supportsEvidenceKeyFromReadyAssets`
* directly against this array, the same predicate the resolver uses, so
* the two can no longer disagree.
* Every question asked of this array -- may the document reference the key,
* and is the referenced Asset decorative -- goes through
* `findResolvableAsset`, the same function the preview projection resolves
* with, so validation can never judge a different Asset than the one that
* renders.
*/
assets: ReadonlyArray<Asset>;
};
@@ -188,27 +182,18 @@ export function validateWorkingCopy(document: WorkingCopy, dependencies: Validat
if (blank(document.bodyMarkdown)) error("CASE_BODY_REQUIRED", "/bodyMarkdown", "본문을 입력하세요.");
else try {
const evidenceCatalog = [...dependencies.catalog, ...evidenceCatalogEntriesFromAssets(dependencies.assets)];
// Fix round 3 (I2 regression, third instance). Gate 1 must ask "does a
// real, resolvable Asset (or the legacy key) back this" -- not "is
// there a catalog row for it" (round 1's bug) and not "is there a
// catalog row synthesized *from* an Asset for it" either (round 2's
// bug: `evidenceCatalogEntryFor` matches on `id || label ||
// publicPath`, which is still gate 2's question over fewer rows, and a
// `READY` Asset with a null/empty `publicPath`, or one whose
// `publicPath` happens to satisfy the legacy convention for a
// *different* key, passed it while the resolver could not produce
// real pixels for it). Gate 1 is now built directly from
// `supportsEvidenceKeyFromReadyAssets` -- the exact predicate the
// resolver uses (`assetKey === key && READY && publicPath truthy`) --
// so the two cannot diverge. Gate 2 (`evidenceCatalogEntryFor` below)
// still reads the merged catalog; only gate 1 changed.
const supportsEvidenceKey = (key: string) =>
isSupportedEvidenceKey(key) || supportsEvidenceKeyFromReadyAssets(dependencies.assets)(key);
const readyAssetsByKey = new Map(dependencies.assets.filter((asset) => asset.managementStatus === "READY").map((asset) => [asset.assetKey, asset]));
// The key gate is the preview projection's gate, verbatim: a resolvable
// Asset or the legacy static key. The catalog check below is a separate
// question ("does some catalog carry a row for this key"), and the
// decorative lookup reads the *same* Asset the projection resolves --
// it used to be a last-wins `Map` against a first-wins `find`, so two
// READY Assets sharing one key could have alt judged against one Asset
// and rendered from another.
const supportsEvidenceKey = supportsResolvableEvidenceKey(dependencies.assets, isSupportedEvidenceKey);
for (const block of parseCaseContent(document.bodyMarkdown)) if (block.type === "EVIDENCE_FIGURE") {
if (!supportsEvidenceKey(block.key)) error("EVIDENCE_UNSUPPORTED", "/bodyMarkdown", `지원하지 않는 Evidence: ${block.key}`);
else if (!evidenceCatalogEntryFor(evidenceCatalog, block.key)) error("EVIDENCE_NOT_FOUND", "/bodyMarkdown", `Evidence 없음: ${block.key}`);
else if (block.alt.trim().length === 0 && !readyAssetsByKey.get(block.key)?.decorative) {
else if (block.alt.trim().length === 0 && !findResolvableAsset(dependencies.assets, block.key)?.decorative) {
// 정적 evidence 자산은 장식용이 아니다. Asset 기반 경로는 실제
// Asset.decorative로 같은 판정을 한다(decorative Asset은 대체
// 텍스트가 없어도 통과한다 -- asset-picker.tsx가 그렇게 directive를