Skip to content

fix(cache): isolate tenants and key every response-affecting input #108

Open

Description

@stackbilt-admin

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

  1. added
    bug
    on Oct 11, 2026
  2. stackbilt-admin commented on Oct 13, 2026

    @stackbilt-admin
    MemberAuthor

    Local implementation checkpoint — 2026-10-12

    This work is uncommitted/unpushed on main, based on 8a9eda6c058d63f0ec08332f6a408aaf409232cf, and is not merged or released. Keep this issue open pending review/integration. The local handoff is docs/maintenance/issue-sweep.md; it will travel with the code.

    Implemented:

    • Versioned SHA-256 request identity includes tenant, namespace, caller key, semantic request fields, metadata/custom gateway routing metadata, provider account/transport options and routing policy. Request IDs and gateway tracing/cache controls are excluded.
    • responseCacheNamespace separates applications/AI bindings/policy revisions. Caller keys cannot override tenant isolation.
    • off and provider-prefix bypass factory reads/writes; response/both use the configured adapter. No strategy preserves adapter opt-in behavior.
    • Circular/non-JSON identities and malformed cached envelopes bypass safely. New keys ignore unsafe old entries.
    • Hits check current local quota policy with zero estimated new spend and mark usage historical (cache.factory.usageKind, currentChargeUsd: 0). They do not record a new provider charge.

    Evidence: src/utils/response-cache.ts, factory/type changes, 45 tests in src/__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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions