: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(personhog): add skill for rpc addition (#58200)
Nick Best717ea9e748ee
diff --git a/.agents/skills/adding-personhog-rpc/SKILL.md b/.agents/skills/adding-personhog-rpc/SKILL.mdnew file mode 100644index 000000000000..33e9cd59c841--- /dev/null+++ b/.agents/skills/adding-personhog-rpc/SKILL.md@@ -0,0 +1,147 @@+---+name: adding-personhog-rpc+description: >+ Guide for adding a new RPC to personhog-replica and personhog-router.+ Covers eligibility checks, proto definition, code generation for Python and Node.js clients,+ Rust implementation (storage trait, postgres queries, service handler, router wiring),+ and index compatibility validation. Use when adding a new gRPC endpoint to personhog,+ migrating a Django ORM query to personhog, or extending the personhog service API.+---++# Adding a personhog RPC++This skill walks through adding a new RPC end-to-end:+proto definition, code generation, Rust implementation, and client updates.++## Before you start: eligibility check++Personhog serves person, distinct ID, group, group type mapping, cohort membership, and feature flag hash key override data.+If the data being accessed doesn't live in one of these tables, this RPC doesn't belong in personhog:++| Table | Data category | Routing |+| ------------------------------------ | ------------- | ------------------------------------------------------------ |+| `posthog_person` | PersonData | Reads: replica (eventual) or leader (strong). Writes: leader |+| `posthog_persondistinctid` | PersonData | Same as person |+| `posthog_group` | NonPersonData | All ops: replica |+| `posthog_grouptypemapping` | NonPersonData | All ops: replica |+| `posthog_cohortpeople` | NonPersonData | All ops: replica |+| `posthog_featureflaghashkeyoverride` | NonPersonData | All ops: replica |+| `posthog_personoverride` | PersonData | Reads/writes follow person routing |+| `posthog_personlessdistinctid` | PersonData | Same as person |++If the table is not listed above, **stop** — this data should not go through personhog.++## Step 0: design the data access pattern++Before writing any proto, figure out the SQL query you need.+Then validate it against the available indexes — see [references/database-indexes.md](references/database-indexes.md).++Key questions:++- What table(s) does this query hit?+- Does the WHERE clause match an existing index? Every query must be an index scan, never a sequential scan.+- Is this a read or write? This determines routing (see table above).+- For reads: does the caller need strong consistency (primary pool) or is eventual (replica pool) acceptable?+- For batch lookups: is the batch within a single team or cross-team?++## Step 1: define proto messages and RPC++All proto files live in `proto/personhog/`.+See [references/proto-conventions.md](references/proto-conventions.md) for message conventions and a worked example.++### Where to add what++1. **Message types** → `proto/personhog/types/v1/<domain>.proto` (person.proto, group.proto, cohort.proto, feature_flag.proto, or common.proto)+2. **Service RPC** → `proto/personhog/service/v1/service.proto` (the public API clients call)+3. **Replica RPC** → `proto/personhog/replica/v1/replica.proto` (the internal API the router delegates to)+4. **Leader RPC** → `proto/personhog/leader/v1/leader.proto` (only if this is a person-data write routed to leader)++The service and replica protos must both declare the RPC with identical signature.+The router delegates from service → replica (or leader) transparently.++## Step 2: generate client stubs++### Python++```bash+bin/generate_personhog_proto.sh+```++Then update three files:++- `posthog/personhog_client/proto/__init__.py` — add re-exports for new request/response message types+- `posthog/personhog_client/client.py` — add a wrapper method matching the pattern of existing methods+- `posthog/personhog_client/fake_client.py` — implement the method for test use++### Node.js++```bash+cd nodejs && pnpm run generate:personhog-proto+```++Then update:++- `nodejs/src/ingestion/personhog/client.ts` — add a wrapper method matching the pattern of existing methods+- `nodejs/src/ingestion/personhog/client.test.ts` — add a default stub to `SERVICE_DEFAULTS` for the new RPC++### Rust++No generation step needed — tonic regenerates on `cargo build`.+But you must implement the RPC (next step), or the build will fail.++## Step 3: implement in Rust++The compiler guides you — once the proto is defined, `cargo build` errors tell you exactly which trait methods are missing.++### 3a. Storage layer (personhog-replica)++1. **Add a trait method** in `rust/personhog-replica/src/storage/traits/<domain>.rs`+2. **Implement the query** in `rust/personhog-replica/src/storage/postgres/<domain>.rs`+ - Use `sqlx::query_as!` or `sqlx::query!` macros+ - Add timing instrumentation via `DB_QUERY_DURATION` and `DB_ROWS_RETURNED` metrics+ - Use `self.replica_pool` for reads, `self.primary_pool` for writes+ - Return early for empty batch inputs+3. **Add storage tests** in `rust/personhog-replica/tests/storage_tests.rs`++### 3b. Service layer (personhog-replica)++1. **Add the RPC handler** in `rust/personhog-replica/src/service/mod.rs`+ - Extract fields from the proto request+ - Call the storage trait method+ - Convert storage results to proto responses+ - Map storage errors to tonic `Status` codes+2. **Add service tests** in `rust/personhog-replica/tests/service_tests.rs`++### 3c. Router wiring (personhog-router)++1. **Add the method** to `rust/personhog-router/src/router/mod.rs`+ - Use the `route_request` function (imported from `routing.rs`) with the correct `DataCategory` and `OperationType`+ - Call the replica (or leader) backend+ - Use the `call_backend!` macro for instrumentation+2. **Add the service impl** to `rust/personhog-router/src/service/mod.rs`+ - Invoke the `route_request!` macro (defined at the top of this file) to delegate to the router+3. **Add to the backend trait** in `rust/personhog-router/src/backend/mod.rs` and implement in `replica.rs`+4. **Add router tests** in `rust/personhog-router/tests/`++Use `rstest` parameterized tests where multiple variations of the same behavior are being tested.++## Step 4: verify++```bash+cargo build -p personhog-proto+cargo build -p personhog-replica+cargo build -p personhog-router+cargo test -p personhog-replica+cargo test -p personhog-router+```++## Checklist++- [ ] Query uses an existing index (no seq scans)+- [ ] Proto messages added to `types/v1/<domain>.proto`+- [ ] RPC added to both `service.proto` and `replica.proto` (and `leader.proto` if needed)+- [ ] Python stubs generated, `proto/__init__.py` updated, `client.py` method added, `fake_client.py` updated+- [ ] Node.js stubs generated, `client.test.ts` SERVICE_DEFAULTS updated+- [ ] Rust storage trait + postgres impl + service handler + router wiring all implemented+- [ ] Tests added at storage, service, and router layers+- [ ] `cargo build` and `cargo test` pass for all three cratesdiff --git a/.agents/skills/adding-personhog-rpc/references/database-indexes.md b/.agents/skills/adding-personhog-rpc/references/database-indexes.mdnew file mode 100644index 000000000000..e08f5a2a1ce8--- /dev/null+++ b/.agents/skills/adding-personhog-rpc/references/database-indexes.md@@ -0,0 +1,128 @@+# Database indexes for personhog tables++Every personhog query must use an index scan.+Before designing your RPC, verify your WHERE clause matches one of these indexes.++All indexes below are sourced from `rust/persons_migrations/` SQL files — the single source of truth for these tables.++## posthog_person++Partitioned by `team_id` (64 hash partitions).+Primary key is composite `(team_id, id)`.++| Index name | Type | Columns | Notes |+| ----------------------------- | ------ | ----------------- | --------------------------------------------------------- |+| `posthog_person_new_pkey` | PK | `(team_id, id)` | Partition-pruned lookup |+| `posthog_person_new_uuid_idx` | UNIQUE | `(team_id, uuid)` | Partition-pruned uuid lookup |+| `posthog_person_p{i}_id_idx` | INDEX | `(id)` | Per-partition index on id (64 indexes, one per partition) |++Constraints: `check_properties_size` — `pg_column_size(properties) <= 655360` (on old unpartitioned table; `personhog_person_tmp` has equivalent).++**Typical query patterns:**++- `WHERE team_id = $1 AND id = $2` → PK scan+- `WHERE team_id = $1 AND uuid = $2` → `posthog_person_new_uuid_idx` (partition-pruned)+- `WHERE team_id = $1 AND id = ANY($2)` → PK scan+- `WHERE team_id = $1 AND uuid = ANY($2)` → `posthog_person_new_uuid_idx` scan++## posthog_persondistinctid++| Index name | Type | Columns | Notes |+| --------------------------------------------- | ------ | ------------------------------------------------------ | ---------------------------------- |+| `unique_distinct_id_for_team` | UNIQUE | `(team_id, distinct_id)` | Primary lookup path |+| `posthog_persondistinctid_person_id_5d655bba` | INDEX | `(person_id)` | Join back to person |+| `posthog_persondistinctid_person_id_fkey` | FK | `(team_id, person_id)` → `posthog_person(team_id, id)` | NOT VALID (added during migration) |++**Typical query patterns:**++- `WHERE team_id = $1 AND distinct_id = $2` → `unique_distinct_id_for_team` scan+- `WHERE person_id = $1` → `posthog_persondistinctid_person_id_5d655bba` scan+- `JOIN posthog_person p ON p.id = d.person_id AND p.team_id = d.team_id WHERE d.team_id = $1 AND d.distinct_id = $2` → unique index + PK++## posthog_personlessdistinctid++| Index name | Type | Columns | Notes |+| ---------------------------------------- | ------ | ------------------------ | ------------------- |+| `unique_personless_distinct_id_for_team` | UNIQUE | `(team_id, distinct_id)` | Primary lookup path |++## posthog_group++| Index name | Type | Columns | Notes |+| ---------------------------------- | ------ | ---------------------------------------- | ------------------- |+| `unique_team_group_key_group_type` | UNIQUE | `(team_id, group_key, group_type_index)` | Primary lookup path |+| `posthog_group_team_id_b3aed896` | INDEX | `(team_id)` | Team-level scans |++**Typical query patterns:**++- `WHERE team_id = $1 AND group_type_index = $2 AND group_key = $3` → `unique_team_group_key_group_type` scan+- `WHERE team_id = $1 AND group_type_index = $2` → partial unique index scan (leading columns)+- `WHERE team_id = $1` → `posthog_group_team_id_b3aed896` scan++## posthog_grouptypemapping++| Index name | Type | Columns | Notes |+| ------------------------------------------------------- | ------ | -------------------------------- | --------------------------- |+| `unique_group_types_for_project` | UNIQUE | `(project_id, group_type)` | Uniqueness |+| `unique_group_type_index_for_project` | UNIQUE | `(project_id, group_type_index)` | Uniqueness |+| `posthog_group_type_proj_idx` | INDEX | `(project_id, group_type)` | Redundant with unique above |+| `posthog_group_type_i_proj_idx` | INDEX | `(project_id, group_type_index)` | Redundant with unique above |+| `posthog_grouptypemapping_project_id_239c0515` | INDEX | `(project_id)` | Project-level scans |+| `posthog_grouptypemapping_team_id_5fb54d04` | INDEX | `(team_id)` | Team-level scans |+| `posthog_grouptypemapping_detail_dashboard_id_54b0edbb` | INDEX | `(detail_dashboard_id)` | Dashboard FK |++Constraints: `group_type_index_is_less_than_or_equal_5`, `group_type_project_id_is_not_null`.++**Typical query patterns:**++- `WHERE project_id = $1` → `posthog_grouptypemapping_project_id_239c0515` or leading column of unique indexes+- `WHERE project_id = $1 AND group_type_index = $2` → `unique_group_type_index_for_project`+- `WHERE team_id = $1` → `posthog_grouptypemapping_team_id_5fb54d04`++## posthog_cohortpeople++| Index name | Type | Columns | Notes |+| ----------------------------------------- | ----- | ------------------------ | ------------------ |+| `posthog_coh_cohort__89c25f_idx` | INDEX | `(cohort_id, person_id)` | Composite lookup |+| `posthog_cohortpeople_cohort_id_1f371733` | INDEX | `(cohort_id)` | Cohort-level scans |+| `posthog_cohortpeople_person_id_33da7d3f` | INDEX | `(person_id)` | Person-level scans |++No FK — the FK to posthog_person was dropped during the partitioning migration and not re-added.++**Typical query patterns:**++- `WHERE cohort_id = $1 AND person_id = $2` → `posthog_coh_cohort__89c25f_idx` scan+- `WHERE cohort_id = $1` → `posthog_cohortpeople_cohort_id_1f371733` scan+- `WHERE person_id = $1` → `posthog_cohortpeople_person_id_33da7d3f` scan++## posthog_featureflaghashkeyoverride++| Index name | Type | Columns | Notes |+| ------------------------------------------------------- | ------ | ---------------------------------------- | ------------------- |+| `unique_hash_key_for_user_team_feature_flag` | UNIQUE | `(team_id, person_id, feature_flag_key)` | Primary lookup path |+| `posthog_featureflaghashkeyoverride_person_id_7e517f7c` | INDEX | `(person_id)` | Person-level scans |+| `posthog_featureflaghashkeyoverride_team_id_b626eed2` | INDEX | `(team_id)` | Team-level scans |++No FK — the FK to posthog_person was dropped during the partitioning migration and not re-added.++**Typical query patterns:**++- `WHERE team_id = $1 AND person_id = $2` → partial `unique_hash_key_for_user_team_feature_flag` scan (leading columns)+- `WHERE team_id = $1 AND person_id = $2 AND feature_flag_key = $3` → full unique index scan++## posthog_personoverride++| Index name | Type | Columns | Notes |+| ----------------------------------------------------- | ------- | ------------------------------------------------------ | -------------------- |+| `unique_override_per_old_person_id` | UNIQUE | `(team_id, old_person_id)` | Primary lookup path |+| `posthog_personoverride_old_person_id_4c1deac0` | INDEX | `(old_person_id)` | Single-column lookup |+| `posthog_personoverride_override_person_id_9f32aab1` | INDEX | `(override_person_id)` | Reverse lookup |+| `posthog_personoverride_team_id_92291e67` | INDEX | `(team_id)` | Team-level scans |+| `exclude_override_person_id_from_being_old_person_id` | EXCLUDE | GiST on `(team_id, override_person_id, old_person_id)` | Integrity |++Constraints: `old_person_id_different_from_override_person_id` — `old_person_id != override_person_id`.+FKs: `old_person_id` and `override_person_id` both reference `posthog_personoverridemapping(id)`.++## If you need a new index++If your query can't use an existing index, you need a new migration in `rust/persons_migrations` before adding the RPC.+Discuss with the team first — new indexes on large partitioned tables have operational implications.diff --git a/.agents/skills/adding-personhog-rpc/references/proto-conventions.md b/.agents/skills/adding-personhog-rpc/references/proto-conventions.mdnew file mode 100644index 000000000000..7637590f0c4c--- /dev/null+++ b/.agents/skills/adding-personhog-rpc/references/proto-conventions.md@@ -0,0 +1,113 @@+# Proto conventions and worked example++## Message conventions++- `int64` for IDs, timestamps (Unix millis), versions+- `bytes` for JSON data (not `string`) — properties, properties_last_updated_at, properties_last_operation, default_columns+- `optional` for nullable fields+- Stay at v1 for additive changes; bump to v2 only for breaking changes+- Never reuse field numbers after deletion+- Request messages: `<RpcName>Request`+- Response messages: `<RpcName>Response` (or a shared response type like `PersonsResponse` if appropriate)+- Include `ReadOptions read_options` field on read requests that need consistency control++## ReadOptions and consistency++```protobuf+// Already defined in common.proto — import it, don't redefine+import "personhog/types/v1/common.proto";++message YourReadRequest {+ int64 team_id = 1;+ // ... other fields ...+ ReadOptions read_options = N; // last field+}+```++`ReadOptions` contains a `ConsistencyLevel` enum:++- `EVENTUAL` (default) — queries the replica pool+- `STRONG` — queries the primary pool (only meaningful for PersonData reads)++For NonPersonData, the replica handles consistency internally — the router always sends to replica regardless of consistency level.++## File organization++| Proto file | Purpose |+| --------------------------------------------- | ----------------------------------------------------------------------------- |+| `proto/personhog/types/v1/person.proto` | Person, DistinctId messages and all person-related request/response types |+| `proto/personhog/types/v1/group.proto` | Group, GroupTypeMapping messages and all group-related request/response types |+| `proto/personhog/types/v1/cohort.proto` | CohortMembership messages and cohort-related request/response types |+| `proto/personhog/types/v1/feature_flag.proto` | HashKeyOverride messages and feature flag request/response types |+| `proto/personhog/types/v1/common.proto` | ReadOptions, ConsistencyLevel, TeamDistinctId — shared across domains |+| `proto/personhog/service/v1/service.proto` | PersonHogService — public API (what clients call) |+| `proto/personhog/replica/v1/replica.proto` | PersonHogReplica — internal API (what the router calls) |+| `proto/personhog/leader/v1/leader.proto` | PersonHogLeader — internal write API for person data |++## Worked example: adding GetPersonCount++### 1. Add messages to `types/v1/person.proto`++```protobuf+message GetPersonCountRequest {+ int64 team_id = 1;+ ReadOptions read_options = 2;+}++message GetPersonCountResponse {+ int64 count = 1;+}+```++### 2. Add RPC to `service/v1/service.proto`++```protobuf+service PersonHogService {+ // ... existing RPCs ...+ rpc GetPersonCount(personhog.types.v1.GetPersonCountRequest) returns (personhog.types.v1.GetPersonCountResponse);+}+```++### 3. Add RPC to `replica/v1/replica.proto`++```protobuf+service PersonHogReplica {+ // ... existing RPCs ...+ rpc GetPersonCount(personhog.types.v1.GetPersonCountRequest) returns (personhog.types.v1.GetPersonCountResponse);+}+```++The RPC signature **must be identical** in both service and replica protos.++### 4. Routing decision++This is a PersonData read → routed to replica for EVENTUAL, leader for STRONG.+In the router, use:++```rust+let route = route_request(+ DataCategory::PersonData,+ OperationType::Read,+ get_consistency(&request.read_options),+)?;+```++### 5. Python client wrapper (in client.py)++```python+def get_person_count(self, request: GetPersonCountRequest) -> GetPersonCountResponse:+ return self._stub.GetPersonCount(request, timeout=self._timeout)+```++### 6. Fake client method (in fake_client.py)++```python+def get_person_count(self, request: Any) -> Any:+ team_id = request.team_id+ count = sum(1 for (tid, _) in self._persons_by_id if tid == team_id)+ call = _Call("get_person_count", request)+ resp = person_pb2.GetPersonCountResponse(count=count) # or however the response is built+ call.response = resp+ self.calls.append(call)+ return resp+```