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.
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.
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 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).
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 (P4)"] -.->|"same tools, read-across"| 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. |
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.
Toolset.| Option | What 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 side | Cross-channel questions work in either agent; everyday questions keep their current meaning. |
| User asks | SP Deep Dive | DSP 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. |
| Metric | Sum across channels? | Why |
|---|---|---|
| Spend / total cost | Yes, if the currency matches | Money actually spent; no attribution involved. |
| Impressions, clicks | Side by side only | DSP counts display and video impressions under different rules than sponsored-ads placements. |
| Sales, orders, units | No | Both channels can claim the same purchase; DSP includes view-through. |
| ROAS, ACOS, conversion rate | No; per channel | Built from sales, so they inherit the overlap. |
| New-to-brand | No; per channel | Each channel measures it against its own attribution. |
| Setup | What works |
|---|---|
| SP and DSP on one Adbrew account | Everything above. References share an account_id, so the ownership check allows joins. |
| SP only | No 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 accounts | No 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.
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:
Entity a channel (sp or dsp; Share of Voice counts as sp). Metric sets and joins are grouped the same way.dsp_advertiser is set (is_dsp_enabled).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.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.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.
dsp_ prefix (dsp_campaign, grain dsp_campaign). Grain names are global keys in GRAIN_FIELDS, so a DSP campaign grain would collide with SP's.campaignId (integer), DSP uses campaign_id (string). Descriptions must say so, because a model joining an SP and a DSP reference on campaign ID would get nothing, or wrong matches.entity argument stays a string. An enum in the tool schema would list both channels' names for every agent and every account, so it wouldn't prevent a wrong-channel choice. The server validates instead.list_references row includes channel. A model that prepared campaign while answering a DSP question sees "channel": "sp" in the result.LLMUtils.get_standard_prompt_template reads ConfigDAO per environment. Rules written into two DB prompts aren't reviewed in PRs, aren't versioned, and can drift between the agents and between environments.CROSS_CHANNEL_RULES constant in analytics_descriptions.py, returned in the schema's cross_channel block only when the account has both channels. SP-only and DSP-only accounts never see them.Toolset contains only its own channel's write tools, so no new checks are needed.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.
adbrew_core/utils/entity_keys.pyAdd 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.
| Entity | Source (report type, segment) | Finest grain |
|---|---|---|
dsp_account | dspAccount daily rollup (null segment); see 6.3 for filtered requests | 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 rows only | + asin |
dsp_inventory | dspInventory, ADGROUPS | + supply_source, site |
dsp_geo | dspGeo, GEO_REGION | + country, region |
dsp_tech | dspTech, ENVIRONMENT_TYPE | + device, OS, environment |
analytics_client/shared/dsp.pyshared/sov.py. DSP ID columns are String; SP's campaignId stays Int64. DSP's native column names are kept.DSPMetricConfigs (visible SUM metrics), filtered by the DAO's per-report availability, not one global list.> 0. So generate the Mongo expression and the SQL formula from one definition, carrying numerator, denominator, multiplier and the DSP "non-zero" rule, inside dsp_metric_configs.py.SUM(eCPM), and would blur the two catalogues. DSP gets its own validation set.ingester.py + DSPReportRecordsDAO_ingest_performance_data dispatches DSP entities to a new _ingest_dsp_data, as it does for SOV.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.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).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.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.dao_registry.pyprepare_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.
engine.execute_sql registers its output with the first input's owners, entity, grain and dates (metas[0]). Register the union of input owners, and describe mixed or reshaped results by their actual columns. This matters already for MCP multi-account use, not only for DSP.hasAll(account_ids, …)) can derive from a reference covering more accounts and stamp the narrower owners without filtering rows. Require identical account sets for parent reuse.intelligence/tools/analytics.pydescribe_analytics_schema gains the account's channels (5.6); the API wrapper passes them explicitly, because the service is currently called with user_context=None.campaign_ids: List[int] and campaign_labels unchanged. Add explicit DSP filters, dsp_campaign_ids and dsp_ad_group_ids (strings), to both prepare tools. Dispatch filters by entity family. Today both prepare tools run the SP campaign resolver before forwarding, so that must happen only for SP entities.get_overall_performance reaches retail when selling-partner accounts are linked. It returns ads, retail and profitability, but no DSP, and the DSP toolset doesn't include it today.overall_change_summary path. Reuse that scoped totals path for explicit "overall" requests in both agents, so total_combined_spend, total_combined_sales (retail), total_roas and total_acos come from one code owner.DSPPerformanceDiagnose.toolset = Toolset(groups=[ANALYTICS, knowledge]); get_tools() returns the 3 write tools. Same shape as the AMC change in #5385.BaseChatAgent), so the analytics change and the API change can be judged separately. Move to the Responses API later, behind its own eval.DSPPerformanceAgentContext.build_context_message becomes a guidance formatter. Read-side resolution and scope errors go with the legacy read tools. Copy SP's old-chat refresh (saved instruction text compared on the next message or Retry).Frontend, the write tools, TTL and row caps, and SP's report-records path. MCP is unchanged until DSP exposure there is decided.
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.
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.
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.
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. 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.
| 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). |
| Decision | Outcome |
|---|---|
| Separate DSP agent through rollout | Yes. Keep entry-point defaults, selection context and write approvals. A merge is not part of the rollout gate. |
campaign_ids type | Keep SP's integer contract; add dsp_campaign_ids / dsp_ad_group_ids as strings (6.6). |
| Pilot flag | Yes. Reads and selection guidance switch together. Chat Completions kept for the first comparison. |
| MCP exposure | Later, after DSP filters and multi-account ownership (6.5) are covered. |
| Cross-channel default | Read across, home channel first, side by side. Explicit "overall" requests use the canonical retail-based totals (6.7). No per-agent read wall. |
| Summing spend | Yes, 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. |
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/.
app_release vs candidate; plus SP cases rerun on an account that also has DSP, to prove SP answers keep their meaning.