Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .claude/commands/create-campaign.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions .claude/commands/optimize-campaign.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
32 changes: 18 additions & 14 deletions .claude/rules/adloop.md

Large diffs are not rendered by default.

32 changes: 18 additions & 14 deletions .cursor/rules/adloop.mdc

Large diffs are not rendered by default.

140 changes: 132 additions & 8 deletions src/adloop/ads/read.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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 "
Expand Down Expand Up @@ -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 = [
Expand All @@ -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"),
Expand Down
60 changes: 48 additions & 12 deletions src/adloop/ads/write.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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 "
Expand All @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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":
Expand Down
Loading
Loading