# Identity graph and rules-based attribution blueprint

Companion to "How to build an identity graph and rules-based attribution models in BigQuery" (Kickflip Analytics, part 2 of the AI marketing analyst series). Load this into Claude or your `CLAUDE.md` and work through it with your own decisions. It assumes a GA4 BigQuery export modelled in Dataform with staging (`stg_`, `int_`), core (`fct_`, `dim_`) and reporting (`rpt_`) layers, as in the part 1 blueprint (`marketing-warehouse-mcp-blueprint.md`), but the design works on any GA4 export.

Placeholders you decide are marked `<like this>`.

---

## 0. Decisions to make first

Ask (or record) these before building anything:

1. **Which IDs do you trust to link browsers?** Usually GA4 `user_id` from a login (`<customer ID>`). Later candidates: hashed email, CRM ID, a server-side ID. Deterministic only.
2. **Population.** Consented observations only (recommended). Unconsented conversions stay on `_unconsented` until a DPIA covers stitching them.
3. **Anchor rules.** Max anchors per profile (recommended 1), max anchors per browser before quarantine (recommended 3), alert threshold for browsers per profile (no hard cap; Safari ITP produces many).
4. **Staff / internal.** Is there a field that identifies staff accounts (e.g. account type)? Relabel to a `staff` channel rather than excluding.
5. **Lookback window.** `<90>` days. One project variable.
6. **What counts as a touchpoint.** Arrivals (recommended) vs sessions. Whether mid-session returns from organic / referral count (recommended yes).
7. **Dedupe rule.** Back-to-back arrivals from the same source / medium within `<30>` minutes count once.
8. **Models.** Last non-direct, first non-direct, linear non-direct, plus GA4's own label kept for reconciliation. Cap on linear path length (test before deciding; default none).
9. **Restatement.** Agree up front that history restates as the graph learns.
10. **Release.** Does the analyst / dashboards read any column you'll rename? Plan to ship both the same day.

---

## 1. Identity graph

### 1.1 Config (`includes/identity.js`)

```js
const ID_TYPES = {
  customer_id:  { anchor: true, priority: 1, max_per_profile: 1, level: "customer" },
  ga_client_id: { anchor: false, max_anchors: 3 }          // > 3 anchors = shared device, quarantined
};
const BLOCKLIST = ["0", "-1", "null", "undefined", "none", "nan", "(not set)", "_na", "_unknown", "_unconsented"];
const STRATEGIES = {
  browser:  { id_types: ["ga_client_id"], links: [] },
  customer: { id_types: ["ga_client_id", "customer_id"], links: [["ga_client_id", "customer_id"]] }
};
const STAFF_ACCOUNT_TYPES = ["<staff>"];
const ATTRIBUTION_STRATEGY = "customer";
const MAX_CLIENT_IDS_PER_PROFILE_ALERT = 500;
```

`profile_key = TO_HEX(SHA256(CONCAT(<id_type>, ':', <id_value>)))` of the anchor (or of the client ID for a browser-only profile). Stable across runs; doesn't expose the raw ID.

### 1.2 Tables (all `table`, rebuilt every run, tag `identity`)

| Table | Layer | Grain | Notes |
|---|---|---|---|
| `int_identity__observations` | staging | date × id_type × id_value × linked id | From GA4 events where analytics consent = granted. Counts, first / last seen, staff signal |
| `int_identity__edges` | staging | id_a → id_b | Oriented non-anchor → anchor. `link_status`: `kept`, `blocked`, `quarantined_shared_id`, `dropped_weaker_link` |
| `int_identity__quarantine` | staging | one row per non-kept link | With the rule that removed it; review after any rule change |
| `dim_identity_map` | core | strategy × id → `profile_key` | The join table. `identity_link_rule`, first / last seen |
| `dim_identity_profiles` | core | strategy × `profile_key` | `profile_level`, anchor type, `<id_type>_count`, `is_staff`, `has_quarantined_id` |

### 1.3 Edge rules

1. Drop blocklisted values.
2. For each browser, count distinct anchors. More than `max_anchors` → every link from that browser is `quarantined_shared_id`.
3. Otherwise keep the strongest link: rank by distinct days seen together, then most recent day, then value (for determinism). Others → `dropped_weaker_link`.
4. A browser with no kept link becomes its own profile.

### 1.4 Rules of use

- Never store `profile_key` on an incremental fact. Facts keep native IDs; models resolve the key at build time by joining `dim_identity_map`.
- Never expose `profile_key` or raw IDs in reporting tables or the AI analyst.
- Right to erasure: delete from the raw export and staging; the graph forgets on the next run.
- Health check: profiles by strategy and level, staff profiles, max client IDs per profile, quarantine counts by rule.

### 1.5 Assertions

- One `profile_key` per id per strategy in the map.
- No profile with more than `max_per_profile` anchors.
- No quarantined id in a kept edge.
- Every observed id appears in the map.
- Browser strategy profiles hold exactly one client ID.
- No blocklisted value anywhere in the map.

---

## 2. Arrivals (touchpoints)

### 2.1 Session signals (`int_ga4__session_sources`, incremental, protected)

Per session (`session_key = user_pseudo_id || '-' || ga_session_id`, plus `report_date`):

- `has_campaign_tags`: any `collected_traffic_source.manual_*` set, or `utm_` in `page_location`.
- `has_click_id`: gclid / dclid / srsltid in `collected_traffic_source`, or gclid / gbraid / wbraid / dclid / msclkid / fbclid / ttclid / srsltid in the URL.
- `external_referrer_host`: the landing page's referrer if it's not one of your own hosts (`<your domains regex>`).
- `has_own_signal` = any of the three.

### 2.2 Mid-session arrivals (`int_ga4__mid_session_arrivals`, incremental, protected)

- `page_view` events more than **60 seconds** after session start (avoids counting the landing twice: it often appears on `session_start` and the first `page_view`).
- With a source from `collected_traffic_source.manual_source / manual_medium`, or a click ID mapped:

| Click ID | source / medium |
|---|---|
| gclid, gbraid, wbraid, dclid | google / cpc |
| srsltid | google / organic |
| msclkid | bing / cpc |
| fbclid | facebook / referral |
| ttclid | tiktok / referral |

- Keep it only if it differs from the session's current source (the previous mid-session arrival, else the session's GA4 label): different source or medium, or a different campaign when one is set.
- **Organic and referral returns** need no extra rule. When a page view part-way through a session comes in from another site, GA4 fills that event's `collected_traffic_source.manual_source` / `manual_medium` with its own classification (e.g. `google` / `organic`, `<site>` / `referral`), with or without UTMs, so the same rule catches tagged links, search returns and referrals. The catch is that you inherit GA4's classification: a return GA4 doesn't classify (e.g. a stripped referrer in some in-app browsers) is missed.
- BigQuery won't accept a non-constant default in `LAG`, so use `COALESCE(LAG(STRUCT(...)) OVER (...), STRUCT(label_source, label_medium, label_campaign))`.

### 2.3 Touchpoints (`int_attribution__touchpoints`, table)

1. **Landing arrivals:** sessions with `has_own_signal` AND a non-direct GA4 label; source / medium / campaign from the GA4 label; `touchpoint_ts` = session start.
2. **Mid-session arrivals:** from 2.2; `touchpoint_ts` = the page view.
3. Attach `profile_key` from `dim_identity_map` (strategy `<customer>`), falling back to the browser key.
4. **Dedupe back-to-back** (compare each arrival only with the one straight before it on the profile):

```sql
deduped AS (
  SELECT *
  FROM (
    SELECT
      *,
      LAG(STRUCT(touchpoint_ts AS ts, LOWER(source) AS source, LOWER(medium) AS medium))
        OVER (PARTITION BY profile_key ORDER BY touchpoint_ts, arrival_type, session_key) AS prev
    FROM arrivals
  )
  WHERE prev.ts IS NULL
     OR NOT (prev.source = LOWER(source) AND prev.medium = LOWER(medium)
             AND touchpoint_ts < TIMESTAMP_ADD(prev.ts, INTERVAL 30 MINUTE))
)
```

Don't partition the dedupe by source / medium: for Google Ads → organic → Google Ads it drops the second ad click and hands last non-direct to organic.

5. `touchpoint_id = session_key || '|' || date || '|' || ROW_NUMBER() OVER (PARTITION BY session_key, report_date ORDER BY touchpoint_ts, arrival_type)`; `touchpoint_type = 'web_arrival'`.

---

## 3. Conversions (`int_attribution__conversions`, table)

One row per conversion (bookings, sign-ups, ...): `attributed_object_type`, id, `report_date`, timestamp, `session_key`, `user_pseudo_id`, `is_unconsented`, `profile_key` (NULL when unconsented).

---

## 4. Credits (`fct_attribution_credits`, table, partitioned by `report_date`, clustered by `attribution_model`, `attributed_object_type`)

### 4.1 Columns

`report_date`, `attributed_object_type` (`web_session` / `<booking>` / `<signup>`), `attributed_object_id`, `attribution_model`, `credited_touchpoint_type`, `credited_touchpoint_id`, `credited_touchpoint_ts`, `credit_share`, `attribution_resolution` (`arrival_same_session` / `arrival_same_browser` / `arrival_other_browser` / `direct` / `unconsented`), `credited_source`, `credited_medium`, `credited_campaign`, `credited_campaign_id`, `credited_ga4_channel`, `touchpoint_number`, `path_touchpoint_count`, `days_before_attributed`.

### 4.2 Logic

- **Timeline** per profile: arrivals (kind 0) + sessions and consented conversions (kind 1), ordered by timestamp, kind, id.
- **Last non-direct** (sessions and conversions): `LAST_VALUE(arrival IGNORE NULLS) OVER (PARTITION BY profile_key ORDER BY ts, kind, id ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)`; credit it if within the window, else Direct (`(direct)` / `(none)`, resolution `direct`). A session's own landing arrival sorts before the session (kind 0 < 1), so it credits itself.
- **First non-direct:** join each conversion to arrivals on the profile within the window; `n = 1`.
- **Linear non-direct:** every arrival in the window, `credit_share = 1 / path_touchpoint_count`.
- **No arrival in the window:** one Direct row, share 1, per model.
- **Unconsented conversions:** one row per model, credited to `_unconsented`.
- Each conversion looks back independently, even when windows overlap.
- **GA4 session IDs repeat** (same `user_pseudo_id` + `ga_session_id` days apart): join on `session_key` AND `report_date` everywhere; for a conversion's own session take the latest one at or before the conversion.

### 4.3 Assertions

- `SUM(credit_share) = 1` per object × model (group including `report_date`).
- Single-touch models have exactly one row per object.
- Coverage: every session / conversion in the facts has credits for every model it supports; no credits for objects that don't exist.
- No NULL source, medium, share or resolution.
- Reporting reconciliation: each model's totals in the reporting table equal the facts.

---

## 5. Model registry (`includes/attribution.js`)

One entry per model, used to generate columns, field descriptions, metrics register rows and CI checks:

```js
const MODELS = {
  last_non_direct:     { display: "last non-direct click", scope: "session",    ga4: { source: "credits" } },
  first_non_direct:    { display: "first non-direct click", scope: "conversion", ga4: { source: "credits" } },
  linear_non_direct:   { display: "linear non-direct",     scope: "conversion", ga4: { source: "credits" },
                         types: { bookings: "FLOAT64", signups: "FLOAT64" } },  // use your own outcome names
  ga4_last_non_direct: { display: "GA4 last non-direct click", scope: "session", ga4: { source: "fact", struct: "attribution_ga4_last_non_direct" } },
  ad_platform:         { display: "Ad platform reported", scope: "platform", platform: { struct: "attribution_ad_platform" } }
};
const ARRIVAL_DEDUPE_MINUTES = 30;
```

Each entry also carries a technical `definition`, a plain-English `business` line (for the metrics register and the AI analyst) and its `population`.

Naming (from part 1): multi-model tables put the model on the metric (`attribution_linear_non_direct_bookings`); single-model tables put it on the dimensions (`attribution_last_non_direct_channel`). Only say "ga4" in a model name when the logic is GA4's own.

---

## 6. Reporting

- **Channel table** (`rpt_channel_daily`): for credit models, join the facts to credits on id AND `report_date`, multiply outcomes by `credit_share` (round fractional counts to 4 dp, values to 2 dp); map credited source / medium to channels; relabel staff profiles to `staff`.
- **Traffic table** (`rpt_web_traffic_daily`): last non-direct on the dimensions, plus `attribution_last_non_direct_resolution`, and `session_source` / `session_medium` / `session_channel` from the session's own landing arrival (else `(direct)` / `(none)`).
- **Traffic sources dim:** union in credited source / medium pairs from the credits table, or mid-session sources that never appear as a session label won't map to a channel.
- Add new metrics to the metrics register; the AI analyst should read it for definitions.

---

## 7. Validate before building

Run each candidate design as one query against production (identity, session sources, mid-session arrivals, touchpoints and credits as CTEs) and look at:

- Bookings by channel under each model vs GA4's label (totals must match).
- Path length quartiles and max.
- Where the last arrival sits (same session / same browser / other browser).
- Arrivals per week, and the share that are mid-session.
- Effect of a path cap (last 20 / last 10) on each channel before deciding on one.

---

## 8. Release

1. Test on dev (sample mode, full refresh: renamed columns and new incremental tables).
2. Merge after the morning production run.
3. Rename any GA4 attribution columns on protected incremental facts: `ALTER TABLE <fact> RENAME COLUMN attribution_last_non_direct TO attribution_ga4_last_non_direct` (metadata only). Check row counts before and after. Do it straight after the merge, before any run starts.
4. Load history for new incremental tables (session sources, mid-session arrivals) in backfill mode, only those actions, full refresh; then put the config back to incremental and recompile.
5. Run the GA4 tag (identity, attribution, reports) without full refresh.
6. Rebuild the metrics register if it's only on the daily tag.
7. Ship the AI analyst update the same day (renamed models, new models, aliases for old names, staff channel, caveats).
8. QA in production: assertions, coverage, reconciliation across models, figures against your pre-release validation.

---

## 9. Gotchas

- `session_traffic_source_last_click` is already last non-direct and inherits across sessions: don't treat every labelled session as a touchpoint.
- `collected_traffic_source` keeps UTMs that the site strips from `page_location`; check both.
- The landing often appears on both `session_start` and the first `page_view`: use a time threshold for mid-session arrivals.
- `ga_session_id` isn't unique, even combined with `user_pseudo_id`: join on key + date.
- `LAG` defaults must be constants in BigQuery: use `COALESCE(LAG(...), ...)`.
- Window dedupe partitioned by source / medium breaks last non-direct (see 2.3).
- Check how your own app or emails tag links. If something variable (e.g. the page path) goes into `utm_source`, two links opened in one visit look like two sources, both count as arrivals, and that channel is flattered under linear and first non-direct. Normalise the source, or dedupe that channel on medium.
- Dev incremental tables don't pick up renamed columns: full refresh in dev.
- A table rebuilt only on the daily tag (e.g. the metrics register) won't reflect the change until tomorrow unless you run it.
- Expect the AI analyst's cached tool descriptions to lag in open chats; test in a new chat.
- Figures restate as the graph learns. Say so to stakeholders before they notice.
