Repository navigation
Description
Priority and outcome
P0 · impact H · effort S · patch · risk: cache misses after a versioned key change.
Two calls with identical messages/model/temperature/maxTokens but different tenant identity or system instructions currently reuse the same cached completion. Fix this before promoting the package for multi-tenant Workers.
Evidence
Audited v1.21.0 at commit 8a9eda6.
- src/factory.ts:253: the key includes only four fields; omits tenantId, systemPrompt, tools, builtInTools, images, response_format, seed, LoRA and provider options.
- src/factory.ts:417: cache lookup returns before route planning and quota checks.
- src/types.ts:70 and src/factory.ts:415: request cache strategy is not consulted by the factory cache; even strategy 'off' performs lookup/write.
- src/tests/factory.test.ts:1197: existing cache tests cover hit/miss/get failure, not semantic collisions.
Verified locally: compiled source into a temporary directory and used a synthetic fetch + Map adapter. Tenant A/system A followed by tenant B/system B causes one fetch; B receives a factory cache hit. No live vendor requests were made.
PR-ready change
Keep the adapter contract. Hash a versioned deterministic identity with Web Crypto; tenant scope must be included even when the caller supplies a cache key. Default metadata handling should be conservative because metadata.useCase changes routing.
import type { LLMRequest } from './types.js';
function stableJson(value: unknown): string {
if (value === null || typeof value !== 'object') {
return JSON.stringify(value) ?? 'null';
}
if (Array.isArray(value)) {
return '[' + value.map(stableJson).join(',') + ']';
}
const record = value as Record<string, unknown>;
return '{' + Object.keys(record)
.filter(key => record[key] !== undefined)
.sort()
.map(key => JSON.stringify(key) + ':' + stableJson(record[key]))
.join(',') + '}';
}
export async function deriveResponseCacheKey(
request: LLMRequest,
namespace: string
): Promise<string> {
const { requestId, gatewayMetadata, cache, ...semanticRequest } = request;
const identity = {
version: 2,
namespace,
tenantId: request.tenantId ?? null,
callerKey: cache?.key ?? null,
request: semanticRequest
};
const digest = await crypto.subtle.digest(
'SHA-256',
new TextEncoder().encode(stableJson(identity))
);
const hex = Array.from(new Uint8Array(digest))
.map(byte => byte.toString(16).padStart(2, '0'))
.join('');
return 'llmp:v2:' + hex;
}Add optional responseCacheNamespace to ProviderFactoryConfig to separate applications and routing-policy revisions. The hash deliberately excludes request ID and gateway tracing fields; if gateway custom metadata influences a downstream dynamic route, include the relevant routing metadata in identity or bypass caching. Validate circular/non-JSON metadata and bypass safely.
Apply cache policy in one place: off/provider-prefix bypass local response caching; response/both enable it; retain existing adapter-level opt-in behavior when no request strategy is given. Scope explicit keys by tenant. Do not implicitly authorize a tenant from a cache hit; document whether quotaHook gates access as well as spend and put access authorization before cache when required.
Tests / acceptance
- Different tenant/system/tools/images/schema/seed/LoRA/reasoning/useCase never collide.
- Object key ordering is stable; prompt content never appears in keys or telemetry.
- strategy off bypasses get and put; response/both work; provider-prefix only does not cache whole responses.
- Caller keys cannot cross tenant/application scopes.
- Cache hit usage is marked historical and not mistaken for newly billed provider usage.
- Key v2 ignores old unsafe entries; corrupt cached envelopes bypass instead of becoming responses.
- Zero runtime dependencies; Workers Web Crypto test.
Semver and README
Patch: fixes unsafe key equivalence; version the cache namespace and note the one-time drop in hit rate. New optional namespace is additive.
Suggested README text:
Factory response caching is opt-in. Entries are hashed from the complete request and isolated by tenant and application namespace. Use cache.strategy: 'off' for agent/tool turns that must run fresh. Prompt caching and response caching remain separate.
Related: #85 covers AI Gateway cache semantics; this issue fixes the independent factory adapter defect.
Activity
stackbilt-admin commentedon Oct 13, 2026
Local implementation checkpoint — 2026-10-12
This work is uncommitted/unpushed on
main, based on8a9eda6c058d63f0ec08332f6a408aaf409232cf, and is not merged or released. Keep this issue open pending review/integration. The local handoff isdocs/maintenance/issue-sweep.md; it will travel with the code.Implemented:
responseCacheNamespaceseparates applications/AI bindings/policy revisions. Caller keys cannot override tenant isolation.offandprovider-prefixbypass factory reads/writes;response/bothuse the configured adapter. No strategy preserves adapter opt-in behavior.cache.factory.usageKind,currentChargeUsd: 0). They do not record a new provider charge.Evidence:
src/utils/response-cache.ts, factory/type changes, 45 tests insrc/__tests__/tenant-safety.test.ts, README and changelog.Remaining: review/integration and an actual Workers runtime Web Crypto/cache test. This fixes the factory layer; it does not replace the independent AI Gateway cache contract in #85.
Validation for the combined local sweep: 605 tests pass across 27 files, TypeScript typecheck passes, Worker-targeted bundle/import smoke passes. Packed entrypoint exports/client methods and all 33 JavaScript sourcemaps were checked on Windows with Node 24.19.0/npm 11.17.0. No live/billable providers or workerd execution; this does not prove minimum Node-version compatibility.
feat: streaming lifecycle, tenant-safe caching, client-scoped resilie…