Adbrew Intelligence · Design proposal

DSP Deep Dive on ClickHouse

Move DSP Deep Dive's read tools onto the same reference-and-SQL analytics engine that Sponsored Ads Deep Dive uses. Keep its DSP prompt, write tools and selection UI.

Final plan · 26 Nov 2026 Reviewed by Codex (gpt-6.2-sol) Traced on app_release @ a4c809d HLD + LLD + rollout

Review status. An independent Codex review (26 Nov, read-only, against app_release) approved the shared-engine design. It found three blockers that this version fixes in the plan: DSP source selection in ingestion, reference ownership on two existing engine paths, and an eval harness that couldn't run DSP cases as drafted. It also corrected how combined totals get their numbers and the eval budget. Each change is marked "Review" below.

The three questions first

Will DSP data join with SP data?
Yes, within one account.

An Adbrew account holds both its SP data and its DSP advertiser (AccountDetails.dsp_advertiser), so SP and DSP references share an account_id. One query_reference call can already join any references the account owns. Sensible join keys are date and ASIN. Campaign IDs never match across channels.

Will SP Deep Dive see DSP data?
Yes, read-only, but not by default.

Both agents use the same analytics tools, so either can prepare the other channel's entities. Each agent answers in its own channel unless the user asks about the other or the question needs it. Cross-channel answers show each channel side by side and never blend them into one number (section 5).

Does DSP Deep Dive still make sense?
As its own data stack, no. As its own entry point, yes for now.

After migration the only DSP-specific parts left are the prompt, three DSP write tools and DSP campaign/line-item selection. Keep them as a separate agent until evals show one agent can handle both channels without losing quality. Then merge.

1. Reference: how Sponsored Ads moved

The Sponsored Ads migration set the pattern this plan copies. Each stage had an exit condition before the next began.

StageWhat it didCondition carried forward
Engine import
#5052
Copied the analytics engine and service into the API with small compatibility edits (Python 3.8, driver 0.4.8, JSON rows, lazy engine).One analytical implementation; Mongo stays the source of truth; ClickHouse holds short-lived derived tables.
Internal pilot
#5053
Config flag + internal-admin gate. Analytics tools added, overlapping fixed reports hidden. Product-scoped chats kept the old tools.Kill switch while unproven; reduced tool list so the model isn't choosing between two ways to read the same data.
Evaluation
#5113 + E2E
Decision-quality eval plus HTTP/model runs checked against raw-Mongo totals.Numbers must match an independent raw-Mongo recomputation, not just "look right".
Customer rollout
#5163
Flag removed. Chat selection became guidance; tools filter only by explicit arguments. Replaced reports deleted. Old chats get one refreshed instruction on their next message or Retry.One behaviour for everyone; no hidden filtering; old saved instructions must not contradict the tools.
Follow-ups#5284 product entity fix, #5297 analytics tools in MCP, #5385 AMC agent on the shared tools, charts. Open: #5176 tool-cache scope, #5168 AI Recommendations.Other agents adopt analytics by adding ANALYTICS to their Toolset (the AMC change is ~25 lines).

Invariants every new data source must keep

2. DSP Deep Dive today

3. What moves, what stays, what goes

ItemDecisionReplacement or reason
get_account_performancemovesPrepare dsp_account for both periods; compare in SQL.
get_campaign_top / _trendingmovesdsp_campaign reference; any metric, sort, filter or period comparison.
get_adgroup_top / _trendingmovesdsp_ad_group (line items).
get_creatives_top / _trendingmovesdsp_creative, with creative type.
get_inventory_top / _trendingmovesdsp_inventory (supply source, site).
get_audience_top / _trendingmovesdsp_audience (segment, type, targeting method).
get_product_top / _trendingmovesdsp_product at ASIN level.
get_geo_top / _trendingmovesdsp_geo (country, region).
get_tech_top / _trendingmovesdsp_tech (device, OS, environment).
Campaign, flight and line-item write toolsstaysUnchanged approval flow and change history. Flight edits stay current-flight-only, as today.
User-defined account context toolstaysShared by every agent.
DSP prompt and DSP selection UIstaysPrompt updated for references and attribution; selection becomes guidance.
Legacy read factory and hard-scope read resolutiongoesDeleted at customer rollout. No other caller exists (checked with git grep).
"Automatically filter" instruction and scope errorsgoesReplaced by a guidance formatter, as in SP.
Postal code / city geo, multi-account currency conversionnot coveredNot exposed today either (postal/city commented out in the geo DAO; Deep Dive is single-account).

4. High-level design

DSP becomes a second source inside the existing engine, next to report records and Share of Voice. No new service and no new tools: the DSP agent gets the same ANALYTICS tool group, and the engine learns DSP entities.

flowchart TD
  UI["DSP Deep Dive chat"] --> AG["DSPPerformanceDiagnose
DSP prompt · selection as guidance"] AG --> TS["Toolset: ANALYTICS
+ 3 DSP write tools"] TS --> SVC["analytics_service (adbrew_core)"] SVC --> ENG["AnalyticsEngine
registry · ingester · ops"] ENG -->|"SP entities"| SP["report_records path
(unchanged)"] ENG -->|"DSP entities (new)"| DSPI["DSP ingest path
DSPReportRecordsDAO pipeline"] DSPI --> MQ["Mongo: aggregate + $merge
query_cached_records (15 min)"] SP --> MQ MQ -->|"mongodb() read"| CH[("ClickHouse analytics.ds_*
references, 15-min TTL")] ENG -->|"entity refs"| META["dsp_campaigns · dsp_adGroups · dsp_creatives"] META --> CH SPA["SP Deep Dive (P4)"] -.->|"same tools, read-across"| TS

Joining across channels (details in section 5)

Join keyValid?Caveat the prompt must state
Date (dt)YesThe DSP advertiser has its own timezone (dsp_advertiser.timezone); if it differs from the SP profile, days don't align exactly.
ASINYesDSP product rows come from the ASIN-level product report; SP from product ads.
Account totalsYes, side by sideDSP sales include view-through attribution and overlap with SP sales. Never add them into one "total sales".
Campaign / ad group IDsNoDifferent ID spaces and types (DSP strings, SP integers).
MoneyCheck firstDSP reports carry campaign_currency; compare only when it matches the SP account currency.

5. Cross-channel behaviour

A prepare call never mixes channels: entity="campaign" builds SP campaigns from report_records, and entity="dsp_campaign" builds DSP campaigns from dsp_report_records. So "can SP and DSP see each other's data" really asks two things: which entities each agent may prepare, and when it should combine them in SQL.

5.1 The rule: read across, answer at home, never blend

5.2 Why not the two extremes

OptionWhat goes wrong
Hard exclusion (each agent sees only its channel)Rebuilds the wall we just removed for selections. Natural questions ("did DSP lift branded search?", "why did total ad spend jump?") get "open the other agent". The tools are already shared, so the wall would be extra code that makes the product worse.
Open and blended by default"Account ROAS" with DSP folded in is a different, inflated number: DSP sales include view-through attribution and overlap SP sales. DSP campaigns are often judged on reach or awareness, not ROAS. Timezone and currency may differ. A user who opened Deep Dive from an SP page expects SP numbers.
Recommended: open, home-first, side by sideCross-channel questions work in either agent; everyday questions keep their current meaning.

5.3 What each agent prepares, by question

User asksSP Deep DiveDSP Deep Dive
"How is my account doing?"SP entities only. If the account has DSP, one closing line offers to include it.DSP entities only; offers SP the same way.
"Which campaigns are wasting spend?"SP campaigns.DSP campaigns and line items, judged against each campaign's goal and KPI.
"Did DSP lift my branded search sales?"Prepare dsp_account daily and SP branded search terms daily, join on dt, show both series side by side with any lag. Say plainly this shows timing, not cause, and point to AMC for real overlap analysis.
"What's my total ad spend across SP and DSP?"Prepare both at account level. Spend can be summed when currencies match; sales and ROAS stay per channel.
"How is ASIN B0… doing across all ads?"SP product and dsp_product, joined on ASIN, side by side.
"Pause DSP line item X" (asked in SP Deep Dive)Explains it can read DSP data but changes must be made in DSP Deep Dive.Normal approval flow.

5.4 Which metrics can be combined

MetricSum across channels?Why
Spend / total costYes, if the currency matchesMoney actually spent; no attribution involved.
Impressions, clicksSide by side onlyDSP counts display and video impressions under different rules than sponsored-ads placements.
Sales, orders, unitsNoBoth channels can claim the same purchase; DSP includes view-through.
ROAS, ACOS, conversion rateNo; per channelBuilt from sales, so they inherit the overlap.
New-to-brandNo; per channelEach channel measures it against its own attribution.

5.5 Account setups

SetupWhat works
SP and DSP on one Adbrew accountEverything above. References share an account_id, so the ownership check allows joins.
SP onlyNo DSP entities in the schema; preparing one returns a clear "this account has no DSP advertiser" error.
DSP only (is_dsp_only)DSP Deep Dive only; SP entities hidden the same way.
Same brand, SP and DSP on two Adbrew accountsNo join today: every reference must belong to the chat's single account. The engine already supports multi-account references (MCP uses them), so a later "linked accounts" feature could allow it with an explicit link and an access check on both accounts. Not in this plan.

How many customers use the two-account setup decides how much cross-channel value this delivers. Measuring it is added to P0.

5.6 Schema per account

v1 decision: group the schema by channel and filter it to the channels the account has, showing both sides in full. The channel argument and per-channel summaries below are deferred until token use is measured.

Today: the API tool calls service.describe_analytics_schema, which calls engine.describe_schema() with no account. Every chat gets the same full list of SP entities, metrics and joins, whatever the account has.

Proposed flow:

  1. Give every Entity a channel (sp or dsp; Share of Voice counts as sp). Metric sets and joins are grouped the same way.
  2. The API tool works out which channels the account has from data the account record already carries: SP unless Sponsored Ads is disabled, DSP when dsp_advertiser is set (is_dsp_enabled).
  3. The tool takes an optional channel argument naming the channel to return in full. Each agent's own tool description (its TOOL_CONFIGS override, applied by add_tool_info) tells the model to call it with that agent's channel. SP Deep Dive passes sp, DSP Deep Dive passes dsp.
  4. engine.describe_schema(channels, detailed) returns the full block for the detailed channel and a short block for any other channel the account has. Channels the account lacks are left out entirely.
  5. Asking for a channel's full details is just another call with that channel.

Why an argument, not a new ToolContext field: ToolContext's own rule is to add a field only if every caller, MCP included, can provide it. MCP has no home channel. Per-agent tool descriptions are the existing mechanism for exactly this kind of agent difference, and the server still decides availability from the account, so a wrong argument can't expose data the account doesn't have.

Response shape (DSP Deep Dive, account with both channels):

{
  "channels": {
    "dsp": { "detail": "full", "timezone": "America/New_York", "currency": "USD",
             "entities": { "dsp_campaign": {...}, "dsp_ad_group": {...}, ... },
             "additive_metrics": [...], "derived_metrics": {...}, "valid_joins": [...] },
    "sp":  { "detail": "summary", "timezone": "America/Los_Angeles", "currency": "USD",
             "entities": ["campaign", "ad_group", "keyword", "search_term", "product", ...],
             "more": "call describe_analytics_schema(channel='sp') for grains and metrics" }
  },
  "cross_channel": { "joins": [...], "rules": "..." }
}

Knowing the account also lets the schema report each channel's timezone and currency. The model needs those to apply the cross-channel rules, and today it has no way to see them.

MCP: MCP's schema call takes no account, so it keeps returning every channel in full, each section tagged with its channel. Its behaviour is unchanged except for the new DSP section.

5.7 Token cost

5.8 Naming and wrong-channel mistakes

5.9 Where the cross-channel rules live

5.10 Other changes

5.11 Where real attribution lives

Deep Dive can show that DSP spend and SP branded sales moved together. It can't say how many SP sales DSP caused, because the two report sources don't share users or exposure paths. Overlap and path-to-conversion questions belong to AMC, which already has its own agent. Cross-channel prompts should say this and offer AMC when the user asks about cause.

5.12 How to check it

6. Low-level design

6.1 Entities — adbrew_core/utils/entity_keys.py

Add DSP members with a dsp_ prefix and a channel attribute (sp or dsp), so they never collide with SP's campaign, ad_group, product or audience. Grain names get the prefix too, because grain names are global keys in GRAIN_FIELDS.

EntitySource (report type, segment)Finest grain
dsp_accountdspAccount daily rollup (null segment); see 6.3 for filtered requestsaccount
dsp_campaigndspCampaign, CAMPAIGNSaccount, campaign_id
dsp_ad_groupdspCampaign, ADGROUPSaccount, campaign_id, adgroup_id
dsp_creativedspCampaign, CREATIVES+ creative_id, creative_type
dsp_audiencedspAudience, ADGROUPS+ audience_segment_id, type, targeting_method
dsp_productdspProduct, ADGROUPS, ASIN-level rows only+ asin
dsp_inventorydspInventory, ADGROUPS+ supply_source, site
dsp_geodspGeo, GEO_REGION+ country, region
dsp_techdspTech, ENVIRONMENT_TYPE+ device, OS, environment

6.2 Columns and metrics — new analytics_client/shared/dsp.py

6.3 Ingestion — ingester.py + DSPReportRecordsDAO

  1. _ingest_performance_data dispatches DSP entities to a new _ingest_dsp_data, as it does for SOV.
  2. Review: source selection must follow the DAO. dspAccount is a persisted daily rollup with a null segment. When campaign or line-item filters are present, the legacy DAO switches to dspCampaign CAMPAIGNS / ADGROUPS rows before filtering (_get_scoped_report_config). Filtering the rollup directly returns nothing. The new pipeline builder reuses that decision.
  3. Review: product rows. Keep the DAO's ASIN-level match so parent-ASIN rollups don't inflate product totals.
  4. Review: dimensions. The DAO's metric accumulator skips CONST fields. Project each grain's dimensions explicitly into the group key and flatten them before staging. campaign_currency isn't visible or present on dspAccount, so currency comes from the account (see 5.6).
  5. Review: scope. Match the authorized account's account / profile / advertiser tuple for performance and metadata. A second advertiser on the same account must never leak in.
  6. Review: dates. Stored YYYYMMDD report dates are calendar labels in the advertiser's timezone. Keep them as labels and fix the week boundary (Monday, as in SP). Daily rows can't be moved into another timezone exactly, so the cross-channel rules say so.
  7. Run the pipeline through QueryCacheManager into query_cached_records; ClickHouse builds the reference with mongodb() + CTAS, the SP path. Review: cache metadata is created before the Mongo fill finishes, so a failed fill can look like an empty hit. Test failure and retry, and treat an unfinished fill as an error, not as zero rows.
  8. An account without a DSP advertiser gets a clear error, not an empty table.

6.4 Entity metadata — dao_registry.py

prepare_entity_reference gains dsp_campaign (dsp_campaigns: name, state, goal, KPI, budget, flights, labels), dsp_ad_group (dsp_adGroups) and dsp_creative (dsp_creatives), flattened by the existing JSON staging path. Review: the registry's current pipeline casts campaign IDs to integers, so DSP needs its own path with string IDs and the account / profile / advertiser match.

6.5 Engine fixes that ship with DSP (Review)

6.6 API tools — intelligence/tools/analytics.py

6.7 Canonical cross-channel totals (Review)

6.8 Agent and context

6.9 Unchanged

Frontend, the write tools, TTL and row caps, and SP's report-records path. MCP is unchanged until DSP exposure there is decided.

7. Rollout lifecycle

P0

Measure first. Count dsp_report_records rows per report type for the largest DSP accounts (inventory and geo are the likely heavy ones). Pull recent DSP Deep Dive questions. Build 10–15 questions with raw-Mongo answers. Fill a parity matrix of the 17 tools against the new entities. Count how many DSP customers have SP on the same Adbrew account versus a separate one (5.5).

Exit: row counts known; any entity too large for a 90-day prepare has a date-range cap.

P1

Engine PR. Sections 6.1–6.5 and the DSP filters in 6.6, with DSP entities behind an allow-list so no public prepare path (chat or MCP) exposes them yet.

Exit: for 3 real accounts, account, campaign, line-item and ASIN totals from references equal the DSP dashboard for the same dates, including a filtered request and a month boundary; one critical test only.

P2

Internal pilot PR. DSP agent on the shared toolset, behind a config flag plus the internal-admin check (the #5053 pattern). Legacy read tools hidden when it's on. Guidance context. Chat Completions kept. Bench changes from the eval plan land here too.

Exit: the ship gate in section 10.

P3

Customer rollout PR. Remove the flag, delete the legacy read factory and hard-scope code, refresh old-chat instructions, post the announcement.

Exit: first deployed smoke test on production; ClickHouse load checked against the capacity baseline.

P4

Cross-channel. Turn on read-across per section 5: schema per account, engine guards, channel tags and the shared cross-channel note in both prompts. Then decide whether one Deep Dive should serve both channels, with its home channel set by where the user opened it.

Exit: the 5.12 checks pass and the SP question set is unchanged on a DSP-enabled account; merge decision recorded.

8. Risks

RiskWhy it mattersMitigation
Data volumeSite-level inventory and geo rows can be large; the staging cache and ClickHouse table hold all of them.P0 measurement; default to aggregated granularity; cap date ranges where needed.
Model path changeDSP moves from Chat Completions to the Responses API and gains SQL tools at the same time.Pilot flag; eval gate in P2; the two changes stay separable if the eval regresses.
SP schema changeWidening campaign_ids to strings changes SP Deep Dive's tool schema.One SP check that the model still passes integer IDs correctly.
Double-counted salesDSP view-through sales overlap SP sales.Prompt rule; cross-channel only in P4.
Timezone and currencyDay boundaries and currencies can differ between the SP profile and the DSP advertiser.Expose both in the schema; prompt checks before comparing.
Engine drift with MCPThe engine is shared code on two branches.Land DSP engine changes where both branches take them (the convergence plan).

9. Decisions (after review)

DecisionOutcome
Separate DSP agent through rolloutYes. Keep entry-point defaults, selection context and write approvals. A merge is not part of the rollout gate.
campaign_ids typeKeep SP's integer contract; add dsp_campaign_ids / dsp_ad_group_ids as strings (6.6).
Pilot flagYes. Reads and selection guidance switch together. Chat Completions kept for the first comparison.
MCP exposureLater, after DSP filters and multi-account ownership (6.5) are covered.
Cross-channel defaultRead across, home channel first, side by side. Explicit "overall" requests use the canonical retail-based totals (6.7). No per-agent read wall.
Summing spendYes, for comparable scope in one currency, using the dashboard's conversion; disclose the currency.
Linked accounts (SP and DSP on separate Adbrew accounts)Defer. Measure in P0; this release is single-account.

10. Evaluation

The plan is only useful if the agent actually behaves this way, so the release is gated on evals in the existing pre-release bench (src/intelligence_bench). Full details are in eval/EVAL-PLAN.md, eval/FIXTURE.md and 22 draft cases in eval/cases/.