From d812d528e4b7120475a6657f978e905c2a2cc01e Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Mon, 5 Oct 2026 14:54:06 +0100 Subject: [PATCH 01/49] bench-313: adding heartbeat functions --- README.md | 47 ++++++++++++++++++++++++++++++++++++++++ config/default.env | 4 ++++ image.png | Bin 0 -> 66133 bytes schemas/primarytables.q | 36 +++++++++++++++--------------- src/common/timer.q | 30 +++++++++++++++++++++++++ src/primary.q | 43 ++++++++++++++++++++++++++++++++++++ src/secondary.q | 24 +++++++++++++++++--- 7 files changed, 163 insertions(+), 21 deletions(-) create mode 100644 image.png create mode 100644 src/common/timer.q diff --git a/README.md b/README.md index e40963f..1a9d7f1 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,49 @@ # Parallelisation-Project 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 +``` + +### Secondaries +These will either be ran as part of the intial start up or the primary will spin up more as needed. They will take the port number `PRIMARY_PORT` + `id` so `secondary 1 `would have a port of `45001` and so on. + +### 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 +``` + +### my notes + +``` +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 +``` + +![alt text](image.png) \ No newline at end of file diff --git a/config/default.env b/config/default.env index 1673864..4f6085a 100644 --- a/config/default.env +++ b/config/default.env @@ -10,3 +10,7 @@ NUM_SECONDARYS=4 GLOBAL_MEM_LIMIT=4294967296 TASK_TYPES=noop,sleep,sum,fail,bigTable + +# for heartbeating +HEARTBEAT_MS=1000 +STALE_MS=5000 \ No newline at end of file diff --git a/image.png b/image.png new file mode 100644 index 0000000000000000000000000000000000000000..907595c3a78cd2d7fd63bf3241f31fce2c7e7759 GIT binary patch literal 66133 zcmeFZWmuG7+b=vrBPED*BT~}REvXWMDBaTC%^)D6w4i{}-61h_DWP;DLnAq)FayjG z`$GNS_r0HIf7tuWyWbCcj$@c(n7U%EbN%YP-aOGzA-X|x0|WvQJyccH27$1bKp+fC zJRIOZ$L^QhzysJrTjc?$Vu)@Fc!FgkuPzS)RmTyWn_~md@m*E*JwPA|w(C3iq4u2v z5a=rZp`yHwugT85lOyePEBj?--P`n^u}++JDR4dBZ2>cDEpd_@w?k7o!Y9Spm*D4j z{L>f8c71Nsmw7Z-5hdZEa#AFd#Ab-_bsodcJ}#5vQ0i-sA*ms9d`3eahJ{ECB)RA&{x6RVrC*Dr35=_AP;IOGj z_Qp4@&M`p#x&M{0!i0_T&FA0bBBIN>vaHiR!C{}@Hm>Nqys7lYg2SpcSpM9`gy};T ztDGn$K40OT?`mY_DnKrFH9TKjklgl{B zYql-%eMgcI%$Z+4k}u)U<{DPgOgdIR@jVDS+E2eV-AFyx3^wZ*TEGBxwDMWEBpTey zs^sH*vKUCZeJnorqsfN|*KO5c%hK)@bh`e+=Ca}N-Nu|_zPTC)^&PHUDs3IPXZ%Uu zR{HXM+7Qk+R0Q=2={a(Cc-}HeSJ4)wbz)BQs3Qsf4Aapti!b#y^^2m5o<2Ug&r2Jv z4?bDXj*NoO+ZTHy=&wc%u|N%wtt*VHBb$cymL1L?VKMuJIp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NaS`LW{qxz<HADCGn5EzrgCzV!npXQ|T zs{^FTH5ui9R3aSZ;|+3(biILL{CY^~D6Q|fovXY+XKihN%2@e#A;z7vU~b$%C*ebT z8B$#Fr~1H_GB&QBRmUWzbeIAxTt+z9NtxdrGY_`W;pMvi<5Go$sQ}aQrSLqo z;p($jL+^|hU|!>(n9l%1r~@QxZa2;f{;8au1uNvJh=FvLW36&tYYr*Tf|o(zQ5zz+}$TzkSXbG!ANTF7XLQg_~D zBy|V~CDy{<#k;Mc_fOXIimF^*vlbxDmSv*3;vpD5*$*(MsizPzDtZ6fm#{+J@Fl#w z&mXe|zJw=MfEXh!pXQETycErc`|U8~E~Hms{^OXfuGFYe_^y>_S;$=LFAUlDqaQC# zR(4#RDam_|q#R%|?>oHe!hD<1hzEUFZF@oj1NsOAebdR)b?B#9ai z8fDUrXI0NhHAlG8xNYY0ql^6rGQdt>O(+zV>pIE0J@003y}cqfCoAhjpGr8<2YxSf z&T}i?&*9!gQjhUkc$`{4@wvLrI@loO9NwawUg2I)_%3_rZ_vx9QS(pe<=+FnL{8_8 zC>GTTbq zJbLN%0Tri*O2c{q13l#Au#{BfDetv4_5L1d!aelvT$R+0vfKf2pRlBIZVKIj?Cglo z9uEBW%RotVgAiZx?NCutnwp*Ux_WaM<+X3qU?7m!bWQ^w?R8(Q-@G4Y{vGT?G8Fgq zNVxm4^*W;PX`}x4!F1AN>)O!3IzvX1KgU}S-2L%yR5kvYobQts{zn3%@&)u; zTef@#H933c(w|Vw|2h=oWk1{`z_9M!prhCId0&5=PFtzl{`UF~VvNKm;*H;F^?&$8 gvH$hj6FvbTt^fc4 literal 0 HcmV?d00001 diff --git a/schemas/primarytables.q b/schemas/primarytables.q index 392cfb6..5caed0c 100644 --- a/schemas/primarytables.q +++ b/schemas/primarytables.q @@ -6,32 +6,32 @@ secondaries : ([id: `long$()] pid: `int$(); host: `$(); port: `int$(); - status: `$(); // `idle`busy`stale`disconnected - lastHeartbeat: `timestamp$(); - lastMemBytes: `long$(); - consecutiveFails: `int$(); + status: `$(); // `free`busy`stale`closed + lastheartbeat: `timestamp$(); + lastmembytes: `long$(); + consecutivefails: `int$(); healthy: `boolean$(); spawned: `boolean$(); // if the master created it or it was up from before - startTime: `timestamp$(); - registeredTime: `timestamp$(); - taskTypes: (); - currentTask: `long$() + starttime: `timestamp$(); + registeredtime: `timestamp$(); + tasktypes: (); + currenttask: `long$() ); // montiro the tasks that are being carried out -tasks : ([taskId: `long$()] - taskType: `$(); +tasks : ([taskid: `long$()] + tasktype: `$(); args: (); priority: `int$(); - submittedTime: `timestamp$(); - timeoutMs: `long$(); - retriesMax: `int$(); - retryCount: `int$(); + submittedtime: `timestamp$(); + timeoutms: `long$(); + 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$(); err: (); reason: `$() // `timeout`unknown`oom ); \ 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..7a4b577 100644 --- a/src/primary.q +++ b/src/primary.q @@ -9,8 +9,51 @@ 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"; +// get env vars +.primary.stale:00:00:00.001*"J"$getenv`STALE_MS; +.primary.heartbeat:00:00:00.001*"J"$getenv`HEARTBEAT_MS; + + +// when a secondary starts add it to the secondaries table +// example run: +// .primary.register ([id:5; handle:0i; pid:4000i; host:`localhost; port:45001i ]) +.primary.register:{[info] + `secondaries upsert (info`id; .z.w; info`pid; info`host; info`port; `free; .z.P; 0N; 0Ni; 1b; 0b; .z.P; .z.P; (); 0N); + .log.info "secondary ", string[info`id], " registered at: ", string .z.P; + }; + +// to be called by each secondary except when its status is running, ran based off HEARTBEAT_MS +.primary.heartbeatcheck:{[mem] + update lastheartbeat:.z.P, lastmembytes: mem, status: `free from `secondaries where handle=.z.w; + }; + + +// 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)]; + }; + + +// ipc handlers that need editted + +// if a connection is close we need to mark it as closed +.z.pc:{[h] + secid: first exec id from secondaries where handle=h; + if[null secid; :()]; + update status:`closed, handle:0Ni from `secondaries where id=secid; + .log.info "secondary ",string[secid]," has closed its connection to the primary"; + }; + + +// start sequence .primary.start:{[] + .timer.addjob.custom[`stalecheck; {.primary.check[]}; (); 1; 2; ()!()]; .log.info "primary started, listening on ",string system "p"; }; diff --git a/src/secondary.q b/src/secondary.q index 9d6f57e..9bee029 100644 --- a/src/secondary.q +++ b/src/secondary.q @@ -6,14 +6,32 @@ // 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"; // 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; port: system"p"]); +// used to ocnnect and register with primary +.secondary.connect:{ + pri:`$"::",getenv `PRIMARY_PORT; + .log.info "trying to open a handle to primary process on: ",string pri; + sech:@[hopen; pri; {.log.error "the secondary has failed to connect to the primary, failed with error: ",x,". Will exit the process now"; exit 0}]; + sech + }; + +// send hb and mem updates to primary +.secondary.heartbeat:{ + neg[.secondary.handle](`.primary.heartbeatcheck; .Q.w[]`used); + }; + +// start sequence .secondary.start:{ + .secondary.handle:: .secondary.connect[]; + neg[.secondary.handle](`.primary.register; .secondary.info); + .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 From c6cd41b417a02d9733a6e2f735f3f644cb88b7f5 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Mon, 5 Oct 2026 16:09:13 +0100 Subject: [PATCH 02/49] bench-313: adding primary testing --- README.md | 22 +++- src/primary.q | 4 +- tests/LICENSE.qspec | 22 ++++ tests/LICENSE.qutil | 22 ++++ tests/bootstrap.q | 194 +++++++++++++++++++++++++++++++++ tests/qspec/fixture.q | 77 +++++++++++++ tests/qspec/init.q | 16 +++ tests/qspec/loader.q | 17 +++ tests/qspec/mock.q | 30 +++++ tests/qspec/output/junit.q | 84 ++++++++++++++ tests/qspec/output/text.q | 78 +++++++++++++ tests/qspec/output/xml.q | 36 ++++++ tests/qspec/output/xunit.q | 79 ++++++++++++++ tests/qspec/tests/assertions.q | 42 +++++++ tests/qspec/tests/expec.q | 68 ++++++++++++ tests/qspec/tests/fuzz.q | 51 +++++++++ tests/qspec/tests/internals.q | 19 ++++ tests/qspec/tests/spec.q | 15 +++ tests/qspec/tests/ui.q | 82 ++++++++++++++ tests/qutil/bootstrap.q | 194 +++++++++++++++++++++++++++++++++ tests/qutil/config_parse.q | 58 ++++++++++ tests/qutil/init.q | 2 + tests/qutil/opts.q | 192 ++++++++++++++++++++++++++++++++ tests/run.sh | 20 ++++ tests/runspecs.q | 10 ++ tests/spec.q | 85 +++++++++++++++ tests/unit/primary.q | 45 ++++++++ 27 files changed, 1561 insertions(+), 3 deletions(-) create mode 100644 tests/LICENSE.qspec create mode 100644 tests/LICENSE.qutil create mode 100644 tests/bootstrap.q create mode 100644 tests/qspec/fixture.q create mode 100644 tests/qspec/init.q create mode 100644 tests/qspec/loader.q create mode 100644 tests/qspec/mock.q create mode 100644 tests/qspec/output/junit.q create mode 100644 tests/qspec/output/text.q create mode 100644 tests/qspec/output/xml.q create mode 100644 tests/qspec/output/xunit.q create mode 100644 tests/qspec/tests/assertions.q create mode 100644 tests/qspec/tests/expec.q create mode 100644 tests/qspec/tests/fuzz.q create mode 100644 tests/qspec/tests/internals.q create mode 100644 tests/qspec/tests/spec.q create mode 100644 tests/qspec/tests/ui.q create mode 100644 tests/qutil/bootstrap.q create mode 100644 tests/qutil/config_parse.q create mode 100644 tests/qutil/init.q create mode 100644 tests/qutil/opts.q create mode 100755 tests/run.sh create mode 100644 tests/runspecs.q create mode 100644 tests/spec.q create mode 100644 tests/unit/primary.q diff --git a/README.md b/README.md index 1a9d7f1..60d2764 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,27 @@ bash bin/startsecondary.sh 1 bash bin/startsecondary.sh 2 ``` -### my notes +## Testing +We will use the qspec testing framework here, i have copied it into the project directly + +### how to run 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/primary.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$ +``` + +### my notes ignroe in any PR reviews till the end ``` jrutledge@homer:~/internalWork/Parallelisation-Project$ bash bin/startprimary.sh diff --git a/src/primary.q b/src/primary.q index 7a4b577..7ca08f2 100644 --- a/src/primary.q +++ b/src/primary.q @@ -18,7 +18,7 @@ system"l src/common/timer.q"; // when a secondary starts add it to the secondaries table // example run: -// .primary.register ([id:5; handle:0i; pid:4000i; host:`localhost; port:45001i ]) +// .primary.register ([id:5; pid:4000i; host:`localhost; port:45001i ]) .primary.register:{[info] `secondaries upsert (info`id; .z.w; info`pid; info`host; info`port; `free; .z.P; 0N; 0Ni; 1b; 0b; .z.P; .z.P; (); 0N); .log.info "secondary ", string[info`id], " registered at: ", string .z.P; @@ -35,7 +35,7 @@ system"l src/common/timer.q"; 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; + update status:`stale from `secondaries where id in stale; .log.warn "no heartbeat from secondary ",(", " sv string stale)]; }; 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/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..9cb04ff --- /dev/null +++ b/tests/run.sh @@ -0,0 +1,20 @@ +#!/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 +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]; + ]; diff --git a/tests/unit/primary.q b/tests/unit/primary.q new file mode 100644 index 0000000..6dc0e60 --- /dev/null +++ b/tests/unit/primary.q @@ -0,0 +1,45 @@ +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["can a secondary register with .primary.register"]{ + before{ + `.log.warn mock {}; + `.log.info mock {}; + .primary.register ([id:1; pid:4000i; host:`localhost; port:45001i ]); + update handle:6i from `secondaries where id = 1; // need to do as we run on handle 0 + }; + 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"]{ + 6i musteq first exec handle from secondaries; + }; + }; + +// should see the above now as stale +system"sleep 6" +.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; + }; + }; + +// can a secondary register +// update it with dummy mem data and check lastupdate is new +// discoonect and test .z.pc +// stale check \ No newline at end of file From 415f4ee16a9d3490199208b797eaa95d0532bdea Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Mon, 5 Oct 2026 17:01:21 +0100 Subject: [PATCH 03/49] bench-313: finished primary testing --- tests/unit/primary.q | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/tests/unit/primary.q b/tests/unit/primary.q index 6dc0e60..5a721c1 100644 --- a/tests/unit/primary.q +++ b/tests/unit/primary.q @@ -14,7 +14,6 @@ system"l src/primary.q"; `.log.warn mock {}; `.log.info mock {}; .primary.register ([id:1; pid:4000i; host:`localhost; port:45001i ]); - update handle:6i from `secondaries where id = 1; // need to do as we run on handle 0 }; should["have 1 secondary present"]{ 1 musteq count secondaries; @@ -23,12 +22,11 @@ system"l src/primary.q"; 1 musteq first exec id from secondaries; }; should["have handle be 6"]{ - 6i musteq first exec handle from secondaries; + 0i musteq first exec handle from secondaries; }; }; -// should see the above now as stale -system"sleep 6" +// should see the above now as stale, uses previous secondary .tst.desc[".primary.check will say the connection is stale"]{ before{ system"sleep 6"; @@ -39,7 +37,18 @@ system"sleep 6" }; }; -// can a secondary register + // update it with dummy mem data and check lastupdate is new -// discoonect and test .z.pc -// stale check \ No newline at end of file +.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 lastmembytes from secondaries where id = 1; + }; + }; + +// .z.pc in integration testing From 9cdecca2997fd21038bfa5be81ef2af13b86100b Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Tue, 6 Oct 2026 09:44:51 +0100 Subject: [PATCH 04/49] bench-313: added schema tests --- README.md | 6 ++++-- tests/unit/primary.q | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 60d2764..fa671e0 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,9 @@ For 1 specifications, 1 expectations were run. jrutledge@homer:~/internalWork/Parallelisation-Project$ ``` -### my notes ignroe in any PR reviews till the end + + +# my notes ignroe in any PR reviews till the end ``` jrutledge@homer:~/internalWork/Parallelisation-Project$ bash bin/startprimary.sh @@ -65,5 +67,5 @@ 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) \ No newline at end of file diff --git a/tests/unit/primary.q b/tests/unit/primary.q index 5a721c1..514f680 100644 --- a/tests/unit/primary.q +++ b/tests/unit/primary.q @@ -9,6 +9,20 @@ system"l src/primary.q"; }; }; +.tst.desc["check table schemas"]{ + should["return 2 tables"]{ + 2 musteq count tables[]; + }; + should["have the correct schema for secondaries table"]{ + (`id`handle`pid`host`port`status`lastheartbeat`lastmembytes`consecutivefails`healthy`spawned`starttime`registeredtime`tasktypes`currenttask) mustmatch cols secondaries; + "jiisispjibbpp j" mustmatch exec t from meta secondaries; + }; + should["have the correct schema for the tasks table"]{ + (`taskid`tasktype`args`priority`submittedtime`timeoutms`retriesmax`retrycount`state`secondaryid`dispatchedtime`startedtime`finishedtime`err`reason) mustmatch cols tasks; + "js ipjiisjppp s" mustmatch exec t from meta tasks; + }; + }; + .tst.desc["can a secondary register with .primary.register"]{ before{ `.log.warn mock {}; @@ -52,3 +66,4 @@ system"l src/primary.q"; }; // .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 From af247b91920f0bb3226e5cd82dde4cdeef4ab825 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Tue, 6 Oct 2026 12:15:31 +0100 Subject: [PATCH 05/49] bench-313: spell fix and renaming primary tests file --- src/secondary.q | 2 +- tests/unit/{primary.q => primarytests.q} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename tests/unit/{primary.q => primarytests.q} (100%) diff --git a/src/secondary.q b/src/secondary.q index 9bee029..6fd5528 100644 --- a/src/secondary.q +++ b/src/secondary.q @@ -13,7 +13,7 @@ system"l src/common/timer.q"; .secondary.id: "J"$first .secondary.opts`id; .secondary.info:([id: .secondary.id; pid: .z.i; host: .z.h; port: system"p"]); -// used to ocnnect and register with primary +// 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; diff --git a/tests/unit/primary.q b/tests/unit/primarytests.q similarity index 100% rename from tests/unit/primary.q rename to tests/unit/primarytests.q From 3f497795bdb19674878302d1aa2a0c46dad95eac Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Tue, 6 Oct 2026 12:17:14 +0100 Subject: [PATCH 06/49] bench-313: style fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fa671e0..4d56f7c 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ bash bin/startprimary.sh ``` ### Secondaries -These will either be ran as part of the intial start up or the primary will spin up more as needed. They will take the port number `PRIMARY_PORT` + `id` so `secondary 1 `would have a port of `45001` and so on. +These will either be ran as part of the intial start up or the primary will spin up more as needed. They will take the port number `PRIMARY_PORT` + `id` so `secondary 1` would have a port of `45001` and so on. ### how to start To bring up 2 secondaries run the below From 57990871d0d5626f5200be061bca444e5f8cf0eb Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Tue, 6 Oct 2026 12:20:19 +0100 Subject: [PATCH 07/49] branch-313: readme file name fix in testing section --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4d56f7c..cafb838 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ We will use the qspec testing framework here, i have copied it into the project 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/primary.q # one file +tests/run.sh tests/unit/primarytests.q # one file ``` Example run From 30dfdda1f3b144fd5b43fb31b8a66c06d1df087f Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Wed, 7 Oct 2026 14:15:48 +0100 Subject: [PATCH 08/49] bench-311: primary can now start up secondaries --- README.md | 47 ++++++++++++++++- config/default.env | 9 +++- config/integration.env | 9 ++++ schemas/primarytables.q | 2 +- src/common/os.q | 1 + src/primary.q | 72 ++++++++++++++++++++++++- src/secondary.q | 19 ++++++- tests/helpers/it.q | 45 ++++++++++++++++ tests/integration.sh | 76 +++++++++++++++++++++++++++ tests/integration/disconnect_spec.q | 16 ++++++ tests/integration/primaryloss_spec.q | 14 +++++ tests/integration/registration_spec.q | 24 +++++++++ tests/integration/spawn_spec.q | 20 +++++++ tests/integration/stale_spec.q | 17 ++++++ tests/integration/stop_spec.q | 16 ++++++ tests/run.sh | 1 + 16 files changed, 379 insertions(+), 9 deletions(-) create mode 100644 config/integration.env create mode 100644 src/common/os.q create mode 100644 tests/helpers/it.q create mode 100755 tests/integration.sh create mode 100644 tests/integration/disconnect_spec.q create mode 100644 tests/integration/primaryloss_spec.q create mode 100644 tests/integration/registration_spec.q create mode 100644 tests/integration/spawn_spec.q create mode 100644 tests/integration/stale_spec.q create mode 100644 tests/integration/stop_spec.q diff --git a/README.md b/README.md index cafb838..f9a1f2b 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # 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 @@ -12,6 +12,11 @@ cd /home/jrutledge/internalWork/Parallelisation-Project bash bin/startprimary.sh ``` +### 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 take the port number `PRIMARY_PORT` + `id` so `secondary 1` would have a port of `45001` and so on. @@ -26,7 +31,7 @@ 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 tests +### 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 @@ -43,6 +48,44 @@ For 1 specifications, 1 expectations were run. jrutledge@homer:~/internalWork/Parallelisation-Project$ ``` +### how to run integration tests +From project top level dir run the below commands +```bash +bash tests/integration.sh +``` +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$ +``` + +## 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 diff --git a/config/default.env b/config/default.env index 4f6085a..8fe6e3a 100644 --- a/config/default.env +++ b/config/default.env @@ -4,7 +4,6 @@ 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 @@ -13,4 +12,10 @@ TASK_TYPES=noop,sleep,sum,fail,bigTable # for heartbeating HEARTBEAT_MS=1000 -STALE_MS=5000 \ No newline at end of file +STALE_MS=5000 + +# for spinning up secondarys via the primary +SPAWN_SECONDARY=1 +NUM_SECONDARYS=4 +STOP_GRACE_PERIOD_SECS=5 +LOG_DIR=logs \ No newline at end of file diff --git a/config/integration.env b/config/integration.env new file mode 100644 index 0000000..96977e7 --- /dev/null +++ b/config/integration.env @@ -0,0 +1,9 @@ +# 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 +SECONDARY_BASE_PORT=46001 +NUM_SECONDARYS=2 +SPAWN_SECONDARY=1 +STOP_GRACE_PERIOD_SECS=1 +STALE_MS=3000 +LOG_DIR=logs/integration diff --git a/schemas/primarytables.q b/schemas/primarytables.q index 5caed0c..8dc0b46 100644 --- a/schemas/primarytables.q +++ b/schemas/primarytables.q @@ -18,7 +18,7 @@ secondaries : ([id: `long$()] currenttask: `long$() ); -// montiro the tasks that are being carried out +// monitor the tasks that are being carried out tasks : ([taskid: `long$()] tasktype: `$(); args: (); 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/primary.q b/src/primary.q index 7ca08f2..846c5a0 100644 --- a/src/primary.q +++ b/src/primary.q @@ -10,17 +10,28 @@ system"l schemas/primarytables.q"; // 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"; // 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.baseport:"J"$getenv`SECONDARY_BASE_PORT; +.primary.stopgraceperiod:"J"$getenv`STOP_GRACE_PERIOD_SECS; +.primary.logdir:getenv`LOG_DIR; +.primary.qbin:getenv[`KDBX_HOME],"/bin/q"; + + +// dict of secondaries ids to their pids that the primary started +.primary.spawned:(`long$())!`int$(); // when a secondary starts add it to the secondaries table // example run: // .primary.register ([id:5; pid:4000i; host:`localhost; port:45001i ]) .primary.register:{[info] - `secondaries upsert (info`id; .z.w; info`pid; info`host; info`port; `free; .z.P; 0N; 0Ni; 1b; 0b; .z.P; .z.P; (); 0N); + `secondaries upsert (info`id; .z.w; info`pid; info`host; info`port; `free; .z.P; 0N; 0Ni; 1b; info[`id] in key .primary.spawned; .z.P; .z.P; (); 0N); .log.info "secondary ", string[info`id], " registered at: ", string .z.P; }; @@ -29,7 +40,6 @@ system"l src/common/timer.q"; update lastheartbeat:.z.P, lastmembytes: mem, status: `free from `secondaries where handle=.z.w; }; - // mark secondaries that arent sedning updates as stale .primary.check:{ if[not count secondaries; :()]; @@ -40,6 +50,61 @@ system"l src/common/timer.q"; }; + +// the one OS call di.os doesn't cover: start q in the background and get its pid +// a wrapper so unit specs can mock it (system can't be mocked) +// .primary.run:{[cmd] system cmd}; use in unit testing +.primary.send:{[h;msg] neg[h] msg; neg[h][]}; + +// command line for secondary n, e.g. /opt/kdbx/.../q src/secondary.q -p 45002 -id 2 +// look at wrapping in protected execution +.primary.spawncmd:{[n] + " " sv (.primary.qbin; "src/secondary.q"; "-p"; string .primary.baseport+n-1; "-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],") on port ",string .primary.baseport+n-1; + }; + +// 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] @[.primary.send[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"; + }; + + + // ipc handlers that need editted // if a connection is close we need to mark it as closed @@ -50,9 +115,12 @@ system"l src/common/timer.q"; .log.info "secondary ",string[secid]," has closed its connection to the primary"; }; +// quitting the primary kills any spawned secondaries +.z.exit:{if[count .primary.spawned; .primary.stop[]]}; // start sequence .primary.start:{[] + if[.primary.spawnsecondaries; .primary.spawn each 1+til .primary.numsecondaries]; .timer.addjob.custom[`stalecheck; {.primary.check[]}; (); 1; 2; ()!()]; .log.info "primary started, listening on ",string system "p"; }; diff --git a/src/secondary.q b/src/secondary.q index 6fd5528..4d10c80 100644 --- a/src/secondary.q +++ b/src/secondary.q @@ -7,6 +7,8 @@ // 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"; + // get the id form start cmd .secondary.opts: .Q.opt .z.x; @@ -17,8 +19,8 @@ system"l src/common/timer.q"; .secondary.connect:{ pri:`$"::",getenv `PRIMARY_PORT; .log.info "trying to open a handle to primary process on: ",string pri; - sech:@[hopen; pri; {.log.error "the secondary has failed to connect to the primary, failed with error: ",x,". Will exit the process now"; exit 0}]; - sech + 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 }; // send hb and mem updates to primary @@ -26,6 +28,19 @@ system"l src/common/timer.q"; neg[.secondary.handle](`.primary.heartbeatcheck; .Q.w[]`used); }; +// 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; + }; + // start sequence .secondary.start:{ .secondary.handle:: .secondary.connect[]; 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..b413f38 --- /dev/null +++ b/tests/integration.sh @@ -0,0 +1,76 @@ +#!/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 primary and any secondary on the test ports (46001 -> "4600", so 46000-46009 only) +stopall() { + if [[ -n "$PRIMARYPID" ]]; then kill -9 "$PRIMARYPID" 2>/dev/null || true; fi + pkill -9 -f "src/secondary.q -p ${SECONDARY_BASE_PORT%?}" 2>/dev/null || true + 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 ports +portsfree() { + local p + for p in $(seq "$PRIMARY_PORT" $((SECONDARY_BASE_PORT + NUM_SECONDARYS + 1))); do + if (exec 3<>"/dev/tcp/localhost/$p") 2>/dev/null; then + echo "port $p is already in use; kill whatever is on it (ss -ltnp | grep $p) and rerun" >&2 + return 1 + fi + done +} + +# 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 ports free up before the next cluster +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 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/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..6c685c5 --- /dev/null +++ b/tests/integration/registration_spec.q @@ -0,0 +1,24 @@ +// 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 and port"]{ + 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; + (exec port from t) mustmatch `int$("J"$getenv`SECONDARY_BASE_PORT)+(exec id from t)-1; + }; + 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/spawn_spec.q b/tests/integration/spawn_spec.q new file mode 100644 index 0000000..ee6f6f3 --- /dev/null +++ b/tests/integration/spawn_spec.q @@ -0,0 +1,20 @@ +// 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]; + }; + }; \ No newline at end of file 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/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/run.sh b/tests/run.sh index 9cb04ff..1377e98 100755 --- a/tests/run.sh +++ b/tests/run.sh @@ -12,6 +12,7 @@ fi set -a source config/default.env +if [[ -n "${EXTRA_ENV:-}" ]]; then source "$EXTRA_ENV"; fi set +a export QHOME="$KDBX_HOME" From a0da46df3c9130a8fc76387146f00baa431ceefe Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Wed, 7 Oct 2026 18:03:15 +0100 Subject: [PATCH 09/49] bench-344: adding primary status functions --- README.md | 6 ++++++ src/primary.q | 28 ++++++++++++++++++++++++++-- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f9a1f2b..1de6366 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,12 @@ 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** diff --git a/src/primary.q b/src/primary.q index 846c5a0..a0f6674 100644 --- a/src/primary.q +++ b/src/primary.q @@ -21,7 +21,9 @@ system"l src/common/os.q"; .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; // dict of secondaries ids to their pids that the primary started .primary.spawned:(`long$())!`int$(); @@ -51,6 +53,27 @@ system"l src/common/os.q"; + +// 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 +.primary.status:{ + secs:select id, pid, port, status, spawned, lastseen:`time$.z.P-lastheartbeat,lastmembytes from 0!secondaries; + ([time: .z.P; uptime: .z.P-.primary.starttime; 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]," =="; + -1 "secondaries: ",fmt pristatus`seccounts; + show pristatus`secondaries; + -1 "tasks: ",fmt pristatus`taskcounts; + }; + + // the one OS call di.os doesn't cover: start q in the background and get its pid // a wrapper so unit specs can mock it (system can't be mocked) // .primary.run:{[cmd] system cmd}; use in unit testing @@ -123,7 +146,8 @@ system"l src/common/os.q"; if[.primary.spawnsecondaries; .primary.spawn each 1+til .primary.numsecondaries]; .timer.addjob.custom[`stalecheck; {.primary.check[]}; (); 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 From 46fa7dd2b7eb23e26a44f12ec19e203942b6dc68 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Thu, 8 Oct 2026 12:51:24 +0100 Subject: [PATCH 10/49] bench-344: adding status testing --- src/primary.q | 2 +- tests/integration/status_spec.q | 28 +++++++++++ tests/spec.q | 2 +- tests/unit/status_spec.q | 88 +++++++++++++++++++++++++++++++++ 4 files changed, 118 insertions(+), 2 deletions(-) create mode 100644 tests/integration/status_spec.q create mode 100644 tests/unit/status_spec.q diff --git a/src/primary.q b/src/primary.q index a0f6674..3042450 100644 --- a/src/primary.q +++ b/src/primary.q @@ -21,7 +21,7 @@ system"l src/common/os.q"; .primary.stopgraceperiod:"J"$getenv`STOP_GRACE_PERIOD_SECS; .primary.logdir:getenv`LOG_DIR; .primary.qbin:getenv[`KDBX_HOME],"/bin/q"; - .primary.starttime:0Np; +.primary.starttime:0Np; .primary.secondarystates:`free`busy`stale`closed; .primary.taskstates:`queued`dispatched`running`done`failed; 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/spec.q b/tests/spec.q index 0bbd504..402aa4f 100644 --- a/tests/spec.q +++ b/tests/spec.q @@ -82,4 +82,4 @@ if[not .tst.halt; ]; if[app.exit; exit `int$not app.passed]; - ]; + ]; \ 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..d3f83c8 --- /dev/null +++ b/tests/unit/status_spec.q @@ -0,0 +1,88 @@ +/ 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`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`port`status`spawned`lastseen`lastmembytes 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; + }; + }; \ No newline at end of file From 7409d5739905cedadd15d31735a02a294a08d0a0 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Thu, 8 Oct 2026 16:59:27 +0100 Subject: [PATCH 11/49] bench-311: updating secondaries oom_score --- README.md | 7 +++++-- src/secondary.q | 9 +++++++++ tests/integration/oomscore_spec.q | 10 ++++++++++ tests/integration/spawn_spec.q | 3 ++- 4 files changed, 26 insertions(+), 3 deletions(-) create mode 100644 tests/integration/oomscore_spec.q diff --git a/README.md b/README.md index 1de6366..2656903 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,9 @@ x src/primary.q -p 45000 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 take the port number `PRIMARY_PORT` + `id` so `secondary 1` would have a port of `45001` and so on. +These will either be ran as part of the intial start up or the primary will spin up more as needed. They will take the port number `PRIMARY_PORT` + `id` so `secondary 1` would have a port of `45001` and so on. 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 @@ -57,7 +59,8 @@ jrutledge@homer:~/internalWork/Parallelisation-Project$ ### how to run integration tests From project top level dir run the below commands ```bash -bash tests/integration.sh +bash tests/integration.sh oomscore # run just the oomscore_spec.q test +bash tests/integration.sh # run all integration tests ``` Example output ```bash diff --git a/src/secondary.q b/src/secondary.q index 4d10c80..771a50d 100644 --- a/src/secondary.q +++ b/src/secondary.q @@ -41,8 +41,17 @@ system"l src/common/os.q"; 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]; + }; + // start sequence .secondary.start:{ + .secondary.oomscore[]; .secondary.handle:: .secondary.connect[]; neg[.secondary.handle](`.primary.register; .secondary.info); .timer.addjob.custom[`heartbeat; {.secondary.heartbeat[]}; (); 1; 2; ()!()]; 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/spawn_spec.q b/tests/integration/spawn_spec.q index ee6f6f3..c7da39a 100644 --- a/tests/integration/spawn_spec.q +++ b/tests/integration/spawn_spec.q @@ -17,4 +17,5 @@ system "l tests/helpers/it.q"; .it.q ".primary.spawn 3"; 1b musteq .it.waitfor[{`free~.it.status 3};10]; }; - }; \ No newline at end of file + }; + From 517eb68d4736d313358bb3f78a0044a526e4a99a Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Fri, 9 Oct 2026 11:39:21 +0100 Subject: [PATCH 12/49] bench-314: added task id function and testing --- config/default.env | 6 +++++- schemas/primarytables.q | 12 ++++++++---- src/primary.q | 19 ++++++++++++++----- tests/unit/primarytests.q | 4 ++-- tests/unit/tasks_spec.q | 17 +++++++++++++++++ 5 files changed, 46 insertions(+), 12 deletions(-) create mode 100644 tests/unit/tasks_spec.q diff --git a/config/default.env b/config/default.env index 8fe6e3a..efbcc70 100644 --- a/config/default.env +++ b/config/default.env @@ -18,4 +18,8 @@ STALE_MS=5000 SPAWN_SECONDARY=1 NUM_SECONDARYS=4 STOP_GRACE_PERIOD_SECS=5 -LOG_DIR=logs \ No newline at end of file +LOG_DIR=logs + +# for tasks, 1hr max time and 3 retries +TASK_TIMEOUT_MS=60000 +TASK_RETRIES_MAX=3 \ No newline at end of file diff --git a/schemas/primarytables.q b/schemas/primarytables.q index 8dc0b46..5f40745 100644 --- a/schemas/primarytables.q +++ b/schemas/primarytables.q @@ -1,4 +1,4 @@ -// tables for the master process +// tables for the primary process // monitor the secondary procs secondaries : ([id: `long$()] @@ -11,7 +11,7 @@ secondaries : ([id: `long$()] lastmembytes: `long$(); consecutivefails: `int$(); healthy: `boolean$(); - spawned: `boolean$(); // if the master created it or it was up from before + spawned: `boolean$(); // if the primary created it or it was up from before starttime: `timestamp$(); registeredtime: `timestamp$(); tasktypes: (); @@ -24,7 +24,8 @@ tasks : ([taskid: `long$()] args: (); priority: `int$(); submittedtime: `timestamp$(); - timeoutms: `long$(); + memestimate: `long$(); + timeout: `time$(); retriesmax: `int$(); retrycount: `int$(); state: `$(); // `queued`dispatched`running`done`failed @@ -32,6 +33,9 @@ tasks : ([taskid: `long$()] dispatchedtime: `timestamp$(); startedtime: `timestamp$(); finishedtime: `timestamp$(); + membefore: `long$(); + memafter: `long$(); err: (); - reason: `$() // `timeout`unknown`oom + reason: `$(); // `timeout`unknown`oom + result: () ); \ No newline at end of file diff --git a/src/primary.q b/src/primary.q index 3042450..23afc96 100644 --- a/src/primary.q +++ b/src/primary.q @@ -24,10 +24,19 @@ system"l src/common/os.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.lasttaskid:0; + + // dict of secondaries ids to their pids that the primary started .primary.spawned:(`long$())!`int$(); +// defaults for the optional task fields, enqueue fills any missing field from here +.primary.taskdefaults:([priority:0i; memestimate: 0N; timeout: .primary.tasktimeout; retriesmax: .primary.taskretries]); + + // when a secondary starts add it to the secondaries table // example run: @@ -52,8 +61,6 @@ system"l src/common/os.q"; }; - - // 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}; @@ -126,9 +133,11 @@ system"l src/common/os.q"; .log.info "stopped"; }; - - -// ipc handlers that need editted +// tasks will only ever go up +.primary.nexttaskid:{ + .primary.lasttaskid+::1; + .primary.lasttaskid + }; // if a connection is close we need to mark it as closed .z.pc:{[h] diff --git a/tests/unit/primarytests.q b/tests/unit/primarytests.q index 514f680..f7abeef 100644 --- a/tests/unit/primarytests.q +++ b/tests/unit/primarytests.q @@ -18,8 +18,8 @@ system"l src/primary.q"; "jiisispjibbpp j" mustmatch exec t from meta secondaries; }; should["have the correct schema for the tasks table"]{ - (`taskid`tasktype`args`priority`submittedtime`timeoutms`retriesmax`retrycount`state`secondaryid`dispatchedtime`startedtime`finishedtime`err`reason) mustmatch cols tasks; - "js ipjiisjppp s" mustmatch exec t from meta tasks; + (`taskid`tasktype`args`priority`submittedtime`memestimate`timeout`retriesmax`retrycount`state`secondaryid`dispatchedtime`startedtime`finishedtime`membefore`memafter`err`reason`result) mustmatch cols tasks; + "js ipjtiisjpppjj s " mustmatch exec t from meta tasks; }; }; diff --git a/tests/unit/tasks_spec.q b/tests/unit/tasks_spec.q new file mode 100644 index 0000000..3cce2ed --- /dev/null +++ b/tests/unit/tasks_spec.q @@ -0,0 +1,17 @@ +/ 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] ::}; + }; + should["start at 1 and go up by one"]{ + 0 musteq .primary.lasttaskid; + 1 musteq .primary.nexttaskid[]; + 1 musteq .primary.lasttaskid; + }; + }; From 430642a6e1ace4ab7f1dae22d3b0c4a8d2bc43e0 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Tue, 13 Oct 2026 09:28:52 +0100 Subject: [PATCH 13/49] bench-314: task update functionality --- src/primary.q | 32 ++++++++++ tests/unit/taskupdate_spec.q | 115 +++++++++++++++++++++++++++++++++++ 2 files changed, 147 insertions(+) create mode 100644 tests/unit/taskupdate_spec.q diff --git a/src/primary.q b/src/primary.q index 23afc96..9250100 100644 --- a/src/primary.q +++ b/src/primary.q @@ -36,6 +36,13 @@ system"l src/common/os.q"; // defaults for the optional task fields, enqueue 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: enlist `dispatched; 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]); + + // when a secondary starts add it to the secondaries table @@ -139,6 +146,31 @@ system"l src/common/os.q"; .primary.lasttaskid }; +// 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] + // check the tasks exists and not completed or failed more than max retires + 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]; + // if[ all `retrycount`retriesmax in key params; + // params[retry] + // ]; + 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 on of the following: ",", " sv string .primary.taskchange oldstate; + :0b]; + // need to update the correct time column depending on the status it is updated too + timecol: (enlist .primary.statustime newstate)!enlist .z.P; + timecol: $[newstate in key .primary.statustime; (enlist .primary.statustime newstate)!enlist .z.P; ()!()]; + params: params, timecol, ([taskid: tid; state: newstate]); + .log.info "updating task id ",string[tid]," from ",string[oldstate]," to ",string newstate; + upsert[`tasks; params]; + .log.info "updated task id ",string[tid]," from ",string[oldstate]," to ",string newstate; + 1b + }; + // if a connection is close we need to mark it as closed .z.pc:{[h] secid: first exec id from secondaries where handle=h; diff --git a/tests/unit/taskupdate_spec.q b/tests/unit/taskupdate_spec.q new file mode 100644 index 0000000..0fa1081 --- /dev/null +++ b/tests/unit/taskupdate_spec.q @@ -0,0 +1,115 @@ +/ unit specs for .primary.taskupdate, the only way a task changes state +/ callers are internal, so argument types are not checked; callers box result with enlist +/ 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`result! + (.ut.tuid;`noop;enlist 1;0i;.z.P;0N;00:01:00.000;3i;0i;s;0N;0Np;0Np;0Np;0N;0N;"";`;enlist (::)) + }; + +/ 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`result!(1000;800;enlist 42)]; + r:.ut.tuget[]; + `done musteq r`state; + 1b musteq not null r`finishedtime; + 42 musteq first r`result; + 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; + }; + }; From 17d6e9a303778240c03021ae14923200e78efe01 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Tue, 13 Oct 2026 10:43:53 +0100 Subject: [PATCH 14/49] bench-314: task update functionality, style fix --- src/primary.q | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/primary.q b/src/primary.q index 9250100..e005cd2 100644 --- a/src/primary.q +++ b/src/primary.q @@ -146,23 +146,24 @@ system"l src/common/os.q"; .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] + // check essential cols are defined + }; + // 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] - // check the tasks exists and not completed or failed more than max retires 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]; - // if[ all `retrycount`retriesmax in key params; - // params[retry] - // ]; 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 on of the following: ",", " sv string .primary.taskchange oldstate; :0b]; - // need to update the correct time column depending on the status it is updated too - timecol: (enlist .primary.statustime newstate)!enlist .z.P; timecol: $[newstate in key .primary.statustime; (enlist .primary.statustime newstate)!enlist .z.P; ()!()]; params: params, timecol, ([taskid: tid; state: newstate]); .log.info "updating task id ",string[tid]," from ",string[oldstate]," to ",string newstate; From 2345a9ec100d744df5028c767c50ddcb5caa4055 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Tue, 13 Oct 2026 13:18:53 +0100 Subject: [PATCH 15/49] bench-314: adding .primary.newtask and testing --- config/default.env | 5 +- src/primary.q | 18 +++++- tests/unit/newtask_spec.q | 114 ++++++++++++++++++++++++++++++++++++++ tests/unit/primarytests.q | 4 +- tests/unit/tasks_spec.q | 1 + 5 files changed, 138 insertions(+), 4 deletions(-) create mode 100644 tests/unit/newtask_spec.q diff --git a/config/default.env b/config/default.env index efbcc70..ecd7f82 100644 --- a/config/default.env +++ b/config/default.env @@ -20,6 +20,7 @@ NUM_SECONDARYS=4 STOP_GRACE_PERIOD_SECS=5 LOG_DIR=logs -# for tasks, 1hr max time and 3 retries +# for tasks TASK_TIMEOUT_MS=60000 -TASK_RETRIES_MAX=3 \ No newline at end of file +TASK_RETRIES_MAX=3 +TASK_TYPES=sleep,sum,fail \ No newline at end of file diff --git a/src/primary.q b/src/primary.q index e005cd2..b1f4c12 100644 --- a/src/primary.q +++ b/src/primary.q @@ -26,6 +26,7 @@ system"l src/common/os.q"; .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; @@ -150,12 +151,27 @@ system"l src/common/os.q"; // 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] - // check essential cols are defined + 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; err:""; reason:`; result:enlist (::)]); + `tasks upsert data; + .log.info "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 +// remove the if statements after we get this working as users should only call .primary.newtask this should be automated .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"; diff --git a/tests/unit/newtask_spec.q b/tests/unit/newtask_spec.q new file mode 100644 index 0000000..621447d --- /dev/null +++ b/tests/unit/newtask_spec.q @@ -0,0 +1,114 @@ +/ 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 (::)~first tasks[id]`result; + }; + 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/primarytests.q b/tests/unit/primarytests.q index f7abeef..60b3cb6 100644 --- a/tests/unit/primarytests.q +++ b/tests/unit/primarytests.q @@ -1,4 +1,5 @@ -system"l src/primary.q"; +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"]{ @@ -12,6 +13,7 @@ system"l src/primary.q"; .tst.desc["check table schemas"]{ should["return 2 tables"]{ 2 musteq count tables[]; + system "l schemas/primarytables.q"; }; should["have the correct schema for secondaries table"]{ (`id`handle`pid`host`port`status`lastheartbeat`lastmembytes`consecutivefails`healthy`spawned`starttime`registeredtime`tasktypes`currenttask) mustmatch cols secondaries; diff --git a/tests/unit/tasks_spec.q b/tests/unit/tasks_spec.q index 3cce2ed..aaec923 100644 --- a/tests/unit/tasks_spec.q +++ b/tests/unit/tasks_spec.q @@ -8,6 +8,7 @@ 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; From 39d7ffac48e09ba2a695d2bd953817fbcf371a94 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Tue, 13 Oct 2026 13:48:31 +0100 Subject: [PATCH 16/49] bench-323: approved functions to be run on secondaries --- src/approvedfunctions.q | 15 +++++++++++++++ src/secondary.q | 1 + 2 files changed, 16 insertions(+) create mode 100644 src/approvedfunctions.q diff --git a/src/approvedfunctions.q b/src/approvedfunctions.q new file mode 100644 index 0000000..941f24d --- /dev/null +++ b/src/approvedfunctions.q @@ -0,0 +1,15 @@ +// 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 + +.secondary.approvedtasks:()!(); + +// these are the test tasks before we define ones that would actually be useful + +.task.sum:{sum x}; +.secondary.approvedtasks[`sum]:.task.sum; + +.task.sleep:{system"sleep ",string x}; +.secondary.approvedtasks[`sleep]:.task.sleep; + +.task.fail:{`fail}; +.secondary.approvedtasks[`fail]:.task.fail; \ No newline at end of file diff --git a/src/secondary.q b/src/secondary.q index 771a50d..fa4f5f6 100644 --- a/src/secondary.q +++ b/src/secondary.q @@ -8,6 +8,7 @@ system"l src/common/log.q"; system"l src/common/timer.q"; system"l src/common/os.q"; +system"l src/approvedfunctions.q"; // get the id form start cmd From e3db8c7c38b9dea9513c375d58d1a45c6a019fb3 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Thu, 15 Oct 2026 16:58:17 +0100 Subject: [PATCH 17/49] bench-324: adding functions to run queued tasks --- config/default.env | 2 +- src/{approvedfunctions.q => approvedtasks.q} | 7 +- src/primary.q | 4 +- src/secondary.q | 22 ++++++- tests/integration/runtask_spec.q | 67 ++++++++++++++++++++ 5 files changed, 96 insertions(+), 6 deletions(-) rename src/{approvedfunctions.q => approvedtasks.q} (70%) create mode 100644 tests/integration/runtask_spec.q diff --git a/config/default.env b/config/default.env index ecd7f82..829ffad 100644 --- a/config/default.env +++ b/config/default.env @@ -23,4 +23,4 @@ LOG_DIR=logs # for tasks TASK_TIMEOUT_MS=60000 TASK_RETRIES_MAX=3 -TASK_TYPES=sleep,sum,fail \ No newline at end of file +TASK_TYPES=sleep,sumtil,fail \ No newline at end of file diff --git a/src/approvedfunctions.q b/src/approvedtasks.q similarity index 70% rename from src/approvedfunctions.q rename to src/approvedtasks.q index 941f24d..c7bab10 100644 --- a/src/approvedfunctions.q +++ b/src/approvedtasks.q @@ -1,15 +1,16 @@ // 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.sum:{sum x}; -.secondary.approvedtasks[`sum]:.task.sum; +.task.sumtil:{sum til x}; +.secondary.approvedtasks[`sumtil]:.task.sumtil; .task.sleep:{system"sleep ",string x}; .secondary.approvedtasks[`sleep]:.task.sleep; -.task.fail:{`fail}; +.task.fail:{'`fail}; .secondary.approvedtasks[`fail]:.task.fail; \ No newline at end of file diff --git a/src/primary.q b/src/primary.q index b1f4c12..4e4a27e 100644 --- a/src/primary.q +++ b/src/primary.q @@ -171,7 +171,6 @@ system"l src/common/os.q"; // 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 -// remove the if statements after we get this working as users should only call .primary.newtask this should be automated .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"; @@ -185,6 +184,9 @@ system"l src/common/os.q"; .log.info "updating task id ",string[tid]," from ",string[oldstate]," to ",string 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]; 1b }; diff --git a/src/secondary.q b/src/secondary.q index fa4f5f6..d767e3a 100644 --- a/src/secondary.q +++ b/src/secondary.q @@ -8,7 +8,7 @@ system"l src/common/log.q"; system"l src/common/timer.q"; system"l src/common/os.q"; -system"l src/approvedfunctions.q"; +system"l src/approvedtasks.q"; // get the id form start cmd @@ -50,6 +50,26 @@ system"l src/approvedfunctions.q"; $[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][]}; + +// sec tells pri it is starting, record mem before, run task, record mem after result, .Q.gc[], send result +.secondary.runtask:{[tid; tasktype; args] + .secondary.send (`.primary.taskupdate; tid; `running; ()!()); + membefore:.Q.w[]`heap; // went with heap here as it might not register if its a small task on used + 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`reason`membefore`memafter!("unknown tasktype: ",string tasktype; `error; membefore; membefore))]; + res:@[{.secondary.approvedtasks[x] y}[tasktype;]; args; {[error] (`failure; error)}]; + memafter:.Q.w[]`heap; + .Q.gc[]; + if[`failure ~ first res; + .log.warn "task ",string[tid],", failed with error: ",last res; + :.secondary.send (`.primary.taskupdate; tid; `failed; `err`reason`membefore`memafter!(last res; `error; membefore; memafter))]; + .log.info "task ",string[tid]," is complete"; + .secondary.send (`.primary.taskupdate; tid; `done; `result`membefore`memafter!(enlist res; membefore; memafter)); + }; + // start sequence .secondary.start:{ .secondary.oomscore[]; diff --git a/tests/integration/runtask_spec.q b/tests/integration/runtask_spec.q new file mode 100644 index 0000000..6b1f195 --- /dev/null +++ b/tests/integration/runtask_spec.q @@ -0,0 +1,67 @@ +/ 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 first t`result; + 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]; + }; + }; \ No newline at end of file From 0d2acef1f0de1741a38005b215689751ef0a1e28 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Fri, 16 Oct 2026 16:44:35 +0100 Subject: [PATCH 18/49] bench-324: function to run queued tasks --- src/primary.q | 48 ++++++++--- tests/unit/dispatch_spec.q | 161 +++++++++++++++++++++++++++++++++++++ 2 files changed, 198 insertions(+), 11 deletions(-) create mode 100644 tests/unit/dispatch_spec.q diff --git a/src/primary.q b/src/primary.q index 4e4a27e..4d7ec6e 100644 --- a/src/primary.q +++ b/src/primary.q @@ -34,7 +34,7 @@ system"l src/common/os.q"; // dict of secondaries ids to their pids that the primary started .primary.spawned:(`long$())!`int$(); -// defaults for the optional task fields, enqueue fills any missing field from here +// 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 @@ -88,12 +88,6 @@ system"l src/common/os.q"; -1 "tasks: ",fmt pristatus`taskcounts; }; - -// the one OS call di.os doesn't cover: start q in the background and get its pid -// a wrapper so unit specs can mock it (system can't be mocked) -// .primary.run:{[cmd] system cmd}; use in unit testing -.primary.send:{[h;msg] neg[h] msg; neg[h][]}; - // command line for secondary n, e.g. /opt/kdbx/.../q src/secondary.q -p 45002 -id 2 // look at wrapping in protected execution .primary.spawncmd:{[n] @@ -131,7 +125,7 @@ system"l src/common/os.q"; .primary.stop:{ .log.info "stopping secondaries"; handles:exec handle from secondaries where not null handle, not status=`closed; - {[h] @[.primary.send[h;];(`.secondary.stop;::);{[e] ::}]} each handles; /// no stop sec func on sec.q script + {[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; @@ -177,7 +171,7 @@ system"l src/common/os.q"; :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 on of the following: ",", " sv string .primary.taskchange oldstate; + .log.warn"the new task state ",string[newstate]," is not a valid option choose on 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]); @@ -190,6 +184,37 @@ system"l src/common/os.q"; 1b }; +// sends the task to the secondary, if sending fails early exit and mark as stale +.primary.sendtask:{[sid; tid] + 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]," to secondary ",string[sid]," to run task ",string t`tasktype; + }; + +// 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:{ + // check for free secondaries + freesec: exec id from secondaries where status=`free; + // if none free exit + if[not count freesec; :()]; + // get queued tasks + qtasks: exec taskid from `priority xdesc select taskid, priority from 0!tasks where state=`queued; + // if no tasks exit early + n:min count[freesec], count qtasks; + if[n=0; :()]; + // get teh min of both tasks and free secs then run .primary.sendtask for each combo available + .primary.sendtask'[n#freesec; n#qtasks]; + }; + // if a connection is close we need to mark it as closed .z.pc:{[h] secid: first exec id from secondaries where handle=h; @@ -199,12 +224,13 @@ system"l src/common/os.q"; }; // quitting the primary kills any spawned secondaries -.z.exit:{if[count .primary.spawned; .primary.stop[]]}; +.z.exit:{ if[count .primary.spawned; .primary.stop[]]}; // start sequence -.primary.start:{[] +.primary.start:{ 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; ()!()]; .log.info "primary started, listening on ",string system "p"; .primary.starttime:: .z.P; }; diff --git a/tests/unit/dispatch_spec.q b/tests/unit/dispatch_spec.q new file mode 100644 index 0000000..2a485c2 --- /dev/null +++ b/tests/unit/dispatch_spec.q @@ -0,0 +1,161 @@ +/ 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 +.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); }]; + }; + +.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 From a575f53189e71677f6d7348b95d33d5e99ec4d24 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Tue, 20 Oct 2026 09:02:49 +0100 Subject: [PATCH 19/49] bench-324: added docs on how to do a manual run of tasks --- README.md | 95 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 94 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 2656903..ecefbbe 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,100 @@ integration: all 2 spec files passed jrutledge@homer:~/internalWork/Parallelisation-Project$ ``` -## AI Usage + +## 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 +``` + + + +# 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 From 18250e818d7df7269998e7418b80a615b626374d Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Tue, 20 Oct 2026 15:31:06 +0100 Subject: [PATCH 20/49] bench-377: fixing secondary and tasks status for a dead secondary while running a task --- src/primary.q | 7 ++- tests/unit/pc_spec.q | 127 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 132 insertions(+), 2 deletions(-) create mode 100644 tests/unit/pc_spec.q diff --git a/src/primary.q b/src/primary.q index 4d7ec6e..4a972f6 100644 --- a/src/primary.q +++ b/src/primary.q @@ -218,9 +218,12 @@ system"l src/common/os.q"; // if a connection is close we need to mark it as closed .z.pc:{[h] secid: first exec id from secondaries where handle=h; - if[null secid; :()]; - update status:`closed, handle:0Ni from `secondaries where id=secid; + tid: first exec currenttask from secondaries where id=secid; + update status:`closed, handle:0Ni, currenttask: 0N from `secondaries where id=secid; .log.info "secondary ",string[secid]," has closed its connection to the primary"; + if[not null tid; + .primary.taskupdate[tid; `failed; ([err:"secondary lost"; reason:`lost])]; + .log.warn "task ",string[tid]," was on secondary ",string[secid],", marking it as failed"]; }; // quitting the primary kills any spawned secondaries diff --git a/tests/unit/pc_spec.q b/tests/unit/pc_spec.q new file mode 100644 index 0000000..6a4cfde --- /dev/null +++ b/tests/unit/pc_spec.q @@ -0,0 +1,127 @@ +/ 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, and a runtask that does nothing +/ 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] ::}]; + }; + +.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; + update handle:5i 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;`result`membefore`memafter!(enlist 1;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 From bff62ba2120244c54ebc6461b71f5dabd8e3bfd9 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Thu, 22 Oct 2026 08:22:21 +0100 Subject: [PATCH 21/49] bench-377: add retry logic .primary.retry --- config/default.env | 5 ++--- src/primary.q | 18 +++++++++++++----- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/config/default.env b/config/default.env index 829ffad..027c5d9 100644 --- a/config/default.env +++ b/config/default.env @@ -8,8 +8,6 @@ SECONDARY_BASE_PORT=45001 # 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 @@ -23,4 +21,5 @@ LOG_DIR=logs # for tasks TASK_TIMEOUT_MS=60000 TASK_RETRIES_MAX=3 -TASK_TYPES=sleep,sumtil,fail \ No newline at end of file +TASK_TYPES=sleep,sumtil,fail +RETRY_REASONS=lost,sendfailed \ No newline at end of file diff --git a/src/primary.q b/src/primary.q index 4a972f6..0dac8f0 100644 --- a/src/primary.q +++ b/src/primary.q @@ -28,6 +28,7 @@ system"l src/common/os.q"; .primary.taskretries:"I"$getenv`TASK_RETRIES_MAX; .primary.tasktypes:`$"," vs getenv`TASK_TYPES; .primary.lasttaskid:0; +.primary.retryreasons:`$"," vs getenv `RETRY_REASONS; @@ -181,6 +182,7 @@ system"l src/common/os.q"; 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]; + if[newstate=`failed; .primary.retry tid]; 1b }; @@ -202,19 +204,25 @@ system"l src/common/os.q"; // 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:{ - // check for free secondaries freesec: exec id from secondaries where status=`free; - // if none free exit if[not count freesec; :()]; - // get queued tasks qtasks: exec taskid from `priority xdesc select taskid, priority from 0!tasks where state=`queued; - // if no tasks exit early n:min count[freesec], count qtasks; if[n=0; :()]; - // get teh min of both tasks and free secs then run .primary.sendtask for each combo available .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; err:""; reason:`])]; + }; + // if a connection is close we need to mark it as closed .z.pc:{[h] secid: first exec id from secondaries where handle=h; From 5824a2e5cf6a096004aa6f8022c1f2ed8d46e142 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Thu, 22 Oct 2026 14:40:56 +0100 Subject: [PATCH 22/49] bench-369: comparing pri/sec setup v running with threads --- README.md | 114 ++++++++++++++++++++++++++++++++++++++++++ bin/startsecondary.sh | 3 ++ config/default.env | 9 ++-- src/approvedtasks.q | 12 ++++- src/primary.q | 3 +- src/secondary.q | 4 ++ 6 files changed, 140 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index ecefbbe..313a515 100644 --- a/README.md +++ b/README.md @@ -175,7 +175,121 @@ taskid tasktype priority submittedtime dispatchedtime 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 +``` # AI Usage 1. qspec installation 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/config/default.env b/config/default.env index 027c5d9..e4a3804 100644 --- a/config/default.env +++ b/config/default.env @@ -14,12 +14,15 @@ STALE_MS=5000 # for spinning up secondarys via the primary SPAWN_SECONDARY=1 -NUM_SECONDARYS=4 +NUM_SECONDARYS=8 STOP_GRACE_PERIOD_SECS=5 LOG_DIR=logs # for tasks TASK_TIMEOUT_MS=60000 TASK_RETRIES_MAX=3 -TASK_TYPES=sleep,sumtil,fail -RETRY_REASONS=lost,sendfailed \ No newline at end of file +TASK_TYPES=sleep,sumtil,fail,vwap +RETRY_REASONS=lost,sendfailed + +# test hdb dir +HDB_DIR=/home/jrutledge/internalWork/hdb \ No newline at end of file diff --git a/src/approvedtasks.q b/src/approvedtasks.q index c7bab10..d8082c1 100644 --- a/src/approvedtasks.q +++ b/src/approvedtasks.q @@ -13,4 +13,14 @@ .secondary.approvedtasks[`sleep]:.task.sleep; .task.fail:{'`fail}; -.secondary.approvedtasks[`fail]:.task.fail; \ No newline at end of file +.secondary.approvedtasks[`fail]:.task.fail; + +// 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/primary.q b/src/primary.q index 0dac8f0..c58c94c 100644 --- a/src/primary.q +++ b/src/primary.q @@ -241,7 +241,8 @@ system"l src/common/os.q"; .primary.start:{ 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[`dispatch; {.primary.dispatch[]}; (); 1; 2; ()!()]; + .timer.addjob.custom[`dispatch; {.primary.dispatch[]}; (); 0; 2; ()!()]; .log.info "primary started, listening on ",string system "p"; .primary.starttime:: .z.P; }; diff --git a/src/secondary.q b/src/secondary.q index d767e3a..0de8145 100644 --- a/src/secondary.q +++ b/src/secondary.q @@ -10,6 +10,10 @@ system"l src/common/timer.q"; system"l src/common/os.q"; system"l src/approvedtasks.q"; +// if hdb set load it in +if[count .primary.hdb:getenv `HDB_DIR; + system "l ",getenv `HDB_DIR; + ]; // get the id form start cmd .secondary.opts: .Q.opt .z.x; From 76bcbfec3a419a43eaece3c86992c750f03dc176 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Thu, 22 Oct 2026 16:02:04 +0100 Subject: [PATCH 23/49] bench-369: bug fixes found in bench marking --- README.md | 8 ++++++++ src/primary.q | 11 ++++++++--- tests/unit/dispatch_spec.q | 5 +++++ tests/unit/pc_spec.q | 7 +++++-- 4 files changed, 26 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 313a515..7e500d7 100644 --- a/README.md +++ b/README.md @@ -291,6 +291,14 @@ 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 diff --git a/src/primary.q b/src/primary.q index c58c94c..5d0a6c9 100644 --- a/src/primary.q +++ b/src/primary.q @@ -56,8 +56,12 @@ system"l src/common/os.q"; }; // 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, lastmembytes: mem, status: `free from `secondaries where handle=.z.w; + update lastheartbeat:.z.P, lastmembytes: 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 @@ -183,11 +187,13 @@ system"l src/common/os.q"; sid:first exec secondaryid from tasks where taskid=tid; update status:`free, currenttask:0N from `secondaries where id=sid, currenttask=tid, status=`busy]; if[newstate=`failed; .primary.retry tid]; + if[newstate in `done`failed; .primary.dispatch[]]; // prevents us waiting on the timer, when bench marking this was the biggest thi 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; @@ -241,8 +247,7 @@ system"l src/common/os.q"; .primary.start:{ 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[`dispatch; {.primary.dispatch[]}; (); 0; 2; ()!()]; + .timer.addjob.custom[`dispatch; {.primary.dispatch[]}; (); 1; 2; ()!()]; .log.info "primary started, listening on ",string system "p"; .primary.starttime:: .z.P; }; diff --git a/tests/unit/dispatch_spec.q b/tests/unit/dispatch_spec.q index 2a485c2..b0fa906 100644 --- a/tests/unit/dispatch_spec.q +++ b/tests/unit/dispatch_spec.q @@ -19,6 +19,9 @@ if[not `primary in key `; system "l src/primary.q"]; .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; @@ -26,6 +29,8 @@ if[not `primary in key `; system "l src/primary.q"]; .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"]{ diff --git a/tests/unit/pc_spec.q b/tests/unit/pc_spec.q index 6a4cfde..132cb44 100644 --- a/tests/unit/pc_spec.q +++ b/tests/unit/pc_spec.q @@ -22,7 +22,7 @@ if[not `primary in key `; system "l src/primary.q"]; tid }; -/ quiet logs (counting warnings), a fixed task type list, and a runtask that does nothing +/ 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] ::}]; @@ -30,6 +30,8 @@ if[not `primary in key `; system "l src/primary.q"]; .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"]{ @@ -93,7 +95,8 @@ if[not `primary in key `; system "l src/primary.q"]; }; should["not touch queued tasks"]{ .ut.pcsend 1; - update handle:5i from `secondaries where id=2; + / 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; From b6e0bd18311152e485d3f863817814caeac77332 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Fri, 23 Oct 2026 12:02:28 +0100 Subject: [PATCH 24/49] bench-322: adding memory stats from the kernal --- README.md | 14 +++++- config/default.env | 3 ++ schemas/primarytables.q | 14 +++++- src/common/mem.q | 39 +++++++++++++++ src/primary.q | 30 ++++++++++- src/secondary.q | 1 + tests/unit/mem_spec.q | 103 ++++++++++++++++++++++++++++++++++++++ tests/unit/pollmem_spec.q | 100 ++++++++++++++++++++++++++++++++++++ tests/unit/primarytests.q | 12 +++-- 9 files changed, 308 insertions(+), 8 deletions(-) create mode 100644 src/common/mem.q create mode 100644 tests/unit/mem_spec.q create mode 100644 tests/unit/pollmem_spec.q diff --git a/README.md b/README.md index 7e500d7..4f5428c 100644 --- a/README.md +++ b/README.md @@ -335,4 +335,16 @@ 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) \ No newline at end of file +![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`) diff --git a/config/default.env b/config/default.env index e4a3804..c8b1bb9 100644 --- a/config/default.env +++ b/config/default.env @@ -24,5 +24,8 @@ TASK_RETRIES_MAX=3 TASK_TYPES=sleep,sumtil,fail,vwap RETRY_REASONS=lost,sendfailed +# mem stats from kernal +MEM_HISTORY_MAX=3600 + # test hdb dir HDB_DIR=/home/jrutledge/internalWork/hdb \ No newline at end of file diff --git a/schemas/primarytables.q b/schemas/primarytables.q index 5f40745..00038ad 100644 --- a/schemas/primarytables.q +++ b/schemas/primarytables.q @@ -15,7 +15,10 @@ secondaries : ([id: `long$()] starttime: `timestamp$(); registeredtime: `timestamp$(); tasktypes: (); - currenttask: `long$() + currenttask: `long$(); + rssanon: `long$(); // in bytes + vmrss: `long$(); // in bytes + memtime: `timestamp$() ); // monitor the tasks that are being carried out @@ -38,4 +41,13 @@ tasks : ([taskid: `long$()] err: (); reason: `$(); // `timeout`unknown`oom result: () + ); + +// one row per memory poll, bounded to the last .primary.memhistorymax rows +memhistory:([] + time: `timestamp$(); + total: `long$(); + primary: `long$(); + secondaries: `long$(); + busy: `int$() ); \ No newline at end of file diff --git a/src/common/mem.q b/src/common/mem.q new file mode 100644 index 0000000..ab27b40 --- /dev/null +++ b/src/common/mem.q @@ -0,0 +1,39 @@ +// All Claude after i ran some commands for it + +// memory figures from the kernel, used by the primary (to watch every secondary, even a busy one) +// and by secondaries (to record each task's peak). See docs/memory-spike.md for why these figures +// all values are in bytes; /proc reports kB (1024 bytes) + +// 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$()); + +// memory figures for a list of pids, one row per pid that is still running +// reads every pid with one cat, so one process start (~4ms) however many pids; read0 can't be used as +// /proc files report size 0. A pid that has exited is left out (cat's error is discarded) +// example: .mem.read 2993539 2993543i +.mem.read:{[pids] + if[not count pids; :.mem.empty]; + files:" " sv {"/proc/",string[x],"/status"} each pids; + l:system "sh -c 'cat ",files," 2>/dev/null; true'"; + // each line looks like "VmRSS:\t 12345 kB": the name before the colon, then the first word after it + k:`$first each ":" vs/: l; + v:{w:" " vs ssr[last ":" vs x;"\t";" "]; first w where 0 /proc/",string[.z.i],"/clear_refs'"; {[e] .log.warn "could not reset VmHWM: ",e}]; + }; diff --git a/src/primary.q b/src/primary.q index 5d0a6c9..6161d58 100644 --- a/src/primary.q +++ b/src/primary.q @@ -11,6 +11,7 @@ system"l schemas/primarytables.q"; system"l src/common/log.q"; system"l src/common/timer.q"; system"l src/common/os.q"; +system"l src/common/mem.q"; // get env vars .primary.stale:00:00:00.001*"J"$getenv`STALE_MS; @@ -29,7 +30,8 @@ system"l src/common/os.q"; .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 // dict of secondaries ids to their pids that the primary started @@ -51,7 +53,7 @@ system"l src/common/os.q"; // example run: // .primary.register ([id:5; pid:4000i; host:`localhost; port:45001i ]) .primary.register:{[info] - `secondaries upsert (info`id; .z.w; info`pid; info`host; info`port; `free; .z.P; 0N; 0Ni; 1b; info[`id] in key .primary.spawned; .z.P; .z.P; (); 0N); + `secondaries upsert (info`id; .z.w; info`pid; info`host; info`port; `free; .z.P; 0N; 0Ni; 1b; info[`id] in key .primary.spawned; .z.P; .z.P; (); 0N; 0N; 0N; 0Np); .log.info "secondary ", string[info`id], " registered at: ", string .z.P; }; @@ -229,6 +231,29 @@ system"l src/common/os.q"; .primary.taskupdate[tid; `queued; ([retrycount:1i+t`retrycount; secondaryid:0N; dispatchedtime:0Np; startedtime:0Np; finishedtime:0Np; membefore:0N; memafter: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`closed}; + +/// + // if a connection is close we need to mark it as closed .z.pc:{[h] secid: first exec id from secondaries where handle=h; @@ -248,6 +273,7 @@ system"l src/common/os.q"; 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; ()!()]; .log.info "primary started, listening on ",string system "p"; .primary.starttime:: .z.P; }; diff --git a/src/secondary.q b/src/secondary.q index 0de8145..81b59f3 100644 --- a/src/secondary.q +++ b/src/secondary.q @@ -9,6 +9,7 @@ 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 .primary.hdb:getenv `HDB_DIR; diff --git a/tests/unit/mem_spec.q b/tests/unit/mem_spec.q new file mode 100644 index 0000000..e401037 --- /dev/null +++ b/tests/unit/mem_spec.q @@ -0,0 +1,103 @@ +/ 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; + }; + }; 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 index 60b3cb6..218e9c2 100644 --- a/tests/unit/primarytests.q +++ b/tests/unit/primarytests.q @@ -11,18 +11,22 @@ if[not `primary in key `; system "l src/primary.q"]; }; .tst.desc["check table schemas"]{ - should["return 2 tables"]{ - 2 musteq count tables[]; + should["return 3 tables"]{ + 3 musteq count tables[]; system "l schemas/primarytables.q"; }; should["have the correct schema for secondaries table"]{ - (`id`handle`pid`host`port`status`lastheartbeat`lastmembytes`consecutivefails`healthy`spawned`starttime`registeredtime`tasktypes`currenttask) mustmatch cols secondaries; - "jiisispjibbpp j" mustmatch exec t from meta secondaries; + (`id`handle`pid`host`port`status`lastheartbeat`lastmembytes`consecutivefails`healthy`spawned`starttime`registeredtime`tasktypes`currenttask`rssanon`vmrss`memtime) mustmatch cols secondaries; + "jiisispjibbpp 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`err`reason`result) mustmatch cols tasks; "js ipjtiisjpppjj s " 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; + }; }; .tst.desc["can a secondary register with .primary.register"]{ From 7edea1456a1af74636a3a08c0839652556a4f4b2 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Fri, 23 Oct 2026 15:56:58 +0100 Subject: [PATCH 25/49] bench-322: memory stats from the kernal monitoring --- README.md | 65 ++++++++++++++++++++++++++++++++ config/default.env | 5 ++- config/integration.env | 1 + src/approvedtasks.q | 8 ++++ src/common/mem.q | 33 ++++++++++------ src/primary.q | 57 +++++++++++++++++++++++++--- src/secondary.q | 4 +- tests/integration/runtask_spec.q | 8 ++++ tests/unit/mem_spec.q | 25 ++++++++++++ 9 files changed, 185 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 4f5428c..ca85ed5 100644 --- a/README.md +++ b/README.md @@ -348,3 +348,68 @@ We can see the kernal mem stats at `/proc//status` file **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`) + +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** 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`. + +### 1. Check homer supports it (read-only) + +```bash +stat -fc %T /sys/fs/cgroup # cgroup2fs +systemctl --user is-system-running # running (or degraded) +cat /sys/fs/cgroup/user.slice/user-$(id -u).slice/user@$(id -u).service/cgroup.controllers # must include memory +free -g # plenty free +``` + +### 2. Check a limit is applied (harmless) + +```bash +systemd-run --user --scope --unit=qfwtest -p MemoryMax=200M -p MemorySwapMax=0 sleep 60 & +sleep 1 +systemctl --user status qfwtest.scope | head -5 # active (running) +cat /sys/fs/cgroup/user.slice/user-$(id -u).slice/user@$(id -u).service/app.slice/qfwtest.scope/memory.max # 209715200 +kill %1 +``` + +If the `memory.max` path doesn't exist: `systemctl --user show qfwtest.scope -p ControlGroup` gives the path under `/sys/fs/cgroup`. + +### 3. Check the kernel kills a process at its limit + +```bash +echo 'a:til 50000000' | systemd-run --user --scope --unit=qfwoom -p MemoryMax=200M -p MemorySwapMax=0 $KDBX_HOME/bin/q -q +echo "exit code: $?" # 137 = killed by the OOM killer +journalctl --user -n 20 --no-pager | grep -i -E "oom|qfwoom" +``` + +**Expected:** `Killed`, exit code `137`, and a journal line saying a process in `qfwoom.scope` was killed by the OOM killer. + +### 4. Run the framework inside a cgroup + +```bash +cd ~/internalWork/Parallelisation-Project +set -a; source config/default.env; set +a +systemd-run --user --scope --unit=qfw -p MemoryMax=4G -p MemorySwapMax=0 $KDBX_HOME/bin/q src/primary.q -p 45000 +``` + +The primary and every secondary it spawns share the 4GB hard limit. Check the secondaries are inside it: + +```q +q)system "cat /proc/",string[.z.i],"/cgroup" / ends in qfw.scope +q)system "cat /proc/",string[first exec pid from secondaries],"/cgroup" / the same +``` + +Keep `MemoryMax` (the kernel's hard limit) at or above `GLOBAL_MEM_LIMIT` (the framework's soft cap), so dispatch pauses before the kernel has to kill anything. + +### Clean up + +```bash +systemctl --user list-units --type=scope | grep qfw # anything still running +systemctl --user stop qfw.scope # stop one by name +``` \ No newline at end of file diff --git a/config/default.env b/config/default.env index c8b1bb9..684c651 100644 --- a/config/default.env +++ b/config/default.env @@ -21,11 +21,14 @@ LOG_DIR=logs # for tasks TASK_TIMEOUT_MS=60000 TASK_RETRIES_MAX=3 -TASK_TYPES=sleep,sumtil,fail,vwap +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 + # 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 index 96977e7..4515e3d 100644 --- a/config/integration.env +++ b/config/integration.env @@ -7,3 +7,4 @@ SPAWN_SECONDARY=1 STOP_GRACE_PERIOD_SECS=1 STALE_MS=3000 LOG_DIR=logs/integration +TASK_TYPES=sumtil,sleep,fail,hold \ No newline at end of file diff --git a/src/approvedtasks.q b/src/approvedtasks.q index d8082c1..74bdf1e 100644 --- a/src/approvedtasks.q +++ b/src/approvedtasks.q @@ -15,7 +15,15 @@ .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 diff --git a/src/common/mem.q b/src/common/mem.q index ab27b40..f6428fd 100644 --- a/src/common/mem.q +++ b/src/common/mem.q @@ -1,5 +1,3 @@ -// All Claude after i ran some commands for it - // memory figures from the kernel, used by the primary (to watch every secondary, even a busy one) // and by secondaries (to record each task's peak). See docs/memory-spike.md for why these figures // all values are in bytes; /proc reports kB (1024 bytes) @@ -12,18 +10,12 @@ // what .mem.read returns when there is nothing to read .mem.empty:([] pid:`int$(); rssanon:`long$(); vmrss:`long$(); vmhwm:`long$()); -// memory figures for a list of pids, one row per pid that is still running -// reads every pid with one cat, so one process start (~4ms) however many pids; read0 can't be used as -// /proc files report size 0. A pid that has exited is left out (cat's error is discarded) -// example: .mem.read 2993539 2993543i -.mem.read:{[pids] - if[not count pids; :.mem.empty]; - files:" " sv {"/proc/",string[x],"/status"} each pids; - l:system "sh -c 'cat ",files," 2>/dev/null; true'"; - // each line looks like "VmRSS:\t 12345 kB": the name before the colon, then the first word after it +// 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/primary.q b/src/primary.q index 6161d58..d172162 100644 --- a/src/primary.q +++ b/src/primary.q @@ -31,8 +31,15 @@ system"l src/common/mem.q"; .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 - +.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 dispatch held back by the memory cap right now +.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.respawns:(`long$())!`long$(); // restarts so far, by secondary id +.primary.stopping:0b; // set while stopping, so secondaries exiting on purpose aren't restarted // dict of secondaries ids to their pids that the primary started .primary.spawned:(`long$())!`int$(); @@ -217,6 +224,8 @@ system"l src/common/mem.q"; qtasks: exec taskid from `priority xdesc select taskid, priority from 0!tasks where state=`queued; n:min count[freesec], count qtasks; if[n=0; :()]; + // the memory gate: send nothing new while total memory is over the cap + if[.primary.overcap[]; :()]; .primary.sendtask'[n#freesec; n#qtasks]; }; @@ -231,9 +240,6 @@ system"l src/common/mem.q"; .primary.taskupdate[tid; `queued; ([retrycount:1i+t`retrycount; secondaryid:0N; dispatchedtime:0Np; startedtime:0Np; finishedtime:0Np; membefore:0N; memafter: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 @@ -248,11 +254,50 @@ system"l src/common/mem.q"; 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:select 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}]; + }; // if a connection is close we need to mark it as closed .z.pc:{[h] diff --git a/src/secondary.q b/src/secondary.q index 81b59f3..314161b 100644 --- a/src/secondary.q +++ b/src/secondary.q @@ -61,12 +61,12 @@ if[count .primary.hdb:getenv `HDB_DIR; // sec tells pri it is starting, record mem before, run task, record mem after result, .Q.gc[], send result .secondary.runtask:{[tid; tasktype; args] .secondary.send (`.primary.taskupdate; tid; `running; ()!()); - membefore:.Q.w[]`heap; // went with heap here as it might not register if its a small task on used + 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`reason`membefore`memafter!("unknown tasktype: ",string tasktype; `error; membefore; membefore))]; res:@[{.secondary.approvedtasks[x] y}[tasktype;]; args; {[error] (`failure; error)}]; - memafter:.Q.w[]`heap; + memafter:first exec vmhwm from .mem.read enlist .z.i; .Q.gc[]; if[`failure ~ first res; .log.warn "task ",string[tid],", failed with error: ",last res; diff --git a/tests/integration/runtask_spec.q b/tests/integration/runtask_spec.q index 6b1f195..74a131a 100644 --- a/tests/integration/runtask_spec.q +++ b/tests/integration/runtask_spec.q @@ -64,4 +64,12 @@ system "l tests/helpers/it.q"; "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/unit/mem_spec.q b/tests/unit/mem_spec.q index e401037..c0f57b6 100644 --- a/tests/unit/mem_spec.q +++ b/tests/unit/mem_spec.q @@ -101,3 +101,28 @@ if[not `primary in key `; system "l src/primary.q"]; 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 From f2a5f150c45f7284b0351c01a853dc3df0b72e05 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Mon, 26 Oct 2026 15:24:52 +0000 Subject: [PATCH 26/49] bench-390: adding seconary respawn functions --- config/integration.env | 5 +- src/primary.q | 23 ++++-- tests/unit/respawn_spec.q | 123 ++++++++++++++++++++++++++++++++ tests/unit/timeout_spec.q | 143 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 289 insertions(+), 5 deletions(-) create mode 100644 tests/unit/respawn_spec.q create mode 100644 tests/unit/timeout_spec.q diff --git a/config/integration.env b/config/integration.env index 4515e3d..95160af 100644 --- a/config/integration.env +++ b/config/integration.env @@ -7,4 +7,7 @@ SPAWN_SECONDARY=1 STOP_GRACE_PERIOD_SECS=1 STALE_MS=3000 LOG_DIR=logs/integration -TASK_TYPES=sumtil,sleep,fail,hold \ No newline at end of file +TASK_TYPES=sumtil,sleep,fail,hold + +# integration specs kill secondaries on purpose and expect them to stay closed +RESPAWN_MAX=0 \ No newline at end of file diff --git a/src/primary.q b/src/primary.q index d172162..a4682f5 100644 --- a/src/primary.q +++ b/src/primary.q @@ -38,8 +38,7 @@ system"l src/common/mem.q"; .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.respawns:(`long$())!`long$(); // restarts so far, by secondary id -.primary.stopping:0b; // set while stopping, so secondaries exiting on purpose aren't restarted + // dict of secondaries ids to their pids that the primary started .primary.spawned:(`long$())!`int$(); @@ -53,7 +52,8 @@ system"l src/common/mem.q"; // 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 @@ -292,14 +292,27 @@ system"l src/common/mem.q"; // 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:select pid from secondaries where id=sid; + 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; + }; + // 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; @@ -308,6 +321,7 @@ system"l src/common/mem.q"; if[not null tid; .primary.taskupdate[tid; `failed; ([err:"secondary lost"; reason:`lost])]; .log.warn "task ",string[tid]," was on secondary ",string[secid],", marking it as failed"]; + .primary.respawnsecondary secid; }; // quitting the primary kills any spawned secondaries @@ -319,6 +333,7 @@ system"l src/common/mem.q"; .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; }; 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/timeout_spec.q b/tests/unit/timeout_spec.q new file mode 100644 index 0000000..3e4a332 --- /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;`result`membefore`memafter!(enlist 1;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 From d6fb07eef6b850a26c02b9c29d559e8cec52b919 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Mon, 26 Oct 2026 16:55:54 +0000 Subject: [PATCH 27/49] bench-344: updated .primary.status to now have memory stats --- src/primary.q | 13 +++++++++---- tests/unit/status_spec.q | 4 ++-- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/src/primary.q b/src/primary.q index a4682f5..37bfc67 100644 --- a/src/primary.q +++ b/src/primary.q @@ -33,7 +33,7 @@ system"l src/common/mem.q"; .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 dispatch held back by the memory cap right now +.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 @@ -87,9 +87,14 @@ system"l src/common/mem.q"; .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, port, status, spawned, lastseen:`time$.z.P-lastheartbeat,lastmembytes from 0!secondaries; - ([time: .z.P; uptime: .z.P-.primary.starttime; secondaries: secs; seccounts: .primary.countby[.primary.secondarystates;exec status from secondaries]; taskcounts: .primary.countby[.primary.taskstates;exec state from tasks]]) + secs:select id, pid, port, status, spawned, currenttask, rssanon, restarts:0^.primary.respawns id, lastseen:.z.P-lastheartbeat, lastmembytes 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 @@ -277,7 +282,7 @@ system"l src/common/mem.q"; // 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}; +.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. diff --git a/tests/unit/status_spec.q b/tests/unit/status_spec.q index d3f83c8..023b4b2 100644 --- a/tests/unit/status_spec.q +++ b/tests/unit/status_spec.q @@ -42,7 +42,7 @@ should["have the correct keys"]{ s:.primary.status[]; 99h musteq type s; - `time`uptime`secondaries`seccounts`taskcounts mustmatch key s; + `time`uptime`memory`dispatch`secondaries`seccounts`taskcounts mustmatch key s; }; should["work with no secondaries and no tasks"]{ s:.primary.status[]; @@ -65,7 +65,7 @@ .ut.reg each 1 2; t:.primary.status[]`secondaries; 2 musteq count t; - `id`pid`port`status`spawned`lastseen`lastmembytes mustmatch cols t; + `id`pid`port`status`spawned`currenttask`rssanon`restarts`lastseen`lastmembytes mustmatch cols t; }; should["show a just-registered secondary as seen moments ago"]{ .ut.reg 1; From 2b149d1c6217357ba5618bf0e63bfb1d102f5af8 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Tue, 27 Oct 2026 11:22:09 +0000 Subject: [PATCH 28/49] bench-344: improved status readability --- src/primary.q | 8 +++-- tests/unit/status_spec.q | 72 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 2 deletions(-) diff --git a/src/primary.q b/src/primary.q index 37bfc67..91b775a 100644 --- a/src/primary.q +++ b/src/primary.q @@ -89,7 +89,7 @@ system"l src/common/mem.q"; // a snapshot of the primarys status // memory is in bytes headroom how far under the cap we are .primary.status:{ - secs:select id, pid, port, status, spawned, currenttask, rssanon, restarts:0^.primary.respawns id, lastseen:.z.P-lastheartbeat, lastmembytes from 0!secondaries; + secs:select id, pid, port, status, spawned, currenttask, rssanon, restarts:0^.primary.respawns id, lastseen:`time$.z.P-lastheartbeat, lastmembytes 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]; @@ -102,8 +102,12 @@ system"l src/common/mem.q"; 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 pristatus`secondaries; + show `id xasc select id, pid, port, status, spawned, task:currenttask, memmb:0.1*floor 0.5+10*rssanon%1048576, restarts, lastseen from pristatus`secondaries; -1 "tasks: ",fmt pristatus`taskcounts; }; diff --git a/tests/unit/status_spec.q b/tests/unit/status_spec.q index 023b4b2..c3781d9 100644 --- a/tests/unit/status_spec.q +++ b/tests/unit/status_spec.q @@ -85,4 +85,76 @@ .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 From 52b0b8b00a793c3995442df608288c1681825a72 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Tue, 27 Oct 2026 15:11:37 +0000 Subject: [PATCH 29/49] bench-391: cgroups and oom functionality --- README.md | 72 ++++++++++++----------- src/common/cgroup.q | 19 ++++++ src/primary.q | 22 ++++++- tests/unit/oom_spec.q | 133 ++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 209 insertions(+), 37 deletions(-) create mode 100644 src/common/cgroup.q create mode 100644 tests/unit/oom_spec.q diff --git a/README.md b/README.md index ca85ed5..d5e7051 100644 --- a/README.md +++ b/README.md @@ -355,61 +355,65 @@ 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** 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. +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`. -### 1. Check homer supports it (read-only) +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 -stat -fc %T /sys/fs/cgroup # cgroup2fs -systemctl --user is-system-running # running (or degraded) -cat /sys/fs/cgroup/user.slice/user-$(id -u).slice/user@$(id -u).service/cgroup.controllers # must include memory -free -g # plenty free +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 ``` -### 2. Check a limit is applied (harmless) +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` -```bash -systemd-run --user --scope --unit=qfwtest -p MemoryMax=200M -p MemorySwapMax=0 sleep 60 & -sleep 1 -systemctl --user status qfwtest.scope | head -5 # active (running) -cat /sys/fs/cgroup/user.slice/user-$(id -u).slice/user@$(id -u).service/app.slice/qfwtest.scope/memory.max # 209715200 -kill %1 -``` - -If the `memory.max` path doesn't exist: `systemctl --user show qfwtest.scope -p ControlGroup` gives the path under `/sys/fs/cgroup`. - -### 3. Check the kernel kills a process at its limit +### How does it decide which process to kill? +How bad a process is can be calculated ```bash -echo 'a:til 50000000' | systemd-run --user --scope --unit=qfwoom -p MemoryMax=200M -p MemorySwapMax=0 $KDBX_HOME/bin/q -q -echo "exit code: $?" # 137 = killed by the OOM killer -journalctl --user -n 20 --no-pager | grep -i -E "oom|qfwoom" +badness = the process's resident memory + its swap + its page tables (in pages) + + oom_score_adj × (total memory allowed ÷ 1000) ``` -**Expected:** `Killed`, exit code `137`, and a journal line saying a process in `qfwoom.scope` was killed by the OOM killer. +Which ever process has the highest `badness` will be killed first by the kernal. -### 4. Run the framework inside a cgroup +### 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=qfw -p MemoryMax=4G -p MemorySwapMax=0 $KDBX_HOME/bin/q src/primary.q -p 45000 +systemd-run --user --scope --unit=qfwoom -p MemoryMax=1G -p MemorySwapMax=0 $KDBX_HOME/bin/q src/primary.q -p 45000 ``` -The primary and every secondary it spawns share the 4GB hard limit. Check the secondaries are inside it: +### What the primary does when a secondary is killed for memory -```q -q)system "cat /proc/",string[.z.i],"/cgroup" / ends in qfw.scope -q)system "cat /proc/",string[first exec pid from secondaries],"/cgroup" / the same -``` +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`). -Keep `MemoryMax` (the kernel's hard limit) at or above `GLOBAL_MEM_LIMIT` (the framework's soft cap), so dispatch pauses before the kernel has to kill anything. +Outside a memory-limited cgroup the count stays 0, so every death is `lost`. -### Clean up +To see it happen: ```bash -systemctl --user list-units --type=scope | grep qfw # anything still running -systemctl --user stop qfw.scope # stop one by name -``` \ No newline at end of file +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. + diff --git a/src/common/cgroup.q b/src/common/cgroup.q new file mode 100644 index 0000000..5b2e66d --- /dev/null +++ b/src/common/cgroup.q @@ -0,0 +1,19 @@ +// 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:{[d] + if[not count d; :0N]; + l:@[system; "cat ",d,"/memory.events 2>/dev/null"; {[e] ()}]; + l:l where l like "oom_kill *"; + $[count l; "J"$last " " vs first l; 0N] + }; + diff --git a/src/primary.q b/src/primary.q index 91b775a..39cc43a 100644 --- a/src/primary.q +++ b/src/primary.q @@ -12,6 +12,7 @@ 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"; // get env vars .primary.stale:00:00:00.001*"J"$getenv`STALE_MS; @@ -320,16 +321,29 @@ system"l src/common/mem.q"; .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 + }; + // 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; - .log.info "secondary ",string[secid]," has closed its connection to the primary"; + // 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; - .primary.taskupdate[tid; `failed; ([err:"secondary lost"; reason:`lost])]; - .log.warn "task ",string[tid]," was on secondary ",string[secid],", marking it as failed"]; + r:$[oom; ([err:"secondary killed by the kernel for using too much memory"; reason:`oom]); ([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; }; @@ -343,6 +357,8 @@ system"l src/common/mem.q"; .timer.addjob.custom[`dispatch; {.primary.dispatch[]}; (); 1; 2; ()!()]; .timer.addjob.custom[`mempoll; {.primary.pollmem[]}; (); 1; 2; ()!()]; .timer.addjob.custom[`timeoutcheck; {.primary.checktimeouts[]}; (); 1; 2; ()!()]; + .primary.cgroupdir:.cgroup.dir[]; + .primary.oomkills:.cgroup.oomkills .primary.cgroupdir; .log.info "primary started, listening on ",string system "p"; .primary.starttime:: .z.P; }; 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 From 9f681ad119a2c694850016cee910d87dbb4101bd Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Wed, 28 Oct 2026 12:22:06 +0000 Subject: [PATCH 30/49] bench-392: results now saved to disk --- README.md | 3 +++ config/default.env | 3 +++ config/integration.env | 1 + schemas/primarytables.q | 5 +++-- src/common/cgroup.q | 11 +++++------ src/primary.q | 12 +++++++++--- src/secondary.q | 30 ++++++++++++++++++++++-------- tests/integration/runtask_spec.q | 2 +- tests/unit/newtask_spec.q | 3 ++- tests/unit/pc_spec.q | 2 +- tests/unit/primarytests.q | 4 ++-- tests/unit/taskupdate_spec.q | 10 +++++----- tests/unit/timeout_spec.q | 2 +- 13 files changed, 58 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index d5e7051..f33d630 100644 --- a/README.md +++ b/README.md @@ -349,6 +349,9 @@ We can see the kernal mem stats at `/proc//status` file **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 diff --git a/config/default.env b/config/default.env index 684c651..bfdbc7c 100644 --- a/config/default.env +++ b/config/default.env @@ -30,5 +30,8 @@ MEM_HISTORY_MAX=3600 # how many times the primary restarts a spawned secondary that dies (timeout, crash, OOM); 0 = never RESPAWN_MAX=3 +# 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 index 95160af..96811e1 100644 --- a/config/integration.env +++ b/config/integration.env @@ -8,6 +8,7 @@ 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 \ No newline at end of file diff --git a/schemas/primarytables.q b/schemas/primarytables.q index 00038ad..711d6f5 100644 --- a/schemas/primarytables.q +++ b/schemas/primarytables.q @@ -39,8 +39,9 @@ tasks : ([taskid: `long$()] membefore: `long$(); memafter: `long$(); err: (); - reason: `$(); // `timeout`unknown`oom - result: () + reason: `$(); // `timeout`oom`error`lost`sendfailed + resultpath: `$(); + resultbytes: `long$() ); // one row per memory poll, bounded to the last .primary.memhistorymax rows diff --git a/src/common/cgroup.q b/src/common/cgroup.q index 5b2e66d..5778aa8 100644 --- a/src/common/cgroup.q +++ b/src/common/cgroup.q @@ -8,12 +8,11 @@ }[]; - // how many processes the kernel has killed for memory in cgroup directory d (the oom_kill line of its memory.events) +// 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:{[d] - if[not count d; :0N]; - l:@[system; "cat ",d,"/memory.events 2>/dev/null"; {[e] ()}]; +.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/primary.q b/src/primary.q index 39cc43a..a2631d6 100644 --- a/src/primary.q +++ b/src/primary.q @@ -39,6 +39,7 @@ system"l src/common/cgroup.q"; .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; // dict of secondaries ids to their pids that the primary started @@ -63,6 +64,7 @@ system"l src/common/cgroup.q"; .primary.register:{[info] `secondaries upsert (info`id; .z.w; info`pid; info`host; info`port; `free; .z.P; 0N; 0Ni; 1b; info[`id] in key .primary.spawned; .z.P; .z.P; (); 0N; 0N; 0N; 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 @@ -180,7 +182,7 @@ system"l src/common/cgroup.q"; 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; err:""; reason:`; result:enlist (::)]); + finishedtime:0Np; membefore:0N; memafter:0N; err:""; reason:`; resultpath:`; resultbytes:0N]); `tasks upsert data; .log.info "new task ",string[tid]," ",string task`tasktype; tid @@ -352,13 +354,17 @@ system"l src/common/cgroup.q"; // start sequence .primary.start:{ + 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; ()!()]; - .primary.cgroupdir:.cgroup.dir[]; - .primary.oomkills:.cgroup.oomkills .primary.cgroupdir; .log.info "primary started, listening on ",string system "p"; .primary.starttime:: .z.P; }; diff --git a/src/secondary.q b/src/secondary.q index 314161b..d3b7643 100644 --- a/src/secondary.q +++ b/src/secondary.q @@ -12,7 +12,7 @@ system"l src/approvedtasks.q"; system"l src/common/mem.q"; // if hdb set load it in -if[count .primary.hdb:getenv `HDB_DIR; +if[count .secondary.hdb:getenv `HDB_DIR; system "l ",getenv `HDB_DIR; ]; @@ -58,28 +58,42 @@ if[count .primary.hdb:getenv `HDB_DIR; // send an async message to the primary and flush it straight away .secondary.send:{[msg] neg[.secondary.handle] msg; neg[.secondary.handle][]}; -// sec tells pri it is starting, record mem before, run task, record mem after result, .Q.gc[], send result +// sec tells pri 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; + 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`reason`membefore`memafter!("unknown tasktype: ",string tasktype; `error; membefore; membefore))]; res:@[{.secondary.approvedtasks[x] y}[tasktype;]; args; {[error] (`failure; error)}]; memafter:first exec vmhwm from .mem.read enlist .z.i; - .Q.gc[]; - if[`failure ~ first res; + if[`failure ~ first res; + .Q.gc[]; .log.warn "task ",string[tid],", failed with error: ",last res; :.secondary.send (`.primary.taskupdate; tid; `failed; `err`reason`membefore`memafter!(last res; `error; membefore; memafter))]; - .log.info "task ",string[tid]," is complete"; - .secondary.send (`.primary.taskupdate; tid; `done; `result`membefore`memafter!(enlist res; membefore; memafter)); + saved:.secondary.save[tid; res]; + res:(::); + .Q.gc[]; + if[`failure ~ first saved; + .log.warn "task ",string[tid],", could not save its result: ",last saved; + :.secondary.send (`.primary.taskupdate; tid; `failed; `err`reason`membefore`memafter!("could not save the result: ",last saved; `savefailed; membefore; memafter))]; + .log.info "task ",string[tid]," is complete, result saved to ",string first saved; + .secondary.send (`.primary.taskupdate; tid; `done; `resultpath`resultbytes`membefore`memafter!(first saved; last saved; membefore; memafter)); + }; + +// 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[]; - neg[.secondary.handle](`.primary.register; .secondary.info); + .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"; }; diff --git a/tests/integration/runtask_spec.q b/tests/integration/runtask_spec.q index 74a131a..9d9473c 100644 --- a/tests/integration/runtask_spec.q +++ b/tests/integration/runtask_spec.q @@ -29,7 +29,7 @@ system "l tests/helpers/it.q"; tid:.it.dispatch[1;`sumtil;`sumtil;1000000]; 1b musteq .it.waitstate[tid;`done;10]; t:.it.task tid; - 499999500000 musteq first t`result; + 499999500000 musteq get t`resultpath; 1 musteq t`secondaryid; 1b musteq all not null t`dispatchedtime`startedtime`finishedtime; }; diff --git a/tests/unit/newtask_spec.q b/tests/unit/newtask_spec.q index 621447d..cb3bec7 100644 --- a/tests/unit/newtask_spec.q +++ b/tests/unit/newtask_spec.q @@ -35,7 +35,8 @@ if[not `primary in key `; system "l src/primary.q"]; id:.primary.newtask `tasktype`args!(`sum;1000000); (enlist 1000000) mustmatch tasks[id]`args; 1000000 musteq first tasks[id]`args; - 1b musteq (::)~first tasks[id]`result; + 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); diff --git a/tests/unit/pc_spec.q b/tests/unit/pc_spec.q index 132cb44..c77d172 100644 --- a/tests/unit/pc_spec.q +++ b/tests/unit/pc_spec.q @@ -114,7 +114,7 @@ if[not `primary in key `; system "l src/primary.q"]; update handle:5i from `secondaries where id=2; tid:.ut.pcsend 1; .primary.taskupdate[tid;`running;()!()]; - .primary.taskupdate[tid;`done;`result`membefore`memafter!(enlist 1;0;0)]; + .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; diff --git a/tests/unit/primarytests.q b/tests/unit/primarytests.q index 218e9c2..5a95a65 100644 --- a/tests/unit/primarytests.q +++ b/tests/unit/primarytests.q @@ -20,8 +20,8 @@ if[not `primary in key `; system "l src/primary.q"]; "jiisispjibbpp 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`err`reason`result) mustmatch cols tasks; - "js ipjtiisjpppjj s " mustmatch exec t from meta tasks; + (`taskid`tasktype`args`priority`submittedtime`memestimate`timeout`retriesmax`retrycount`state`secondaryid`dispatchedtime`startedtime`finishedtime`membefore`memafter`err`reason`resultpath`resultbytes) mustmatch cols tasks; + "js ipjtiisjpppjj ssj" mustmatch exec t from meta tasks; }; should["have the correct schema for memhistory table"]{ (`time`total`primary`secondaries`busy) mustmatch cols memhistory; diff --git a/tests/unit/taskupdate_spec.q b/tests/unit/taskupdate_spec.q index 0fa1081..d77b59a 100644 --- a/tests/unit/taskupdate_spec.q +++ b/tests/unit/taskupdate_spec.q @@ -1,5 +1,4 @@ / unit specs for .primary.taskupdate, the only way a task changes state -/ callers are internal, so argument types are not checked; callers box result with enlist / 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 @@ -10,8 +9,8 @@ if[not `primary in key `; system "l src/primary.q"]; / 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`result! - (.ut.tuid;`noop;enlist 1;0i;.z.P;0N;00:01:00.000;3i;0i;s;0N;0Np;0Np;0Np;0N;0N;"";`;enlist (::)) + `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 @@ -45,11 +44,12 @@ if[not `primary in key `; system "l src/primary.q"]; }; should["move running to done and store the result and memory"]{ .ut.tuset `running; - 1b musteq .primary.taskupdate[.ut.tuid;`done;`membefore`memafter`result!(1000;800;enlist 42)]; + 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; - 42 musteq first r`result; + `:/tmp/x musteq r`resultpath; + 16 musteq r`resultbytes; 1000 musteq r`membefore; 800 musteq r`memafter; }; diff --git a/tests/unit/timeout_spec.q b/tests/unit/timeout_spec.q index 3e4a332..0aa20fb 100644 --- a/tests/unit/timeout_spec.q +++ b/tests/unit/timeout_spec.q @@ -116,7 +116,7 @@ if[not `primary in key `; system "l src/primary.q"]; 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;`result`membefore`memafter!(enlist 1;0;0)]; + .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[]; From 28026160ce1c0113792ea2d17f5c10ba688ff193 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Wed, 28 Oct 2026 12:54:54 +0000 Subject: [PATCH 31/49] bench-392: adding results testing and how to get results --- src/primary.q | 10 ++++++++ tests/unit/results_spec.q | 52 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 tests/unit/results_spec.q diff --git a/src/primary.q b/src/primary.q index a2631d6..984cdf7 100644 --- a/src/primary.q +++ b/src/primary.q @@ -333,6 +333,16 @@ system"l src/common/cgroup.q"; 1b }; +// gets the result for a given taskid, also allows results to live beyond the life of the primary +// fails if the task doesnt exist or has a null result +.primary.getresult:{[tid] + r:tasks tid; + if[null r`state; '"no task ",string tid]; + if[not `done~r`state; '"task ",string[tid]," is ",string r`state]; + if[null r`resultpath; '"task ",string[tid]," has no result"]; + get r`resultpath + }; + // 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] diff --git a/tests/unit/results_spec.q b/tests/unit/results_spec.q new file mode 100644 index 0000000..2185600 --- /dev/null +++ b/tests/unit/results_spec.q @@ -0,0 +1,52 @@ +/ unit specs for .primary.getresult: loading a finished task's result from disk +/ loads primary.q once (spawning off). A result is saved by hand in a temporary folder; no secondaries are +/ registered, so newtask only queues +/ run: tests/run.sh tests/unit/results_spec.q + +setenv[`SPAWN_SECONDARY;enlist "0"]; +if[not `primary in key `; system "l src/primary.q"]; + +.ut.rddir:"/tmp/qfw-results-spec"; + +/ an empty test folder and tasks table, then two tasks: .ut.rddone (done, result 45 saved as file 1) and .ut.rdqueued +.ut.rdreset:{[] + system "rm -rf ",.ut.rddir; + system "mkdir -p ",.ut.rddir; + delete from `tasks; + .primary.lasttaskid:0; + `.ut.rddone set .primary.newtask `tasktype`args!(`sumtil;10); + `.ut.rdqueued set .primary.newtask `tasktype`args!(`sumtil;10); + p:hsym `$.ut.rddir,"/",string .ut.rddone; + p set 45; + update state:`done, resultpath:p, resultbytes:hcount p from `tasks where taskid=.ut.rddone; + }; + +.tst.desc[".primary.getresult"]{ + before{ + `.log.info mock {[x] ::}; + `.log.warn mock {[x] ::}; + `.primary.tasktypes mock `sumtil`sleep`fail; + `.primary.memcap mock 0N; + .ut.rdreset[]; + }; + after{ + system "rm -rf ",.ut.rddir; + }; + should["load a finished task's result"]{ + 45 musteq .primary.getresult .ut.rddone; + }; + should["error for a task that isn't done"]{ + mustthrow[(); {[] .primary.getresult .ut.rdqueued}]; + }; + should["error for a task that doesn't exist"]{ + mustthrow[(); {[] .primary.getresult 99}]; + }; + should["error for a done task with no result"]{ + update resultpath:`, resultbytes:0N from `tasks where taskid=.ut.rddone; + mustthrow[(); {[] .primary.getresult .ut.rddone}]; + }; + should["error when the result file has gone"]{ + system "rm -f ",.ut.rddir,"/*"; + mustthrow[(); {[] .primary.getresult .ut.rddone}]; + }; + }; \ No newline at end of file From b660328e2359906ed16c7098b253247807dd33fe Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Wed, 28 Oct 2026 17:03:33 +0000 Subject: [PATCH 32/49] bench-392: added jobs for combining tasks --- schemas/primarytables.q | 18 ++- src/primary.q | 53 ++++++++- tests/unit/jobs_spec.q | 224 ++++++++++++++++++++++++++++++++++++++ tests/unit/primarytests.q | 6 +- tests/unit/results_spec.q | 3 +- 5 files changed, 297 insertions(+), 7 deletions(-) create mode 100644 tests/unit/jobs_spec.q diff --git a/schemas/primarytables.q b/schemas/primarytables.q index 711d6f5..3b3b1d2 100644 --- a/schemas/primarytables.q +++ b/schemas/primarytables.q @@ -41,14 +41,28 @@ tasks : ([taskid: `long$()] err: (); reason: `$(); // `timeout`oom`error`lost`sendfailed resultpath: `$(); - resultbytes: `long$() + resultbytes: `long$(); + jobid: `long$() ); // one row per memory poll, bounded to the last .primary.memhistorymax rows -memhistory:([] +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: `$(); + ntasks: `int$(); + state: `$(); + submittedtime: `timestamp$(); + finishedtime: `timestamp$(); + combinetask: `long$(); // taskid of the combine task, null until it is queued + resultpath: `$(); // the combined result, null until the job is done + resultbytes: `long$(); + err: () // why the job failed, "" when it hasn't ); \ No newline at end of file diff --git a/src/primary.q b/src/primary.q index 984cdf7..3cd744f 100644 --- a/src/primary.q +++ b/src/primary.q @@ -40,6 +40,7 @@ system"l src/common/cgroup.q"; .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; // dict of secondaries ids to their pids that the primary started @@ -49,7 +50,7 @@ system"l src/common/cgroup.q"; .primary.taskdefaults:([priority:0i; memestimate: 0N; timeout: .primary.tasktimeout; retriesmax: .primary.taskretries]); // what each task status can move too -.primary.taskchange:([queued: enlist `dispatched; dispatched: `running`failed; running: `done`failed; done:`$(); failed:enlist `queued]); +.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]); @@ -208,6 +209,7 @@ system"l src/common/cgroup.q"; sid:first exec secondaryid from tasks where taskid=tid; update status:`free, currenttask:0N from `secondaries where id=sid, currenttask=tid, status=`busy]; 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 thi 1b }; @@ -343,6 +345,55 @@ system"l src/common/cgroup.q"; get r`resultpath }; +// splits a job up into individual tasks +// .primary.newjob[`vwap; 2026.01.01 2026.01.02 2026.01.03] +.primary.newjob:{[tasktype; args] + if[not tasktype in .primary.tasktypes; '"unknown task type ",string tasktype]; + if[not count args; '"no args: a job needs at least one task"]; + jid:.primary.lastjobid+:1; + ids:.primary.newtask each {([tasktype: x; args: y])}[tasktype] each args; // maybe change the name of the variable to taskt ? + update jobid:jid from `tasks where taskid in ids; + `jobs upsert (jid; tasktype; `int$count ids; `running; .z.P; 0Np; 0N; `; 0N; ""); + .log.info "new job ",string[jid],": ",string[count ids]," ",string[tasktype]," tasks (",string[first ids],"..",string[last ids],")"; + 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"; + }; + +// the result files of a finished job's parts, in task order, for the caller to load and combine: +// raze get each .primary.jobpaths jid +// errors if the job doesn't exist or isn't done +.primary.getjobresult:{[jid] + state:first exec state from jobs where jobid = jid; + if[not `done ~ state; '"job ",string[jid]," is ",string state]; + raze .primary.getresult each exec taskid from tasks where jobid = jid, not null resultpath + }; + // 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] diff --git a/tests/unit/jobs_spec.q b/tests/unit/jobs_spec.q new file mode 100644 index 0000000..f40d80d --- /dev/null +++ b/tests/unit/jobs_spec.q @@ -0,0 +1,224 @@ +/ unit specs for jobs: .primary.newjob, .primary.jobcheck (via taskupdate), .primary.canceljob and .primary.getjobresult +/ 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; + }; + }; + +.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.getjobresult"]{ + before{ + .ut.jbmocks[]; + .ut.jbreset[]; + }; + after{ + system "rm -rf ",.ut.jbdir; + }; + should["combine 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 .primary.getjobresult 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 .primary.getjobresult j; + }; + should["skip parts that returned no result"]{ + j:.ut.jbnew 3; + t:.ut.jbtids j; + .ut.jbdone'[t; (1 2;::;3 4)]; + 1 2 3 4 mustmatch .primary.getjobresult j; + }; + should["error for a job that isn't done"]{ + `.ut.jbj set .ut.jbnew 2; + mustthrow[(); {[] .primary.getjobresult .ut.jbj}]; + }; + should["error for a failed job"]{ + `.ut.jbj set .ut.jbnew 2; + .ut.jbfail[first .ut.jbtids .ut.jbj; `error]; + mustthrow[(); {[] .primary.getjobresult .ut.jbj}]; + }; + should["error for a job that doesn't exist"]{ + mustthrow[(); {[] .primary.getjobresult 99}]; + }; + }; \ No newline at end of file diff --git a/tests/unit/primarytests.q b/tests/unit/primarytests.q index 5a95a65..9ace95b 100644 --- a/tests/unit/primarytests.q +++ b/tests/unit/primarytests.q @@ -12,7 +12,7 @@ if[not `primary in key `; system "l src/primary.q"]; .tst.desc["check table schemas"]{ should["return 3 tables"]{ - 3 musteq count tables[]; + 4 musteq count tables[]; system "l schemas/primarytables.q"; }; should["have the correct schema for secondaries table"]{ @@ -20,8 +20,8 @@ if[not `primary in key `; system "l src/primary.q"]; "jiisispjibbpp 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`err`reason`resultpath`resultbytes) mustmatch cols tasks; - "js ipjtiisjpppjj ssj" mustmatch exec t from meta tasks; + (`taskid`tasktype`args`priority`submittedtime`memestimate`timeout`retriesmax`retrycount`state`secondaryid`dispatchedtime`startedtime`finishedtime`membefore`memafter`err`reason`resultpath`resultbytes`jobid) mustmatch cols tasks; + "js ipjtiisjpppjj ssjj" mustmatch exec t from meta tasks; }; should["have the correct schema for memhistory table"]{ (`time`total`primary`secondaries`busy) mustmatch cols memhistory; diff --git a/tests/unit/results_spec.q b/tests/unit/results_spec.q index 2185600..b0c2fc1 100644 --- a/tests/unit/results_spec.q +++ b/tests/unit/results_spec.q @@ -49,4 +49,5 @@ if[not `primary in key `; system "l src/primary.q"]; system "rm -f ",.ut.rddir,"/*"; mustthrow[(); {[] .primary.getresult .ut.rddone}]; }; - }; \ No newline at end of file + }; + From 7f6b8f36b34e5d594fdca0dcaa17337c9a6ac415 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Thu, 29 Oct 2026 09:18:23 +0000 Subject: [PATCH 33/49] bench-392: changing to just return result path --- src/primary.q | 15 +++++++-------- tests/unit/jobs_spec.q | 27 +++++++++++++++++---------- tests/unit/results_spec.q | 27 ++++++++++++++------------- 3 files changed, 38 insertions(+), 31 deletions(-) diff --git a/src/primary.q b/src/primary.q index 3cd744f..fa500ad 100644 --- a/src/primary.q +++ b/src/primary.q @@ -335,14 +335,14 @@ system"l src/common/cgroup.q"; 1b }; -// gets the result for a given taskid, also allows results to live beyond the life of the primary +// gets the result path for a given taskid, also allows results to live beyond the life of the primary // fails if the task doesnt exist or has a null result -.primary.getresult:{[tid] +.primary.resultpath:{[tid] r:tasks tid; if[null r`state; '"no task ",string tid]; if[not `done~r`state; '"task ",string[tid]," is ",string r`state]; if[null r`resultpath; '"task ",string[tid]," has no result"]; - get r`resultpath + r`resultpath }; // splits a job up into individual tasks @@ -385,13 +385,12 @@ system"l src/common/cgroup.q"; .log.warn "job ",string[jid],": cancelled ",string[count qdtasks]," queued tasks"; }; -// the result files of a finished job's parts, in task order, for the caller to load and combine: -// raze get each .primary.jobpaths jid -// errors if the job doesn't exist or isn't done -.primary.getjobresult:{[jid] +// 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]; - raze .primary.getresult each exec taskid from tasks where jobid = jid, not null resultpath + exec resultpath from tasks where jobid = jid, not null resultpath }; // if a connection is close we need to mark it as closed diff --git a/tests/unit/jobs_spec.q b/tests/unit/jobs_spec.q index f40d80d..7786977 100644 --- a/tests/unit/jobs_spec.q +++ b/tests/unit/jobs_spec.q @@ -1,4 +1,4 @@ -/ unit specs for jobs: .primary.newjob, .primary.jobcheck (via taskupdate), .primary.canceljob and .primary.getjobresult +/ 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 @@ -183,7 +183,7 @@ if[not `primary in key `; system "l src/primary.q"]; }; }; -.tst.desc[".primary.getjobresult"]{ +.tst.desc[".primary.jobpaths"]{ before{ .ut.jbmocks[]; .ut.jbreset[]; @@ -191,34 +191,41 @@ if[not `primary in key `; system "l src/primary.q"]; after{ system "rm -rf ",.ut.jbdir; }; - should["combine the parts' results in task order, whatever order they finished in"]{ + 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 .primary.getjobresult j; + 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 .primary.getjobresult j; + ([] a:1 2 3 4) mustmatch raze get each .primary.jobpaths j; }; - should["skip parts that returned no result"]{ + should["leave out parts that returned no result"]{ j:.ut.jbnew 3; t:.ut.jbtids j; .ut.jbdone'[t; (1 2;::;3 4)]; - 1 2 3 4 mustmatch .primary.getjobresult j; + 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.getjobresult .ut.jbj}]; + 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.getjobresult .ut.jbj}]; + mustthrow[(); {[] .primary.jobpaths .ut.jbj}]; }; should["error for a job that doesn't exist"]{ - mustthrow[(); {[] .primary.getjobresult 99}]; + mustthrow[(); {[] .primary.jobpaths 99}]; }; }; \ No newline at end of file diff --git a/tests/unit/results_spec.q b/tests/unit/results_spec.q index b0c2fc1..8b3d169 100644 --- a/tests/unit/results_spec.q +++ b/tests/unit/results_spec.q @@ -1,4 +1,4 @@ -/ unit specs for .primary.getresult: loading a finished task's result from disk +/ unit specs for .primary.resultpath: where a finished task's result is saved / loads primary.q once (spawning off). A result is saved by hand in a temporary folder; no secondaries are / registered, so newtask only queues / run: tests/run.sh tests/unit/results_spec.q @@ -8,11 +8,11 @@ if[not `primary in key `; system "l src/primary.q"]; .ut.rddir:"/tmp/qfw-results-spec"; -/ an empty test folder and tasks table, then two tasks: .ut.rddone (done, result 45 saved as file 1) and .ut.rdqueued +/ an empty test folder and fresh tables, then two tasks: .ut.rddone (done, result 45 saved as a file) and .ut.rdqueued .ut.rdreset:{[] system "rm -rf ",.ut.rddir; system "mkdir -p ",.ut.rddir; - delete from `tasks; + system "l schemas/primarytables.q"; .primary.lasttaskid:0; `.ut.rddone set .primary.newtask `tasktype`args!(`sumtil;10); `.ut.rdqueued set .primary.newtask `tasktype`args!(`sumtil;10); @@ -21,7 +21,7 @@ if[not `primary in key `; system "l src/primary.q"]; update state:`done, resultpath:p, resultbytes:hcount p from `tasks where taskid=.ut.rddone; }; -.tst.desc[".primary.getresult"]{ +.tst.desc[".primary.resultpath"]{ before{ `.log.info mock {[x] ::}; `.log.warn mock {[x] ::}; @@ -32,22 +32,23 @@ if[not `primary in key `; system "l src/primary.q"]; after{ system "rm -rf ",.ut.rddir; }; - should["load a finished task's result"]{ - 45 musteq .primary.getresult .ut.rddone; + should["give the path of a finished task's result"]{ + (hsym `$.ut.rddir,"/",string .ut.rddone) musteq .primary.resultpath .ut.rddone; + 45 musteq get .primary.resultpath .ut.rddone; }; should["error for a task that isn't done"]{ - mustthrow[(); {[] .primary.getresult .ut.rdqueued}]; + mustthrow[(); {[] .primary.resultpath .ut.rdqueued}]; }; should["error for a task that doesn't exist"]{ - mustthrow[(); {[] .primary.getresult 99}]; + mustthrow[(); {[] .primary.resultpath 99}]; }; should["error for a done task with no result"]{ update resultpath:`, resultbytes:0N from `tasks where taskid=.ut.rddone; - mustthrow[(); {[] .primary.getresult .ut.rddone}]; + mustthrow[(); {[] .primary.resultpath .ut.rddone}]; }; - should["error when the result file has gone"]{ + should["give the path even when the file has gone, so get is what errors"]{ system "rm -f ",.ut.rddir,"/*"; - mustthrow[(); {[] .primary.getresult .ut.rddone}]; + mustnotthrow[(); {[] .primary.resultpath .ut.rddone}]; + mustthrow[(); {[] get .primary.resultpath .ut.rddone}]; }; - }; - + }; \ No newline at end of file From 9cebfa1a2d88b33a558e280ac82d6114386744c0 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Thu, 29 Oct 2026 09:48:18 +0000 Subject: [PATCH 34/49] bench-392: removing .primary.resultpath as not needed now --- README.md | 19 ++++++++++++++ src/primary.q | 10 -------- tests/unit/results_spec.q | 54 --------------------------------------- 3 files changed, 19 insertions(+), 64 deletions(-) delete mode 100644 tests/unit/results_spec.q diff --git a/README.md b/README.md index f33d630..fefb5c4 100644 --- a/README.md +++ b/README.md @@ -420,3 +420,22 @@ 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 and how to run jobs, start with cgroups +2. do a comparison between 8 secondaries and 8 threads for the same query + 1. show the mem used for a single job before and after +3. show a job failing with; + 1. timeout error + 2. oom + 3. retry +4. how to get results + +## 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, probably stick things in separate scripts where possible + + \ No newline at end of file diff --git a/src/primary.q b/src/primary.q index fa500ad..a05e14c 100644 --- a/src/primary.q +++ b/src/primary.q @@ -335,16 +335,6 @@ system"l src/common/cgroup.q"; 1b }; -// gets the result path for a given taskid, also allows results to live beyond the life of the primary -// fails if the task doesnt exist or has a null result -.primary.resultpath:{[tid] - r:tasks tid; - if[null r`state; '"no task ",string tid]; - if[not `done~r`state; '"task ",string[tid]," is ",string r`state]; - if[null r`resultpath; '"task ",string[tid]," has no result"]; - r`resultpath - }; - // splits a job up into individual tasks // .primary.newjob[`vwap; 2026.01.01 2026.01.02 2026.01.03] .primary.newjob:{[tasktype; args] diff --git a/tests/unit/results_spec.q b/tests/unit/results_spec.q deleted file mode 100644 index 8b3d169..0000000 --- a/tests/unit/results_spec.q +++ /dev/null @@ -1,54 +0,0 @@ -/ unit specs for .primary.resultpath: where a finished task's result is saved -/ loads primary.q once (spawning off). A result is saved by hand in a temporary folder; no secondaries are -/ registered, so newtask only queues -/ run: tests/run.sh tests/unit/results_spec.q - -setenv[`SPAWN_SECONDARY;enlist "0"]; -if[not `primary in key `; system "l src/primary.q"]; - -.ut.rddir:"/tmp/qfw-results-spec"; - -/ an empty test folder and fresh tables, then two tasks: .ut.rddone (done, result 45 saved as a file) and .ut.rdqueued -.ut.rdreset:{[] - system "rm -rf ",.ut.rddir; - system "mkdir -p ",.ut.rddir; - system "l schemas/primarytables.q"; - .primary.lasttaskid:0; - `.ut.rddone set .primary.newtask `tasktype`args!(`sumtil;10); - `.ut.rdqueued set .primary.newtask `tasktype`args!(`sumtil;10); - p:hsym `$.ut.rddir,"/",string .ut.rddone; - p set 45; - update state:`done, resultpath:p, resultbytes:hcount p from `tasks where taskid=.ut.rddone; - }; - -.tst.desc[".primary.resultpath"]{ - before{ - `.log.info mock {[x] ::}; - `.log.warn mock {[x] ::}; - `.primary.tasktypes mock `sumtil`sleep`fail; - `.primary.memcap mock 0N; - .ut.rdreset[]; - }; - after{ - system "rm -rf ",.ut.rddir; - }; - should["give the path of a finished task's result"]{ - (hsym `$.ut.rddir,"/",string .ut.rddone) musteq .primary.resultpath .ut.rddone; - 45 musteq get .primary.resultpath .ut.rddone; - }; - should["error for a task that isn't done"]{ - mustthrow[(); {[] .primary.resultpath .ut.rdqueued}]; - }; - should["error for a task that doesn't exist"]{ - mustthrow[(); {[] .primary.resultpath 99}]; - }; - should["error for a done task with no result"]{ - update resultpath:`, resultbytes:0N from `tasks where taskid=.ut.rddone; - mustthrow[(); {[] .primary.resultpath .ut.rddone}]; - }; - should["give the path even when the file has gone, so get is what errors"]{ - system "rm -f ",.ut.rddir,"/*"; - mustnotthrow[(); {[] .primary.resultpath .ut.rddone}]; - mustthrow[(); {[] get .primary.resultpath .ut.rddone}]; - }; - }; \ No newline at end of file From 896d1ac8b75e41167415e449c95da93628898cc7 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Thu, 29 Oct 2026 12:21:32 +0000 Subject: [PATCH 35/49] bench-322: adding memory after .Q.gc stats --- README.md | 2 +- schemas/primarytables.q | 7 +++---- src/primary.q | 11 +++++++---- src/secondary.q | 10 ++++++---- tests/unit/primarytests.q | 8 ++++++-- 5 files changed, 23 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index fefb5c4..a8f074f 100644 --- a/README.md +++ b/README.md @@ -436,6 +436,6 @@ killing it, and homer already uses a lot of swap. 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, probably stick things in separate scripts where possible +3. a tidy up of the code (mix of 4 and before dict usages), probably stick things in separate scripts where possible \ No newline at end of file diff --git a/schemas/primarytables.q b/schemas/primarytables.q index 3b3b1d2..be3729a 100644 --- a/schemas/primarytables.q +++ b/schemas/primarytables.q @@ -36,8 +36,9 @@ tasks : ([taskid: `long$()] dispatchedtime: `timestamp$(); startedtime: `timestamp$(); finishedtime: `timestamp$(); - membefore: `long$(); - memafter: `long$(); + membefore: `long$(); // RssAnon before running + memafter: `long$(); // peak during the task VmHWN + memaftergc: `long$(); // RssAnon after the task ends and .Q.gc err: (); reason: `$(); // `timeout`oom`error`lost`sendfailed resultpath: `$(); @@ -61,8 +62,6 @@ jobs : ([jobid: `long$()] state: `$(); submittedtime: `timestamp$(); finishedtime: `timestamp$(); - combinetask: `long$(); // taskid of the combine task, null until it is queued - resultpath: `$(); // the combined result, null until the job is done resultbytes: `long$(); err: () // why the job failed, "" when it hasn't ); \ No newline at end of file diff --git a/src/primary.q b/src/primary.q index a05e14c..cdc40fa 100644 --- a/src/primary.q +++ b/src/primary.q @@ -183,7 +183,7 @@ system"l src/common/cgroup.q"; 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; err:""; reason:`; resultpath:`; resultbytes:0N]); + finishedtime:0Np; membefore:0N; memafter:0N; memaftergc:0N; err:""; reason:`; resultpath:`; resultbytes:0N]); `tasks upsert data; .log.info "new task ",string[tid]," ",string task`tasktype; tid @@ -251,7 +251,7 @@ system"l src/common/cgroup.q"; .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; err:""; reason:`])]; + .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 @@ -340,10 +340,13 @@ system"l src/common/cgroup.q"; .primary.newjob:{[tasktype; args] if[not tasktype in .primary.tasktypes; '"unknown task type ",string tasktype]; if[not count args; '"no args: a job needs at least one task"]; + ids:.primary.newtask each {([tasktype: x; args: y])}[tasktype] 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; - ids:.primary.newtask each {([tasktype: x; args: y])}[tasktype] each args; // maybe change the name of the variable to taskt ? update jobid:jid from `tasks where taskid in ids; - `jobs upsert (jid; tasktype; `int$count ids; `running; .z.P; 0Np; 0N; `; 0N; ""); + `jobs upsert (jid; tasktype; `int$count ids; `running; .z.P; 0Np; 0N; ""); .log.info "new job ",string[jid],": ",string[count ids]," ",string[tasktype]," tasks (",string[first ids],"..",string[last ids],")"; jid }; diff --git a/src/secondary.q b/src/secondary.q index d3b7643..d5bbf1d 100644 --- a/src/secondary.q +++ b/src/secondary.q @@ -58,7 +58,7 @@ if[count .secondary.hdb:getenv `HDB_DIR; // send an async message to the primary and flush it straight away .secondary.send:{[msg] neg[.secondary.handle] msg; neg[.secondary.handle][]}; -// sec tells pri 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 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 @@ -69,16 +69,18 @@ if[count .secondary.hdb:getenv `HDB_DIR; memafter:first exec vmhwm from .mem.read enlist .z.i; if[`failure ~ first res; .Q.gc[]; + memaftergc:first exec rssanon from .mem.read enlist .z.i; .log.warn "task ",string[tid],", failed with error: ",last res; - :.secondary.send (`.primary.taskupdate; tid; `failed; `err`reason`membefore`memafter!(last res; `error; membefore; memafter))]; + :.secondary.send (`.primary.taskupdate; tid; `failed; `err`reason`membefore`memafter`memaftergc!(last res; `error; membefore; memafter; memaftergc))]; saved:.secondary.save[tid; res]; res:(::); .Q.gc[]; + memaftergc:first exec rssanon from .mem.read enlist .z.i; if[`failure ~ first saved; .log.warn "task ",string[tid],", could not save its result: ",last saved; - :.secondary.send (`.primary.taskupdate; tid; `failed; `err`reason`membefore`memafter!("could not save the result: ",last saved; `savefailed; membefore; memafter))]; + :.secondary.send (`.primary.taskupdate; tid; `failed; `err`reason`membefore`memafter`memaftergc!("could not save the result: ",last saved; `savefailed; membefore; memafter; memaftergc))]; .log.info "task ",string[tid]," is complete, result saved to ",string first saved; - .secondary.send (`.primary.taskupdate; tid; `done; `resultpath`resultbytes`membefore`memafter!(first saved; last saved; membefore; memafter)); + .secondary.send (`.primary.taskupdate; tid; `done; `resultpath`resultbytes`membefore`memafter`memaftergc!(first saved; last saved; membefore; memafter; memaftergc)); }; // save a tasks result, returns path and bytes, doesnt save if a null is the result diff --git a/tests/unit/primarytests.q b/tests/unit/primarytests.q index 9ace95b..c10d9a7 100644 --- a/tests/unit/primarytests.q +++ b/tests/unit/primarytests.q @@ -20,13 +20,17 @@ if[not `primary in key `; system "l src/primary.q"]; "jiisispjibbpp 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`err`reason`resultpath`resultbytes`jobid) mustmatch cols tasks; - "js ipjtiisjpppjj ssjj" mustmatch exec t from meta tasks; + (`taskid`tasktype`args`priority`submittedtime`memestimate`timeout`retriesmax`retrycount`state`secondaryid`dispatchedtime`startedtime`finishedtime`membefore`memafter`memaftergc`err`reason`resultpath`resultbytes`jobid) mustmatch cols tasks; + "js ipjtiisjpppjjj ssjj" 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`ntasks`state`submittedtime`finishedtime`resultbytes`err) mustmatch cols jobs; + "jsisppj " mustmatch exec t from meta jobs; + }; }; .tst.desc["can a secondary register with .primary.register"]{ From 74e5050a8e0283f16db1c2f3de88b9fb40f0ffce Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Mon, 2 Nov 2026 12:08:31 +0000 Subject: [PATCH 36/49] bench-393: demo prep --- README.md | 191 ++++++++++++++++++++++++++++++++++++-- config/default.env | 6 +- schemas/primarytables.q | 1 + src/primary.q | 16 +++- tests/unit/jobs_spec.q | 82 ++++++++++++++-- tests/unit/primarytests.q | 4 +- 6 files changed, 275 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index a8f074f..e583962 100644 --- a/README.md +++ b/README.md @@ -423,19 +423,194 @@ killing it, and homer already uses a lot of swap. # Demo -1. show how to start and how to run jobs, start with cgroups +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 - 1. show the mem used for a single job before and after -3. show a job failing with; - 1. timeout error - 2. oom - 3. retry -4. how to get results +```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 +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/config/default.env b/config/default.env index bfdbc7c..d52df92 100644 --- a/config/default.env +++ b/config/default.env @@ -2,8 +2,8 @@ KDBX_HOME=/opt/kdbx/5.0/2026.07.23 # process info -PRIMARY_PORT=45000 -SECONDARY_BASE_PORT=45001 +PRIMARY_PORT=55000 +SECONDARY_BASE_PORT=55001 # 4GB currently for testing, need to run on 30GB eventually GLOBAL_MEM_LIMIT=4294967296 @@ -19,7 +19,7 @@ STOP_GRACE_PERIOD_SECS=5 LOG_DIR=logs # for tasks -TASK_TIMEOUT_MS=60000 +TASK_TIMEOUT_MS=60000 # 60 seconds timeout TASK_RETRIES_MAX=3 TASK_TYPES=sleep,sumtil,fail,vwap,hold RETRY_REASONS=lost,sendfailed diff --git a/schemas/primarytables.q b/schemas/primarytables.q index be3729a..38358ac 100644 --- a/schemas/primarytables.q +++ b/schemas/primarytables.q @@ -59,6 +59,7 @@ memhistory : ([] jobs : ([jobid: `long$()] tasktype: `$(); ntasks: `int$(); + priority: `int$(); state: `$(); submittedtime: `timestamp$(); finishedtime: `timestamp$(); diff --git a/src/primary.q b/src/primary.q index cdc40fa..25d54fd 100644 --- a/src/primary.q +++ b/src/primary.q @@ -335,19 +335,25 @@ system"l src/common/cgroup.q"; 1b }; +.primary.taskdefaults:([priority:0i; memestimate: 0N; timeout: .primary.tasktimeout; retriesmax: .primary.taskretries]); // splits a job up into individual tasks -// .primary.newjob[`vwap; 2026.01.01 2026.01.02 2026.01.03] -.primary.newjob:{[tasktype; args] +// .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"]; - ids:.primary.newtask each {([tasktype: x; args: y])}[tasktype] each args; + if[not all key[params] in key .primary.taskdefaults; '"optional parasm are: ",", " sv string key .primary.taskdefaults]; + params:@[.primary.taskdefaults, params; `priority`retriesmax; `int$]; + 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 from `tasks where taskid in ids; - `jobs upsert (jid; tasktype; `int$count ids; `running; .z.P; 0Np; 0N; ""); - .log.info "new job ",string[jid],": ",string[count ids]," ",string[tasktype]," tasks (",string[first ids],"..",string[last ids],")"; + pri:params`priority; + `jobs upsert (jid; tasktype; `int$count ids; pri; `running; .z.P; 0Np; 0N; ""); + .log.info "new job ",string[jid],": ",string[count ids]," ",string[tasktype]," tasks (",string[first ids],"..",string[last ids],"), priority ",string pri; + .primary.dispatch[]; jid }; diff --git a/tests/unit/jobs_spec.q b/tests/unit/jobs_spec.q index 7786977..2b5145f 100644 --- a/tests/unit/jobs_spec.q +++ b/tests/unit/jobs_spec.q @@ -18,7 +18,7 @@ if[not `primary in key `; system "l src/primary.q"]; / 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]; + j:.primary.newjob[`sumtil; 10*1+til n; ()!()]; update retriesmax:3i from `tasks where jobid=j; j }; @@ -66,29 +66,29 @@ if[not `primary in key `; system "l src/primary.q"]; system "rm -rf ",.ut.jbdir; }; should["create one task per arg, all with the job's id"]{ - j:.primary.newjob[`sumtil; 10 20 30]; + 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]; + 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]; + 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; + 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]}]; + 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; ()]}]; + mustthrow[(); {[] .primary.newjob[`sumtil; (); ()!()]}]; 0 musteq count jobs; 0 musteq count tasks; }; @@ -228,4 +228,72 @@ if[not `primary in key `; system "l src/primary.q"]; 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; + }; }; \ No newline at end of file diff --git a/tests/unit/primarytests.q b/tests/unit/primarytests.q index c10d9a7..0d205e3 100644 --- a/tests/unit/primarytests.q +++ b/tests/unit/primarytests.q @@ -28,8 +28,8 @@ if[not `primary in key `; system "l src/primary.q"]; "pjjji" mustmatch exec t from meta memhistory; }; should["have the correct schema for the jobs table"]{ - (`jobid`tasktype`ntasks`state`submittedtime`finishedtime`resultbytes`err) mustmatch cols jobs; - "jsisppj " mustmatch exec t from meta jobs; + (`jobid`tasktype`ntasks`priority`state`submittedtime`finishedtime`resultbytes`err) mustmatch cols jobs; + "jsiisppj " mustmatch exec t from meta jobs; }; }; From a45bacde6bbab3d0efabef6a6c497d996e5cee7e Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Mon, 2 Nov 2026 14:50:40 +0000 Subject: [PATCH 37/49] bench-400: can only connect to the secondaries via the primary and adding user col --- README.md | 2 +- config/default.env | 3 +-- config/integration.env | 1 - schemas/primarytables.q | 4 +++- src/primary.q | 14 +++++------ src/secondary.q | 2 +- tests/integration.sh | 34 +++++++++++++++++---------- tests/integration/registration_spec.q | 5 ++-- tests/unit/jobs_spec.q | 9 +++++++ tests/unit/primarytests.q | 8 +++---- 10 files changed, 50 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index e583962..79a36e2 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ x src/primary.q -p 45000 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 take the port number `PRIMARY_PORT` + `id` so `secondary 1` would have a port of `45001` and so on. A secondary cannot start if the primary process is not up. +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`. diff --git a/config/default.env b/config/default.env index d52df92..b327700 100644 --- a/config/default.env +++ b/config/default.env @@ -2,8 +2,7 @@ KDBX_HOME=/opt/kdbx/5.0/2026.07.23 # process info -PRIMARY_PORT=55000 -SECONDARY_BASE_PORT=55001 +PRIMARY_PORT=45000 # 4GB currently for testing, need to run on 30GB eventually GLOBAL_MEM_LIMIT=4294967296 diff --git a/config/integration.env b/config/integration.env index 96811e1..8a536da 100644 --- a/config/integration.env +++ b/config/integration.env @@ -1,7 +1,6 @@ # 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 -SECONDARY_BASE_PORT=46001 NUM_SECONDARYS=2 SPAWN_SECONDARY=1 STOP_GRACE_PERIOD_SECS=1 diff --git a/schemas/primarytables.q b/schemas/primarytables.q index 38358ac..1a941de 100644 --- a/schemas/primarytables.q +++ b/schemas/primarytables.q @@ -43,7 +43,8 @@ tasks : ([taskid: `long$()] reason: `$(); // `timeout`oom`error`lost`sendfailed resultpath: `$(); resultbytes: `long$(); - jobid: `long$() + jobid: `long$(); + user: `$() ); // one row per memory poll, bounded to the last .primary.memhistorymax rows @@ -58,6 +59,7 @@ memhistory : ([] // 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: `$(); diff --git a/src/primary.q b/src/primary.q index 25d54fd..3511c35 100644 --- a/src/primary.q +++ b/src/primary.q @@ -115,10 +115,10 @@ system"l src/common/cgroup.q"; -1 "tasks: ",fmt pristatus`taskcounts; }; -// command line for secondary n, e.g. /opt/kdbx/.../q src/secondary.q -p 45002 -id 2 +// 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"; "-p"; string .primary.baseport+n-1; "-id"; string 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 @@ -145,7 +145,7 @@ system"l src/common/cgroup.q"; pid:"I"$first system startcmd; .log.info "running system command: ", startcmd; .primary.spawned[n]:pid; - .log.info "spawned secondary ",string[n]," (pid ",string[pid],") on port ",string .primary.baseport+n-1; + .log.info "spawned secondary ",string[n]," (pid ",string[pid],")"; }; // used to shut down all spawned secondaries @@ -183,7 +183,7 @@ system"l src/common/cgroup.q"; 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]); + finishedtime:0Np; membefore:0N; memafter:0N; memaftergc:0N; err:""; reason:`; resultpath:`; resultbytes:0N; jobid:0N; user:`]); `tasks upsert data; .log.info "new task ",string[tid]," ",string task`tasktype; tid @@ -349,10 +349,10 @@ system"l src/common/cgroup.q"; 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 from `tasks where taskid in ids; + update jobid:jid, user:.z.u from `tasks where taskid in ids; pri:params`priority; - `jobs upsert (jid; tasktype; `int$count ids; pri; `running; .z.P; 0Np; 0N; ""); - .log.info "new job ",string[jid],": ",string[count ids]," ",string[tasktype]," tasks (",string[first ids],"..",string[last ids],"), priority ",string pri; + `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 }; diff --git a/src/secondary.q b/src/secondary.q index d5bbf1d..1af2b27 100644 --- a/src/secondary.q +++ b/src/secondary.q @@ -1,6 +1,6 @@ // this is a secondary process: it runs tasks the master 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 diff --git a/tests/integration.sh b/tests/integration.sh index b413f38..a6c1de8 100755 --- a/tests/integration.sh +++ b/tests/integration.sh @@ -21,25 +21,33 @@ FILTER="${1:-}" mkdir -p "$LOG_DIR" PRIMARYPID="" -# kill the primary and any secondary on the test ports (46001 -> "4600", so 46000-46009 only) +# 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; fi - pkill -9 -f "src/secondary.q -p ${SECONDARY_BASE_PORT%?}" 2>/dev/null || true + 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 ports +# refuse to start if something is already on the test primary's port (secondaries don't listen) portsfree() { - local p - for p in $(seq "$PRIMARY_PORT" $((SECONDARY_BASE_PORT + NUM_SECONDARYS + 1))); do - if (exec 3<>"/dev/tcp/localhost/$p") 2>/dev/null; then - echo "port $p is already in use; kill whatever is on it (ss -ltnp | grep $p) and rerun" >&2 - return 1 - fi - done + 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 @@ -67,10 +75,10 @@ for spec in tests/integration/*_spec.q; do 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 ports free up before the next cluster + 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 +exit $rc \ No newline at end of file diff --git a/tests/integration/registration_spec.q b/tests/integration/registration_spec.q index 6c685c5..11eceb3 100644 --- a/tests/integration/registration_spec.q +++ b/tests/integration/registration_spec.q @@ -6,12 +6,13 @@ system "l tests/helpers/it.q"; should["have every spawned secondary register as free"]{ 1b musteq .it.ready[]; }; - should["mark them as spawned, each with its own handle and port"]{ + should["mark them as spawned, each with its own handle and no port"]{ 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; - (exec port from t) mustmatch `int$("J"$getenv`SECONDARY_BASE_PORT)+(exec id from t)-1; + / secondaries don't listen: nothing can connect to them, the primary uses the connection they opened + (count[t]#0i) mustmatch exec port from t; }; should["record a pid for each that is a running process"]{ 1b musteq all .it.alive each exec pid from .it.sec[]; diff --git a/tests/unit/jobs_spec.q b/tests/unit/jobs_spec.q index 2b5145f..ef737a0 100644 --- a/tests/unit/jobs_spec.q +++ b/tests/unit/jobs_spec.q @@ -92,6 +92,15 @@ if[not `primary in key `; system "l src/primary.q"]; 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"]{ diff --git a/tests/unit/primarytests.q b/tests/unit/primarytests.q index 0d205e3..eb98f13 100644 --- a/tests/unit/primarytests.q +++ b/tests/unit/primarytests.q @@ -20,16 +20,16 @@ if[not `primary in key `; system "l src/primary.q"]; "jiisispjibbpp 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) mustmatch cols tasks; - "js ipjtiisjpppjjj ssjj" mustmatch exec t from meta tasks; + (`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`ntasks`priority`state`submittedtime`finishedtime`resultbytes`err) mustmatch cols jobs; - "jsiisppj " mustmatch exec t from meta jobs; + (`jobid`tasktype`user`ntasks`priority`state`submittedtime`finishedtime`resultbytes`err) mustmatch cols jobs; + "jssiisppj " mustmatch exec t from meta jobs; }; }; From ee4eb303309cf7f14097427031ab8433c7dedf69 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Tue, 3 Nov 2026 15:29:25 +0000 Subject: [PATCH 38/49] bench-401: job estimation functionality --- schemas/primarytables.q | 2 +- src/primary.q | 57 ++++++++++++++++++++++- tests/unit/jobs_spec.q | 101 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 157 insertions(+), 3 deletions(-) diff --git a/schemas/primarytables.q b/schemas/primarytables.q index 1a941de..3870583 100644 --- a/schemas/primarytables.q +++ b/schemas/primarytables.q @@ -37,7 +37,7 @@ tasks : ([taskid: `long$()] startedtime: `timestamp$(); finishedtime: `timestamp$(); membefore: `long$(); // RssAnon before running - memafter: `long$(); // peak during the task VmHWN + 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`oom`error`lost`sendfailed diff --git a/src/primary.q b/src/primary.q index 3511c35..f322188 100644 --- a/src/primary.q +++ b/src/primary.q @@ -335,7 +335,6 @@ system"l src/common/cgroup.q"; 1b }; -.primary.taskdefaults:([priority:0i; memestimate: 0N; timeout: .primary.tasktimeout; retriesmax: .primary.taskretries]); // 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; ()!()] @@ -344,6 +343,11 @@ system"l src/common/cgroup.q"; 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; @@ -392,6 +396,55 @@ system"l src/common/cgroup.q"; 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])]]; + + ([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] @@ -402,7 +455,7 @@ system"l src/common/cgroup.q"; 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]); ([err:"secondary lost"; reason:`lost])]; + 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; diff --git a/tests/unit/jobs_spec.q b/tests/unit/jobs_spec.q index ef737a0..f82887f 100644 --- a/tests/unit/jobs_spec.q +++ b/tests/unit/jobs_spec.q @@ -305,4 +305,105 @@ if[not `primary in key `; system "l src/primary.q"]; 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; + }; + }; + +.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; + }; }; \ No newline at end of file From 62506bf1b04fe8d708f990c85d0366654796c5ae Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Tue, 3 Nov 2026 15:55:05 +0000 Subject: [PATCH 39/49] bench-401: changed mem cap comparison to be anything killed with oom cap --- src/primary.q | 5 +++++ tests/unit/jobs_spec.q | 9 ++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/primary.q b/src/primary.q index f322188..354c27c 100644 --- a/src/primary.q +++ b/src/primary.q @@ -442,6 +442,11 @@ system"l src/common/cgroup.q"; " 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:""]) }; diff --git a/tests/unit/jobs_spec.q b/tests/unit/jobs_spec.q index f82887f..cfa4ff9 100644 --- a/tests/unit/jobs_spec.q +++ b/tests/unit/jobs_spec.q @@ -380,6 +380,12 @@ if[not `primary in key `; system "l src/primary.q"]; 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"]{ @@ -406,4 +412,5 @@ if[not `primary in key `; system "l src/primary.q"]; j:.primary.newjob[`sumtil; 30 40; ([memestimate:5*.ut.esmb])]; 1b musteq all (5*.ut.esmb)=exec memestimate from tasks where jobid=j; }; - }; \ No newline at end of file + }; + From 6709556115cbbed2a3d807bc6b307021046ee131 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Tue, 3 Nov 2026 16:13:59 +0000 Subject: [PATCH 40/49] bench-401: now only send tasks whose memory estimate fits under the cap --- src/primary.q | 39 ++++++++++++- tests/unit/fit_spec.q | 125 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 161 insertions(+), 3 deletions(-) create mode 100644 tests/unit/fit_spec.q diff --git a/src/primary.q b/src/primary.q index 354c27c..97d2c87 100644 --- a/src/primary.q +++ b/src/primary.q @@ -230,16 +230,49 @@ system"l src/common/cgroup.q"; .log.info "sent task ",string[tid]," to secondary ",string[sid]," to run task ",string t`tasktype; }; +// 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 +.primary.fit:{[qtasks; n] + if[null .primary.memcap; :n sublist qtasks]; + headroom:.primary.memcap-.primary.committedmem[]; + taskest:0^(exec taskid!memestimate from tasks) qtasks; + // nothing running: send the first task whatever its estimate, so it can't wait for ever on the secondaries' + // own baseline memory + if[not count select from secondaries where status=`busy; headroom:headroom|first taskest]; + // the headroom left after each task: one that fits uses up its estimate, one that doesn't leaves it unchanged + left:headroom {[room;est] $[est<=room; room-est; room]}\ taskest; + // a task fits if its estimate is within what was left before it + fits:taskest<=headroom,-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; - n:min count[freesec], count qtasks; - if[n=0; :()]; + 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]; }; @@ -446,7 +479,7 @@ system"l src/common/cgroup.q"; // (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:""]) }; diff --git a/tests/unit/fit_spec.q b/tests/unit/fit_spec.q new file mode 100644 index 0000000..42c50ff --- /dev/null +++ b/tests/unit/fit_spec.q @@ -0,0 +1,125 @@ +/ 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 +/ 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, 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}]; + `.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; + }; + }; + +.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 From dbe4f417280615f1a130d8bb9594f9e5ab0229ad Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Tue, 3 Nov 2026 16:45:28 +0000 Subject: [PATCH 41/49] bench-401: primary checks secondarys memory once a task is complete --- src/primary.q | 7 ++++++- tests/unit/fit_spec.q | 13 +++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/primary.q b/src/primary.q index 97d2c87..7e326bd 100644 --- a/src/primary.q +++ b/src/primary.q @@ -207,7 +207,12 @@ system"l src/common/cgroup.q"; .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]; + 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 thi diff --git a/tests/unit/fit_spec.q b/tests/unit/fit_spec.q index 42c50ff..89cd33a 100644 --- a/tests/unit/fit_spec.q +++ b/tests/unit/fit_spec.q @@ -94,6 +94,19 @@ if[not `primary in key `; system "l src/primary.q"]; .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.committedmem"]{ From c4ebada07d791efb96c7b92e8311f55f73a2087d Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Wed, 4 Nov 2026 10:16:20 +0000 Subject: [PATCH 42/49] bench-300: todying up --- schemas/primarytables.q | 1 - src/primary.q | 14 ++++++-------- src/secondary.q | 2 +- tests/integration/registration_spec.q | 4 +--- tests/unit/primarytests.q | 6 +++--- tests/unit/status_spec.q | 2 +- 6 files changed, 12 insertions(+), 17 deletions(-) diff --git a/schemas/primarytables.q b/schemas/primarytables.q index 3870583..e688e5f 100644 --- a/schemas/primarytables.q +++ b/schemas/primarytables.q @@ -5,7 +5,6 @@ secondaries : ([id: `long$()] handle: `int$(); pid: `int$(); host: `$(); - port: `int$(); status: `$(); // `free`busy`stale`closed lastheartbeat: `timestamp$(); lastmembytes: `long$(); diff --git a/src/primary.q b/src/primary.q index 7e326bd..597193b 100644 --- a/src/primary.q +++ b/src/primary.q @@ -19,7 +19,6 @@ system"l src/common/cgroup.q"; .primary.heartbeat:00:00:00.001*"J"$getenv`HEARTBEAT_MS; .primary.spawnsecondaries:"B"$getenv`SPAWN_SECONDARY; .primary.numsecondaries:"J"$getenv`NUM_SECONDARYS; -.primary.baseport:"J"$getenv`SECONDARY_BASE_PORT; .primary.stopgraceperiod:"J"$getenv`STOP_GRACE_PERIOD_SECS; .primary.logdir:getenv`LOG_DIR; .primary.qbin:getenv[`KDBX_HOME],"/bin/q"; @@ -61,9 +60,9 @@ system"l src/common/cgroup.q"; // when a secondary starts add it to the secondaries table // example run: -// .primary.register ([id:5; pid:4000i; host:`localhost; port:45001i ]) +// .primary.register ([id:5; pid:4000i; host:`localhost]) .primary.register:{[info] - `secondaries upsert (info`id; .z.w; info`pid; info`host; info`port; `free; .z.P; 0N; 0Ni; 1b; info[`id] in key .primary.spawned; .z.P; .z.P; (); 0N; 0N; 0N; 0Np); + `secondaries upsert (info`id; .z.w; info`pid; info`host; `free; .z.P; 0N; 0Ni; 1b; info[`id] in key .primary.spawned; .z.P; .z.P; (); 0N; 0N; 0N; 0Np); .log.info "secondary ", string[info`id], " registered at: ", string .z.P; .primary.resultsdir }; @@ -93,7 +92,7 @@ system"l src/common/cgroup.q"; // a snapshot of the primarys status // memory is in bytes headroom how far under the cap we are .primary.status:{ - secs:select id, pid, port, status, spawned, currenttask, rssanon, restarts:0^.primary.respawns id, lastseen:`time$.z.P-lastheartbeat, lastmembytes from 0!secondaries; + secs:select id, pid, status, spawned, currenttask, rssanon, restarts:0^.primary.respawns id, lastseen:`time$.z.P-lastheartbeat, lastmembytes 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]; @@ -111,7 +110,7 @@ system"l src/common/cgroup.q"; 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, port, status, spawned, task:currenttask, memmb:0.1*floor 0.5+10*rssanon%1048576, restarts, lastseen from pristatus`secondaries; + 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; }; @@ -185,7 +184,7 @@ system"l src/common/cgroup.q"; ([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.info "new task ",string[tid]," ",string task`tasktype; + .log.debug "new task ",string[tid]," ",string task`tasktype; tid }; @@ -202,7 +201,6 @@ system"l src/common/cgroup.q"; :0b]; timecol: $[newstate in key .primary.statustime; (enlist .primary.statustime newstate)!enlist .z.P; ()!()]; params: params, timecol, ([taskid: tid; state: newstate]); - .log.info "updating task id ",string[tid]," from ",string[oldstate]," to ",string newstate; upsert[`tasks; params]; .log.info "updated task id ",string[tid]," from ",string[oldstate]," to ",string newstate; if[newstate in `done`failed; @@ -232,7 +230,7 @@ system"l src/common/cgroup.q"; 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]," to secondary ",string[sid]," to run task ",string t`tasktype; + .log.info "sent task ",string[tid]," (",string[t`tasktype],") to secondary ",string sid; }; // Claude diff --git a/src/secondary.q b/src/secondary.q index 1af2b27..54dab09 100644 --- a/src/secondary.q +++ b/src/secondary.q @@ -19,7 +19,7 @@ if[count .secondary.hdb:getenv `HDB_DIR; // get the id form start cmd .secondary.opts: .Q.opt .z.x; .secondary.id: "J"$first .secondary.opts`id; -.secondary.info:([id: .secondary.id; pid: .z.i; host: .z.h; port: system"p"]); +.secondary.info:([id: .secondary.id; pid: .z.i; host: .z.h]); // used to connect and register with primary .secondary.connect:{ diff --git a/tests/integration/registration_spec.q b/tests/integration/registration_spec.q index 11eceb3..5df9ce0 100644 --- a/tests/integration/registration_spec.q +++ b/tests/integration/registration_spec.q @@ -6,13 +6,11 @@ system "l tests/helpers/it.q"; should["have every spawned secondary register as free"]{ 1b musteq .it.ready[]; }; - should["mark them as spawned, each with its own handle and no port"]{ + 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; - / secondaries don't listen: nothing can connect to them, the primary uses the connection they opened - (count[t]#0i) mustmatch exec port from t; }; should["record a pid for each that is a running process"]{ 1b musteq all .it.alive each exec pid from .it.sec[]; diff --git a/tests/unit/primarytests.q b/tests/unit/primarytests.q index eb98f13..9124764 100644 --- a/tests/unit/primarytests.q +++ b/tests/unit/primarytests.q @@ -16,8 +16,8 @@ if[not `primary in key `; system "l src/primary.q"]; system "l schemas/primarytables.q"; }; should["have the correct schema for secondaries table"]{ - (`id`handle`pid`host`port`status`lastheartbeat`lastmembytes`consecutivefails`healthy`spawned`starttime`registeredtime`tasktypes`currenttask`rssanon`vmrss`memtime) mustmatch cols secondaries; - "jiisispjibbpp jjjp" mustmatch exec t from meta secondaries; + (`id`handle`pid`host`status`lastheartbeat`lastmembytes`consecutivefails`healthy`spawned`starttime`registeredtime`tasktypes`currenttask`rssanon`vmrss`memtime) mustmatch cols secondaries; + "jiisspjibbpp 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; @@ -37,7 +37,7 @@ if[not `primary in key `; system "l src/primary.q"]; before{ `.log.warn mock {}; `.log.info mock {}; - .primary.register ([id:1; pid:4000i; host:`localhost; port:45001i ]); + .primary.register ([id:1; pid:4000i; host:`localhost]); }; should["have 1 secondary present"]{ 1 musteq count secondaries; diff --git a/tests/unit/status_spec.q b/tests/unit/status_spec.q index c3781d9..582c02f 100644 --- a/tests/unit/status_spec.q +++ b/tests/unit/status_spec.q @@ -65,7 +65,7 @@ .ut.reg each 1 2; t:.primary.status[]`secondaries; 2 musteq count t; - `id`pid`port`status`spawned`currenttask`rssanon`restarts`lastseen`lastmembytes mustmatch cols t; + `id`pid`status`spawned`currenttask`rssanon`restarts`lastseen`lastmembytes mustmatch cols t; }; should["show a just-registered secondary as seen moments ago"]{ .ut.reg 1; From 644663b75e8fdd9be93a723d786d1e7e87d4ef06 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Wed, 4 Nov 2026 10:56:15 +0000 Subject: [PATCH 43/49] bench-300 tidy up of memory tracking --- schemas/primarytables.q | 1 - src/primary.q | 6 +++--- src/secondary.q | 11 +++++++---- tests/unit/primarytests.q | 6 +++--- tests/unit/status_spec.q | 2 +- 5 files changed, 14 insertions(+), 12 deletions(-) diff --git a/schemas/primarytables.q b/schemas/primarytables.q index e688e5f..15066cd 100644 --- a/schemas/primarytables.q +++ b/schemas/primarytables.q @@ -7,7 +7,6 @@ secondaries : ([id: `long$()] host: `$(); status: `$(); // `free`busy`stale`closed lastheartbeat: `timestamp$(); - lastmembytes: `long$(); consecutivefails: `int$(); healthy: `boolean$(); spawned: `boolean$(); // if the primary created it or it was up from before diff --git a/src/primary.q b/src/primary.q index 597193b..fbb7888 100644 --- a/src/primary.q +++ b/src/primary.q @@ -62,7 +62,7 @@ system"l src/common/cgroup.q"; // example run: // .primary.register ([id:5; pid:4000i; host:`localhost]) .primary.register:{[info] - `secondaries upsert (info`id; .z.w; info`pid; info`host; `free; .z.P; 0N; 0Ni; 1b; info[`id] in key .primary.spawned; .z.P; .z.P; (); 0N; 0N; 0N; 0Np); + `secondaries upsert (info`id; .z.w; info`pid; info`host; `free; .z.P; 0Ni; 1b; info[`id] in key .primary.spawned; .z.P; .z.P; (); 0N; 0N; 0N; 0Np); .log.info "secondary ", string[info`id], " registered at: ", string .z.P; .primary.resultsdir }; @@ -72,7 +72,7 @@ system"l src/common/cgroup.q"; // before a task arrived can be processed after dispatch has marked it busy .primary.heartbeatcheck:{[mem] - update lastheartbeat:.z.P, lastmembytes: mem from `secondaries where handle=.z.w; + update lastheartbeat:.z.P, rssanon: mem from `secondaries where handle=.z.w; update status:`free from `secondaries where handle=.z.w, status=`stale; }; @@ -92,7 +92,7 @@ system"l src/common/cgroup.q"; // 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, lastmembytes from 0!secondaries; + 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]; diff --git a/src/secondary.q b/src/secondary.q index 54dab09..5ef965a 100644 --- a/src/secondary.q +++ b/src/secondary.q @@ -1,4 +1,4 @@ -// 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 -id 1 @@ -29,9 +29,12 @@ if[count .secondary.hdb:getenv `HDB_DIR; 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; .Q.w[]`used); + neg[.secondary.handle](`.primary.heartbeatcheck; .secondary.rssanon[]); }; // called by the primary to kill spawned secondaries @@ -69,13 +72,13 @@ if[count .secondary.hdb:getenv `HDB_DIR; memafter:first exec vmhwm from .mem.read enlist .z.i; if[`failure ~ first res; .Q.gc[]; - memaftergc:first exec rssanon from .mem.read enlist .z.i; + memaftergc:.secondary.rssanon[]; .log.warn "task ",string[tid],", failed with error: ",last res; :.secondary.send (`.primary.taskupdate; tid; `failed; `err`reason`membefore`memafter`memaftergc!(last res; `error; membefore; memafter; memaftergc))]; saved:.secondary.save[tid; res]; res:(::); .Q.gc[]; - memaftergc:first exec rssanon from .mem.read enlist .z.i; + 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`reason`membefore`memafter`memaftergc!("could not save the result: ",last saved; `savefailed; membefore; memafter; memaftergc))]; diff --git a/tests/unit/primarytests.q b/tests/unit/primarytests.q index 9124764..feaffe8 100644 --- a/tests/unit/primarytests.q +++ b/tests/unit/primarytests.q @@ -16,8 +16,8 @@ if[not `primary in key `; system "l src/primary.q"]; system "l schemas/primarytables.q"; }; should["have the correct schema for secondaries table"]{ - (`id`handle`pid`host`status`lastheartbeat`lastmembytes`consecutivefails`healthy`spawned`starttime`registeredtime`tasktypes`currenttask`rssanon`vmrss`memtime) mustmatch cols secondaries; - "jiisspjibbpp jjjp" mustmatch exec t from meta secondaries; + (`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; @@ -71,7 +71,7 @@ if[not `primary in key `; system "l src/primary.q"]; `free musteq first exec status from secondaries where id = 1; }; should["have memory as 100"]{ - 100 musteq first exec lastmembytes from secondaries where id = 1; + 100 musteq first exec rssanon from secondaries where id = 1; }; }; diff --git a/tests/unit/status_spec.q b/tests/unit/status_spec.q index 582c02f..79f9916 100644 --- a/tests/unit/status_spec.q +++ b/tests/unit/status_spec.q @@ -65,7 +65,7 @@ .ut.reg each 1 2; t:.primary.status[]`secondaries; 2 musteq count t; - `id`pid`status`spawned`currenttask`rssanon`restarts`lastseen`lastmembytes mustmatch cols 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; From 6b223e844a9e097bb7cca6b14d552c76e956de09 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Wed, 4 Nov 2026 11:00:25 +0000 Subject: [PATCH 44/49] bench-300 tidy up of memory tracking --- src/primary.q | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/primary.q b/src/primary.q index fbb7888..723f395 100644 --- a/src/primary.q +++ b/src/primary.q @@ -62,7 +62,9 @@ system"l src/common/cgroup.q"; // example run: // .primary.register ([id:5; pid:4000i; host:`localhost]) .primary.register:{[info] - `secondaries upsert (info`id; .z.w; info`pid; info`host; `free; .z.P; 0Ni; 1b; info[`id] in key .primary.spawned; .z.P; .z.P; (); 0N; 0N; 0N; 0Np); + `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 }; From eac1588c9e3442f8cf3202fe0535d2acc235c839 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Wed, 4 Nov 2026 11:11:10 +0000 Subject: [PATCH 45/49] bench-300 consistent dict type in main files --- src/secondary.q | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/secondary.q b/src/secondary.q index 5ef965a..428a01e 100644 --- a/src/secondary.q +++ b/src/secondary.q @@ -67,23 +67,23 @@ if[count .secondary.hdb:getenv `HDB_DIR; 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`reason`membefore`memafter!("unknown tasktype: ",string tasktype; `error; membefore; membefore))]; + :.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`reason`membefore`memafter`memaftergc!(last res; `error; membefore; memafter; memaftergc))]; + :.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`reason`membefore`memafter`memaftergc!("could not save the result: ",last saved; `savefailed; membefore; memafter; memaftergc))]; + :.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`resultbytes`membefore`memafter`memaftergc!(first saved; last saved; membefore; memafter; memaftergc)); + .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 From fe22b1b6186db6e0a859fd5a016b767285eeca2e Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Wed, 4 Nov 2026 11:26:03 +0000 Subject: [PATCH 46/49] bench-300: style changes --- src/common/mem.q | 4 ---- src/primary.q | 4 ++-- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/src/common/mem.q b/src/common/mem.q index f6428fd..dfd6ad6 100644 --- a/src/common/mem.q +++ b/src/common/mem.q @@ -1,7 +1,3 @@ -// memory figures from the kernel, used by the primary (to watch every secondary, even a busy one) -// and by secondaries (to record each task's peak). See docs/memory-spike.md for why these figures -// all values are in bytes; /proc reports kB (1024 bytes) - // 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 diff --git a/src/primary.q b/src/primary.q index 723f395..1d875c3 100644 --- a/src/primary.q +++ b/src/primary.q @@ -199,7 +199,7 @@ system"l src/common/cgroup.q"; :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 on of the following: ",", " sv string .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]); @@ -215,7 +215,7 @@ system"l src/common/cgroup.q"; 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 thi + 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 }; From 8689b549d8739bd9526cd1c89d0a43d8e419330b Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Thu, 5 Nov 2026 16:19:08 +0000 Subject: [PATCH 47/49] bench-317: adding a stop script and starting primarys in a cgroup --- bin/startprimary.sh | 21 ++++++++++++--- bin/stopall.sh | 60 ++++++++++++++++++++++++++++++++++++++++++ config/default.env | 3 +++ config/integration.env | 4 ++- 4 files changed, 84 insertions(+), 4 deletions(-) create mode 100644 bin/stopall.sh 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/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 b327700..200e268 100644 --- a/config/default.env +++ b/config/default.env @@ -29,6 +29,9 @@ 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 + # where to store results RESULTS_DIR=/home/jrutledge/internalWork/Parallelisation-Project/results diff --git a/config/integration.env b/config/integration.env index 8a536da..3e633f6 100644 --- a/config/integration.env +++ b/config/integration.env @@ -10,4 +10,6 @@ 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 \ No newline at end of file +RESPAWN_MAX=0 + +USE_CGROUP=0 \ No newline at end of file From 57ef86cfe89d7b15022c1fd427fcb9e7d5aaccea Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Fri, 6 Nov 2026 15:26:26 +0000 Subject: [PATCH 48/49] bench-300: happy path integration testing --- .vscode/extensions.json | 6 ++++ tests/integration/gating_spec.q | 47 ++++++++++++++++++++++++++++ tests/integration/gc_spec.q | 39 ++++++++++++++++++++++++ tests/integration/happypath_spec.q | 49 ++++++++++++++++++++++++++++++ tests/integration/kill_spec.q | 42 +++++++++++++++++++++++++ tests/integration/timeout_spec.q | 44 +++++++++++++++++++++++++++ 6 files changed, 227 insertions(+) create mode 100644 .vscode/extensions.json create mode 100644 tests/integration/gating_spec.q create mode 100644 tests/integration/gc_spec.q create mode 100644 tests/integration/happypath_spec.q create mode 100644 tests/integration/kill_spec.q create mode 100644 tests/integration/timeout_spec.q 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/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/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]; + }; + }; From 7d9cfcb3c2525e5644f3661ffc0975cea5073004 Mon Sep 17 00:00:00 2001 From: jamesrut1996 Date: Tue, 10 Nov 2026 11:41:39 +0000 Subject: [PATCH 49/49] bench-300: memory cap env vars added --- config/default.env | 6 +++++ src/primary.q | 28 ++++++++++++++------- tests/unit/fit_spec.q | 58 +++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 81 insertions(+), 11 deletions(-) diff --git a/config/default.env b/config/default.env index 200e268..1739797 100644 --- a/config/default.env +++ b/config/default.env @@ -32,6 +32,12 @@ 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 diff --git a/src/primary.q b/src/primary.q index 1d875c3..d5947b2 100644 --- a/src/primary.q +++ b/src/primary.q @@ -40,6 +40,8 @@ system"l src/common/cgroup.q"; .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 @@ -251,17 +253,23 @@ system"l src/common/cgroup.q"; // 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]; - headroom:.primary.memcap-.primary.committedmem[]; - taskest:0^(exec taskid!memestimate from tasks) qtasks; - // nothing running: send the first task whatever its estimate, so it can't wait for ever on the secondaries' - // own baseline memory - if[not count select from secondaries where status=`busy; headroom:headroom|first taskest]; - // the headroom left after each task: one that fits uses up its estimate, one that doesn't leaves it unchanged - left:headroom {[room;est] $[est<=room; room-est; room]}\ taskest; - // a task fits if its estimate is within what was left before it - fits:taskest<=headroom,-1_left; + // 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 }; @@ -509,6 +517,8 @@ system"l src/common/cgroup.q"; // 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; diff --git a/tests/unit/fit_spec.q b/tests/unit/fit_spec.q index 89cd33a..ed08c94 100644 --- a/tests/unit/fit_spec.q +++ b/tests/unit/fit_spec.q @@ -1,7 +1,8 @@ / 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 +/ 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"]; @@ -20,7 +21,8 @@ if[not `primary in key `; system "l src/primary.q"]; / 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, sends recorded +/ 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] ::}]; @@ -28,6 +30,8 @@ if[not `primary in key `; system "l src/primary.q"]; .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}]; }; @@ -109,6 +113,56 @@ if[not `primary in key `; system "l src/primary.q"]; }; }; +.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[];