ADVERTISING / NOTEBOOK LESSON

54 · A08 · Ad candidate indexes and constrained matching

Verify constrained ad retrieval against a brute-force oracle and recheck eligibility.

Constructed mechanism / simulationRead-only · saved experiment

Saved outputs come from recorded teaching runs; opening this page does not rerun an experiment. The code and original outputs are preserved; original-language data and annotations may remain.

A08 · Ad candidate indexes and constrained matching

Prerequisites: foundations 31–34; A07.

Evidence: explicitly constructed mechanism experiments, not real ad logs. This chapter does not claim industrial-system reproduction or online gains.

Learning order: predict → change one variable → run → explain.

English companion. All instructional Markdown is translated. Experiment code, Chinese language examples, execution counts, and saved outputs remain as in the source edition; historical output text may therefore be Chinese. The initial setup cell anchors the working directory and Python import path for this companion's deeper folder; it does not change the experiment. Saved outputs are historical evidence, not a new run. Run from the top after preparing the required data and models.

PYTHON · 01
# English companions live one directory deeper; keep the original experiment code unchanged.
from pathlib import Path as _TranslationPath
import os as _translation_os
import sys as _translation_sys
_translation_root = next((p for p in [_TranslationPath.cwd(), *_TranslationPath.cwd().parents]
                          if (p / "reclab").is_dir()), None)
if _translation_root is None:
    raise RuntimeError("Open this notebook from inside the Search Recommendation Ads Lab checkout.")
_translation_os.chdir(_translation_root)
if str(_translation_root) not in _translation_sys.path:
    _translation_sys.path.insert(0, str(_translation_root))

Problem and input/output contract

Build a postings set per keyword, OR query terms, then AND the result with geography, enabled campaigns, and positive budgets. Top-k operates only on eligible candidates. A brute-force scan is this example’s oracle for checking the index. High vector similarity cannot override eligibility. Budget may change after retrieval and must be rechecked before bidding or charging.

Before running, predict which result the changed variable will affect and which invariants must hold.

PYTHON · 02
from pathlib import Path
import sys
root=Path.cwd()
if not (root/'reclab').exists(): root=root.parent
if str(root) not in sys.path: sys.path.insert(0,str(root))
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from reclab import ads_curriculum as ac

Run the one-variable comparison

Inputs are small constructed examples visible in source. Output units and constraints are defined above. Run assertions to verify mathematics and accounting.

PYTHON · 03
for query in ('跑鞋','运动 旅行','未知'):
 for region in ('上海','北京'):
  print(query,region,[a['id'] for a in ac.candidates(query,region)])
assert len(ac.candidates(topk=1))==1
assert ac.candidates(query='旅行')==[]
import inspect
print(inspect.getsource(ac.candidates))
Saved notebook output · not executed on this page
跑鞋 上海 ['a', 'b']
跑鞋 北京 ['b']
运动 旅行 上海 ['a']
运动 旅行 北京 []
未知 上海 []
未知 北京 []
def candidates(query='跑鞋', region='上海', topk=3):
    ads=inventory(); index={}
    for a in ads:
        for key in a['keywords']: index.setdefault(key,set()).add(a['id'])
    tokens=set(query.split()); recalled=set().union(*(index.get(t,set()) for t in tokens))
    eligible=[a for a in ads if a['id'] in recalled and region in a['regions'] and a['active'] and a['budget']>0]
    oracle=[a for a in ads if tokens & a['keywords'] and region in a['regions'] and a['active'] and a['budget']>0]
    assert {a['id'] for a in eligible}=={a['id'] for a in oracle}
    return sorted(eligible,key=lambda a:(-a['quality']*a['bid'],a['id']))[:topk]

Interpretation and limits

OR across terms must not become OR across every condition. Candidate d has a travel keyword but zero budget and incompatible geography, so it must be excluded. Fewer than k results is valid; do not relax hard constraints to fill slots.

Inspect source, then try an exercise

Change term OR to AND and verify with the brute-force oracle. Simulate a campaign pausing after retrieval and confirm charging stops.

PYTHON · 04
import inspect
print(inspect.getsource(ac.candidates))
Saved notebook output · not executed on this page
def candidates(query='跑鞋', region='上海', topk=3):
    ads=inventory(); index={}
    for a in ads:
        for key in a['keywords']: index.setdefault(key,set()).add(a['id'])
    tokens=set(query.split()); recalled=set().union(*(index.get(t,set()) for t in tokens))
    eligible=[a for a in ads if a['id'] in recalled and region in a['regions'] and a['active'] and a['budget']>0]
    oracle=[a for a in ads if tokens & a['keywords'] and region in a['regions'] and a['active'] and a['budget']>0]
    assert {a['id'] for a in eligible}=={a['id'] for a in oracle}
    return sorted(eligible,key=lambda a:(-a['quality']*a['bid'],a['id']))[:topk]

Sources and next step

Targeting/auction sections in the A-LIU outline; the constrained candidate index is an original Lab extension. This is an original Lab exercise, not a copy of the complete lecture text.

Chinese GitHub chapter · Authors’ RTB slides. The Chinese deck is not a complete modern advertising-engineering course. Historical descriptions of platforms are not presented as current market facts.

After the exercise, return to the ads learning path and continue to the next semantic unit.

GO TO THE SOURCE

Sources for this lesson

Completion marks are optional and stored only in this browser. Reading a page does not mark it complete.