factcat 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- factcat-0.1.0/.gitignore +12 -0
- factcat-0.1.0/PKG-INFO +52 -0
- factcat-0.1.0/README.md +32 -0
- factcat-0.1.0/factcat/__init__.py +34 -0
- factcat-0.1.0/factcat/_emit.py +61 -0
- factcat-0.1.0/factcat/dialects.py +68 -0
- factcat-0.1.0/factcat/funnel.py +103 -0
- factcat-0.1.0/factcat/retention.py +109 -0
- factcat-0.1.0/factcat/spec.py +102 -0
- factcat-0.1.0/pyproject.toml +35 -0
- factcat-0.1.0/tests/__init__.py +0 -0
- factcat-0.1.0/tests/conftest.py +48 -0
- factcat-0.1.0/tests/test_dialects.py +105 -0
- factcat-0.1.0/tests/test_funnel.py +113 -0
- factcat-0.1.0/tests/test_retention_nutrafol.py +85 -0
factcat-0.1.0/.gitignore
ADDED
factcat-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: factcat
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Product analytics on the event model already in your warehouse
|
|
5
|
+
Project-URL: Homepage, https://github.com/gordonkjlee/factcat
|
|
6
|
+
Project-URL: Source, https://github.com/gordonkjlee/factcat
|
|
7
|
+
Author: Gordon Lee
|
|
8
|
+
License: MIT
|
|
9
|
+
Keywords: analytics,dbt,funnel,retention,sql,warehouse
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Topic :: Database
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Requires-Dist: sqlglot>=25.0.0
|
|
16
|
+
Provides-Extra: dev
|
|
17
|
+
Requires-Dist: duckdb>=1.0.0; extra == 'dev'
|
|
18
|
+
Requires-Dist: pytest>=8.0.0; extra == 'dev'
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# factcat
|
|
22
|
+
|
|
23
|
+
Product analytics on the event model already in your warehouse. Your grain, your periods,
|
|
24
|
+
your definitions.
|
|
25
|
+
|
|
26
|
+
Every other product analytics tool hard-codes `entity = user`, `period = a calendar bucket`,
|
|
27
|
+
and `retained = did any event`. Real definitions violate all three:
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
from factcat import RetentionSpec, retention_sql
|
|
31
|
+
|
|
32
|
+
spec = RetentionSpec(
|
|
33
|
+
table="analytics.fct_subscription_payments",
|
|
34
|
+
entity="subscription_id", # not the user
|
|
35
|
+
entity_time="sub_start",
|
|
36
|
+
event_time="paid_at",
|
|
37
|
+
period_days=35, # a billing cycle plus dunning, not a calendar bucket
|
|
38
|
+
n_periods=12,
|
|
39
|
+
retained="status = 'collected' AND within_period_offset <= 5",
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
print(retention_sql(spec, dialect="snowflake"))
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
`retained` is arbitrary SQL over any column in your table, plus the derived columns
|
|
46
|
+
`offset_days`, `period_index` and `within_period_offset`.
|
|
47
|
+
|
|
48
|
+
Generates SQL and queries in place. No SDK, no ingestion, no copy of your data. Supports
|
|
49
|
+
DuckDB, Postgres, BigQuery, Snowflake, Databricks, Spark, Trino, Presto, ClickHouse and
|
|
50
|
+
Redshift.
|
|
51
|
+
|
|
52
|
+
Full documentation: https://github.com/gordonkjlee/factcat
|
factcat-0.1.0/README.md
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# factcat
|
|
2
|
+
|
|
3
|
+
Product analytics on the event model already in your warehouse. Your grain, your periods,
|
|
4
|
+
your definitions.
|
|
5
|
+
|
|
6
|
+
Every other product analytics tool hard-codes `entity = user`, `period = a calendar bucket`,
|
|
7
|
+
and `retained = did any event`. Real definitions violate all three:
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
from factcat import RetentionSpec, retention_sql
|
|
11
|
+
|
|
12
|
+
spec = RetentionSpec(
|
|
13
|
+
table="analytics.fct_subscription_payments",
|
|
14
|
+
entity="subscription_id", # not the user
|
|
15
|
+
entity_time="sub_start",
|
|
16
|
+
event_time="paid_at",
|
|
17
|
+
period_days=35, # a billing cycle plus dunning, not a calendar bucket
|
|
18
|
+
n_periods=12,
|
|
19
|
+
retained="status = 'collected' AND within_period_offset <= 5",
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
print(retention_sql(spec, dialect="snowflake"))
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
`retained` is arbitrary SQL over any column in your table, plus the derived columns
|
|
26
|
+
`offset_days`, `period_index` and `within_period_offset`.
|
|
27
|
+
|
|
28
|
+
Generates SQL and queries in place. No SDK, no ingestion, no copy of your data. Supports
|
|
29
|
+
DuckDB, Postgres, BigQuery, Snowflake, Databricks, Spark, Trino, Presto, ClickHouse and
|
|
30
|
+
Redshift.
|
|
31
|
+
|
|
32
|
+
Full documentation: https://github.com/gordonkjlee/factcat
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Factcat - product analytics on the event model already in your warehouse.
|
|
2
|
+
|
|
3
|
+
A **fact** table is what you build; **cat** is how you read a file. Factcat
|
|
4
|
+
reads your fact tables where they sit, and never copies them anywhere.
|
|
5
|
+
|
|
6
|
+
from factcat import RetentionSpec, retention_sql
|
|
7
|
+
|
|
8
|
+
spec = RetentionSpec(
|
|
9
|
+
table="payments",
|
|
10
|
+
entity="subscription_id", # not the user
|
|
11
|
+
entity_time="sub_start",
|
|
12
|
+
event_time="paid_at",
|
|
13
|
+
period_days=35, # not a calendar bucket
|
|
14
|
+
n_periods=2,
|
|
15
|
+
retained="status = 'collected' AND within_period_offset <= 5",
|
|
16
|
+
)
|
|
17
|
+
print(retention_sql(spec, dialect="snowflake"))
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
from .dialects import SUPPORTED, period_grid
|
|
23
|
+
from .funnel import build_sql as funnel_sql
|
|
24
|
+
from .retention import build_sql as retention_sql
|
|
25
|
+
from .spec import FunnelSpec, RetentionSpec
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"FunnelSpec",
|
|
29
|
+
"RetentionSpec",
|
|
30
|
+
"SUPPORTED",
|
|
31
|
+
"funnel_sql",
|
|
32
|
+
"period_grid",
|
|
33
|
+
"retention_sql",
|
|
34
|
+
]
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Shared SQL emission helpers.
|
|
2
|
+
|
|
3
|
+
The strategy: build one query in DuckDB dialect, transpile it with sqlglot, and
|
|
4
|
+
splice in the one construct that does not transpile (the integer series). See
|
|
5
|
+
``dialects.py`` for why that construct is the only per-warehouse code here.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import sqlglot
|
|
11
|
+
|
|
12
|
+
from .dialects import period_grid
|
|
13
|
+
|
|
14
|
+
# The relation name the retention query joins against for its period grid. It is
|
|
15
|
+
# never defined as a CTE in the pre-transpile SQL - sqlglot simply renders it as
|
|
16
|
+
# an identifier - and the real CTE is prepended afterwards.
|
|
17
|
+
GRID_RELATION = "factcat_period_grid"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def day_diff(start: str, end: str) -> str:
|
|
21
|
+
"""Whole days between two instants, in DuckDB dialect for later transpilation."""
|
|
22
|
+
return f"date_diff('day', {start}, {end})"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def floor_div(numerator: str, divisor: int) -> str:
|
|
26
|
+
"""Integer division spelled portably.
|
|
27
|
+
|
|
28
|
+
DuckDB's ``/`` is float division, and a float period index will not join
|
|
29
|
+
against the integer period grid. ``//`` does not transpile cleanly, so this
|
|
30
|
+
goes through FLOOR and an explicit cast.
|
|
31
|
+
"""
|
|
32
|
+
return f"CAST(FLOOR(({numerator}) * 1.0 / {divisor}) AS BIGINT)"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def transpile(sql: str, dialect: str) -> str:
|
|
36
|
+
"""Transpile DuckDB-dialect SQL to ``dialect``."""
|
|
37
|
+
if dialect == "duckdb":
|
|
38
|
+
return sql
|
|
39
|
+
return sqlglot.transpile(sql, read="duckdb", write=dialect, pretty=True)[0]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def transpile_with_grid(sql: str, dialect: str, n_periods: int) -> str:
|
|
43
|
+
"""Transpile ``sql`` and prepend the dialect-native period grid as a CTE.
|
|
44
|
+
|
|
45
|
+
``sql`` must reference :data:`GRID_RELATION` and must already begin with a
|
|
46
|
+
``WITH`` clause, which every query in this package does.
|
|
47
|
+
|
|
48
|
+
Raises:
|
|
49
|
+
RuntimeError: if the transpiled SQL does not start with ``WITH``. That
|
|
50
|
+
would mean the grid CTE could not be attached, leaving a query that
|
|
51
|
+
references an undefined relation - a failure worth making loud
|
|
52
|
+
rather than emitting SQL that dies at the warehouse.
|
|
53
|
+
"""
|
|
54
|
+
out = transpile(sql, dialect).lstrip()
|
|
55
|
+
if not out.upper().startswith("WITH "):
|
|
56
|
+
raise RuntimeError(
|
|
57
|
+
"expected the transpiled query to open with a WITH clause so the "
|
|
58
|
+
f"period grid could be prepended, got: {out[:60]!r}"
|
|
59
|
+
)
|
|
60
|
+
grid = period_grid(n_periods, dialect)
|
|
61
|
+
return f"WITH {GRID_RELATION} AS (\n{grid}\n),\n{out[len('WITH '):]}"
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Per-dialect SQL that cannot be transpiled.
|
|
2
|
+
|
|
3
|
+
sqlglot handles almost everything: date arithmetic, casting, string functions,
|
|
4
|
+
window functions. Measured across the retention query, exactly one construct
|
|
5
|
+
does not survive transpilation cleanly - **generating a series of integers**.
|
|
6
|
+
|
|
7
|
+
duckdb UNNEST(GENERATE_SERIES(0, n))
|
|
8
|
+
snowflake renders as a double FLATTEN over ARRAY_GENERATE_RANGE
|
|
9
|
+
redshift fails outright: "Unsupported EXPLODE() function"
|
|
10
|
+
|
|
11
|
+
So the period grid is written by hand per dialect, and that is the entire
|
|
12
|
+
per-warehouse surface area of this engine. Everything else is one emitter.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
SUPPORTED: tuple[str, ...] = (
|
|
18
|
+
"duckdb",
|
|
19
|
+
"postgres",
|
|
20
|
+
"bigquery",
|
|
21
|
+
"snowflake",
|
|
22
|
+
"databricks",
|
|
23
|
+
"spark",
|
|
24
|
+
"trino",
|
|
25
|
+
"presto",
|
|
26
|
+
"clickhouse",
|
|
27
|
+
"redshift",
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _union_all_grid(n: int) -> str:
|
|
32
|
+
"""The universal fallback: an explicit union of integers.
|
|
33
|
+
|
|
34
|
+
Verbose, but valid in every SQL dialect ever written. Used for Redshift,
|
|
35
|
+
which has no row generator reachable without a system table.
|
|
36
|
+
"""
|
|
37
|
+
return " UNION ALL ".join(f"SELECT {i} AS period_index" for i in range(n + 1))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def period_grid(n_periods: int, dialect: str) -> str:
|
|
41
|
+
"""SQL returning one row per period index, 0..n_periods inclusive.
|
|
42
|
+
|
|
43
|
+
The result must expose a single column named ``period_index``.
|
|
44
|
+
"""
|
|
45
|
+
if n_periods < 0:
|
|
46
|
+
raise ValueError("n_periods must be >= 0")
|
|
47
|
+
n = n_periods
|
|
48
|
+
|
|
49
|
+
if dialect == "duckdb":
|
|
50
|
+
return f"SELECT UNNEST(GENERATE_SERIES(0, {n})) AS period_index"
|
|
51
|
+
if dialect == "postgres":
|
|
52
|
+
return f"SELECT GENERATE_SERIES(0, {n}) AS period_index"
|
|
53
|
+
if dialect == "bigquery":
|
|
54
|
+
return f"SELECT period_index FROM UNNEST(GENERATE_ARRAY(0, {n})) AS period_index"
|
|
55
|
+
if dialect == "snowflake":
|
|
56
|
+
return (
|
|
57
|
+
"SELECT SEQ4() AS period_index "
|
|
58
|
+
f"FROM TABLE(GENERATOR(ROWCOUNT => {n + 1}))"
|
|
59
|
+
)
|
|
60
|
+
if dialect in ("databricks", "spark"):
|
|
61
|
+
return f"SELECT EXPLODE(SEQUENCE(0, {n})) AS period_index"
|
|
62
|
+
if dialect in ("trino", "presto"):
|
|
63
|
+
return f"SELECT period_index FROM UNNEST(SEQUENCE(0, {n})) AS t(period_index)"
|
|
64
|
+
if dialect == "clickhouse":
|
|
65
|
+
return f"SELECT arrayJoin(range(0, {n + 1})) AS period_index"
|
|
66
|
+
|
|
67
|
+
# Redshift and anything unrecognised. Correct everywhere, ugly above ~200.
|
|
68
|
+
return _union_all_grid(n)
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Ordered funnel SQL generation.
|
|
2
|
+
|
|
3
|
+
Same principle as retention: the entity is a parameter, the step predicates are
|
|
4
|
+
arbitrary SQL, and the completion window is measured from the first step rather
|
|
5
|
+
than from the previous one. Each step takes the **earliest** qualifying event at
|
|
6
|
+
or after the previous step, which is the semantics every funnel tool implements
|
|
7
|
+
and few document.
|
|
8
|
+
|
|
9
|
+
Internal join keys are prefixed ``fc_`` so a source column called ``entity_id``
|
|
10
|
+
cannot make the join ambiguous. Step predicates reference source columns
|
|
11
|
+
directly and unqualified, as the caller wrote them.
|
|
12
|
+
|
|
13
|
+
No period grid is needed here, so this transpiles straight through sqlglot.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from ._emit import day_diff, transpile
|
|
19
|
+
from .spec import FunnelSpec
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _quote(label: str) -> str:
|
|
23
|
+
"""Render a label as a SQL string literal."""
|
|
24
|
+
return "'" + label.replace("'", "''") + "'"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def build_sql(spec: FunnelSpec, dialect: str = "duckdb") -> str:
|
|
28
|
+
"""Render ``spec`` as SQL for ``dialect``.
|
|
29
|
+
|
|
30
|
+
The result has one row per step: index, label, entities reaching that step,
|
|
31
|
+
and the percentage of the first step's entities that got there.
|
|
32
|
+
"""
|
|
33
|
+
where = f"WHERE {spec.where}" if spec.where else ""
|
|
34
|
+
labels = spec.labels()
|
|
35
|
+
|
|
36
|
+
ctes: list[str] = [
|
|
37
|
+
f"""src AS (
|
|
38
|
+
SELECT * FROM {spec.table} {where}
|
|
39
|
+
)""",
|
|
40
|
+
f"""base AS (
|
|
41
|
+
SELECT
|
|
42
|
+
src.*,
|
|
43
|
+
{spec.entity} AS fc_entity,
|
|
44
|
+
{spec.event_time} AS fc_event_ts
|
|
45
|
+
FROM src
|
|
46
|
+
)""",
|
|
47
|
+
f"""step_0 AS (
|
|
48
|
+
SELECT
|
|
49
|
+
fc_entity AS fc_entity,
|
|
50
|
+
MIN(fc_event_ts) AS fc_reached_at,
|
|
51
|
+
MIN(fc_event_ts) AS fc_first_at
|
|
52
|
+
FROM base
|
|
53
|
+
WHERE ({spec.steps[0]})
|
|
54
|
+
GROUP BY 1
|
|
55
|
+
)""",
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
for i, predicate in enumerate(spec.steps[1:], start=1):
|
|
59
|
+
window = ""
|
|
60
|
+
if spec.within_days is not None:
|
|
61
|
+
elapsed = day_diff("p.fc_first_at", "b.fc_event_ts")
|
|
62
|
+
window = f"AND {elapsed} <= {spec.within_days}"
|
|
63
|
+
ctes.append(
|
|
64
|
+
f"""step_{i} AS (
|
|
65
|
+
SELECT
|
|
66
|
+
p.fc_entity,
|
|
67
|
+
MIN(b.fc_event_ts) AS fc_reached_at,
|
|
68
|
+
p.fc_first_at
|
|
69
|
+
FROM step_{i - 1} p
|
|
70
|
+
JOIN base b ON b.fc_entity = p.fc_entity
|
|
71
|
+
WHERE b.fc_event_ts >= p.fc_reached_at
|
|
72
|
+
AND ({predicate})
|
|
73
|
+
{window}
|
|
74
|
+
GROUP BY p.fc_entity, p.fc_first_at
|
|
75
|
+
)"""
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
counts = "\n UNION ALL\n ".join(
|
|
79
|
+
f"SELECT {i} AS step_index, {_quote(labels[i])} AS step_label, "
|
|
80
|
+
f"COUNT(*) AS entities FROM step_{i}"
|
|
81
|
+
for i in range(len(spec.steps))
|
|
82
|
+
)
|
|
83
|
+
ctes.append(
|
|
84
|
+
f"""counts AS (
|
|
85
|
+
{counts}
|
|
86
|
+
)"""
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
# Joined outside the f-string: a backslash in an f-string expression is only
|
|
90
|
+
# legal from Python 3.12 (PEP 701), and this package supports 3.10.
|
|
91
|
+
cte_sql = ",\n ".join(ctes)
|
|
92
|
+
sql = f"""
|
|
93
|
+
WITH {cte_sql}
|
|
94
|
+
SELECT
|
|
95
|
+
c.step_index,
|
|
96
|
+
c.step_label,
|
|
97
|
+
c.entities,
|
|
98
|
+
ROUND(100.0 * c.entities / NULLIF(t.total, 0), 2) AS pct_of_first
|
|
99
|
+
FROM counts c
|
|
100
|
+
CROSS JOIN (SELECT entities AS total FROM counts WHERE step_index = 0) t
|
|
101
|
+
ORDER BY 1
|
|
102
|
+
"""
|
|
103
|
+
return transpile(sql, dialect)
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Retention SQL generation.
|
|
2
|
+
|
|
3
|
+
Every product analytics tool, warehouse-native ones included, hard-codes three
|
|
4
|
+
things:
|
|
5
|
+
|
|
6
|
+
entity = user
|
|
7
|
+
period = a calendar bucket (day / week / month)
|
|
8
|
+
retained = did any event
|
|
9
|
+
|
|
10
|
+
Real retention definitions violate all three. This module fixes none of them in
|
|
11
|
+
place, so a definition like
|
|
12
|
+
|
|
13
|
+
"the subscription is retained in a 35-day billing period if payment is
|
|
14
|
+
collected within 5 days of the period opening"
|
|
15
|
+
|
|
16
|
+
is expressed directly rather than approximated.
|
|
17
|
+
|
|
18
|
+
Internal join keys are prefixed ``fc_`` so that a caller whose source table
|
|
19
|
+
happens to contain a column called ``entity_id`` or ``cohort`` does not collide
|
|
20
|
+
with the generated SQL. The three derived columns a predicate may reference -
|
|
21
|
+
``offset_days``, ``period_index`` and ``within_period_offset`` - are deliberately
|
|
22
|
+
unprefixed, because they are the public API of the ``retained`` expression.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
from ._emit import GRID_RELATION, day_diff, floor_div, transpile_with_grid
|
|
28
|
+
from .spec import RetentionSpec
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def build_sql(spec: RetentionSpec, dialect: str = "duckdb") -> str:
|
|
32
|
+
"""Render ``spec`` as SQL for ``dialect``.
|
|
33
|
+
|
|
34
|
+
The result has one row per (cohort, period_index) with the cohort size, the
|
|
35
|
+
number of retained entities, and the percentage.
|
|
36
|
+
"""
|
|
37
|
+
where = f"WHERE {spec.where}" if spec.where else ""
|
|
38
|
+
|
|
39
|
+
offset = day_diff("c.cohort_ts", "b.fc_event_ts")
|
|
40
|
+
period_index = floor_div(offset, spec.period_days)
|
|
41
|
+
within = f"{offset} - ({period_index}) * {spec.period_days}"
|
|
42
|
+
|
|
43
|
+
sql = f"""
|
|
44
|
+
WITH src AS (
|
|
45
|
+
SELECT * FROM {spec.table} {where}
|
|
46
|
+
),
|
|
47
|
+
base AS (
|
|
48
|
+
SELECT
|
|
49
|
+
src.*,
|
|
50
|
+
{spec.entity} AS fc_entity,
|
|
51
|
+
{spec.entity_time} AS fc_entity_ts,
|
|
52
|
+
{spec.event_time} AS fc_event_ts
|
|
53
|
+
FROM src
|
|
54
|
+
),
|
|
55
|
+
entities AS (
|
|
56
|
+
SELECT
|
|
57
|
+
fc_entity,
|
|
58
|
+
MIN(fc_entity_ts) AS cohort_ts
|
|
59
|
+
FROM base
|
|
60
|
+
GROUP BY 1
|
|
61
|
+
),
|
|
62
|
+
-- `cohort_ts` is exposed under that exact name because `spec.cohort_bucket`
|
|
63
|
+
-- is caller-supplied SQL that references it.
|
|
64
|
+
cohorts AS (
|
|
65
|
+
SELECT
|
|
66
|
+
fc_entity,
|
|
67
|
+
cohort_ts,
|
|
68
|
+
{spec.cohort_bucket} AS fc_cohort
|
|
69
|
+
FROM entities
|
|
70
|
+
),
|
|
71
|
+
observations AS (
|
|
72
|
+
SELECT
|
|
73
|
+
b.*,
|
|
74
|
+
c.fc_cohort,
|
|
75
|
+
{offset} AS offset_days,
|
|
76
|
+
{period_index} AS period_index,
|
|
77
|
+
{within} AS within_period_offset
|
|
78
|
+
FROM base b
|
|
79
|
+
JOIN cohorts c ON b.fc_entity = c.fc_entity
|
|
80
|
+
),
|
|
81
|
+
retained_periods AS (
|
|
82
|
+
SELECT DISTINCT fc_entity, period_index
|
|
83
|
+
FROM observations
|
|
84
|
+
WHERE period_index BETWEEN 0 AND {spec.n_periods}
|
|
85
|
+
AND ({spec.retained})
|
|
86
|
+
),
|
|
87
|
+
grid AS (
|
|
88
|
+
SELECT c.fc_cohort, c.fc_entity, p.period_index
|
|
89
|
+
FROM cohorts c
|
|
90
|
+
CROSS JOIN {GRID_RELATION} p
|
|
91
|
+
)
|
|
92
|
+
SELECT
|
|
93
|
+
g.fc_cohort AS cohort,
|
|
94
|
+
g.period_index,
|
|
95
|
+
COUNT(DISTINCT g.fc_entity) AS cohort_size,
|
|
96
|
+
COUNT(DISTINCT r.fc_entity) AS retained_entities,
|
|
97
|
+
ROUND(
|
|
98
|
+
100.0 * COUNT(DISTINCT r.fc_entity)
|
|
99
|
+
/ NULLIF(COUNT(DISTINCT g.fc_entity), 0),
|
|
100
|
+
2
|
|
101
|
+
) AS retention_pct
|
|
102
|
+
FROM grid g
|
|
103
|
+
LEFT JOIN retained_periods r
|
|
104
|
+
ON r.fc_entity = g.fc_entity
|
|
105
|
+
AND r.period_index = g.period_index
|
|
106
|
+
GROUP BY 1, 2
|
|
107
|
+
ORDER BY 1, 2
|
|
108
|
+
"""
|
|
109
|
+
return transpile_with_grid(sql, dialect, spec.n_periods)
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Analysis definitions.
|
|
2
|
+
|
|
3
|
+
Every field that other product analytics tools hard-code is a parameter here.
|
|
4
|
+
That is the whole point of the library, so the dataclasses are the design
|
|
5
|
+
document as much as the code is.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class RetentionSpec:
|
|
15
|
+
"""A retention definition.
|
|
16
|
+
|
|
17
|
+
Attributes:
|
|
18
|
+
table: source relation. Typically a dbt mart, not a raw event stream.
|
|
19
|
+
entity: the grain retention is measured at. **Not** assumed to be the
|
|
20
|
+
user: a subscription, a household, a device, a seat or an
|
|
21
|
+
account are all valid, and they give different answers on the
|
|
22
|
+
same data.
|
|
23
|
+
entity_time: expression giving the entity's cohort entry instant.
|
|
24
|
+
event_time: expression giving the instant of an observation.
|
|
25
|
+
period_days: period length in days. Arbitrary. 35 is a 30-day billing cycle
|
|
26
|
+
plus a 5-day dunning window, and no calendar bucket expresses it.
|
|
27
|
+
n_periods: how many periods to project.
|
|
28
|
+
retained: arbitrary SQL boolean deciding whether a row counts as retention
|
|
29
|
+
for its period. May reference any source column plus the derived
|
|
30
|
+
columns below.
|
|
31
|
+
cohort_bucket: expression bucketing entities into cohorts.
|
|
32
|
+
where: optional filter applied to the source relation.
|
|
33
|
+
|
|
34
|
+
Derived columns available to ``retained``:
|
|
35
|
+
``offset_days``
|
|
36
|
+
whole days from the entity's cohort entry.
|
|
37
|
+
``period_index``
|
|
38
|
+
which period the observation falls in, counting from zero.
|
|
39
|
+
``within_period_offset``
|
|
40
|
+
whole days since this period opened. A 5-day dunning window is
|
|
41
|
+
``within_period_offset <= 5``.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
table: str
|
|
45
|
+
entity: str
|
|
46
|
+
entity_time: str
|
|
47
|
+
event_time: str
|
|
48
|
+
period_days: int
|
|
49
|
+
n_periods: int
|
|
50
|
+
retained: str
|
|
51
|
+
cohort_bucket: str = "date_trunc('month', cohort_ts)"
|
|
52
|
+
where: str | None = None
|
|
53
|
+
|
|
54
|
+
def __post_init__(self) -> None:
|
|
55
|
+
if self.period_days < 1:
|
|
56
|
+
raise ValueError("period_days must be >= 1")
|
|
57
|
+
if self.n_periods < 1:
|
|
58
|
+
raise ValueError("n_periods must be >= 1")
|
|
59
|
+
if not self.retained.strip():
|
|
60
|
+
raise ValueError("retained must be a SQL boolean expression")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(frozen=True)
|
|
64
|
+
class FunnelSpec:
|
|
65
|
+
"""An ordered funnel definition.
|
|
66
|
+
|
|
67
|
+
Steps are matched in order and each step must occur at or after the previous
|
|
68
|
+
one, taking the **earliest** qualifying event at every stage. As with
|
|
69
|
+
retention, the entity is yours to choose - a funnel over subscriptions and a
|
|
70
|
+
funnel over users are different questions about the same table.
|
|
71
|
+
|
|
72
|
+
Attributes:
|
|
73
|
+
table: source relation.
|
|
74
|
+
entity: the grain the funnel is counted at.
|
|
75
|
+
event_time: expression giving the instant of an observation.
|
|
76
|
+
steps: ordered SQL boolean expressions, one per step. At least two.
|
|
77
|
+
step_labels: optional display labels, defaulting to ``step_0``, ``step_1``...
|
|
78
|
+
within_days: optional completion window, measured from the first step. None
|
|
79
|
+
means unbounded.
|
|
80
|
+
where: optional filter applied to the source relation.
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
table: str
|
|
84
|
+
entity: str
|
|
85
|
+
event_time: str
|
|
86
|
+
steps: tuple[str, ...]
|
|
87
|
+
step_labels: tuple[str, ...] | None = None
|
|
88
|
+
within_days: int | None = None
|
|
89
|
+
where: str | None = None
|
|
90
|
+
|
|
91
|
+
def __post_init__(self) -> None:
|
|
92
|
+
if len(self.steps) < 2:
|
|
93
|
+
raise ValueError("a funnel needs at least two steps")
|
|
94
|
+
if self.step_labels is not None and len(self.step_labels) != len(self.steps):
|
|
95
|
+
raise ValueError("step_labels must match steps in length")
|
|
96
|
+
if self.within_days is not None and self.within_days < 0:
|
|
97
|
+
raise ValueError("within_days must be >= 0")
|
|
98
|
+
|
|
99
|
+
def labels(self) -> tuple[str, ...]:
|
|
100
|
+
if self.step_labels is not None:
|
|
101
|
+
return self.step_labels
|
|
102
|
+
return tuple(f"step_{i}" for i in range(len(self.steps)))
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "factcat"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Product analytics on the event model already in your warehouse"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "Gordon Lee" }]
|
|
13
|
+
keywords = ["analytics", "retention", "funnel", "warehouse", "sql", "dbt"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"License :: OSI Approved :: MIT License",
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Topic :: Database",
|
|
18
|
+
"Topic :: Scientific/Engineering :: Information Analysis",
|
|
19
|
+
]
|
|
20
|
+
dependencies = ["sqlglot>=25.0.0"]
|
|
21
|
+
|
|
22
|
+
[project.optional-dependencies]
|
|
23
|
+
# DuckDB is the reference dialect and the engine the test suite executes against.
|
|
24
|
+
dev = ["duckdb>=1.0.0", "pytest>=8.0.0"]
|
|
25
|
+
|
|
26
|
+
[project.urls]
|
|
27
|
+
Homepage = "https://github.com/gordonkjlee/factcat"
|
|
28
|
+
Source = "https://github.com/gordonkjlee/factcat"
|
|
29
|
+
|
|
30
|
+
[tool.hatch.build.targets.wheel]
|
|
31
|
+
packages = ["factcat"]
|
|
32
|
+
|
|
33
|
+
[tool.pytest.ini_options]
|
|
34
|
+
testpaths = ["tests"]
|
|
35
|
+
addopts = "-q"
|
|
File without changes
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Shared fixtures.
|
|
2
|
+
|
|
3
|
+
The payments table is the fixture for the whole suite because it is the shape
|
|
4
|
+
the library exists for: a subscription business whose retention definition no
|
|
5
|
+
product analytics tool can express.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import duckdb
|
|
11
|
+
import pytest
|
|
12
|
+
|
|
13
|
+
# subscription_id, user_id, sub_start, paid_at, status
|
|
14
|
+
PAYMENTS = [
|
|
15
|
+
# S1 pays on time in every period.
|
|
16
|
+
("S1", "U1", "2026-01-01", "2026-01-01", "collected"),
|
|
17
|
+
("S1", "U1", "2026-01-01", "2026-02-05", "collected"), # day 35, offset 0
|
|
18
|
+
("S1", "U1", "2026-01-01", "2026-03-12", "collected"), # day 70, offset 0
|
|
19
|
+
# S2 pays period 1 three days late - INSIDE the 5-day dunning window.
|
|
20
|
+
("S2", "U1", "2026-01-01", "2026-01-01", "collected"),
|
|
21
|
+
("S2", "U1", "2026-01-01", "2026-02-08", "collected"), # day 38, offset 3
|
|
22
|
+
# S3 pays period 1 six days late - OUTSIDE the window. Churned.
|
|
23
|
+
("S3", "U2", "2026-01-15", "2026-01-15", "collected"),
|
|
24
|
+
("S3", "U2", "2026-01-15", "2026-02-25", "collected"), # day 41, offset 6
|
|
25
|
+
# S4 is the February cohort, with one collected payment.
|
|
26
|
+
("S4", "U3", "2026-02-01", "2026-02-01", "collected"),
|
|
27
|
+
# A failed payment must never count as retention.
|
|
28
|
+
("S4", "U3", "2026-02-01", "2026-03-08", "failed"), # day 35, offset 0
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
DUNNING_DAYS = 5
|
|
32
|
+
RETAINED = f"status = 'collected' AND within_period_offset <= {DUNNING_DAYS}"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@pytest.fixture()
|
|
36
|
+
def con() -> duckdb.DuckDBPyConnection:
|
|
37
|
+
connection = duckdb.connect()
|
|
38
|
+
connection.execute(
|
|
39
|
+
"CREATE TABLE payments ("
|
|
40
|
+
" subscription_id VARCHAR,"
|
|
41
|
+
" user_id VARCHAR,"
|
|
42
|
+
" sub_start DATE,"
|
|
43
|
+
" paid_at DATE,"
|
|
44
|
+
" status VARCHAR"
|
|
45
|
+
")"
|
|
46
|
+
)
|
|
47
|
+
connection.executemany("INSERT INTO payments VALUES (?, ?, ?, ?, ?)", PAYMENTS)
|
|
48
|
+
return connection
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Cross-dialect emission.
|
|
2
|
+
|
|
3
|
+
The prototype these tests came from failed exactly one dialect - Redshift, with
|
|
4
|
+
``Unsupported EXPLODE() function`` - because the period grid used DuckDB's
|
|
5
|
+
``GENERATE_SERIES``. sqlglot logs that as a warning rather than raising, so the
|
|
6
|
+
broken SQL was emitted silently. These tests turn that warning into a failure.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
|
|
13
|
+
import pytest
|
|
14
|
+
|
|
15
|
+
from factcat import SUPPORTED, FunnelSpec, RetentionSpec, funnel_sql, retention_sql
|
|
16
|
+
from factcat._emit import GRID_RELATION, transpile_with_grid
|
|
17
|
+
|
|
18
|
+
RETENTION = RetentionSpec(
|
|
19
|
+
table="payments",
|
|
20
|
+
entity="subscription_id",
|
|
21
|
+
entity_time="sub_start",
|
|
22
|
+
event_time="paid_at",
|
|
23
|
+
period_days=35,
|
|
24
|
+
n_periods=2,
|
|
25
|
+
retained="status = 'collected' AND within_period_offset <= 5",
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
FUNNEL = FunnelSpec(
|
|
29
|
+
table="events",
|
|
30
|
+
entity="entity_id",
|
|
31
|
+
event_time="occurred_at",
|
|
32
|
+
steps=("event_name = 'view'", "event_name = 'cart'"),
|
|
33
|
+
within_days=7,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class _Capture(logging.Handler):
|
|
38
|
+
def __init__(self) -> None:
|
|
39
|
+
super().__init__()
|
|
40
|
+
self.messages: list[str] = []
|
|
41
|
+
|
|
42
|
+
def emit(self, record: logging.LogRecord) -> None:
|
|
43
|
+
self.messages.append(record.getMessage())
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@pytest.fixture()
|
|
47
|
+
def sqlglot_warnings():
|
|
48
|
+
logger = logging.getLogger("sqlglot")
|
|
49
|
+
handler = _Capture()
|
|
50
|
+
logger.addHandler(handler)
|
|
51
|
+
yield handler
|
|
52
|
+
logger.removeHandler(handler)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@pytest.mark.parametrize("dialect", SUPPORTED)
|
|
56
|
+
def test_retention_emits_without_warnings(dialect, sqlglot_warnings):
|
|
57
|
+
sql = retention_sql(RETENTION, dialect=dialect)
|
|
58
|
+
|
|
59
|
+
assert sqlglot_warnings.messages == [], (
|
|
60
|
+
f"sqlglot warned while emitting for {dialect}: {sqlglot_warnings.messages}"
|
|
61
|
+
)
|
|
62
|
+
assert GRID_RELATION in sql, "the period grid CTE was not attached"
|
|
63
|
+
assert "GENERATE_SERIES" not in sql.upper() or dialect in ("duckdb", "postgres")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@pytest.mark.parametrize("dialect", SUPPORTED)
|
|
67
|
+
def test_funnel_emits_without_warnings(dialect, sqlglot_warnings):
|
|
68
|
+
funnel_sql(FUNNEL, dialect=dialect)
|
|
69
|
+
|
|
70
|
+
assert sqlglot_warnings.messages == [], (
|
|
71
|
+
f"sqlglot warned while emitting for {dialect}: {sqlglot_warnings.messages}"
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@pytest.mark.parametrize("dialect", SUPPORTED)
|
|
76
|
+
def test_grid_defines_the_relation_the_query_joins(dialect):
|
|
77
|
+
"""The grid CTE must be named exactly what the query references."""
|
|
78
|
+
sql = retention_sql(RETENTION, dialect=dialect)
|
|
79
|
+
assert sql.lstrip().upper().startswith("WITH " + GRID_RELATION.upper())
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def test_period_grid_row_counts_are_correct():
|
|
83
|
+
"""The grid must be inclusive of both ends: 0..n is n+1 rows."""
|
|
84
|
+
import duckdb
|
|
85
|
+
|
|
86
|
+
from factcat import period_grid
|
|
87
|
+
|
|
88
|
+
for n in (0, 1, 5, 20):
|
|
89
|
+
rows = duckdb.connect().execute(period_grid(n, "duckdb")).fetchall()
|
|
90
|
+
assert [r[0] for r in rows] == list(range(n + 1))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def test_redshift_falls_back_to_a_union_grid():
|
|
94
|
+
"""Redshift has no reachable row generator, so it gets an explicit union."""
|
|
95
|
+
from factcat import period_grid
|
|
96
|
+
|
|
97
|
+
grid = period_grid(2, "redshift")
|
|
98
|
+
assert grid.count("UNION ALL") == 2
|
|
99
|
+
assert "GENERATE_SERIES" not in grid.upper()
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def test_missing_with_clause_is_loud_not_silent():
|
|
103
|
+
"""A query the grid cannot attach to must raise, never emit broken SQL."""
|
|
104
|
+
with pytest.raises(RuntimeError, match="WITH clause"):
|
|
105
|
+
transpile_with_grid("SELECT 1 AS x", "duckdb", 2)
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""Ground-truth tests for ordered funnels.
|
|
2
|
+
|
|
3
|
+
The fixture is built to exercise the two things funnels get wrong: **ordering**
|
|
4
|
+
(a step only counts if it happens at or after the previous one) and the
|
|
5
|
+
**completion window** (measured from the first step, not the previous one).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import duckdb
|
|
11
|
+
import pytest
|
|
12
|
+
|
|
13
|
+
from factcat import FunnelSpec, funnel_sql
|
|
14
|
+
|
|
15
|
+
# entity_id, event_name, occurred_at
|
|
16
|
+
EVENTS = [
|
|
17
|
+
# E1 completes the whole funnel inside the window.
|
|
18
|
+
("E1", "view", "2026-03-01"),
|
|
19
|
+
("E1", "cart", "2026-03-02"),
|
|
20
|
+
("E1", "checkout", "2026-03-03"),
|
|
21
|
+
# E2 stops at the cart.
|
|
22
|
+
("E2", "view", "2026-03-01"),
|
|
23
|
+
("E2", "cart", "2026-03-02"),
|
|
24
|
+
# E3 checks out without ever adding to cart - must not skip a step.
|
|
25
|
+
("E3", "view", "2026-03-01"),
|
|
26
|
+
("E3", "checkout", "2026-03-02"),
|
|
27
|
+
# E4 carts on day 10, outside a 7-day window.
|
|
28
|
+
("E4", "view", "2026-03-01"),
|
|
29
|
+
("E4", "cart", "2026-03-11"),
|
|
30
|
+
("E4", "checkout", "2026-03-12"),
|
|
31
|
+
# E5 carted BEFORE viewing, so the cart does not count.
|
|
32
|
+
("E5", "cart", "2026-03-01"),
|
|
33
|
+
("E5", "view", "2026-03-02"),
|
|
34
|
+
("E5", "checkout", "2026-03-03"),
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@pytest.fixture()
|
|
39
|
+
def events() -> duckdb.DuckDBPyConnection:
|
|
40
|
+
con = duckdb.connect()
|
|
41
|
+
con.execute(
|
|
42
|
+
"CREATE TABLE events (entity_id VARCHAR, event_name VARCHAR, occurred_at DATE)"
|
|
43
|
+
)
|
|
44
|
+
con.executemany("INSERT INTO events VALUES (?, ?, ?)", EVENTS)
|
|
45
|
+
return con
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _spec(**overrides) -> FunnelSpec:
|
|
49
|
+
base = dict(
|
|
50
|
+
table="events",
|
|
51
|
+
entity="entity_id",
|
|
52
|
+
event_time="occurred_at",
|
|
53
|
+
steps=(
|
|
54
|
+
"event_name = 'view'",
|
|
55
|
+
"event_name = 'cart'",
|
|
56
|
+
"event_name = 'checkout'",
|
|
57
|
+
),
|
|
58
|
+
step_labels=("viewed", "carted", "checked out"),
|
|
59
|
+
within_days=7,
|
|
60
|
+
)
|
|
61
|
+
base.update(overrides)
|
|
62
|
+
return FunnelSpec(**base)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def test_ordered_funnel_counts(events):
|
|
66
|
+
rows = events.execute(funnel_sql(_spec())).fetchall()
|
|
67
|
+
counts = {int(i): (label, int(n), pct) for i, label, n, pct in rows}
|
|
68
|
+
|
|
69
|
+
# Every entity has a view.
|
|
70
|
+
assert counts[0] == ("viewed", 5, 100.00)
|
|
71
|
+
# E1 and E2 only: E3 never carted, E4's cart is outside the window,
|
|
72
|
+
# and E5 carted before viewing.
|
|
73
|
+
assert counts[1] == ("carted", 2, 40.00)
|
|
74
|
+
# E1 alone reaches checkout through the ordered path.
|
|
75
|
+
assert counts[2] == ("checked out", 1, 20.00)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def test_a_step_cannot_be_skipped(events):
|
|
79
|
+
"""E3 checked out but never carted, so it must not reach the final step."""
|
|
80
|
+
rows = events.execute(funnel_sql(_spec())).fetchall()
|
|
81
|
+
checkout = next(int(n) for i, _, n, _ in rows if int(i) == 2)
|
|
82
|
+
assert checkout == 1, "an out-of-order checkout was counted as a completion"
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def test_widening_the_window_admits_the_late_cart(events):
|
|
86
|
+
"""Mutation guard: E4's day-10 cart is excluded only by the window."""
|
|
87
|
+
rows = events.execute(funnel_sql(_spec(within_days=30))).fetchall()
|
|
88
|
+
counts = {int(i): int(n) for i, _, n, _ in rows}
|
|
89
|
+
|
|
90
|
+
assert counts[1] == 3, "widening the window should admit E4's late cart"
|
|
91
|
+
assert counts[2] == 2, "E4 should now complete the funnel too"
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def test_unbounded_window_is_allowed(events):
|
|
95
|
+
rows = events.execute(funnel_sql(_spec(within_days=None))).fetchall()
|
|
96
|
+
counts = {int(i): int(n) for i, _, n, _ in rows}
|
|
97
|
+
assert counts[1] == 3
|
|
98
|
+
assert counts[2] == 2
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def test_labels_default_when_not_supplied(events):
|
|
102
|
+
rows = events.execute(funnel_sql(_spec(step_labels=None))).fetchall()
|
|
103
|
+
assert [label for _, label, _, _ in rows] == ["step_0", "step_1", "step_2"]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def test_a_funnel_needs_two_steps():
|
|
107
|
+
with pytest.raises(ValueError, match="at least two steps"):
|
|
108
|
+
FunnelSpec(
|
|
109
|
+
table="events",
|
|
110
|
+
entity="entity_id",
|
|
111
|
+
event_time="occurred_at",
|
|
112
|
+
steps=("event_name = 'view'",),
|
|
113
|
+
)
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Ground-truth tests for a retention definition no other tool can express.
|
|
2
|
+
|
|
3
|
+
Taken verbatim from a real 2019 engagement note:
|
|
4
|
+
|
|
5
|
+
1. Who is being measured: the SUBSCRIPTION
|
|
6
|
+
2. What is being measured: any subscription start date
|
|
7
|
+
3. Period: 35 days (30-day billing + 5 days dunning)
|
|
8
|
+
4. Retained: payment collected; churned if dunning fails
|
|
9
|
+
|
|
10
|
+
The entity is not the user, the period is not a calendar bucket, and "retained"
|
|
11
|
+
is a payment state rather than an event occurrence. Every expected matrix below
|
|
12
|
+
is computed by hand from the fixture in ``conftest.py``.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from factcat import RetentionSpec, retention_sql
|
|
18
|
+
|
|
19
|
+
from .conftest import RETAINED
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _run(con, spec: RetentionSpec) -> dict[tuple[str, int], float]:
|
|
23
|
+
rows = con.execute(retention_sql(spec)).fetchall()
|
|
24
|
+
return {(str(cohort)[:10], int(period)): pct for cohort, period, _, _, pct in rows}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _spec(**overrides) -> RetentionSpec:
|
|
28
|
+
base = dict(
|
|
29
|
+
table="payments",
|
|
30
|
+
entity="subscription_id",
|
|
31
|
+
entity_time="sub_start",
|
|
32
|
+
event_time="paid_at",
|
|
33
|
+
period_days=35,
|
|
34
|
+
n_periods=2,
|
|
35
|
+
retained=RETAINED,
|
|
36
|
+
)
|
|
37
|
+
base.update(overrides)
|
|
38
|
+
return RetentionSpec(**base)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def test_retention_at_subscription_grain(con):
|
|
42
|
+
"""The grain the business actually bills at."""
|
|
43
|
+
got = _run(con, _spec())
|
|
44
|
+
|
|
45
|
+
# January cohort is S1, S2, S3.
|
|
46
|
+
# P0 all three pay on day 0 -> 3/3
|
|
47
|
+
# P1 S1 (offset 0) and S2 (offset 3); S3 offset 6 -> 2/3
|
|
48
|
+
# P2 S1 only -> 1/3
|
|
49
|
+
assert got[("2026-01-01", 0)] == 100.00
|
|
50
|
+
assert got[("2026-01-01", 1)] == 66.67
|
|
51
|
+
assert got[("2026-01-01", 2)] == 33.33
|
|
52
|
+
# February cohort is S4, whose day-35 payment FAILED.
|
|
53
|
+
assert got[("2026-02-01", 0)] == 100.00
|
|
54
|
+
assert got[("2026-02-01", 1)] == 0.00
|
|
55
|
+
assert got[("2026-02-01", 2)] == 0.00
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def test_same_data_at_user_grain_gives_a_different_answer(con):
|
|
59
|
+
"""Entity is a modelling decision, not a vendor's. U1 holds two subscriptions."""
|
|
60
|
+
got = _run(con, _spec(entity="user_id"))
|
|
61
|
+
|
|
62
|
+
# January cohort is U1 and U2.
|
|
63
|
+
# P1 U1 retained via either subscription; U2 missed the window -> 1/2
|
|
64
|
+
assert got[("2026-01-01", 0)] == 100.00
|
|
65
|
+
assert got[("2026-01-01", 1)] == 50.00
|
|
66
|
+
assert got[("2026-01-01", 2)] == 50.00
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def test_period_length_is_arbitrary(con):
|
|
70
|
+
"""At 30 days, S2's day-38 payment lands in period 1 at offset 8 - outside dunning."""
|
|
71
|
+
got = _run(con, _spec(period_days=30))
|
|
72
|
+
|
|
73
|
+
# S1 day 35 -> period 1 offset 5, just inside. S2 day 38 -> offset 8, out.
|
|
74
|
+
# S3 day 41 -> offset 11, out. So 1 of 3.
|
|
75
|
+
assert got[("2026-01-01", 1)] == 33.33
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def test_failed_payments_never_retain(con):
|
|
79
|
+
"""Mutation guard: with the predicate disabled, February period 1 becomes 100%."""
|
|
80
|
+
got = _run(con, _spec(retained="1 = 1"))
|
|
81
|
+
|
|
82
|
+
assert got[("2026-02-01", 1)] == 100.00, (
|
|
83
|
+
"the naive 'any event retains' model counts a FAILED payment as "
|
|
84
|
+
"retention - this is the number the incumbent tools report"
|
|
85
|
+
)
|