Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
59b45da
chore(bench): baseline from bench run 45965246339
github-actions[bot] Nov 27, 2026
00f9758
feat(bench,engine): drafted bench specs rewritten from documentation;…
claude Nov 27, 2026
4b0f4da
feat(bench): log accepted drift with its reason (AdventureWorks DimPr…
claude Nov 27, 2026
ffec5fa
revert: chore(bench): baseline from bench run 45965246339
claude Nov 27, 2026
8e5f79e
fix(engine): SCD2 moved starts stay on the source's later-version starts
claude Nov 27, 2026
844f760
fix(bench): Berka spec from the PKDD'99 data description
claude Nov 27, 2026
ec92bd5
feat(bench): IBM AML (HI-Small) as a monthly benchmark dataset
claude Nov 27, 2026
9fb2cb1
fix(bench): AML builder writes through the DuckDB relation API
claude Nov 27, 2026
23fc8b4
feat(bench): IBM AML from the authors' Kaggle dataset; Bitcoin rule; …
claude Nov 27, 2026
bcd82a5
fix(bench): the Kaggle credential is the KAGGLE_API_TOKEN secret
claude Nov 27, 2026
03f441b
fix(engine): rule-linked categorical joints, unique keys over stratif…
claude Nov 27, 2026
22618b2
chore(bench): pin the SHA-256 of the Kaggle HI-Small_Trans.csv
claude Nov 27, 2026
8936a48
fix(evaluate): count categorical join columns once in join_metrics
claude Nov 27, 2026
9b9612a
fix(engine): test unique-key nulls with math.isnan (CodeQL comparison…
claude Nov 27, 2026
428191a
fix(marginals): continuous columns with point masses keep their tails
claude Nov 27, 2026
4256f8f
chore(bench): log the owner-accepted ACS privacy-distance and census …
claude Nov 27, 2026
97b6c40
feat(marginals): point-mass knots as the setting marginals.point_mass…
claude Nov 27, 2026
5a29399
fix(quality): fan-out checks of a sampled fact use its exact per-pare…
claude Nov 27, 2026
465e68a
fix(engine): exact derives and lookups that read a soft rule's column…
claude Nov 27, 2026
ab2b5db
fix(engine): review findings on SCD recent entities, affinity under u…
claude Nov 27, 2026
51f98e1
fix(evaluate): level shares of joined ancestor columns counted on the…
claude Nov 28, 2026
2c5eb81
fix(evaluate): support check of a fact's reference keys on integer codes
claude Nov 28, 2026
fb70089
fix(bench): run errors in logs show the exception line
claude Nov 28, 2026
c5a073f
fix(quality): real-vs-real splits need two clusters; empty halves no …
claude Nov 28, 2026
15f5bfb
chore(bench): log the owner-accepted Berka integrity drift
claude Nov 28, 2026
7a1e837
Merge remote-tracking branch 'origin/main' into claude/project-thread…
claude Nov 28, 2026
54a4575
docs(changelog): quality report with a one-row parent
claude Nov 28, 2026
e5d5ba0
fix(engine): SCD2 sources whose closed versions end before they start…
claude Nov 28, 2026
0cce5b7
fix(bench): watchdog tracebacks in logs show the innermost frames
claude Nov 28, 2026
beb8d68
fix(quality): one-cluster data splits rows for its real-vs-real null
claude Nov 28, 2026
c70727c
fix(quality): detection null selects half rows instead of copying facts
claude Nov 28, 2026
a01a14e
Merge remote-tracking branch 'origin/main' into claude/project-thread…
claude Nov 28, 2026
42839dd
Merge origin/main (#81) and drop the Berka accepted drift
claude Nov 28, 2026
3697029
fix(quality): aggregate only the sampled parent rows for detection an…
claude Nov 29, 2026
62851c3
fix(quality,engine): CodeRabbit review of #82
claude Nov 29, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ All notable user-visible changes are recorded here, following [Keep a Changelog

### Fixed

- **SCD type 2 sources whose closed versions end before they start** (AdventureWorksDW products: start 2011/2012, end 2007/2008) keep their end dates. The engine replaced each such end date with start + 1 day, so DimProduct.EndDate and every fact's joined product EndDate failed (KS 0.59 to 0.06 on AdventureWorks). New setting `detection.scd_wellformed_share` (default 0.99): below this share of closed latest versions ending after their start, the source's own lengths are kept. Well-formed sources are unchanged (byte-identical on every fake scenario).
- **Quality report memory on large facts** (`relsynth quality`, `assess_quality`): the null of the aggregation detection check built both half databases and re-aggregated them for every split, copying every fact below the split root; on TPC-DS SF1 (the 11.7M-row inventory and the sales facts) the report passed 12 GiB and the weekly `tpcds_sf1` run was stopped. A half's aggregated rows are rows of the whole aggregated table (a parent row's children follow it into its half), so the split now selects them with masks drawn exactly as before. The aggregated table itself is now built only for the parent rows the models read (at most `max_rows`, a sample drawn as the utility checks already drew it): a large parent with many links (TPC-DS `customer_demographics`, 1.9M rows and 154 features at every scale factor) held about 2.2 GiB per side. Parents with one link per child give the same values as before; a parent with several links from one child (order, due and ship dates) now counts each link in both halves as it does on the compared tables, where the half databases kept only the children of the first link.
- **Quality report with a one-row parent** (`relsynth quality`, `assess_quality`): a relationship whose parent has a single row, or whose rows all hang from one root row (one store or call centre), stopped the report with a `KeyError` or `zero-size array` error, because a real-vs-real split left one half empty. With a single cluster the rows are now the split units (the null law then measures the rows' sampling noise), and only a table with fewer than two rows keeps the fixed tolerance. The weekly `tpcds_sf1` bench run failed on this; on AdventureWorks the 50 currency rates, all of one currency, are judged against their real-vs-real gap (0.25 to 0.33 at half size) instead of the 0.05 fixed tolerance, which the synthetic gap of 0.24 failed although it is within the real data's own noise.
- **Late rules are enforced** (`synthesis.rules.late`, default `enforce`; Prop. 1881). A check rule that reads an aggregate column, on its own table or through a link (a card issued on or after its account's opening date, when that date is the account's first transaction), was only counted. After the aggregates, the rows that break one are redrawn from their own conditional and kept only when every late rule holds, every other rule that held still holds, unique keys over attributes stay unique and the row is not a near copy; the aggregates are then recomputed. The redraw is skipped, with the reason in the sample log (`late_rules`), when other values were computed from the row's attributes (a rule of another table reading them, conditioned facts, offsets, versions, sequences, scenario maps). `report` keeps the earlier behaviour. Tables without late rules are unchanged.
- **Unique keys of one link and fixed columns are placed exactly** (`synthesis.uniqueness.free_parent_repair`, default `auto`; Prop. 1880). Rows the unique-key sampler cannot place (one owner per account, when nearly every account already has one) now get a parent drawn by the link model among the parents whose key is still free for the row, instead of uniformly among all parents. Berka: 25 accounts with two owners and 27 unresolved rows became 0. Only rows that broke a unique key are affected; `off` restores the uniform fallback.
- Pushdown: a sampled fact with a date offset (or another hidden column of the internal model) no longer
Expand Down
15 changes: 12 additions & 3 deletions bench/regress.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,19 @@

def error_summary(err: str, n: int = 300) -> str:
"""A run's error for a log line: its first line and, for a Python traceback, the exception
(the last non-empty line), which a head of the text alone cuts off."""
lines = [x.strip() for x in str(err).splitlines() if x.strip()]
(the last non-empty line), which a head of the text alone cuts off. A faulthandler dump (the
memory watchdog's) lists the most recent call first, so its innermost frames are kept instead,
each as file:line in function."""
text = str(err)
if "Current thread" in text:
frames = re.findall(r'File "([^"]+)", line (\d+) in (\S+)', text[text.index("Current thread"):])
if frames:
where = " < ".join(f"{Path(f).name}:{ln} in {fn}" for f, ln, fn in frames[:6])
head = text[: text.index("Current thread")].strip()
return ((head + " " if head else "") + where)[:n]
lines = [x.strip() for x in text.splitlines() if x.strip()]
if len(lines) <= 1:
return str(err)[:n]
return text[:n]
head, last = lines[0], lines[-1]
return (head[: n // 3] + " ... " + last[: n - n // 3])

Expand Down
1 change: 1 addition & 0 deletions docs/settings-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ Generated from `relsynth.settings` (`python -m relsynth.settings > docs/settings
| `repair.occupancy_rounds` | int | `20` | 0 … 10000 | | Redraws that give every parent its mandatory first row in occupancy facts. |
| `detection.group_effect_share` | float | `0.95` | 0 … 1 | | A group effect holding on fewer source groups than this share is reported. |
| `detection.scd_stable_share` | float | `0.99` | 0 … 1 | | SCD2 stable auto: columns equal across versions on at least this share of keys. |
| `detection.scd_wellformed_share` | float | `0.99` | 0 … 1 | | SCD2: below this share of source closed latest versions ending after their start, the source's own version lengths (signs included) are kept. |
| `detection.scd_max_versions` | int | `50` | 1 … 1e+06 | | Largest number of versions per key modelled exactly (more are pooled). |
| `evaluation.thresholds` | map | `{}` | | | Fixed tolerances of the scorecard by name (ks, tvd, auc, ...; see the table below). Each limit is the larger of its tolerance and its sampling limit. |
| `evaluation.assoc_max_rows` | int | `20000` | 100 … 1e+09 | | Rows sampled for the association metrics. |
Expand Down
22 changes: 18 additions & 4 deletions src/relsynth/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -6604,7 +6604,13 @@ def _fit_scd(self, tables):
keep = np.argsort(gc)[-50:]
gv, gc = gv[keep], gc[keep]
# lengths of closed latest versions (days), for a latest version drawn closed
dur = (fr["e"] - fr["s"])[last].dt.days.dropna().to_numpy(dtype=float)
span = (fr["e"] - fr["s"])[last].dropna()
dur = span.dt.days.to_numpy(dtype=float)
# share of closed latest versions that end after they start (on the spans, so a
# positive span under one day counts): a source whose intervals are not well formed
# (end dates loaded before the start, placeholder ends) keeps its own lengths, signs
# included, instead of having them forced positive
wf = float((span > pd.Timedelta(0)).mean()) if len(span) else 1.0
dur = np.quantile(dur, np.linspace(0, 1, 51)) if len(dur) > 51 else dur
# days from one version's start to the next one's (a version's length): a start
# drawn on or before the previous version's start moves this far past it
Expand Down Expand Up @@ -6645,7 +6651,8 @@ def _fit_scd(self, tables):
break
st = {"nk": nk, "vf": vf, "vt": vt if vt in df.columns else None, "vcount": vcount,
"cur_h": cur_h, "cur_n": cur_n, "gaps": gv, "gcount": gc.astype(float), "stable": stable,
"current": cur, "dur": dur, "step": step, "starts": ls}
"current": cur, "dur": dur, "step": step, "starts": ls,
"wellformed": wf >= _setting(self, "detection", "scd_wellformed_share", 0.99)}

def draw(rng, st=st):
st["vw"] = rng.dirichlet(st["vcount"] + 0.5)
Expand Down Expand Up @@ -6798,8 +6805,15 @@ def _apply_scd(self, t, df, seg, out=None):
# takes a closed length from the source instead: a closed latest version's length,
# else (no closed latest version in the source) a version length
lens = st["dur"] if len(st["dur"]) else (st["step"] if has else np.ones(1))
dd = np.maximum(lens[rng.integers(0, len(lens), size=n)], 1)
fix = (e_ <= sv) if not len(st["dur"]) else (np.isnat(e_) | (e_ <= sv))
dd = lens[rng.integers(0, len(lens), size=n)]
if st.get("wellformed", True):
dd = np.maximum(dd, 1)
fix = (e_ <= sv) if not len(st["dur"]) else (np.isnat(e_) | (e_ <= sv))
else:
# the source's closed latest versions often end on or before their start
# (detection.scd_wellformed_share): the drawn end is kept, and a missing one
# takes a source length with its sign
fix = np.isnat(e_)
e_ = np.where(fix, sv + (dd * 86400e9).astype("timedelta64[ns]"), e_)
ev = np.where(is_last, e_, nxt + (gap * 86400e9).astype("timedelta64[ns]"))
# the open version is the row the model drew open (one per key after the spread)
Expand Down
50 changes: 50 additions & 0 deletions src/relsynth/quality/calibrate.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,23 @@ def cluster_ids(spec, tables, t):
return ids.fillna("__null__").astype(str).to_numpy()


def splittable(ids) -> bool:
"""Whether real-vs-real splits exist: at least two units, so that each half gets one."""
return len(np.unique(ids)) >= 2


def split_units(ids):
"""The units a real-vs-real split moves whole: the clusters of Prop. 109 (i) when there are
at least two. Rows that all hang from one root row (one store, one call centre, rates of a
single currency) form one cluster, which cannot be split; their rows are then the units, so
the null law measures the rows' sampling noise. Within-cluster dependence is not estimable
from one cluster, so this limit can be tighter than a clustered one; it is still far closer
to the real-vs-real noise than the fixed tolerance, which ignores the sample size. With
fewer than two rows nothing can be split and the checks use the fixed tolerance."""
ids = np.asarray(ids)
return ids if splittable(ids) else np.arange(len(ids)).astype(str)


def cluster_halves(ids, rng):
"""Boolean mask of half A: whole clusters assigned at random to the halves."""
u, inv = np.unique(ids, return_inverse=True)
Expand All @@ -92,6 +109,39 @@ def split_db_root(spec, tables, t, rng):
return split_db(spec, tables, chain[-1][2] if chain else t, rng)


def split_masks(spec, tables, t, rng):
"""The rows of t in each half of split_db_root(spec, tables, t, rng), as two boolean masks,
with the same draws from rng, without building the halves. split_db_root copies every
table below the root (on TPC-DS SF1 the 11.7M-row inventory and every sales fact, per
split); a metric that reads t only through per-row values computed once on the whole table
(aggregated child features, whose children follow their parent row into its half) needs
only the masks."""
chain = anchor_chain(spec, tables, t)
root = chain[-1][2] if chain else t
n = len(tables[root])
perm = rng.permutation(n)
up = {c: (c, fk, p, pk) for c, fk, p, pk in descendants(spec, root)}
path, cur = [], t
while cur != root: # t's line from the root, as split_db reaches it
path.append(up[cur])
cur = up[cur][2]
path.reverse()
keys = {}

def k(tab, col):
if (tab, col) not in keys:
keys[(tab, col)] = keystr(tables[tab][col])
return keys[(tab, col)]
out = []
for idx in (np.sort(perm[: n // 2]), np.sort(perm[n // 2:])):
m = np.zeros(n, dtype=bool)
m[idx] = True
for c, fk, p, pk in path:
m = k(c, fk).isin(set(k(p, pk)[m].dropna())).to_numpy()
out.append(m)
return out


def split_db(spec, tables, t, rng, follow=True):
"""Two half-databases: the rows of t split at random into halves, every
table below t (with follow) keeps the rows whose parent is in the half;
Expand Down
29 changes: 29 additions & 0 deletions src/relsynth/quality/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,8 @@ def _pair_trend(xa, xb, ya, yb, cat_x, cat_y, bins=10, dx=None, dy=None):
ra = pearsonr(fa[oka], ga[oka]).statistic
rb = pearsonr(fb[okb], gb[okb]).statistic if np.ptp(fb[okb]) > 0 and np.ptp(gb[okb]) > 0 else 0.0
return float(1 - abs(ra - rb) / 2)
if not len(xa) or not len(xb): # a side without rows (a split half under a one-row root): no score
return None
xa_, xb_ = dx if dx is not None else _discretise(xa, xb, cat_x, bins)
ya_, yb_ = dy if dy is not None else _discretise(ya, yb, cat_y, bins)
ka = xa_.astype(np.int64) * (10 ** 6 + 2) + ya_
Expand Down Expand Up @@ -246,6 +248,33 @@ def aggregated(spec, tables, parent, factors=None):
return df, kinds


def parent_sample(spec, tables, parent, idx):
"""The tables that aggregated(spec, ·, parent) reads, restricted to rows idx of the parent
and the rows of its direct children that point at them. A parent row's features depend
only on its own children, so aggregated(parent_sample(...)) equals the rows idx of
aggregated(tables) without building the whole frame: one float column per child column
and link for every parent row (TPC-DS customer_demographics: 1.9M rows, over 100
features, several GiB per side)."""
from ..data import canonical_keys
pk = spec["tables"][parent]["primary_key"]
base = tables[parent].iloc[idx]
out = dict(tables)
out[parent] = base
masks = {}
pkeys = canonical_keys(tables[parent][pk])
for _name, p, _pk, c, fk in relations(spec):
if p == parent and c in tables: # a child with several links keeps a row any of them reaches
ck = canonical_keys(tables[c][fk])
if ck.dtype == pkeys.dtype: # integer keys: compared as numbers, no string copy
m = ck.isin(pkeys.iloc[idx].dropna().unique()).to_numpy()
else: # mixed kinds ("1" against 1): as aggregated does
m = keystr(tables[c][fk]).isin(keystr(base[pk]).dropna().unique()).to_numpy()
masks[c] = masks[c] | m if c in masks else m
for c, m in masks.items():
out[c] = tables[c] if m.all() else tables[c][m]
return out


def _as_spec_cols(kinds):
"""A minimal table spec for feature_matrix on an aggregated frame."""
return {"tables": {"_agg": {"columns": {c: {"type": "categorical" if v else "float"} for c, v in kinds.items()}}}}
Expand Down
Loading
Loading