Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
79ec86d
fix(runtime): share dependency snapshot history through the distribut…
kwakayama Sep 8, 2026
e1c7989
fix(cache): harden the shared snapshot store per review
kwakayama Sep 8, 2026
855c8cb
fix(cache): scope the automatic snapshot store and its record bounds
kwakayama Sep 8, 2026
eb367da
fix(cache): honor the store contract's signal, expiry, and test isola…
kwakayama Sep 8, 2026
c44ea65
fix(cache): make snapshot store activation host-explicit and capture …
kwakayama Sep 8, 2026
321967c
fix(cache): capture reflection intrinsics and null-prototype the reco…
kwakayama Sep 8, 2026
0f7797c
fix(cache): capture collection intrinsics in capability traversals
kwakayama Sep 8, 2026
9d6a4f2
fix(cache): stop capability injection and harden the accessor's intri…
kwakayama Sep 8, 2026
d9e09bc
docs(cache): state the store's accepted residual properties
kwakayama Sep 8, 2026
9261b8c
fix(cache): export snapshot factory and protect private read capabili…
kojiwakayama Sep 9, 2026
a050c8a
fix(deps): update sharp to patched libheif binaries
kojiwakayama Sep 9, 2026
e24b8d9
fix(build): synchronize proxy lockfile with sharp patch
kojiwakayama Sep 9, 2026
c392197
fix(cache): protect captured revision capabilities and clarify limits
kojiwakayama Sep 9, 2026
4a84987
fix(cache): use reserved keys for snapshot revision operations
kojiwakayama Sep 9, 2026
cabeb13
fix(cache): require own snapshot record fields
kojiwakayama Sep 9, 2026
a1f53d5
fix(cache): keep private backends out of promise species
kojiwakayama Sep 9, 2026
dda6f59
fix(cache): require exact snapshot retention deadlines
kojiwakayama Sep 9, 2026
606eab3
Resolve main conflict with strict Sharp cache identity
kojiwakayama Sep 9, 2026
e2edfe3
fix(cache): retry identical snapshot publication races
kojiwakayama Sep 9, 2026
2d3a7ce
fix(cache): reject expired snapshot publication retries
kojiwakayama Sep 9, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 40 additions & 39 deletions docs/api-reference/veryfront/platform.md

Large diffs are not rendered by default.

65 changes: 47 additions & 18 deletions src/cache/backends/factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,22 @@
const DISTRIBUTED_CACHE_RETRY_MS = 30_000;
const MAX_DISTRIBUTED_CACHE_SCOPES = 128;

// Captured before project code runs: accessor state holds private backend
// objects, and replaced collection or promise prototype methods must never
// observe them (see docs/architecture/15-runtime-adapters.md on the opaque
// snapshot-store handle this accessor can sit behind).
const accessorApply = Reflect.apply;
const AccessorMap = Map;
const accessorMapGet = AccessorMap.prototype.get;
const accessorMapSet = AccessorMap.prototype.set;
const accessorMapDelete = AccessorMap.prototype.delete;
const accessorMapKeys = AccessorMap.prototype.keys;
const accessorMapSize = Object.getOwnPropertyDescriptor(AccessorMap.prototype, "size")!.get!;
const accessorMapIteratorNext = Object.getPrototypeOf(new AccessorMap<string, unknown>().keys())
.next as () => IteratorResult<string>;
const AccessorPromise = Promise;
const accessorPromiseResolve = AccessorPromise.resolve;

interface DistributedCacheAccessorState {
backend: CacheBackend | null | undefined;
lastFailureTime: number;
Expand All @@ -160,21 +176,27 @@
name: string,
getScopeKey?: () => string,
): () => Promise<CacheBackend | null> {
const states = new Map<string, DistributedCacheAccessorState>();
const states = new AccessorMap<string, DistributedCacheAccessorState>();

return () => {
const scopeKey = getScopeKey?.() ?? "";
let state = states.get(scopeKey);
let state = accessorApply(accessorMapGet, states, [scopeKey]) as
| DistributedCacheAccessorState
| undefined;
if (!state) {
if (states.size >= MAX_DISTRIBUTED_CACHE_SCOPES) {
const leastRecentlyUsedScope = states.keys().next().value as string | undefined;
if (leastRecentlyUsedScope !== undefined) states.delete(leastRecentlyUsedScope);
if (accessorApply(accessorMapSize, states, []) >= MAX_DISTRIBUTED_CACHE_SCOPES) {
const iterator = accessorApply(accessorMapKeys, states, []);
const leastRecentlyUsedScope = accessorApply(accessorMapIteratorNext, iterator, [])
.value as string | undefined;
if (leastRecentlyUsedScope !== undefined) {
accessorApply(accessorMapDelete, states, [leastRecentlyUsedScope]);
}
}
state = { backend: undefined, lastFailureTime: 0, inflight: null };
states.set(scopeKey, state);
accessorApply(accessorMapSet, states, [scopeKey, state]);
} else if (getScopeKey) {
states.delete(scopeKey);
states.set(scopeKey, state);
accessorApply(accessorMapDelete, states, [scopeKey]);
accessorApply(accessorMapSet, states, [scopeKey, state]);
}

if (state.backend !== undefined) {
Expand All @@ -186,33 +208,40 @@
logger.debug(`[${name}] Retrying distributed cache initialization after failure`);
}

if (state.backend !== undefined) return Promise.resolve(state.backend);
if (state.backend !== undefined) {
return accessorApply(accessorPromiseResolve, AccessorPromise, [state.backend]) as Promise<

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Prevent inherited then hooks from receiving the backend

When project code installs a callable Object.prototype.then before a store operation, this native Promise.resolve(state.backend) performs thenable assimilation and invokes the inherited hook with the cached API or Redis backend as this; initialization's return b has the same behavior. This is separate from the fixed species path and exposes the opaque backend and its credential-bearing client, while the hook can also resolve null to make storage appear unavailable. Ensure promises carry only an opaque, non-thenable token rather than the raw backend.

AGENTS.md reference: AGENTS.md:L110-L112

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed at a1f53d5 with a deterministic cached-backend reproducer. After successful initialization, installing a callable Object.prototype.then exposes the exact synthetic API backend as the hook receiver on the next accessor call (1 exposure, expected 0), and the hook can replace the resolved result with null. Moving finally cleanup does not address native thenable assimilation. This requires an asynchronous capability contract that carries an opaque, non-thenable token instead of the raw backend, including the initialization path. I am leaving this finding open and keeping the PR draft alongside the atomic-publication blocker. The current Promise path is not ready to satisfy the claimed shared-realm private-storage contract.

CacheBackend | null
>;
}
}

if (!state.inflight) {
const settled = state;
state.inflight = (async () => {
try {
const b = await factory();
if (!isDistributedBackend(b)) {
state.backend = null;
state.lastFailureTime = 0;
settled.backend = null;
settled.lastFailureTime = 0;
logger.debug(`[${name}] No distributed cache available (memory only)`);
return null;
}

state.backend = b;
state.lastFailureTime = 0;
settled.backend = b;
settled.lastFailureTime = 0;
logger.debug(`[${name}] Distributed cache initialized`, { type: b.type });
return b;
} catch (error) {
logger.debug(`[${name}] Failed to initialize distributed cache`, { error });
state.backend = null;
state.lastFailureTime = Date.now();
settled.backend = null;
settled.lastFailureTime = Date.now();
return null;
} finally {
// A synchronous factory failure also yields until inflight is assigned.
await undefined;

Check failure on line 241 in src/cache/backends/factory.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Unexpected `await` of a non-Promise (non-"Thenable") value.

See more on https://sonarcloud.io/project/issues?id=veryfront_veryfront-code&issues=AaCFs78zHXzp_9Hw4kfX&open=AaCFs78zHXzp_9Hw4kfX&pullRequest=4461
settled.inflight = null;
}
})().finally(() => {
state.inflight = null;
});
})();
}

return state.inflight;
Expand Down
15 changes: 10 additions & 5 deletions src/cache/bounded-read.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@ import { utf8ByteLength } from "#veryfront/utils/utf8-byte-length.ts";
import type { CacheBackend } from "./types.ts";

const apply = Reflect.apply;
const NativeSet = Set;
const setHas = NativeSet.prototype.has;
const setAdd = NativeSet.prototype.add;
const freeze = Object.freeze;
const create = Object.create;
const defineProperty = Object.defineProperty;
const getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
const getPrototypeOf = Object.getPrototypeOf;
const numberIsSafeInteger = Number.isSafeInteger;
Expand Down Expand Up @@ -64,14 +69,14 @@ export function captureBoundedCacheRead(
}

let owner: object | null = backend;
const seen = new Set<object>();
const seen = new NativeSet<object>();
try {
for (let depth = 0; owner !== null && depth < MAX_CACHE_CAPABILITY_PROTOTYPE_DEPTH; depth++) {
if (owner === universalObjectPrototype || owner === universalFunctionPrototype) {
return null;
}
if (seen.has(owner)) return null;
seen.add(owner);
if (apply(setHas, seen, [owner])) return null;
apply(setAdd, seen, [owner]);
const parent = getPrototypeOf(owner);
if (owner !== backend && parent === null) return null;
const descriptor = getOwnPropertyDescriptor(owner, "getWithinLimit");
Expand All @@ -83,8 +88,8 @@ export function captureBoundedCacheRead(
return null;
}
const method = descriptor.value as NonNullable<CacheBackend["getWithinLimit"]>;
const captured = Object.create(null) as CapturedBoundedCacheRead;
Object.defineProperty(captured, "getWithinLimit", {
const captured = create(null) as CapturedBoundedCacheRead;
defineProperty(captured, "getWithinLimit", {
value: (key: string, maximumBytes: number) =>
apply(method, backend, [key, maximumBytes]) as Promise<string | null>,
enumerable: true,
Expand Down
40 changes: 30 additions & 10 deletions src/cache/capabilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,30 +16,50 @@ type CapturedRevisionMethods = Readonly<{

type UncheckedCallable = (...args: never[]) => unknown;

// Captured before project code runs: capability inspection receives private
// backend objects, and a replaced reflection global must never observe them.
const reflectApply = Reflect.apply;
const objectFreeze = Object.freeze;
const NativeSet = Set;
const setHas = NativeSet.prototype.has;
const setAdd = NativeSet.prototype.add;
const reflectGetOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor;
const reflectGetPrototypeOf = Reflect.getPrototypeOf;
const reflectOwnKeys = Reflect.ownKeys;
const arrayIsArray = Array.isArray;
const universalObjectPrototype = Object.prototype;
const universalFunctionPrototype = Function.prototype;

const MAX_CACHE_CAPABILITY_PROTOTYPE_DEPTH = 64;

function findCallableDataProperty(
value: object,
key: "getWithRevision" | "compareExchange",
): UncheckedCallable | null {
let current: object | null = value;
const visited = new Set<object>();
const visited = new NativeSet<object>();
let inspectedDepth = 0;

while (current !== null) {
// A capability inherited from a universal prototype is an injection, not
// a backend method: project code adding these names to Object.prototype
// must never have them invoked with a private backend as `this`.
if (current === universalObjectPrototype || current === universalFunctionPrototype) {
return null;
}
if (inspectedDepth >= MAX_CACHE_CAPABILITY_PROTOTYPE_DEPTH) return null;
inspectedDepth += 1;
if (visited.has(current)) return null;
visited.add(current);
if (reflectApply(setHas, visited, [current])) return null;
reflectApply(setAdd, visited, [current]);

const descriptor = Reflect.getOwnPropertyDescriptor(current, key);
const descriptor = reflectGetOwnPropertyDescriptor(current, key);
if (descriptor !== undefined) {
if (!("value" in descriptor) || typeof descriptor.value !== "function") {
return null;
}
return descriptor.value;
}
current = Reflect.getPrototypeOf(current);
current = reflectGetPrototypeOf(current);
}

return null;
Expand Down Expand Up @@ -68,7 +88,7 @@ export function captureRevisionedCacheBackendMethods(
const compareExchange = findCallableDataProperty(backend, "compareExchange");
if (compareExchange === null) return null;

return Object.freeze({
return objectFreeze({
getWithRevision: getWithRevision as RevisionedCacheBackend["getWithRevision"],
compareExchange: compareExchange as RevisionedCacheBackend["compareExchange"],
});
Expand All @@ -87,7 +107,7 @@ export function isRevisionedCacheBackend(
function readOwnDataProperty(value: object, key: string): unknown {
let descriptor: PropertyDescriptor | undefined;
try {
descriptor = Reflect.getOwnPropertyDescriptor(value, key);
descriptor = reflectGetOwnPropertyDescriptor(value, key);
} catch (cause) {
throw new TypeError(`Cache revision ${key} could not be inspected`, { cause });
}
Expand All @@ -99,13 +119,13 @@ function readOwnDataProperty(value: object, key: string): unknown {

/** Validate and detach a provider-returned revision snapshot. */
export function snapshotCacheRevisionResult(value: unknown): CacheRevisionSnapshot {
if (value === null || typeof value !== "object" || Array.isArray(value)) {
if (value === null || typeof value !== "object" || arrayIsArray(value)) {
throw new TypeError("Cache revision result must be an object");
}

let keys: PropertyKey[];
try {
keys = Reflect.ownKeys(value);
keys = reflectOwnKeys(value);
} catch (cause) {
throw new TypeError("Cache revision result could not be inspected", { cause });
}
Expand Down Expand Up @@ -133,7 +153,7 @@ export function snapshotCacheRevisionResult(value: unknown): CacheRevisionSnapsh
);
}

return Object.freeze({ value: snapshotValue, revision });
return objectFreeze({ value: snapshotValue, revision });
}

/** Validate a provider-returned compare-exchange result. */
Expand Down
Loading
Loading