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.

feat(support): improve visibility during long batch script runs (#93211)

Xanderd04f7a6303b6
diff --git a/products/support/scripts/AGENTS.md b/products/support/scripts/AGENTS.md
index 26f23ca86e74..2db6e9770395 100644
--- a/products/support/scripts/AGENTS.md
+++ b/products/support/scripts/AGENTS.md
@@ -15,13 +15,13 @@ Don't re-export through `lib/__init__.py` - a `from .` re-export there trips the
```python
from lib.errors import PostHogScriptError # the one error type; raise for any expected, operator-facing failure
-from lib.console import confirm, format_status_counts, log, printable
-from lib.posthog_api import request_with_retries, resolve_host, setup_session_auth
+from lib.console import close_log_file, confirm, format_status_counts, log, printable, resolve_output_base, set_log_file
+from lib.posthog_api import build_session, request_with_retries, resolve_host
```
- `lib.errors` - `PostHogScriptError`.
-- `lib.console` - `log` (stderr output), `printable` (escape untrusted text), `confirm` (typed-keyword prompt, EOF-safe), `format_status_counts` (status histogram).
-- `lib.posthog_api` - `resolve_host`, `request_with_retries` (every HTTP call), `setup_session_auth` (browser-session/impersonation auth), plus `MAX_RETRIES`.
+- `lib.console` - `log` (stderr output), `printable` (escape untrusted text), `confirm` (typed-keyword prompt, EOF-safe), `format_status_counts` (status histogram), `resolve_output_base` (numbers `--output` around an existing findings/log pair instead of overwriting it), `set_log_file`/`close_log_file` (stream every `log()` line to a file too, in addition to stderr - see Output below).
+- `lib.posthog_api` - `resolve_host`, `request_with_retries` (every HTTP call), `build_session` (auth per the standard `--personal-api-key`/`--session-id` flags), `setup_session_auth` (the browser-session half of `build_session`, for a script that needs bespoke auth flow), `log_session_expiry` (logs the impersonated session's remaining idle-timeout time; no-op for personal-API-key auth), plus `MAX_RETRIES`.
Never re-implement retries, host resolution, auth, output, or the error type inside a script.
If a second script needs a new shared helper, add it to `lib/` (`errors` / `console` / `posthog_api`) instead of copying it.
@@ -32,9 +32,6 @@ Route every request through `request_with_retries(session, method, url, ...)`.
It already retries 429 (with defensive Retry-After parsing) and 5xx with backoff.
Do not call `session.request` or `requests.get` directly.
-Build one `requests.Session`.
-For a personal API key set `session.headers["Authorization"] = f"Bearer {key}"`; for a browser session call `setup_session_auth(session, host, session_id)`.
-
Paginate defensively: honor the `next` URL for list APIs, and use keyset pagination (not `OFFSET`) for query-API scans, the way `find_affected_persons_hogql` does.
## Auth
@@ -44,14 +41,18 @@ Support both credentials, like the reference scripts:
- `--personal-api-key` / `POSTHOG_PERSONAL_API_KEY` (sent as a Bearer token).
- `--session-id` / `POSTHOG_SESSION_ID`, the browser `sessionid` cookie, for impersonated staff sessions.
-`setup_session_auth` handles the CSRF token, the HTTPS-only host-scoped cookie, and the mandatory acting-user confirmation.
-Just call it; don't set the cookie yourself.
+Build the session with `build_session(args)` - it branches on `args.personal_api_key` vs. `args.session_id` and, for the browser-session path, calls `setup_session_auth` (CSRF token, HTTPS-only host-scoped cookie, mandatory acting-user confirmation).
+Just call it; don't set the cookie or the `Authorization` header yourself.
## Output
All human output goes to **stderr** via `log()`, so **stdout** stays clean for `--output` JSON or piped data.
Do not use `print` (ruff `T2` flags it).
+`--output NAME` (a base name, no extension) writes two files: `NAME-findings.json` (the scan report, written once discovery finishes) and `NAME-log.txt` (every `log()` line, streamed as it happens via `set_log_file`/`close_log_file`).
+Resolve `args.output` through `resolve_output_base(args.output)` first, at the very top of `main()` - if either file already exists (a previous run at the same name), it numbers up (`NAME-2`, `NAME-3`, ...) instead of overwriting them, and reassigns `args.output` so every downstream use picks up the resolved name automatically.
+Call `set_log_file(f"{args.output}-log.txt")` right after that (using the resolved name) and `close_log_file()` in a `finally` around the call into `run()`, so a crash or Ctrl-C mid-run still leaves a complete transcript up to that point - never buffer log lines in memory to write out at the end.
+
Wrap any value that originated from ingested data (property names, `distinct_id`s, an API error body) in `printable()` before logging it.
Those strings can carry terminal escape sequences that would otherwise spoof or wipe the operator's terminal.
@@ -68,10 +69,10 @@ Anything that writes or deletes follows this order:
1. Scan and dedupe the affected set.
2. Log a total, a per-target breakdown, and a sample (first ~10).
-3. Offer `--output <file>` to dump the full affected set as JSON.
+3. Offer `--output <name>` to dump the full affected set as JSON to `<name>-findings.json` (see Output above).
4. `--dry-run` returns here, changing nothing.
5. Otherwise confirm with `confirm(prompt, "<verb>", eof_message=...)` (a typed keyword such as `scrub` / `prune`), skippable with `--yes`.
-6. When there is no bulk endpoint, mutate one item per request and report outcomes with `format_status_counts`: count only 2xx as success, surface a 403 hint (read-only credential or field-level access control), and cap the printed failure list.
+6. When there is no bulk endpoint, mutate one item per request and report outcomes: count only 2xx as success, log a `FAILED: ...` line with the HTTP status/message immediately for every failure (don't wait until the run finishes), and log a running `format_status_counts` histogram every batch. Surface a 403 hint (read-only credential or field-level access control) and a final failure total at the end - don't re-print the individual failures there, they already scrolled by live.
Call out anything eventually-consistent (e.g. ingestion lag) in the module docstring so the operator isn't surprised when a value lingers after the run.
@@ -79,6 +80,24 @@ Call out anything eventually-consistent (e.g. ingestion lag) in the module docst
- Module docstring first: what the script does, how it discovers targets, how it mutates them, any consistency caveats, and a usage block with the env vars and a `--dry-run` example.
- `parse_args() -> argparse.Namespace`, then `main() -> int` returning an exit code.
+- If the script offers a `--output` findings report (the scrub/prune shape), keep `main()` thin and put the actual work in `run(args: argparse.Namespace) -> int`, so `main()` only wires up the log file around it:
+
+ ```python
+ def main() -> int:
+ args = parse_args()
+ if args.output:
+ args.output = resolve_output_base(args.output)
+ set_log_file(f"{args.output}-log.txt")
+ try:
+ return run(args)
+ finally:
+ close_log_file()
+
+
+ def run(args: argparse.Namespace) -> int:
+ ...
+ ```
+
- Standard bottom guard:
```python
diff --git a/products/support/scripts/lib/console.py b/products/support/scripts/lib/console.py
index 461c12b3c5b1..cb4303f2c0bc 100644
--- a/products/support/scripts/lib/console.py
+++ b/products/support/scripts/lib/console.py
@@ -1,14 +1,58 @@
"""Terminal output and confirmation helpers shared by the support CLI scripts."""
+import os
import sys
from collections import Counter
+from typing import Optional, TextIO
from .errors import PostHogScriptError
+_log_file: Optional[TextIO] = None
+
+
+def resolve_output_base(base: str) -> str:
+ """Return `base`, or `base-2`/`base-3`/... if its findings/log files already exist.
+
+ Keeps a --output run from clobbering a previous one's report or transcript. Both files
+ always share the same resolved base, so e.g. `NAME-2-findings.json` pairs with
+ `NAME-2-log.txt`.
+ """
+ candidate = base
+ suffix = 1
+ while os.path.exists(f"{candidate}-findings.json") or os.path.exists(f"{candidate}-log.txt"):
+ suffix += 1
+ candidate = f"{base}-{suffix}"
+ if candidate != base:
+ log(f" {base}-findings.json / {base}-log.txt already exist - using {candidate} instead")
+ return candidate
+
+
+def set_log_file(path: str) -> None:
+ """Stream every subsequent log() call to `path` too, starting fresh.
+
+ Opens `path` once, in write mode, so every log() line lands in it as it happens, in the
+ same order the operator sees on stderr - a crash or Ctrl-C mid-run still leaves a
+ complete transcript up to that point, rather than losing output that was only ever held
+ in memory.
+ """
+ global _log_file
+ _log_file = open(path, "w")
+
+
+def close_log_file() -> None:
+ """Flush and close the file opened by set_log_file(), if any. Safe to call unconditionally."""
+ global _log_file
+ if _log_file is not None:
+ _log_file.close()
+ _log_file = None
+
def log(message: str) -> None:
"""Write a progress/report line to stderr, keeping stdout free for piped data."""
print(message, file=sys.stderr) # noqa: T201 - stderr logging is this CLI's output channel
+ if _log_file is not None:
+ _log_file.write(message + "\n")
+ _log_file.flush()
def printable(value: str) -> str:
diff --git a/products/support/scripts/lib/posthog_api.py b/products/support/scripts/lib/posthog_api.py
index 39f587dc48ca..e7dc019db6a3 100644
--- a/products/support/scripts/lib/posthog_api.py
+++ b/products/support/scripts/lib/posthog_api.py
@@ -4,15 +4,20 @@ A tiny PostHog REST client: region/host resolution, a request wrapper that retri
limits and 5xx, and session-cookie authentication for impersonated staff sessions. Both
scripts hit the same API surface, so keeping retry/backoff, defensive Retry-After parsing,
cookie scoping, and the acting-user safety check here means every script gets them.
+`log_session_expiry` also lets a long batch run confirm the impersonated session's idle
+timer is resetting as expected.
"""
import time
-from typing import Any
+import argparse
+import itertools
+from datetime import UTC, datetime
+from typing import Any, Optional
from urllib.parse import urlparse
import requests
-from .console import confirm, log
+from .console import confirm, log, printable
from .errors import PostHogScriptError
MAX_RETRIES = 5
@@ -20,6 +25,11 @@ BACKOFF_BASE_SECONDS = 2.0
RETRY_AFTER_MAX_SECONDS = 60.0
REGION_HOSTS = {"us": "https://us.posthog.com", "eu": "https://eu.posthog.com"}
+# Sequential id per request_with_retries() call, so "rate limited" log lines can be told
+# apart: a repeated id means the same request is still retrying, a new id means a different
+# request just got rate-limited for the first time - not that the run is stuck.
+_request_counter = itertools.count(1)
+
def resolve_host(value: str) -> str:
"""Map a region shorthand ('us'/'eu', any case) to its Cloud host; pass explicit hosts through."""
@@ -30,7 +40,9 @@ def request_with_retries(
session: requests.Session, method: str, url: str, max_retries: int = MAX_RETRIES, **kwargs: Any
) -> requests.Response:
"""Issue a request, retrying on 429 (honoring Retry-After) and 5xx with backoff."""
+ request_id = next(_request_counter)
last_error = ""
+ was_rate_limited = False
for attempt in range(max_retries):
try:
response = session.request(method, url, timeout=60, **kwargs)
@@ -39,6 +51,7 @@ def request_with_retries(
time.sleep(BACKOFF_BASE_SECONDS * 2**attempt)
continue
if response.status_code == 429:
+ was_rate_limited = True
last_error = f"HTTP {response.status_code}: {response.text[:200]}"
default_wait = BACKOFF_BASE_SECONDS * 2**attempt
raw_retry_after = response.headers.get("Retry-After")
@@ -48,15 +61,38 @@ def request_with_retries(
except ValueError:
retry_after = default_wait
retry_after = min(max(retry_after, 0.0), RETRY_AFTER_MAX_SECONDS)
- log(f" rate limited, retrying in {retry_after:.0f}s...")
+ log(f" [req {request_id}] rate limited, retrying in {retry_after:.0f}s...")
time.sleep(retry_after)
continue
if response.status_code >= 500:
last_error = f"HTTP {response.status_code}: {response.text[:200]}"
time.sleep(BACKOFF_BASE_SECONDS * 2**attempt)
continue
+ if was_rate_limited:
+ log(f" [req {request_id}] succeeded after being rate limited")
return response
- raise PostHogScriptError(f"{method} {url} failed after {max_retries} attempts: {last_error}")
+ raise PostHogScriptError(f"[req {request_id}] {method} {url} failed after {max_retries} attempts: {last_error}")
+
+
+def run_hogql_query(
+ session: requests.Session, host: str, project_id: str, query: str, max_retries: int = MAX_RETRIES
+) -> list[list[Any]]:
+ """Run a HogQL query through the query API and return its result rows."""
+ response = request_with_retries(
+ session,
+ "POST",
+ f"{host}/api/projects/{project_id}/query/",
+ max_retries=max_retries,
+ json={"query": {"kind": "HogQLQuery", "query": query}},
+ )
+ if response.status_code != 200:
+ raise PostHogScriptError(f"HogQL query failed (HTTP {response.status_code}): {response.text[:500]}")
+ return response.json()["results"]
+
+
+def hogql_string_literal(value: str) -> str:
+ escaped = value.replace("\\", "\\\\").replace("'", "\\'")
+ return f"'{escaped}'"
def confirm_acting_user(email: str) -> None:
@@ -110,3 +146,44 @@ def setup_session_auth(session: requests.Session, host: str, session_id: str) ->
raise PostHogScriptError("Could not determine the session's authenticated user")
confirm_acting_user(email)
log(f"Authenticated via session as {email}")
+
+
+def build_session(args: argparse.Namespace) -> requests.Session:
+ """Build a Session authenticated per the standard --personal-api-key/--session-id flags."""
+ session = requests.Session()
+ if args.personal_api_key:
+ session.headers["Authorization"] = f"Bearer {args.personal_api_key}"
+ else:
+ setup_session_auth(session, args.host, args.session_id)
+ return session
+
+
+def get_session_expiry(session: requests.Session, host: str) -> Optional[datetime]:
+ """Return when the current impersonated session expires, or None if it isn't impersonated.
+
+ Reads `is_impersonated_until` from /api/users/@me/ - the same value
+ AutoLogoutImpersonateMiddleware enforces server-side. Always None for personal-API-key
+ auth, which isn't impersonation.
+ """
+ response = request_with_retries(session, "GET", f"{host}/api/users/@me/", max_retries=1)
+ if response.status_code != 200:
+ return None
+ expires_at = response.json().get("is_impersonated_until")
+ return datetime.fromisoformat(expires_at) if expires_at else None
+
+
+def log_session_expiry(session: requests.Session, host: str) -> None:
+ """Log how much time an impersonated session has left; no-op for personal-API-key auth.
+
+ Meant to be called from a batch-report checkpoint so a long run can confirm the idle
+ timer is resetting as expected instead of silently counting down.
+ """
+ try:
+ expires_at = get_session_expiry(session, host)
+ except PostHogScriptError as err:
+ log(f" could not check session expiry: {printable(str(err))}")
+ return
+ if expires_at is None:
+ return
+ minutes_left = max(int((expires_at - datetime.now(UTC)).total_seconds() // 60), 0)
+ log(f" session active for {minutes_left}m more (expires {expires_at.isoformat()})")
diff --git a/products/support/scripts/prune_property_definitions.py b/products/support/scripts/prune_property_definitions.py
index 2d3a079c55e4..a4a53b4c5ee7 100644
--- a/products/support/scripts/prune_property_definitions.py
+++ b/products/support/scripts/prune_property_definitions.py
@@ -19,6 +19,11 @@ incoming events, so fix the source instrumentation first. For a full server-side
cleanup (Postgres + event properties + ClickHouse), use the `cleanup-property-definitions`
Temporal workflow instead.
+--output NAME writes two files: NAME-findings.json (the matched-definitions report, written
+once discovery finishes) and NAME-log.txt (every line the operator sees on stderr, written as
+it happens - a dry run, an aborted confirm, a completed prune, or a crash mid-run all leave a
+complete transcript up to that point).
+
Usage:
export POSTHOG_PERSONAL_API_KEY=phx_... # needs property_definition:read and :write
python products/support/scripts/prune_property_definitions.py temp_prop other_prop \\
@@ -46,9 +51,9 @@ from typing import Any, Optional
from urllib.parse import urlencode
import requests
-from lib.console import confirm, format_status_counts, log, printable
+from lib.console import close_log_file, confirm, format_status_counts, log, printable, resolve_output_base, set_log_file
from lib.errors import PostHogScriptError
-from lib.posthog_api import request_with_retries, resolve_host, setup_session_auth
+from lib.posthog_api import build_session, log_session_expiry, request_with_retries, resolve_host
def iter_property_definitions(
@@ -133,15 +138,20 @@ def prune_definitions(
except PostHogScriptError as err:
status_counts["error"] += 1
batch_counts["error"] += 1
- failures.append(f"{definition['name']} ({definition['id']}): {err}")
+ message = f"{definition['name']} ({definition['id']}): {err}"
+ failures.append(message)
+ log(f" FAILED: {printable(message)}")
else:
code = response.status_code
status_counts[str(code)] += 1
batch_counts[str(code)] += 1
if not 200 <= code < 300:
- failures.append(f"{definition['name']} ({definition['id']}): HTTP {code} {response.text[:200]}")
+ message = f"{definition['name']} ({definition['id']}): HTTP {code} {response.text[:200]}"
+ failures.append(message)
+ log(f" FAILED: {printable(message)}")
if index % batch_size == 0 or index == total:
log(f" deletes {batch_start}-{index} of {total}: {format_status_counts(batch_counts)}")
+ log_session_expiry(session, host)
batch_counts = Counter()
batch_start = index + 1
return status_counts, failures
@@ -193,7 +203,12 @@ def parse_args() -> argparse.Namespace:
parser.add_argument(
"--batch-size", type=int, default=50, help="How many deletes to group per reported status-code batch"
)
- parser.add_argument("--output", help="Write the matched definitions report to this JSON file")
+ parser.add_argument(
+ "--output",
+ metavar="NAME",
+ help="Base name for output files (no extension): writes <NAME>-findings.json (the matched "
+ "definitions report) and <NAME>-log.txt (the full run log, written as it happens)",
+ )
parser.add_argument("--yes", "-y", action="store_true", help="Skip the confirmation prompt")
args = parser.parse_args()
@@ -226,14 +241,19 @@ def parse_args() -> argparse.Namespace:
def main() -> int:
args = parse_args()
- names = sorted(set(args.names))
+ if args.output:
+ args.output = resolve_output_base(args.output)
+ set_log_file(f"{args.output}-log.txt")
+ try:
+ return run(args)
+ finally:
+ close_log_file()
- session = requests.Session()
- if args.personal_api_key:
- session.headers["Authorization"] = f"Bearer {args.personal_api_key}"
- else:
- setup_session_auth(session, args.host, args.session_id)
+def discover_matches(
+ session: requests.Session, args: argparse.Namespace, names: list[str]
+) -> tuple[list[dict[str, Any]], list[str]]:
+ """Scan for matching definitions, log a summary, and write the --output findings report."""
match_desc = f"regex /{args.regex}/" if args.regex else f"{len(names)} name(s)"
log(f"Scanning {args.prop_type} property definitions in project {args.project_id} matching {match_desc}")
definitions = list(
@@ -260,7 +280,8 @@ def main() -> int:
log(f" {printable(name)}")
if args.output:
- with open(args.output, "w") as f:
+ findings_path = f"{args.output}-findings.json"
+ with open(findings_path, "w") as f:
json.dump(
{
"type": args.prop_type,
@@ -272,12 +293,12 @@ def main() -> int:
f,
indent=2,
)
- log(f"Wrote report to {args.output}")
+ log(f"Wrote report to {findings_path}")
+
+ return matched, not_found
- if not matched:
- log("Nothing to prune.")
- return 0
+def log_preview(matched: list[dict[str, Any]]) -> None:
preview = matched[:10]
log("")
log("Sample of definitions that would be pruned:")
@@ -295,22 +316,24 @@ def main() -> int:
"Data Management > Properties, not event-property mappings or the ClickHouse mirror."
)
- if args.dry_run:
- log("")
- log("DRY RUN: no changes made.")
- return 0
- if not args.yes:
- prompt = (
- f"\nAbout to permanently delete {len(matched)} {args.prop_type} property definitions "
- f"from project {args.project_id}. Type 'prune' to continue: "
- )
- if not confirm(
- prompt, "prune", eof_message="Confirmation requires interactive input; pass --yes for non-interactive runs."
- ):
- log("Aborted.")
- return 1
+def confirm_prune(args: argparse.Namespace, matched: list[dict[str, Any]]) -> bool:
+ """Prompt to confirm the prune (unless --yes); return whether to proceed."""
+ if args.yes:
+ return True
+ prompt = (
+ f"\nAbout to permanently delete {len(matched)} {args.prop_type} property definitions "
+ f"from project {args.project_id}. Type 'prune' to continue: "
+ )
+ if confirm(
+ prompt, "prune", eof_message="Confirmation requires interactive input; pass --yes for non-interactive runs."
+ ):
+ return True
+ log("Aborted.")
+ return False
+
+def execute_prune(session: requests.Session, args: argparse.Namespace, matched: list[dict[str, Any]]) -> int:
status_counts, failures = prune_definitions(session, args.host, args.project_id, matched, args.batch_size)
deleted = sum(n for code, n in status_counts.items() if code.isdigit() and 200 <= int(code) < 300)
log("")
@@ -321,15 +344,34 @@ def main() -> int:
f" {forbidden} forbidden (HTTP 403): the credential can't delete these - a read-only "
"session/key, or field-level access control on restricted properties."
)
- for failure in failures[:20]:
- log(f" FAILED: {printable(failure)}")
- if len(failures) > 20:
- log(f" ... and {len(failures) - 20} more failures")
if failures:
+ log(f" {len(failures)} failure(s) - see the FAILED lines above for details")
return 1
return 0
+def run(args: argparse.Namespace) -> int:
+ names = sorted(set(args.names))
+ session = build_session(args)
+ matched, _not_found = discover_matches(session, args, names)
+
+ if not matched:
+ log("Nothing to prune.")
+ return 0
+
+ log_preview(matched)
+
+ if args.dry_run:
+ log("")
+ log("DRY RUN: no changes made.")
+ return 0
+
+ if not confirm_prune(args, matched):
+ return 1
+
+ return execute_prune(session, args, matched)
+
+
if __name__ == "__main__":
try:
sys.exit(main())
diff --git a/products/support/scripts/scrub_person_properties.py b/products/support/scripts/scrub_person_properties.py
index 2365ba92237d..6e2cf3eb63ac 100644
--- a/products/support/scripts/scrub_person_properties.py
+++ b/products/support/scripts/scrub_person_properties.py
@@ -22,6 +22,11 @@ Scrubbing happens either by:
Scrubbing is processed by the ingestion pipeline, so it is eventually consistent: persons
can keep showing the property for a short while after the script finishes.
+--output NAME writes two files: NAME-findings.json (the affected-persons report, written once
+discovery finishes) and NAME-log.txt (every line the operator sees on stderr, written as it
+happens - a dry run, an aborted confirm, a completed scrub, or a crash mid-run all leave a
+complete transcript up to that point).
+
Usage:
export POSTHOG_PERSONAL_API_KEY=phx_... # needs query:read and person:read (+ person:write for api mode)
export POSTHOG_PROJECT_API_KEY=phc_... # only needed for events mode
@@ -47,36 +52,22 @@ from typing import Any, Optional
from urllib.parse import urlencode
import requests
-from lib.console import confirm, format_status_counts, log, printable
+from lib.console import close_log_file, confirm, format_status_counts, log, printable, resolve_output_base, set_log_file
from lib.errors import PostHogScriptError
-from lib.posthog_api import MAX_RETRIES, request_with_retries, resolve_host, setup_session_auth
+from lib.posthog_api import (
+ build_session,
+ hogql_string_literal,
+ log_session_expiry,
+ request_with_retries,
+ resolve_host,
+ run_hogql_query,
+)
# api mode deletes the properties for one person per request (all matched properties in one $unset list);
# report a status-code histogram every this many so a long run shows steady progress.
API_REPORT_EVERY = 50
-def run_hogql_query(
- session: requests.Session, host: str, project_id: str, query: str, max_retries: int = MAX_RETRIES
-) -> list[list[Any]]:
- """Run a HogQL query through the query API and return its result rows."""
- response = request_with_retries(
- session,
- "POST",
- f"{host}/api/projects/{project_id}/query/",
- max_retries=max_retries,
- json={"query": {"kind": "HogQLQuery", "query": query}},
- )
- if response.status_code != 200:
- raise PostHogScriptError(f"HogQL query failed (HTTP {response.status_code}): {response.text[:500]}")
- return response.json()["results"]
-
-
-def hogql_string_literal(value: str) -> str:
- escaped = value.replace("\\", "\\\\").replace("'", "\\'")
- return f"'{escaped}'"
-
-
def iter_persons(
session: requests.Session, host: str, project_id: str, property_filters: list[dict[str, Any]], page_size: int
) -> Iterator[dict[str, Any]]:
@@ -253,7 +244,9 @@ def scrub_via_api(
except PostHogScriptError as err:
status_counts["error"] += 1
batch_counts["error"] += 1
- failures.append(f"{person['uuid']} / {', '.join(props)}: {err}")
+ message = f"{person['uuid']} / {', '.join(props)}: {err}"
+ failures.append(message)
+ log(f" FAILED: {printable(message)}")
else:
code = response.status_code
status_counts[str(code)] += 1
@@ -261,9 +254,12 @@ def scrub_via_api(
if 200 <= code < 300:
values_deleted += len(props)
else:
- failures.append(f"{person['uuid']} / {', '.join(props)}: HTTP {code} {response.text[:200]}")
+ message = f"{person['uuid']} / {', '.join(props)}: HTTP {code} {response.text[:200]}"
+ failures.append(message)
+ log(f" FAILED: {printable(message)}")
if index % API_REPORT_EVERY == 0 or index == total:
log(f" persons {batch_start}-{index} of {total}: {format_status_counts(batch_counts)}")
+ log_session_expiry(session, host)
batch_counts = Counter()
batch_start = index + 1
return status_counts, failures, values_deleted
@@ -310,7 +306,12 @@ def parse_args() -> argparse.Namespace:
parser.add_argument("--dry-run", action="store_true", help="Only report who would be affected; change nothing")
parser.add_argument("--batch-size", type=int, default=500, help="Events per batch capture request (events mode)")
parser.add_argument("--page-size", type=int, default=500, help="Persons fetched per page when scanning")
- parser.add_argument("--output", help="Write the affected persons report to this JSON file")
+ parser.add_argument(
+ "--output",
+ metavar="NAME",
+ help="Base name for output files (no extension): writes <NAME>-findings.json (the affected "
+ "persons report) and <NAME>-log.txt (the full run log, written as it happens)",
+ )
parser.add_argument("--yes", "-y", action="store_true", help="Skip the confirmation prompt")
args = parser.parse_args()
@@ -336,14 +337,19 @@ def parse_args() -> argparse.Namespace:
def main() -> int:
args = parse_args()
- properties = sorted(set(args.properties))
+ if args.output:
+ args.output = resolve_output_base(args.output)
+ set_log_file(f"{args.output}-log.txt")
+ try:
+ return run(args)
+ finally:
+ close_log_file()
- session = requests.Session()
- if args.personal_api_key:
- session.headers["Authorization"] = f"Bearer {args.personal_api_key}"
- else:
- setup_session_auth(session, args.host, args.session_id)
+def discover_affected(
+ session: requests.Session, args: argparse.Namespace, properties: list[str]
+) -> list[dict[str, Any]]:
+ """Scan for affected persons, log a summary, and write the --output findings report."""
log(f"Finding persons in project {args.project_id} with any of: {', '.join(properties)}")
affected_by_uuid = find_affected_persons(session, args.host, args.project_id, properties, args.page_size)
affected = sorted(affected_by_uuid.values(), key=lambda p: p["uuid"])
@@ -355,16 +361,15 @@ def main() -> int:
log(f" {prop}: {count} persons")
if args.output:
- with open(args.output, "w") as f:
+ findings_path = f"{args.output}-findings.json"
+ with open(findings_path, "w") as f:
json.dump({"properties": properties, "affected_persons": affected}, f, indent=2)
- log(f"Wrote report to {args.output}")
+ log(f"Wrote report to {findings_path}")
- if not affected:
- log("Nothing to scrub.")
- return 0
+ return affected
- pair_count = sum(len(p["matched_properties"]) for p in affected)
+def log_preview(affected: list[dict[str, Any]]) -> None:
preview = affected[:10]
log("")
log("Sample of affected persons:")
@@ -374,52 +379,77 @@ def main() -> int:
if len(affected) > len(preview):
log(f" ... and {len(affected) - len(preview)} more (use --output to save the full list)")
- if args.dry_run:
- log("")
- log("DRY RUN: no changes made.")
- return 0
- if not args.yes:
- prompt = (
- f"\nAbout to permanently scrub {pair_count} property values "
- f"from {len(affected)} persons via {args.mode} mode. Type 'scrub' to continue: "
- )
- if not confirm(
- prompt, "scrub", eof_message="Confirmation requires interactive input; pass --yes for non-interactive runs."
- ):
- log("Aborted.")
- return 1
+def confirm_scrub(args: argparse.Namespace, affected: list[dict[str, Any]], pair_count: int) -> bool:
+ """Prompt to confirm the scrub (unless --yes); return whether to proceed."""
+ if args.yes:
+ return True
+ prompt = (
+ f"\nAbout to permanently scrub {pair_count} property values "
+ f"from {len(affected)} persons via {args.mode} mode. Type 'scrub' to continue: "
+ )
+ if confirm(
+ prompt, "scrub", eof_message="Confirmation requires interactive input; pass --yes for non-interactive runs."
+ ):
+ return True
+ log("Aborted.")
+ return False
+
+def execute_scrub(
+ session: requests.Session, args: argparse.Namespace, affected: list[dict[str, Any]], pair_count: int
+) -> int:
if args.mode == "events":
sent, request_count = scrub_via_events(args.host, args.project_api_key, affected, args.batch_size)
log("")
log(f"Done: sent {sent} scrub events in {request_count} batch requests.")
log("Ingestion is asynchronous - properties disappear once the events are processed.")
- else:
- status_counts, failures, values_deleted = scrub_via_api(session, args.host, args.project_id, affected)
- log("")
+ return 0
+
+ status_counts, failures, values_deleted = scrub_via_api(session, args.host, args.project_id, affected)
+ log("")
+ log(
+ f"Done: {values_deleted}/{pair_count} property values deleted "
+ f"({len(affected)} requests). Status breakdown: {format_status_counts(status_counts)}"
+ )
+ forbidden = status_counts.get("403", 0)
+ if forbidden:
+ log(f" {forbidden} forbidden (HTTP 403): the credential can't delete these - likely a read-only key.")
+ bad_request = status_counts.get("400", 0)
+ if bad_request:
log(
- f"Done: {values_deleted}/{pair_count} property values deleted "
- f"({len(affected)} requests). Status breakdown: {format_status_counts(status_counts)}"
+ f" {bad_request} rejected (HTTP 400): often field-level access control on one of the "
+ "properties - a request naming any restricted property fails as a whole."
)
- forbidden = status_counts.get("403", 0)
- if forbidden:
- log(f" {forbidden} forbidden (HTTP 403): the credential can't delete these - likely a read-only key.")
- bad_request = status_counts.get("400", 0)
- if bad_request:
- log(
- f" {bad_request} rejected (HTTP 400): often field-level access control on one of the "
- "properties - a request naming any restricted property fails as a whole."
- )
- for failure in failures[:20]:
- log(f" FAILED: {printable(failure)}")
- if len(failures) > 20:
- log(f" ... and {len(failures) - 20} more failures")
- if failures:
- return 1
+ if failures:
+ log(f" {len(failures)} failure(s) - see the FAILED lines above for details")
+ return 1
return 0
+def run(args: argparse.Namespace) -> int:
+ properties = sorted(set(args.properties))
+ session = build_session(args)
+ affected = discover_affected(session, args, properties)
+
+ if not affected:
+ log("Nothing to scrub.")
+ return 0
+
+ pair_count = sum(len(p["matched_properties"]) for p in affected)
+ log_preview(affected)
+
+ if args.dry_run:
+ log("")
+ log("DRY RUN: no changes made.")
+ return 0
+
+ if not confirm_scrub(args, affected, pair_count):
+ return 1
+
+ return execute_scrub(session, args, affected, pair_count)
+
+
if __name__ == "__main__":
try:
sys.exit(main())