: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
fix(hobby): finish wiring the feature-flags service (#114813)
Paul D'Ambradf9b6d3f99d8
diff --git a/bin/deploy-hobby b/bin/deploy-hobbyindex 7dab5ccd7d53..a5cf2184e1a6 100755--- a/bin/deploy-hobby+++ b/bin/deploy-hobby@@ -164,10 +164,13 @@ else# Django's SECRET_KEY (the compose file falls back to POSTHOG_SECRET when unset, for# installs whose .env predates this variable).BROWSERLESS_SECRET=$(openssl rand -hex 32)+ # Dedicated token for Django -> feature-flags calls, for the same reason.+ INTERNAL_REQUEST_TOKEN=$(openssl rand -hex 32)cat > .env <<EOFPOSTHOG_SECRET=$POSTHOG_SECRETENCRYPTION_SALT_KEYS=$ENCRYPTION_SALT_KEYSBROWSERLESS_SECRET=$BROWSERLESS_SECRET+INTERNAL_REQUEST_TOKEN=$INTERNAL_REQUEST_TOKENDOMAIN=$DOMAINTLS_BLOCK=$TLS_BLOCKREGISTRY_URL=$REGISTRY_URLdiff --git a/bin/hobby-ci-setup-user.py b/bin/hobby-ci-setup-user.pyindex 23d67f01d638..e6a81e98e3da 100644--- a/bin/hobby-ci-setup-user.py+++ b/bin/hobby-ci-setup-user.py@@ -38,6 +38,13 @@ PersonalAPIKey.objects.create(label="ci-smoke-test",secure_value=hash_key_value(raw_key),mask_value=mask_key_value(raw_key),- scopes=["query:read", "logs:read", "error_tracking:read", "session_recording:read", "tracing:read"],+ scopes=[+ "query:read",+ "logs:read",+ "error_tracking:read",+ "session_recording:read",+ "tracing:read",+ "feature_flag:write",+ ],)print(f"{team.api_token}|||{raw_key}") # noqa: T201diff --git a/bin/hobby-ci.py b/bin/hobby-ci.pyindex 8348b03b13ce..ee5fe5358544 100644--- a/bin/hobby-ci.py+++ b/bin/hobby-ci.py@@ -495,6 +495,11 @@ runcmd:if not output_line:return False, f"Could not parse API keys from output: {result['stdout'][:200]}"project_api_token, personal_api_key = output_line[-1].split("|||")+ headers = {"Authorization": f"Bearer {personal_api_key}"}++ flag_error = self._smoke_test_feature_flag(base_url, project_api_token, headers, timeout_seconds, poll_interval)+ if flag_error:+ return False, flag_errorcapture_id = str(uuid.uuid4())exception_value = f"hobby_ci_error_smoke_test_{time.time_ns()}"@@ -537,7 +542,6 @@ runcmd:)print(f"⏳ Polling for events (timeout {timeout_seconds}s)...", flush=True)- headers = {"Authorization": f"Bearer {personal_api_key}"}deadline = time.time() + timeout_secondsattempt = 0pending_event_names = {event["event"] for event in events}@@ -805,7 +809,7 @@ runcmd:print(f"✅ Trace found after {attempt} poll(s)", flush=True)return (True,- "Preflight healthy; events, log, exception issue, session recording, and trace ingested successfully",+ "Preflight healthy; feature flag evaluated; events, log, exception issue, session recording, and trace ingested successfully",)if query_resp.status_code != 200:print(f" Poll {attempt}: trace HTTP {query_resp.status_code}", flush=True)@@ -817,6 +821,69 @@ runcmd:return False, f"Trace did not appear within {timeout_seconds}s ({attempt} polls)"+ @staticmethod+ def _smoke_test_feature_flag(+ base_url: str, project_api_token: str, headers: dict[str, str], timeout_seconds: int, poll_interval: int+ ) -> str | None:+ flag_key = f"hobby-ci-smoke-test-{time.time_ns()}"+ distinct_id = f"hobby-ci-flags-{uuid.uuid4()}"++ print(f"🚩 Creating feature flag '{flag_key}'...", flush=True)+ try:+ create_resp = requests.post(+ f"{base_url}/api/projects/@current/feature_flags/", # nosemgrep: python.lang.security.audit.insecure-transport.requests.request-with-http.request-with-http+ json={"key": flag_key, "filters": {"groups": [{"properties": [], "rollout_percentage": 100}]}},+ headers=headers,+ timeout=30,+ )+ flag_id = create_resp.json()["id"] if create_resp.status_code == 201 else None+ except Exception as e:+ return f"Feature flag create request failed: {type(e).__name__}: {e}"+ if flag_id is None:+ return f"Feature flag create failed: HTTP {create_resp.status_code} - {create_resp.text[:200]}"++ print(f"⏳ Polling /flags for the new flag (timeout {timeout_seconds}s)...", flush=True)+ deadline = time.time() + timeout_seconds+ attempt = 0+ flag_enabled = False+ while time.time() < deadline:+ attempt += 1+ try:+ flags_resp = requests.post(+ f"{base_url}/flags/", # nosemgrep: python.lang.security.audit.insecure-transport.requests.request-with-http.request-with-http+ params={"v": 2},+ json={"token": project_api_token, "distinct_id": distinct_id},+ timeout=10,+ )+ if flags_resp.status_code == 200 and flags_resp.json().get("flags", {}).get(flag_key, {}).get(+ "enabled"+ ):+ print(f"✅ /flags returned the flag as enabled after {attempt} poll(s)", flush=True)+ flag_enabled = True+ break+ print(f" Poll {attempt}: /flags HTTP {flags_resp.status_code}, flag not enabled yet", flush=True)+ except Exception as e:+ print(f" Poll {attempt}: /flags returned {type(e).__name__}", flush=True)+ time.sleep(poll_interval)+ if not flag_enabled:+ return f"/flags did not return the flag as enabled within {timeout_seconds}s ({attempt} polls)"++ print("🚩 Running the flag's test evaluation...", flush=True)+ try:+ test_resp = requests.post(+ f"{base_url}/api/projects/@current/feature_flags/{flag_id}/test_evaluation/", # nosemgrep: python.lang.security.audit.insecure-transport.requests.request-with-http.request-with-http+ json={"distinct_id": distinct_id},+ headers=headers,+ timeout=30,+ )+ evaluated_true = test_resp.status_code == 200 and test_resp.json().get("result") is True+ except Exception as e:+ return f"Feature flag test evaluation request failed: {type(e).__name__}: {e}"+ if not evaluated_true:+ return f"Feature flag test evaluation failed: HTTP {test_resp.status_code} - {test_resp.text[:200]}"+ print("✅ Test evaluation returned true", flush=True)+ return None+@staticmethoddef find_existing_droplet_for_pr(token, pr_number):"""Find an existing droplet for a PR by tag"""diff --git a/bin/hobby-installer/core/env.go b/bin/hobby-installer/core/env.goindex a6f5cbc74e0a..9cb8bdbc144e 100644--- a/bin/hobby-installer/core/env.go+++ b/bin/hobby-installer/core/env.go@@ -9,8 +9,13 @@ import ("time")+// Service-to-service secrets that each get their own random value, so a leak from one+// container cannot yield POSTHOG_SECRET, which is Django's SECRET_KEY.+var dedicatedSecretKeys = []string{"INTERNAL_REQUEST_TOKEN", "BROWSERLESS_SECRET"}+type EnvConfig struct {PosthogSecret string+ DedicatedSecrets map[string]stringEncryptionSaltKeys stringDomain stringTLSBlock string@@ -26,6 +31,15 @@ func NewEnvConfig(domain, version string) (*EnvConfig, error) {return nil, fmt.Errorf("failed to generate secret: %w", err)}+ dedicatedSecrets := make(map[string]string, len(dedicatedSecretKeys))+ for _, key := range dedicatedSecretKeys {+ value, err := GenerateSecret()+ if err != nil {+ return nil, fmt.Errorf("failed to generate %s: %w", key, err)+ }+ dedicatedSecrets[key] = value+ }+encryptionKey, err := GenerateEncryptionKey()if err != nil {return nil, fmt.Errorf("failed to generate encryption key: %w", err)@@ -45,6 +59,7 @@ func NewEnvConfig(domain, version string) (*EnvConfig, error) {return &EnvConfig{PosthogSecret: secret,+ DedicatedSecrets: dedicatedSecrets,EncryptionSaltKeys: encryptionKey,Domain: domain,TLSBlock: tlsBlock,@@ -78,6 +93,9 @@ SESSION_RECORDING_V2_METADATA_SWITCHOVER=%sc.PosthogNodeTag,c.SessionRecordingDate,)+ for _, key := range dedicatedSecretKeys {+ content += fmt.Sprintf("%s=%s\n", key, c.DedicatedSecrets[key])+ }return os.WriteFile(".env", []byte(content), 0600)}@@ -97,6 +115,8 @@ func LoadExistingEnv() map[string]string {"OBJECT_STORAGE_MINIO_REMOVED",}+ keys = append(keys, dedicatedSecretKeys...)+for _, key := range keys {if val := ReadEnvValue(key); val != "" {values[key] = val@@ -140,6 +160,19 @@ func UpdateEnvForUpgrade(version string) error {}}+ for _, key := range dedicatedSecretKeys {+ if existing[key] != "" {+ continue+ }+ value, err := GenerateSecret()+ if err != nil {+ return err+ }+ if err := AppendToEnv(key, value); err != nil {+ return err+ }+ }+if existing["SESSION_RECORDING_V2_METADATA_SWITCHOVER"] == "" {if err := AppendToEnv("SESSION_RECORDING_V2_METADATA_SWITCHOVER", time.Now().Format(time.RFC3339)); err != nil {return errdiff --git a/bin/hobby-installer/core/env_test.go b/bin/hobby-installer/core/env_test.gonew file mode 100644index 000000000000..c98cfc4c5b83--- /dev/null+++ b/bin/hobby-installer/core/env_test.go@@ -0,0 +1,55 @@+package core++import (+ "os"+ "testing"+)++func TestDedicatedSecretsAreGeneratedAndKept(t *testing.T) {+ for _, key := range []string{"INTERNAL_REQUEST_TOKEN", "BROWSERLESS_SECRET"} {+ cases := []struct {+ name string+ existing string+ wantValue string+ }{+ {name: "fresh install generates it"},+ {name: "upgrade adds it when missing", existing: "POSTHOG_SECRET=s3cret\nDOMAIN=example.com\n"},+ {+ name: "upgrade keeps an existing value",+ existing: "POSTHOG_SECRET=s3cret\nDOMAIN=example.com\n" + key + "=keep-me\n",+ wantValue: "keep-me",+ },+ }++ for _, tc := range cases {+ t.Run(key+"/"+tc.name, func(t *testing.T) {+ t.Chdir(t.TempDir())++ if tc.existing == "" {+ config, err := NewEnvConfig("example.com", "latest")+ if err != nil {+ t.Fatal(err)+ }+ if err := config.WriteEnvFile(); err != nil {+ t.Fatal(err)+ }+ } else {+ if err := os.WriteFile(".env", []byte(tc.existing), 0600); err != nil {+ t.Fatal(err)+ }+ if err := UpdateEnvForUpgrade(""); err != nil {+ t.Fatal(err)+ }+ }++ value := ReadEnvValue(key)+ if tc.wantValue != "" && value != tc.wantValue {+ t.Fatalf("%s = %q, want %q", key, value, tc.wantValue)+ }+ if value == "" || value == ReadEnvValue("POSTHOG_SECRET") {+ t.Fatalf("%s = %q, want a value of its own", key, value)+ }+ })+ }+ }+}diff --git a/bin/upgrade-hobby b/bin/upgrade-hobbyindex e9de28006f71..c4fd0d68f577 100755--- a/bin/upgrade-hobby+++ b/bin/upgrade-hobby@@ -141,6 +141,16 @@ elsefifi+# Service-to-service secrets that each get their own random value, so a leak from one container+# cannot yield POSTHOG_SECRET (Django's SECRET_KEY). Installs from before a secret existed have+# none, so add it. Keep this list in step with dedicatedSecretKeys in bin/hobby-installer.+for key in INTERNAL_REQUEST_TOKEN BROWSERLESS_SECRET; do+ if ! grep -qE "^$key=.+" .env; then+ echo "$key=$(openssl rand -hex 32)" >> .env+ echo "Added missing $key to .env file"+ fi+done+# PostHog's AI features (the Max assistant, SQL/regex assist) run on your own LLM provider key.# If none is configured yet, offer to add one. Existing keys are never touched — we only append# when the key is absent, so this is safe to run on every upgrade.diff --git a/docker-compose.hobby.yml b/docker-compose.hobby.ymlindex d43b6c80514e..acefb0c1aeed 100644--- a/docker-compose.hobby.yml+++ b/docker-compose.hobby.yml@@ -14,6 +14,15 @@ x-logging: &default-loggingmax-size: '50m'max-file: '3'+# HyperCache's S3 tier for the Rust readers. With no endpoint the AWS SDK dials real S3 on+# every Redis miss and waits out its retries (~4s) before falling back to Postgres.+# Services using this also wait for objectstorage to be healthy: it registers these+# credentials after start and rejects them until then.+x-hypercache-s3: &hypercache-s3+ OBJECT_STORAGE_ENDPOINT: http://objectstorage:19000+ AWS_ACCESS_KEY_ID: 'object_storage_root_user'+ AWS_SECRET_ACCESS_KEY: 'object_storage_root_password'+services:db:extends:@@ -113,6 +122,9 @@ services:# Point Django at the Rust feature-flags container; the setting# otherwise defaults to localhost:3001.FEATURE_FLAGS_SERVICE_URL: 'http://feature-flags:3001'+ # Must match INTERNAL_REQUEST_TOKEN on the feature-flags service; flag test+ # evaluation otherwise fails with "Internal request token not configured".+ INTERNAL_REQUEST_TOKEN: ${INTERNAL_REQUEST_TOKEN:-}# The logs product uses a dedicated ClickHouse cluster config (separate# from CLICKHOUSE_HOST) whose host defaults to localhost and whose SECURE# defaults to true outside DEBUG. Point it at the stack's ClickHouse over@@ -178,6 +190,9 @@ services:# Point Django at the Rust feature-flags container; the setting# otherwise defaults to localhost:3001.FEATURE_FLAGS_SERVICE_URL: 'http://feature-flags:3001'+ # Must match INTERNAL_REQUEST_TOKEN on the feature-flags service; flag test+ # evaluation otherwise fails with "Internal request token not configured".+ INTERNAL_REQUEST_TOKEN: ${INTERNAL_REQUEST_TOKEN:-}# The logs product uses a dedicated ClickHouse cluster config (separate# from CLICKHOUSE_HOST) whose host defaults to localhost and whose SECURE# defaults to true outside DEBUG. Point it at the stack's ClickHouse over@@ -514,6 +529,9 @@ services:# Point Django at the Rust feature-flags container; the setting# otherwise defaults to localhost:3001.FEATURE_FLAGS_SERVICE_URL: 'http://feature-flags:3001'+ # Must match INTERNAL_REQUEST_TOKEN on the feature-flags service; flag test+ # evaluation otherwise fails with "Internal request token not configured".+ INTERNAL_REQUEST_TOKEN: ${INTERNAL_REQUEST_TOKEN:-}# The logs product uses a dedicated ClickHouse cluster config (separate# from CLICKHOUSE_HOST) whose host defaults to localhost and whose SECURE# defaults to true outside DEBUG. Point it at the stack's ClickHouse over@@ -632,9 +650,20 @@ services:file: docker-compose.base.ymlservice: feature-flagslogging: *default-logging+ environment:+ <<: *hypercache-s3+ # Shared secret for authenticated Django → flags calls (flag test evaluation);+ # must match INTERNAL_REQUEST_TOKEN on web and worker. The installers generate it.+ # Never fall back to POSTHOG_SECRET: this container faces the internet, and that+ # value is Django's SECRET_KEY.+ INTERNAL_REQUEST_TOKEN: ${INTERNAL_REQUEST_TOKEN:-}depends_on:- - db- - redis7+ db:+ condition: service_started+ redis7:+ condition: service_started+ objectstorage:+ condition: service_healthyhypercache-server:build:@@ -643,8 +672,12 @@ services:file: docker-compose.base.ymlservice: hypercache-serverlogging: *default-logging+ environment: *hypercache-s3depends_on:- - redis7+ redis7:+ condition: service_started+ objectstorage:+ condition: service_healthykafka-init:image: docker.io/redpandadata/redpanda:v25.1.9