chore(review): 1105 브라우저 파일·캐시·저장소 조치 브랜치를 합친다

This commit is contained in:
DongHyeonka
2026-11-06 02:59:01 +09:00
27 changed files with 1348 additions and 273 deletions
+1 -1
View File
@@ -373,7 +373,7 @@
},
"consumerIdentityField": "logicalName",
"consumerDirectories": ["src", "tests"],
"orphanExemptRows": ["QUERY_PERSISTENCE", "AUTH_TOKEN"],
"orphanExemptRows": ["QUERY_PERSISTENCE", "AUTH_TOKEN", "AUTH_REDIRECT_TRANSACTION"],
"breakingFields": [
"logicalName",
"physicalKey",
@@ -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`이고
@@ -965,6 +969,20 @@ build-produced manifest
```
한 entry라도 실패하면 candidate는 incomplete이며 active로 전환하지 않는다.
이미 있는 candidate를 같은 manifest로 다시 stage하면 entry를 하나씩 다시
검증한다. 모두 맞으면 그대로 쓴다. entry가 없거나 바이트·헤더가 manifest와
다르면(`INTEGRITY_FAILED`·`CORRUPT_DATA`·`POLICY_REJECTED`·`LIMIT_EXCEEDED`)
모든 asset을 다시 받아 같은 cache에 덮어쓴다. entry는 있는데 저장된 본문을
읽지 못해도(`UNAVAILABLE`·`NOT_READABLE` 등) 같은 길로 다시 쓴다(1105/02-02).
본문 읽기 실패는 손상의 증거가 아니라서 activation은 그 code를 그대로
돌려주지만, recovery는 `REHYDRATE`(같은 manifest로 다시 stage)다. 다시 쓰기
전까지 계속 읽히지 않는 entry(blob 손실 등)는 이 길로만 돌아온다. rollback
대상 release와 서비스 중인 release도 같다. 덮어쓰는 바이트는 digest로 검증한
같은 바이트이고 cache를 지우지 않으므로, 서비스 중인 release를 해치지 않는다.
일시 오류에서는 다시 받는 비용이 든다. 중단(`ABORTED`)과 `cache.match` 자체의
실패는 다시 쓰지 않고 실패를 돌려준다. 조회(`matchActiveExact`)의 본문 읽기
실패는 그대로 `UNAVAILABLE`/`RETRY`다.
static Cache-only 조합은 waiting worker, `skipWaiting()`, `clients.claim()` 또는
controlled-client drain을 activation 전제나 성공 증거로 사용하지 않는다.
composition owner가 exact release ID와 manifest digest로
+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
View File
@@ -44,6 +44,7 @@
- `fetcher`는 마감이 없다. owner에서 쓰지 않는다. 응답하지 않는 호출 하나가 세션을 "복구 중"에 영원히 둔다.
- `page`: 지금 URL, URL 바꾸기, 다른 페이지로 이동. 로그인 리다이렉트에 쓴다.
- `redirectStorage`: 페이지의 sessionStorage. 리다이렉트 한 번 동안의 상태만 둔다. 토큰은 두지 않는다(`AUTH_TOKEN`은 `src/contracts/storage-keys.ts`에서 `forbidden`이다).
- 키는 registry의 `AUTH_REDIRECT_TRANSACTION`(`backend: "external"`)에서 가져온다. 그래야 `APP_NAMESPACE`를 바꿀 때 같이 바뀐다. 새 owner도 키를 글자로 적지 않는다.
- `readCookie`: 페이지 쿠키 읽기.
4. recipe는 `src/bootstrap/` 아래로 **복사**한다. import하지 않는다.
- `src`가 `recipes/`를 import하면 `check:optional-recipes`가 `PRODUCTION_IMPORTS_RECIPE`로 막는다.
@@ -40,23 +40,24 @@ cleanup 결과를 확인하지 못하면 성공 값이 아니라 실패로 답
계속 돌고, 관측은 `OBJECT_RECONCILE` `DEGRADED` / `CORRUPT_DATA`로 남는다
([0929] 05-01). reconcile은 그 row를 지우지 않는다. 그 partition이 승인된
purge로 통째로 지워질 때 함께 지워지는 것은 partition 키(`logicalKey`)를
읽을 수 있는 row뿐이다(§7). 승인된 LOGOUT/ACCOUNT_DELETION purge는 그런
row를 보면 그 partition을 지운다(2026-11-03 05-01).
읽을 수 있는 row뿐이다(§7). 승인된 LOGOUT/ACCOUNT_DELETION purge는 객체를
끝까지 돌면 늘 그 partition을 지운다(1103/05-01 잔여).
- `unattributedCorruptTransactions`: 위 수 가운데 `logicalKey`까지 읽을 수
없는 row 수다. 어느 partition에도 속하지 않아 partition 삭제도 지우지
못한다. 그래서 따로 세고 `DEGRADED` 관측에서 뺀다(2026-11-03 05-03). 예전에는
이런 row 하나가 reconcile마다 `DEGRADED`를 남겨 경보가 늘 켜졌다. 같은 수로
남아 있으면 할 일이 없다. 수가 늘면 키 없는 row를 쓴 writer(다른 release,
외부 도구)를 찾는다. 이 row도 수동으로 지우지 않는다(3번). 그 row의
staging은 partition 디렉터리 안에 있어 그 partition이 지워지면 함께
지워지지만, 이 row는 purge의 partition 삭제 조건에 들지 않는다.
staging은 partition 디렉터리 안에 있어 승인된 purge가 그 partition을
지울 때 함께 지워진다. 예전에는 purge가 이 row를 세지 못해 chunk sweep으로
끝났고, staging receipt가 지킨 chunk·manifest가 `COMPLETED` 뒤에도
남았다(1103/05-01 잔여).
3. journal row를 수동으로 삭제하지 않는다. row가 사라지면 stale staging을 추적할
근거가 사라지고 quota만 누수된다.
4. OPFS root나 journal database를 통째로 삭제하거나 schema를 downgrade하지
않는다. rollback은 새 v2 write admission을 닫고 v1+v2 reader를 유지하는 것으로
수행한다. runtime이 스스로 지우는 것은 승인된 purge가 손상이나 끝나지 않은
transaction 때문에 끝나지 못할 때의 그 partition 디렉터리 하나와 그 partition의
journal row뿐이다(§7).
수행한다. runtime이 스스로 통째로 지우는 것은 승인된 LOGOUT/ACCOUNT_DELETION
purge의 그 partition 디렉터리 하나와 그 partition의 journal row뿐이다(§7).
## 1. 공통 원칙
@@ -450,27 +451,33 @@ VD-15 목표 runtime을 먼저 구현한다.
- `COMMITTED` + file missing/corrupt: reconstructable만 server rehydrate;
user-created private는 read-only/export/recovery
- stale staging/orphan chunk는 grace period와 bounded mark/sweep 후 제거
- `LOGOUT`/`ACCOUNT_DELETION` purge는 객체를 모두 지운 뒤 그 partition의 journal
row를 센다. 하나라도 있으면(다른 tab에서 진행 중인 put·delete, crash가 남긴
`PREPARING`·`FILES_READY`, 키는 읽히는 손상 row) sweep 대신 아래 partition
삭제로 간다(2026-11-03 05-01). 예전에는 이 row를 보지 않고 `COMPLETED`를
돌려줬다. 그래서 진행 중 put의 객체가 purge 뒤에도 읽혔고, `FILES_READY` row는
다음 reconcile이 commit해 객체로 되살렸다. row가 없으면 그 partition의 chunk를
grace 없이 sweep한다(05-04, `opfs-byte-store-adapter.ts` `enforcePolicies`).
staging receipt가 참조하는 chunk는 이때도 지우지 않는다. 이 두 reason에서는
report의 `chunkSweep`이 `COMPLETED`이거나 `partitionDeleted`가 있을 때 그
partition의 bytes가 지워진 것이다. `DEADLINE_REACHED`면 같은
purge를 다시 호출하고, `STAGING_STATE_UNREADABLE`이면 읽을 수 없는 staging부터
처리한다. 다른 탭이 바꾸고 있던 객체를 지우지 못하면 report는
`moreObjectsAvailable: true`이고 `chunkSweep`이 없다. 이때도 같은 purge를 다시
호출한다([0929] 05-02)
- 손상이나 끝나지 않은 transaction 때문에 끝나지 못하는 `LOGOUT`/
`ACCOUNT_DELETION` purge는 partition을 통째로 지운다([0929] 05-01,
2026-11-03 05-01, `opfs-byte-store-adapter.ts` `enforcePolicies`).
- `LOGOUT`/`ACCOUNT_DELETION` purge는 객체를 하나씩 지운 뒤, 마지막 객체까지
돌았으면 늘 아래 partition 삭제로 끝낸다(1103/05-01 잔여,
`opfs-byte-store-adapter.ts` `enforcePolicies`). chunk sweep으로 끝내지 않는다.
- 예전 동작: 객체를 다 돈 뒤 journal row를 한 번 세고, 0이면 chunk를 grace 없이
sweep해 `chunkSweep: "COMPLETED"`를 돌려줬다(05-04, 2026-11-03 05-01). 목록과
세기는 각각 한 순간만 본다. 그래서 두 경우에 bytes가 남은 채 `COMPLETED`였다.
① 다른 tab이 새 객체를 put하는 중이고 partition에 객체가 3개 이상이면, 그 put이
목록 뒤에 commit하고 세기 전에 끝났다. 목록에도 row 수에도 없어 sweep이 그
chunk를 건너뛰었고, 그 파일이 계정 삭제 뒤에도 읽혔다(메모리 20/20, Chromium
6/6). ② 멈춘 put의 journal row가 `logicalKey`를 잃으면 세지 못했고, 그
staging receipt·chunk·manifest가 purge마다 남았다.
- 이제 결과: 그 partition의 bytes가 지워진 것은 report에 `partitionDeleted`가
있을 때다. `chunkSweep`은 더 이상 채우지 않는다(port 타입에는 호환을 위해
남겼다).
- 예산(`budgetMs`·`maxObjects`)이나 다른 tab의 변경 때문에 객체를 끝까지 돌지
못하면 report는 `moreObjectsAvailable: true`이고 `partitionDeleted`가 없다.
같은 purge를 다시 호출한다([0929] 05-02). 다만 이때 그 partition의 journal
row(다른 tab에서 진행 중인 put·delete, crash가 남긴 `PREPARING`·`FILES_READY`,
키는 읽히는 손상 row)가 하나라도 있으면 그 호출이 바로 partition을 지운다
(2026-11-03 05-01).
- 승인된 `LOGOUT`/`ACCOUNT_DELETION` purge의 partition 삭제([0929] 05-01,
2026-11-03 05-01, 1103/05-01 잔여, `opfs-byte-store-adapter.ts`
`enforcePolicies`).
- 조건: 정책이 그 reason을 허용하고, authority가 이번 purge의 proof를 내주고
consumer가 소비했을 때(IndexedDB의 database 전체 삭제와 같은 승인). 그리고
다음 중 하나를 만났을 때: 목록에서 건너뛴 손상 object row, 손상 row 때문에
`CORRUPT_DATA`로 끝난 remove나 chunk sweep, `STAGING_STATE_UNREADABLE`, 그
다음 중 하나일 때: 마지막 객체까지 돌았다, 목록에서 건너뛴 손상 object row,
손상 row 때문에 `CORRUPT_DATA`로 끝난 remove, 끝까지 돌지 못한 호출에서 그
partition 키를 가진 journal row(`countPartitionTransactions`가 1 이상).
TTL·SESSION_END·UNTIL_SYNCED·PRESSURE는 손상 row를 건너뛰고 세기만 한다.
- 범위: worker가 origin mutation lease를 쥔 채
@@ -482,8 +489,9 @@ VD-15 목표 runtime을 먼저 구현한다.
row는 남긴다. 다른 partition은 건드리지 않는다.
- 결과: `partitionDeleted: true`, `moreObjectsAvailable: false`, 건너뛴 row 수
`corruptObjects`. 이 report면 그 partition의 bytes는 모두 지워진 것이다.
`chunkSweep`은 없다. 디렉터리는 지웠는데 journal 정리가 실패하면 실패를
반환한다. 같은 purge를 다시 호출하면 이어서 끝난다.
`removedObjects`·`releasedBytes`는 삭제 전에 하나씩 지운 객체만 센다.
디렉터리는 지웠는데 journal 정리가 실패하면 실패를 반환한다. 같은 purge를
다시 호출하면 이어서 끝난다.
- 다른 tab의 put·delete와의 순서: 모든 put·delete는 journal `begin`부터 끝날
때까지 partition lock(Web Lock
`<mutationLockName>:partition:<authorityToken>:<namespaceToken>:<partitionToken>`)을
@@ -504,9 +512,10 @@ VD-15 목표 runtime을 먼저 구현한다.
멈추고 `ABORTED`를 반환한다. 삭제 뒤에 줄 선 put·delete도 자기 `signal`로
기다림을 멈춘다. 어느 쪽이든 partition lock 기다림은
`mutationLockWaitTimeoutMs`(기본 10분)에서 `BLOCKED`(retryable)로 끝난다
(2026-11-03 05-02). purge가 journal row를 센 뒤에 시작한 put, 삭제가
lock을 요청한 뒤 온 put의 데이터는 남는다(point-in-time). purge 전에 그
partition의 쓰기를 멈추는 것이 composition의 몫이다.
(2026-11-03 05-02). 삭제가 lock을 요청한 뒤 온 put의 데이터는 남는다
(point-in-time). 그 전에 시작한 put은 삭제가 기다렸다가 함께 지운다.
모든 승인 purge가 이제 이 lock을 기다리므로, 다른 tab에서 오래 걸리는 put이
있으면 purge도 그만큼 늦게 끝난다.
- lock/worker 문제면 OPFS write off → approved capped fallback 또는 online-only
- scope binding mismatch면 affected scope를 read-only로 격리하고 registry/
composition을 forward fix; 다른 token path로 bytes를 이동하거나 추측 복구 금지
@@ -20,8 +20,17 @@ export type SessionBrowserFiles = Readonly<{
*
* file-transfer is an opt-in recipe (`productionComposition: false`), so the
* template does not build this. A product that installs a feature using it
* augments `FeaturePlatformCapabilities` with `files: SessionBrowserFiles` and
* returns both halves from `src/bootstrap/product-composition.ts`:
* types the capability in `src/features/product-capabilities.ts`, as
* `docs/manual/03-outside-feature-folder.md` says:
*
* export interface ProductFeaturePlatformCapabilities {
* readonly files: SessionBrowserFiles;
* }
*
* not with a `declare module` augmentation of `FeaturePlatformCapabilities`,
* whose key `check:types:node` does not see (1105/02-03). The feature lists
* `files` in `needs`, and the product returns both halves from
* `src/bootstrap/product-composition.ts`:
*
* const browserFiles = createSessionBrowserFileCapability(() =>
* createBrowserFileRuntime({ input, policies, limits, download }),
@@ -1652,8 +1652,9 @@ type MemoryDurableObjectStoreOptions = Readonly<{
* a journal row, and a LOGOUT or ACCOUNT_DELETION the policy allows leaves the
* partition empty. `reconcile` rolls a row that stopped while PREPARING back
* and commits one that stopped after FILES_READY, like the runtime's
* roll-forward; such a purge also drops every stopped row and reports
* `partitionDeleted` (2026-11-03 05-01, 05-04).
* roll-forward; such a purge also drops every stopped row. Every purge
* reports `partitionDeleted`, never a chunk sweep (2026-11-03 05-01, 05-04,
* 1103/05-01 rest).
*
* It does not model the worker, Web Locks, the composition authority, chunk
* dedup, orphan GC or the other maintenance reasons (`UNSUPPORTED`). Its
@@ -1926,8 +1927,9 @@ export class MemoryDurableObjectStore
const removedObjects = this.#objects.size;
this.#objects.clear();
// 2026-11-03 05-01. A stopped put goes with the partition, as the
// runtime's partition delete takes its row and its files.
const partitionDeleted = this.#pending.size > 0;
// runtime's partition delete takes its row and its files. 1103/05-01
// rest: the runtime ends every purge that walked all objects in that
// delete, so this one always reports it.
this.#pending.clear();
return dataSuccess(
Object.freeze({
@@ -1936,9 +1938,7 @@ export class MemoryDurableObjectStore
releasedBytes,
moreObjectsAvailable: false,
deadlineReached: false,
...(partitionDeleted
? { partitionDeleted: true as const }
: { chunkSweep: "COMPLETED" as const }),
partitionDeleted: true as const,
}),
);
}
@@ -8,6 +8,7 @@ import type {
ProductSessionOwnerPage,
SessionOwnerFetch,
} from "../../src/bootstrap/product-composition-contract.ts";
import { STORAGE_REGISTRY } from "../../src/contracts/storage-keys.ts";
/**
* 1103/09-03. A session owner for the paired backend's JWT mode
@@ -40,8 +41,15 @@ import type {
* shows the realm client and the wiring.
*/
/** `buildPhysicalKey("auth", 1, "oidc-pkce-transaction")`; never a token. */
export const OIDC_PKCE_TRANSACTION_KEY = "ca-frontend:auth:v1:oidc-pkce-transaction";
/**
* The sessionStorage key of the sign-in transaction; never a token.
* 1105/05-01. It comes from the storage registry
* (`AUTH_REDIRECT_TRANSACTION`, `backend: "external"`), so it follows the
* app's `APP_NAMESPACE` like every other Web Storage key. It used to be a
* literal that kept `ca-frontend:` after a product renamed the namespace.
*/
export const OIDC_PKCE_TRANSACTION_KEY =
STORAGE_REGISTRY.AUTH_REDIRECT_TRANSACTION.physicalKey;
export type OidcPkceSessionOwnerOptions = Readonly<{
/** Exact issuer, e.g. `http://localhost:8081/realms/ca-skeleton`. HTTPS off this machine. */
@@ -490,12 +490,20 @@ export function createPublicResponseCacheAdapter(
return browserDataSuccess(summaryFromMarker(marker.value));
}
if (verified.kind === "UNKNOWN") {
// Abort or an unreadable candidate is never stage success and
// never silently deletes an owned candidate. 2026-11-01
// 02-03: the verdict is shared with activation, so the
// failure is re-labelled as this stage call's own.
// Abort or a Cache Storage that cannot be asked is never
// stage success and never silently deletes an owned
// candidate. 2026-11-01 02-03: the verdict is shared with
// activation, so the failure is re-labelled as this stage
// call's own.
return rebaseFailure(verified.failure.error, "CACHE_STAGE");
}
// 1105/02-02. A damaged entry, and also one whose stored body
// cannot be read, is written again below. An entry that stays
// unreadable until it is rewritten had no other way back: the
// retry it was told to make met the same entry, and a rollback
// target that cleanup keeps could never be activated again.
// Writing digest-verified bytes over it deletes nothing, so a
// release that is serving traffic keeps serving.
}
}
@@ -684,6 +692,17 @@ export function createPublicResponseCacheAdapter(
"CACHE_ACTIVATE",
);
}
if (candidate.kind === "UNREADABLE") {
// 1105/02-02. Still not reported as damage, but the way out is
// to stage the same manifest again, which rewrites the entry.
return rebaseFailure(
Object.freeze({
...candidate.failure.error,
recovery: "REHYDRATE" as const,
}),
"CACHE_ACTIVATE",
);
}
if (candidate.kind === "REPAIRABLE") {
return browserDataFailure(
"INTEGRITY_FAILED",
@@ -1077,7 +1096,13 @@ type ReleaseCandidateVerdict =
| Readonly<{ kind: "VERIFIED" }>
/** An exact, owned entry is missing or no longer matches the manifest. */
| Readonly<{ kind: "REPAIRABLE" }>
/** Abort or an unreadable candidate: never success, never a silent delete. */
/**
* 1105/02-02. An entry is there but reading its stored body failed
* (UNAVAILABLE, NOT_READABLE, ...). That says nothing about the bytes, so
* it is no damage; staging the same manifest writes the entry again.
*/
| Readonly<{ kind: "UNREADABLE"; failure: BrowserFailureResult }>
/** Abort or a failed lookup: never success, never a silent delete. */
| Readonly<{ kind: "UNKNOWN"; failure: BrowserFailureResult }>;
const REPAIRABLE_READ_CODES: ReadonlySet<string> = new Set([
@@ -1134,14 +1159,15 @@ async function verifyReleaseCandidate(
);
if (!verified.ok) {
// 2026-11-03 02-02. Only a verdict about the stored bytes or headers is
// damage. A body read that failed (UNAVAILABLE, NOT_READABLE, ABORTED)
// says nothing about them, so it stays unknown and is retried.
return REPAIRABLE_READ_CODES.has(verified.error.code)
? Object.freeze({ kind: "REPAIRABLE" as const })
: Object.freeze({
kind: "UNKNOWN" as const,
failure: asFailure(verified),
});
// damage. A body read that failed (UNAVAILABLE, NOT_READABLE) says
// nothing about them (1105/02-02: UNREADABLE); an abort is unknown.
if (REPAIRABLE_READ_CODES.has(verified.error.code)) {
return Object.freeze({ kind: "REPAIRABLE" as const });
}
const failure = asFailure(verified);
return verified.error.code === "ABORTED" || signal?.aborted
? Object.freeze({ kind: "UNKNOWN" as const, failure })
: Object.freeze({ kind: "UNREADABLE" as const, failure });
}
}
return Object.freeze({ kind: "VERIFIED" as const });
@@ -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({
@@ -805,8 +805,7 @@ export function createOpfsByteStoreAdapter(
const sweeping =
request.reason === "LOGOUT" || request.reason === "ACCOUNT_DELETION";
// [0929] 05-01. Rows the journal could not read and skipped, and damage
// met past the listing: a remove or the sweep failing on an unreadable
// row, or staging the sweep cannot read.
// met past the listing: a remove failing on an unreadable row.
let corruptObjects = 0;
let damaged = false;
@@ -888,14 +887,25 @@ export function createOpfsByteStoreAdapter(
}
afterObjectId = page.value.nextObjectId;
}
// 2026-11-03 05-01. A put or delete of this partition that has not
// finished holds bytes the object walk never sees and the sweep skips:
// one running in another tab, or a row a crash left (PREPARING, or
// FILES_READY, which the next reconcile would commit) or nothing can
// read. Any such row sends the purge to the partition delete below,
// which first waits for every live one.
// 1103/05-01 (rest). A walk that reached the last object no longer ends
// in a chunk sweep. The walk and a journal count each see one moment:
// another tab's put of a new object that committed after the listing
// and settled before the count was in neither, and a stopped put whose
// row lost its partition key is never counted. The sweep then skipped
// their chunks and staging and still reported COMPLETED, so the file
// stayed readable after the account deletion. Such a walk now always
// ends in the partition delete below, which waits for every put and
// delete of the partition and takes the whole directory, staging
// included, so nothing that began before it is left.
const walkFinished = !moreObjectsAvailable && !deadlineReached;
// 2026-11-03 05-01. A walk the budget or another tab's change stopped
// leaves the rest for the next call, unless a put or delete of this
// partition has not finished: one running in another tab, or a row a
// crash left (PREPARING, or FILES_READY, which the next reconcile would
// commit) or nothing can read. Any such row sends this call to the
// partition delete too.
let unfinished = 0;
if (sweeping && !request.signal?.aborted) {
if (sweeping && !walkFinished && !request.signal?.aborted) {
const counted = await dependencies.journal.countPartitionTransactions(
dependencies.scope,
);
@@ -904,40 +914,6 @@ export function createOpfsByteStoreAdapter(
}
unfinished = counted.value;
}
// 05-04. Removing an object leaves its chunks, and GC only takes a
// chunk 24 h after it was written, so a purged user's bytes stayed on
// the device. Once every object is gone the partition's chunks are swept
// without that grace. The sweep still skips any chunk the journal or a
// staged put references.
let chunkSweep: OpfsPolicyMaintenanceReport["chunkSweep"];
if (
sweeping &&
!unfinished &&
!corruptObjects &&
!damaged &&
!moreObjectsAvailable &&
!deadlineReached &&
!request.signal?.aborted
) {
const swept = await reconcileOrphanChunks(
deadline,
request.signal,
now(),
);
if (!swept.ok) {
if (swept.error.code !== "CORRUPT_DATA") {
return rebaseFailure(swept.error, "OBJECT_RECONCILE");
}
damaged = true;
} else {
chunkSweep = swept.value.status;
damaged = chunkSweep === "STAGING_STATE_UNREADABLE";
if (chunkSweep === "DEADLINE_REACHED") {
deadlineReached = true;
moreObjectsAvailable = true;
}
}
}
// [0929] 05-01. A row nothing can read never lets this purge finish, so
// the user's bytes would stay on the device for good. The authority
// approved this exact LOGOUT or ACCOUNT_DELETION (the same approval the
@@ -949,7 +925,7 @@ export function createOpfsByteStoreAdapter(
// wait for every put and delete of the partition in any tab.
const partitionDeleted =
sweeping &&
(corruptObjects > 0 || damaged || unfinished > 0) &&
(walkFinished || corruptObjects > 0 || damaged || unfinished > 0) &&
!request.signal?.aborted;
if (partitionDeleted) {
const removed = await withPartitionLock(
@@ -970,8 +946,12 @@ export function createOpfsByteStoreAdapter(
if (!removed.ok) {
return rebaseFailure(removed.error, "OBJECT_RECONCILE");
}
chunkSweep = undefined;
moreObjectsAvailable = false;
} else if (sweeping) {
// Only an abort between the walk and the delete gets here with the
// walk finished. Either way the partition still holds bytes, so a
// purge reports exactly one of `partitionDeleted` and more work.
moreObjectsAvailable = true;
}
const report: OpfsPolicyMaintenanceReport = Object.freeze({
inspectedObjects,
@@ -979,7 +959,6 @@ export function createOpfsByteStoreAdapter(
releasedBytes,
moreObjectsAvailable,
deadlineReached,
...(chunkSweep ? { chunkSweep } : {}),
...(corruptObjects ? { corruptObjects } : {}),
...(partitionDeleted ? { partitionDeleted } : {}),
});
@@ -1365,7 +1344,6 @@ export function createOpfsByteStoreAdapter(
async function reconcileOrphanChunks(
deadline: number,
signal: AbortSignal | undefined,
olderThanEpochMs = Math.max(0, now() - policy.orphanGracePeriodMs),
): Promise<
BrowserDataResult<
Readonly<{
@@ -1378,6 +1356,7 @@ export function createOpfsByteStoreAdapter(
}>
>
> {
const olderThanEpochMs = Math.max(0, now() - policy.orphanGracePeriodMs);
let inspected = 0;
let deleted = 0;
// R-5.1. Candidates include committed chunks, so a page can be all
@@ -52,8 +52,22 @@ export type PublicCacheInspection = Readonly<{
activeReleaseRegistryId: string | null;
ownedCacheCount: number;
unreadableOwnedCacheCount: number;
/**
* 0929/02-02. Every owned release cache with a readable marker. To fill
* `verified`, inspect reads back every entry of every candidate, so its cost
* grows with caches times entries. It has no cursor, deadline or signal
* (VD-15's target runtime adds a cursor and a deadline). Keep it off a boot
* path.
*/
releaseCandidates: readonly Readonly<{
releaseRegistryId: string;
/**
* `true` only when every entry was read back and matched the manifest.
* `false` when an entry is missing or no longer matches, and also when it
* could not be read at all (a failed body read or lookup): inspect does
* not tell those apart. Activating the candidate does, and staging the
* same manifest again rewrites either (1105/02-02).
*/
verified: boolean;
entryCount: number | null;
}>[];
@@ -152,12 +152,15 @@ export type OpfsPolicyMaintenanceReport = Readonly<{
moreObjectsAvailable: boolean;
deadlineReached: boolean;
/**
* 05-04. LOGOUT and ACCOUNT_DELETION only, once every object is removed and
* no put or delete of the partition is unfinished: how the sweep of the
* partition's now unreferenced chunks ended. For those two reasons the
* partition's bytes are gone exactly when this is `COMPLETED` or
* `partitionDeleted` is set; a put that begins after the purge reached its
* journal check is kept (2026-11-03 05-01).
* 05-04. How a LOGOUT or ACCOUNT_DELETION chunk sweep ended.
*
* @deprecated The reference runtime and the recipe fake no longer set it
* (1103/05-01 rest): a sweep after the object walk missed a new object
* another tab's put settled during the walk, and the staging of a stopped
* put whose journal row lost its partition key, and still said
* `COMPLETED`. Such a purge now ends in the partition delete, so
* `partitionDeleted` is the one completion signal. Kept so code that reads
* it still compiles; it is always absent.
*/
chunkSweep?: "COMPLETED" | "DEADLINE_REACHED" | "STAGING_STATE_UNREADABLE";
/**
@@ -166,12 +169,16 @@ export type OpfsPolicyMaintenanceReport = Readonly<{
*/
corruptObjects?: number;
/**
* [0929] 05-01. An approved LOGOUT or ACCOUNT_DELETION that damage kept
* from finishing, or that found an unfinished put or delete of the
* partition (2026-11-03 05-01), removed the whole partition directory and
* the partition's journal rows instead, after every put and delete of the
* partition then running in any tab had returned. Every byte of the
* partition is gone.
* [0929] 05-01. An approved LOGOUT or ACCOUNT_DELETION removed the whole
* partition directory and the partition's journal rows, after every put
* and delete of the partition then running in any tab had returned. Every
* byte of the partition is gone; a put that begins after that delete is
* kept. A purge that walked every object always ends this way (1103/05-01
* rest). One the budget or another tab's change stopped part-way ends this
* way only when damage or an unfinished put or delete of the partition
* (2026-11-03 05-01) was met; otherwise it reports `moreObjectsAvailable`
* and the caller runs it again. For these two reasons the partition's bytes
* are gone exactly when this is set.
*/
partitionDeleted?: true;
}>;
@@ -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;
+22
View File
@@ -133,6 +133,28 @@ export const STORAGE_REGISTRY = Object.freeze({
migration: "discard",
quotaFallback: "feature-disable",
}),
/**
* 1105/05-01. The OIDC PKCE session owner recipe
* (`recipes/session-owners/oidc-pkce-session-owner.ts`) keeps one sign-in
* transaction here in sessionStorage: the PKCE verifier, `state`, `nonce`
* and the return path, never a token, for at most ten minutes, and the
* callback deletes it first. The recipe owns the value format, so only the
* name lives here and StoragePort refuses the key. It is not
* `sensitive-forbidden`, which means "never stored"; this one is stored by
* design for one redirect.
*/
AUTH_REDIRECT_TRANSACTION: defineStorageKey({
logicalName: "AUTH_REDIRECT_TRANSACTION",
scope: "auth",
name: "oidc-pkce-transaction",
backend: "external",
classification: "opaque-cache",
schemaVersion: 1,
valueCodec: "none",
ttl: "session",
migration: "discard",
quotaFallback: "no-persist",
}),
});
export function defineStorageKey<Definition extends StorageKeyInput>(
+118 -86
View File
@@ -329,97 +329,129 @@ async function removeOpfsAuthority(
// 2026-11-03 05-01 X1. The purge used to report a completed sweep while the
// other tab's put landed, and the object stayed readable after the account
// deletion. It now waits for that put and takes it with the partition.
test("05-01 an approved purge in another tab waits for a live put and takes it with the partition", async ({
page,
}) => {
const secondPage = await page.context().newPage();
const suffix = crypto.randomUUID().replaceAll("-", "");
const scope: OpfsTabScope = {
namespace: "durable-objects",
authorityToken: `authority_${suffix}`,
namespaceToken: `namespace_${suffix}`,
partitionToken: `partition_${suffix}`,
};
type Tab = import("../../src/adapters/storage/opfs/browser-opfs-runtime.ts").BrowserOpfsRuntime;
try {
await Promise.all([page.goto("/"), secondPage.goto("/")]);
if (!(await installOpfsTab(page, scope))) return;
expect(await installOpfsTab(secondPage, scope, true)).toBe(true);
// 1103/05-01 rest. That fix still reported a completed sweep, with the new
// object readable, once the purged partition held three or more objects:
// each remove waits for the origin lease the put holds, so the put settled
// before the purge counted the journal. A purge that walked every object now
// always ends in the partition delete.
for (const committedObjects of [0, 3]) {
test(`05-01 an approved purge in another tab waits for a live put and takes it with the partition (${committedObjects} committed objects)`, async ({
page,
}) => {
const secondPage = await page.context().newPage();
const suffix = crypto.randomUUID().replaceAll("-", "");
const scope: OpfsTabScope = {
namespace: "durable-objects",
authorityToken: `authority_${suffix}`,
namespaceToken: `namespace_${suffix}`,
partitionToken: `partition_${suffix}`,
};
type Tab = import("../../src/adapters/storage/opfs/browser-opfs-runtime.ts").BrowserOpfsRuntime;
try {
await Promise.all([page.goto("/"), secondPage.goto("/")]);
if (!(await installOpfsTab(page, scope))) return;
expect(await installOpfsTab(secondPage, scope, true)).toBe(true);
await page.evaluate(async () => {
const state = globalThis as unknown as {
__opfsTab: Tab;
__release?: () => void;
__put?: Promise<unknown>;
};
let streaming!: () => void;
const started = new Promise<void>((resolve) => {
streaming = resolve;
});
const gate = new Promise<void>((resolve) => {
state.__release = resolve;
});
state.__put = state.__opfsTab.objects.put({
objectId: "object_tab_12345678",
expectedGeneration: null,
mediaType: "application/octet-stream",
source: {
byteLength: 4,
async *stream() {
streaming();
await gate;
yield { ok: true as const, value: new Uint8Array([2, 7, 1, 8]) };
const seeded = await secondPage.evaluate(async (count) => {
const runtime = (globalThis as unknown as { __opfsTab: Tab }).__opfsTab;
const codes: string[] = [];
for (let index = 0; index < count; index += 1) {
const put = await runtime.objects.put({
objectId: `object_secret_${String(index).padStart(4, "0")}`,
expectedGeneration: null,
mediaType: "application/octet-stream",
source: {
byteLength: 1,
async *stream() {
yield { ok: true as const, value: new Uint8Array([index + 1]) };
},
},
});
codes.push(put.ok ? "OK" : put.error.code);
}
return codes;
}, committedObjects);
expect(seeded).toEqual(Array.from({ length: committedObjects }, () => "OK"));
await page.evaluate(async () => {
const state = globalThis as unknown as {
__opfsTab: Tab;
__release?: () => void;
__put?: Promise<unknown>;
};
let streaming!: () => void;
const started = new Promise<void>((resolve) => {
streaming = resolve;
});
const gate = new Promise<void>((resolve) => {
state.__release = resolve;
});
state.__put = state.__opfsTab.objects.put({
objectId: "object_tab_12345678",
expectedGeneration: null,
mediaType: "application/octet-stream",
source: {
byteLength: 4,
async *stream() {
streaming();
await gate;
yield { ok: true as const, value: new Uint8Array([2, 7, 1, 8]) };
},
},
});
await started;
});
await secondPage.evaluate(() => {
const state = globalThis as unknown as {
__opfsTab: Tab;
__purge?: Promise<unknown>;
};
state.__purge = state.__opfsTab.maintenance.enforcePolicies({
reason: "ACCOUNT_DELETION",
});
});
await page.waitForTimeout(250);
const put = await page.evaluate(async () => {
const state = globalThis as unknown as {
__release: () => void;
__put: Promise<unknown>;
};
state.__release();
return await state.__put;
});
const report = await secondPage.evaluate(
async () =>
await (globalThis as unknown as { __purge: Promise<unknown> }).__purge,
);
const opened = await secondPage.evaluate(async () => {
const runtime = (globalThis as unknown as { __opfsTab: Tab }).__opfsTab;
const result = await runtime.objects.open({
objectId: "object_tab_12345678",
});
return result.ok ? "OPENED" : result.error.code;
});
expect(put).toMatchObject({ ok: true, value: { generation: 1 } });
expect(report).toMatchObject({
ok: true,
value: {
removedObjects: committedObjects,
moreObjectsAvailable: false,
partitionDeleted: true,
},
});
await started;
});
await secondPage.evaluate(() => {
const state = globalThis as unknown as {
__opfsTab: Tab;
__purge?: Promise<unknown>;
};
state.__purge = state.__opfsTab.maintenance.enforcePolicies({
reason: "ACCOUNT_DELETION",
});
});
await page.waitForTimeout(250);
const put = await page.evaluate(async () => {
const state = globalThis as unknown as {
__release: () => void;
__put: Promise<unknown>;
};
state.__release();
return await state.__put;
});
const report = await secondPage.evaluate(
async () =>
await (globalThis as unknown as { __purge: Promise<unknown> }).__purge,
);
const opened = await secondPage.evaluate(async () => {
const runtime = (globalThis as unknown as { __opfsTab: Tab }).__opfsTab;
const result = await runtime.objects.open({
objectId: "object_tab_12345678",
});
return result.ok ? "OPENED" : result.error.code;
});
expect(put).toMatchObject({ ok: true, value: { generation: 1 } });
expect(report).toMatchObject({
ok: true,
value: { moreObjectsAvailable: false, partitionDeleted: true },
});
expect(opened).toBe("NOT_FOUND");
} finally {
for (const tab of [page, secondPage]) {
await tab.evaluate(() =>
(globalThis as unknown as { __opfsTab?: Tab }).__opfsTab?.close(),
);
expect(opened).toBe("NOT_FOUND");
} finally {
for (const tab of [page, secondPage]) {
await tab.evaluate(() =>
(globalThis as unknown as { __opfsTab?: Tab }).__opfsTab?.close(),
);
}
expect(await removeOpfsAuthority(page, scope)).toBe("DELETED");
await secondPage.close();
}
expect(await removeOpfsAuthority(page, scope)).toBe("DELETED");
await secondPage.close();
}
});
});
}
test("05-01 a reconcile in another tab skips a live put and the put stays readable", async ({
page,
@@ -9,7 +9,10 @@ import {
type BrowserFilePolicyProfile,
} from "../../src/adapters/browser-files/index.ts";
import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts";
import { createSessionBrowserFileCapability } from "../../recipes/frontend-capabilities/browser-file-session-capability.ts";
import {
createSessionBrowserFileCapability,
type SessionBrowserFiles,
} from "../../recipes/frontend-capabilities/browser-file-session-capability.ts";
import { testRuntimeConfig } from "../helpers/runtime-config.ts";
/**
@@ -17,7 +20,9 @@ import { testRuntimeConfig } from "../helpers/runtime-config.ts";
* filling only its own `product-composition.ts`: the recipe capability goes to
* features, its scope participant to the template. The real
* `createRuntimeAdapters` runs; only the product-owned file is replaced, with
* what a product would write in it.
* what a product would write in it. 1105/02-03. The test drives the runtime
* through the capability the template hands the feature loaders, so dropping
* `files` from the composition's `capabilities` fails it.
*/
const selectPolicy = browserFilePolicyReference("session-file", "select-text");
@@ -57,6 +62,8 @@ const fixture = vi.hoisted(() => ({
files: undefined as
| ReturnType<typeof createSessionBrowserFileCapability>["files"]
| undefined,
/** What the template hands the installed features' loaders. */
featureCapabilities: undefined as Readonly<Record<string, unknown>> | undefined,
inputs: [] as HTMLInputElement[],
handoffs: 0,
owner: undefined as
@@ -139,19 +146,37 @@ vi.mock("../../src/bootstrap/product-composition.ts", () => ({
);
fixture.files = browserFiles.files;
return {
capabilities: {},
capabilities: { files: browserFiles.files },
credentialProviders: {},
scopeParticipants: [browserFiles.scopeParticipant],
};
},
}));
/** Records the capabilities features receive; the loaders run unchanged. */
vi.mock("../../src/features/installed-feature-adapters.ts", async (importOriginal) => {
const original =
await importOriginal<typeof import("../../src/features/installed-feature-adapters.ts")>();
return {
...original,
createInstalledFeatureLoaders(
...args: Parameters<typeof original.createInstalledFeatureLoaders>
) {
fixture.featureCapabilities = args[0] as unknown as Readonly<
Record<string, unknown>
>;
return original.createInstalledFeatureLoaders(...args);
},
};
});
let current: Awaited<ReturnType<typeof createRuntimeAdapters>> | undefined;
afterEach(() => {
current?.infrastructure.dispose();
current = undefined;
for (const input of fixture.inputs.splice(0)) input.remove();
fixture.files = undefined;
fixture.featureCapabilities = undefined;
fixture.handoffs = 0;
});
@@ -202,9 +227,15 @@ async function compose() {
},
host: {},
});
const files = fixture.files;
const owner = fixture.owner;
if (!files || !owner) throw new Error("The product composition did not run");
if (!fixture.files || !owner) {
throw new Error("The product composition did not run");
}
// What a feature that lists `files` in `needs` is given.
const files = fixture.featureCapabilities?.files as
| SessionBrowserFiles
| undefined;
if (!files) throw new Error("Features did not receive the files capability");
return { adapters: current, files, owner };
}
@@ -672,12 +672,14 @@ describe("production browser file and storage recipe contracts", () => {
expectedGeneration: asObjectGeneration(2),
}),
).toMatchObject({ ok: false, error: { code: "CONFLICT" } });
expect(
await store.enforcePolicies({ reason: "ACCOUNT_DELETION" }),
).toMatchObject({
// 1103/05-01 rest. Like the runtime, a purge that walked every object
// ends in the partition delete, never in a chunk sweep.
const purged = await store.enforcePolicies({ reason: "ACCOUNT_DELETION" });
expect(purged).toMatchObject({
ok: true,
value: { removedObjects: 1, chunkSweep: "COMPLETED" },
value: { removedObjects: 1, partitionDeleted: true },
});
expect(purged.ok && purged.value.chunkSweep).toBeUndefined();
expect(await store.open({ objectId })).toMatchObject({
ok: false,
error: { code: "NOT_FOUND" },
@@ -3,6 +3,7 @@ import { createHash } from "node:crypto";
import { describe, expect, it, vi } from "vitest";
import type { SessionOwnerFetch } from "../../src/bootstrap/product-composition-contract.ts";
import { STORAGE_REGISTRY } from "../../src/contracts/storage-keys.ts";
import {
createOidcPkceSessionOwner,
OIDC_PKCE_TRANSACTION_KEY,
@@ -193,6 +194,14 @@ describe("OIDC PKCE session owner: sign-in", () => {
expect(transaction.returnTo).toBe("/items?limit=1");
expect(transaction.verifier).toMatch(/^[A-Za-z0-9_-]{43}$/u);
expect(setup.storage.size).toBe(1);
// 1105/05-01. The key is the storage registry's row, so it follows the
// app's APP_NAMESPACE instead of a literal `ca-frontend:` prefix.
expect([...setup.storage.keys()]).toEqual([
STORAGE_REGISTRY.AUTH_REDIRECT_TRANSACTION.physicalKey,
]);
expect(OIDC_PKCE_TRANSACTION_KEY).toBe(
STORAGE_REGISTRY.AUTH_REDIRECT_TRANSACTION.physicalKey,
);
});
it("returns only to a path of this app", async () => {
+95
View File
@@ -385,6 +385,101 @@ describe("browser cross-context host", () => {
]);
});
// 1101/02-04 (2), N38. sessionStorage and every other Storage area raise
// the same `storage` event, so the host trusts only the localStorage object
// it captured, compared by identity. The transport tests above hand the core
// a ready-made area verdict, so removing that comparison passed them all.
it("takes a storage pulse only from the localStorage object it captured", () => {
type Listener = (event: unknown) => void;
type Tab = {
listeners: Set<Listener>;
localStorage: Record<string, unknown>;
sessionStorage: Record<string, unknown>;
};
const tabs: Tab[] = [];
let arrivingFrom: "localStorage" | "sessionStorage" | "lookalike" =
"localStorage";
const storageArea = (tab: Tab) => {
const values = new Map<string, string>();
const notify = (key: string, newValue: string | null) => {
const from = arrivingFrom;
for (const other of tabs) {
if (other === tab) continue;
// Same shape, another object: identity, not shape, is the test.
const area =
from === "lookalike" ? { ...other.localStorage } : other[from];
for (const listener of [...other.listeners]) {
listener({ key, newValue, storageArea: area });
}
}
};
return {
getItem: (key: string) => values.get(key) ?? null,
setItem(key: string, value: string) {
values.set(key, value);
notify(key, value);
},
removeItem(key: string) {
values.delete(key);
notify(key, null);
},
};
};
const hostOfNewTab = (): Record<string, unknown> => {
const tab: Tab = {
listeners: new Set(),
localStorage: {},
sessionStorage: {},
};
tab.localStorage = storageArea(tab);
tab.sessionStorage = storageArea(tab);
tabs.push(tab);
// No BroadcastChannel, so the storage pulse is the only transport.
return {
crypto: globalThis.crypto,
localStorage: tab.localStorage,
sessionStorage: tab.sessionStorage,
addEventListener(type: string, listener: Listener) {
if (type === "storage") tab.listeners.add(listener);
},
removeEventListener(type: string, listener: Listener) {
if (type === "storage") tab.listeners.delete(listener);
},
};
};
const topics = [{ topic: TOPIC, topicVersion: 1 }];
const publisher = createBrowserCrossContextInvalidationFromHost({
host: hostOfNewTab(),
cacheEpoch: CACHE_EPOCH,
topics,
});
const receiver = createBrowserCrossContextInvalidationFromHost({
host: hostOfNewTab(),
cacheEpoch: CACHE_EPOCH,
topics,
});
if (!publisher || !receiver) throw new Error("host runtime not created");
const received = vi.fn();
receiver.subscribe(received);
for (const area of ["sessionStorage", "lookalike"] as const) {
arrivingFrom = area;
expect(
publisher.publish({ topic: TOPIC, topicVersion: 1 }),
).toMatchObject({ ok: true });
}
expect(received).not.toHaveBeenCalled();
arrivingFrom = "localStorage";
expect(
publisher.publish({ topic: TOPIC, topicVersion: 1 }),
).toMatchObject({ ok: true });
expect(received).toHaveBeenCalledOnce();
publisher.close();
receiver.close();
});
it("derives a valid, stable cache epoch from any release id (Q-6.2-9)", () => {
const releaseIds = [
"1.2.3+sha.abc",
+226 -19
View File
@@ -2254,15 +2254,17 @@ describe("05-04 a LOGOUT or ACCOUNT_DELETION purge leaves no partition bytes beh
expect(await putBytes(purged, "object_secret_2", [4, 5])).toMatchObject({ ok: true });
expect(await putBytes(kept, "object_kept_0001", [7, 7])).toMatchObject({ ok: true });
expect(await purged.maintenance.enforcePolicies({ reason })).toMatchObject({
const report = await purged.maintenance.enforcePolicies({ reason });
expect(report).toMatchObject({
ok: true,
value: {
removedObjects: 2,
moreObjectsAvailable: false,
deadlineReached: false,
chunkSweep: "COMPLETED",
partitionDeleted: true,
},
});
expect(report.ok && report.value.chunkSweep).toBeUndefined();
expect(filesUnder(root, scopeA)).toEqual([]);
expect(await openedBytes(kept, "object_kept_0001")).toEqual({
generation: 1,
@@ -2273,7 +2275,7 @@ describe("05-04 a LOGOUT or ACCOUNT_DELETION purge leaves no partition bytes beh
// 1101/13.6. A journal may hand back a page shorter than the limit (the port
// does not promise full pages). A purge that walked two such pages and
// removed everything is finished: it must say so and sweep the chunks.
// removed everything is finished: it must say so and take the partition.
it("finishes a purge that walked more than one journal page", async () => {
const { root, idb, tab } = sharedRootTabs();
const journal = createIndexedDbOpfsJournal({
@@ -2300,7 +2302,7 @@ describe("05-04 a LOGOUT or ACCOUNT_DELETION purge leaves no partition bytes beh
inspectedObjects: 2,
removedObjects: 2,
moreObjectsAvailable: false,
chunkSweep: "COMPLETED",
partitionDeleted: true,
},
});
expect(filesUnder(root, scopeA)).toEqual([]);
@@ -2310,25 +2312,89 @@ describe("05-04 a LOGOUT or ACCOUNT_DELETION purge leaves no partition bytes beh
// it, report a completed sweep and leave that object readable. A put or
// delete of the partition that has not finished now sends the purge to the
// partition delete, which waits for it and then takes it.
it("waits for a put that began before the purge and takes it with the partition", async () => {
const { root, tab } = sharedRootTabs();
const purger = tab("p", authority);
// 1103/05-01 rest (Y1b). That fix counted the journal once, after the walk.
// Each remove waits for the origin lease the other tab's put holds, so with
// three or more objects the put committed and settled before the count:
// neither the listing nor the count saw it, the sweep skipped its chunks
// and said COMPLETED, and the file stayed readable. One object hid this.
it.each([1, 3, 8])(
"waits for a put that began before the purge and takes it with the partition (%i committed objects)",
async (count) => {
const { root, tab } = sharedRootTabs();
const purger = tab("p", authority);
const writer = tab("w", authority);
for (let index = 1; index <= count; index += 1) {
expect(
await putBytes(purger, `object_secret_${index}`, [index]),
).toMatchObject({ ok: true });
}
const stalled = stalledSource();
const put = writer.objects.put({
objectId: "object_late_0001",
expectedGeneration: null,
mediaType: "application/octet-stream",
source: stalled.source,
});
await stalled.streaming;
const purge = purger.maintenance.enforcePolicies({ reason: "LOGOUT" });
await new Promise((resolve) => setTimeout(resolve, 20));
stalled.release();
expect(await put).toMatchObject({ ok: true });
const report = await purge;
expect(report).toMatchObject({
ok: true,
value: {
removedObjects: count,
moreObjectsAvailable: false,
partitionDeleted: true,
},
});
expect(report.ok && report.value.chunkSweep).toBeUndefined();
expect(filesUnder(root, scopeA)).toEqual([]);
expect(await openedBytes(writer, "object_late_0001")).toBe("NOT_FOUND");
},
);
// 1103/05-01 rest (Y1a). The same gap without timing: another tab's put of
// a new object commits and settles right after the purge lists the
// partition, so the listing misses it and no journal row is left to count.
it("takes a new object another tab's put settles between the purge's listing and its end", async () => {
const { root, idb, tab } = sharedRootTabs();
const journal = createIndexedDbOpfsJournal({
authorityToken: scopeA.authorityToken,
factory: idb.factory,
keyRange: idb.keyRange,
});
const stalled = stalledSource();
let late: ReturnType<typeof writer.objects.put> | undefined;
const purger = tab("p", {
...authority,
journal: {
...journal,
async listCommittedObjects(request) {
const page = await journal.listCommittedObjects(request);
stalled.release();
await late;
return page;
},
},
});
const writer = tab("w", authority);
expect(await putBytes(purger, "object_secret_1", [1, 2, 3])).toMatchObject({ ok: true });
const stalled = stalledSource();
const put = writer.objects.put({
late = writer.objects.put({
objectId: "object_late_0001",
expectedGeneration: null,
mediaType: "application/octet-stream",
source: stalled.source,
});
await stalled.streaming;
const purge = purger.maintenance.enforcePolicies({ reason: "LOGOUT" });
await new Promise((resolve) => setTimeout(resolve, 20));
stalled.release();
expect(await put).toMatchObject({ ok: true });
const report = await purge;
const report = await purger.maintenance.enforcePolicies({
reason: "ACCOUNT_DELETION",
});
expect(await late).toMatchObject({ ok: true, value: { generation: 1 } });
expect(report).toMatchObject({
ok: true,
value: {
@@ -2339,7 +2405,72 @@ describe("05-04 a LOGOUT or ACCOUNT_DELETION purge leaves no partition bytes beh
});
expect(report.ok && report.value.chunkSweep).toBeUndefined();
expect(filesUnder(root, scopeA)).toEqual([]);
expect(await openedBytes(writer, "object_late_0001")).toBe("NOT_FOUND");
expect(await openedBytes(purger, "object_late_0001")).toBe("NOT_FOUND");
});
// 2026-11-03 05-01. A walk the budget stops part-way is no finished purge.
// It leaves the rest for the next call, unless a put or delete of the
// partition is unfinished: then that call takes the partition at once.
it("continues a purge the object budget stopped, and takes the partition when a put is unfinished", async () => {
const { root, idb, tab } = sharedRootTabs();
const purger = tab("p", authority);
for (const objectId of ["object_secret_1", "object_secret_2", "object_secret_3"]) {
expect(await putBytes(purger, objectId, [1])).toMatchObject({ ok: true });
}
const first = await purger.maintenance.enforcePolicies({
reason: "ACCOUNT_DELETION",
maxObjects: 1,
});
expect(first).toEqual({
ok: true,
value: {
inspectedObjects: 1,
removedObjects: 1,
releasedBytes: 1,
moreObjectsAvailable: true,
deadlineReached: false,
},
});
expect(filesUnder(root, scopeA)).not.toEqual([]);
// A put that died before it wrote anything leaves a PREPARING row.
const journal = createIndexedDbOpfsJournal({
authorityToken: scopeA.authorityToken,
factory: idb.factory,
keyRange: idb.keyRange,
});
expect(
await journal.begin({
transactionId: "transaction_left_0001",
mutation: "PUT",
scope: scopeA,
objectId: "object_left_0001",
expectedGeneration: null,
targetGeneration: 1,
targetByteLength: 1,
targetStoragePolicy: storagePolicy,
startedAtEpochMs: 2,
}),
).toMatchObject({ ok: true });
expect(
await purger.maintenance.enforcePolicies({
reason: "ACCOUNT_DELETION",
maxObjects: 1,
}),
).toMatchObject({
ok: true,
value: {
inspectedObjects: 1,
removedObjects: 1,
moreObjectsAvailable: false,
partitionDeleted: true,
},
});
expect(filesUnder(root, scopeA)).toEqual([]);
expect(idb.readRaw("opfs-journal", "transaction_left_0001")).toBeUndefined();
expect(await openedBytes(purger, "object_secret_3")).toBe("NOT_FOUND");
});
// 2026-11-03 05-01 X2, X2b, X3. A put that stopped before it finished leaves
@@ -2420,11 +2551,87 @@ describe("05-04 a LOGOUT or ACCOUNT_DELETION purge leaves no partition bytes beh
},
);
// 1103/05-01 rest (Y2). The journal counts rows by their partition key, so a
// stopped put whose row lost that key was never counted. Its staging
// receipt kept its chunk out of the sweep, and every purge said COMPLETED
// with the receipt, the chunk and the manifest still on disk. The partition
// delete takes them; the keyless row itself stays, counted apart (05-03).
it("leaves no bytes of a stopped put whose journal row lost its partition key", async () => {
const { root, idb, tab } = sharedRootTabs();
const journal = createIndexedDbOpfsJournal({
authorityToken: scopeA.authorityToken,
factory: idb.factory,
keyRange: idb.keyRange,
});
const writerWorker = loopbackGateway(
createOpfsWorkerRuntime({
root: root as unknown as FileSystemDirectoryHandle,
crypto: globalThis.crypto,
policy: runtimePolicy,
leaseManager: exclusiveLeases(),
dedicatedWorker: true,
supportsSynchronousAccessHandles: false,
}),
);
const unavailable = async () =>
browserDataFailure("UNAVAILABLE", "INDEXEDDB_WRITE", {
retryable: true,
recovery: "RETRY",
});
// The tab crashes before commit: neither the commit nor its compensation
// lands, so the row stays FILES_READY with its staging on disk.
const writer = tab("w", {
journal: { ...journal, commitPut: unavailable } as OpfsJournalPort,
worker: {
...writerWorker,
abortPreparedPut: async () =>
browserDataFailure("UNAVAILABLE", "OBJECT_WRITE", {
retryable: true,
recovery: "RETRY",
}),
},
});
const purger = tab("p", authority);
expect(await putBytes(purger, "object_secret_1", [1, 2, 3])).toMatchObject({ ok: true });
expect(await putBytes(writer, "object_dead_0001", [9, 9, 9])).toMatchObject({
ok: false,
});
const { logicalKey: _dropped, ...keyless } = idb.readRaw(
"opfs-journal",
"transaction_w_1",
) as Record<string, unknown>;
idb.seed("opfs-journal", keyless);
expect(filesUnder(root, scopeA)).not.toEqual([]);
for (let run = 0; run < 2; run += 1) {
const report = await purger.maintenance.enforcePolicies({
reason: "ACCOUNT_DELETION",
});
expect(report).toMatchObject({
ok: true,
value: { moreObjectsAvailable: false, partitionDeleted: true },
});
expect(report.ok && report.value.chunkSweep).toBeUndefined();
expect(filesUnder(root, scopeA)).toEqual([]);
expect(await purger.maintenance.reconcile()).toMatchObject({
ok: true,
value: {
committedTransactions: 0,
corruptTransactions: 1,
unattributedCorruptTransactions: 1,
},
});
}
expect(await openedBytes(purger, "object_dead_0001")).toBe("NOT_FOUND");
expect(idb.readRaw("opfs-journal", "transaction_w_1")).toBeDefined();
});
// [0929] 05-02. Another tab overwrites the object the purge is removing, so
// the purge's remove ends in CONFLICT. That purge is not finished and must
// not claim a completed chunk sweep. The overwrite finishes between the
// purge's listing and its remove: one still running when the purge checks
// the journal sends it to the partition delete instead (2026-11-03 05-01).
// not claim to be. The overwrite finishes between the purge's listing and
// its remove: one still running when the purge checks the journal sends it
// to the partition delete instead (2026-11-03 05-01). The next call walks
// every object and takes the partition (1103/05-01 rest).
it("reports a purge that skipped a changing object as unfinished", async () => {
const { root, idb, tab } = sharedRootTabs();
const journal = createIndexedDbOpfsJournal({
@@ -2472,7 +2679,7 @@ describe("05-04 a LOGOUT or ACCOUNT_DELETION purge leaves no partition bytes beh
value: {
removedObjects: 1,
moreObjectsAvailable: false,
chunkSweep: "COMPLETED",
partitionDeleted: true,
},
});
expect(filesUnder(root, scopeA)).toEqual([]);
+349 -10
View File
@@ -1,6 +1,9 @@
import { describe, expect, it } from "vitest";
import type { PublicCacheAsset } from "../../src/application/ports/browser-file-storage/cache-storage-ports.ts";
import type {
PublicCacheAsset,
PublicCacheReleaseManifest,
} from "../../src/application/ports/browser-file-storage/cache-storage-ports.ts";
import {
activePointerRequest,
controlCacheName,
@@ -174,7 +177,7 @@ describe("public response cache repair is failure-atomic", () => {
]);
});
it("reports a cached body that cannot be read during activation as retryable, not as damage (2026-11-03 02-02)", async () => {
it("reports a cached body that cannot be read during activation as unreadable, not as damage (2026-11-03 02-02)", async () => {
const release = await stagedRelease("unreadable-body");
const cache = release.cacheStorage.caches.get(release.cacheName)!;
const realMatch = cache.match.bind(cache);
@@ -195,13 +198,13 @@ describe("public response cache repair is failure-atomic", () => {
{ headers: stored.headers },
);
};
const transient = (operation: string) => ({
const unreadable = (operation: string, recovery: string) => ({
ok: false,
error: {
code: "UNAVAILABLE",
operation,
retryable: true,
recovery: "RETRY",
recovery,
},
});
@@ -209,20 +212,25 @@ describe("public response cache repair is failure-atomic", () => {
await release.adapter.responses.matchActiveExact({
absoluteUrl: release.assets[0]!.absoluteUrl,
}),
).toMatchObject(transient("CACHE_LOOKUP"));
).toMatchObject(unreadable("CACHE_LOOKUP", "RETRY"));
// 1105/02-02. Activation keeps the code but points at staging the same
// manifest again, which is what fixes an entry that stays unreadable.
expect(
await release.adapter.admin.activateRelease(
release.manifest.releaseRegistryId,
release.manifest.manifestDigestHex,
),
).toMatchObject(transient("CACHE_ACTIVATE"));
// The stage fast path shares the verdict: an unreadable candidate is
// neither reused nor fetched again over the network.
).toMatchObject(unreadable("CACHE_ACTIVATE", "REHYDRATE"));
// 1105/02-02. The stage fast path no longer stops at an unreadable
// candidate: it fetches every asset again and writes it over the entry.
// It used to fail with no fetch, so nothing could bring the entry back.
const fetchesBefore = release.fetchLog.length;
expect(
await release.adapter.admin.stageRelease(release.manifest),
).toMatchObject(transient("CACHE_STAGE"));
expect(release.fetchLog).toHaveLength(fetchesBefore);
).toMatchObject({ ok: true });
expect(release.fetchLog).toHaveLength(
fetchesBefore + release.assets.length,
);
cache.match = realMatch;
expect(
@@ -341,6 +349,337 @@ describe("public response cache repair is failure-atomic", () => {
});
});
/**
* 1105/02-02. After 2026-11-03 02-02 a body read failure is no damage, and the
* stage fast path stopped there with no fetch. An entry that stays unreadable
* until it is written again (a lost blob) was then never written again: the
* candidate kept failing activation, a rollback target that cleanup keeps
* could not be activated again, and the active release kept missing the
* asset. Staging the same manifest now writes such an entry again.
*/
describe("a cached body that stays unreadable until it is written again (1105/02-02)", () => {
async function deployments() {
const policy = createDefaultPublicCachePolicy(
"https://assets.example.test",
);
const firstBytes = new Uint8Array([1, 1, 1, 1]);
const secondBytes = new Uint8Array([2, 2, 2, 2]);
const assets: readonly PublicCacheAsset[] = [
{
absoluteUrl: "https://assets.example.test/first.js",
expectedByteLength: firstBytes.byteLength,
expectedContentType: "application/javascript",
integrity: {
algorithm: "SHA-256",
digestHex: await digestHex(firstBytes),
},
},
{
absoluteUrl: "https://assets.example.test/second.js",
expectedByteLength: secondBytes.byteLength,
expectedContentType: "application/javascript",
integrity: {
algorithm: "SHA-256",
digestHex: await digestHex(secondBytes),
},
},
];
const bodies = new Map<string, Uint8Array>([
[assets[0]!.absoluteUrl, firstBytes],
[assets[1]!.absoluteUrl, secondBytes],
]);
const cacheStorage = new MemoryCacheStorage();
const fetchLog: string[] = [];
const adapter = createPublicResponseCacheAdapter({
cacheStorage: cacheStorage as unknown as CacheStorage,
crypto: globalThis.crypto,
mutationLock: immediateLock,
policy,
fetcher: async (request: Request) => {
fetchLog.push(request.url);
const body = bodies.get(request.url);
if (!body) throw new TypeError(`unknown asset ${request.url}`);
return new Response(Uint8Array.from(body), {
headers: {
"cache-control": "public",
"content-type": "application/javascript",
},
});
},
});
const manifests = new Map<string, PublicCacheReleaseManifest>();
const manifest = async (releaseRegistryId: string) => {
let found = manifests.get(releaseRegistryId);
if (!found) {
found = await manifestFor(releaseRegistryId, assets, policy);
manifests.set(releaseRegistryId, found);
}
return found;
};
const cacheOf = (releaseRegistryId: string) => {
const name = [...cacheStorage.caches.keys()].find((candidate) =>
candidate.includes(`release:${releaseRegistryId}:`),
);
const cache = name ? cacheStorage.caches.get(name) : undefined;
if (!cache) throw new Error(`no cache for ${releaseRegistryId}`);
return cache;
};
return {
assets,
async stage(releaseRegistryId: string) {
const before = fetchLog.length;
const result = await adapter.admin.stageRelease(
await manifest(releaseRegistryId),
);
return { ok: result.ok, fetched: fetchLog.length - before };
},
async activate(releaseRegistryId: string) {
const { manifestDigestHex } = await manifest(releaseRegistryId);
return await adapter.admin.activateRelease(
releaseRegistryId,
manifestDigestHex,
);
},
lookup: (absoluteUrl: string) =>
adapter.responses.matchActiveExact({ absoluteUrl }),
inspect: () => adapter.admin.inspect(),
cacheOf,
/** The entry's body fails to read until something writes it again. */
unreadableUntilRewritten(
releaseRegistryId: string,
url: string,
error: () => unknown,
) {
const cache = cacheOf(releaseRegistryId);
const state = { unreadable: true };
const realMatch = cache.match.bind(cache);
const realPut = cache.put.bind(cache);
const urlOf = (request: RequestInfo | URL) =>
request instanceof Request ? request.url : String(request);
cache.put = async (request, response) => {
if (urlOf(request) === url) state.unreadable = false;
await realPut(request, response);
};
cache.match = async (request) => {
const stored = await realMatch(request);
if (!stored || urlOf(request) !== url || !state.unreadable) {
return stored;
}
return new Response(
new ReadableStream<Uint8Array>({
pull(controller) {
controller.error(error());
},
}),
{ headers: stored.headers },
);
};
return state;
},
};
}
it.each([
["a TypeError", () => new TypeError("blob missing"), "UNAVAILABLE"],
[
"a NotReadableError",
() => new DOMException("unreadable", "NotReadableError"),
"NOT_READABLE",
],
] as const)(
"repairs a staged candidate whose entry fails with %s by staging it again (E-1a, E-1b)",
async (_label, error, code) => {
const world = await deployments();
expect(await world.stage("r1")).toEqual({ ok: true, fetched: 2 });
expect(await world.activate("r1")).toMatchObject({ ok: true });
expect(await world.stage("r2")).toEqual({ ok: true, fetched: 2 });
const entry = world.unreadableUntilRewritten(
"r2",
world.assets[0]!.absoluteUrl,
error,
);
expect(await world.activate("r2")).toMatchObject({
ok: false,
error: { code, operation: "CACHE_ACTIVATE", recovery: "REHYDRATE" },
});
expect(await world.stage("r2")).toEqual({ ok: true, fetched: 2 });
expect(entry.unreadable).toBe(false);
expect(await world.activate("r2")).toMatchObject({ ok: true });
},
);
// 1105/02-04. Which stored-entry failures count as damage decides what an
// activation reports; the stage fast path writes every one of them again.
// Each row is one code of the damage list or one body read failure outside
// it, so taking a code out of the list or adding one fails its row.
const replaced =
(make: (stored: Response) => Response) =>
(world: Awaited<ReturnType<typeof deployments>>, url: string) => {
const cache = world.cacheOf("r2");
const index = cache.responses.findIndex(
(entry) => entry.request.url === url,
);
const entry = cache.responses[index]!;
cache.responses.splice(index, 1, {
request: entry.request,
response: make(entry.response),
});
};
const withHeader = (name: string, value: string) =>
replaced((stored) => {
const headers = new Headers(stored.headers);
headers.set(name, value);
return new Response(new Uint8Array([1, 1, 1, 1]), { headers });
});
const unreadableWith =
(error: () => unknown) =>
(world: Awaited<ReturnType<typeof deployments>>, url: string) => {
world.unreadableUntilRewritten("r2", url, error);
};
it.each([
[
"bytes that no longer match the digest",
replaced(
(stored) =>
new Response(new Uint8Array([9, 9, 9, 9]), {
headers: stored.headers,
}),
),
"INTEGRITY_FAILED",
],
[
"a header outside the policy",
withHeader("cache-control", "no-store"),
"INTEGRITY_FAILED",
],
[
"a declared length over the entry limit",
withHeader("content-length", "99999999999"),
"INTEGRITY_FAILED",
],
[
"a body that fails as corrupt data",
unreadableWith(() => new DOMException("bad record", "DataError")),
"INTEGRITY_FAILED",
],
[
"a body read that fails with a TypeError",
unreadableWith(() => new TypeError("blob missing")),
"UNAVAILABLE",
],
[
"a body read that fails with a NotReadableError",
unreadableWith(() => new DOMException("unreadable", "NotReadableError")),
"NOT_READABLE",
],
] as const)(
"reports a staged entry with %s on activation and rewrites it on the next stage",
async (_label, damage, code) => {
const world = await deployments();
expect(await world.stage("r1")).toMatchObject({ ok: true });
expect(await world.activate("r1")).toMatchObject({ ok: true });
expect(await world.stage("r2")).toEqual({ ok: true, fetched: 2 });
damage(world, world.assets[0]!.absoluteUrl);
expect(await world.activate("r2")).toMatchObject({
ok: false,
error: { code, operation: "CACHE_ACTIVATE", recovery: "REHYDRATE" },
});
expect(await world.stage("r2")).toEqual({ ok: true, fetched: 2 });
expect(await world.activate("r2")).toMatchObject({ ok: true });
},
);
// 0929/02-02 (M05). `verified` is true only when every entry was read back
// and matched. A candidate inspect could not read is not verified, whether
// its body read or the lookup itself failed; reporting it verified passed
// every test before.
it("lists a candidate it could not read as unverified", async () => {
const world = await deployments();
for (const releaseRegistryId of ["r1", "r2", "r3"]) {
expect(await world.stage(releaseRegistryId)).toMatchObject({ ok: true });
}
world.unreadableUntilRewritten(
"r2",
world.assets[0]!.absoluteUrl,
() => new TypeError("blob missing"),
);
const lookupFails = world.cacheOf("r3");
const realMatch = lookupFails.match.bind(lookupFails);
const assetUrls = new Set(world.assets.map((asset) => asset.absoluteUrl));
lookupFails.match = async (request) => {
const url = request instanceof Request ? request.url : String(request);
if (assetUrls.has(url)) {
throw new DOMException("Storage is busy", "InvalidStateError");
}
return await realMatch(request);
};
const inspected = await world.inspect();
expect(inspected.ok).toBe(true);
if (!inspected.ok) return;
expect(
Object.fromEntries(
inspected.value.releaseCandidates.map((candidate) => [
candidate.releaseRegistryId,
candidate.verified,
]),
),
).toEqual({ r1: true, r2: false, r3: false });
});
it("lets a retained rollback target be activated again after staging it again (E-1c)", async () => {
const world = await deployments();
for (const releaseRegistryId of ["r1", "r2"]) {
expect(await world.stage(releaseRegistryId)).toMatchObject({ ok: true });
expect(await world.activate(releaseRegistryId)).toMatchObject({
ok: true,
});
}
world.unreadableUntilRewritten(
"r1",
world.assets[0]!.absoluteUrl,
() => new TypeError("blob missing"),
);
expect(await world.activate("r1")).toMatchObject({
ok: false,
error: { code: "UNAVAILABLE", recovery: "REHYDRATE" },
});
expect(await world.stage("r1")).toEqual({ ok: true, fetched: 2 });
expect(await world.activate("r1")).toMatchObject({ ok: true });
});
it("serves the active release's asset again once it is staged again (E-1d)", async () => {
const world = await deployments();
expect(await world.stage("r1")).toMatchObject({ ok: true });
expect(await world.activate("r1")).toMatchObject({ ok: true });
const [first, second] = world.assets;
world.unreadableUntilRewritten(
"r1",
first!.absoluteUrl,
() => new TypeError("blob missing"),
);
expect(await world.lookup(first!.absoluteUrl)).toMatchObject({
ok: false,
error: { code: "UNAVAILABLE", recovery: "RETRY" },
});
expect(await world.lookup(second!.absoluteUrl)).toMatchObject({
ok: true,
value: expect.anything(),
});
expect(await world.stage("r1")).toEqual({ ok: true, fetched: 2 });
expect(await world.lookup(first!.absoluteUrl)).toMatchObject({
ok: true,
value: expect.anything(),
});
});
});
/**
* 0929/02-01. The active pointer was checked against the policy of the build
* reading it, so lowering `retainedPreviousReleaseCount` or a damaged pointer
@@ -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")],
]);
});
});
+38
View File
@@ -200,6 +200,44 @@ describe("storage registry", () => {
);
});
// 1105/05-01. The OIDC PKCE recipe wrote its sessionStorage key as a
// literal outside the registry, so renaming APP_NAMESPACE split it off. The
// key is now a registry row the recipe reads, and StoragePort refuses it
// like the pulse key.
it("registers the PKCE sign-in transaction key as externally owned and refuses it", () => {
const transaction = STORAGE_REGISTRY.AUTH_REDIRECT_TRANSACTION;
const raw = JSON.stringify({ state: "s", nonce: "n" });
const { storage, values, setItem, removeItem } = createStorage({
initial: { [transaction.physicalKey]: raw },
});
const adapter = createBrowserStorageAdapter({ sessionStorage: storage });
expect(transaction).toMatchObject({
scope: "auth",
name: "oidc-pkce-transaction",
backend: "external",
valueCodec: "none",
});
expect(transaction.physicalKey).toBe(
buildPhysicalKey("auth", 1, "oidc-pkce-transaction"),
);
expect(adapter.read("AUTH_REDIRECT_TRANSACTION")).toMatchObject({
ok: false,
});
expect(adapter.write("AUTH_REDIRECT_TRANSACTION", "hello")).toMatchObject({
ok: false,
});
expect(adapter.remove("AUTH_REDIRECT_TRANSACTION")).toMatchObject({
ok: false,
});
expect(setItem).not.toHaveBeenCalled();
expect(removeItem).not.toHaveBeenCalled();
expect(values.get(transaction.physicalKey)).toBe(raw);
expect(() => getStorageDefinition("AUTH_REDIRECT_TRANSACTION")).toThrow(
"Externally owned storage key: AUTH_REDIRECT_TRANSACTION",
);
});
it("rejects a value codec on an externally owned key", () => {
expect(() =>
defineStorageKey({