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.

fix(flags): stop person merges from losing real hash keys (#113480)

Phil Haackd89edf9d5652
diff --git a/nodejs/src/common/persons/person-utils.ts b/nodejs/src/common/persons/person-utils.ts
index 9224307dd9a3..f92bab4f14ae 100644
--- a/nodejs/src/common/persons/person-utils.ts
+++ b/nodejs/src/common/persons/person-utils.ts
@@ -44,7 +44,9 @@ const BARE_CASE_INSENSITIVE_ILLEGAL_IDS = [
'false',
]
-// '$posthog_cookieless' is the cookieless mode sentinel. Every cookieless visitor shares it.
+/** Every cookieless visitor shares this distinct id. */
+export const COOKIELESS_SENTINEL_VALUE = '$posthog_cookieless'
+
const BARE_CASE_SENSITIVE_ILLEGAL_IDS = [
'[object Object]',
'NaN',
@@ -53,7 +55,7 @@ const BARE_CASE_SENSITIVE_ILLEGAL_IDS = [
'null',
'0',
'undefined',
- '$posthog_cookieless',
+ COOKIELESS_SENTINEL_VALUE,
]
// we have seen illegal ids received but wrapped in double quotes
diff --git a/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts b/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts
index 96c8dbea8be0..5c55996e1d60 100644
--- a/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts
+++ b/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts
@@ -7,6 +7,7 @@ import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { PERSONS_OUTPUT, PERSON_DISTINCT_IDS_OUTPUT } from '~/common/outputs/persons'
import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'
import { PersonMessage } from '~/common/persons/person-message'
+import { COOKIELESS_SENTINEL_VALUE } from '~/common/persons/person-utils'
import { closeHub, createHub } from '~/common/utils/db/hub'
import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'
import { parseJSON } from '~/common/utils/json-parse'
@@ -2498,12 +2499,24 @@ describe('PostgresPersonRepository', () => {
feature_flag_key: 'beta-feature',
hash_key: 'existing_override_value_for_beta_feature',
})
+ await insertRow(hub.postgres, 'posthog_featureflaghashkeyoverride', {
+ team_id: team.id,
+ person_id: sourcePersonID,
+ feature_flag_key: 'gamma',
+ hash_key: 'override_value_for_gamma',
+ })
+ await insertRow(hub.postgres, 'posthog_featureflaghashkeyoverride', {
+ team_id: team.id,
+ person_id: targetPersonID,
+ feature_flag_key: 'gamma',
+ hash_key: COOKIELESS_SENTINEL_VALUE,
+ })
await repository.updateCohortsAndFeatureFlagsForMerge(team.id, sourcePersonID, targetPersonID)
const result = await getAllHashKeyOverrides()
- expect(result.length).toEqual(2)
+ expect(result.length).toEqual(3)
expect(result).toEqual(
expect.arrayContaining([
{
@@ -2516,6 +2529,11 @@ describe('PostgresPersonRepository', () => {
hash_key: 'override_value_for_aloha',
person_id: targetPersonID,
},
+ {
+ feature_flag_key: 'gamma',
+ hash_key: 'override_value_for_gamma',
+ person_id: targetPersonID,
+ },
])
)
})
@@ -3594,29 +3612,30 @@ describe('PostgresPersonRepository', () => {
})
describe('updateCohortsAndFeatureFlagsForMergeBatch()', () => {
- it('moves overrides from multiple sources, keeping target values on conflict', async () => {
+ it('moves overrides from multiple sources, keeping target values on conflict unless they are the cookieless sentinel', async () => {
const source1 = await createTestPerson(team.id, 'fold-ff-source-1', {})
const source2 = await createTestPerson(team.id, 'fold-ff-source-2', {})
const target = await createTestPerson(team.id, 'fold-ff-target', {})
- await insertRow(hub.postgres, 'posthog_featureflaghashkeyoverride', {
- team_id: team.id,
- person_id: source1.id,
- feature_flag_key: 'aloha',
- hash_key: 'source1_aloha',
- })
- await insertRow(hub.postgres, 'posthog_featureflaghashkeyoverride', {
- team_id: team.id,
- person_id: source2.id,
- feature_flag_key: 'beta-feature',
- hash_key: 'source2_beta',
- })
- await insertRow(hub.postgres, 'posthog_featureflaghashkeyoverride', {
- team_id: team.id,
- person_id: target.id,
- feature_flag_key: 'beta-feature',
- hash_key: 'target_beta',
- })
+ for (const [personId, flagKey, hashKey] of [
+ [source1.id, 'aloha', COOKIELESS_SENTINEL_VALUE],
+ [source2.id, 'aloha', 'source2_aloha'],
+ [source2.id, 'beta-feature', 'source2_beta'],
+ [target.id, 'beta-feature', 'target_beta'],
+ [source1.id, 'gamma', 'source1_gamma'],
+ [target.id, 'gamma', COOKIELESS_SENTINEL_VALUE],
+ [source1.id, 'delta', 'source1_delta'],
+ [source2.id, 'delta', 'source2_delta'],
+ [target.id, 'delta', COOKIELESS_SENTINEL_VALUE],
+ [source1.id, 'epsilon', COOKIELESS_SENTINEL_VALUE],
+ ]) {
+ await insertRow(hub.postgres, 'posthog_featureflaghashkeyoverride', {
+ team_id: team.id,
+ person_id: personId,
+ feature_flag_key: flagKey,
+ hash_key: hashKey,
+ })
+ }
await repository.updateCohortsAndFeatureFlagsForMergeBatch(team.id, [source1.id, source2.id], target.id)
@@ -3628,11 +3647,17 @@ describe('PostgresPersonRepository', () => {
)
expect(result.rows).toEqual(
expect.arrayContaining([
- { feature_flag_key: 'aloha', hash_key: 'source1_aloha', person_id: target.id },
+ { feature_flag_key: 'aloha', hash_key: 'source2_aloha', person_id: target.id },
{ feature_flag_key: 'beta-feature', hash_key: 'target_beta', person_id: target.id },
+ { feature_flag_key: 'gamma', hash_key: 'source1_gamma', person_id: target.id },
+ {
+ feature_flag_key: 'delta',
+ hash_key: expect.stringMatching(/^source[12]_delta$/),
+ person_id: target.id,
+ },
])
)
- expect(result.rows).toHaveLength(2)
+ expect(result.rows).toHaveLength(4)
})
it('is a no-op for empty sources', async () => {
diff --git a/nodejs/src/common/persons/repositories/postgres-person-repository.ts b/nodejs/src/common/persons/repositories/postgres-person-repository.ts
index be284aa45f53..c71cbf52b131 100644
--- a/nodejs/src/common/persons/repositories/postgres-person-repository.ts
+++ b/nodejs/src/common/persons/repositories/postgres-person-repository.ts
@@ -12,6 +12,7 @@ import {
} from '~/common/persons/metrics'
import { canTrimProperty } from '~/common/persons/person-property-utils'
import { PersonUpdate, toInternalPerson } from '~/common/persons/person-update-batch'
+import { COOKIELESS_SENTINEL_VALUE } from '~/common/persons/person-utils'
import { CreatePersonResult, MoveDistinctIdsResult, PersonPropertiesSize } from '~/common/utils/db/db'
import {
moveDistinctIdsCountHistogram,
@@ -2445,37 +2446,12 @@ export class PostgresPersonRepository
targetPersonID: InternalPerson['id'],
tx?: TransactionClient
): Promise<void> {
- // When personIDs change, update places depending on a person_id foreign key
-
- await this.postgres.query(
- tx ?? PostgresUse.PERSONS_WRITE,
- // Do two high level things in a single round-trip to the DB.
- //
- // 1. Update cohorts.
- // 2. Update (delete+insert) feature flags.
- //
- // NOTE: Every override is unique for a team-personID-featureFlag combo. In case we run
- // into a conflict we would ideally use the override from most recent personId used, so
- // the user experience is consistent, however that's tricky to figure out this also
- // happens rarely, so we're just going to do the performance optimal thing i.e. do
- // nothing on conflicts, so we keep using the value that the person merged into had
- `WITH cohort_update AS (
- UPDATE posthog_cohortpeople
- SET person_id = $1
- WHERE person_id = $2
- RETURNING person_id
- ),
- deletions AS (
- DELETE FROM posthog_featureflaghashkeyoverride
- WHERE team_id = $3 AND person_id = $2
- RETURNING team_id, person_id, feature_flag_key, hash_key
- )
- INSERT INTO posthog_featureflaghashkeyoverride (team_id, person_id, feature_flag_key, hash_key)
- SELECT team_id, $1, feature_flag_key, hash_key
- FROM deletions
- ON CONFLICT DO NOTHING`,
- [targetPersonID, sourcePersonID, teamID],
- 'updateCohortAndFeatureFlagsPeople'
+ await this.moveCohortsAndFeatureFlags(
+ teamID,
+ [sourcePersonID],
+ targetPersonID,
+ 'updateCohortAndFeatureFlagsPeople',
+ tx
)
}
@@ -2489,10 +2465,29 @@ export class PostgresPersonRepository
return
}
- // Multi-source variant of updateCohortsAndFeatureFlagsForMerge — same
- // two operations, one round-trip for all folded source persons.
+ await this.moveCohortsAndFeatureFlags(
+ teamID,
+ sourcePersonIDs,
+ targetPersonID,
+ 'updateCohortAndFeatureFlagsPeopleBatch',
+ tx
+ )
+ }
+
+ private async moveCohortsAndFeatureFlags(
+ teamID: Team['id'],
+ sourcePersonIDs: InternalPerson['id'][],
+ targetPersonID: InternalPerson['id'],
+ tag: string,
+ tx?: TransactionClient
+ ): Promise<void> {
await this.postgres.query(
tx ?? PostgresUse.PERSONS_WRITE,
+ // On a conflict the target's override wins, because the most recent person's override is hard
+ // to determine. The cookieless sentinel is not a real key. The merge drops a source's sentinel
+ // row. A source's real key replaces a sentinel on the target. Postgres rejects an
+ // ON CONFLICT DO UPDATE statement that changes the same row twice, so DISTINCT ON keeps one
+ // row per flag.
`WITH cohort_update AS (
UPDATE posthog_cohortpeople
SET person_id = $1
@@ -2505,11 +2500,14 @@ export class PostgresPersonRepository
RETURNING team_id, person_id, feature_flag_key, hash_key
)
INSERT INTO posthog_featureflaghashkeyoverride (team_id, person_id, feature_flag_key, hash_key)
- SELECT team_id, $1, feature_flag_key, hash_key
+ SELECT DISTINCT ON (feature_flag_key) team_id, $1, feature_flag_key, hash_key
FROM deletions
- ON CONFLICT DO NOTHING`,
- [targetPersonID, sourcePersonIDs, teamID],
- 'updateCohortAndFeatureFlagsPeopleBatch'
+ WHERE hash_key <> $4
+ ON CONFLICT (team_id, person_id, feature_flag_key) DO UPDATE
+ SET hash_key = EXCLUDED.hash_key
+ WHERE posthog_featureflaghashkeyoverride.hash_key = $4`,
+ [targetPersonID, sourcePersonIDs, teamID, COOKIELESS_SENTINEL_VALUE],
+ tag
)
}
diff --git a/nodejs/src/ingestion/common/cookieless/cookieless-manager.test.ts b/nodejs/src/ingestion/common/cookieless/cookieless-manager.test.ts
index 975cb6cf8675..97c1aa90395b 100644
--- a/nodejs/src/ingestion/common/cookieless/cookieless-manager.test.ts
+++ b/nodejs/src/ingestion/common/cookieless/cookieless-manager.test.ts
@@ -3,6 +3,7 @@ import { Message } from 'node-rdkafka'
import path from 'path'
import { cookielessRedisErrorCounter } from '~/common/metrics'
+import { COOKIELESS_SENTINEL_VALUE } from '~/common/persons/person-utils'
import { RedisOperationError } from '~/common/utils/db/error'
import { PostgresUse } from '~/common/utils/db/postgres'
import { parseJSON } from '~/common/utils/json-parse'
@@ -16,7 +17,6 @@ import { CookielessServerHashMode, EventHeaders, PipelineEvent, Team } from '~/t
import {
COOKIELESS_MODE_FLAG_PROPERTY,
- COOKIELESS_SENTINEL_VALUE,
CookielessManager,
bufferToSessionState,
extractRootDomain,
diff --git a/nodejs/src/ingestion/common/cookieless/cookieless-manager.ts b/nodejs/src/ingestion/common/cookieless/cookieless-manager.ts
index f38234d953f1..3f1fdcbf5e6f 100644
--- a/nodejs/src/ingestion/common/cookieless/cookieless-manager.ts
+++ b/nodejs/src/ingestion/common/cookieless/cookieless-manager.ts
@@ -11,6 +11,7 @@ import { getDomain } from 'tldts'
import * as siphashDouble from '@posthog/siphash/lib/siphash-double'
import { cookielessRedisErrorCounter } from '~/common/metrics'
+import { COOKIELESS_SENTINEL_VALUE } from '~/common/persons/person-utils'
import { instrumentFn } from '~/common/tracing/tracing-utils'
import { ConcurrencyController } from '~/common/utils/concurrencyController'
import { RedisOperationError } from '~/common/utils/db/error'
@@ -72,7 +73,6 @@ import { RedisHelpers } from './redis-helpers'
*/
const TIMEZONE_FALLBACK = 'UTC'
-export const COOKIELESS_SENTINEL_VALUE = '$posthog_cookieless'
export const COOKIELESS_MODE_FLAG_PROPERTY = '$cookieless_mode'
export const COOKIELESS_EXTRA_HASH_CONTENTS_PROPERTY = '$cookieless_extra'
const MAX_NEGATIVE_TIMEZONE_HOURS = 12
diff --git a/nodejs/src/ingestion/common/steps/event-preprocessing/rate-limit-to-overflow-step.test.ts b/nodejs/src/ingestion/common/steps/event-preprocessing/rate-limit-to-overflow-step.test.ts
index d2a4d440aa8e..2ad7add2ad85 100644
--- a/nodejs/src/ingestion/common/steps/event-preprocessing/rate-limit-to-overflow-step.test.ts
+++ b/nodejs/src/ingestion/common/steps/event-preprocessing/rate-limit-to-overflow-step.test.ts
@@ -1,5 +1,5 @@
import { OVERFLOW_OUTPUT } from '~/common/outputs'
-import { COOKIELESS_SENTINEL_VALUE } from '~/ingestion/common/cookieless/cookieless-manager'
+import { COOKIELESS_SENTINEL_VALUE } from '~/common/persons/person-utils'
import { OverflowRedirectService } from '~/ingestion/common/overflow-redirect/overflow-redirect-service'
import { PipelineResultType } from '~/ingestion/framework/results'
import { createTestEventHeaders } from '~/tests/helpers/event-headers'
diff --git a/nodejs/src/ingestion/ingestion-consumer.serial.test.ts b/nodejs/src/ingestion/ingestion-consumer.serial.test.ts
index 9c1a683c6626..232427d41525 100644
--- a/nodejs/src/ingestion/ingestion-consumer.serial.test.ts
+++ b/nodejs/src/ingestion/ingestion-consumer.serial.test.ts
@@ -12,14 +12,12 @@ import { template as geoipTemplate } from '~/cdp/templates/_transformations/geoi
import { compileHog } from '~/cdp/templates/compiler'
import { HogFunctionType } from '~/cdp/types'
import { ClickhouseGroupRepository } from '~/common/groups/repositories/clickhouse-group-repository'
+import { COOKIELESS_SENTINEL_VALUE } from '~/common/persons/person-utils'
import { PostgresUse } from '~/common/utils/db/postgres'
import { parseJSON } from '~/common/utils/json-parse'
import { logger } from '~/common/utils/logger'
import { UUIDT } from '~/common/utils/utils'
-import {
- COOKIELESS_MODE_FLAG_PROPERTY,
- COOKIELESS_SENTINEL_VALUE,
-} from '~/ingestion/common/cookieless/cookieless-manager'
+import { COOKIELESS_MODE_FLAG_PROPERTY } from '~/ingestion/common/cookieless/cookieless-manager'
import { BatchWritingPersonsStore } from '~/ingestion/common/persons/batch-writing-person-store'
import { createPrepareEventStep } from '~/ingestion/common/steps/event-processing/prepare-event-step'
import { createProcessGroupsStep } from '~/ingestion/common/steps/event-processing/process-groups-step'
diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts
index bb2d3c8c1600..930da01ca5b8 100644
--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts
+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts
@@ -6,6 +6,7 @@ import { KafkaProducerWrapper } from '~/common/kafka/producer'
import { TophogOutput } from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'
+import { COOKIELESS_SENTINEL_VALUE } from '~/common/persons/person-utils'
import { PersonReadRepository } from '~/common/persons/repositories/person-repository'
import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'
import { EventIngestionRestrictionManager, RestrictionType } from '~/common/utils/event-ingestion-restrictions'
@@ -13,7 +14,7 @@ import { parseJSON } from '~/common/utils/json-parse'
import { PromiseScheduler } from '~/common/utils/promise-scheduler'
import { TeamManager } from '~/common/utils/team-manager'
import { UUIDT } from '~/common/utils/utils'
-import { COOKIELESS_SENTINEL_VALUE, CookielessManager } from '~/ingestion/common/cookieless/cookieless-manager'
+import { CookielessManager } from '~/ingestion/common/cookieless/cookieless-manager'
import { OverflowRedirectService } from '~/ingestion/common/overflow-redirect/overflow-redirect-service'
import { TopHogRegistry } from '~/ingestion/framework/extensions/tophog'
import { createOkContext } from '~/ingestion/framework/helpers'
diff --git a/rust/personhog-common/src/persons.rs b/rust/personhog-common/src/persons.rs
index 5f41f55c87ce..c0c817e761e6 100644
--- a/rust/personhog-common/src/persons.rs
+++ b/rust/personhog-common/src/persons.rs
@@ -20,6 +20,10 @@ pub fn person_uuid(team_id: i64, distinct_id: &str) -> Uuid {
)
}
+/// Every cookieless visitor shares this distinct id. Mirrors the constant in
+/// `common-cookieless`, which the personhog services do not depend on.
+pub const COOKIELESS_SENTINEL_VALUE: &str = "$posthog_cookieless";
+
/// Validate a configured table identifier before it is interpolated into
/// SQL (identifiers cannot be bound as parameters).
pub fn validate_table_name(table: &str) -> Result<(), String> {
diff --git a/rust/personhog-identity/src/lifecycle/merge.rs b/rust/personhog-identity/src/lifecycle/merge.rs
index c0a53749978d..425e37f03ea4 100644
--- a/rust/personhog-identity/src/lifecycle/merge.rs
+++ b/rust/personhog-identity/src/lifecycle/merge.rs
@@ -37,7 +37,7 @@ use std::sync::Arc;
use async_trait::async_trait;
use common_sqlx_macros::{mirrored_query, mirrored_query_as, mirrored_query_scalar};
use futures::stream::{self, StreamExt};
-use personhog_common::persons::person_uuid;
+use personhog_common::persons::{person_uuid, COOKIELESS_SENTINEL_VALUE};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tonic::{Code, Status};
@@ -1760,7 +1760,9 @@ async fn move_cohort_membership(
}
/// Hash-key overrides move target-wins: the target's existing override
-/// for a flag beats any source's.
+/// for a flag beats any source's. The cookieless sentinel is not a real
+/// key. The merge drops a source's sentinel row. A source's real key
+/// replaces a sentinel on the target.
async fn move_hash_key_overrides(
tx: &mut Tx<'_>,
tables: &IdentityTables,
@@ -1768,6 +1770,8 @@ async fn move_hash_key_overrides(
sources: &[i64],
target: i64,
) -> Result<(), SagaError> {
+ // Postgres rejects an ON CONFLICT DO UPDATE statement that changes the
+ // same row twice, so DISTINCT ON keeps one row per flag.
let move_sql = format!(
r#"
WITH removed AS (
@@ -1776,8 +1780,12 @@ async fn move_hash_key_overrides(
RETURNING feature_flag_key, hash_key
)
INSERT INTO {override_table} (team_id, person_id, feature_flag_key, hash_key)
- SELECT $1, $3, feature_flag_key, hash_key FROM removed
- ON CONFLICT (team_id, person_id, feature_flag_key) DO NOTHING
+ SELECT DISTINCT ON (feature_flag_key) $1, $3, feature_flag_key, hash_key
+ FROM removed
+ WHERE hash_key <> $4
+ ON CONFLICT (team_id, person_id, feature_flag_key) DO UPDATE
+ SET hash_key = EXCLUDED.hash_key
+ WHERE {override_table}.hash_key = $4
"#,
override_table = tables.ff_hash_key_override,
);
@@ -1785,6 +1793,7 @@ async fn move_hash_key_overrides(
.bind(team_id)
.bind(sources)
.bind(target)
+ .bind(COOKIELESS_SENTINEL_VALUE)
.execute(&mut **tx)
.await?;
Ok(())
diff --git a/rust/personhog-identity/src/lifecycle/validation.rs b/rust/personhog-identity/src/lifecycle/validation.rs
index e2453f513a69..3b2d86318fc3 100644
--- a/rust/personhog-identity/src/lifecycle/validation.rs
+++ b/rust/personhog-identity/src/lifecycle/validation.rs
@@ -4,6 +4,7 @@ use std::sync::LazyLock;
use tonic::Status;
use uuid::Uuid;
+use personhog_common::persons::COOKIELESS_SENTINEL_VALUE;
use personhog_proto::personhog::identity::v1::MergePersonsRequest;
use personhog_proto::personhog::lifecycle::v1::DeletePersonsRequest;
@@ -46,7 +47,6 @@ const BARE_CASE_INSENSITIVE_ILLEGAL_IDS: &[&str] = &[
"true",
"false",
];
-// '$posthog_cookieless' is the cookieless mode sentinel. Every cookieless visitor shares it.
const BARE_CASE_SENSITIVE_ILLEGAL_IDS: &[&str] = &[
"[object Object]",
"NaN",
@@ -55,7 +55,7 @@ const BARE_CASE_SENSITIVE_ILLEGAL_IDS: &[&str] = &[
"null",
"0",
"undefined",
- "$posthog_cookieless",
+ COOKIELESS_SENTINEL_VALUE,
];
fn with_quoted(ids: &[&str]) -> HashSet<String> {
diff --git a/rust/personhog-identity/tests/lifecycle_merge_tests.rs b/rust/personhog-identity/tests/lifecycle_merge_tests.rs
index fc0b89033fac..a8cf6af0e34b 100644
--- a/rust/personhog-identity/tests/lifecycle_merge_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_merge_tests.rs
@@ -17,7 +17,7 @@ use chrono::Utc;
use common::sim_leader::{LeaderCall, Rpc, SimLeader, FENCED_METADATA_KEY};
use common::TestContext;
use personhog_common::grpc::semantic_refusal;
-use personhog_common::persons::person_uuid;
+use personhog_common::persons::{person_uuid, COOKIELESS_SENTINEL_VALUE};
use serde_json::json;
use sqlx::postgres::PgPool;
use sqlx::Row;
@@ -110,6 +110,23 @@ impl MergeHarness {
.expect("insert distinct id");
}
+ async fn insert_hash_key_override(&self, person_id: i64, flag: &str, hash_key: &str) {
+ sqlx::query(&format!(
+ r#"
+ INSERT INTO {} (team_id, person_id, feature_flag_key, hash_key)
+ VALUES ($1, $2, $3, $4)
+ "#,
+ self.ctx.tables.ff_hash_key_override
+ ))
+ .bind(self.ctx.team_id as i32)
+ .bind(person_id)
+ .bind(flag)
+ .bind(hash_key)
+ .execute(&self.ctx.pool)
+ .await
+ .expect("insert hash key override");
+ }
+
async fn set_person(&self, person_id: i64, properties: &str, version: i64, identified: bool) {
sqlx::query(&format!(
r#"
@@ -396,21 +413,10 @@ async fn a_merge_folds_repoints_tombstones_and_records_the_outcome() {
.execute(&h.ctx.pool)
.await
.unwrap();
- for (person, hash) in [(target, "target-hash"), (source, "source-hash")] {
- sqlx::query(
- r#"
- INSERT INTO posthog_featureflaghashkeyoverride
- (feature_flag_key, hash_key, person_id, team_id)
- VALUES ('flag', $2, $1, $3)
- "#,
- )
- .bind(person)
- .bind(hash)
- .bind(h.ctx.team_id as i32)
- .execute(&h.ctx.pool)
- .await
- .unwrap();
- }
+ h.insert_hash_key_override(target, "flag", "target-hash")
+ .await;
+ h.insert_hash_key_override(source, "flag", "source-hash")
+ .await;
// The source was seen after the target: the fold must carry the max.
h.leader.set_last_seen(target, 1_000);
@@ -508,6 +514,68 @@ async fn a_merge_folds_repoints_tombstones_and_records_the_outcome() {
h.ctx.cleanup().await.expect("cleanup");
}
+#[tokio::test]
+async fn a_merge_keeps_a_real_hash_key_over_the_cookieless_sentinel() {
+ let h = MergeHarness::new().await;
+ let target = h
+ .ctx
+ .insert_person_with_distinct_id("sentinel-target")
+ .await;
+ let s1 = h.ctx.insert_person_with_distinct_id("sentinel-s1").await;
+ let s2 = h.ctx.insert_person_with_distinct_id("sentinel-s2").await;
+ for (person, flag, hash) in [
+ (target, "target-sentinel", COOKIELESS_SENTINEL_VALUE),
+ (s1, "target-sentinel", "s1-hash"),
+ (s1, "shared", COOKIELESS_SENTINEL_VALUE),
+ (s2, "shared", "s2-hash"),
+ (target, "both-real", COOKIELESS_SENTINEL_VALUE),
+ (s1, "both-real", "s1-both"),
+ (s2, "both-real", "s2-both"),
+ (s1, "source-sentinel", COOKIELESS_SENTINEL_VALUE),
+ ] {
+ h.insert_hash_key_override(person, flag, hash).await;
+ }
+
+ let outcome = h
+ .execute(
+ Uuid::now_v7(),
+ &merge_request("sentinel-target", &["sentinel-s1", "sentinel-s2"]),
+ )
+ .await
+ .expect("merge completes");
+ assert!(!outcome.aborted);
+
+ let overrides: Vec<(i64, String, String)> = sqlx::query_as(&format!(
+ r#"
+ SELECT person_id, feature_flag_key, hash_key FROM {}
+ WHERE team_id = $1
+ ORDER BY feature_flag_key
+ "#,
+ h.ctx.tables.ff_hash_key_override
+ ))
+ .bind(h.ctx.team_id as i32)
+ .fetch_all(&h.ctx.pool)
+ .await
+ .unwrap();
+ let flags: Vec<(i64, &str)> = overrides
+ .iter()
+ .map(|(person, flag, _)| (*person, flag.as_str()))
+ .collect();
+ assert_eq!(
+ flags,
+ [
+ (target, "both-real"),
+ (target, "shared"),
+ (target, "target-sentinel"),
+ ]
+ );
+ assert!(["s1-both", "s2-both"].contains(&overrides[0].2.as_str()));
+ assert_eq!(overrides[1].2, "s2-hash");
+ assert_eq!(overrides[2].2, "s1-hash");
+
+ h.ctx.cleanup().await.expect("cleanup");
+}
+
/// The state-machine walkthrough: one `step_once` per transition, with
/// the full invariant set asserted in every state — what is persisted,
/// which fences and marks are held, and what other actors (ordinary