: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
feat(business knowledge): initial migrations and models (#57984)
Alex Vd4ebf0f5ff80
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yamlindex 87797bafc9f2..9ef2470bc506 100644--- a/.semgrep/rules/idor-team-scoped-models.yaml+++ b/.semgrep/rules/idor-team-scoped-models.yaml@@ -141,6 +141,9 @@ rules:|InsightVariable|Integration|IntegrationRepositoryCacheEntry+ |KnowledgeChunk+ |KnowledgeDocument+ |KnowledgeSource|Link|LiveDebuggerBreakpoint|LogsAlertConfiguration@@ -352,6 +355,9 @@ rules:|InsightVariable|Integration|IntegrationRepositoryCacheEntry+ |KnowledgeChunk+ |KnowledgeDocument+ |KnowledgeSource|Link|LiveDebuggerBreakpoint|LLMModelConfigurationdiff --git a/products/business_knowledge/backend/migrations/0001_initial.py b/products/business_knowledge/backend/migrations/0001_initial.pynew file mode 100644index 000000000000..256e4ac95f26--- /dev/null+++ b/products/business_knowledge/backend/migrations/0001_initial.py@@ -0,0 +1,260 @@+# Generated by Django 5.2.13 on 2026-05-07 13:56++import django.db.models.deletion+import django.contrib.postgres.indexes+from django.conf import settings+from django.db import migrations, models++import posthog.models.utils+++class Migration(migrations.Migration):+ initial = True++ dependencies = [+ ("posthog", "1148_backfill_encrypted_payloads_invariant"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.CreateModel(+ name="KnowledgeSource",+ fields=[+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("name", models.CharField(max_length=255)),+ (+ "source_type",+ models.CharField(+ choices=[("text", "Text"), ("url", "URL"), ("file", "File")],+ max_length=16,+ ),+ ),+ (+ "status",+ models.CharField(+ choices=[+ ("pending", "Pending"),+ ("processing", "Processing"),+ ("ready", "Ready"),+ ("error", "Error"),+ ],+ default="pending",+ max_length=16,+ ),+ ),+ ("error_message", models.TextField(blank=True, default="")),+ (+ "source_url",+ models.URLField(blank=True, default="", max_length=2048),+ ),+ ("last_refresh_at", models.DateTimeField(blank=True, null=True)),+ (+ "last_refresh_status",+ models.CharField(+ blank=True,+ choices=[+ ("success", "Success"),+ ("not_modified", "Not modified"),+ ("error", "Error"),+ ],+ default="",+ max_length=16,+ ),+ ),+ ("last_refresh_error", models.TextField(blank=True, default="")),+ ("last_etag", models.CharField(blank=True, default="", max_length=255)),+ (+ "crawl_mode",+ models.CharField(+ blank=True,+ choices=[+ ("single", "Single page"),+ ("sitemap", "Sitemap"),+ ("same_origin", "Same origin crawl"),+ ("github_repo", "GitHub repository"),+ ],+ default="single",+ max_length=16,+ ),+ ),+ ("crawl_config", models.JSONField(blank=True, default=dict)),+ (+ "original_filename",+ models.CharField(blank=True, default="", max_length=255),+ ),+ (+ "file_content_type",+ models.CharField(blank=True, default="", max_length=128),+ ),+ ("file_size_bytes", models.PositiveIntegerField(blank=True, null=True)),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "team",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="business_knowledge_sources",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "db_table": "posthog_business_knowledge_knowledgesource",+ "ordering": ["-created_at"],+ },+ ),+ migrations.CreateModel(+ name="KnowledgeDocument",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("stable_id", models.CharField(max_length=512)),+ ("title", models.CharField(blank=True, default="", max_length=512)),+ ("content", models.TextField()),+ ("metadata", models.JSONField(blank=True, default=dict)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ ("url", models.URLField(blank=True, default="", max_length=2048)),+ ("etag", models.CharField(blank=True, default="", max_length=255)),+ (+ "content_hash",+ models.CharField(blank=True, default="", max_length=64),+ ),+ ("tombstoned_at", models.DateTimeField(blank=True, null=True)),+ (+ "team",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ (+ "source",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="documents",+ to="business_knowledge.knowledgesource",+ ),+ ),+ ],+ options={+ "db_table": "posthog_business_knowledge_knowledgedocument",+ },+ ),+ migrations.CreateModel(+ name="KnowledgeChunk",+ fields=[+ (+ "id",+ models.UUIDField(editable=False, primary_key=True, serialize=False),+ ),+ (+ "heading_path",+ models.CharField(blank=True, default="", max_length=1024),+ ),+ ("ordinal", models.IntegerField()),+ ("content", models.TextField()),+ ("char_count", models.PositiveIntegerField()),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ (+ "team",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ (+ "document",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="chunks",+ to="business_knowledge.knowledgedocument",+ ),+ ),+ (+ "source",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="chunks",+ to="business_knowledge.knowledgesource",+ ),+ ),+ ],+ options={+ "db_table": "posthog_business_knowledge_knowledgechunk",+ },+ ),+ migrations.AddIndex(+ model_name="knowledgesource",+ index=models.Index(fields=["team", "-created_at"], name="bk_source_team_created"),+ ),+ migrations.AddIndex(+ model_name="knowledgesource",+ index=models.Index(fields=["team", "status"], name="bk_source_team_status"),+ ),+ migrations.AddIndex(+ model_name="knowledgesource",+ index=models.Index(fields=["team", "source_type"], name="bk_source_team_type"),+ ),+ migrations.AddIndex(+ model_name="knowledgedocument",+ index=models.Index(fields=["team", "source"], name="bk_doc_team_source"),+ ),+ migrations.AddIndex(+ model_name="knowledgedocument",+ index=models.Index(fields=["source"], name="bk_doc_source"),+ ),+ migrations.AddConstraint(+ model_name="knowledgedocument",+ constraint=models.UniqueConstraint(fields=("source", "stable_id"), name="bk_doc_unique_per_source"),+ ),+ migrations.AddIndex(+ model_name="knowledgechunk",+ index=models.Index(fields=["team", "source"], name="bk_chunk_team_source"),+ ),+ migrations.AddIndex(+ model_name="knowledgechunk",+ index=models.Index(fields=["document", "ordinal"], name="bk_chunk_doc_ordinal"),+ ),+ migrations.AddIndex(+ model_name="knowledgechunk",+ index=django.contrib.postgres.indexes.GinIndex(+ fields=["content"],+ name="bk_chunk_content_trgm",+ opclasses=["gin_trgm_ops"],+ ),+ ),+ migrations.AddConstraint(+ model_name="knowledgechunk",+ constraint=models.UniqueConstraint(+ fields=("document", "heading_path", "ordinal"),+ name="bk_chunk_unique_position",+ ),+ ),+ ]diff --git a/products/business_knowledge/backend/migrations/__init__.py b/products/business_knowledge/backend/migrations/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/business_knowledge/backend/migrations/max_migration.txt b/products/business_knowledge/backend/migrations/max_migration.txtnew file mode 100644index 000000000000..cbab66dde92a--- /dev/null+++ b/products/business_knowledge/backend/migrations/max_migration.txt@@ -0,0 +1 @@+0001_initialdiff --git a/products/business_knowledge/backend/models.py b/products/business_knowledge/backend/models.pydeleted file mode 100644index aa8b59292bfd..000000000000--- a/products/business_knowledge/backend/models.py+++ /dev/null@@ -1,9 +0,0 @@-"""Django models for business_knowledge."""---# Define your models here-# Important:-# - Keep models thin, no business logic, use logic.py instead-# - Use types from facade/contracts.py or facade/enums.py where applicable-# - Do not use ForeignKeys to models outside this app unless allowed, as you will make implicit dependencies.-# - If you make a ForeignKey to a common model, disallow reverse relations with related_name='+'diff --git a/products/business_knowledge/backend/models/__init__.py b/products/business_knowledge/backend/models/__init__.pynew file mode 100644index 000000000000..c84ba661449d--- /dev/null+++ b/products/business_knowledge/backend/models/__init__.py@@ -0,0 +1,14 @@+from .constants import CrawlMode, RefreshStatus, SourceStatus, SourceType+from .knowledge_chunk import KnowledgeChunk+from .knowledge_document import KnowledgeDocument+from .knowledge_source import KnowledgeSource++__all__ = [+ "CrawlMode",+ "KnowledgeChunk",+ "KnowledgeDocument",+ "KnowledgeSource",+ "RefreshStatus",+ "SourceStatus",+ "SourceType",+]diff --git a/products/business_knowledge/backend/models/constants.py b/products/business_knowledge/backend/models/constants.pynew file mode 100644index 000000000000..2ba94d63c527--- /dev/null+++ b/products/business_knowledge/backend/models/constants.py@@ -0,0 +1,50 @@+from django.db import models+++class SourceType(models.TextChoices):+ TEXT = "text", "Text"+ # Reserved for Stage 2 / Stage 3 — declared up front so the DB choice+ # set is stable and we don't need a migration to widen it later.+ URL = "url", "URL"+ FILE = "file", "File"+++class SourceStatus(models.TextChoices):+ # Stage 1 text sources jump straight to READY inside the create+ # endpoint. PENDING / PROCESSING / ERROR exist for Stage 2+ async flows.+ PENDING = "pending", "Pending"+ PROCESSING = "processing", "Processing"+ READY = "ready", "Ready"+ ERROR = "error", "Error"+++class RefreshStatus(models.TextChoices):+ """+ Outcome of the last refresh attempt on a URL source. Decoupled from+ `SourceStatus` because we want to keep a source `READY` even if the+ latest refresh returned `NOT_MODIFIED` or `ERROR` — the old chunks are+ still serving queries.+ """++ SUCCESS = "success", "Success"+ NOT_MODIFIED = "not_modified", "Not modified"+ ERROR = "error", "Error"+++class CrawlMode(models.TextChoices):+ """+ How to expand a URL source into documents.++ - SINGLE: Stage 2a behavior — exactly one doc per source.+ - SITEMAP: fetch sitemap.xml(+index) from the entry URL, treat listed+ URLs as documents.+ - SAME_ORIGIN: BFS from the entry URL up to `max_depth`, staying on the+ same (scheme, host, port). Respects robots.txt.+ - GITHUB_REPO: reserved — landed later so existing rows don't need a+ migration when we add it.+ """++ SINGLE = "single", "Single page"+ SITEMAP = "sitemap", "Sitemap"+ SAME_ORIGIN = "same_origin", "Same origin crawl"+ GITHUB_REPO = "github_repo", "GitHub repository"diff --git a/products/business_knowledge/backend/models/knowledge_chunk.py b/products/business_knowledge/backend/models/knowledge_chunk.pynew file mode 100644index 000000000000..2284b5c62e4c--- /dev/null+++ b/products/business_knowledge/backend/models/knowledge_chunk.py@@ -0,0 +1,62 @@+from typing import Any++from django.contrib.postgres.indexes import GinIndex+from django.db import models++from posthog.models.scoping.manager import TeamScopedManager++from .knowledge_document import KnowledgeDocument+from .knowledge_source import KnowledgeSource+++class KnowledgeChunk(models.Model):+ """+ A retrievable text chunk — the grain the AI agent queries with ILIKE.++ `id` is deterministic: uuid5(document.stable_id, f"{heading_path}|{ordinal}"),+ set in logic.py before save. Re-parsing the same text yields the same+ chunk ids, which keeps any future citations / embeddings stable across+ refreshes.+ """++ id = models.UUIDField(primary_key=True, editable=False) # set by logic.py via deterministic uuid5+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+")+ source = models.ForeignKey(KnowledgeSource, on_delete=models.CASCADE, related_name="chunks")+ document = models.ForeignKey(KnowledgeDocument, on_delete=models.CASCADE, related_name="chunks")++ # Best-effort section path, e.g. "Getting started > Installation". Empty+ # for Stage 1 plain text where we don't extract headings.+ heading_path = models.CharField(max_length=1024, blank=True, default="")+ # 0-based position within (document, heading_path). Combined with the+ # document stable_id, it seeds the deterministic chunk id.+ ordinal = models.IntegerField()+ content = models.TextField()+ # Rough character length; kept separately so the agent can ORDER BY / LIMIT+ # without loading content into HogQL context.+ char_count = models.PositiveIntegerField()+ created_at = models.DateTimeField(auto_now_add=True)++ objects = TeamScopedManager()++ class Meta:+ db_table = "posthog_business_knowledge_knowledgechunk"+ indexes = [+ models.Index(fields=["team", "source"], name="bk_chunk_team_source"),+ models.Index(fields=["document", "ordinal"], name="bk_chunk_doc_ordinal"),+ GinIndex(fields=["content"], opclasses=["gin_trgm_ops"], name="bk_chunk_content_trgm"),+ ]+ # One physical chunk per (document, heading_path, ordinal). Matches+ # the uuid5 seed so the deterministic id can never collide silently.+ constraints = [+ models.UniqueConstraint(+ fields=["document", "heading_path", "ordinal"],+ name="bk_chunk_unique_position",+ ),+ ]++ def save(self, *args: Any, **kwargs: Any) -> None:+ if self.pk is None:+ raise ValueError(+ "KnowledgeChunk.id must be set before save — use logic.py's deterministic chunk_id() to compute it."+ )+ super().save(*args, **kwargs)diff --git a/products/business_knowledge/backend/models/knowledge_document.py b/products/business_knowledge/backend/models/knowledge_document.pynew file mode 100644index 000000000000..25dfecb05038--- /dev/null+++ b/products/business_knowledge/backend/models/knowledge_document.py@@ -0,0 +1,57 @@+from django.db import models++from posthog.models.scoping.manager import TeamScopedManager+from posthog.models.utils import UUIDModel++from .knowledge_source import KnowledgeSource+++class KnowledgeDocument(UUIDModel):+ """+ One parsed artifact inside a KnowledgeSource. Stage 1 text sources have+ exactly one document per source; Stage 2/3 URL/file sources can have many.+ """++ # team_id is denormalized off source.team_id so every HogQL-exposed table+ # can be filtered independently without forcing a join.+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+")+ source = models.ForeignKey(KnowledgeSource, on_delete=models.CASCADE, related_name="documents")+ # Stable identity across refreshes. For Stage 1 text it's the document's+ # own UUID. For Stage 2+ URLs it will be set to the normalized URL so a+ # re-crawl replaces rather than duplicates.+ stable_id = models.CharField(max_length=512)+ title = models.CharField(max_length=512, blank=True, default="")+ # The raw parsed text. Kept so we can re-chunk without re-parsing the+ # source. Bounded by MAX_TEXT_SIZE_BYTES at the API layer.+ content = models.TextField()+ metadata = models.JSONField(default=dict, blank=True)+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)++ # --- Stage 2a: URL-document fields ---+ # Absolute fetched URL (after any redirects). For Stage 2a this mirrors+ # `source.source_url`; Stage 2b crawl makes them diverge.+ url = models.URLField(max_length=2048, blank=True, default="")+ # Per-document ETag — deliberately separate from `source.last_etag` so+ # the crawl case can use per-page conditional GETs later.+ etag = models.CharField(max_length=255, blank=True, default="")+ # sha256 of the parsed text we stored in `content`. Lets us skip+ # re-chunking when a refresh returns new HTML but semantically identical+ # content (common with news/CMS templates).+ content_hash = models.CharField(max_length=64, blank=True, default="")+ # Set when a crawl stops seeing a page that used to exist. Stage 2a+ # never writes this; kept as a forward-compatible field so Stage 2b+ # doesn't need another migration.+ tombstoned_at = models.DateTimeField(null=True, blank=True)++ objects = TeamScopedManager()++ class Meta:+ db_table = "posthog_business_knowledge_knowledgedocument"+ indexes = [+ models.Index(fields=["team", "source"], name="bk_doc_team_source"),+ models.Index(fields=["source"], name="bk_doc_source"),+ ]+ constraints = [+ models.UniqueConstraint(fields=["source", "stable_id"], name="bk_doc_unique_per_source"),+ ]diff --git a/products/business_knowledge/backend/models/knowledge_source.py b/products/business_knowledge/backend/models/knowledge_source.pynew file mode 100644index 000000000000..06fde12d8237--- /dev/null+++ b/products/business_knowledge/backend/models/knowledge_source.py@@ -0,0 +1,70 @@+from django.db import models++from posthog.models.activity_logging.model_activity import ModelActivityMixin+from posthog.models.scoping.manager import TeamScopedManager+from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel++from .constants import CrawlMode, RefreshStatus, SourceStatus, SourceType+++class KnowledgeSource(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFields, UUIDModel):+ """+ A user-created collection of business knowledge (e.g. "Product docs",+ "Support macros"). One source groups one or more documents.+ """++ activity_logging_on_delete = True++ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="business_knowledge_sources")+ name = models.CharField(max_length=255)+ source_type = models.CharField(max_length=16, choices=SourceType.choices)+ status = models.CharField(max_length=16, choices=SourceStatus.choices, default=SourceStatus.PENDING)+ # Human-facing failure reason. Empty when status != ERROR.+ error_message = models.TextField(blank=True, default="")++ # --- Stage 2a: URL-source fields (all nullable — additive, text sources+ # leave them empty) ---+ # Canonical submitted URL (after SSRF validation and userinfo strip).+ # Stage 2b will widen this into a multi-page crawl; for now it's the+ # single URL we fetched.+ source_url = models.URLField(max_length=2048, blank=True, default="")+ # Last time we successfully reached out to `source_url` (regardless of+ # whether content actually changed).+ last_refresh_at = models.DateTimeField(null=True, blank=True)+ last_refresh_status = models.CharField(max_length=16, choices=RefreshStatus.choices, blank=True, default="")+ # Human-facing failure reason from the most recent refresh attempt. Kept+ # separate from `error_message` because refresh failures don't knock the+ # source out of READY — old chunks keep serving.+ last_refresh_error = models.TextField(blank=True, default="")+ # Last ETag received; fed back via `If-None-Match` on the next refresh+ # to get cheap 304 responses. Not an index — we only look it up by source.+ last_etag = models.CharField(max_length=255, blank=True, default="")++ # --- Stage 2b: multi-page crawl fields ---+ # How to expand `source_url` into N documents. `single` keeps Stage 2a+ # semantics (one doc per source); other modes run the discover pipeline.+ crawl_mode = models.CharField(max_length=16, choices=CrawlMode.choices, blank=True, default=CrawlMode.SINGLE)+ # Free-form knobs for the crawl: `include_globs`, `exclude_globs`,+ # `max_depth`, `max_pages`. Stored as JSON so adding a knob doesn't+ # require a migration. Validated at the serializer layer; logic.py+ # re-reads with safe defaults.+ crawl_config = models.JSONField(default=dict, blank=True)++ # --- Stage 3: file-source metadata (all nullable — additive) ---+ # Sanitized original filename from the upload. Never used as a path.+ original_filename = models.CharField(max_length=255, blank=True, default="")+ # Content type detected from magic bytes, not from the upload header.+ file_content_type = models.CharField(max_length=128, blank=True, default="")+ # Size of the uploaded file in bytes (compressed, as received).+ file_size_bytes = models.PositiveIntegerField(null=True, blank=True)++ objects = TeamScopedManager()++ class Meta:+ db_table = "posthog_business_knowledge_knowledgesource"+ ordering = ["-created_at"]+ indexes = [+ models.Index(fields=["team", "-created_at"], name="bk_source_team_created"),+ models.Index(fields=["team", "status"], name="bk_source_team_status"),+ models.Index(fields=["team", "source_type"], name="bk_source_team_type"),+ ]