Repository navigation
Description
Follow-up to #727 / #732 (shipped as 5.5.0). The framework derivation half is great; this is about the gap blocking salesagent's adoption of PgProposalStore itself.
The gap
ProposalStore.put_draft(account_id=..., proposal_id=..., ...) carries only one identity dimension: account_id. From the Protocol's POV that's the buyer-side scope. For multi-tenant seller deployments, that's insufficient — a single salesagent process serves many seller tenants, each with their own buyer principals. We need both:
- Seller tenant (which publisher's agent is being called)
- Buyer principal (which buyer is calling)
The framework's RequestContext exposes ctx.account but no ctx.tenant / ctx.seller_id. So multi-tenant adopters end up encoding both dimensions into the single account_id field. salesagent does this via f\"{tenant_id}:{ref}\":
Why this is a real correctness issue, not aesthetic
-
FK integrity — adopters want
proposals.tenant_idFK →tenantsso a tenant deletion cascades to their proposals. Without a Protocol-level tenant field, the FK target has to be derived from string-parsingaccount_id. A typo, race, or convention change silently produces orphan rows. -
Cascade delete semantics —
ON DELETE CASCADEfrom a tenant table requires a real column. Adopters can't get this without owning the schema (which is what they're trying to delegate toPgProposalStore). -
Index efficiency — "list proposals for tenant X" wants
WHERE tenant_id = ?(equality on indexed column). Today:WHERE account_id LIKE 'tenant_x:%'(prefix scan). -
Identity conflation — encoding seller and buyer identity into one string at the storage layer means a Protocol change to
account_idframing breaks every adopter that depends on the encoding. The two dimensions should be orthogonal in the store. -
PgProposalStoreschema can't model this — even if adopters wanted a generated columntenant_id GENERATED ALWAYS AS (split_part(account_id, ':', 1)), that couples the upstream library to an adopter encoding convention. Wrong layer.
Concrete proposal (backward-compatible)
Add an optional tenant_id: str | None = None to every ProposalStore Protocol method that already takes account_id / expected_account_id:
class ProposalStore(Protocol):
async def put_draft(
self,
*,
proposal_id: str,
account_id: str,
tenant_id: str | None = None, # NEW — adopters who don't need it ignore it
recipes: Mapping[str, Recipe],
proposal_payload: Mapping[str, Any],
) -> None: ...
async def get(
self,
proposal_id: str,
*,
expected_account_id: str | None = None,
expected_tenant_id: str | None = None, # NEW
) -> ProposalRecord | None: ...
# ... same for try_reserve_consumption, commit, mark_consumed, discard, release_consumption, get_by_media_buy_idFramework wires tenant_id from a new RequestContext field (or however the framework resolves the seller side — happy to defer the source). Single-tenant adopters leave it None and Protocol semantics are unchanged.
For PgProposalStore:
- Add
tenant_id TEXT NULLto the schema. - Filter
tenant_idin WHERE clauses when supplied (alongsideaccount_id). - Adopters who want FK enforcement add
ALTER TABLE … ADD CONSTRAINT … FOREIGN KEY (tenant_id) REFERENCES tenants(...)aftercreate_schema(). Library stays decoupled from any specific tenant table.
ProposalRecord gains an optional tenant_id field for round-tripping.
Why not just leave the encoding as-is
Adopters can keep doing account_id = f\"{tenant_id}:{ref}\". The cost is that every adopter rebuilds the same hack, and the Protocol claims multi-tenant support it doesn't actually carry. This is exactly the shape of #712 / #714 / #720 (filed-shipped-adopted-deleted) — get the right primitive into the library so adopters stop reinventing it.
salesagent timeline (FYI for prioritization)
We're holding off PgProposalStore adoption pending this. Going to adopt the framework derivation half of #732 (the derive_packages_from_allocations=True capability flag) immediately — that part is well-designed and store-agnostic. Will swap our SalesAgentProposalStore for PgProposalStore once this lands.
Happy to draft the PR if useful. Reference adopter shape: bokelley/salesagent#390.
Activity
bokelley commentedon May 14, 2026
Triage
Classification: Feature request
Bucket(s): handlers, middleware (neither label exists in this repo — flagged for label-gap in run summary)
Status: drafting-pr
What the experts said:
NULL = NULLis falsy (needIS NOT DISTINCT FROM);_row_to_recordtuple arity must be extended to match new SELECT column; all dispatch call sites inproposal_dispatch.pymust thread the new dimension;InMemoryProposalStoremedia-buy index tuple must be expanded; migration sync test (test_migration_sql_matches_proposal_store_sql_file) will fail if.sql+migration_sql()+create_schema()diverge. All fixable.tenant_idalready has two distinct meanings in this codebase (ctx.account.metadata["tenant_id"]= router dispatch key;ToolContext.tenant_id= transport-layer field); adding a third meaning silently collides. Recommendspublisher_id/expected_publisher_id. Also:ProposalRecorddataclass ordering bug in the issue's proposal (optional field before required fields →TypeError); and amigration_sql_add_publisher_id()classmethod is needed for adopters upgrading existing tables.My take: Design is sound and non-breaking (all
= Nonedefaults). Drafting PR withpublisher_idnaming (avoids codebase collision),IS NOT DISTINCT FROMSQL filtering, dispatch layer threading viactx.tenant_id, and a dedicated migration helper. Single-tenant adopters see zero behaviour change.Triaged by Claude Code. Session: https://claude.ai/code/session_01LNqGrRYB4a9gLycJcGDEXA
Generated by Claude Code
feat(decisioning): add publisher_id to ProposalStore for multi-tenant…
feat(decisioning): add publisher_id to PgProposalStore and proposal_d…
bokelley commentedon May 14, 2026
Closing as wrong-layer after a closer read of
AccountStore.resolve()semantics.What I got wrong
I treated
account_idat the ProposalStore layer as the buyer-side wire reference. It isn't. By the time any downstream store (ProposalStore/IdempotencyStore/TaskRegistry) sees it, the adopter'sAccountStore.resolve()has already minted a resolvedAccount.idthat the adopter fully controls. Multi-tenant adopters encode tenant scope intoAccount.idat the AccountStore layer — exactly the patterncreate_tenant_storecodifies.salesagent already does this correctly:
SalesagentAccountStore.resolve()mintsaccount.id = f"{tenant_id}:{ref}"and stampsaccount.metadata = {"tenant_id": tenant_id}for adopter-internal use. The bug was on our side —SalesAgentProposalStore._resolve_tenant_id_for_accountreaches back intoaccount.idand parses it, when it should treataccount.idas opaque and readaccount.metadata["tenant_id"]if it needs the tenant. That's a salesagent fix, not a Protocol change.Why the four consequences I listed dissolve
accounts → proposalslayer (proposals.account_id → accounts.account_id ON DELETE CASCADE), nottenants → proposals. The accounts table is the right hop. If an adopter has no accounts table (because their AccountStore is computed-not-persisted), application-layer cleanup on tenant delete is the honest choice — not a workaround for a Protocol gap.WHERE account_id IN (SELECT account_id FROM accounts WHERE tenant_id = ?)is equality-on-indexed on both sides. Adopters without an accounts table can keep a prefix scan, which they're already paying for with the encoding choice.account.id), which is the right number.(account_id, proposal_id)PK never collides becauseaccount.idis already globally unique by virtue of the tenant prefix the AccountStore put there. The collision surface I worried about was an artifact of imagining adopters might pass raw buyer refs through — they don't, because the framework runsresolve()first.Follow-up, separate issue
The real gap is documentation: adopters need a clear pointer to the encoding seam. Filing a small docs-only issue/PR for that —
AccountStoredocstring should call out the multi-tenant encoding pattern, andProposalStore/IdempotencyStore/TaskRegistrydocstrings should state explicitly that they treataccount.idas opaque.create_tenant_storemention as the canonical example. Should be a ~30-line diff, not a Protocol change.Sorry for the noise here — appreciate the pushback that surfaced this.
docs(decisioning): document AccountStore.resolve() as the multi-tenan…