diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..7a7d526 --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,6 @@ +{ + "recommendations": [ + "ms-vscode-remote.remote-ssh", + "KX.kdb" + ] +} diff --git a/README.md b/README.md index e40963f..79a36e2 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,616 @@ # Parallelisation-Project -Build a pure q parallelisation framework with a master proc that can spin up secondary procs to complete tasks +Build a pure q parallelisation framework with a master proc that can spin up secondary procs to complete tasks. + +## Primary +This is the main process which will manage secondaries and tasks + +### how to start +Go to the directory and start this will run the default config and start on port `45000` + +```bash +cd /home/jrutledge/internalWork/Parallelisation-Project +bash bin/startprimary.sh +``` + +For starting it interactively do +```bash +bash config/config.sh # this is jsut a coipy of deaful.coinfig and im doing it for testing atm, will probs move out +x src/primary.q -p 45000 +``` + +### tables +**secondaries** + +This is a table to monitor the secondary processes used for carrying out tasks assigned by the primary. In this table we track key information such as the `status` of a secondary process. + +### Secondaries +These will either be ran as part of the intial start up or the primary will spin up more as needed. They will not start with a port number so only the primary can connect to it, the primary does this by recording the handle a secondary connects with on startup and runs commands through that handle. A secondary cannot start if the primary process is not up. + +We are going to set all secondaries `oom_score` to `1000`. For anyone not familiar with this `-1000` means shut me down last and `1000` means shut me down first in the case we are out of memory. You can check a processes `oom_score` using `cat /proc//oom_score`. + +### how to start +To bring up 2 secondaries run the below +```bash +cd /home/jrutledge/internalWork/Parallelisation-Project +bash bin/startsecondary.sh 1 +bash bin/startsecondary.sh 2 +``` + +## Testing +We will use the qspec testing framework here, i have copied it into the project directly + +### how to run unit tests +From the project top level dir, you run the below commands +```bash +tests/run.sh tests/unit # a whole folder +tests/run.sh tests/unit/primarytests.q # one file +``` + +Example run +```bash +jrutledge@homer:~/internalWork/Parallelisation-Project$ tests/run.sh tests/unit/primary.q +. + +For 1 specifications, 1 expectations were run. +1 passed, 0 failed. 0 errors. +jrutledge@homer:~/internalWork/Parallelisation-Project$ +``` + +### how to run integration tests +From project top level dir run the below commands +```bash +bash tests/integration.sh oomscore # run just the oomscore_spec.q test +bash tests/integration.sh # run all integration tests +``` +Example output +```bash +jrutledge@homer:~/internalWork/Parallelisation-Project$ bash tests/integration.sh + +== tests/integration/stale_spec.q +.. + +For 1 specifications, 2 expectations were run. +2 passed, 0 failed. 0 errors. +tests/integration.sh: line 25: 2899594 Killed "$Q" src/primary.q -p "$PRIMARY_PORT" < /dev/null >> "$LOG_DIR/primary.log" 2>&1 + +== tests/integration/stop_spec.q +.. + +For 1 specifications, 2 expectations were run. +2 passed, 0 failed. 0 errors. +tests/integration.sh: line 25: 2899874 Killed "$Q" src/primary.q -p "$PRIMARY_PORT" < /dev/null >> "$LOG_DIR/primary.log" 2>&1 + +integration: all 2 spec files passed +jrutledge@homer:~/internalWork/Parallelisation-Project$ +``` + + +## Manual testing + +A guide to manually test and run commands as i feel it give a bit of confidence to run the code yourself at times. It starts a primary with 4 secondaries and runs tasks through them. + +### Start the primary +Go to the directory where you have downloaded hte project to and run the below +```bash +set -a; source config/default.env; set +a +export NUM_SECONDARYS=4 +x src/primary.q -p 45000 +``` + +Wait a couple of seconds until all 4 secondaries have registered: + +```q +.primary.showstatus[] +``` + +You should see something like the below +```q +q).primary.showstatus[] +== primary status 2026.10.16D14:39:06.274222113 uptime 0D00:00:06.864868790 == +secondaries: 4 free, 0 busy, 0 stale, 0 closed +id pid port status spawned lastseen lastmembytes +-------------------------------------------------------- +1 527736 45001 free 1 00:00:00.552 620432 +2 527741 45002 free 1 00:00:00.447 620432 +3 527746 45003 free 1 00:00:00.542 620432 +4 527750 45004 free 1 00:00:00.438 620432 +tasks: 0 queued, 0 dispatched, 0 running, 0 done, 0 failed +``` + +To watch the secondaries work, open a second terminal and follow today's secondary logs. You'll see a `task N is complete` line for each task: + +```bash +tail -f logs/sec*.$(date +%Y.%m.%d)*.log +``` + +### 1. One task, end to end + +```q +// run a task and record its taskid +t:.primary.newtask `tasktype`args!(`sumtil;1000000) +// look at the task you just ran +tasks t +// you should see all secondaries as free and tasks having 1 done +.primary.showstatus[] +``` + +If you increase the size of the argument to the task it will take longer so you can check the tasks and secondaries table to see different status's. This will also increase the `memafter` column as the `heap` will have increased. +eg. + +```q +.primary.newtask `tasktype`args!(`sumtil;1000000000) +``` + +### 2. Many tasks: 20 one-second sleeps on 4 secondaries + +```q +ids:.primary.newtask each ([] tasktype:20#`sleep; args:20#1) +``` + +You can perform the same checks as we did above when just running one task. + + +### 3. Priority: a high-priority task goes ahead of the queue + +First fill all 4 secondaries with 5-second tasks, sleep for 2 seconds then send 4 low and 1 high priority task. + +```q +.primary.newtask each ([] tasktype:4#`sleep; args:4#5); system"sleep 2"; lo:.primary.newtask each ([] tasktype:4#`sumtil; args:4#1000); hi:.primary.newtask `tasktype`args`priority!(`sumtil;1000;9i) +``` + +If we check the tasks table and when each task was dispatched we will see the high priority task was dispatched before the low priority ones. + +```q +`dispatchedtime xasc select taskid, tasktype, priority, submittedtime, dispatchedtime from tasks +taskid tasktype priority submittedtime dispatchedtime +------------------------------------------------------------------------------------ +9 sumtil 9 2026.10.20D08:51:37.677650727 2026.10.20D08:51:37.678739277 +1 sleep 0 2026.10.20D08:51:35.673197691 2026.10.20D08:51:37.679028709 +2 sleep 0 2026.10.20D08:51:35.673400356 2026.10.20D08:51:37.679254365 +3 sleep 0 2026.10.20D08:51:35.673533294 2026.10.20D08:51:37.679470841 +4 sleep 0 2026.10.20D08:51:35.673653260 2026.10.20D08:51:38.696035079 +5 sumtil 0 2026.10.20D08:51:37.677263059 2026.10.20D08:51:38.696375433 +6 sumtil 0 2026.10.20D08:51:37.677406335 2026.10.20D08:51:38.696626593 +7 sumtil 0 2026.10.20D08:51:37.677493443 2026.10.20D08:51:38.696865825 +8 sumtil 0 2026.10.20D08:51:37.677572699 2026.10.20D08:51:42.995350280 +``` + +# Benchmarking +trades table is on avg 5100 rows per day +## 1st run +Pri/Sec side: +1. we ran with 4 secondaries +2. `.log.info` was running +3. query was +```q +alld:d where not null d:"D"$string key hsym `$getenv `HDB_DIR +d:alld where alld within 2014.09.12 2015.09.11 +ids:.primary.newtask each ([] tasktype:(count d)#`vwap; args: d) +``` +4. this took 1min 9secs (`0D00:01:09.599248039`) +```q +exec count i by state from tasks +raze exec first each result from tasks where state=`done //result +exec (max finishedtime)-min startedtime from tasks +``` +5. only difference is we dont get the result returned +6. dispatch ran every 1 second + +threads side: +1. started `x hdb -s 4` +2. ran much quicker +```q +rutledge@homer:~/internalWork$ x hdb/ -s 8 +KDB-X 5.0 2026.07.23 Copyright (C) 1993-2026 Kx Systems +l64/ 64()core 385394MB jrutledge homer.aquaq.co.uk 127.0.1.1 EXPIRE 2027.03.26 dataintellect.com KXMS #104376 + +.task.vwap:{[d] select vwap: size wavg price by date,sym from trades where date = d }; +alld:d where not null d:"D"$string key hsym `$"/home/jrutledge/internalWork/hdb" +d:alld where alld within 2014.09.12 2015.09.11 +startTime:.z.P; .task.vwap peach d ; .z.P-startTime +0D00:00:00.077755113 +``` + +I believe the main difference is the `dispatch` job only running every second, as the first task took ` 0D00:00:00.001581139` + +## 2nd run +pri/sec: +1. changed `dispatch` job to check every 0.01 seconds now +2. this has sped it up significantly to 6.5 seconds `0D00:00:06.500832005` + +## 3rd run +threads: +1. startged with 8 threads +```q +rutledge@homer:~/internalWork$ x hdb/ -s 8 +KDB-X 5.0 2026.07.23 Copyright (C) 1993-2026 Kx Systems +l64/ 64()core 385394MB jrutledge homer.aquaq.co.uk 127.0.1.1 EXPIRE 2027.03.26 dataintellect.com KXMS #104376 + +.task.vwap:{[d] select vwap: size wavg price by date,sym from trades where date = d }; +alld:d where not null d:"D"$string key hsym `$"/home/jrutledge/internalWork/hdb" +d:alld where alld within 2014.09.12 2015.09.11 +startTime:.z.P; .task.vwap peach d ; .z.P-startTime +0D00:00:00.089224031 +``` + +pri/sec: +1. Changed to run 8 secondary processes +2. changed teh `dispatch` to check every 0.0001 seconds +```q +f:{alld:d where not null d:"D"$string key hsym `$getenv `HDB_DIR ; d:alld where alld within 2014.09.12 2015.09.11; ids:.primary.newtask each ([] tasktype:(count d)#`vwap; args: d)} +f[] +exec (max finishedtime)-min startedtime from tasks +0D00:00:03.201173431 +``` + +## 4th run +lets up the amount of data, with fakedb.q we ran +```q +makehdb[`:hdb; 365; 100; 1000000] +``` + +threads: +```q +.task.vwap:{[d] select vwap: size wavg price by date,sym from trades where date = d }; +alld:d where not null d:"D"$string key hsym `$"/home/jrutledge/internalWork/hdb" +d:alld where alld within 2014.09.12 2015.09.11 +startTime:.z.P; .task.vwap peach d ; .z.P-startTime +0D00:00:00.307302246 +``` + +pri/sec: +```q +q)f:{alld:d where not null d:"D"$string key hsym `$getenv `HDB_DIR ; d:alld where alld within 2014.09.12 2015.09.11; ids:.primary.newtask each ([] tasktype:(count d)#`vwap; args: d)} + +exec (max finishedtime)-min startedtime from tasks +0D00:00:03.225075485 +``` + +## 5th run +bump up the size of trades again +``` +makehdb[`:hdb; 365; 100; 10000000] +// i ctrl+c 'ed this as it was taking ages and homer was tight for disk space +``` +will do a smaller date range as i dont want to kill homer + +threads (8) +```q +q).task.vwap:{[d] select vwap: size wavg price by date,sym from trades where date = d }; +q)alld:d where not null d:"D"$string key hsym `$"/home/jrutledge/internalWork/hdb" +q)startTime:.z.P; .task.vwap peach alld ; .z.P-startTime +0D00:00:00.643 +``` + +pri/sec: +```q +f:{alld:d where not null d:"D"$string key hsym `$getenv `HDB_DIR ;.primary.newtask each ([] tasktype:(count alld)#`vwap; args: alld)} +f[] + +exec (max finishedtime)-min startedtime from tasks +0D00:00:01.348516461 +``` + +## change + +after we added the below line to `.primary.taskupdate` so it would rerun after a task is complete instead of waiting for `.primary.dispatch` to run in our `.timer.getalljobs[]` table. +``` + if[newstate in `done`failed; .primary.dispatch[]]; + ``` + This got the time to 0.939 seconds (`0D00:00:00.939179837`) with the same setup as the 5th run + +# AI Usage +1. qspec installation +2. planning it out after i had an intial plan + - was mostly good think it maybe went into too much detail for version 1 + - got some things i hadnt considered +3. bash scripting, for any bash scripts primary/secondary/testing +4. q usage + - simpler tasks eg. creating tables + - used it in the spawning functionality for spawning secondaries from the primary and the testing + Worked well mostly with a couple of style fixes (reordering so less brackets) and redefining variable names eg. in qspec it used `before` as a variable and had used `value` in another instance + + + +# my notes ignroe in any PR reviews till the end + +``` +jrutledge@homer:~/internalWork/Parallelisation-Project$ bash bin/startprimary.sh + +start primary: port 45000, config config/default.env +startprimary: port 45000, config config/default.env, pid 1362094, log logs/primary.2026.10.05D13.29.29.log + +jrutledge@homer:~/internalWork/Parallelisation-Project$ bash bin/startsecondary.sh 1 +start secondary: id 1, port 45001, config config/default.env, pid 1362384, log logs/sec1.2026.10.05D13.29.34.log + +jrutledge@homer:~/internalWork/Parallelisation-Project$ bash bin/startsecondary.sh 2 +start secondary: id 2, port 45002, config config/default.env, pid 1362708, log logs/sec2.2026.10.05D13.29.37.log +jrutledge@homer:~/internalWork/Parallelisation-Project$ +``` + +### q stuff +```q +pri:hopen `::45000 + +sec1:hopen `::45001 +``` +### create an images folder or stick them all under docs/images and look at referncing them better +![alt text](image.png) + + +## info on kernal memory +We can see the kernal mem stats at `/proc//status` file + +**VmRSS**: Resident memory, this is all the physical RAM a process occupies. Its is roughly `RssAnon + RssFile`. + +**RssAnon**: RAM not backed by a file. For q essentially the heap pages actually in use. The kernal cannot drop it so its the memory that leads to swapping or the OOM killer. In q the `heap` is what has been promised and available but `RssAnon` is what the kernal has promised, so usually the `heap > RssAnon`. + +**RssFile**: RAM holding file page eg. q binary, libs and mapped files. The kernal can drop and read it from disk again so it is not a real cost. This is different to `mmap` in q as this is only files q mapped where as `RssFile` has the binarys and libs. + +**VmHWM**: The largest `VmRSS` has been since the process has started or the last reset. (this can be done by writing `5` to `/pric//clear_refs`) + +We are using these instead of `.Q.w[]` as we can read `/proc//status` at any time and `RSS` is what the kernal enforces. + + +Too test `OOM` i might need to use `cgroups` this allows me to allocate a certain amount of RAM to my processes so they will be chosen to kill first if mem limits are reached + +Claude steps + +## Testing out-of-memory safely on homer (cgroups) + +homer is shared, so anything that might run out of memory runs inside a **cgroup (control group)** with its own memory limit. When the limit is reached, the kernel kills a process **inside the cgroup** (a secondary, as they set `oom_score_adj=1000`) and nothing outside it is affected. Always use `MemorySwapMax=0`: homer already uses a lot of swap, and without it a cgroup at its limit would swap instead of being killed. + +`systemd-run` doesn't know shell aliases, so use the full path to q (`$KDBX_HOME/bin/q`), not `x`. + +To do this we edit the file `/proc//cgroup` by changing the start to use `/sys/fs/cgroup`. This can be seen in the function `.cgroup.dir`. + +In the files under our cgroup directory we have the following; +```bash +d= +cat $d/memory.current # bytes the whole cgroup is using right now (all its processes together) +cat $d/memory.max # the limit: "max" means no limit +cat $d/memory.events # counters: how often the limit was hit, and oom_kill +cat $d/cgroup.procs # the pids in this cgroup +``` + +So we will edit the `memory.max` file, so every process started in the same cgroup will be subjected to this. Since we start the secondary processes from the primary they will be under the same cgroup. When `memory.current` reaches `memory.max` the kernal will look at which processes have the highest `oom_score` and kill them first. As we start all secondary processes with an `oom_score_adj`=1000 it kills secondary processes first. It will add 1 to `oom_kill` in that cgroups `memory.events` + +### How does it decide which process to kill? + +How bad a process is can be calculated +```bash +badness = the process's resident memory + its swap + its page tables (in pages) + + oom_score_adj × (total memory allowed ÷ 1000) +``` + +Which ever process has the highest `badness` will be killed first by the kernal. + +### How to start the primary in a cgroup + +```bash +cd ~/internalWork/Parallelisation-Project +set -a; source config/default.env; set +a +systemd-run --user --scope --unit=qfwoom -p MemoryMax=1G -p MemorySwapMax=0 $KDBX_HOME/bin/q src/primary.q -p 45000 +``` + +### What the primary does when a secondary is killed for memory + +At start the primary finds its cgroup (`/proc//cgroup`) and remembers the +`oom_kill` count from that cgroup's `memory.events`. When a secondary's connection +closes, the primary reads the count again. If it has gone up, the secondary was +killed by the kernel: its task is marked `failed` with reason `oom` and is **not** +retried (`oom` is not in `RETRY_REASONS`), because it would only be killed again. +Otherwise the reason is `lost` and the task is retried as usual. Either way the +secondary is restarted (up to `RESPAWN_MAX`). + +Outside a memory-limited cgroup the count stays 0, so every death is `lost`. + +To see it happen: + +```bash +set -a; source config/default.env; set +a +systemd-run --user --scope --unit=qfwoom -p MemoryMax=1G -p MemorySwapMax=0 $KDBX_HOME/bin/q src/primary.q -p 45000 +``` +```q +q)t:.primary.newtask `tasktype`args!(`hold;`mb`secs!(1500;10)) +q)tasks[t]`state`reason`retrycount / `failed`oom, 0i +q)system "cat ",.primary.cgroupdir,"/memory.events" / oom_kill 1 +q).primary.showstatus[] / that secondary is back, restarts 1 +``` +Always set `MemorySwapMax=0`: without it the kernel swaps the process instead of +killing it, and homer already uses a lot of swap. + + +# Demo + +1. show how to start with cgroups +```bash +set -a; source config/default.env; set +a +systemd-run --user --scope -p MemoryMax=$GLOBAL_MEM_LIMIT -p MemorySwapMax=0 $KDBX_HOME/bin/q src/primary.q -p 45000 +# systemd-run --user --scope # run a command in a new cgroup of its own +# -p MemoryMax=$GLOBAL_MEM_LIMIT # the hard cap: the kernel kills inside this cgroup above 4GB +# -p MemorySwapMax=0 # kill rather than swap +# $KDBX_HOME/bin/q # it has to be the full path as systemd-run can't see the x alias +``` +```q +.primary.cgroupdir / the cgroup the primary and secondaries are in +system "cat ",.primary.cgroupdir,"/memory.max" / 4294967296: the kernel's cap +.primary.showstatus[] / 8 secondaries, all free +``` + +2. do a comparison between 8 secondaries and 8 threads for the same query +```bash +# in a different terminal run +cd ~/internalWork/Parallelisation-Project +set -a; source config/default.env; set +a +x src/approvedtasks.q -s 8 +``` +Then +```q +// load in the hdb +\l /home/jrutledge/internalWork/hdb + +// check the number of dates +count date + +// check our function exists +.task.vwap + +// time how long it takes +start:.z.P; raze .task.vwap peach date ; .z.P-start +// 0D00:00:09.232734870 + +// cache loaded in +start:.z.P; raze .task.vwap peach date ; .z.P-start +// 0D00:00:00.770165808 +``` +Now connect to the primary +```q +// connect to the primary +h:hopen 45000 + +// check the approved functions +h".primary.tasktypes" + +// show a bad task: only approved task types can run, this is refused before anything is created +jobID:h(`.primary.newjob; `bad; date; ()!()) + +// run a good task: one job, one task per date, ()!() for no params +jobID:h(`.primary.newjob; `vwap; date; ()!()) + +// run this until it is done +h({jobs x}; jobID) + +// time how long it took to run +h({exec finishedtime-submittedtime from jobs where jobid=x}; jobID) +start:.z.P; raze get each h(`.primary.jobpaths; jobID); .z.P-start +// 0D00:00:00.002124168 + +// compare results +(raze get each h(`.primary.jobpaths; jobID))~raze .task.vwap peach date +``` + +3. show the mem used for a single job before and after +```q +// check the mem for each task in MB +h({select[10] taskid, before:`long$membefore%1048576, peak:`long$memafter%1048576, aftergc:`long$memaftergc%1048576 from tasks where jobid=x}; jobID) + +// a job that uses 300MB per task, to make it obvious +jm:h(`.primary.newjob; `hold; 8#enlist `mb`secs!(300;1); ()!()) +h({select taskid, before:`long$membefore%1048576, peak:`long$memafter%1048576, aftergc:`long$memaftergc%1048576 from tasks where jobid=x}; jm) +/ every task: about 2MB before, about 300MB peak, back to about 2MB after the gc +``` + +4. show how to run high priority jobs +```q +// a long job: 40 tasks of 3 seconds on 8 secondaries, so most of it is queued, priority 0 +jl:h(`.primary.newjob; `sleep; 40#3; ()!()) + +// an urgent job, submitted after it, priority 10 +ju:h(`.primary.newjob; `sumtil; 1000 2000 3000; ([priority:10])) + +// run on primary, both jobs and their priorities +select jobid, priority, state, submittedtime, finishedtime from jobs +``` + +5. show dispatch pausing above the memory cap and resuming below it +```q +// soft cap down to 2GB; the kernel's hard cap stays at 4GB +h".primary.memcap:2147483648" + +// 16 tasks of 300MB, held for 2 to 9 seconds +jg:h(`.primary.newjob; `hold; ([] mb:16#300; secs:16#2 3 4 5 6 7 8 9); ()!()) + +// in the primary's terminal, every second or two: the dispatch line shows PAUSED, then running +.primary.showstatus[] + +// how many times it paused, and for how long +.primary.status[]`dispatch + +// soft cap back to 4GB +.primary.memcap:4294967296 +``` + +6. show jobs failing, and what the framework does about it + +6.1 a task that throws an error: reported, not retried, the job fails +```q +je:h(`.primary.newjob; `fail; enlist 0; ()!()) +h({select taskid, state, reason, err, retrycount from tasks where jobid=x}; je) +``` + +6.2 a timeout: this job has a 5 second timeout, the secondary is killed and restarted, we give it a sleep 20 so it will timeout. Look at the secondaries start time +```q +.primary.tasktimeout +jt:h(`.primary.newjob; `sleep; enlist 20; ([timeout:00:00:05.000])) +h({select taskid, state, reason, err, retrycount from tasks where jobid=x}; jt) / after 5s: timeout +``` + +6.3 out of memory: one part asks for 5GB, over the kernel's 4GB cap +```q +jo:.primary.newjob[`hold; ([] mb:(3#100),5000,8#100; secs:12#5); ()!()] +select taskid, state, reason from tasks where jobid=jo / part 4 oom, parts 9-12 cancelled, the rest done +system "cat ",.primary.cgroupdir,"/memory.events" / oom_kill 1 +``` + +6.4 a secondary crashing mid-task: its task is retried, the job still finishes +```q +jk:.primary.newjob[ `sleep; 16#3; ()!()]; p:first exec pid from secondaries where status=`busy; system "kill -9 ",string p +select taskid, state, retrycount from tasks where jobid=jk +``` + +after 6.2, 6.3 and 6.4, in the primary's terminal: the killed secondary is back with a new pid and restarts 1 +```q +.primary.showstatus[] +``` + +7. show where the results are, and that they don't need the primary +```q +h(`.primary.jobpaths; jobID) / one file per task, in task order +h({jobs x}; jobID) / resultbytes: the total size before you load it +paths:h(`.primary.jobpaths; jobID) +``` +stop the primary (\\ in its terminal), then: +```q +(raze get each paths)~raze .task.vwap peach date / 1b: the results don't need the primary +``` + +8. Talking points (no commands) +- Why not -w: + - it's per process, not one global cap; + - it counts q's heap, not what the kernel enforces; + - '-w abort can't be trapped, and takes every thread's work with it; + - a cgroup gives one hard cap, real RSS, and a labelled oom. +- Soft cap vs hard cap: running tasks overshoot the soft cap, and the cgroup also counts the HDB's page cache. So in real use the hard cap should sit above the soft cap. Section 5 shows why. +- Priority: every task of a job carries the job's priority; dispatch sends the highest first, then the oldest. A running task is never interrupted, and there's no ageing yet, so a steady stream of urgent work could starve priority 0. + +9. What's next +- From the brief, not done yet: + - V2 scheduler: only send a task if its expected size (from the peaks recorded per task type) fits in the headroom left, thinking of doing this with a tasks compairson of peak mem used for same types of tasks + - backoff on retries, and quarantine for a secondary that keeps failing + - integration tests for the brief's list: happy path, gating, timeout, gc +- Building on what's there: + - one blocking call that waits for a job and returns its paths (deferred reply) + - memory per job on the jobs table: its footprint and its biggest task + - a soft cap below the hard cap in the start scripts + - fairness for priorities: ageing, so low-priority work can't be starved + - cheaper /proc reads, and a retention policy for old results + - the 30GB run +- Bigger steps: + - secondaries on other machines + - starting more secondaries when the queue is deep and there's memory to spare + - packaging as a di.parallel module + + +## To Do + +1. add in the global mem cap limit and test with 30GB +2. add deferred sync so when i run a job form another processes it will block the user until the job is complete +3. a tidy up of the code (mix of 4 and before dict usages), probably stick things in separate scripts where possible. Can probably get rid of alot of columns that i dont think i need anymore as well like start/registered time in the secondaries +4. change the log timestamps to be local time instead of utc, dont know if that is possible since we use a module +5. fix the start bash scripts to use the mem cap limit and start with a cgroup +6. Tidy up the readme +7. add a function to calcualte the mem used for a job and maybe store that data in the jobs table +8. do we need to run dispatch on a timer does it do naything? Yes for when a secondary crashes with an OOM failure so it can pick up tasks after a restart. It also picks up free tasks if the mem limit is hit once that task is done + + \ No newline at end of file diff --git a/bin/startprimary.sh b/bin/startprimary.sh index ff03c32..6ebbbf8 100644 --- a/bin/startprimary.sh +++ b/bin/startprimary.sh @@ -19,11 +19,26 @@ export QHOME="$KDBX_HOME" # used for creating logs # todo: have it create the absolute path mkdir -p logs -echo "start primary: port $PRIMARY_PORT, config $CONFIG" LOG="logs/primary.$(date -u +%Y.%m.%dD%H.%M.%S).log" +# Claude +# the command, wrapped in systemd-run when starting under a cgroup +USE_CGROUP="${USE_CGROUP:-1}" +CMD=("$KDBX_HOME/bin/q" src/primary.q -p "$PRIMARY_PORT") +if [[ "$USE_CGROUP" == 1 && -n "${GLOBAL_MEM_LIMIT:-}" ]]; then + if ! systemctl --user show-environment > /dev/null 2>&1; then # checks if there is a systemd user manager so we can create a cgroup + echo "startprimary: USE_CGROUP=1 but there's no systemd user session to make a cgroup in; set USE_CGROUP=0 to start without the memory cap" >&2 + exit 1 + fi + # --scope runs the command itself in a new cgroup; MemorySwapMax=0 means kill rather than swap; --quiet keeps systemd-run's own message out of the log + CMD=(systemd-run --user --scope --quiet -p MemoryMax="$GLOBAL_MEM_LIMIT" -p MemorySwapMax=0 "${CMD[@]}") + CAP="memory cap $GLOBAL_MEM_LIMIT bytes" +else + CAP="no memory cap" +fi + # nohup to run in backgorund if want to run interactively just use x src/primary.q -nohup "$KDBX_HOME/bin/q" src/primary.q -p "$PRIMARY_PORT" < /dev/null >> "$LOG" 2>&1 & +nohup "${CMD[@]}" < /dev/null >> "$LOG" 2>&1 & echo $! > logs/primary.pid -echo "startprimary: port $PRIMARY_PORT, config $CONFIG, pid $!, log $LOG" \ No newline at end of file +echo "startprimary: port $PRIMARY_PORT, $CAP, config $CONFIG, pid $!, log $LOG" \ No newline at end of file diff --git a/bin/startsecondary.sh b/bin/startsecondary.sh index 515ed77..7419874 100644 --- a/bin/startsecondary.sh +++ b/bin/startsecondary.sh @@ -34,6 +34,9 @@ LOG="logs/sec$ID.$(date -u +%Y.%m.%dD%H.%M.%S).log" # nohup to run in bbackgorund if want to run interactively just use x src/primary.q nohup "$KDBX_HOME/bin/q" src/secondary.q -p "$PORT" -id "$ID" < /dev/null >> "$LOG" 2>&1 & +# should we use secondaries +#nohup "$KDBX_HOME/bin/q" src/secondary.q -p "$PORT" -id "$ID" -s 8 < /dev/null >> "$LOG" 2>&1 & + echo $! > "logs/sec$ID.pid" echo "start secondary: id $ID, port $PORT, config $CONFIG, pid $!, log $LOG" diff --git a/bin/stopall.sh b/bin/stopall.sh new file mode 100644 index 0000000..296e4f9 --- /dev/null +++ b/bin/stopall.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash + +# Claude +# stop the primary and every secondary started with one config + +# forces script to exit as soon a the command fails, or an unset variable is used, or a pipe fails +set -euo pipefail + +CONFIG="${1:-config/default.env}" + +# set -a exports every variable the file sets, so q can read them with getenv +set -a +source "$CONFIG" +set +a + +# this user's primary and secondary processes for this config: PRIMARY_PORT in their environment, +# or, for a primary started without the config loaded, -p PRIMARY_PORT on its command line +ourpids() { + for pid in $(pgrep -u "$USER" -f 'src/(primary|secondary)\.q' || true); do + if tr '\0' '\n' < "/proc/$pid/environ" 2>/dev/null | grep -qx "PRIMARY_PORT=$PRIMARY_PORT" \ + || tr '\0' ' ' < "/proc/$pid/cmdline" 2>/dev/null | grep -q -- "-p $PRIMARY_PORT "; then + echo "$pid" + fi + done +} + +before=$(ourpids) +if [[ -z "$before" ]]; then + echo "stopall: nothing running for PRIMARY_PORT $PRIMARY_PORT" + exit 0 +fi +echo "stopall: running for PRIMARY_PORT $PRIMARY_PORT: pids $(echo $before)" + +# 1. ask the primary to exit (2s to connect); if it isn't there or doesn't answer, go straight to the wait and kill +"$KDBX_HOME/bin/q" -q <<'EOF' || true +h:@[hopen; (`$"::",getenv`PRIMARY_PORT; 2000); 0Ni]; +if[null h; -1 "stopall: could not connect to the primary, will kill instead"; exit 1]; +-1 "stopall: asking the primary to exit"; +neg[h]"exit 0"; neg[h][]; +exit 0 +EOF + +# 2. wait for everything to exit: the primary's own grace period, plus 5s +wait=$(( ${STOP_GRACE_PERIOD_SECS:-5} + 5 )) +for ((i=0; i/dev/null || true +sleep 2 +left=$(ourpids) +if [[ -n "$left" ]]; then + echo "stopall: killing with -9: pids $(echo $left)" + kill -9 $left 2>/dev/null || true +fi +echo "stopall: all stopped" \ No newline at end of file diff --git a/config/default.env b/config/default.env index 1673864..1739797 100644 --- a/config/default.env +++ b/config/default.env @@ -3,10 +3,43 @@ KDBX_HOME=/opt/kdbx/5.0/2026.07.23 # process info PRIMARY_PORT=45000 -SECONDARY_BASE_PORT=45001 -NUM_SECONDARYS=4 # 4GB currently for testing, need to run on 30GB eventually GLOBAL_MEM_LIMIT=4294967296 -TASK_TYPES=noop,sleep,sum,fail,bigTable +# for heartbeating +HEARTBEAT_MS=1000 +STALE_MS=5000 + +# for spinning up secondarys via the primary +SPAWN_SECONDARY=1 +NUM_SECONDARYS=8 +STOP_GRACE_PERIOD_SECS=5 +LOG_DIR=logs + +# for tasks +TASK_TIMEOUT_MS=60000 # 60 seconds timeout +TASK_RETRIES_MAX=3 +TASK_TYPES=sleep,sumtil,fail,vwap,hold +RETRY_REASONS=lost,sendfailed + +# mem stats from kernal +MEM_HISTORY_MAX=3600 + +# how many times the primary restarts a spawned secondary that dies (timeout, crash, OOM); 0 = never +RESPAWN_MAX=3 + +# start the primary under a cgroup with GLOBAL_MEM_LIMIT as the kernel's hard cap (bin/startprimary.sh); 0 for none +USE_CGROUP=1 + +# this is the multiple of the spare memory, 0 means no headroom, 0.1 means keep 10% free +MIN_HEADROOM=0 + +# this is the multiple of how much memory a task will use, 1 means use the current estimate 1.25 would mean estimate each task to use 25% more than the max memory task so far +ESTIMATE_MARGIN=1 + +# where to store results +RESULTS_DIR=/home/jrutledge/internalWork/Parallelisation-Project/results + +# test hdb dir +HDB_DIR=/home/jrutledge/internalWork/hdb \ No newline at end of file diff --git a/config/integration.env b/config/integration.env new file mode 100644 index 0000000..3e633f6 --- /dev/null +++ b/config/integration.env @@ -0,0 +1,15 @@ +# overrides for tests/integration.sh, sourced after config/default.env +# separate ports so a test run never clashes with a dev primary on 45000 +PRIMARY_PORT=46000 +NUM_SECONDARYS=2 +SPAWN_SECONDARY=1 +STOP_GRACE_PERIOD_SECS=1 +STALE_MS=3000 +LOG_DIR=logs/integration +TASK_TYPES=sumtil,sleep,fail,hold +RESULTS_DIR=/tmp/integrationtesting + +# integration specs kill secondaries on purpose and expect them to stay closed +RESPAWN_MAX=0 + +USE_CGROUP=0 \ No newline at end of file diff --git a/image.png b/image.png new file mode 100644 index 0000000..907595c Binary files /dev/null and b/image.png differ diff --git a/schemas/primarytables.q b/schemas/primarytables.q index 392cfb6..15066cd 100644 --- a/schemas/primarytables.q +++ b/schemas/primarytables.q @@ -1,37 +1,68 @@ -// tables for the master process +// tables for the primary process // monitor the secondary procs secondaries : ([id: `long$()] handle: `int$(); pid: `int$(); host: `$(); - port: `int$(); - status: `$(); // `idle`busy`stale`disconnected - lastHeartbeat: `timestamp$(); - lastMemBytes: `long$(); - consecutiveFails: `int$(); + status: `$(); // `free`busy`stale`closed + lastheartbeat: `timestamp$(); + consecutivefails: `int$(); healthy: `boolean$(); - spawned: `boolean$(); // if the master created it or it was up from before - startTime: `timestamp$(); - registeredTime: `timestamp$(); - taskTypes: (); - currentTask: `long$() + spawned: `boolean$(); // if the primary created it or it was up from before + starttime: `timestamp$(); + registeredtime: `timestamp$(); + tasktypes: (); + currenttask: `long$(); + rssanon: `long$(); // in bytes + vmrss: `long$(); // in bytes + memtime: `timestamp$() ); -// montiro the tasks that are being carried out -tasks : ([taskId: `long$()] - taskType: `$(); +// monitor the tasks that are being carried out +tasks : ([taskid: `long$()] + tasktype: `$(); args: (); priority: `int$(); - submittedTime: `timestamp$(); - timeoutMs: `long$(); - retriesMax: `int$(); - retryCount: `int$(); + submittedtime: `timestamp$(); + memestimate: `long$(); + timeout: `time$(); + retriesmax: `int$(); + retrycount: `int$(); state: `$(); // `queued`dispatched`running`done`failed - secondaryId: `long$(); - dispatchedTime: `timestamp$(); - startedTime: `timestamp$(); - finishedTime: `timestamp$(); + secondaryid: `long$(); + dispatchedtime: `timestamp$(); + startedtime: `timestamp$(); + finishedtime: `timestamp$(); + membefore: `long$(); // RssAnon before running + memafter: `long$(); // peak during the task VmHWN; or a task killed for memory, the cap it was killed under + memaftergc: `long$(); // RssAnon after the task ends and .Q.gc err: (); - reason: `$() // `timeout`unknown`oom + reason: `$(); // `timeout`oom`error`lost`sendfailed + resultpath: `$(); + resultbytes: `long$(); + jobid: `long$(); + user: `$() + ); + +// one row per memory poll, bounded to the last .primary.memhistorymax rows +memhistory : ([] + time: `timestamp$(); + total: `long$(); + primary: `long$(); + secondaries: `long$(); + busy: `int$() + ); + +// groups of tasks submitted together; when every part is done their results are combined into one +jobs : ([jobid: `long$()] + tasktype: `$(); + user: `$(); + ntasks: `int$(); + priority: `int$(); + state: `$(); + submittedtime: `timestamp$(); + finishedtime: `timestamp$(); + resultbytes: `long$(); + err: () // why the job failed, "" when it hasn't ); \ No newline at end of file diff --git a/src/approvedtasks.q b/src/approvedtasks.q new file mode 100644 index 0000000..74bdf1e --- /dev/null +++ b/src/approvedtasks.q @@ -0,0 +1,34 @@ +// this is a file containing any approved task +// we define an empty dict at the top, then a task then after we add this to the approved task +// all tasks that needs several args should be passed as a dict + +.secondary.approvedtasks:()!(); + +// these are the test tasks before we define ones that would actually be useful + +.task.sumtil:{sum til x}; +.secondary.approvedtasks[`sumtil]:.task.sumtil; + +.task.sleep:{system"sleep ",string x}; +.secondary.approvedtasks[`sleep]:.task.sleep; + +.task.fail:{'`fail}; +.secondary.approvedtasks[`fail]:.task.fail; + +/claude for the kernal mem stuff +/ test task: take a`mb MB of memory and keep it for a`secs seconds, so the memory gate can see it; a is `mb`secs!(mb;secs) +/ 131072 longs = 1MB; filling with 0 writes every page, so the memory really is used (RssAnon) +// .task.hold ([mb:600; secs:10]) +.task.hold:{[a] v:(a[`mb]*131072)#0; system "sleep ",string a`secs; count v}; +.secondary.approvedtasks[`hold]:.task.hold; + +// actual useful ones + +// lets add in a vwap where each secondary will do it for a different month for a time period +// means if we start with 4 secondarys, the primary needs to spin up 8 more if we are doing it over a year +// we will also need to combine the results correctly +// params is just a dict with sdate and edate +.task.vwap:{[d] + select vwap: size wavg price by date,sym from trades where date = d + }; +.secondary.approvedtasks[`vwap]:.task.vwap; \ No newline at end of file diff --git a/src/common/cgroup.q b/src/common/cgroup.q new file mode 100644 index 0000000..5778aa8 --- /dev/null +++ b/src/common/cgroup.q @@ -0,0 +1,18 @@ +// Claude minor edits +// the cgroup v2 directory this primary and the secondaries it spawns run in, e.g. /sys/fs/cgroup/user.slice/.../qfw.scope +// "" if it can't be found. Its memory.events file counts kernel OOM kills (only meaningful under a MemoryMax limit) +.cgroup.dir:{ + l:@[system; "cat /proc/",string[.z.i],"/cgroup"; {[e] ()}]; + l:l where l like "0::*"; + $[count l; "/sys/fs/cgroup",3_first l; ""] + }[]; + + +// how many processes the kernel has killed for memory in cgroup directory d (the oom_kill line of its memory.events) +// 0N if it can't be read: no directory, not cgroup v2, or no memory controller +.cgroup.oomkills:{[dir] + if[not count dir; :0N]; + l:@[system; "cat ",dir,"/memory.events 2>/dev/null"; {[e] ()}]; + l:l where l like "oom_kill *"; + $[count l; "J"$last " " vs first l; 0N] + }; \ No newline at end of file diff --git a/src/common/mem.q b/src/common/mem.q new file mode 100644 index 0000000..dfd6ad6 --- /dev/null +++ b/src/common/mem.q @@ -0,0 +1,44 @@ +// the fields read from /proc//status +// RssAnon = the process's own memory (q's heap as the kernel sees it), what the global cap adds up +// VmRSS = all resident memory (RssAnon + file pages), VmHWM = the high-water mark of VmRSS +.mem.fields:`RssAnon`VmRSS`VmHWM; + +// what .mem.read returns when there is nothing to read +.mem.empty:([] pid:`int$(); rssanon:`long$(); vmrss:`long$(); vmhwm:`long$()); + +// turn the lines of one or more /proc//status files into a table, one row per process +// each line looks like "VmRSS:\t 12345 kB": the name before the colon, then the first word after it +// every status file starts with a Name line, so a running count of Name lines says which process a line is from +.mem.parse:{[l] + k:`$first each ":" vs/: l; + v:{w:" " vs ssr[last ":" vs x;"\t";" "]; first w where 0/dev/null; true'" + }; + +// reset this process's VmHWM to its current VmRSS, so the next reading of vmhwm is the peak since now +// written through sh as clear_refs is write-only and hopen can't open it; uses our own pid, as /proc/self in sh is the shell +.mem.clearhwm:{[] + @[system; "sh -c 'echo 5 > /proc/",string[.z.i],"/clear_refs'"; {[e] .log.warn "could not reset VmHWM: ",e}]; + }; + +// this process's figures (a dict) and then reset VmHWM, in one shell call instead of two (~4ms saved per task) +// used just before a task: rssanon is the starting point, and vmhwm read after the task is the task's peak +.mem.readandclear:{[] + p:string .z.i; + first .mem.parse system "sh -c 'cat /proc/",p,"/status; echo 5 > /proc/",p,"/clear_refs 2>/dev/null; true'" + }; \ No newline at end of file diff --git a/src/common/os.q b/src/common/os.q new file mode 100644 index 0000000..01dc787 --- /dev/null +++ b/src/common/os.q @@ -0,0 +1 @@ +.os:use `di.os \ No newline at end of file diff --git a/src/common/timer.q b/src/common/timer.q new file mode 100644 index 0000000..6161133 --- /dev/null +++ b/src/common/timer.q @@ -0,0 +1,30 @@ +// is this good practice since it isnt under kx? +.timer:use`di.timer; + +// run jobs +.timer.init[]; + + +/ +this is just for me to haeva quick reference and some examples of how to use while im doing dev work + +// adding job +use .timer.addjob.custom +.timer.addjob.custom[id; func; params; period; mode; opts] +id: job name +func: what function we want to run +params: params to be passed to the function +period: time period running in seconds +mode: when the next run time is (use 2 it runs period seconds after the actual start) +opts: extra options i.e maxruns/maxtime/disableonfail/startattime + +eg. +.timer.addjob.custom[`stalecheck; {.primary.check[]}; (); 1; 2; (enlist`disableonfail)!enlist 0b]; + +// how to check what jobs are scheduled +.timer.getalljobs[] + +// how to start +.timer.init starts all jobs running + +\ \ No newline at end of file diff --git a/src/primary.q b/src/primary.q index 46deac2..d5947b2 100644 --- a/src/primary.q +++ b/src/primary.q @@ -9,10 +9,530 @@ system"l schemas/primarytables.q"; // todo: change this in the future to load in the entire common code or all files with an each // also look at resolving the dir name for a full file path use an env var in the config file system"l src/common/log.q"; +system"l src/common/timer.q"; +system"l src/common/os.q"; +system"l src/common/mem.q"; +system"l src/common/cgroup.q"; -.primary.start:{[] +// get env vars +.primary.stale:00:00:00.001*"J"$getenv`STALE_MS; +.primary.heartbeat:00:00:00.001*"J"$getenv`HEARTBEAT_MS; +.primary.spawnsecondaries:"B"$getenv`SPAWN_SECONDARY; +.primary.numsecondaries:"J"$getenv`NUM_SECONDARYS; +.primary.stopgraceperiod:"J"$getenv`STOP_GRACE_PERIOD_SECS; +.primary.logdir:getenv`LOG_DIR; +.primary.qbin:getenv[`KDBX_HOME],"/bin/q"; +.primary.starttime:0Np; +.primary.secondarystates:`free`busy`stale`closed; +.primary.taskstates:`queued`dispatched`running`done`failed; +.primary.tasktimeout:`time$"J"$getenv `TASK_TIMEOUT_MS; +.primary.taskretries:"I"$getenv`TASK_RETRIES_MAX; +.primary.tasktypes:`$"," vs getenv`TASK_TYPES; +.primary.lasttaskid:0; +.primary.retryreasons:`$"," vs getenv `RETRY_REASONS; +.primary.memhistorymax:"J"$getenv`MEM_HISTORY_MAX; +.primary.selfmem:0N; // the primary's own rssanon, bytes, from the last poll // these are Claudes +.primary.memcap:"J"$getenv`GLOBAL_MEM_LIMIT; // the global cap in bytes; null (unset or empty) = no cap +.primary.paused:0b; // is dispatching new tasks held back by the mem cap +.primary.pausedsince:0Np; // when the current pause started +.primary.pausedtotal:0D; // total time spent paused +.primary.pausecount:0; // how many times dispatch has paused +.primary.respawnmax:"J"$getenv`RESPAWN_MAX; // how many times a spawned secondary is restarted after dying; 0 or null = never +.primary.resultsroot:getenv `RESULTS_DIR; +.primary.lastjobid:0; +.primary.minheadroom:0f^"F"$getenv`MIN_HEADROOM_FRACTION; +.primary.estimatemargin:1f^"F"$getenv`ESTIMATE_MARGIN; + + +// dict of secondaries ids to their pids that the primary started +.primary.spawned:(`long$())!`int$(); + +// defaults for the optional task fields, newtask fills any missing field from here +.primary.taskdefaults:([priority:0i; memestimate: 0N; timeout: .primary.tasktimeout; retriesmax: .primary.taskretries]); + +// what each task status can move too +.primary.taskchange:([queued: `dispatched`failed; dispatched: `running`failed; running: `done`failed; done:`$(); failed:enlist `queued]); + +// the time column that gets updated at each task status +.primary.statustime:([dispatched: `dispatchedtime; running: `startedtime; done: `finishedtime; failed: `finishedtime]); + +// restarts so far, by secondary id +.primary.respawns:(`long$())!`long$(); + + +// when a secondary starts add it to the secondaries table +// example run: +// .primary.register ([id:5; pid:4000i; host:`localhost]) +.primary.register:{[info] + `secondaries upsert ([id: info`id; handle: .z.w; pid: info`pid; host: info`host; status: `free; + lastheartbeat: .z.P; consecutivefails: 0i; healthy: 1b; spawned: info[`id] in key .primary.spawned; + starttime: .z.P; registeredtime: .z.P; tasktypes: (); currenttask: 0N; rssanon: 0N; vmrss: 0N; memtime: 0Np]); + .log.info "secondary ", string[info`id], " registered at: ", string .z.P; + .primary.resultsdir + }; + +// to be called by each secondary except when its status is running, ran based off HEARTBEAT_MS +// CLAUDE: a heartbeat only brings a stale secondary back: it must never free a busy one, a heartbeat sent just +// before a task arrived can be processed after dispatch has marked it busy + +.primary.heartbeatcheck:{[mem] + update lastheartbeat:.z.P, rssanon: mem from `secondaries where handle=.z.w; + update status:`free from `secondaries where handle=.z.w, status=`stale; + }; + +// mark secondaries that arent sedning updates as stale +.primary.check:{ + if[not count secondaries; :()]; + stale: exec id from secondaries where status=`free, lastheartbeat < .z.P - .primary.stale; + if[count stale; + update status:`stale from `secondaries where id in stale; + .log.warn "no heartbeat from secondary ",(", " sv string stale)]; + }; + + +// how many of each state appear in the status col, done like this so can have 0 for failed say if no failed in the status col +.primary.countby:{[states;statuscol] states!sum each statuscol=/:states}; + +// a snapshot of the primarys status +// memory is in bytes headroom how far under the cap we are +.primary.status:{ + secs:select id, pid, status, spawned, currenttask, rssanon, restarts:0^.primary.respawns id, lastseen:`time$.z.P-lastheartbeat from 0!secondaries; + tot:.primary.totalmem[]; + mem:([total:tot; cap:.primary.memcap; headroom:.primary.memcap-tot; primary:.primary.selfmem]); + pt:.primary.pausedtotal+$[.primary.paused; .z.P-.primary.pausedsince; 0D]; + disp:([paused:.primary.paused; pausecount:.primary.pausecount; pausedtotal:pt; pausedsince:.primary.pausedsince]); + ([time: .z.P; uptime: .z.P - .primary.starttime; memory: mem; dispatch: disp; secondaries: secs; seccounts: .primary.countby[.primary.secondarystates;exec status from secondaries]; taskcounts: .primary.countby[.primary.taskstates;exec state from tasks]]) + }; + +// the same snapshot, printed for a person at the console +.primary.showstatus:{ + pristatus:.primary.status[]; + fmt:{[d] ", " sv {[d;k] string[d k]," ",string k}[d] each key d}; + -1 "== primary status ",string[pristatus`time]," uptime ",string[pristatus`uptime]," =="; + m:pristatus`memory; + -1 "memory: ",.primary.mb[m`total]," in use, ",$[null m`cap; "no cap"; .primary.mb[m`cap]," cap, ",.primary.mb[m`headroom]," headroom"]; + d:pristatus`dispatch; + -1 "dispatch: ",$[d`paused; "PAUSED (memory over the cap) since ",string d`pausedsince; "running"],", paused ",string[d`pausecount]," times for ",string d`pausedtotal; + -1 "secondaries: ",fmt pristatus`seccounts; + show `id xasc select id, pid, status, spawned, task:currenttask, memmb:0.1*floor 0.5+10*rssanon%1048576, restarts, lastseen from pristatus`secondaries; + -1 "tasks: ",fmt pristatus`taskcounts; + }; + +// command line for secondary n, e.g. /opt/kdbx/.../q src/secondary.q -id 2 +// look at wrapping in protected execution +.primary.spawncmd:{[n] + " " sv (.primary.qbin; "src/secondary.q"; "-id"; string n) + }; + +// ids taken right now: registered and still connected, or spawned by this primary and still running +.primary.usedids:{ + exec id from secondaries where status<>`closed + }; + +// the lowest id not in use, e.g. 3 when 1, 2 and 4 are taken +.primary.nextid:{ + ids:.primary.usedids[]; + min (1+til 1+count ids) except ids + }; + +// bring up a secondary with a given id +// example uage: +// .primary.spawn 1 +.primary.spawn:{[n] + if[n in .primary.usedids[]; + .log.warn "secondary ",string[n]," already exists; next available id is ",string .primary.nextid[]; + :()]; + .os.mkdir .primary.logdir; + logfile:.primary.logdir,"/sec",string[n],".",ssr[19#string .z.P;":";"."],".log"; + startcmd:.primary.spawncmd[n]," < /dev/null >> ",logfile," 2>&1 & echo $!"; + pid:"I"$first system startcmd; + .log.info "running system command: ", startcmd; + .primary.spawned[n]:pid; + .log.info "spawned secondary ",string[n]," (pid ",string[pid],")"; + }; + +// used to shut down all spawned secondaries +.primary.stop:{ + .log.info "stopping secondaries"; + handles:exec handle from secondaries where not null handle, not status=`closed; + {[h] @[neg[h];(`.secondary.stop;::);{[e] ::}]} each handles; /// no stop sec func on sec.q script + .os.sleep .primary.stopgraceperiod; + left:p where .os.exists each "/proc/",/:string p:value .primary.spawned; + if[count left; + .log.warn "killing secondaries that didn't exit: pids ",", " sv string left; + {[p] @[.os.kill9;p;{[e] ::}]} each left]; + .primary.spawned:(`long$())!`int$(); + .log.info "stopped"; + }; + +// tasks will only ever go up +.primary.nexttaskid:{ + .primary.lasttaskid+::1; + .primary.lasttaskid + }; + + +// add a new tesk to the tasks table +// task is a dict with tasktype and args always required evry other col is optional +.primary.newtask:{[task] + if[not 99h=type task; + .log.warn "newtask: a task must be a dict"; :0N]; + if[not all `tasktype`args in key task; + .log.warn "newtask: tasktype and args are required"; :0N]; + if[not task[`tasktype] in .primary.tasktypes; + .log.warn "newtask: unknown task type ",string task`tasktype; :0N]; // this can be rejected here before it gets to a secondary + if[count bad:key[task] except `tasktype`args,key .primary.taskdefaults; + .log.warn "newtask: unknown fields ",", " sv string bad; :0N]; + tid:.primary.nexttaskid[]; + data:.primary.taskdefaults,task, + ([taskid:tid; args:enlist task`args; submittedtime:.z.P; retrycount:0i; state:`queued; secondaryid:0N; dispatchedtime:0Np; startedtime:0Np; + finishedtime:0Np; membefore:0N; memafter:0N; memaftergc:0N; err:""; reason:`; resultpath:`; resultbytes:0N; jobid:0N; user:`]); + `tasks upsert data; + .log.debug "new task ",string[tid]," ",string task`tasktype; + tid + }; + +// update task status using .primary.taskchange and .primary.statustime +// params allows us to update other columns eg. maxretires and retrycount +// if nothing for params it should be an empty dict +.primary.taskupdate:{[tid; newstate; params] + if[not count exec taskid from tasks where taskid=tid; + .log.warn"the task id ",string[tid]," is not present in the tasks table"; + :0b]; + oldstate: first exec state from tasks where taskid=tid; + if[not newstate in .primary.taskchange oldstate; + .log.warn"the new task state ",string[newstate]," is not a valid option choose one of the following: ",", " sv string .primary.taskchange oldstate; + :0b]; + timecol: $[newstate in key .primary.statustime; (enlist .primary.statustime newstate)!enlist .z.P; ()!()]; + params: params, timecol, ([taskid: tid; state: newstate]); + upsert[`tasks; params]; + .log.info "updated task id ",string[tid]," from ",string[oldstate]," to ",string newstate; + if[newstate in `done`failed; + sid:first exec secondaryid from tasks where taskid=tid; + update status:`free, currenttask:0N from `secondaries where id=sid, currenttask=tid, status=`busy; + // Claude as part of bench-401 + // the secondary has just given its memory back (.Q.gc[]): use its own after-gc figure until the next poll, + // so dispatch sees the freed memory straight away instead of the last poll's reading + if[`memaftergc in key params; + if[not null params`memaftergc; update rssanon:params`memaftergc from `secondaries where id=sid]]]; + if[newstate=`failed; .primary.retry tid]; + if[newstate in `done`failed; .primary.jobcheck tid]; + if[newstate in `done`failed; .primary.dispatch[]]; // prevents us waiting on the timer, when bench marking this was the biggest this was biggest bottleneck so added it + 1b + }; + +// sends the task to the secondary, if sending fails early exit and mark as stale +.primary.sendtask:{[sid; tid] + if[not (`free~secondaries[sid]`status) and `queued~tasks[tid]`state; :()]; // double check if this is needed in testing remove it for a bit + h:first exec handle from secondaries where id=sid; + t:tasks tid; + update status:`busy, currenttask:tid from `secondaries where id=sid; + .primary.taskupdate[tid; `dispatched; ([secondaryid: sid])]; + res:@[neg[h]; (`.secondary.runtask; tid; t`tasktype; first t`args); {[error] (`sendfailed; error)}]; + if[`sendfailed~ first res; + .log.warn "cannot send task ",string[tid]," to secondary ",string sid; + update status:`stale, currenttask: 0N from `secondaries where id=sid; + :.primary.taskupdate[tid; `failed; ([err:"send failed with error: ",last res; reason:`sendfailed])]; + ]; + .log.info "sent task ",string[tid]," (",string[t`tasktype],") to secondary ",string sid; + }; + +// Claude +// memory in use, or about to be, in bytes: the primary, plus each live secondary's current memory (rssanon) or, +// for a busy one, its task's estimate if that's more: a task that has just started hasn't grown yet +// before the first memory poll, the primary's own figure is unknown (0N), so it counts as 0 +.primary.committedmem:{ + s:select rssanon, currenttask from secondaries where status<>`closed; + // each secondary's current task's estimate; 0 for a free secondary or a task with no estimate + taskest:0^(exec taskid!memestimate from tasks) s`currenttask; + (0^.primary.selfmem) + sum (0^s`rssanon)|taskest + }; + +// Claude with edits from me +// which of the queued tasks to send now: at most n of qtasks (already in dispatch order), each only if its +// memestimate fits in the memory left under the cap; what's sent is reserved, so one dispatch can't hand out +// the same headroom twice. A task that doesn't fit waits and a smaller one behind it can go; a task with no +// estimate always goes (it's how a new task type is learnt). With no cap set, the first n go as before +// two settings make it more careful, both off by default: +// - MIN_HEADROOM_FRACTION: each task must leave this fraction of the cap free (the brief's dispatchWatermarkBytes); +// a task with no estimate only goes if at least that much is free +// - ESTIMATE_MARGIN: each task counts as its estimate times this (the brief's headroomSafetyFactor, turned round) +.primary.fit:{[qtasks; n] + if[null .primary.memcap; :n sublist qtasks]; + // the memory we can hand out: what's left under the cap, less the spare we keep + usable:.primary.memcap-.primary.committedmem[]+`long$.primary.minheadroom*.primary.memcap; + // what each task counts as: its estimate plus the margin, rounded up; 0 for a task with no estimate + need:ceiling .primary.estimatemargin*0^(exec taskid!memestimate from tasks) qtasks; + // nothing running: send the first task whatever its size, so it can't wait for ever on the secondaries' + // own baseline memory, the spare or the margin + if[not count select from secondaries where status=`busy; usable:usable|first need]; + // the memory left after each task: one that fits uses up what it needs, one that doesn't leaves it unchanged + left:usable {[room;need] $[need<=room; room-need; room]}\ need; + // a task fits if what it needs is within what was left before it + fits:need<=usable,-1_left; + n sublist qtasks where fits + }; + +// hand a queued task to a secondary, do it by priority then by oldest first +// will run on a timer every 1 sec +.primary.dispatch:{ + freesec: exec id from secondaries where status=`free; + if[not count freesec; :()]; + qtasks: exec taskid from `priority xdesc select taskid, priority from 0!tasks where state=`queued; + if[not count qtasks; :()]; + // the memory gate: send nothing new while total memory is over the cap + if[.primary.overcap[]; :()]; + // V2: only the tasks whose estimates fit in what's left under the cap + qtasks:.primary.fit[qtasks; count freesec]; + n:min count[freesec], count qtasks; + if[n=0; :()]; + .primary.sendtask'[n#freesec; n#qtasks]; + }; + +// rerun a failed task or one where a secondary has died +.primary.retry:{[tid] + t:tasks tid; + if[not t[`reason] in .primary.retryreasons; :0b]; + if[t[`retrycount]>=t`retriesmax; + .log.warn "task ",string[tid]," has used all ",string[t`retriesmax]," retries, leaving it failed"; + :0b]; + .log.info "retrying task ",string[tid],", retry ",string[1+t`retrycount]," of ",string t`retriesmax; + .primary.taskupdate[tid; `queued; ([retrycount:1i+t`retrycount; secondaryid:0N; dispatchedtime:0Np; startedtime:0Np; finishedtime:0Np; membefore:0N; memafter:0N; memaftergc:0N; err:""; reason:`])]; + }; + +// Claude with minor edits from me +// read our own memory and every live secondary's from /proc in one call, store it, and add a history row +// works for busy secondaries too: nothing is asked of them. A pid that has gone gets nulls until .z.pc closes it +.primary.pollmem:{ + m:.mem.read .z.i, exec pid from secondaries where status<>`closed; + .primary.selfmem:first exec rssanon from m where pid=.z.i; + ra:exec pid!rssanon from m; + rs:exec pid!vmrss from m; + update rssanon:ra pid, vmrss:rs pid, memtime:.z.P from `secondaries where status<>`closed; + sec:exec sum rssanon from secondaries where status<>`closed; + `memhistory insert (.z.P; .primary.selfmem+sec; .primary.selfmem; sec; exec `int$count i from secondaries where status=`busy); + if[.primary.memhistorymax.primary.memcap; + if[overcap and not .primary.paused; + .primary.paused:1b; .primary.pausedsince:.z.P; .primary.pausecount+:1; + .log.warn "pausing dispatch: memory ",.primary.mb[tot]," is over the cap of ",.primary.mb .primary.memcap]; + if[.primary.paused and not overcap; + .primary.paused:0b; .primary.pausedtotal+:.z.P-.primary.pausedsince; + .log.info "resuming dispatch: memory ",.primary.mb[tot]," is under the cap of ",.primary.mb[.primary.memcap],", was paused for ",string .z.P-.primary.pausedsince]; + overcap + }; + +// Claude with minor edits from me +// total memory in use: the primary plus every live secondary, from the last poll, in bytes +.primary.totalmem:{.primary.selfmem + exec sum rssanon from secondaries where status<>`closed}; + +// claude +// fail tasks that have run past their timeout. A busy secondary can't be interrupted, so its process is killed. +// Counts from startedtime, or dispatchedtime if the secondary never reported running +.primary.checktimeouts:{ + late:0!select taskid, secondaryid, timeout from tasks where state in `dispatched`running, .z.P>timeout + dispatchedtime^startedtime; + if[not count late; :()]; + .primary.timeout'[late`taskid; late`secondaryid; late`timeout]; + }; + +//claude minor edits +// time out one task: take its secondary out of use and fail the task first, then kill the process. +// .z.pc fires once the process is dead, finds no task to fail as lost, and respawns the secondary +.primary.timeout:{[tid;sid;t] + pid:first exec pid from secondaries where id=sid; + .log.warn "task ",string[tid]," on secondary ",string[sid]," has run past its timeout of ",string[t],", killing pid ",string pid; + update status:`closed, currenttask:0N from `secondaries where id=sid; + .primary.taskupdate[tid; `failed; ([err:"timed out after ",string t; reason:`timeout])]; + @[.os.kill9; pid; {[e] .log.warn "could not kill secondary: ",e}]; + }; + +// restart a spawned secondary that has died capped with .primary.respawnsmax +.primary.respawnsecondary:{[sid] + if[not sid in key .primary.spawned; :()]; + n:0^.primary.respawns sid; + if[not n < .primary.respawnmax; + .log.warn "secondary ",string[sid]," has been restarted ",string[n]," times already, max secondary restarts is ",string .primary.respawnmax; + :()]; + .primary.respawns[sid]:n+1; + .log.info "restarting secondary ",string[sid],", restart ",string[n+1]," of ",string .primary.respawnmax; + .primary.spawn sid; + }; + +// 1b if the kernel has killed a process in our cgroup for memory since we last checked, and count that kill as accounted for +// the kernel counts the kill before the connection close reaches us, so this is called from .z.pc +.primary.oomkilled:{ + n:.cgroup.oomkills .primary.cgroupdir; + if[null n; :0b]; + if[n<=.primary.oomkills; :0b]; + .primary.oomkills+:1; + 1b + }; + +// splits a job up into individual tasks +// .primary.newjob[`vwap; 2026.01.01 2026.01.02 2026.01.03; ([priority:1])] +// .primary.newjob[`vwap; 2026.01.01 2026.01.02 2026.01.03; ()!()] +.primary.newjob:{[tasktype; args; params] + if[not tasktype in .primary.tasktypes; '"unknown task type ",string tasktype]; + if[not count args; '"no args: a job needs at least one task"]; + if[not all key[params] in key .primary.taskdefaults; '"optional parasm are: ",", " sv string key .primary.taskdefaults]; + params:@[.primary.taskdefaults, params; `priority`retriesmax; `int$]; + est:.primary.estimatemem[tasktype; args]; + if[not est`run; + .log.warn "job refused for ",string[.z.u],": ",est`reason; + '"job refused: ",est`reason]; + if[null params`memestimate; params[`memestimate]:est`estimate]; + ids:.primary.newtask each {y,([tasktype: x; args: z])}[tasktype;params] each args; + if[any null ids; + delete from `tasks where taskid in ids; + '"could not create every task for the job, see the log"]; + jid:.primary.lastjobid+:1; + update jobid:jid, user:.z.u from `tasks where taskid in ids; + pri:params`priority; + `jobs upsert (jid; tasktype; .z.u;`int$count ids; pri; `running; .z.P; 0Np; 0N; ""); + .log.info "new job ",string[jid]," for ",string[.z.u],": ",string[count ids]," ",string[tasktype]," tasks (",string[first ids],"..",string[last ids],"), priority ",string pri; + .primary.dispatch[]; + jid + }; + +// checks if a job has completed, if yes updates the total size of the result of it +// if it fails anywhere +.primary.jobcheck:{[tid] + jid:first exec jobid from tasks where taskid = tid; + if[null jid; :()]; + if[not `running ~ first exec state from jobs where jobid = jid; :()]; + states:exec state from tasks where jobid = jid; + if[`failed in states; + fail:first 0!select taskid, reason, err from tasks where jobid = jid, state = `failed; + error:"task ",string[fail`taskid]," failed (",string[fail`reason],"): ",fail`err; + update state:`failed, finishedtime:.z.P, err:enlist error from `jobs where jobid = jid; + .primary.canceljob jid; + :.log.warn "job ",string[jid]," failed: ",error]; + if[all states=`done; + bytesize:exec sum resultbytes from tasks where jobid=jid; + update state:`done, finishedtime:.z.P, resultbytes:bytesize from `jobs where jobid = jid; + .log.info "job ",string[jid]," is done: ",string[count states]," tasks, ",.primary.mb bytesize]; + }; + +// if a task fails that is part of a bigger job it will cancel the remaining tasks for that job that havent started +.primary.canceljob:{[jid] + qdtasks:exec taskid from tasks where jobid = jid, state = `queued; + if[not count qdtasks; :()]; + .primary.taskupdate[; `failed; ([err:"cancelled: another part of job ",string[jid]," failed"; reason:`cancelled])] each qdtasks; + .log.warn "job ",string[jid],": cancelled ",string[count qdtasks]," queued tasks"; + }; + +// get the paths to where the result was saved for all tasks under the same jobid +// example run; raze get each .primary.jobpaths 1 +.primary.jobpaths:{[jid] + state:first exec state from jobs where jobid = jid; + if[not `done ~ state; '"job ",string[jid]," is ",string state]; + exec resultpath from tasks where jobid = jid, not null resultpath + }; + +// Claude +// what earlier tasks say about a job of ttype with jobargs, checked for the whole job at once +// ttype: the job's task type, e.g. `vwap (not called tasktype: inside q-sql the column would win) +// jobargs: the job's args, one per task (a list, or a table with one row per task) +// 1. the task type: the estimate is the most any successful task of this type has used; refused if that's +// at or over the cap, as such a job could never fit +// 2. the args: earlier tasks given any of this job's args; refused if any of them was killed for memory under +// a cap at least as high as now (raising the cap lets it run again) +// returns ([estimate: bytes, 0N if nothing is known; run: 1b if the job can run; reason: "" or why not]) +// history is the tasks table, so it is in memory only and starts empty when the primary restarts +.primary.estimatemem:{[ttype; jobargs] + // every finished task of this type; peak minus before is what the task used + // args stay boxed as stored (enlisted); unboxing a list of dicts in the select turns it into a table, which breaks in + history:0!select args, reason, state, memused:memafter-membefore, memafter + from tasks where tasktype=ttype, state in `done`failed; + + // first time this type has been run: nothing to go on, so let it run and learn from it + if[not count history; + .log.info "no history for ",string[ttype]," tasks yet, running without an estimate"; + :([estimate:0N; run:1b; reason:""])]; + + // 1. the task type: the most any successful task of this type has used + // (max of an empty list is -0W in q, not null, so check there are some first) + used:exec memused from history where state=`done, not null memused; + estimate:$[count used; max used; 0N]; + if[(not null estimate) and (not null .primary.memcap) and estimate>=.primary.memcap; + :([estimate:estimate; run:0b; reason:string[ttype]," tasks need about ",.primary.mb[estimate], + ", at or over the cap of ",.primary.mb .primary.memcap])]; + + // 2. the args: earlier tasks given any of this job's args, all compared in one go + // each arg is compared as its serialised bytes (-8!), which works for any kind of arg: dates, numbers, lists, + // and dicts as hold uses. first unboxes the stored args; -8!' goes item by item, or row by row for a table of args + history:update argbytes:-8!'first each args from history; + seen:select from history where argbytes in -8!'jobargs; + if[not count seen; + .log.info "none of this job's ",string[ttype]," args have run before"; + :([estimate:estimate; run:1b; reason:""])]; + + // any of them killed for memory under a cap at least as high as now? memafter is that cap (set in .z.pc) + if[not null .primary.memcap; + kills:select from seen where reason=`oom, not null memafter, memafter>=.primary.memcap; + if[count kills; + :([estimate:estimate; run:0b; reason:string[count distinct kills`argbytes]," of this job's ",string[ttype], + " args were killed for memory before, under a ",.primary.mb[max kills`memafter]," cap (e.g. ",(-3!first first kills`args), + "); the cap is ",.primary.mb .primary.memcap])]]; + + // args killed for memory before needed at least the cap they hit: never estimate them below it + // (only reached when the cap has since been raised, otherwise the job was refused above) + killedat:exec max memafter from seen where reason=`oom, not null memafter; + if[not null killedat; estimate:estimate|killedat]; + + ([estimate:estimate; run:1b; reason:""]) + }; + +// if a connection is close we need to mark it as closed +// we will now restart a secondary if it is closed and under .primary.respawnsmax +.z.pc:{[h] + secid: first exec id from secondaries where handle=h; + tid: first exec currenttask from secondaries where id=secid; + update status:`closed, handle:0Ni, currenttask: 0N from `secondaries where id=secid; + // was it killed by the kernel for memory? only check for secondaries, so other connections closing don't use up a kill + oom:$[null secid; 0b; .primary.oomkilled[]]; + .log.info "secondary ",string[secid]," has closed its connection to the primary",$[oom; ": killed by the kernel for using too much memory"; ""]; + if[not null tid; + r:$[oom; ([err:"secondary killed by the kernel for using too much memory"; reason:`oom; memafter:.primary.memcap]); ([err:"secondary lost"; reason:`lost])]; + .primary.taskupdate[tid; `failed; r]; + .log.warn "task ",string[tid]," was on secondary ",string[secid],", marking it as failed (",string[r`reason],")"]; + .primary.respawnsecondary secid; + }; + +// quitting the primary kills any spawned secondaries +.z.exit:{ if[count .primary.spawned; .primary.stop[]]}; + +// start sequence +.primary.start:{ + if[not .primary.minheadroom within 0 0.99; '"MIN_HEADROOM_FRACTION must be from 0 to 0.99"]; + if[.primary.estimatemargin<=0; '"ESTIMATE_MARGIN must be more than 0"]; + if[not count .primary.resultsroot; '"RESULTS_DIR is not set"]; + .primary.resultsdir::.primary.resultsroot,"/",ssr[string .z.P;":";"."]; + system "mkdir -p ",.primary.resultsdir; + .log.info "task results will be saved in ",.primary.resultsdir; + .primary.cgroupdir:.cgroup.dir[]; + .primary.oomkills:.cgroup.oomkills .primary.cgroupdir; + if[.primary.spawnsecondaries; .primary.spawn each 1+til .primary.numsecondaries]; + .timer.addjob.custom[`stalecheck; {.primary.check[]}; (); 1; 2; ()!()]; + .timer.addjob.custom[`dispatch; {.primary.dispatch[]}; (); 1; 2; ()!()]; + .timer.addjob.custom[`mempoll; {.primary.pollmem[]}; (); 1; 2; ()!()]; + .timer.addjob.custom[`timeoutcheck; {.primary.checktimeouts[]}; (); 1; 2; ()!()]; .log.info "primary started, listening on ",string system "p"; - }; + .primary.starttime:: .z.P; + }; // start primary .primary.start[]; \ No newline at end of file diff --git a/src/secondary.q b/src/secondary.q index 9d6f57e..428a01e 100644 --- a/src/secondary.q +++ b/src/secondary.q @@ -1,19 +1,106 @@ -// this is a secondary process: it runs tasks the master sends it and reports back +// this is a secondary process: it runs tasks the primary sends it and reports back // example run -// x src/secondary.q -p 45001 -id 1 +// x src/secondary.q -id 1 // load in common code libs // todo: change this in the future to load in the entire common code or all files with an each // also look at resolving the dir name for a full file path use an env var in the config file system"l src/common/log.q"; +system"l src/common/timer.q"; +system"l src/common/os.q"; +system"l src/approvedtasks.q"; +system"l src/common/mem.q"; + +// if hdb set load it in +if[count .secondary.hdb:getenv `HDB_DIR; + system "l ",getenv `HDB_DIR; + ]; // get the id form start cmd -.secondary.opts:.Q.opt .z.x; -.secondary.id:"J"$first .secondary.opts`id; +.secondary.opts: .Q.opt .z.x; +.secondary.id: "J"$first .secondary.opts`id; +.secondary.info:([id: .secondary.id; pid: .z.i; host: .z.h]); + +// used to connect and register with primary +.secondary.connect:{ + pri:`$"::",getenv `PRIMARY_PORT; + .log.info "trying to open a handle to primary process on: ",string pri; + sechandle:@[hopen; pri; {.log.error "the secondary has failed to connect to the primary, failed with error: ",x,". Will exit the process now"; exit 0}]; + sechandle + }; + +// this secondary's memory as the kernel counts it (RssAnon, bytes) +.secondary.rssanon:{first exec rssanon from .mem.read enlist .z.i} + +// send hb and mem updates to primary +.secondary.heartbeat:{ + neg[.secondary.handle](`.primary.heartbeatcheck; .secondary.rssanon[]); + }; + +// called by the primary to kill spawned secondaries +.secondary.stop:{ + .log.info "told to stop by the primary, exiting"; + exit 0; + }; + +// if the primary's connection closes there's nothing to work for, so exit +.z.pc:{[h] + if[not h~.secondary.handle; :()]; + .log.error "lost the connection to the primary, exiting"; + exit 1; + }; + +// we will set any secondarys oom_score to 1000 so it will be shut down first if the OS is out of memory +.secondary.oomscore:{ + oomscorepath:"/proc/",string[.z.i],"/oom_score_adj"; + system "sh -c 'echo 1000 > ",oomscorepath,"'"; + score:system"cat ",oomscorepath; + $[score~"1000"; .log.info "oom_score_adj set to 1000"; .log.warn "could not set oom_score_adj, it is ",score]; + }; + +// send an async message to the primary and flush it straight away +.secondary.send:{[msg] neg[.secondary.handle] msg; neg[.secondary.handle][]}; + +// secondary tells primary it is starting, record mem before, run task, record mem after result, .Q.gc[], save result, returns where result is saved and its size +.secondary.runtask:{[tid; tasktype; args] + .secondary.send (`.primary.taskupdate; tid; `running; ()!()); + membefore:.mem.readandclear[]`rssanon; // better than using .Q.w[]`heap + if[not tasktype in at: key .secondary.approvedtasks; + .log.warn "the task ",string[tasktype]," is not in the approved tasks list. Approved tasks are: ",", " sv string at; + :.secondary.send (`.primary.taskupdate; tid; `failed; ([err: "unknown tasktype: ",string tasktype; reason: `error; membefore: membefore; memafter: membefore]))]; + res:@[{.secondary.approvedtasks[x] y}[tasktype;]; args; {[error] (`failure; error)}]; + memafter:first exec vmhwm from .mem.read enlist .z.i; + if[`failure ~ first res; + .Q.gc[]; + memaftergc:.secondary.rssanon[]; + .log.warn "task ",string[tid],", failed with error: ",last res; + :.secondary.send (`.primary.taskupdate; tid; `failed; ([err: last res; reason: `error; membefore: membefore; memafter: memafter; memaftergc: memaftergc]))]; + saved:.secondary.save[tid; res]; + res:(::); + .Q.gc[]; + memaftergc:.secondary.rssanon[]; + if[`failure ~ first saved; + .log.warn "task ",string[tid],", could not save its result: ",last saved; + :.secondary.send (`.primary.taskupdate; tid; `failed; ([err: "could not save the result: ",last saved; reason: `savefailed; membefore: membefore; memafter: memafter; memaftergc: memaftergc]))]; + .log.info "task ",string[tid]," is complete, result saved to ",string first saved; + .secondary.send (`.primary.taskupdate; tid; `done; ([resultpath: first saved; resultbytes: last saved; membefore: membefore; memafter: memafter; memaftergc: memaftergc])); + }; + +// save a tasks result, returns path and bytes, doesnt save if a null is the result +.secondary.save:{[tid; res] + if[(::)~res; :(`; 0)]; + path:hsym `$.secondary.resultsdir,"/",string tid; + @[{[p;r] p set r; (p; hcount p)}[path]; res; {[e] (`failure; e)}] + }; +// start sequence .secondary.start:{ + .secondary.oomscore[]; + .secondary.handle:: .secondary.connect[]; + .secondary.resultsdir:: @[.secondary.handle; (`.primary.register; .secondary.info); {[error] .log.error "registering with the primary failed with error: ",error,". Will exit the process now"; exit 1}]; + .log.info "registered with the primary, saving results in ",.secondary.resultsdir; + .timer.addjob.custom[`heartbeat; {.secondary.heartbeat[]}; (); 1; 2; ()!()]; .log.info "secondary ",string[.secondary.id]," started, listening on ",string system "p"; }; -// start up secondary process .secondary.start[]; \ No newline at end of file diff --git a/tests/LICENSE.qspec b/tests/LICENSE.qspec new file mode 100644 index 0000000..66047bf --- /dev/null +++ b/tests/LICENSE.qspec @@ -0,0 +1,22 @@ +Copyright (c) 2013 Daniel Nugent + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/tests/LICENSE.qutil b/tests/LICENSE.qutil new file mode 100644 index 0000000..2c7beaf --- /dev/null +++ b/tests/LICENSE.qutil @@ -0,0 +1,22 @@ +Copyright (c) 2009 Daniel Nugent + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/tests/bootstrap.q b/tests/bootstrap.q new file mode 100644 index 0000000..cc20da2 --- /dev/null +++ b/tests/bootstrap.q @@ -0,0 +1,194 @@ +.utl.LOADED:() +.utl.LOADING:`symbol$() +.utl.PKGSLOADED:enlist[""]!enlist[`:] +.utl.FILELOADING:` +.utl.PKGLOADING:"" +.utl.DEBUG:0b +.utl.PKGSTRUCTURE:` +.utl.LOADSTRUCTURE:` +.utl.LOADERROR:() + +.utl.baseLoadV:{[x;v;allowReload]; + oldStructure:.utl.LOADSTRUCTURE; + .utl.LOADSTRUCTURE:.utl.PKGSTRUCTURE; + pkgInfo: .utl.requireVH.getPackageInfo[x;v;allowReload]; + .utl.LOADSTRUCTURE:oldStructure; + / The convention used for packages will be to start by using an init file + file: $[not 11h ~ type key pkgInfo[`file];pkgInfo[`file];` sv pkgInfo[`file],`init.q]; + if[not count key file; '"File '",(1 _ string file),"' not found"]; + oldFileLoading: .utl.FILELOADING; + oldPkgLoading: .utl.PKGLOADING; + / Let the name of the file being loaded and the "package" if available be accessed + `.utl.PKGLOADING set .utl.requireVH.getPackageLoading[x;pkgInfo]; + `.utl.FILELOADING set .utl.realPath file; + result:1b; + / The require function prevents files from being loaded that have already been loaded + / Files should NEVER be loaded recursively + if[(allowReload or not file in .utl.LOADED) and not file in .utl.LOADING; + .[`.utl.LOADING;();union;file]; + result:.utl.requireVH.loadFile file; + .[`.utl.LOADING;();except;file]; + if[1b ~ result;.[`.utl.LOADED;();union;file]]; + ]; + if[not 1b ~ result; + .utl.LOADERROR,:file; + ]; + `.utl.FILELOADING set oldFileLoading; + `.utl.PKGLOADING set oldPkgLoading; + $[1b ~ result; + 1b; + result like "*.utl.LOADERROR*"; + 'result; + '"Error while loading. Please see .utl.LOADERROR: ",result + ]; + } + +.utl.loadV:.utl.baseLoadV[;;1b] +.utl.load:.utl.baseLoadV[;"";1b] +.utl.requireV:.utl.baseLoadV[;;0b] +.utl.require:.utl.baseLoadV[;"";0b] + +// Convenience funciton for loading files inside of pakcages +.utl.pkg:{.utl.load $[10h ~ type .utl.PKGLOADING;.utl.PKGLOADING,"/",x;.utl.PKGLOADING,x]} + +/Get the real path of a filehandle cross platform (hopefully) +.utl.realPath:{ + rPath:{[absm;p] $[p like absm;p;` sv (hsym `$system "cd"), (`$1 _ string p)]}; + $["w" ~ (string .z.o) 0; + rPath[":[A-z]:*";x]; + rPath[":/*";x] + ] + } + +.utl.requireVH:((),`)!(),(::) +.utl.requireVH.loadFile:{[file]; + f:1 _ string file; + if[0i ~ system "e"; + :@[{system "l ", x;1b};1 _ string file;(::)]; + ]; + system "l ",f; + 1b + } + +.utl.requireVH.getPackageInfo:{[loadArg;v;allowReload]; + $[-11h ~ type loadArg; + `file`package!2#$[null[.utl.LOADSTRUCTURE] or loadArg like "*.q";loadArg;` sv loadArg,.utl.LOADSTRUCTURE]; + / If a generic list is passed, we treat it as a symbol and characters, using the symbol as a package name + / This is useful to allow requires that reference relative paths + 0h ~ type loadArg; + `file`package!(` sv loadArg[0],`$"/" vs 1 _ loadArg;loadArg[0]); + .utl.requireVH.findV[loadArg;v;allowReload] + ] + } + +.utl.requireVH.getPackageLoading:{[loadArg;pkgInfo]; + / Package specified with a file handle using init.q extension + $[(-11h ~ type loadArg) and pkgInfo[`file] like "*init.q"; + first ` vs pkgInfo[`file]; + / Package specified with a file handle and string component using directory path + (0h ~ type loadArg) and 11h ~ type key pkgInfo `file; + pkgInfo[`file]; + / All other .q files + pkgInfo[`file] like "*.q"; + .utl.PKGLOADING; + / The rest (new packages defined by loading argument) + pkgInfo[`package] + ] + } + +.utl.requireVH.packagesLoaded:{[package;v;allowReload]; + / If the the thing attempting to be loaded isn't a pure package, we're not going to try restricing it based on package id + if[("" ~ v) and (package like "*-*") and package like "*[.0-9]"; + l: {$[1 < count x;("-" sv -1 _ x;-1#x);x]} "-" vs raze string package; + v: raze "=",last l; + package: first l]; + if[not package in key .utl.PKGSLOADED;:`]; + $[.utl.requireVH.makeFilter[v] file:.utl.PKGSLOADED package; + file; + allowReload; + `; + '"Error loading package '", package, "' with version '", v, "', there was a conflicting package version already loaded at ", 1 _ string file + ] + } + +.utl.requireVH.allPackages:{raze {(` sv x,) each key x} each .utl.QPATH} +.utl.requireVH.findV:{[x;v;allowReload]; + / The paths passed to require should be the same across platforms + packageName: first pathComponents: "/" vs x; + if[not null path:.utl.requireVH.packagesLoaded[packageName;v;allowReload]; + :.utl.requireVH.foundDict[path;pathComponents] + ]; + matchingPackages:.utl.requireVH.getMatchingPackages[allPackages:.utl.requireVH.allPackages[];packageName;v]; + allMatchingPackages:.utl.requireVH.getMatchingPackages[allPackages:.utl.requireVH.allPackages[];packageName;""]; + highestMatch:.utl.requireVH.highestPackage matchingPackages; + exactPackage: $[count matchingPackages; + first matchingPackages where matchingPackages like "*",packageName; + first allMatchingPackages where allMatchingPackages like "*",packageName + ]; + / If a Version String has been provided (not "") we want to use the most recent matching + / package and *then* fall back to an exact package name match. + path: $[(v ~ "") and not null exactPackage;exactPackage; + not null highestMatch;highestMatch; + not null exactPackage;exactPackage; + '"A matching package was not found for '",x,"' with version string '",v,"'. Paths searched:\n\t", "\n\t" sv string .utl.QPATH]; + rval:.utl.requireVH.foundDict[path;pathComponents]; + / Keep track of loaded packages to prevent mismatching requires + .utl.PKGSLOADED,:enlist["-" sv {$[(last[x] like "*[.0-9]") and 1 < count x;-1 _ x;x]} "-" vs packageName]!enlist[path]; + //.utl.PKGSLOADED,:enlist[first "-" vs packageName]!enlist[path]; + rval + } + +.utl.requireVH.getMatchingPackages:{[allPackages;packageName;v]; + matchingPackages: allPackages where ('[last;vs[`]] each allPackages) like packageName,"*"; / Only consider the last part of the available paths as package names + matchingPackages where .utl.requireVH.makeFilter[v] each matchingPackages + } + +.utl.requireVH.highestPackage:{[matchingPackages]; + first matchingPackages idesc (),.utl.requireVH.numVNStr .utl.requireVH.VNStrPath each matchingPackages + } + +/ Package numbers are only considered at the top level, special logic to support +/ sub-package elements (packages and files within a versioned package) is needed +.utl.requireVH.foundDict:{[path;pathComponents]; + subPackagePath: $[1 < count pathComponents;`$ 1 _ string ` sv `$@[1 _ pathComponents;0;":",];()]; + file: ` sv path,$[null .utl.LOADSTRUCTURE;();.utl.LOADSTRUCTURE],subPackagePath; + package: 1 _ string ` sv (hsym last ` vs path),subPackagePath; + `file`package!(file;package) + } + +/ Compare two Version Number Strings given an operator +/ It's much easier to do the partial application of the arguments for our purposes +/ if the second arg (the one on the right hand side) is passed in first +.utl.requireVH.cmpVNStr:{[op;vsn2;vsn1]; + if[not count vsn1;:0b]; + if[not count vsn2;:1b]; + op . .utl.requireVH.numVNStr (vsn1;vsn2) + } + +/ Create ordinal numbers from a list of Version Number Strings (Because a Version Number String could ostensibly have infinite depth, we need to work on them in groupings) +.utl.requireVH.numVNStr:{[vns0]; + if[not count vns0;:0]; + vns:"I"$"." vs' (),/:vns0; + s: max count each vns; + ns:{@[x#0;til count y;:;y]}[s] each vns; / Fill out each list with 0's + mvn:max each flip ns; + exponents: reverse sums reverse ?[(1 _ mvn) > 0;1+`int$log[1 _ mvn] div log[10];1],0; + sum each ns *\: `long$10 xexp' exponents / Get the total version numbers + } + +/ Get a Version Number String from the last element of a path +.utl.requireVH.VNStrPath:{`char$raze last "-" vs string last ` vs x} + +/ Create a pair of operator and Version Number String +.utl.requireVH.parseVStr:{ + v: trim each "," vs x; + pairs: {(0,0^1 + last x ss "[<>=]") _ x} each v; / Split the version specifiers into operator and number. + .[pairs;(::;0);:;(("";(),"=";(),"<";(),">";">=";"<=";"<>")!(=;=;<;>;>=;<=;<>)) pairs[;0]] / Create the comparators + } + +/ Creates a Filter function based on a Version String +/ Individual comparison functions are created from each of the comma separated version string elements +.utl.requireVH.makeFilter:{[vstr]; + if[vstr ~ "";:{1b}]; + {all x @\: .utl.requireVH.VNStrPath y}[.utl.requireVH.cmpVNStr ./: .utl.requireVH.parseVStr vstr] / Partially apply the version string elements to get a list of comparators + } diff --git a/tests/helpers/it.q b/tests/helpers/it.q new file mode 100644 index 0000000..3431f6d --- /dev/null +++ b/tests/helpers/it.q @@ -0,0 +1,45 @@ +// Claude +/ helpers for the integration specs: a client connection to the primary and a few readers +/ not a spec itself: it lives outside the folders qspec is pointed at + +.it.ep:`$"::",getenv`PRIMARY_PORT; +.it.n:"J"$getenv`NUM_SECONDARYS; +.it.h:0Ni; + +/ a handle to the primary, opened on first use (retries for up to 10s) +.it.connect:{ + if[not null .it.h;:.it.h]; + n:0; + while[n<50; + h:@[hopen;(.it.ep;1000);{[e] 0Ni}]; + if[not null h;.it.h:h;:h]; + system "sleep 0.2"; + n+:1]; + '"could not connect to the primary at ",string .it.ep}; + +/ run q on the primary and return the result +.it.q:{[s] .it.connect[] s}; + +/ the primary's secondaries table, unkeyed +.it.sec:{.it.q "0!secondaries"}; + +/ how many secondaries are free right now +.it.nfree:{t:.it.sec[]; sum t[`status]=`free}; + +/ status of secondarys id, secid +.it.status:{[secid] t:.it.sec[]; first exec status from t where id=secid}; + +/ is this pid still running? +.it.alive:{[p] not ()~key hsym `$"/proc/",string p}; + +/ call f[] every 0.2s until it returns 1b or secs seconds pass; says whether it did +.it.waitfor:{[f;secs] + n:0; + while[n<5*secs; + if[f[];:1b]; + system "sleep 0.2"; + n+:1]; + :0b}; + +/ wait for every spawned secondary to register as free (up to 20s) +.it.ready:{.it.waitfor[{.it.n<=.it.nfree[]};20]}; \ No newline at end of file diff --git a/tests/integration.sh b/tests/integration.sh new file mode 100755 index 0000000..a6c1de8 --- /dev/null +++ b/tests/integration.sh @@ -0,0 +1,84 @@ +#!/usr/bin/env bash +# end to end tests +# for each tests/integration/*_spec.q: start a fresh primary (which spawns its own secondaries), +# run that spec against it with qspec, then kill everything +# usage (from anywhere): tests/integration.sh run every spec +# tests/integration.sh stale run only specs whose file name contains "stale" +set -uo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" + +set -a +source config/default.env +source config/integration.env +set +a +export QHOME="$KDBX_HOME" +# export QPATH="$ROOT/tests:/opt/kdbx/mod:/home/jrutledge/x/kdbx-modules-main" + +Q="$KDBX_HOME/bin/q" +FILTER="${1:-}" +mkdir -p "$LOG_DIR" +PRIMARYPID="" + +# kill the test primary and its secondaries +# secondaries have no port, so they're found by the PRIMARY_PORT they inherited from the test primary; +# /proc//environ is only readable for our own processes, and any other primary's secondaries have a +# different PRIMARY_PORT, so nothing else is touched +stopall() { + if [[ -n "$PRIMARYPID" ]]; then + kill -9 "$PRIMARYPID" 2>/dev/null || true + wait "$PRIMARYPID" 2>/dev/null || true # reap it, so bash doesn't print "Killed" + fi + local p + for p in $(pgrep -f "src/secondary.q"); do + if tr '\0' '\n' < "/proc/$p/environ" 2>/dev/null | grep -qx "PRIMARY_PORT=$PRIMARY_PORT"; then + kill -9 "$p" 2>/dev/null || true + fi + done + PRIMARYPID="" +} + +# used to kill any processes incase script stops early eg. CTRL+C +trap stopall EXIT + +# refuse to start if something is already on the test primary's port (secondaries don't listen) +portsfree() { + if (exec 3<>"/dev/tcp/localhost/$PRIMARY_PORT") 2>/dev/null; then + echo "port $PRIMARY_PORT is already in use; kill whatever is on it (ss -ltnp | grep $PRIMARY_PORT) and rerun" >&2 + return 1 + fi +} + +# start the primary in the background and wait until it is listening +startprimary() { + "$Q" src/primary.q -p "$PRIMARY_PORT" < /dev/null >> "$LOG_DIR/primary.log" 2>&1 & + PRIMARYPID=$! + for _ in $(seq 50); do + if (exec 3<>"/dev/tcp/localhost/$PRIMARY_PORT") 2>/dev/null; then return 0; fi + sleep 0.2 + done + echo "primary never started listening; see $LOG_DIR/primary.log" >&2 + return 1 +} + +portsfree || exit 1 + +rc=0 +ran=0 +for spec in tests/integration/*_spec.q; do + if [[ -n "$FILTER" && "$spec" != *"$FILTER"* ]]; then continue; fi + ran=$((ran + 1)) + echo + echo "== $spec" + echo "== $(date -u +%Y.%m.%dD%H:%M:%S) $spec" >> "$LOG_DIR/primary.log" + if ! startprimary; then rc=1; stopall; continue; fi + if ! EXTRA_ENV=config/integration.env tests/run.sh "$spec"; then rc=1; fi + stopall + sleep 0.5 # let the processes exit and the primary's port free up before the next spec +done + +echo +if [[ $ran -eq 0 ]]; then echo "no specs matched '$FILTER'" >&2; exit 1; fi +if [[ $rc -eq 0 ]]; then echo "integration: all $ran spec files passed"; else echo "integration: failures; logs are in $LOG_DIR"; fi +exit $rc \ No newline at end of file diff --git a/tests/integration/disconnect_spec.q b/tests/integration/disconnect_spec.q new file mode 100644 index 0000000..608d1b8 --- /dev/null +++ b/tests/integration/disconnect_spec.q @@ -0,0 +1,16 @@ +// Claude +/ end to end: a secondary is killed and the primary's .z.pc marks it closed +system "l tests/helpers/it.q"; + +.tst.desc["end to end: a secondary is killed"]{ + should["mark it closed and leave the other free"]{ + .it.ready[]; + pid:first exec pid from .it.sec[] where id=1; + system "kill -9 ",string pid; + 1b musteq .it.waitfor[{`closed~.it.status 1};10]; + `free musteq .it.status 2; + }; + should["should not have an open handle"]{ + 1b musteq null first exec handle from .it.sec[] where id=1; + }; + }; \ No newline at end of file diff --git a/tests/integration/gating_spec.q b/tests/integration/gating_spec.q new file mode 100644 index 0000000..4ea7128 --- /dev/null +++ b/tests/integration/gating_spec.q @@ -0,0 +1,47 @@ +system "l tests/helpers/it.q"; +/ integration: the brief's memory gating - set a low limit, verify dispatch pauses and resumes +/ run with: bash tests/integration.sh gating +/ a fresh primary has no memory history, so these tasks have no estimate and V2 lets the first wave go; +/ the cap is then crossed while they run, so the next dispatch has to pause until they finish and gc + +.gt.wait:{[f;secs] end:.z.p+`timespan$1e9*secs; while[(not f[]) and .z.p1; + }; + should["start under a low cap, not paused"]{ + / 250MB: idle (a few MB each) is under it, and one 300MB task still running is over it + .it.q ({`.primary.memcap set x}; 250*.gt.mb); + 0b musteq .it.q ({.primary.overcap[]}; ::); + 0 musteq .it.q ({.primary.pausecount}; ::); + }; + should["pause while the first wave holds memory, then resume and finish every task"]{ + / two waves: 300MB each, held for 2 to 5 seconds, so the first one to finish frees a secondary while others still hold memory + n2:2*.gt.n; + `.gt.j set .gt.job[`hold; ([] mb:n2#300; secs:n2#2 3 4 5); ()!()]; + 1b musteq .gt.wait[{`done~.gt.jobstate .gt.j}; 90]; + 1b musteq 0<.it.q ({.primary.pausecount}; ::); + 1b musteq 0D<.it.q ({.primary.pausedtotal}; ::); + }; + should["end resumed, with no task killed for memory"]{ + 0b musteq .it.q ({.primary.paused}; ::); + t:.gt.tasks .gt.j; + 1b musteq all `done=t`state; + 0i musteq sum `oom=t`reason; + }; + should["have held the second wave back until the whole first wave had finished"]{ + t:`dispatchedtime xasc .gt.tasks .gt.j; + first1:.gt.n#t; + next1:first .gt.n _ t; + / without the gate, the next task would go as soon as the first task finished and freed its secondary + 1b musteq next1[`dispatchedtime]>=max first1`finishedtime; + }; + }; diff --git a/tests/integration/gc_spec.q b/tests/integration/gc_spec.q new file mode 100644 index 0000000..55be45f --- /dev/null +++ b/tests/integration/gc_spec.q @@ -0,0 +1,39 @@ +system "l tests/helpers/it.q"; +/ integration: the brief's GC verification - .Q.gc[] runs after each task and the after-gc memory is recorded +/ run with: bash tests/integration.sh gc + +.gc.wait:{[f;secs] end:.z.p+`timespan$1e9*secs; while[(not f[]) and .z.p=290*.gc.mb; + }; + should["see the 300MB given back after the gc: within 50MB of where each task started"]{ + 1b musteq all .gc.t[`memaftergc]<.gc.t[`membefore]+50*.gc.mb; + 1b musteq all (.gc.t[`memafter]-.gc.t`memaftergc)>=250*.gc.mb; + }; + should["show each secondary back at its small after-gc memory"]{ + s:.gc.secs[]; + 1b musteq all s[`rssanon]<50*.gc.mb; + }; + }; diff --git a/tests/integration/happypath_spec.q b/tests/integration/happypath_spec.q new file mode 100644 index 0000000..fa78154 --- /dev/null +++ b/tests/integration/happypath_spec.q @@ -0,0 +1,49 @@ +system "l tests/helpers/it.q"; +/ integration: the brief's happy path - N secondaries, M tasks, all succeed +/ run with: bash tests/integration.sh happypath + +/ wait up to secs seconds for f[] to be true; returns f[] +.hp.wait:{[f;secs] end:.z.p+`timespan$1e9*secs; while[(not f[]) and .z.p1; + }; + should["run every task of a job to done"]{ + `.hp.j set .hp.job[`sumtil; .hp.args; ()!()]; + 1b musteq .hp.wait[{`done~.hp.jobstate .hp.j}; 60]; + t:.hp.tasks .hp.j; + (count .hp.args) musteq count t; + 1b musteq all `done=t`state; + 0i musteq sum t`retrycount; + }; + should["save every result to disk, the same as running the task here"]{ + paths:.it.q ({.primary.jobpaths x}; .hp.j); + (count .hp.args) musteq count paths; + (.secondary.approvedtasks[`sumtil] each .hp.args) mustmatch get each paths; + }; + should["use every secondary, and never run more tasks at once than there are secondaries"]{ + t:.hp.tasks .hp.j; + .hp.n musteq count distinct t`secondaryid; + 1b musteq .hp.mostatonce[t]<=.hp.n; + }; + should["leave every secondary free with no task"]{ + s:.hp.secs[]; + 1b musteq all `free=s`status; + 1b musteq all null s`currenttask; + }; + }; diff --git a/tests/integration/kill_spec.q b/tests/integration/kill_spec.q new file mode 100644 index 0000000..5b61021 --- /dev/null +++ b/tests/integration/kill_spec.q @@ -0,0 +1,42 @@ +system "l tests/helpers/it.q"; +/ integration: the brief's secondary kill - terminate a secondary mid-task, verify the task is re-queued and finishes +/ run with: bash tests/integration.sh kill +/ needs lost in RETRY_REASONS and TASK_RETRIES_MAX of 1 or more (the defaults) + +.kl.wait:{[f;secs] end:.z.p+`timespan$1e9*secs; while[(not f[]) and .z.p1; + }; + should["kill a secondary while it runs a task"]{ + n2:2*.kl.n; + `.kl.j set .kl.job[`sleep; n2#3; ()!()]; + 1b musteq .kl.wait[{not null .kl.running[]`id}; 15]; + `.kl.victim set .kl.running[]; + system "kill -9 ",string .kl.victim`pid; + / its connection closes: the primary marks it closed + 1b musteq .kl.wait[{`closed~first exec status from .kl.secs[] where id=.kl.victim`id}; 15]; + }; + should["retry its task on another secondary, and finish the job"]{ + 1b musteq .kl.wait[{`done~.kl.jobstate .kl.j}; 60]; + t:first select from .kl.tasks[.kl.j] where taskid=.kl.victim`currenttask; + `done musteq t`state; + 1i musteq t`retrycount; + 1b musteq not t[`secondaryid]=.kl.victim`id; + }; + should["finish every other task without a retry"]{ + t:.kl.tasks .kl.j; + 1b musteq all `done=t`state; + 1i musteq sum t`retrycount; + }; + }; diff --git a/tests/integration/oomscore_spec.q b/tests/integration/oomscore_spec.q new file mode 100644 index 0000000..6256561 --- /dev/null +++ b/tests/integration/oomscore_spec.q @@ -0,0 +1,10 @@ +// check the oom score of the secondaries +system "l tests/helpers/it.q"; + +.tst.desc["check the score of all secondaries oom score"]{ + should["return 1000 for all secondaries"]{ + pids:exec pid from .it.sec[]; + paths:{"/proc/",string[x],"/oom_score_adj"} each pids; + 1b musteq all raze 1000="J"$ {system x}each "cat ",/:paths + } + }; \ No newline at end of file diff --git a/tests/integration/primaryloss_spec.q b/tests/integration/primaryloss_spec.q new file mode 100644 index 0000000..0429544 --- /dev/null +++ b/tests/integration/primaryloss_spec.q @@ -0,0 +1,14 @@ +// Claude +/ end to end: when the primary dies, its secondaries exit through their own .z.pc +/ kill -9 means the primary's .z.exit never runs, so this checks the secondaries clean themselves up +system "l tests/helpers/it.q"; + +.tst.desc["end to end: the primary dies"]{ + should["take its secondaries with it"]{ + .it.ready[]; + pids:value .it.q ".primary.spawned"; + primarypid:.it.q ".z.i"; + system "kill -9 ",string primarypid; + 1b musteq .it.waitfor[{[p;x] not any .it.alive each p}[pids];10]; + }; + }; \ No newline at end of file diff --git a/tests/integration/registration_spec.q b/tests/integration/registration_spec.q new file mode 100644 index 0000000..5df9ce0 --- /dev/null +++ b/tests/integration/registration_spec.q @@ -0,0 +1,23 @@ +// Claude +/ end to end: the primary spawns NUM_SECONDARYS secondaries and they register and heartbeat +system "l tests/helpers/it.q"; + +.tst.desc["end to end: spawned secondaries register and heartbeat"]{ + should["have every spawned secondary register as free"]{ + 1b musteq .it.ready[]; + }; + should["mark them as spawned, each with its own handle"]{ + t:.it.sec[]; + (asc exec id from t) mustmatch 1 2; + 1b musteq all exec spawned from t; + 2 musteq count distinct exec handle from t; + }; + should["record a pid for each that is a running process"]{ + 1b musteq all .it.alive each exec pid from .it.sec[]; + }; + should["keep receiving heartbeats"]{ + t0:max .it.sec[]`lastheartbeat; + system "sleep 2.5"; + 1b musteq t0<(max .it.sec[]`lastheartbeat); + }; + }; \ No newline at end of file diff --git a/tests/integration/runtask_spec.q b/tests/integration/runtask_spec.q new file mode 100644 index 0000000..9d9473c --- /dev/null +++ b/tests/integration/runtask_spec.q @@ -0,0 +1,75 @@ +/ end to end: a real secondary runs tasks it is sent and reports back to the primary +/ dispatch isn't built yet, so .it.dispatch does on the primary by hand what .primary.dispatch will do: +/ create the task, mark the secondary busy, move the task to dispatched, send it .secondary.runtask +/ run: bash tests/integration.sh runtask +system "l tests/helpers/it.q"; + +/ create a task of type tt with args a and send it to secondary sid as type st (st is normally tt; +/ a different st tests the secondary's own whitelist). Runs on the primary over IPC, returns the task id +.it.dispatch:{[sid;tt;st;a] + .it.q ({[sid;tt;st;a] + tid:.primary.newtask `tasktype`args!(tt;a); + update status:`busy, currenttask:tid from `secondaries where id=sid; + .primary.taskupdate[tid;`dispatched;enlist[`secondaryid]!enlist sid]; + h:first exec handle from secondaries where id=sid; + neg[h](`.secondary.runtask; tid; st; first tasks[tid]`args); + tid}; sid; tt; st; a) + }; + +/ a task's row from the primary, its state, and waiting for it to reach a state +.it.task:{[tid] .it.q ({[t] tasks t}; tid)}; +.it.taskstate:{[tid] .it.task[tid]`state}; +.it.waitstate:{[tid;s;secs] .it.waitfor[{[t;s;x] s~.it.taskstate t}[tid;s]; secs]}; + +.tst.desc["end to end: a secondary runs the tasks it is sent"]{ + should["have every spawned secondary registered and free"]{ + 1b musteq .it.ready[]; + }; + should["run a sumtil task and send back its result"]{ + tid:.it.dispatch[1;`sumtil;`sumtil;1000000]; + 1b musteq .it.waitstate[tid;`done;10]; + t:.it.task tid; + 499999500000 musteq get t`resultpath; + 1 musteq t`secondaryid; + 1b musteq all not null t`dispatchedtime`startedtime`finishedtime; + }; + should["free the secondary once its task is done"]{ + 1b musteq .it.waitfor[{`free~.it.status 1};5]; + 1b musteq null first exec currenttask from .it.sec[] where id=1; + }; + should["record a higher peak than the starting heap for a big task"]{ + tid:.it.dispatch[2;`sumtil;`sumtil;50000000]; + 1b musteq .it.waitstate[tid;`done;20]; + t:.it.task tid; + 1b musteq t[`memafter]>t`membefore; + }; + should["keep the secondary busy while the task runs"]{ + tid:.it.dispatch[1;`sleep;`sleep;2]; + 1b musteq .it.waitstate[tid;`running;5]; + `busy musteq .it.status 1; + 1b musteq .it.waitstate[tid;`done;10]; + 1b musteq .it.waitfor[{`free~.it.status 1};5]; + }; + should["report a task that throws as failed, with its error"]{ + tid:.it.dispatch[1;`fail;`fail;::]; + 1b musteq .it.waitstate[tid;`failed;10]; + t:.it.task tid; + "fail" mustmatch t`err; + `error musteq t`reason; + 1b musteq .it.waitfor[{`free~.it.status 1};5]; + }; + should["refuse a task type the secondary has not approved, without running it"]{ + tid:.it.dispatch[2;`sumtil;`rm;"-rf /"]; + 1b musteq .it.waitstate[tid;`failed;10]; + "unknown tasktype: rm" mustmatch .it.task[tid]`err; + 1b musteq .it.waitfor[{`free~.it.status 2};5]; + }; + should["record the task's real peak memory, not q's rounded heap"]{ + tid:.it.dispatch[1;`hold;`hold;`mb`secs!(300;1)]; + 1b musteq .it.waitstate[tid;`done;10]; + t:.it.task tid; + / a 300MB task: peak about 300MB plus q itself (~7MB); the old heap figure would have been 512MB + 1b musteq (t[`memafter]%1048576) within 300 340; + 1b musteq t[`membefore]<50*1048576; + }; + }; \ No newline at end of file diff --git a/tests/integration/spawn_spec.q b/tests/integration/spawn_spec.q new file mode 100644 index 0000000..c7da39a --- /dev/null +++ b/tests/integration/spawn_spec.q @@ -0,0 +1,21 @@ +// Claude +/ end to end: spawning more secondaries by hand on a running primary +/ assumes NUM_SECONDARYS=2 (config/integration.env) +system "l tests/helpers/it.q"; + +.tst.desc["end to end: spawning more secondaries by hand"]{ + should["refuse an id that's already running"]{ + .it.ready[]; + n:.it.q "count .primary.spawned"; + .it.q ".primary.spawn 1"; + n musteq .it.q "count .primary.spawned"; + }; + should["suggest the next free id"]{ + 3 musteq .it.q ".primary.nextid[]"; + }; + should["spawn that id, and it registers as free"]{ + .it.q ".primary.spawn 3"; + 1b musteq .it.waitfor[{`free~.it.status 3};10]; + }; + }; + diff --git a/tests/integration/stale_spec.q b/tests/integration/stale_spec.q new file mode 100644 index 0000000..ad9630a --- /dev/null +++ b/tests/integration/stale_spec.q @@ -0,0 +1,17 @@ +// Claude +/ end to end: a frozen (SIGSTOP) secondary stays connected but stops heartbeating +system "l tests/helpers/it.q"; + +.tst.desc["end to end: a secondary goes quiet"]{ + should["mark a frozen secondary stale and leave the other free"]{ + .it.ready[]; + `.it.frozen set first exec pid from .it.sec[] where id=2; + system "kill -STOP ",string .it.frozen; + 1b musteq .it.waitfor[{`stale~.it.status 2};10]; + `free musteq .it.status 1; + }; + should["mark it free again once it heartbeats"]{ + system "kill -CONT ",string .it.frozen; + 1b musteq .it.waitfor[{`free~.it.status 2};10]; + }; + }; \ No newline at end of file diff --git a/tests/integration/status_spec.q b/tests/integration/status_spec.q new file mode 100644 index 0000000..4589f9e --- /dev/null +++ b/tests/integration/status_spec.q @@ -0,0 +1,28 @@ +/ end to end: .primary.status called over IPC on a live primary +system "l tests/helpers/it.q"; + +.it.status:{[] .it.q ".primary.status[]"}; + +.tst.desc["end to end: status over IPC"]{ + should["return a dictionary from a remote call"]{ + .it.ready[]; + 99h musteq type .it.status[]; + }; + should["show every spawned secondary as free"]{ + s:.it.status[]; + .it.n musteq s[`seccounts;`free]; + .it.n musteq count s`secondaries; + }; + should["show recent heartbeats for all of them"]{ + 1b musteq all (.it.status[][`secondaries]`lastseen)<00:00:02.000; + }; + should["report a positive uptime"]{ + 1b musteq .it.status[][`uptime]>0D00:00:00; + }; + should["count a killed secondary as closed"]{ + pid:first exec pid from .it.status[][`secondaries] where id=1; + system "kill -9 ",string pid; + 1b musteq .it.waitfor[{1=.it.status[][`seccounts;`closed]};10]; + (.it.n-1) musteq .it.status[][`seccounts;`free]; + }; + }; \ No newline at end of file diff --git a/tests/integration/stop_spec.q b/tests/integration/stop_spec.q new file mode 100644 index 0000000..36cd798 --- /dev/null +++ b/tests/integration/stop_spec.q @@ -0,0 +1,16 @@ +//Claude +/ end to end: .primary.stop[] shuts every spawned secondary down +system "l tests/helpers/it.q"; + +.tst.desc["end to end: stopping the secondaries"]{ + should["leave no secondary processes and every row closed"]{ + .it.ready[]; + pids:value .it.q ".primary.spawned"; + .it.q ".primary.stop[]"; / synchronous: returns after the grace period + 1b musteq .it.waitfor[{[p;x] not any .it.alive each p}[pids];5]; + 1b musteq .it.waitfor[{all `closed=.it.sec[]`status};5]; + }; + should["forget the spawned secondaries"]{ + 0 musteq .it.q "count .primary.spawned"; + }; + }; \ No newline at end of file diff --git a/tests/integration/timeout_spec.q b/tests/integration/timeout_spec.q new file mode 100644 index 0000000..bf7591d --- /dev/null +++ b/tests/integration/timeout_spec.q @@ -0,0 +1,44 @@ +system "l tests/helpers/it.q"; +/ integration: the brief's timeout - a long task is stopped at its timeout +/ run with: bash tests/integration.sh timeout + +.to.wait:{[f;secs] end:.z.p+`timespan$1e9*secs; while[(not f[]) and .z.p/dev/null"; 1b}; p; {[e] 0b}]}; + +.tst.desc["timeout: a task that runs past its timeout fails, and its secondary is killed"]{ + should["have every spawned secondary registered and free"]{ + 1b musteq .it.ready[]; + }; + should["fail a 20 second task with a 2 second timeout, as timeout"]{ + `.to.j set .to.job[`sleep; enlist 20; ([timeout:00:00:02.000])]; + 1b musteq .to.wait[{`failed~.to.jobstate .to.j}; 15]; + t:first .to.tasks .to.j; + `failed musteq t`state; + `timeout musteq t`reason; + `.to.task set t; + }; + should["fail it soon after the timeout, not when the task would have ended"]{ + took:.to.task[`finishedtime]-.to.task[`dispatchedtime]^.to.task`startedtime; + 1b musteq took>=0D00:00:02; + / the timeout check runs every second + 1b musteq took<0D00:00:05; + }; + should["not retry it"]{ + 0i musteq .to.task`retrycount; + }; + should["kill the secondary that was running it"]{ + sid:.to.task`secondaryid; + s:first select from .to.secs[] where id=sid; + 1b musteq .to.wait[{[p;x] not .to.alive p}[s`pid]; 10]; + 1b musteq (s`status) in `closed`free; + }; + should["still run new work on the other secondaries"]{ + j2:.to.job[`sumtil; 100 200; ()!()]; + 1b musteq .to.wait[{[j;x] `done~.to.jobstate j}[j2]; 30]; + }; + }; diff --git a/tests/qspec/fixture.q b/tests/qspec/fixture.q new file mode 100644 index 0000000..e83737d --- /dev/null +++ b/tests/qspec/fixture.q @@ -0,0 +1,77 @@ +/ Need to manage directories or only attempt to use absolute paths (latter is probably easier) +.tst.fixtureAs:{[fixtureName;name]; + dirPath: (` vs .tst.tstPath) 0; + fixtureInDir:{$[any mp:x = (` vs' ps:(key y))[;0];` sv y,first ps where mp;`]}; + fixture: $[not ` ~ fp:fixtureInDir[fixtureName;dirPath]; + .tst.loadFixture[fp;name]; + (`fixtures in key dirPath) and not ` ~ fp:fixtureInDir[fixtureName;` sv dirPath,`fixtures]; + .tst.loadFixture[fp;name]; + '"Error loading fixture '", (string fixtureName), "', not found in:\n\t", (1 _ string dirPath),"\n\t", (1 _ string ` sv dirPath,`fixtures)]; + fixture ^ name + } + +.tst.loadFixture:{[path;name]; + $[2 = count fixtureName:` vs (` vs path) 1; / If there is an extension on the file path of the fixture + .tst.loadFixtureTxt[path;name]; + -11h = type key path; + .tst.loadFixtureFile[path;name]; + all -11h = (type key@) each ` sv' path,'key path; / If the path is a directory of files (splayed dir) + .tst.loadFixtureFile[path;name]; + .tst.loadFixtureDir[path;name]]; + first fixtureName + } + +.tst.fixture:.tst.fixtureAs[;`] +.tst.currentDirFixture:` + +.tst.loadFixtureDir:{[f;name]; + fixtureName: (` vs f) 1; + dirFixtureLoaded: not ` ~ .tst.currentDirFixture; + if[not dirFixtureLoaded;.tst.saveDir[];]; + if[not fixtureName ~ .tst.currentDirFixture; + if[dirFixtureLoaded;.tst.removeDirVars[];]; + system "l ", 1 _ string f; + .tst.currentDirFixture: fixtureName; + ]; + } + +.tst.loadFixtureTxt:{[f;name]; + fname: ((` vs (` vs f) 1) 0) ^ name; + .tst.mock[fname;(raze l[0;1] vs l[0];enlist l[0;1]) 0: 1 _ l: read0 f]; + fname + } + +.tst.loadFixtureFile:{[f;name]; + .tst.mock[fname:((` vs f) 1) ^ name;get f]; + fname + } + +.tst.savedDir:.tst.defaultSavedDir:`directory`vars!("";(`,())!(),(::)) +.tst.saveDir:{ + if[not () ~ dirVars: .tst.findDirVars[]; + .tst.savedDir:`directory`vars!(system "cd";(!).(::;get each)@\:` sv' `.,'dirVars); + .tst.removeDirVars dirVars]; + } + +.tst.removeDirVars:{![`.;();0b;] $[(::) ~ x;.tst.findDirVars[];x]} + +.tst.restoreDir:{ + if[not ` ~ .tst.currentDirFixture; + .tst.removeDirVars[]; + .tst.currentDirFixture:`]; + if[not "" ~ .tst.savedDir.directory; + system "l ", .tst.savedDir.directory; + (key .tst.savedDir.vars) set' value .tst.savedDir.vars; + .tst.savedDir: .tst.defaultSavedDir;] + } + + +/ Get a list of files (and thus variables) from the partition directory that do not match special partition directory files: +/ ie: Exclue the par.txt file and any partition directories (contained in the list .Q.ps), include the partition variable (.Q.pf) and the known partition tables (.Q.pt) +/ These will be the variables to delete from the top level namespace when we swap out a partition directory fixture +.tst.findDirVars:{ + $[count where -1h = (type .Q.qp get@) each ` sv' `.,'tables `.; /.Q.qp returns a boolean only when a table is a partition table or a splayed table + distinct @[get;`.Q.pf;()],@[get;`.Q.pt;()],pvals where not any (pvals:key `:.) like/:(string @[get;`.Q.pv;()]),enlist "par.txt"; + ()] + } + diff --git a/tests/qspec/init.q b/tests/qspec/init.q new file mode 100644 index 0000000..797e5e8 --- /dev/null +++ b/tests/qspec/init.q @@ -0,0 +1,16 @@ +.utl.require .utl.PKGLOADING,"/mock.q" +.utl.require .utl.PKGLOADING,"/fixture.q" +.utl.require .utl.PKGLOADING,"/tests/internals.q" +.utl.require .utl.PKGLOADING,"/tests/assertions.q" +.utl.require .utl.PKGLOADING,"/tests/ui.q" +.utl.require .utl.PKGLOADING,"/tests/spec.q" +.utl.require .utl.PKGLOADING,"/tests/expec.q" +.utl.require .utl.PKGLOADING,"/tests/fuzz.q" +.utl.require .utl.PKGLOADING,"/loader.q" + +.tst.PKGNAME: .utl.PKGLOADING + +.tst.loadOutputModule:{[module]; + if[not module in ("text";"xunit";"junit"); '"Unknown OutputModule ",module]; + .utl.require .tst.PKGNAME,"/output/",module,".q" + } diff --git a/tests/qspec/loader.q b/tests/qspec/loader.q new file mode 100644 index 0000000..c68a5a0 --- /dev/null +++ b/tests/qspec/loader.q @@ -0,0 +1,17 @@ +\d .tst + +loadTests:{[paths]; .utl.require each findTests[paths]} + +findTests:{[paths]; + distinct raze suffixMatch[".q"] each distinct (),paths + } + +suffixMatch:{[suffix;path]; + if[path like "*",suffix;:enlist path]; + f: ` sv' path,'f where not (f:(),key path) like ".*"; + d: f where 11h = (type key@) each f; + f: f where f like "*",suffix; + raze f, .z.s[suffix] each d + } + +testFilePath:{` sv (` vs .tst.tstPath)[0],x} diff --git a/tests/qspec/mock.q b/tests/qspec/mock.q new file mode 100644 index 0000000..fa97d4c --- /dev/null +++ b/tests/qspec/mock.q @@ -0,0 +1,30 @@ +\d .tst +initStore:store:(enlist `)!enlist (::) +removeList:() + +/ Used to replace the variable specified by name with newVal. Existing values will be clobbered +/ until restored. Standard variable re-assignment caveats apply +/ CAUTION: Mocking out the mock functions and variables is inadvisable +mock:{[name;newVal]; + name:$[$[1 = c:count vn:` vs name;1b;not null first vn]; + / Create fully qualified name if given a local one + ` sv .tst.context,name; + (2 = c) and ` ~ first vn; + '"Can't mock top-level namespaces!"; + name]; + / Early abort if name will be removed later + if[name in removeList; :name set newVal]; + if[`dne ~ @[get;name;`dne]; removeList,:name; :name set newVal]; + if[not name in key store; store[name]:get name]; + name set newVal + } + +/ Restores the environment to the previous state before any .tst.mock calls were made +restore:{ + / Restore all fully qualified symbols + (set') . (key;value) @\: 1 _ store; + `.tst.store set initStore; + / Drop each fully qualified symbol from its respective namespace + if[count removeList;(.[;();_;]') . flip ((` sv -1 _;last) @\: ` vs) each removeList]; + `.tst.removeList set (); + } diff --git a/tests/qspec/output/junit.q b/tests/qspec/output/junit.q new file mode 100644 index 0000000..fcdc158 --- /dev/null +++ b/tests/qspec/output/junit.q @@ -0,0 +1,84 @@ +.utl.require .tst.PKGNAME,"/output/xml.q" +\d .tst + +printJUnitTime:{string[`int$`second$x],$["000" ~ ns:3#((9 - count n)#"0"),9#n:string nano:(`long$x) mod 1000000000;"";".",ns]} + +expecTypes:`test`fuzz`perf!("should";"it holds that";"performs") + +output:()!() +output[`top]:{[specs] + xml.node["testsuites";()!()] raze output.spec each specs + } +output[`spec]:{[spec]; + e:spec`expectations; + attrs:`name`skipped`tests`errors`failures`time!(spec`title;0;count e;sum e[;`result] like "*Error";sum e[;`result]=`testFail;printJUnitTime sum e[;`time]); + xml.node["testsuite";attrs;-1 _ ` sv output[`expectation] each e] + } + +output[`expectation]:{[e]; + label: expecTypes[e`type]," ",name:e[`desc]; + outstr:output[e`type][e]; + atr:`name`time!(label;printJUnitTime e[`time]); + //if[e[`result] like "*Error";'blah;]; + xml.node["testcase";atr] $[(e[`result] like "*Error") or count e`failures; + output[e`type][e]; + "" + ] + } + +output[`code]:{[e]; + o:""; + if[not "{}" ~ last value e[`before];o,:"Before code: \n", (last value e[`before]),"\n"]; + o,:"Test code: \n",(last value e[`code]),"\n"; + if[not "{}" ~ last value e[`after];o,:"After code: \n", (last value e[`after]),"\n"]; + o + } + +output[`anyFailures]:{[t];(`failures in key t) and count t[`failures]} + +output[`assertsRun]:{[t]; + (string t[`assertsRun]), $[1 = t[`assertsRun];" assertion was";" assertions were"]," run.\n" + } + +codeOutput:{[e] (output[`assertsRun] e),output.code e} + +output[`error]:{[e]; + o:$[count e[`errorText]; + xml.node["error";`type`message!(e[`errorText];xml.safeString[e`result], " occurred in test execution");xml.cdata codeOutput e]; + "" + ]; + o + } + +output[`test]:{[t]; + o:""; + o,:output.error[t]; + if[output[`anyFailures] t; + o,:raze {xml.node["failure";`type`message!(y;"Assertion failure occured during test");xml.cdata codeOutput x]}[t] each t`failures; + ]; + o + } + +output[`fuzzLimit]:10; +output[`fuzz]:{[t]; + o:""; + o,:output.error[t]; + / If the fuzz assertions errors out after tests have been run, but not all failure processing has completed, the output will not pring correctly + / Consider trying to figure out how to print the fuzz that the test failed on (store last fuzz?) + if[(o~"") and output[`anyFailures] t; + o,:raze {[t;f] + h:"Maximum accepted failure rate: ", (string t[`maxFailRate]), "\n"; + h,:"Failure rate was ", (string t[`failRate]), " for ", (string t[`runs]), " runs\n"; + h,:"Displaying ", (string displayFuzz:min (.tst.output.fuzzLimit;count t[`fuzzFailureMessages])), " of ", (string count t[`fuzzFailureMessages]), " fuzz failures messages\n"; + h,:raze (raze displayFuzz # t[`fuzzFailureMessages]),\:"\n"; + xml.node["failure";`type`message!(f;"Fuzz failure occured during test");xml.cdata h,codeOutput t] + }[t] each t`failures; + ]; + o + } + +output[`perf]:{[p]; + } + +output[`always]:1b +output[`interactive]:0b diff --git a/tests/qspec/output/text.q b/tests/qspec/output/text.q new file mode 100644 index 0000000..df756b9 --- /dev/null +++ b/tests/qspec/output/text.q @@ -0,0 +1,78 @@ +\d .tst + +expecTypes:`test`fuzz`perf!("should";"it holds that";"performs") + +output:()!() +output[`top]:{[specs] + raze output.spec each specs + } +output[`spec]:{[spec]; + if[spec[`result] ~ `pass; :""]; / Never print passed specs + o: spec[`title],"::\n"; + o,: raze output[`expectation] each spec[`expectations] $[.tst.output.mode ~ `describe; + (::); + where spec[`expectations;;`result] <> `pass]; + o + } + +output[`expectation]:{[e]; + o: "- ",expecTypes[e`type]," ",e[`desc],$[.tst.output.mode ~ `describe;"";":"],"\n"; + if[not .tst.output.mode ~ `describe; + o,:output[e`type][e]; + ]; + o + } + +output[`code]:{[e]; + o:""; + if[not "{}" ~ last value e[`before];o,:"Before code: \n", (last value e[`before]),"\n"]; + o,:"Test code: \n",(last value e[`code]),"\n"; + if[not "{}" ~ last value e[`after];o,:"After code: \n", (last value e[`after]),"\n"]; + o + } + +output[`anyFailures]:{[t];(`failures in key t) and count t[`failures]} + +output[`assertsRun]:{[t]; + (string t[`assertsRun]), $[1 = t[`assertsRun];" assertion was";" assertions were"]," run.\n" + } + +output[`error]:{[e]; + o:$[count e[`errorText];"Error: ",(string e[`result]), " '", e[`errorText],"\n";""]; + if[not output[`anyFailures] e;o,:output[`assertsRun] e]; + o + } + +output[`test]:{[t]; + o:""; + o,:output.error[t]; + if[output[`anyFailures] t; + o,:raze "Failure: ",/:t[`failures],\:"\n"; + o,:output[`assertsRun] t; + ]; + o,:output.code[t]; + o,"\n" + } + +output[`fuzzLimit]:10; +output[`fuzz]:{[f]; + o:""; + o,:output.error[f]; + / If the fuzz assertions errors out after tests have been run, but not all failure processing has completed, the output will not pring correctly + / Consider trying to figure out how to print the fuzz that the test failed on (store last fuzz?) + if[(o~"") and output[`anyFailures] f; + o,:raze "Failure: ",/:f[`failures],\: "\n"; + o,:"Maximum accepted failure rate: ", (string f[`maxFailRate]), "\n"; + o,:"Failure rate was ", (string f[`failRate]), " for ", (string f[`runs]), " runs\n"; + o,:"Displaying ", (string displayFuzz:min (.tst.output.fuzzLimit;count f[`fuzzFailureMessages])), " of ", (string count f[`fuzzFailureMessages]), " fuzz failures messages\n"; + o,:raze (raze displayFuzz # f[`fuzzFailureMessages]),\:"\n"; + ]; + o,:output.code[f]; + o,"\n" + } + +output[`perf]:{[p]; + } + +output[`always]:0b +output[`interactive]:1b diff --git a/tests/qspec/output/xml.q b/tests/qspec/output/xml.q new file mode 100644 index 0000000..d293d01 --- /dev/null +++ b/tests/qspec/output/xml.q @@ -0,0 +1,36 @@ +\d .tst + +xml:enlist[`]!enlist[::] +xml.safeString:{ + if[not count x;:()]; + $[10h = type x; + x; + 0h <= type x; + // To ensure type conversion isn't an issue, we prepend and drop a dummy string + 1 _ @[x;where not 10h = type each x:enlist[" "],x;string]; + string x + ] + } +xml.attrib:{ + k:xml.safeString key x; + v:"\"",'(xml.entitySub each xml.safeString value x),'"\""; + " " sv k,'"=",'v + } + +xml.node:{[name;attrib;body]; + startNode:"<",(name:xml.safeString[name]),{$[count x;" ",x;""]}[xml.attrib[attrib]],$[count body;">";"/>"]; + $[count body; + ` sv (startNode;xml.safeString body;""); + startNode + ] + } + +xml.entitySub:{ssr/[x;"<>&'\"";("<";">";"&";"'";""")]} + +xml.bodySub:{ + splitCDATA:{(0,raze[flip 0 3 + x ss/: ("")]) cut x}; + raze @[s;i where not (i:til[count s:splitCDATA x]) mod 2;xml.entitySub] + } + +xml.cdata:{[data]""} + diff --git a/tests/qspec/output/xunit.q b/tests/qspec/output/xunit.q new file mode 100644 index 0000000..e775e13 --- /dev/null +++ b/tests/qspec/output/xunit.q @@ -0,0 +1,79 @@ +.utl.require .tst.PKGNAME,"/output/xml.q" +\d .tst + +expecTypes:`test`fuzz`perf!("should";"it holds that";"performs") + +output:()!() +output[`top]:{[specs] + xml.node["test-suite";()!()] raze output.spec each specs + } +output[`spec]:{[spec]; + e:spec`expectations; + attrs:`name`reports`skips`tests`errors`failures!(spec`title;1;0;sum e`assertsRun;sum e[`result] like "*Error";sum e[`result]=`testFail); + attrs,:(`$("test-cases";"errors-detail";"failures-detail"))!(count e;sum e[`result] like "*Error";sum count each e`failures); + xml.node["test-suite";attrs;-1 _ ` sv output[`expectation] each e] + } + +output[`expectation]:{[e]; + label: expecTypes[e`type]," ",name:e[`desc]; + sysout:output[e`type][e]; + atr:`name`label`errors`failures`skip`tests!(name;label;e[`result] like "*Error";count e`failures;0;e`assertsRun); + xml.node["test-case";atr] $[(e[`result] like "*Error") or count e`failures; + xml.node["sysout";()!();xml.bodySub sysout]; + "" + ] + } + +output[`code]:{[e]; + o:""; + if[not "{}" ~ last value e[`before];o,:"Before code: \n", (last value e[`before]),"\n"]; + o,:"Test code: \n",(last value e[`code]),"\n"; + if[not "{}" ~ last value e[`after];o,:"After code: \n", (last value e[`after]),"\n"]; + o + } + +output[`anyFailures]:{[t];(`failures in key t) and count t[`failures]} + +output[`assertsRun]:{[t]; + (string t[`assertsRun]), $[1 = t[`assertsRun];" assertion was";" assertions were"]," run.\n" + } + +output[`error]:{[e]; + o:$[count e[`errorText];"Error: ",(string e[`result]), " '", e[`errorText],"\n";""]; + if[not output[`anyFailures] e;o,:output[`assertsRun] e]; + o + } + +output[`test]:{[t]; + o:""; + o,:output.error[t]; + if[output[`anyFailures] t; + o,:raze "Failure: ",/:t[`failures],\:"\n"; + o,:output[`assertsRun] t; + ]; + o,:output.code[t]; + o,"\n" + } + +output[`fuzzLimit]:10; +output[`fuzz]:{[f]; + o:""; + o,:output.error[f]; + / If the fuzz assertions errors out after tests have been run, but not all failure processing has completed, the output will not pring correctly + / Consider trying to figure out how to print the fuzz that the test failed on (store last fuzz?) + if[(o~"") and output[`anyFailures] f; + o,:raze "Failure: ",/:f[`failures],\: "\n"; + o,:"Maximum accepted failure rate: ", (string f[`maxFailRate]), "\n"; + o,:"Failure rate was ", (string f[`failRate]), " for ", (string f[`runs]), " runs\n"; + o,:"Displaying ", (string displayFuzz:min (.tst.output.fuzzLimit;count f[`fuzzFailureMessages])), " of ", (string count f[`fuzzFailureMessages]), " fuzz failures messages\n"; + o,:raze (raze displayFuzz # f[`fuzzFailureMessages]),\:"\n"; + ]; + o,:output.code[f]; + o,"\n" + } + +output[`perf]:{[p]; + } + +output[`always]:1b +output[`interactive]:0b diff --git a/tests/qspec/tests/assertions.q b/tests/qspec/tests/assertions.q new file mode 100644 index 0000000..3073eb9 --- /dev/null +++ b/tests/qspec/tests/assertions.q @@ -0,0 +1,42 @@ +\d .tst + +asserts:()!() +asserts[`must]:{[val;message]; + .tst.assertState.assertsRun+:1; + if[not all val;.tst.assertState.failures,: enlist message]; + } + +asserts[`musteq]:{[l;r]; asserts.must[l=r;"Expected ", (-3!l), " to be equal to ", (-3!r)]} +asserts[`mustmatch]:{[l;r]; asserts.must[l~r;"Expected ", (-3!l), " to match ", (-3!r)]} +asserts[`mustnmatch]:{[l;r]; asserts.must[not l~r;"Expected ", (-3!l), " to not match ", (-3!r)]} +asserts[`mustne]:{[l;r]; asserts.must[l<>r;"Expected ", (-3!l), " to not be equal to ", (-3!r)]} +asserts[`mustlt]:{[l;r]; asserts.must[lr;"Expected ", (-3!l), " to be greater than ", (-3!r)]} +asserts[`mustlike]:{[l;r]; asserts.must[l like r;"Expected ", (-3!l), " to be like ", (-3!r)]} +asserts[`mustin]:{[l;r]; asserts.must[l in r;"Expected ", (-3!l), " to be in ", (-3!r)]} +asserts[`mustnin]:{[l;r]; asserts.must[not l in r;"Expected ", (-3!l), " to not be in ", (-3!r)]} +asserts[`mustwithin]:{[l;r]; asserts.must[l within r;"Expected ", (-3!l), " to be within ", (-3!r)]} +asserts[`mustdelta]:{[tol;l;r]; asserts.must[l within (r - abs tol;r + abs tol);"Expected ", (-3!l), " to be within +/-", (-3!tol), " of ", (-3!r)]} +asserts[`mustthrow]:{[e;c]; + r:@[{value $[1 = count x;((),x),(::);x];""};c;(::)]; + m:"Expected '", (-3!c), "' to throw ",$[not count e; + "an error."; + 10h = type e; + [e: enlist e; + "the error '",(first e),"'."]; + "one of the errors ", ("," sv {"'",x,"'"} each e), "."]; + p:1b; + if[(not count r);m,:" No error thrown";p:0b]; + if[(count e) and not any r like/:e;m,: " Error thrown: '",r,"'";p:0b]; + asserts.must[p;m] + } + +asserts[`mustnotthrow]:{[e;c]; + r:@[{value $[1 = count x;((),x),(::);x];""};c;(::)]; + m:"Expected '", (-3!c), "' to not throw "; + if[10h = type e;e:enlist e]; + p:1b; + if[(count r) and not count e;m,:"an error. Error thrown: '",r,"'";p:0b]; + if[any r like/:e;m,: "the error '",r,"'";p:0b]; + asserts.must[p;m] + } diff --git a/tests/qspec/tests/expec.q b/tests/qspec/tests/expec.q new file mode 100644 index 0000000..eb04521 --- /dev/null +++ b/tests/qspec/tests/expec.q @@ -0,0 +1,68 @@ +\d .tst +runExpec:{[spec;expec]; + time:.z.n; + startExpec:expec; + expec:setupExpec[spec;expec]; + beforeBad:`before; + expec,: @[{x[];()};expec`before;expecError[expec;"before"]]; + beforeBad:`test; + / Only run the expectation code when the setup works + if[not count expec[`result];expec,: @[callExpec;expec;expecError[expec;string expec[`type]]]]; + beforeBad:`after; + expec,: @[{x[];()};expec`after;expecError[expec;"after"]]; + expec:teardownExpec[spec;expec]; + if[.tst.halt; + stageBadExpec[spec;startExpec;beforeBad]; + ]; + expec[`time]:.z.n - time; + expec + } + +stageBadExpec:{[spec;expec;beforeBad] + expec:setupExpec[spec;expec]; + if[beforeBad ~ `before;:(::)]; + expec,: @[{x[];()};expec`before;expecError[expec;"before"]]; + if[beforeBad ~ `test;:(::)]; + @[callExpec;expec;expecError[expec;string expec[`type]]]; + } + +setupExpec:{[spec;expec]; + expec[`result]:(); + ((` sv `.q,) each uiRuntimeNames,key asserts) .tst.mock' uiRuntimeCode,value asserts; + system "d ", string .tst.context; + expec + } + +teardownExpec:{[spec;expec]; + system "d .tst"; + .tst.restore[]; + / Clear any state for assertions + .tst.assertState:.tst.defaultAssertState; + .tst.callbacks.expecRan[spec;expec]; + expec + } + +expecError:{[expec;errorType;errorText]; + expec[`result]: `$errorType,"Error"; + expec[`errorText],:errorText; + expec[`failures]:.tst.assertState.failures; + expec[`assertsRun]:.tst.assertState.assertsRun; + expec + } + +callExpec:{[expec]; + $[expec[`type] in key runners; + runners[expec`type] expec; + 'badExpecType] + } + +runners:()!() +runners[`perf]:{[expec];} +runners[`test]:{[expec]; + expec[`code][]; + / We use just a dab of state to communicate with the assertions + expec[`failures]:.tst.assertState.failures; + expec[`assertsRun]:.tst.assertState.assertsRun; + expec[`result]: $[count expec`failures;`testFail;`pass]; + expec + } diff --git a/tests/qspec/tests/fuzz.q b/tests/qspec/tests/fuzz.q new file mode 100644 index 0000000..a48cd62 --- /dev/null +++ b/tests/qspec/tests/fuzz.q @@ -0,0 +1,51 @@ +\d .tst +fuzzListMaxLength:100 + +typeNames: `boolean`guid`byte`short`int`long`real`float`char`symbol`timestamp`month`date`datetime`timespan`minute`second`time +typeCodes: 1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19h +typeDefaults:(0b;0Ng;0x0;0h;0;0j;10000e;1000000f;" ";`7;value (string `year$.z.D),".12.31D23:59:59.999999999";2000.01m;2000.01.01;value (string `year$.z.D),".12.31T23:59:59.999";0D0;00:00;00:00:00;00:00:00.000) +typeFuzzN: typeNames!typeDefaults +typeFuzzC: typeCodes!typeDefaults + +pickFuzz:{[x;runs] + $[-11h ~ t:type x; / [`type] form. Use the default fuzz for the type pneumonic (`symbol/`int/etc) + runs ? typeFuzzN[x]; + 100h ~ type x; / [{...}] form. function type, x is a fuzz generator + x each til runs; + 99h ~ type x; / [`name1`name2...`nameN!...] form. Wants multiple fuzzes + flip pickFuzz[;runs] each x; + $[(type x) > 0; / Any list form. Fuzz should be a fuzzy list of fuzz + pickListFuzz[x;runs]; + runs ? x / Geneal list/atom value form. + ]] + } + +pickListFuzz:{[x;runs]; + $[(count x) = 0; / [`type$()] form. Use default fuzz by type, but create variable length lists + { y ? typeFuzzC[x]}[abs type x] each runs ? fuzzListMaxLength; + null[first distinct x] and 1 = count distinct x; / [`type$n#0N] form. Use default fuzz by type with user specified max list length + { y ? typeFuzzC[x]}[abs type x] each runs ? count x; / Type safe comparison needed (symbol list) + 1 = count distinct x; / [`type$n#val] form. Use provided value for fuzz generator with specified max length + { y ? x }[first x] each runs ? count x; + runs ? x / [`type$(val1;val2;val3)] General uniform list form + ] + } + +runners[`fuzz]:{[expec]; + fuzzResults:fuzzRunCollecter[expec`code] each pickFuzz[expec`vars;expec`runs]; + expec,:exec failedFuzz, fuzzFailureMessages:fuzzFailures from fuzzResults where 0 < count each failedFuzz; + assertsRun:$[not count fuzzResults;0;max fuzzResults[`assertsRun]]; + $[(expec[`failRate]:(count expec`failedFuzz)%expec`runs) > expec`maxFailRate; + expec[`failures`result`assertsRun]:(enlist "Over max failure rate";`fuzzFail;assertsRun); + expec[`failures`result`assertsRun]:(();`pass;assertsRun)]; + expec + } + +fuzzRunCollecter:{[code;fuzz]; + .tst.assertState:.tst.defaultAssertState; + code[fuzz]; + $[count .tst.assertState.failures; + `failedFuzz`fuzzFailures`assertsRun!(fuzz;.tst.assertState.failures;.tst.assertState.assertsRun); + `failedFuzz`fuzzFailures`assertsRun!(();();.tst.assertState.assertsRun)] + } + diff --git a/tests/qspec/tests/internals.q b/tests/qspec/tests/internals.q new file mode 100644 index 0000000..1cf450f --- /dev/null +++ b/tests/qspec/tests/internals.q @@ -0,0 +1,19 @@ +\d .tst +.tst.defaultAssertState:.tst.assertState:``failures`assertsRun!(::;();0); +.tst.tstPath: `; + +halt:0b +internals:()!() +internals[`]:()!() +internals[`specObj]:`result`title`failHard!(`didNotRun;"";0b) +internals[`defaultExpecObj]:`result`errorText!(`didNotRun;()) +internals[`testObj]: internals[`defaultExpecObj], ((),`type)!(),`test +internals[`fuzzObj]: internals[`defaultExpecObj], `type`runs`vars`maxFailRate!(`fuzz;100;`int;0f) +internals[`perfObj]: internals[`defaultExpecObj], ((),`type)!(),`perf + +if[not `callbacks in key .tst; / Avoid callback overwriting issue when dogfooding + callbacks:((),`)!(),(::); + callbacks[`descLoaded]:{}; + callbacks[`expecRan]:{[x;y]}; + ]; + diff --git a/tests/qspec/tests/spec.q b/tests/qspec/tests/spec.q new file mode 100644 index 0000000..a063b59 --- /dev/null +++ b/tests/qspec/tests/spec.q @@ -0,0 +1,15 @@ +\d .tst + +.tst.context:`. +runSpec:{ + oldContext: .tst.context; + .tst.context: x[`context]; + .tst.tstPath: x[`tstPath]; + x:@[x;`expectations;{[s;e]if[.tst.halt;:()];runExpec[s;e]}[x] each]; + if[.tst.halt;:()]; + .tst.restoreDir[]; + .tst.context: oldContext; + .tst.tstPath: `; + x[`result]:$[all `pass = x[`expectations;;`result];`pass;`fail]; + x + } diff --git a/tests/qspec/tests/ui.q b/tests/qspec/tests/ui.q new file mode 100644 index 0000000..b834130 --- /dev/null +++ b/tests/qspec/tests/ui.q @@ -0,0 +1,82 @@ +\d .tst +uiSet:{.[`.tst;(),x;:;y]} + +resetExpecList:{uiSet[`expecList;enlist ()!()]} / Asserts are built up into this variable +resetExpecList[]; +currentBefore:{} +currentAfter:{} + +before:{[code]; + uiSet[`currentBefore;code] + } + +after:{[code]; + uiSet[`currentAfter;code] + } + +// Before and After values can be set after the expectation (under the specification) +fillExpecBA:{ + x:@[x;1 _ where {not `before in key x} each x;{x,enlist[`before]!enlist currentBefore}]; + 1 _ @[x;1 _ where {not `after in key x} each x;{x,enlist[`after]!enlist currentAfter}] + } + +alt:{[code]; / Alt blocks allow different before/after behavior to be defined + oldBefore: currentBefore; + oldAfter: currentAfter; + oldExpecList: expecList; + resetExpecList[]; + code[]; + el:fillExpecBA expecList; + / Reset environment + `expecList`currentBefore`currentAfter uiSet' (oldExpecList;oldBefore;oldAfter); + expecList,:el; + } + +should:{[des;code]; + expecList,: enlist .tst.internals.testObj, (`desc`code!(des;code)) + } + +holds:{[des;props;code]; + expecList,: enlist .tst.internals.fuzzObj, (`desc`code!(des;code)), props + } + +perf:{[des;props;code]; + expecList,: enlist .tst.internals.perfObj, (`desc`code!(des;code)), props + } + +uiRuntimeNames:`fixture`fixtureAs`mock +uiRuntimeCode: (.tst.fixture;.tst.fixtureAs;.tst.mock) +uiNames:`before`after`should`holds`perf`alt +uiCode:(before;after;should;holds;perf;alt) + +/ Note on Global References: +/ Because of the way Q handles global references, we cannot use the code object of the expectations parameter +/ Instead We take the value string of the object and re-evaluate it to execute a new code object with the +/ .q assertions functions in place. (You may see this by taking an expectation function definition and +/ examining the list of globals "(value expectations) 3" without a custom .q function defined and with one +/ defined. E.g: +/ (value {2 musteq 2}) 3 +/ .q.musteq: {x+y} +/ (value {2 musteq 2}) 3 + +.tst.desc:{[title;expectations]; + oldBefore: currentBefore; + oldAfter: currentAfter; + oldExpecList: expecList; + resetExpecList[]; + specObj: .tst.internals.specObj; + specObj[`title]:title; + / set up the UI for the expectation call + / mock isn't exactly the right name for this usage. Think of it more like "substitute" + ((` sv `.q,) each uiRuntimeNames,uiNames,key asserts) .tst.mock' uiRuntimeCode,uiCode,value asserts; / See Note on Global References + (value string expectations)[]; / See Note on Global References + specObj[`context]: system "d"; + specObj[`tstPath]: .utl.FILELOADING; + specObj[`expectations]:fillExpecBA expecList; + / Reset environment + `expecList`currentBefore`currentAfter uiSet' (oldExpecList;oldBefore;oldAfter); + .tst.restore[]; + .tst.callbacks.descLoaded specObj; + specObj + } + diff --git a/tests/qutil/bootstrap.q b/tests/qutil/bootstrap.q new file mode 100644 index 0000000..cc20da2 --- /dev/null +++ b/tests/qutil/bootstrap.q @@ -0,0 +1,194 @@ +.utl.LOADED:() +.utl.LOADING:`symbol$() +.utl.PKGSLOADED:enlist[""]!enlist[`:] +.utl.FILELOADING:` +.utl.PKGLOADING:"" +.utl.DEBUG:0b +.utl.PKGSTRUCTURE:` +.utl.LOADSTRUCTURE:` +.utl.LOADERROR:() + +.utl.baseLoadV:{[x;v;allowReload]; + oldStructure:.utl.LOADSTRUCTURE; + .utl.LOADSTRUCTURE:.utl.PKGSTRUCTURE; + pkgInfo: .utl.requireVH.getPackageInfo[x;v;allowReload]; + .utl.LOADSTRUCTURE:oldStructure; + / The convention used for packages will be to start by using an init file + file: $[not 11h ~ type key pkgInfo[`file];pkgInfo[`file];` sv pkgInfo[`file],`init.q]; + if[not count key file; '"File '",(1 _ string file),"' not found"]; + oldFileLoading: .utl.FILELOADING; + oldPkgLoading: .utl.PKGLOADING; + / Let the name of the file being loaded and the "package" if available be accessed + `.utl.PKGLOADING set .utl.requireVH.getPackageLoading[x;pkgInfo]; + `.utl.FILELOADING set .utl.realPath file; + result:1b; + / The require function prevents files from being loaded that have already been loaded + / Files should NEVER be loaded recursively + if[(allowReload or not file in .utl.LOADED) and not file in .utl.LOADING; + .[`.utl.LOADING;();union;file]; + result:.utl.requireVH.loadFile file; + .[`.utl.LOADING;();except;file]; + if[1b ~ result;.[`.utl.LOADED;();union;file]]; + ]; + if[not 1b ~ result; + .utl.LOADERROR,:file; + ]; + `.utl.FILELOADING set oldFileLoading; + `.utl.PKGLOADING set oldPkgLoading; + $[1b ~ result; + 1b; + result like "*.utl.LOADERROR*"; + 'result; + '"Error while loading. Please see .utl.LOADERROR: ",result + ]; + } + +.utl.loadV:.utl.baseLoadV[;;1b] +.utl.load:.utl.baseLoadV[;"";1b] +.utl.requireV:.utl.baseLoadV[;;0b] +.utl.require:.utl.baseLoadV[;"";0b] + +// Convenience funciton for loading files inside of pakcages +.utl.pkg:{.utl.load $[10h ~ type .utl.PKGLOADING;.utl.PKGLOADING,"/",x;.utl.PKGLOADING,x]} + +/Get the real path of a filehandle cross platform (hopefully) +.utl.realPath:{ + rPath:{[absm;p] $[p like absm;p;` sv (hsym `$system "cd"), (`$1 _ string p)]}; + $["w" ~ (string .z.o) 0; + rPath[":[A-z]:*";x]; + rPath[":/*";x] + ] + } + +.utl.requireVH:((),`)!(),(::) +.utl.requireVH.loadFile:{[file]; + f:1 _ string file; + if[0i ~ system "e"; + :@[{system "l ", x;1b};1 _ string file;(::)]; + ]; + system "l ",f; + 1b + } + +.utl.requireVH.getPackageInfo:{[loadArg;v;allowReload]; + $[-11h ~ type loadArg; + `file`package!2#$[null[.utl.LOADSTRUCTURE] or loadArg like "*.q";loadArg;` sv loadArg,.utl.LOADSTRUCTURE]; + / If a generic list is passed, we treat it as a symbol and characters, using the symbol as a package name + / This is useful to allow requires that reference relative paths + 0h ~ type loadArg; + `file`package!(` sv loadArg[0],`$"/" vs 1 _ loadArg;loadArg[0]); + .utl.requireVH.findV[loadArg;v;allowReload] + ] + } + +.utl.requireVH.getPackageLoading:{[loadArg;pkgInfo]; + / Package specified with a file handle using init.q extension + $[(-11h ~ type loadArg) and pkgInfo[`file] like "*init.q"; + first ` vs pkgInfo[`file]; + / Package specified with a file handle and string component using directory path + (0h ~ type loadArg) and 11h ~ type key pkgInfo `file; + pkgInfo[`file]; + / All other .q files + pkgInfo[`file] like "*.q"; + .utl.PKGLOADING; + / The rest (new packages defined by loading argument) + pkgInfo[`package] + ] + } + +.utl.requireVH.packagesLoaded:{[package;v;allowReload]; + / If the the thing attempting to be loaded isn't a pure package, we're not going to try restricing it based on package id + if[("" ~ v) and (package like "*-*") and package like "*[.0-9]"; + l: {$[1 < count x;("-" sv -1 _ x;-1#x);x]} "-" vs raze string package; + v: raze "=",last l; + package: first l]; + if[not package in key .utl.PKGSLOADED;:`]; + $[.utl.requireVH.makeFilter[v] file:.utl.PKGSLOADED package; + file; + allowReload; + `; + '"Error loading package '", package, "' with version '", v, "', there was a conflicting package version already loaded at ", 1 _ string file + ] + } + +.utl.requireVH.allPackages:{raze {(` sv x,) each key x} each .utl.QPATH} +.utl.requireVH.findV:{[x;v;allowReload]; + / The paths passed to require should be the same across platforms + packageName: first pathComponents: "/" vs x; + if[not null path:.utl.requireVH.packagesLoaded[packageName;v;allowReload]; + :.utl.requireVH.foundDict[path;pathComponents] + ]; + matchingPackages:.utl.requireVH.getMatchingPackages[allPackages:.utl.requireVH.allPackages[];packageName;v]; + allMatchingPackages:.utl.requireVH.getMatchingPackages[allPackages:.utl.requireVH.allPackages[];packageName;""]; + highestMatch:.utl.requireVH.highestPackage matchingPackages; + exactPackage: $[count matchingPackages; + first matchingPackages where matchingPackages like "*",packageName; + first allMatchingPackages where allMatchingPackages like "*",packageName + ]; + / If a Version String has been provided (not "") we want to use the most recent matching + / package and *then* fall back to an exact package name match. + path: $[(v ~ "") and not null exactPackage;exactPackage; + not null highestMatch;highestMatch; + not null exactPackage;exactPackage; + '"A matching package was not found for '",x,"' with version string '",v,"'. Paths searched:\n\t", "\n\t" sv string .utl.QPATH]; + rval:.utl.requireVH.foundDict[path;pathComponents]; + / Keep track of loaded packages to prevent mismatching requires + .utl.PKGSLOADED,:enlist["-" sv {$[(last[x] like "*[.0-9]") and 1 < count x;-1 _ x;x]} "-" vs packageName]!enlist[path]; + //.utl.PKGSLOADED,:enlist[first "-" vs packageName]!enlist[path]; + rval + } + +.utl.requireVH.getMatchingPackages:{[allPackages;packageName;v]; + matchingPackages: allPackages where ('[last;vs[`]] each allPackages) like packageName,"*"; / Only consider the last part of the available paths as package names + matchingPackages where .utl.requireVH.makeFilter[v] each matchingPackages + } + +.utl.requireVH.highestPackage:{[matchingPackages]; + first matchingPackages idesc (),.utl.requireVH.numVNStr .utl.requireVH.VNStrPath each matchingPackages + } + +/ Package numbers are only considered at the top level, special logic to support +/ sub-package elements (packages and files within a versioned package) is needed +.utl.requireVH.foundDict:{[path;pathComponents]; + subPackagePath: $[1 < count pathComponents;`$ 1 _ string ` sv `$@[1 _ pathComponents;0;":",];()]; + file: ` sv path,$[null .utl.LOADSTRUCTURE;();.utl.LOADSTRUCTURE],subPackagePath; + package: 1 _ string ` sv (hsym last ` vs path),subPackagePath; + `file`package!(file;package) + } + +/ Compare two Version Number Strings given an operator +/ It's much easier to do the partial application of the arguments for our purposes +/ if the second arg (the one on the right hand side) is passed in first +.utl.requireVH.cmpVNStr:{[op;vsn2;vsn1]; + if[not count vsn1;:0b]; + if[not count vsn2;:1b]; + op . .utl.requireVH.numVNStr (vsn1;vsn2) + } + +/ Create ordinal numbers from a list of Version Number Strings (Because a Version Number String could ostensibly have infinite depth, we need to work on them in groupings) +.utl.requireVH.numVNStr:{[vns0]; + if[not count vns0;:0]; + vns:"I"$"." vs' (),/:vns0; + s: max count each vns; + ns:{@[x#0;til count y;:;y]}[s] each vns; / Fill out each list with 0's + mvn:max each flip ns; + exponents: reverse sums reverse ?[(1 _ mvn) > 0;1+`int$log[1 _ mvn] div log[10];1],0; + sum each ns *\: `long$10 xexp' exponents / Get the total version numbers + } + +/ Get a Version Number String from the last element of a path +.utl.requireVH.VNStrPath:{`char$raze last "-" vs string last ` vs x} + +/ Create a pair of operator and Version Number String +.utl.requireVH.parseVStr:{ + v: trim each "," vs x; + pairs: {(0,0^1 + last x ss "[<>=]") _ x} each v; / Split the version specifiers into operator and number. + .[pairs;(::;0);:;(("";(),"=";(),"<";(),">";">=";"<=";"<>")!(=;=;<;>;>=;<=;<>)) pairs[;0]] / Create the comparators + } + +/ Creates a Filter function based on a Version String +/ Individual comparison functions are created from each of the comma separated version string elements +.utl.requireVH.makeFilter:{[vstr]; + if[vstr ~ "";:{1b}]; + {all x @\: .utl.requireVH.VNStrPath y}[.utl.requireVH.cmpVNStr ./: .utl.requireVH.parseVStr vstr] / Partially apply the version string elements to get a list of comparators + } diff --git a/tests/qutil/config_parse.q b/tests/qutil/config_parse.q new file mode 100644 index 0000000..7998e5b --- /dev/null +++ b/tests/qutil/config_parse.q @@ -0,0 +1,58 @@ +\d .utl +configParsing:((),`)!enlist (::) + +configParsing.stripComments:{[l];l where not any l like/: (";*";"#*")} +configParsing.stripEmptyLines:{[l];l where not "" ~/: configParsing.trim[" \t"] l} +/ Regular trim functions only handle spaces +configParsing.ltrim:{$[not type y;.z.s[x] each y;any x = first y;(sum scan[and] over[or] x=\:y)_ y;y]} +configParsing.rtrim:{$[not type y;.z.s[x] each y;any x = last y;reverse configParsing.ltrim[x] reverse y;y]} +configParsing.trim:{configParsing.ltrim[x] configParsing.rtrim[x] y} + +configParsing.sections:{[fn;l]; + cl:count l; + p:where (rtrim each l) like "[[]*]"; / Left square brackets can't simply be escaped + if[not count p;'"There were no sections found in the file: '",fn,"'"]; + sectionNames:(1 _ -1 _ rtrim @) each l p; + sectionNames!l (p cut til count l) except\: p / Cut in such a way as to return only the lines in each section + } + +configParsing.pairs:{[fn;l]; + if[not count l;:()!()]; + n:where any l like\:/: ("*:*";"*=*"); + if[not 0 in n;'"There was an improperly formatted line in the file: '",fn,"'"]; + badLines: where not (l (til count l) except n) like "[ \t]*"; + if[count badLines;'"There was an improperly formatted line in the file: '",fn,"'";]; + l:raze each n cut l; + nPos: {min raze x ss/: "=:"} each l; + d:flip (0,'nPos) cut' l; + d[0]: configParsing.trim[" \t"] each d[0]; + d[1]: (configParsing.ltrim[" \t"] 1 _) each d[1]; + d:(!) . d; + if[any "" ~/: key d;'"There was an empty key in the file: '",fn,"'";]; + dk!reverse[d] dk:distinct key d + } + +configParsing.substituteLine:{[d;l]; + pred:(p[0] < p[1]) and 2 = count p: first flip l ss/: ("%(";")s"); + if[() ~ pred;:l]; / If there are no substitution characters, p is an empty list and the normal predicate doesn't work right + $[pred; + $[(lookup:2 _ (pieces:(0,p) cut l) 1) in key d; + .z.s[d;pieces[0],d[lookup],2 _ pieces 2]; + not "" ~ e:getenv `$lookup; + .z.s[d;pieces[0],e,2 _ pieces 2]; + l + ]; + l / The substitution strings were in the wrong order or there was only one and there was no substitution to perform + ] + } + +parseRawConfig:{[file]; + l:$[-11h ~ type file;[fn:1 _ string file;read0 file];[fn:"input string";file]]; + l:configParsing.stripEmptyLines configParsing.stripComments l; + configParsing.pairs[fn] each configParsing.sections[fn] l + } + +parseConfig:{[file]; + cfg:parseRawConfig[file]; + {configParsing.substituteLine[d] each d:x,y}[cfg["DEFAULT"]] each enlist["DEFAULT"] _ cfg + } diff --git a/tests/qutil/init.q b/tests/qutil/init.q new file mode 100644 index 0000000..fe836c3 --- /dev/null +++ b/tests/qutil/init.q @@ -0,0 +1,2 @@ +.utl.require .utl.PKGLOADING,"/opts.q" +.utl.require .utl.PKGLOADING,"/config_parse.q" diff --git a/tests/qutil/opts.q b/tests/qutil/opts.q new file mode 100644 index 0000000..e82f41b --- /dev/null +++ b/tests/qutil/opts.q @@ -0,0 +1,192 @@ +\d .utl +arg.args: .z.x +/Drop all at indices +arg.outHandle:-1; +arg.dropAll:{.[x;();_/;desc y]} +arg.boolOpts:() +arg.regOpts:() +arg.regDefOpts:() +arg.posArgs:() +arg.typeDict:typeDict:(("*";0b;1b),"BGXHIJEFCSPMDZNUVT")!("\"String Literal\"";"Disable Flag";"Enable Flag";"BOOL";"GUID";"BYTE";"SHORT";"INT";"LONG";"REAL";"FLOAT";"CHARACTER";"SYMBOL";"YYYY.MM.DDDHH:MM:SS.mmmmmmmmm";"YYYY.MM";"YYYY.MM.DD";"YYYY.MM.DDTHH:MM:SS.mmm";"NDHH:MM:SS.mmmmmmmmm";"HH:MM";"HH:MM:SS";"HH:MM:SS.mmm") + +/ Pass 1b or 0b as typ to affirm/disaffirm that a param is used +/ For instance, we might have verbosity turned off by seeing if the quiet flag is present: +/ .utl.addOpt["quiet,silent";0b;`verbose] +/ q script.q --quiet +/ q) verbose +/ 0b +addArg:{[typ;default;num;handler]; + arg.posArgs,:enlist (typ;default;num;handler); + } + +/ Regular options are only invoked when there is a value available +addOpt:{[flags;typ;handler]; + isBool:-1h ~ type typ; + arg:enlist (flags;typ;handler); + $[isBool; + arg.boolOpts,:arg; + arg.regOpts,:arg + ]; + } + +/ Default value options are always invoked +addOptDef:{[flags;typ;default;handler]; + if[-1h ~ type typ; '"Default value options cannot be boolean"]; + arg.regDefOpts,:enlist (flags;typ;default;handler); + } + +arg.processReg:{[flags;typ;handler]; + / Get all candidate options from the arguments + val:arg.filterVals arg.getRegOpt each arg.filterFlags flags; + if[count val;arg.setReg[typ;handler;1b;val];]; + } + +arg.processDefReg:{[flags;typ;default;handler]; + val:arg.filterVals arg.getRegOpt each arg.filterFlags flags; + $[count val; + arg.setReg[typ;handler;1b;val]; + arg.setReg[typ;handler;0b;default] + ]; + } + +arg.processBool:{[flags;typ;handler]; + / Get all candidate options from the arguments + val:any arg.getBoolOpt each arg.filterFlags flags; + if[count val;arg.setBool[typ;handler;val];]; + } + +arg.processArg:{[typ;default;num;handler]; + val:typ$$[count[arg.args] < first num; + '"Insufficient arguments"; + 0h < type num; / If num is a list (eg (),3), we consume all remaining values + arg.args; + first[$[(num~0) and count arg.args;num:1;num]]#arg.args / If a zero is used as the num, it's treated as a single optional argument (just don't wanna do 1#() + ]; + $[(0 <> first num) and 0h < type num; + arg.setReg["";handler;0b;val]; + arg.setReg["";handler;0b;$[1 ~ num;first;::] $[0 = count val;default;val]] + ]; + arg.dropAll[`.utl.arg.args;til count val]; + } + +arg.filterFlags:{"--" ,/: "," vs (),x} +arg.filterVals:{$[1h ~ type x;any x;first x where not () ~/: x]} + +arg.getRegOpt:{ + l:where (arg.args like x,"=*") or arg.args like x; + / Options where the param values are separate from the param flag (value is at next index) + separated: x ~/: arg.args l; + r:$[count separated; + ?[separated;arg.args 1 + l;(count x,"=") _' arg.args l]; + () + ]; + arg.dropAll[`.utl.arg.args;l,1 + (l where separated)]; + first r + } + +/ The typ is really only expected to be a char list or a single char +/ If it is a char list, it is assumed that the value will be a space separated list of arguments +/ .utl.addOpt["ints";enlist "I";`intList] +/ q script.q --ints "20 30 40" +/ q) intList +/ 20 30 40 +/ Only the first character from a char list is used +arg.setReg:{[typ;handler;parseVal;val]; + if[parseVal; + val: (first typ)$$[10h ~ type typ;" " vs val;val]; + ]; + $[-11h ~ type handler; + handler set val; + (1 = count handler); + handler val; + (handler 0) set (handler 1) val + ]; + } + +/ Boolean options are always invoked +arg.getBoolOpt:{ + arg.dropAll[`.utl.arg.args;l:where arg.args ~\: x]; + 0 < count l + } + +/ Boolean options affirm or disaffirm that an option was set. +/ NOTE:If a function is the handler, it is *ONLY* called when the flag +/ is present (the bval is passed simply because a function *always* has at least one argument) +/ If a symbol/function pair is the handler, it is *ALWAYS* called with the bval +/ The reasoning is that any boolean variables mentioned should be set +arg.setBool:{[b;handler;val]; + bval:b ~ val; / This is basically not XOR. The boolean value is true when both are the same + $[-11h ~ type handler; + handler set bval; + (1 = count handler); + if[val;handler[bval]]; + (handler 0) set (handler 1) bval]; + } + +parseArgs:{ + output:("";()); + output[0],: raze arg.argMessage .' arg.posArgs; + if[count arg.regDefOpts; + output: output,'raze each flip arg.optDefMessage .' arg.regDefOpts; + ]; + if[count arg.boolOpts,arg.regOpts; + output: output,'raze each flip arg.optMessage .' arg.boolOpts,arg.regOpts; + ]; + r:@[;::;::]{ + arg.processBool .' arg.boolOpts; + arg.processReg .' arg.regOpts; + arg.processDefReg .' arg.regDefOpts; + arg.processArg .' arg.posArgs; + arg.handleUnrecognized[]; + }; + if[(10h ~ type r) or not 0 = count arg.args; + if[10h ~ type r; arg.outHandle "error: ", r]; + arg.outHandle "usage: ",ssr[$[(::) ~ x;"q ",string[.z.f]," %cmd%";x];"%cmd%";1 _ output[0]]; / There will be one extra line of padding at the front of the command line string + if[count output 1;arg.outHandle ` sv output 1;]; + arg.exit 1; / Explicitly name exit function to allow test override + ]; + } + +arg.exit:{if[not .utl.DEBUG;exit x];} + +arg.optMessage:{[flags;typ;handler]; + cmdLine: " [ ",(" | " sv arg.filterFlags flags),$[-11h ~ type first handler; + " ",string first handler; + 10h ~ type typ; + " \"",arg.typeDict[first typ]," ...\""; + -1h ~ type typ; + ""; + " ",arg.typeDict[first typ] + ]," ]"; + explainLine: ("," sv arg.filterFlags[flags])," ",$[-11h ~ type first handler;string[first handler]," - ";""],arg.typeDict first typ; + (cmdLine;enlist "\t",explainLine) + } + +arg.optDefMessage:{[flags;typ;default;handler]; + defText:":(",$[10h ~ type default;"\"",default,"\"";" " sv string (),default],")"; + cmdLine: " [ ",first[arg.filterFlags flags]," ",$[-11h ~ type first handler; + string first handler; + 10h ~ type typ; + "\"",arg.typeDict[first typ]," ...\""; + arg.typeDict[first typ] + ],defText," ]"; + explainLine: ("," sv arg.filterFlags[flags])," ",$[-11h ~ type first handler;string[first handler]," - ";""],arg.typeDict first typ, defText; + (cmdLine;enlist "\t",explainLine) + } + +arg.argMessage:{[typ;default;num;handler]; + defText:$[10h ~ type default;":(\"",default,"\")";() ~ default;"";":(",(" " sv string (),default),")"]; + cmdLine: " ", " " sv first[max (num;1)]#enlist $[-11h ~ type first handler; + string first handler; + arg.typeDict[first typ] + ],defText; + {[num;cmdLine] $[first[num] ~ 0;" [",cmdLine," ]";cmdLine]}[num] cmdLine,$[0h < type num;"...";""] + } + +arg.handleUnrecognized:{[messageGiven]; + msg:"Unrecognized options: \n\t", "\n\t" sv arg.args where arg.args like "-*"; + if[any arg.args like "-*"; + 'msg + ]; + } + diff --git a/tests/run.sh b/tests/run.sh new file mode 100755 index 0000000..1377e98 --- /dev/null +++ b/tests/run.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" + +if [[ $# -eq 0 ]]; then + echo "usage: tests/run.sh [qspec flags]" >&2 + echo " e.g. tests/run.sh tests/unit" >&2 + exit 2 +fi + +set -a +source config/default.env +if [[ -n "${EXTRA_ENV:-}" ]]; then source "$EXTRA_ENV"; fi +set +a + +export QHOME="$KDBX_HOME" +export QPATH="$ROOT/tests:/opt/kdbx/mod:/home/jrutledge/x/kdbx-modules-main" + +"$KDBX_HOME/bin/q" tests/runspecs.q -q "$@" diff --git a/tests/runspecs.q b/tests/runspecs.q new file mode 100644 index 0000000..b68bab8 --- /dev/null +++ b/tests/runspecs.q @@ -0,0 +1,10 @@ +// load qutil the way its sample q.q does (we can't edit the shared KDB-X q.q), then run qspec's runner +// usage (from the repo root): q tests/runspecs.q -q [--fail-fast] [--desc] ... +{[envvar] + sep:$["w"~first string .z.o;";";":"]; + .utl.QPATH:hsym each `$sep vs getenv envvar; + b:` sv' .utl.QPATH,'`bootstrap.q; + system "l ",1_string first b where 0 count app.runSpecs;.tst.app.specs: app.specs where (or) over app.specs[;`title] like/: app.runSpecs]; +if[0 <> count app.excludeSpecs;.tst.app.specs: app.specs where not (or) over app.specs[;`title] like/: app.excludeSpecs]; + +app.results: $[not app.describeOnly;.tst.runSpec each app.specs;app.specs] + +if[not .tst.halt; + app.passed:all `pass = app.results[;`result]; + if[not app.passOnly; + if[.tst.output.interactive and not app.describeOnly;-1 "\n"]; + if[.tst.output.always or not app.passed; + -1 {-1 _ x} .tst.output.top app.results; + ]; + if[not app.describeOnly; + if[.tst.output.interactive; + -1 "For ", string[count app.specs], " specifications, ", string[app.expectationsRan]," expectations were run."; + -1 string[app.expectationsPassed]," passed, ",string[app.expectationsFailed]," failed. ",string[app.expectationsErrored]," errors."; + ]; + ]; + ]; + + if[app.exit; exit `int$not app.passed]; + ]; \ No newline at end of file diff --git a/tests/unit/dispatch_spec.q b/tests/unit/dispatch_spec.q new file mode 100644 index 0000000..b0fa906 --- /dev/null +++ b/tests/unit/dispatch_spec.q @@ -0,0 +1,166 @@ +/ unit specs for .primary.dispatch and .primary.sendtask +/ loads primary.q once (spawning off). Secondaries are added with .primary.register, which stores .z.w, +/ and .z.w is 0i when called locally. A send on handle 0i (neg 0i is 0i) runs the message here, +/ so .secondary.runtask is mocked to record what would have been sent. A bad handle makes the send fail +/ run: tests/run.sh tests/unit/dispatch_spec.q + +setenv[`SPAWN_SECONDARY;enlist "0"]; +if[not `primary in key `; system "l src/primary.q"]; + +/ empty both tables, then register secondaries with ids ids (all free, all on handle 0i) +.ut.dpreset:{[ids] + delete from `secondaries; + delete from `tasks; + .primary.lasttaskid:0; + {[i] .primary.register `id`pid`host`port!(i;100i+`int$i;`localhost;45000i+`int$i)} each ids; + }; + +/ add a queued task with priority p, returns its id +.ut.dptask:{[p] .primary.newtask `tasktype`args`priority!(`sumtil;100;p)}; + +/ the mocks shared by every test: quiet logs, a fixed task type list, and a runtask that records its calls +/ the mocks shared by every test: quiet logs, a fixed task type list, a runtask that records its calls, and no retries +/ uses .tst.mock[name;value] with brackets: the infix "mock" only exists while qspec runs a spec, +/ so it can't be used in a helper defined out here at load time +.ut.dpmocks:{[] + .tst.mock[`.log.info; {[x] ::}]; + `.ut.dpwarns set 0; + .tst.mock[`.log.warn; {[x] .ut.dpwarns+:1}]; + .tst.mock[`.primary.tasktypes; `sumtil`sleep`fail]; + `.ut.dpsent set (); + .tst.mock[`.secondary.runtask; {[tid;tt;a] .ut.dpsent,:enlist (tid;tt;a); }]; + / retries are tested in retry_spec.q, so a failed send stays failed here + .tst.mock[`.primary.retryreasons; `$()]; + }; + +.tst.desc[".primary.dispatch - pairing"]{ + before{ + .ut.dpmocks[]; + .ut.dpreset 1 2 3; + }; + should["do nothing when there are no queued tasks"]{ + .primary.dispatch[]; + 0 musteq count .ut.dpsent; + 3 musteq exec count i from secondaries where status=`free; + }; + should["do nothing when no secondary is free"]{ + update status:`busy from `secondaries; + .ut.dptask each 0 0i; + .primary.dispatch[]; + 0 musteq count .ut.dpsent; + 2 musteq exec count i from tasks where state=`queued; + }; + should["send one task to each free secondary and leave the rest queued"]{ + .ut.dptask each 5#0i; + .primary.dispatch[]; + 3 musteq count .ut.dpsent; + 3 musteq exec count i from tasks where state=`dispatched; + 2 musteq exec count i from tasks where state=`queued; + 0 musteq exec count i from secondaries where status=`free; + }; + should["leave spare secondaries free when there are fewer tasks"]{ + .ut.dptask 0i; + .primary.dispatch[]; + 1 musteq count .ut.dpsent; + 2 musteq exec count i from secondaries where status=`free; + }; + should["never give one secondary two tasks"]{ + .ut.dptask each 6#0i; + .primary.dispatch[]; + .primary.dispatch[]; + 1 musteq max exec count i by secondaryid from tasks where state=`dispatched; + }; + should["skip busy, stale and closed secondaries"]{ + update status:`busy from `secondaries where id=1; + update status:`stale from `secondaries where id=2; + .primary.register `id`pid`host`port!(4;104i;`localhost;45004i); + update status:`closed, handle:0Ni from `secondaries where id=4; + .ut.dptask each 4#0i; + .primary.dispatch[]; + (enlist 3) mustmatch exec secondaryid from tasks where state=`dispatched; + }; + }; + +.tst.desc[".primary.dispatch - order"]{ + before{ + .ut.dpmocks[]; + .ut.dpreset enlist 1; + }; + should["send the highest priority task first"]{ + .ut.dptask 0i; + hi:.ut.dptask 5i; + .ut.dptask 1i; + .primary.dispatch[]; + hi musteq first first .ut.dpsent; + }; + should["send the oldest task first when priorities are equal"]{ + first3:.ut.dptask each 3#2i; + .primary.dispatch[]; + (first first3) musteq first first .ut.dpsent; + }; + should["work through the queue in priority order over several rounds"]{ + ids:.ut.dptask each 1 3 2i; + {[x] .primary.dispatch[]; update status:`free, currenttask:0N from `secondaries} each til 3; + (ids 1 2 0) mustmatch first each .ut.dpsent; + }; + }; + +.tst.desc[".primary.sendtask - a send that works"]{ + before{ + .ut.dpmocks[]; + .ut.dpreset enlist 1; + }; + should["mark the secondary busy with the task"]{ + tid:.ut.dptask 0i; + .primary.sendtask[1;tid]; + `busy musteq secondaries[1]`status; + tid musteq secondaries[1]`currenttask; + }; + should["move the task to dispatched with the secondary and time"]{ + tid:.ut.dptask 0i; + .primary.sendtask[1;tid]; + r:tasks tid; + `dispatched musteq r`state; + 1 musteq r`secondaryid; + 1b musteq not null r`dispatchedtime; + }; + should["send runtask the task id, type and unboxed args"]{ + tid:.primary.newtask `tasktype`args!(`sleep;0.5); + .primary.sendtask[1;tid]; + (enlist (tid;`sleep;0.5)) mustmatch .ut.dpsent; + }; + }; + +.tst.desc[".primary.sendtask - a send that fails"]{ + before{ + .ut.dpmocks[]; + .ut.dpreset 1 2; + / no connection on this handle, so neg[h] throws + update handle:99999i from `secondaries where id=1; + }; + should["mark the secondary stale with no current task"]{ + tid:.ut.dptask 0i; + .primary.sendtask[1;tid]; + `stale musteq secondaries[1]`status; + 1b musteq null secondaries[1]`currenttask; + }; + should["fail the task with reason sendfailed"]{ + tid:.ut.dptask 0i; + .primary.sendtask[1;tid]; + r:tasks tid; + `failed musteq r`state; + `sendfailed musteq r`reason; + 1b musteq r[`err] like "send failed*"; + 1b musteq not null r`finishedtime; + 1 musteq .ut.dpwarns; + }; + should["not stop dispatch sending to the other secondaries"]{ + .ut.dptask each 0 0i; + .primary.dispatch[]; + `stale musteq secondaries[1]`status; + `busy musteq secondaries[2]`status; + 1 musteq count .ut.dpsent; + 1 musteq exec count i from tasks where state=`failed; + 1 musteq exec count i from tasks where state=`dispatched; + }; + }; \ No newline at end of file diff --git a/tests/unit/fit_spec.q b/tests/unit/fit_spec.q new file mode 100644 index 0000000..ed08c94 --- /dev/null +++ b/tests/unit/fit_spec.q @@ -0,0 +1,192 @@ +/ unit specs for the V2 headroom check: .primary.committedmem, .primary.fit and its use in .primary.dispatch +/ loads primary.q once (spawning off). Secondaries are registered on handle 0i, so sends run in this process and +/ .secondary.runtask is mocked to record them. Memory is set by hand: the primary 0, each secondary's rssanon 0, +/ a 1000MB cap; tasks are given their memestimate directly. The spare memory and estimate margin are off +/ (0 and 1) unless a test sets them +/ run: tests/run.sh tests/unit/fit_spec.q + +setenv[`SPAWN_SECONDARY;enlist "0"]; +if[not `primary in key `; system "l src/primary.q"]; + +.ut.ftmb:1048576; + +/ fresh tables and n secondaries, free and using no memory +.ut.ftreset:{[n] + system "l schemas/primarytables.q"; + .primary.lasttaskid:0; + {[i] .primary.register `id`pid`host`port!(i;100i+`int$i;`localhost;0i)} each 1+til n; + update rssanon:0 from `secondaries; + }; + +/ a queued sleep task expected to need mb MB (0N for no estimate); returns its id +.ut.ftnew:{[mb] .primary.newtask `tasktype`args`memestimate!(`sleep;1;$[null mb;0N;mb*.ut.ftmb])}; + +/ logs silenced, a 1000MB cap, the primary using nothing, the over-the-cap gate off, no spare memory and no +/ estimate margin, sends recorded +.ut.ftmocks:{[] + .tst.mock[`.log.info; {[x] ::}]; + .tst.mock[`.log.warn; {[x] ::}]; + .tst.mock[`.primary.tasktypes; `sumtil`sleep`fail]; + .tst.mock[`.primary.memcap; 1000*.ut.ftmb]; + .tst.mock[`.primary.selfmem; 0]; + .tst.mock[`.primary.overcap; {[] 0b}]; + .tst.mock[`.primary.minheadroom; 0f]; + .tst.mock[`.primary.estimatemargin; 1f]; + `.ut.ftsent set `long$(); + .tst.mock[`.secondary.runtask; {[tid;tt;a] .ut.ftsent,:tid}]; + }; + +.tst.desc[".primary.fit and dispatch - sending only what fits"]{ + before{ + .ut.ftmocks[]; + .ut.ftreset 4; + }; + should["send every task when they all fit"]{ + t:.ut.ftnew each 100 200 300; + .primary.dispatch[]; + t mustmatch .ut.ftsent; + }; + should["not hand out the same headroom twice in one dispatch"]{ + t:.ut.ftnew each 600 600; + .primary.dispatch[]; + (1#t) mustmatch .ut.ftsent; + `queued musteq tasks[last t]`state; + }; + should["let a smaller task behind one that doesn't fit go first"]{ + big:.ut.ftnew 800; + .ut.ftnew 600; + small:.ut.ftnew 100; + .primary.dispatch[]; + / 800 goes first (fits in 1000), then 600 doesn't fit in the 200 left, 100 does + (big,small) mustmatch .ut.ftsent; + }; + should["count a busy secondary's task estimate as committed"]{ + first1:.ut.ftnew 700; + .primary.dispatch[]; + next1:.ut.ftnew 400; + .primary.dispatch[]; + / 700 is still running (estimate 700, rssanon 0), so 400 doesn't fit in the 300 left + (enlist first1) mustmatch .ut.ftsent; + `queued musteq tasks[next1]`state; + }; + should["send the waiting task once the running one finishes"]{ + first1:.ut.ftnew 700; + .primary.dispatch[]; + next1:.ut.ftnew 400; + .primary.dispatch[]; + / finishing frees the secondary and its memory, and taskupdate dispatches again + .primary.taskupdate[first1;`running;()!()]; + .primary.taskupdate[first1;`done;([resultpath:`; resultbytes:0; membefore:0; memafter:0])]; + (first1,next1) mustmatch .ut.ftsent; + }; + should["always send a task with no estimate"]{ + .ut.ftnew 900; + unknown:.ut.ftnew 0N; + .primary.dispatch[]; + 1b musteq unknown in .ut.ftsent; + }; + should["send the first task when nothing is running, even if it seems not to fit"]{ + / 4 secondaries at 100MB each leave 600MB, less than the task's 950MB + update rssanon:100*.ut.ftmb from `secondaries; + t:.ut.ftnew 950; + .primary.dispatch[]; + (enlist t) mustmatch .ut.ftsent; + }; + should["send as before when there is no cap"]{ + `.primary.memcap mock 0N; + t:.ut.ftnew each 900 900 900; + .primary.dispatch[]; + t mustmatch .ut.ftsent; + }; + should["see a finished task's memory freed straight away, without waiting for a poll"]{ + / a 700MB task on secondary 1 and a small one on secondary 2, so a secondary stays busy + a:.ut.ftnew 700; + .ut.ftnew 10; + .primary.dispatch[]; + / the last poll saw secondary 1 at 700MB while its task ran + update rssanon:700*.ut.ftmb from `secondaries where id=1; + b:.ut.ftnew 400; + / secondary 1 finishes and reports 2MB after its gc: 400 now fits, and goes at once + .primary.taskupdate[a;`running;()!()]; + .primary.taskupdate[a;`done;([resultpath:`; resultbytes:0; membefore:0; memafter:0; memaftergc:2*.ut.ftmb])]; + 1b musteq b in .ut.ftsent; + }; + }; + +.tst.desc[".primary.fit - spare memory and the estimate margin"]{ + before{ + .ut.ftmocks[]; + .ut.ftreset 4; + }; + should["not send a task that would leave less than the spare free"]{ + `.primary.minheadroom mock 0.1; + a:.ut.ftnew 700; + b:.ut.ftnew 300; + .primary.dispatch[]; + / 100MB kept spare: 700 fits in 900, then 300 doesn't fit in the 200 left (it would without the spare) + (enlist a) mustmatch .ut.ftsent; + `queued musteq tasks[b]`state; + }; + should["hold back a task with no estimate when less than the spare is free"]{ + `.primary.minheadroom mock 0.1; + .ut.ftnew 950; + .primary.dispatch[]; + / 950 went because nothing was running; with it busy, only 50MB is free, under the 100MB spare + unknown:.ut.ftnew 0N; + .primary.dispatch[]; + `queued musteq tasks[unknown]`state; + }; + should["hold back a task whose estimate plus the margin doesn't fit"]{ + `.primary.estimatemargin mock 1.25; + .ut.ftnew 10; + .primary.dispatch[]; + / 990MB left: 800 counts as 1000, so it waits (it would go without the margin) + big:.ut.ftnew 800; + .primary.dispatch[]; + `queued musteq tasks[big]`state; + }; + should["still send a task whose estimate plus the margin fits"]{ + `.primary.estimatemargin mock 1.25; + .ut.ftnew 10; + .primary.dispatch[]; + / 990MB left: 790 counts as 988, so it goes + ok:.ut.ftnew 790; + .primary.dispatch[]; + 1b musteq ok in .ut.ftsent; + }; + should["still send the first task when nothing is running, whatever the spare and margin"]{ + `.primary.minheadroom mock 0.5; + `.primary.estimatemargin mock 2f; + t:.ut.ftnew 600; + .primary.dispatch[]; + (enlist t) mustmatch .ut.ftsent; + }; + }; + +.tst.desc[".primary.committedmem"]{ + before{ + .ut.ftmocks[]; + .ut.ftreset 2; + }; + should["be the primary plus every secondary's memory when none are busy"]{ + `.primary.selfmem mock 10*.ut.ftmb; + update rssanon:20*.ut.ftmb from `secondaries; + (50*.ut.ftmb) musteq .primary.committedmem[]; + }; + should["use a busy secondary's task estimate when it's more than its memory"]{ + .ut.ftnew 300; + .primary.dispatch[]; + (300*.ut.ftmb) musteq .primary.committedmem[]; + }; + should["use a busy secondary's memory when it's more than its task's estimate"]{ + .ut.ftnew 300; + .primary.dispatch[]; + update rssanon:500*.ut.ftmb from `secondaries where status=`busy; + (500*.ut.ftmb) musteq .primary.committedmem[]; + }; + should["count the primary as 0 before its first memory poll"]{ + `.primary.selfmem mock 0N; + update rssanon:20*.ut.ftmb from `secondaries; + (40*.ut.ftmb) musteq .primary.committedmem[]; + }; + }; \ No newline at end of file diff --git a/tests/unit/jobs_spec.q b/tests/unit/jobs_spec.q new file mode 100644 index 0000000..cfa4ff9 --- /dev/null +++ b/tests/unit/jobs_spec.q @@ -0,0 +1,416 @@ +/ unit specs for jobs: .primary.newjob, .primary.jobcheck (via taskupdate), .primary.canceljob and .primary.jobpaths +/ loads primary.q once (spawning off). No secondaries are registered, so nothing is dispatched: each test moves a +/ job's tasks through their states with .primary.taskupdate, as a secondary would, and saves results by hand +/ run: tests/run.sh tests/unit/jobs_spec.q + +setenv[`SPAWN_SECONDARY;enlist "0"]; +if[not `primary in key `; system "l src/primary.q"]; + +.ut.jbdir:"/tmp/qfw-jobs-spec"; + +/ fresh tables from the schema and an empty results folder +.ut.jbreset:{[] + system "l schemas/primarytables.q"; + .primary.lasttaskid:0; + system "rm -rf ",.ut.jbdir; + system "mkdir -p ",.ut.jbdir; + }; + +/ a job of n sumtil tasks with 3 retries each, returns the job id +.ut.jbnew:{[n] + j:.primary.newjob[`sumtil; 10*1+til n; ()!()]; + update retriesmax:3i from `tasks where jobid=j; + j + }; + +/ the task ids of job j, in order +.ut.jbtids:{[j] exec taskid from tasks where jobid=j}; + +/ move a queued task to running, as dispatch and the secondary would +.ut.jbrun:{[tid] + .primary.taskupdate[tid;`dispatched;()!()]; + .primary.taskupdate[tid;`running;()!()]; + }; + +/ finish a task as done with result r saved on disk (r is :: for no result) +.ut.jbdone:{[tid;r] + if[`queued~tasks[tid]`state; .ut.jbrun tid]; + p:$[(::)~r; `; [p:hsym `$.ut.jbdir,"/",string tid; p set r; p]]; + .primary.taskupdate[tid;`done;([resultpath:p; resultbytes:$[null p; 0; hcount p]; membefore:0; memafter:0])]; + }; + +/ fail a task with reason rsn +.ut.jbfail:{[tid;rsn] + if[`queued~tasks[tid]`state; .ut.jbrun tid]; + .primary.taskupdate[tid;`failed;([err:"boom"; reason:rsn; membefore:0; memafter:0])]; + }; + +/ logs silenced except jobcheck's "job N failed: ..." warnings, which are counted +/ KDB-X like throws 'nyi for a * in the middle of a pattern, so match with two patterns that only use * at the ends +.ut.jbmocks:{[] + .tst.mock[`.log.info; {[x] ::}]; + `.ut.jbfails set 0; + .tst.mock[`.log.warn; {[x] if[(x like "job*") and x like "*failed:*"; .ut.jbfails+:1]}]; + .tst.mock[`.primary.tasktypes; `sumtil`sleep`fail]; + .tst.mock[`.primary.retryreasons; `lost`sendfailed]; + .tst.mock[`.primary.memcap; 0N]; + .tst.mock[`.primary.lastjobid; 0]; + }; + +.tst.desc[".primary.newjob"]{ + before{ + .ut.jbmocks[]; + .ut.jbreset[]; + }; + after{ + system "rm -rf ",.ut.jbdir; + }; + should["create one task per arg, all with the job's id"]{ + j:.primary.newjob[`sumtil; 10 20 30; ()!()]; + 3 musteq count .ut.jbtids j; + 1b musteq all j=exec jobid from tasks; + }; + should["give each task its own arg, in order"]{ + j:.primary.newjob[`sumtil; 10 20 30; ()!()]; + 10 20 30 mustmatch exec first each args from tasks where jobid=j; + }; + should["add the job as running with its number of tasks"]{ + j:.primary.newjob[`sumtil; 10 20 30; ()!()]; + (`running;3i) mustmatch jobs[j]`state`ntasks; + 1b musteq not null jobs[j]`submittedtime; + }; + should["give each job the next id"]{ + 1 2 mustmatch {[x] .primary.newjob[`sumtil; 1 2; ()!()]} each 1 2; + }; + should["error for an unknown task type and create nothing"]{ + mustthrow[(); {[] .primary.newjob[`nope; 1 2; ()!()]}]; + 0 musteq count jobs; + 0 musteq count tasks; + }; + should["error for no args and create nothing"]{ + mustthrow[(); {[] .primary.newjob[`sumtil; (); ()!()]}]; + 0 musteq count jobs; + 0 musteq count tasks; + }; + should["record who submitted the job, on the job and on each of its tasks"]{ + j:.primary.newjob[`sumtil; 10 20; ()!()]; + .z.u musteq jobs[j]`user; + 1b musteq all .z.u=exec user from tasks where jobid=j; + }; + should["not let the caller set the user"]{ + mustthrow[(); {[] .primary.newjob[`sumtil; 10 20; ([user:`someoneelse])]}]; + 0 musteq count jobs; + }; + }; + +.tst.desc[".primary.jobcheck - a job's state follows its tasks"]{ + before{ + .ut.jbmocks[]; + .ut.jbreset[]; + }; + after{ + system "rm -rf ",.ut.jbdir; + }; + should["leave the job running while some parts are not done"]{ + j:.ut.jbnew 3; + .ut.jbdone[first .ut.jbtids j; 1]; + `running musteq jobs[j]`state; + }; + should["mark the job done when every part is done, with the total result size"]{ + j:.ut.jbnew 3; + .ut.jbdone[;1] each .ut.jbtids j; + `done musteq jobs[j]`state; + 1b musteq not null jobs[j]`finishedtime; + (exec sum resultbytes from tasks where jobid=j) musteq jobs[j]`resultbytes; + }; + should["mark the job failed when a part fails for good, naming the part"]{ + j:.ut.jbnew 3; + t:.ut.jbtids j; + .ut.jbfail[t 1; `error]; + `failed musteq jobs[j]`state; + 1b musteq jobs[j][`err] like "task ",string[t 1]," failed (error)*"; + 1 musteq .ut.jbfails; + }; + should["keep the job running when a lost part is retried"]{ + j:.ut.jbnew 3; + t:.ut.jbtids j; + .ut.jbfail[first t; `lost]; + `queued musteq tasks[first t]`state; + `running musteq jobs[j]`state; + }; + should["finish the job done after a lost part is retried and succeeds"]{ + j:.ut.jbnew 2; + t:.ut.jbtids j; + .ut.jbfail[first t; `lost]; + .ut.jbdone[;1] each t; + `done musteq jobs[j]`state; + }; + should["not change a failed job when its other parts finish"]{ + j:.ut.jbnew 3; + t:.ut.jbtids j; + .ut.jbrun t 1; + .ut.jbfail[first t; `error]; + .ut.jbdone[t 1; 1]; + `failed musteq jobs[j]`state; + 1 musteq .ut.jbfails; + }; + should["leave jobs alone for a task submitted on its own"]{ + `.ut.jbtid set .primary.newtask `tasktype`args!(`sumtil;10); + mustnotthrow[(); {[] .ut.jbdone[.ut.jbtid;1]}]; + 0 musteq count jobs; + }; + }; + +.tst.desc[".primary.canceljob - the rest of a failed job"]{ + before{ + .ut.jbmocks[]; + .ut.jbreset[]; + }; + after{ + system "rm -rf ",.ut.jbdir; + }; + should["cancel the queued parts when a part fails"]{ + j:.ut.jbnew 4; + t:.ut.jbtids j; + .ut.jbfail[first t; `error]; + `failed`failed`failed mustmatch tasks[([] taskid:1_t)]`state; + `cancelled`cancelled`cancelled mustmatch tasks[([] taskid:1_t)]`reason; + }; + should["leave a part that is already running alone"]{ + j:.ut.jbnew 3; + t:.ut.jbtids j; + .ut.jbrun t 1; + .ut.jbfail[first t; `error]; + `running musteq tasks[t 1]`state; + `failed musteq tasks[t 2]`state; + }; + should["not retry cancelled parts"]{ + j:.ut.jbnew 3; + t:.ut.jbtids j; + .ut.jbfail[first t; `error]; + 1b musteq all 0i=exec retrycount from tasks where jobid=j; + }; + }; + +.tst.desc[".primary.jobpaths"]{ + before{ + .ut.jbmocks[]; + .ut.jbreset[]; + }; + after{ + system "rm -rf ",.ut.jbdir; + }; + should["give the parts' result files in task order"]{ + j:.ut.jbnew 3; + t:.ut.jbtids j; + .ut.jbdone[;1] each t; + ({hsym `$.ut.jbdir,"/",string x} each t) mustmatch .primary.jobpaths j; + }; + should["combine to the parts' results in task order, whatever order they finished in"]{ + j:.ut.jbnew 3; + t:.ut.jbtids j; + .ut.jbdone'[reverse t; (5 6;3 4;1 2)]; + 1 2 3 4 5 6 mustmatch raze get each .primary.jobpaths j; + }; + should["combine tables into one table"]{ + j:.ut.jbnew 2; + t:.ut.jbtids j; + .ut.jbdone'[t; (([] a:1 2); ([] a:3 4))]; + ([] a:1 2 3 4) mustmatch raze get each .primary.jobpaths j; + }; + should["leave out parts that returned no result"]{ + j:.ut.jbnew 3; + t:.ut.jbtids j; + .ut.jbdone'[t; (1 2;::;3 4)]; + 2 musteq count .primary.jobpaths j; + 1 2 3 4 mustmatch raze get each .primary.jobpaths j; + }; + should["error for a job that isn't done"]{ + `.ut.jbj set .ut.jbnew 2; + mustthrow[(); {[] .primary.jobpaths .ut.jbj}]; + }; + should["error for a failed job"]{ + `.ut.jbj set .ut.jbnew 2; + .ut.jbfail[first .ut.jbtids .ut.jbj; `error]; + mustthrow[(); {[] .primary.jobpaths .ut.jbj}]; + }; + should["error for a job that doesn't exist"]{ + mustthrow[(); {[] .primary.jobpaths 99}]; + }; + }; + +.tst.desc[".primary.newjob - params"]{ + before{ + .ut.jbmocks[]; + .ut.jbreset[]; + }; + after{ + system "rm -rf ",.ut.jbdir; + }; + should["give every task the job's params"]{ + j:.primary.newjob[`sumtil; 10 20; ([priority:5i; timeout:00:00:05.000; retriesmax:1i])]; + 5 5i mustmatch exec priority from tasks where jobid=j; + 1b musteq all 00:00:05.000=exec timeout from tasks where jobid=j; + 1 1i mustmatch exec retriesmax from tasks where jobid=j; + }; + should["record the job's priority"]{ + j:.primary.newjob[`sumtil; 10 20; ([priority:5i])]; + 5i musteq jobs[j]`priority; + }; + should["use the defaults when there are no params"]{ + j:.primary.newjob[`sumtil; 10 20; ()!()]; + (.primary.taskdefaults`priority) musteq jobs[j]`priority; + 1b musteq all .primary.tasktimeout=exec timeout from tasks where jobid=j; + }; + should["accept a priority given as a long"]{ + j:.primary.newjob[`sumtil; 10 20; ([priority:7])]; + 7 7i mustmatch exec priority from tasks where jobid=j; + 7i musteq jobs[j]`priority; + }; + should["error for an unknown param and create nothing"]{ + mustthrow[(); {[] .primary.newjob[`sumtil; 10 20; ([prioirty:5])]}]; + 0 musteq count jobs; + 0 musteq count tasks; + }; + }; + +/ finish a task that has been sent: running, then done with no result file +.ut.jbfinish:{[tid] + .primary.taskupdate[tid;`running;()!()]; + .primary.taskupdate[tid;`done;([resultpath:`; resultbytes:0; membefore:0; memafter:0])]; + }; + +.tst.desc["priority: a later, higher-priority job goes ahead of an earlier one"]{ + before{ + .ut.jbmocks[]; + .ut.jbreset[]; + / record the order tasks are sent in; one secondary on handle 0i, so sends run here + `.ut.jbsent set `long$(); + .tst.mock[`.secondary.runtask; {[tid;tt;a] .ut.jbsent,:tid}]; + .primary.register `id`pid`host`port!(1;101i;`localhost;45001i); + }; + after{ + system "rm -rf ",.ut.jbdir; + }; + should["send the high-priority job's tasks next, then the rest of the earlier job"]{ + lo:.ut.jbtids .primary.newjob[`sumtil; 10 20 30; ()!()]; + hi:.ut.jbtids .primary.newjob[`sumtil; 40 50; ([priority:10])]; + / the first low task went straight away; each finish frees the secondary and sends the next + do[4; .ut.jbfinish last .ut.jbsent]; + ((first lo),hi,1_lo) mustmatch .ut.jbsent; + }; + should["keep tasks of the same priority in the order they were submitted"]{ + a:.ut.jbtids .primary.newjob[`sumtil; 10 20; ()!()]; + b:.ut.jbtids .primary.newjob[`sumtil; 30 40; ()!()]; + do[3; .ut.jbfinish last .ut.jbsent]; + (a,b) mustmatch .ut.jbsent; + }; + }; + +.ut.esmb:1048576; + +/ history: a job of tt with args, each task finished done having used usedmb MB (membefore 1MB, memafter 1MB+used) +.ut.esdone:{[tt;args;usedmb] + t:.ut.jbtids .primary.newjob[tt; args; ()!()]; + {[t;u] .ut.jbrun t; .primary.taskupdate[t;`done;([resultpath:`; resultbytes:0; membefore:.ut.esmb; memafter:.ut.esmb*1+u])]}'[t;usedmb]; + t + }; + +/ history: a task of tt with arg killed for memory under a cap of capmb MB (memafter holds the cap, as .z.pc sets it) +.ut.esoom:{[tt;arg;capmb] + t:first .ut.jbtids .primary.newjob[tt; enlist arg; ()!()]; + .ut.jbrun t; + .primary.taskupdate[t;`failed;([err:"killed"; reason:`oom; memafter:capmb*.ut.esmb])]; + t + }; + +/ the job mocks, with hold allowed and a 1000MB cap +.ut.esmocks:{[] + .ut.jbmocks[]; + .tst.mock[`.primary.tasktypes; `sumtil`sleep`fail`hold]; + .tst.mock[`.primary.memcap; 1000*.ut.esmb]; + }; + +.tst.desc[".primary.estimatemem"]{ + before{ + .ut.esmocks[]; + .ut.jbreset[]; + }; + after{ + system "rm -rf ",.ut.jbdir; + }; + should["let a task type with no history run, with no estimate"]{ + e:.primary.estimatemem[`sumtil; 10 20]; + 1b musteq e`run; + 1b musteq null e`estimate; + }; + should["estimate the most any done task of the type used"]{ + .ut.esdone[`sumtil; 10 20; 100 300]; + e:.primary.estimatemem[`sumtil; enlist 99]; + (300*.ut.esmb) musteq e`estimate; + 1b musteq e`run; + }; + should["refuse when the type's estimate is at or over the cap"]{ + .ut.esdone[`sumtil; enlist 10; enlist 1000]; + 0b musteq .primary.estimatemem[`sumtil; enlist 99]`run; + }; + should["refuse a job that includes an arg killed for memory under the current cap"]{ + .ut.esoom[`sumtil; 50; 1000]; + e:.primary.estimatemem[`sumtil; 10 50 90]; + 0b musteq e`run; + 1b musteq e[`reason] like "*killed for memory*"; + }; + should["let a job run when none of its args were killed"]{ + .ut.esoom[`sumtil; 50; 1000]; + 1b musteq .primary.estimatemem[`sumtil; 10 90]`run; + }; + should["let the killed arg run again once the cap is raised above the one it was killed under"]{ + .ut.esoom[`sumtil; 50; 1000]; + `.primary.memcap mock 2000*.ut.esmb; + 1b musteq .primary.estimatemem[`sumtil; enlist 50]`run; + }; + should["refuse nothing when there is no cap"]{ + .ut.esoom[`sumtil; 50; 1000]; + .ut.esdone[`sumtil; enlist 10; enlist 5000]; + `.primary.memcap mock 0N; + 1b musteq .primary.estimatemem[`sumtil; enlist 50]`run; + }; + should["match dict args, as hold uses"]{ + .ut.esoom[`hold; `mb`secs!(5000;5); 1000]; + 0b musteq .primary.estimatemem[`hold; ([] mb:30 5000; secs:1 5)]`run; + 1b musteq .primary.estimatemem[`hold; enlist `mb`secs!(30;1)]`run; + }; + should["estimate killed args at least at the cap they were killed under, once allowed"]{ + .ut.esdone[`sumtil; enlist 10; enlist 100]; + .ut.esoom[`sumtil; 50; 1000]; + `.primary.memcap mock 2000*.ut.esmb; + (1000*.ut.esmb) musteq .primary.estimatemem[`sumtil; enlist 50]`estimate; + }; + }; + +.tst.desc[".primary.newjob - the memory estimate"]{ + before{ + .ut.esmocks[]; + .ut.jbreset[]; + }; + after{ + system "rm -rf ",.ut.jbdir; + }; + should["refuse a job that can't run, and create nothing"]{ + .ut.esoom[`sumtil; 50; 1000]; + n:count tasks; + mustthrow[(); {[] .primary.newjob[`sumtil; 10 50; ()!()]}]; + n musteq count tasks; + }; + should["store the estimate on every task of the job"]{ + .ut.esdone[`sumtil; 10 20; 100 300]; + j:.primary.newjob[`sumtil; 30 40; ()!()]; + 1b musteq all (300*.ut.esmb)=exec memestimate from tasks where jobid=j; + }; + should["keep the caller's memestimate when one is given"]{ + .ut.esdone[`sumtil; 10 20; 100 300]; + j:.primary.newjob[`sumtil; 30 40; ([memestimate:5*.ut.esmb])]; + 1b musteq all (5*.ut.esmb)=exec memestimate from tasks where jobid=j; + }; + }; + diff --git a/tests/unit/mem_spec.q b/tests/unit/mem_spec.q new file mode 100644 index 0000000..c0f57b6 --- /dev/null +++ b/tests/unit/mem_spec.q @@ -0,0 +1,128 @@ +/ unit specs for src/common/mem.q: reading memory figures from /proc, and resetting VmHWM +/ loads primary.q once (spawning off), which loads mem.q. Uses this process and short-lived sleep processes +/ run: tests/run.sh tests/unit/mem_spec.q + +setenv[`SPAWN_SECONDARY;enlist "0"]; +if[not `primary in key `; system "l src/primary.q"]; + +/ start a sleep process in the background and return its pid +.ut.mmsleep:{[] "I"$first system "sh -c 'sleep 30 > /dev/null 2>&1 & echo $!'"}; +/ stop processes started by a test +.ut.mmkill:{[pids] if[count pids; system "sh -c 'kill ",(" " sv string pids)," 2>/dev/null; true'"]}; + +.tst.desc[".mem.read - this process"]{ + before{ + `.log.warn mock {[x] ::}; + }; + should["return one row for the current process"]{ + r:.mem.read enlist .z.i; + 1 musteq count r; + .z.i musteq first r`pid; + }; + should["have the agreed columns and types"]{ + (exec c!t from meta .mem.read enlist .z.i) mustmatch `pid`rssanon`vmrss`vmhwm!"ijjj"; + }; + should["give figures in bytes that fit together"]{ + r:first .mem.read enlist .z.i; + / a q process is at least a megabyte resident + 1b musteq r[`vmrss]>1048576; + 1b musteq r[`rssanon]>0; + 1b musteq r[`vmrss]>=r`rssanon; + 1b musteq r[`vmhwm]>=r`vmrss; + }; + should["see rssanon rise with an allocation and fall after the gc"]{ + m0:first exec rssanon from .mem.read enlist .z.i; + a:til 10000000; + m1:first exec rssanon from .mem.read enlist .z.i; + a:0; .Q.gc[]; + m2:first exec rssanon from .mem.read enlist .z.i; + / 10M longs is about 76MB + 1b musteq (m1-m0)>50*1048576; + 1b musteq (m1-m2)>50*1048576; + }; + }; + +.tst.desc[".mem.read - other processes"]{ + before{ + `.log.warn mock {[x] ::}; + `.ut.mmpids set .ut.mmsleep each til 2; + }; + after{ + .ut.mmkill .ut.mmpids; + }; + should["read several processes in one call, one row each"]{ + pids:.z.i,.ut.mmpids; + r:.mem.read pids; + 3 musteq count r; + (asc pids) mustmatch asc r`pid; + }; + should["leave out a process that has exited, without an error"]{ + .ut.mmkill 1#.ut.mmpids; + system "sleep 0.2"; + r:.mem.read .z.i,.ut.mmpids; + 2 musteq count r; + 0b musteq (first .ut.mmpids) in r`pid; + }; + should["return an empty table when every process has exited"]{ + .ut.mmkill .ut.mmpids; + system "sleep 0.2"; + r:.mem.read .ut.mmpids; + 0 musteq count r; + (cols .mem.empty) mustmatch cols r; + }; + }; + +.tst.desc[".mem.read - nothing to read"]{ + should["return an empty table for an empty list"]{ + r:.mem.read `int$(); + .mem.empty mustmatch r; + }; + }; + +.tst.desc[".mem.clearhwm"]{ + before{ + `.ut.mmwarns set 0; + `.log.warn mock {[x] .ut.mmwarns+:1}; + }; + should["reset vmhwm to about the current vmrss"]{ + / push the peak up, then free it + a:til 10000000; a:0; .Q.gc[]; + r0:first .mem.read enlist .z.i; + 1b musteq (r0[`vmhwm]-r0`vmrss)>50*1048576; + .mem.clearhwm[]; + r1:first .mem.read enlist .z.i; + 1b musteq (r1[`vmhwm]-r1`vmrss)<10*1048576; + 0 musteq .ut.mmwarns; + }; + should["record the peak of what ran after the reset"]{ + .mem.clearhwm[]; + a:til 10000000; a:0; .Q.gc[]; + r:first .mem.read enlist .z.i; + 1b musteq (r[`vmhwm]-r`vmrss)>50*1048576; + }; + }; + + +.tst.desc[".mem.readandclear"]{ + before{ + `.log.warn mock {[x] ::}; + }; + should["return this process's figures as a dict"]{ + r:.mem.readandclear[]; + .z.i musteq r`pid; + 1b musteq r[`rssanon]>0; + 1b musteq r[`vmrss]>=r`rssanon; + }; + should["reset vmhwm so the next reading is the peak since now"]{ + a:til 10000000; a:0; .Q.gc[]; + .mem.readandclear[]; + r:first .mem.read enlist .z.i; + 1b musteq (r[`vmhwm]-r`vmrss)<10*1048576; + }; + should["record the peak of what ran after it"]{ + .mem.readandclear[]; + a:til 10000000; a:0; .Q.gc[]; + r:first .mem.read enlist .z.i; + 1b musteq (r[`vmhwm]-r`vmrss)>50*1048576; + }; + }; \ No newline at end of file diff --git a/tests/unit/newtask_spec.q b/tests/unit/newtask_spec.q new file mode 100644 index 0000000..cb3bec7 --- /dev/null +++ b/tests/unit/newtask_spec.q @@ -0,0 +1,115 @@ +/ unit specs for .primary.newtask, the one way tasks get into the tasks table +/ loads primary.q once (spawning off); each test starts with an empty tasks table +/ the allowed task types are mocked, so the tests don't depend on TASK_TYPES in config +/ run: tests/run.sh tests/unit/newtask_spec.q + +setenv[`SPAWN_SECONDARY;enlist "0"]; +if[not `primary in key `; system "l src/primary.q"]; + +.tst.desc[".primary.newtask - accepted tasks"]{ + before{ + `.log.info mock {[x] ::}; + `.log.warn mock {[x] ::}; + `.primary.tasktypes mock `sum`sleep`fail; + delete from `tasks; + }; + should["return the next task id"]{ + n:.primary.lasttaskid; + (n+1) musteq .primary.newtask `tasktype`args!(`sum;1000000); + (n+1) musteq .primary.lasttaskid; + }; + should["add the task as queued with its lifecycle columns set"]{ + id:.primary.newtask `tasktype`args!(`sum;1000000); + r:tasks id; + `sum musteq r`tasktype; + `queued musteq r`state; + 0i musteq r`retrycount; + 1b musteq not null r`submittedtime; + 1b musteq null r`secondaryid; + 1b musteq all null r`dispatchedtime`startedtime`finishedtime; + 1b musteq all null r`membefore`memafter; + "" mustmatch r`err; + 1b musteq null r`reason; + }; + should["store args and result boxed"]{ + id:.primary.newtask `tasktype`args!(`sum;1000000); + (enlist 1000000) mustmatch tasks[id]`args; + 1000000 musteq first tasks[id]`args; + 1b musteq null tasks[id]`resultpath; + 1b musteq null tasks[id]`resultbytes; + }; + should["fill the optional fields from the defaults"]{ + id:.primary.newtask `tasktype`args!(`sleep;200); + r:tasks id; + d:.primary.taskdefaults; + (d`priority) musteq r`priority; + (d`timeout) musteq r`timeout; + (d`retriesmax) musteq r`retriesmax; + 1b musteq null r`memestimate; + }; + should["let the caller override the optional fields"]{ + id:.primary.newtask `tasktype`args`priority`retriesmax`timeout!(`sum;10;5i;1i;00:00:05.000); + r:tasks id; + 5i musteq r`priority; + 1i musteq r`retriesmax; + 00:00:05.000 musteq r`timeout; + }; + should["add one task per row when called with each on a table"]{ + n:.primary.lasttaskid; + ids:.primary.newtask each ([] tasktype:`sum`sleep`fail; args:(100;500;::)); + (n+1 2 3) mustmatch ids; + 3 musteq count tasks; + }; + should["keep args of different types in the same column"]{ + ids:.primary.newtask each ([] tasktype:`sum`fail`sleep; args:(100;::;`a`b)); + (100;::;`a`b) mustmatch first each tasks[([] taskid:ids)]`args; + }; + should["show new tasks as queued in the status counts"]{ + .primary.newtask each ([] tasktype:`sum`sum; args:(1;2)); + 2i musteq .primary.status[][`taskcounts;`queued]; + }; + }; + +.tst.desc[".primary.newtask - rejected tasks"]{ + before{ + `.log.info mock {[x] ::}; + `.ut.ntwarns set 0; + `.log.warn mock {[x] .ut.ntwarns+:1}; + `.primary.tasktypes mock `sum`sleep`fail; + delete from `tasks; + }; + should["reject an unknown task type"]{ + 1b musteq null .primary.newtask `tasktype`args!(`rm;"-rf /"); + 0 musteq count tasks; + 1 musteq .ut.ntwarns; + }; + should["reject a task with no args"]{ + 1b musteq null .primary.newtask enlist[`tasktype]!enlist `sum; + 0 musteq count tasks; + }; + should["reject a task with no tasktype"]{ + 1b musteq null .primary.newtask enlist[`args]!enlist 100; + 0 musteq count tasks; + }; + should["reject an unknown field"]{ + 1b musteq null .primary.newtask `tasktype`args`prority!(`sum;10;1i); + 0 musteq count tasks; + }; + should["not let the caller set taskid or state"]{ + 1b musteq null .primary.newtask `tasktype`args`taskid`state!(`sum;10;999;`done); + 0 musteq count tasks; + }; + should["reject anything that is not a dict"]{ + 1b musteq null .primary.newtask 42; + 1b musteq null .primary.newtask "sum"; + 1b musteq null .primary.newtask `sum; + 0 musteq count tasks; + }; + should["not use up a task id when it rejects"]{ + n:.primary.lasttaskid; + .primary.newtask `tasktype`args!(`rm;::); + .primary.newtask 42; + n musteq .primary.lasttaskid; + (n+1) musteq .primary.newtask `tasktype`args!(`sum;1); + }; + }; diff --git a/tests/unit/oom_spec.q b/tests/unit/oom_spec.q new file mode 100644 index 0000000..f8590fa --- /dev/null +++ b/tests/unit/oom_spec.q @@ -0,0 +1,133 @@ +/ unit specs for OOM labelling: .primary.oomkilled, and its use in .z.pc to fail a task as oom rather than lost +/ loads primary.q once (spawning off). .cgroup.oomkills is mocked to return .ut.omn (the kernel's oom_kill count), +/ .primary.spawn is mocked to record restarts, and .z.pc is called directly with the handle that closed +/ run: tests/run.sh tests/unit/oom_spec.q + +setenv[`SPAWN_SECONDARY;enlist "0"]; +if[not `primary in key `; system "l src/primary.q"]; + +/ empty the tables and register secondaries with ids ids (all free, all on handle 0i) +.ut.omreset:{[ids] + delete from `secondaries; + delete from `tasks; + .primary.lasttaskid:0; + {[i] .primary.register `id`pid`host`port!(i;100i+`int$i;`localhost;45000i+`int$i)} each ids; + }; + +/ send a 10s sleep task to secondary sid and mark it running, returns its id +.ut.omrun:{[sid] + tid:.primary.newtask `tasktype`args!(`sleep;10); + .primary.sendtask[sid;tid]; + .primary.taskupdate[tid;`running;()!()]; + tid + }; + +/ logs silenced, no memory cap, kernel count under test control (starts at 0, as does ours), restarts recorded +.ut.ommocks:{[] + .tst.mock[`.log.info; {[x] ::}]; + .tst.mock[`.log.warn; {[x] ::}]; + .tst.mock[`.primary.tasktypes; `sumtil`sleep`fail]; + .tst.mock[`.primary.retryreasons; `lost`sendfailed]; + .tst.mock[`.primary.memcap; 0N]; + .tst.mock[`.primary.cgroupdir; "/sys/fs/cgroup/test.scope"]; + .tst.mock[`.primary.oomkills; 0]; + `.ut.omn set 0; + .tst.mock[`.cgroup.oomkills; {[d] .ut.omn}]; + .tst.mock[`.primary.spawned; 1 2!101 102i]; + .tst.mock[`.primary.respawnmax; 3]; + .tst.mock[`.primary.respawns; (`long$())!`long$()]; + `.ut.omspawns set `long$(); + .tst.mock[`.primary.spawn; {[n] .ut.omspawns,:n}]; + .tst.mock[`.secondary.runtask; {[tid;tt;a] ::}]; + }; + +.tst.desc[".primary.oomkilled"]{ + before{ + .ut.ommocks[]; + }; + should["be false when the kernel count has not changed"]{ + 0b musteq .primary.oomkilled[]; + 0 musteq .primary.oomkills; + }; + should["be true when the kernel count has risen, and count the kill"]{ + `.ut.omn set 1; + 1b musteq .primary.oomkilled[]; + 1 musteq .primary.oomkills; + }; + should["be false the second time for the same kill"]{ + `.ut.omn set 1; + .primary.oomkilled[]; + 0b musteq .primary.oomkilled[]; + 1 musteq .primary.oomkills; + }; + should["claim one kill per call when several happen at once"]{ + `.ut.omn set 2; + 110b mustmatch {[x] .primary.oomkilled[]} each til 3; + 2 musteq .primary.oomkills; + }; + should["be false when the cgroup count cannot be read"]{ + `.ut.omn set 0N; + 0b musteq .primary.oomkilled[]; + 0 musteq .primary.oomkills; + }; + }; + +.tst.desc[".z.pc - a secondary killed for memory"]{ + before{ + .ut.ommocks[]; + .ut.omreset enlist 1; + }; + should["fail its task with reason oom"]{ + tid:.ut.omrun 1; + `.ut.omn set 1; + .z.pc 0i; + `failed musteq tasks[tid]`state; + `oom musteq tasks[tid]`reason; + 1b musteq tasks[tid][`err] like "*too much memory*"; + }; + should["not retry the task"]{ + tid:.ut.omrun 1; + `.ut.omn set 1; + .z.pc 0i; + 0i musteq tasks[tid]`retrycount; + }; + should["still restart the secondary"]{ + .ut.omrun 1; + `.ut.omn set 1; + .z.pc 0i; + (enlist 1) mustmatch .ut.omspawns; + `closed musteq secondaries[1]`status; + }; + should["count the kill even when the secondary had no task"]{ + `.ut.omn set 1; + mustnotthrow[(); {[] .z.pc 0i}]; + 1 musteq .primary.oomkills; + }; + }; + +.tst.desc[".z.pc - any other close"]{ + before{ + .ut.ommocks[]; + .ut.omreset enlist 1; + }; + should["fail the task as lost and retry it when the kernel count has not changed"]{ + tid:.ut.omrun 1; + .z.pc 0i; + 1i musteq tasks[tid]`retrycount; + / the only secondary is now closed, so the retry waits in the queue + `queued musteq tasks[tid]`state; + 0 musteq .primary.oomkills; + }; + should["not use up a kill for a connection that is not a secondary"]{ + `.ut.omn set 1; + .z.pc 77i; + 0 musteq .primary.oomkills; + }; + should["fail the task as lost when there is no cgroup count"]{ + tid:.ut.omrun 1; + `.ut.omn set 0N; + .z.pc 0i; + 1i musteq tasks[tid]`retrycount; + 0 musteq .primary.oomkills; + }; + }; \ No newline at end of file diff --git a/tests/unit/pc_spec.q b/tests/unit/pc_spec.q new file mode 100644 index 0000000..c77d172 --- /dev/null +++ b/tests/unit/pc_spec.q @@ -0,0 +1,130 @@ +/ unit specs for .z.pc on the primary: a closed secondary is marked closed and its in-flight task is failed +/ loads primary.q once (spawning off). Secondaries are added with .primary.register, which stores .z.w (0i locally), +/ tasks are given to them with .primary.sendtask (the send on 0i runs locally, .secondary.runtask is mocked), +/ and the tests call .z.pc directly with the handle that closed +/ run: tests/run.sh tests/unit/pc_spec.q + +setenv[`SPAWN_SECONDARY;enlist "0"]; +if[not `primary in key `; system "l src/primary.q"]; + +/ empty both tables, then register secondaries with ids ids (all free, all on handle 0i) +.ut.pcreset:{[ids] + delete from `secondaries; + delete from `tasks; + .primary.lasttaskid:0; + {[i] .primary.register `id`pid`host`port!(i;100i+`int$i;`localhost;45000i+`int$i)} each ids; + }; + +/ add a task and send it to secondary sid, returns the task id +.ut.pcsend:{[sid] + tid:.primary.newtask `tasktype`args!(`sleep;10); + .primary.sendtask[sid;tid]; + tid + }; + +/ quiet logs (counting warnings), a fixed task type list, a runtask that does nothing, and no retries +/ uses .tst.mock[name;value]: the infix "mock" only exists inside .tst.desc +.ut.pcmocks:{[] + .tst.mock[`.log.info; {[x] ::}]; + `.ut.pcwarns set 0; + .tst.mock[`.log.warn; {[x] .ut.pcwarns+:1}]; + .tst.mock[`.primary.tasktypes; `sumtil`sleep`fail]; + .tst.mock[`.secondary.runtask; {[tid;tt;a] ::}]; + / retries are tested in retry_spec.q, so a failed task stays failed here + .tst.mock[`.primary.retryreasons; `$()]; + }; + +.tst.desc[".z.pc - a secondary with a task"]{ + before{ + .ut.pcmocks[]; + .ut.pcreset enlist 1; + }; + should["fail a dispatched task with reason lost"]{ + tid:.ut.pcsend 1; + `dispatched musteq tasks[tid]`state; + .z.pc 0i; + r:tasks tid; + `failed musteq r`state; + `lost musteq r`reason; + "secondary lost" mustmatch r`err; + 1b musteq not null r`finishedtime; + }; + should["fail a running task with reason lost"]{ + tid:.ut.pcsend 1; + .primary.taskupdate[tid;`running;()!()]; + .z.pc 0i; + `failed musteq tasks[tid]`state; + `lost musteq tasks[tid]`reason; + }; + should["mark the secondary closed with no handle and no current task"]{ + .ut.pcsend 1; + .z.pc 0i; + `closed musteq secondaries[1]`status; + 1b musteq null secondaries[1]`handle; + 1b musteq null secondaries[1]`currenttask; + }; + should["log one warning for the lost task"]{ + .ut.pcsend 1; + .z.pc 0i; + 1 musteq .ut.pcwarns; + }; + should["not give the closed secondary another task"]{ + .ut.pcsend 1; + .z.pc 0i; + tid:.primary.newtask `tasktype`args!(`sleep;1); + .primary.dispatch[]; + `queued musteq tasks[tid]`state; + }; + }; + +.tst.desc[".z.pc - leaves everything else alone"]{ + before{ + .ut.pcmocks[]; + .ut.pcreset 1 2; + }; + should["not touch another secondary or its task"]{ + t1:.ut.pcsend 1; + t2:.ut.pcsend 2; + / give secondary 2 its own handle so only secondary 1 is on 0i + update handle:5i from `secondaries where id=2; + .z.pc 0i; + `failed musteq tasks[t1]`state; + `dispatched musteq tasks[t2]`state; + `busy musteq secondaries[2]`status; + t2 musteq secondaries[2]`currenttask; + }; + should["not touch queued tasks"]{ + .ut.pcsend 1; + / secondary 2 busy on its own handle, so the dispatch after the failure has nowhere to send the queued task + update handle:5i, status:`busy from `secondaries where id=2; + qt:.primary.newtask `tasktype`args!(`sleep;1); + .z.pc 0i; + `queued musteq tasks[qt]`state; + }; + should["change no task when a free secondary closes"]{ + update handle:5i from `secondaries where id=2; + qt:.primary.newtask `tasktype`args!(`sleep;1); + t0:tasks; + .z.pc 0i; + `closed musteq secondaries[1]`status; + t0 mustmatch tasks; + 0 musteq .ut.pcwarns; + }; + should["leave a task that already finished as done"]{ + update handle:5i from `secondaries where id=2; + tid:.ut.pcsend 1; + .primary.taskupdate[tid;`running;()!()]; + .primary.taskupdate[tid;`done;`resultpath`resultbytes`membefore`memafter!(`:x;0;0;0)]; + .z.pc 0i; + `done musteq tasks[tid]`state; + `closed musteq secondaries[1]`status; + }; + should["do nothing for a handle that is not a secondary"]{ + tid:.ut.pcsend 1; + s0:secondaries; + t0:tasks; + .z.pc 77i; + s0 mustmatch secondaries; + t0 mustmatch tasks; + }; + }; \ No newline at end of file diff --git a/tests/unit/pollmem_spec.q b/tests/unit/pollmem_spec.q new file mode 100644 index 0000000..276d610 --- /dev/null +++ b/tests/unit/pollmem_spec.q @@ -0,0 +1,100 @@ +/ unit specs for .primary.pollmem and .primary.totalmem: the primary reads its own and every live secondary's memory +/ loads primary.q once (spawning off). The "secondaries" are registered with the pids of short-lived sleep processes, +/ so .mem.read has real processes to read +/ run: tests/run.sh tests/unit/pollmem_spec.q + +setenv[`SPAWN_SECONDARY;enlist "0"]; +if[not `primary in key `; system "l src/primary.q"]; + +/ start a sleep process in the background and return its pid; stop a list of them +.ut.pmsleep:{[] "I"$first system "sh -c 'sleep 30 > /dev/null 2>&1 & echo $!'"}; +.ut.pmkill:{[pids] if[count pids; system "sh -c 'kill ",(" " sv string pids)," 2>/dev/null; true'"]}; + +/ empty the tables, start two sleeps and register them as secondaries 1 and 2 +.ut.pmreset:{[] + delete from `secondaries; + delete from `memhistory; + `.ut.pmpids set .ut.pmsleep each til 2; + {[i;p] .primary.register `id`pid`host`port!(i;p;`localhost;45000i+`int$i)}'[1 2;.ut.pmpids]; + }; + +.tst.desc[".primary.pollmem"]{ + before{ + `.log.info mock {[x] ::}; + `.log.warn mock {[x] ::}; + .ut.pmreset[]; + }; + after{ + .ut.pmkill .ut.pmpids; + }; + should["fill in rssanon, vmrss and memtime for every live secondary"]{ + t0:.z.P; + .primary.pollmem[]; + r:0!secondaries; + 1b musteq all r[`rssanon]>0; + 1b musteq all r[`vmrss]>=r`rssanon; + 1b musteq all r[`memtime]>=t0; + }; + should["record the primary's own memory"]{ + .primary.pollmem[]; + 1b musteq .primary.selfmem>1048576; + / a fresh read can differ by a few pages, so compare to within 1MB + 1b musteq 1048576>abs .primary.selfmem-first exec rssanon from .mem.read enlist .z.i; + }; + should["leave a closed secondary alone"]{ + update status:`closed, handle:0Ni from `secondaries where id=2; + .primary.pollmem[]; + 1b musteq null secondaries[2]`rssanon; + 1b musteq null secondaries[2]`memtime; + 1b musteq not null secondaries[1]`rssanon; + }; + should["give nulls for a secondary whose process has gone"]{ + .ut.pmkill 1#.ut.pmpids; + system "sleep 0.2"; + .primary.pollmem[]; + 1b musteq null secondaries[1]`rssanon; + 1b musteq not null secondaries[2]`rssanon; + }; + should["add one history row per poll with the total split into primary and secondaries"]{ + .primary.pollmem[]; + .primary.pollmem[]; + 2 musteq count memhistory; + h:last memhistory; + h[`total] musteq h[`primary]+h`secondaries; + (exec sum rssanon from secondaries where status<>`closed) musteq h`secondaries; + }; + should["count busy secondaries in the history"]{ + update status:`busy from `secondaries where id=1; + .primary.pollmem[]; + 1i musteq last memhistory`busy; + }; + should["keep only the last memhistorymax rows"]{ + `.primary.memhistorymax mock 3; + do[5; .primary.pollmem[]]; + 3 musteq count memhistory; + }; + }; + +.tst.desc[".primary.totalmem"]{ + before{ + `.log.info mock {[x] ::}; + `.log.warn mock {[x] ::}; + .ut.pmreset[]; + }; + after{ + .ut.pmkill .ut.pmpids; + }; + should["be the primary plus every live secondary"]{ + .primary.pollmem[]; + (.primary.selfmem + exec sum rssanon from secondaries) musteq .primary.totalmem[]; + }; + should["leave out closed secondaries"]{ + .primary.pollmem[]; + update status:`closed from `secondaries where id=2; + (.primary.selfmem + secondaries[1]`rssanon) musteq .primary.totalmem[]; + }; + should["match the latest history row"]{ + .primary.pollmem[]; + (last memhistory`total) musteq .primary.totalmem[]; + }; + }; \ No newline at end of file diff --git a/tests/unit/primarytests.q b/tests/unit/primarytests.q new file mode 100644 index 0000000..feaffe8 --- /dev/null +++ b/tests/unit/primarytests.q @@ -0,0 +1,79 @@ +setenv[`SPAWN_SECONDARY;enlist "0"]; +if[not `primary in key `; system "l src/primary.q"]; + +.tst.desc["check env vars are as excpected"]{ + should["STALE_MS should be 5 seconds"]{ + 00:00:05 musteq .primary.stale; + }; + should["HEARTBEAT_MS should be 1 seconds"]{ + 00:00:01 musteq .primary.heartbeat + }; + }; + +.tst.desc["check table schemas"]{ + should["return 3 tables"]{ + 4 musteq count tables[]; + system "l schemas/primarytables.q"; + }; + should["have the correct schema for secondaries table"]{ + (`id`handle`pid`host`status`lastheartbeat`consecutivefails`healthy`spawned`starttime`registeredtime`tasktypes`currenttask`rssanon`vmrss`memtime) mustmatch cols secondaries; + "jiisspibbpp jjjp" mustmatch exec t from meta secondaries; + }; + should["have the correct schema for the tasks table"]{ + (`taskid`tasktype`args`priority`submittedtime`memestimate`timeout`retriesmax`retrycount`state`secondaryid`dispatchedtime`startedtime`finishedtime`membefore`memafter`memaftergc`err`reason`resultpath`resultbytes`jobid`user) mustmatch cols tasks; + "js ipjtiisjpppjjj ssjjs" mustmatch exec t from meta tasks; + }; + should["have the correct schema for memhistory table"]{ + (`time`total`primary`secondaries`busy) mustmatch cols memhistory; + "pjjji" mustmatch exec t from meta memhistory; + }; + should["have the correct schema for the jobs table"]{ + (`jobid`tasktype`user`ntasks`priority`state`submittedtime`finishedtime`resultbytes`err) mustmatch cols jobs; + "jssiisppj " mustmatch exec t from meta jobs; + }; + }; + +.tst.desc["can a secondary register with .primary.register"]{ + before{ + `.log.warn mock {}; + `.log.info mock {}; + .primary.register ([id:1; pid:4000i; host:`localhost]); + }; + should["have 1 secondary present"]{ + 1 musteq count secondaries; + }; + should["have id be 1"]{ + 1 musteq first exec id from secondaries; + }; + should["have handle be 6"]{ + 0i musteq first exec handle from secondaries; + }; + }; + +// should see the above now as stale, uses previous secondary +.tst.desc[".primary.check will say the connection is stale"]{ + before{ + system"sleep 6"; + .primary.check[]; + }; + should["have a status of stale"]{ + `stale musteq first exec status from secondaries where id = 1; + }; + }; + + +// update it with dummy mem data and check lastupdate is new +.tst.desc[".primary.heartbeatcheck updates secondary status to free"]{ + before{ + .primary.heartbeatcheck 100; + }; + should["return status as free"]{ + `free musteq first exec status from secondaries where id = 1; + }; + should["have memory as 100"]{ + 100 musteq first exec rssanon from secondaries where id = 1; + }; + }; + +// .z.pc in integration testing +// add in table checks that meta is correct and all expected tables are present \ No newline at end of file diff --git a/tests/unit/respawn_spec.q b/tests/unit/respawn_spec.q new file mode 100644 index 0000000..1b7b10d --- /dev/null +++ b/tests/unit/respawn_spec.q @@ -0,0 +1,123 @@ +/ unit specs for restarting dead secondaries: .primary.respawnsecondary, and the call to it from .z.pc +/ loads primary.q once (spawning off). .primary.spawn is mocked to record the ids it would start, .primary.spawned is +/ mocked to say which ids this primary spawned, and .z.pc is called directly with the handle that closed +/ run: tests/run.sh tests/unit/respawn_spec.q + +setenv[`SPAWN_SECONDARY;enlist "0"]; +if[not `primary in key `; system "l src/primary.q"]; + +/ empty the tables and register secondaries with ids ids (all free, all on handle 0i) +.ut.rsreset:{[ids] + delete from `secondaries; + delete from `tasks; + .primary.lasttaskid:0; + {[i] .primary.register `id`pid`host`port!(i;100i+`int$i;`localhost;45000i+`int$i)} each ids; + }; + +/ logs counted, secondaries 1 and 2 spawned by us, up to 3 restarts each, spawns and kills recorded +.ut.rsmocks:{[] + `.ut.rsinfos`.ut.rswarns set' 0; + .tst.mock[`.log.info; {[x] if[x like "restarting*"; .ut.rsinfos+:1]}]; + .tst.mock[`.log.warn; {[x] .ut.rswarns+:1}]; + .tst.mock[`.primary.tasktypes; `sumtil`sleep`fail]; + .tst.mock[`.primary.retryreasons; `lost`sendfailed]; + .tst.mock[`.primary.memcap; 0N]; + .tst.mock[`.primary.spawned; 1 2!101 102i]; + .tst.mock[`.primary.respawnmax; 3]; + .tst.mock[`.primary.respawns; (`long$())!`long$()]; + `.ut.rsspawns set `long$(); + .tst.mock[`.primary.spawn; {[n] .ut.rsspawns,:n}]; + .tst.mock[`.secondary.runtask; {[tid;tt;a] ::}]; + `.ut.rskills set `int$(); + .tst.mock[`.os.kill9; {[p] .ut.rskills,:p}]; + }; + +.tst.desc[".primary.respawnsecondary"]{ + before{ + .ut.rsmocks[]; + / secondaries 1 and 2 have died, as they would have by the time .z.pc calls this + .ut.rsreset 1 2; + update status:`closed, handle:0Ni from `secondaries; + }; + should["restart a secondary this primary spawned"]{ + .primary.respawnsecondary 1; + (enlist 1) mustmatch .ut.rsspawns; + 1 musteq .primary.respawns 1; + 1 musteq .ut.rsinfos; + }; + should["count restarts separately for each secondary"]{ + .primary.respawnsecondary each 1 1 2; + 2 musteq .primary.respawns 1; + 1 musteq .primary.respawns 2; + }; + should["stop restarting a secondary after respawnmax restarts"]{ + do[5; .primary.respawnsecondary 1]; + 3 musteq count .ut.rsspawns; + 3 musteq .primary.respawns 1; + / one warning for each refused restart + 2 musteq .ut.rswarns; + }; + should["not restart a secondary this primary did not spawn"]{ + .primary.respawnsecondary 5; + 0 musteq count .ut.rsspawns; + }; + should["never restart when respawnmax is 0"]{ + `.primary.respawnmax mock 0; + .primary.respawnsecondary 1; + 0 musteq count .ut.rsspawns; + }; + should["never restart when respawnmax is not set"]{ + `.primary.respawnmax mock 0N; + .primary.respawnsecondary 1; + 0 musteq count .ut.rsspawns; + }; + should["do nothing for a null id"]{ + .primary.respawnsecondary 0N; + 0 musteq count .ut.rsspawns; + }; + }; + +.tst.desc[".z.pc restarts the secondary that closed"]{ + before{ + .ut.rsmocks[]; + .ut.rsreset enlist 1; + }; + should["restart a spawned secondary when its connection closes"]{ + .z.pc 0i; + (enlist 1) mustmatch .ut.rsspawns; + `closed musteq secondaries[1]`status; + }; + should["fail its task as lost and then restart it"]{ + tid:.primary.newtask `tasktype`args!(`sleep;10); + `.primary.retryreasons mock `$(); + .primary.sendtask[1;tid]; + .z.pc 0i; + `lost musteq tasks[tid]`reason; + (enlist 1) mustmatch .ut.rsspawns; + }; + should["not restart anything for a handle that is not a secondary"]{ + .z.pc 77i; + 0 musteq count .ut.rsspawns; + }; + }; + +.tst.desc["a timeout followed by .z.pc"]{ + before{ + .ut.rsmocks[]; + .ut.rsreset enlist 1; + }; + should["leave the task failed as timeout, not lost, and restart the secondary"]{ + tid:.primary.newtask `tasktype`args`timeout!(`sleep;10;00:00:01.000); + .primary.sendtask[1;tid]; + .primary.taskupdate[tid;`running;()!()]; + update startedtime:.z.P-0D00:00:02 from `tasks where taskid=tid; + .primary.checktimeouts[]; + / the kill would close the connection, which fires .z.pc + .z.pc 0i; + `failed musteq tasks[tid]`state; + `timeout musteq tasks[tid]`reason; + 0i musteq tasks[tid]`retrycount; + (enlist 101i) mustmatch .ut.rskills; + (enlist 1) mustmatch .ut.rsspawns; + }; + }; \ No newline at end of file diff --git a/tests/unit/status_spec.q b/tests/unit/status_spec.q new file mode 100644 index 0000000..79f9916 --- /dev/null +++ b/tests/unit/status_spec.q @@ -0,0 +1,160 @@ +/ unit specs for .primary.status and .primary.countby +/ run with: tests/run.sh tests/unit/status_spec.q + +/ load primary.q at the first test, only if no other spec file has already loaded it, +/ with spawning off so no real secondaries start; then put it back to an empty state +/ called at the start of every before +.ut.reset:{[] + if[not `primary in key `; + setenv[`SPAWN_SECONDARY;enlist "0"]; + system "l src/primary.q"]; + delete from `secondaries; + delete from `tasks; + .primary.spawned:(`long$())!`int$(); + .primary.starttime:.z.P-0D00:01; + }; + +/ register a fake secondary with id i (port 45000+i) +.ut.reg:{[i] .primary.register `id`pid`host`port!(i;100i;`localhost;45000i+`int$i)}; + + +.tst.desc[".primary.countby"]{ + before{ + .ut.reset[]; + `.log.info mock {[x] ::}; + }; + should["have the correct count of each state"]{ + .primary.countby[`free`busy`stale`closed;`free`closed`free] mustmatch `free`busy`stale`closed!2 0 0 1i; + }; + should["give all 0s for an empty list"]{ + .primary.countby[`free`busy`stale`closed; `$()] mustmatch `free`busy`stale`closed!0 0 0 0i; + }; + should["return ints"]{ + 6h musteq type value .primary.countby[`free`busy;`free`free]; + }; + }; + +.tst.desc[".primary.status"]{ + before{ + .ut.reset[]; + `.log.info mock {[x] ::}; + }; + should["have the correct keys"]{ + s:.primary.status[]; + 99h musteq type s; + `time`uptime`memory`dispatch`secondaries`seccounts`taskcounts mustmatch key s; + }; + should["work with no secondaries and no tasks"]{ + s:.primary.status[]; + 0 musteq count s`secondaries; + (`free`busy`stale`closed!0 0 0 0i) mustmatch s`seccounts; + (`queued`dispatched`running`done`failed!0 0 0 0 0i) mustmatch s`taskcounts; + }; + should["count secondaries by status"]{ + .ut.reg each 1 2 3 4; + update status:`closed from `secondaries where id=3; + update status:`stale from `secondaries where id=4; + (`free`busy`stale`closed!2 0 1 1i) mustmatch .primary.status[]`seccounts; + }; + should["count every secondary in some state"]{ + .ut.reg each 1 2 3; + update status:`busy from `secondaries where id=2; + (count secondaries) musteq `long$sum .primary.status[]`seccounts; + }; + should["show one row per secondary with the R1 fields"]{ + .ut.reg each 1 2; + t:.primary.status[]`secondaries; + 2 musteq count t; + `id`pid`status`spawned`currenttask`rssanon`restarts`lastseen mustmatch cols t; + }; + should["show a just-registered secondary as seen moments ago"]{ + .ut.reg 1; + 1b musteq (first .primary.status[][`secondaries]`lastseen)<00:00:01.000; + }; + should["show how long ago a quiet secondary was last seen"]{ + .ut.reg 1; + update lastheartbeat:.z.P-0D00:00:10 from `secondaries where id=1; + 1b musteq (first .primary.status[][`secondaries]`lastseen) within 00:00:10.000 00:00:11.000; + }; + should["report uptime since start"]{ + 1b musteq .primary.status[][`uptime]>=0D00:01; + }; + should["not change the secondaries table"]{ + .ut.reg each 1 2; + t0:secondaries; + .primary.status[]; + t0 mustmatch secondaries; + }; + }; + +.tst.desc[".primary.status - memory, dispatch and the new secondary columns"]{ + before{ + .ut.reset[]; + `.log.info mock {[x] ::}; + `.primary.memcap mock 1000; + `.primary.selfmem mock 100; + `.primary.paused mock 0b; + `.primary.pausedsince mock 0Np; + `.primary.pausedtotal mock 0D; + `.primary.pausecount mock 0; + `.primary.respawns mock (`long$())!`long$(); + }; + should["have total, cap, headroom and primary in the memory section"]{ + `total`cap`headroom`primary mustmatch key .primary.status[]`memory; + }; + should["add up the primary and the live secondaries, with headroom under the cap"]{ + .ut.reg each 1 2; + update rssanon:200 300 from `secondaries; + m:.primary.status[]`memory; + 600 musteq m`total; + 1000 musteq m`cap; + 400 musteq m`headroom; + 100 musteq m`primary; + }; + should["show negative headroom when over the cap"]{ + .ut.reg 1; + update rssanon:1500 from `secondaries; + -600 musteq .primary.status[][`memory;`headroom]; + }; + should["show null cap and headroom when there is no cap"]{ + `.primary.memcap mock 0N; + m:.primary.status[]`memory; + 1b musteq null m`cap; + 1b musteq null m`headroom; + }; + should["show dispatch running with no pauses"]{ + d:.primary.status[]`dispatch; + 0b musteq d`paused; + 0 musteq d`pausecount; + 0D musteq d`pausedtotal; + }; + should["count a pause that is still going on in pausedtotal"]{ + `.primary.paused mock 1b; + `.primary.pausecount mock 2; + `.primary.pausedtotal mock 0D00:00:01; + `.primary.pausedsince mock .z.P-0D00:00:02; + d:.primary.status[]`dispatch; + 1b musteq d`paused; + 2 musteq d`pausecount; + / 1s from earlier pauses plus ~2s of this one + 1b musteq d[`pausedtotal] within 0D00:00:03 0D00:00:04; + }; + should["show each secondary's current task, memory and restarts"]{ + .ut.reg each 1 2; + update currenttask:7 0N, rssanon:200 300 from `secondaries; + `.primary.respawns mock (enlist 2)!enlist 1; + t:`id xasc .primary.status[]`secondaries; + 7 0N mustmatch t`currenttask; + 200 300 mustmatch t`rssanon; + 0 1 mustmatch t`restarts; + }; + should["print without an error, paused or not, with or without a cap"]{ + .ut.reg each 1 2; + mustnotthrow[();{.primary.showstatus[]}]; + `.primary.paused mock 1b; + `.primary.pausedsince mock .z.P; + mustnotthrow[();{.primary.showstatus[]}]; + `.primary.memcap mock 0N; + mustnotthrow[();{.primary.showstatus[]}]; + }; + }; \ No newline at end of file diff --git a/tests/unit/tasks_spec.q b/tests/unit/tasks_spec.q new file mode 100644 index 0000000..aaec923 --- /dev/null +++ b/tests/unit/tasks_spec.q @@ -0,0 +1,18 @@ +/ unit specs for the task schema, the task defaults and task ids +/ loads primary.q once (spawning off), each test starts from an empty tasks table +/ run: tests/run.sh tests/unit/tasks_spec.q + +setenv[`SPAWN_SECONDARY;enlist "0"]; +if[not `primary in key `; system "l src/primary.q"]; + +.tst.desc[".primary.nexttaskid"]{ + before{ + `.log.info mock {[x] ::}; + .primary.lasttaskid:0; + }; + should["start at 1 and go up by one"]{ + 0 musteq .primary.lasttaskid; + 1 musteq .primary.nexttaskid[]; + 1 musteq .primary.lasttaskid; + }; + }; diff --git a/tests/unit/taskupdate_spec.q b/tests/unit/taskupdate_spec.q new file mode 100644 index 0000000..d77b59a --- /dev/null +++ b/tests/unit/taskupdate_spec.q @@ -0,0 +1,115 @@ +/ unit specs for .primary.taskupdate, the only way a task changes state +/ loads primary.q once (spawning off); each test puts its own task (id 900) in a known state first +/ run: tests/run.sh tests/unit/taskupdate_spec.q + +setenv[`SPAWN_SECONDARY;enlist "0"]; +if[not `primary in key `; system "l src/primary.q"]; + +.ut.tuid:900; + +/ a full task row for .ut.tuid in state s +.ut.tuprow:{[s] + `taskid`tasktype`args`priority`submittedtime`memestimate`timeout`retriesmax`retrycount`state`secondaryid`dispatchedtime`startedtime`finishedtime`membefore`memafter`err`reason`resultpath`resultbytes! + (.ut.tuid;`noop;enlist 1;0i;.z.P;0N;00:01:00.000;3i;0i;s;0N;0Np;0Np;0Np;0N;0N;"";`; `; 0N) + }; + +/ put task .ut.tuid into state s, replacing any earlier row +.ut.tuset:{[s] + delete from `tasks where taskid=.ut.tuid; + `tasks upsert .ut.tuprow s; + }; + +.ut.tuget:{[] tasks .ut.tuid}; + +.tst.desc[".primary.taskupdate - legal moves"]{ + before{ + `.log.info mock {[x] ::}; + `.ut.warns set 0; + `.log.warn mock {[x] .ut.warns+:1}; + }; + should["move queued to dispatched and record the secondary"]{ + .ut.tuset `queued; + 1b musteq .primary.taskupdate[.ut.tuid;`dispatched;enlist[`secondaryid]!enlist 2]; + r:.ut.tuget[]; + `dispatched musteq r`state; + 2 musteq r`secondaryid; + 1b musteq not null r`dispatchedtime; + }; + should["move dispatched to running and stamp the start time"]{ + .ut.tuset `dispatched; + 1b musteq .primary.taskupdate[.ut.tuid;`running;()!()]; + r:.ut.tuget[]; + `running musteq r`state; + 1b musteq not null r`startedtime; + }; + should["move running to done and store the result and memory"]{ + .ut.tuset `running; + 1b musteq .primary.taskupdate[.ut.tuid;`done;`membefore`memafter`resultpath`resultbytes!(1000;800;`:/tmp/x;16)]; + r:.ut.tuget[]; + `done musteq r`state; + 1b musteq not null r`finishedtime; + `:/tmp/x musteq r`resultpath; + 16 musteq r`resultbytes; + 1000 musteq r`membefore; + 800 musteq r`memafter; + }; + should["move running to failed and store the error"]{ + .ut.tuset `running; + 1b musteq .primary.taskupdate[.ut.tuid;`failed;`err`reason!("boom";`unknown)]; + r:.ut.tuget[]; + `failed musteq r`state; + "boom" mustmatch r`err; + `unknown musteq r`reason; + 1b musteq not null r`finishedtime; + }; + should["allow dispatched to failed (secondary died before starting)"]{ + .ut.tuset `dispatched; + 1b musteq .primary.taskupdate[.ut.tuid;`failed;()!()]; + `failed musteq .ut.tuget[]`state; + }; + should["show the move in the status task counts"]{ + .ut.tuset `queued; + n:.primary.status[]`taskcounts; + .primary.taskupdate[.ut.tuid;`dispatched;()!()]; + m:.primary.status[]`taskcounts; + (n[`queued]-1i) musteq m`queued; + (n[`dispatched]+1i) musteq m`dispatched; + }; + }; + +.tst.desc[".primary.taskupdate - rejected moves leave the task alone"]{ + before{ + `.log.info mock {[x] ::}; + `.ut.warns set 0; + `.log.warn mock {[x] .ut.warns+:1}; + }; + should["reject a late done for a task that already failed"]{ + .ut.tuset `failed; + r0:.ut.tuget[]; + 0b musteq .primary.taskupdate[.ut.tuid;`done;()!()]; + r0 mustmatch .ut.tuget[]; + 1 musteq .ut.warns; + }; + should["reject skipping a state (queued to done)"]{ + .ut.tuset `queued; + r0:.ut.tuget[]; + 0b musteq .primary.taskupdate[.ut.tuid;`done;()!()]; + r0 mustmatch .ut.tuget[]; + }; + should["treat done as final"]{ + .ut.tuset `done; + r0:.ut.tuget[]; + 0b musteq any .primary.taskupdate[.ut.tuid;;()!()] each `queued`dispatched`running`failed; + r0 mustmatch .ut.tuget[]; + }; + should["reject an unknown task without creating it"]{ + delete from `tasks where taskid=.ut.tuid; + 0b musteq .primary.taskupdate[.ut.tuid;`dispatched;()!()]; + 0 musteq count select from tasks where taskid=.ut.tuid; + }; + should["not let info override the new state"]{ + .ut.tuset `queued; + 1b musteq .primary.taskupdate[.ut.tuid;`dispatched;`state`secondaryid!(`done;2)]; + `dispatched musteq .ut.tuget[]`state; + }; + }; diff --git a/tests/unit/timeout_spec.q b/tests/unit/timeout_spec.q new file mode 100644 index 0000000..0aa20fb --- /dev/null +++ b/tests/unit/timeout_spec.q @@ -0,0 +1,143 @@ +/ unit specs for task timeouts: .primary.checktimeouts and .primary.timeout +/ loads primary.q once (spawning off). Secondaries are registered on handle 0i (sends run locally, .secondary.runtask +/ is mocked), .os.kill9 is mocked to record the pids it would kill, and task times are backdated to make tasks late +/ run: tests/run.sh tests/unit/timeout_spec.q + +setenv[`SPAWN_SECONDARY;enlist "0"]; +if[not `primary in key `; system "l src/primary.q"]; + +/ empty the tables and register secondaries with ids ids (all free, all on handle 0i, pid 100+id) +.ut.toreset:{[ids] + delete from `secondaries; + delete from `tasks; + .primary.lasttaskid:0; + {[i] .primary.register `id`pid`host`port!(i;100i+`int$i;`localhost;45000i+`int$i)} each ids; + }; + +/ send a 10s sleep task with a 1s timeout to secondary sid, optionally mark it running, returns its id +.ut.tosend:{[sid;run] + tid:.primary.newtask `tasktype`args`timeout!(`sleep;10;00:00:01.000); + .primary.sendtask[sid;tid]; + if[run; .primary.taskupdate[tid;`running;()!()]]; + tid + }; + +/ make a task look like it started (and was dispatched) secs seconds ago +.ut.tolate:{[tid;secs] update dispatchedtime:.z.P-secs*0D00:00:01, startedtime:?[null startedtime;startedtime;.z.P-secs*0D00:00:01] from `tasks where taskid=tid}; + +/ logs counted, retries as in config, sends and kills recorded +.ut.tomocks:{[] + .tst.mock[`.log.info; {[x] ::}]; + `.ut.towarns set 0; + .tst.mock[`.log.warn; {[x] .ut.towarns+:1}]; + .tst.mock[`.primary.tasktypes; `sumtil`sleep`fail]; + .tst.mock[`.primary.retryreasons; `lost`sendfailed]; + .tst.mock[`.primary.memcap; 0N]; + .tst.mock[`.secondary.runtask; {[tid;tt;a] ::}]; + `.ut.tokills set `int$(); + .tst.mock[`.os.kill9; {[p] .ut.tokills,:p}]; + }; + +.tst.desc[".primary.checktimeouts - late tasks"]{ + before{ + .ut.tomocks[]; + .ut.toreset enlist 1; + }; + should["fail a running task that is past its timeout, with reason timeout"]{ + tid:.ut.tosend[1;1b]; + .ut.tolate[tid;2]; + .primary.checktimeouts[]; + r:tasks tid; + `failed musteq r`state; + `timeout musteq r`reason; + 1b musteq r[`err] like "timed out*"; + }; + should["kill the secondary's process"]{ + tid:.ut.tosend[1;1b]; + .ut.tolate[tid;2]; + .primary.checktimeouts[]; + (enlist 101i) mustmatch .ut.tokills; + }; + should["take the secondary out of use with no current task"]{ + tid:.ut.tosend[1;1b]; + .ut.tolate[tid;2]; + .primary.checktimeouts[]; + `closed musteq secondaries[1]`status; + 1b musteq null secondaries[1]`currenttask; + }; + should["time out a dispatched task whose secondary never reported running"]{ + tid:.ut.tosend[1;0b]; + .ut.tolate[tid;2]; + .primary.checktimeouts[]; + `failed musteq tasks[tid]`state; + `timeout musteq tasks[tid]`reason; + }; + should["not retry a task that timed out"]{ + tid:.ut.tosend[1;1b]; + .ut.tolate[tid;2]; + .primary.checktimeouts[]; + 0i musteq tasks[tid]`retrycount; + `failed musteq tasks[tid]`state; + }; + should["not give the killed secondary another task"]{ + tid:.ut.tosend[1;1b]; + q:.primary.newtask `tasktype`args!(`sleep;1); + .ut.tolate[tid;2]; + .primary.checktimeouts[]; + `queued musteq tasks[q]`state; + }; + should["log one warning per timeout"]{ + tid:.ut.tosend[1;1b]; + .ut.tolate[tid;2]; + .primary.checktimeouts[]; + 1 musteq .ut.towarns; + }; + should["log, not throw, when the kill fails"]{ + `.os.kill9 mock {[p] '"no such process"}; + tid:.ut.tosend[1;1b]; + .ut.tolate[tid;2]; + .primary.checktimeouts[]; + `failed musteq tasks[tid]`state; + 2 musteq .ut.towarns; + }; + }; + +.tst.desc[".primary.checktimeouts - everything else is left alone"]{ + before{ + .ut.tomocks[]; + .ut.toreset 1 2; + }; + should["leave a task that is still within its timeout"]{ + tid:.ut.tosend[1;1b]; + .primary.checktimeouts[]; + `running musteq tasks[tid]`state; + 0 musteq count .ut.tokills; + }; + should["leave queued and done tasks alone however old"]{ + / finish d first: its done would dispatch any task already queued + d:.ut.tosend[1;1b]; + .primary.taskupdate[d;`done;`resultpath`resultbytes`membefore`memafter!(`:x;0;0;0)]; + qt:.primary.newtask `tasktype`args`timeout!(`sleep;1;00:00:01.000); + update submittedtime:.z.P-0D01:00, dispatchedtime:.z.P-0D01:00, startedtime:.z.P-0D01:00 from `tasks; + .primary.checktimeouts[]; + 0 musteq count .ut.tokills; + `done`queued mustmatch tasks[([] taskid:d,qt)]`state; + }; + should["time out every late task in one check"]{ + t1:.ut.tosend[1;1b]; + t2:.ut.tosend[2;1b]; + .ut.tolate[t1;2]; + .ut.tolate[t2;2]; + .primary.checktimeouts[]; + `failed`failed mustmatch tasks[([] taskid:t1,t2)]`state; + (asc 101 102i) mustmatch asc .ut.tokills; + }; + should["only time out the late task when one is late and one is not"]{ + t1:.ut.tosend[1;1b]; + t2:.ut.tosend[2;1b]; + .ut.tolate[t1;2]; + .primary.checktimeouts[]; + `failed`running mustmatch tasks[([] taskid:t1,t2)]`state; + `busy musteq secondaries[2]`status; + }; + }; \ No newline at end of file