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.

chore(data-modeling): return frozen dataclasses instead of tuples (#76128)

Arno Hillen70803aeddb15
diff --git a/posthog/temporal/data_modeling/activities/materialize_view.py b/posthog/temporal/data_modeling/activities/materialize_view.py
index 5b8a463d8193..7a703f308293 100644
--- a/posthog/temporal/data_modeling/activities/materialize_view.py
+++ b/posthog/temporal/data_modeling/activities/materialize_view.py
@@ -445,10 +445,18 @@ async def hogql_table(query: str, team: Team, logger: FilteringBoundLogger, view
yield (empty_batch, ch_typings_pairs)
[email protected](frozen=True, kw_only=True, slots=True)
+class MatviewInputObjects:
+ team: Team
+ node: Node
+ saved_query: DataWarehouseSavedQuery
+ job: DataModelingJob
+
+
@database_sync_to_async_pool
def _get_matview_input_objects(
inputs: MaterializeViewInputs,
-) -> tuple[Team, Node, DataWarehouseSavedQuery, DataModelingJob]:
+) -> MatviewInputObjects:
team = Team.objects.get(id=inputs.team_id)
node = Node.objects.prefetch_related("saved_query").get(
id=inputs.node_id, team_id=inputs.team_id, dag_id=inputs.dag_id
@@ -467,7 +475,7 @@ def _get_matview_input_objects(
prepare_executable_query(saved_query)
job = DataModelingJob.objects.get(id=inputs.job_id, team_id=inputs.team_id)
- return (team, node, saved_query, job)
+ return MatviewInputObjects(team=team, node=node, saved_query=saved_query, job=job)
@activity.defn
@@ -478,10 +486,10 @@ async def materialize_view_activity(inputs: MaterializeViewInputs) -> Materializ
tag_queries(team_id=inputs.team_id, product=Product.WAREHOUSE, feature=Feature.DATA_MODELING)
- team, node, saved_query, job = await _get_matview_input_objects(inputs)
- await logger.ainfo(f"Starting materialization for node {node.name}")
+ objects = await _get_matview_input_objects(inputs)
+ await logger.ainfo(f"Starting materialization for node {objects.node.name}")
- table_uri = _build_model_table_uri(team.pk, saved_query.id.hex, saved_query.normalized_name)
+ table_uri = _build_model_table_uri(objects.team.pk, objects.saved_query.id.hex, objects.saved_query.normalized_name)
await logger.adebug(f"Delta table URI = {table_uri}")
async with Heartbeater():
@@ -494,7 +502,7 @@ async def materialize_view_activity(inputs: MaterializeViewInputs) -> Materializ
except FileNotFoundError:
await logger.adebug(f"Skipping deletion because table not found: uri={table_uri}")
- hogql_query = typing.cast(dict, saved_query.query)["query"]
+ hogql_query = typing.cast(dict, objects.saved_query.query)["query"]
row_count = 0
storage_options = _get_aws_storage_options()
@@ -511,7 +519,7 @@ async def materialize_view_activity(inputs: MaterializeViewInputs) -> Materializ
# batch (hogql_table yields ~100MB combined batches) and, because each write is a
# brief to_thread released between batches, never pins a worker thread for the whole
# read — which is what starved the shared executor that heartbeats/db/logging use.
- async for batch, ch_types in hogql_table(hogql_query, team, logger):
+ async for batch, ch_types in hogql_table(hogql_query, objects.team, logger):
batch = _transform_unsupported_decimals(batch)
batch = _transform_date_and_datetimes(batch, ch_types)
batch = _force_nullable(batch)
@@ -536,8 +544,8 @@ async def materialize_view_activity(inputs: MaterializeViewInputs) -> Materializ
storage_options=storage_options,
)
row_count = row_count + batch.num_rows
- job.rows_materialized = row_count
- await database_sync_to_async_pool(job.save)()
+ objects.job.rows_materialized = row_count
+ await database_sync_to_async_pool(objects.job.save)()
await logger.ainfo(f"Finished writing to delta table. row_count={row_count}")
file_uris = []
@@ -557,12 +565,12 @@ async def materialize_view_activity(inputs: MaterializeViewInputs) -> Materializ
# queryable folder has a file with a schema attached that's queryable
empty_parquet_uri = await _write_empty_parquet_for_zero_rows(table_uri, pa_schema, logger)
file_uris = [empty_parquet_uri]
- await logger.ainfo(f"Materialized node {node.name} with {row_count} rows")
+ await logger.ainfo(f"Materialized node {objects.node.name} with {row_count} rows")
return MaterializeViewResult(
- node_id=node.id,
- node_name=node.name,
+ node_id=objects.node.id,
+ node_name=objects.node.name,
row_count=row_count,
table_uri=table_uri,
file_uris=file_uris,
- saved_query_id=str(saved_query.id),
+ saved_query_id=str(objects.saved_query.id),
)
diff --git a/posthog/temporal/data_modeling/activities/preempt_dag_run.py b/posthog/temporal/data_modeling/activities/preempt_dag_run.py
index a177c70028d9..f6c6e4dafbe7 100644
--- a/posthog/temporal/data_modeling/activities/preempt_dag_run.py
+++ b/posthog/temporal/data_modeling/activities/preempt_dag_run.py
@@ -52,9 +52,13 @@ def _get_running_jobs_for_dag(team_id: int, dag_id: str) -> list[DataModelingJob
)
-def partition_running_jobs(
- jobs: list[DataModelingJob], dag_id: str, node_ids: list[str] | None
-) -> tuple[list[DataModelingJob], list[DataModelingJob]]:
[email protected](frozen=True, kw_only=True, slots=True)
+class PartitionedJobs:
+ owned: list[DataModelingJob]
+ others: list[DataModelingJob]
+
+
+def partition_running_jobs(jobs: list[DataModelingJob], dag_id: str, node_ids: list[str] | None) -> PartitionedJobs:
"""Split this DAG's running jobs into the nodes this run owns and everything else.
Cadence tiers of one DAG hold disjoint node sets, so only the owned half may be preempted —
@@ -73,7 +77,7 @@ def partition_running_jobs(
ours.append(job)
else:
others.append(job)
- return ours, others
+ return PartitionedJobs(owned=ours, others=others)
async def _abandoned_jobs(temporal: Client, candidates: list[DataModelingJob]) -> list[DataModelingJob]:
@@ -134,8 +138,8 @@ async def preempt_dag_run_activity(inputs: PreemptDAGRunInputs) -> None:
logger = LOGGER.bind()
running_jobs = await _get_running_jobs_for_dag(inputs.team_id, inputs.dag_id)
- ours, others = partition_running_jobs(running_jobs, inputs.dag_id, inputs.node_ids)
- if not ours and not others:
+ partitioned = partition_running_jobs(running_jobs, inputs.dag_id, inputs.node_ids)
+ if not partitioned.owned and not partitioned.others:
await logger.adebug("No previous DAG run to preempt")
return
@@ -155,27 +159,27 @@ async def preempt_dag_run_activity(inputs: PreemptDAGRunInputs) -> None:
# the new run free to materialize the same node concurrently. Cancelling first also means a
# crash between the two steps is recoverable: the rows are still Running, so the retry
# re-finds them and cancellation is idempotent.
- if ours:
+ if partitioned.owned:
await logger.ainfo(
- f"Preempting previous DAG run: found {len(ours)} running jobs",
+ f"Preempting previous DAG run: found {len(partitioned.owned)} running jobs",
dag_id=inputs.dag_id,
)
- for workflow_id in {job.workflow_id for job in ours if job.workflow_id}:
+ for workflow_id in {job.workflow_id for job in partitioned.owned if job.workflow_id}:
try:
await temporal.get_workflow_handle(workflow_id).cancel()
await logger.ainfo(f"Requested cancellation of materialize workflow {workflow_id}")
except Exception as e:
# workflow may have already completed — that's fine
await logger.awarning(f"Could not cancel materialize workflow {workflow_id}: {str(e)}")
- updated_count = await _mark_jobs_failed([str(job.id) for job in ours], PREEMPTED_ERROR)
+ updated_count = await _mark_jobs_failed([str(job.id) for job in partitioned.owned], PREEMPTED_ERROR)
await logger.ainfo(f"Marked {updated_count} jobs as preempted", dag_id=inputs.dag_id)
- if not others:
+ if not partitioned.others:
return
# Best-effort cleanup: it must never undo or block the preemption above.
try:
- abandoned = await _abandoned_jobs(temporal, others)
+ abandoned = await _abandoned_jobs(temporal, partitioned.others)
if abandoned:
reaped = await _mark_jobs_failed([str(job.id) for job in abandoned], ABANDONED_ERROR)
await logger.ainfo(f"Reaped {reaped} abandoned jobs", dag_id=inputs.dag_id)
diff --git a/posthog/temporal/data_modeling/activities/succeed_materialization.py b/posthog/temporal/data_modeling/activities/succeed_materialization.py
index 87cad6108074..d61fe870f4bf 100644
--- a/posthog/temporal/data_modeling/activities/succeed_materialization.py
+++ b/posthog/temporal/data_modeling/activities/succeed_materialization.py
@@ -72,10 +72,18 @@ def _view_enrichment_needed(node: Node | None) -> tuple[bool, str | None]:
return False, str(node.saved_query_id)
[email protected](frozen=True, kw_only=True, slots=True)
+class SucceedNodeAndJobOutcome:
+ node: Node | None
+ job: DataModelingJob
+ enrichment_needed: bool
+ enrichment_saved_query_id: str | None
+
+
@database_sync_to_async_pool
def _succeed_node_and_data_modeling_job(
inputs: SucceedMaterializationInputs,
-) -> tuple[Node | None, DataModelingJob, bool, str | None]:
+) -> SucceedNodeAndJobOutcome:
node: Node | None = None
if inputs.update_node:
with transaction.atomic():
@@ -102,7 +110,12 @@ def _succeed_node_and_data_modeling_job(
# if the job is already in a terminal state, don't overwrite it
if job.status in (DataModelingJobStatus.FAILED, DataModelingJobStatus.CANCELLED, DataModelingJobStatus.COMPLETED):
- return node, job, enrichment_needed, enrichment_saved_query_id
+ return SucceedNodeAndJobOutcome(
+ node=node,
+ job=job,
+ enrichment_needed=enrichment_needed,
+ enrichment_saved_query_id=enrichment_saved_query_id,
+ )
job.status = DataModelingJobStatus.COMPLETED
job.rows_materialized = inputs.row_count
@@ -114,7 +127,12 @@ def _succeed_node_and_data_modeling_job(
saved_query_id = str(node.saved_query_id)
team_id = inputs.team_id
transaction.on_commit(lambda: _enqueue_custom_property_sync(team_id, saved_query_id))
- return node, job, enrichment_needed, enrichment_saved_query_id
+ return SucceedNodeAndJobOutcome(
+ node=node,
+ job=job,
+ enrichment_needed=enrichment_needed,
+ enrichment_saved_query_id=enrichment_saved_query_id,
+ )
def _enqueue_custom_property_sync(team_id: int, saved_query_id: str) -> None:
@@ -133,10 +151,12 @@ async def succeed_materialization_activity(inputs: SucceedMaterializationInputs)
bind_contextvars(team_id=inputs.team_id)
logger = LOGGER.bind()
- node, job, enrichment_needed, saved_query_id = await _succeed_node_and_data_modeling_job(inputs)
+ outcome = await _succeed_node_and_data_modeling_job(inputs)
await logger.ainfo(
- f"Succeeded materialization job: node={inputs.node_id} dag={inputs.dag_id} job={job.id} "
- f"workflow={job.workflow_id} workflow_run={job.workflow_run_id}"
+ f"Succeeded materialization job: node={inputs.node_id} dag={inputs.dag_id} job={outcome.job.id} "
+ f"workflow={outcome.job.workflow_id} workflow_run={outcome.job.workflow_run_id}"
+ )
+ return SucceedMaterializationResult(
+ enrichment_needed=outcome.enrichment_needed, saved_query_id=outcome.enrichment_saved_query_id
)
- return SucceedMaterializationResult(enrichment_needed=enrichment_needed, saved_query_id=saved_query_id)
diff --git a/products/data_modeling/backend/logic/freshness.py b/products/data_modeling/backend/logic/freshness.py
index a0128f196a80..9fcb6dddc4a9 100644
--- a/products/data_modeling/backend/logic/freshness.py
+++ b/products/data_modeling/backend/logic/freshness.py
@@ -98,14 +98,20 @@ def format_cadence(interval: timedelta) -> str:
return str(interval)
-def _adjacency(edges: list[tuple[str, str]]) -> tuple[dict[str, list[str]], dict[str, list[str]]]:
- """Return (children, parents) maps. Edges are (upstream, downstream)."""
[email protected](frozen=True, kw_only=True, slots=True)
+class Adjacency:
+ children: dict[str, list[str]] # upstream id -> downstream ids
+ parents: dict[str, list[str]] # downstream id -> upstream ids
+
+
+def _adjacency(edges: list[tuple[str, str]]) -> Adjacency:
+ """Return the children/parents maps. Edges are (upstream, downstream)."""
children: dict[str, list[str]] = defaultdict(list)
parents: dict[str, list[str]] = defaultdict(list)
for upstream, downstream in edges:
children[upstream].append(downstream)
parents[downstream].append(upstream)
- return children, parents
+ return Adjacency(children=children, parents=parents)
def compute_effective_cadences(
@@ -120,9 +126,9 @@ def compute_effective_cadences(
no declared target and no scheduled descendant demanding freshness (the
ride-downstream opt-out). Source nodes are not expected in `nodes`.
"""
- children, parents = _adjacency(edges)
+ adj = _adjacency(edges)
# reverse-topological pass, iterative because recursion overflows on deep chains
- out_degree = {node: sum(1 for child in children.get(node, []) if child in nodes) for node in nodes}
+ out_degree = {node: sum(1 for child in adj.children.get(node, []) if child in nodes) for node in nodes}
queue = deque(node for node in nodes if out_degree[node] == 0)
resolved: dict[str, timedelta | None] = {}
while queue:
@@ -130,12 +136,12 @@ def compute_effective_cadences(
candidates: list[timedelta] = []
if node in declared_targets:
candidates.append(declared_targets[node])
- for child in children.get(node, []):
+ for child in adj.children.get(node, []):
if child in nodes and (child_effective := resolved[child]) is not None:
candidates.append(child_effective)
# min = the finest demand wins (smaller timedelta = fresher)
resolved[node] = min(candidates) if candidates else None
- for parent in parents.get(node, []):
+ for parent in adj.parents.get(node, []):
if parent in nodes:
out_degree[parent] -= 1
if out_degree[parent] == 0:
@@ -158,9 +164,9 @@ def all_source_floors(edges: list[tuple[str, str]], source_intervals: dict[str,
than O(N^2). STREAMING for a derived node with no parents. Nodes in a cycle are omitted
(callers default them to STREAMING; the scheduling path rejects cycles upstream).
"""
- children, parents = _adjacency(edges)
+ adj = _adjacency(edges)
all_ids = set(source_intervals) | {node for edge in edges for node in edge}
- in_degree = {node: len(parents.get(node, [])) for node in all_ids}
+ in_degree = {node: len(adj.parents.get(node, [])) for node in all_ids}
queue = deque(node for node in all_ids if in_degree[node] == 0)
floor: dict[str, timedelta] = {}
while queue:
@@ -168,8 +174,8 @@ def all_source_floors(edges: list[tuple[str, str]], source_intervals: dict[str,
if node in source_intervals:
floor[node] = source_intervals[node]
else:
- floor[node] = min((floor[parent] for parent in parents.get(node, [])), default=STREAMING)
- for child in children.get(node, []):
+ floor[node] = min((floor[parent] for parent in adj.parents.get(node, [])), default=STREAMING)
+ for child in adj.children.get(node, []):
in_degree[child] -= 1
if in_degree[child] == 0:
queue.append(child)
@@ -181,17 +187,17 @@ def all_consumer_ceilings(
) -> dict[str, timedelta | None]:
"""Every node's consumer ceiling (finest declared target among strict descendants) in one
reverse pass. None when no descendant declares a target. Cyclic nodes are omitted."""
- children, parents = _adjacency(edges)
+ adj = _adjacency(edges)
all_ids = set(declared_targets) | {node for edge in edges for node in edge}
- out_degree = {node: len(children.get(node, [])) for node in all_ids}
+ out_degree = {node: len(adj.children.get(node, [])) for node in all_ids}
queue = deque(node for node in all_ids if out_degree[node] == 0)
ceiling: dict[str, timedelta | None] = {}
while queue:
node = queue.popleft()
- candidates = [declared_targets[child] for child in children.get(node, []) if child in declared_targets]
- candidates += [c for child in children.get(node, []) if (c := ceiling.get(child)) is not None]
+ candidates = [declared_targets[child] for child in adj.children.get(node, []) if child in declared_targets]
+ candidates += [c for child in adj.children.get(node, []) if (c := ceiling.get(child)) is not None]
ceiling[node] = min(candidates) if candidates else None
- for parent in parents.get(node, []):
+ for parent in adj.parents.get(node, []):
out_degree[parent] -= 1
if out_degree[parent] == 0:
queue.append(parent)