Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

docs(cohorts): realtime cohorts internal docs (#106269)

Matheus Batistaae90bd52925e
diff --git a/docs/internal/realtime-cohorts/README.md b/docs/internal/realtime-cohorts/README.md
new file mode 100644
index 000000000000..c873708960d0
--- /dev/null
+++ b/docs/internal/realtime-cohorts/README.md
@@ -0,0 +1,169 @@
+# Realtime cohorts
+
+Realtime cohorts compute dynamic cohort membership continuously from the event stream, one person at a time, instead of recomputing whole cohorts on a schedule.
+Membership changes land in a Postgres table that feature flags and workflows read per person.
+
+This directory explains the whole pipeline at a level that should stay true as the code evolves.
+Each page covers one part, and links to the others where they meet.
+
+## Why a streaming pipeline
+
+The batch path recalculates a cohort by querying ClickHouse for everyone who matches.
+Its cost grows with persons times cohorts, whether or not anything changed, and a person who stops matching only leaves at the next recalculation.
+
+The streaming pipeline keeps a small piece of state per person per criterion, updates it as events arrive, and recomposes a cohort for a person only when one of that person's criteria changes its answer.
+Its cost follows the events that matter, and it can say "left because time passed" by tracking when each criterion expires.
+
+The batch path still runs for every dynamic cohort.
+Insights, person counts and person lists come from it.
+
+## The system at a glance
+
+```mermaid
+flowchart LR
+ subgraph Django
+ Save[Cohort save] --> Cohort[(posthog_cohort)]
+ Save --> Runs[(backfill runs)]
+ Final[Finalizer] --> Cohort
+ end
+ subgraph Live path
+ Ingest[Ingestion] --> Firehose[(clickhouse_events_json)]
+ Ingest --> Merges[(person_merge_events)]
+ Firehose --> Shuffler[cohort-event-shuffler]
+ Shuffler --> Stream[(cohort_stream_events)]
+ end
+ subgraph Backfill path
+ CH[(ClickHouse)] --> Seeder[cohort-seeder]
+ Runs --> Seeder
+ Seeder --> SeedTopic[(cohort_stream_seed_events)]
+ Seeder --> Runs
+ end
+ Stream --> Proc[cohort-stream-processor<br/>RocksDB state]
+ Merges --> Proc
+ SeedTopic --> Proc
+ Cohort -. definitions .-> Proc
+ Proc --> Changes[(cohort_membership_changed)]
+ Proc --> Markers[(cohort_reconcile_markers)]
+ Markers --> Seeder
+ Runs --> Final
+ Changes --> Consumer[CDP membership consumer]
+ Markers --> Consumer
+ Consumer --> Table[(cohort_membership<br/>Postgres)]
+ Table --> Flags[Feature flags service]
+ Table --> Workflows[Workflows]
+ Cohort -. readiness .-> Flags
+```
+
+| Component | Language | Role |
+| ------------------------- | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
+| Cohort API and models | Python | Compile each criterion, decide whether a cohort is realtime, create and finalize backfill runs, write readiness stamps |
+| `cohort-core` | Rust | The shared evaluation kernel: parsing, classification, state keys, eligibility, HogVM setup, time math, partitioning, the backfill wire format |
+| `cohort-event-shuffler` | Rust | Re-keys the ingestion firehose by person |
+| `cohort-stream-processor` | Rust | Keeps per-person state and emits membership changes |
+| `cohort-seeder` | Rust | Replays history from ClickHouse into the processor, and drives backfill completion |
+| CDP membership consumer | TypeScript | Writes membership changes to Postgres and sweeps stale rows |
+| Feature flags service | Rust | Reads membership for realtime cohorts during flag evaluation |
+
+## The two paths
+
+**Live evaluation.**
+Ingestion writes every event to the firehose.
+The shuffler forwards events from enabled teams to `cohort_stream_events`, keyed by person, so all of a person's events reach one partition.
+The processor gives each partition to one worker.
+The worker folds each event into the person's state for every criterion the event can affect, and when a criterion flips, it recomposes the cohorts that use it and emits `entered` or `left`.
+A sweep expires criteria whose window has passed.
+
+**Backfill.**
+When a cohort is created, or edited in a way that changes what it matches, Django creates a backfill run and pins the definition.
+It does so only for teams where automatic runs are enabled and every gate is open, and operators create the other runs.
+The seeder scans ClickHouse history for that definition and sends it to the processor as seeds, which merge into the same state the live path maintains.
+Then every partition re-emits the cohort's full membership, a step called reconcile, and reports completion.
+When all partitions have reported, Django stamps the cohort ready, and feature flags may read it from the membership table.
+
+## Three things to know first
+
+- **Live output is at most once, and the next reconcile repairs it.**
+ The live paths commit state before they produce a membership change, so a failed produce loses the change for good on that path.
+ At most once means a failed produce is never retried, not that a change never repeats: a host crash that loses unflushed writes can emit it again.
+ Every backfill ends with a reconcile that re-emits the cohort's full membership, and the downstream sweep deletes rows the reconcile did not re-assert.
+ Reconcile runs only inside a backfill, and nothing schedules one, so a change lost on a cohort nobody edits stays lost until an edit or an operator starts a run, and that run repairs it only with reconcile enabled on the processor.
+ Reconcile re-emits from the state the processor holds, so it repairs lost output, not lost state.
+ [Processor runtime](processor-runtime.md#delivery-semantics) lists each path's guarantee.
+- **The processor runs as a single pod.**
+ Its state lives in a local RocksDB store that never moves between pods, so a second replica would corrupt state without any error.
+- **Most of the pipeline is off by default.**
+ The processor writes to a shadow output topic unless configured otherwise, and seed apply, reconcile, cascades, durable restore, the seeder's completion driver and Django's finalizer each have their own switch.
+ The pages name the switch where each behavior is described.
+
+## Reading order
+
+1. [Definitions and eligibility](definitions-and-eligibility.md): the cohort filter tree, what Django compiles, condition hashes and leaf state keys, which cohorts the processor can evaluate.
+2. [Event routing](event-routing.md): the shuffler, and the partitioning rule every topic shares.
+3. [Processor runtime](processor-runtime.md): consumers, workers, lanes, offsets, and what each path guarantees about delivery.
+4. [Live evaluation](live-evaluation.md): Stage 1 and Stage 2, a traced event, and the hot-path optimizations.
+5. [Time and eviction](time-and-eviction.md): windows, deadlines and the sweep.
+6. [Merges and cascades](merges-and-cascades.md): person merges, cohorts that reference cohorts, and Stage 2 cleanup.
+7. [State store and durability](state-store-and-durability.md): the RocksDB layout, atomic writes, durability and restart.
+8. [Backfill overview](backfill-overview.md): why backfill exists, its correctness model, and one run end to end.
+9. [Backfill coordination](backfill-coordination.md): how Django decides a run is owed, pins it and supersedes it.
+10. [The seeder](seeder.md): planning, claiming, scanning and producing seeds.
+11. [Seed apply and reconcile](seed-apply-and-reconcile.md): the processor's side of backfill.
+12. [Completion and readiness](completion-and-readiness.md): how a run finishes and what its stamp unlocks.
+13. [Membership output and readers](membership-output-and-readers.md): the consumer, the Postgres table, mark-and-sweep, feature flags and workflows.
+14. [Invariants](invariants.md): the rules the whole system depends on, in one place.
+
+## Where the code lives
+
+| Area | Location |
+| ------------------------------------------ | ------------------------------------- |
+| Cohort model and save path | `products/cohorts/backend/models/` |
+| Backfill runs, pinning, finalizer, stamps | `products/cohorts/backend/backfill/` |
+| Filter validation and bytecode compilation | `posthog/api/cohort.py` |
+| Shared evaluation kernel | `rust/cohort-core/` |
+| Shuffler | `rust/cohort-event-shuffler/` |
+| Processor | `rust/cohort-stream-processor/` |
+| Seeder | `rust/cohort-seeder/` |
+| Membership consumer and sweeper | `nodejs/src/cdp/` |
+| Membership table migrations | `rust/behavioral_cohorts_migrations/` |
+| Flags read path | `rust/feature-flags/src/cohorts/` |
+
+## Examples in these pages
+
+The pages share one invented setup: team 7, cohort 42, persons p-1 and p-2, and p-1's partition 26.
+Cohort 42 is usually "3 or more `/pricing` pageviews in the last 7 days", sometimes with "email is set" added.
+Each page states the setup its example needs, and the details differ where a page needs them to.
+
+## Glossary
+
+| Term | Meaning |
+| -------------------- | ----------------------------------------------------------------------------------------------------------------- |
+| Leaf | One criterion of a cohort: a behavioral condition, a person-property condition, or a reference to another cohort |
+| Condition hash | A 16-character hash of a leaf's compiled matcher. Leaves that match the same events share it |
+| Leaf state key (LSK) | The identity of one leaf's per-person state: the condition hash plus the window and count settings |
+| Catalog | An immutable per-team index of parsed realtime cohorts, rebuilt periodically from Postgres |
+| Eligibility class | Whether and how the processor composes a cohort: single leaf, composable, composable with references, or excluded |
+| Stage 1 | Folding an event into per-person leaf state and detecting flips |
+| Stage 2 | Recomposing a cohort from its leaves when one of them flips |
+| Person record | One row per person holding which person conditions match, plus fingerprints that skip unchanged work |
+| Replay marks | Per row, the highest firehose offset applied from each firehose partition. Used to skip redelivered events |
+| Firehose | The ingestion topic `clickhouse_events_json`, which the shuffler reads |
+| Eviction deadline | The earliest time a leaf's answer can change without a new event |
+| Sweep | The periodic pass that applies eviction deadlines |
+| Tombstone | A forwarding address from a merged-away person to the survivor |
+| Cascade | Recomposing cohorts that reference a cohort whose membership flipped |
+| Tenure | The time one worker owns a partition, from assignment to the next revoke or restart |
+| Run | One backfill of one kind, for one cohort or a whole team |
+| Participation | One cohort's membership in a run, with its pinned definition and outcome |
+| Pinning | Freezing the definition a run replays |
+| Shape hash | A fingerprint of a cohort's behavioral or person leaves, used to invalidate readiness when they change |
+| Boundary (`B`) | The instant that splits a run's history: seeded before its day, live from then on |
+| Chunk | One unit of seeder work: a day and band, or a person id range |
+| `S_chunk` | The instant a chunk was claimed. The scan counts only events that arrived before it |
+| Day tile | A seed carrying the absolute count of one condition's matches for one person on one day |
+| Person seed | A seed carrying which pinned person conditions a person was evaluated against and which matched |
+| Fence | The rule that a day tile applies only after the live path has passed its `S_chunk` plus a margin |
+| Live watermark | The newest broker timestamp the live path has folded on a partition |
+| Reconcile | Re-emitting every Stage 2 row of a cohort, on every partition, after a run's seeds |
+| Marker | The message a partition produces when it finishes reconciling a cohort for a run |
+| Readiness stamp | A timestamp on the cohort saying a backfill of its current definition completed, per kind |
+| Mark-and-sweep | Deleting membership rows that a completed reconcile did not re-assert |
diff --git a/docs/internal/realtime-cohorts/backfill-coordination.md b/docs/internal/realtime-cohorts/backfill-coordination.md
new file mode 100644
index 000000000000..656dae204277
--- /dev/null
+++ b/docs/internal/realtime-cohorts/backfill-coordination.md
@@ -0,0 +1,278 @@
+# Backfill coordination in Django
+
+Django decides when a backfill is owed, freezes what it must replay, and at the end decides whether the finished run may open the cohort to feature flags.
+It never turns history into seeds, never produces to Kafka and never reconciles.
+Its one ClickHouse query is the size estimate for person runs.
+This page covers the run tables, the save path that triggers runs, pinning, supersession, the gates, and what happens when things go wrong.
+The last step, finalization and readiness stamps, is in [completion and readiness](completion-and-readiness.md).
+[Backfill overview](backfill-overview.md) explains what a run does and its lifecycle.
+
+## The tables
+
+Three Postgres tables in the cohorts product hold all backfill coordination.
+
+| Table | One row per | Main contents |
+| ----------------------------- | ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `cohort_backfill_runs` | run | Kind, scope, trigger, status, the team's timezone, the boundary, the pinned payload, operator attestations, and the seeder's completion bookkeeping |
+| `cohort_backfill_run_cohorts` | cohort in a run, called a **participation** | The cohort's pinned filters and hashes, and the per-cohort outcome: reconcile markers seen, completed, superseded, stamped |
+| `cohort_backfill_chunks` | unit of seeder work | A day and band for behavioral runs, or a person id range for person runs, plus claim, lease and progress columns |
+
+Django creates runs and participations, and writes their final outcomes: supersession, cancellation, stamps, and `completed` or `superseded`.
+The seeder writes the in-flight run columns and the participations' reconcile outcomes, and it alone writes chunks.
+
+A cohort-scoped run has one participation.
+A team-scoped run has one participation for each eligible cohort of the team, or of the subset an operator names.
+
+A run in `awaiting_boundary`, `blocked`, `seeding` or `reconciling` is **active**.
+A participation is **open** until it is superseded.
+Two partial unique indexes enforce the basic exclusivity:
+
+- at most one active cohort-scoped run per cohort and kind,
+- at most one active team-scoped run per team and kind.
+
+A cohort can sit in a team-scoped run and a cohort-scoped run of the same kind at once.
+So the creators also check, under a row lock on the cohort, that the cohort has no open participation of that kind in any active run.
+The readiness stamp must come from exactly one backfill of the current definition.
+
+## When a run is owed
+
+A run is owed when the cohort's current definition has state or downstream rows that no backfill has built yet.
+
+| Trigger | Created by | Scope |
+| ------------------- | -------------------------------------------------------------------------------- | ------ |
+| `cohort_created` | Saving a new realtime cohort | Cohort |
+| `cohort_edited` | An edit that invalidates a kind, see below | Cohort |
+| `team_enablement` | An operator command, to backfill every eligible cohort of a team, or chosen ones | Team |
+| `disaster_recovery` | An operator command after a store loss | Team |
+
+A disaster-recovery run needs the operator to pass the boundary where live coverage restarted.
+The command does not require it, and without it the run waits in `awaiting_boundary` forever while holding the team's slot.
+Nothing checks that the boundary is in the past.
+
+### Which edits invalidate which kind
+
+Each kind of run is tied to one shape hash on the cohort row.
+[Definitions and eligibility](definitions-and-eligibility.md#shape-hashes) describes them.
+
+- The **behavioral** kind is invalidated when the behavioral shape hash moves: a behavioral leaf was added, removed, or changed its matcher, window, operator or threshold.
+- The **person** kind is invalidated when the person shape hash moves: a person condition was added, removed or changed.
+
+Composition edits move neither hash.
+Switching AND and OR, flipping a leaf's negation, or adding a cohort reference keeps every leaf.
+But the live path recomposes a person only when one of their leaves flips, so persons whose leaf answers stay the same keep the old composition.
+A run is still owed.
+
+So on every save that moves the whole-definition fingerprint, Django adds repair runs to whatever the kind hashes already invalidated:
+
+- **Behavioral**, when the cohort has a behavioral leaf and neither kind's own hash moved.
+ Behavioral leaf state survives a composition change, so the run only has to reconcile again.
+ Clearing the events stamp is also what takes the cohort out of flag routing until the run completes.
+- **Person**, when the cohort has a person leaf and no `person_metadata` leaf, the person hash did not move, and either the **person view** of the tree moved, or no behavioral run re-walks the tree.
+
+The person view is the tree with its person leaves and their negation kept, and every other leaf replaced by one anonymous placeholder.
+Depending on a seeder setting, person runs may emit seeds only for persons whose person-leaf values can change some cohort's answer, and that pruning is computed against the pinned tree.
+When the tree around the person leaves changes, the earlier pruning no longer holds, so the person seeds must be recomputed.
+
+Two examples:
+
+- `AND[person P, in cohort C]`, with the reference's negation flipped: the person view does not move, but no behavioral run exists to re-walk the tree, so a person run is owed.
+- `AND[behavioral B over 7 days, person P]` edited to `OR[B over 14 days, P]`: the behavioral hash moves, and the person view moves too, so both kinds are owed.
+
+## The save path
+
+Everything starts inside `Cohort.save()` and its `post_save` receivers.
+
+```mermaid
+sequenceDiagram
+ participant API as Cohort API
+ participant Save as Cohort.save()
+ participant DB as Postgres
+ participant Recv as post_save receivers
+ participant Redis
+ participant Task as Celery task (5 min later)
+ API->>Save: validated filters, cohort_type
+ Save->>Save: compute hashes,<br/>decide invalidated kinds
+ Save->>DB: UPDATE filters, hashes,<br/>clear invalidated stamps
+ Save->>Recv: post_save
+ Recv->>DB: on commit: supersede active runs<br/>of invalidated kinds
+ opt team trigger-allowlisted, cohort created or kind invalidated
+ Recv->>Redis: on commit: SET pending key NX EX 300
+ Recv->>Task: apply_async(countdown=300)
+ end
+ Task->>DB: lock cohort, re-check, pin definition,<br/>insert run + participation
+```
+
+1. **Hashes and stamps.**
+ For a realtime, non-static, non-deleted cohort on a realtime-allowlisted team, on a save that includes `filters`, `save()` computes the new fingerprints and compares them with the stored ones.
+ For each invalidated kind, it clears that kind's readiness stamp, and the legacy `last_realtime_cohort_calculation_at`, in the same `UPDATE` that stores the new definition.
+ While the cohort stays realtime and this maintenance succeeds, no committed state pairs a new definition with a stamp of a kind the edit invalidated.
+ A stamp of a kind the edit did not invalidate stays, because it still vouches for that kind's unchanged leaves.
+ Maintenance is best effort: an error is logged and the save goes ahead.
+2. **Supersede, on commit.**
+ Active cohort-scoped runs of an invalidated kind move to `superseded`.
+ In a team-scoped run, only this cohort's participation is superseded, and the team run carries on for the other cohorts.
+3. **Debounce, on commit.**
+ For a team in both the realtime and the trigger allowlists, when the save created the cohort or invalidated a kind, and the cohort has leaves of that kind to backfill, Django sets a Redis key per cohort and kind with `SET NX` and a 5-minute expiry, and schedules a Celery task 5 minutes out.
+ If the key already exists, a task is already pending, and this save adds nothing.
+ Saves within five minutes of the first one produce one run, pinned to the definition current when the task fires.
+4. **Create, 5 minutes later.**
+ The task re-checks the trigger allowlist and the [attestations](#gates), then calls the run creator.
+ The creator locks the cohort row, re-checks eligibility and exclusivity, pins the current definition, and inserts the run in `awaiting_boundary` with its participation.
+ A person creator first estimates the run's size against ClickHouse without holding the lock, and under the lock refuses if the person conditions changed in the meantime.
+
+From there the seeder takes over.
+[The seeder](seeder.md) describes the rest.
+
+## Pinning
+
+A run's seeds replay a frozen definition and never switch to the live one.
+Reconcile is different.
+The processor walks the cohort with its own current catalog and checks only the shape hash of the run's kind, as [seed apply and reconcile](seed-apply-and-reconcile.md#the-walk) explains.
+
+The creator pins:
+
+- on each participation: the cohort's full `filters` JSON, its definition hash, and the shape hash of the run's kind,
+- on a behavioral run: every behavioral condition to replay, with its condition hash, window fields, operator, threshold, window in days and event name, plus the union of event names to scan,
+- on a person run: every person condition hash to evaluate, and a **horizon**: only persons whose record changed within the last N days are scanned.
+
+The seeder builds its catalog from these pinned filters with the same `cohort-core` code the processor uses.
+The finalizer later compares the pinned hash, and the pinned filters, with the cohort's current ones.
+
+An edit that invalidates the run's kind supersedes it.
+A cohort-scoped run then stops at the seeder's next lease renewal.
+In a team-scoped run, the seeder drops the edited cohort's conditions and carries on for the rest.
+
+Supersession lives in Postgres, and the processor and the membership consumer never read it.
+Reconcile requests already on the seed topic still run unless the edit moved the shape hash of their kind, and they still produce markers.
+The seeder ignores a marker for a superseded participation, so it can never complete or stamp it.
+The membership consumer does count those markers toward its sweep, see [membership output and readers](membership-output-and-readers.md#mark-and-sweep).
+
+## Gates
+
+Several independent gates decide whether anything happens.
+Missing one of them fails quietly, so they are worth knowing.
+
+| Gate | Effect |
+| ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `REALTIME_COHORT_TEAM_ALLOWLIST` | Teams whose cohorts get hash maintenance, stamp invalidation, supersession and any run at all. Unset means no teams in Django, but the shuffler, processor and seeder default to team 2, so set it explicitly on every service. Set but empty means **all** teams. Must match the value the Rust services use |
+| `COHORT_BACKFILL_TRIGGER_TEAM_ALLOWLIST` | Teams whose saves create runs automatically. Unset or empty means **no** teams |
+| Operator attestations | Settings an operator sets to declare that prerequisites hold. They are declarations, not live checks. Behavioral runs need `BEHAVIORAL_BACKFILL_MERGE_GATE_ATTESTED` and `BEHAVIORAL_BACKFILL_DURABILITY_ATTESTED`. Person runs also need the person TTL and sizing attestations and a positive seed-bytes budget |
+| Person sizing budget | A cohort-scoped person run is refused when the team's active person-run estimates plus its own would exceed the budget. The check reads the active estimates before the run exists and reserves nothing, so two cohorts sized at the same time can together exceed the budget. A team run checks only its own estimate. Hitting the size estimate's scan cap, or the cap on pinned conditions, also refuses |
+
+The Rust services have their own switches, and Django cannot see them.
+Two of them gate person runs, and they must open in order.
+The processor's `COHORT_SEED_PERSON_APPLY_ENABLED` must be on everywhere before the seeder's `SEEDER_PERSON_SEEDS_ENABLED`, or the processor skips and commits the seeds.
+The seeder's switch must be on before a team with person-leaf cohorts joins the trigger allowlist.
+Until it is, the seeder never discovers person runs, so each one waits in `awaiting_boundary`, holding its cohort's run slot.
+[Completion and readiness](completion-and-readiness.md#gates) lists the switches that completion needs.
+
+The difference between the two allowlists matters.
+On a team that is realtime-allowlisted but not trigger-allowlisted, an edit clears the readiness stamp and supersedes the run, but nothing creates a replacement.
+The cohort stays unavailable to flags until an operator runs a team backfill.
+
+A run created while an attestation is missing is recorded as `blocked`, and nothing ever moves a run out of `blocked` except an edit, for a cohort-scoped run, or cancellation.
+So the save path and the operator command both refuse when an attestation is missing, instead of creating one.
+Only a direct call to a creator function, for example from a shell, writes a `blocked` run.
+
+## Operator tools
+
+Two management commands cover operator work.
+
+- `create_cohort_backfill_run` creates team-scoped runs, behavioral or person, including disaster-recovery runs with a pinned boundary.
+ It can narrow the run to chosen cohorts, which is how an operator re-drives one cohort whose trigger was lost.
+ It refuses when an attestation is missing or when a target cohort already has an open participation, and it supports a dry run.
+- `manage_cohort_backfill_runs inventory` lists and classifies active runs.
+ `manage_cohort_backfill_runs terminalize` cancels chosen runs.
+ It is a dry run unless told otherwise, and it never cancels a run that already stamped.
+
+## When things go wrong
+
+Run creation is at most once per save.
+The task retries exceptions a few times, but nothing re-drives:
+
+- a lost enqueue, because Redis or the Celery broker was down at save time,
+- a skipped attestation,
+- a refusal: a run slot occupied, a budget or cap exceeded, or an ineligible cohort.
+
+Each case is counted, and the save itself always succeeds.
+There is no periodic sweep that finds eligible cohorts without a stamp and without a run.
+A cohort created before its team was trigger-allowlisted also gets no run on its own.
+
+Other cases to know:
+
+- **A run never ends.**
+ A run stuck in `awaiting_boundary`, `seeding` or `reconciling` holds its slot, and its unfinished cohorts stay unstamped.
+ Examples: a disaster-recovery run without a boundary, a person run while the seeder's person switch is off, a run whose cohort has no condition the seeder can replay, or a run parked in `reconciling` by a shortfall or a disabled finalizer.
+ Nothing times these out.
+ An edit clears a cohort-scoped one.
+ A run held by a retryable shortfall needs reconcile dispatched again, after which the finalizer can finish it.
+ `terminalize` cancels other stuck team-scoped runs, but it refuses any run with a stamped participation.
+ A team run held by one short cohort can already have stamped its other cohorts, because the finalizer stamps each complete participation before it holds the run.
+- **Supersession fails.**
+ A failed supersession is only logged.
+ The replacement task then finds the stale run's participation still open and refuses, and the stale run later fails its stamp check, so the cohort ends up with neither run nor stamp.
+- **An edit races the finalizer.**
+ The cohort row lock serializes them.
+ If an edit that invalidates the run's kind commits first, the stamp's hash or composition check fails and the run is superseded.
+ If the stamp commits first, the edit clears it.
+ Either way no stamp of an invalidated kind survives over the new definition.
+ An edit that invalidates only the other kind leaves this run and its stamp valid.
+- **An edit is reverted.**
+ Editing A to B and back to A restores the old hashes, but the participation superseded during B can never stamp.
+ The state it seeded went stale while B was live.
+ The revert's own save schedules a fresh run.
+- **A cohort leaves the realtime set mid-run.**
+ A soft delete, a switch to static, or losing realtime support skips hash maintenance, so Django does not supersede the run, and the finalizer does not re-check `deleted` or `cohort_type`.
+ At its next catalog refresh the processor drops a cohort that is deleted or no longer `realtime`, and then discards the cohort's reconcile requests without markers.
+ So the run stamps only if every marker landed first.
+ Otherwise a soft delete ends with the seeder superseding the participation, and losing realtime support leaves a retryable shortfall that holds the run in `reconciling`.
+- **A cohort re-enters the realtime set without a leaf change.**
+ An undelete, a static-to-dynamic switch, or regained realtime support leaves the hashes as they were, so no run is owed, and the cohort keeps whatever stamps it had.
+- **A save from a stale copy of the row.**
+ The API saves the whole row, so a rename that read the cohort before the finalizer stamped can write the empty stamp back.
+ The cohort loses readiness until the next invalidating edit or an operator run.
+- **A seeder-side failure.**
+ A run the seeder fails keeps its stamp empty and frees its slot.
+ Nothing re-creates it.
+
+## Worked example
+
+Team 7 is in both allowlists and every attestation is set.
+Cohort 42 has one behavioral leaf, "performed `$pageview` in the last 30 days", and a stamped, completed earlier run.
+No active feature flag uses cohort 42, since the API would refuse the edit otherwise.
+
+**10:00, the user changes the window to 7 days.**
+
+1. `save()` sees the behavioral shape hash move, because the window is part of the leaf's identity.
+ The condition hash does not change, because the matcher is the same.
+2. The same `UPDATE` stores the new filters and hashes and clears `last_backfill_events_at`.
+ Cohort 42 stops being flag-compatible, so the flag editor refuses it until a new run stamps.
+3. On commit, supersession finds no active run.
+ Redis `SET NX` succeeds and a task is scheduled for 10:05.
+4. At 10:05 the task creates run R1 pinned to the 7-day window.
+
+**Variant: a second edit at 10:03**, from 7 days to 14.
+The hashes move again and the stamp stays cleared.
+The Redis key from 10:00 still exists, so no second task is scheduled.
+The 10:05 task pins the 14-day definition.
+One run.
+
+**Variant: a second edit at 10:12, while R1 is seeding.**
+On commit, R1 is superseded.
+The 10:00 key expired at 10:05, so a new task is scheduled for 10:17.
+The seeder notices at its next lease renewal that R1 is no longer `seeding` and stops its chunks.
+Tiles R1 already produced still apply harmlessly.
+Tiles are keyed by condition hash, which the window edit did not change, so they max-merge into the 14-day leaf.
+They hold absolute counts for days that R2 re-seeds anyway.
+A tile whose condition hash no longer maps to any leaf would be dropped.
+At 10:17 the task creates R2 for the 14-day window, and R2 seeds all 14 days.
+
+## Things that surprise people
+
+- A save that does not change the definition, such as a rename, triggers nothing.
+- Readiness stamps are written with a queryset update that bypasses model signals, so the finalizer invalidates the flags cache explicitly after it stamps.
+- A `PATCH` that leaves any behavioral leaf in a cohort used by an active feature flag, directly or through a nested cohort, is refused.
+ That covers every filter edit of a behavioral or mixed cohort, not only behavioral edits, and it keeps a live flag out of the window where the stamp is cleared.
+ Only `PATCH` is checked.
+- Copying a cohort to another project drops its stamps.
+ The copy gets a run on its own only if the target team is trigger-allowlisted.
diff --git a/docs/internal/realtime-cohorts/backfill-overview.md b/docs/internal/realtime-cohorts/backfill-overview.md
new file mode 100644
index 000000000000..6fbbaeb6466a
--- /dev/null
+++ b/docs/internal/realtime-cohorts/backfill-overview.md
@@ -0,0 +1,303 @@
+# Backfill overview
+
+Live evaluation only knows about events it has seen.
+Backfill fills in everything else: it replays history from ClickHouse into the processor's state, and then re-tells downstream the full membership of the cohort.
+This page explains why backfill exists, the correctness model that lets it run alongside live traffic, the run lifecycle, and one run end to end.
+
+It assumes [definitions and eligibility](definitions-and-eligibility.md), for condition hashes, leaf state keys, shape hashes and the catalog, and [live evaluation](live-evaluation.md), for leaf state and Stage 2 rows.
+The details of each part of backfill are in:
+
+- [backfill coordination](backfill-coordination.md), for how Django creates and pins runs,
+- [the seeder](seeder.md), for scanning ClickHouse and producing seeds,
+- [seed apply and reconcile](seed-apply-and-reconcile.md), for what the processor does with them,
+- [completion and readiness](completion-and-readiness.md), for how a run finishes and what it unlocks.
+
+## Why live evaluation is not enough
+
+- **A new leaf usually starts empty.**
+ A new cohort, or an edit that changes a leaf's matcher, window, operator or threshold, gets a new leaf state key with no history, unless another cohort of the team already has the identical leaf.
+ "3 or more pageviews in the last 7 days" needs the last 7 days of pageviews, and the processor has none.
+- **Persons are recomposed only when a leaf flips.**
+ The live path recomposes a person's cohort only when one of that person's leaves changes its answer, on an event or at the sweep.
+ After a composition edit, or a person condition removed from the catalog, persons whose leaf answers do not change keep their old membership forever.
+- **Live output is at most once.**
+ A membership change lost to a failed produce is never retried on the live path.
+- **Stores get lost.**
+ A schema change, a wiped volume or a cold start leaves the processor with no history at all.
+
+Backfill answers all four.
+It **seeds** leaf state from history, and it **reconciles**: for each cohort, every partition re-emits the current membership of every person it holds a Stage 2 row for, so the downstream table can be corrected and stale rows removed.
+
+## The moving parts
+
+```mermaid
+flowchart LR
+ Save[Cohort save<br/>or operator] --> Run[(Run row<br/>Postgres)]
+ Run --> Seeder[cohort-seeder]
+ CH[(ClickHouse<br/>events, persons)] --> Seeder
+ Seeder -->|seeds| Seeds[(cohort_stream_seed_events)]
+ Seeder -->|reconcile requests| Seeds
+ Seeds --> Proc[cohort-stream-processor<br/>seed lane]
+ Proc -->|origin seed / reconcile| Out[(membership output)]
+ Proc -->|reconcile_complete| Markers[(cohort_reconcile_markers)]
+ Markers --> Seeder
+ Seeder -->|outcomes, observed| Run
+ Run --> Final[Django finalizer]
+ Final -->|readiness stamp| Cohort[(posthog_cohort)]
+```
+
+1. Django creates a **run** row and **pins** the definition it must replay.
+2. The **seeder** picks up the run, sets its boundary and plans chunks of work.
+ Its workers claim the chunks, scan ClickHouse, evaluate each row with the same HogVM code the processor uses, and produce **seeds** to `cohort_stream_seed_events`, keyed like the event stream so each seed reaches the worker that owns the person.
+ A chunk is **confirmed** once Kafka has acknowledged all its seeds.
+3. The **processor** folds each seed into the same leaf state the live path writes, recomposes cohorts, and emits changes tagged `origin: seed`.
+4. When every chunk is confirmed, the seeder sends a **reconcile request** for each cohort to every partition, on the same seed topic.
+ On each partition the request waits behind that partition's earlier seeds.
+ Each partition then re-emits the cohort's membership, tagged `origin: reconcile`, and produces a **completion marker**.
+5. The seeder collects markers.
+ When every cohort of the run has either all 64 markers or a settled shortfall, it records each cohort's outcome and marks the run **observed**.
+6. Django's **finalizer** closes the run and writes the cohort's **readiness stamp** for that kind.
+ For a cohort with behavioral leaves, that stamp is what lets feature flags read its membership from the membership table.
+
+## Two kinds of run
+
+| Kind | Replays | Seed message | Applied to |
+| ----------------- | ------- | ------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------- |
+| `behavioral` | Events | A **day tile**: the absolute count of matching events for one person, one condition hash and one team-timezone day | Every behavioral leaf that shares the condition hash |
+| `person_property` | Persons | A **person seed**: for one person, which pinned person conditions were evaluated and which matched | The person record |
+
+A cohort that mixes behavioral and person leaves can need both kinds.
+Each kind has its own run, its own readiness stamp and its own shape hash.
+An edit invalidates a kind when that kind's shape hash moves, or when the edit owes that kind a repair run even though its hash did not move.
+A composition change owes one, and so does an edit that changes a behavioral leaf together with the tree around a person leaf, which owes a person run as well as the behavioral one.
+
+A run is either **cohort-scoped**, for one cohort, or **team-scoped**, covering every eligible cohort of a team at once.
+Save-triggered runs are cohort-scoped.
+Operators create team-scoped runs to enable a team, and disaster-recovery runs after a store loss.
+
+## The correctness model
+
+Backfill writes into the same state that live events are updating at the same moment.
+Rules 1 to 3 below cover behavioral runs, and rule 4 covers person runs.
+Together they let the two writers agree without coordination.
+
+### Rule 1: split days at a boundary
+
+When the seeder first picks up a run, it sets the run's **boundary** `B` to the current time.
+Seeding covers whole team-timezone days strictly before the day of `B`.
+The live path owns the day of `B` onward, starting from the moment the processor loaded the leaf.
+
+```text
+ day(B)
+ ... | d-3 | d-2 | d-1 | d | d+1 ...
+ <---- seeded by the run --->|<------ live path ------>
+ ^ B, somewhere inside day d
+```
+
+The boundary day itself is never seeded.
+On that day the live counter holds the events the live path saw, and a seed would hold events that arrived before it was scanned.
+Two partial counts of one day cannot be combined correctly by either `max` or `+`, so the day is left to live.
+
+The split holds in one direction only.
+Seeds never cover the boundary day or later days, but the live path counts every event it receives inside a leaf's window.
+So a seeded day can already hold live counts: events live folded after it loaded the leaf, and late events for old days.
+Rules 2 and 3 make that overlap safe.
+Events on day `d` that the processor received before it loaded the leaf are in neither domain.
+That gap is accepted.
+It affects every behavioral leaf: a matching event in the gap is missing from the person's state until its day leaves the window.
+
+For a disaster-recovery run the operator must pin `B`, at the point where live coverage restarted after the store loss.
+Without it the run waits in `awaiting_boundary`.
+
+### Rule 2: tiles are absolute counts, merged with max
+
+A day tile says "person p-1 matched condition H **4 times** on 2026-03-05".
+It is not "add 4".
+For a count leaf, the processor merges it into that day's bucket with `bucket = max(bucket, tile)`.
+For a `performed_event` leaf, a tile simply records that the person matched on that day.
+
+`max` is what makes backfill safe to repeat.
+Applying a tile twice, applying two tiles in either order, or applying a tile from a retried chunk all give the same result.
+The seeder's produce is at least once, and the processor's apply can be replayed after a crash, so this matters constantly.
+
+`max` is also correct next to live counts, as long as every event live counted for that day is also in the tile.
+Rule 3 provides that for events that reached ClickHouse before the scan.
+Later arrivals are the residue described there.
+
+### Rule 3: the arrival bound and the apply fence
+
+Each claim of a chunk stamps an instant, `S_chunk`, and a retried chunk gets a new one.
+The seeder's ClickHouse query counts only events that **arrived** in ClickHouse before `S_chunk`, whatever their event time.
+So a tile is fixed by the pinned definition, the day and band, and `S_chunk`.
+
+The processor holds each tile until its partition's **live watermark** has passed `S_chunk` plus a margin.
+The live watermark is the newest broker timestamp the live path has folded on that partition, or the current time when the partition has folded everything available.
+By then, provided the live topic trails ClickHouse by less than the margin, every event the tile counted has also reached the live path.
+So every event in the tile that live will ever count is already counted, and `max` cannot count it twice.
+
+Without the fence, a tile could apply while an event it already counted is still waiting in the live topic.
+When that event arrived, live would add 1 on top of the tile and double count it.
+A shuffler stall longer than the margin can still cause that.
+
+One residue remains.
+A late event that reaches ClickHouse after `S_chunk` is not in the tile.
+If live folds it before the tile applies, `max` takes the larger of two disjoint counts instead of their sum, so the day is under-counted.
+If live folds it after the tile applies, live adds it on top of the tile, which is correct.
+That is bounded to late arrivals on old days.
+It can drop a person out of a `gte` or `gt` cohort, and wrongly keep one in an `lt`, `lte`, `eq` or negated one.
+
+### Rule 4: person seeds are judged by time, with a margin
+
+A person seed lists every pinned person condition the seeder evaluated and the subset that matched.
+A condition that was evaluated and did not match retracts a stored match.
+
+The seed was computed from the person's properties as ClickHouse had them when the chunk was scanned.
+Live person evaluation may have seen newer properties since.
+So the processor applies a person seed only when:
+
+- the person has no usable record, or
+- the scan instant is later than the record's stamp, the event time of the newest change live applied, by more than a margin, or
+- the record was evaluated live against a different set of person conditions, and the scan is not older than its stamp.
+
+Otherwise the live answer stands.
+Applying a seed never touches the replay marks of the live path.
+
+The check compares two clocks, not property versions: the seeder's scan instant and the client's event time.
+The margin, `COHORT_SEED_PERSON_LIVE_MARGIN_MS`, 15 minutes by default, covers ClickHouse replication lag and client clock skew.
+A property change that reaches ClickHouse later than the margin, or a client clock skewed by more than it, lets a scan with older properties overwrite the live answer.
+Person seeds have no apply fence to catch that.
+
+This is not last-write-wins between seeds.
+A seed that changes nothing writes nothing, so it leaves no stamp for a later seed to compare against.
+When two runs share a person condition, the newer scan can arrive first, change nothing, and leave an older scan free to apply after it.
+Each seed is safe to apply twice, but seeds from different runs are not ordered by scan time.
+
+### Reconcile: tell everyone again
+
+Seeding fixes state.
+Reconcile fixes what downstream was told.
+
+After every chunk of a run is confirmed, the seeder sends one reconcile request per cohort to each of the 64 partitions.
+Each request waits behind that partition's earlier tiles, so it cannot overtake a tile that admission still holds.
+That is not proof that every earlier seed applied.
+A seed run that fails before its Stage 1 commit is held for the next tenure to replay, while the request behind it still runs.
+A tile re-keyed to a merge survivor on another partition joins the back of that partition.
+[Invariant 23](invariants.md#backfill) names both.
+The processor then walks every Stage 2 row of the cohort on the partition, recomputes it from stored leaf state, and emits it, `entered` or `left`, whether or not it changed.
+Rows whose stored bit was wrong are corrected.
+When the walk is done, the partition produces a completion marker for the cohort and the run.
+
+Reconcile works only from the state the store holds.
+It cannot bring back an event that live failed to fold, and it cannot find a person whose first Stage 2 row for the cohort was never written.
+[Seed apply and reconcile](seed-apply-and-reconcile.md#the-walk) says what repairs those.
+
+Reconcile emits every row, not only changes, because live output is at most once.
+Comparing state to state cannot find an emission that was lost on the wire.
+Downstream, the membership consumer also uses the full snapshot to find and delete rows that no reconcile asserted.
+[Membership output and readers](membership-output-and-readers.md) explains that sweep.
+
+A reconcile request carries the pinned shape hash of the run's kind.
+A processor whose catalog holds a different hash for that kind discards the request without a marker.
+That hash is the processor's only check on the definition.
+The walk composes the cohort's current tree, so an edit that leaves this kind's hash alone does not stop it.
+The final guard against stamping a stale definition is Django's: supersession on edit, and the finalizer's hash and composition checks.
+
+When a cohort's markers come up short, the seeder settles it anyway.
+If the shape hash of the run's kind moved or cannot be read, or the cohort was deleted, its participation is superseded.
+Otherwise it is a retryable shortfall, and the run waits in `reconciling` until an operator dispatches reconcile again.
+An edit that owes this kind a repair run never gets that far, because Django supersedes the participation when the edit commits.
+[Completion and readiness](completion-and-readiness.md#deciding-the-outcome) explains this.
+
+## Run lifecycle
+
+```mermaid
+stateDiagram-v2
+ [*] --> awaiting_boundary: Django creates run
+ [*] --> blocked: attestation missing
+ awaiting_boundary --> seeding: seeder sets B
+ seeding --> reconciling: seeder, chunks confirmed
+ reconciling --> seeding: seeder, chunks reappeared
+ reconciling --> completed: finalizer, at least one stamp
+ reconciling --> superseded: finalizer, no stamp
+ awaiting_boundary --> failed: seeder
+ seeding --> failed: seeder
+ awaiting_boundary --> superseded: edit
+ seeding --> superseded: edit
+ reconciling --> superseded: edit
+ awaiting_boundary --> cancelled: operator
+ seeding --> cancelled: operator
+ reconciling --> cancelled: operator
+ blocked --> superseded: edit
+ blocked --> cancelled: operator
+```
+
+- Django owns creation, supersession, cancellation and the final `completed` or `superseded`.
+- The seeder owns the boundary, `seeding`, `reconciling`, `failed`, and the observation that the finalizer waits for.
+- At most one active cohort-scoped run may exist per cohort and kind, and one active team-scoped run per team and kind.
+ On top of that, the creators refuse a cohort that already has an open participation of that kind in any active run.
+- An edit that invalidates a run's kind supersedes a cohort-scoped run of that kind.
+ In a team-scoped run, only the edited cohort's participation is superseded, and the run continues for the others.
+ An edit that invalidates no kind, such as a rename, leaves active runs alone.
+
+## One run, end to end
+
+Team 7 uses UTC.
+At 10:00:00 on 2026-03-10 a user creates cohort 42: "3 or more `/pricing` pageviews in the last 7 days".
+Person p-1, who hashes to partition 26, made 4 matching pageviews on 2026-03-05.
+Every backfill gate is on, and the default timings apply: a 5-minute save debounce, a 10-minute fence margin, and a finalizer every 2 minutes.
+
+1. **10:00:00, save.**
+ Django compiles the cohort, marks it `realtime`, stores its shape hashes, and schedules a backfill task 5 minutes out.
+ Within a few minutes the processor loads the new definition, and live `/pricing` pageviews start counting into the new leaf.
+2. **10:05:00, run created.**
+ The task pins cohort 42's definition into run R, status `awaiting_boundary`.
+3. **10:05:10, boundary.**
+ The seeder picks up R and sets `B` to 10:05:10.
+ It plans one chunk per day from 2026-03-03 through 2026-03-09.
+4. **10:05:25, scan.**
+ Workers claim chunks oldest day first.
+ The 2026-03-05 chunk is claimed at 10:05:25, so its `S_chunk` is 10:05:25.
+ ClickHouse returns p-1's 4 pageviews, all of which arrived long ago.
+ The seeder produces a tile: p-1, condition H, 2026-03-05, count 4.
+ Kafka acknowledges it, and the chunk is confirmed.
+5. **10:05:45, reconcile dispatch.**
+ All seven chunks are confirmed, so on its next tick the seeder moves R to `reconciling` and sends a reconcile request for cohort 42 to all 64 partitions.
+6. **10:05:50, most partitions reconcile.**
+ The 63 partitions with no held tile walk their Stage 2 rows for cohort 42 within seconds, re-emit them with `origin: reconcile`, and produce markers.
+7. **10:15:30, apply on partition 26.**
+ On partition 26 the tile has been waiting for the live watermark to pass 10:15:25, and the reconcile request waits behind it.
+ The fence opens.
+ The processor slides the leaf's window to today, merges `max(0, 4) = 4` into the 2026-03-05 bucket, and the leaf flips to true.
+ It emits `entered` for cohort 42 and p-1, with `origin: seed`.
+8. **10:15:35, reconcile on partition 26.**
+ The request runs, re-emits p-1's row as `entered`, and produces the 64th marker.
+9. **10:15:45, observed.**
+ The seeder's marker watcher has all 64 markers for cohort 42, so the next tick marks the participation complete and the run observed.
+10. **10:16:00, stamp.**
+ The finalizer checks that cohort 42's behavioral shape hash still equals the pinned one, stamps `last_backfill_events_at`, moves R to `completed`, and triggers a rebuild of the flags cache.
+ Feature flags can now read cohort 42 from the membership table.
+
+The fence dominates a small run.
+In this example, save to readiness takes about 16 minutes, and up to about 18 depending on the finalizer's schedule.
+A backlog, a failure or a slow catalog refresh makes it longer.
+
+## What backfill does not fix
+
+- The part of the boundary day the processor received before it loaded the leaf.
+- History older than the seeder's lookback cap.
+ Longer windows are truncated and the run records a warning.
+- History for `performed_event` leaves with an hour or minute window.
+ Only live events fill them.
+- Leaves the pipeline cannot represent at all, such as count windows under a day.
+- Events for a seeded day that reach ClickHouse after the chunk's scan and that live folds before the tile applies, the under-count of Rule 3.
+- A person condition's stale match for a person the person run pruned or did not scan.
+ Person runs scan only persons updated within a horizon.
+- State left under a merged-away person after a lost merge event.
+
+## Things that surprise people
+
+- A chunk is confirmed when Kafka acknowledges its seeds, not when the processor applies them.
+ So reconcile is dispatched long before most seeds apply, and the ordering on each partition is what keeps a reconcile behind its run's held seeds.
+- Reconcile requests are not fenced.
+ A request that reaches a partition before the processor has loaded the cohort's current definition is discarded without a marker, and the run ends with a retryable shortfall.
+- Every chunk of every run is claimed oldest day first, so a small new cohort's recent days wait behind a large team run's older days.
diff --git a/docs/internal/realtime-cohorts/completion-and-readiness.md b/docs/internal/realtime-cohorts/completion-and-readiness.md
new file mode 100644
index 000000000000..18d4a0f7389d
--- /dev/null
+++ b/docs/internal/realtime-cohorts/completion-and-readiness.md
@@ -0,0 +1,275 @@
+# Completion and readiness
+
+A backfill run is only useful if something can tell, safely, that it finished and that its result still matches the cohort's definition.
+This page covers the completion protocol between the seeder, the processor and Django, the readiness stamps it produces, and what a stamp does and does not unlock.
+
+It uses terms from [backfill overview](backfill-overview.md) and [backfill coordination](backfill-coordination.md): a run pins a cohort's definition into a **participation**, one per cohort, and each kind of run is tied to one **shape hash**, a fingerprint of the cohort's leaves of that kind.
+
+## The question completion answers
+
+"Every chunk was produced" is not enough to call a run done.
+The processor may still be holding tiles behind the fence, and reconcile may not have re-told downstream yet.
+A run is complete for a cohort only when **every one of the 64 processor partitions** has finished reconciling that cohort for this run.
+Each partition proves it by producing a `reconcile_complete` marker.
+
+Completion is split three ways:
+
+- the **seeder** dispatches reconcile, watches markers, and records each cohort's outcome in Postgres,
+- the **processor** walks each cohort and produces the markers,
+- **Django's finalizer** reads only Postgres, closes the run, and writes the readiness stamp.
+
+```mermaid
+sequenceDiagram
+ participant S as Seeder
+ participant PG as Postgres (run rows)
+ participant K as Seed topic
+ participant P as Processor (64 partitions)
+ participant M as Marker topic
+ participant F as Django finalizer
+ S->>PG: seeding → reconciling (planning proof, all chunks confirmed)
+ S->>M: record the marker topic's start positions
+ S->>K: one reconcile request per cohort per partition
+ S->>PG: record request offsets and dispatch epoch
+ P->>M: reconcile_complete (cohort, run, partition)
+ S->>M: watcher folds markers into per-cohort bitmaps
+ opt a cohort is short
+ S->>K: read the processor's committed seed offsets
+ S->>M: capture the marker topic's ends, read up to them
+ end
+ S->>PG: participation complete / retryable / superseded
+ S->>PG: reconcile_observed_at (last write)
+ F->>PG: stamp readiness, run → completed
+```
+
+## Gates
+
+Every stage of completion is off by default, except the finalizer's run allowlist, which admits every run.
+
+| Setting | Stage |
+| ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `COHORT_SEED_CONSUMER_ENABLED` | The processor consumes the seed topic. Without it, no request is ever committed, so the liveness proof below never passes and runs stay in `reconciling` |
+| `COHORT_SEED_RECONCILE_ENABLED` | The processor walks reconcile requests and produces markers. Without it, requests are skipped and committed, and every cohort ends as a retryable shortfall |
+| `COHORT_SEED_PERSON_APPLY_ENABLED` | The processor applies person seeds. Without it, person seeds are skipped and committed while reconcile still produces every marker, so a person run can complete and be stamped ready over state the seeds never wrote. Turn it on everywhere before any person run is dispatched |
+| `SEEDER_RECONCILE_AUTO_DISPATCH_ENABLED` | The seeder dispatches reconcile on its own. It also requires `SEEDER_CONFIRM_REGISTER_BACKFILLED`. Without it, an operator dispatches with the `reconcile_dispatch` tool |
+| `SEEDER_RECONCILE_OBSERVER_ENABLED` | The seeder watches markers and records outcomes, for runs dispatched either way |
+| `SEEDER_PERSON_RECONCILE_DISPATCH_ENABLED` | Completion also covers person runs |
+| `BEHAVIORAL_BACKFILL_FINALIZER_ENABLED` | Django finalizes observed runs and writes stamps |
+| `BEHAVIORAL_BACKFILL_FINALIZER_RUN_ALLOWLIST` | Which observed runs the finalizer may close. The default, `all`, admits every run |
+| `BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED` | Whether person runs are finalized at all |
+
+Two orderings matter.
+The processor switches must be on across the fleet before the seeder dispatches, or no marker arrives.
+And a stamp cannot be undone, so set the run allowlist to `none`, or to a list of run ids someone has checked, in every region before turning the finalizer on.
+Otherwise the finalizer stamps every observed run at once, including runs nobody reviewed.
+
+## Dispatch
+
+The seeder dispatches reconcile for a run when its planning proof is stamped and every chunk is confirmed.
+
+1. A compare-and-set moves the run from `seeding` to `reconciling`.
+ It requires the planning proof and no unconfirmed chunk, and planning locks the run row, so no chunk can appear between the check and the move.
+2. The seeder records the current end of each marker-topic partition as the watcher's **start positions**.
+ Markers already on the topic before this dispatch are not counted.
+3. It produces one reconcile request per participating cohort to each of the 64 seed partitions, and records the highest offset it produced on each partition.
+4. In one transaction it stores those offsets, the start positions, and a **dispatch epoch**.
+ For every participation that is not superseded, it clears the marker bitmap, the completion time and any error.
+ It also clears `reconcile_observed_at`, which is how a dispatch reopens a run that was held on a shortfall.
+
+Every later write for this dispatch is conditioned on the dispatch epoch, so a newer dispatch of the same run makes an older one's writes miss.
+Markers themselves carry no epoch.
+A marker from an earlier dispatch of the same run that lands after the start positions still counts, which is harmless because it certifies a walk of the same run and pinned hash.
+
+If every participation was superseded while the run was seeding, the seeder marks the run observed without dispatching, and the finalizer moves it to `superseded`.
+
+## Watching markers
+
+A single watcher task in the seeder tails the marker topic.
+For each marker it sets the partition's bit in the matching participation's 64-bit bitmap.
+Setting a bit twice changes nothing, so duplicate markers are harmless.
+When a cohort reaches 64 of 64, the watcher writes its bits to Postgres at once instead of waiting for its timer.
+That write records the bits only.
+The observation pass, below, decides when the participation is marked complete.
+
+## Deciding the outcome
+
+When every active participation of the run has all 64 bits, the next observation pass marks them all **complete**, and no further check is needed.
+
+When any participation is short, the pass needs more.
+Deciding that a cohort is **short** is harder: the seeder must be sure no more markers are coming.
+It proves that in two steps.
+
+1. **Liveness.**
+ The processor's seed consumer must have committed past every reconcile request on all 64 partitions.
+ The processor produces a partition's marker, and waits for its acknowledgment, before it lets that request's offset be committed.
+ A request the processor discarded, or skipped because reconcile is disabled, is committed with no marker.
+ So after this point every marker of the dispatch is already on the marker topic.
+2. **Read to the end.**
+ The seeder records the marker topic's current end, and waits until the watcher has read that far.
+
+Only then does it settle the run.
+Participations with all 64 bits are marked complete at this point, so in a team run a cohort with every marker waits for the proof its short siblings need.
+Each short participation gets one of these outcomes:
+
+| Participation | Outcome written |
+| ---------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
+| Markers missing, and the cohort's current shape hash for this kind still equals the pinned one | Retryable shortfall: an error is recorded, and the participation stays open |
+| Markers missing, and this kind's shape hash moved or cannot be read, or the cohort is deleted | Superseded |
+
+Missing markers with an unchanged hash usually mean the processor discarded or skipped the request, for example because reconcile was disabled on it.
+An edit that moved only the other kind's hash also leaves this kind's hash unchanged and gives a retryable shortfall.
+A composition-only edit that owes this kind a repair run is different: Django supersedes the participation when the edit commits, so the seeder never settles it.
+For a behavioral participation, that is any composition-only edit on a cohort with a hashed behavioral leaf.
+A retryable shortfall needs an operator to dispatch the run again.
+Until then the run keeps the cohort's run slot for that kind, and the automatic driver never retries an observed run.
+
+Two rarer cases hold a run with no outcome at all, so the finalizer never sees it.
+If the marker topic's retention passes a run's start positions before the watcher reads them, the watcher drops the run and counts `seeder_reconcile_watch_truncated_total`.
+If the marker topic gains partitions after a dispatch, the watcher never reads the new ones.
+In both cases a run still short of markers never finishes the read-to-end step, and only a new dispatch with `reconcile_dispatch` recovers it.
+
+The seeder writes `reconcile_observed_at` **last**, after every participation's outcome.
+Django never sees an observed run with an undecided participation.
+
+## Finalization in Django
+
+A Celery beat task runs every two minutes, when finalization is enabled.
+It picks up runs in `reconciling` with `reconcile_observed_at` set, for each kind that may be finalized, and handles each run in its own transaction:
+
+1. Lock the run row, skipping it if another worker holds it.
+2. For each participation:
+ - superseded: count it as superseded,
+ - already stamped: count it as stamped,
+ - complete: try to stamp, below,
+ - otherwise: hold the run for a later pass.
+3. When every participation is decided, move the run to `completed` if at least one stamped, or to `superseded` if none did.
+4. After the transaction commits, invalidate the team's cached cohort data and trigger a rebuild of the flags cache.
+ Stamps are written with a queryset update that bypasses model signals, so the finalizer has to do this itself.
+
+### The stamp
+
+Each kind has its own stamp column on the cohort:
+
+| Kind | Stamp |
+| --------------- | ------------------------------------ |
+| Behavioral | `last_backfill_events_at` |
+| Person property | `last_backfill_person_properties_at` |
+
+Stamping is a compare-and-set, under a lock on the cohort row:
+
+```sql
+UPDATE posthog_cohort
+SET <stamp> = now()
+WHERE id = <cohort> AND team_id = <team>
+ AND <kind shape hash> = <hash pinned on the participation>
+ AND <stamp> IS NULL
+```
+
+together with marking the participation `stamped_at` in the same transaction.
+
+- If the cohort's shape hash for this kind has moved since pinning, the update matches nothing, and the participation is superseded, as is a cohort-scoped run.
+- A composition edit moves no kind hash, so before the update the finalizer also compares the pinned filters with the current filters.
+ If the edit owes a repair run of this kind, or either definition cannot be parsed, the stamp is refused and the participation superseded.
+- A participation that was ever superseded never stamps, even if the definition was later edited back to the pinned one.
+- If the stamp is already set and the hash still matches, the participation is ratified without changing the timestamp.
+
+Stamps are written once.
+A stamp is cleared only by a save that invalidates its kind, and only while the cohort is realtime, not static and not deleted, on an allowlisted team.
+
+Keying the stamp on the kind's own shape hash, not on the whole definition, means a person-only leaf edit does not invalidate a still-valid behavioral backfill, and the reverse.
+A structural edit can still owe both kinds a run.
+
+### Why person readiness has its own gate
+
+Person runs are finalized only when person readiness is enabled.
+Until then they wait, observed, in `reconciling`.
+
+The reason is the flags service's stamp policy.
+Under the default policy, `any_backfill_stamp`, either stamp routes a cohort with behavioral conditions to the membership table.
+A person stamp alone would then route a mixed cohort whose behavioral half was never backfilled: "in cohort" would match nobody, and "not in cohort" would match everybody.
+The other policy, `events_or_calculation_stamp`, requires the events stamp, or the legacy calculation stamp on a `realtime` cohort.
+Person readiness may be enabled only once every region's flags service runs that policy.
+
+## What readiness unlocks
+
+### In Django
+
+`Cohort.is_flag_compatible` is true when the cohort is realtime and **every** stamp its filters need is set, and they need at least one:
+
+- a behavioral leaf needs the events stamp,
+- a person leaf needs the person stamp,
+- a mixed cohort needs both.
+
+A `person_metadata` leaf makes a cohort non-realtime in the first place, so such a cohort is never compatible.
+A cohort made only of references needs no stamp, so it is never compatible either.
+
+The flag API accepts a cohort with event-based criteria, or one that depends on such a cohort, only when the realtime targeting rollout flag is on for the user and every such cohort is flag-compatible.
+The same rollout flag lets the flag editor's cohort picker list these cohorts.
+
+Behind the same rollout flag, for allowlisted teams, the cohort API's `realtime` field reports one state per cohort that has event or person criteria: `static`, `person_properties`, `daily`, `building`, `rebuilding`, `ready`, or `needs_attention`.
+
+### In the feature flags service
+
+The Rust flags service reads cohorts from the flags cache, or from Postgres through a short-lived cache when the flags cache has none.
+It routes a cohort to the membership table when all of these hold:
+
+- the team is in `REALTIME_COHORT_EVALUATION_TEAM_IDS`,
+- the cohort's type is `realtime`, or the legacy `behavioral` type,
+- its `condition_type` marks a behavioral or lifecycle condition,
+- its stamps satisfy the configured stamp policy.
+
+Otherwise the cohort is evaluated dynamically from person properties, where behavioral leaves can never match.
+[Membership output and readers](membership-output-and-readers.md#feature-flags) describes the read path.
+
+The Django rule and the Rust rule are separate predicates.
+Django decides whether a flag may be **saved** with the cohort.
+Rust decides, on every request, where to **read** membership from.
+They diverge in both directions.
+The stamp policy can accept fewer stamps than Django requires, so an existing flag can keep reading the table in a state where Django would refuse a new one.
+And Django can accept a flag that Rust then evaluates dynamically, for example when the team is not in the flags service's list.
+
+## What a stamp does not mean
+
+- **It does not mean downstream has caught up.**
+ The finalizer trusts the seeder's observation of markers.
+ Neither checks how far the membership consumer has applied the reconcile rows, or whether the stale-row sweep has run.
+- **It does not mean fresh.**
+ A stamp says a backfill of the current definition completed once.
+ Live changes lost afterwards are repaired only by a later reconcile.
+- **It does not mean complete history.**
+ A person stamp covers persons updated since the run's horizon.
+ A behavioral stamp covers history only up to the seeder's lookback cap.
+- **It does not cover leaving the realtime set.**
+ The finalizer does not check whether the cohort was deleted, made static or stopped being realtime while the run was in flight.
+
+## Worked example
+
+Run R for cohort 42 on team 7 has one participation, pinned with behavioral shape hash `B7`.
+
+1. **10:05:45.**
+ All 7 chunks are confirmed.
+ The seeder moves R to `reconciling`, records the marker topic's start positions, produces 64 reconcile requests for cohort 42, and records their offsets and dispatch epoch E1.
+2. **10:05:50 to 10:15:35.**
+ Partitions finish their walks at different times, the last ones only after their held tiles apply.
+ The watcher sets bits as markers arrive.
+3. **10:15:35.**
+ The last marker arrives.
+ The bitmap reads 64 of 64, and the watcher writes it.
+4. **10:15:45.**
+ The seeder's next pass finds every participation complete, marks it complete without any liveness check, and writes `reconcile_observed_at`.
+5. **10:16:00.**
+ The finalizer locks R, finds the participation complete, locks cohort 42, confirms the current filters owe no repair, and runs the stamp update with `behavioral_filters_shape_hash = 'B7'`.
+ One row matches.
+ It marks the participation stamped, moves R to `completed`, and after commit triggers the flags cache rebuild for team 7.
+
+**Variant: an edit at 10:10.**
+The user changes the cohort's window, which moves the behavioral hash to `B14`.
+When the edit commits, its supersede hook marks the participation and R superseded.
+The finalizer never sees R.
+The stamp's hash check is only the backstop for an edit that commits before that hook runs.
+The edit's own run will build readiness for the new definition.
+
+**Variant: one processor had reconcile disabled.**
+Every partition that processor owns skips the request, so markers for those partitions never arrive.
+The seeder waits for the liveness proof, reads the marker topic to its end, and finds partitions missing.
+The hash still matches, so it records a retryable shortfall and marks the run observed.
+The finalizer holds R on every pass until an operator dispatches it again.
diff --git a/docs/internal/realtime-cohorts/definitions-and-eligibility.md b/docs/internal/realtime-cohorts/definitions-and-eligibility.md
new file mode 100644
index 000000000000..ff6690f08f4c
--- /dev/null
+++ b/docs/internal/realtime-cohorts/definitions-and-eligibility.md
@@ -0,0 +1,460 @@
+# Cohort definitions and the realtime catalog
+
+This page explains how a cohort definition saved in Django becomes something the Rust services can evaluate.
+It covers the cohort filter tree, what the cohort API compiles on save, the two identities every leaf gets, how the Rust services load and classify definitions, and what each kind of edit changes.
+
+Every other page in this directory builds on the vocabulary introduced here.
+Read it first.
+
+## A cohort is a boolean tree of leaves
+
+A dynamic cohort stores its criteria in the `filters` JSON column.
+The root is always a group, and groups nest.
+
+```json
+{
+ "properties": {
+ "type": "OR",
+ "values": [
+ {
+ "type": "AND",
+ "values": [
+ { "type": "behavioral", "value": "performed_event_multiple", "key": "$pageview", "...": "..." },
+ { "type": "person", "key": "email", "operator": "is_set", "...": "..." }
+ ]
+ }
+ ]
+ }
+}
+```
+
+A group is `{"type": "AND" | "OR", "values": [...]}`.
+Everything else is a **leaf**, one criterion of the cohort.
+Groups carry no negation.
+Negation lives on each leaf as `negation: true`.
+
+The realtime pipeline understands three types of leaf, one of them in two variants.
+
+| Leaf | What it asks | Example |
+| --------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ---------------------------------------------------- |
+| `behavioral` with `value: performed_event` | Did the person perform this event at least once inside the window? | Viewed `/pricing` in the last 30 days |
+| `behavioral` with `value: performed_event_multiple` | Did the person perform this event a number of times inside the window, compared with an operator? | Viewed `/pricing` 3 or more times in the last 7 days |
+| `person` | Does a person property match? | `email` is set |
+| `cohort` | Is the person in another cohort? | In cohort 17 |
+
+Every other behavioral value, such as `performed_event_first_time`, `performed_event_sequence`, `performed_event_regularly`, `stopped_performing_event` and `restarted_performing_event`, is not supported in realtime.
+Neither are behavioral leaves keyed on an action instead of an event name, and `person_metadata` leaves, which read top-level person columns such as "first seen".
+One unsupported leaf makes the whole cohort non-realtime.
+
+## What the cohort API compiles on save
+
+The cohort API validates the filter tree and compiles each leaf before the row is written.
+The Rust services never call Django.
+They read the columns Django writes, so everything they need has to be derived at save time.
+A cohort created directly through the ORM, bypassing the API serializer, gets no bytecode and no `cohort_type`.
+
+```mermaid
+flowchart LR
+ Editor[Cohort editor / API] --> Validate[Validate the filter tree<br/>compile each leaf]
+ Validate --> Filters["filters JSON<br/>bytecode + conditionHash per leaf"]
+ Validate --> Type["cohort_type = realtime or null"]
+ Filters --> Hashes["shape hashes"]
+ Hashes --> Stamps["readiness stamps<br/>cleared when a shape moves"]
+ Filters --> Rust["Processor and seeder"]
+ Type --> Rust
+ Hashes --> Rust
+ Type --> Flags["Feature flags service"]
+ Stamps --> Flags
+```
+
+### Bytecode and the condition hash
+
+Each supported leaf gets two fields written into the stored `filters` JSON.
+
+- `bytecode` is a HogVM program that answers the leaf's matcher.
+ For a behavioral leaf the matcher is `event = <key> AND <event property filters>`.
+ For a person leaf it is the property predicate, including its operator.
+ For a cohort reference it is `inCohort` or `notInCohort`.
+- `conditionHash` is the first 16 hex characters of a SHA-256 over the bytecode serialized as JSON with sorted keys.
+
+The condition hash names the matcher and nothing else.
+The window, the count operator, the count threshold, the cohort id and the team id are all outside it.
+A person or behavioral leaf's negation is outside it too, because negation is not compiled into those leaves' bytecode.
+Two leaves that match the same events with the same property filters share one condition hash, even when their windows differ and even across cohorts.
+
+The Rust services treat the hash as 16 opaque ASCII bytes.
+They never hex-decode it and never recompute it from the bytecode.
+A hash that is not exactly 16 bytes makes its leaf unusable.
+
+### The realtime decision
+
+The API serializer sets `cohort_type = 'realtime'` when all of the following hold:
+
+- every leaf compiled to bytecode without an error,
+- no leaf is `person_metadata`,
+- every cohort reference points to a cohort that is itself realtime at the moment of this save,
+- the cohort does not use `filterTestAccounts`, because the test-account filters are added at query time and the realtime evaluator cannot see them,
+- on edits, the last known person count is under a size cap.
+
+The rule reads the criteria only.
+No team allowlist or rollout flag is involved, so any project can hold `realtime` cohorts, and the Rust services choose which teams they actually process.
+The rule also checks no composition, which matters later on this page.
+
+Other writers can take `realtime` away after a save.
+The batch recalculation clears it when a cohort's count grows past the size cap, and a resave management command clears it for some nested references.
+
+Legacy ClickHouse recalculation keeps running for every dynamic cohort, realtime or not.
+Insights, person counts and person lists still come from that path.
+The realtime membership serves two readers: feature flags on teams enabled in the flags service, and workflow conditions that check cohort membership.
+[Membership output and readers](membership-output-and-readers.md) covers both.
+
+### Shape hashes
+
+For realtime, non-static, non-deleted cohorts on teams in `REALTIME_COHORT_TEAM_ALLOWLIST`, every save that includes `filters` also maintains three hash columns on the cohort row.
+
+| Column | What it fingerprints | Read by |
+| ------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
+| `behavioral_filters_shape_hash` | The behavioral leaves, each identified by its condition hash plus every window and count field | The processor, to reject reconcile work for a stale definition. Django's finalizer, as the key of the events readiness stamp |
+| `person_filters_shape_hash` | The person leaves, each identified by its condition hash | The same, for the person readiness stamp |
+| `filters_shape_hash` | The whole definition, including AND/OR structure, leaf negation and cohort references | Django only |
+
+The two kind hashes ignore the order of leaves, where a leaf sits in the tree, and whether it is negated.
+Duplicate leaves still count.
+The definition hash sees composition.
+A fourth fingerprint, the person view of the tree, is computed on the fly and never stored.
+[Backfill coordination](backfill-coordination.md) explains how Django uses the definition hash and the person view to decide which backfill an edit owes.
+Backfill runs pin a copy of the kind hashes when they are created.
+[Reconcile](seed-apply-and-reconcile.md#reconcile) and the finalizer compare that pinned copy with the current one.
+
+When a kind hash moves, the same `UPDATE` that stores the new definition also clears that kind's readiness stamp.
+A composition-only edit, which moves no kind hash, clears the stamp of each kind Django decides to re-run.
+While the cohort stays realtime and the maintenance succeeds, a stamp therefore never outlives the definition it was earned for.
+The maintenance is best effort: if hashing raises an error, Django logs it, saves the new definition anyway, and leaves the old stamps in place.
+An edit that takes the cohort out of realtime, a soft delete, a switch to static, or the size-cap clear skips this maintenance and leaves the stamps in place.
+[Completion and readiness](completion-and-readiness.md) covers the stamps.
+
+## Two identities per leaf: condition hash and leaf state key
+
+The pipeline keeps per-person state for each behavioral and person leaf.
+The condition hash cannot be the key for that state, because two leaves with the same matcher but different windows need different state.
+"Viewed pricing 3 or more times in 7 days" and "viewed pricing in the last 30 days" match exactly the same events, yet one needs 8 daily counters and the other needs one boolean.
+
+So every behavioral and person leaf has two identities.
+A cohort reference has neither: it keeps no state of its own, and Stage 2 reads the referenced cohort's membership instead.
+
+- The **condition hash** identifies the matcher.
+ The processor runs each condition hash's program once per event.
+- The **leaf state key** (LSK) identifies one leaf's state.
+ For a behavioral leaf it is a SHA-256 over the condition hash plus the leaf's `value`, `time_value`, `time_interval`, `explicit_datetime`, `explicit_datetime_to`, `operator` and `operator_value`, truncated to 16 bytes.
+ For a person leaf it is the condition hash itself, because a person predicate has no window.
+
+```text
+ condition hash H (event = '$pageview' AND url ILIKE '%/pricing%')
+ |
+ evaluated once per event
+ |
+ +----------+-----------+
+ | |
+ LSK A LSK B
+ multiple, gte 3, 7 days single, 30 days
+ | |
+ cohorts 42, 51 cohort 60
+```
+
+Three consequences follow.
+
+- **Evaluate once, fan out.**
+ One VM run per condition hash per event, however many windows, operators or cohorts use it.
+ The result fans out to every LSK that shares the hash.
+- **Cohorts share state.**
+ Two cohorts on the same team with an identical leaf get the same LSK and share one row of state per person.
+ Teams never share state, because every store key includes the team.
+- **Negation and the event name are not in the key.**
+ The event name is already inside the condition hash.
+ Negation lives only in the tree, so `A` in one cohort and `NOT A` in another share state.
+
+The LSK derivation is frozen.
+A golden vector test in Rust pins the bytes, and Django's behavioral shape hash normalizes exactly the same eight fields the same way.
+Changing the derivation would re-key every behavioral state row in every store, orphaning all of it.
+
+## How the Rust services load definitions
+
+Every Rust service that needs definitions builds a **catalog**: an immutable, per-team index of parsed cohorts.
+The shared `cohort-core` crate owns the parsing, classification and indexing, so the processor and the seeder interpret a definition with the same code.
+
+- The **processor** loads every row with `cohort_type = 'realtime' AND deleted = false AND filters IS NOT NULL`, joined to the team's timezone.
+ It keeps only teams in its own copy of `REALTIME_COHORT_TEAM_ALLOWLIST`, builds the catalog off the async runtime, and swaps it in atomically.
+ It refreshes every few minutes with jitter.
+ A failed refresh keeps the previous catalog, so a database outage freezes definitions instead of emptying them.
+- The **seeder** never loads the live definitions.
+ It builds a catalog from the filters Django pinned into each backfill run, so a run's seeds replay exactly the definition it was created for.
+ That catalog holds only the run's cohorts, and it always has cascades off.
+ A run's reconcile is different, because it runs on the processor against the processor's live catalog.
+ See [the seeder](seeder.md).
+- The **shuffler** only needs to know which teams have realtime cohorts.
+ It keeps a team index from the same predicate.
+ See [event routing](event-routing.md).
+
+Definitions do not travel through Kafka.
+Each service polls Postgres, so an edit reaches the processor within one refresh interval.
+
+### Parsing
+
+The parser turns the JSON tree into groups and leaves exactly as written.
+It never merges siblings, flattens groups or simplifies the tree.
+When a leaf is dropped, its group stays in place, possibly empty.
+
+### Leaf classification
+
+Each leaf is kept, dropped with a reason, or recorded as a cohort reference.
+A kept behavioral leaf also gets a **state variant**, which decides how its state is stored and counted.
+
+| Leaf | Window | State variant |
+| -------------------------- | ------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
+| `performed_event` | Any window that resolves, including sub-day ones | `BehavioralSingle`: remembers whether it matched and the most recent match |
+| `performed_event` | No window at all | Dropped |
+| `performed_event_multiple` | A sliding window of 1 to 180 whole days | `BehavioralDailyBuckets`: one counter per team-timezone day |
+| `performed_event_multiple` | A sliding window of more than 180 days | `BehavioralCompressedHistory`: a compact per-day history |
+| `performed_event_multiple` | Anything else: no window, an absolute date range, or an hour or minute window of any length | Dropped |
+| `person` | None | `PersonProperty`: a bit in the person's record |
+
+A few window rules are worth knowing.
+
+- A month is 30 days and a year is 365 days.
+ The batch ClickHouse query uses calendar months and years instead, so month and year windows differ from it at the edges.
+ The gap grows with the window: one month can be a day or two off, and 12 months are 360 days here against 365 or 366 in the batch query.
+- `explicit_datetime` and `explicit_datetime_to` take precedence over `time_value` and `time_interval`.
+ Absolute dates are calendar days in the team's timezone, not instants.
+ A `performed_event` leaf with absolute dates has a fixed window, so its membership never expires.
+- A relative upper bound, an unparseable bound, or a mix of relative lower bound and absolute upper bound drops the leaf.
+- Operators other than `gte`, `lte`, `gt` and `lt` behave as equality.
+ A count of zero is never a match, even for `lt 1`.
+
+A leaf is also dropped when its behavioral value is unsupported, when it is keyed on an action, when its condition hash or bytecode is missing or malformed, or when its type is unknown.
+Every drop is counted by reason.
+
+## Eligibility: which cohorts the processor composes
+
+After classification, each cohort gets an **eligibility class**.
+The class decides whether the processor emits membership for the cohort and how it computes it.
+Stage 1 and Stage 2 below are the two halves of live evaluation: Stage 1 keeps each leaf's state, and Stage 2 combines leaves into a cohort.
+[Live evaluation](live-evaluation.md) explains both.
+
+| Class | Meaning |
+| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `SingleLeaf` | Exactly one leaf. The leaf's own state is the membership, so no composition is needed |
+| `Stage2Composable` | Two or more leaves under a root that is not negated. Membership is the tree folded over the leaf answers |
+| `Stage2ComposableRef` | The cohort references other cohorts, and cascades are enabled. Every positively referenced cohort must be in the team's catalog and eligible itself, as a single-leaf, composable or referencing cohort, and there must be no reference cycle |
+| `Excluded(reason)` | Nothing is emitted for this cohort |
+
+The exclusion checks run in a fixed order, and the first match wins.
+
+1. **Dropped leaf.** Any dropped leaf excludes the whole cohort, even when other leaves are fine.
+ A cohort evaluated without one of its leaves would produce wrong members.
+ A missing cohort is the safe failure.
+2. **Empty group.** Any group with no children.
+3. **Negated root.** An `AND` group is negated when all its children are negated.
+ An `OR` group is negated when any child is.
+ So `AND[A, NOT B]` is composable, while `OR[A, NOT B]` and a lone `NOT A` are excluded.
+ A negated root would match every person with no state at all, and the processor has no way to enumerate those persons.
+4. **Cohort reference.** Excluded unless cascades are enabled, which they are not by default.
+ [Merges and cascades](merges-and-cascades.md#cascades-cohorts-that-reference-cohorts) explains cascades, cycle detection and why a negated reference to an untracked cohort does not block.
+
+Excluded cohorts still cost work.
+Their valid leaves stay in the index, so the processor keeps maintaining that leaf state even though it emits nothing for the cohort.
+
+The processor and the seeder reach the same class for every cohort without references.
+For a cohort with references, the processor may compose it through cascades while the seeder, which never enables cascades, excludes it.
+
+### Where Django and Rust disagree
+
+Django's realtime rule is looser than Rust's eligibility.
+Django marks these shapes `realtime`, and Rust excludes them:
+
+- a negated root, such as a cohort whose only criterion is "did not perform event X",
+- an empty group,
+- any behavioral leaf whose window Rust cannot represent, such as a `performed_event` with no window or a `performed_event_multiple` over less than a day,
+- a cohort reference when cascades are disabled.
+
+Such a cohort gets `cohort_type = 'realtime'`, is loaded into the catalog, and produces no membership.
+Keep this in mind when a realtime cohort appears to match nobody.
+The `cohort_eligibility_total{class}` metric counts every loaded cohort by class, and an excluded class names its reason, for example `excluded_top_level_negation`.
+Both the processor and the seeder emit it, so filter by job.
+
+## The reverse index
+
+The frozen catalog for a team is a set of lookup maps built once per refresh.
+The processor's hot path never walks all cohorts.
+It goes from an event to the few map entries that matter.
+
+| Map | From → to | Used for |
+| ----------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
+| Behavioral candidates by event name | event name → the condition hashes whose leaf `key` is that event | The event-name gate. An event whose name no behavioral condition mentions runs no behavioral program |
+| Condition → program | condition hash → decoded HogVM program | The program to run, decoded once per catalog build |
+| Condition → leaf state keys | condition hash → every LSK that shares it | Fan-out after a match, and when applying a backfill tile |
+| Leaf state metadata | LSK → variant, window, count operator | The parameters of the Stage 1 update |
+| Single-leaf cohorts | LSK → cohorts whose only leaf this is | A leaf flip is the cohort flip |
+| Composable cohorts | LSK → cohorts that contain this leaf | Which cohorts Stage 2 recomposes when the leaf flips |
+| Referencing cohorts | cohort → cohorts that reference it | Cascades |
+| Person conditions, ordered | sorted list of person condition hashes | The person evaluation order |
+| Catalog fingerprint | digest of the sorted person condition hashes | Skipping person re-evaluation while nothing changed |
+| Eligibility and trees | cohort → class, cohort → parsed tree | Stage 2 composition |
+| Shape hashes | cohort → behavioral and person shape hash | Rejecting reconcile work for a stale definition |
+| Timezone | the team's IANA timezone | Every calendar-day computation |
+
+The catalog build is deterministic.
+Conditions are sorted, teams freeze in id order, and a shared static-analysis budget is spent in that order, so every replica derives the same catalog from the same rows.
+
+## The HogVM evaluation contract
+
+Leaves are evaluated with the Rust HogVM, configured the same way in every process that links `cohort-core`.
+
+- The stored bytecode has no trailing `RETURN`, so the loader appends one before decoding.
+ Each program is decoded once per catalog build.
+- The cohort evaluator enables type-coercing comparisons, as the Python and TypeScript HogVMs do, and orders dates by their instant, as ClickHouse does.
+ A string compares as a number only when the other side is a number, and `1 == 1.0` is true.
+- A program that fails at runtime, calls an unknown function, or returns a non-boolean counts as `false`.
+ Failures are counted by reason.
+- An event with malformed `properties` JSON skips only the behavioral side.
+ Malformed `person_properties` skips the whole event when the person side has to evaluate.
+ An event with an unparseable timestamp is skipped.
+
+The processor builds two kinds of globals for the VM.
+Behavioral globals mirror what the Node CDP filters see: the event name, uuid, distinct id, timestamp, properties, and the person with its properties.
+Person globals hold only the person id, the person properties and the project id.
+
+### Static analysis of conditions
+
+At catalog build, `cohort-core` analyzes each behavioral program without running it.
+The analysis computes the set of globals and property paths the program can read.
+Two consumers use it.
+
+- The processor builds only the globals an event's candidate conditions can read, and parses a JSON payload only when some behavioral condition of the team can read it.
+ On a team whose behavioral conditions read only `event` and `properties.$current_url`, the behavioral side never parses person properties.
+- The seeder asks ClickHouse only for the columns and property keys its conditions read.
+
+The analysis fails wide.
+Any construct it does not model, and any program that exceeds its budget, falls back to "reads everything".
+A read set that is too small would silently change answers, while one that is too wide only costs time.
+Each consumer has its own test in `rust/cohort-core/tests/`.
+A property-based test in `analysis_equivalence.rs` covers the seeder: evaluating on an event pruned to the read set, the way the projected scan returns it, must match evaluating on the full event.
+A fixture test in `analysis_parity_corpus.rs` covers the processor: each fixture must decide the same way from globals that hold only its planned roots.
+
+## What an edit changes
+
+Because state is keyed per LSK and the kind hashes follow the LSK fields, the effect of an edit follows directly from which identity it moves.
+
+| Edit | Condition hash | LSK | Kind hash | Definition hash | Effect on live state |
+| --------------------------------------------------------- | -------------- | ---- | ---------------- | --------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
+| Change a behavioral leaf's event or event property filter | New | New | Behavioral moves | Moves | The new leaf starts empty, unless another cohort on the team already uses it |
+| Change a behavioral leaf's window, operator or threshold | Same | New | Behavioral moves | Moves | Same as above |
+| Change a person leaf's property, operator or value | New | New | Person moves | Moves | The new leaf starts empty |
+| Toggle a person or behavioral leaf's negation | Same | Same | Same | Moves | State is reused. Composition changes, and eligibility can too: negating the only leaf excludes the cohort |
+| Switch AND and OR, or regroup | Same | Same | Same | Moves, unless the group has one child or only the order changed | State is reused. Composition changes, and eligibility can too |
+| Add or remove a cohort reference | n/a | n/a | Same | Moves | With cascades off, adding a reference excludes the cohort. Referencing a non-realtime cohort makes this cohort non-realtime |
+| Rename the cohort | Same | Same | Same | Same | Nothing |
+
+A new LSK has no history.
+Live events fill it from the moment the processor sees the new definition, and a backfill run fills the past.
+Rows of an LSK that no cohort uses any more stay on disk, and nothing reclaims them.
+
+A composition-only edit keeps every leaf's state.
+But the live path recomposes a person only when one of their leaves flips, so a person whose leaf answers do not change keeps the old composition.
+That is why Django owes a repair run even for composition-only edits.
+[Backfill overview](backfill-overview.md) explains how that repairs them.
+
+## Worked example
+
+Team 7 is in `REALTIME_COHORT_TEAM_ALLOWLIST`.
+It saves cohort 42, "Pricing regulars":
+viewed a page whose URL contains `/pricing` 3 or more times in the last 7 days, and has an email.
+
+### What Django stores
+
+The stored filters after validation, trimmed:
+
+```json
+{
+ "properties": {
+ "type": "OR",
+ "values": [
+ {
+ "type": "AND",
+ "values": [
+ {
+ "type": "behavioral",
+ "value": "performed_event_multiple",
+ "key": "$pageview",
+ "event_filters": [{ "type": "event", "key": "$current_url", "operator": "icontains", "value": "/pricing" }],
+ "time_value": 7,
+ "time_interval": "day",
+ "operator": "gte",
+ "operator_value": 3,
+ "negation": false,
+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11, "..."],
+ "conditionHash": "b938e32d52f73122"
+ },
+ {
+ "type": "person",
+ "key": "email",
+ "operator": "is_set",
+ "negation": false,
+ "bytecode": ["_H", 1, 31, 32, "email", 32, "properties", 32, "person", 1, 3, 12],
+ "conditionHash": "b165e0485bac04e7"
+ }
+ ]
+ }
+ ]
+ }
+}
+```
+
+- The behavioral bytecode encodes `event = '$pageview' AND toString(properties.$current_url) ILIKE '%/pricing%'`.
+ The 7-day window and `gte 3` are not in it.
+- The person bytecode encodes `person.properties.email != null`.
+- `cohort_type` is `realtime`.
+ Both kind hashes are set, because team 7 is allowlisted, and both readiness stamps are empty until a backfill completes.
+
+### What the catalog builds
+
+```text
+cohort 42, team 7
+ OR
+ └── AND
+ ├── behavioral H_b = "b938e32d52f73122" variant BehavioralDailyBuckets
+ │ window 7 days, gte 3 LSK_b = sha256(H_b ‖ fields)[..16]
+ └── person H_p = "b165e0485bac04e7" variant PersonProperty
+ LSK_p = H_p
+eligibility: Stage2Composable (two leaves, root not negated)
+```
+
+The index entries for team 7:
+
+```text
+behavioral candidates by event name "$pageview" → [H_b]
+condition → leaf state keys H_b → [LSK_b] H_p → [LSK_p]
+leaf state metadata LSK_b → daily buckets, 7 days, gte 3
+ LSK_p → person property
+composable cohorts LSK_b → [42] LSK_p → [42]
+person conditions, ordered [H_p]
+```
+
+A `$pageview` event from any person on team 7 runs one behavioral program, `H_b`.
+A `$autocapture` event runs no behavioral program and parses no event properties.
+Because team 7 has a person condition, any event that carries person properties still has them fingerprinted.
+They are parsed and `H_p` runs when the person has no record yet or the properties changed since the last evaluation.
+
+### Two edits
+
+- The user changes "3 or more" to "5 or more".
+ `H_b` stays the same, because the bytecode did not change.
+ `LSK_b` changes, because `operator_value` is part of it.
+ The new leaf starts empty, the behavioral shape hash moves, the events readiness stamp is cleared, and a behavioral backfill is owed.
+- The user changes the inner `AND` to `OR`.
+ No condition hash, LSK or kind hash moves, so every leaf keeps its state.
+ The definition hash moves.
+ Django clears both readiness stamps and owes repair runs, so that every person's membership is recomposed under `OR`.
+
+## Invariants on this page
+
+Invariants 1 to 5 and 26 in [invariants](invariants.md#definitions-and-the-catalog) state the rules this page depends on.
diff --git a/docs/internal/realtime-cohorts/event-routing.md b/docs/internal/realtime-cohorts/event-routing.md
new file mode 100644
index 000000000000..a8ed7255b1d7
--- /dev/null
+++ b/docs/internal/realtime-cohorts/event-routing.md
@@ -0,0 +1,214 @@
+# Event routing and partition affinity
+
+This page explains how events get from ingestion to the stream processor, and the partitioning rule that the whole pipeline depends on.
+It covers the shuffler, the envelope it writes, and every topic that must share its partitioning.
+
+## Why events are re-keyed
+
+The processor keeps state per person: counters for each behavioral criterion, a record of which person-property criteria match, and the last computed membership of each cohort.
+[Live evaluation](live-evaluation.md) describes that state.
+To update it without locks, one worker must own everything about a given person.
+
+Ingestion's firehose topic, `clickhouse_events_json`, is keyed by event UUID.
+A person's events are spread across all of its partitions.
+The **shuffler** (`cohort-event-shuffler`) fixes that.
+It reads the firehose, keeps only the events the pipeline can use, and republishes them to `cohort_stream_events` keyed by `"{team_id}:{person_id}"`.
+After the re-key, every event of one person lands on one partition, and the processor assigns each partition to one worker.
+
+```mermaid
+flowchart LR
+ Ingest[Ingestion] -->|keyed by event uuid| Firehose[(clickhouse_events_json)]
+ Firehose --> Shuffler[cohort-event-shuffler<br/>stateless]
+ Shuffler -->|"keyed by team:person"| Stream[(cohort_stream_events<br/>64 partitions)]
+ Stream --> Processor[cohort-stream-processor<br/>one worker per partition]
+```
+
+The shuffler is stateless and can run many replicas.
+The processor is stateful, which is why routing matters so much.
+
+## The shuffler
+
+### Which events it keeps
+
+Most firehose events are irrelevant to realtime cohorts, so the shuffler filters before it does any expensive work.
+It parses every message in two phases.
+
+1. **A cheap gate.**
+ The first parse reads only `team_id` and whether `person_id` is present.
+ Large fields such as `properties` and `person_properties` are skipped without being allocated.
+2. **A full parse for survivors.**
+ Only events that pass the gate are parsed completely and turned into the output envelope.
+
+An event passes the gate when it has a person id and its team is in the **team index**.
+The team index is the set of teams that have at least one realtime cohort, intersected with `REALTIME_COHORT_TEAM_ALLOWLIST`.
+The shuffler rebuilds it from Postgres every few minutes and swaps it in atomically.
+
+Apart from the person id check, the gate looks at the team only.
+It cannot filter by event name: person-property criteria are re-evaluated from every event that carries person properties, whatever the event is called.
+So every event from an enabled team with a person id is forwarded.
+
+The shuffler consumes nothing until the team index has loaded once.
+If Postgres is down when it boots, the shuffler lags and retries on its refresh interval.
+It loses nothing as long as its consumer group has a committed offset that is still inside the firehose's retention.
+A group with no usable offset starts at the tail when consumption begins, as described below, so it skips what arrived during the wait.
+
+### The envelope
+
+Each forwarded event becomes a slim JSON record on `cohort_stream_events`.
+
+```json
+{
+ "team_id": 7,
+ "person_id": "0192f3a0-7c1e-7d2a-9b3c-000000000001",
+ "distinct_id": "anon-7f3e",
+ "uuid": "0192f3a1-0000-7000-8000-00000000abcd",
+ "event": "$pageview",
+ "timestamp": "2026-09-24 14:03:05.120000",
+ "properties": "{\"$current_url\":\"/pricing\"}",
+ "person_properties": "{\"email\":\"[email protected]\"}",
+ "elements_chain": null,
+ "source_partition": 3,
+ "source_offset": 9870001
+}
+```
+
+- `properties` and `person_properties` stay as raw JSON strings.
+ The processor parses them only when a criterion needs them.
+- `person_properties` is the person's properties as ingestion saw them for this event, including anything the event itself sets with `$set`.
+ A change made any other way, such as an API edit or a person merge, is seen on the person's next event.
+- Events ingested **without person processing** still carry a real `person_id` when the distinct id has a person, but their `person_properties` is an empty object.
+ The envelope does not say which kind of event it is, so the processor evaluates those events as a person with no properties.
+- `source_partition` and `source_offset` are the event's coordinates in the firehose.
+ The processor uses them to recognize an event it already applied.
+- Events that the processor re-keys after a person merge also carry `redirected_from` and `redirect_hops`.
+ The shuffler never sets them.
+
+### Delivery and commits
+
+The shuffler sends forwards without waiting for each acknowledgment, and keeps a per-partition ledger of forwards still in flight.
+The offset it commits for a firehose partition is the oldest offset still in flight, or one past the highest offset seen when nothing is in flight.
+It commits every few seconds.
+
+Across crashes and rebalances this is at least once: a restart replays the uncommitted tail, and the processor discards what it already applied.
+But a forward that is not acknowledged within the producer's delivery timeout, for any reason, is **abandoned** and committed past.
+A broker or network outage longer than that timeout abandons every forward still waiting when its timeout expires.
+Other losses:
+
+- a message that cannot be parsed,
+- a forward the producer rejects outright, for example because it is too large,
+- an event for a team that has just gained its first realtime cohort and is not yet in the team index.
+ These are counted together with every other out-of-scope team, so they are not separately visible.
+
+The consumer group starts at the tail of the firehose when it has no committed offset, or when its committed offset has aged out of the firehose's retention.
+A shuffler outage longer than the retention silently skips the gap.
+History is the backfill's job, not the shuffler's.
+
+## Partition affinity
+
+Partition affinity is the invariant everything else rests on.
+
+> Every message about one person that can change that person's state is on partition `murmur2("{team_id}:{person_id}") mod 64` of a topic that shares this partitioning, and one worker owns that partition number on every such topic.
+
+The partition function is Kafka's Java-client `murmur2`, masked to a positive number, modulo the partition count.
+Because the same key and function are used everywhere, the processor can also compute where any person lives.
+Person merges depend on that.
+
+These topics must share the partitioning:
+
+| Topic | Key | Producers |
+| ----------------------------- | ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `cohort_stream_events` | `team:person` | Shuffler. The processor also re-keys an event for a merged person to the survivor's partition |
+| `person_merge_events` | `team:old_person` | Node ingestion's Postgres-backed merge path, for teams in its own allowlist, after the merge commits |
+| `cohort_merge_state_transfer` | `team:new_person` | Processor, when a merge moves state to another partition |
+| `cohort_cascade_events` | `team:person` | Processor, for membership flips, when cascades are enabled |
+| `cohort_stream_seed_events` | `team:person` for backfill tiles and person seeds | Seeder, and the processor when it re-keys a seed for a merged person. Reconcile requests are the exception: the seeder sends one to every partition explicitly |
+
+[Merges and cascades](merges-and-cascades.md) covers merges and cascades.
+[Backfill overview](backfill-overview.md) covers seeds and reconcile requests.
+
+Two output topics are deliberately not co-partitioned.
+The membership output topic is keyed by `person_id` alone and has its own partition count.
+The reconcile marker topic is keyed per run and partition.
+Neither is read back by the processor.
+
+librdkafka's default partitioner is not `murmur2`, so every producer sets it explicitly.
+The Rust producers configure `murmur2_random`.
+The Node merge producer computes the partition itself, because the Node client ignores a global partitioner setting.
+Test fixtures in Rust and Node pin the same key to the same partition.
+
+### The partition count
+
+The count is 64.
+It is configured in three places: `COHORT_PARTITION_COUNT` on the processor and on the seeder, and `PERSON_MERGE_EVENTS_PARTITION_COUNT` on Node.
+All of them must equal the topics' partition count.
+
+Two of those are checked.
+At startup the processor reads broker metadata and refuses to run unless the stream topic has `COHORT_PARTITION_COUNT` partitions and the merge and transfer topics match it.
+It checks the cascade and seed topics the same way when those consumers are enabled.
+The seeder refuses to produce to a seed topic with any other count.
+Node's modulus is not checked against anything, so a mismatch there would misroute merges silently.
+
+The count is also fixed in code.
+`cohort-core` defines it as a constant, and with its completion driver or observer enabled, the seeder refuses to start when its setting disagrees.
+Completion tracks markers in a 64-bit bitmap, and the Node sweeper has its own constant of 64.
+
+The processor runs one worker per partition, so 64 is also the pipeline's parallelism ceiling.
+Changing the count would move almost every person to a different partition, and each worker's state would belong to someone else.
+A change means code changes to those constants, a new marker format for any count above 64, and then wiping every store and rebuilding from backfills.
+Treat the count as a constant of the system, not a tuning knob.
+
+### What breaks if affinity breaks
+
+If one producer computed partitions differently, a person's merge, cascade or seed would reach a worker that does not hold the person's state.
+That worker would build state for the person from nothing, and the real owner would never see the message.
+There is no error to catch.
+Membership would silently diverge.
+
+## Worked example
+
+Team 7 has realtime cohorts and is allowlisted.
+Person p-1 is `0192f3a0-7c1e-7d2a-9b3c-000000000001`.
+
+1. Ingestion writes a `$pageview` from p-1 to firehose partition 3, at offset 9870001.
+2. The shuffler's cheap gate reads `team_id: 7` and sees a `person_id`.
+ Team 7 is in the team index, so the event passes.
+3. The full parse builds the envelope with `source_partition: 3, source_offset: 9870001`.
+4. The key is `"7:0192f3a0-7c1e-7d2a-9b3c-000000000001"`.
+ `murmur2` of it, masked and taken modulo 64, is 26.
+5. The shuffler sends to `cohort_stream_events` partition 26 and records offset 9870001 as in flight for firehose partition 3.
+ Until the forward resolves, acknowledged or abandoned, the shuffler will not commit partition 3 past it.
+6. The acknowledgment arrives.
+ On the next commit tick, the shuffler commits partition 3 at 9870002, or later if it has read further and nothing older is in flight.
+7. The processor's worker for partition 26 receives the event.
+ Every later event, cascade and backfill seed for p-1 also arrives at worker 26.
+ If another person is later merged into p-1, that merge message lands on the other person's partition, and the state it transfers comes to worker 26.
+
+If the shuffler crashes after the acknowledgment in step 6 but before its commit, the new owner replays from the last commit and forwards the event again.
+The processor sees firehose offset 9870001 from partition 3 for p-1 a second time and skips it.
+
+## Optimizations
+
+- **Two-phase parsing.**
+ The gate parses two fields, and only survivors pay for a full parse.
+ Most firehose events are discarded at the gate.
+- **Pipelined forwarding.**
+ Consuming, producing and committing run independently.
+ Thousands of forwards can be in flight at once, so slow broker acknowledgments do not throttle consumption.
+ For typical event sizes, the in-flight cap sits below the producer's byte queue, so the shuffler pauses cleanly instead of churning on a full queue.
+- **Lock-free team index.**
+ The refresh builds a new set and swaps a pointer.
+ The hot path never waits on it.
+
+## Things that surprise people
+
+- The processor's event-name gate only skips behavioral evaluation, after the event is already on `cohort_stream_events`.
+- The shuffler and the processor each read their own copy of `REALTIME_COHORT_TEAM_ALLOWLIST` at startup, and each polls Postgres on its own schedule.
+ Only teams in both are processed, and a newly enabled team can lose a few minutes of events until both have refreshed.
+ Merges also need the team in Node's merge allowlist, and backfills need it in the seeder's copy.
+- The processor recognizes applied events with a high-water mark per firehose partition, not a set of offsets.
+ The shuffler's producer does not guarantee ordering on retries, so an event that is overtaken by a later event from the same firehose partition is skipped as if it were a replay.
+- The broker timestamp on `cohort_stream_events` is the shuffler's send time, not the event's time.
+ The processor's live watermark, which paces backfill, is built from these timestamps.
+ [Seed apply and reconcile](seed-apply-and-reconcile.md) explains why that matters.
+- Person merge events from Node are best effort.
+ They are produced after the Postgres transaction commits, and a failed send is logged and dropped.
diff --git a/docs/internal/realtime-cohorts/invariants.md b/docs/internal/realtime-cohorts/invariants.md
new file mode 100644
index 000000000000..a092bf9ae25f
--- /dev/null
+++ b/docs/internal/realtime-cohorts/invariants.md
@@ -0,0 +1,269 @@
+# Invariants
+
+This page collects the rules the realtime cohorts pipeline depends on.
+Each one says what must hold, why, what keeps it true, and what breaks if it does not.
+The linked pages explain the mechanisms in context.
+
+When you change the pipeline, check your change against this list first.
+Most of these are not enforced by a single test, and a violation usually shows up as silently wrong membership, not as an error.
+
+## Definitions and the catalog
+
+**1. A condition hash is a pure function of the compiled matcher, and every service treats it as the same 16 bytes.**
+
+- Why: seed tiles, catalog entries and pinned backfill conditions find each other by this value.
+- Kept by: Django hashes the bytecode serialized with sorted keys, and the Rust services never decode or recompute it.
+- If broken: tiles miss their leaves, and a compiler change that alters the bytecode of an unchanged filter moves every affected hash.
+- See [definitions and eligibility](definitions-and-eligibility.md#bytecode-and-the-condition-hash).
+
+**2. The leaf state key derivation is frozen, and Django's behavioral shape hash moves whenever the LSK fields of the cohort's leaves change.**
+
+- Why: behavioral state is keyed by it, and readiness is invalidated by the shape hash.
+- Kept by: a golden vector test in Rust, and a Python shape hash over the same normalized fields.
+- If broken: every stored row is orphaned at once, or an edit changes state without clearing readiness.
+
+**3. The processor and the seeder parse and classify a definition with the same code.**
+
+- Why: seeded state and live state must mean the same thing.
+- Kept by: both link `cohort-core` for parsing, classification, state keys, windows, the HogVM configuration and day math.
+ The seeder never enables cascades, so cohorts with references are the one place their classes differ.
+- Limit: composition is not shared.
+ The processor folds the tree in its own crate, and the seeder's relevance pruning runs a separate three-valued fold that agrees with it only by inspection, with no test tying the two together.
+ A change to the processor's fold has to be made in the seeder's too.
+- If broken: backfills write state the live path reads differently.
+
+**4. A cohort with any leaf the pipeline cannot represent emits nothing.**
+
+- Why: evaluating a cohort without one of its leaves gives wrong members, and no answer is safer than a wrong one.
+- Kept by: a dropped leaf excludes its cohort first in the eligibility order.
+- If broken: flags and workflows act on memberships computed from part of a definition.
+
+**5. Static analysis of conditions fails wide.**
+
+- Why: a read set that is too small silently changes answers, while one that is too wide only costs time.
+- Kept by: every construct the analysis does not model, and any analysis over budget, falls back to "reads everything".
+ A property-based test in `cohort-core` covers the seeder's pruned scan, and a fixture test covers the processor's planned globals.
+
+## Routing and the runtime
+
+**6. Every message that can change a person's state reaches the worker that owns that person.**
+
+- Why: workers keep state without locks, and a merge computes where the survivor lives.
+- Kept by: the key `"{team_id}:{person_id}"`, Kafka's `murmur2` partitioner set explicitly on every Rust producer and computed by hand in Node, the partition count shared by configuration, and startup checks on the processor and the seeder.
+ Node's merge producer computes its partition from its own setting, which nothing checks.
+- If broken: state for one person splits across workers with no error.
+- See [event routing](event-routing.md#partition-affinity).
+
+**7. While a worker runs, it is the only writer of its partition's state.**
+
+- Why: reads must see the worker's own previous writes, with no locks or snapshots.
+- Kept by: every event, merge, cascade, sweep, backfill and reconcile step for the partition runs on its worker.
+ A revoke wipes a slice after its worker exits, and a partition that moves in after boot is wiped just before its worker spawns.
+- Limit: with durable restore on, nothing makes boot recovery finish before workers start.
+ The events consumer dispatches polls that arrive before its assignment settles, and the followers start once the catalog loads, so a worker can run while the boot redrive clears outbox rows.
+ This is a gap in the ordering, not a reproduced failure.
+ See [processor runtime](processor-runtime.md#startup).
+
+**8. A committed offset never runs ahead of state on disk.**
+
+- Why: writes do not wait for the disk, so a crash can lose recent writes, and Kafka must still redeliver them.
+- Kept by: every consumer forces the write-ahead log to disk before each commit, and skips the commit if that fails.
+- If broken: a crash loses writes whose inputs are never redelivered.
+- Limit: it covers writes that succeeded.
+ A live event skipped on a store error, the batch the events consumer drops when boot recovery settles, a wiped slice, and a follower rewind that failed after a checkpoint restore are outside it.
+- See [state store and durability](state-store-and-durability.md#the-durability-invariant).
+
+**9. A later success never commits past an earlier failure that set a floor.**
+
+- Why: merges, cascades, seeds and reconcile requests must be retried, not skipped.
+- Kept by: held and deferred floors in each offset tracker, and holdovers that retry older messages before newer ones.
+- Note: the live event path sets no floor.
+ Live output is at most once because state commits before the produce, so a redelivered event is a replay and emits nothing.
+ A floor would only stall the commit, not bring a lost change back.
+
+**10. Live work comes first.**
+
+- Why: backfill must not make membership stale.
+- Kept by: each worker checks its live lane before its seed lane, seed runs are sized by a row budget, and seeds pause when the live watermark lags.
+ The sweep alternates with live batches so neither starves the other.
+- Limit: a seed heavier than the whole row budget still applies in a run of its own, so the budget does not cap how long live work waits behind that one run.
+
+## Live evaluation
+
+**11. Each event's Stage 1 changes commit as one atomic batch before the next event reads.**
+
+- Why: counters, stamps and replay marks are read, modified and written.
+- Kept by: one staged write batch per event, awaited before the next event.
+
+**12. A redelivered event changes nothing.**
+
+- Why: input is at least once.
+- Kept by: per-row replay marks, the highest firehose offset applied from each firehose partition.
+- Assumes: one person's events from one firehose partition arrive in offset order.
+ An event overtaken by a later one from the same firehose partition is skipped as a replay.
+- Limit: the marks live inside their row.
+ Once the sweep deletes a row, or the person record time-to-live expires a record, a redelivered old event is folded again.
+
+**13. The live path's Stage 1 fold never reads the wall clock.**
+
+- Why: replaying the same events must give the same state.
+- Kept by: on the live path, windows advance only with event time.
+ The sweep and backfill tile apply move them to the current wall-clock day, so applying the same tiles on a later day can slide a window and flip a leaf.
+- Consequence: a leaf's answer "as of now" is right only after the sweep has run.
+
+**14. Stage 2 recomputes the whole cohort from stored state and compares it with the stored bit.**
+
+- Why: composition must be idempotent and self-correcting.
+- Kept by: one recompute-and-diff routine shared by the live, sweep, merge, cascade, seed and reconcile paths.
+ A `left` writes an explicit `false` so reconcile can find the person later.
+- Each path decides what to emit from the diff.
+ Every path except reconcile emits only when the stored bit changes, and reconcile emits every row it walks.
+
+**15. Every time-bounded row sits in the eviction queue at its current deadline.**
+
+- Why: a person who sends no events leaves only through the sweep.
+- Kept by: every fold reschedules its row, the sweep re-arms rows it keeps, and a worker rebuilds its queue at spawn when durable restore is on.
+- If broken: dormant members never leave.
+- Limit: a sweep drops a key without rescheduling it when its team is missing from the catalog, or its leaf, row or encoding is gone or bad.
+ That row waits for the person's next matching event, or for a durable-restore rebuild when a worker spawns.
+
+**16. A merge is applied once, and its state survives until it is applied.**
+
+- Why: merge messages and transfers are redelivered, redriven and retried.
+- Kept by: drain and apply markers keyed by the original merge message, and an outbox row that is cleared only after the transfer is acknowledged.
+- Limit: markers are local to a partition and expire after their retention, and a revoke or a wipe deletes the outbox with the rest of the slice.
+- See [merges and cascades](merges-and-cascades.md).
+
+**17. Cascades are bounded.**
+
+- Why: cohorts can reference each other in chains and cycles.
+- Kept by: cohorts in a reference cycle are excluded at catalog build, and each cascade message carries a depth and a chain checked on every hop, plus a fan-out cap.
+
+## Backfill
+
+**18. A run never seeds its boundary day or any later day.**
+
+- Why: on the boundary day, the live count and a seed would be two partial counts of one day, which neither `max` nor `+` can merge correctly.
+- Kept by: a run seeds only whole team-timezone days before the day of its boundary.
+- Note: earlier days can hold live counts as well, from events live folded after loading the leaf and from late events.
+ That overlap is expected.
+ Invariants 19 and 20 keep it from counting an event twice, but a late arrival can still leave the day under-counted, see the limit of invariant 20.
+- See [backfill overview](backfill-overview.md#rule-1-split-days-at-a-boundary).
+
+**19. Seeds carry absolute values and merge idempotently.**
+
+- Why: seeds are produced at least once and applied again after failures.
+- Kept by: day tiles carry absolute counts merged with `max`.
+ A person seed applies when the person has no record, when its scan instant beats the record's stamp by a margin, or when the record was evaluated live against a different set of person conditions and the scan is not older than its stamp.
+- Limit: a person seed that changes nothing leaves no stamp, so person seeds from different runs are not ordered by scan time.
+- Limit: the person check compares clocks, not property versions.
+ A property change that reaches ClickHouse later than the margin can lose to an older scan, and after any change to the team's person conditions, the third case lets a scan inside the margin overwrite live state.
+
+**20. A day tile applies only after the live path should have folded every event the tile counted.**
+
+- Why: otherwise live adds a count on top of a tile that already has it.
+- Kept by: the scan counts only events that reached ClickHouse before the chunk's claim instant, and the processor holds each tile until the partition's live watermark passes that instant plus a margin.
+- Limit: it holds only while the live topic trails ClickHouse by less than the margin.
+ An event the shuffler abandoned never reaches the live path, so only the tile counts it, which `max` handles correctly.
+- Limit: it prevents double counting, not under-counting.
+ A late event that reaches ClickHouse after the claim instant is not in the tile, and if live folds it before the tile applies, `max` keeps the larger of two disjoint counts.
+ [Backfill overview](backfill-overview.md#rule-3-the-arrival-bound-and-the-apply-fence) describes this residue.
+
+**21. Seeds never touch replay marks.**
+
+- Why: replay marks track live topic offsets, and seed offsets would collide with them.
+- Kept by: every seed merge copies the marks through unchanged.
+
+**22. A seed slides a window before it counts into it.**
+
+- Why: applying an expired day would resurrect a row and cause an `entered` then `left` flap.
+
+**23. A reconcile request runs on each partition only after that partition applied the run's earlier seeds.**
+
+- Why: a marker must certify the run's seeds on that partition.
+- Kept by: per-partition order on the seed topic, and admission that never lets a later message overtake a held one.
+- Limit: a seed run that fails before its Stage 1 commit does not stop a later reconcile in the same tenure.
+ A seed re-keyed to a merge survivor on another partition joins the back of that partition, so that partition's marker does not cover it.
+
+**24. Reconcile emits every Stage 2 row, and a request whose kind hash no longer matches emits nothing.**
+
+- Why: live output is at most once, so only a full re-telling repairs downstream, and a stale definition must never be certified.
+- Kept by: the walk emits members and explicit non-members alike, and each request carries the pinned shape hash of its kind, checked on every drain.
+- Limit: the walk composes the processor's current tree, and the guard ignores the composition and the other kind's hash.
+ Django's finalizer checks those before it stamps.
+- Limit: the walk covers only rows the store holds.
+ It cannot restore a skipped event or find a person whose first Stage 2 row was never written.
+
+**25. A run completes only with proof.**
+
+- Why: readiness must not be certified over unplanned days, unproduced seeds or missing markers.
+- Kept by: the move to `reconciling` requires the planning proof and every chunk confirmed.
+ A short cohort is settled only after the processor has committed past every reconcile request and the marker topic has been read to its end.
+ Every outcome write is fenced by the dispatch epoch, and `reconcile_observed_at` is written last.
+- Limit: the proof covers planned days, not persons.
+ Raising the seeder's band count while a run is seeding leaves persons unscanned, and every chunk still confirms.
+- See [completion and readiness](completion-and-readiness.md).
+
+**26. A readiness stamp vouches only for the definition its run replayed.**
+
+- Why: flags read the membership table on the strength of the stamp.
+- Kept by: an edit clears the stamp in the same write that stores the new definition, while the cohort stays realtime on an allowlisted team and the hash maintenance succeeds.
+ The finalizer stamps with a compare-and-set on the pinned shape hash, refuses a run that predates a composition repair, and never stamps from a superseded participation.
+- Limit: the maintenance is best effort.
+ If hashing fails, the save still stores the new definition, and the old stamp stays.
+
+**27. At most one open participation in an active run exists per cohort and kind.**
+
+- Why: a stamp must come from exactly one backfill of the current definition.
+- Kept by: partial unique indexes on active runs, and the creators' check of open participations under a lock on the cohort row.
+
+## Membership output
+
+**28. The newest change for a cohort and person wins.**
+
+- Why: changes arrive late, twice, and out of order.
+- Kept by: with `COHORT_MEMBERSHIP_VERSION_WRITES_ENABLED` on, the consumer applies a change only if its version is at least the stored one, and versions increase strictly within one worker's tenure on a processor partition.
+ With it off, which is the default, the last message in Kafka order wins.
+- Limit: across a restart or a partition move, version order follows the wall clock.
+ A change with no usable version bypasses the ordering.
+- See [membership output and readers](membership-output-and-readers.md).
+
+**29. Membership rows, snapshot bookkeeping and consumer progress commit together.**
+
+- Why: the sweep trusts progress to mean the rows are there.
+- Kept by: one transaction per batch, when `COHORT_MEMBERSHIP_VERSION_WRITES_ENABLED` is on.
+ With it off, the consumer does a plain upsert and records no progress, and the sweep cannot run.
+
+**30. The sweep deletes only rows the latest reconcile did not re-assert, and only after they could have arrived.**
+
+- Why: a premature sweep deletes members whose re-assertion is still queued.
+- Kept by: the threshold is the lower of the snapshot's and the markers' lowest versions, and the sweep waits until the consumer has applied the membership topic up to the ends captured after all markers arrived.
+
+**31. Readers trust only `in_cohort = true`, and flags read the table only with positive proof of readiness.**
+
+- Why: the table holds non-members too, and an unready cohort's table is incomplete.
+- Kept by: both readers filter on `in_cohort`, and the flags service routes a cohort to the table only for enabled teams, realtime cohorts with a behavioral condition, and stamps its policy accepts.
+
+## Delivery, in one table
+
+| Path | Guarantee | What repairs a loss |
+| ------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | --------------------------------------------- |
+| Firehose to stream topic | At least once, with counted abandons | Backfill |
+| Node to person merge events | At most once, uncounted | Backfill, for the survivor's counts |
+| Live event to membership change | At most once | Reconcile |
+| Merge membership output, composed sweep output, first-hop cascades from the live, merge and sweep paths | At most once | Reconcile |
+| Single-leaf sweep output | At least once while the worker runs, and across a restart only with durable restore on | Retries within the path |
+| Cascade messages consumed | At least once | Holds and replays |
+| Merge state and its transfer | At least once while the partition stays assigned. A revoke deletes a pending transfer | The outbox and its redrive |
+| Seeds and reconcile, including their first-hop cascades | At least once | Replays after holds |
+| Membership consumer | At least once, applied idempotently | The version guard, when version writes are on |
+
+"At most once" means the path never retries a failed produce.
+It does not rule out duplicates: a store that loses unflushed writes, or is wiped, replays its inputs against older state and can emit a change a second time.
+
+Reconcile repairs lost output, not lost state.
+It re-tells the rows the store holds.
+An event that Stage 1 skipped needs a later seed that covers it, and a person whose first Stage 2 row was never written needs a seed or a leaf flip that touches them.
+
+The system is built on one bargain: live paths favor speed and may lose a change, and every backfill ends with a reconcile that re-tells everything the store holds.
+Anything that stops reconcile from running, or from covering a cohort, leaves downstream wrong with no signal.
diff --git a/docs/internal/realtime-cohorts/live-evaluation.md b/docs/internal/realtime-cohorts/live-evaluation.md
new file mode 100644
index 000000000000..1a56ed531ef8
--- /dev/null
+++ b/docs/internal/realtime-cohorts/live-evaluation.md
@@ -0,0 +1,355 @@
+# Live membership evaluation
+
+This page follows one event through the processor and explains how it turns into `entered` and `left` changes.
+It covers the two stages of evaluation, behavioral leaves, person-property leaves, composition, replay safety, what a catalog edit does to live state, and the optimizations on the hot path.
+
+Read [definitions and eligibility](definitions-and-eligibility.md) first for leaves, condition hashes, leaf state keys and eligibility classes.
+Time windows and the sweep that produces "left because time passed" are in [time and eviction](time-and-eviction.md).
+
+## The core idea: keep leaf state, compose on change
+
+A batch system answers "who is in this cohort" by recomputing the whole cohort for every person on a schedule.
+Its cost grows with the number of persons times the number of cohorts, whether or not anything changed.
+
+The processor instead keeps a small piece of state for each person and each leaf.
+That state answers the leaf without looking at any other person or at the person's event history.
+Events update it, and the processor recomposes a cohort for a person only when one of that person's leaves changes its answer.
+The work is proportional to the events that matter, not to the size of the cohort.
+
+Evaluation happens in two stages.
+
+- **Stage 1** folds an event into the person's leaf state and reports which leaves **flipped**, from false to true or from true to false.
+- **Stage 2** recomposes each cohort that contains a flipped leaf and compares the result with the membership it stored last time.
+ A difference becomes a membership change.
+
+```mermaid
+flowchart LR
+ Ev[Event for person P] --> S1[Stage 1<br/>fold into leaf state]
+ S1 -->|no leaf flipped| Done[nothing to emit]
+ S1 -->|leaf flipped| Map{Which cohorts<br/>use this leaf?}
+ Map -->|single-leaf cohort| Reg[the flip is the<br/>membership change]
+ Map -->|composed cohort| S2[Stage 2<br/>recompose the tree,<br/>compare with stored bit]
+ Reg --> Out[(membership changes)]
+ S2 -->|bit changed| Out
+```
+
+## The state a worker keeps
+
+The processor's RocksDB store is divided into column families, separate keyspaces with their own settings.
+Three of them hold the evaluation state.
+
+| State | One row per | Holds |
+| --------------------- | ------------------------- | ---------------------------------------------------------------------------------------------------------------- |
+| Behavioral leaf state | person and leaf state key | The leaf's counters or last match, its eviction deadline, and replay marks |
+| Person record | person | Which person conditions currently match, the fingerprints used to skip work, a freshness stamp, and replay marks |
+| Stage 2 membership | cohort and person | The membership bit the processor last decided for the pair |
+
+Behavioral rows and person records are keyed by partition, team and person first, so one person's Stage 1 state sits together on disk.
+Stage 2 rows are keyed by partition, team, cohort and then person, so one cohort's rows sit together for reconcile to walk.
+A fourth column family, the merge tombstones, is checked on every event.
+[State store and durability](state-store-and-durability.md) has the key layouts.
+
+A missing behavioral row reads as false.
+Either the person never matched the leaf, or the sweep deleted the row after the match aged out.
+A missing Stage 2 row means the processor holds no decision for that cohort and person.
+
+## Life of an event
+
+Each worker handles its partition's events one at a time, in offset order.
+For one event the steps are:
+
+1. **Find the team's definitions.**
+ The worker takes one snapshot of the catalog for the whole event.
+ An event for a team with no definitions is skipped.
+2. **Follow merges.**
+ The worker looks up the person in the merge tombstones.
+ If the person was merged into another person, the event is redirected to the survivor.
+ [Merges and cascades](merges-and-cascades.md) explains how.
+3. **Plan, without touching the rest of the store.**
+ - The event-name gate picks the behavioral conditions whose leaf names this event.
+ If there are none, the behavioral side is done and its payloads are not parsed.
+ - Otherwise the worker builds only the HogVM globals those conditions read, and parses each JSON payload that any behavioral condition of the team can read.
+ - It runs each candidate condition once.
+ Each condition that matches fans out to every leaf state key that shares its condition hash.
+ - If the team has person conditions and the event carries person properties, the worker fingerprints the raw person properties for the person side.
+4. **Read once.**
+ One batched read fetches every behavioral row the plan needs and the person record.
+5. **Fold, as a pure function.**
+ The person side runs first, then each behavioral row.
+ Each fold returns the new row and, if the leaf flipped, a transition.
+6. **Write once.**
+ All Stage 1 rows, the person record, and the Stage 2 rows of any single-leaf cohort whose leaf flipped go into one atomic RocksDB write batch.
+ The section on Stage 2 below explains why single-leaf cohorts get Stage 2 rows too.
+ The next event on the partition reads this write.
+7. **Map single-leaf transitions.**
+ A flip of a leaf that is the whole cohort becomes a membership change directly.
+8. **Compose.**
+ For each composed cohort containing a flipped leaf, Stage 2 recomputes the cohort for this person, and commits any changed bit in a second write batch.
+9. **Buffer the changes, then schedule expiry.**
+ The event's changes join the sub-batch's output buffer.
+ Each behavioral row with a finite deadline is placed in the worker's eviction queue at its new deadline.
+10. **Produce at the end of the sub-batch.**
+ The worker produces the buffered changes and, with cascades enabled, one cascade message per change, then marks the offsets.
+ [Processor runtime](processor-runtime.md#the-worker-loop) describes this step.
+
+## Behavioral leaves
+
+A behavioral leaf's state depends on its variant.
+
+| Variant | Used for | State | Member when |
+| ----------------------------- | --------------------------------------------------------- | ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `BehavioralSingle` | `performed_event` | Whether it matched, and the newest match's time | It matched and the sweep has not yet deleted the row. The sweep deletes it after the newest match leaves the window. A window with absolute dates never expires |
+| `BehavioralDailyBuckets` | `performed_event_multiple` with a window of 1 to 180 days | One counter per team-timezone day in the window | The window's total is at least 1 and satisfies the operator, such as `gte 3` |
+| `BehavioralCompressedHistory` | `performed_event_multiple` with a longer window | A sparse list of days and counts | Same as daily buckets |
+
+For windows counted in days, the window includes today.
+"The last 7 days" is today plus the 7 days before it, which is 8 calendar days in the team's timezone.
+
+Stage 1 never reads the wall clock.
+A daily window's "today" is the later of the newest event day folded into it and the day of the last sweep that touched it.
+When an event lands on a later day, the window slides forward to that day first, and then the event is counted.
+For a row that already exists, an event older than the window's first day is recorded as seen but not counted.
+With no row yet, such an event anchors a new window at its own day and is counted.
+On the live path, only the sweep moves a window forward without an event.
+Backfill tiles and merges also slide windows.
+This keeps a replay deterministic: folding the same events in the same order always gives the same state.
+
+A daily or compressed leaf can flip either way on an event.
+With `gte 3`, the third matching event makes it true.
+With `lte 2`, the third makes it false.
+A `performed_event` leaf only flips to true on an event.
+It becomes false only when the sweep deletes its row.
+
+## Person-property leaves
+
+Person conditions are evaluated from the `person_properties` snapshot that ingestion attaches to each event.
+The processor never reads a `$set` payload.
+It re-evaluates person conditions against the properties the event carries.
+[Event routing](event-routing.md#the-envelope) explains what that snapshot holds, including the empty snapshot on events ingested without person processing.
+
+Each person has one **person record**.
+It stores the set of person condition hashes that currently match, plus:
+
+- a **properties fingerprint**, a digest of the raw `person_properties` string last evaluated,
+- a **catalog fingerprint**, a digest of the team's distinct person condition hashes when last evaluated,
+- a **stamp**, the event time and firehose offset of the newest event applied.
+
+For each event with person properties, the worker makes one of four decisions.
+
+| Decision | When | What happens |
+| --------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Replay | The record's replay mark for the event's firehose partition is at or above the event's offset | Nothing |
+| Stale | The event is not newer than the stamp, comparing event time and then firehose offset | Record the event as seen. Membership does not change |
+| Skip evaluation | Both fingerprints match the record | Adopt the new stamp. No HogVM runs |
+| Evaluate | Either fingerprint changed, or there is no record | Parse the properties, run every person condition of the team, diff against the stored set, and emit a transition for each hash that entered or left |
+
+Most events run no person condition, because they are either stale or have unchanged fingerprints.
+When something does change, the worker evaluates the team's whole set of person conditions, not only the ones touching the changed key.
+There is no index from a property key to the conditions that read it.
+
+The stamp makes person state converge to the newest event by event time.
+A backdated event cannot overwrite properties that a newer event already applied.
+
+If the person side must evaluate and `person_properties` does not parse, the whole event is skipped, behavioral leaves included.
+On the other decisions the behavioral side still folds.
+
+A condition removed from the catalog stays in a person's matched set without a `left`.
+If the same condition returns later, even in a new cohort, persons still holding it get no `entered` from the live path.
+Reconcile and backfill clean up membership for cohorts whose definitions changed.
+
+## Replay safety
+
+Events arrive at least once.
+A crash, a rebalance or a shuffler retry can deliver the same event twice.
+Counting it twice would corrupt a daily counter, so every behavioral row and every person record keeps **replay marks**: for each partition of the ingestion topic the shuffler reads, called the firehose in [event routing](event-routing.md), the highest offset folded into this row.
+An event whose offset is at or below the mark for its firehose partition is a replay and changes nothing.
+
+The marks are per row, not global.
+Two leaves of the same person each know independently which events they already counted.
+Rows that absorbed a merged person also keep that person's marks under the merged-away person's id, so a late event for the merged-away person is still recognized.
+
+This check relies on one ordering property: events from one firehose partition for one person reach the processor in offset order.
+If that breaks, an event that arrives after a higher offset from its firehose partition is dropped as a replay.
+The marks also live inside their row, so when the sweep deletes a row, a redelivered old event is folded again.
+
+## Stage 2: composing cohorts
+
+On the event path, Stage 2 runs only when a Stage 1 leaf flips.
+An event that changes counters without flipping any leaf never reaches Stage 2.
+Cascades, backfill and reconcile also recompose cohorts, through the same code.
+
+For each composed cohort that contains a flipped leaf, Stage 2:
+
+1. reads the person's state for every leaf in the cohort's tree, and for a referenced cohort, its leaf state if it is single-leaf or its stored bit if it is composed,
+2. folds the tree: `AND` needs every child, `OR` needs any child, and a negated leaf inverts its answer,
+3. compares the result with the stored Stage 2 bit for this cohort and person,
+4. on a difference, writes the new bit and emits `entered` or `left`.
+
+Stage 2 recomputes the whole tree from stored leaf state every time.
+So it is idempotent: running it twice gives the same bit, and a flip is emitted only when the stored bit changes.
+
+A missing Stage 2 row reads as "not in the cohort".
+A `left` writes an explicit `false` instead of deleting the row.
+That way reconcile can later enumerate every person the store holds a decision for, including the ones it decided should leave.
+Single-leaf cohorts get the same kind of row, written in Stage 1's batch, for the same reason.
+
+The stored bit is the processor's decision, not proof that downstream received it.
+On the live path the bit commits before the change is produced.
+
+## Output
+
+Each change is a small JSON message on the membership output topic, keyed by `person_id`.
+
+```json
+{
+ "team_id": 7,
+ "cohort_id": 42,
+ "person_id": "0192f3a0-...",
+ "last_updated": "2026-09-14 14:00:03.512344",
+ "status": "entered"
+}
+```
+
+- `status` is `entered` or `left`.
+- `last_updated` is the processing time.
+ Each step of a partition worker gets a stamp strictly newer than the previous one, and all changes caused by one input message share it.
+ The downstream consumer uses it as the row version, so the newest change for each cohort and person wins.
+ The order is guaranteed only within one worker's tenure on a partition.
+ A new worker keeps no floor from the old one, so its stamps follow the wall clock.
+- Backfill paths add `origin` and `run_id`.
+ Live changes carry neither.
+
+Live output is at most once.
+State commits before the change is produced.
+If the produce fails, the next successful batch commits past it, and a replay finds nothing left to emit.
+The pipeline accepts this and relies on reconcile to repair the downstream table.
+[Processor runtime](processor-runtime.md#delivery-semantics) lists every path's guarantee.
+
+## What a catalog edit does to live state
+
+The processor picks up a new catalog every few minutes and swaps it in.
+It does not re-evaluate anything at that moment.
+Every change applies lazily, person by person, on their next relevant event, flip, sweep, backfill or reconcile.
+
+- **A leaf with a new leaf state key**, from a changed window, threshold or matcher, starts with no state unless another cohort of the team already uses it.
+ Live events fill it from now on.
+ Unless another cohort still uses the old key, its rows become orphans: never deleted, with their eviction entries dropped by the sweep.
+ If the edit is reverted, those stale rows are read again.
+- **The swap itself retracts no member the edit disqualifies.**
+ Take `gte 3` edited to `gte 5` on a single-leaf cohort: a member with 4 events starts counting from zero on the new key, never flips, and stays in the cohort until reconcile corrects them.
+ This holds whether or not the person sends events.
+ In a composed cohort, the next flip of another of the person's leaves recomposes the new tree, which reads the empty new key as false, so the member can leave before reconcile.
+- **A composition edit** keeps every leaf's state.
+ A person is recomposed under the new tree when one of their leaves next flips, or, with cascades on, when a cohort it references flips for them.
+- **A change to the set of distinct person conditions** changes the catalog fingerprint, so every person in the team is re-evaluated on their next event with person properties.
+ A new cohort that reuses a person condition the team already has does not change the fingerprint, so the reused condition makes no transition.
+ Its current matchers enter a single-leaf cohort only through the backfill, and a composed cohort through the backfill or the next flip of one of its other leaves.
+- **A cohort that is deleted, stops being realtime, or becomes excluded** stops producing output.
+ No `left` is emitted, and Stage 2 garbage collection later deletes its rows silently.
+
+That is why every definition change owes a backfill run, which includes a reconcile.
+Django creates it automatically only for teams on the backfill trigger allowlist.
+[Backfill coordination](backfill-coordination.md) explains when runs are created, and [backfill overview](backfill-overview.md) how they repair membership.
+
+## Worked example
+
+Team 7 uses UTC.
+Cohort 42 is `AND[A, B]`:
+
+- A: performed `$pageview` where the URL contains `/pricing`, 3 or more times in the last 7 days.
+ Daily buckets, 8 buckets.
+- B: person property `email` is set.
+
+Cohort 43 is `AND[B]`, a single-leaf cohort on the same person condition.
+Person p-1 lives on partition 26.
+
+### The third pageview
+
+Before, on 2026-09-14 at 14:00 UTC:
+
+- A's row for p-1 counts 2 pageviews today, and its buckets are `[0,0,0,0,0,0,0,2]`.
+- p-1's person record has `B` in its matched set, and its fingerprints match the current properties and catalog.
+- Stage 2 has a `true` row for cohort 43 and no row for cohort 42.
+ When B matched earlier, cohort 42 composed to false, so nothing was written.
+
+A third `/pricing` pageview arrives.
+
+1. The tombstone lookup finds no merge for p-1.
+2. The `$pageview` bucket holds A's condition hash.
+ The worker builds globals with only `event` and `properties`, and the condition matches.
+3. One batched read fetches A's row and the person record.
+4. Person side: the event is newer than the stamp and both fingerprints match, so the decision is "skip evaluation".
+ The record takes the new stamp.
+5. A's fold: today is still the window's last day, so the last bucket goes from 2 to 3.
+ `gte 3` was false and is now true, so A flips.
+6. One write batch commits A's row and the person record.
+7. No single-leaf cohort uses A.
+8. Stage 2 recomposes cohort 42: A is true, B is true, so `AND` is true.
+ The stored bit is absent, which reads as false, so this is a flip.
+ A second batch writes `true` for cohort 42.
+9. The change is buffered, and A's eviction deadline is rescheduled, unchanged because the oldest counted day did not change.
+10. At the end of the sub-batch, the worker produces `entered` for cohort 42 and p-1.
+
+If the same event is redelivered, A's row and the person record both see its offset at or below their marks, and nothing happens.
+
+### Email is removed
+
+Two days later, p-1 sends an event whose `person_properties` no longer contain `email`.
+
+1. The event name matches no behavioral condition, so the behavioral side parses nothing.
+2. The properties fingerprint differs from the record, so the decision is "evaluate".
+3. The worker parses the person properties and runs every person condition of team 7.
+ B is now false.
+ The diff against the stored set emits a `left` transition for B.
+4. One write batch commits the new person record and an explicit `false` Stage 2 row for cohort 43.
+5. Cohort 43 is a single-leaf cohort, so its `left` is emitted directly.
+6. Stage 2 recomposes cohort 42: A is still true from its stored buckets, and B is false, so `AND` is false.
+ The stored bit was true, so this is a flip.
+7. The worker produces two `left` changes, for cohorts 43 and 42.
+
+### Why a composed cohort can lag
+
+Suppose p-1's pageviews age out while p-1 sends no events.
+Nothing in Stage 1 runs until the sweep reaches A's deadline.
+[Time and eviction](time-and-eviction.md#worked-example) continues from "the third pageview", with p-1 keeping their email.
+
+## Optimizations on the hot path
+
+- **One Stage 1 read and one Stage 1 write per event.**
+ A person's Stage 1 state is clustered under one key prefix, so the snapshot is one batched read of a few adjacent blocks, after one tombstone lookup.
+ A flip that recomposes cohorts adds a few reads per cohort and one more write batch for all of them.
+ In a same-load comparison, clustering the keys this way and folding all person-property state into one record with fingerprints cut reads and CPU per event by more than an order of magnitude.
+- **The event-name gate.**
+ Conditions are bucketed by the event their leaf names.
+ An event only runs the conditions in its bucket, and an event with an empty bucket parses nothing for the behavioral side.
+- **Evaluate once per condition, then fan out.**
+ Cohorts and windows that share a matcher share one VM run per event.
+- **Programs decoded once per catalog.**
+ Swapping programs between conditions costs two reference-count bumps instead of a decode.
+- **Globals built by move.**
+ Parsed payloads move into the globals map without a second copy.
+ In a benchmark on a large event, that roughly halved the cost of building globals.
+- **Globals built by plan.**
+ Static analysis of the team's conditions decides which globals to build and which payloads to parse.
+ An event whose candidate conditions read only `properties.$current_url` never materializes the person object.
+- **Fingerprints skip person evaluation.**
+ An event whose person properties and team person conditions are unchanged runs no person condition.
+- **No match, little work.**
+ An event with no matching condition and no person side skips the snapshot read and the write, after its tombstone lookup.
+ Stage 2 writes only on a flip, so persons who were never members leave no Stage 2 rows.
+
+## Things that surprise people
+
+- A catalog refresh does not re-evaluate anyone.
+- Person conditions update only from events that carry person properties, and only when the event is the newest one seen for that person.
+- Events ingested without person processing carry empty person properties, so they can flip person conditions off until the person's next normal event.
+- A HogVM error reads as false.
+ For a person condition that was true, that emits `left`.
+- A late event older than a window, for a person with no row for the leaf, creates state anchored at that old day.
+ It can emit `entered`, and the next sweep emits `left` shortly after.
+ This applies to both `performed_event` and count leaves.
+- Excluded cohorts still cost Stage 1 work, because their valid leaves are indexed and maintained.
+- One event can cause two write batches, one for Stage 1 and one for Stage 2.
+ A crash between them, or a store error in Stage 2, loses the composed flip.
+ A later flip repairs it, and so does reconcile if the person already had a Stage 2 row for the cohort.
+ A store error in Stage 1 drops the event entirely, and reconcile cannot bring it back.
diff --git a/docs/internal/realtime-cohorts/membership-output-and-readers.md b/docs/internal/realtime-cohorts/membership-output-and-readers.md
new file mode 100644
index 000000000000..da726ce9a929
--- /dev/null
+++ b/docs/internal/realtime-cohorts/membership-output-and-readers.md
@@ -0,0 +1,287 @@
+# Membership output and its readers
+
+The processor's output is a stream of per-person `entered` and `left` changes.
+This page follows those changes to where they are used: a Node consumer writes them into a Postgres table, a mark-and-sweep removes rows no reconcile vouches for, and feature flags and workflows read the table.
+It uses terms from [live evaluation](live-evaluation.md), notably the processor's Stage 2 rows, one membership decision per cohort and person, and from [completion and readiness](completion-and-readiness.md), notably readiness stamps.
+
+## What the processor emits
+
+Most of the processor's topics are internal to the pipeline.
+Two of them are read outside it.
+
+**Membership changes**, one message per person, cohort and change, keyed by `person_id`:
+
+```json
+{
+ "team_id": 7,
+ "cohort_id": 42,
+ "person_id": "0192f0a1-...",
+ "last_updated": "2026-09-20 10:15:03.123456",
+ "status": "entered",
+ "origin": "reconcile",
+ "run_id": "01928c3e-..."
+}
+```
+
+- `status` is `entered` or `left`.
+- `last_updated` is the change's **version**: processing time with microseconds.
+ Each step of a partition's worker gets a stamp strictly newer than that worker's previous one.
+ All changes caused by one input message, and all rows of one reconcile page, share a stamp.
+ The worker keeps its last stamp only in memory.
+ After a restart or a partition move, the new worker's stamps follow the wall clock, so a clock that went back can stamp a newer change below an older one.
+- `origin` and `run_id` are set only by backfill: `seed` for seed apply, `reconcile` for reconcile.
+ Live changes carry neither.
+
+The processor's output topic is configured by `COHORT_MEMBERSHIP_CHANGED_TOPIC`.
+Its compiled default is `cohort_membership_changed_shadow`, which only a parity diagnostic reads, so a deployment must point it at `cohort_membership_changed` for the table to fill.
+
+**Reconcile markers**, on `cohort_reconcile_markers`, one per cohort, run and processor partition, produced after that partition's reconcile rows were all acknowledged:
+
+```json
+{
+ "type": "reconcile_complete",
+ "team_id": 7,
+ "cohort_id": 42,
+ "partition": 17,
+ "run_id": "01928c3e-...",
+ "last_updated": "..."
+}
+```
+
+The seeder reads markers to decide run completion.
+The membership consumer reads them to decide when stale rows may be deleted.
+
+The 64 processor partitions that markers count are unrelated to the partitions of the membership topic, which has its own count.
+
+## The `cohort_membership` table
+
+The table lives in a dedicated Postgres database for behavioral cohorts, separate from the main PostHog database.
+If the Node service has no URL for that database, it silently writes to the main Postgres instead.
+
+```text
+cohort_membership
+ team_id, cohort_id, person_id unique together
+ in_cohort true after entered, false after left
+ version the producer's last_updated; '-infinity' for a row no versioned write has touched
+ last_updated when the consumer wrote the row
+```
+
+The table holds `in_cohort = false` rows as well as members.
+Reconcile writes a `left` row for every person the processor holds a Stage 2 row for and who is not a member, so row count is not member count.
+Readers only trust `in_cohort = true`, and a missing row means "not a member".
+
+## The membership consumer
+
+A Node service in the CDP plugin server consumes `cohort_membership_changed` in batches.
+
+Two settings, both off by default, decide how much of what follows runs:
+
+- `COHORT_MEMBERSHIP_VERSION_WRITES_ENABLED` turns on the versioned, transactional write described below.
+ Without it, the consumer does one plain upsert per batch, and the last message in Kafka order wins.
+- `COHORT_MEMBERSHIP_SWEEP_ENABLED` turns on the marker consumer and the sweep.
+ It requires version writes and the marker topic.
+
+Each pod refuses the sweep without version writes, but nothing checks the pairing across the fleet.
+During a rolling change, a pod with version writes off writes rows without a new version, and a sweep on another pod can delete them even when a reconcile just asserted them.
+So turn version writes on across the whole fleet before turning the sweep on, and turn the sweep off before turning version writes off.
+
+With version writes on, for each batch the consumer:
+
+1. parses and validates every message,
+2. keeps one change per `(team, cohort, person)`: the highest version, with Kafka order breaking ties,
+3. runs one transaction that
+ - upserts the rows, applying a change only if its version is at least the stored version,
+ - for reconcile rows, records the lowest version each `(run, cohort)` wrote, its **snapshot minimum**,
+ - records, per topic partition, how far the consumer has applied,
+4. commits the Kafka offsets after the transaction.
+
+The version guard makes the consumer idempotent and safe against reordering, as far as the versions themselves are ordered.
+A replayed or late change cannot overwrite a newer one, and a crash only replays batches whose rows are already applied or rolled back.
+Versions are ordered only within one processor worker's tenure, as the field list above says.
+After a restart with a clock that went back, the guard can reject a newer change as stale.
+Recording progress in the same transaction as the rows means progress never claims rows that rolled back.
+
+A change with no `last_updated`, or with a non-empty one that does not match the producer's fixed-width format, is still applied, but without ordering: it overwrites the row whatever its version, and an off-format value is counted.
+A reconcile row like that also drags its run's snapshot minimum to the lowest possible value, so that run sweeps nothing.
+The consumer checks only the format, and it skips the check for an empty string.
+So an empty string, or a value in the right format that Postgres cannot read as a timestamp, such as one with a thirteenth month, reaches the database and fails the whole batch.
+
+A message that fails validation fails the whole batch every time.
+There is no dead-letter queue, so a malformed message stops the feed until it is skipped or the code is fixed.
+
+## Mark and sweep
+
+Live output is never retried, so it can lose changes, and a cohort edit or a person merge can leave rows that no longer match.
+Reconcile re-emits every person the processor holds a Stage 2 row for, but re-emitting only overwrites rows.
+It cannot remove a row for a person the processor no longer holds any row for, such as a person merged away.
+The sweep does that.
+
+The idea: every row a reconcile wrote carries a version at least as new as the oldest row that reconcile wrote.
+Any row of the cohort with an older version was not written by that reconcile, nor by anything since, so it is stale.
+
+```mermaid
+stateDiagram-v2
+ [*] --> collecting: first reconcile row or marker
+ collecting --> ready: all 64 markers,<br/>topic ends captured
+ ready --> sweeping: consumer has applied<br/>up to the captured ends
+ sweeping --> swept: no row below the threshold
+ sweeping --> ready: interrupted, or rows locked
+ collecting --> abandoned: no progress for days, or too old
+ ready --> abandoned: too old
+ sweeping --> abandoned: too old, or no usable threshold
+```
+
+A ledger row per `(run, cohort)` tracks the process.
+
+1. **Collecting.**
+ The consumer records the snapshot minimum as reconcile rows arrive.
+ A separate marker consumer sets one bit per processor partition as markers arrive, and records the lowest marker version.
+2. **Ready.**
+ When all 64 bits are set, the sweeper records the current end of every partition of the membership topic.
+ Every reconcile row was produced before its partition's marker, so every row of this snapshot sits below those ends.
+3. **Gate.**
+ The sweeper waits until the consumer fleet has applied the membership topic up to those ends.
+ Sweeping earlier would delete rows whose reconcile copies are still queued.
+4. **Sweep.**
+ The **threshold** is the lower of the snapshot minimum and the marker minimum.
+ The sweeper deletes the cohort's rows with a version below the threshold, in small pages, skipping rows another writer has locked.
+ A row the consumer refreshed in the meantime has a newer version and survives.
+5. **Swept.**
+ When no row below the threshold remains, the run is done.
+
+The threshold needs the snapshot minimum.
+Each partition stamps its marker after its own rows, so any marker, even the earliest, is newer than rows the run wrote.
+A threshold built from markers alone would delete rows the run had just re-asserted.
+Taking the lower of the two can only make the sweep delete less.
+
+The consumer knows nothing about Django's supersession.
+A run that an edit superseded after its reconcile was dispatched can still collect all 64 markers.
+The processor discards the remaining requests only when the edit moved the shape hash of the run's kind, and it cannot take back markers it already produced.
+A run with every marker sweeps like any other run.
+A run whose markers stay incomplete never leaves `collecting`, and it is abandoned after a few days.
+
+### What the table converges to
+
+After a swept reconcile, the table holds the processor's Stage 2 state for the cohort, plus any row written at or after the reconcile began.
+It converges to what the processor believes, not to the cohort's definition.
+A true member for whom the processor holds no Stage 2 row gets no reconcile row, and the sweep deletes their old row.
+
+Some rows are never swept:
+
+- when the sweep is disabled,
+- rows of a cohort that was never reconciled, or whose reconcile emitted nothing,
+- rows of a cohort whose run never completed its markers, for example because an edit moved its kind's shape hash before every partition reconciled, or a marker was lost,
+- rows of a cohort whose reconcile included a change with no usable version,
+- rows of a cohort that was deleted, made static, or left the realtime pipeline, once any run that already had every marker has swept,
+- rows of a team that is no longer enabled.
+
+## Feature flags
+
+The Rust flags service reads the table when a flag condition targets a realtime cohort.
+Its connection pool, cache and timeout settings are in [the flags service overview](../feature-flags/rust-service-overview.md#behavioral-cohorts), and its lookup metrics are in [database interaction patterns](../feature-flags/database-interaction-patterns.md#prometheus-metrics).
+
+### When a cohort is read from the table
+
+For each request on a team in `REALTIME_COHORT_EVALUATION_TEAM_IDS`, the flags service routes a cohort to the table only if:
+
+- the cohort's type is `realtime`, or the legacy `behavioral` type,
+- its `condition_type` marks a behavioral or lifecycle condition,
+- its [readiness stamps](completion-and-readiness.md#what-readiness-unlocks) satisfy the configured stamp policy.
+
+`condition_type` is derived by Django on save.
+A cohort whose `condition_type` is empty is never routed, and resaving it fills the column.
+
+Every other non-static cohort is evaluated dynamically from the person's properties, where a behavioral condition can never match.
+
+### How it reads
+
+1. The service collects every routed cohort among the cohorts in the team's flags payload, or among all the team's cohorts when the payload carries none.
+2. It makes at most one query per request for the person, for the routed cohorts its cache does not already hold: which of them have an `in_cohort = true` row.
+3. Answers are cached per pod, per team and person, for `COHORT_MEMBERSHIP_CACHE_TTL_SECONDS`, 60 seconds by default.
+ Adding a cohort to an existing entry restarts the timer for the whole entry, so an older answer can outlive the TTL.
+4. The routed cohorts' answers are merged into the cohort matches before flag conditions are evaluated.
+
+Because the routed set comes from every flag in the team's payload, one flag on a routed cohort adds this lookup to every request of the team that evaluates person properties.
+
+### When the read fails
+
+A query error, a timeout, or a person with no known id makes every routed cohort **false** for that request.
+A condition "in cohort 42" then fails, and a condition "not in cohort 42" **passes**.
+The error is counted and logged, and not cached.
+
+If the team list is set but `BEHAVIORAL_COHORTS_READ_DATABASE_URL` is empty, the service installs a provider that answers false for every routed cohort on every request.
+
+### Authoring versus reading
+
+Django decides whether a flag may be saved with a realtime cohort.
+Behind the realtime targeting rollout flag, it accepts a cohort with event-based criteria only when the cohort is flag-compatible, meaning every readiness stamp its filters need is set.
+
+The flags service never reads that rollout flag.
+It decides, per request, where to read membership from, using its own routing rules.
+An existing flag keeps being evaluated whatever the rollout flag says, and the stamp policy can accept fewer stamps than Django requires.
+
+## Workflows
+
+The workflows executor reads the table from `conditional_branch` and `wait_until_condition` actions whose compiled condition calls `inCohort` or `notInCohort`.
+When evaluation reaches such a condition, it loads the person's full set of `in_cohort = true` cohorts once per action and passes it to the condition.
+An invocation with no person is a non-member of every cohort.
+
+A failed lookup fails the action, and the lookup is not retried.
+With `abort`, the run stops.
+With the default error handling, the run takes the action's continue edge at once.
+For `conditional_branch` that is the same edge it takes when no condition matches.
+For `wait_until_condition` it is not: an unmatched wait with a maximum duration checks again until its deadline, but a failed lookup ends the wait immediately.
+
+No workflow save path compiles a cohort condition yet: the compiler rejects cohort filters in workflow conditions.
+This read path is therefore dormant.
+
+## Worked example
+
+Team 7 has cohort 42, "performed `$pageview` in the last 30 days", with its events readiness stamp set.
+The flags service has team 7 in its reader list, and flag `new-checkout` targets cohort 42.
+The table starts with:
+
+| person | in_cohort | version | how it got there |
+| ------ | --------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
+| p-2 | true | 2026-08-10 09:00:00 | a live `entered`. On 2026-09-10 the sweep expired p-2 and wrote `false` in the processor, but the `left` produce failed, so this row is stale |
+| p-3 | true | 2026-08-20 08:00:00 | a live `entered`. On 2026-09-15 p-3 was merged into p-1, and the merge deleted p-3's Stage 2 rows without emitting anything |
+
+**A live change.**
+On 2026-09-20 at 10:15 p-1 enters cohort 42.
+The consumer upserts `(7, 42, p-1, true, version 10:15:03.123456)` and records its progress on the topic partition, in one transaction.
+
+**A reconcile.**
+On 2026-09-21 at 03:00 a reconcile runs for cohort 42.
+
+1. The processor re-emits every Stage 2 row of the cohort:
+ p-1 `entered` at 03:00:00.514002, and p-2 `left` at 03:00:00.214331 from its stored `false`.
+ The processor holds no row for p-3, so nothing is emitted for p-3.
+2. The consumer applies both rows.
+ p-2's row becomes `in_cohort = false`.
+ The ledger row for the run records a snapshot minimum of 03:00:00.214331.
+3. All 64 markers arrive.
+ At its next tick, the sweeper records the membership topic's ends and waits until the consumer has applied up to them.
+4. Assuming no marker is older, the threshold is 03:00:00.214331.
+ The sweeper deletes cohort 42's rows with an older version: p-3's row goes.
+ p-1 and p-2 are newer and stay.
+
+**A flag request.**
+At 03:05, `/flags` for p-1 routes cohort 42 to the table.
+The query finds `in_cohort = true` for cohort 42, so the condition matches.
+The same request for p-2 finds `in_cohort = false`, and for p-3 finds no row, so neither is in cohort 42.
+Before the reconcile, both p-2 and p-3 would have matched.
+
+## Things that surprise people
+
+- `cohort_membership.last_updated` is when the consumer wrote the row.
+ The producer's version is in `version`.
+- A table in ClickHouse is also named `cohort_membership`.
+ It is a separate, legacy copy, and the flags service does not read it.
+- The processor's changes reach flags through several hops: Kafka, the consumer's batch, the database through the flags service's read connection, and the flags pod's cache.
+ Workflows read through the Node services' read-write pool for that database and do not cache.
+- A readiness stamp does not mean the consumer has applied the reconcile or that the sweep has run.
+- The partition count, 64, is also a constant in the Node consumer.
+ If the processor ran fewer partitions, no run would ever complete its bitmap, and no sweep would ever run.
+- A cohort that references a realtime cohort and is itself evaluated dynamically does not use the table answer for the referenced cohort.
+ The referenced cohort is recomputed dynamically, where its behavioral leaves are false.
+ Django still lets such a flag be saved, because it checks the referenced cohort's readiness, not how it will be read.
diff --git a/docs/internal/realtime-cohorts/merges-and-cascades.md b/docs/internal/realtime-cohorts/merges-and-cascades.md
new file mode 100644
index 000000000000..fb45209d6822
--- /dev/null
+++ b/docs/internal/realtime-cohorts/merges-and-cascades.md
@@ -0,0 +1,243 @@
+# Person merges, cascades and Stage 2 cleanup
+
+This page covers three mechanisms that change membership without a plain event for the person:
+
+- **person merges**, when ingestion merges one person into another and the processor must move the merged-away person's state onto the survivor,
+- **cascades**, when a cohort references another cohort and the referenced cohort's membership flips,
+- **Stage 2 garbage collection**, when a cohort leaves the catalog and its stored membership rows must go.
+
+It assumes [live evaluation](live-evaluation.md), especially leaf state, replay marks and Stage 2 rows, and the offset tracking in [processor runtime](processor-runtime.md#offset-tracking).
+
+## Person merges
+
+### Why the processor must handle merges
+
+When ingestion identifies two persons as the same user, it merges the old person into a new one in Postgres.
+From then on, every event of that user carries the new person id.
+But the processor keyed all the old person's history under the old id, and possibly on another partition.
+Without help, the survivor would be missing everything the old person did.
+A survivor with one `/pricing` pageview would stay out of "3 or more pageviews" even though the user made three.
+
+So the processor moves the old person's leaf state onto the survivor and folds it in.
+
+### Where merges come from
+
+After a person merge commits in Postgres, Node ingestion produces a message to `person_merge_events`.
+In this example `p-2` and `p-1` stand for person UUIDs:
+
+```json
+{ "team_id": 7, "old_person_uuid": "p-2", "new_person_uuid": "p-1", "merged_at_ms": 1789912800000, "schema_version": 1 }
+```
+
+The key is `"{team_id}:{old_person_uuid}"`, so the message lands on the old person's partition.
+The producer is gated per team and best effort.
+A failed send is logged and dropped.
+
+### The protocol
+
+A merge runs in two phases, one on each person's partition.
+
+```mermaid
+sequenceDiagram
+ participant Node as Node ingestion
+ participant W17 as Worker 17 (old person p-2)
+ participant T as cohort_merge_state_transfer
+ participant W26 as Worker 26 (survivor p-1)
+ participant Out as membership output
+ Node->>W17: person_merge_events (key 7:p-2)
+ Note over W17: drain: one atomic batch<br/>outbox entry, drain marker,<br/>delete p-2 state, tombstone p-2
+ W17->>T: transfer (key 7:p-1)
+ Note over W17: on ack, clear outbox,<br/>mark merge offset
+ T->>W26: transfer
+ Note over W26: apply: merge each leaf into p-1,<br/>apply marker, one atomic batch
+ W26->>Out: entered / left for p-1
+```
+
+**Drain, on the old person's worker.**
+
+1. Check the drain marker, keyed by the merge message's partition and offset.
+ If this merge was already drained, skip the drain, and if its outbox entry is still there, produce it again.
+2. Read all of the old person's behavioral rows with one prefix scan, and the replay marks from its person record.
+3. Work out where the survivor lives.
+ The processor computes the survivor's partition with the same partitioner everything else uses.
+4. Commit one atomic batch that removes the old person and leaves a forwarding address:
+ - delete the old person's leaf rows and person record, and the Stage 2 rows of every cohort the current catalog tracks,
+ - write a **tombstone** that maps the old person to the survivor,
+ - write the drain marker,
+ - if the survivor is on another partition and the old person has state to move, write an **outbox** entry holding that state.
+5. If the survivor is on the same partition, the same batch also merges the state into the survivor directly.
+ This is the fast path: no transfer and no apply marker.
+ The worker then produces the survivor's membership changes, as in apply step 4.
+6. Otherwise, produce the outbox entry to `cohort_merge_state_transfer`, keyed by the survivor.
+ After the acknowledgment, clear the outbox and mark the merge offset.
+ If there was nothing to move, mark the offset without producing.
+ If the produce keeps failing, the outbox entry stays and a periodic redrive retries it.
+
+Stage 2 rows of cohorts no longer in the catalog are left for Stage 2 garbage collection.
+
+**Apply, on the survivor's worker.**
+
+1. Skip if this transfer was already applied on this partition.
+ An apply marker keyed by the original merge message's coordinates records that, so duplicates produced by redelivery, redrive or a retried send are all recognized.
+2. If the survivor was itself merged away in the meantime, follow its tombstone.
+ Apply to the final survivor on this partition, or forward the transfer to the next survivor's partition, which keeps resolving, up to a hop limit.
+3. Read the survivor's rows for every transferred leaf in one batched read, merge each pair, and commit the result with the apply marker in one atomic batch.
+4. Map any leaf flips to membership changes, run Stage 2 for composed cohorts, and produce the changes.
+
+Apply markers are local to a partition.
+If a chain later grows onto another partition, a duplicate that follows it there can apply twice.
+
+### How two states merge
+
+Each leaf merges according to its variant.
+
+| Variant | Merge rule |
+| ------------------ | ------------------------------------------------------------------------------------------- |
+| `BehavioralSingle` | Matched if either matched. Keep the newer match time and the later deadline |
+| Daily buckets | Slide both windows to the more recent window start, then add the counts day by day |
+| Compressed history | Slide both to the more recent window start, then combine counts by day |
+| Replay marks | The survivor keeps its own marks. The old person's marks are kept under the old person's id |
+
+A daily window starts N days before the newest day it has counted, so the two persons' windows can start on different days.
+Aligning them first is what makes the day-by-day sum line up.
+
+Adding counts is right because each live event was folded into exactly one of the two persons.
+One narrow race breaks that: a backfill tile scanned after the merge, which already counts the old person's events under the survivor, can land on the survivor before the transfer does.
+
+The replay-marks rule matters for late events.
+An event for the old person that is re-addressed to the survivor keeps its own firehose coordinates, the event's partition and offset on the ingestion topic.
+The survivor checks them against the marks kept under the old person's id.
+An event the old person already counted is skipped, and a new one is counted.
+
+A leaf that the survivor's current catalog no longer knows is dropped.
+The person record does not travel: the survivor's matched person conditions follow its own person properties on its next event.
+When register transfer is enabled with `COHORT_REGISTER_TRANSFER_ENABLED`, the old person's Stage 2 rows ride along too, but they only fill rows the survivor lacks.
+
+### Stragglers and tombstones
+
+Events for the old person keep arriving for a while after the merge.
+Every event first checks for a tombstone on its person.
+
+- If the survivor is on the same partition, the worker rewrites the event to the survivor and folds it in place.
+- If the survivor is on another partition, the worker re-produces the event to `cohort_stream_events` keyed by the survivor.
+- Chains such as `A → B → C` are followed through successive tombstones, with a hop limit that stops a corrupt cycle.
+
+Drain and apply markers are kept one day longer than the merge and transfer topics' retention, measured from the merge time, so a redelivered merge still finds its marker.
+Tombstones are kept one day longer than a late event can take to arrive.
+Both are settings sized to the topic retentions, and nothing checks that they still match.
+
+The outbox is never garbage-collected.
+Until the transfer is acknowledged, it is the only copy of the old person's state.
+A partition revoke still deletes it with the rest of the slice.
+
+### Worked example
+
+Cohort 44 on team 7 is a single leaf: 3 or more `/pricing` pageviews in the last 30 days.
+Single-leaf cohorts also keep a Stage 2 row, the processor's last decision for the person.
+Person p-2 lives on partition 17 and made two matching pageviews, on 2026-09-18 and 2026-09-19.
+Person p-1 lives on partition 26 and made one, on 2026-09-20.
+Neither is a member.
+
+1. On 2026-09-20, ingestion merges p-2 into p-1 and produces the merge message to partition 17.
+2. Worker 17 drains p-2.
+ p-1 is on partition 26, so this is the slow path.
+ One batch writes the outbox entry, the drain marker and a tombstone `p-2 → p-1`, and deletes p-2's rows.
+3. Worker 17 produces the transfer to partition 26, then clears the outbox and marks the merge offset.
+4. Worker 26 applies it.
+ p-2's window starts one day earlier than p-1's, so p-2's buckets slide by one day.
+ The counts add up to 3 across 2026-09-18, 2026-09-19 and 2026-09-20.
+5. `gte 3` flips to true.
+ The batch writes p-1's merged row, a Stage 2 row for cohort 44 and the apply marker.
+ The row's new deadline comes from its oldest counted day, 2026-09-18.
+6. Worker 26 produces `entered` for cohort 44 and p-1.
+
+A few seconds later a p-2 pageview that was in flight reaches worker 17.
+The tombstone points to p-1 on partition 26, so worker 17 re-produces the event keyed by p-1.
+Worker 26 checks it against p-2's marks, finds it new, counts it, and p-1's total becomes 4 without a flip.
+
+### What merges do not do
+
+- **No `left` for the old person.**
+ The drain deletes the old person's state silently.
+ Downstream rows for the old person stay until the next backfill of that cohort.
+ Its reconcile does not re-tell the old person, because the drain deleted the old person's Stage 2 rows, so the downstream sweep deletes those rows.
+ Reconcile runs only as part of a backfill.
+- **Merge output is at most once.**
+ Merge state is applied once and survives failures, but membership changes are produced after the state commits.
+ A lost change is repaired only by reconcile.
+ [Processor runtime](processor-runtime.md#delivery-semantics) explains what at most once does and does not rule out.
+- **A lost merge message is never detected.**
+ The old person's state stays under the old id, the survivor under-counts, and stragglers keep folding into the old person.
+ A backfill gives the survivor the right counts, because the seeder resolves persons through the merge overrides in ClickHouse.
+ The old person's leftover state is not removed by it.
+- **A cross-partition transfer that keeps failing blocks the old person's worker**, and so every event on that partition, for up to about half a minute of inline retries, before the redrive takes over.
+
+## Cascades: cohorts that reference cohorts
+
+A cohort can include another cohort as a leaf: "in cohort 51 and email is set".
+Its membership depends on the referenced cohort's membership, which the processor also computes.
+When cohort 51 flips for a person, every cohort that references 51 must be recomposed for that person.
+
+Cascades are disabled by default, and `COHORT_CASCADE_ENABLED` turns them on.
+With cascades off, a cohort that holds any cohort reference is excluded and emits nothing.
+With cascades on, the catalog promotes a referencing cohort to `Stage2ComposableRef` when every cohort it references positively is in the team's catalog and itself single-leaf or composable, and there is no reference cycle.
+
+A reference reached only through negation never blocks promotion.
+A missing referenced cohort reads as "not a member", and negated that is "true".
+That answer is wrong for anyone who really is in the untracked cohort.
+"Email is set and not in cohort X", with X static or not realtime, matches every person with an email, including X's real members.
+
+### How a cascade flows
+
+1. With cascades on, every membership flip produces a **cascade message** keyed `"{team}:{person}"` to `cohort_cascade_events`, whether or not any cohort references the flipped one.
+ This applies to flips on the live, merge, sweep, seed-apply and reconcile paths.
+ The sweep and reconcile send them only for recomposed cohorts.
+ The message carries the flipped cohort, a depth, and the chain of cohorts visited so far.
+2. The topic is co-partitioned with the event stream, so the message comes back to the same worker, the one that owns the person's state.
+3. The worker finds every cohort that references the flipped cohort and recomposes each referrer that composes.
+ It reads a single-leaf referenced cohort from its leaf state, a composed one from its Stage 2 row, and an untracked one as not a member.
+4. For each referrer that flips, it produces the membership change and, if the chain may continue, a further cascade message.
+5. Only after both produces are acknowledged does it write the referrers' new Stage 2 bits and mark the offset.
+ A failure pins the partition's cascade commit at that message.
+ Kafka redelivers it after the next restart or rebalance, and the redelivered message recomputes the same flip.
+ Until then, cascade commits for that partition stall.
+
+Three limits bound the work:
+
+- a **depth cap** on onward hops,
+- a **cycle check**: a hop to a cohort already in the message's chain is dropped,
+- a **fan-out cap** on how many referrers one message considers.
+ Referrers past the cap are not recomposed.
+
+Cycles are also removed at catalog build, where any cohort in a reference cycle is excluded.
+
+### Cascade caveats
+
+- First cascades on the live, merge and sweep paths are produced after the flip is committed, so a lost one is not retried.
+ Seed apply and reconcile produce before they write state, so theirs are retried.
+- A sweep expiry of a single-leaf cohort produces no cascade.
+- A referrer that missed a cascade catches up only when one of its own leaves flips.
+- A cohort built only from references has no leaves of its own.
+ It is recomposed only by cascades.
+ Django never creates a backfill run for it, so no reconcile covers it either.
+
+## Stage 2 garbage collection
+
+When a cohort is deleted, stops being realtime, or becomes excluded, its Stage 2 rows are useless.
+Once an hour each worker scans a bounded slice of its Stage 2 rows and deletes rows whose cohort no longer registers membership in the current catalog.
+It resumes from a cursor, so large partitions are covered over several runs.
+
+Rows received through a merge are the exception.
+With register transfer enabled, a merge records a person-first inventory entry for each row it moves onto the survivor, and the collection never deletes a row that still has one.
+The protection ends when the row is deleted, when a local evaluation overwrites it, or when the current catalog registers the cohort with the same register kind the transfer carried.
+A catalog that registers the cohort with a different kind, for example after an edit from one leaf to two, does not end it, and only a local evaluation does.
+Absence from the catalog alone does not end it either, so a transferred row for a cohort that never comes back stays, with its inventory entry.
+
+Two gates protect it.
+It never runs before the first catalog load, and it never runs when the catalog is empty, because an empty catalog after a database hiccup would otherwise wipe everything.
+
+The collection deletes rows without producing `left`.
+Downstream rows for a deleted cohort are not retracted by the processor.
+
+Behavioral leaf rows orphaned by an edit are not collected.
+They stay until a merge drain or a partition wipe removes them.
diff --git a/docs/internal/realtime-cohorts/processor-runtime.md b/docs/internal/realtime-cohorts/processor-runtime.md
new file mode 100644
index 000000000000..e086a2d12c41
--- /dev/null
+++ b/docs/internal/realtime-cohorts/processor-runtime.md
@@ -0,0 +1,282 @@
+# Processor runtime
+
+This page describes the skeleton of `cohort-stream-processor`: how it consumes its topics, how work reaches the per-partition workers, how offsets are tracked and committed, and what each path guarantees about delivery.
+What a worker does with one event is in [live evaluation](live-evaluation.md).
+How state is stored is in [state store and durability](state-store-and-durability.md).
+
+## The shape of the process
+
+The processor is deployed as one pod, which owns every partition, 64 by default.
+Inside it, one worker task per partition owns that partition's slice of an embedded RocksDB store.
+Everything that can change a person's state reaches that person's worker, in order, through two queues called lanes.
+
+```mermaid
+flowchart TB
+ subgraph Kafka inputs
+ E[(cohort_stream_events)]
+ M[(person_merge_events)]
+ T[(cohort_merge_state_transfer)]
+ C[(cohort_cascade_events)]
+ S[(cohort_stream_seed_events)]
+ end
+ E --> EC[Events consumer<br/>the only group member]
+ M --> F[Follower consumers<br/>mirror the events assignment]
+ T --> F
+ C --> F
+ S --> SF[Seed follower]
+ EC -->|live lane| R[Partition router]
+ F -->|live lane| R
+ SF -->|seed lane| R
+ R --> W1[Worker p0]
+ R --> W2[Worker ...]
+ R --> W3[Worker p63]
+ W1 --> DB[(RocksDB<br/>one store, sliced by partition)]
+ W1 --> Out[(membership output,<br/>cascades, transfers, markers)]
+```
+
+Timers feed the same workers.
+The eviction sweep, the pending-transfer redrive, merge garbage collection and the reconcile drain all send messages through the router instead of touching the store themselves.
+So while a worker runs, it is the only writer of its partition, and nothing needs a lock.
+Boot recovery and revoke cleanup are the only code that touches a slice from outside its worker.
+Revoke cleanup waits for the worker to exit.
+Boot recovery is meant to finish before any worker starts, but nothing enforces that, as [startup](#startup) explains.
+
+## Consumers and ownership
+
+The **events consumer** is the only consumer that joins a Kafka consumer group with a real assignment.
+It reads `cohort_stream_events` with cooperative-sticky assignment and static membership, so a quick restart reclaims the same partitions without a rebalance.
+
+**Follower consumers** read the other co-partitioned topics.
+Merges and merge transfers always have one.
+Cascades and seeds have one when those features are enabled.
+Followers never subscribe.
+Whenever the events consumer is assigned or revoked a partition, the followers are assigned or unassigned the same partition number, resuming at their group's committed offsets.
+One rebalance decides ownership of partition N on every input topic at once, which is what [partition affinity](event-routing.md#partition-affinity) needs.
+
+The merge, transfer, cascade and seed followers start only after the first catalog load.
+The events consumer does not wait.
+
+Workers spawn lazily, on the first message for an owned partition.
+A **tenure** is the time a worker owns a partition, from an assignment to the next revoke or restart.
+
+## From a Kafka batch to a worker
+
+The events consumer reads batches of up to a thousand messages.
+It splits each batch by partition and offers each sub-batch to that partition's live lane without waiting.
+
+Each partition has an **intake budget**, a cap on events sitting in its live lane.
+When a partition is over budget or its lane is full, the sub-batch goes into a holdover, and a separate task pauses fetching for that partition in the Kafka client.
+Held sub-batches are retried first on every cycle, so a newer message never overtakes an older one.
+When the holdover drains, the partition resumes.
+
+The consume loop never waits on a worker.
+A slow partition turns into lag on that partition only.
+The consumer keeps polling and keeps reporting itself alive, other partitions keep flowing, and the pod does not look stalled to its liveness check.
+A blocking send on a full lane would stop that liveness report and get the pod restarted in a loop.
+
+Merge, transfer and cascade followers also use the live lane, but they do not count toward the intake budget, and their dispatch waits when the lane is full.
+Their topics carry little traffic.
+Waiting there cannot block the events consumer, but one full lane stalls that follower topic, and its commits, on every partition until the lane drains.
+
+The seed follower uses the separate **seed lane** and never waits.
+A full seed lane holds the seeds and pauses that partition, like the events consumer does.
+[Seed apply and reconcile](seed-apply-and-reconcile.md) describes the seed follower's admission rules.
+
+## The worker loop
+
+Each worker drains two lanes:
+
+- the **live lane**, carrying events, merges, transfers, cascades and timer messages in partition order,
+- the **seed lane**, carrying backfill tiles, person seeds and reconcile requests.
+
+On every turn the worker picks one unit of work in this priority order:
+
+1. a batch of the eviction sweep, if a live batch ran since the last sweep batch,
+2. the next live sub-batch,
+3. a sweep batch, when there is no live work,
+4. the next run of the current seed quantum,
+5. a new seed quantum, only when no run is pending.
+
+Seed runs wait behind live work, and live work waits at most one seed run.
+Reconcile is the exception: a reconcile request only queues a job, and the job's page walks run as a timer message on the live lane, one bounded page per tick.
+The sweep alternates with live batches, so a large wave of expirations at midnight cannot starve live events, and a flood of live events cannot starve expirations.
+[Time and eviction](time-and-eviction.md) explains the sweep.
+
+Each live sub-batch holds one topic's messages, or one timer tick, in offset order.
+As a guard, before any merge, transfer, cascade, sweep or reconcile message, the worker first produces the membership changes it has buffered, so the order of output matches the order of state changes.
+It yields to the async runtime every few milliseconds, so a CPU-heavy backlog cannot starve other tasks.
+
+At the end of an events sub-batch the worker:
+
+1. produces its membership changes and waits for every acknowledgment,
+2. produces first-hop cascade messages, when cascades are enabled,
+3. re-keys events for merged persons to their survivor's partition,
+4. marks the events tracker at the highest event offset of the sub-batch,
+5. advances the partition's live watermark to the newest broker timestamp it folded.
+
+If any produce fails, the worker skips the mark.
+Merge, transfer and cascade messages settle their own trackers as each one is handled.
+
+## Offset tracking
+
+Each input topic has its own offset tracker with five values per partition.
+
+| Value | Meaning |
+| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| dispatched | The ceiling: one past the highest offset handed to the worker. For events and seeds it counts only what landed in the lane |
+| processed | One past the highest offset a handler marked finished. It is a running maximum that never passes dispatched, so an earlier offset that failed without setting a floor is passed over |
+| held | A sticky floor at a failed message's own offset. Used by the merge, cascade and seed paths |
+| deferred | Releasable floors, used for reconcile requests, which finish long after they arrive |
+| committed | The next offset to consume, as last sent to Kafka |
+
+The committable offset is the lowest of processed, held and every deferred floor.
+A later success can never commit past an earlier failure that set a floor.
+
+Every few seconds, each consumer snapshots its committable offsets, forces the RocksDB write-ahead log to disk, and commits the snapshot only if the flush succeeded.
+The events consumer does this on its own task, and the followers do it in their consume loops.
+This is the durability invariant: **a committed offset never runs ahead of state that is on disk**.
+Hot-path writes do not wait for the disk, so this one flush per commit is what makes them durable.
+
+## Delivery semantics
+
+Different paths make different promises.
+This table is worth knowing before you debug a missing or duplicated membership change.
+
+| Path | Guarantee | Why |
+| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Events into Stage 1 state | At least once across restarts, applied once, except the batch described in [startup](#startup). Within a tenure, an event whose fold fails on a store error, or whose re-key to a survivor's partition fails, is skipped and later committed past | Offsets commit after the work. A redelivered event is recognized by its replay marks. Only the merge, cascade and seed paths hold a failed offset |
+| Event to membership change | At most once | State commits inside the fold, before the produce. If the produce fails, the next clean sub-batch marks past it, and a replay finds no transition to emit |
+| First-hop cascade messages | At most once from the live, merge and sweep paths. At least once from seed apply and reconcile | The live, merge and sweep paths produce them after the flip is committed. Seed apply and reconcile produce them before writing the flip, and retry on failure |
+| Sweep expiry of a single-leaf cohort | At least once while the worker runs | The sweep produces before it writes, and reschedules the keys on failure. The retry lives in the in-memory queue, so a restart keeps it only with durable restore on |
+| Sweep expiry that recomposes a cohort | At most once | The composed result is written before it is produced |
+| Cascade messages consumed | At least once | Produce before state, and a failure holds the offset |
+| Merge state | At least once, applied once | Drain and apply markers keyed by the original merge message |
+| Merge state transfer | At least once while the partition stays assigned | An outbox row survives until the transfer is acknowledged, and a timer redrives it. A revoke deletes the row with the slice, and later merges may already have committed past its merge offset |
+| Merge membership output | At most once | State commits before the produce, and a failed produce is dropped |
+| Backfill seed runs | At least once | A failure holds the run's first offset, and the seed replays on the next tenure. A redelivered seed re-emits a change that was lost |
+| Reconcile | At least once | A failed page retries on the next tick, and a deferred floor keeps the request uncommitted until the job completes |
+
+So live, merge, sweep-recompose and their first-hop cascade output can all lose a membership change, and nothing on those paths puts it back.
+The pipeline accepts that and relies on reconcile, run as part of every backfill, to re-emit the full membership of a cohort.
+Reconcile re-emits from stored state, so it repairs a lost change but not a lost Stage 1 write.
+[Backfill overview](backfill-overview.md) covers reconcile, and [membership output and readers](membership-output-and-readers.md) explains how the consumer tolerates duplicates.
+
+"At most once" here means the path never retries a failed produce.
+It is not a promise against duplicates.
+Writes reach the disk only at the next commit's flush, while output is acknowledged as soon as it is produced.
+A host crash that loses unflushed writes rolls state back to the last flush, and the replayed inputs can emit the same changes again.
+A wiped store does the same.
+
+## Rebalance and the single-pod constraint
+
+When the events consumer loses a partition, the processor:
+
+1. stops routing to the partition and unassigns the followers,
+2. lets the worker drain both lanes and exit,
+3. forgets every tracker's progress for the partition without committing it,
+4. deletes the partition's slice of the store.
+
+If a cooperative rebalance hands the partition straight back, the cleanup is skipped and the slice is kept.
+
+State never moves with a partition.
+Whoever owns the partition next, even the same pod later, starts from an empty slice at the last committed offset.
+It rebuilds no history, so every cohort on that partition is wrong until a backfill runs.
+That is why the processor runs as a single pod that owns every partition.
+Nothing moves state between pods, so more than one replica is unsupported, and running two would corrupt state without any error.
+
+## Startup
+
+At boot the processor:
+
+1. validates its configuration and refuses unsafe combinations,
+2. loads the catalog once,
+3. decides where the store comes from: with durable restore enabled, the live store on disk or a checkpoint, otherwise an empty store,
+4. checks the partition counts of the co-partitioned topics against broker metadata,
+5. starts the timer loops, the followers once the catalog has loaded, and the events consumer.
+
+By default the store is wiped at boot.
+With durable restore enabled, a restart reopens the same local store instead, and a worker that spawns rebuilds its in-memory eviction queue by scanning its slice of behavioral state.
+[State store and durability](state-store-and-durability.md) covers the restore order.
+
+With durable restore enabled, the events consumer also runs boot recovery once its assignment settles.
+It deletes the slices of partitions it does not own, and re-produces every transfer waiting in the merge outbox, clearing each outbox row from outside the worker.
+The ordering has a gap.
+The events consumer dispatches polls that arrive before its assignment settles, and the followers start after the first catalog load without waiting for boot recovery.
+So a worker can already be running while the boot redrive clears outbox rows on its partition.
+The code does not prevent this, although no failure from it has been reproduced.
+
+Boot recovery also loses events.
+The poll on which the assignment settles runs the redrive and then skips dispatching the batch it already pulled, up to a thousand events.
+Without a restore manifest, which covers every reopen of the live store and every cold start, no seek rewinds the partition.
+The next batch moves the offsets past the skipped events, so they are committed without ever reaching Stage 1 state, and reconcile cannot bring them back.
+
+## Store access lanes
+
+By default workers reach RocksDB through a handle that runs blocking I/O on a thread pool, so RocksDB calls never block the async runtime.
+Store operations take permits from two pools, which cap how many run at once per kind of work:
+
+- the **maintenance** pool covers the sweep's state reads, merge drain and apply, garbage collection, reconcile pages and backfill seed runs,
+- the **event** pool covers live-path reads, and Stage 2 recomposition on the live, sweep, merge and cascade paths.
+
+The maintenance pool is smaller, so background work cannot take all store concurrency away from live traffic.
+Plain writes and the write-ahead-log flush take no permit.
+A maintenance section's writes run while it holds its maintenance permit.
+
+## Worked example: one event's offset
+
+Partition 26's events tracker reads `dispatched 1204560, processed 1204560, committed 1204501`.
+Durable restore is enabled.
+
+1. The consumer reads a batch that holds offsets 1204560 to 1204567 for partition 26.
+2. The intake budget admits the 8 events.
+ The lane accepts the sub-batch, and dispatched becomes 1204568.
+3. The worker folds the 8 events.
+ The last one, 1204567, is a `$pageview` from p-1.
+ Its fold commits the new leaf state to RocksDB without waiting for the disk.
+ The leaf flips, so cohort 42 gets an `entered` change for p-1.
+4. At the end of the sub-batch, the worker produces the change and waits for the acknowledgment.
+ Processed becomes 1204568.
+5. On the next commit tick, the task flushes the write-ahead log and commits 1204568.
+
+Three variations show the edges.
+
+- **Backpressure.** If partition 26 already held more than 1,016 events, the default budget of 1,024 would refuse these 8.
+ The sub-batch would go to the holdover and fetching for the partition would pause.
+ Dispatched would stay at 1204560 until the worker caught up.
+- **Produce failure.** If the produce in step 4 failed, processed would not move.
+ But the leaf state is already committed.
+ When the next sub-batch succeeds, processed jumps past 1204567, and the `entered` is never emitted on the live path.
+ A restart before that would replay 1204567 against the reopened store, see it as a duplicate, and still emit nothing.
+ Only reconcile repairs it.
+- **Revoke.** If partition 26 were revoked between steps 4 and 5, the commit would never happen.
+ The slice would be deleted, and the next owner would start empty and replay from 1204501.
+
+## Optimizations
+
+- **Non-blocking dispatch with per-partition pause.**
+ Backpressure becomes lag on one partition instead of a stalled consumer.
+- **An intake budget counted in events.**
+ Lane capacity counts sub-batches of any size, so the event budget is what bounds memory on a busy partition.
+- **A separate seed lane with live priority.**
+ Backfill work gets its own bounded queue, and each worker checks live work first.
+ Together with batched seed apply, this keeps live freshness close to real time while a large backfill is applying.
+- **A bounded, interleaved sweep.**
+ Expirations run in small batches that alternate with live batches, instead of one pass that holds the worker and a large working set in memory.
+- **I/O on a thread pool, with two permit pools.**
+ RocksDB calls never block the async runtime, and background work cannot use up all store concurrency.
+- **One WAL flush per commit, not per write.**
+ Writes stay fast, and the durability invariant still holds at every commit.
+
+## Things that surprise people
+
+- Log lines on a failed produce say the offset is held for replay.
+ On the event path it is not.
+ Only the merge, cascade and seed paths hold.
+- The events consumer does not wait for the catalog.
+ If the first catalog load fails, events are consumed, skipped for lack of definitions, and committed.
+- A revoke does not commit.
+ Anything processed since the last commit replays on the next owner.
+- A held offset stays held for the rest of the partition's tenure.
+ With one pod, that means until the next restart, and the symptom is growing lag on that topic and partition.
+- A timer message does not spawn a worker.
+ After a restart, a partition's overdue evictions wait until its first message arrives.
diff --git a/docs/internal/realtime-cohorts/seed-apply-and-reconcile.md b/docs/internal/realtime-cohorts/seed-apply-and-reconcile.md
new file mode 100644
index 000000000000..5bb61618d44f
--- /dev/null
+++ b/docs/internal/realtime-cohorts/seed-apply-and-reconcile.md
@@ -0,0 +1,305 @@
+# Seed apply and reconcile
+
+This page covers the processor's side of backfill: how seeds get from `cohort_stream_seed_events` into leaf state without disturbing live traffic, how their membership changes are emitted, and how reconcile re-tells downstream the full membership of a cohort.
+Read [backfill overview](backfill-overview.md) first for the boundary, max-merge and fence rules this page implements.
+In short: `S_chunk` is the instant a seeder chunk was claimed, and the scan counts only events that reached ClickHouse before it.
+A shape hash fingerprints a cohort's leaves of one kind, and a reconcile request carries the pinned one.
+
+Three kinds of message arrive on the seed topic:
+
+- **day tiles** from behavioral runs,
+- **person seeds** from person runs,
+- **reconcile requests**, one per cohort per partition, sent after a run's seeds.
+
+Messages the processor cannot decode, of an unknown kind, or with a newer schema are counted and skipped in order, so they never stall a partition.
+
+```mermaid
+flowchart LR
+ Topic[(cohort_stream_seed_events)] --> Adm{Seed follower<br/>admission gates}
+ Adm -->|held| Hold[Holdover,<br/>partition paused]
+ Hold --> Adm
+ Adm -->|admitted| Lane[Worker seed lane]
+ Lane --> Runs[Runs of tiles<br/>or person seeds]
+ Lane --> Queue[Reconcile queue]
+ Runs --> Out[(membership output<br/>origin seed)]
+ Tick[Drain tick<br/>on the live lane] --> Queue
+ Queue --> Out2[(membership output<br/>origin reconcile)]
+ Queue --> Markers[(reconcile markers)]
+```
+
+## Admission: the seed consumer
+
+The seed consumer is a follower of the events consumer.
+It is assigned exactly the partitions the events consumer owns, so every seed reaches the worker that owns its person.
+It starts only after the first catalog load.
+
+Each poll, it decides per partition which seeds may go to the worker now.
+
+- **The fence.**
+ A day tile may apply only when the partition's **live watermark** is past the tile's `S_chunk` plus a margin, `COHORT_SEED_FENCE_MARGIN_MS`, 10 minutes by default.
+ The live watermark is the newest broker timestamp of a live event the worker has folded and marked processed.
+ It is reset whenever the partition is assigned, and a partition with no watermark keeps its fence closed.
+ Person seeds and reconcile requests have no fence of their own.
+- **The idle probe.**
+ A quiet partition may receive no live events for a long time, and its watermark would never move.
+ Every 30 seconds a probe checks whether the worker has folded, and marked processed, every message on that partition of the live events topic.
+ If it has, the probe moves the watermark to now, so the fence can open.
+- **The live-lag gate.**
+ If the live watermark is falling behind real time, seeds for that partition pause until live catches up.
+ Live freshness always wins over backfill.
+- **A full seed lane.**
+ When the worker's seed lane is full, the rest of the partition's seeds go back to the holdover.
+ An optional disk-usage gate, off by default, can hold every partition.
+- **No leapfrogging.**
+ From the first held message on a partition, everything after it on that partition waits too, including reconcile requests and skips.
+ A reconcile request must not run before the tiles of its run on that partition, or its marker would certify an incomplete snapshot.
+
+Held messages sit in a holdover, and fetching for the partition is paused.
+Admitted seeds go onto the worker's **seed lane**.
+
+## The worker's seed lane
+
+Each worker takes seeds in **quanta** of up to a few hundred, and only when the live lane is empty, no sweep work is pending, and the previous quantum has fully applied.
+It splits a quantum into **runs**: groups of seeds of one kind, sized by a row budget.
+The budget weighs each seed by the leaves and Stage 2 rows it can touch, and a run closes before a seed that would push it over.
+A seed heavier than the whole budget still applies, in a run of its own, so the budget sizes runs but does not cap the work of one run.
+A reconcile request always forms a group of its own.
+
+The worker applies one run per turn, checking the live lane first on every turn, so live events wait behind at most one run.
+
+## Applying a run of day tiles
+
+1. **Follow merges.**
+ The run's persons are checked for tombstones in one batched read.
+ A tile for a person merged on this partition applies to the survivor.
+ A tile for a person merged onto another partition is re-produced to the seed topic, keyed by the survivor, with the same `S_chunk`.
+2. **Fan out.**
+ Each tile's condition hash maps to every leaf state key that shares it, through the current catalog.
+ A tile whose hash no longer maps to any leaf is dropped, which is expected after an edit.
+3. **Read** every leaf row the run can touch, in one batched read on the maintenance I/O lane.
+4. **Fold**, per tile and per leaf.
+ Later tiles in the same run fold onto the result of earlier ones.
+ - **"Performed N times" leaves**, stored as daily buckets or compressed history.
+ Slide the window forward to today, or to the tile's day if that is later.
+ A tile for a day that is already outside the window is dropped without a write.
+ Otherwise set that day's count to `max(stored, tile)`.
+ - **"Performed at least once" leaves.**
+ A tile means "matched on that day".
+ The row's newest match time becomes the end of that day in the team's timezone, unless it was already later.
+ A tile whose day would already have expired, or that falls outside the leaf's explicit date range, is dropped.
+ Leaves with sub-day windows are never seeded.
+ - The row's replay marks, the record of which live-topic messages were already applied, are copied through untouched.
+ Seed-topic offsets would collide with them.
+5. **Find the net flip** of each leaf over the whole run, by comparing its membership before the run with its membership after.
+
+Sliding before evaluating matters.
+Applying an expired day would resurrect a row, emit `entered`, and let the next sweep emit `left`: a flap downstream.
+
+## Applying a run of person seeds
+
+A person seed says which pinned person conditions were evaluated for the person and which matched.
+
+1. Conditions the team's catalog no longer has are removed from the seed.
+2. Merges are followed as for tiles.
+3. Each person record is read and compared with the seed.
+ The seed applies if the person has no readable record, or if the scan instant minus a margin is later than the record's **stamp**.
+ The stamp is the event time of the record's newest evaluation, or the floor an earlier seed left.
+ Only a seed that changed the record leaves a floor.
+ It also applies if the record was evaluated live against a different set of person conditions and the scan is not older than the stamp.
+ Otherwise the stored answer stands.
+4. An applied seed sets the matched set to: the seed's matches, plus any stored match the seed did not evaluate.
+ A condition that was evaluated and did not match is removed, which emits `left` for a stale match.
+
+A person with no record who matches nothing costs one read and no write.
+A skipped seed still re-checks what downstream was told, in the next section.
+
+Because a seed that changes nothing writes nothing, it leaves no stamp behind.
+So seeds from two runs that share a person condition are not ordered by scan time.
+Suppose the newer scan says "no match", reaches a person with no record first, and writes nothing.
+The older scan says "match" and arrives later.
+It still finds no record, so it applies, and the older answer wins.
+Each seed on its own is safe to apply twice.
+
+## After the fold: the shared pipeline
+
+Both kinds finish the same way, in an order the code enforces with types.
+
+1. **Decide single-leaf emissions.**
+ For each single-leaf cohort backed by a folded leaf, emit when the run flipped the leaf, or when the stored Stage 2 row disagrees with the truth.
+ A missing row counts as "never told", so a member with no row is emitted.
+2. **Stage 1 commit.**
+ One write batch holds the new leaf rows or person records and, for each single-leaf cohort about to be emitted, a Stage 2 row set to the value being **replaced**.
+3. **Schedule** eviction deadlines for the changed leaf rows.
+4. **Recompose** composed cohorts, reading each person's state once for all their cohorts, and decide their emissions.
+5. **Produce**, in parallel: the membership changes tagged `origin: seed` with the run id, first-hop cascades if enabled, and re-keyed seeds for merged persons.
+6. **Stage 2 commit.**
+ Write the new truth into the Stage 2 rows.
+7. **Mark** the run's offsets, published once the whole quantum has applied, or **hold** the first offset at once if any step failed.
+
+This order is what makes seed output self-healing.
+If the produce in step 5 fails, the offset is held, and the seed is redelivered at the next rebalance or restart.
+On redelivery the fold changes nothing: for a tile, `max` of the same count is the same count, and for a person seed, its own earlier write makes the verdict a skip.
+But the single-leaf Stage 2 rows still hold the replaced value, and the composed cohorts' Stage 2 bits were never written, so both disagree with the truth and the change is emitted again.
+Live output has no such repair, which is why live is at most once and seeds are at least once.
+
+## Reconcile
+
+A reconcile request names a cohort, a run, and the shape hash the run was pinned to.
+The seeder sends one to every partition after all of the run's tiles.
+
+### Admission
+
+The request's own offset is **deferred**: the partition cannot commit past it until the reconcile finishes, so a crash replays the request and restarts the walk.
+Seeds after it keep applying.
+If a request with a lower offset for the same cohort and kind is still queued, even one in the middle of a walk, it is dropped and the new one joins the back of the queue.
+A replayed older request never displaces a newer one.
+
+### The walk
+
+Each worker keeps a queue of reconcile jobs.
+A timer sends a drain message down every worker's live lane every couple of seconds while any job exists, and each drain advances the head job by one page.
+
+1. **Guard**, checked on every drain.
+ The job is discarded without a marker if the team or cohort left the catalog, if the cohort no longer emits membership, or if its current shape hash for the run's kind is missing or differs from the pinned one.
+ Before the first catalog load, the job waits.
+ The guard checks only that one hash.
+ The walk composes the cohort's tree from the processor's current catalog, so an edit that changes only the composition, or only the other kind's leaves, does not stop it.
+2. **Scanning.**
+ Read the next page of the cohort's Stage 2 rows on this partition.
+ Recompute each row from stored leaf state and emit it, `entered` or `left`, tagged `origin: reconcile` with the run id, whether or not it changed.
+ Correct any stored bit that was wrong.
+3. **Draining dirty rows.**
+ While the job is at the head of the queue, every write to one of the cohort's Stage 2 rows on this partition also leaves a **dirty marker**, whichever path wrote it.
+ Each settled page clears its own rows' markers.
+ After the last page, the markers that remain name the rows changed behind the cursor, and the worker re-settles them and clears their markers.
+4. **Marker ready.**
+ When no dirty marker is left, the worker produces a `reconcile_complete` marker for the cohort, run and partition.
+ Once the marker is acknowledged, the job is done and the deferred offset is released.
+
+The walk re-tells every person this store holds a Stage 2 row for, members and explicit non-members alike.
+Live, sweep and merge paths write a row on every transition, including an explicit `false` on a `left`.
+Seed paths write rows only for persons they emit.
+
+Persons that downstream still holds but this store has no row for are not re-told.
+Examples are a merged-away person, whose rows the merge drain deleted, and a member from before a store loss.
+The downstream sweep removes their rows, because this run's snapshot did not re-assert them.
+
+Reconcile re-tells what the store holds, and it cannot bring back what the store lost.
+An event that Stage 1 skipped on a store error is missing from the leaf state, so the walk recomputes the same wrong answer.
+A person whose first Stage 2 row for the cohort was never written, for example after a crash between a Stage 1 batch and its Stage 2 batch, is not in the walk at all.
+Seeds from a later run that cover the missed event repair the first case.
+A seed or a leaf flip that touches the person repairs the second.
+
+### Why every row is emitted
+
+Live and merge output are at most once, so a lost `entered` or `left` leaves state and downstream disagreeing with no trace in the state itself.
+Only re-telling everything repairs that.
+Downstream, once the run completes, the consumer deletes the cohort's rows that nothing has written since the run's snapshot.
+[Membership output and readers](membership-output-and-readers.md#mark-and-sweep) explains that sweep.
+
+## Commits
+
+The seed consumer commits on the same cadence as the other consumers, after forcing the write-ahead log to disk.
+The committable offset is the lowest of the processed offset, any held offset, and any deferred reconcile.
+
+## Failure behavior
+
+| Failure | Result |
+| -------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| A store read or write fails during a run | The run's first offset is held for the rest of the partition's tenure. Later runs still apply, but the commit stays at the hold until a restart or rebalance replays from it |
+| A run fails before its Stage 1 commit, and a reconcile request for the same cohort follows it on the partition | The reconcile still completes and produces its marker, so the partition is certified without that tile. The tile applies, and emits its change, only when the next tenure replays from the hold |
+| A membership produce fails | Hold. At the next rebalance or restart the redelivered seed emits the change again, through the pre-written row for single-leaf cohorts and the unwritten Stage 2 bit for composed ones |
+| The processor crashes mid-run | Nothing was committed past the run, so it replays. Every step is idempotent |
+| A tile is redelivered | `max` of the same count changes nothing |
+| The cohort is edited mid-run | Old tiles whose hash still maps to a leaf are max-merged into the current leaves, harmlessly. Old reconcile requests are discarded if the edit changed the shape hash for their kind. Otherwise they walk the current definition |
+| A restart interrupts a reconcile | The job's cursor lives in memory, so the replayed request walks the cohort again from the start |
+| A reconcile page's produce or commit fails | The same page retries on the next drain, and its rows are emitted again |
+| A marker produce fails | The worker retries on the next drain |
+| A restart after the marker is acknowledged but before the commit | The request replays and produces a second marker for the same run and partition, which the seeder counts once |
+| The reconcile gate is off on the processor | Requests are skipped and committed, so the run never completes until reconcile is dispatched again |
+| The person apply gate is off on the processor | Person seeds are skipped and committed, but reconcile still walks and produces every marker. With person completion and person readiness on, the run completes and Django stamps the cohort ready over state the seeds never wrote. Turn person apply on everywhere before any person run is dispatched. A cohort already stamped this way keeps its stamp, so run a new person backfill for it after turning person apply on |
+
+## Optimizations
+
+- **Batched apply.**
+ A run of seeds pays one tombstone read, one leaf read, one Stage 2 diff, one commit per stage and one parallel produce.
+ Batched apply keeps up with the seeder's production rate.
+ Its limit is the membership produce acknowledgment for each run.
+- **A separate seed lane with live priority.**
+ Live events wait behind at most one seed run.
+- **Shared Stage 2 inputs.**
+ Recomposition reads each person's leaves, person record and Stage 2 rows once for all of that person's cohorts, in bounded sections, instead of once per cohort.
+- **A bounded page reader for reconcile.**
+ One read plan serves the whole page.
+ Rows are read and evaluated in bounded blocking sections, and the store permit is released between sections, so a page costs a few thread handoffs instead of one or more per row.
+- **The maintenance I/O lane.**
+ Seed and reconcile reads never take permits from the live read pool.
+- **Dirty markers instead of a second full walk.**
+ Only rows changed behind the cursor are revisited.
+- **Drain ticks only while work exists.**
+
+Reconcile throughput is at most the page size times the partition count per tick interval.
+The work per row matters only once one page takes longer than a tick.
+
+## Worked example
+
+Team 7 uses UTC.
+Cohort 45 is a single leaf: "2 or more `$pageview` in the last 30 days".
+Person p-1 lives on partition 26.
+
+p-1 viewed a page at 10:00 on 2026-03-08, which reached ClickHouse normally, and again at 23:30 on 2026-03-08 from a client that was offline, which reached ingestion at 08:30 on 2026-03-10.
+A backfill run has boundary `B` = 08:00 on 2026-03-10.
+The live path folded only the late pageview, because it arrived after live coverage began, so the 2026-03-08 bucket holds 1 and p-1 is not a member.
+
+1. **The tile.**
+ The seeder claims the 2026-03-08 chunk at 09:00 on 2026-03-10.
+ Both pageviews reached ClickHouse before then, so the tile says count 2, with `S_chunk` = 09:00.
+2. **The fence.**
+ With the default 10-minute margin, the tile may apply once partition 26's watermark passes 09:10.
+ At first the watermark reads 09:05, so the tile and everything after it on partition 26 are held and fetching pauses.
+ When the worker folds live events stamped 09:11, the fence opens.
+3. **The fold.**
+ The leaf's window slides to today, 2026-03-10.
+ 2026-03-08 is still inside it.
+ The bucket becomes `max(1, 2) = 2`, and `gte 2` flips to true.
+4. **Emit.**
+ Cohort 45 has no Stage 2 row for p-1, so the Stage 1 batch writes a row holding `false`, the value being replaced.
+ The worker produces `entered` with `origin: seed`, then writes `true`, then marks the offset.
+ Had the produce failed, the redelivered tile would change nothing in the leaf, but the row's `false` would disagree with the truth and `entered` would be emitted again.
+5. **Reconcile.**
+ A reconcile request for cohort 45 arrives on partition 26 behind the tile.
+ Its offset is deferred.
+6. **The walk.**
+ The first page returns three rows:
+ - p-1, stored `true`, recomputed `true`: emits `entered`,
+ - p-2, stored `false` from an earlier expiry: emits `left`,
+ - p-3, stored `true` from before an earlier edit, but its leaf under the current definition has no state: recomputes `false`, emits `left` and corrects the row.
+7. **Dirty rows.**
+ Between drains, a live pageview makes p-4 enter cohort 45.
+ The live path writes p-4's row and a dirty marker.
+ The next drain re-settles p-4, emits `entered`, and clears the marker.
+8. **Marker.**
+ No dirty markers remain, so the worker produces `reconcile_complete` for cohort 45, run R and partition 26.
+ When it is acknowledged, the deferred offset is released.
+ The seeder now holds 1 of the 64 markers it needs.
+
+If p-1's late pageview had instead reached ClickHouse after 09:00, the tile would have said 1, live would also hold 1 for a different event, and `max(1, 1) = 1` would under-count.
+That is the accepted residue of the arrival bound.
+
+## Things that surprise people
+
+- The fence reads broker timestamps of the live topic, which are the shuffler's send times.
+ A lagging shuffler holds seeds back even when the processor is healthy.
+- The idle probe trusts that the live topic is complete.
+ A silent shuffler stall longer than the margin lets it open a fence early.
+- A partition whose live lane never empties makes no seed progress.
+ That is deliberate: live comes first.
+- Reconcile pages run on the live lane, so they add a little latency to that partition's live events.
+- An unchanged tile still costs Stage 2 work.
+ Re-running a backfill over already-seeded state is not free.
+- A run's changes carry the id of the last seed that touched each leaf, so two interleaved runs are not cleanly separated in `run_id`.
+- A tile handed to a merge survivor on another partition joins the back of that partition, so it can apply after that partition's reconcile marker.
+- A person-kind reconcile still recomposes the whole cohort, behavioral leaves included.
+ The kind only selects which shape hash guards it.
+- Reconcile cost grows with Stage 2 rows, not with members.
+ The rows include every person who has left the cohort since the store was built, not only current members.
diff --git a/docs/internal/realtime-cohorts/seeder.md b/docs/internal/realtime-cohorts/seeder.md
new file mode 100644
index 000000000000..cde854ce3178
--- /dev/null
+++ b/docs/internal/realtime-cohorts/seeder.md
@@ -0,0 +1,324 @@
+# The seeder
+
+`cohort-seeder` turns a backfill run into seeds.
+It claims units of work from Postgres, scans ClickHouse, evaluates every row with the same `cohort-core` code the processor runs, and produces idempotent seeds to `cohort_stream_seed_events`.
+It also drives the seeder half of completion.
+
+It never creates runs and never sets a run to `completed` or `superseded`.
+It does fail runs, and it can mark a participation superseded when it settles completion.
+It never touches the processor's state directly.
+[Backfill overview](backfill-overview.md) explains the correctness model this page implements.
+
+## The poll loop
+
+The seeder is a set of replicas polling Postgres, every 15 seconds by default.
+Each tick it:
+
+1. discovers runs in `awaiting_boundary` or `seeding` for allowlisted teams and enabled kinds, where person runs need `SEEDER_PERSON_SEEDS_ENABLED`,
+2. sets the boundary on newly discovered runs,
+3. validates each run's pinned payload and plans its chunks,
+4. fails chunks abandoned at the attempt cap, and fails runs that hold an exhausted chunk,
+5. fills its free claim slots with chunks,
+6. if completion is enabled, dispatches reconcile for fully confirmed runs and observes runs already reconciling.
+
+Claims are also refilled whenever a chunk finishes.
+Planning and validation repeat on every tick.
+Both are idempotent, so any replica can do them and a restart loses nothing.
+
+## Behavioral runs
+
+### Boundary
+
+The first time the seeder picks up a run, it moves the run from `awaiting_boundary` to `seeding` with a compare-and-set that sets `boundary_at` to the Postgres clock.
+A disaster-recovery run instead waits for Django to have pinned `boundary_at`, and the compare-and-set only changes the status.
+
+### Validation against a frozen catalog
+
+The seeder builds a catalog from the run's pinned filters, one per active participation, with the same builder the processor uses.
+Cascades are always off in this catalog.
+Each pinned condition is then looked up by its leaf state key:
+
+- a condition of a superseded participation is skipped,
+- a condition keyed on an action is dropped,
+- a condition whose leaf the catalog refused, or cannot find, is dropped,
+- every other condition gets a **lookback**: a sliding window of N days, a sub-day window, or a fixed date range.
+
+Dropped conditions add a warning to the run's error column.
+
+### Planning
+
+The days to seed are the union, over surviving conditions, of each condition's window ending the day before the boundary:
+
+- a sliding window of N days plans `day(B) - N` through `day(B) - 1`,
+- a sub-day window plans only `day(B) - 1`, although the processor drops sub-day tiles, so this day costs a scan and seeds nothing,
+- a fixed date range plans its days, clamped to the lookback cap.
+
+No day before `day(B)` minus the lookback cap is ever planned.
+A longer window is truncated, and the run records a warning.
+
+Each day becomes one or more chunks, `(run, day, band)`.
+With more than one band per day, a chunk takes only the persons whose hashed id falls in its band, so one chunk's in-memory aggregate stays bounded.
+The band count a scan divides by is the number of chunk rows its day has when the chunk is claimed.
+The insert is `ON CONFLICT DO NOTHING`, so replanning on every tick is safe while the band setting stays the same.
+Raising the lookback cap mid-run is safe too, because it only adds chunks for older days.
+
+Raising the band count while a run is seeding is not safe.
+Replanning adds the new bands to days that already have chunks, and it does not re-scan the bands already confirmed.
+Take a day planned with two bands, where band 0 is confirmed: it covered every person whose hash is even.
+The setting goes to three, so the day's remaining scans take hash `% 3 = 1` and hash `% 3 = 2`.
+A person whose hash is 9 is odd, so band 0 skipped them, and `9 % 3 = 0`, so neither new scan takes them either.
+Every chunk still confirms, and the run completes with those persons never seeded.
+Lowering the setting changes nothing for days already planned, because their chunk rows stay.
+Change the band count only while no behavioral run is seeding.
+
+Once every active participation has at least one surviving condition, the seeder stamps `chunks_planned_at`.
+That stamp is the **planning proof**: completion refuses to move a run to `reconciling` without it, so a run can never be certified over days that were never planned.
+The proof covers days, not persons, so it does not catch the band change above.
+
+If an active participation has no surviving condition, for example because all its behavioral leaves are keyed on actions, or the catalog refused one of them, the proof is withheld.
+Nothing fails the run.
+It stays in `seeding`, holding the cohort's run slot, until an operator cancels it.
+
+### Claiming and fencing
+
+A worker claims the next chunk with one statement using `FOR UPDATE SKIP LOCKED`.
+It picks the oldest day first across all seeding runs, and admits:
+
+- pending chunks and failed chunks past their backoff, both under the attempt cap,
+- `scanning` chunks whose lease expired, under the attempt cap,
+- `produced` chunks whose lease expired, at any attempt count.
+
+The claim:
+
+- sets the chunk to `scanning`,
+- charges one attempt,
+- increments its **claim epoch**,
+- sets a lease, renewed in the background at a third of its length,
+- stamps **`S_chunk`**, the claim instant, which becomes the scan's arrival bound.
+
+Every later write to the chunk is conditioned on its claim epoch and a live status, so a worker that lost its lease cannot write over a chunk another worker now owns.
+The lease renewal also requires the run to still be `seeding`, so a worker whose run was superseded or cancelled stops at its next renewal.
+Any failed renewal, even one caused by a Postgres error, cancels the scan and the produce, and fails the chunk.
+
+`S_chunk` is stamped again on every claim, including retries.
+A retried chunk therefore counts a slightly wider arrival window and waits for a later fence on the processor.
+Max-merge makes that harmless.
+
+### Scanning
+
+One chunk is one streaming ClickHouse query:
+
+```text
+SELECT <projected columns>, canonical person_id
+FROM events
+LEFT JOIN (latest person override per distinct_id for the team) ON distinct_id
+WHERE team_id = <team>
+ AND timestamp in [start of day, start of next day) in the run's timezone
+ AND event IN (<event names of the conditions whose window still covers this day>)
+ AND coalesce(inserted_at, _timestamp) < S_chunk
+ [AND hash(person) % bands = band]
+```
+
+- **Canonical persons.** The join maps each distinct id through the latest person override, so events of merged persons count toward the survivor.
+- **Timezone days.** The day's bounds are computed in the run's pinned timezone.
+- **Arrival bound.** Only events that reached ClickHouse before `S_chunk` count.
+- **Active conditions.** Conditions whose window has slid past this day by scan time are left out.
+ If none remain, the chunk is done without a query.
+
+### Evaluating and producing
+
+For each row, the seeder builds the same behavioral globals the processor would build and runs every active condition for the row's event name through the HogVM.
+Each match increments a count for `(person, condition hash)`.
+At the end of the chunk, each count becomes one **day tile**:
+
+```json
+{
+ "schema_version": 1,
+ "kind": "behavioral_tile",
+ "team_id": 7,
+ "person_id": "...",
+ "condition_hash": "b938e32d52f73122",
+ "day_idx": 20517,
+ "count": 4,
+ "run_id": "...",
+ "s_chunk_ms": 1773154820000,
+ "claim_epoch": 1
+}
+```
+
+Tiles are keyed `"{team_id}:{person_id}"`, so each lands on the partition of the worker that owns the person.
+A shared rate limiter paces production, and a cap bounds the tiles in flight.
+
+The chunk then moves to `produced`, which means every tile was handed to the producer, waits for every acknowledgment, and moves to `confirmed`.
+
+### Chunk states and retries
+
+```mermaid
+stateDiagram-v2
+ [*] --> pending: planned
+ pending --> scanning: claim
+ scanning --> produced: every tile enqueued
+ produced --> confirmed: every tile acknowledged
+ scanning --> failed: error or lost lease
+ produced --> failed: error or lost lease
+ failed --> scanning: reclaim after backoff, under the attempt cap
+ scanning --> scanning: reclaim after lease expiry, under the cap
+ produced --> scanning: reclaim after lease expiry
+ scanning --> pending: shutdown before produced, attempt refunded
+ scanning --> failed: lease expired at the attempt cap
+ failed --> [*]: at the attempt cap, the run fails
+```
+
+A failed chunk backs off exponentially with jitter before it can be claimed again.
+A chunk that fails at the attempt cap, or whose `scanning` lease expires at the cap, fails the whole run, which frees the cohort's run slot.
+A `produced` chunk whose lease expires is reclaimed at any attempt count, so a chunk whose worker keeps dying after `produced` never fails the run.
+A reclaimed chunk is scanned and produced again from scratch.
+The duplicate tiles are absorbed by max-merge.
+A graceful shutdown before a chunk is marked produced returns it to `pending`, even if some of its tiles already reached Kafka.
+
+## Person-property runs
+
+A person run seeds the person record instead of behavioral leaves.
+It scans persons whose record changed within the run's **horizon**, a pinned number of days.
+
+### Planning by person id range
+
+Planning a person run needs a scan, so it runs off the poll loop, one at a time per replica, under a cluster-wide advisory lock per run.
+The seeder streams the ids of the team's persons that changed within the horizon, keeps every Nth id as a boundary, and inserts chunks that tile the whole id space.
+The insert is all or nothing.
+
+Person chunks have their own claim slots, so they run alongside behavioral work.
+If a person run has no surviving condition at all while a participation is active, the seeder fails it.
+
+### Scanning and evaluating
+
+Each chunk reads the latest properties of every person in its id range who changed within the horizon.
+For each person the seeder evaluates every surviving pinned person condition and builds a **person seed**: the conditions it evaluated, and the subset that matched.
+A condition the VM could not answer is left out of `evaluated`.
+The seed's scan time, which the processor compares with live updates, is the chunk's claim instant.
+Seeds are produced as the scan streams, never buffered, so memory stays constant.
+
+One optimization applies to every person run:
+
+- **The vacuous-key shortcut.**
+ A condition that reads only certain property keys has a fixed answer for a person who has none of those keys.
+ That answer is computed once per run, and a row without the keys skips the VM for that condition.
+
+### Which persons get a seed
+
+A process-wide setting chooses between two modes.
+
+- **Every scanned person**, the code default.
+ This is the only mode that retracts stale matches for persons who now match nothing.
+- **Only persons whose seed can change a participating cohort's answer.**
+ Persons who match nothing are skipped, and so are persons whose results cannot change any cohort.
+
+The second mode adds two optimizations.
+
+- **Relevance pruning.**
+ For each participating cohort, the seeder evaluates the cohort's tree with the person's condition results as known values and every other leaf as unknown, in three-valued logic.
+ It emits the person only if some cohort's answer differs from its answer for a person matching nothing.
+ A person with an unanswered condition is emitted without judging.
+ If some cohort's answer for a person matching nothing is already unknown, pruning is off for the whole run.
+- **The key-presence filter.**
+ When every condition is decidable by keys, every such answer is a real verdict, and a person without the keys is never relevant, the ClickHouse query itself filters out persons whose properties contain none of the keys.
+ Those persons never leave ClickHouse.
+ Properties that are not a JSON object always come through, and the filter is dropped if it would make the query too long.
+
+These matter for broad conditions.
+"Email does not contain `@example.com`" is true for every person with no email, so without pruning an `AND` of "email is set" and that condition would seed every person of the team.
+
+## Completion
+
+Automatic reconcile dispatch and observation are separate gates, off by default.
+Without the dispatch gate, an operator dispatches reconcile with the `reconcile_dispatch` command-line tool.
+The tool only dispatches, so the seeder records an outcome only while the observer gate is on.
+
+When every chunk of a run is confirmed and the planning proof is stamped, the seeder:
+
+1. moves the run to `reconciling` with a compare-and-set,
+2. records where the reconcile marker topic currently ends,
+3. produces one reconcile request per participating cohort to each of the 64 seed partitions,
+4. records the high-water mark of those requests per partition.
+
+If unconfirmed chunks show up after the move anyway, it reverts the run to `seeding`.
+
+A watcher then tails the marker topic and records, per participation, which partitions have reported.
+When every cohort of the run has all 64 markers, the seeder marks them all complete at once, with no further check.
+To call a cohort short, the seeder first needs proof that no more markers are coming: the processor's seed consumer must have committed past every reconcile request, and the watcher must have read the marker topic to the end captured after that.
+Until that proof arrives, the run's complete cohorts wait with the short ones.
+Then each participation is marked complete, retryable, or superseded, and the run is marked observed.
+[Completion and readiness](completion-and-readiness.md) covers this protocol and what Django does next.
+
+## Optimizations
+
+- **Column projection.**
+ Static analysis of the run's conditions decides, per chunk, which columns and property keys to read.
+ A column no condition reads comes back empty and is never parsed.
+ A property blob comes back rebuilt with only the keys the conditions read.
+ Without projection, most of the seeder's CPU goes to parsing JSON and assembling globals.
+ In local measurements, a chunk ran about 3 times faster with keys rebuilt and about 60 times faster when no blob was needed.
+ Rebuilding keys costs ClickHouse more, so the gain is on the seeder's side.
+ On real data, projection raised client throughput per core by more than an order of magnitude.
+ One side effect: a row whose skipped blob is malformed, which the live path would drop, is still evaluated here on its other fields.
+- **Shadow compare.**
+ A mode that re-scans each projected chunk at full width and diffs the tiles, to prove projection changes nothing.
+ It is on by default in code, adds a full-width query per chunk and roughly doubles scan memory, so it is meant to be turned off once projection is proven.
+- **Scan-time window gate.**
+ A chunk whose day has slid out of every active window issues no query.
+- **Bands.**
+ Splitting a day by person hash bounds one chunk's memory, at the cost of reading the day once per band.
+- **Pacing.**
+ One rate limiter per kind per process, shared by all chunks, protects the seed topic and the processor's apply rate.
+- **Backoff and attribution.**
+ Failed chunks back off with jitter instead of being retried every tick.
+ Every query carries a structured log comment with the team, the run and the scan phase, so ClickHouse cost can be attributed.
+ A chunk scan also names the chunk and its band, and a behavioral chunk scan names its day.
+- **Person-run pruning.**
+ In a synthetic test where few persons carried the relevant key, the key-presence filter cut rows returned 200 times and bytes sent about 156 times.
+ In a micro-benchmark where every condition was answered from the cached value, the vacuous-key shortcut cut VM time per row about 17 times.
+
+## Worked example
+
+For this example team 7 uses `America/Sao_Paulo`, three hours behind UTC, to show the timezone math.
+Cohort 42 is "3 or more `$pageview` with `$pathname = /pricing` in the last 7 days".
+Person p-1 has two distinct ids, `d-1` and `anon-9`, and `anon-9` was merged into p-1.
+p-1 hashes to partition 26.
+
+1. **Boundary.**
+ At 15:00:00 UTC on 2026-03-10 the seeder picks up run R and sets `B` to that instant.
+ Local time is 12:00, so `day(B)` is 2026-03-10.
+2. **Validate and plan.**
+ The pinned condition resolves to a 7-day sliding window.
+ The seeder plans 7 chunks, for 2026-03-03 through 2026-03-09, one band each, and stamps the planning proof.
+3. **Claim.**
+ Workers claim chunks oldest day first.
+ At 15:00:20 one of them claims the 2026-03-05 chunk.
+ `S_chunk` is 15:00:20 and the claim epoch is 1.
+4. **Scan.**
+ The day's bounds are 03:00 UTC on 03-05 to 03:00 UTC on 03-06.
+ Projection reads only `properties.$pathname`, and the other blobs come back empty.
+ The query returns four `/pricing` pageviews for p-1: three from `d-1`, and one from `anon-9` that the override join resolves to p-1.
+ A fifth pageview for 03-05, sent late by an offline client, reached the live path at 15:00:10, but ClickHouse stored it only at 15:00:40, after `S_chunk`, so the scan does not return it.
+5. **Tile.**
+ The seeder produces `{p-1, H, day 03-05, count 4}` to the partition of `"7:p-1"`, then marks the chunk produced and, after the acknowledgments, confirmed.
+6. **Processor, for context.**
+ With the default 10-minute margin, the tile waits until partition 26's live watermark passes 15:10:20.
+ The live path folded the late fifth pageview at 15:00:10, so the bucket holds 1.
+ The apply takes `max(1, 4) = 4`.
+ The true count is 5, which is the bounded under-count from a late arrival, and p-1 still enters.
+7. **Completion.**
+ When the other six chunks confirm, the seeder moves R to `reconciling` and sends 64 reconcile requests for cohort 42.
+
+## Things that surprise people
+
+- `B` is the moment the seeder first saw the run, not when the run was created, except for disaster-recovery runs, whose `B` Django pins.
+- Claims take the oldest day first across every run, so a small new cohort's recent days wait behind a large team run's older days.
+- A chunk in `produced` has enqueued its tiles but may not have all acknowledgments yet.
+- The seeder writes the claim epoch into every tile, but the processor ignores it.
+ Fencing is purely a Postgres concern, and duplicates are absorbed by max-merge.
+- The seeder evaluates every row through the VM, even for conditions that only test the event name.
+- Person runs scan only persons whose record changed within the horizon.
+ A dormant person with a stale match outside the horizon keeps it.
+- The seeder has no merge repair of its own.
+ It resolves canonical persons at scan time, and the processor redirects tiles for persons merged after the scan.
diff --git a/docs/internal/realtime-cohorts/state-store-and-durability.md b/docs/internal/realtime-cohorts/state-store-and-durability.md
new file mode 100644
index 000000000000..09cf290cdd1d
--- /dev/null
+++ b/docs/internal/realtime-cohorts/state-store-and-durability.md
@@ -0,0 +1,200 @@
+# State store and durability
+
+The processor keeps all membership state in an embedded RocksDB database on the pod's disk.
+This page explains the store's layout, why it is shaped around the person, how writes stay atomic, what "durable" means for the processor, and how it restarts.
+
+It uses terms from [live evaluation](live-evaluation.md) (leaf state keys, the person record, Stage 2, replay marks), [merges and cascades](merges-and-cascades.md) (drains, tombstones, the transfer outbox) and [time and eviction](time-and-eviction.md) (the sweep).
+
+## Kafka is the log, RocksDB is the view
+
+The processor treats its input topics as the source of truth and the store as a local materialization of them.
+Any state could in principle be rebuilt by replaying input, but the events topic keeps about a day and the merge topics about a week, while windows reach back months.
+So the store is precious in practice.
+Losing it means rebuilding from backfills, not from Kafka.
+
+There is one RocksDB database per pod, holding every partition the pod owns.
+Every key except the schema stamp starts with the partition number, so one partition's state is one contiguous key range.
+Wiping a partition is one range delete per partitioned column family.
+
+## Column families
+
+A column family is a separate keyspace inside the database, with its own settings.
+
+| Column family | One row per | Holds |
+| ------------------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `cf_behavioral` | person and behavioral leaf state key | Behavioral leaf state, its eviction deadline, and replay marks: the firehose offsets already applied |
+| `cf_person_records` | person | The person record: matched person conditions, fingerprints, stamp, replay marks |
+| `cf_stage2` | cohort and person | The membership bit the processor registered for the pair. On the live, sweep, merge, cascade and reconcile paths it is the recomputed truth. On the seed path it is what downstream was last told. Also reconcile dirty markers, and an inventory of membership rows received through merges |
+| `cf_merge_drains_applied` | merge message | Marker: this merge was drained |
+| `cf_merge_applied` | merge message and target | Marker: this transfer was applied |
+| `cf_pending_transfers` | merged-away person | Outbox of state waiting to be transferred to another partition |
+| `cf_merge_tombstones` | merged-away person | Forwarding address to the survivor |
+| `cf_meta` | store | The schema version |
+
+## Keys are clustered by person
+
+Behavioral rows and person records are keyed by a 26-byte **person prefix**:
+
+```text
+person prefix = [partition u16][team u64][person uuid 16 bytes]
+
+cf_behavioral key = person prefix + leaf state key (16 bytes)
+cf_person_records key = person prefix
+cf_stage2 key = [partition][team][cohort u64][person]
+```
+
+Integers are big-endian, so byte order is numeric order.
+All of one person's behavioral rows sort next to each other, and the person record uses the bare prefix as its key in its own column family.
+The tombstone and outbox column families are keyed by the same prefix.
+
+This layout is the most important performance decision in the processor.
+An event touches only its person's rows, so its behavioral reads and its person-record read each hit one small key range, however large the store grows, plus a tombstone probe that a bloom filter usually answers.
+Collapsing all of a person's person-property state into one record, with fingerprints that let most events skip evaluation, is what keeps the number of keys an event reads small.
+Behavioral state is still one row per person and leaf the person matched.
+
+The same clustering makes merges cheap.
+Draining a person is one prefix scan and one range delete.
+
+`cf_stage2` is the exception.
+It is keyed cohort first, so reconcile can walk every row of one cohort as a range scan.
+The cost is that a merge drain cannot list one person's Stage 2 rows by prefix.
+It deletes them using the catalog's list of cohorts, plus a person-first inventory of rows it received through earlier merges.
+
+## Writes are atomic per unit of work
+
+A worker collects the changes of one unit of work into one batch and commits it as one RocksDB write batch.
+Examples of a unit: one event's Stage 1 fold, one merge drain, one merge apply, one sweep batch's single-leaf leg, one cascade message, one reconcile page, one group of seed messages' Stage 1 writes.
+A crash can never leave half of one: a merged-away person deleted without its tombstone, or a leaf updated without its single-leaf Stage 2 row.
+Flushes are atomic across column families too.
+
+Composed Stage 2 rows are always their own, later batch.
+A crash between a Stage 1 batch and its Stage 2 batch drops that composed flip until the person's leaves flip again.
+Reconcile also repairs it if the person already had a Stage 2 row for the cohort.
+If the lost write would have been the person's first row, reconcile never sees the person, and only a seed or a later flip that touches them repairs it.
+
+While a partition's worker runs, it is the only writer of its key range.
+Merges, cascades, sweeps, garbage collection, backfill and reconcile all run on that worker, so reads always see the worker's own previous writes.
+Partition wipes and the boot redrive of the transfer outbox run from outside the worker.
+A revoke wipes a slice after its worker exits, and a partition that moves in after boot is wiped just before its worker spawns.
+The boot redrive is meant to run before workers exist, but nothing enforces that, so a worker can already be running while it clears outbox rows.
+[Processor runtime](processor-runtime.md#startup) describes the gap.
+The processor needs no locks and no RocksDB snapshots.
+
+## The durability invariant
+
+Writes do not wait for the disk.
+Each write batch reaches the write-ahead log in the operating system's page cache and returns.
+Durability comes from the offset commit instead:
+
+1. every few seconds, each consumer captures the offsets it is allowed to commit,
+2. it forces the write-ahead log to disk,
+3. only if that succeeds, it commits the captured offsets to Kafka.
+
+So **a committed offset never runs ahead of state on disk**.
+After a crash, Kafka redelivers everything after the last commit, and each path's idempotence absorbs the replay: replay marks for events, markers for merges, max-merge for backfill tiles.
+The invariant holds for every input topic, whether or not durable restore is enabled.
+It protects state, not output.
+Output is acknowledged before the flush, so a host crash that loses unflushed writes can make the replay emit changes a second time.
+
+It covers writes that succeeded.
+A failed Stage 1 read or write on the live path skips the event without holding its offset, so that event's effect is lost from the leaf state.
+Reconcile recomputes from that same state, so it cannot bring the event back.
+Only a later backfill whose seeds cover the event restores it.
+
+## Schema version
+
+The store records a schema version in `cf_meta`.
+Opening a store whose stamp is missing or different fails, unless `COHORT_WIPE_ON_SCHEMA_MISMATCH` allows a wipe.
+A store with an unknown column family fails to open even with that flag.
+There are no in-place migrations.
+An incompatible key or value change bumps the version, and the store is rebuilt from nothing, which means re-running backfills.
+
+## Restarting
+
+Durable restore, `DURABLE_RESTORE_ENABLED`, is off by default, and with it off the store is wiped at every start.
+A deployment that relies on backfilled state must enable it.
+
+With durable restore on, the processor picks where its store comes from at boot, in this order:
+
+1. **Reopen the live store** on the persistent volume, if it is there.
+2. **A local checkpoint**, if checkpoints are enabled and a recent one exists.
+3. **A remote checkpoint** downloaded from object storage, if checkpoints are enabled.
+4. **An empty store**, the cold start.
+
+Checkpoints, `CHECKPOINT_ENABLED`, are disabled by default, so in practice the choice is between reopening the live store and starting empty.
+A checkpoint restore that fails to clear the store, copy or download the checkpoint, or read its offsets falls back to a cold start.
+The restore never opens the RocksDB files, so a checkpoint whose files cannot open passes it, and the store open that follows fails the pod instead.
+A live store that fails to open does not fall back either: the pod fails to start.
+
+A cold start does not rebuild history.
+The consumers resume at their committed offsets, so the store only fills from new traffic, and every cohort's past membership has to come back through a backfill.
+A backfill cannot bring back everything.
+`performed_event` leaves with an hour or minute window refill only from new live events, and a cohort made only of references refills through cascades from the backfills of the cohorts it references.
+
+With durable restore on, the processor also:
+
+- deletes the slices of partitions it no longer owns, once its assignment settles,
+- re-produces every transfer still waiting in the merge outbox,
+- rebuilds each partition's in-memory eviction queue from its behavioral rows when that partition's worker spawns,
+- wipes the old slice of a partition that moves in after boot, before its worker spawns.
+
+After a checkpoint restore it also rewinds the consumers to the offsets recorded in the checkpoint.
+The events consumer retries its seek until it succeeds.
+It seeks only once its assignment settles, so a poll that arrives earlier is still dispatched, the same startup gap as the boot redrive.
+The merge, transfer, cascade and seed followers get one attempt each.
+A failed attempt only logs a warning, and a checkpoint with no offsets for the topic skips the rewind silently.
+Either way the follower resumes at its broker-stored offsets.
+Those can be ahead of the restored state, and the inputs in between are never applied.
+
+When a partition is revoked, its worker drains and exits, and its slice is deleted.
+State never moves between pods, which is why the processor runs as a single pod.
+[Processor runtime](processor-runtime.md#rebalance-and-the-single-pod-constraint) explains that constraint.
+
+## Keeping the store bounded
+
+- **Behavioral rows** leave through the sweep, which deletes rows that aged out and emits `left` on the way.
+ They are never expired by RocksDB itself, because an expiry that RocksDB performs silently would skip the `left`.
+- **Person records** can be expired by a compaction filter on a last-seen time, when `COHORT_PERSON_RECORD_TTL_DAYS` sets a time-to-live. It defaults to 0, which turns expiry off.
+ An expired record loses its matched set and its replay marks.
+ On the person's next event, current matches re-emit `entered` for single-leaf cohorts, and a condition that stopped matching while the person was dormant cannot emit `left`.
+ Keep the time-to-live well beyond topic retention.
+- **Stage 2 rows** of cohorts that left the catalog are removed by the hourly Stage 2 garbage collection.
+ The exception is a row received through a merge while register transfer is enabled, which the collection keeps until its protection ends.
+ [Merges and cascades](merges-and-cascades.md#stage-2-garbage-collection) explains when that happens.
+ Rows of live cohorts are never deleted, because a person who leaves keeps an explicit `false` row.
+ So `cf_stage2` grows with every person who was ever registered in a live cohort.
+- **Merge markers and tombstones** are removed after their retention period.
+- **Orphaned behavioral rows**, left behind when a leaf's definition changes, a cohort is deleted, or a team leaves the catalog, are not collected.
+ They are removed only by a merge drain or a partition wipe.
+
+## Tuning that matters
+
+- **One block cache** shared by all column families also holds index and filter blocks, so memory use is predictable.
+- **Bloom filters** on every column family make misses cheap.
+ That matters because every event probes the tombstone column family, and nearly every probe misses.
+- **A prefix extractor** on the 26-byte person prefix makes one person's behavioral rows a single prefix scan.
+- **Compaction on deletion** compacts files dense with deletes, which the sweep and merges produce in waves.
+- **Range deletes** remove a person or a partition in one operation.
+
+## Store access from async code
+
+Workers are async tasks, and RocksDB calls block.
+By default every store call runs on a blocking thread pool, and reads and whole maintenance sections take permits from two pools:
+
+- an **event** pool, for live-path reads and for Stage 2 recomposition on the live, sweep, merge and cascade paths,
+- a smaller **maintenance** pool, for the sweep's state reads, merge drains and applies, garbage collection, reconcile pages and backfill seed runs.
+
+Plain writes and the write-ahead-log flush take no permit, so the commit cadence never waits behind reads.
+A lint rule denies direct calls to most store I/O methods, and the synchronous sections that need them opt out explicitly.
+
+## Things that surprise people
+
+- Reopening the live store checks only that RocksDB's `CURRENT` file exists.
+ A damaged store that has one is chosen, fails to open, and the pod crash-loops.
+ It never falls back to a checkpoint.
+- A store directory without a `CURRENT` file is neither reopened nor wiped, and the open fails on the missing schema stamp.
+- Static group membership keeps a restart from causing a revoke.
+ A second group member, or a pod that loses its session or stops polling, still causes one.
+ Each revoke deletes the whole slice, including merge transfers not yet sent, whose merge offsets may already be committed.
+- Person records grow with every person seen on a team with person-property conditions, including those that match nothing, unless a time-to-live is configured.
+- The person record time-to-live is judged against event time, so importing old events can write records that are already eligible for expiry.
diff --git a/docs/internal/realtime-cohorts/time-and-eviction.md b/docs/internal/realtime-cohorts/time-and-eviction.md
new file mode 100644
index 000000000000..d475469122e2
--- /dev/null
+++ b/docs/internal/realtime-cohorts/time-and-eviction.md
@@ -0,0 +1,184 @@
+# Time, windows and eviction
+
+A behavioral leaf such as "viewed pricing in the last 7 days" can become false without any event.
+The person simply stops doing the thing, and time passes.
+This page explains how the processor models time and how the eviction sweep produces "left because time passed".
+
+It assumes the vocabulary of [live evaluation](live-evaluation.md): leaves, their state variants, Stage 1, which keeps each leaf's state, and Stage 2, which recomposes cohorts when a leaf flips.
+
+## Days belong to the team's timezone
+
+Behavioral windows counted in days use calendar days in the team's timezone.
+An event at 02:30 UTC on 2026-09-18 belongs to 2026-09-17 for a team in `America/New_York`.
+
+The processor turns a timestamp into a **day index**, the number of days since 1970-01-01 in the team's timezone.
+That direction is never ambiguous.
+The reverse, the instant a given day starts, needs two rules around daylight saving changes, and every daily deadline uses it:
+
+- when local midnight happens twice, the day starts at the earlier instant,
+- when local midnight falls inside a skipped hour, the day starts at the first valid instant after the gap.
+
+The timezone comes from the team row when the catalog is built.
+An unknown timezone falls back to UTC and is counted.
+
+## What "the last N days" means
+
+A window of N days covers today plus the N days before it, so N + 1 calendar days.
+"The last 7 days" on 2026-09-24 covers 2026-09-17 through 2026-09-24.
+
+For `performed_event` this matches the batch cohort query, which also starts the window at local midnight N days ago.
+For `performed_event_multiple`, the batch query uses a rolling `now - N days` instead, so the realtime window can hold up to one extra partial day.
+
+Months count as 30 days and years as 365 days.
+The batch query uses calendar months and years, so month and year windows differ from it at the edges.
+The gap grows with the window: one month can be a day or two off, and 12 months are 360 days here against 365 or 366 in the batch query.
+
+Hour and minute windows are durations, not calendar days.
+Only `performed_event` supports them.
+A count leaf with an hour or minute window is not supported and has no state.
+
+A `performed_event` window written with absolute dates, using `explicit_datetime` and `explicit_datetime_to`, is a fixed calendar range, so a match inside it never expires.
+`performed_event_multiple` does not support absolute dates.
+A relative `explicit_datetime` such as `-30d` with no upper bound slides like `time_value`.
+
+## Every row carries its own deadline
+
+Stage 1 never reads the wall clock.
+Instead, every time it folds an event into a behavioral row, it computes the row's **eviction deadline**: the earliest instant at which the leaf's answer could change without another event.
+
+| Variant | Deadline |
+| --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
+| `performed_event` with a window in days | Local midnight at the start of day `newest match + N + 1` |
+| `performed_event` with a window in hours or minutes | `newest match + window` |
+| `performed_event` with absolute dates | None |
+| Daily buckets or compressed history | Local midnight at the start of day `oldest counted day + N + 1`, the moment the oldest counted day leaves the window |
+| Person-property leaves | None. The sweep never touches them |
+
+A `performed_event` leaf with a 7-day window, matched at 11:00 on day D, stays true through the end of day D + 7 and expires at midnight starting day D + 8.
+It does not expire at "match time + 7 × 24 hours".
+
+A daily-buckets leaf's deadline is only the next moment its total can drop.
+When the oldest day slides out, the total may still satisfy the operator, and the row simply gets a later deadline.
+
+## The eviction queue
+
+Each worker keeps an in-memory **eviction queue** of its partition's behavioral rows, ordered by deadline.
+Every fold reschedules its row at the new deadline, earlier or later, replacing the old entry exactly.
+Rows with no deadline are never queued.
+
+The queue lives only in memory.
+With durable restore enabled, a worker rebuilds it from its slice of behavioral state when it spawns, before it handles its first message.
+A worker spawns only when its partition's first message arrives, so after a restart that partition's overdue evictions wait for that message.
+[Processor runtime](processor-runtime.md) explains worker lifecycle and durable restore.
+
+## The sweep
+
+A timer fires every 30 seconds, after an initial delay at boot.
+Each tick sends a sweep request to every running worker with a **cutoff** of `now - safety margin`.
+The margin, 5 minutes by default, absorbs up to that much consumer lag.
+A person whose events are still sitting in the input topic should not be evicted just because the processor is behind.
+With more lag than the margin, a person can leave and then re-enter when the delayed event arrives.
+
+The worker does not sweep on receipt.
+It records the request, keeping only the latest cutoff, and works through it on later turns.
+
+1. **Select.**
+ Up to 10,000 due keys are selected from the queue in deadline order, then grouped by person.
+ Due keys beyond that wait for the next tick.
+2. **Batch.**
+ Whole persons from one team, as far as this pass selected them, are packed into a batch of about 256 keys.
+ Each key is claimed only if its deadline is still due, so a key that an event rescheduled since selection is skipped.
+3. **Read.**
+ The batch's rows are read with one batched read that uses the maintenance I/O permits, the pool reserved for background work.
+4. **Evict.**
+ - A `performed_event` row past its deadline is deleted.
+ If it matched, the leaf flips to false.
+ - A daily or compressed row slides its window to the cutoff's day and recomputes its total.
+ The leaf can flip either way.
+ With `lte 2`, `lt 3` or `eq 2`, a total falling from 3 to 2 makes the leaf true again.
+ A total that falls to zero is never a member.
+ The row is rewritten and rescheduled at its next deadline, or deleted when it has no counts left.
+5. **Emit.**
+ Flips go through the same leaf-to-cohort lookup as live events.
+ A flip of a single-leaf cohort becomes a change directly.
+ A flip of a leaf in a composed cohort triggers Stage 2 for that person and cohort.
+
+Sweep batches alternate with live batches on the worker.
+Neither can starve the other, and a sweep never holds the whole partition while a large wave of deadlines expires.
+
+The 10,000-key cut comes before the grouping, so it can split one person's due leaves across two passes, about one tick apart.
+Keys that share a deadline sit in the order they were scheduled, so in a midnight wave the cut can split many persons, not only the last one.
+Between the two passes, Stage 2 composes against half of the person's evictions.
+Take `AND[A, NOT B]` with A and B due at the same midnight: if the first pass evicts only B, the cohort emits `entered`, and the second pass then emits `left`.
+
+A batch drops its keys without rescheduling them when their team is missing from the catalog, including before the first catalog load, and when a key's leaf, row or encoding is gone or bad.
+Those rows are not scheduled again until the person's next matching event, or a durable-restore rebuild.
+
+### Delivery on the sweep
+
+The two kinds of sweep output make different promises.
+
+- **Single-leaf cohorts** are produced first and committed after the acknowledgment.
+ If the produce or the commit fails, the keys go back on their deadlines and the next pass retries them.
+ This is at least once while the worker runs.
+ The retry lives in the in-memory queue.
+ After a restart it survives only with durable restore on, where the row is still on disk and the rebuild at spawn queues it again.
+ With durable restore off, the restart wipes the store, and the missed `left` is lost with the rest of the state.
+- **Composed cohorts** are committed by Stage 2 first and produced after.
+ A failed Stage 2 read, commit or produce is dropped.
+ This is at most once.
+ Downstream stays wrong until the cohort flips again for that person, or until a backfill run's reconcile re-emits the cohort.
+
+## Why deadlines cluster at midnight
+
+Daily windows expire at local midnight, so a team's rows reach their deadlines together, just after midnight in that team's timezone, plus the safety margin.
+For a large team that is a wave of evictions at once.
+The sweep is bounded for this reason.
+It reads and writes a small batch at a time, interleaved with live traffic, so the wave costs a steady trickle of work instead of a memory spike and a stall of the live path.
+
+## Worked example
+
+This continues from "The third pageview" in [live evaluation](live-evaluation.md#worked-example), and assumes p-1 keeps their email.
+Team 7 uses UTC, and cohort 42 is `AND[A, B]`, with A = "3 or more `/pricing` pageviews in the last 7 days" and B = "email is set".
+
+p-1 made 3 matching pageviews on 2026-09-14 and entered cohort 42.
+A's row has all 3 counts on day 2026-09-14.
+Its deadline is midnight starting 2026-09-14 + 7 + 1 = 2026-09-22.
+
+p-1 sends nothing more.
+
+1. At 2026-09-22 00:05:15 UTC a tick fires with cutoff 00:00:15, the first cutoff past A's deadline.
+2. On its next sweep turn, the worker for partition 26 selects A's row for p-1 and claims it.
+3. The window slides to the cutoff's day, 2026-09-22.
+ The window now starts on 2026-09-15, so the three counts from 2026-09-14 fall out.
+ The total drops to 0, and A flips to false.
+ The row has no counts left, so it is deleted.
+4. No single-leaf cohort uses A.
+5. Stage 2 recomposes cohort 42 for p-1: A is false, B is true, so `AND` is false.
+ The stored bit is true, so this is a flip.
+ Stage 2 writes `false` and the worker produces `left`.
+
+p-1 was a member from 2026-09-14 14:00 until about 00:05 on 2026-09-22.
+"The last 7 days" covered 8 calendar days, and the safety margin plus the tick interval added a few minutes on top.
+
+**Variant.**
+Suppose p-1 had made one more matching pageview on 2026-09-20.
+That event slides the window to end on 2026-09-20, which drops nothing because 2026-09-14 is still inside, and adds a count on 2026-09-20.
+The oldest counted day is still 2026-09-14, so the deadline stays 2026-09-22.
+At the sweep on 2026-09-22 the total drops from 4 to 1, A still flips to false, and the row is rewritten with a new deadline of midnight starting 2026-09-28 instead of being deleted.
+
+## Things that surprise people
+
+- Every `left` produced by time carries the safety margin as extra latency.
+ A leaf with a one-hour window leaves more than 5 minutes after the hour ends.
+- Windows advance with event time on the live path.
+ For a person with no state for a leaf, a late event older than the window creates state anchored at its own old day, emits `entered`, and is swept out on the next tick.
+- The sweep can emit `entered`, for operators like `lte`, `lt` or `eq`.
+- With cascades on, a sweep expiry of a single-leaf cohort sends no cascade message.
+ A cohort that only references it keeps the person and never emits the missed `left`.
+ Its answer is right again only if the person re-enters, or after a reconcile.
+- Person-property leaves have no window, so the sweep never expires them.
+ With the default settings, "email is set" stays true until an event carries properties without an email.
+ The exception is the optional person record time-to-live, off by default, which deletes a dormant person's whole record.
+ After that, a recomposition or a reconcile reads the person's conditions as not matching, with no `left` emitted at the moment of deletion.
+ [State store and durability](state-store-and-durability.md#keeping-the-store-bounded) describes it.