Columnar¶
Columnar stores a table the way kdb+ stores a partitioned splayed table.
- Layout: one directory per partition and one file per column.
- Symbols: enumerated to int32 codes against a domain that the source's tables share.
- Today's partition: appendable, and every local reader shares its pages through the page cache. This is kdb+'s RDB.
- Past partitions: sorted by symbol,
p#-indexed and block-compressed. This is kdb+'s HDB.
Queries follow q-sql: where constraints apply left to right, then by, xbar and aggregates. A query reads only the columns it references.
It is a separate container. It does not replace tables, which stay SharedData's row store. The
SharedData.columnar() factory imports the engine only when requested. The aim is kdb+'s capabilities without the q language: what q
expresses in its syntax is a Python call here.
from SharedData.Columnar import Columnar, aj, wj, lj, fby, lit, xbar
from SharedData import ColumnarQ as q # q's built-in functions, joins, table utilities, q-sql on DataFrames
from SharedData.ColumnarServer import ColumnarServer, ColumnarClient, Tickerplant, replay, RealtimeSubscriber, Replica
from SharedData.ColumnarKdb import KdbServer, KdbConnection, serialize, deserialize # kdb+'s own wire protocol
| kdb+ capability | Where |
|---|---|
| splayed / partitioned (date, month, year, int) / segmented (par.txt) databases, sym enumeration, attributes, compression, encryption at rest | Columnar, ColumnarStorage |
| RDB → HDB end of day, compressed append, map-on-demand, object storage (S3/MinIO) | Columnar |
q-sql select exec update delete, by, xbar, fby, select[n], select[>c], select distinct, virtual i and partition columns |
Columnar.select/exec/update/delete |
| q-sql on in-memory tables | ColumnarQ.select/exec_/update/delete |
keyed tables, upsert, foreign keys, link columns, t[k] |
Columnar(keys=...), fk:, link: |
| q's aggregate, uniform, moving, time, string, set, search and list functions | ColumnarOps.aggregate, ColumnarQ |
joins aj aj0 ajf ajf0 asof wj wj1 lj ljf ij ijf ej pj uj ujf |
ColumnarOps, ColumnarQ, Columnar.aj/wj |
| peach over partitions, map-reduce aggregation | Columnar (thread pool) |
IPC server and client (sync, async, callbacks, timer, auth, TLS), tickerplant, -11! log replay, RDB process |
ColumnarServer |
dbmaint: add/drop/rename/copy/cast/reorder columns, rename table, set/clear attributes, amend, .Q.chk, sym compaction |
Columnar, Columnar.chk, Columnar.compact_domain |
kdb+ IPC (-8!/-9!, handshake, compression, .u.upd/.u.sub), q and PyKX clients |
ColumnarKdb |
HTTP (.z.ph/.z.pp), WebSocket (.z.ws), .z.pw auth, -T query timeout, -w limits, deferred replies (-30!), unix sockets |
ColumnarServer |
logging and replication (-l mutation log, -r replica) |
ColumnarServer(mutation_log=...), replay_mutations, Replica |
DARE: password-protected master key files (kdb+'s format, -36!), encrypted symbol domains, nothing plaintext on disk |
ColumnarStorage.load_master_key, encrypt='all' |
When to choose it¶
- High-volume, append-only records, such as ticks, quotes and trades. Most queries read a few columns of one symbol or one time range.
- Disk and S3 footprint, which matters more than in-place updates: sealed partitions are sorted and compressed.
- Analytics by symbol and time:
select … by,xbarbars and as-of joins.
Use a Table when other SharedData components (the HTTP API, Dashboard, SharedNumpy users) must read the data: they know Tables, not Columnar.
Measured¶
Real data from a benchmark host (THETADATA/QUOTES of 2026-11-11, Table row 88 bytes, symbol |S32). Scripts live outside the repo;
the numbers below are from a 2M-row and a 10M-row mid-day slice, not a full day.
| Bytes/row | |
|---|---|
| Table | 88 |
| Columnar open partition (enumerated, uncompressed, before capacity) | 60 |
| Columnar sealed (sorted by symbol, time; zstd-3, 128 KB blocks), 2M-row sample | 10.7 |
| Same, DATABENTO/BBO1S (Table 110 B/row), 2M-row sample | 8.0 |
Query timings against a numba floor are in the performance section.
Open or create¶
c = Columnar('MarketData', 'RT', 'DATABENTO', 'BBO1S',
names=['date', 'symbol', 'bid', 'ask', 'bidsz', 'venue', 'note'],
formats=['<M8[ns]', 'sym', '<f8', '<f8', '<i4', 'sym:venue', 'str'],
attributes={'symbol': 'g', 'date': 's'}, # g# while open, p# on symbol at seal
partitioning='daily', compression='default')
r = Columnar('MarketData', 'RT', 'DATABENTO', 'BBO1S') # existing table, read-only (mode='r')
Existing SharedData routines can use the local factory:
from SharedData.SharedData import SharedData
sd = SharedData(__file__, user='master')
c = sd.columnar('MarketData', 'RT', 'DATABENTO', 'BBO1S',
names=['date', 'symbol', 'bid', 'ask'],
formats=['timestamp', 'sym', 'float', 'float'])
r = sd.columnar('MarketData', 'RT', 'DATABENTO', 'BBO1S') # a fresh, read-only handle
The factory defaults to the instance's user and dbfolders[0]; user= and root= override them. It forwards
the constructor's options, validates a supplied schema even if another handle already exists, and keeps read and
write handles separate. Other containers and clients do not load Columnar unless the factory is called.
- Address:
{DATABASE_FOLDER}/{user}/{database}/{period}/{source}/columnar/{tablename}. Passroot=to place it elsewhere, andshareddata=to take its user. - Validation:
databaseandperiodare checked against SharedData's lists, and the database's key columns must be in the schema. Their uniqueness is not enforced: a kdb+ splayed table is not keyed. - Mode: passing a schema creates the table, or validates an existing one (names and formats; the stored attributes, partitioning and compression win), and opens it with
mode='w'. Without a schema the table opens withmode='r', where every write raises. - Windows: writers work. Windows cannot extend a file another process has mapped, so there readers map only
for the duration of a query,
col()returns a copy, and a writer retries growth for up to 30 s (SHAREDDATA_COLUMNAR_EPHEMERAL_MAPS=1gives the same mode elsewhere). - Formats:
- q type names:
boolean guid byte short int long real float char symbol timestamp month date datetime timespan minute second time string - numpy dtypes:
<f8,<i4,u1,?,|Sn,|V16,<M8[ns|ms|D|M],<m8[ns|ms|s|m](values finer than the unit raise) sym, orsym:<domain>for a separate domainqtimestamp/qdatetime: native q values (int64 nanoseconds / float64 days since 2000.01.01). These explicit formats preserve q's full timestamp range and datetime double precision. The oldertimestamp/datetimenames retain their NumPy ns / ms representations.str(nested chars),list:<type>(q's nested lists of one type),any(q's mixed lists: any value per row)fk:TABLE/link:TABLE(orfk:DB/PERIOD/SOURCE/TABLE): foreign key into a keyed table, link columnpartitioning:'daily'(default),'monthly','yearly','int'(an integer partition column, kdb+'s int-partitioned database) orNone(one splayed partition).keys=[...]on a splayed table makes it a keyed table (see below).segments=[dir, ...]: kdb+'spar.txt. Partitions are spread round-robin by date over these directories; the schema and lock stay in the main root. As in kdb+, one date may span segments:append(rows, segment=k)writes to segmentk; the copies are partitionsD,D@kand every query reads them all, in par.txt order.- Databases: a SharedData database name (
MarketData,Symbols, ...) brings its period list and required key columns; any other name is a plain kdb+ database directory with no required column (Columnar('db', 'any', 'src', 't', names=['x'], formats=['<i8'], partitioning=None)). encrypt=True: sealed blocks are AES-256-GCM encrypted and the symbol domain is AES-256-CTR encrypted (kdb+ 4.0 data at rest, which also encrypts enumeration domains). The master key comes fromload_master_key(path, password)(q's-36!: a password-protected key file in kdb+'s own format,openssl aes-256-cbc -pbkdf2 -iter 50000;create_master_keywrites one), elseCOLUMNAR_KEY(hex or base64), elseCOLUMNAR_KEY_FILE(a raw key, or a protected one opened withCOLUMNAR_KEY_PASSWORD). Keys are never stored; a fingerprint detects a wrong key and block ids are authenticated.encrypt='all': as above, and nothing is ever plaintext on disk: every partition is born sealed (compressed and encrypted, appends extend it), and rewrites stage their plaintext in RAM (COLUMNAR_SCRATCH, else/dev/shm).compression: also a dict per column, kdb+'s.z.zdper column:{'default': 'zstd', 'px': ('gzip', 9), 'flags': None}; a triple sets that column's logical block size too, as kdb+'s per-file(block; algo; level):'px': ('zstd', 3, 16).compression(table default):'default'is zstd level 3 whenzstandardis installed (pip install shareddata[columnar]), else lz4. The codec actually chosen is stored in the schema.- Also accepted:
'zstd','lz4','gzip','snappy','qipc',(algo, level), orNone. WithNone, sealed partitions are sorted but stay plain and mapped. 'snappy'is kdb+'s algorithm 3. It is a compiled implementation of the snappy block format, and its streams decode with the reference library and the other way round.'qipc'is kdb+'s algorithm 1: q's IPC compression, applied per block.sort_by: the order the seal sorts by. The default is thep(else the firstg) column, then thescolumn.
Writing¶
res = c.append(df) # DataFrame, dict of arrays, structured array (Table records) or list of dicts
res.rows, res.ranges # {'2026.11.15': (start, end)} committed rows per partition
c.import_table(table_records, batch_rows=1_000_000) # copy a Table's rows (extra fields such as mtime dropped)
c.seal() # end of day: every open partition whose day (UTC) has ended
- Columns: an append must give exactly the schema's columns, as kdb+'s
insertrequires. Values that do not fit the column type (1e30 or 2**40 into<i4, 1.5 into an int column) raise instead of wrapping or becoming nulls; the int null itself (the type minimum) may be written directly. Values are checked and cast first, and nothing is written when a check fails. - Routing: rows go to partitions by the partition column, in input order. Each partition is published by one commit; several partitions are not one transaction, and
rangesreports what was committed. - Late rows: by default a row for a sealed partition raises.
late='reopen'republishes that partition as an open version first; the nextsealsorts it again.late='append'appends to the sealed partition and keeps it sealed and compressed, as kdb+ 4.x appends to compressed files: full compressed blocks are copied and only the last block is recompressed. The appended rows are in arrival order, sop#,g#,u#andsorted_withinare dropped (kdb+ drops an attribute an append breaks);s#stays where the column is still sorted. The nextsealrestores them.
seal() without arguments seals the dated partitions whose period has ended; a splayed table is sealed with seal(partitions='splayed').
Copying existing history and processing large results¶
import_table captures a SharedData Table's committed read view before batching, so preallocated capacity and
later appends are excluded. Concurrent in-place updates are not isolated: use a closed partition or coordinate
its writers when a stable copy is required. Only fields declared in the destination schema are copied. Include
mtime explicitly to preserve receive/update timestamps alongside event timestamps and raw symbol values.
tape = sd.table('Trades', 'RT', 'THETADATA', 'FULL/20261116')
history = sd.columnar('Trades', 'RT', 'THETADATA', 'HISTORY',
names=list(tape.dtype.names),
formats=['sym' if name == 'symbol' else tape.dtype[name].str
for name in tape.dtype.names],
attributes={'symbol': 'g'})
history.import_table(tape, batch_rows=250_000) # copy once into a new history container
history.seal()
for batch in history.iter_batches(['date', 'symbol', 'price', 'qty'],
where=[('symbol', '=', 'AAPL')], batch_rows=100_000):
consume(batch) # each result is a flat DataFrame
# Transfer selected fields to an existing, writable container without collecting the results:
target.import_batches(history.iter_batches(target.names, batch_rows=100_000))
iter_batchesprojects names or{alias: column}mappings, including virtual and dereferenced fields. It reads output values for at mostbatch_rowsrows at a time; aggregations and computed projections useselect.- Batches follow partition and storage order. Even for a keyed table they are flat frames with keys as columns.
Symbols default to strings;
sym='code'or'category'is also supported (categories are local to each batch). - Each partition is pinned when reached. Later appends, seals or rewrites do not change that partition's captured
rows. For one captured set of versions/counts across all partitions, call
snapshot()first and iterate it. Pinning opens all column files to retain their versions and can fetch remote column files. In-place amendments to an open plain file are not isolated by a pinned version/count. wherekeeps full-partition semantics, includingfbyand callables. Filters can allocate partition-sized masks or row indices; batching bounds result materialization, not every filter's working memory.start/endprune partitions, likeselect; usewherefor exact timestamp bounds. Close an unfinished iterator to release its pinned partition promptly (contextlib.closingworks).- Imports consume batches lazily and commit each one separately. A later error leaves prior batches committed; retrying a whole import can duplicate rows. They provide no durable cursor or exactly-once Kafka checkpoint.
batch_rowsmust be a positive integer. Empty inputs import zero rows; empty query results yield no batches.
The seal is kdb+'s .Q.dpft. It runs under the writer lock, so no append can land in the version being sealed. It:
1. Sorts each partition by sort_by (when the table has one: a p/g/s attribute or an explicit sort_by; otherwise rows keep their order and no p# is written): a stable counting sort by symbol value, then by time (other sort columns: a stable sort with nulls first, as xasc).
2. Writes p# on the first sort column.
3. Records which columns are globally sorted (s#) and which are sorted within each p# group.
4. Builds the g# and u# indexes.
5. Compresses every column in independent blocks, and publishes the new version atomically.
u# fails the seal (u# fail) when its column is not unique.
update, delete, set_attr and clear_attr rewrite each affected partition as one new version, in the same state. A sealed partition is rebuilt and sealed in a private staging directory, so either the new sealed version is published or nothing changes (a u# fail, for example, leaves the partition as it was). This differs from kdb+, which rewrites column files in place. add_column republishes the open partitions with the new column; sealed partitions read it as typed nulls. rename_column and drop_column are one atomic schema write: the schema maps each column name to its files, and a dropped column's file name is retired, so a later column with the same name never reads old data. The partition column cannot be updated.
Keyed tables and references¶
sec = Columnar('Symbols', 'D1', 'REF', 'SEC', names=['symbol', 'sector', 'lot'], formats=['sym', 'sym', 'long'],
partitioning=None, keys=['symbol'])
sec.upsert(df) # existing keys replaced in place (row positions stay), new keys appended
sec.insert(df) # raises if a key exists (q's insert into a keyed table)
sec.get('IBM') # q's kt[`IBM]: the row as a dict, or None
trade = Columnar('MarketData', 'D1', 'SRC', 'TRADE', names=['date', 'symbol', 'sec', 'px'],
formats=['timestamp', 'sym', 'fk:Symbols/D1/REF/SEC', 'float'])
trade.select(['px', 'sec.sector'], where=[('sec.lot', '>', 50)]) # q's sec.sector: foreign-key dereference
- Keyed tables are splayed, as in kdb+ (a keyed table cannot be partitioned). Within one upsert batch the last row of a key wins.
select()of a keyed table is keyed (indexed by the keys). - An
fkcolumn stores the row position of a key in the referenced keyed table; it reads as the key value, an unknown key raises (q's cast error), a null is the int null.linkcolumns store row ids into any splayed table.col.fielddereferences either, inselect,whereandby.
q's functions and q-sql on in-memory tables¶
ColumnarQ holds q's built-in functions as numpy functions with q's null rules, usable in expressions:
- uniform and running: deltas ratios sums prds maxs mins avgs fills prev next_ xprev differ rank iasc idesc asc desc xrank ema rotate
- moving: mavg msum mmax mmin mcount mdev
- statistics: cor cov scov sdev svar
- math: abs_ neg signum floor ceiling sqrt exp log xlog xexp reciprocal mod div
- time: date month year mm dd hh uu ss_ minute second time week
- search and set: bin binr find where distinct union inter except_ in_ within cross group
- strings: like (q patterns * ? [abc] [^abc]), ss ssr sv vs lower upper trim ltrim rtrim string
- lists: cut sublist take drop raze first last, and guid(n)
- tables: ungroup xgroup xasc xdesc xcol xcols xkey upsert meta
- joins: ajf ajf0 asof pj ljf ijf ujf uj_keyed
- .Q and .h utilities: fmt f fu fc id_ sha1 md5 btoa atob ts, h_cd h_td h_xd h_ed h_xs h_hc h_hr h_hu h_hug h_ty
h_hy h_hn h_he h_hp h_htc h_hta h_htac h_ha h_hb h_html h_xmp h_text (and Columnar.ind, Columnar.par,
Columnar.view)
c.update({'d': (q.deltas, 'px')}, by='symbol') # q: update d:deltas px by sym
c.select({'m5': (lambda p: q.mavg(5, p), 'px'), 'vwap': ('wavg', 'sz', 'px')}, by='symbol')
q.select(df, {'n': ('count',)}, by='sym') # q-sql on a DataFrame, same engine and semantics
q.update(df, {'flag': (lambda x: x > 0, 'px')}) # may add columns, like q
Under by, an expression runs once per group (as q): an atom result is a custom aggregate, a vector becomes one list
per group, and update ... by writes each group's vector back to its rows. fby also takes a function.
Aggregates have q's result types: boolean, byte, short and int sum to int, long to long, real to real; prd of ints is
an exact integer; avg, dev, var, med are float.
- Added in round 7:
- Temporal values: aggregates, running and moving functions on temporals use q's underlying value (days since 2000.01.01 for dates, etc.) with KX's result types. Dates past 2262 compare, sort,
binand as-of join in their own unit. - Iterators:
each_left/each_right; KX's converge rules forover/scan(with an iteration cap);priorseeds; null rules on numpy fast paths. - Collections and casts:
asc/iascon dicts and tables,take/dropby keys and column names,flipextends atoms,castto a list of types, andtype_recognises the kdb+ IPC wrappers. - Added in round 6:
- Text and conversion:
castandtok(q's$matrix and text parsing),.j(j_j,j_jd,j_k),.h(h_cd,h_td,h_xd,h_ed). - Iterators:
each,over(including converge),scan,prior. - Small builtins:
bar,pad,flip,type_,key. - Grouped kernels:
prev,next_andxprevingrouped. - Byte semantics for q text:
count,likeandsswork on UTF-8 bytes. - KX rules now followed:
wsumof two integer lists is a float (/ref/sum#wsum), andmsumkeeps q's result types. - Added in round 5:
hash(a stable 64-bit hash withmatchequality; KX publishes no algorithm for its ownhash, so the values differ from kdb+'s),hg/hp(.Q.hg/.Q.hp), the moving family andavgsingrouped(update … bywithfunctools.partial(q.mavg, 3)), q'sdivtype matrix including temporals,xbarin the column's own temporal unit, and q's temporal rules forabs,neg,signum,allandany. - Added in round 4:
and_,or_,not_andmatch(q's~, exact; nulls follow KX).wavg/wsumas functions.grouped(fn, x, gid, ng):sums deltas prds ratios maxs mins fillsper group in one pass, whichupdate … byuses. Loaders:load_text(q's0:, delimited or fixed width, q type chars, q null parsing),load_fixed(1:, binary records), andfs/fsn(.Q.fsline-aligned chunk streaming).
Parallel and map-reduce execution¶
Partitions are filtered and gathered on a thread pool, kdb+'s peach over an HDB (SHAREDDATA_COLUMNAR_THREADS,
default min(8, cpus); 1 disables). A grouped or plain query whose aggregates are all decomposable (count sum avg min
max first last wavg wsum prd) over several partitions is map-reduced: each partition is aggregated, then the partials
are combined, so memory follows the number of groups, not rows, and the result equals the single-pass one.
Reading: q-sql¶
c.select(['date', 'bid'], where=[('symbol', '=', 'ESZ6'), ('date', 'within', (t0, t1))])
c.select({'n': ('count',), 'vwap': ('wavg', 'bidsz', 'bid')}, by='symbol')
c.select({'o': ('first', 'bid'), 'h': ('max', 'bid')}, by={'symbol': 'symbol', 'bar': ('xbar', '5min', 'date')})
c.select(where=[('bid', '=', fby('max', 'bid', 'symbol'))])
c.exec('bid', where=[('symbol', '=', 'ESZ6')]) # an array
c.exec(('sum', 'bidsz')) # a scalar
c.update({'symbol': lit('ESH7')}, where=[('symbol', '=', 'ESZ6')])
c.delete(where=[('bid', '<', 0)])
- Columns:
None(all), a list of names, one expression, or{name: expression}. An expression is one of: - a column name (a bare
stralways names a column; uselit('x')for a literal) - an aggregate tuple
('xbar', width, expr)(func, expr, ...), applied to the gathered arrays; when its arguments are aggregates it is evaluated per group on their results (q'smax[px]-min[px]):{'spread': (np.subtract, ('max', 'px'), ('min', 'px'))}- a callable taking the gathered columns, with symbols decoded
- an unknown aggregate name raises (q's
'type), never passes through as text - Aggregates:
count sum avg min max first last med dev sdev var svar wavg wsum distinct prd, plusnunique(q'scount distinct). - Nulls are skipped as in kdb+, except
med, which (as q) sorts nulls first and counts them (med 0n 1 2is 1). Integer, unsigned and boolsumis exact int64 (uint64 for u8);avg,dev,var,med,prdandwavgare float.prdof nothing is 1. min/maxof a group with no value return q's identities:0w/-0wfor floats,0W/-0W(type max, min+1) for ints and times.wavgwith zero total weight is NaN.- On symbols:
first,last,distinctandnuniquework on the stored codes;minandmaxcompare symbol values; the results are decoded. Arithmetic aggregates on symbols raise. distinctreturns the distinct values in first-occurrence order (an array per group).countcounts rows, nulls included.firstandlastare positional and keep nulls and the column's type.sumof an all-null group is 0.where:(column, op, value)with op one of= == <> != < <= > >= in 'not in' within like null 'not null', or a callable that takes the current rows and returns a mask.- Constraints apply in the order written, each to the rows the previous ones kept.
- An index (
p#,g#,u#,s#) only speeds up a constraint in its own position; it never reorders them. - Nulls compare as in q: a null equals a null and sorts below every value (
x = 0nfinds NaN rows,x < 0includes them). Integer nulls and NaT are already the type minimum. - Numbers compare by value, never cast into the column's type: an int column never equals 1.5, an int8 column is below 200. Floats use q's tolerant equality (relative 2^-43, as in kdb+), so
0.1 + 0.2 = 0.3;in, like q's?, is exact; float columns therefore never use an index. Integer columns against integer literals compare exactly (no float rounding of large int64 values). withinis inclusive at both ends.likeis a glob on symbols or strings. Ordered comparisons on symbols compare values ('' lowest).- Unknown symbols match nothing.
- A value may be an
fby. - Nested columns (
list:<type>,list:sym,any):('tags', 'has', v)(q'sv in/: tags),('tags', 'has all', [v, w]),('tags', 'match', [v, w])(whole list, q's~),=/<>against a list,('tags', 'count', ('>', n)), andnull/not null(an empty list is the null). - Per partition, as in kdb+ on a partitioned table:
where(includingfby) and groupedupdateare evaluated within each partition. - Constraints on the partition column, or on the virtual column
part(the partition's start, as kdb+'s virtualdate:('part', '=', '2026-03-01')), prune partitions first.partcan also be selected or grouped on. start/endselect partitions by date.- Result order:
- Partitions come in ascending order.
- Rows within an open partition are in arrival order; within a sealed one, in sort order.
byresults are keyed by the grouping columns and sorted by key, with symbols sorted by value.- Inside a group, row order is kept.
- A plain column under
bygives a list per group (select bid by sym). Expressions underbysee decoded symbols. select by symwith no columns gives the last row per group. Foreign keys andlist:symread as their values there and inaj/wjresults, as everywhere else.- Aggregates without
bygive one row. Next to plain columns, they are repeated on every row. - Symbols:
sym='category'(default forselect) returnspd.Categorical, whose categories are only the values present, sorted, with code 0 as''.sym='str'returns strings.sym='code'returns the stored int32 codes, which are only comparable within one domain (c.info()['domains']gives its uuid). - Raw columns:
c.col('bid', '2026.11.14')returns one column of one partition. It is a zero-copy view for a plain column, and decompressed blocks for a sealed one.
Joins¶
Module functions take DataFrames. The Columnar methods use the table as the right side and load only the symbols and
partitions the left table needs; a caller's where is applied first, unchanged, and the left table's symbols after it. Null
keys match null keys (None, NaN and '' are the one null symbol).
| Function | kdb+ | Semantics |
|---|---|---|
aj(on, left, right) / c.aj(on, left, columns=) |
aj |
For each left row, the last right row with the same on[:-1] keys and time <= the left time. Equal right times give the last arrival. Left order and left time are kept. Common columns take the right value where matched. Unmatched rows get typed nulls of the right column's type (ints keep int64, strings get ''); values are gathered by row index, never through float. c.aj matches each left row only within the partition holding its time, as kdb+ joins an HDB one date at a time. |
aj0 |
aj0 |
As aj, but the time column holds the matched right time. |
wj((w0, w1), on, left, right, {name: (agg, col)}) |
wj |
Closed windows, plus the value prevailing at the window start (c.wj searches earlier partitions for it). count counts rows (nulls included); first/last keep the type and nulls; integer sum is exact; min/max skip nulls (q identities when none); avg is float. An empty right table gives empty windows. c.wj windows may span partitions. |
wj1 |
wj1 |
Only the rows inside the window. |
lj(left, right, on) / ij |
lj / ij |
Right must be keyed (unique on on, else an error). Right values win where matched; typed nulls for unmatched right-only columns. ij keeps matched rows only. |
ej(on, left, right) |
ej |
Every matching pair. |
uj(left, right) |
uj (unkeyed) |
Rows of both, columns united; a column one side lacks gets that type's typed null. |
Attributes and nulls¶
| Attribute | Open partition | Sealed partition |
|---|---|---|
s# (fixed-width columns; use p#/g# for symbols) |
A flag per column. An append keeps it only when the batch is sorted, starts at or above the last value and has no NaN (NaT and int nulls order lowest, as in q). It is cleared before the rows are committed. | Kept only if the column is still globally sorted after the seal sort. A column sorted within each p# group is recorded as sorted_within, so symbol = X, date within … binary-searches. |
g# (sym columns) |
Chains: {col}.gl holds the last row of each code and {col}.gp the previous row of each row. |
A CSR index (#gk, #go, #gr) for a g column that is not the p# column. |
p# |
— | The first sort column: one (key, start, end) range per value. |
u# |
Declared only. | Sorted values plus row ids. The seal fails if the column has duplicates. |
Typed nulls:
| Type | Null |
|---|---|
| float | NaN |
| signed int | the minimum value (0Nh, 0Ni, 0Nj) |
| time | NaT (int64 min, the bits of kdb+'s 0Np; timestamps count from 1970, not 2000) |
| sym | code 0, '' |
| str | '' |
| guid, fixed bytes | all zero |
| unsigned int, bool | none (q has no byte or boolean null) |
Missing pandas values convert to these on append. Timestamps are stored as naive UTC; tz-aware input is converted.
Concurrency, crash safety, durability¶
- Writers: one per table at a time, serialized across processes by an OS file lock,
{source}/columnar/.{table}.lock. It is not inside a version directory, and the OS releases it when the holder dies. - Every writer re-reads
CURRENTunder the lock. - A symbol domain has its own lock. The lock order is table, then domain, never the reverse.
- One writer host per source: two hosts writing one source would assign different codes.
- Readers take no lock.
- Each partition has a 64-byte
.partheader whosecommittedword (int64 at offset 8) decides visibility. - The writer stores every column value, string byte, offset and
g#link, then issues a release fence (Utils.table_release_fence, the fenceSharedNumpyuses), then storescommitted. - A reader loads
committedonce per partition per query, issues an acquire fence, and reads at most that many rows of every column. Column files only grow, so a reader remaps when its map is shorter. g#chains:- The writer stores row
r's previous link before it publishesras the head of its code. Links are stored as row+1, so zero-filled growth means "none". - A reader reads the head once, skips rows at or beyond its
committed, checks that every row it returns holds the code and that links strictly decrease, and falls back to a scan of the committed rows otherwise. - A writer that dies mid-append leaves
pending != committed. Rows pastcommittedare invisible. The next writer rebuilds the chains with the.partwordidxseq(offset 40) odd for the whole rebuild; readers that see it odd, or see it change during their walk, scan instead. Then it overwrites them. - Domains:
- The domain's
countcommits its symbols the same way. A lookup never returns a code at or above the count it loaded, and misses are re-checked under the domain lock. - A crashed domain append leaves
pending != countin the header; the next writer rebuilds the hash from the committed symbols before adding any. Readers map the domain read-only. - Each domain has a uuid. The table records it at creation and refuses to open against a replaced domain.
- Versions:
- Version numbers are above every directory on disk, so an orphan left by a crash is never reused.
CURRENTalso carries a randomgen, and a version's directory isv{n}_{gen12}: a partition dropped and recreated never reuses a path, so a reader that opens a column of the old version lazily fails and retries instead of mixing generations. Snapshots do not follow liveg#chain files (they scan their pinned rows). - Every structural change writes
v{n+1}.tmp, fsyncs its files and the directory, renames it tov{n+1}, then replacesCURRENTwithos.replaceand fsyncs the directory again. A crash before the replace leaves the old version current; the staging directory is removed later. - The previous version is kept until the next change, so a reader that opens columns lazily can finish.
- Every read re-checks
CURRENTand retries a partition up to 4 times. After that it raisesColumnarError('… changed repeatedly; retry the read'). snapshot()opens every file at once, so it stays readable across any number of later changes on Linux.vacuum()removes every superseded version.- Durability: an append is visible to other local processes at once and survives a process crash.
- It survives a power loss only with
append(..., durable=True). That msyncs the domain, then the column data, then storescommittedand msyncs the header. flush()msyncs the open partitions.- The seal and rewrites fsync before they publish.
Files¶
Little-endian throughout. Plain arrays start at offset 64.
| File | Header (64 bytes) | Payload |
|---|---|---|
{col} plain column |
magic 'SDCOL001', dtype |S16 (numpy str), itemsize <i8, reserved |
values; capacity = (size − 64) / itemsize |
{col}.z compressed |
magic 'SDCOLZ01', algo u1 (1 lz4 block, 2 zstd frame, 3 zlib, 4 snappy, 5 q IPC with a raw/compressed flag byte), level i1, block_log2 u1, pad 5, dtype |S16, rows <i8, raw_bytes <i8, nblocks <i8, index_off <i8 |
blocks of 2**block_log2 raw bytes, each compressed alone, then nblocks int64 cumulative compressed ends at index_off |
{col} + {col}# (str) |
plain or .z |
int64 end offsets, plus the UTF-8 bytes |
.part |
magic 'SDPART01', committed <i8, pending <i8, state <i4 (0 open, 1 sealed), version <i4, sflags <u8 (bit i = s# of .d sbits[i]), idxseq <i8, reserved |
— |
{table}/.d |
json schema: names, formats, attributes, partitioning, sort_by, compression, physical (column name -> file name), retired (file names of dropped columns), domains (name -> uuid) |
— |
v{n}/.d |
json: file names, formats, state, compression, sbits, sorted, sorted_within, parted, attrs (file names) | — |
CURRENT |
json {"version": n, "state": "open"/"sealed", "gen": uuid}; the version lives in v{n}_{gen[:12]}/ |
— |
_sym/{d}.hdr |
magic 'SDSYM001', count <i8, hash_gen <i8, uuid |S16, pending <i8, reserved |
— |
_sym/{d}.dat, .off, .h{gen} |
plain columns | bytes; int64 end offsets (code c is [off[c-1], off[c])); int32 open-addressing hash, −1 empty, djb2 of the bytes, linear probing, power-of-two size, load ≤ 1/2 |
{col}.gl, {col}.gp |
plain columns | int64 g# heads by code; previous links by row |
{col}#p.npy etc. |
numpy .npy |
sealed indexes, mapped with np.load(mmap_mode='r') |
Segments and object storage¶
segments=[...] spreads partitions over disks round-robin by date (kdb+'s par.txt); every operation follows the
partition to its segment. upload() ships sealed partitions (immutable v{n}_{gen} files, CURRENT last), the symbol
domains and the schema to S3/MinIO through SharedData's IO.AWSS3; on another host list_remote() and fetch() bring
missing or newer sealed partitions (checking the domain uuid, refreshing a grown domain), which queries then map like
local ones. Columnar(..., remote=True) reads through: a partition is listed from object storage and, on first
touch, only its metadata comes down; each column is fetched the first time a query reads it (kdb+ object storage
reads only what a query touches, through a local cache). fetch(p, columns=[...]) does the same explicitly.
IPC, tickerplant and real-time database¶
srv = ColumnarServer(root=..., port=5010, ssl_context=ctx).start() # token from COLUMNAR_TOKEN
srv.functions['vwap'] = lambda sym: ... # a server function
srv.timer(1.0, lambda now: ...) # .z.ts
h = ColumnarClient(port=5010) # hopen
h.select(['MarketData', 'RT', 'SRC', 'QUOTES'], columns=['px'], where=[('symbol', '=', 'IBM')])
h.send('append', [...], rows=df) # async (neg h)
tp = Tickerplant('/logs', server=srv, rdb_root=...) # tick.q
h.call('upd', [...], rows=df) # .u.upd: log, publish, RDB append
tp.end_of_day() # .u.end: notify, seal, roll the log
replay('/logs/tp2026.11.16.log', lambda table, rows: ...) # -11!, stops at a torn tail
RealtimeSubscriber(ColumnarClient(port=5010), [[...]], root=...) # r.q
- Frames are
CQ+ type (sync, async, response, error) + flags (lz4 over 2000 bytes) + length + BSON; numpy arrays, DataFrames and times travel typed. No pickle: a peer never makes the other side run code, so functions are registered on the server (as q functions are defined there) and referenced by name. - A server without a token binds only to loopback. Hooks
on_open,on_close,on_sync,on_asyncplay.z.po,.z.pc,.z.pg,.z.ps. Errors come back to the caller (q's signal) and the connection survives. - Publication never blocks the tickerplant: every connection has its own outbound queue and sender thread;
server.pending()/server.flush()are q's.z.W/ flush.max_memory_bytesrefuses requests (wsfull) above a process RSS;server.workspace()reports it (q's.Q.w). - Subscribers may filter by symbols;
end_of_daybroadcastsendand seals the ended date's RDB partitions (even before UTC midnight).subanswers(count, log)atomically with registering, soRealtimeSubscriberreplays the log up to that count and then applies what it buffered (r.q's handoff); its state file stops a restart from applying a record twice. Callbacks run on their own thread, so a callback may call the same connection. ColumnarServer(mutation_log=path)is q's-l, write-ahead: every mutation (append, upsert, update, delete, seal, and server functions named inserver.mutating) is logged before it applies, and a failed one gets an abort record (a failed multi-partition mutation has no effect, so the abort is exact);mutation_log_sync=Truefsyncs each record (q's-L);roll_mutation_log(path)starts a new log at a checkpoint and replay follows the chain;replay_mutations(path, root)rebuilds a database from it (a torn tail is cut), andReplica(ColumnarClient(...), root=...)is-r: it catches up from the log, then follows live. Each mutation record carries a token of the state it touches (the target partitions' versions and commit words), and adonerecord follows a successful apply. On start, the server resolves the last mutation that has no outcome before it serves requests:- If the state still matches the token, the mutation never landed, so it is applied now.
- Otherwise it already landed, and only
doneis written.
So each logged mutation is applied exactly once across a crash. There are two limits:
- A keyed upsert that only rewrites existing keys has no token change, so it is re-applied. That writes the same
values, so the result is unchanged.
- A multi-partition append cut off by a crash counts as applied. Multi-partition appends are atomic on errors, not
on crashes.
- http_port=0 adds HTTP (POST /call, JSON in and out: .z.pp; GET /call?req=<json> or
GET /?op=select&table=db/period/source/table&columns=a,b: .z.ph, overridable with on_http_get) and WebSocket on
the same port (.z.ws; JSON
text frames or CQ binary frames; sub pushes updates). on_auth(user, token) is .z.pw; query_timeout is
-T (a stop error); max_result_rows and max_message_bytes are -w (wsfull); a server function may
return a Deferred and reply later (-30!); unix_path= serves a unix domain socket (Linux and macOS, as kdb+).
Messages of any size travel (arrays over 1 MB go after the BSON document, payloads over 4 GB span frames).
Native q disk files¶
SharedData.ColumnarDisk adds a native disk path alongside the live Columnar store.
New databases created with KdbTable.create contain native q files directly. They
have no SDCOL headers, JSON .d, version directories or private domain sidecars.
Existing live stores keep their format and transactional behavior; conversion is explicit.
from SharedData.ColumnarDisk import KdbTable
# NEW destination; existing directories/files are always refused.
native = KdbTable.create('/data/native-db', 'trade', {
'symbol': np.array(['IBM', 'MSFT'], dtype=object),
'price': np.array([201.5, 410.0], dtype='float64'),
})
native.vector('price').raw # read-only np.memmap, native float64 payload
native.select({'total': ('sum', 'price')}, by=['symbol'])
# Pin committed rows in all source partitions, then publish a NEW native database.
native = tape.export_kdb('/data/native-tape', table='trade', batch_rows=100_000)
again = Columnar.open_kdb('/data/native-tape', 'trade')
destination.import_kdb('/data/native-tape', 'trade', batch_rows=100_000)
The writer streams bounded record batches into a staging directory, writes shared
symbol domains and binary column-order files, fsyncs them, and publishes by atomic
no-replace rename. There is no spare capacity in exported columns. A failed conversion
does not publish a partial database or change the source. Publication currently needs
Linux renameat2 or Windows rename semantics. Import commits each batch independently.
The native path supports uncompressed fixed vectors (types 1, 2, 4–19), exact 2000-epoch
timestamp/datetime values, FF01 symbol files (.d and shared domains), modern 4096-byte
enum headers with int64 indices, reading legacy int32 enums, and legacy homogeneous
nested columns with raw # companions. Export preserves the partition directory names
and actual stored time columns. It does not synthesize q's virtual partition column.
Native enum indices remain int64 at the disk boundary; they are never narrowed to the
live store's int32 codes. Attributes are deliberately omitted on write; sorted input
files can be read, while attribute-index trailers are refused.
Direct reads expose mapped fixed/enum payloads. Symbol decoding, calendar conversion,
query results and combining partitions allocate memory. External q writers must be
quiescent while reading a table: native files have no Columnar commit word or snapshot
protocol. KdbTable is an immutable reader; publish a new database to write a snapshot.
Segmented source partitions need explicit consolidation before native export.
Compressed/encrypted native containers, modern anymap (type 77), nested symbol domains, mixed/BSON columns, foreign-key columns and attribute-index trailers fail explicitly. They are not silently interpreted as private formats. The live store's compression and encryption containers are still private and do not become native merely by sharing a codec.
Fixed and modern enum layouts are checked against unchanged header/payload excerpts
from KX Systems' published PyKX test files; fixture provenance and Apache-2.0 license
are in tests/data/kdb-native. Other type/nested tests check the supported layouts and
round trips. A full external q read/write run still requires a licensed q executable;
an unlicensed PyKX installation cannot provide that validation. This is a supported
subset, not a claim that every file produced by every q version is interchangeable.
Format references: KX documentation for native files, splayed tables and working with sym files. The unpublished test fixture manifest records the exact upstream source.
kdb+'s own IPC protocol¶
SharedData.ColumnarKdb speaks kdb+'s wire protocol, so real q processes, PyKX and kdb+ feedhandlers work with
Columnar:
from SharedData.ColumnarKdb import KdbServer, KdbConnection, serialize, deserialize
srv = KdbServer(tables={'trade': ['MarketData', 'RT', 'SRC', 'TRADE']}, tickerplant=tp).start() # q: hopen
srv.functions['vwap'] = lambda sym: ... # q: h(`vwap; `IBM)
# from q: h(`columnar.select; `trade) h(".u.upd"; `trade; data) h(".u.sub"; `trade; `IBM`MSFT)
h = KdbConnection(port=5001) # Python -> a real kdb+ process
h.subscribe('trade', on_upd) # .u.sub on a kdb+ tickerplant
- Every q type in KX's documented examples round-trips byte-exact (checked byte for byte): char vectors
(
QChars), vector attributes (QVector.qattr), sorted dictionaries, temporal table columns. Typed scalars are extracted fromZArray/PArray. The native tick endpoint filters onsym, answers.u.subin u.q's shape, and supports.u.add/.u.deland.u.end. Timestamps past 2262 decode toPArray/QTimestamp, which keep kdb+'s raw int64. Datetimes keep the float day-count (ZArray, or rawDArrayoutside the ns calendar range). Dictionaries keep typed and duplicate keys (QDict).KdbServer/KdbConnectiontakessl_context=andunix_path=. serialize/deserializeare q's-8!/-9!: atoms, typed vectors (2000-epoch temporals), symbols, strings, general lists, dictionaries, tables, keyed tables and errors; kdb+-compressed messages are decompressed. Tests check the bytes against KX's documented examples and run PyKX (KX's client) against the server.- q clients call functions by name
(fn; args); q text is not evaluated (the q language is out of scope) and returns an error saying so. kdb+'s tick protocol is built in:.u.updgoes to the Tickerplant and its RDB,.u.subsubscribes a q process, which then receives(upd;table; data)` like from kdb+'s u.q. - Native hooks are
on_open(conn),on_close(conn),on_sync(conn, request),on_async(conn, request)andon_auth(user, password), corresponding to.z.po,.z.pc,.z.pg,.z.psand.z.pw. Sync/async hooks replace the default function dispatch; callserver.call(conn, request)inside a hook to retain it. - A sync hook or registered function may return
ColumnarKdb.Deferred(), keep it and later calldeferred.reply(result=value)ordeferred.reply(error=exception). Each sync request has one reply slot; pipelined replies leave the connection in request order, even when deferred work finishes in a different order. Async requests have no reply. Late/duplicate replies are ignored after resolution or disconnect. query_timeoutbounds sync reads and deferred replies; Columnar queries also receive a cooperative deadline. An unbound buffered value remains subject to the request deadline when it is bound; an expired request returnsstop. A timeout cannot forcibly cancel arbitrary Python callables. Tickerplant calls and functions listed inserver.mutatingare exempt from timeout during normal dispatch.max_result_rows,max_message_bytesandmax_memory_bytesbound result rows, message bytes and process RSS checks; errors use native q signals.- Login is q's
user:password, checked byon_authwhen supplied, otherwise againstCOLUMNAR_TOKEN. Without a token or auth hook the endpoint binds only to loopback.
Inspection and maintenance¶
meta() returns kdb+'s meta table (c t f a). dbmaint: add_column, drop_column, rename_column, copy_column,
cast_column (new files, every partition converted), reorder_columns, rename_table, set_attr, clear_attr, and
Columnar.transaction(root) makes any sequence of Columnar calls on one thread all-or-nothing on an exception; a
server uses it for functions listed in server.mutating. It uses two-phase locking over its write set: the first write
to a table records that table's state and takes its write lock until the transaction ends, so other threads and
processes wait to write it. An abort restores only those tables and removes the ones it created. A table the
transaction never wrote, and anything other writers did to it, is not touched. Inside it nothing is written in place,
every version it started from is kept, and drops and renames are moves that the abort undoes. Two transactions that
lock the same tables in opposite orders can deadlock, as with any lock-based scheme. s# asserts the order the data has now and never
re-sorts it; nulls sort first, as in q.
u# follows kdb+. An append or update that introduces a duplicate does not fail: that partition simply has no
u# index after its seal. Applying u# to data with duplicates (set_attr) is a u-fail, and s# on unsorted data is
an s-fail. A keyed upsert of existing keys on an open table writes in place, using a cached key index.
amend(partition, column, rows, values) (q's @[path;col;:;values]: in place on an open partition's plain
fixed-width columns, else one new version). A failed multi-partition update, delete or append has no effect: each
touched partition goes back to its previous version (kept until the next write) or commit word. cast_column keeps the
original column file in every new version until the new schema is published, so a reader on the old schema never sees
a converted or missing value. Columnar.view(partitions, database=, period=, source=) is .Q.view: it narrows what
every query of the process sees (writes are not filtered). The other inspection and maintenance calls:
- ind(rows, columns=): .Q.ind, the rows at these indexes in the concatenation of all partitions, returned in the
order given
- stats(): rows, partitions, disk bytes, domain sizes, block cache (kdb+'s .Q.w)
- info()
- partition_meta(p)
- capabilities(): what is and is not implemented
- Columnar.tables(db, period, source): q's tables[]; Columnar.chk([t1, t2]): .Q.chk, gives every table every
partition
- Columnar.compact_domain(db, period, source): KX's "compacting an HDB sym file" — drops symbols no table uses and
re-enumerates every column of the domain. Offline, as in kdb+ (close the source's tables in every process);
crash-safe through a journal (running it again finishes the job; tables refuse the domain meanwhile).
- verify(deep=True): offsets, codes, s#, p# and g# against a scan
- disk_usage()
- drop_partition(p)
- drop(): the domain stays, because other tables may use it
- close()
Native temporal and enumeration values¶
from SharedData.ColumnarTemporal import TemporalArray, DArray
from SharedData.ColumnarKdb import PArray
from SharedData.ColumnarEnum import EnumDomain
from SharedData import ColumnarQ as q
# Create a table with names=['date', 'dt'], formats=['qtimestamp', 'qdatetime'].
# These vectors contain q's underlying values, with its epoch and typed nulls.
c.append({'date': PArray(raw_ns), 'dt': DArray(float_days)})
frame = c.select(sym='enum')
frame['date'].array.raw # exact PArray, including nanoseconds after 2262
frame['dt'].array.raw # exact DArray, including sub-millisecond fractions
frame['date'].array.to_datetime64('us') # explicit calendar conversion; ns overflow raises
domain = EnumDomain('venue', ['', 'CME', 'ICE'])
venues = q.cast(domain, ['CME', 'ICE'])
q.cast('i', venues) # underlying int32 codes
q.key(venues) # 'venue'
q.value(venues) # decoded symbols
q.enum_extend(domain, ['NEW']) # explicit extension; cast alone refuses unknown symbols
sym='enum' works with select, exec, col and iter_batches. EnumArray holds codes and a domain identity;
slicing, pandas concatenation within a domain, q list operations and grouped keys retain both. Find/membership
between different domains reconcile symbol values instead of comparing unrelated code numbers. q.match
requires the same domain. As in q, q.null on an enum always returns false, even for a null backing symbol;
pandas also has its own missing-code marker for alignment. Stored-domain compaction requires reopening arrays.
Exact temporal columns use TemporalArray, a pandas extension array. Query results, grouping, batch imports,
sealing and snapshots preserve the physical eight-byte values. Convert to a NumPy calendar unit explicitly when
needed; microseconds give a wider calendar range but discard sub-microsecond display precision. Raw arrays remain
exact. q.cast, q.type_, q.string, aggregate and list operations accept the typed columns.
The Python CQ protocol retains enum domains and exact temporal arrays. Native q IPC transmits enums as symbol
values (q's own behavior) and temporals as their native q type and payload. This does not change schemas of
existing tables. Cast a non-partition column explicitly with cast_column; changing a partition column requires
importing into a new table. Exact temporal predicates currently scan rather than using attribute lookup indexes,
and exact temporal aggregates use one combined pass across partitions to preserve their logical result types.
Exact temporal as-of joins support symbol, fixed-width and string group keys; other key kinds require explicit
conversion and raise an error rather than going through a fallback that loses temporal metadata.
Not implemented¶
- The q language itself: its interpreter, q text queries, q lambdas and views. Their capabilities are Python calls.
- The live store's on-disk format remains private; use the native disk path above for supported q file layouts.
A q process cannot directly
\lthe live store (q processes reach the data over kdb+'s IPC protocol, see above). - Object storage: S3/MinIO through SharedData's
IO.AWSS3, fetching whole column files on first use (no byte-range reads of single blocks, no GCS or Azure backends). Segments (par.txt) are local paths; a segment cannot be an object-store URI. - kdb+ IPC capability 6 (vectors over 2 billion items): the handshake answers 5; messages over 2 GB use the documented length byte but were tested only at the header level.
- The workspace limit is the process RSS (q's
-wcaps its own heap).ColumnarQ.ts(fn, *args)is.Q.ts, but it counts the memory Python's tracemalloc sees, not q's heap. - Distributed peach over remote secondary processes (kdb+'s negative
-swith.z.pd). A query runs its partitions on a thread pool in one process, andq.peachcan use a local process pool. Large grouped reductions and join probes also use secondary threads within a partition; operations without a parallel leaf kernel still run on one thread per partition. - The ODBC and SQL interfaces (q server for ODBC3,
s)queries). - The tickerplant log and the mutation log are Columnar's own record format: q's
-11!cannot replay them. Replay goes through Columnar (ColumnarServer.replay,replay_mutations), and a q client reads.u.i/.u.Land subscribes over IPC instead. - Attributes on nested or mixed columns (
s#/u#on general lists), and attributes carried by in-memory dictionaries/tables: attributes belong to stored columns. - Nested (
list:<type>) columns read as one numpy array per row from a shared buffer, not as kdb+'s mapped inner vectors. - A head-to-head run against kdb+ itself: no kdb+ licence on these hosts. The performance section measures every query against a hand-written numba kernel instead.
- SharedData HTTP API, Dashboard and MCP integration: these consumers do not know Columnar yet. Local Python
routines can use
SharedData.columnar()and the explicit import/batch APIs.
Performance¶
The hot paths are compiled numba kernels that release the GIL; most run in one pass over the data:
- grouping: O(n) on dense keys (symbol codes, small integer ranges); sparse integer, time and float keys are hashed in O(n), then their distinct values are sorted (O(u log u) for u groups) because by returns groups in key order; equality joins, find, in and distinct never sort; counting-sort group order
- aggregates: fused sum, count, min, max, avg, wavg, first and last, with q's null rules inside the loop
- comparisons: tolerant float compare, in through a lookup table
- joins: as-of binary search over right rows that are already in symbol-then-time order (a sealed p# partition needs no sort); aj/wj match on symbol codes and never decode the right side
- seal: gather by permutation, column by column in parallel
- symbols: decode and categorical via a code lookup table; an intern memo makes tick-sized appends skip re-hashing.
Decoded names are cached for domains up to 1,048,576 symbols, with amortized array growth; a first sparse lookup
into a large domain decodes only the requested symbols. Hash rebuilds preserve the name cache.
Queries read sealed uncompressed columns straight from the map (no copy) when they only aggregate. Python's cyclic GC is paused inside appends and queries, because a full collection over many live objects costs seconds.
Where Python remains, by design:
- Per distinct value, by design: string functions (like, lower, upper, string of text) call Python's
string methods once per distinct value, so text with millions of distinct values costs Python speed. Symbol columns
are distinct-heavy only in their domain.
- Your own callables: a Python function evaluated per group (a lambda under by, a custom wj aggregate or a custom fby) runs once per group or window. q's built-in running functions (sums, deltas, prds, ratios, maxs, mins, fills) under update … by take the grouped kernel instead.
- Fixed cost per query: a warm process measured 0.2 ms of dispatch for exec sum (schema and partition checks, result DataFrame); grouped results add the DataFrame and symbol assembly. kdb+ pays about 10–100 µs.
- First call in a new process: numba compiles each kernel on first use (about 2 s in total) and caches it in NUMBA_CACHE_DIR. Keep that directory persistent and writable. ColumnarServer(warm=True) / ColumnarServer.warm_kernels() compile at start, so the first client query does not pay it.
- Within one partition: large sum/count/avg/min/max/first/last, weighted and moment reductions, as-of probes,
window bounds and window reductions split across threads. SHAREDDATA_COLUMNAR_THREADS caps the width. The
4,194,304-row threshold amortizes scheduling, and worker-private group buffers have a 16 MiB budget; excessive
group cardinality falls back to the serial kernel. Partitions run in parallel (peach); nested fan-out is suppressed.
Parallel floating reductions can differ in their last bits because they combine partials in a different order.
scripts/columnar_parallel_bench.py compares one thread with several on identical data; speedup depends on the
kernel and memory bandwidth.
scripts/columnar_bench.py runs the classic kdb+ TAQ workload. The aggregate, join and ema queries are timed against
the same answer computed by a hand-written single-threaded numba kernel on in-memory arrays (the floor); the other
entries report throughput. tests/test_columnar_perf.py
(COLUMNAR_PERF=1) gates it: a Python-speed path sneaking back in fails the test.
Within-partition run of 2026-11-17: python scripts/columnar_parallel_bench.py --rows 8388608 --groups 256
--threads 8 --repeats 5, in an isolated 8-CPU/16-GB container, warm compiled kernels, medians of five runs.
The thread argument is a cap; workload size and buffer budget can select fewer workers.
The reduction inputs contain nulls and an empty group. Serial and parallel answers are checked against each
other; the functional suite separately checks integer wrap, null identities, arrival order, memory fallback and
suppression of nested work. These are comparisons within this Python engine, with other host load present.
| Kernel | Thread cap 1 | Thread cap 8 | Speedup |
|---|---|---|---|
| grouped count, 8.39M rows | 2.89 ms | 1.01 ms | 2.87x |
| grouped int64 sum, 8.39M rows | 7.02 ms | 4.82 ms | 1.46x |
| grouped weighted average, 8.39M rows | 9.27 ms | 6.68 ms | 1.39x |
| grouped float64 variance, 8.39M rows | 8.97 ms | 3.91 ms | 2.29x |
| as-of, 4.29M probes / 4.19M right rows | 287.71 ms | 86.30 ms | 3.33x |
| window bounds, 4.29M windows / 4.19M right rows | 416.23 ms | 143.75 ms | 2.90x |
Run of 2026-11-16 (evening) on a benchmark host:
- Host: 32 cores, other load present; the container was limited to 8 CPUs and 24 GB.
- Data: 5 days, 20M trades and 40M quotes, 5,000 symbols with Zipf activity.
- Timing: best of 5 warm runs.
- Floors: casts and key preparation happen outside the timed floor; the aj floor also builds the joined table.
| Query (q) | Uncompressed (kdb+'s default) | x floor | zstd-3 | x floor |
|---|---|---|---|---|
| append trades, 1M-row batches (2 symbol columns) | 10.9 M rows/s | 10.9 M rows/s | ||
| append quotes, 1M-row batches | 17.4 M rows/s | 17.2 M rows/s | ||
| append, 1k-row ticks | 2.7 M rows/s (0.37 ms each) | 2.6 M rows/s | ||
seal (.Q.dpft: sort p#sym, indexes) trades / quotes |
10.4 / 18.0 M rows/s | 22.6 / 15.3 M rows/s | ||
exec sum size from trade (20M) |
8 ms (2.5 G rows/s) | 2.4 | 34 ms | 10.1 |
select max price from trade where size>500 |
33 ms | 0.7 | 131 ms | 2.8 |
select from trade where sym=`S0000 (all days) |
4.7 ms | 11 ms | ||
select from trade where date=d, sym=`S0000 |
2.0 ms | 3.5 ms | ||
select size wavg price by sym from trade |
39 ms | 2.1 | 181 ms | 9.9 |
select sum size, count i by sym from trade |
33 ms | 2.1 | 81 ms | 5.0 |
select o,h,l,c by sym, 1 xbar time.minute (one day, 856k groups) |
162 ms | 4.5 | 177 ms | 5.1 |
select from trade where price>(avg;price) fby sym |
120 ms | 190 ms | ||
select distinct sym from trade |
110 ms | 122 ms | ||
select count i by date from trade |
0.4 ms (metadata) | 0.4 ms | ||
aj[`sym`time; 4M trades; 8M quotes] |
367 ms | 1.8 | 419 ms | 2.0 |
wj 200k windows of 1 s, max bid and count |
191 ms | 229 ms | ||
0.2 ema x (1M floats) |
1.6 ms | 1.4 | ||
x?x, group x, 5 mmax x (1M ints) |
4.9 / 3.3 / 6.5 ms | |||
idesc x (1M floats) |
59 ms | |||
x like "S00*" (1M symbols) |
17 ms | |||
t lj 1!r (1M left rows, 1k keys) |
3.6 ms | |||
| IPC round trip, 200k rows with a symbol column | 27 ms | |||
kdb+ -8!/-9! of 80k symbols |
9.1 ms |
With zstd the extra time over the floor is decompression; kdb+ pays it too with compressed files.
A second run after round 5, on another benchmark host (24 cores, load about 2, same container limits, uncompressed), gave:
- exec sum size: 5 ms, at the floor (x1.0)
- filtered max: x0.6
- wavg by sym: x2.1
- sum, count by sym: x2.4
- OHLC bars: x4.9
- aj: x1.7
- ema: x1.7
- appends: 14.1 (trades) and 25.7 (quotes) M rows/s
After round 11 (commit 3a1611a2), on another benchmark host (load about 1.4, 3 days, 2M trades and 4M quotes a day, uncompressed):
- The opt-in gate (tests/test_columnar_perf.py) passed.
- Ratios to the floor:
- exec sum size x2.1, filtered max x0.8
- wavg by sym x2.9, sum/count by sym x3.6
- OHLC x6.3 (21.8 M rows/s, the same throughput as round 5)
- aj x2.1, wj x7.1, ema x1.8
- Every floor's answer was checked against the engine.
The same suite on a busy benchmark host (load about 17) ran 2 to 10 times slower, floors included. Measure on an idle host.
The x floor column is what to watch. The fixed per-call cost is about 1-3 ms (Python dispatch, partition views),
which is why small queries sit further from the floor than large ones.
Round-13 Linux comparison, 2026-11-17: baseline a29b0aab versus direct symbol-code grouping, dense
temporal bars and cached group ordering/names. Both ran sequentially on the same host in isolated containers
(8 CPU limit, 16 GB memory limit), with SHAREDDATA_COLUMNAR_THREADS=1, 2 days of 2M trades each, 2,000 symbols, no compression,
and best of 5 warm runs. Another 200k tick-sized appends bring the grouped-query total to 4.2M rows; OHLC reads
2.2M rows on the first day. The host had other load, so these are local comparisons, not portable latency targets.
| Query | Baseline | Optimized | Optimized / numba floor |
|---|---|---|---|
| VWAP by symbol | 25.0 ms | 13.7 ms | 3.9 |
| Sum/count by symbol | 17.3 ms | 5.0 ms | 1.5 |
| OHLC by symbol and minute | 88.1 ms | 60.8 ms | 3.8 |
Every result, including the OHLC labels and four values, matched the independent floor. These measurements do not establish performance parity with kdb+: a licensed head-to-head run is still outstanding.
Validation: 762 functional tests passed (3 skipped). Both opt-in performance-gate cases (uncompressed and zstd)
passed with COLUMNAR_PERF=1 COLUMNAR_PERF_FORCE=1; the busy-host skip was overridden, and all throughput and
kernel-ratio bounds ran. The proposed paired min/max scan was omitted because it added work to single-min queries.
Local integration and batch-scan validation, 2026-11-17: the Columnar suite plus
tests/test_standalone_storage.py passed 796 tests (3 skipped); both opt-in performance-gate cases passed with
COLUMNAR_PERF=1 COLUMNAR_PERF_FORCE=1, including the new batch-scan bound. The TAQ workload (3 days, 1M trades
per day plus 200k extra ticks, 2,000 symbols, no compression, best of 5 warm runs in an 8-CPU/16-GB container)
scanned and summed all 3.2M size values in 250k-row batches in 3.7 ms (870M rows/s, 7.7 times its sum-only
kernel floor). The regular aggregate took 2.0 ms. All checked answers matched. The batch scan includes result
copies and DataFrame construction and is intended for bounded result processing; aggregate queries should use
exec/select directly. This remains a comparison with compiled kernels, not a measured kdb+ head-to-head.