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.

Proposal · 25 Nov 2026 Traced on app_release @ a4c809d HLD + LLD + rollout

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?
It can, almost for free.

Both agents would use the same shared analytics tools, so new DSP entities show up in describe_analytics_schema for any agent with those tools. That's why exposure needs a deliberate per-account gate and its own phase (P4), read-only, with rules on how to compare channels.

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 (phase 4)"] -.->|"same tools, gated"| TS

Joining across channels (phase 4 rules)

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. Low-level design

5.1 Entities — adbrew_core/utils/entity_keys.py

Add DSP members with a dsp_ prefix so they never collide with SP's campaign, ad_group, product or audience. Each records its report type and segment.

EntitySource (report type, segment)Finest grain
dsp_accountdspAccount, noneaccount
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)+ asin
dsp_inventorydspInventory, ADGROUPS+ supply_source, site
dsp_geodspGeo, GEO_REGION+ country, region
dsp_techdspTech, ENVIRONMENT_TYPE+ device, OS, environment

Grain fields come from DSP_BREAKDOWN_CONFIGS, so DSP dimensions keep one definition. Each entity gets one finest grain that includes the campaign and line-item IDs where the segment has them; the model rolls up in SQL. Phase 1 disables superset reuse for DSP (no parent-grain derivation) to keep the registry change small.

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

5.3 Ingestion — ingester.py + DSPReportRecordsDAO

  1. _ingest_performance_data dispatches DSP entities to a new _ingest_dsp_data, as it already does for SOV.
  2. A new DSPReportRecordsDAO.build_analytics_ingest_pipeline(...) reuses the DAO's existing builders: _get_date_range_records_match_expr_builder (account, profile, advertiser, report type, segment, dates), _get_scope_filter_expr_builder (campaign / line-item filters), and _add_metrics_to_group_expr_builder (visible metrics). It groups by the grain fields, plus the day/week/month bucket when granularity isn't aggregated.
  3. The pipeline runs through QueryCacheManager into query_cached_records. ClickHouse then builds the reference from it with mongodb() + CTAS: exactly the SP path.
  4. Profile and advertiser IDs come from AccountDetails.dsp_advertiser. An account without a DSP advertiser gets a clear error, not an empty table.
  5. No currency conversion (single account). The reference keeps campaign_currency so the model can check it.

5.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: name, status, delivery status, budget caps, frequency caps, bid) and dsp_creative (dsp_creatives). They're matched on account and advertiser and flattened by the existing JSON staging path. Labels become queryable the way SP labels are, with has(labels, ...).

5.5 API tools — intelligence/tools/analytics.py

5.6 Agent and context

5.7 Unchanged

Frontend (DSP selection and analytics tool labels already exist), the write tools, the reference ownership check, TTL and row caps, and SP's report-records path. The MCP server shares the engine code, so it would get DSP entities when it next syncs; exposing them to MCP clients is a separate decision.

6. 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.

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

P1

Engine PR. Sections 5.1–5.4, plus the tool typing in 5.5. No agent change, so nothing user-visible.

Exit: for 3 real accounts, account, campaign and line-item totals from references equal the DSP dashboard for the same dates; 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 and the Responses API.

Exit: the P0 question set matches raw Mongo; DSP eval not worse than the legacy agent; one to two end-to-end HTTP runs.

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. For accounts with a DSP advertiser, let SP Deep Dive use DSP entities read-only (and the DSP agent use SP entities), with the join rules above in both prompts. Then decide whether one Deep Dive should serve both channels.

Exit: a cross-channel question set graded; merge decision recorded.

7. 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).

8. Decisions for the team

  1. Agree DSP Deep Dive stays a separate agent through P3, with the merge decision in P4.
  2. Accept the campaign_ids typing change (5.5), or keep SP's schema and add DSP-only ID parameters instead.
  3. Use a pilot flag for P2 (recommended: this is a new data source and a new model path), removed in P3.
  4. Choose whether MCP exposes DSP entities in the same release or later.
  5. Decide whether cross-channel access (P4) is on by default for DSP-enabled accounts or opt-in.