Build a pure q parallelisation framework with a primary process that can spin up secondary processes to complete jobs
One primary process and N secondary processes run on one machine.
- The primary owns the task queue. It decides which task runs where and watches memory against one cap for the primary and every secondary together (
GLOBAL_MEM_LIMIT). It holds back new work while memory is over that cap. - The secondaries run tasks, one at a time. They report back to the primary: status, memory, results. After each task they run
.Q.gc[], so its memory is returned before the next one. - Jobs: work is submitted as a job, one task type and a list of args. The primary makes one task per arg and spreads them across the secondaries. Each secondary saves its result to disk and returns only the path, so results never pass through the primary.
- Global memory cap: the primary reads its own and every secondary's memory every second, busy secondaries included. While the total is over
GLOBAL_MEM_LIMIT, no new task is sent; dispatch resumes once memory falls back under. Tasks already running carry on.
Pre-requisites
- KDB-X, with
KDBX_HOMEset. The framework uses itskx.log,di.timeranddi.osmodules. - Linux. Memory figures are read from
/proc, and the kernel's memory cap uses cgroups v2. - For the kernel's memory cap, a systemd user session (
systemd-run --user). This part is optional: without it, start withUSE_CGROUP=0and only the framework's cap applies.
Set up:
git clone git@github.com:DataIntellectTech/Parallelisation-Project.git
cd Parallelisation-ProjectThen edit config/default.env. These are the settings to look at first:
| Setting | What it is |
|---|---|
PRIMARY_PORT |
the port the primary listens on |
NUM_SECONDARYS |
how many secondaries the primary starts |
GLOBAL_MEM_LIMIT |
the framework's memory cap in bytes, for the primary and every secondary together; empty means no cap |
CGROUP_MEM_LIMIT |
the kernel's memory cap in bytes, used when starting under a cgroup: above it, the kernel kills a secondary. Must be above GLOBAL_MEM_LIMIT, roughly x1.25 |
RESULTS_DIR |
where task results are saved |
TASK_TYPES |
the task types users may run |
HDB_DIR |
an HDB for the secondaries to load, if your tasks need one |
LOCKDOWN |
1 (default) limits what connecting processes can call: see Access |
USER_FUNCS |
the functions users can call when LOCKDOWN=1 |
SEC_CODE |
the code a secondary must send to register; change it from the default on a real deployment |
Settings for restarts and housekeeping are described in their own sections.
Run every command from the repo's top folder, as the scripts load files by relative path.
Load the config into the environment first, in every terminal you use:
# source env vars
set -a; source config/default.env; set +a
# start with no cap useful for development
x src/primary.q -p $PRIMARY_PORT
# start with cgroups and a memory cap
systemd-run --user --scope -p MemoryMax=$CGROUP_MEM_LIMIT -p MemorySwapMax=0 $KDBX_HOME/bin/q src/primary.q -p $PRIMARY_PORTThere are two caps. GLOBAL_MEM_LIMIT is the framework's: above it, dispatch pauses. CGROUP_MEM_LIMIT is the kernel's: above it, the kernel kills a process in the cgroup (a secondary, never the primary). The kernel's cap must be higher. With swap off, the kernel acts the moment a process tries to go past its cap, so if the two were equal, the framework would never get to pause. The gap gives tasks already running room to keep growing after dispatch has paused. Every secondary sets its oom_score_adj to 1000 when it starts, and the primary keeps 0, so when the cgroup runs out of memory the kernel picks a secondary.
Or use the scripts, which load the config themselves and run the primary in the background:
bin/startprimary.sh # under a cgroup capped at CGROUP_MEM_LIMIT
USE_CGROUP=0 bin/startprimary.sh # without the kernel's cap
bin/startsecondary.sh 9 # start one more secondary by hand (it reads SEC_CODE from the config)
bin/stopall.sh # stop the primary and every secondary for this configEach script takes the config file as its last argument (default config/default.env). Logs go to logs/, and the primary's pid to logs/primary.pid. To check the kernel's cap on a running primary:
cat /sys/fs/cgroup$(cut -d: -f3 /proc/$(cat logs/primary.pid)/cgroup)/memory.maxWhen the primary starts, it loads any saved jobs and tasks (see Restarts), runs housekeeping, then spins up its secondaries itself: 8 by default.
To check that it's up, in the primary:
.primary.showstatus[] / memory, dispatch, every secondary and the task countsTo stop everything, quit the primary (\\): it saves the jobs and tasks tables, asks its secondaries to exit, and kills any still running after STOP_GRACE_PERIOD_SECS. To start one more secondary from the primary, use .primary.spawn <next available id>. From a shell, bin/stopall.sh stops everything the same way, and kills anything still running after the grace period.
Work is submitted as jobs, from any q session connected to the primary. A job is one task type and a list of args: the primary makes one task per arg and runs them across the secondaries.
h:hopen 45000
/ one job, three tasks: the call waits until the job finishes
r:h(`.primary.newjob; `sumtil; 1000 2000 3000; ()!())
r`jobid / the job's id
raze get each r`resultpaths / the results: one file per task, in task order
r`helpmsg / how to load them, and how to get the paths again later
/ the paths again, any time later
h(`.primary.jobpaths; r`jobid)- A sync call (
h(...)) waits until the job finishes, then returnsjobid,resultpathsandhelpmsg. If the job fails, the call throwsjob N failed: ..., naming the task that failed and why. While you wait, the primary carries on as normal: dispatching, and answering other users. - An async call (
neg[h](...)) runs the job and returns nothing. Find the job in thejobstable (below), then get its paths with.primary.jobpathsonce it's done. Use this for long jobs you don't want to wait for. - On the primary's console,
.primary.newjobreturns the job id straight away.
For several inputs per task, pass a table: each row becomes one task's args, as a dict.
Params, for every task of the job (()!() for none):
| Param | Type | Default | Meaning |
|---|---|---|---|
priority |
int | 0 | higher goes first; ties go oldest first |
timeout |
time | TASK_TIMEOUT_MS |
a task running longer than this has its secondary killed |
retriesmax |
int | TASK_RETRIES_MAX |
how many retries, for the reasons in RETRY_REASONS |
memestimate |
long | learnt | the memory each task is expected to use, in bytes; learnt from earlier tasks of the type if not given |
For example:
h(`.primary.newjob; `vwap; 2014.04.21 2014.04.22; ([priority:10; timeout:00:00:30.000]))Other calls:
h(`.primary.gettable; `jobs) / the jobs table: query it in your own process
select taskid, state, reason, err from h(`.primary.gettable; `tasks) where jobid=7
h(`.primary.status; ::) / the status as a dict
h(`.primary.spawn; 9) / start one more secondaryOnly the functions in USER_FUNCS can be called: see Access.
A job is refused before anything runs (the call errors and no task is made) if:
- its task type isn't approved, or it has no args;
- a param is unknown, or of the wrong type (
priorityandretriesmaxaccept any whole number); - earlier tasks of its type needed at least
GLOBAL_MEM_LIMIT, so it could never fit; - any of its args were killed for memory before, under a kernel cap (
CGROUP_MEM_LIMIT) at least as high as now. Raising that cap lets them run again.
A job fails as soon as one of its tasks fails for good, that is, after any retries. Its queued tasks
are then cancelled and never sent; tasks already running finish. err on the job says which task failed
and why, and a user waiting on the job gets the same error.
Results are saved under RESULTS_DIR/<jobid>/<taskid>. A task made on the primary's console with
.primary.newtask, outside a job, goes under RESULTS_DIR/nojob/<taskid>. Old jobs and their results are
deleted by housekeeping.
Each job and its tasks record the user who submitted it (.z.u: the name the client gives, not checked).
More detail, including the memory estimate and every error message, is in Jobs.
Adding a task type:
- Add the function to
src/approvedtasks.q. It takes exactly one argument; for several inputs, use a dict. - Add its name to
TASK_TYPES. - Restart.
With LOCKDOWN=1 (the default), a process connecting to the primary can only call:
- users: the functions in
USER_FUNCS; - secondaries:
.primary.register,.primary.heartbeatcheckand.primary.taskupdate. To register, a secondary must sendSEC_CODE, and an id that's already running can't register again.
A call must be a function name and its args, e.g. h(.primary.status; ::)`. Anything else is refused, the reason is sent back, and the primary logs a warning:
- q code sent as a string (
h"..."), or a lambda (h({...}; x)); - a function that isn't on the caller's list.
HTTP to the primary's port always gets 403 Forbidden. The primary's own console and its timers aren't affected.
| Setting | What it is |
|---|---|
LOCKDOWN |
1 limits calls as above; 0 lets anyone connecting run anything (the integration tests use this) |
USER_FUNCS |
the functions users can call, comma separated |
SEC_CODE |
the code a secondary sends to register. config/default.env is in git, so on a real deployment set it in a config only the primary's OS user can read |
This limits what can be called, not who can connect: .z.u is whatever name the client sends, and anyone on the machine who knows SEC_CODE can register a secondary.
The jobs and tasks tables are saved to TABLE_DIR whenever a job finishes and when the primary stops. They're loaded back when it starts, so job ids, result paths and the learnt memory estimates survive a restart.
- Jobs and tasks that were running when the primary stopped are marked
failed, witherr"primary restarted" (their tasks get reasonrestart). Submit them again. - New jobs and tasks carry on from the highest saved ids, so an id is never reused.
.primary.jobpathsstill works for a job that finished before the restart, until housekeeping deletes it.
| Setting | What it is |
|---|---|
TABLE_DIR |
where the tables are saved; empty means nothing is saved or loaded |
SAVED_TABLES |
which tables to save, comma separated (default jobs,tasks) |
Old jobs, their results and old logs are deleted when the primary starts, and every PURGE_INTERVAL_SECS after that.
- Jobs and results: first, any job that finished (done or failed) more than
JOBS_MAX_AGE_SECSago; then the oldest finished jobs overJOBS_MAX_ROWS. Deleting a job removes itsRESULTS_DIR/<jobid>folder, its tasks and its row. A running job is never deleted. - Logs:
.logfiles directly inLOG_DIRthat were last written more thanLOG_AGE_DAYSwhole days ago, except any a running process is still writing to.
Either can be run by hand on the primary's console:
.primary.purgeresults[] / returns how many jobs it deleted
.primary.purgelogs[] / returns how many log files it deleted| Setting | What it is | Empty means |
|---|---|---|
JOBS_MAX_AGE_SECS |
how long a finished job and its results are kept | no age limit |
JOBS_MAX_ROWS |
the most finished jobs kept | no row limit |
PURGE_INTERVAL_SECS |
how often the purge runs | only at start-up |
LOG_AGE_DAYS |
how old a log file can get | logs are never deleted |
.primary.status[] returns a snapshot of the primary as a dict, for code to read. From another process, call it as h(.primary.status; ::)`.
| Key | What it holds |
|---|---|
time, uptime |
when the snapshot was taken (UTC) and how long the primary has been running |
memory |
total in use (the primary plus every live secondary, RssAnon, bytes), cap (GLOBAL_MEM_LIMIT), headroom (cap minus total), primary (the primary's own) |
dispatch |
paused, pausecount, pausedtotal (includes the current pause), pausedsince |
secondaries |
one row per secondary: id, pid, status, spawned, current task, rssanon, restarts, time since its last heartbeat (lastseen) |
seccounts |
how many secondaries are free, busy, stale and closed |
taskcounts |
how many tasks are queued, dispatched, running, done and failed |
.primary.showstatus[] prints the same snapshot for a person at the console:
== primary status 2026.11.13D13:51:09.408361778 uptime 0D00:01:29.987809969 ==
memory: 17MB in use, 4096MB cap, 4079MB headroom
dispatch: running, paused 0 times for 0D00:00:00.000000000
secondaries: 8 free, 0 busy, 0 stale, 0 closed
id pid status spawned task memmb restarts lastseen
----------------------------------------------------------
1 3775257 free 1 2.1 0 00:00:00.641
...
tasks: 0 queued, 0 dispatched, 0 running, 1 done, 1 failed
A closed secondary keeps its last memory reading in the table but is not counted in the total.
- Errors in a task's own code are reported (
failed, reasonerror) and not retried. - A secondary that dies mid-task: its task fails as
lostand is retried on another secondary. The secondary is restarted, up toRESPAWN_MAXtimes. - A task that runs too long: it fails as
timeoutand isn't retried. Its secondary is killed, since a busy q process can't be interrupted, and then restarted. - A secondary the kernel kills for memory (over
CGROUP_MEM_LIMIT): its task fails asoomand isn't retried, since the same args would need the same memory again. Itsmemafterrecords the kernel's cap. The secondary is restarted, up toRESPAWN_MAXtimes. - The primary stops while jobs are running: on restart, those jobs and their unfinished tasks are
marked
failed(reasonrestart). See Restarts.
Per task, timeout and retriesmax can be set when it's submitted; otherwise
TASK_TIMEOUT_MS and TASK_RETRIES_MAX apply:
.primary.newtask ([tasktype:`sleep; args:10; timeout:00:00:02.000; retriesmax:1i])More detail, including the order things happen in, is in How it works, and how a memory kill is spotted is in Memory kills.
All memory figures come from the kernel, in /proc/<pid>/status, in bytes. The framework doesn't use .Q.w[]: the kernel's figures are what it actually enforces, and they can be read from outside a process, which matters because a secondary running a task can't answer.
| Figure | What it counts, in q terms |
|---|---|
| RssAnon | q's heap: vectors, tables, dicts and query results held in memory, plus IPC buffers. What .Q.gc[] gives back |
| RssFile | memory-mapped files: HDB column files a query has touched, and anything get maps rather than copies. Shared between processes, and the kernel can drop it under pressure |
| VmRSS | the two together |
| VmHWM | the highest VmRSS since the peak was last reset |
Who reads what, and when
- The primary, every second: its own RssAnon and every live secondary's, in one read, including busy secondaries, since nothing is asked of them. Each secondary's figure is kept in
secondaries, and the total as a row inmemhistory(the lastMEM_HISTORY_MAXrows). - Each idle secondary, every couple of seconds: sends its RssAnon with its heartbeat.
- Each task, recorded by its secondary:
membefore: RssAnon just before the task. The peak is reset (clear_refs) at the same momentmemafter: VmHWM at the end, the task's peak. RssAnon is only a snapshot of one moment, and would miss a spike while the task runsmemaftergc: RssAnon after the.Q.gc[]that follows the task. The primary uses it straight away, so freed memory counts before the next poll.
The global cap. While the total (the primary plus every live secondary) is over GLOBAL_MEM_LIMIT, dispatch sends nothing new. It resumes when the total falls back under. Each pause and resume is logged, and counted in .primary.pausecount and .primary.pausedtotal. Tasks already running are never stopped: the cap only holds back new ones. .primary.pausedtotal covers finished pauses; one still in progress started at .primary.pausedsince. Under a cgroup, the kernel's own cap (CGROUP_MEM_LIMIT) sits above this one, so the framework pauses before the kernel has to kill anything.
-5#memhistory / the last 5 readings: total, primary, secondaries, busy
select id, status, rssanon, memtime from secondaries
.primary.pausecount / how many times dispatch has pausedA known overstatement. A task's memafter − membefore includes file pages it read: the peak counts them, but "before" doesn't. For a task that reads an HDB, that's the heap it used plus the pages it touched: on a 31-day query, about 145MB more. For tasks that only compute, it's accurate. The kernel keeps no peak for the heap alone, and q's .Q.w[]peak` can't be reset for each task, so VmHWM is the only per-task peak available. The error is on the safe side: the cgroup counts file pages too, and an estimate that's too high holds tasks back rather than letting too many run.
tests/run.sh tests/unit # unit specs (qspec)
bash tests/integration.sh # end to end: starts a real primary and secondaries, using config/integration.envThe integration tests run with LOCKDOWN=0 (in config/integration.env), except lockdown_spec.q, which switches it on.
The same work run three ways on homer (64 logical CPUs: 32 physical cores on 2 sockets). Each time is the average of 3 runs per task.
vwap, 50 days |
sumtil, 50 × 50,000,000 |
|
|---|---|---|
KDB-X, -s 0 (one thread) |
3.40s | 4.41s |
KDB-X, -s 8 (peach) |
0.62s | 0.67s |
| Framework, 8 secondaries, 1 thread each | 1.22s | 2.22s |
vwap: the VWAP bydate,symfor each of the HDB's 50 days, one day per task. It reads from disk.sumtil:sum til 50000000, 50 times. Pure compute, about 400MB per task.- KDB-X:
raze .task.vwap peach daysand.task.sumtil peach n, timed with.z.P. - Framework: one job of 50 tasks,
finishedtime - submittedtimefromjobs.
What the numbers say
-
The framework is 2–3 times faster than a single thread.
-
On small, even tasks like these,
peachis faster than the framework: about 2 times forvwapand 3.4 times forsumtil. Every framework task pays a fixed cost:- reading memory from
/proc, and resetting the peak; - IPC;
- writing its result to disk;
- a
.Q.gc[]afterwards.
- reading memory from
-
The bigger
sumtilgap is mostly the gc. Each task gives its 400MB back to the OS, so the next one has to get it again.peachthreads keep their memory and reuse it. -
The cost is per task, so it matters less as tasks get longer.
-
What the extra time buys:
- a task killed for memory takes out one secondary, not the whole process;
- a hung task is killed at its timeout;
- a global memory cap is enforced, and dispatch only sends what fits;
- each task's memory is measured and freed;
- results are on disk, and still there after the primary stops.
With
peach, one memory kill or one error loses every thread's work.
To reproduce
- Warm the cache first by running each workload once. A cold
vwaprun takes several seconds, nearly all of it reading the HDB. - KDB-X:
x -s 8(or-s 0), then loadsrc/approvedtasks.qand the HDB. - Framework: start the primary, then submit
.primary.newjob[vwap; days; ()!()]and.primary.newjob[sumtil; 50#50000000; ()!()]on its console, one job at a time.
Full steps are in the demo guide.
This project was built with the help of Claude
What it did:
- Code: Code was written mostly by me checking functions against Claude with the exception of when we needed to get meory stats from the kernal and start with cgroups. Anything in the code that I used Claude for is marked with a
// Claude. - Tests: most of the specs were AI-written, I made some corrections and fixes. Claude helped install qspec. I started off reviewing teh unit and integreation tests but along the way it seemed it was only style issues so just ran them and reported errors back to Claude for it to fix
- Docs: first drafts of these docs