Skip to content
Logo

Census

A schema describes structure you already know. Realistic data also needs statistics of the real thing: how values are spread, how often a field is missing or null, how long strings are, and which strings are really enums. That part is usually guessed. @ghostry/fabricator-census takes a census of real data and reports those statistics as fabricator config: distribution variants, whereby ranges, .weighted(...) weights, and string composition.

import { census, report } from "@ghostry/fabricator-census";
 
const users = census.from(rows);
 
console.log(report(users));

rows is any iterable of plain JS values, such as an array parsed from JSON or rows from a database driver. You don't declare anything first. A census reads plain values, never a Schema, and works out the structure as it goes. The report has one line per path, written as the builder call it suggests for that path:

Census of 5000 values.

$  T.object({ "id", "age", "plan", "referrer", "nickname", "spend" })
$.id  T.number.integer.sequence
    note: Values ran 1, 2, 3, … in input order; T.number.integer.sequence counts the same way.
$.age  T.number.integer.whereby({ min: 18, max: 79, distribution: { kind: "normal", mean: 38.31, spread: 11.95 } }).admits({ min: -Infinity, max: Infinity })
    fit: normal 0.0049 · triangular 0.0956 · skew 0.1823 · uniform 0.3254 (simpler wins within 0.0192, n = 5000)
$.plan  T.enum.weighted([[3528, "free"], [1237, "pro"], [235, "team"]])
$.referrer  T.nullable(T.string.whereby({ length: 8, composition: { uppercase: 5046, digit: 5018 } }).admits({ length: { min: 0, max: Infinity } })).weighted({ null: 3742, value: 1258 })
    note: composition draws each code point uniformly within its source, so per-character frequencies are not reproduced.
$.nickname  T.omittable(T.string.whereby({ length: { min: 2, max: 10, distribution: { kind: "uniform" } }, composition: { lowercase: 9744 } }).admits({ length: { min: 0, max: Infinity } })).weighted({ omitted: 3367, value: 1633 })
    note: composition draws each code point uniformly within its source, so per-character frequencies are not reproduced.
    fit: normal 0.0053 · skew 0.0078 · uniform 0.0116 · triangular 0.1176 (simpler wins within 0.0337, n = 1633)
$.spend  T.number.whereby({ min: 3.428821919648706e-11, max: 4995.5303206052795, distribution: { kind: "skew", exponent: 2.922 } }).admits({ min: -Infinity, max: Infinity })
    fit: skew 0.0168 · normal 0.2150 · triangular 0.2773 · uniform 0.3827 · logarithmic 0.6920 (simpler wins within 0.0192, n = 5000)

Not detected: cross-field correlations (a field present only when another holds some value), discriminated unions, positional tuples, and recursive schemas.

The whereby ranges are what the census saw, and they shape the data you fabricate. The .admits(...) after each one is for adapters. Without it, a TypeBox schema converted from the suggestion would reject any value outside what the sample happened to contain. To state upfront what a field really accepts, pass limits.

Taking a census

census.from(values) reads an iterable in one pass. For any other source, such as a driver cursor, a stream, or several batches, census.begin() returns an accumulator and you write the loop:

const tally = census.begin();
 
for await (const row of cursor) tally.add(row);
 
const users = tally.finish();

That is why there is no async version: the loop is the only async part. finish() returns the census, and calling add after it throws.

Every value is counted, so counts, type mixes, and presence are exact. Quantiles, histograms, and fits are also exact until a field has seen more than reservoir values. After that, they come from a uniform sample of that size.

OptionDefaultWhat it bounds
reservoir10_000Values kept per numeric tally, for quantiles, histograms and fits.
distinct256Distinct values tracked per field. Past it, the field is high-cardinality and its values are dropped.
fields256Distinct keys tracked per object. Past it, the object is read as a record: one merged value, one key tally.
depth16Nesting levels descended into. Deeper arrays and objects are counted, not opened.
bins20Histogram bins.
points1001Quantile points kept per numeric summary, which is what a fit is scored against.
seednoneMakes the reservoir sample reproducible for a given input order.
factsnoneWhole-table facts per top-level field. See Facts.
limitsnoneWhat each top-level field accepts. See Limits.

These limits keep memory use flat, so data keyed by id or a deep tree can't make a census grow without bound. A suggestion notes wherever a limit was reached.

A census is plain data. You can JSON.stringify it, store it, and suggest from it later. Values JSON can't hold are tagged, such as a bigint as { type: "bigint", value: "…" }.

Reading the suggestions

suggest(census) returns the tree that report prints. It has one node per path, each naming the kind it suggests and holding that builder's arguments as data.

import { suggest } from "@ghostry/fabricator-census";
 
const suggestion = suggest(users);
 
if (suggestion.kind === "object") {
  suggestion.fields.find((field) => field.key === "plan");
  // { key: "plan", value: { kind: "enum", items: [[3528, "free"], …], notes: [] } }
}

A suggestion is data, not a Schema and not source code. You read it and write the schema yourself. That keeps it serializable and leaves the decisions it can't make to you.

ObservedSuggested
a key missing from some objectsT.omittable(x).weighted({ omitted, value })
a key missing, or present as undefinedT.optional(x).weighted({ omitted, undefined, value })
undefined, never missingT.undefinable(x).weighted({ undefined, value })
nullT.nullable(x).weighted({ null, value })
null and undefinedT.nullish(x).weighted({ null, undefined, value })
a key missing, and null when presentT.omittable(T.nullable(x)), each with its own weights
more than one typeT.choice.weighted([[count, x], …])
one value onlyT.always(value)
few distinct values, each seen repeatedlyT.enum.weighted([[count, value], …])
numbersT.number.whereby({ min, max, distribution })
whole numbersT.number.integer.whereby({ min, max, distribution })
whole numbers running 1, 2, 3, … in input orderT.number.integer.sequence
NaN or an infinity among numbersa T.choice with a T.always arm for each
bigintsT.bigint.whereby({ min, max })
booleansT.boolean.weighted({ true, false })
Date objectsT.date.whereby({ min, max, distribution })
stringsT.string.whereby({ length, composition })
strings that are ISO date-timesT.derive({ to: T.string, from: [T.date.whereby(…)] })
strings that are uuids, emails or urlsT.string, with a note naming the faker builder
arraysT.array(element).whereby({ length })
objectsT.object({ … })
objects with more keys than fieldsT.record(key, value).whereby({ size })

Weights are the observed counts, not rounded. Fabricator's weights are relative, so { null: 3742, value: 1258 } and { null: 3, value: 1 } describe nearly the same schema. A nested wrapper's weights only count what the outer wrapper let through. In T.omittable(T.nullable(x)), the inner null and value add up to the number of objects that had the key.

A string's length counts UTF-16 code units, the same way T.string does, so "😀".length is 2 in both.

Fits

For every range, a census tries each distribution that could apply and scores it by the largest gap between the data's cumulative distribution and the candidate's. The fit: line lists the candidates, best first.

  • Scores only rank candidates. Each candidate's parameters come from the same data it is scored against, so a score is not a significance test.
  • The simpler candidate wins a near-tie. A candidate with fewer parameters is chosen when its score is within 1.36 / √n of the best, which is the "simpler wins within" number. uniform has no parameters, so data with no real shape reads as uniform instead of a faint normal, as nickname's length does above.
  • Whole numbers are scored the way fabricator draws them. T.number.integer and every length are drawn as whole numbers, so those fields are scored against whole-number buckets instead of a continuous curve.
  • logarithmic is only tried where it fits: a range that starts above zero and spans at least two orders of magnitude.
  • Two peaks are not fitted. multi and custom are never suggested. A field with two peaks shows up as every candidate scoring poorly. Its histogram is on the census, at node.number.summary.histogram.

Paste a fitted distribution into the explorer to see its shape. fit(numeric, options) is also exported, so you can fit any numeric tally in a census yourself.

Notes

Every suggestion has notes for things the builder call alone doesn't tell you. For example:

  • Every value was distinct, but values fabricated from the suggested range will collide. T.unique draws the same range without repeating.
  • composition draws evenly within each character class, so letter frequencies are not reproduced.
  • An object's keys look like data rather than structure.

What a census does not detect

  • Fields that depend on each other, such as shippedAt being present only when status is "shipped". Use .refine or T.derive for those.
  • Discriminated unions. Objects of different shapes merge into one node with many misleading T.omittable fields. If a string field with few values cleanly predicts which other fields are present, it gets a note saying so.
  • Positional tuples. An array is one merged element and a length.
  • Recursive schemas. A tree is described level by level, down to depth.

Writing the schema

The report above, written out:

const User = T.object({
  id: T.number.integer.sequence,
  age: T.number.integer.whereby({
    min: 18,
    max: 90,
    distribution: { kind: "normal", mean: 38, spread: 12 },
  }),
  plan: T.enum.weighted([
    [14, "free"],
    [5, "pro"],
    [1, "team"],
  ]),
  referrer: T.nullable(
    T.string.whereby({ length: 8, composition: { uppercase: 1, digit: 1 } }),
  ).weighted({ null: 3, value: 1 }),
  nickname: T.omittable(
    T.string.whereby({
      length: { min: 2, max: 10 },
      composition: { lowercase: 1 },
    }),
  ).weighted({ omitted: 2, value: 1 }),
  spend: T.number.whereby({
    min: 0,
    max: 5000,
    distribution: { kind: "skew", exponent: 3 },
  }),
});

The differences are the judgment calls a census leaves to you:

  • Ranges. A sample's extremes fall inside the true range. 79 was the oldest user seen, but the real limit is 90. 3.4e-11 is really zero.
  • Weights and parameters. These are rounded to what the numbers support. A spread of 11.95 from 5,000 rows is 12.
  • Defaults. distribution: { kind: "uniform" } is the default, so it is left out.
  • Validation. Without .admits(...), an adapter turns these ranges into limits: a converted User rejects an age of 91. That's right when a range is the field's real limit, as 90 is here. When a range only sets what you fabricate, keep its .admits(...) call.

How many rows

sampleSize() tells you how large a sample a census needs for its statistics to be accurate within a margin:

import { sampleSize } from "@ghostry/fabricator-census";
 
sampleSize();
// { n: 4612, reasons: [{ criterion: "shape", n: 4612, … }, …] }
 
sampleSize({ population: 20_000, rare: 0.001 });
// { n: 3748, reasons: [{ criterion: "shape", n: 3748, … }, …] }

n is the largest of the requirements below, and reasons lists each one:

CriterionGuaranteesAt the defaults
shapeevery point of the cumulative distribution within margin4612
proportionevery presence, null or enum weight within margin2401
rarea value of frequency rare seen at least once; applies only when given—

margin defaults to 0.02 and confidence to 0.95. population applies the finite population correction and caps n at the population. The number doesn't grow with the table: 4,612 rows describe two million rows as well as twenty thousand.

From PostgreSQL

@ghostry/fabricator-census/postgres builds the queries that feed a census: a sample of the right size, and facts about the whole table. It never opens a connection. Every query runs through your own driver.

import { census, report } from "@ghostry/fabricator-census";
import { collect, type Run } from "@ghostry/fabricator-census/postgres";
 
const run: Run = async (text, values) =>
  (await client.query(text, values)).rows;
 
const { rows, facts, limits } = await collect(run, { table: "users" });
 
console.log(report(census.from(rows, { facts, limits })));

run is the whole integration: it takes query text with $1 placeholders and an array of values, and returns rows. The line above works for both node-postgres and PGlite. A table is a name, or { schema, table }.

collect runs these, in order:

  1. The planner's row estimate, from pg_class. A table that was never analyzed has none, so its rows are counted instead.
  2. The table's columns and their types.
  3. The planner's statistics, from pg_stats, as estimated facts.
  4. A sample, sized by sampleSize against the row count.
  5. One aggregate query per column, as exact facts.

It also reads each column's limits from its type, which needs no query of its own. It returns the sampled rows, the facts, and the limits, along with the columns, the population, the size it chose, and every query it ran as queries.

Facts: what the whole table knows

Some things a sample can't tell you reliably, but the database can answer exactly with one aggregate each. Facts are those answers, per column:

A sample saysA fact says
no nulls appeared in 4,000 rowsthe table has 37
values ran from 3 to 9,840the true extremes are 1 and 10,000
status took three valuesstatus has exactly those three, weighted 600k, 300k, 100k
these ids look randomids are 1 to the row count with none repeated: a serial

Pass them as census.from(rows, { facts }). When suggesting, an exact fact is used first, then an estimated one, then the sample.

  • Exact facts come from the aggregates, which read every row.
  • Estimated facts come from the planner's statistics. They are free to read, but ANALYZE took them from its own sample, so a suggestion that used one says so in its notes.

Facts set presence weights, ranges, enum members and their weights, and uniqueness. The distribution's shape is still fitted from the sample, within the table's range, because no aggregate describes a shape. The table's extremes can only widen a range, never narrow it.

Facts have limits. They only describe top-level columns, so anything nested inside a json column comes from the sample alone. And they describe the whole table, while sample.where filters only the sample, so don't use the two together.

Facts is plain data with nothing PostgreSQL-specific in it. You can get facts from another database, a cache, or write them by hand.

Limits: what a column accepts

Facts describe what a column holds. Limits describe what it accepts: a varchar(20) may currently hold names up to 14 characters long, but it accepts 20. Facts shape whereby, so they change the data you fabricate. Limits only go into .admits(...), so they change what an adapter accepts and nothing else.

collect reads limits from these column types:

Column typeLimit
varchar(n), char(n)a maximum length of n
int2, int4, int8the type's range
numeric(p, s)below 10^(p − s) in either direction
anything elsenone, including text, an unconstrained varchar or numeric, floats

CHECK constraints and a domain's checks are not read, nor is NOT NULL.

Pass them as census.from(rows, { limits }). A census only uses a limit that contains every value the suggestion fabricates. When the sample breaks one, the limit is left out and a note says why:

$.name  T.string.whereby({ length: { min: 2, max: 10, … } }).admits({ length: { min: 0, max: Infinity } })
    note: The declared maximum length, 5, is below the greatest length drawn here, 10, so no maximum is admitted.

Text is the usual cause. PostgreSQL counts a varchar(n) length in code points, while fabricator and TypeBox count UTF-16 units, so a character outside the Basic Multilingual Plane counts twice. A value that fits the column can still be too long for the converted schema, and every length limit from collect carries a note saying so.

Like facts, limits are plain data. You can write them by hand, one entry per top-level field:

census.from(rows, {
  limits: [
    { column: "age", limits: { min: 0, max: 150 } },
    { column: "nickname", limits: { length: { max: 32 } } },
  ],
});

min and max are numbers, or { type: "bigint", value } past 2^53, and a date's are epoch milliseconds. length.max is the longest value: characters for text, elements for an array. An end you leave out accepts anything. A field with more than one type, or one suggested as an enum, always, sequence, or derive, takes no limits.

What it costs

Every query carries a cost, and collect's queries lists what ran:

CostReadsQueries
catalogsystem catalogs onlythe estimate, the columns, statistics
sampleevery page, or a sample of themthe sample
scanevery row, once per columnthe aggregates, and a count if needed

On a large table, the scans are the expensive part. Run them against a replica, set a statement_timeout, or skip them:

await collect(run, { table: "users", budget: "catalog" });

With budget: "catalog", every fact is an estimate, and a table that was never analyzed is an error instead of being counted. A serial column also stops being suggested as T.number.integer.sequence, because that needs exact extremes and the planner's fall inside the true range.

An exact distinct count is the one aggregate left out by default, because count(DISTINCT …) is the most expensive. The planner's estimate is used instead. Pass aggregates: { distinct: "exact" } to get the real count.

Choosing a sampling method

await collect(run, {
  table: "events",
  sample: { method: "hash", key: "id", seed: 1 },
});
MethodReadsBiasSame rows next time
bernoulli (default)every pagenonewith a seed, while the physical layout is unchanged
systemonly sampled pageswherever physical order tracks the valueswith a seed, while the physical layout is unchanged
hashevery rownone, but rows sharing a key move togetheralways, and stable as rows are added

system is fastest on a huge table, but wrong for an append-only, time-ordered table, where each page holds rows from the same moment. Use hash when a census should be repeatable against a table that keeps changing.

No method uses LIMIT, because cutting a scan short favors whichever rows it reaches first. So the row count lands near n, not exactly on it.

The builders on their own

collect is a shortcut. Each step is a builder that returns a Query with text, values, cost, notes, and a read function that parses the driver's rows:

import { census, sampleSize } from "@ghostry/fabricator-census";
import {
  aggregates,
  coerce,
  columns,
  count,
  estimate,
  estimatedFacts,
  limits,
  sample,
  statistics,
  type Query,
} from "@ghostry/fabricator-census/postgres";
 
const execute = async <$Result>(query: Query<$Result>) =>
  query.read(await run(query.text, query.values));
 
const population =
  (await execute(estimate("users"))) ?? (await execute(count("users")));
const described = await execute(columns("users"));
 
const facts = estimatedFacts(
  await execute(statistics("users")),
  described,
  population,
);
 
const { n } = sampleSize({ population });
const rows = coerce(
  await execute(sample("users", { n, population })),
  described,
);
 
for (const query of aggregates("users", described))
  facts.push(await execute(query));
 
const users = census.from(rows, { facts, limits: limits(described) });

Using the builders directly lets you sample on one connection and aggregate on another, cache the facts, or leave a column out.

Identifiers are always quoted, and numbers are always passed as parameters, never written into the query text. sample's where is the one exception: it is raw SQL, so only pass trusted text.

How column types are read

Drivers return some of the types a census cares about differently, so coerce reads each column by its declared type. collect runs it for you.

ColumnRead as
int8a number when every value is safe, otherwise a bigint throughout the column
numerica number, which holds about 15 to 17 significant digits
boolean left as t/fa boolean
everything elsewhatever the driver returned

A few types have a caveat, which appears as a note on the suggestion:

  • timestamp without time zone has no offset, so drivers read it in the local time zone, and its values shift depending on where the census runs.
  • date reads as local or UTC midnight depending on the driver.
  • Text lengths. PostgreSQL's char_length counts code points, while a census counts UTF-16 units. The table's lengths are used only when the sample had no characters outside the Basic Multilingual Plane. Otherwise the sample's lengths are used.

SQL rows are flat, and every column is present in every row. So a column is never suggested as T.omittable. A missing value is a null, and is suggested as T.nullable.