Skip to content
Merged
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
32 changes: 32 additions & 0 deletions alembic/versions/2026-10-30_meme_ok_created_at_index.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
"""Index fresh ok memes by created_at for explore_budget_v1 feed queries.

low_sent_pool (labeling budget, < 7d) and fresh_viral (< 72h) filter on
meme.created_at; without this index they bitmap-scan every ok meme of the
user's languages (~400ms per heavy user on prod).

Revision ID: b2d4f6a8c0e1
Revises: a7c9e2f5b8d1
Create Date: 2026-10-30
"""

from alembic import op

revision = "b2d4f6a8c0e1"
down_revision = "a7c9e2f5b8d1"
branch_labels = None
depends_on = None


def upgrade() -> None:
with op.get_context().autocommit_block():
# A failed CONCURRENTLY build leaves an INVALID index; drop it so reruns rebuild.
op.execute("DROP INDEX CONCURRENTLY IF EXISTS ix_meme_ok_created_at")
op.execute(
"CREATE INDEX CONCURRENTLY ix_meme_ok_created_at "
"ON meme (created_at) WHERE status = 'ok'"
)


def downgrade() -> None:
with op.get_context().autocommit_block():
op.execute("DROP INDEX CONCURRENTLY IF EXISTS ix_meme_ok_created_at")
135 changes: 135 additions & 0 deletions docs/analyst/explore-budget-v1.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
-- explore_budget_v1 readout (one SELECT; read-only)
-- Experiment doc: experiments/active/2026-10-30-explore-budget.md
-- Rows: variant x segment (mod = moderator/admin, user = everyone else).
-- Per-user means, feed sends only (recommended_by NOT LIKE 'broadcast%'),
-- counted from each user's assigned_at.
--
-- Primary: likes_per_user_week, memes_per_session
-- Guardrails: pos2_abandon (first feed meme after a reacted push, no reaction
-- within 30 min), fresh_ru_labeled_share (global, same on every row:
-- RU ok memes created 14..7d ago with >= 10 reactions within 7d;
-- must stay >= 0.90; global, not per arm, and only reflects the
-- experiment once memes created after its start are 7d old). Empty-queue errors live in Sentry/logs
-- ("recommendation batch diagnostics", selected_count = 0).
-- Diagnostics: like_rate, low_sent_share, fresh_viral_share.
--
-- Bounded: user_meme_reaction is read via (user_id, sent_at) and
-- (sent_at, meme_id, user_id) indexes only; no meme_id-keyed scans.
WITH assigned AS (
SELECT
EA.user_id,
EA.variant,
EA.assigned_at,
CASE WHEN U.type IN ('moderator', 'admin') THEN 'mod' ELSE 'user' END AS seg
FROM experiment_assignment EA
JOIN "user" U ON U.id = EA.user_id
WHERE EA.experiment_id = 'explore_budget_v1'
),
sends AS (
SELECT
A.variant,
A.seg,
A.user_id,
A.assigned_at,
R.sent_at,
R.reacted_at,
R.reaction_id,
R.recommended_by,
R.recommended_by LIKE 'broadcast%' AS is_push
FROM assigned A
JOIN user_meme_reaction R
ON R.user_id = A.user_id
AND R.sent_at >= A.assigned_at
),
feed AS (
SELECT
*,
CASE
WHEN LAG(sent_at) OVER (PARTITION BY user_id ORDER BY sent_at) IS NULL
OR sent_at - LAG(sent_at) OVER (PARTITION BY user_id ORDER BY sent_at)
> INTERVAL '30 minutes'
THEN 1 ELSE 0
END AS new_session
FROM sends
WHERE NOT is_push
),
per_user AS (
SELECT
variant,
seg,
user_id,
COUNT(*) FILTER (WHERE reaction_id = 1) AS likes,
COUNT(*) FILTER (WHERE reaction_id IS NOT NULL) AS reactions,
COUNT(*) AS feed_sends,
COUNT(*) FILTER (WHERE recommended_by = 'low_sent_pool') AS low_sent_sends,
COUNT(*) FILTER (WHERE recommended_by = 'fresh_viral') AS fresh_viral_sends,
SUM(new_session) AS sessions,
GREATEST(EXTRACT(EPOCH FROM NOW() - MIN(assigned_at)) / 604800.0, 1.0 / 7) AS weeks
FROM feed
GROUP BY 1, 2, 3
),
pushes AS (
SELECT variant, seg, user_id, reacted_at
FROM sends
WHERE is_push AND reacted_at IS NOT NULL
),
pos2 AS (
SELECT
P.variant,
P.seg,
(NXT.reacted_at IS NULL OR NXT.reacted_at > NXT.sent_at + INTERVAL '30 minutes')
AS abandoned
FROM pushes P
JOIN LATERAL (
SELECT R.sent_at, R.reacted_at
FROM user_meme_reaction R
WHERE R.user_id = P.user_id
AND R.sent_at >= P.reacted_at
AND R.sent_at < P.reacted_at + INTERVAL '30 minutes'
AND R.recommended_by NOT LIKE 'broadcast%'
ORDER BY R.sent_at
LIMIT 1
) NXT ON TRUE
),
fresh_ru AS (
SELECT
AVG(CASE WHEN COALESCE(L.n, 0) >= 10 THEN 1.0 ELSE 0.0 END) AS labeled_share,
COUNT(*) AS memes
FROM meme M
LEFT JOIN (
SELECT R.meme_id, COUNT(*) AS n
FROM user_meme_reaction R
JOIN meme M2 ON M2.id = R.meme_id
WHERE R.sent_at >= NOW() - INTERVAL '14 days'
AND R.reaction_id IS NOT NULL
AND R.reacted_at < M2.created_at + INTERVAL '7 days'
GROUP BY 1
) L ON L.meme_id = M.id
WHERE M.status = 'ok'
AND M.language_code = 'ru'
AND M.created_at >= NOW() - INTERVAL '14 days'
AND M.created_at < NOW() - INTERVAL '7 days'
)
SELECT
U.variant,
U.seg,
COUNT(*) AS users,
SUM(U.feed_sends) AS feed_sends,
ROUND(AVG(U.likes / U.weeks)::numeric, 2) AS likes_per_user_week,
ROUND(AVG(U.feed_sends::numeric / NULLIF(U.sessions, 0)), 2) AS memes_per_session,
ROUND(AVG(U.likes::numeric / NULLIF(U.reactions, 0)), 3) AS like_rate,
ROUND(SUM(U.low_sent_sends)::numeric / NULLIF(SUM(U.feed_sends), 0), 3) AS low_sent_share,
ROUND(SUM(U.fresh_viral_sends)::numeric / NULLIF(SUM(U.feed_sends), 0), 3)
AS fresh_viral_share,
(SELECT COUNT(*) FROM pos2 WHERE pos2.variant = U.variant AND pos2.seg = U.seg)
AS pos2_n,
(
SELECT ROUND(AVG(CASE WHEN abandoned THEN 1.0 ELSE 0.0 END), 3)
FROM pos2
WHERE pos2.variant = U.variant AND pos2.seg = U.seg
) AS pos2_abandon,
(SELECT ROUND(labeled_share, 3) FROM fresh_ru) AS fresh_ru_labeled_share,
(SELECT memes FROM fresh_ru) AS fresh_ru_memes
FROM per_user U
GROUP BY 1, 2
ORDER BY 2, 1
1 change: 1 addition & 0 deletions docs/growth/HYPOTHESES.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ Readout: [`docs/analyst/readouts/2026-10-30-experiment-closure.md`](../analyst/r
| **2026-08-23** | Feed exp finals if needed | H1 primarily |
| **2026-08-24** | Taste shadow readout | **H7** |
| Ad-hoc | Bot→channel ML re-run / walk-forward | **H8** |
| **2026-11-20** | `explore_budget_v1` keep/kill — [`experiments/active/2026-10-30-explore-budget.md`](../../experiments/active/2026-10-30-explore-budget.md) | explore budget |
| Ad-hoc | After any ranking/deploy incident | all active |

Agent prompt on resume (copy-paste):
Expand Down
106 changes: 106 additions & 0 deletions experiments/active/2026-10-30-explore-budget.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
# Experiment: Explore budget v1 (labeling budget + fresh-viral + idle-return slot)

Created: 2026-10-30
Status: active
Owner: engineer / analyst
Deployed: pending (first `explore_budget_v1` assignment row = start)
Measure after: 2026-11-20

## Hypothesis

Moderators are super-users and should not be stuck on a worse feed. They get
`low_sent_pool` in 75% of batches today: 256k sends in 30d at LR 0.24–0.32,
against 0.31–0.42 from other engines for the same users. 40% of those sends go
to memes that are 180–360 days old at their 21st+ send, and 75% go to sources
the user mostly dislikes. That is far more than labeling needs: about 390 fresh
RU+EN memes/day × ~10 reactions ≈ 3.9k labels/day, while low_sent delivers
about 8.5k/day. Meanwhile regular users rarely see fresh winners. Early LR
predicts later LR: first-20 LR ≥ 0.50 means later regular-user LR 0.46 vs a
0.436 baseline, and < 0.40 means 0.355. Sessions die on the first feed meme
after a push (23% abandon). That slot is lr_smoothed today; warm-queue
engines abandon 11–15% there.

Spending exploration only where it labels fresh memes, while showing proven
fresh winners to everyone, should raise likes per active user and memes per
session without starving labeling.

## Changes Made (treatment only)

1. **Labeling budget**: moderator low_sent quota is 50% instead of 75%
(`feed_turn.planner.low_sent_quota`). `low_sent_pool` serves only memes
< 7d old with < 20 reactions. It early-stops when smoothed LR
`(likes+1)/(reactions+2)` < 0.25 after ≥ 10 reactions, and orders the user's
disliked sources last (`RECOMMENDATION_DEMOTE_*`). An unfilled quota falls
through to the normal blend, which is existing behavior.
2. **Fresh-viral**: `fresh_viral` engine (`like_spread_and_recent_memes(fresh_viral=True)`)
serves memes < 72h old with ≥ 20 reactions and raw LR ≥ 0.50. It takes 15%
of the mature blend mass, with other engines scaled ×0.85. All blend engines
drop fresh memes (< 7d) with ≥ 20 reactions and LR < 0.40.
3. **Idle-return first slot**: with an empty queue, the first meme comes from
`like_spread_and_recent_memes` instead of `lr_smoothed`. The queue's Redis TTL
is 1h, so an empty queue means the user was idle > 1h or arrived from a
push. Moderators get that meme before their labeling memes. Known noise:
the TTL restarts on every refill, and the queue can also be empty mid-session
(a refill still in flight). If the push itself falls back to the queue, it
takes this slot.
4. Migration `ix_meme_ok_created_at` (partial `meme(created_at) WHERE status='ok'`)
keeps the fresh-window queries well under 300 ms per user (see Latency).

Code: `src/recommendations/pipeline.py`, `candidates.py`, `blender_experiments.py`,
`meme_queue.py`, `src/feed_turn/planner.py`.

## Assignment

- Eligible: users at batch build with `nmemes_sent ≥ 30`. Cold start is untouched.
- Split: `sha256("explore_budget_v1:" + user_id) % 2`, persisted in
`experiment_assignment` on the first eligible batch (variant `control` / `treatment`).
- Kill switch: `EXPLORE_BUDGET_V1_ENABLED=false`, which serves everyone the control feed.
Assignment rows stay readable.

## Decision rule (check 2026-11-20)

Readout: `docs/analyst/explore-budget-v1.sql` (one SELECT, read-only). Read it per
segment (`mod` / `user`), with per-user means over feed sends only (broadcasts excluded).

**Primary**
- `likes_per_user_week` (likes per active user per week)
- `memes_per_session` (30-min gap sessions)

**Guardrails**
- `fresh_ru_labeled_share` ≥ 0.90: RU ok memes reach ≥ 10 reactions within 7d.
Baseline 1.000 on 2026-10-30, with n = 2251 memes created 14..7d ago. This is
global, not per arm, and only reflects the experiment from about day 14.
- Empty-queue errors: Sentry/logs `recommendation batch diagnostics` with
`selected_count = 0` or `last_resort_used = true` must not rise vs pre-deploy.
- `pos2_abandon` (first feed meme after a reacted push, no reaction ≤ 30 min)
must be ≤ control.

**Ship** (treatment becomes default, experiment code collapses) if both primaries
are ≥ control in both segments, at least one is up ≥ 3% relative, and every
guardrail holds.
**Kill** (set the kill switch, then remove the code) if any guardrail breaks or both
primaries are down. Otherwise **hold** to 2026-12-04. If only the labeling
guardrail breaks, raise the moderator quota back toward 75% before killing.

## Latency (prod EXPLAIN ANALYZE, 2026-10-30, heaviest 3-language moderator)

| query | before index | index-equivalent plan |
|---|---|---|
| low_sent control (current prod) | 3,581 ms | (unchanged) |
| low_sent treatment | 441 ms | 97 ms |
| fresh_viral | 365 ms | 57 ms |
| bad-fresh filter (90 ids, PK) | 1.6 ms | 1.6 ms |

"Index-equivalent" bounds `meme.id` to the 7d / 72h range, which is the same
range scan the new partial index provides.

## Metrics Before / After

| Window | users C/T (mod) | users C/T (user) | likes/user/wk C/T | memes/session C/T | pos2 abandon C/T | fresh RU labeled | Decision |
|---|---|---|---|---|---|---|---|
| 2026-11-06 smoke | | | | | | | |
| 2026-11-20 | | | | | | | |

## Conclusion

_Filled on completion only._
3 changes: 3 additions & 0 deletions src/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ class Config(BaseSettings):
# H10 cold_start_fresh_viral_v1: KILLED 2026-10-30 (first tap and 1h block
# rate both worse in treatment). Off = no new assignment, everyone is control.
COLD_START_FRESH_VIRAL_EXPERIMENT_ENABLED: bool = False
# explore_budget_v1: 50/50 non-cold-start users get the labeling budget,
# fresh-viral blend slot and idle-return first slot. Kill switch = all control.
EXPLORE_BUDGET_V1_ENABLED: bool = True

# Recommendation batch diagnostics are realtime operational data, not
# durable product facts. Keep compact logs/spans always on and sample full
Expand Down
24 changes: 19 additions & 5 deletions src/feed_turn/planner.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import annotations

from dataclasses import dataclass
from dataclasses import dataclass, replace
from math import ceil
from types import MappingProxyType
from typing import Any, Mapping
Expand All @@ -13,6 +13,13 @@

MODERATOR_USER_TYPES = frozenset({"moderator", "admin"})

# explore_budget_v1 treatment: smaller labeling share for moderators, and the
# first meme after an idle gap (empty queue; queue TTL is 1h) comes from an
# engine with lower post-push abandonment than lr_smoothed.
LOW_SENT_SHARE = 0.75
EXPLORE_BUDGET_LOW_SENT_SHARE = 0.5
IDLE_RETURN_FIRST_SLOT_ENGINE = "like_spread_and_recent_memes"

# Single source of truth for default blend weights. Experiments must import
# these maps rather than re-declaring the control blend.
GROWING_BLEND_WEIGHTS: Mapping[str, float] = MappingProxyType(
Expand Down Expand Up @@ -130,22 +137,29 @@ def plan_candidate_selection_for_user(
cold_start_nsessions_gate_enabled: bool,
limit: int | None = None,
cold_start_account_too_old: bool = False,
idle_return: bool = False,
) -> CandidateSelectionPlan:
"""Plan candidate selection with the production cold-start session gate.

``limit`` is accepted for batch-pipeline call sites that already carry it;
candidate selection depends on maturity, session count, and account age.
``idle_return`` swaps the lr_smoothed first slot for
``IDLE_RETURN_FIRST_SLOT_ENGINE`` (explore_budget_v1 treatment).
"""
_ = limit
dormant_returner = (nsessions or 0) > 1 or cold_start_account_too_old
if cold_start_nsessions_gate_enabled and dormant_returner and nmemes_sent < 30:
return plan_candidate_selection(30)
plan = plan_candidate_selection(30)
else:
plan = plan_candidate_selection(nmemes_sent)

return plan_candidate_selection(nmemes_sent)
if idle_return and plan.fixed_pos.get(0) == "lr_smoothed":
return replace(plan, fixed_pos={0: IDLE_RETURN_FIRST_SLOT_ENGINE})
return plan


def low_sent_quota(limit: int, user_type: str | None) -> int:
def low_sent_quota(limit: int, user_type: str | None, explore_budget: bool = False) -> int:
value = getattr(user_type, "value", user_type)
if value is None or str(value) not in MODERATOR_USER_TYPES:
return 0
return ceil(limit * 0.75)
return ceil(limit * (EXPLORE_BUDGET_LOW_SENT_SHARE if explore_budget else LOW_SENT_SHARE))
35 changes: 35 additions & 0 deletions src/recommendations/blender_experiments.py
Original file line number Diff line number Diff line change
Expand Up @@ -447,3 +447,38 @@ async def get_text_light_blender_v1_weights(
# mature user gets the shipped default. Existing assignment rows stay for readouts.
async def get_mature_blend_weights_with_experiments(user_id: int) -> dict[str, float]:
return await get_recently_liked_blender_v2_weights(user_id)


# --- explore_budget_v1: labeling budget + fresh-viral + idle-return first slot ---
# See experiments/active/2026-10-30-explore-budget.md.

EXPLORE_BUDGET_V1_EXPERIMENT_ID = "explore_budget_v1"
EXPLORE_BUDGET_V1_CONTROL = "control"
EXPLORE_BUDGET_V1_TREATMENT = "treatment"
EXPLORE_BUDGET_V1_MIN_MEMES_SENT = 30 # cold start keeps its own engines


def explore_budget_v1_variant_for_user(user_id: int) -> str:
key = f"{EXPLORE_BUDGET_V1_EXPERIMENT_ID}:{user_id}"
bucket = int.from_bytes(hashlib.sha256(key.encode("utf-8")).digest()[:8], "big") % 2
return EXPLORE_BUDGET_V1_CONTROL if bucket == 0 else EXPLORE_BUDGET_V1_TREATMENT


async def is_explore_budget_v1_treatment(user_id: int, nmemes_sent: int) -> bool:
if nmemes_sent < EXPLORE_BUDGET_V1_MIN_MEMES_SENT:
return False
try:
assignment = await get_experiment_assignment(user_id, EXPLORE_BUDGET_V1_EXPERIMENT_ID)
if assignment is not None:
return assignment["variant"] == EXPLORE_BUDGET_V1_TREATMENT
variant = explore_budget_v1_variant_for_user(user_id)
await assign_experiment(
user_id,
EXPLORE_BUDGET_V1_EXPERIMENT_ID,
variant,
{"assignment_strategy": "sha256(experiment_id:user_id)%2"},
)
except Exception:
logger.warning("explore_budget_v1 assignment failed for user %d", user_id, exc_info=True)
return False
return variant == EXPLORE_BUDGET_V1_TREATMENT
Loading
Loading