Colony Colony Segmentation

Developer Guide

For a developer who has never seen this service. It has two parts: Part 1 shows how the data is stored and how the pieces of data connect, Part 2 shows how the service is wired together and how a request, a new interaction or a nightly run travels through it.

The diagrams are text (Mermaid), kept in dev-guide.md, so you can edit them like any other file. For the API itself (every endpoint, with examples) see the API guide.

The service in one sentence. It reads every interaction a listener has with a radio station (messages, competition entries, surveys, USSD), builds one profile per listener from them, places each listener in one of seven segments, and lets the station explore, enrich (with AI), save and retarget those listeners from a dashboard.


Part 1. The database

The big picture

MongoDB holds everything except the search vectors, which live in Qdrant. Almost every collection exists once per station: its name ends with the station's company ID (for example segmentation_8). A few are shared by all stations.

The listener and what hangs off it. This is the heart of the database.

erDiagram
    PROFILE["segmentation_ID"] {
        string originator PK "the listener: phone, email or handle"
        int company_id
        string current_segment
        date last_interaction_at
        list top_campaigns "campaign id, title, count"
        list inferred_interests
        map interest_sources
        bool permission
        bool opt_in
    }
    HISTORY["segmentation_ID_history"] {
        string originator FK
        string from_segment
        string to_segment
        date changed_at
        map rfm_snapshot
    }
    AUDIENCE["audiences_ID"] {
        string audience_id PK
        string name
        list members "originators"
        date expires_at
    }
    BUCKET["retarget_bucket_ID"] {
        string group_key PK
        string label
        list originators
        int count
    }
    TOPIC["topics_ID"] {
        string key PK "campaign:1803"
        string kind
        list topics
        string brand
        string source "ai or station"
    }
    VECTOR["Qdrant listeners_ID"] {
        int id "hash of originator"
        list vector "384 numbers"
    }

    PROFILE ||--o{ HISTORY : "one row per segment change"
    PROFILE }o--o{ AUDIENCE : "is a member of"
    PROFILE }o--o{ BUCKET : "is set aside in"
    PROFILE }o--o{ TOPIC : "took part in a campaign about"
    PROFILE ||--o| VECTOR : "one vector"

Everything else, tied together by the station. These collections are shared by all stations; each row carries its company_id.

erDiagram
    STATION["STATION (company_id, not a collection)"]
    CREDITS["ai_credits"] {
        int company_id PK
        float credits_remaining
        bool paused
        map feature_caps "monthly limits"
        list load_history
    }
    USAGE["ai_usage_log"] {
        int company_id FK
        string endpoint
        int total_tokens
        float credits_charged
        date timestamp
    }
    JOB["bulk_enrich_jobs"] {
        int company_id FK
        string status
        int total
        int done
        float credits_used
    }
    OVERRIDE["consent_overrides"] {
        int company_id FK
        string purpose "enrich, retarget, export"
        int listeners
        string requested_by
    }
    CACHE["response_cache"] {
        string cache_key PK
        string cache_type
        int company_id FK
        map result
        date cached_at
    }
    LOCK["response_cache_locks"] {
        string id PK "same as cache_key"
        date expires_at
    }
    PROGRESS["backfill_progress"] {
        string id PK "station, from, to"
        int last_page
    }
    RECO["recommendation_cache_ID"] {
        string cache_key PK
        map result
    }

    STATION ||--o| CREDITS : "has"
    CREDITS ||--o{ USAGE : "every AI call"
    STATION ||--o{ JOB : "bulk enrichment runs"
    STATION ||--o{ OVERRIDE : "consent audit trail"
    STATION ||--o{ CACHE : "saved dashboard answers"
    CACHE ||--o| LOCK : "while refreshing"
    STATION ||--o{ PROGRESS : "backfill checkpoints"
    STATION ||--o| RECO : "saved recommendations"

How to read it: a line with a crow's foot means "many". A listener (PROFILE) has many history rows, can be in many audiences, many retarget groups, and is linked to many topics through the campaigns they took part in. Nothing is joined by the database: the links are plain values (an originator string, a campaign ID) that the code looks up.

Collections at a glance

Collection One per What it holds Written by Read by
segmentation_<id> station The listener profiles. One document per listener, identified by originator (unique). The realtime worker, the backfill, the nightly job, enrichment Almost everything
segmentation_<id>_history station One row each time a listener changes segment (from, to, when, and the scores at that moment). The worker and the nightly job The movement arrows, segment insights
topics_<id> station What each campaign, show and question is about: topics, brand, who set them (AI or the station). Key looks like campaign:1803. Topics refresh, station corrections Free interests, audiences, enrichment
audiences_<id> station Saved audiences: the description, the AI strategy, the member list, dates. Audience create and refresh Audiences, the nightly refresh
audience_verdicts_<id> station The AI's yes or no on doubtful audience matches, kept so each text is read once. Audience create and refresh Audiences, the nightly refresh
retarget_bucket_<id> station The retargeting bucket: groups (group_key, label, list of originators). Add to bucket Bucket and export
recommendation_cache_<id> station Saved campaign recommendations. Campaign recommender Campaign recommender
ai_credits station (one document each) Credit balance, loads, monthly limits per feature. Credit loads, usage Every AI call (checked first)
ai_usage_log shared One row per AI call: station, endpoint, model, tokens, credits charged. Every AI call AI usage panel, monthly limits
admin_jobs shared One row per job started from the admin page: what, which station, who, when, status and the last 300 lines of output. It is the record of who ran what, so the app never deletes it. The admin page The admin page
bulk_enrich_jobs shared One row per bulk enrichment run: status, totals, credits used. Bulk enrich Bulk enrich progress
consent_overrides shared The audit trail: who chose to include people who had not consented, for what, how many. Enrich, retarget and export Audit only
response_cache shared Saved dashboard answers, keyed by a hash of type, station and filters. Dashboard endpoints, the warm job Dashboard endpoints
response_cache_locks shared A short lock so only one process refreshes a cached answer at a time. Cache refresh Cache refresh
backfill_progress shared Checkpoints: how far each backfill date range got, so a rerun resumes. The backfill The backfill
Qdrant listeners_<id> station One vector per listener, for search and find-similar. Worker, backfill index step Search, find similar

Inside a listener profile

One profile document is built from groups of fields. The groups live in db/models/listener_profile.py; the code that fills them is in aggregation/.

flowchart TB
    subgraph WHO["Who"]
        direction TB
        ID["Identity<br/>company_id, originator,<br/>originator_type"]
        LINK["Identity links<br/>linked_identifiers,<br/>station_overrides"]
        DEM["Demographics<br/>gender, age_group, location,<br/>language, ethnicity<br/>(each with a source)"]
        CON["Consent<br/>permission, opt_in,<br/>consent_by_channel"]
        ID ~~~ LINK ~~~ DEM ~~~ CON
    end
    subgraph DOES["What they do"]
        direction TB
        REC["Recency and frequency<br/>last_interaction_at, recency_days,<br/>interactions 7/30/90 days, momentum"]
        CH["Channels<br/>channel_distribution,<br/>primary_channel_type"]
        CA["Campaigns and shows<br/>top_campaigns, campaign types,<br/>timeslot_distribution"]
        TP["Time patterns<br/>day of week, hour, month,<br/>public holidays"]
        REC ~~~ CH ~~~ CA ~~~ TP
    end
    subgraph SAYS["What they say and like"]
        direction TB
        CONV["What they wrote<br/>messages (last 50),<br/>ussd_answers, survey_answers"]
        AI["Interests<br/>inferred_*, inferred_interests,<br/>interest_sources, profiles_enriched_at"]
        CONV ~~~ AI
    end
    subgraph RESULT["Where they end up"]
        direction TB
        SEG["Segment<br/>current_segment, previous_segment,<br/>segment_updated_at, tags"]
        PRED["Predictions<br/>return_likelihood,<br/>return_probability, tiers"]
        SEG ~~~ PRED
    end
    DOES --> RESULT
    SAYS --> RESULT

Things worth knowing about a profile:

Indexes

Created by ensure_indexes (profiles) and db/indexes.py (the rest). The ones that matter:

Collection Index Why
profiles originator (unique) One profile per listener
profiles segment_stats_1 (segment, recency, interactions, channels) Segment counts answered from the index alone
profiles profiles_enriched_at, linked_identifiers.*, top_campaigns.id, inferred_interests Enrichment filters, identity links, topics, interests
response_cache cache_key (unique) Every dashboard read
ai_usage_log company, endpoint, time Monthly limits and the usage panel

Part 2. How the service fits together

The big picture

Four codebases cooperate. The browser never talks to this service directly: it goes through Elixir.

flowchart TB
    U["Station user (browser)"] --> FE["live-frontend<br/>Vue 2 + Element UI"]
    FE -->|"GraphQL"| EX["live-core-ex (Elixir)<br/>GraphQL for the dashboard"]
    EX -->|"HTTP + X-Segmentation-Key"| API

    PY["live-core-py (Django)<br/>owns interactions and stations"] -->|"new interaction"| MQ[("RabbitMQ<br/>segmentation.interaction.created")]
    MQ --> WK

    subgraph SEG["Segmentation service (this repo)"]
        direction LR
        API["FastAPI<br/>/api/v1/..."]
        WK["Celery worker<br/>one interaction at a time"]
        BT["Celery beat<br/>02:00 every night"] --> JOBS["Jobs and scripts<br/>backfill, nightly, warm cache"]
    end

    WK -.->|"fetch the interaction"| PY
    JOBS -.->|"fetch history"| PY

    SEG --> STORES[("Data stores<br/>MongoDB: profiles and the rest<br/>Qdrant: search vectors<br/>Redis: location lookup limits")]
    SEG --> AIX["AI<br/>OpenAI: enrichment, topics, audiences, AI search<br/>Local model: search and similar listeners"]
Piece Repo / folder Job
Dashboard live-frontend/src/containers/segmentation, src/components/segmentation, src/graphql/segmentation What the station sees. The container loads data; Dashboard.vue lays it out.
GraphQL layer live-core-ex/lib/live_web/graphql/segmentation, lib/live/segmentation/repos Turns dashboard queries into HTTP calls to this service. The rules live here in Python, not in Elixir.
Interaction source live-core-py/colony/apps/segmentation Emits one event per saved interaction (only for stations with the plugin) and serves interactions to us over HTTP.
This service colony-segmentation-service Everything below.

The plugin switch. A station only gets segmentation when the plugin with route app.profiles.segmentation is on. That one switch controls both what the dashboard shows and whether live-core sends this service that station's interactions (is_segmentation_enabled). It does not affect the backfill, which reads history with the shared key whether or not the plugin is on, so a new station is backfilled first and the plugin is switched on last.

Life of a new interaction

When a listener does something (sends a message, enters a competition), this is what happens, usually within seconds.

sequenceDiagram
    autonumber
    participant LC as live-core-py
    participant MQ as RabbitMQ
    participant W as Segmentation worker
    participant AG as aggregation
    participant DB as MongoDB
    participant VS as Qdrant

    LC->>LC: save the interaction
    LC->>LC: is the plugin on for this station?
    LC->>MQ: event (station, interaction id, originator)
    MQ->>W: process_interaction_event
    W->>W: validate (skip or reject bad events)
    W->>LC: GET /segmentation/interactions/ID (fetch it in full)
    W->>DB: make sure indexes exist (once per station)
    W->>DB: load the listener's profile (or create it)
    W->>AG: aggregate(profile, interaction)
    Note over AG: recency, frequency, channels, campaigns,<br/>time patterns, what they wrote, consent,<br/>scores, segment, tags, free interests
    AG-->>W: updated profile
    W->>DB: save the profile
    W->>VS: update the listener's vector
    W->>DB: if the segment changed, add a history row

The code: consumers/interaction_consumer.py (the steps), aggregation/profile_aggregator.py (how a profile is updated), aggregation/signal_extractor.py (each signal), scoring/ (RFM scores, segment rules, tags).

Names and photos: what is trusted

live-core's ORE mixes the person's own data with things found in the text or on a photo, so a campaign title, a product in a bot question or a till slip can end up as a "name" or a profile picture. What the service trusts:

Value Kept when Never kept when
display_name The channel gave it (WhatsApp profile name) It is a campaign title, the bot's own wording, or runs into HTML
detected_name (found in text by live-core) It is a candidate for name, from a short plain message It comes from a question, a bot conversation, a long text or a photo message
profile_image It is a real profile picture It is a photo the person sent (those stay in media)

Life of a dashboard request

The dashboard is slow if every view scans every listener, so each answer is cached in MongoDB and served stale while a fresh one is computed.

sequenceDiagram
    autonumber
    participant B as Browser
    participant EX as Elixir (GraphQL)
    participant API as FastAPI
    participant C as response_cache
    participant DB as Listener profiles

    B->>EX: query (segments, insights, listeners...)
    EX->>API: HTTP GET with the service key
    API->>C: look up the answer
    alt fresh (inside its window)
        C-->>API: saved answer
    else old but still usable
        C-->>API: saved answer (served now)
        API-)DB: refresh in the background (one at a time)
    else nothing saved
        API->>DB: compute (one computation per answer)
        API->>C: save it
    end
    API-->>EX: JSON
    EX-->>B: GraphQL response
    Note over B: every minute the dashboard checks freshness<br/>and quietly reloads if the data changed

Backfill: loading a station's history

For a new station (or after a reset). Steps and commands are in the API guide under "Adding a New Station".

flowchart LR
    S["scripts/backfill_chunks.sh<br/>station, start date, end date"] --> F
    subgraph F["Fetch, one chunk at a time (weekly by default)"]
        direction TB
        F1["Ask live-core-py for a page<br/>of interactions"] --> F2["aggregate() each one<br/>into the listener's profile"]
        F2 --> F3["Save profiles<br/>and checkpoint the page"]
    end
    F --> IM["Clear dead profile images"]
    IM --> IX["Index: embed every profile<br/>into Qdrant"]
    IX -.->|"then, by hand"| RC["Run the recalculation<br/>jobs/nightly_recalculation.py"]

The checkpoints (backfill_progress) are why a failed backfill can be rerun safely: finished pages are skipped. Qdrant is only touched once, at the end, because indexing per chunk made the backfill take hours.

The nightly job

Celery beat starts it at 02:00 (South African time) for every station. A station is any collection named segmentation_<id>.

flowchart TB
    START["02:00: jobs/nightly_recalculation.py"] --> EACH["For each station"]
    EACH --> IDX["Make sure indexes exist"]
    IDX --> CAT["Load the topic catalogue"]
    CAT --> LOOP["For each listener, 1000 at a time:<br/>recency and frequency scores, age group,<br/>segment, tags, free interests"]
    LOOP --> HIST["Write a history row<br/>for every segment change"]
    HIST --> CLEAN["Clean junk and shared<br/>names and identifiers"]
    CLEAN --> PRED["Work out each listener's<br/>return outlook"]
    PRED --> AUD["Refresh saved audiences"]
    AUD --> WARM["Warm the dashboard cache"]
    WARM --> EACH

Each of the last four steps can be switched off in config.py (NIGHTLY_*). To run it for one station by hand: python jobs/nightly_recalculation.py <id>.

AI: enrichment and free interests

Two sources fill the same fields, and they never fight: the free one runs for everyone, the AI one runs when a station asks.

flowchart TB
    subgraph FREE["Free, automatic"]
        T["Topic catalogue<br/>(campaign to topics)"] --> A["services/interests/activity.py"]
        C["Campaigns joined and<br/>what the listener wrote"] --> A
        A --> FI["interests and product affinity<br/>tagged: activity"]
    end

    subgraph PAID["On request, uses credits"]
        R["Enrich a listener or a list"] --> K{"Consent?<br/>permission = true"}
        K -->|"no, and not included"| X["Left out"]
        K -->|"yes"| CR{"Credits left and<br/>monthly limit not reached?"}
        CR -->|"no"| E["402 / 429 error"]
        CR -->|"yes"| O["OpenAI: demographics,<br/>interests, outlook"]
        O --> LG["Log usage, deduct credits"]
        O --> MI["Merge: add to the free ones<br/>tagged: ai or both"]
    end

    FI --> P["Listener profile"]
    MI --> P

Two flags decide what a listener can be included in. The server enforces it; the dialogs on the dashboard only ask.

flowchart LR
    L["Listener"] --> PF{"permission"}
    L --> OF{"opt_in"}
    PF -->|"true"| EN["May be enriched with AI"]
    OF -->|"true"| RT["May go in the retarget bucket<br/>and be exported"]
    PF -->|"false or unknown"| NO1["Left out unless the station<br/>chooses to include them"]
    OF -->|"false or unknown"| NO2["Left out unless the station<br/>chooses to include them"]
    NO1 --> AU["Every choice is written to<br/>consent_overrides"]
    NO2 --> AU

Email, Twitter, Facebook, Instagram and TikTok count as implied permission (never implied opt_in) when no consent was recorded. A recorded refusal on any channel beats it. The code: services/consent/, and update_permission_signals in aggregation/signal_extractor.py.

Code map

colony-segmentation-service/
  api/
    main.py               the FastAPI app, startup, docs pages
    dependencies.py       service-key check, the shared filter parameters
    routers/              one file per area (segments, analytics, listeners,
                          ai, bulk_enrich, audiences, topics, credits,
                          retargeting, retarget_bucket, export, search ...)
    routers/utils/        filters, caches, pipelines, formatting helpers
  aggregation/            builds a profile from an interaction
  scoring/                RFM scores, segment rules, tag rules
  consumers/              the Celery task for one new interaction
  db/
    mongo.py              collection names and connection
    indexes.py            indexes for the non-profile collections
    models/               the shape of a listener profile
    repositories/         reads and writes (profiles, audiences, buckets ...)
  services/
    ai/                   AI client, prompts, credits, enrichment
    interests/            free interests from activity
    topics/               the topic catalogue
    audiences/            audience matching and evidence
    consent/              consent rules and the audit trail
    search/               vectors, similar listeners
    export/, intelligence/, prediction/, agent/
  jobs/                   backfill, nightly recalculation, warm cache,
                          audience refresh, return prediction, indexing
  scripts/                backfill_chunks.sh, one-off database scripts
  tests/                  unit/ and integration/

Where to change things

I want to... Start here
Change what makes someone a Super fan or Dormant scoring/segment_rules.py
Add or change a behavioural tag scoring/tag_rules.py
Record a new signal on a listener db/models/listener_profile.py (add the field) and aggregation/signal_extractor.py (fill it)
Add a filter api/dependencies.py (the parameter), api/routers/utils/filters/filter_queries.py (the query), then the Elixir filter type and live-frontend/.../filterHelpers.js
Add a number to the dashboard The router in api/routers/ (wrap it in cached_or_compute), then the Elixir query and the Vue component
Change how long answers are cached config.py (AGGREGATE_CACHE_TTL_*, CACHE_STALE_SECONDS)
Change an AI prompt or the model services/ai/prompts.py, OPENAI_MODEL in settings
Change consent rules services/consent/, update_permission_signals
Change which channels imply permission IMPLIED_PERMISSION_CHANNELS in settings
Add a step to the nightly job jobs/nightly_recalculation.py
Add an index db/indexes.py (other collections) or ensure_indexes in db/repositories/listener_profile_repo.py (profiles)
Change the dashboard layout live-frontend/src/components/segmentation/Dashboard.vue

Settings you will meet

Setting Meaning
SEGMENTATION_API_KEY The key Elixir sends in X-Segmentation-Key. Must match on both sides.
LIVE_CORE_API_URL, LIVE_CORE_API_KEY Where to fetch interactions from, and the key to do it.
MONGODB_URL, MONGODB_DB_NAME, QDRANT_HOST, QDRANT_PORT, REDIS_URL, CELERY_BROKER_URL The stores and the queue.
OPENAI_API_KEY, OPENAI_MODEL AI. Without a key the AI buttons fail; everything else works.
ERASURE_HASH_SECRET Keys the hashes written when a listener is erased (POPIA). Set it before the first erasure and never change it.
IMPLIED_PERMISSION_CHANNELS Channels that count as implied permission (default 1, 2, 3, 10, 22).
NIGHTLY_* Switch the optional nightly steps off.
ADMIN_COOKIE_SECURE Send the admin sign-in cookie over HTTPS only. True in production, false for local http.
ENSURE_INDEXES_ON_STARTUP, WARM_SEARCH_MODEL_ON_STARTUP What the API does when it starts.

The admin page

/admin lets Colony staff run the operational scripts (backfill, recalculate, indexes, cache, search vectors) from a browser. It runs the same scripts as the terminal (api/admin/commands.py lists them), so the two cannot behave differently.

flowchart LR
    S["Staff browser<br/>/admin"] -->|"JWT cookie"| API["API<br/>api/admin/router.py"]
    API -->|"verify token"| LC["live-core"]
    API -->|"queue job"| Q["RabbitMQ<br/>segmentation.admin"]
    Q --> W["Admin worker<br/>jobs/admin_tasks.py"]
    W -->|"child process"| SC["Existing scripts<br/>backfill, recalculate, ..."]
    W -->|"output, status"| DB[("MongoDB<br/>admin_jobs, admin_audit")]
    API --> DB
    S -->|"polls"| API

Handy commands

Run from the service folder, with PYTHONPATH=. in front.

Command What it does
uvicorn api.main:app --port 8001 Run the API (make api)
celery -A celery_app worker --queues=segmentation.interaction.created --pool=solo Run the interaction worker (make worker)
celery -A celery_app worker --queues=segmentation.admin --pool=solo Run the admin page's job worker (make admin-worker)
celery -A celery_app beat Run the scheduler (make beat)
pytest tests/unit Unit tests. pytest tests runs everything
./scripts/backfill_chunks.sh <id> <start date> Load a station's history
python jobs/nightly_recalculation.py <id> Recalculate one station now
python jobs/warm_dashboard.py <id> Fill the dashboard cache for a station
python scripts/db/ensure_indexes.py <id> Create every index for a station
python scripts/cache/clear_cache.py all <id> Clear a station's cached answers
python scripts/db/drop_company_data.py <id> Delete everything stored for a station and start over (local only; asks first)