Skip to content

Analytics Extensions

Mohammad Rasoul Kazemi edited this page Nov 26, 2026 · 4 revisions

Analytics Extensions

Phase 12 adds three extensions: kingres_sketch 1.0 (approximate aggregates), kingres_timepart 0.3 (time partitioning) and kingres_columnar 0.2 (columnar storage). Phase 12 is built: the extensions, the parts in kingres_shard 0.9 (repartitioned joins, MERGE, columnar and time-partitioned distributed tables, approximate count(DISTINCT); see Sharding Query Pushdown), and the control-plane and console parts (approximate aggregates per database, conversion of a table or partition between row and columnar storage with a preview, time-partitioning policies with a plan, runs and a scheduler, and the preload of kingres_columnar; REST contract 0.18.0 and later). The aggregates of kingres_sketch are computed in part by the shard groups (see Sharding). Designs: queries and storage. All three build for PostgreSQL 18 and 19 from one source (Building from Source).

kingres_sketch

Approximate aggregates in the schema kingres_sketch (a fixed schema, not relocatable; no shared_preload_libraries entry, no restart). Three types: hll (HyperLogLog, distinct count), topn (Space-Saving, most frequent items) and tdigest (merging t-digest, percentiles). A sketch is a small value that can be built with an aggregate, stored in a column such as a rollup table, united and read. The aggregates support partial aggregation, so parallel and partitionwise aggregates use them.

CREATE EXTENSION kingres_sketch;
SET search_path = public, kingres_sketch;

SELECT approx_count_distinct(user_id) FROM events;
SELECT approx_percentile(0.95, latency_ms) FROM requests;
SELECT hll_cardinality(hll_union_agg(s)) FROM daily_rollup;   -- s is an hll column
SELECT * FROM topn_list(topn_add_agg(url, 100), 10);

Main functions: hll_add_agg, hll_union_agg, hll_cardinality, hll_fold; topn_add_agg, topn_union_agg, topn_list, topn_total; tdigest_agg, tdigest_weighted_agg, tdigest_union_agg, tdigest_quantile, tdigest_rank. Sketches of different precision, capacity or compression cannot be united directly (only an hll can be folded to a lower precision). topn accepts only types whose text does not depend on a setting (integers, numeric, text, uuid, bool and similar). approx_percentile is a plain aggregate, not percentile_cont ... WITHIN GROUP, which stays exact.

The memory of aggregate states in a backend is bounded by kingres_sketch.state_memory_ceiling (set only by a superuser) and kingres_sketch.state_memory_limit (a role's own). With kingres_shard.count_distinct_mode = 'approximate' a count(DISTINCT x) over a hash-distributed table is rewritten to approx_count_distinct, and every shard group answers with one sketch instead of its rows. The sketches are approximate by design.

kingres_timepart

Time partitioning of ordinary tables and, since 0.3, of distributed tables, written in SQL and PL/pgSQL (no C code, no background process, no preload). For a table partitioned by RANGE on one date, timestamp or timestamptz column it creates partitions ahead, converts old partitions to columnar storage, drops or detaches partitions past a retention, keeps a policy per table and a history of runs. A run happens when something calls it (psql, pg_cron) or when the scheduler of the control plane (kingresd) calls it; the control plane also has the plan, the runs and the policies in the REST API and the console.

CREATE EXTENSION kingres_timepart;     -- superuser; objects live in schema kingres
SELECT kingres.timepart_set_policy('tpv.cpol', '1 day', create_ahead => '1 day',
                                   retention => '30 days', columnar_after => '2 days');
SELECT * FROM kingres.timepart_plan('tpv.cpol');          -- what a run would do
CALL kingres.timepart_run('tpv.cpol');                    -- superuser; cannot run in a transaction block
CALL kingres.convert_partition('tpv.cpol', 'tpv.cpol_p20260101', 'columnar');

Other functions: create_time_partitions, drop_old_time_partitions, timepart_unset_policy, timepart_partitions, timepart_check, convert_old_partitions. Execution is revoked from PUBLIC and granted by an administrator. Bounds follow a grid (hours, days, weeks, months, years) in a time zone that defaults to UTC. A policy acts only after the interface sealed it, so a row restored from a dump does nothing until a superuser runs timepart_adopt. A superuser's session does not maintain a table of another role unless a setting says owners are trusted.

Conversion needs kingres_columnar and refuses partitions with hash, GiST, GIN, BRIN or SP-GiST indexes, foreign keys, row triggers and some other objects (see its README). One behaviour stays and is stated: a REPEATABLE READ or SERIALIZABLE transaction whose snapshot is older than the swap and that has not read the table yet sees the partition empty, as with TRUNCATE.

Distributed tables (0.3). A table that kingres_shard 0.9 distributed and partitioned by RANGE on a time column can have a policy. Everything is done on the map group primary, by a superuser (the service role of the control plane). A time partition is one logical object (a row of kingres.dist_partition) with one leaf per bucket on the node that holds the bucket. Partitions are created ahead with kingres.create_partition on every server, retired with drop_partition or detach_partition, and old partitions are converted to columnar storage leaf by leaf on the node that holds each leaf (convert_distributed_partition, timepart_dist_partitions). The colocation group is claimed during a conversion, so no bucket moves meanwhile; a leaf that is refused or fails leaves the partition mixed, which reads correctly, and the next run converts the rest. The policy is refused when its steady state would pass kingres_shard.max_partition_leaves (8192), and a daily policy on 128 buckets adds 128 leaves a day. list partitions and a default partition are refused for a policy on a distributed table. kingres_timepart 0.3 must be installed in the database of every node that holds a leaf, and kingres_columnar for a conversion; the control plane installs both with the database.

kingres_columnar

A table access method, columnar, that stores each column separately and compressed in stripes of rows (150000 by default), with minimum and maximum values to skip stripes. It is meant for append-only analytic data: time series, events, logs and old partitions. Its WAL is logged under the resource manager id 255, registered for KingresColumnar on the PostgreSQL wiki list of custom WAL resource managers. The library must be preloaded on every node that writes, replays or restores columnar data, standbys included:

shared_preload_libraries = 'kingres_columnar'
CREATE EXTENSION kingres_columnar;      -- superuser
CREATE TABLE events (ts timestamptz, device int, value float8) USING columnar;
ALTER TABLE t SET ACCESS METHOD columnar;   -- rewrites; "heap" converts back
SELECT * FROM kingres.columnar_info('events');
SELECT kingres.columnar_compact('events', NULL);

Codecs: none, pglz, lz4, zstd (setting kingres_columnar.compression, default auto). Version 0.2 adds B-tree indexes (unique ones and primary keys included), a parallel scan, logical decoding of inserts and reuse of freed file space. kingresd preloads the library on every instance it creates (shared_preload_libraries = 'kingres_shard,kingres_ledger,kingres_columnar,pg_stat_statements'; kingres_columnar and pg_stat_statements are left out when their library is absent from the installation). The list takes effect at a restart of the instance, so restart the standbys of a group before its primary. The Extensions tab of the Configuration page says whether each extension is preloaded.

Refused (SQLSTATE 0A000): UPDATE, DELETE and MERGE that match a row (the table is append-only; convert to heap, change, convert back, or drop whole partitions), row locks, TABLESAMPLE, CLUSTER, indexes other than B-tree, CREATE INDEX CONCURRENTLY and REINDEX CONCURRENTLY, foreign keys on or to a columnar table, row-level AFTER triggers, temporary and unlogged tables. Many tiny transactions make tiny stripes: load in big transactions and use columnar_compact. Other limits: no TOAST, serial and parallel scans only (no bitmap, index-only or parallel index scans), no vectorised execution, logical decoding covers inserts only (and doubles the log of a load at wal_level = logical), up to about 8.8 x 10^12 rows per table.

In a distributed database. A hash-distributed table can be columnar and bucket moves carry the access method (with kingres_columnar 0.2 or later; run kingres.columnar_compact afterwards, a move does not compact). The online variants of the table operations and a bucket split are refused for a columnar table, a reference table is always row storage, a ledger table cannot be columnar, and columnar tables in a distributed schema are not tested.

Function reference

Taken from the install scripts (kingres_sketch--1.0.sql, kingres_timepart--0.3.sql, kingres_columnar--0.2.sql) and the "SQL interface" sections of the READMEs. Internal helpers (names with __, aggregate support functions) are not listed.

kingres_sketch (schema kingres_sketch)

All functions are IMMUTABLE and PARALLEL SAFE; a NULL argument gives NULL unless the README says otherwise. Types: hll (precision 4 to 18), topn (capacity 1 to 100000), tdigest (compression 10 to 10000); each has casts to and from bytea.

Function or aggregate Arguments Result and purpose
hll_empty precision int DEFAULT 14 An empty sketch.
hll_hash anyelement The 64-bit hash of an element (bigint).
hll_add, hll_add_hash hll, anyelement / hll, bigint The sketch with an element or hash added.
hll_union, hll_fold hll, hll / hll, precision int Union (error 22023 if precisions differ); lower the precision.
hll_cardinality, hll_precision, hll_is_empty hll The estimate (bigint), the precision, whether empty.
hll_add_agg anyelement [, precision int] Aggregate: the sketch of the non-NULL inputs.
hll_union_agg hll Aggregate: union of sketches of one precision.
approx_count_distinct anyelement [, precision int] Aggregate: the estimate in one step (bigint); 0 over no rows.
topn_empty capacity int DEFAULT 1000 An empty summary.
topn_add, topn_union topn, anyelement / topn, topn Add an item; merge (error 22023 if capacities differ).
topn_list topn, n int DEFAULT NULL Table (item text, frequency bigint, max_error bigint), most frequent first.
topn_total, topn_capacity topn Number of items added; capacity.
topn_add_agg, topn_union_agg anyelement [, capacity int] / topn Aggregates.
tdigest_empty compression int DEFAULT 100 An empty digest.
tdigest_add, tdigest_union tdigest, x float8, weight bigint DEFAULT 1 / tdigest, tdigest Add a value; merge.
tdigest_quantile tdigest, q float8 or q float8[] The value at a fraction; NULL for an empty digest.
tdigest_rank tdigest, x float8 The estimated fraction of the weight at or below x.
tdigest_count, tdigest_min, tdigest_max, tdigest_compression tdigest Exact count, minimum, maximum; compression.
tdigest_agg, tdigest_weighted_agg, tdigest_union_agg x float8 [, compression int] / x float8, weight bigint, compression int / tdigest Aggregates.
approx_percentile q float8, x float8 [, compression int] Aggregate: the approximate value at fraction q.
self_test, sketch_kind, state_bytes, state_limit none / bytea Diagnostics: a text that must be equal on every node that exchanges sketches; the kind of a sketch's bytes; the memory of aggregate states in this backend and its limit.

Settings: kingres_sketch.state_memory_ceiling (superuser) and kingres_sketch.state_memory_limit.

kingres_timepart (schema kingres)

Execute rights are revoked from PUBLIC; an administrator grants them (the README lists the GRANT statements). Policy and history are read through the views kingres.timepart_policy, kingres.timepart_run and kingres.timepart_run_action; a role sees the rows of tables it owns.

Function or procedure Arguments Purpose
create_time_partitions rel regclass, partition_every interval, end_at timestamptz, start_from timestamptz DEFAULT now(), access_method name DEFAULT NULL, timezone text DEFAULT 'UTC' Creates the partitions from start_from to end_at.
drop_old_time_partitions rel regclass, older_than timestamptz, detach_only boolean DEFAULT false, timezone text DEFAULT 'UTC' Drops (or detaches) partitions older than a time; takes any partition, also a misaligned one.
timepart_set_policy rel regclass, partition_every interval, create_ahead interval DEFAULT '7 days', retention interval DEFAULT NULL, retention_action text DEFAULT 'drop', columnar_after interval DEFAULT NULL, columnar_sort text[] DEFAULT NULL, columnar_options jsonb DEFAULT NULL, timezone text DEFAULT 'UTC', run_every interval DEFAULT '1 hour', enabled boolean DEFAULT true Sets the policy of a table. retention_action is drop or detach.
timepart_unset_policy rel regclass Removes the policy.
timepart_plan rel regclass, as_of timestamptz DEFAULT now() What a run would do; changes nothing.
timepart_run (procedure) rel regclass, as_of timestamptz DEFAULT now(), phases text[] DEFAULT '{create,convert,retire}', INOUT run_id bigint DEFAULT NULL Runs the policy; superuser as the README states; cannot run in a transaction block.
timepart_due as_of_time timestamptz DEFAULT now() The tables whose policy is due (schema, table, time).
timepart_begin_run, timepart_finish_run rel regclass, as_of timestamptz, trigger text / run_id bigint The two ends of a run for a caller that drives the steps itself (a scheduler).
timepart_partitions rel regclass The partitions of a table with their state.
timepart_check min_ahead interval DEFAULT NULL, as_of timestamptz DEFAULT now() Table (schema_name, table_name, problem, detail); problems include ahead_low, last_run_failed, retire_blocked, default_partition_present.
convert_partition (procedure) parent regclass, part regclass, access_method name DEFAULT 'columnar', sort_by text[] DEFAULT NULL, options jsonb DEFAULT NULL Converts one partition. Needs kingres_columnar.
convert_old_partitions (procedure) parent regclass, older_than timestamptz, access_method name DEFAULT 'columnar', sort_by text[] DEFAULT NULL, options jsonb DEFAULT NULL Converts every partition older than a time.
timepart_dist_partitions rel regclass Distributed tables (0.3), superuser: the logical partitions with their bounds, leaves, columnar leaves and storage (heap, columnar or mixed).
convert_distributed_partition parent regclass, partition_name name, access_method name DEFAULT 'columnar', sort_by text[] DEFAULT NULL, options jsonb DEFAULT NULL Distributed tables (0.3), superuser: converts the leaves of one logical partition, one after the other on their nodes. convert_leaf converts one leaf and is called by it, not by hand.
timepart_adopt p_own_stamp boolean DEFAULT false Superuser: makes policies restored from a dump active.
timepart_grant_driver, timepart_revoke_driver role name Superuser. Gives a role, or takes from it, the EXECUTE to drive the maintenance of its own tables from its own session.
timepart_prune_runs, timepart_part_name see the README History clean-up (runs are kept for 90 days, at most 1000 per table); the name of a partition.

kingres_columnar (schema kingres)

Function Arguments Purpose
columnar_set_options rel regclass, compression text, compression_level int, stripe_row_count int, chunk_row_count int (all but rel default NULL = keep) Options for stripes written from now on; owner only.
columnar_options rel regclass The options in force.
columnar_info rel regclass Stripes, chunk groups, rows, bytes on disk and uncompressed, ratio, unreferenced_bytes.
columnar_stripes rel regclass One row per visible stripe.
columnar_compact rel regclass, min_rows int DEFAULT NULL Merges small stripes; returns the number of stripes written; owner only.
columnar_check fix boolean DEFAULT false Superuser. Any returned row means "not clean".
columnar_check_clean none Superuser. True only if every table was checked and nothing was found.
columnar_check_indexes rel regclass Superuser. Cross-checks the indexes of a table against its stripes.
columnar_reconcile none Superuser. Deletes catalog rows of files no relation uses; returns how many (NULL if it did nothing).
columnar_write_paths reset boolean DEFAULT false Diagnostic counters of the write side (superuser, grantable).
columnar_identity, columnar_creating_xid, columnar_table_xid rel regclass Identity and transaction ids stored in the metapage (need SELECT).
columnar_is_columnar_am, columnar_on_drop, columnar_check_ddl, columnar_finish_rewrites see the README Internal guards.

Settings (README, "Settings"): kingres_columnar.compression (auto), compression_level (3), stripe_row_count (150000), chunk_row_count (10000), write_buffer_memory (128MB), enable_custom_scan and enable_chunk_skipping (on); the others are developer settings.

Sources

Clone this wiki locally