repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
posthog | products/growth/backend/models.py | .py | import json
import hashlib
from django.db import models
from django.db.models import Q
from posthog.models.utils import UpdatedMetaFields, UUIDModel
class ProductPushCampaign(UUIDModel, UpdatedMetaFields):
"""One product pushed to a whole organization for a bounded window.
A single table holds the queue (S... | 295 | 12,974 |
posthog | products/growth/backend/apps.py | .py | from django.apps import AppConfig
class GrowthConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "products.growth.backend"
label = "growth"
| 8 | 182 |
posthog | products/growth/backend/constants.py | .py | from typing import Literal, TypedDict
from django.conf import settings
SDK_CACHE_EXPIRY = 60 * 60 * 24 * 7 # 7 days β used by the GitHub `latestVersion` cache (hourly Dagster job)
# Team-events snapshot TTL β sized to self-heal one missed daily cron run.
# The Temporal `sdk_outdated` cron starts at 08:00 UTC; per-t... | 255 | 10,577 |
posthog | products/growth/backend/sdk_health.py | .py | """
SDK Health health assessment.
The single source of truth for SDK outdatedness detection. Consumed by:
- the `sdk_outdated` Temporal health check (alerts / HealthIssue rows),
- the SDK Health report endpoint (posthog/api/sdk_health.py), which the SDK Health UI and the
SDK Health MCP tool both read.
The fro... | 876 | 32,638 |
posthog | products/growth/backend/routes.py | .py | from posthog.api.routing import RouterRegistry
from products.growth.backend.api.ai_enrichment import AIEnrichmentViewSet
from products.growth.backend.api.identity_matching import IdentityMatchingLinkViewSet
from products.growth.backend.api.product_push import ProductPushCampaignViewSet
def register_routes(routers: R... | 20 | 861 |
posthog | products/growth/backend/management/commands/backfill_enrichment_fields.py | .py | """Re-derive enrichment fields from each org's latest archived Harmonic payload and rewrite them.
Generic by design: this re-runs the CURRENT transform_harmonic_company against the stored raw
payload, so it always picks up every field the transform produces at run time -- not just the
fields present when this command ... | 140 | 6,723 |
posthog | products/growth/backend/management/commands/backfill_signup_enrichment.py | .py | """Re-dispatch signup enrichment for organizations whose enrichment never persisted.
Targets orgs created in a window that were eligible at signup (work email recorded) but have
no archived provider fetch β the archive row is the first write of every enrichment run, so
its absence means the run never completed. Re-dis... | 122 | 6,325 |
posthog | products/growth/backend/management/commands/enrichment_label_dry_run.py | .py | """Dry-run lab for iterating on an EnrichmentPromptConfig against real archived payloads.
Nothing here persists: this is the interactive loop for iterating on prompt/version
choices before a version is worth shadow-running for real via enrichment_label_batch.
"""
from pathlib import Path
from typing import Any
from ... | 182 | 8,424 |
posthog | products/growth/backend/management/commands/backfill_harmonic_ownership.py | .py | """Backfill ownership_status/parent_company/parent_company_domain for orgs enriched before
Harmonic ownership lookup shipped.
Targets OrganizationEnrichment rows with no "ownership_status" key in `data`, restricted to
orgs the live pipeline actually fetched from a provider (an OrganizationEnrichmentFetch row
exists) a... | 216 | 10,671 |
posthog | products/growth/backend/management/commands/enrichment_label_batch.py | .py | """Shadow batch runner: computes an EnrichmentLabelResult for every org's latest fetch.
Idempotent and resumable β a killed or re-run pass skips any (org, label, version, fetch)
already computed, so partial progress is never redone and a re-enriched org naturally
recomputes under the same version. Nothing here is cons... | 372 | 18,894 |
posthog | products/growth/backend/temporal/__init__.py | .py | from products.growth.backend.temporal.signup_enrichment import (
ACTIVITIES as SIGNUP_ENRICHMENT_ACTIVITIES,
WORKFLOWS as SIGNUP_ENRICHMENT_WORKFLOWS,
)
WORKFLOWS = [*SIGNUP_ENRICHMENT_WORKFLOWS]
ACTIVITIES = [*SIGNUP_ENRICHMENT_ACTIVITIES]
| 9 | 251 |
posthog | products/growth/backend/temporal/signup_enrichment/workflow.py | .py | """Real-time signup enrichment: a fire-and-forget Temporal workflow started after signup.
The workflow wraps the orchestration-agnostic enrichment core (products/growth), writes the
live stores, wires the write-once at-signup snapshot, and emits a launch fill-rate/failure
signal. It is dispatched from the signup reque... | 211 | 10,486 |
posthog | products/growth/backend/temporal/signup_enrichment/trigger.py | .py | """Fire-and-forget dispatch of the signup enrichment workflow from the request path.
Every guard lives here so the signup serializer stays a one-line call. Dispatch is gated by the
kill switch and the Cloud region (self-hosted never dispatches), and never raises β a Temporal
outage degrades to "enrichment did not run"... | 174 | 7,075 |
posthog | products/growth/backend/temporal/signup_enrichment/__init__.py | .py | from products.growth.backend.temporal.signup_enrichment.workflow import (
SignupEnrichmentWorkflow,
enrich_signup_organization_activity,
)
WORKFLOWS = [SignupEnrichmentWorkflow]
ACTIVITIES = [enrich_signup_organization_activity]
| 9 | 239 |
posthog | products/growth/backend/temporal/signup_enrichment/tests/test_trigger.py | .py | import pytest
from unittest.mock import patch
from django.test import override_settings
from temporalio.exceptions import WorkflowAlreadyStartedError
from products.growth.backend.temporal.signup_enrichment.trigger import (
dispatch_signup_enrichment,
start_signup_enrichment_workflow,
)
from products.growth.b... | 236 | 11,165 |
posthog | products/growth/backend/temporal/signup_enrichment/tests/test_workflow.py | .py | import uuid
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import UnsandboxedWorkflowRunner, Worker
from products.growth.backend.enrichment.fields import EnrichmentFields
from products.growth.backend.temporal.signup_enrich... | 114 | 5,003 |
posthog | products/growth/backend/temporal/signup_enrichment/tests/test_activity.py | .py | import threading
import dataclasses
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
from asgiref.sync import sync_to_async
from temporalio.testing import ActivityEnvironment
from products.growth.backend.enrichment.fields import EnrichmentFields
from products.growth.backend.temporal.signup_enrichm... | 98 | 4,440 |
posthog | products/growth/backend/temporal/health_checks/sdk_outdated.py | .py | import json
from collections import defaultdict
from typing import Any
import structlog
from posthog.dags.common.owners import JobOwners
from posthog.models.health_issue import HealthIssue
from posthog.redis import get_client
from posthog.temporal.health_checks.detectors import HealthExecutionPolicy
from posthog.temp... | 294 | 12,096 |
posthog | products/growth/backend/temporal/health_checks/tests/test_sdk_outdated.py | .py | from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase
from parameterized import parameterized
from posthog.models.health_issue import HealthIssue
from products.growth.backend.constants import TEAM_SDK_CACHE_EXPIRY
from products.growth.backend.temporal.health_checks.sdk_outdated import Sd... | 293 | 11,996 |
posthog | products/growth/backend/tests/test_product_push_service.py | .py | from datetime import timedelta
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
from django.utils import timezone
from posthog.models.organization import Organization
from posthog.models.product_intent.product_intent import ProductIntent
from products.growth.backend.models import Pr... | 268 | 11,965 |
posthog | products/growth/backend/tests/test_enrichment_clearbit.py | .py | from parameterized import parameterized
from products.growth.backend.enrichment.clearbit import ClearbitInputs, clearbit_inputs_from_person_properties
from products.growth.backend.enrichment.score import IcpScoreInputs, compute_icp_score
def _properties(band=None):
company = {"metrics": {"estimatedAnnualRevenue"... | 56 | 2,301 |
posthog | products/growth/backend/tests/test_enrichment_core.py | .py | from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
from asgiref.sync import async_to_sync
from parameterized import parameterized
from products.growth.backend.enrichment.bridge import ClayBridgeInputs
from products.growth.backend.enrichment.core import enrich_organization
from products.... | 418 | 19,839 |
posthog | products/growth/backend/tests/test_cross_sell_candidate_selector.py | .py | from django.test import TestCase
from hypothesis import (
given,
settings,
strategies as st,
)
from posthog.schema import ProductItemCategory, ProductKey
from posthog.products import Products
from products.growth.backend.cross_sell_candidate_selector import (
BASE_PREFERENCE_WEIGHTS,
DEFAULT_IGN... | 335 | 14,703 |
posthog | products/growth/backend/tests/test_backfill_enrichment_fields.py | .py | import datetime as dt
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
from django.core.management import CommandError, call_command
from django.utils import timezone
from parameterized import parameterized
from posthog.models.organization import Organization
from products.growth.b... | 165 | 6,880 |
posthog | products/growth/backend/tests/test_enrichment_labels.py | .py | import json
import datetime as dt
from io import StringIO
from posthog.test.base import BaseTest, NonAtomicBaseTest
from unittest.mock import MagicMock, patch
from django.core.management import call_command
from django.core.management.base import CommandError
from django.test import SimpleTestCase
import openai
from... | 708 | 31,316 |
posthog | products/growth/backend/tests/test_enrichment_providers.py | .py | import pytest
from unittest.mock import AsyncMock, MagicMock, patch
from products.growth.backend.enrichment.providers import HarmonicEnrichmentProvider
def _fake_harmonic_client(company, *, parent_company=None, parent_side_effect=None):
"""Build a mock standing in for `async with AsyncHarmonicClient() as client`... | 134 | 5,966 |
posthog | products/growth/backend/tests/test_enrichment_bridge.py | .py | from posthog.test.base import BaseTest
from unittest.mock import patch
from parameterized import parameterized
from posthog.models.group.group import Group
from products.growth.backend.enrichment.bridge import (
ClayBridgeInputs,
OrganizationGroupTypeMissing,
read_clay_bridge_inputs,
)
_ORGANIZATION_GRO... | 87 | 3,821 |
posthog | products/growth/backend/tests/test_enrichment_fields.py | .py | from products.growth.backend.enrichment.fields import EnrichmentFields
def test_to_dict_drops_unset_fields():
fields = EnrichmentFields(company_type="startup", headcount=42)
assert fields.to_dict() == {"company_type": "startup", "headcount": 42}
def test_to_dict_keeps_falsey_but_set_values():
fields = E... | 39 | 1,288 |
posthog | products/growth/backend/tests/test_snapshot.py | .py | from posthog.test.base import BaseTest
from unittest.mock import MagicMock
from parameterized import parameterized
from products.growth.backend.enrichment.snapshot import (
SNAPSHOT_EVENT_NAME,
SignupEnrichmentSnapshot,
capture_signup_enrichment_snapshot,
)
from products.growth.backend.models import Enric... | 113 | 4,132 |
posthog | products/growth/backend/tests/test_enrichment_score.py | .py | from parameterized import parameterized
from products.growth.backend.enrichment.score import SCORE_VERSION, IcpScoreInputs, compute_icp_score
# A country on the allowlist keeps the -5 penalty out of the way, so each case isolates its branch.
def _inputs(**overrides) -> IcpScoreInputs:
return IcpScoreInputs(count... | 173 | 5,298 |
posthog | products/growth/backend/tests/test_sdk_health.py | .py | from datetime import UTC, datetime, timedelta
from django.test import SimpleTestCase
from parameterized import parameterized
from products.growth.backend.sdk_health import (
LEGACY_JAVA_MIGRATION_REASON,
LEGACY_JAVA_VERSION_LABEL,
MINOR_AGE_THRESHOLD_DAYS,
MINOR_VERSIONS_BEHIND_THRESHOLD,
SINGLE_... | 940 | 37,017 |
posthog | products/growth/backend/tests/test_enrichment_writer.py | .py | from posthog.test.base import BaseTest
from unittest.mock import MagicMock
from products.growth.backend.enrichment.fields import EnrichmentFields
from products.growth.backend.enrichment.writer import record_signup_work_email, write_organization_enrichment
from products.growth.backend.models import OrganizationEnrichme... | 73 | 3,131 |
posthog | products/growth/backend/tests/test_product_push_admin.py | .py | from typing import Any
from posthog.test.base import BaseTest
from django import forms
from django.contrib.admin import AdminSite
from django.db.models.fields import BLANK_CHOICE_DASH
from django.test import RequestFactory
from django.urls import reverse
from posthog.models.organization import Organization
from pro... | 141 | 6,205 |
posthog | products/growth/backend/tests/test_enrichment_transform.py | .py | from parameterized import parameterized
from products.growth.backend.enrichment.transform import MAX_INVESTORS, transform_harmonic_company
def _company(**overrides):
company = {
"companyType": "STARTUP",
"headcount": 120,
"location": {"country": "United States"},
"foundingDate": {... | 207 | 7,878 |
posthog | products/growth/backend/tests/test_enrichment_admin.py | .py | from typing import Any
from posthog.test.base import BaseTest
from django.contrib.admin import AdminSite
from django.core.exceptions import ValidationError
from django.test import RequestFactory, SimpleTestCase
from parameterized import parameterized
from products.growth.backend.admin import (
EnrichmentLabelNa... | 261 | 10,643 |
posthog | products/growth/backend/tests/test_backfill_harmonic_ownership.py | .py | import uuid
from io import StringIO
from typing import Any, Optional
from posthog.test.base import BaseTest
from unittest.mock import AsyncMock, MagicMock, patch
from django.core.management import call_command
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.user impor... | 305 | 13,273 |
posthog | products/growth/backend/tests/test_enrichment_label_commands.py | .py | import json
import threading
from io import StringIO
from typing import Any
from posthog.test.base import BaseTest, NonAtomicBaseTest
from unittest.mock import MagicMock, patch
from django.core.management import call_command
from django.core.management.base import CommandError
from django.db import connection
from p... | 587 | 26,377 |
posthog | products/growth/backend/tests/test_product_push_selection.py | .py | from datetime import UTC, datetime, timedelta
from posthog.test.base import BaseTest
from django.test import SimpleTestCase
from parameterized import parameterized
from posthog.models.product_intent.product_intent import ProductIntent
from posthog.models.project import Project
from posthog.products import Products
... | 160 | 7,625 |
posthog | products/growth/backend/tests/test_enrichment_backfill_command.py | .py | import datetime as dt
from posthog.test.base import BaseTest
from unittest.mock import patch
from django.core.management import CommandError, call_command
from django.test import override_settings
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.user import User
from ... | 113 | 4,696 |
posthog | products/growth/backend/tests/test_team_sdk_versions.py | .py | from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase
from products.growth.backend.constants import TEAM_SDK_CACHE_EXPIRY
from products.growth.backend.team_sdk_versions import get_and_cache_team_sdk_versions, get_sdk_versions_for_team
class TestGetSdkVersionsForTeam(SimpleTestCase):
... | 41 | 1,720 |
posthog | products/growth/backend/tests/test_enrichment_labels_validation.py | .py | import json
from typing import Any
from posthog.test.base import BaseTest
from unittest.mock import MagicMock
from django.test import SimpleTestCase
from parameterized import parameterized
from products.growth.backend.enrichment.labels import (
MAX_INPUT_COLUMNS,
MAX_INPUT_DEPTH,
MAX_INPUT_LIST_ITEMS,
... | 402 | 16,719 |
posthog | products/growth/backend/tests/test_product_push_cadence.py | .py | from datetime import UTC, date, datetime
from django.test import SimpleTestCase
from parameterized import parameterized
from products.growth.backend.product_push.cadence import (
campaign_ends_at,
is_cooldown_over,
is_grace_period_over,
is_pin_due,
is_retry_eligible,
)
NOW = datetime(2026, 7, 1,... | 60 | 2,195 |
posthog | products/growth/backend/api/ai_enrichment.py | .py | """Staff-only DRF API for the enrichment "AI enrichment": list labels, list a label's prompt
config versions, create a new immutable version, test-run a draft config against recent
archived orgs, and flip which version is active.
Shaped around config version + input rows + verdict rows, not around enrichment orgs, so ... | 379 | 18,164 |
posthog | products/growth/backend/api/__init__.py | .py | from products.growth.backend.api.identity_matching import IdentityMatchingLinkViewSet
__all__ = ["IdentityMatchingLinkViewSet"]
| 4 | 129 |
posthog | products/growth/backend/api/test_ai_enrichment.py | .py | import json
import uuid
import asyncio
from typing import Any
from posthog.test.base import APIBaseTest, NonAtomicAPIBaseTest
from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase
from parameterized import parameterized
from rest_framework import status
from posthog.models.organization i... | 830 | 40,565 |
posthog | products/growth/backend/api/test_identity_matching.py | .py | import hashlib
from datetime import UTC, datetime, timedelta
from typing import Any
from uuid import uuid4
from posthog.test.base import APIBaseTest
from django.test import override_settings
from parameterized import parameterized
from rest_framework import status
from posthog.clickhouse.client import sync_execute
... | 270 | 12,676 |
posthog | products/growth/backend/api/product_push.py | .py | from typing import cast
from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field
from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import NotFound, ValidationError
from rest_framework.request import Request... | 115 | 5,287 |
posthog | products/growth/backend/api/test_product_push.py | .py | from datetime import timedelta
from typing import TYPE_CHECKING
from freezegun import freeze_time
from posthog.test.base import APIBaseTest
from django.utils import timezone
from rest_framework import status
from posthog.constants import AvailableFeature
from posthog.models.organization import Organization, Organiz... | 133 | 5,742 |
posthog | products/growth/backend/api/identity_matching.py | .py | """Read-only API over the identity matching links.
Each run of the `identity_matching_job` Dagster job (products/growth/dags/identity_matching.py)
writes its links and candidate pairs as Parquet to a per-run S3 prefix
(`<prefix>/team_<team_id>/<job_id>/...`); nothing is persisted on the ClickHouse cluster. Every
query... | 483 | 24,718 |
posthog | products/growth/backend/api/ai_enrichment_serializers.py | .py | """Request and response serializers for the staff AI enrichment API (see ai_enrichment.py).
These are the source of truth for the generated frontend types and MCP tool schemas, so every
field carries help_text and every response shape is a declared serializer rather than a raw dict.
"""
from typing import Any
from d... | 244 | 12,122 |
posthog | products/growth/backend/enrichment/clearbit.py | .py | """Clearbit fallback for the ICP score's est_revenue input.
A separate hog function projects Clearbit's own company lookup onto the signer's person
profile under `person.properties.clearbit.*`, independently of the Clay bridge and on its
own delay (median ~8s after signup, p99 ~3min). Pure extraction: no I/O β callers... | 54 | 2,462 |
posthog | products/growth/backend/enrichment/transform.py | .py | """Transform a Harmonic company response into the enrichment field registry.
Tag/YC/safe-cast heuristics are shared with the Salesforce enrichment transforms in
ee/billing/salesforce_enrichment/enrichment.py and imported from there rather than copied.
"""
from typing import Any, Optional
from products.growth.backend... | 137 | 5,874 |
posthog | products/growth/backend/enrichment/labels.py | .py | """Classifier runner for versioned AI enrichment labels.
Pure functions only: no persistence, no client construction. Callers build the OpenAI
client via `get_llm_client(product="growth")` and pass it in β this module just turns
an archived Harmonic payload plus a prompt config into a stamped verdict.
"""
import re
i... | 516 | 25,655 |
posthog | products/growth/backend/enrichment/fields.py | .py | """Typed field registry for firmographic enrichment.
The single source of truth every enrichment writer imports, so the Postgres record,
the ClickHouse group-property projection, and the at-signup snapshot stay in lockstep.
Provider-agnostic: providers transform their responses into this shape. The ICP score is
delibe... | 65 | 2,684 |
posthog | products/growth/backend/enrichment/score.py | .py | """ICP scoring, transcribed from the Clay "ICP Scoring" formula column.
A faithful port, not a redesign: the formula, its weights, and its quirks are owned by
#team-demand-gen and revised separately. Scores are version-stamped so a later revision can
recompute historical orgs from the fetch archive under a new version... | 96 | 3,859 |
posthog | products/growth/backend/enrichment/writer.py | .py | """Writers for the live enrichment stores.
Orchestration-agnostic: plain functions any orchestrator (the real-time Temporal
workflow, a later batch Dagster asset) can call. Two of the three stores are written
here β the Postgres record read in-request and the ClickHouse group-property
projection. The at-signup person-... | 119 | 5,163 |
posthog | products/growth/backend/enrichment/bridge.py | .py | """Read the scoring inputs Clay still owns, off the organization group it writes.
The ICP score's revenue input has no first-party source, so while Clay runs in parallel we
read its own group property back and score on it. That keeps our scores bit-comparable with
Clay's on the orgs it also scores.
The formula's thir... | 95 | 4,281 |
posthog | products/growth/backend/enrichment/countries.py | .py | """Country-name to ISO 3166-1 alpha-2 mapping for provider responses.
Providers (Harmonic) return long English country names; the `icp_country` group
property holds ISO alpha-2 codes. The base mapping comes from babel's CLDR
territory data (already a dependency), inverted name->code; `_ALIASES` covers
provider spellin... | 60 | 2,021 |
posthog | products/growth/backend/enrichment/snapshot.py | .py | """At-signup enrichment snapshot.
Captures the firmographic enrichment values as they were at signup, separate from the
live values that later enrichment runs continuously refresh onto the organization group.
The snapshot is emitted once as a person-scoped event and never updated.
"""
import dataclasses
from typing i... | 75 | 2,704 |
posthog | products/growth/backend/enrichment/lab.py | .py | """Runner pieces behind the staff AI enrichment lab endpoints (products/growth/backend/api/ai_enrichment.py):
the gateway model list, and the concurrent stream that drives a test run.
Org-agnostic on purpose: everything here takes (config, fetch, client) in and a verdict out.
Callers build the input fetches themselves... | 174 | 8,957 |
posthog | products/growth/backend/enrichment/providers.py | .py | """Enrichment provider interface and the Harmonic implementation.
The interface keeps the enrichment core provider-agnostic; Harmonic is the first
provider. AsyncHarmonicClient (ee/billing/salesforce_enrichment) is reused as-is β
tach already allows products.growth to import ee.
"""
import abc
import dataclasses
from... | 93 | 3,544 |
posthog | products/growth/backend/enrichment/core.py | .py | """Orchestration-agnostic enrichment core.
Wraps a provider lookup and the live-store write into one coroutine that any
orchestrator can await β the real-time Temporal workflow (fire-and-forget from
signup) today, a batch Dagster asset later. No orchestration concerns leak in here.
"""
import dataclasses
from typing ... | 215 | 10,092 |
posthog | products/growth/backend/product_push/selection.py | .py | """Next-product selection for organization product push campaigns.
TAM-scheduled rows always take precedence, in TAM-defined order. Otherwise we
walk BLESSED_PRODUCT_ORDER and pick the first product the org is not excluded
from β there is deliberately no preference between never-pushed products and
retry-eligible ones... | 164 | 7,301 |
posthog | products/growth/backend/product_push/service.py | .py | """State transitions and adoption detection for product push campaigns.
Adoption is ProductIntent-based for v1. Extension path: plug ClickHouse usage
counters (posthog/tasks/usage_report.py `get_teams_with_*_count_in_period`
helpers) as a second source inside `org_adopted_product` β its contract stays
fixed. We delibe... | 354 | 14,292 |
posthog | products/growth/backend/product_push/cadence.py | .py | """Cadence rules for organization product push campaigns.
Pure date math β no DB access β so the rules are unit-testable in isolation.
Campaigns are rolling windows anchored on their own start (not on the org's
signup anniversary): the between-campaigns cooldown and early adoption closes
make anniversary anchoring imp... | 49 | 1,834 |
posthog | products/legal_documents/backend/admin.py | .py | from typing import IO, Any, cast
from django import forms
from django.contrib import admin, messages
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import UploadedFile
from django.core.validators import FileExtensionValidator
from django.db import IntegrityError, transaction
fro... | 371 | 15,330 |
posthog | products/legal_documents/backend/storage.py | .py | """
Object storage helpers for legal documents β kept separate from logic/ so
admin.py (autodiscovered very early by django.contrib.admin) doesn't transitively
pull ee.billing.BillingManager and trigger an import cycle.
"""
from __future__ import annotations
from django.conf import settings
from .models import Legal... | 21 | 715 |
posthog | products/legal_documents/backend/models.py | .py | from django.db import models
from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel
class LegalDocument(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFields, UUIDModel):
class DocumentType(models.TextChoic... | 59 | 2,443 |
posthog | products/legal_documents/backend/apps.py | .py | from django.apps import AppConfig
class LegalDocumentsConfig(AppConfig):
name = "products.legal_documents.backend"
label = "legal_documents"
verbose_name = "Legal documents"
def ready(self) -> None:
# Register the activity-log signal handler for LegalDocument.
from . import signals #... | 12 | 332 |
posthog | products/legal_documents/backend/signals.py | .py | from __future__ import annotations
import dataclasses
import structlog
from posthog.models.activity_logging.activity_log import (
ActivityContextBase,
ActivityScope,
Detail,
changes_between,
log_activity,
)
from posthog.models.signals import model_activity_signal, mutable_receiver
from posthog.mo... | 73 | 2,046 |
posthog | products/legal_documents/backend/routes.py | .py | from posthog.api.routing import RouterRegistry
from products.legal_documents.backend.presentation.views import LegalDocumentViewSet
def register_routes(routers: RouterRegistry) -> None:
routers.organizations.register(
r"legal_documents",
LegalDocumentViewSet,
"organization_legal_documents... | 13 | 358 |
posthog | products/legal_documents/backend/tasks/tasks.py | .py | """
Celery tasks for legal_documents.
Async entrypoints that call the facade (facade/api.py).
Keep task functions thin β only call facade methods.
"""
from __future__ import annotations
from uuid import UUID
import structlog
from celery import shared_task
from ..facade import api
logger = structlog.get_logger(__n... | 50 | 1,426 |
posthog | products/legal_documents/backend/tasks/schedules.py | .py | """Celery beat schedules for legal_documents."""
# Define periodic task schedules here
| 3 | 87 |
posthog | products/legal_documents/backend/presentation/serializers.py | .py | from typing import Any
from rest_framework import serializers
from rest_framework.exceptions import PermissionDenied
from rest_framework_dataclasses.serializers import DataclassSerializer
from posthog.models.organization import Organization
from ..facade import api
from ..facade.contracts import LegalDocumentDTO
fro... | 65 | 2,567 |
posthog | products/legal_documents/backend/presentation/views.py | .py | from typing import cast
from uuid import UUID
from django.core.exceptions import ValidationError as DjangoValidationError
from django.http import HttpResponseRedirect
from drf_spectacular.utils import extend_schema
from rest_framework import exceptions, permissions, status, viewsets
from rest_framework.decorators imp... | 132 | 6,347 |
posthog | products/legal_documents/backend/presentation/urls.py | .py | """URL routes for legal_documents."""
from rest_framework.routers import DefaultRouter
# from .views import ...
router = DefaultRouter()
urlpatterns = router.urls
| 9 | 166 |
posthog | products/legal_documents/backend/presentation/permissions.py | .py | from typing import cast
from rest_framework import exceptions
from rest_framework.permissions import BasePermission
from rest_framework.request import Request
from rest_framework.views import APIView
from posthog.cloud_utils import is_cloud, is_dev_mode
from posthog.models.organization import OrganizationMembership
f... | 51 | 2,143 |
posthog | products/legal_documents/backend/presentation/webhook.py | .py | import json
from django.conf import settings
import structlog
from drf_spectacular.utils import OpenApiTypes, extend_schema
from rest_framework import status
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.request import Request
from rest_framework.respon... | 133 | 5,692 |
posthog | products/legal_documents/backend/tests/test_api.py | .py | import hmac
import json
import hashlib
from contextlib import contextmanager
from datetime import timedelta
from typing import Any
from posthog.test.base import APIBaseTest
from unittest.mock import patch
from django.db import IntegrityError
from django.test import override_settings
from django.utils import timezone
... | 1,138 | 55,015 |
posthog | products/legal_documents/backend/tests/test_pandadoc.py | .py | import hmac
import hashlib
from unittest.mock import MagicMock, patch
from django.test import TestCase, override_settings
from parameterized import parameterized
from products.legal_documents.backend.logic import pandadoc
class TestPandaDocClient(TestCase):
@override_settings(PANDADOC_API_KEY="", PANDADOC_API... | 322 | 16,070 |
posthog | products/legal_documents/backend/tests/test_reconcile_tasks.py | .py | from typing import Any
from posthog.test.base import NonAtomicTestMigrations
from django.test import SimpleTestCase
from posthog.celery import app
from products.legal_documents.backend.facade import api as legal_api
from products.legal_documents.backend.tasks.tasks import archive_signed_legal_document_pdf
class T... | 75 | 3,371 |
posthog | products/legal_documents/backend/tests/test_admin.py | .py | from typing import Any
from posthog.test.base import APIBaseTest
from unittest.mock import patch
from django.contrib.admin import AdminSite
from django.contrib.admin.widgets import AutocompleteSelect
from django.contrib.messages.storage.fallback import FallbackStorage
from django.core.exceptions import ValidationErro... | 416 | 19,948 |
posthog | products/legal_documents/backend/tests/test_logic.py | .py | from typing import Any
from posthog.test.base import APIBaseTest
from unittest.mock import patch
from django.test import override_settings
from products.legal_documents.backend.logic import (
delete_document,
pandadoc as pandadoc_module,
)
from products.legal_documents.backend.models import LegalDocument
c... | 131 | 6,265 |
posthog | products/legal_documents/backend/facade/contracts.py | .py | """
Contract types for legal_documents.
Stable, framework-free frozen dataclasses that define what this product
exposes to the rest of the codebase. No Django imports.
"""
from dataclasses import dataclass
from datetime import datetime
from uuid import UUID
@dataclass(frozen=True)
class LegalDocumentCreator:
fi... | 55 | 1,426 |
posthog | products/legal_documents/backend/facade/enums.py | .py | """Exported enums and constants for legal_documents."""
from enum import StrEnum
class DocumentType(StrEnum):
BAA = "BAA"
DPA = "DPA"
MSA = "MSA"
class LegalDocumentStatus(StrEnum):
SUBMITTED_FOR_SIGNATURE = "submitted_for_signature"
SIGNED = "signed"
| 15 | 277 |
posthog | products/legal_documents/backend/facade/api.py | .py | """
Facade for legal_documents.
This is the ONLY module other products (and the presentation layer) are allowed
to import. Accepts frozen dataclasses as input, returns frozen dataclasses as
output, and never leaks ORM instances or QuerySets across the boundary.
"""
from __future__ import annotations
from collections... | 363 | 15,633 |
posthog | products/legal_documents/backend/facade/tasks.py | .py | """Facade re-export for the legal_documents Celery tasks.
Core's beat schedule (``posthog/tasks/scheduled.py``) imports the reconciliation
task object and calls ``.s()`` on it, so the wiring crosses the boundary as an
object, not data. Re-exporting the tasks keeps that coupling at the facade
boundary. Each ``name=`` i... | 13 | 605 |
posthog | products/legal_documents/backend/logic/__init__.py | .py | """
Business logic for legal_documents.
ORM queries, validation, calculations, business rules.
Called by facade/api.py β do not call from outside this module.
"""
from __future__ import annotations
from collections.abc import Callable, Iterable
from datetime import timedelta
from uuid import UUID
from django.conf i... | 617 | 25,406 |
posthog | products/legal_documents/backend/logic/pandadoc.py | .py | """
Thin client for the PandaDoc public API.
We hit these endpoints:
POST /public/v1/documents -> create a document from a template
GET /public/v1/documents/{id} -> read an envelope's current status
POST /public/v1/documents/{id}/send -> email the signing envelope
PATCH /pub... | 317 | 13,799 |
posthog | products/ai_observability/skills/exploring-llm-clusters/scripts/print_clusters.py | .py | """Print a summary of clusters from a clustering run result."""
import json
import sys
def load_result_file(path):
with open(path) as f:
raw = json.load(f)
if isinstance(raw, list) and raw and isinstance(raw[0], dict) and raw[0].get("type") == "text":
raw = json.loads(raw[0]["text"])
retu... | 104 | 3,949 |
posthog | products/ai_observability/skills/exploring-llm-traces/scripts/extract_conversation.py | .py | """Extract user/assistant messages from LLM generation events in a trace.
Env vars:
MAX_LEN β truncation limit per message (default 500, 0 for unlimited)
"""
import json
import os
import sys
def load_trace_file(path):
with open(path) as f:
raw = json.load(f)
# Claude Code persists large MCP tool ... | 107 | 4,055 |
posthog | products/ai_observability/skills/exploring-llm-traces/scripts/extract_span.py | .py | """Extract a specific span's full input/output state by name.
Usage:
SPAN="upsert_dashboard" python3 scripts/extract_span.py FILE
SPAN="router" python3 scripts/extract_span.py FILE
Env vars:
SPAN β span name to match (case-insensitive substring match)
MAX_LEN β truncation limit (default 0 = unlimited)
""... | 77 | 2,454 |
posthog | products/ai_observability/skills/exploring-llm-traces/scripts/search_traces.py | .py | """Search for a keyword across all event properties in a trace."""
import json
import os
import sys
def load_trace_file(path):
with open(path) as f:
raw = json.load(f)
# Claude Code persists large MCP tool results as [{"type": "text", "text": "<json>"}] β unwrap to get the actual trace data.
if i... | 46 | 1,685 |
posthog | products/ai_observability/skills/exploring-llm-traces/scripts/print_summary.py | .py | """Print a concise trace summary: metadata, tool calls, and final LLM output."""
import json
import os
import sys
def load_trace_file(path):
with open(path) as f:
raw = json.load(f)
if isinstance(raw, list) and raw and raw[0].get("type") == "text":
raw = json.loads(raw[0]["text"])
metadat... | 152 | 5,727 |
posthog | products/ai_observability/skills/exploring-llm-traces/scripts/show_structure.py | .py | """Show JSON keys and types without values. Reads from stdin or a file argument."""
import json
import sys
def load_trace_data(source):
raw = json.load(source)
# Claude Code persists large MCP tool results as [{"type": "text", "text": "<json>"}] β unwrap to get the actual trace data.
if isinstance(raw, l... | 45 | 1,435 |
posthog | products/ai_observability/skills/exploring-llm-traces/scripts/print_timeline.py | .py | """Print a chronological timeline of tool calls and generations in a trace."""
import json
import sys
def load_trace_file(path):
with open(path) as f:
raw = json.load(f)
# Claude Code persists large MCP tool results as [{"type": "text", "text": "<json>"}] β unwrap to get the actual trace data.
if... | 51 | 2,214 |
posthog | products/ai_observability/backend/dataset_limits.py | .py | MAX_DATASET_EXPORT_MEGABYTES = 250
MAX_DATASET_EXPORT_BYTES = MAX_DATASET_EXPORT_MEGABYTES * 1_000_000
MAX_ITEMS_PER_DATASET = 600
# Reserve space for identifiers, provenance fields, JSON keys, and escaping in each JSONL row.
MAX_DATASET_EXPORT_ROW_OVERHEAD_BYTES = 10_000
MAX_DATASET_ITEM_PAYLOAD_BYTES = (
MAX_DA... | 11 | 406 |
posthog | products/ai_observability/backend/dataset_queries.py | .py | from uuid import UUID
from django.db.models import F, OuterRef, QuerySet, Subquery
from products.ai_observability.backend.models.datasets import DatasetItemVersion, DatasetRevision
def consistent_dataset_item_versions(
queryset: QuerySet[DatasetItemVersion, DatasetItemVersion],
) -> QuerySet[DatasetItemVersion,... | 52 | 1,683 |
posthog | products/ai_observability/backend/apps.py | .py | from typing import TYPE_CHECKING
from django.apps import AppConfig
if TYPE_CHECKING:
from products.exports.backend.models.exported_asset import ExportedAsset
def _export_dataset_jsonl(asset: "ExportedAsset") -> None:
from products.ai_observability.backend.dataset_export import ( # noqa: PLC0415 -- keeps da... | 32 | 1,302 |
posthog | products/ai_observability/backend/score_definition_configs.py | .py | import re
from typing import Any
from drf_spectacular.utils import PolymorphicProxySerializer, extend_schema_field
from rest_framework import serializers
SCORE_DEFINITION_KEY_PATTERN = re.compile(r"^[a-z0-9]+(?:[_-][a-z0-9]+)*$")
def normalize_score_definition_key(value: str, *, field_name: str = "key") -> str:
... | 208 | 7,980 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.