fix(bootstrap): 실패한 scope closer를 label과 함께 진단에 남긴다

문제: 1103/02-01이 제품 closer를 scope reset에 넣었다. template
participant 하나가 제품 closer를 차례로 부르고, 하나라도 던지면 이유 없는
Error를 던진다. scope runtime은 그 실패를 `failed = true`로만 받아 scope를
`FAILED`에 둔다. 그동안 모든 서버 요청이 `SCOPE_FENCED`로 막히는데 진단
기록은 0건이다(리뷰 실험 E-3). 계약의 `ProductScopeParticipant.label`을
읽는 코드도 없다. 개발자는 "로그아웃 뒤 앱이 요청을 안 보낸다"만 보고 원인
closer를 찾으려면 closer를 하나씩 지워 봐야 한다.

고른 방법(리뷰 대안 (다)):
- scope runtime이 reset의 실패 단계마다 `cache.operation.failed`를 하나
  남긴다. `operation: "SCOPE_RESET"`, `reason`은 `PARTICIPANT_FAILED`·
  `CACHE_RESET_FAILED`·`GENERATION_ACTIVATION_FAILED`(+ 목록 함수가 던질
  때 `PARTICIPANTS_UNREADABLE`), `error_kind`, participant 실패면
  `scope_participant: <label>`. template participant 실패도 같은 길로
  남는다.
- 진단 계약에 `scope_participant` 키를 더한다(cardinality `topology`,
  값 정책 `isScopeParticipantLabel` = 소문자 kebab-case 48자 이하). label은
  제품 코드가 고른 문자열이라 projection이 받는 닫힌 토큰으로 제한했다.
- 제품 closer를 wrapper 하나로 감싸지 않고 각자 order 10 participant로
  넘긴다. 그래서 `participants`가 reset마다 읽는 함수도 받는다
  (`ServerStateScopeDependencies`, 배열은 그대로 받는다). 순서와 "하나가
  실패해도 나머지를 부른다"는 그대로다.
- 조립은 형식에 맞지 않는 제품 label을 `TypeError`로 거절한다. 부팅에서
  바로 드러나야 진단에서 label이 빠지는 일이 없다.

버린 대안:
- (가) 문서에 "closer는 던지지 않게 쓴다"만 적기: 결함이 그대로다.
- (나) wrapper만 제품 label을 기록: template participant 실패는 계속
  조용하고, 한 실패가 wrapper와 runtime에서 두 번 기록된다.
- label을 `operation`이나 `reason` 값에 섞기: 계약 변경은 없지만 그 키의
  뜻이 흐려진다.

위험·한계:
- 진단 계약(`src/contracts/diagnostics.ts`)에 키 하나, 함수 하나가 더해진다.
  더하기만 해서 호환은 깨지지 않는다. CHANGELOG [계약] 행이 필요하다.
- 제품 label 형식이 좁아졌다. `Browser Files` 같은 label을 쓰던 제품은
  부팅에서 `TypeError`가 난다. 저장소 안의 label(`browser-files`, 테스트의
  label)은 모두 맞는다.
- 화면이 `FAILED`를 어떻게 보이는지는 바꾸지 않았다(영역 08·09).

검증: desktop batch에서 확인
- node scripts/run-vitest.ts run tests/unit/server-state-scope-runtime.test.ts
  tests/unit/runtime-adapters-product-scope-participants.test.ts
  tests/unit/observability-cardinality.test.ts tests/unit/diagnostics.test.ts
- corepack pnpm check:diagnostics
- node scripts/run-vitest.ts run tests/recipes/browser-file-session-capability.test.ts

Refs: 1105/02-01
This commit is contained in:
DongHyeonka
2026-11-05 22:14:54 +09:00
parent 23662fb23a
commit f738348d9d
8 changed files with 267 additions and 34 deletions
@@ -376,6 +376,10 @@ digest 또는 별도 검토된 streaming hash adapter를 사용한다.
`scopeParticipants`로 `dispose()`를 돌려주면 템플릿이 로그아웃·계정 전환마다
FENCED와 READY 사이에서 부르고, 실패하면 READY로 가지 않는다
(`ProductScopeParticipant`, `src/bootstrap/product-composition-contract.ts`).
실패한 close마다 진단 `cache.operation.failed`(`operation: SCOPE_RESET`,
`reason: PARTICIPANT_FAILED`, `scope_participant: <label>`)가 하나 남는다
(1105/02-01). 그래서 `label`은 소문자 kebab-case 토큰이어야 하고, 아니면
조립이 `TypeError`로 멈춘다.
`composeProduct`는 부팅 때 한 번만 불리므로 기능에는 runtime 대신 getter를
주고 그 뒤에서 세대마다 새 runtime을 만든다. 예제는
`recipes/frontend-capabilities/browser-file-session-capability.ts`이고
+2
View File
@@ -106,6 +106,8 @@ release admission refused for staging:
- `product-composition.ts` 안에서 `FeaturePlatformCapabilities`를 보강(`declare module`)하면 `check:types:node`가 그 키를 보지 못한다.
- `src/bootstrap/product-composition.ts`: 위 capability의 값을 돌려줄 때. 제품 인증 프로필의 자격 증명도 여기서 준다.
- 로그아웃·계정 전환 때 닫아야 하는 것(파일 runtime 등)은 `scopeParticipants`로 돌려준다. 예제: `recipes/frontend-capabilities/browser-file-session-capability.ts`.
- `label`은 `browser-files` 같은 소문자 kebab-case 토큰으로 쓴다. 다른 형식이면 조립이 `TypeError`로 멈춘다.
- `close`가 던지면 scope가 `FAILED`에 머물고 모든 서버 요청이 `SCOPE_FENCED`로 막힌다. 진단 `cache.operation.failed`에 `reason: PARTICIPANT_FAILED`와 `scope_participant: <label>`이 남으니 그 기록으로 원인 closer를 찾는다.
- 템플릿 파일 `src/bootstrap/runtime-adapters.ts`는 고치지 않는다.
- 실시간 갱신: 짝 백엔드의 실시간 출구(STOMP·NDJSON)와 프론트 realtime 어댑터(SSE·`realtime.v1` WebSocket)는 그대로 연결되지 않는다. 지금 되는 경로는 bounded polling이다. 대응표: [realtime 설계 0.1절](../architecture/realtime-events-web-push-and-bounded-polling.md#01-짝-백엔드-템플릿과의-대응-110304-02).
- `src/contracts/product-contracts.ts`: 제품 인증 프로필이나 제품 런타임 설정 키가 필요할 때.
@@ -1,5 +1,9 @@
import type { AuthSessionPort } from "../../application/ports/auth-session-port.ts";
import type { DiagnosticsPort } from "../../application/ports/diagnostics-port.ts";
import {
isScopeParticipantLabel,
safeErrorKind,
} from "../../contracts/diagnostics.ts";
import type { QueryInvalidationCoordinator } from "../../contracts/query-invalidation.ts";
import {
createRuntimeIdentityRegistry,
@@ -20,6 +24,11 @@ import type {
export type ScopeResetParticipant = Readonly<{
/** Lower runs earlier; the §10.6 step number is used as the rank. */
order: number;
/**
* 1105/02-01. Names the participant in the diagnostic a failed close
* records (`scope_participant`). Use a lowercase kebab-case token
* (`isScopeParticipantLabel`); any other is left out of that record.
*/
label: string;
close(): void | Promise<void>;
}>;
@@ -32,10 +41,20 @@ export type ServerStateScopeDependencies = Readonly<{
session: Pick<AuthSessionPort, "subscribe"> &
Partial<Pick<AuthSessionPort, "getState" | "getSubject">>;
queryInvalidation: Pick<QueryInvalidationCoordinator, "resetLocal">;
/** Hears about an authenticated session that could not name its subject. */
/**
* Hears about an authenticated session that could not name its subject, and
* about every step of a reset that failed (1105/02-01).
*/
diagnostics?: DiagnosticsPort;
tokenFactory?: () => string;
participants?: readonly ScopeResetParticipant[];
/**
* The closers, or a function read at each reset (1105/02-01): composition
* that learns some of them only after the runtime exists, such as the
* product's, passes the function instead of wrapping them in one closer.
*/
participants?:
| readonly ScopeResetParticipant[]
| (() => readonly ScopeResetParticipant[]);
activateNextGeneration?: () => void | Promise<void>;
}>;
@@ -46,9 +65,11 @@ export function createServerStateScopeRuntime(
const lifecycleListeners = new Set<
(event: ClientScopeLifecycleEvent) => void
>();
const participants = [...(dependencies.participants ?? [])].sort(
(left, right) => left.order - right.order,
);
const listParticipants = dependencies.participants;
const fixedParticipants =
typeof listParticipants === "function"
? undefined
: orderParticipants(listParticipants ?? []);
let generation = 1;
let identities = newIdentityRegistry(dependencies.tokenFactory);
@@ -132,18 +153,39 @@ export function createServerStateScopeRuntime(
.catch(() => {})
.then(async () => {
let failed = false;
// 1105/02-01. Each failed step is recorded once, with the label of
// the participant that threw. A FAILED scope fences every request, and
// without this nothing said which closer kept it there.
const report = (
reason: ScopeResetFailureReason,
error: unknown,
label?: string,
) => reportResetFailure(dependencies.diagnostics, reason, error, label);
let participants: readonly ScopeResetParticipant[] = [];
try {
participants =
fixedParticipants ??
orderParticipants(
(listParticipants as () => readonly ScopeResetParticipant[])(),
);
} catch (error) {
failed = true;
report("PARTICIPANTS_UNREADABLE", error);
}
// Steps 4-11: close admission, cancel and clear, release leases.
for (const participant of participants) {
try {
await participant.close();
} catch {
} catch (error) {
failed = true;
report("PARTICIPANT_FAILED", error, participant.label);
}
}
try {
await dependencies.queryInvalidation.resetLocal();
} catch {
} catch (error) {
failed = true;
report("CACHE_RESET_FAILED", error);
}
previousIdentities.close();
@@ -152,8 +194,9 @@ export function createServerStateScopeRuntime(
if (!failed) {
try {
await dependencies.activateNextGeneration?.();
} catch {
} catch (error) {
failed = true;
report("GENERATION_ACTIVATION_FAILED", error);
}
}
if (disposed || generation !== targetGeneration) return;
@@ -236,6 +279,40 @@ function readSessionIdentity(
}
}
function orderParticipants(
participants: readonly ScopeResetParticipant[],
): readonly ScopeResetParticipant[] {
return [...participants].sort((left, right) => left.order - right.order);
}
type ScopeResetFailureReason =
| "PARTICIPANTS_UNREADABLE"
| "PARTICIPANT_FAILED"
| "CACHE_RESET_FAILED"
| "GENERATION_ACTIVATION_FAILED";
function reportResetFailure(
diagnostics: DiagnosticsPort | undefined,
reason: ScopeResetFailureReason,
error: unknown,
label: string | undefined,
): void {
try {
diagnostics?.record({
level: "warn",
eventId: "cache.operation.failed",
context: {
operation: "SCOPE_RESET",
reason,
error_kind: safeErrorKind(error),
...(isScopeParticipantLabel(label) ? { scope_participant: label } : {}),
},
});
} catch {
// The reset ends FAILED whether or not diagnostics works.
}
}
function reportSubjectMissing(diagnostics: DiagnosticsPort | undefined): void {
try {
diagnostics?.record({
@@ -98,6 +98,14 @@ export type ProductCompositionContext = Readonly<{
* or rejects keeps the scope from reaching READY, as the template's own do.
*/
export type ProductScopeParticipant = Readonly<{
/**
* 1105/02-01. A lowercase kebab-case token such as `browser-files`
* (`isScopeParticipantLabel` in `src/contracts/diagnostics.ts`). A close
* that throws or rejects records `cache.operation.failed` with
* `operation: "SCOPE_RESET"`, `reason: "PARTICIPANT_FAILED"` and this label
* as `scope_participant`, so the stuck scope names its cause. Composition
* throws a `TypeError` on any other label.
*/
label: string;
close(): void | Promise<void>;
}>;
+32 -25
View File
@@ -13,6 +13,7 @@ import {
import {
attemptBucket,
durationBucket,
isScopeParticipantLabel,
statusGroup,
type DiagnosticRecordInput,
} from "../contracts/diagnostics.ts";
@@ -390,37 +391,34 @@ export async function createRuntimeAdapters(
});
});
// 2026-11-03 02-01. The product's closers. `composeProduct` runs after the
// scope exists (its context needs the fence), so they join through this one
// slot, filled below. Each runs even when an earlier one fails, and any
// failure keeps the scope from READY, as for the template's own.
// scope exists (its context needs the fence), so they join through this
// list, filled below, which the scope reads at each reset. Each runs even
// when an earlier one fails, and any failure keeps the scope from READY, as
// for the template's own. 1105/02-01. Each is its own participant at the
// offline-lease step (10), so a failed close is recorded under its label.
const productScopeParticipants: ProductScopeParticipant[] = [];
const templateScopeParticipants = Object.freeze([
Object.freeze({
order: 4,
label: "conditional-validators",
close: () => conditionalValidators.clear(),
}),
]);
const serverStateScope = createServerStateScopeRuntime({
session: authSession,
diagnostics,
queryInvalidation: {
resetLocal: () => serverStateGeneration.resetCurrent(),
},
participants: [
{
order: 4,
label: "conditional-validators",
close: () => conditionalValidators.clear(),
},
{
order: 10,
label: "product",
async close() {
let failed = false;
for (const participant of productScopeParticipants) {
try {
await participant.close();
} catch {
failed = true;
}
}
if (failed) throw new Error("A product scope participant failed.");
},
},
participants: () => [
...templateScopeParticipants,
...productScopeParticipants.map((participant) =>
Object.freeze({
order: 10,
label: participant.label,
close: () => participant.close(),
}),
),
],
activateNextGeneration: () => serverStateGeneration.activateNext(),
});
@@ -678,7 +676,16 @@ export async function createRuntimeAdapters(
const productContract: ProductComposition = product;
const productCredentialProviders = productContract.credentialProviders;
const onProductCredentialRejected = productContract.onCredentialRejected;
productScopeParticipants.push(...(productContract.scopeParticipants ?? []));
for (const participant of productContract.scopeParticipants ?? []) {
// 1105/02-01. The label names the participant in diagnostics, so it must
// be a token the diagnostic projection keeps.
if (!isScopeParticipantLabel(participant.label)) {
throw new TypeError(
"A product scope participant label must be a lowercase kebab-case token (isScopeParticipantLabel).",
);
}
productScopeParticipants.push(participant);
}
// Each installed contribution receives only the capabilities it declares.
// The template's own capabilities come last, so a product cannot replace
// them. 09-05. `indexedDb` is not built here: IndexedDB is an opt-in
+15
View File
@@ -44,6 +44,7 @@ export const DIAGNOSTIC_CONTEXT_ALLOWLIST = Object.freeze([
"queue_size_bucket",
"feature_override_key",
"effect_certainty",
"scope_participant",
] as const);
export type DiagnosticContextKey =
(typeof DIAGNOSTIC_CONTEXT_ALLOWLIST)[number];
@@ -90,6 +91,9 @@ export const DIAGNOSTIC_CONTEXT_CARDINALITY = Object.freeze({
feature_override_key: "deployment",
// 1103/03-05. The V3 effect certainty, five values.
effect_certainty: "bounded",
// 1105/02-01. The label of a scope reset participant, set in source by the
// template or the product composition, never by traffic.
scope_participant: "topology",
} satisfies Readonly<Record<DiagnosticContextKey, DiagnosticCardinalityClass>>);
export type DiagnosticContext = Readonly<
@@ -118,6 +122,7 @@ const BOUNDED_CONTEXT_VALUE_POLICIES: Readonly<
queue_size_bucket: (value) =>
typeof value === "string" && /^(?:0|1-10|11-50|51\+)$/.test(value),
effect_certainty: isEffectCertainty,
scope_participant: isScopeParticipantLabel,
});
/**
@@ -133,6 +138,16 @@ export function isEffectCertainty(value: unknown): value is string {
);
}
/**
* 1105/02-01. A scope reset participant's label: a lowercase kebab-case token
* of at most 48 characters that starts with a letter. A failed close is
* recorded under it (`scope_participant`), so the label must pass this
* projection; product composition refuses any other.
*/
export function isScopeParticipantLabel(value: unknown): value is string {
return typeof value === "string" && /^[a-z][a-z0-9-]{0,47}$/.test(value);
}
export type DiagnosticRecordInput = Readonly<{
level: DiagnosticLevel;
eventId: DiagnosticEventId;
@@ -103,7 +103,11 @@ async function compose() {
});
const owner = fixture.owner;
if (!owner) throw new Error("The product session owner was not asked");
return { scope: current.infrastructure.serverStateScope, owner };
return {
scope: current.infrastructure.serverStateScope,
owner,
diagnostics: current.outputPorts.diagnostics,
};
}
describe("product scope participants (2026-11-03 02-01)", () => {
@@ -150,4 +154,51 @@ describe("product scope participants (2026-11-03 02-01)", () => {
await vi.waitFor(() => expect(scope.getPhase()).toBe("FAILED"));
expect(closed).toEqual(["after"]);
});
// 1105/02-01 (E-3). A failing closer left the scope FAILED, every request
// SCOPE_FENCED, and no diagnostic at all: the label was never read.
it("records which participant kept the scope from READY, on every retry", async () => {
fixture.participants = [
{
label: "broken-closer",
close() {
throw new Error("cannot close");
},
},
{ label: "fine-closer", close() {} },
];
const { scope, owner, diagnostics } = await compose();
const resetFailures = () =>
diagnostics
.entries()
.filter(
(entry) =>
entry.eventId === "cache.operation.failed" &&
entry.context.operation === "SCOPE_RESET",
)
.map((entry) => entry.context);
owner.switchUser("user-b");
await vi.waitFor(() => expect(scope.getPhase()).toBe("FAILED"));
expect(resetFailures()).toEqual([
{
operation: "SCOPE_RESET",
reason: "PARTICIPANT_FAILED",
error_kind: "ERROR",
scope_participant: "broken-closer",
},
]);
// The same identity retries a FAILED reset; it fails and says so again.
owner.switchUser("user-b");
await vi.waitFor(() => expect(resetFailures()).toHaveLength(2));
await vi.waitFor(() => expect(scope.getPhase()).toBe("FAILED"));
expect(resetFailures()[1]).toMatchObject({ scope_participant: "broken-closer" });
});
it("refuses a participant label the diagnostics could not carry", async () => {
fixture.participants = [{ label: "Browser Files", close() {} }];
await expect(compose()).rejects.toThrow(TypeError);
});
});
@@ -113,9 +113,26 @@ describe("server-state session generation runtime", () => {
await vi.waitFor(() => expect(runtime.getPhase()).toBe("READY"));
});
// 1105/02-01. Each failure below is also recorded, with the participant's
// label when a participant threw; it used to leave no trace.
const resetFailure = (
reason: string,
participant?: string,
): DiagnosticRecordInput => ({
level: "warn",
eventId: "cache.operation.failed",
context: {
operation: "SCOPE_RESET",
reason,
error_kind: "ERROR",
...(participant ? { scope_participant: participant } : {}),
},
});
it("remains failed when a mandatory participant cannot close", async () => {
let sessionListener: () => void = () => {};
const resetLocal = vi.fn(async () => {});
const record = vi.fn<(input: DiagnosticRecordInput) => void>();
const runtime = createServerStateScopeRuntime({
session: {
subscribe(listener) {
@@ -126,6 +143,7 @@ describe("server-state session generation runtime", () => {
queryInvalidation: {
resetLocal,
},
diagnostics: { record },
participants: [
{
order: 4,
@@ -145,10 +163,14 @@ describe("server-state session generation runtime", () => {
expect(runtime.getPhase() as string).toBe("FAILED"),
);
expect(runtime.getSnapshot().isCurrent()).toBe(false);
expect(record.mock.calls).toEqual([
[resetFailure("PARTICIPANT_FAILED", "mandatory-admission")],
]);
});
it("remains failed when local cache reset rejects", async () => {
let sessionListener: () => void = () => {};
const record = vi.fn<(input: DiagnosticRecordInput) => void>();
const runtime = createServerStateScopeRuntime({
session: {
subscribe(listener) {
@@ -161,6 +183,7 @@ describe("server-state session generation runtime", () => {
throw new Error("reset failed");
},
},
diagnostics: { record },
tokenFactory: () => "scope-reset-token-0000001",
});
@@ -170,11 +193,53 @@ describe("server-state session generation runtime", () => {
expect(runtime.getPhase() as string).toBe("FAILED"),
);
expect(runtime.getSnapshot().isCurrent()).toBe(false);
expect(record.mock.calls).toEqual([[resetFailure("CACHE_RESET_FAILED")]]);
});
it("reads a participant list function at each reset and records a label it cannot carry without it", async () => {
let sessionListener: () => void = () => {};
const record = vi.fn<(input: DiagnosticRecordInput) => void>();
const closed: string[] = [];
const later: { order: number; label: string; close(): void }[] = [];
const runtime = createServerStateScopeRuntime({
session: {
subscribe(listener) {
sessionListener = listener;
return () => {};
},
},
queryInvalidation: { resetLocal: async () => {} },
diagnostics: { record },
participants: () => [
{ order: 4, label: "admission", close: () => void closed.push("admission") },
...later,
],
tokenFactory: () => "scope-participant-list-0001",
});
// Joins after the runtime exists, as the product's closers do.
later.push({
order: 10,
label: "Not A Token",
close() {
closed.push("late");
throw new Error("late close failed");
},
});
sessionListener();
await vi.waitFor(() =>
expect(runtime.getPhase() as string).toBe("FAILED"),
);
expect(closed).toEqual(["admission", "late"]);
// Still recorded, without the label the projection would refuse.
expect(record.mock.calls).toEqual([[resetFailure("PARTICIPANT_FAILED")]]);
});
it("activates the next generation after reset and fails closed on activation error", async () => {
let sessionListener: () => void = () => {};
const steps: string[] = [];
const record = vi.fn<(input: DiagnosticRecordInput) => void>();
const runtime = createServerStateScopeRuntime({
session: {
subscribe(listener) {
@@ -191,6 +256,7 @@ describe("server-state session generation runtime", () => {
steps.push("activate");
throw new Error("activation failed");
},
diagnostics: { record },
tokenFactory: () => "scope-activation-token-001",
} as Parameters<typeof createServerStateScopeRuntime>[0] & {
activateNextGeneration(): Promise<void>;
@@ -202,6 +268,9 @@ describe("server-state session generation runtime", () => {
await vi.waitFor(() =>
expect(runtime.getPhase() as string).toBe("FAILED"),
);
expect(record.mock.calls).toEqual([
[resetFailure("GENERATION_ACTIVATION_FAILED")],
]);
});
});