From 4eef98282513e33d068163fe1e17a027026b01a5 Mon Sep 17 00:00:00 2001 From: Illia Sapryga Date: Mon, 16 Nov 2026 16:51:33 -0600 Subject: [PATCH] Match four pieces of Google Ads advice to Google's documentation - Search campaigns: language_ids is no longer required. Google retired manual language targeting for Search campaigns in late September 2026. When it is passed, the preview warns and it is sent unchanged; update_campaign accepts language_ids=[] to remove campaign-level language criteria. - The '5x target CPA' budget warning no longer says 'Google recommends'. It is AdLoop's rule of thumb; Google's own guideline is 2 to 3 times the target CPA. - get_campaign_performance: for Maximize conversions and Maximize conversion value run without a target, the budget-lost share is marked unreliable, gets its own insight and is left out of the dashboard's budget alert. Google says the Lost IS (budget) column is incompatible with those strategies. - Rules: 'Learning' status is described as Google documents it. Budget, target, creative and targeting changes never trigger it. --- .claude/commands/create-campaign.md | 4 +- .claude/commands/optimize-campaign.md | 4 +- .claude/rules/adloop.md | 32 +- .cursor/rules/adloop.mdc | 32 +- src/adloop/ads/read.py | 140 +++- src/adloop/ads/write.py | 60 +- src/adloop/rules/adloop.md | 32 +- src/adloop/rules/commands/create-campaign.md | 4 +- .../rules/commands/optimize-campaign.md | 4 +- src/adloop/server.py | 20 +- src/adloop/views/performance.py | 9 +- tests/evals/planning.json | 4 +- tests/evals/write.json | 4 +- tests/test_google_guidance_accuracy.py | 599 ++++++++++++++++++ tests/test_server.py | 2 +- 15 files changed, 867 insertions(+), 83 deletions(-) create mode 100644 tests/test_google_guidance_accuracy.py diff --git a/.claude/commands/create-campaign.md b/.claude/commands/create-campaign.md index 4b8dc06a..5d0cacd5 100644 --- a/.claude/commands/create-campaign.md +++ b/.claude/commands/create-campaign.md @@ -13,14 +13,14 @@ Create a new Google Ads campaign for: $ARGUMENTS ## 2. Budget estimation - If user hasn't specified a budget, call `estimate_budget` with proposed keywords -- Ask for target geography and language if not clear (common: 2276=Germany, 2840=USA, 2826=UK) +- Ask for target geography if not clear (common: 2276=Germany, 2840=USA, 2826=UK). Search campaigns take no language targeting (Google retired it in late September 2026): confirm which language the ads and landing page are in instead - Present the forecast: estimated clicks, impressions, cost, avg CPC ## 3. Pre-write checks (CRITICAL) - Bidding strategy: recommend MAXIMIZE_CONVERSIONS or TARGET_CPA over MANUAL_CPC - Conversion tracking: run `attribution_check` — if zero conversions across the board, WARN that a new campaign won't help until tracking is fixed -- Budget: must be <= max_daily_budget in config, ideally >= 5x target CPA +- Budget: must be <= max_daily_budget in config, ideally >= 5x target CPA (AdLoop's rule of thumb, not a Google requirement; Google's own guideline is 2 to 3 times) - Keywords: if using BROAD match, campaign MUST use Smart Bidding — otherwise use PHRASE or EXACT ## 4. Draft campaign diff --git a/.claude/commands/optimize-campaign.md b/.claude/commands/optimize-campaign.md index 371828b0..c694fdd7 100644 --- a/.claude/commands/optimize-campaign.md +++ b/.claude/commands/optimize-campaign.md @@ -43,12 +43,12 @@ Follow this checklist in order — earlier items have higher impact. ## 6. Budget -- Is daily budget >= 5x target CPA? +- Is daily budget >= 5x target CPA? (AdLoop's rule of thumb, not a Google requirement; Google's low-traffic guide suggests 2 to 3 times) - If not: either increase budget or focus on reducing CPA first - Use `estimate_budget` if considering budget changes ## Rules - One change at a time — show preview, wait for approval -- Never edit during Learning Phase +- Google's "Learning" status (up to 7 days) follows a new or reactivated bid strategy, a change in what the strategy covers, or a significant conversion-goal change. Budget, target, creative and targeting changes never trigger it. Avoid several target changes within one conversion cycle - Priority order: tracking > negatives > QS > ad copy > bidding > budget diff --git a/.claude/rules/adloop.md b/.claude/rules/adloop.md index a5f6e556..0715ba06 100644 --- a/.claude/rules/adloop.md +++ b/.claude/rules/adloop.md @@ -94,7 +94,7 @@ You have access to AdLoop MCP tools that connect Google Ads, Reddit Ads and Goog - Ads read tools automatically compute `metrics.cost` and `metrics.cpa` from `metrics.cost_micros` — no manual division needed. `metrics.currency` contains the account's currency code (auto-detected). - `metrics.average_cpc_amount` is also pre-computed where available. - `get_ad_performance` returns full `headlines` and `descriptions` lists for RSAs, plus `ad_group_ad.policy_summary.approval_status`, `review_status` and `policy_topics` (topic names only) per ad. Ads that are `DISAPPROVED` (cannot serve) or `APPROVED_LIMITED` (serving restricted) are listed in `policy_issues` with their spend and flagged in `insights[]`; compact mode adds `by_approval_status` counts. -- `get_campaign_performance` returns `metrics.search_impression_share`, `metrics.search_budget_lost_impression_share` and `metrics.search_rank_lost_impression_share` as fractions (0.25 = 25%) with matching `*_pct` percentages. Google caps the reported values: 0.0999 means below 10% share, 0.9001 means above 90% lost. They are `null` for campaigns that do not serve on Search (Display, Video, PMax, ...) or had no impressions, which means "does not apply", not zero. `budget_limited_converters` and `insights[]` flag converting campaigns losing 20% or more of impressions to budget: those can absorb more budget, rank-lost share instead points at bids, ad relevance and quality. +- `get_campaign_performance` returns `metrics.search_impression_share`, `metrics.search_budget_lost_impression_share` and `metrics.search_rank_lost_impression_share` as fractions (0.25 = 25%) with matching `*_pct` percentages. Google caps the reported values: 0.0999 means below 10% share, 0.9001 means above 90% lost. They are `null` for campaigns that do not serve on Search (Display, Video, PMax, ...) or had no impressions, which means "does not apply", not zero. `budget_limited_converters` and `insights[]` flag converting campaigns losing 20% or more of impressions to budget: those can absorb more budget, rank-lost share instead points at bids, ad relevance and quality. Exception: for a campaign on Maximize conversions or Maximize conversion value with no target CPA and no target ROAS, the budget-lost share is not a reliable signal. Without a target those strategies aim to spend the full daily budget, and Google says its Lost IS (budget) column is incompatible with them. Such campaigns carry `budget_share_reliability: "unreliable"` and get their own insight; Google's budget simulator is the place to check before raising their budget. The target is read from the campaign or from its portfolio strategy. When it cannot be read (a portfolio the account cannot read, or a failed lookup) the value is `"unknown"` and a third insight says so: treat those as unconfirmed, not as short of budget. Entries without the key are on strategies the column works with and are listed first; only those raise the dashboard's budget alert. - `get_change_history` returns changes newest first with counts `by_resource_type`, `by_client`, `by_user` and `by_day`. Google Ads keeps 30 days of change history, so an older start date is moved forward (see `notes`). `insights[]` flag auto-applied recommendations and budget or bidding changes. `truncated: true` means the limit was hit; narrow the range or filters to see older changes. - `get_recommendations` returns each recommendation's `recommendation.id` (what `draft_dismiss_recommendations` takes) and `estimated_improvement` per recommendation (potential minus base metrics) and `insights[]` that flag budget-increase recommendations, whose projected gain comes from spending more. - PMax tools: `get_pmax_performance` returns `insights[]` flagging weak ad strength and zero-conversion asset groups. `segments.ad_network_type` includes MIXED — a Google catch-all for most PMax traffic. Full channel splits (Search vs YouTube vs Display vs Discover) are not available via the API. @@ -374,7 +374,7 @@ Conversions that happen offline (a sales call, a lead that turned into a deal) g | Tool | What It Does | Validation | |------|-------------|------------| -| `draft_campaign` | Create full campaign structure (budget + campaign + ad group + keywords + geo/language targeting) | `campaign_name`, `daily_budget`, `bidding_strategy`, `geo_target_ids` (REQUIRED), `language_ids` (REQUIRED), optional `search_partners_enabled`, `display_network_enabled`, `display_expansion_enabled`, optional `max_cpc` for MANUAL_CPC ad-group bids or TARGET_SPEND CPC caps, optional `location_option` / `negative_location_option`, optional `tracking_url_template` / `final_url_suffix` / `url_custom_parameters`, optional `geo_exclude_ids` / `ad_schedule` | +| `draft_campaign` | Create full campaign structure (budget + campaign + ad group + keywords + geo/language targeting) | `campaign_name`, `daily_budget`, `bidding_strategy`, `geo_target_ids` (REQUIRED), optional `language_ids` (leave out: Google retired language targeting for Search campaigns in late September 2026), optional `search_partners_enabled`, `display_network_enabled`, `display_expansion_enabled`, optional `max_cpc` for MANUAL_CPC ad-group bids or TARGET_SPEND CPC caps, optional `location_option` / `negative_location_option`, optional `tracking_url_template` / `final_url_suffix` / `url_custom_parameters`, optional `geo_exclude_ids` / `ad_schedule` | | `draft_shopping_campaign` | Create a Standard Shopping campaign for a Merchant Center feed: budget + campaign (PAUSED) + product ad group + Shopping ad + one "All products" product group, atomically | `campaign_name`, `daily_budget`, `merchant_id` (must be linked to the Ads account; checked), `product_bid` (CPC of the product group, required by Google), `geo_target_ids` (REQUIRED), `bidding_strategy` MANUAL_CPC (default) / TARGET_SPEND (Maximize clicks, optional `max_cpc`) / TARGET_ROAS (+ `target_roas`), `campaign_priority` LOW/MEDIUM/HIGH, optional `feed_label`. No keywords, no languages | | `draft_asset_group_assets` | Add and/or remove assets of an existing PMax asset group in one atomic change: text, images, YouTube videos | `asset_group_id`, `headlines` (≤30), `long_headlines` (≤90), `descriptions` (≤90), `business_name` (≤25), `images` (`{"url"}` or `{"upload_id"}`, optional `role` marketing/logo/landscape_logo; marketing images sorted into landscape 1.91:1, square 1:1, portrait 4:5 by ratio), `youtube_video_ids`, `remove_asset_ids` | | `draft_asset_group_signals` | Add search themes or set the audience signal of a PMax asset group, or remove signals | `asset_group_id`, `add_search_themes` (≤80 chars, up to 50 per group), `audience_id` (one per group), `remove_signal_ids` | @@ -457,8 +457,8 @@ Same draft → preview → `confirm_and_apply` gate; the plan carries `platform: **Safety behaviors:** - New campaigns and RSAs (and every Reddit campaign, ad group and ad) are created as PAUSED — user must explicitly enable them after review. -- `draft_campaign` REQUIRES `geo_target_ids` and `language_ids` — campaigns without targeting waste budget. The tool rejects drafts with missing targeting. -- `draft_campaign` enforces the `max_daily_budget` safety cap, rejects BROAD match + non-Smart Bidding, warns if budget is below 5x target CPA, and interprets `max_cpc` by bidding strategy: MANUAL_CPC seeds the initial ad-group bid, TARGET_SPEND sets the Maximize Clicks CPC ceiling. +- `draft_campaign` REQUIRES `geo_target_ids` — campaigns without geo targeting waste budget, and the tool rejects such drafts. `language_ids` is optional and best left out: Google retired manual language targeting for Search campaigns in late September 2026, and Search ads now match on the language of the ads and landing page plus the user's language preferences. If it is passed, the preview warns and the dry run shows whether Google still accepts it. On `update_campaign`, `language_ids=[]` removes a campaign's campaign-level language criteria. +- `draft_campaign` enforces the `max_daily_budget` safety cap, rejects BROAD match + non-Smart Bidding, warns if budget is below 5x target CPA (AdLoop's rule of thumb, not a Google requirement), and interprets `max_cpc` by bidding strategy: MANUAL_CPC seeds the initial ad-group bid, TARGET_SPEND sets the Maximize Clicks CPC ceiling. - `display_network_enabled` is the canonical Search display-expansion flag. `display_expansion_enabled` is only a compatibility alias and should be normalized away before presenting the plan to the user. - `update_ad_group` is the right tool for later MANUAL_CPC bid changes. Use `update_campaign` for TARGET_SPEND (Maximize Clicks) `max_cpc` changes. - Ad-group pause/enable is already handled by `pause_entity` / `enable_entity` with `entity_type="ad_group"`; do not invent a separate pause tool. @@ -466,7 +466,7 @@ Same draft → preview → `confirm_and_apply` gate; the plan carries `platform: - Location options: `location_option` is who the geo targets reach — `PRESENCE` (people in or regularly in the locations), `PRESENCE_OR_INTEREST` (Google's default; also people elsewhere who show interest in them) or `SEARCH_INTEREST`. `negative_location_option` (`PRESENCE` or `PRESENCE_OR_INTEREST`) is who the exclusions exclude. Empty leaves the value as it is. The preview warns when a change widens reach: for `location_option` that is anything but `PRESENCE`, for `negative_location_option` it is `PRESENCE`, because then the exclusions only keep out people physically there, not people interested in the excluded places; `update_campaign` shows the current value as `current_location_option` / `current_negative_location_option`. Read back with `get_campaign_settings`. - Campaign URL options (`tracking_url_template`, `final_url_suffix`, `url_custom_parameters`): omitted leaves a value unchanged, `""` or `[]` removes it, and `url_custom_parameters` replaces the whole list. The template must contain `{lpurl}` or a variant (`{lpurl+2}`, `{unescapedlpurl}`, `{escapedlpurl+3}`, ...). Custom parameter keys are alphanumeric, at most 8 characters. The `update_campaign` preview shows each current value (`current_tracking_url_template` etc.), warns on a removal, and gives `example_click`: one of the campaign's final URLs with the campaign's options applied. It is approximate: a template on the ad group, ad or keyword overrides the campaign's, and ValueTrack parameters are filled at click time. Check it for typos before approving. Read back with `get_campaign_settings`. - Campaign-level broad match: `update_campaign` `keyword_match_type="BROAD"` CONVERTS every existing phrase and exact keyword in the campaign into broad match. Google shows the originals as Removed, turning the setting off does not restore them, and since September 2026 Google also upgrades such campaigns to AI Max. It is refused unless the campaign (or the `bidding_strategy` in the same call) is Smart Bidding — the same rule as BROAD keywords — checked again at apply, and needs a double confirmation. `keyword_match_type="UNSPECIFIED"` turns it off (single confirmation): no further conversions, but converted keywords stay broad and must be re-added as phrase/exact by hand. Moving a broad-match campaign to a non-Smart `bidding_strategy` is refused unless the same call passes `UNSPECIFIED`. Never turn it on to "get more traffic" on an exact/phrase campaign; read it back with `get_campaign_settings`, which lists it in `widening_settings`. -- `update_campaign` replaces POSITIVE geo/language targets entirely (not append). Pass the full desired list. NEGATIVE geo exclusions (criteria with `negative=TRUE`) are **preserved** across a positive-geo replacement — they survive the swap — unless `geo_exclude_ids` is passed in the same call. The preview surfaces preserved negative geo IDs in `preserved_negative_geo_target_ids` so the change is auditable. To ADD negative geo exclusions (e.g. exclude a city inside a targeted state), use `add_negative_locations` — do not try to express exclusions through `geo_target_ids`. To remove a negative geo exclusion explicitly, use `remove_entity` with `entity_type="campaign_criterion"`, or pass `geo_exclude_ids` without it. +- `update_campaign` replaces POSITIVE geo/language targets entirely (not append). Pass the full desired list. `language_ids` is for campaign types that still take language targeting (Display, Video, App, Demand Gen with campaign-level languages, and the YouTube, Display, Discover and Gmail channels of Performance Max). For a Search campaign Google's documentation says new language criteria are no longer accepted (retired late September 2026); `language_ids=[]` removes the campaign-level ones. NEGATIVE geo exclusions (criteria with `negative=TRUE`) are **preserved** across a positive-geo replacement — they survive the swap — unless `geo_exclude_ids` is passed in the same call. The preview surfaces preserved negative geo IDs in `preserved_negative_geo_target_ids` so the change is auditable. To ADD negative geo exclusions (e.g. exclude a city inside a targeted state), use `add_negative_locations` — do not try to express exclusions through `geo_target_ids`. To remove a negative geo exclusion explicitly, use `remove_entity` with `entity_type="campaign_criterion"`, or pass `geo_exclude_ids` without it. - `geo_exclude_ids` and `ad_schedule` set exclusions and windows when creating a campaign, in the same atomic request. A schedule there gets a warning, not a double confirmation: the campaign is created PAUSED, and once it is enabled it serves only inside the windows. On `update_campaign` they REPLACE the whole list: omitted leaves it unchanged, `[]` clears it. Use them to set the complete state; `add_negative_locations` and `add_ad_schedule` add to what is there. The preview shows the current values (`current_geo_exclude_ids`, `current_ad_schedule`), only the entries that differ are removed or added, and apply refuses if the current values changed after the preview. `update_campaign` needs a double confirmation for a campaign's first schedule (every other hour stops serving), for clearing a schedule (the campaign serves at all hours again) and for dropping an exclusion (it can serve there again). A location can move between `geo_target_ids` and `geo_exclude_ids` in one call; a location in both lists is refused. - **Asset scope:** callouts and snippets link where the id points (`ad_group_id` → ad group, `campaign_id` → campaign). Account-wide (`scope="account"`) reaches every campaign without assets of its own; use it only when the user asks for account level. **Asset edits** (`update_callout`, `update_sitelink`, `update_structured_snippet`) change the asset everywhere it is linked; check with GAQL (`campaign_asset`, `ad_group_asset`, `customer_asset`) where else it is used before editing a shared asset. If the apply reports the asset changed in Google Ads since the preview, draft again. - **Call assets, schedules, promotions and prices.** Never guess `country_code` or `language_code`: take them from the number and the landing page, and ask when unclear. Money amounts are in the account currency (the preview names it); pass `currency_code` only for a different one. Ad schedule hours are in the **account time zone** (the previews show it), not the searcher's: convert the user's local hours first. A campaign without a schedule serves at all hours, so its first `add_ad_schedule` windows switch off every other hour and day: say so, the preview needs a double confirmation. To change a window, pass the complete list as `update_campaign` `ad_schedule`, or remove the old one with `remove_entity` (`entity_type="campaign_criterion"`, the `remove_id` from the preview) and add the new one. Prices must match the landing page or Google disapproves them. @@ -586,12 +586,12 @@ Most websites (especially in the EU) use a GDPR cookie consent banner. This has 3. **Pre-write checks (CRITICAL):** - **Bidding strategy**: Default to MAXIMIZE_CONVERSIONS. It tells Google the goal is conversions (not just clicks), doesn't waste budget on non-converting clicks, and starts building the conversion model from day one — even with zero history, Google uses broad signals (search intent, device, time of day). Only use TARGET_SPEND/MANUAL_CPC if the user explicitly requests it and understands the trade-offs. - **Geo targeting**: ALWAYS ask the user which countries/regions to target if not specified. Never create a campaign without geo targets — untargeted campaigns waste budget on irrelevant geographies. Common IDs: 2276=Germany, 2040=Austria, 2756=Switzerland, 2840=USA, 2826=UK. - - **Language targeting**: ALWAYS ask the user which languages to target if not specified. Language targeting restricts ads to users whose browser/Google language matches — without it, ads show to anyone in the geo region regardless of language. Common IDs: 1001=German, 1000=English, 1002=French. + - **Language**: do not ask for language targets for a Search campaign. Google retired manual language targeting there in late September 2026; Search ads match on the language of the ads and landing page plus the user's language preferences. Confirm which language the ads and landing page are in instead. - Does the account have conversion tracking working? Call `attribution_check` — if zero conversions across the board, WARN that new campaigns won't help until tracking is fixed. - - Is the proposed budget reasonable? Must be ≤ `max_daily_budget` in config, and ideally ≥ 5x target CPA. -4. Call `draft_campaign` with campaign name, daily budget, bidding strategy, `geo_target_ids`, `language_ids`, ad group name, and optional keywords + - Is the proposed budget reasonable? Must be ≤ `max_daily_budget` in config, and ideally ≥ 5x target CPA (AdLoop's rule of thumb, not a Google requirement; Google's low-traffic troubleshooting guide suggests 2 to 3 times the target CPA). +4. Call `draft_campaign` with campaign name, daily budget, bidding strategy, `geo_target_ids`, ad group name, and optional keywords 5. Review the preview and any `warnings` (budget sufficiency, MANUAL_CPC warning, BROAD match rejection) -6. Present the complete preview to the user — emphasize the campaign will be created as PAUSED, and confirm the geo/language targets are correct +6. Present the complete preview to the user — emphasize the campaign will be created as PAUSED, and confirm the geo targets are correct 7. After campaign creation, remind the user to: - Add ads via `draft_responsive_search_ad` (with display paths set) - Add sitelinks via `draft_sitelinks` (at least 4 recommended) @@ -630,8 +630,8 @@ Most websites (especially in the EU) use a GDPR cookie consent banner. This has 3. **Pre-write checks:** - If changing to MAXIMIZE_CONVERSIONS: good default choice — confirm with the user - If changing to MANUAL_CPC: warn about the trade-offs (no automation, requires constant monitoring) - - If removing geo or language targets: warn that this broadens targeting and may waste budget - - If the campaign is in a learning phase: warn that changes will restart the learning phase + - If removing geo targets: warn that this broadens targeting and may waste budget. Language criteria on a Search campaign are no longer used by Google (retired late September 2026), so removing them there changes nothing; on campaign types that still take language targeting they narrow who sees the ads, so removing them can widen it + - Say whether the change shows Google's "Learning" status (up to 7 days, ads keep serving): a new or reactivated bid strategy, campaigns added to or removed from a portfolio strategy, or a significant change of conversion goals does. Budget, target, creative and targeting changes do not (budget, target and targeting changes apply from the next auction; new or edited ads go through policy review before they serve) - **Shared budgets and portfolio strategies:** a budget change on a SHARED budget changes the daily budget of every campaign using it, and a bidding change on a campaign in a portfolio bid strategy takes it out of the portfolio. The preview names the other campaigns and asks for a double confirmation; tell the user plainly before they confirm. If they meant only this campaign, its own budget has to be set up in Google Ads first 4. Call `update_campaign` with only the parameters that need to change 5. Present the preview — clearly show what's changing (old → new) @@ -1003,6 +1003,10 @@ For cities/regions, use `run_gaql` with `geo_target_constant` resource or look u ### Common Language IDs (languageConstants) +For the Keyword Planner tools (`discover_keywords`, `estimate_budget`) and for +campaigns that still take language targeting. Search campaigns do not (see +Marketing Best Practices). + Verified against the `language_constant` resource. Google accepts a wrong language ID silently, so confirm anything not listed here with: `SELECT language_constant.id, language_constant.code, language_constant.name FROM language_constant` @@ -1033,11 +1037,11 @@ When advising on Google Ads: - **Bid strategy default**: Prefer MAXIMIZE_CONVERSIONS for new campaigns. It leverages Google's signals from day one, even without conversion history. TARGET_SPEND (Maximize Clicks) only makes sense as a deliberate data-collection phase — and even then, MAXIMIZE_CONVERSIONS is usually better because it starts optimizing for conversions immediately instead of just accumulating clicks. - **Geo targeting is mandatory**: Every campaign must target specific countries/regions. Untargeted campaigns serve globally and waste budget. ALWAYS set geo_target_ids when creating campaigns. -- **Language targeting is mandatory**: Every campaign must target specific languages. Without it, ads show to all users in the geo region regardless of browser language. A German-language ad shown to an English speaker in Germany wastes budget. ALWAYS set language_ids when creating campaigns. +- **Search campaigns take no language targeting**: Google retired manual language targeting for Search campaigns in late September 2026. Search ads match on the language of the ads and landing page plus the user's language preferences, so write both in the language you want to reach. Language targeting still applies to Display, Video, App and Demand Gen campaigns, and within Performance Max to YouTube, Display, Discover and Gmail (not to its Search or Shopping ads). - **Match types**: Never recommend Broad Match without Smart Bidding (tCPA or tROAS) active on the campaign. Broad Match without Smart Bidding leads to budget waste. - **CPA monitoring**: Flag any campaign where CPA exceeds 3x the target for review. -- **Budget sufficiency**: A campaign's daily budget should be at least 5x its target CPA to generate enough data for the algorithm. -- **Learning phase**: Don't edit campaigns that are in an active learning phase (Google Ads shows "Learning" or "Learning (limited)" status). Wait until the learning phase completes before making changes. +- **Budget sufficiency**: AdLoop's rule of thumb is a daily budget of at least 5x the target CPA, so a campaign can collect several conversions a day. It is not a Google requirement: Google's low-traffic troubleshooting guide suggests at least 2 to 3 times the target CPA, or 10 times the expected CPC. Treat a smaller budget as a prompt to check, not as an error. +- **Learning status**: Google shows "Learning" for up to 7 days after a bid strategy is created or reactivated, after campaigns, ad groups or keywords are added to or removed from it, or after the conversion goals change significantly. Ads keep serving meanwhile. Changes to budgets, targets, creatives and targeting never trigger it. Budget, target and targeting changes apply from the next auction; new or edited ads have to pass policy review before they serve. Unless the business needs it, avoid several target changes within one conversion cycle: Google's guidance is to give a new target 1 to 2 conversion cycles. - **Negative keyword hygiene**: After reviewing search terms, always suggest adding irrelevant terms as negatives. Group them by theme. - **RSA best practices**: Provide at least 8-10 unique headlines (out of max 15) and 3-4 descriptions (out of max 4). Make headlines diverse — don't repeat the same message. **Pin only when necessary** — pinning reduces Google's ability to rotate assets and typically lowers ad strength. Reach for the dict shape `{"text": "...", "pinned_field": "HEADLINE_1"}` only for concrete brand-safety/compliance reasons. For phone numbers, prefer a campaign-level call asset over a pinned headline. See "Ad Copy Character Limits" section below for language-specific guidance. - **Quality Score**: If keywords have quality score < 5, prioritize improving ad relevance and landing page experience over bid increases. diff --git a/.cursor/rules/adloop.mdc b/.cursor/rules/adloop.mdc index 8d48e9b5..38e4e7ff 100644 --- a/.cursor/rules/adloop.mdc +++ b/.cursor/rules/adloop.mdc @@ -96,7 +96,7 @@ You have access to AdLoop MCP tools that connect Google Ads, Reddit Ads and Goog - Ads read tools automatically compute `metrics.cost` and `metrics.cpa` from `metrics.cost_micros` — no manual division needed. `metrics.currency` contains the account's currency code (auto-detected). - `metrics.average_cpc_amount` is also pre-computed where available. - `get_ad_performance` returns full `headlines` and `descriptions` lists for RSAs, plus `ad_group_ad.policy_summary.approval_status`, `review_status` and `policy_topics` (topic names only) per ad. Ads that are `DISAPPROVED` (cannot serve) or `APPROVED_LIMITED` (serving restricted) are listed in `policy_issues` with their spend and flagged in `insights[]`; compact mode adds `by_approval_status` counts. -- `get_campaign_performance` returns `metrics.search_impression_share`, `metrics.search_budget_lost_impression_share` and `metrics.search_rank_lost_impression_share` as fractions (0.25 = 25%) with matching `*_pct` percentages. Google caps the reported values: 0.0999 means below 10% share, 0.9001 means above 90% lost. They are `null` for campaigns that do not serve on Search (Display, Video, PMax, ...) or had no impressions, which means "does not apply", not zero. `budget_limited_converters` and `insights[]` flag converting campaigns losing 20% or more of impressions to budget: those can absorb more budget, rank-lost share instead points at bids, ad relevance and quality. +- `get_campaign_performance` returns `metrics.search_impression_share`, `metrics.search_budget_lost_impression_share` and `metrics.search_rank_lost_impression_share` as fractions (0.25 = 25%) with matching `*_pct` percentages. Google caps the reported values: 0.0999 means below 10% share, 0.9001 means above 90% lost. They are `null` for campaigns that do not serve on Search (Display, Video, PMax, ...) or had no impressions, which means "does not apply", not zero. `budget_limited_converters` and `insights[]` flag converting campaigns losing 20% or more of impressions to budget: those can absorb more budget, rank-lost share instead points at bids, ad relevance and quality. Exception: for a campaign on Maximize conversions or Maximize conversion value with no target CPA and no target ROAS, the budget-lost share is not a reliable signal. Without a target those strategies aim to spend the full daily budget, and Google says its Lost IS (budget) column is incompatible with them. Such campaigns carry `budget_share_reliability: "unreliable"` and get their own insight; Google's budget simulator is the place to check before raising their budget. The target is read from the campaign or from its portfolio strategy. When it cannot be read (a portfolio the account cannot read, or a failed lookup) the value is `"unknown"` and a third insight says so: treat those as unconfirmed, not as short of budget. Entries without the key are on strategies the column works with and are listed first; only those raise the dashboard's budget alert. - `get_change_history` returns changes newest first with counts `by_resource_type`, `by_client`, `by_user` and `by_day`. Google Ads keeps 30 days of change history, so an older start date is moved forward (see `notes`). `insights[]` flag auto-applied recommendations and budget or bidding changes. `truncated: true` means the limit was hit; narrow the range or filters to see older changes. - `get_recommendations` returns each recommendation's `recommendation.id` (what `draft_dismiss_recommendations` takes) and `estimated_improvement` per recommendation (potential minus base metrics) and `insights[]` that flag budget-increase recommendations, whose projected gain comes from spending more. - PMax tools: `get_pmax_performance` returns `insights[]` flagging weak ad strength and zero-conversion asset groups. `segments.ad_network_type` includes MIXED — a Google catch-all for most PMax traffic. Full channel splits (Search vs YouTube vs Display vs Discover) are not available via the API. @@ -376,7 +376,7 @@ Conversions that happen offline (a sales call, a lead that turned into a deal) g | Tool | What It Does | Validation | |------|-------------|------------| -| `draft_campaign` | Create full campaign structure (budget + campaign + ad group + keywords + geo/language targeting) | `campaign_name`, `daily_budget`, `bidding_strategy`, `geo_target_ids` (REQUIRED), `language_ids` (REQUIRED), optional `search_partners_enabled`, `display_network_enabled`, `display_expansion_enabled`, optional `max_cpc` for MANUAL_CPC ad-group bids or TARGET_SPEND CPC caps, optional `location_option` / `negative_location_option`, optional `tracking_url_template` / `final_url_suffix` / `url_custom_parameters`, optional `geo_exclude_ids` / `ad_schedule` | +| `draft_campaign` | Create full campaign structure (budget + campaign + ad group + keywords + geo/language targeting) | `campaign_name`, `daily_budget`, `bidding_strategy`, `geo_target_ids` (REQUIRED), optional `language_ids` (leave out: Google retired language targeting for Search campaigns in late September 2026), optional `search_partners_enabled`, `display_network_enabled`, `display_expansion_enabled`, optional `max_cpc` for MANUAL_CPC ad-group bids or TARGET_SPEND CPC caps, optional `location_option` / `negative_location_option`, optional `tracking_url_template` / `final_url_suffix` / `url_custom_parameters`, optional `geo_exclude_ids` / `ad_schedule` | | `draft_shopping_campaign` | Create a Standard Shopping campaign for a Merchant Center feed: budget + campaign (PAUSED) + product ad group + Shopping ad + one "All products" product group, atomically | `campaign_name`, `daily_budget`, `merchant_id` (must be linked to the Ads account; checked), `product_bid` (CPC of the product group, required by Google), `geo_target_ids` (REQUIRED), `bidding_strategy` MANUAL_CPC (default) / TARGET_SPEND (Maximize clicks, optional `max_cpc`) / TARGET_ROAS (+ `target_roas`), `campaign_priority` LOW/MEDIUM/HIGH, optional `feed_label`. No keywords, no languages | | `draft_asset_group_assets` | Add and/or remove assets of an existing PMax asset group in one atomic change: text, images, YouTube videos | `asset_group_id`, `headlines` (≤30), `long_headlines` (≤90), `descriptions` (≤90), `business_name` (≤25), `images` (`{"url"}` or `{"upload_id"}`, optional `role` marketing/logo/landscape_logo; marketing images sorted into landscape 1.91:1, square 1:1, portrait 4:5 by ratio), `youtube_video_ids`, `remove_asset_ids` | | `draft_asset_group_signals` | Add search themes or set the audience signal of a PMax asset group, or remove signals | `asset_group_id`, `add_search_themes` (≤80 chars, up to 50 per group), `audience_id` (one per group), `remove_signal_ids` | @@ -459,8 +459,8 @@ Same draft → preview → `confirm_and_apply` gate; the plan carries `platform: **Safety behaviors:** - New campaigns and RSAs (and every Reddit campaign, ad group and ad) are created as PAUSED — user must explicitly enable them after review. -- `draft_campaign` REQUIRES `geo_target_ids` and `language_ids` — campaigns without targeting waste budget. The tool rejects drafts with missing targeting. -- `draft_campaign` enforces the `max_daily_budget` safety cap, rejects BROAD match + non-Smart Bidding, warns if budget is below 5x target CPA, and interprets `max_cpc` by bidding strategy: MANUAL_CPC seeds the initial ad-group bid, TARGET_SPEND sets the Maximize Clicks CPC ceiling. +- `draft_campaign` REQUIRES `geo_target_ids` — campaigns without geo targeting waste budget, and the tool rejects such drafts. `language_ids` is optional and best left out: Google retired manual language targeting for Search campaigns in late September 2026, and Search ads now match on the language of the ads and landing page plus the user's language preferences. If it is passed, the preview warns and the dry run shows whether Google still accepts it. On `update_campaign`, `language_ids=[]` removes a campaign's campaign-level language criteria. +- `draft_campaign` enforces the `max_daily_budget` safety cap, rejects BROAD match + non-Smart Bidding, warns if budget is below 5x target CPA (AdLoop's rule of thumb, not a Google requirement), and interprets `max_cpc` by bidding strategy: MANUAL_CPC seeds the initial ad-group bid, TARGET_SPEND sets the Maximize Clicks CPC ceiling. - `display_network_enabled` is the canonical Search display-expansion flag. `display_expansion_enabled` is only a compatibility alias and should be normalized away before presenting the plan to the user. - `update_ad_group` is the right tool for later MANUAL_CPC bid changes. Use `update_campaign` for TARGET_SPEND (Maximize Clicks) `max_cpc` changes. - Ad-group pause/enable is already handled by `pause_entity` / `enable_entity` with `entity_type="ad_group"`; do not invent a separate pause tool. @@ -468,7 +468,7 @@ Same draft → preview → `confirm_and_apply` gate; the plan carries `platform: - Location options: `location_option` is who the geo targets reach — `PRESENCE` (people in or regularly in the locations), `PRESENCE_OR_INTEREST` (Google's default; also people elsewhere who show interest in them) or `SEARCH_INTEREST`. `negative_location_option` (`PRESENCE` or `PRESENCE_OR_INTEREST`) is who the exclusions exclude. Empty leaves the value as it is. The preview warns when a change widens reach: for `location_option` that is anything but `PRESENCE`, for `negative_location_option` it is `PRESENCE`, because then the exclusions only keep out people physically there, not people interested in the excluded places; `update_campaign` shows the current value as `current_location_option` / `current_negative_location_option`. Read back with `get_campaign_settings`. - Campaign URL options (`tracking_url_template`, `final_url_suffix`, `url_custom_parameters`): omitted leaves a value unchanged, `""` or `[]` removes it, and `url_custom_parameters` replaces the whole list. The template must contain `{lpurl}` or a variant (`{lpurl+2}`, `{unescapedlpurl}`, `{escapedlpurl+3}`, ...). Custom parameter keys are alphanumeric, at most 8 characters. The `update_campaign` preview shows each current value (`current_tracking_url_template` etc.), warns on a removal, and gives `example_click`: one of the campaign's final URLs with the campaign's options applied. It is approximate: a template on the ad group, ad or keyword overrides the campaign's, and ValueTrack parameters are filled at click time. Check it for typos before approving. Read back with `get_campaign_settings`. - Campaign-level broad match: `update_campaign` `keyword_match_type="BROAD"` CONVERTS every existing phrase and exact keyword in the campaign into broad match. Google shows the originals as Removed, turning the setting off does not restore them, and since September 2026 Google also upgrades such campaigns to AI Max. It is refused unless the campaign (or the `bidding_strategy` in the same call) is Smart Bidding — the same rule as BROAD keywords — checked again at apply, and needs a double confirmation. `keyword_match_type="UNSPECIFIED"` turns it off (single confirmation): no further conversions, but converted keywords stay broad and must be re-added as phrase/exact by hand. Moving a broad-match campaign to a non-Smart `bidding_strategy` is refused unless the same call passes `UNSPECIFIED`. Never turn it on to "get more traffic" on an exact/phrase campaign; read it back with `get_campaign_settings`, which lists it in `widening_settings`. -- `update_campaign` replaces POSITIVE geo/language targets entirely (not append). Pass the full desired list. NEGATIVE geo exclusions (criteria with `negative=TRUE`) are **preserved** across a positive-geo replacement — they survive the swap — unless `geo_exclude_ids` is passed in the same call. The preview surfaces preserved negative geo IDs in `preserved_negative_geo_target_ids` so the change is auditable. To ADD negative geo exclusions (e.g. exclude a city inside a targeted state), use `add_negative_locations` — do not try to express exclusions through `geo_target_ids`. To remove a negative geo exclusion explicitly, use `remove_entity` with `entity_type="campaign_criterion"`, or pass `geo_exclude_ids` without it. +- `update_campaign` replaces POSITIVE geo/language targets entirely (not append). Pass the full desired list. `language_ids` is for campaign types that still take language targeting (Display, Video, App, Demand Gen with campaign-level languages, and the YouTube, Display, Discover and Gmail channels of Performance Max). For a Search campaign Google's documentation says new language criteria are no longer accepted (retired late September 2026); `language_ids=[]` removes the campaign-level ones. NEGATIVE geo exclusions (criteria with `negative=TRUE`) are **preserved** across a positive-geo replacement — they survive the swap — unless `geo_exclude_ids` is passed in the same call. The preview surfaces preserved negative geo IDs in `preserved_negative_geo_target_ids` so the change is auditable. To ADD negative geo exclusions (e.g. exclude a city inside a targeted state), use `add_negative_locations` — do not try to express exclusions through `geo_target_ids`. To remove a negative geo exclusion explicitly, use `remove_entity` with `entity_type="campaign_criterion"`, or pass `geo_exclude_ids` without it. - `geo_exclude_ids` and `ad_schedule` set exclusions and windows when creating a campaign, in the same atomic request. A schedule there gets a warning, not a double confirmation: the campaign is created PAUSED, and once it is enabled it serves only inside the windows. On `update_campaign` they REPLACE the whole list: omitted leaves it unchanged, `[]` clears it. Use them to set the complete state; `add_negative_locations` and `add_ad_schedule` add to what is there. The preview shows the current values (`current_geo_exclude_ids`, `current_ad_schedule`), only the entries that differ are removed or added, and apply refuses if the current values changed after the preview. `update_campaign` needs a double confirmation for a campaign's first schedule (every other hour stops serving), for clearing a schedule (the campaign serves at all hours again) and for dropping an exclusion (it can serve there again). A location can move between `geo_target_ids` and `geo_exclude_ids` in one call; a location in both lists is refused. - **Asset scope:** callouts and snippets link where the id points (`ad_group_id` → ad group, `campaign_id` → campaign). Account-wide (`scope="account"`) reaches every campaign without assets of its own; use it only when the user asks for account level. **Asset edits** (`update_callout`, `update_sitelink`, `update_structured_snippet`) change the asset everywhere it is linked; check with GAQL (`campaign_asset`, `ad_group_asset`, `customer_asset`) where else it is used before editing a shared asset. If the apply reports the asset changed in Google Ads since the preview, draft again. - **Call assets, schedules, promotions and prices.** Never guess `country_code` or `language_code`: take them from the number and the landing page, and ask when unclear. Money amounts are in the account currency (the preview names it); pass `currency_code` only for a different one. Ad schedule hours are in the **account time zone** (the previews show it), not the searcher's: convert the user's local hours first. A campaign without a schedule serves at all hours, so its first `add_ad_schedule` windows switch off every other hour and day: say so, the preview needs a double confirmation. To change a window, pass the complete list as `update_campaign` `ad_schedule`, or remove the old one with `remove_entity` (`entity_type="campaign_criterion"`, the `remove_id` from the preview) and add the new one. Prices must match the landing page or Google disapproves them. @@ -588,12 +588,12 @@ Most websites (especially in the EU) use a GDPR cookie consent banner. This has 3. **Pre-write checks (CRITICAL):** - **Bidding strategy**: Default to MAXIMIZE_CONVERSIONS. It tells Google the goal is conversions (not just clicks), doesn't waste budget on non-converting clicks, and starts building the conversion model from day one — even with zero history, Google uses broad signals (search intent, device, time of day). Only use TARGET_SPEND/MANUAL_CPC if the user explicitly requests it and understands the trade-offs. - **Geo targeting**: ALWAYS ask the user which countries/regions to target if not specified. Never create a campaign without geo targets — untargeted campaigns waste budget on irrelevant geographies. Common IDs: 2276=Germany, 2040=Austria, 2756=Switzerland, 2840=USA, 2826=UK. - - **Language targeting**: ALWAYS ask the user which languages to target if not specified. Language targeting restricts ads to users whose browser/Google language matches — without it, ads show to anyone in the geo region regardless of language. Common IDs: 1001=German, 1000=English, 1002=French. + - **Language**: do not ask for language targets for a Search campaign. Google retired manual language targeting there in late September 2026; Search ads match on the language of the ads and landing page plus the user's language preferences. Confirm which language the ads and landing page are in instead. - Does the account have conversion tracking working? Call `attribution_check` — if zero conversions across the board, WARN that new campaigns won't help until tracking is fixed. - - Is the proposed budget reasonable? Must be ≤ `max_daily_budget` in config, and ideally ≥ 5x target CPA. -4. Call `draft_campaign` with campaign name, daily budget, bidding strategy, `geo_target_ids`, `language_ids`, ad group name, and optional keywords + - Is the proposed budget reasonable? Must be ≤ `max_daily_budget` in config, and ideally ≥ 5x target CPA (AdLoop's rule of thumb, not a Google requirement; Google's low-traffic troubleshooting guide suggests 2 to 3 times the target CPA). +4. Call `draft_campaign` with campaign name, daily budget, bidding strategy, `geo_target_ids`, ad group name, and optional keywords 5. Review the preview and any `warnings` (budget sufficiency, MANUAL_CPC warning, BROAD match rejection) -6. Present the complete preview to the user — emphasize the campaign will be created as PAUSED, and confirm the geo/language targets are correct +6. Present the complete preview to the user — emphasize the campaign will be created as PAUSED, and confirm the geo targets are correct 7. After campaign creation, remind the user to: - Add ads via `draft_responsive_search_ad` (with display paths set) - Add sitelinks via `draft_sitelinks` (at least 4 recommended) @@ -632,8 +632,8 @@ Most websites (especially in the EU) use a GDPR cookie consent banner. This has 3. **Pre-write checks:** - If changing to MAXIMIZE_CONVERSIONS: good default choice — confirm with the user - If changing to MANUAL_CPC: warn about the trade-offs (no automation, requires constant monitoring) - - If removing geo or language targets: warn that this broadens targeting and may waste budget - - If the campaign is in a learning phase: warn that changes will restart the learning phase + - If removing geo targets: warn that this broadens targeting and may waste budget. Language criteria on a Search campaign are no longer used by Google (retired late September 2026), so removing them there changes nothing; on campaign types that still take language targeting they narrow who sees the ads, so removing them can widen it + - Say whether the change shows Google's "Learning" status (up to 7 days, ads keep serving): a new or reactivated bid strategy, campaigns added to or removed from a portfolio strategy, or a significant change of conversion goals does. Budget, target, creative and targeting changes do not (budget, target and targeting changes apply from the next auction; new or edited ads go through policy review before they serve) - **Shared budgets and portfolio strategies:** a budget change on a SHARED budget changes the daily budget of every campaign using it, and a bidding change on a campaign in a portfolio bid strategy takes it out of the portfolio. The preview names the other campaigns and asks for a double confirmation; tell the user plainly before they confirm. If they meant only this campaign, its own budget has to be set up in Google Ads first 4. Call `update_campaign` with only the parameters that need to change 5. Present the preview — clearly show what's changing (old → new) @@ -1005,6 +1005,10 @@ For cities/regions, use `run_gaql` with `geo_target_constant` resource or look u ### Common Language IDs (languageConstants) +For the Keyword Planner tools (`discover_keywords`, `estimate_budget`) and for +campaigns that still take language targeting. Search campaigns do not (see +Marketing Best Practices). + Verified against the `language_constant` resource. Google accepts a wrong language ID silently, so confirm anything not listed here with: `SELECT language_constant.id, language_constant.code, language_constant.name FROM language_constant` @@ -1035,11 +1039,11 @@ When advising on Google Ads: - **Bid strategy default**: Prefer MAXIMIZE_CONVERSIONS for new campaigns. It leverages Google's signals from day one, even without conversion history. TARGET_SPEND (Maximize Clicks) only makes sense as a deliberate data-collection phase — and even then, MAXIMIZE_CONVERSIONS is usually better because it starts optimizing for conversions immediately instead of just accumulating clicks. - **Geo targeting is mandatory**: Every campaign must target specific countries/regions. Untargeted campaigns serve globally and waste budget. ALWAYS set geo_target_ids when creating campaigns. -- **Language targeting is mandatory**: Every campaign must target specific languages. Without it, ads show to all users in the geo region regardless of browser language. A German-language ad shown to an English speaker in Germany wastes budget. ALWAYS set language_ids when creating campaigns. +- **Search campaigns take no language targeting**: Google retired manual language targeting for Search campaigns in late September 2026. Search ads match on the language of the ads and landing page plus the user's language preferences, so write both in the language you want to reach. Language targeting still applies to Display, Video, App and Demand Gen campaigns, and within Performance Max to YouTube, Display, Discover and Gmail (not to its Search or Shopping ads). - **Match types**: Never recommend Broad Match without Smart Bidding (tCPA or tROAS) active on the campaign. Broad Match without Smart Bidding leads to budget waste. - **CPA monitoring**: Flag any campaign where CPA exceeds 3x the target for review. -- **Budget sufficiency**: A campaign's daily budget should be at least 5x its target CPA to generate enough data for the algorithm. -- **Learning phase**: Don't edit campaigns that are in an active learning phase (Google Ads shows "Learning" or "Learning (limited)" status). Wait until the learning phase completes before making changes. +- **Budget sufficiency**: AdLoop's rule of thumb is a daily budget of at least 5x the target CPA, so a campaign can collect several conversions a day. It is not a Google requirement: Google's low-traffic troubleshooting guide suggests at least 2 to 3 times the target CPA, or 10 times the expected CPC. Treat a smaller budget as a prompt to check, not as an error. +- **Learning status**: Google shows "Learning" for up to 7 days after a bid strategy is created or reactivated, after campaigns, ad groups or keywords are added to or removed from it, or after the conversion goals change significantly. Ads keep serving meanwhile. Changes to budgets, targets, creatives and targeting never trigger it. Budget, target and targeting changes apply from the next auction; new or edited ads have to pass policy review before they serve. Unless the business needs it, avoid several target changes within one conversion cycle: Google's guidance is to give a new target 1 to 2 conversion cycles. - **Negative keyword hygiene**: After reviewing search terms, always suggest adding irrelevant terms as negatives. Group them by theme. - **RSA best practices**: Provide at least 8-10 unique headlines (out of max 15) and 3-4 descriptions (out of max 4). Make headlines diverse — don't repeat the same message. **Pin only when necessary** — pinning reduces Google's ability to rotate assets and typically lowers ad strength. Reach for the dict shape `{"text": "...", "pinned_field": "HEADLINE_1"}` only for concrete brand-safety/compliance reasons. For phone numbers, prefer a campaign-level call asset over a pinned headline. See "Ad Copy Character Limits" section below for language-specific guidance. - **Quality Score**: If keywords have quality score < 5, prioritize improving ad relevance and landing page experience over bid increases. diff --git a/src/adloop/ads/read.py b/src/adloop/ads/read.py index 37e3a4f6..bcf76da4 100644 --- a/src/adloop/ads/read.py +++ b/src/adloop/ads/read.py @@ -91,19 +91,44 @@ def get_campaign_performance( _enrich_cost_fields(rows, currency_code) share_error = _attach_impression_share(config, customer_id, rows, date_clause) budget_limited = _budget_limited_converters(rows) + target_error = _classify_budget_share(config, customer_id, budget_limited) + flag_pct = int(_BUDGET_LOST_FLAG * 100) share_insights: list[str] = [] - if budget_limited: - names = ", ".join( - f"{r['name']} ({r['search_budget_lost_impression_share_pct']}% lost to budget)" - for r in budget_limited[:5] - ) + reliable = [r for r in budget_limited if not r.get(_BUDGET_SHARE_KEY)] + by_design = [r for r in budget_limited if r.get(_BUDGET_SHARE_KEY) == "unreliable"] + unknown = [r for r in budget_limited if r.get(_BUDGET_SHARE_KEY) == "unknown"] + if reliable: share_insights.append( - f"{len(budget_limited)} converting campaign(s) lose at least " - f"{int(_BUDGET_LOST_FLAG * 100)}% of Search impression share to " - f"budget: {names}. They run out of budget while converting; " + f"{len(reliable)} converting campaign(s) lose at least " + f"{flag_pct}% of Search impression share to " + f"budget: {_budget_lost_names(reliable)}. They run out of budget while converting; " f"compare their CPA with the account before moving budget to them." ) + if by_design: + share_insights.append( + f"{len(by_design)} converting campaign(s) on Maximize conversions or " + f"Maximize conversion value without a target also report at least " + f"{flag_pct}% lost to budget: {_budget_lost_names(by_design)}. Do not " + f"read that as room for more budget: without a target these " + f"strategies aim to spend the full daily budget, and Google says " + f"its Lost IS (budget) column is incompatible with them. Check " + f"Google's budget simulator before raising their budget." + ) + if unknown: + why = ( + f"the target lookup failed ({target_error})" if target_error + else "AdLoop could not read whether a target CPA or target ROAS is set" + ) + share_insights.append( + f"{len(unknown)} converting campaign(s) on Maximize conversions or " + f"Maximize conversion value also report at least {flag_pct}% lost " + f"to budget, and {why}: {_budget_lost_names(unknown)}. Treat that " + f"share as unconfirmed: if no target is set, Google says its Lost " + f"IS (budget) column is incompatible with the strategy. Check the " + f"target and Google's budget simulator before treating them as " + f"short of budget." + ) if not compact: result: dict = { @@ -174,6 +199,16 @@ def get_campaign_performance( "metrics.search_rank_lost_impression_share", ) _BUDGET_LOST_FLAG = 0.2 +# Without a target, Maximize conversions and Maximize conversion value aim to +# spend the whole daily budget, so they count as "limited by budget" by +# design. Google's help page says the Lost IS (budget) column is incompatible +# with them and points to the budget simulator instead: +# https://support.google.com/google-ads/answer/7381968 +# With a target CPA or target ROAS set they may not spend the full budget +# (https://developers.google.com/google-ads/api/reference/rpc/v25/MaximizeConversionValue), +# and the API reports the same strategy type either way, so the target has to +# be read before the caveat applies. +_SPENDS_FULL_BUDGET_STRATEGIES = ("MAXIMIZE_CONVERSIONS", "MAXIMIZE_CONVERSION_VALUE") _IMPRESSION_SHARE_NOTE = ( "Search impression share fields are fractions from the API (0.25 = 25%); " "the matching *_pct fields carry the same value as a percentage. Google " @@ -233,6 +268,94 @@ def _attach_impression_share( return error +def _budget_lost_names(items: list[dict], limit: int = 5) -> str: + """The first few flagged campaigns with their share, and how many more.""" + names = ", ".join( + f"{r['name']} ({r['search_budget_lost_impression_share_pct']}% lost to budget)" + for r in items[:limit] + ) + more = len(items) - limit + return names + (f" and {more} more" if more > 0 else "") + + +_BUDGET_SHARE_KEY = "budget_share_reliability" +_BUDGET_SHARE_ORDER = {None: 0, "unknown": 1, "unreliable": 2} +_UNREADABLE_STRATEGY_TYPES = ("", "UNSPECIFIED", "UNKNOWN") + + +def _classify_budget_share( + config: AdLoopConfig, customer_id: str, flagged: list[dict] +) -> str | None: + """Say how far the budget-lost share of each flagged campaign can be trusted. + + Only Maximize conversions and Maximize conversion value need a second + look: with no target CPA and no target ROAS, Google calls the Lost IS + (budget) column incompatible with them. The target is read in one extra + query, from the campaign or from its portfolio strategy, and only when a + flagged campaign uses one of those strategy types. + + Sets ``budget_share_reliability`` to "unreliable" (no target) or + "unknown" (the target could not be read) and leaves the key off every + campaign whose share reads as usual. Campaigns the column works with are + then listed first. Returns the lookup error, if there was one. + """ + from adloop.ads.gaql import _parse_gaql_error, execute_query + + candidates = [ + r for r in flagged + if r.get("bidding_strategy_type") in _SPENDS_FULL_BUDGET_STRATEGIES + ] + if not candidates: + return None + + error: str | None = None + targets: dict[str, dict] = {} + ids = ", ".join(str(r["id"]) for r in candidates if str(r.get("id") or "").isdigit()) + if ids: + query = f""" + SELECT campaign.id, campaign.bidding_strategy, + campaign.maximize_conversions.target_cpa_micros, + campaign.maximize_conversion_value.target_roas, + bidding_strategy.type, + bidding_strategy.maximize_conversions.target_cpa_micros, + bidding_strategy.maximize_conversion_value.target_roas + FROM campaign + WHERE campaign.id IN ({ids}) + """ + try: + targets = { + str(t.get("campaign.id")): t + for t in execute_query(config, customer_id, query) + } + except Exception as exc: # noqa: BLE001 - report it, keep the report + error = _parse_gaql_error(exc) + + for row in candidates: + state = _budget_share_state(targets.get(str(row.get("id")))) + if state: + row[_BUDGET_SHARE_KEY] = state + flagged.sort(key=lambda r: _BUDGET_SHARE_ORDER[r.get(_BUDGET_SHARE_KEY)]) + return error + + +def _budget_share_state(target: dict | None) -> str | None: + """None when a target is set, "unreliable" without one, "unknown" if unread.""" + if target is None: + return "unknown" + prefix = "campaign" + if target.get("campaign.bidding_strategy"): + # A portfolio strategy keeps the target on the portfolio. If the + # lookup cannot read the portfolio's type, its target is unknown. + if str(target.get("bidding_strategy.type") or "") in _UNREADABLE_STRATEGY_TYPES: + return "unknown" + prefix = "bidding_strategy" + has_target = ( + (target.get(f"{prefix}.maximize_conversions.target_cpa_micros") or 0) > 0 + or (target.get(f"{prefix}.maximize_conversion_value.target_roas") or 0) > 0 + ) + return None if has_target else "unreliable" + + def _budget_limited_converters(rows: list[dict]) -> list[dict]: """Converting campaigns that lose a significant share of Search to budget.""" limited = [ @@ -249,6 +372,7 @@ def _budget_limited_converters(rows: list[dict]) -> list[dict]: { "name": r.get("campaign.name"), "id": r.get("campaign.id"), + "bidding_strategy_type": r.get("campaign.bidding_strategy_type"), "conversions": r.get("metrics.conversions"), "cost": r.get("metrics.cost"), "cpa": r.get("metrics.cpa"), diff --git a/src/adloop/ads/write.py b/src/adloop/ads/write.py index 35caf6cb..50a590db 100644 --- a/src/adloop/ads/write.py +++ b/src/adloop/ads/write.py @@ -2160,8 +2160,10 @@ def draft_campaign( geo_target_ids: list of geo target constant IDs (e.g. ["2276"] for Germany, ["2840"] for USA). REQUIRED — campaigns must target specific countries. - language_ids: list of language constant IDs (e.g. ["1001"] for German, - ["1000"] for English). REQUIRED — campaigns must target specific languages. + language_ids: optional list of language constant IDs (e.g. ["1001"] for + German, ["1000"] for English). Google retired manual language + targeting for Search campaigns in late September 2026, so this is no + longer required; when given it is still sent, with a warning. location_option / negative_location_option: campaign.geo_target_type_setting. Empty leaves Google's default (PRESENCE_OR_INTEREST for both). tracking_url_template / final_url_suffix / url_custom_parameters: campaign @@ -2452,8 +2454,6 @@ def update_campaign( if geo_target_ids is not None and len(geo_target_ids) == 0: errors.append("geo_target_ids cannot be empty — provide at least one geo target") - if language_ids is not None and len(language_ids) == 0: - errors.append("language_ids cannot be empty — provide at least one language") if geo_exclude_ids is not None: geo_exclude_ids, exclude_errors = _normalize_geo_exclude_ids(geo_exclude_ids, geo_target_ids) errors.extend(exclude_errors) @@ -2498,6 +2498,13 @@ def update_campaign( if errors: return {"error": "Validation failed", "details": errors} + if language_ids is not None: + warnings.append( + "On a Search campaign: " + _SEARCH_LANGUAGE_WARNING + if language_ids + else _LANGUAGE_CLEAR_WARNING + ) + if bs == "MANUAL_CPC": warnings.append( "MANUAL_CPC bidding requires constant monitoring. Consider using " @@ -2509,7 +2516,9 @@ def update_campaign( currency_code = get_currency_code(config, customer_id) warnings.append( f"Daily budget {format_currency(daily_budget, currency_code)} is less than 5x target CPA " - f"{format_currency(target_cpa, currency_code)}. Google recommends at least 5x." + f"{format_currency(target_cpa, currency_code)}. 5x is AdLoop's rule of thumb, not a " + f"Google requirement; Google's low-traffic troubleshooting guide suggests a daily " + f"budget of 2 to 3 times the target CPA." ) # Surface negative geo exclusions that will survive a positive-geo @@ -4090,6 +4099,34 @@ def _validate_rsa( _VALID_CHANNEL_TYPES = {"SEARCH", "DISPLAY", "SHOPPING", "VIDEO", "PERFORMANCE_MAX"} +# Google retired manual language targeting for Search campaigns in late +# September 2026 (https://developers.google.com/google-ads/api/docs/deprecations, +# https://developers.google.com/google-ads/api/docs/targeting/criteria and +# https://support.google.com/google-ads/answer/1722078). Search ads match on +# the language of the ads and landing page plus the user's language +# preferences; existing language criteria read back and can be removed. The +# documentation says adding one fails, and tells API users to stop sending +# them. AdLoop no longer asks for language_ids and passes them through +# unchanged when they are given, so the dry run reports Google's own answer. +_SEARCH_LANGUAGE_WARNING = ( + "Google retired manual language targeting for Search campaigns in late " + "September 2026: Search ads now match on the language of the ads and " + "landing page plus the user's language preferences. Google's API " + "documentation tells developers to stop sending language criteria for " + "Search campaigns and says adding one fails with " + "OPERATION_NOT_PERMITTED_FOR_CONTEXT. language_ids is passed through as " + "given, so the dry run shows Google's answer; leave it out unless there " + "is a reason to send it." +) +_LANGUAGE_CLEAR_WARNING = ( + "language_ids=[] removes all campaign-level language criteria. On a " + "Search campaign Google no longer uses them (retired late September " + "2026). On campaigns that still take language targeting (Display, Video, " + "App, Demand Gen with campaign-level languages, and the YouTube, Display, " + "Discover and Gmail channels of Performance Max) removing them can widen " + "who sees the ads." +) + # campaign.geo_target_type_setting. Google's default for a new campaign is # PRESENCE_OR_INTEREST, which also reaches people elsewhere who show interest # in the targeted locations. @@ -4379,11 +4416,8 @@ def _validate_campaign( "geo_target_ids is required — campaigns must target at least one " "country/region (e.g. ['2276'] for Germany, ['2840'] for USA)" ) - if not language_ids: - errors.append( - "language_ids is required — campaigns must target at least one " - "language (e.g. ['1001'] for German, ['1000'] for English)" - ) + if language_ids: + warnings.append(_SEARCH_LANGUAGE_WARNING) bs = bidding_strategy.upper() if bs not in _VALID_BIDDING_STRATEGIES: @@ -4474,8 +4508,10 @@ def _validate_campaign( currency_code = get_currency_code(config, customer_id) warnings.append( f"Daily budget {format_currency(daily_budget, currency_code)} is less than 5x target CPA " - f"{format_currency(target_cpa, currency_code)}. Google recommends at least 5x target CPA " - f"({format_currency(5 * target_cpa, currency_code)}/day) for sufficient learning data." + f"{format_currency(target_cpa, currency_code)} " + f"({format_currency(5 * target_cpa, currency_code)}/day). 5x is AdLoop's rule of thumb, " + f"not a Google requirement; Google's low-traffic troubleshooting guide suggests a daily " + f"budget of 2 to 3 times the target CPA." ) if bs == "MANUAL_CPC": diff --git a/src/adloop/rules/adloop.md b/src/adloop/rules/adloop.md index a5f6e556..0715ba06 100644 --- a/src/adloop/rules/adloop.md +++ b/src/adloop/rules/adloop.md @@ -94,7 +94,7 @@ You have access to AdLoop MCP tools that connect Google Ads, Reddit Ads and Goog - Ads read tools automatically compute `metrics.cost` and `metrics.cpa` from `metrics.cost_micros` — no manual division needed. `metrics.currency` contains the account's currency code (auto-detected). - `metrics.average_cpc_amount` is also pre-computed where available. - `get_ad_performance` returns full `headlines` and `descriptions` lists for RSAs, plus `ad_group_ad.policy_summary.approval_status`, `review_status` and `policy_topics` (topic names only) per ad. Ads that are `DISAPPROVED` (cannot serve) or `APPROVED_LIMITED` (serving restricted) are listed in `policy_issues` with their spend and flagged in `insights[]`; compact mode adds `by_approval_status` counts. -- `get_campaign_performance` returns `metrics.search_impression_share`, `metrics.search_budget_lost_impression_share` and `metrics.search_rank_lost_impression_share` as fractions (0.25 = 25%) with matching `*_pct` percentages. Google caps the reported values: 0.0999 means below 10% share, 0.9001 means above 90% lost. They are `null` for campaigns that do not serve on Search (Display, Video, PMax, ...) or had no impressions, which means "does not apply", not zero. `budget_limited_converters` and `insights[]` flag converting campaigns losing 20% or more of impressions to budget: those can absorb more budget, rank-lost share instead points at bids, ad relevance and quality. +- `get_campaign_performance` returns `metrics.search_impression_share`, `metrics.search_budget_lost_impression_share` and `metrics.search_rank_lost_impression_share` as fractions (0.25 = 25%) with matching `*_pct` percentages. Google caps the reported values: 0.0999 means below 10% share, 0.9001 means above 90% lost. They are `null` for campaigns that do not serve on Search (Display, Video, PMax, ...) or had no impressions, which means "does not apply", not zero. `budget_limited_converters` and `insights[]` flag converting campaigns losing 20% or more of impressions to budget: those can absorb more budget, rank-lost share instead points at bids, ad relevance and quality. Exception: for a campaign on Maximize conversions or Maximize conversion value with no target CPA and no target ROAS, the budget-lost share is not a reliable signal. Without a target those strategies aim to spend the full daily budget, and Google says its Lost IS (budget) column is incompatible with them. Such campaigns carry `budget_share_reliability: "unreliable"` and get their own insight; Google's budget simulator is the place to check before raising their budget. The target is read from the campaign or from its portfolio strategy. When it cannot be read (a portfolio the account cannot read, or a failed lookup) the value is `"unknown"` and a third insight says so: treat those as unconfirmed, not as short of budget. Entries without the key are on strategies the column works with and are listed first; only those raise the dashboard's budget alert. - `get_change_history` returns changes newest first with counts `by_resource_type`, `by_client`, `by_user` and `by_day`. Google Ads keeps 30 days of change history, so an older start date is moved forward (see `notes`). `insights[]` flag auto-applied recommendations and budget or bidding changes. `truncated: true` means the limit was hit; narrow the range or filters to see older changes. - `get_recommendations` returns each recommendation's `recommendation.id` (what `draft_dismiss_recommendations` takes) and `estimated_improvement` per recommendation (potential minus base metrics) and `insights[]` that flag budget-increase recommendations, whose projected gain comes from spending more. - PMax tools: `get_pmax_performance` returns `insights[]` flagging weak ad strength and zero-conversion asset groups. `segments.ad_network_type` includes MIXED — a Google catch-all for most PMax traffic. Full channel splits (Search vs YouTube vs Display vs Discover) are not available via the API. @@ -374,7 +374,7 @@ Conversions that happen offline (a sales call, a lead that turned into a deal) g | Tool | What It Does | Validation | |------|-------------|------------| -| `draft_campaign` | Create full campaign structure (budget + campaign + ad group + keywords + geo/language targeting) | `campaign_name`, `daily_budget`, `bidding_strategy`, `geo_target_ids` (REQUIRED), `language_ids` (REQUIRED), optional `search_partners_enabled`, `display_network_enabled`, `display_expansion_enabled`, optional `max_cpc` for MANUAL_CPC ad-group bids or TARGET_SPEND CPC caps, optional `location_option` / `negative_location_option`, optional `tracking_url_template` / `final_url_suffix` / `url_custom_parameters`, optional `geo_exclude_ids` / `ad_schedule` | +| `draft_campaign` | Create full campaign structure (budget + campaign + ad group + keywords + geo/language targeting) | `campaign_name`, `daily_budget`, `bidding_strategy`, `geo_target_ids` (REQUIRED), optional `language_ids` (leave out: Google retired language targeting for Search campaigns in late September 2026), optional `search_partners_enabled`, `display_network_enabled`, `display_expansion_enabled`, optional `max_cpc` for MANUAL_CPC ad-group bids or TARGET_SPEND CPC caps, optional `location_option` / `negative_location_option`, optional `tracking_url_template` / `final_url_suffix` / `url_custom_parameters`, optional `geo_exclude_ids` / `ad_schedule` | | `draft_shopping_campaign` | Create a Standard Shopping campaign for a Merchant Center feed: budget + campaign (PAUSED) + product ad group + Shopping ad + one "All products" product group, atomically | `campaign_name`, `daily_budget`, `merchant_id` (must be linked to the Ads account; checked), `product_bid` (CPC of the product group, required by Google), `geo_target_ids` (REQUIRED), `bidding_strategy` MANUAL_CPC (default) / TARGET_SPEND (Maximize clicks, optional `max_cpc`) / TARGET_ROAS (+ `target_roas`), `campaign_priority` LOW/MEDIUM/HIGH, optional `feed_label`. No keywords, no languages | | `draft_asset_group_assets` | Add and/or remove assets of an existing PMax asset group in one atomic change: text, images, YouTube videos | `asset_group_id`, `headlines` (≤30), `long_headlines` (≤90), `descriptions` (≤90), `business_name` (≤25), `images` (`{"url"}` or `{"upload_id"}`, optional `role` marketing/logo/landscape_logo; marketing images sorted into landscape 1.91:1, square 1:1, portrait 4:5 by ratio), `youtube_video_ids`, `remove_asset_ids` | | `draft_asset_group_signals` | Add search themes or set the audience signal of a PMax asset group, or remove signals | `asset_group_id`, `add_search_themes` (≤80 chars, up to 50 per group), `audience_id` (one per group), `remove_signal_ids` | @@ -457,8 +457,8 @@ Same draft → preview → `confirm_and_apply` gate; the plan carries `platform: **Safety behaviors:** - New campaigns and RSAs (and every Reddit campaign, ad group and ad) are created as PAUSED — user must explicitly enable them after review. -- `draft_campaign` REQUIRES `geo_target_ids` and `language_ids` — campaigns without targeting waste budget. The tool rejects drafts with missing targeting. -- `draft_campaign` enforces the `max_daily_budget` safety cap, rejects BROAD match + non-Smart Bidding, warns if budget is below 5x target CPA, and interprets `max_cpc` by bidding strategy: MANUAL_CPC seeds the initial ad-group bid, TARGET_SPEND sets the Maximize Clicks CPC ceiling. +- `draft_campaign` REQUIRES `geo_target_ids` — campaigns without geo targeting waste budget, and the tool rejects such drafts. `language_ids` is optional and best left out: Google retired manual language targeting for Search campaigns in late September 2026, and Search ads now match on the language of the ads and landing page plus the user's language preferences. If it is passed, the preview warns and the dry run shows whether Google still accepts it. On `update_campaign`, `language_ids=[]` removes a campaign's campaign-level language criteria. +- `draft_campaign` enforces the `max_daily_budget` safety cap, rejects BROAD match + non-Smart Bidding, warns if budget is below 5x target CPA (AdLoop's rule of thumb, not a Google requirement), and interprets `max_cpc` by bidding strategy: MANUAL_CPC seeds the initial ad-group bid, TARGET_SPEND sets the Maximize Clicks CPC ceiling. - `display_network_enabled` is the canonical Search display-expansion flag. `display_expansion_enabled` is only a compatibility alias and should be normalized away before presenting the plan to the user. - `update_ad_group` is the right tool for later MANUAL_CPC bid changes. Use `update_campaign` for TARGET_SPEND (Maximize Clicks) `max_cpc` changes. - Ad-group pause/enable is already handled by `pause_entity` / `enable_entity` with `entity_type="ad_group"`; do not invent a separate pause tool. @@ -466,7 +466,7 @@ Same draft → preview → `confirm_and_apply` gate; the plan carries `platform: - Location options: `location_option` is who the geo targets reach — `PRESENCE` (people in or regularly in the locations), `PRESENCE_OR_INTEREST` (Google's default; also people elsewhere who show interest in them) or `SEARCH_INTEREST`. `negative_location_option` (`PRESENCE` or `PRESENCE_OR_INTEREST`) is who the exclusions exclude. Empty leaves the value as it is. The preview warns when a change widens reach: for `location_option` that is anything but `PRESENCE`, for `negative_location_option` it is `PRESENCE`, because then the exclusions only keep out people physically there, not people interested in the excluded places; `update_campaign` shows the current value as `current_location_option` / `current_negative_location_option`. Read back with `get_campaign_settings`. - Campaign URL options (`tracking_url_template`, `final_url_suffix`, `url_custom_parameters`): omitted leaves a value unchanged, `""` or `[]` removes it, and `url_custom_parameters` replaces the whole list. The template must contain `{lpurl}` or a variant (`{lpurl+2}`, `{unescapedlpurl}`, `{escapedlpurl+3}`, ...). Custom parameter keys are alphanumeric, at most 8 characters. The `update_campaign` preview shows each current value (`current_tracking_url_template` etc.), warns on a removal, and gives `example_click`: one of the campaign's final URLs with the campaign's options applied. It is approximate: a template on the ad group, ad or keyword overrides the campaign's, and ValueTrack parameters are filled at click time. Check it for typos before approving. Read back with `get_campaign_settings`. - Campaign-level broad match: `update_campaign` `keyword_match_type="BROAD"` CONVERTS every existing phrase and exact keyword in the campaign into broad match. Google shows the originals as Removed, turning the setting off does not restore them, and since September 2026 Google also upgrades such campaigns to AI Max. It is refused unless the campaign (or the `bidding_strategy` in the same call) is Smart Bidding — the same rule as BROAD keywords — checked again at apply, and needs a double confirmation. `keyword_match_type="UNSPECIFIED"` turns it off (single confirmation): no further conversions, but converted keywords stay broad and must be re-added as phrase/exact by hand. Moving a broad-match campaign to a non-Smart `bidding_strategy` is refused unless the same call passes `UNSPECIFIED`. Never turn it on to "get more traffic" on an exact/phrase campaign; read it back with `get_campaign_settings`, which lists it in `widening_settings`. -- `update_campaign` replaces POSITIVE geo/language targets entirely (not append). Pass the full desired list. NEGATIVE geo exclusions (criteria with `negative=TRUE`) are **preserved** across a positive-geo replacement — they survive the swap — unless `geo_exclude_ids` is passed in the same call. The preview surfaces preserved negative geo IDs in `preserved_negative_geo_target_ids` so the change is auditable. To ADD negative geo exclusions (e.g. exclude a city inside a targeted state), use `add_negative_locations` — do not try to express exclusions through `geo_target_ids`. To remove a negative geo exclusion explicitly, use `remove_entity` with `entity_type="campaign_criterion"`, or pass `geo_exclude_ids` without it. +- `update_campaign` replaces POSITIVE geo/language targets entirely (not append). Pass the full desired list. `language_ids` is for campaign types that still take language targeting (Display, Video, App, Demand Gen with campaign-level languages, and the YouTube, Display, Discover and Gmail channels of Performance Max). For a Search campaign Google's documentation says new language criteria are no longer accepted (retired late September 2026); `language_ids=[]` removes the campaign-level ones. NEGATIVE geo exclusions (criteria with `negative=TRUE`) are **preserved** across a positive-geo replacement — they survive the swap — unless `geo_exclude_ids` is passed in the same call. The preview surfaces preserved negative geo IDs in `preserved_negative_geo_target_ids` so the change is auditable. To ADD negative geo exclusions (e.g. exclude a city inside a targeted state), use `add_negative_locations` — do not try to express exclusions through `geo_target_ids`. To remove a negative geo exclusion explicitly, use `remove_entity` with `entity_type="campaign_criterion"`, or pass `geo_exclude_ids` without it. - `geo_exclude_ids` and `ad_schedule` set exclusions and windows when creating a campaign, in the same atomic request. A schedule there gets a warning, not a double confirmation: the campaign is created PAUSED, and once it is enabled it serves only inside the windows. On `update_campaign` they REPLACE the whole list: omitted leaves it unchanged, `[]` clears it. Use them to set the complete state; `add_negative_locations` and `add_ad_schedule` add to what is there. The preview shows the current values (`current_geo_exclude_ids`, `current_ad_schedule`), only the entries that differ are removed or added, and apply refuses if the current values changed after the preview. `update_campaign` needs a double confirmation for a campaign's first schedule (every other hour stops serving), for clearing a schedule (the campaign serves at all hours again) and for dropping an exclusion (it can serve there again). A location can move between `geo_target_ids` and `geo_exclude_ids` in one call; a location in both lists is refused. - **Asset scope:** callouts and snippets link where the id points (`ad_group_id` → ad group, `campaign_id` → campaign). Account-wide (`scope="account"`) reaches every campaign without assets of its own; use it only when the user asks for account level. **Asset edits** (`update_callout`, `update_sitelink`, `update_structured_snippet`) change the asset everywhere it is linked; check with GAQL (`campaign_asset`, `ad_group_asset`, `customer_asset`) where else it is used before editing a shared asset. If the apply reports the asset changed in Google Ads since the preview, draft again. - **Call assets, schedules, promotions and prices.** Never guess `country_code` or `language_code`: take them from the number and the landing page, and ask when unclear. Money amounts are in the account currency (the preview names it); pass `currency_code` only for a different one. Ad schedule hours are in the **account time zone** (the previews show it), not the searcher's: convert the user's local hours first. A campaign without a schedule serves at all hours, so its first `add_ad_schedule` windows switch off every other hour and day: say so, the preview needs a double confirmation. To change a window, pass the complete list as `update_campaign` `ad_schedule`, or remove the old one with `remove_entity` (`entity_type="campaign_criterion"`, the `remove_id` from the preview) and add the new one. Prices must match the landing page or Google disapproves them. @@ -586,12 +586,12 @@ Most websites (especially in the EU) use a GDPR cookie consent banner. This has 3. **Pre-write checks (CRITICAL):** - **Bidding strategy**: Default to MAXIMIZE_CONVERSIONS. It tells Google the goal is conversions (not just clicks), doesn't waste budget on non-converting clicks, and starts building the conversion model from day one — even with zero history, Google uses broad signals (search intent, device, time of day). Only use TARGET_SPEND/MANUAL_CPC if the user explicitly requests it and understands the trade-offs. - **Geo targeting**: ALWAYS ask the user which countries/regions to target if not specified. Never create a campaign without geo targets — untargeted campaigns waste budget on irrelevant geographies. Common IDs: 2276=Germany, 2040=Austria, 2756=Switzerland, 2840=USA, 2826=UK. - - **Language targeting**: ALWAYS ask the user which languages to target if not specified. Language targeting restricts ads to users whose browser/Google language matches — without it, ads show to anyone in the geo region regardless of language. Common IDs: 1001=German, 1000=English, 1002=French. + - **Language**: do not ask for language targets for a Search campaign. Google retired manual language targeting there in late September 2026; Search ads match on the language of the ads and landing page plus the user's language preferences. Confirm which language the ads and landing page are in instead. - Does the account have conversion tracking working? Call `attribution_check` — if zero conversions across the board, WARN that new campaigns won't help until tracking is fixed. - - Is the proposed budget reasonable? Must be ≤ `max_daily_budget` in config, and ideally ≥ 5x target CPA. -4. Call `draft_campaign` with campaign name, daily budget, bidding strategy, `geo_target_ids`, `language_ids`, ad group name, and optional keywords + - Is the proposed budget reasonable? Must be ≤ `max_daily_budget` in config, and ideally ≥ 5x target CPA (AdLoop's rule of thumb, not a Google requirement; Google's low-traffic troubleshooting guide suggests 2 to 3 times the target CPA). +4. Call `draft_campaign` with campaign name, daily budget, bidding strategy, `geo_target_ids`, ad group name, and optional keywords 5. Review the preview and any `warnings` (budget sufficiency, MANUAL_CPC warning, BROAD match rejection) -6. Present the complete preview to the user — emphasize the campaign will be created as PAUSED, and confirm the geo/language targets are correct +6. Present the complete preview to the user — emphasize the campaign will be created as PAUSED, and confirm the geo targets are correct 7. After campaign creation, remind the user to: - Add ads via `draft_responsive_search_ad` (with display paths set) - Add sitelinks via `draft_sitelinks` (at least 4 recommended) @@ -630,8 +630,8 @@ Most websites (especially in the EU) use a GDPR cookie consent banner. This has 3. **Pre-write checks:** - If changing to MAXIMIZE_CONVERSIONS: good default choice — confirm with the user - If changing to MANUAL_CPC: warn about the trade-offs (no automation, requires constant monitoring) - - If removing geo or language targets: warn that this broadens targeting and may waste budget - - If the campaign is in a learning phase: warn that changes will restart the learning phase + - If removing geo targets: warn that this broadens targeting and may waste budget. Language criteria on a Search campaign are no longer used by Google (retired late September 2026), so removing them there changes nothing; on campaign types that still take language targeting they narrow who sees the ads, so removing them can widen it + - Say whether the change shows Google's "Learning" status (up to 7 days, ads keep serving): a new or reactivated bid strategy, campaigns added to or removed from a portfolio strategy, or a significant change of conversion goals does. Budget, target, creative and targeting changes do not (budget, target and targeting changes apply from the next auction; new or edited ads go through policy review before they serve) - **Shared budgets and portfolio strategies:** a budget change on a SHARED budget changes the daily budget of every campaign using it, and a bidding change on a campaign in a portfolio bid strategy takes it out of the portfolio. The preview names the other campaigns and asks for a double confirmation; tell the user plainly before they confirm. If they meant only this campaign, its own budget has to be set up in Google Ads first 4. Call `update_campaign` with only the parameters that need to change 5. Present the preview — clearly show what's changing (old → new) @@ -1003,6 +1003,10 @@ For cities/regions, use `run_gaql` with `geo_target_constant` resource or look u ### Common Language IDs (languageConstants) +For the Keyword Planner tools (`discover_keywords`, `estimate_budget`) and for +campaigns that still take language targeting. Search campaigns do not (see +Marketing Best Practices). + Verified against the `language_constant` resource. Google accepts a wrong language ID silently, so confirm anything not listed here with: `SELECT language_constant.id, language_constant.code, language_constant.name FROM language_constant` @@ -1033,11 +1037,11 @@ When advising on Google Ads: - **Bid strategy default**: Prefer MAXIMIZE_CONVERSIONS for new campaigns. It leverages Google's signals from day one, even without conversion history. TARGET_SPEND (Maximize Clicks) only makes sense as a deliberate data-collection phase — and even then, MAXIMIZE_CONVERSIONS is usually better because it starts optimizing for conversions immediately instead of just accumulating clicks. - **Geo targeting is mandatory**: Every campaign must target specific countries/regions. Untargeted campaigns serve globally and waste budget. ALWAYS set geo_target_ids when creating campaigns. -- **Language targeting is mandatory**: Every campaign must target specific languages. Without it, ads show to all users in the geo region regardless of browser language. A German-language ad shown to an English speaker in Germany wastes budget. ALWAYS set language_ids when creating campaigns. +- **Search campaigns take no language targeting**: Google retired manual language targeting for Search campaigns in late September 2026. Search ads match on the language of the ads and landing page plus the user's language preferences, so write both in the language you want to reach. Language targeting still applies to Display, Video, App and Demand Gen campaigns, and within Performance Max to YouTube, Display, Discover and Gmail (not to its Search or Shopping ads). - **Match types**: Never recommend Broad Match without Smart Bidding (tCPA or tROAS) active on the campaign. Broad Match without Smart Bidding leads to budget waste. - **CPA monitoring**: Flag any campaign where CPA exceeds 3x the target for review. -- **Budget sufficiency**: A campaign's daily budget should be at least 5x its target CPA to generate enough data for the algorithm. -- **Learning phase**: Don't edit campaigns that are in an active learning phase (Google Ads shows "Learning" or "Learning (limited)" status). Wait until the learning phase completes before making changes. +- **Budget sufficiency**: AdLoop's rule of thumb is a daily budget of at least 5x the target CPA, so a campaign can collect several conversions a day. It is not a Google requirement: Google's low-traffic troubleshooting guide suggests at least 2 to 3 times the target CPA, or 10 times the expected CPC. Treat a smaller budget as a prompt to check, not as an error. +- **Learning status**: Google shows "Learning" for up to 7 days after a bid strategy is created or reactivated, after campaigns, ad groups or keywords are added to or removed from it, or after the conversion goals change significantly. Ads keep serving meanwhile. Changes to budgets, targets, creatives and targeting never trigger it. Budget, target and targeting changes apply from the next auction; new or edited ads have to pass policy review before they serve. Unless the business needs it, avoid several target changes within one conversion cycle: Google's guidance is to give a new target 1 to 2 conversion cycles. - **Negative keyword hygiene**: After reviewing search terms, always suggest adding irrelevant terms as negatives. Group them by theme. - **RSA best practices**: Provide at least 8-10 unique headlines (out of max 15) and 3-4 descriptions (out of max 4). Make headlines diverse — don't repeat the same message. **Pin only when necessary** — pinning reduces Google's ability to rotate assets and typically lowers ad strength. Reach for the dict shape `{"text": "...", "pinned_field": "HEADLINE_1"}` only for concrete brand-safety/compliance reasons. For phone numbers, prefer a campaign-level call asset over a pinned headline. See "Ad Copy Character Limits" section below for language-specific guidance. - **Quality Score**: If keywords have quality score < 5, prioritize improving ad relevance and landing page experience over bid increases. diff --git a/src/adloop/rules/commands/create-campaign.md b/src/adloop/rules/commands/create-campaign.md index 4b8dc06a..5d0cacd5 100644 --- a/src/adloop/rules/commands/create-campaign.md +++ b/src/adloop/rules/commands/create-campaign.md @@ -13,14 +13,14 @@ Create a new Google Ads campaign for: $ARGUMENTS ## 2. Budget estimation - If user hasn't specified a budget, call `estimate_budget` with proposed keywords -- Ask for target geography and language if not clear (common: 2276=Germany, 2840=USA, 2826=UK) +- Ask for target geography if not clear (common: 2276=Germany, 2840=USA, 2826=UK). Search campaigns take no language targeting (Google retired it in late September 2026): confirm which language the ads and landing page are in instead - Present the forecast: estimated clicks, impressions, cost, avg CPC ## 3. Pre-write checks (CRITICAL) - Bidding strategy: recommend MAXIMIZE_CONVERSIONS or TARGET_CPA over MANUAL_CPC - Conversion tracking: run `attribution_check` — if zero conversions across the board, WARN that a new campaign won't help until tracking is fixed -- Budget: must be <= max_daily_budget in config, ideally >= 5x target CPA +- Budget: must be <= max_daily_budget in config, ideally >= 5x target CPA (AdLoop's rule of thumb, not a Google requirement; Google's own guideline is 2 to 3 times) - Keywords: if using BROAD match, campaign MUST use Smart Bidding — otherwise use PHRASE or EXACT ## 4. Draft campaign diff --git a/src/adloop/rules/commands/optimize-campaign.md b/src/adloop/rules/commands/optimize-campaign.md index 371828b0..c694fdd7 100644 --- a/src/adloop/rules/commands/optimize-campaign.md +++ b/src/adloop/rules/commands/optimize-campaign.md @@ -43,12 +43,12 @@ Follow this checklist in order — earlier items have higher impact. ## 6. Budget -- Is daily budget >= 5x target CPA? +- Is daily budget >= 5x target CPA? (AdLoop's rule of thumb, not a Google requirement; Google's low-traffic guide suggests 2 to 3 times) - If not: either increase budget or focus on reducing CPA first - Use `estimate_budget` if considering budget changes ## Rules - One change at a time — show preview, wait for approval -- Never edit during Learning Phase +- Google's "Learning" status (up to 7 days) follows a new or reactivated bid strategy, a change in what the strategy covers, or a significant conversion-goal change. Budget, target, creative and targeting changes never trigger it. Avoid several target changes within one conversion cycle - Priority order: tracking > negatives > QS > ad copy > bidding > budget diff --git a/src/adloop/server.py b/src/adloop/server.py index 3de32ef5..7e798ea0 100644 --- a/src/adloop/server.py +++ b/src/adloop/server.py @@ -183,8 +183,10 @@ def _build_orchestration_instructions() -> str: "`attribution_check` — they factor this in.\n" "- `cost_micros / 1,000,000` = actual currency. Read tools " "auto-compute `metrics.cost`; only `run_gaql` returns raw micros.\n" - "- New campaigns MUST have `geo_target_ids` and `language_ids` set. " - "Untargeted campaigns waste budget." + "- New campaigns MUST have `geo_target_ids` set. Untargeted campaigns " + "waste budget. Search campaigns take no language targeting any more " + "(Google retired it in late September 2026): write the ads and landing " + "page in the language you want to reach." ) @@ -3892,7 +3894,7 @@ def draft_campaign( daily_budget: float, bidding_strategy: str, geo_target_ids: _StrList, - language_ids: _StrList, + language_ids: _StrListOpt = None, customer_id: str = "", target_cpa: float = 0, target_roas: float = 0, @@ -3937,7 +3939,10 @@ def draft_campaign( geo_target_ids: REQUIRED list of geo target constant IDs. Common: "2276" Germany, "2040" Austria, "2756" Switzerland, "2840" USA, "2826" UK, "2250" France. Full list: Google Ads API geo target constants. - language_ids: REQUIRED list of language constant IDs. + language_ids: Optional list of language constant IDs. Google retired + manual language targeting for Search campaigns in late September + 2026 (ads match on the language of the ads and landing page), so + leave it out; when given it is still sent and the preview warns. Common: "1001" German, "1000" English, "1002" French, "1003" Spanish, "1004" Italian, "1014" Portuguese. Full list: Google Ads API language constants. @@ -4120,8 +4125,11 @@ def update_campaign( geo_target_ids: REPLACES all positive geo targets; must not be empty when given. Common IDs: "2276" Germany, "2040" Austria, "2756" Switzerland, "2840" USA, "2826" UK. - language_ids: REPLACES all language targets; must not be empty when - given. Common IDs: "1001" German, "1000" English, "1002" French, + language_ids: REPLACES all campaign-level language targets; [] + removes them. Not for Search campaigns: Google retired manual + language targeting there in late September 2026 and documents + that existing criteria can only be removed; the preview warns. + Common IDs: "1001" German, "1000" English, "1002" French, "1003" Spanish, "1004" Italian. search_partners_enabled: Include ads on Search partners. Omitted leaves the setting unchanged. diff --git a/src/adloop/views/performance.py b/src/adloop/views/performance.py index 87e98a81..af025a6f 100644 --- a/src/adloop/views/performance.py +++ b/src/adloop/views/performance.py @@ -186,8 +186,13 @@ def _alerts(rows: list[dict], result: dict) -> dict: idle = [i for i in result.get("zero_conversion_spenders") or [] if isinstance(i, dict)] else: idle = [{"name": r["name"], "cost": r["cost"]} for r in rows if r["cost"] > 0 and not r["conversions"]] - limited = [i for i in result.get("budget_limited_converters") or [] if isinstance(i, dict)] - if not limited: + flagged = [i for i in result.get("budget_limited_converters") or [] if isinstance(i, dict)] + # Google calls the budget-lost share incompatible with Maximize conversions + # and Maximize conversion value run without a target, so those campaigns + # are not presented as held back by budget. + # A campaign whose target could not be read is left out as well. + limited = [i for i in flagged if not i.get("budget_share_reliability")] + if not flagged: limited = [ {"name": r["name"], "search_budget_lost_impression_share_pct": round(r["lost_to_budget"] * 100)} for r in rows diff --git a/tests/evals/planning.json b/tests/evals/planning.json index 90e55544..d8e44cad 100644 --- a/tests/evals/planning.json +++ b/tests/evals/planning.json @@ -5,11 +5,11 @@ { "id": 1, "prompt": "How much should I budget for Google Ads if I want to target 'CRM software' and 'customer management tool' keywords in the US market?", - "expected_output": "Should call estimate_budget with appropriate geo/language IDs (2840/1000), present forecast results, explain budget sufficiency (5x CPA rule).", + "expected_output": "Should call estimate_budget with appropriate geo/language IDs (2840/1000), present forecast results, explain budget sufficiency (AdLoop's 5x target CPA rule of thumb).", "expectations": [ "Calls estimate_budget with relevant keywords and geo_target_id=2840 (US) and language_id=1000 (English)", "Presents the forecast results: estimated clicks, impressions, cost, avg CPC", - "Mentions the budget sufficiency rule (daily budget >= 5x target CPA)", + "Mentions AdLoop's budget rule of thumb (daily budget >= 5x target CPA) without presenting it as a Google requirement", "Suggests a budget that captures at least 70% of available impressions or advises on budget sizing" ] }, diff --git a/tests/evals/write.json b/tests/evals/write.json index 0fa5158e..3cc43034 100644 --- a/tests/evals/write.json +++ b/tests/evals/write.json @@ -5,10 +5,10 @@ { "id": 1, "prompt": "Create a new search campaign for my swimming school in Berlin. Target Germany, German language, daily budget 30 euros, maximize conversions.", - "expected_output": "Should check existing campaigns, create draft_campaign with correct geo/language IDs, emphasize PAUSED status, use two-step write pattern, present full preview, wait for approval.", + "expected_output": "Should check existing campaigns, create draft_campaign with the correct geo IDs and no language IDs (Google retired language targeting for Search campaigns), emphasize PAUSED status, use two-step write pattern, present full preview, wait for approval.", "expectations": [ "Calls get_campaign_performance or list_accounts to check existing structure first", - "Uses geo_target_ids containing 2276 (Germany) and language_ids containing 1001 (German)", + "Uses geo_target_ids containing 2276 (Germany), leaves language_ids out, and plans the ads and landing page in German", "Sets bidding_strategy to MAXIMIZE_CONVERSIONS", "Presents a preview/plan before applying and waits for user approval", "Mentions that the campaign will be created as PAUSED", diff --git a/tests/test_google_guidance_accuracy.py b/tests/test_google_guidance_accuracy.py new file mode 100644 index 00000000..be5fc513 --- /dev/null +++ b/tests/test_google_guidance_accuracy.py @@ -0,0 +1,599 @@ +"""Advice that has to match Google's own documentation. + +Four statements AdLoop used to make are corrected here, each against a Google +page: + +- Search campaigns no longer take manual language targeting (retired late + September 2026), so ``language_ids`` cannot be required for them. + https://developers.google.com/google-ads/api/docs/deprecations + https://developers.google.com/google-ads/api/docs/targeting/criteria + https://support.google.com/google-ads/answer/1722078 +- The "at least 5x target CPA" budget warning is AdLoop's rule of thumb. The + warning used to say "Google recommends"; Google's own guideline is 2 to 3 + times the target CPA. + https://support.google.com/google-ads/answer/12092760 +- The Lost IS (budget) share is not a reliable signal for Maximize conversions + and Maximize conversion value run without a target. + https://support.google.com/google-ads/answer/7381968 +- "Learning" status is not triggered by budget, target, creative or targeting + changes (rules text only, checked in ``TestRulesText``). + https://support.google.com/google-ads/answer/13020501 +""" + +from __future__ import annotations + +import inspect +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from adloop.ads import read, write +from adloop.config import AdLoopConfig, AdsConfig, SafetyConfig +from adloop.safety import preview as preview_store +from adloop.views import performance as performance_view +from tests.test_ads_write import ( + _FakeClient, + _FakeGoogleAdsService, + _FakeMutateOperationResponse, + _FakePathService, +) + +REPO = Path(__file__).resolve().parent.parent + + +@pytest.fixture(autouse=True) +def _plans(): + preview_store.set_plan_store(preview_store.InMemoryPlanStore()) + yield + preview_store.set_plan_store(preview_store.InMemoryPlanStore()) + + +@pytest.fixture +def config(tmp_path) -> AdLoopConfig: + return AdLoopConfig( + ads=AdsConfig(customer_id="1234567890"), + safety=SafetyConfig(log_file=str(tmp_path / "audit.log"), max_daily_budget=500), + ) + + +@pytest.fixture +def no_queries(monkeypatch): + """Drafts that only touch targeting must not need the API in these tests.""" + monkeypatch.setattr("adloop.ads.gaql.execute_query", lambda *_a, **_k: []) + + +def _draft(config, **kwargs): + base = dict( + customer_id="1234567890", + campaign_name="Search", + daily_budget=20, + bidding_strategy="TARGET_SPEND", + geo_target_ids=["2840"], + ) + base.update(kwargs) + return write.draft_campaign(config, **base) + + +def _criterion_ops(operations, kind): + return [ + op.campaign_criterion_operation + for op in operations + if op.campaign_criterion_operation._pb.WhichOneof("operation") == kind + ] + + +def _language_creates(operations): + return [ + op.create.language.language_constant + for op in _criterion_ops(operations, "create") + if op.create.language.language_constant + ] + + +class TestSearchLanguageDraft: + def test_draft_campaign_no_longer_needs_language_ids(self, config): + result = _draft(config) + + assert "error" not in result + assert result["changes"]["language_ids"] == [] + assert not any("language" in w.lower() for w in result.get("warnings", [])) + + def test_draft_preview_keeps_language_ids_and_adds_googles_notice(self, config): + result = _draft(config, language_ids=["1001"]) + + assert "error" not in result + assert result["changes"]["language_ids"] == ["1001"] + notice = [w for w in result["warnings"] if "language targeting" in w] + assert len(notice) == 1 + assert "late September 2026" in notice[0] + assert "OPERATION_NOT_PERMITTED_FOR_CONTEXT" in notice[0] + + def test_geo_targets_stay_required(self, config): + result = _draft(config, geo_target_ids=[]) + + assert result["error"] == "Validation failed" + assert any("geo_target_ids is required" in d for d in result["details"]) + assert not any("language_ids" in d for d in result["details"]) + + def test_server_tool_makes_language_ids_optional(self): + from adloop import server + + tool = getattr(server.draft_campaign, "fn", server.draft_campaign) + params = inspect.signature(tool).parameters + + assert params["language_ids"].default is None + assert params["geo_target_ids"].default is inspect.Parameter.empty + + def test_update_draft_accepts_an_empty_language_list(self, config, no_queries): + result = write.update_campaign( + config, customer_id="1234567890", campaign_id="1001", language_ids=[], + ) + + assert "error" not in result + assert result["changes"]["language_ids"] == [] + warning = [w for w in result["warnings"] if "language" in w.lower()] + assert len(warning) == 1 + assert "removes all campaign-level language criteria" in warning[0] + assert "can widen who sees the ads" in warning[0] + + def test_update_draft_warns_when_setting_languages(self, config, no_queries): + result = write.update_campaign( + config, customer_id="1234567890", campaign_id="1001", language_ids=["1000"], + ) + + assert "error" not in result + notice = [w for w in result["warnings"] if "language targeting" in w] + assert len(notice) == 1 + assert notice[0].startswith("On a Search campaign:") + + def test_update_draft_without_languages_says_nothing_about_them( + self, config, no_queries + ): + result = write.update_campaign( + config, customer_id="1234567890", campaign_id="1001", + search_partners_enabled=False, + ) + + assert "error" not in result + assert not any("language" in w.lower() for w in result.get("warnings", [])) + + +class TestSearchLanguageApply: + """What actually reaches Google, not what the preview says.""" + + @staticmethod + def _create(language_ids): + service = _FakeGoogleAdsService([ + _FakeMutateOperationResponse("campaign_budget_result", "customers/1/campaignBudgets/1"), + _FakeMutateOperationResponse("campaign_result", "customers/1/campaigns/2"), + _FakeMutateOperationResponse("ad_group_result", "customers/1/adGroups/3"), + ]) + client = _FakeClient({ + "GoogleAdsService": service, + "CampaignService": _FakePathService("campaigns"), + "CampaignBudgetService": _FakePathService("campaignBudgets"), + "AdGroupService": _FakePathService("adGroups"), + }) + write._apply_create_campaign(client, "1234567890", { + "campaign_name": "Search Launch", + "daily_budget": 50, + "bidding_strategy": "MAXIMIZE_CONVERSIONS", + "channel_type": "SEARCH", + "ad_group_name": "Main", + "geo_target_ids": ["2840"], + "language_ids": language_ids, + }) + return service.operations + + def test_create_without_languages_sends_no_language_criterion(self): + operations = self._create([]) + + assert _language_creates(operations) == [] + geo = [ + op.create.location.geo_target_constant + for op in _criterion_ops(operations, "create") + if op.create.location.geo_target_constant + ] + assert geo == ["geoTargetConstants/2840"] + + def test_create_passes_given_languages_through_unchanged(self): + operations = self._create(["1001", "1000"]) + + assert _language_creates(operations) == [ + "languageConstants/1001", "languageConstants/1000", + ] + + @staticmethod + def _update(language_ids): + queries: list[str] = [] + existing = [ + "customers/1234567890/campaignCriteria/1001~1000", + "customers/1234567890/campaignCriteria/1001~1003", + ] + + class _Searchable(_FakeGoogleAdsService): + def search(self, customer_id: str, query: str): + queries.append(query) + return [ + SimpleNamespace(campaign_criterion=SimpleNamespace(resource_name=rn)) + for rn in existing + ] + + service = _Searchable([ + _FakeMutateOperationResponse("campaign_criterion_result", "customers/1/campaignCriteria/x"), + ]) + client = _FakeClient({ + "GoogleAdsService": service, + "CampaignService": _FakePathService("campaigns"), + }) + write._apply_update_campaign( + client, "1234567890", {"campaign_id": "1001", "language_ids": language_ids}, + ) + return service.operations, queries, existing + + def test_update_with_empty_list_removes_and_creates_nothing(self): + operations, queries, existing = self._update([]) + + assert len(queries) == 1 + assert "campaign_criterion.type = 'LANGUAGE'" in queries[0] + assert [op.remove for op in _criterion_ops(operations, "remove")] == existing + assert _criterion_ops(operations, "create") == [] + + def test_update_with_languages_replaces_the_criteria(self): + operations, _queries, existing = self._update(["1001"]) + + assert [op.remove for op in _criterion_ops(operations, "remove")] == existing + assert _language_creates(operations) == ["languageConstants/1001"] + + +class TestBudgetRuleOfThumb: + def test_draft_warning_does_not_cite_google_for_5x(self, config, monkeypatch): + monkeypatch.setattr("adloop.ads.currency.get_currency_code", lambda *_a, **_k: "USD") + + result = _draft( + config, bidding_strategy="TARGET_CPA", target_cpa=50, daily_budget=100, + ) + + warning = [w for w in result["warnings"] if "5x target CPA" in w] + assert len(warning) == 1 + assert "Google recommends" not in warning[0] + assert "AdLoop's rule of thumb, not a Google requirement" in warning[0] + assert "2 to 3 times the target CPA" in warning[0] + + def test_no_message_in_the_write_module_says_google_recommends_5x(self): + source = (REPO / "src" / "adloop" / "ads" / "write.py").read_text() + + assert "Google recommends at least 5x" not in source + assert "publishes no fixed multiple" not in source + # draft_campaign and update_campaign each carry the corrected wording. + assert source.count("5x is AdLoop's rule of thumb") == 2 + assert source.count("2 to 3 times the target CPA") == 2 + + +def _campaign(cid, name, strategy): + return { + "campaign.id": cid, "campaign.name": name, + "campaign.advertising_channel_type": "SEARCH", + "campaign.bidding_strategy_type": strategy, + "metrics.impressions": 1000, "metrics.clicks": 100, + "metrics.cost_micros": 50_000_000, "metrics.conversions": 5, + } + + +def _share(cid, lost=0.35): + return { + "campaign.id": cid, "metrics.impressions": 1000, + "metrics.search_impression_share": 0.4, + "metrics.search_budget_lost_impression_share": lost, + "metrics.search_rank_lost_impression_share": 0.25, + } + + +def _target(cid, *, portfolio="", portfolio_type="UNSPECIFIED", cpa=0, roas=0.0, + portfolio_cpa=0, portfolio_roas=0.0): + return { + "campaign.id": cid, "campaign.bidding_strategy": portfolio, + "campaign.maximize_conversions.target_cpa_micros": cpa, + "campaign.maximize_conversion_value.target_roas": roas, + "bidding_strategy.type": portfolio_type, + "bidding_strategy.maximize_conversions.target_cpa_micros": portfolio_cpa, + "bidding_strategy.maximize_conversion_value.target_roas": portfolio_roas, + } + + +_PORTFOLIO = "customers/123/biddingStrategies/9" + + +def _performance(monkeypatch, campaigns, targets, *, compact=False): + """Run get_campaign_performance with the three queries answered from lists. + + ``targets`` may be an exception to simulate the target lookup failing. + """ + import adloop.ads.gaql as gaql + + seen: list[str] = [] + + def _query(_config, _cid, query): + seen.append(query) + if "target_cpa_micros" in query: + if isinstance(targets, Exception): + raise targets + return [dict(t) for t in targets] + if "search_impression_share" in query: + return [_share(c["campaign.id"]) for c in campaigns] + return [dict(c) for c in campaigns] + + monkeypatch.setattr(gaql, "execute_query", _query) + monkeypatch.setattr("adloop.ads.currency.get_currency_code", lambda *_a, **_k: "USD") + config = AdLoopConfig(ads=AdsConfig(customer_id="123")) + result = read.get_campaign_performance(config, customer_id="123", compact=compact) + return result, seen + + +def _caveats(result): + return [i for i in result.get("insights", []) if "Do not read that as room" in i] + + +def _unconfirmed(result): + return [i for i in result.get("insights", []) if "unconfirmed" in i] + + +def _plain(result): + return [i for i in result.get("insights", []) if "run out of budget" in i] + + +KEY = "budget_share_reliability" + + +class TestBudgetLostShareOnFullBudgetStrategies: + @pytest.mark.parametrize("strategy", ["MAXIMIZE_CONVERSIONS", "MAXIMIZE_CONVERSION_VALUE"]) + @pytest.mark.parametrize("compact", [False, True]) + def test_untargeted_strategy_gets_the_caveat_and_not_the_plain_claim( + self, monkeypatch, strategy, compact + ): + result, _ = _performance( + monkeypatch, [_campaign(1, "Search Converting", strategy)], [_target(1)], + compact=compact, + ) + + flagged = result["budget_limited_converters"] + assert flagged[0]["bidding_strategy_type"] == strategy + assert flagged[0][KEY] == "unreliable" + caveat = _caveats(result) + assert len(caveat) == 1 + assert "Search Converting" in caveat[0] + assert "without a target" in caveat[0] + assert "incompatible" in caveat[0] + assert "budget simulator" in caveat[0] + assert _plain(result) == [] + assert _unconfirmed(result) == [] + + @pytest.mark.parametrize("strategy", ["MAXIMIZE_CONVERSIONS", "MAXIMIZE_CONVERSION_VALUE"]) + def test_an_untargeted_portfolio_strategy_gets_the_caveat_too(self, monkeypatch, strategy): + target = _target(1, portfolio=_PORTFOLIO, portfolio_type=strategy) + + result, _ = _performance( + monkeypatch, [_campaign(1, "Search Converting", strategy)], [target], + ) + + assert result["budget_limited_converters"][0][KEY] == "unreliable" + assert len(_caveats(result)) == 1 + assert _plain(result) == [] + + @pytest.mark.parametrize("strategy,target", [ + ("MAXIMIZE_CONVERSIONS", _target(1, cpa=40_000_000)), + ("MAXIMIZE_CONVERSION_VALUE", _target(1, roas=4.0)), + ("MAXIMIZE_CONVERSIONS", + _target(1, portfolio=_PORTFOLIO, portfolio_type="MAXIMIZE_CONVERSIONS", + portfolio_cpa=40_000_000)), + ("MAXIMIZE_CONVERSION_VALUE", + _target(1, portfolio=_PORTFOLIO, portfolio_type="MAXIMIZE_CONVERSION_VALUE", + portfolio_roas=4.0)), + ], ids=["target-cpa", "target-roas", "portfolio-target-cpa", "portfolio-target-roas"]) + def test_a_target_keeps_the_plain_reading(self, monkeypatch, strategy, target): + result, _ = _performance( + monkeypatch, [_campaign(1, "Search Converting", strategy)], [target], + ) + + assert KEY not in result["budget_limited_converters"][0] + assert _caveats(result) == [] + assert _unconfirmed(result) == [] + assert len(_plain(result)) == 1 + + @pytest.mark.parametrize("targets", [ + [], + [_target(1, portfolio=_PORTFOLIO)], + [_target(1, portfolio=_PORTFOLIO, portfolio_type="UNKNOWN")], + ], ids=["no-row", "unreadable-portfolio", "unknown-portfolio-type"]) + def test_an_unread_target_is_unconfirmed_not_a_budget_claim(self, monkeypatch, targets): + result, _ = _performance( + monkeypatch, [_campaign(1, "Search Converting", "MAXIMIZE_CONVERSIONS")], targets, + ) + + assert result["budget_limited_converters"][0][KEY] == "unknown" + note = _unconfirmed(result) + assert len(note) == 1 + assert "Search Converting" in note[0] + assert "could not read whether a target" in note[0] + assert _plain(result) == [] + assert _caveats(result) == [] + + def test_the_lookup_reads_campaign_and_portfolio_targets_in_one_query(self, monkeypatch): + campaigns = [ + _campaign(1, "One", "MAXIMIZE_CONVERSIONS"), + _campaign(2, "Two", "MAXIMIZE_CONVERSION_VALUE"), + _campaign(3, "Three", "TARGET_CPA"), + ] + + _, seen = _performance(monkeypatch, campaigns, [_target(1), _target(2)]) + + lookups = [q for q in seen if "target_cpa_micros" in q] + assert len(lookups) == 1 + for field in ( + "campaign.id", + "campaign.bidding_strategy", + "campaign.maximize_conversions.target_cpa_micros", + "campaign.maximize_conversion_value.target_roas", + "bidding_strategy.type", + "bidding_strategy.maximize_conversions.target_cpa_micros", + "bidding_strategy.maximize_conversion_value.target_roas", + ): + assert field in lookups[0], field + assert "campaign.id IN (1, 2)" in lookups[0] + + def test_a_failed_lookup_is_reported_not_swallowed(self, monkeypatch): + result, _ = _performance( + monkeypatch, [_campaign(1, "Search Converting", "MAXIMIZE_CONVERSIONS")], + RuntimeError("quota exhausted"), + ) + + assert result["budget_limited_converters"][0][KEY] == "unknown" + note = _unconfirmed(result) + assert len(note) == 1 + assert "the target lookup failed" in note[0] + assert "quota exhausted" in note[0] + assert _plain(result) == [] + + @pytest.mark.parametrize("strategy", ["TARGET_CPA", "TARGET_ROAS", "MANUAL_CPC", "TARGET_SPEND"]) + def test_other_strategies_never_trigger_the_target_lookup(self, monkeypatch, strategy): + result, seen = _performance( + monkeypatch, [_campaign(1, "Search Converting", strategy)], [_target(1)], + ) + + assert not any("target_cpa_micros" in q for q in seen) + assert KEY not in result["budget_limited_converters"][0] + assert _caveats(result) == [] + assert len(_plain(result)) == 1 + + def test_an_affected_campaign_beyond_the_first_five_is_still_named(self, monkeypatch): + campaigns = [_campaign(i, f"Target {i}", "TARGET_CPA") for i in range(1, 6)] + campaigns.append(_campaign(6, "Untargeted Six", "MAXIMIZE_CONVERSIONS")) + + result, _ = _performance(monkeypatch, campaigns, [_target(6)]) + + assert len(result["budget_limited_converters"]) == 6 + caveat = _caveats(result) + assert len(caveat) == 1 and "Untargeted Six" in caveat[0] + plain = _plain(result) + assert len(plain) == 1 + assert plain[0].startswith("5 converting campaign(s)") + assert "Untargeted Six" not in plain[0] + + def test_long_lists_say_how_many_names_were_left_out(self, monkeypatch): + campaigns = [_campaign(i, f"Target {i}", "TARGET_CPA") for i in range(1, 8)] + + result, _ = _performance(monkeypatch, campaigns, []) + + assert "and 2 more" in _plain(result)[0] + + def test_campaigns_the_column_works_with_are_listed_first(self, monkeypatch): + campaigns = [ + _campaign(1, "Untargeted", "MAXIMIZE_CONVERSIONS"), + _campaign(2, "Unread", "MAXIMIZE_CONVERSIONS"), + _campaign(3, "On Target CPA", "TARGET_CPA"), + ] + + result, _ = _performance(monkeypatch, campaigns, [_target(1)]) + + order = [(f["name"], f.get(KEY)) for f in result["budget_limited_converters"]] + assert order == [ + ("On Target CPA", None), ("Unread", "unknown"), ("Untargeted", "unreliable"), + ] + + +class TestDashboardBudgetAlert: + @staticmethod + def _rows(*names): + return [ + {"name": n, "cost": 50.0, "conversions": 5, "lost_to_budget": 0.35} + for n in names + ] + + @pytest.mark.parametrize("state", ["unreliable", "unknown"]) + def test_unconfirmed_campaigns_are_not_shown_as_held_back_by_budget(self, state): + result = {"budget_limited_converters": [ + {"name": "Maximize", "search_budget_lost_impression_share_pct": 35.0, KEY: state}, + ]} + + alerts = performance_view._alerts(self._rows("Maximize"), result) + + assert "limited" not in alerts + + def test_reliable_campaigns_still_raise_the_alert(self): + result = {"budget_limited_converters": [ + {"name": "On Target CPA", "search_budget_lost_impression_share_pct": 35.0}, + {"name": "Untargeted", "search_budget_lost_impression_share_pct": 40.0, + KEY: "unreliable"}, + ]} + + alerts = performance_view._alerts(self._rows("Untargeted", "On Target CPA"), result) + + assert alerts["limited"]["title"].startswith("1 campaign") + assert "On Target CPA" in alerts["limited"]["detail"] + assert "Untargeted" not in alerts["limited"]["detail"] + + @pytest.mark.parametrize("compact,untargeted", [(True, 5), (False, 10)]) + def test_a_real_alert_survives_the_truncated_list(self, monkeypatch, compact, untargeted): + """Enough unconfirmed campaigns to fill the returned list must not hide + the one campaign the budget alert is about.""" + campaigns = [ + _campaign(i, f"Untargeted {i}", "MAXIMIZE_CONVERSIONS") + for i in range(1, untargeted + 1) + ] + campaigns.append(_campaign(99, "On Target CPA", "TARGET_CPA")) + targets = [_target(i) for i in range(1, untargeted + 1)] + + result, _ = _performance(monkeypatch, campaigns, targets, compact=compact) + + returned = result["budget_limited_converters"] + assert len(returned) == untargeted + assert returned[0]["name"] == "On Target CPA" + alerts = performance_view._alerts(self._rows("On Target CPA"), result) + assert alerts["limited"]["title"].startswith("1 campaign") + assert "On Target CPA" in alerts["limited"]["detail"] + + +class TestRulesText: + """The three copies of the rules must carry the corrected statements.""" + + _COPIES = ( + REPO / ".cursor" / "rules" / "adloop.mdc", + REPO / ".claude" / "rules" / "adloop.md", + REPO / "src" / "adloop" / "rules" / "adloop.md", + ) + + @pytest.mark.parametrize("path", _COPIES, ids=lambda p: p.parent.parent.name + "/" + p.name) + def test_outdated_statements_are_gone(self, path): + text = path.read_text() + + assert "Language targeting is mandatory" not in text + assert "`language_ids` (REQUIRED)" not in text + assert "Don't edit campaigns that are in an active learning phase" not in text + assert "changes will restart the learning phase" not in text + assert "take effect at once" not in text + assert "publishes no fixed multiple" not in text + + @pytest.mark.parametrize("path", _COPIES, ids=lambda p: p.parent.parent.name + "/" + p.name) + def test_corrected_statements_are_present(self, path): + text = path.read_text() + + assert "Search campaigns take no language targeting" in text + assert "never trigger it" in text + assert "pass policy review before they serve" in text + assert "AdLoop's rule of thumb" in text + assert "2 to 3 times the target CPA" in text + assert "Lost IS (budget) column is incompatible" in text + assert "with no target CPA and no target ROAS" in text + assert '`budget_share_reliability: "unreliable"`' in text + assert '`"unknown"`' in text + + def test_the_three_copies_have_the_same_body(self): + def body(path): + text = path.read_text() + if text.startswith("---"): + text = text.split("---", 2)[2] + return text.strip() + + cursor, claude, packaged = (body(p) for p in self._COPIES) + assert cursor == claude == packaged diff --git a/tests/test_server.py b/tests/test_server.py index 577a3b1a..433b7b9b 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -163,7 +163,7 @@ def test_instructions_cover_data_literacy(self): text = _build_orchestration_instructions() # GDPR consent gap is the #1 source of misdiagnosed "tracking issues". assert "GDPR" in text or "consent" in text.lower() - # Geo / language targeting is mandatory. + # Geo targeting is mandatory; language is explained (Search takes none). assert "geo" in text.lower() assert "language" in text.lower()