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.
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.
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.
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.
The Sponsored Ads migration set the pattern this plan copies. Each stage had an exit condition before the next began.
| Stage | What it did | Condition 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). |
DATASET_TTL); reads are capped at 10,000 rows.validate_select_sql, ratio check).query_cached_records staging cache.report_records gets its own ingest path. Share of Voice is the precedent (Entity.SOV, shared/sov.py, _ingest_sov_data).DSPPerformanceDiagnose uses Chat Completions on gpt-5.4 by default, with parallel tool calls off. It has no shared Toolset; all tools come from the legacy factory get_dsp_performance_diagnose_tools, whose only caller is this agent.DSPDashboardController. Account performance, plus "top" and "trending" for campaign, line item, creative, inventory, audience, product, geo and tech, each fixed at 10 rows.DSPPerformanceAgentContext (campaign_ids, adgroup_ids) still uses the old hard scope: "Tool outputs will automatically filter to these campaigns only."dsp_report_records keyed by account_id, dsp_profile_id, dsp_advertiser_id, report_type and segment, daily. Metadata comes from dsp_campaigns, dsp_adGroups and dsp_creatives. DSP IDs are strings.dsp_metric_configs.py. 354 stored metrics (65 visible; 286 summed, 68 constant/dimension) and 40 derived metrics. All 40 derived metrics are simple two-input ratios (e.g. eCPM = cost × 1000 / impressions).DSP_BREAKDOWN_CONFIGS maps each dimension (campaign, line item, creative, audience, ASIN, supply source, site, country, region, device, OS, environment, goal) to its report type, segment and field. It's the natural source for DSP grains.| Item | Decision | Replacement or reason |
|---|---|---|
get_account_performance | moves | Prepare dsp_account for both periods; compare in SQL. |
get_campaign_top / _trending | moves | dsp_campaign reference; any metric, sort, filter or period comparison. |
get_adgroup_top / _trending | moves | dsp_ad_group (line items). |
get_creatives_top / _trending | moves | dsp_creative, with creative type. |
get_inventory_top / _trending | moves | dsp_inventory (supply source, site). |
get_audience_top / _trending | moves | dsp_audience (segment, type, targeting method). |
get_product_top / _trending | moves | dsp_product at ASIN level. |
get_geo_top / _trending | moves | dsp_geo (country, region). |
get_tech_top / _trending | moves | dsp_tech (device, OS, environment). |
| Campaign, flight and line-item write tools | stays | Unchanged approval flow and change history. Flight edits stay current-flight-only, as today. |
| User-defined account context tool | stays | Shared by every agent. |
| DSP prompt and DSP selection UI | stays | Prompt updated for references and attribution; selection becomes guidance. |
| Legacy read factory and hard-scope read resolution | goes | Deleted at customer rollout. No other caller exists (checked with git grep). |
| "Automatically filter" instruction and scope errors | goes | Replaced by a guidance formatter, as in SP. |
| Postal code / city geo, multi-account currency conversion | not covered | Not exposed today either (postal/city commented out in the geo DAO; Deep Dive is single-account). |
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
| Join key | Valid? | Caveat the prompt must state |
|---|---|---|
Date (dt) | Yes | The DSP advertiser has its own timezone (dsp_advertiser.timezone); if it differs from the SP profile, days don't align exactly. |
| ASIN | Yes | DSP product rows come from the ASIN-level product report; SP from product ads. |
| Account totals | Yes, side by side | DSP sales include view-through attribution and overlap with SP sales. Never add them into one "total sales". |
| Campaign / ad group IDs | No | Different ID spaces and types (DSP strings, SP integers). |
| Money | Check first | DSP reports carry campaign_currency; compare only when it matches the SP account currency. |
adbrew_core/utils/entity_keys.pyAdd 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.
| Entity | Source (report type, segment) | Finest grain |
|---|---|---|
dsp_account | dspAccount, none | account |
dsp_campaign | dspCampaign, CAMPAIGNS | account, campaign_id |
dsp_ad_group | dspCampaign, ADGROUPS | account, campaign_id, adgroup_id |
dsp_creative | dspCampaign, CREATIVES | + creative_id, creative_type |
dsp_audience | dspAudience, ADGROUPS | + audience_segment_id, type, targeting_method |
dsp_product | dspProduct, ADGROUPS (ASIN level) | + asin |
dsp_inventory | dspInventory, ADGROUPS | + supply_source, site |
dsp_geo | dspGeo, GEO_REGION | + country, region |
dsp_tech | dspTech, 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.
analytics_client/shared/dsp.pyshared/sov.py. DSP ID columns are String (SP's campaignId is Int64); DSP raw names (campaign_id, adgroup_id) stay distinct from SP's camelCase names.DSPMetricConfigs: visible SUM metrics become additive columns, visible CONST metrics become dimensions. Nothing is hand-listed, so new DSP metrics flow through.create_derived_metric_config to record numerator, denominator and multiplier alongside the existing Mongo lambda. That gives SQL the same ratio definitions as the dashboard, from one source, and fits the engine's existing (numerator, denominator, multiplier) shape used for SP.SUM(ecpm).ingester.py + DSPReportRecordsDAO_ingest_performance_data dispatches DSP entities to a new _ingest_dsp_data, as it already does for SOV.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.QueryCacheManager into query_cached_records. ClickHouse then builds the reference from it with mongodb() + CTAS: exactly the SP path.AccountDetails.dsp_advertiser. An account without a DSP advertiser gets a clear error, not an empty table.campaign_currency so the model can check it.dao_registry.pyprepare_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, ...).
intelligence/tools/analytics.pydescribe_analytics_schema gains a DSP section; analytics_descriptions.py adds DSP entities, grains and attribution notes.campaign_ids is typed List[int] today, which DSP's string IDs can't use. Proposal: type it as a list of strings, and have the engine cast per source (int for SP, str for DSP). Add an optional ad_group_ids for DSP. This changes the SP tool schema, so it needs one SP regression check.DSPPerformanceDiagnose.toolset = Toolset(groups=[ANALYTICS, knowledge]); get_tools() returns only the 3 write tools. This mirrors the AMC change in #5385.use_responses_api = True). This changes the model call path, so it lands in the pilot and is judged by the eval, not assumed.DSPPerformanceAgentContext.build_context_message becomes a guidance formatter that prints the selected campaign and line-item IDs, as SP's does. Read-side resolution and scope errors are removed with the legacy read tools.should_update_context also compares the saved instruction text, so old DSP chats get one corrected instruction on their next message or Retry.dsp_performance_analysis_prompt): describe the DSP entities, view-through attribution and currency, and say not to sum DSP and SP sales.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.
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.
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.
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.
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.
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.
| Risk | Why it matters | Mitigation |
|---|---|---|
| Data volume | Site-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 change | DSP 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 change | Widening campaign_ids to strings changes SP Deep Dive's tool schema. | One SP check that the model still passes integer IDs correctly. |
| Double-counted sales | DSP view-through sales overlap SP sales. | Prompt rule; cross-channel only in P4. |
| Timezone and currency | Day 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 MCP | The engine is shared code on two branches. | Land DSP engine changes where both branches take them (the convergence plan). |
campaign_ids typing change (5.5), or keep SP's schema and add DSP-only ID parameters instead.