From 875e34fba76fa7a01d8825d9fc9890075760d2ad Mon Sep 17 00:00:00 2001 From: alowrydi Date: Mon, 19 Oct 2026 16:48:28 +0100 Subject: [PATCH 01/39] di.eodtime: read the clock once in getdailyadjustment getdailyadjustment read .z.p twice, so the data-timezone offset drifted by nanoseconds between the two reads and was never exact. It now reads the clock once. Tests assert an exact +9h offset for Asia/Tokyo (no DST). Co-Authored-By: Claude Opus 5.5 --- di/eodtime/eodtime.q | 4 +++- di/eodtime/test.csv | 5 +++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/di/eodtime/eodtime.q b/di/eodtime/eodtime.q index 7bb3e64cd..3161ba161 100644 --- a/di/eodtime/eodtime.q +++ b/di/eodtime/eodtime.q @@ -48,7 +48,9 @@ getday:{[p]"d"$(p+adjtime[p])-rolltimeoffset}; getdailyadjustment:{ / utc-equivalent timezones have zero offset if[datatimezone in utczones;:0D]; - `timespan$tz.gmttolocal[datatimezone;.z.p]-.z.p + / one clock read, so the offset is exact + p:.z.p; + `timespan$tz.gmttolocal[datatimezone;p]-p }; / returns normalised roll time-of-day (utc) for the zone offset at timestamp p, wrapped to [0D,1D) diff --git a/di/eodtime/test.csv b/di/eodtime/test.csv index 2f91097fa..1f14fc9d1 100644 --- a/di/eodtime/test.csv +++ b/di/eodtime/test.csv @@ -61,6 +61,11 @@ run,0,0,q,eodtime.init[`rolltimezone`datatimezone`rolltimeoffset`log!(`$"GMT";`$ true,0,0,q,-16h=type eodtime.getdailyadjustment[],1,1,Europe/London datatimezone returns timespan type true,0,0,q,0D<=eodtime.getdailyadjustment[],1,1,Europe/London datatimezone returns non-negative offset +comment,,,,,,,the daily adjustment is an exact offset (Asia/Tokyo is +9h with no DST) +run,0,0,q,eodtime.init[`rolltimezone`datatimezone`rolltimeoffset`log!(`$"GMT";`$"Asia/Tokyo";0D00:00:00.000;logdep)],1,1,reinit with Tokyo datatimezone +true,0,0,q,0D09=eodtime.getdailyadj[],1,1,the adjustment stored at init is exactly 9 hours +true,0,0,q,all 0D09={eodtime.getdailyadjustment[]} each til 100,1,1,every computed adjustment is exactly 9 hours + comment,,,,,,,init - empty config (just log dep) applies all defaults run,0,0,q,eodtime.init[enlist[`log]!enlist logdep],1,1,init with just log dep applies all defaults true,0,0,q,0D=eodtime.getdailyadj[],1,1,default datatimezone (GMT) produces zero daily adjustment From cc5aac6ba9c877996739d0e67e32043d9048f850 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Mon, 19 Oct 2026 16:48:29 +0100 Subject: [PATCH 02/39] di.pubsub: read the filters column TorQ sends in filtered subscriptions addfiltered read the condition column `filts`, but TorQ's pubsub.q and the port's own .ps.subtablefiltered send `filters`, so filtered subscriptions on the tickerplant path were silently unfiltered. addfiltered and subscribestrfilter now use `filters`. Tests cover the parsed where clause and column list, filtered delivery, and rejection of an invalid filter. Co-Authored-By: Claude Opus 5.5 --- di/pubsub/pubsub.md | 2 +- di/pubsub/pubsub.q | 4 ++-- di/pubsub/test.csv | 14 +++++++++++++- 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/di/pubsub/pubsub.md b/di/pubsub/pubsub.md index 1cc0a7b44..8b56c05a3 100644 --- a/di/pubsub/pubsub.md +++ b/di/pubsub/pubsub.md @@ -70,7 +70,7 @@ q)pubsub.subscribe[`;`AAPL`GOOG] q)pubsub.subscribe[`trade;`AAPL] q)pubsub.subscribe[`trade;`] -q)conditions:([tabname:`trade`quote] filts:("";"bid>100,bid<200"); columns:("time,sym,price";"")) +q)conditions:([tabname:`trade`quote] filters:("";"bid>100,bid<200"); columns:("time,sym,price";"")) q)pubsub.subscribe[`;conditions] q)pubsub.subscribestr["trade";"GOOG,AAPL"] diff --git a/di/pubsub/pubsub.q b/di/pubsub/pubsub.q index daba39f9e..baab6ec90 100644 --- a/di/pubsub/pubsub.q +++ b/di/pubsub/pubsub.q @@ -52,7 +52,7 @@ subfiltered:{[table;filters] addfiltered:{[table;cond] / subscribe to tables with custom conditions / if either filters or columns parsing fails, subscription should not be logged as no half query should be created - filters:$[all null f:cond[table;`filts];();@[parse;"select from t where ",f;{'"incorrect filters for parsing"}][2]]; + filters:$[all null f:cond[table;`filters];();@[parse;"select from t where ",f;{'"incorrect filters for parsing"}][2]]; columns:$[all null c:cond[table;`columns];();@[parse;"select ",c," from t";{'"incorrect columns for parsing"}][4]]; @[eval;(?;schemas table;filters;0b;columns);{'"incorrect query with filters-",.Q.s1[y]," columns-",.Q.s1[z]," error-",x}[;filters;columns]]; @[.z.M;`reqfilteredtbl;upsert;(table;.z.w;filters;columns)] @@ -111,7 +111,7 @@ subscribestr:{[table;syms] subscribestrfilter:{[table;filters;columns] / allow non-kdb+ process to subscribe to tables with custom conditions - res:subscribe[`$table;1!enlist `table`filts`columns!(`$table;filters;columns)]; + res:subscribe[`$table;1!enlist `table`filters`columns!(`$table;filters;columns)]; :$[10h~type last res;'last res;res]; }; diff --git a/di/pubsub/test.csv b/di/pubsub/test.csv index 4f7b23cb3..4fe04d3ac 100644 --- a/di/pubsub/test.csv +++ b/di/pubsub/test.csv @@ -74,7 +74,7 @@ run,0,0,q,res:h"select from .m.di.0pubsub.reqfilteredtbl where table in `trade", run,0,0,q,res:select from res where handle=clt,1,,check filtered table for the subscription true,0,0,q,res[`filts][0]~enlist enlist(in;`sym;enlist `AAPL`GOOG),1,, test symbols are listed under filters -run,0,0,q,"conditions:([tabname:`trade`quote]filts:("""";""bid>100,bid<200"");columns:(""time,sym,price"";""""))",1,,create custom conditions for subscription +run,0,0,q,"conditions:([tabname:`trade`quote]filters:("""";""bid>100,bid<200"");columns:(""time,sym,price"";""""))",1,,create custom conditions for subscription run,0,0,q,res:h(`pubsub.subscribe;`;conditions),1,,test subscribe with custom conditions true,0,0,q,`trade`quote~res[0],1,,client receives subscribed table confirmation true,0,0,q,98h~type res[1;0],1,,client receives table schema @@ -114,6 +114,18 @@ run,0,0,q,res:h"select from .m.di.0pubsub.reqfilteredtbl where table=`quote",1,, run,0,0,q,res:select from res where handle=clt,1,,check filtered table for the subscription true,0,0,q,res[`filts][0]~enlist enlist(>;`bid;50f),1,, test symbols are listed under filters +run,0,0,q,"tconds:([tabname:enlist`trade]filters:enlist""price>10"";columns:enlist""sym,price"")",1,,conditions in TorQ's tabname/filters/columns shape +run,0,0,q,res:h(`pubsub.subscribe;`trade;tconds),1,,subscribe trade with TorQ-shaped conditions +run,0,0,q,res:h"select from .m.di.0pubsub.reqfilteredtbl where table=`trade",1,,check filtered table for the subscription +run,0,0,q,res:select from res where handle=clt,1,,check filtered table for the subscription +true,0,0,q,(enlist enlist enlist(>;`price;10))~res`filts,1,,filters column is parsed into the where clause +true,0,0,q,(enlist`sym`price!`sym`price)~res`columns,1,,columns are parsed into the column list +run,0,0,q,delete from `trade,1,,clear the local trade table +run,0,0,q,"h(`pubsub.publish;`trade;([]time:3#.z.p;sym:`IBM`AAPL`IBM;price:5 20 30f;tsize:1 2 3i))",1,,publish rows either side of the filter +true,0,0,q,20 30f~trade`price,1,,only rows meeting the filter are received +true,0,0,q,all null trade`tsize,1,,only the selected columns are received +fail,0,0,q,"h(`pubsub.subscribe;`trade;([tabname:enlist`trade]filters:enlist""price>>"";columns:enlist""""))",1,,an invalid filter is rejected + comment,,,,,,,root .stpps/.u.sub/.ps true,0,0,q,"h"".ps.loaded""",1,,.ps.loaded is set when the module loads run,0,0,q,"h""pubsub.init[enlist[`log]!enlist `info`warn`error!3#enlist{[c;m] `lastlog set (c;m)}]""",1,,wire a recording log through init From 1187c800073a4eea7381b10378ab1192debad0ca Mon Sep 17 00:00:00 2001 From: alowrydi Date: Mon, 19 Oct 2026 16:48:43 +0100 Subject: [PATCH 03/39] di.merge: restore TorQ merge.q failure and attribute behaviour - getextrapartitiontype returns () after logging when neither the table nor default has a p# row, as legacy does, instead of the logger's return value. - mergebypart reads segments unprotected (get each partchunks): an unreadable segment fails the batch before anything is upserted. - mergebypart's upsert handler logs ERR and then re-signals the error. - checkenumerabletype logs ERR and then signals for a non-enumerable column. - mergehybrid no longer re-sorts the whole destination and applies p#; the callers apply p# after merging, as in TorQ. Its tests and docs go with it. A failed merge now stops end of day before the segments are deleted; a wdb caller-level test (failedmerge) covers this. Co-Authored-By: Claude Opus 5.5 --- di/merge/merge.md | 67 +++++++-------------------------------- di/merge/merge.q | 56 +++++++------------------------- di/merge/test.csv | 32 ++++++++++--------- di/torq/proc/wdb/test.csv | 1 + di/torq/proc/wdb/test.q | 11 +++++++ 5 files changed, 51 insertions(+), 116 deletions(-) diff --git a/di/merge/merge.md b/di/merge/merge.md index 2165b6554..830db67d1 100644 --- a/di/merge/merge.md +++ b/di/merge/merge.md @@ -95,7 +95,7 @@ merge.getpartchunks[partdirs; 1000000] ``` ### `mergebypart[extrapartitiontype;dest;partchunks]` -Merge one batch of whole partition segments into destination partition `dest`, re-sorting by the parted column(s) `extrapartitiontype` first if the `p#` attribute cannot otherwise be applied. Typically iterated over the output of `getpartchunks`. Each segment in `partchunks` is read individually and protected: a missing or corrupt segment file is error-logged and dropped, it does not take its batch-mates down with it - the rest of the batch still merges. If every segment in the batch fails to read, nothing is upserted and that is error-logged too. +Merge one batch of whole partition segments into destination partition `dest`, re-sorting by the parted column(s) `extrapartitiontype` first if the `p#` attribute cannot otherwise be applied. Typically iterated over the output of `getpartchunks`. As in TorQ, the segments are read unprotected: a missing or corrupt segment fails the batch before anything is upserted. A failed upsert is error-logged and then signalled. Either way the error reaches the caller, which therefore does not go on to delete the segments. ```q merge.mergebypart[`sym; ` sv dest,`] each merge.getpartchunks[partdirs;lim] ``` @@ -107,13 +107,13 @@ merge.mergebycol[(`trade;schema); dest] each partdirs ``` ### `mergehybrid[extrapartitiontype;tableinfo;dest;partdirs;mergelimit]` -Merge `partdirs` using whichever method fits each: whole-partition for those within `mergelimit`, column-by-column for any single partition over it (creating the `.d` file if column-by-column merging produced none). If `extrapartitiontype` is non-empty, once both paths have finished it re-sorts and re-applies the `p#` attribute to `dest` as a whole - see "The parted attribute is applied once, on the whole destination" below for why that happens here rather than per-batch. +Merge `partdirs` using whichever method fits each: whole-partition for those within `mergelimit`, column-by-column for any single partition over it (creating the `.d` file if column-by-column merging produced none). As in TorQ, `dest` is not re-sorted or re-attributed; the callers apply `p#` after merging (di.torq.proc.wdb, di.torq.proc.tickerlogreplay). ### `checkpartitiontype[tablename;extrapartitiontype]` Error-log any parted column supplied for the table that is absent from it. ### `checkenumerabletype[tablename;extrapartitiontype]` -Confirm every parted column has an enumerable type (`h`/`i`/`j`/`s`) so it can key a partition; error-logs otherwise. +Confirm every parted column has an enumerable type (`h`/`i`/`j`/`s`) so it can key a partition. Otherwise it error-logs and signals. ### `getextrapartitions[tablename;extrapartitiontype]` Return the distinct combinations of the parted column values - one per partition directory. @@ -122,7 +122,7 @@ Return the distinct combinations of the parted column values - one per partition Return the partition values grouped by the first character of the (single) parted column. ### `getextrapartitiontype[sortconfig;tablename]` -Return the parted (`p#`) column(s) for `tablename` from `sortconfig` (a sort table with `tabname`, `column`, `sort` and `att` columns, e.g. di.dbwrite's `getconfig[]`): the table's own sorted `p#` columns, else those of the `default` row. Error-logs when neither is defined. +Return the parted (`p#`) column(s) for `tablename` from `sortconfig` (a sort table with `tabname`, `column`, `sort` and `att` columns, e.g. di.dbwrite's `getconfig[]`): the table's own sorted `p#` columns, else those of the `default` row. When neither is defined it error-logs and returns `()`, as TorQ does. ```q merge.getextrapartitiontype[dbw.getconfig[]; `trade] ``` @@ -182,56 +182,11 @@ unmerged with no trace. When `init` finds pre-existing tracked partitions it say the log rather than something a future debugger has to discover by reading source. A fresh, first-ever `init` (nothing tracked yet) logs the plain `"di.merge initialised"` with no such claim. -**`mergebycol` deliberately keeps failing uncaught on a missing/corrupt segment column; `mergebypart` -does not.** These are not equivalent failure modes, so making them match would not obviously be the -safer choice - it might be the wrong one. `mergebypart` reads each segment in a batch individually and -protected: a missing/corrupt segment file is error-logged and dropped without disturbing its -batch-mates, which still merge. The remaining, surviving segments in the batch are then joined and -upserted as one unit - if *that* upsert itself fails (e.g. a schema mismatch), the whole batch's data -is lost together, which is incomplete but still internally consistent: `dest` simply doesn't get that -batch's data yet, nothing else in `dest` is disturbed. `mergebycol` merges one column at a time into -the *same* `dest`; if a swallowed failure let it carry on past a bad column, `dest` would end up with -some columns reflecting the new data and others silently stale - a genuinely worse, -silently-inconsistent partition, not just a delayed merge. So `mergebycol`'s column read is -intentionally left unprotected: a missing or unreadable segment column throws straight out of -`mergebycol`/`mergehybrid`'s column-by-column path, by design, rather than risking a half-updated -destination. (This also happens to match the legacy TorQ source and Olly's draft, both of which have -the same unprotected-read structure - but the reason to keep it here is the partial-column-write risk -above, not merely that it matches prior behaviour.) - ---- - -## The parted attribute is applied once, on the whole destination - -A full write-down-and-merge smoke test (real segments, real `di.log`, both of TorQ's `partbyenum` -and `partbyfirstchar` write patterns) found that `mergehybrid` never actually left `dest` with the -`p#` attribute set, even when every batch merged cleanly - `mergebypart`'s own resort logic decides -*whether* `p#` could apply and reorders rows accordingly, but applying the attribute to an in-memory -batch and then `upsert`-ing it to disk does not persist the attribute: `upsert` appends raw values -onto the on-disk column, it does not carry an in-memory attribute through to the file. Confirmed -empirically (`meta` on the merged destination showed no attribute on the parted column, in a -mergebypart-only scenario with nothing left to resort). - -Worse, `mergebycol` never even tries: for TorQ's `partbyfirstchar` write mode, a single segment can -hold *several* parted-column values in arrival order, not one. If that segment is large enough to -route through `mergebycol` instead of `mergebypart`, its rows are appended as-is - the destination -ends up genuinely unsorted and non-contiguous by the parted column. Confirmed empirically too: after -merging first-character-grouped segments through `mergehybrid`, the destination's parted column was -neither sorted nor grouped on disk. - -Trying to fix this per-batch (inside `mergebypart`, or per-column inside `mergebycol`) cannot give a -real guarantee either way: a batch that is already correctly grouped in isolation can still land next -to a *different* batch's values on disk, and `upsert` does not re-validate the combined result. -The only way to genuinely guarantee `` `p# `` on `dest` is to look at the whole thing at once. So -`mergehybrid` does that as a final step, after every whole-partition batch and every column-by-column -segment has been merged: it reads `dest` back, re-sorts it by `extrapartitiontype`, re-applies the -attribute, and writes the whole table back. This is a deliberate, necessary departure from this -module's "keeps memory flat" design goal (see the file header) for that one final step - the -alternative is a `dest` that is silently never truly parted, which is worse. Batch-by-batch merging -into `dest` still only ever holds one batch/column in memory at a time; only this last step reads -`dest` in full, once, per `mergehybrid` call. `mergebypart` called standalone in a caller-driven loop -(bypassing `mergehybrid` - see its usage example above) does **not** get this guarantee automatically; -route through `mergehybrid` if a properly parted `dest` matters. +**A failed merge is signalled, as in TorQ.** A missing or unreadable segment fails `mergebypart` (whole +batch) or `mergebycol` (that column) before the data reaches `dest`. A failed `mergebypart` upsert is +error-logged and then signalled. In each case the caller's merge stops before it deletes the segments, +so the data can be merged again. One difference remains: a failed per-column upsert in `mergebycol` is +error-logged and the merge continues. Legacy swallowed it silently, because its handler was never called. --- @@ -285,7 +240,7 @@ k4unit:use`di.k4unit k4unit.moduletest`di.merge ``` -The test suite injects a no-op binary mock logger (and a capturing logger for the log-path assertions). It covers: dependency validation (non-dict deps / missing / non-dict / incomplete `log` all throw, with the `di.merge` error prefix); the `requireinit` guard rejecting every exported function before `init` has run; config application via row-count vs byte-size batching, defaults and overrides; `trackpartition`/`getpartsizes`/`clearpartsizes`/`syncpartsizes`; the `getpartchunks` batching and `partlimit` splitting logic; `version`/`getapimeta` shape; end-to-end `mergebypart`, `mergebycol` and `mergehybrid` against real on-disk segments written to a scratch directory (cleaned up afterwards); `mergebypart` isolating one missing segment from healthy batch-mates in the same batch; and `mergehybrid` re-sorting and re-attributing the whole destination once both merge paths have run. +The test suite injects a no-op binary mock logger (and a capturing logger for the log-path assertions). It covers: dependency validation (non-dict deps / missing / non-dict / incomplete `log` all throw, with the `di.merge` error prefix); the `requireinit` guard rejecting every exported function before `init` has run; config application via row-count vs byte-size batching, defaults and overrides; `trackpartition`/`getpartsizes`/`clearpartsizes`/`syncpartsizes`; the `getpartchunks` batching and `partlimit` splitting logic; `version`/`getapimeta` shape; end-to-end `mergebypart`, `mergebycol` and `mergehybrid` against real on-disk segments written to a scratch directory (cleaned up afterwards); `mergebypart` failing the batch on a missing segment and signalling a failed upsert; `mergehybrid` leaving the destination in write order with no attribute; `getextrapartitiontype` returning `()` when no row applies; and `checkenumerabletype` signalling a non-enumerable column. Mock loggers only check that a message was logged at the right level - they do not process the message content the way a real logger does, so they cannot catch a malformed message (a list where a flat string was expected, for instance). Where a message's *shape* matters, not just that it fired, the test asserts on structure too (e.g. `10h=type` on the captured message) rather than relying on the mock alone. @@ -297,4 +252,4 @@ Mock loggers only check that a message was logged at the right level - they do n - `init` must be called before any other function - enforced by the `requireinit` guard on every other exported function, not just documented convention. - The `VERSION`-file read pattern (fail loud on missing/unreadable/empty, `trim` against trailing whitespace) follows `di.servers`, not `di.eodtime` (which has no `VERSION` handling at all). - The merge functions operate on on-disk paths (`get`/`set`/`upsert` against file symbols); they do not manage the segment or destination directory lifecycle - that remains the caller's responsibility. -- A real-logger smoke test (see "The parted attribute is applied once, on the whole destination" above) also caught `checkenumerabletype`'s error-message construction building a malformed list instead of a flat string for a multi-symbol `extrapartitiontype` - the k4unit mock loggers don't process message content, so this was invisible there. Fixed to match `checkpartitiontype`'s already-correct `", " sv string ...` pattern, with a regression test that checks the message's shape (`10h=type`), not just that it fired. +- A real-logger smoke test also caught `checkenumerabletype`'s error-message construction building a malformed list instead of a flat string for a multi-symbol `extrapartitiontype` - the k4unit mock loggers don't process message content, so this was invisible there. Fixed to match `checkpartitiontype`'s already-correct `", " sv string ...` pattern, with a regression test that checks the message's shape (`10h=type`), not just that it fired. diff --git a/di/merge/merge.q b/di/merge/merge.q index 519c41819..76bde63e1 100644 --- a/di/merge/merge.q +++ b/di/merge/merge.q @@ -141,38 +141,21 @@ mergebypart:{[extrapartitiontype;dest;partchunks] / re-sorts the batch by the parted column(s) first if the p# attribute cannot otherwise be applied requireinit[`mergebypart]; .z.m.loginfo[`merge;"reading partition/partitions ",", " sv string partchunks]; - / read each segment separately and protected, so one missing/corrupt segment file does not take - / its batch-mates down with it - a bare get each/join here would fail the whole batch together - reads:{[p] @[get;p;{[p;e] .z.m.logerr[`merge;"failed to read segment ",(string p), - ", not merged this batch - error is - ",e];(::)}[p;]]} each partchunks; - ok:98h=type each reads; - if[not all ok; - .z.m.logerr[`merge;"skipping ",string[sum not ok]," of ",string[count partchunks], - " segment(s) in this batch that failed to read"]]; - chunks:reads where ok; - if[0=count chunks; - .z.m.logerr[`merge;"no segments in this batch read successfully, nothing upserted to ",string dest]; - :(::)]; + / an unreadable segment fails the batch before anything is upserted, so the segments are kept + chunks:get each partchunks; / a single segment reads back as a table; multiple read back as a list of tables to join if[98<>type chunks;chunks:(,/)chunks]; .z.m.loginfo[`resort;"checking that the contents of this subpartition conform"]; / can the p# attribute be applied as-is? if not, the data must be re-sorted by the parted column - / applying p# here would not survive the upsert below - upsert appends raw values onto the - / on-disk column and does not persist an in-memory attribute, so this only orders the rows - / within this batch; mergehybrid applies the real, persisted attribute once across the whole - / destination after every batch (and any mergebycol columns) have been upserted pattrtest:@[{@[x;y;`p#];0b}[chunks;];extrapartitiontype;{1b}]; if[pattrtest; .z.m.loginfo[`resort;"re-sorting contents of subpartition"]; chunks:xasc[extrapartitiontype;chunks]; ]; .z.m.loginfo[`merge;"upserting ",(string count chunks)," rows to ",string dest]; - / append the merged rows to permanent storage, logging (not throwing) on failure - / e arrives already a string from the protected-apply mechanism - do not re-stringify it: string - / of an already-string value maps over each char individually, corrupting the message and making - / this handler itself throw, which defeats the log-not-throw contract this line exists to provide + / append the merged rows to permanent storage; a failure is logged and signalled so the caller keeps the segments .[upsert;(dest;chunks); - {[e;d;p] .z.m.logerr[`merge;"failed to merge to ",string[d]," from segments ",(", " sv string p)," Error is - ",e]}[;dest;partchunks]]; + {[e;d;p] .z.m.logerr[`merge;"failed to merge to ",string[d]," from segments ",(", " sv string p)," Error is - ",e];'e}[;dest;partchunks]]; }; / merge one segment into the destination partition a column at a time @@ -206,25 +189,6 @@ mergehybrid:{[extrapartitiontype;tableinfo;dest;partdirs;mergelimit] (` sv dest,`.d) set cols tableinfo[1]; ]; ]; - / mergebypart applies p# per batch and mergebycol applies none at all, so neither guarantees the - / full destination ends up grouped once multiple batches and/or both methods have all appended - / to it - re-sort and re-apply the attribute to the whole destination once, here, after every - / path above has finished, rather than leaving that guarantee split across per-batch calls - if[0 Date: Mon, 19 Oct 2026 16:49:19 +0100 Subject: [PATCH 04/39] di.timer: log failed jobs through the injected logger; jobs reschedule as TorQ's .timer.repeat - init requires a `log dependency in its dict; the (::) config form is gone. The only non-test caller, di.torq buildtimerdep, now passes the log dep. - Single trap, as TorQ's timer.q: execute no longer traps, so a job's error reaches runandschedule's handler (jobfailed), which logs ERR with the job id and error whatever debug is set to, and returns 0b. - gateway gwtimeout/gwrmqueries/gwrminactive, wdb wdbsave and torq querylogflush move from mode 1 to mode 3 (reschedule from the end of the previous run). Co-Authored-By: Claude Opus 5.5 --- di/timer/init.q | 22 ++++++++++++++------- di/timer/test.csv | 36 ++++++++++++++++++++++++++++++++++ di/timer/timer.md | 18 ++++++++++------- di/torq/proc/gateway/gateway.q | 9 +++++---- di/torq/proc/gateway/test.csv | 5 +++++ di/torq/proc/wdb/test.csv | 1 + di/torq/proc/wdb/test.q | 9 +++++++++ di/torq/proc/wdb/wdb.md | 2 +- di/torq/proc/wdb/wdb.q | 3 ++- di/torq/test.csv | 1 + di/torq/torq.md | 4 ++-- di/torq/torq.q | 10 +++++----- 12 files changed, 93 insertions(+), 27 deletions(-) diff --git a/di/timer/init.q b/di/timer/init.q index 3259377eb..77e52601d 100644 --- a/di/timer/init.q +++ b/di/timer/init.q @@ -102,14 +102,21 @@ getalljobs:{jobs} nextruntime:-0Wp; / configurable function to alter how timer functions are executed -execute:{.[{$[count y; x . (),y; x@`];1b};(x;y);{if[debug;msg.err"Job execution failed for function: ",(-3!x)," with error: ",y]0b}[x]]}; +execute:{$[count y; x . (),y; x@`];1b}; + +jobfailed:{[id;dof;e] + / logs a failed job, as TorQ's timer does, and reports the failure to runandschedule + if[debug;msg.err"Job start failed for job id : ",(string id)," with error: ",e]; + .z.m.logerr[`timer;"timer ID ",(string id)," failed with error ",e,$[dof;". The function will not be rescheduled";""]]; + :0b; + }; runandschedule:{[id] / runs function, schedules next runs and updates any additional status info if applicable for given job id r:.z.M.jobs[id]; if[debug;msg.info"Executing job id: ",(string id)," for start time: ",(string r`nextstart)]; r[`actualstart]:cp[]; - ret:@[$[logcall;0;value];(execute;r`func;r`params);{if[debug;msg.err"Job start failed for job id : ",(string x)," with error: ",y];0b}[id]]; + ret:@[$[logcall;0;value];(execute;r`func;r`params);jobfailed[id;r`disableonfail]]; if[(not ret)&r`disableonfail;r[`status]:0b]; r:upd.status[r]; / update status based on job status and configurable options @[.z.M.jobs;id;:;r]; @@ -131,16 +138,17 @@ main:{ setcp:{.z.m.cp:x}; init:{[configs] - / sets default config vars + / sets default config vars; configs must carry the injected `log dependency + if[not (99h=type configs) and `log in key configs; + '"di.timer: log dependency is required; pass `info`warn`error functions keyed on `log - see di.util.log"]; + .z.m.logerr:configs[`log]`error; .z.m.debug:0b; / if enabled displays messages for jobs starting and any errors in execution .z.m.logcall:1b; / if enabled will execute timer functions through 0 handle .z.m.cycletime:100; / frequency to check for new jobs to start (in ms) / set custom config vars - if[not configs~(::); - vars:`logcall`cycletime`debug inter key configs; - (.Q.dd[.z.M] each key[vars#configs]) set' value[vars#configs]; - ]; + vars:`logcall`cycletime`debug inter key configs; + (.Q.dd[.z.M] each key[vars#configs]) set' value[vars#configs]; / appends to any existing .z.ts logic and start system cycle for timer job evaluation $[enabled;:();.z.m.enabled:1b]; / bomb out of function if already enabled $[@[{value x;1b};`.z.ts;0b]; / test if there is a pre-existing .z.ts definition diff --git a/di/timer/test.csv b/di/timer/test.csv index 2b9353775..e555ddb20 100644 --- a/di/timer/test.csv +++ b/di/timer/test.csv @@ -83,3 +83,39 @@ true,0,0,q,.test.exec2,1,,Test run succeeded for exec 2 run,0,0,q,testexec3:{.test.exec3:x+y};timer.addjob.default[`testexec3;`testexec3;(2;3);10;1],1,,Add job for exec 3 run,0,0,q,.m.di.0timer.runandschedule[`testexec3],1,,Test timer function exec 3 true,0,0,q,.test.exec3=5,1,,Test run succeeded for exec 3 + +comment,,,,,,,init requires the injected logger and a failed job is logged through it +fail,0,0,q,timer.init[()!()],1,,init without a log dependency must error +fail,0,0,q,timer.init[(::)],1,,init without deps must error +run,0,0,q,"caplog:([] fn:`symbol$();ctx:`symbol$();msg:())",1,,capture table for the log assertions +run,0,0,q,logcap:`info`warn`error!({[c;m]`caplog upsert(`info;c;m)};{[c;m]`caplog upsert(`warn;c;m)};{[c;m]`caplog upsert(`error;c;m)}),1,,capturing logger +run,0,0,q,timer.init[`log`debug!(logcap;0b)],1,,init with the capturing logger and debug off +run,0,0,q,system"t 0",1,,stop the timer cycle so jobs only run when the test calls them +run,0,0,q,timer.addjob.custom[`testfail1;{'"boom"};();10;1;()!()],1,,add a job that fails +run,0,0,q,.m.di.0timer.runandschedule[`testfail1],1,,run the failing job +true,0,0,q,1=count select from caplog where fn=`error,1,,the failure is logged once as an error with debug off +true,0,0,q,"any {all 00; .z.m.qlflushtime:ft*0D00:00:01; - (deps[`timer][`addjob])[`querylogflush;flushquerylog;();"j"$opt[`flushinterval;1800];1h;()!()]]; + (deps[`timer][`addjob])[`querylogflush;flushquerylog;();"j"$opt[`flushinterval;1800];3h;()!()]]; msg:"query logging on (level ",(string cfg`level),", memory=",(string cfg`logtomemory),", disk=",(string cfg`logtodisk),")"; deps[`log][`info][`torq;msg," - di.querylog wraps .z.* directly; see torq.md Query logging"]; } @@ -292,7 +292,7 @@ init:{[proctype;procname;overrides] / the process.csv phone-book path, so di.torq.servers (and any consumer building its own startup config / slice from this config) can dial peers without reading env itself - keeps di.servers' env-free boundary. config:config,enlist[`processcsv]!enlist reqenv[`TORQXAPPCONFIG],"/process.csv"; - timerdep:buildtimerdep[overrides]; + timerdep:buildtimerdep[overrides;logdep]; handlersdep:buildhandlersdep[overrides;logdep]; / servers is built LAST (it consumes log/timer/handlers at init) and injected alongside / them, so consumers read deps`servers instead of `use`+init-ing di.torq.servers themselves. From 16d72321a1b8e59089d38273d2b0705da0483c76 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 20 Oct 2026 09:43:13 +0100 Subject: [PATCH 05/39] di.timer: store params as a list, disable at maxtime and rescan as TorQ's timer D-T1: addjob.custom stores (),params and upserts a keyed row, so a job with an atom parameter no longer types the params column. D-T2: a job whose next run would fall after maxtime is disabled after its run, as TorQ's timer checks the next run against the period end. D-T3: nextruntime is recomputed after each run instead of every tick, as TorQ's timer does, so a job added after the table empties still runs. Co-Authored-By: Claude Opus 5.5 --- di/timer/init.q | 11 ++++++++--- di/timer/test.csv | 27 +++++++++++++++++++++++++++ di/timer/timer.md | 4 ++-- 3 files changed, 37 insertions(+), 5 deletions(-) diff --git a/di/timer/init.q b/di/timer/init.q index 77e52601d..bb77aacd8 100644 --- a/di/timer/init.q +++ b/di/timer/init.q @@ -31,7 +31,9 @@ addjob.custom:{[id;func;params;period;mode;opts] if[id in key .z.M.jobs;'"Cannot add id : ",(string id)," already exists in jobs"]; if[-11h=type func;get func]; opts:addjob.opts,opts; - .z.M.jobs insert (id;func;params;cp[];`int$period;`short$mode;0Np;0Np;0Np;0Np;0i;1b;`int$(opts`maxruns);opts`maxtime;opts`disableonfail;opts`startattime); + row:cols[.z.M.jobs]!(id;func;(),params;cp[];`int$period;`short$mode;0Np;0Np;0Np;0Np;0i;1b;`int$(opts`maxruns);opts`maxtime;opts`disableonfail;opts`startattime); + / params is stored as a list so an atom parameter cannot type the column + .z.M.jobs upsert 1!enlist row; $[null (r:.z.M.jobs[id])`startattime; upd.start[id]; [r[`nextstart]:r`startattime;@[.z.M.jobs;id;:;r]] @@ -55,7 +57,6 @@ upd.status:{[r] r[`prevstart]:r`nextstart; r[`runs]+:1; if[(not null r[`maxruns])&r[`maxruns]<=r`runs;r[`status]:0b]; - if[(not null r[`maxtime])&r[`maxtime]<=r`prevend;r[`status]:0b]; r}; nextstart:()!(); @@ -121,6 +122,11 @@ runandschedule:{[id] r:upd.status[r]; / update status based on job status and configurable options @[.z.M.jobs;id;:;r]; if[r[`status];upd.start[id]]; / update next start time after run + / as TorQ's timer, a job whose next run would fall after its end time is disabled + r:.z.M.jobs id; + if[(not null r`maxtime)&r[`maxtime] Date: Tue, 20 Oct 2026 09:43:34 +0100 Subject: [PATCH 06/39] di.timer: add addjob.once and removefunc, as TorQ's .timer.once and .timer.removefunc addjob.once schedules a one-off job at a set time (startattime, maxruns 1). removefunc deletes every job running a function with given parameters. Co-Authored-By: Claude Opus 5.5 --- di/timer/init.q | 6 +++++- di/timer/test.csv | 31 +++++++++++++++++++++++++++++++ di/timer/timer.md | 12 ++++++++++++ 3 files changed, 48 insertions(+), 1 deletion(-) diff --git a/di/timer/init.q b/di/timer/init.q index bb77aacd8..54384e92e 100644 --- a/di/timer/init.q +++ b/di/timer/init.q @@ -42,6 +42,8 @@ addjob.custom:{[id;func;params;period;mode;opts] addjob.default:addjob.custom[;;;;;()!()]; addjob.simple:addjob.custom[;;();;1;()!()]; +/ one-off job at runtime, as TorQ's .timer.once +addjob.once:{[id;func;params;runtime] addjob.custom[id;func;params;1;1;`startattime`maxruns!(runtime;1)]}; / internal utility functions msg.custom:{[code;msg]neg[1] (string cp[])," ### ",code," ### ",msg;}; @@ -94,6 +96,8 @@ enable:{.[.z.M.enabled;();:;1b];}; enablejobs:{[ids] ids:(),ids;.z.m.jobs:update status:1b from jobs where id in ids}; disablejobs:{[ids] ids:(),ids;.z.m.jobs:update status:0b from jobs where id in ids}; deletejobs:{[ids] ids:(),ids;.z.m.jobs:delete from jobs where id in ids}; +/ remove jobs by function and parameters, as TorQ's .timer.removefunc +removefunc:{[f;p] .z.m.jobs:delete from jobs where (f~/:func)&((),p)~/:params}; getactivejobs:{select from jobs where status}; @@ -163,4 +167,4 @@ init:{[configs] }; -export:([init;getactivejobs;getalljobs;addjob;deletejobs;enablejobs;disablejobs;enable;disable;setcp]) +export:([init;getactivejobs;getalljobs;addjob;deletejobs;removefunc;enablejobs;disablejobs;enable;disable;setcp]) diff --git a/di/timer/test.csv b/di/timer/test.csv index 50bd71ba2..3bfbb300e 100644 --- a/di/timer/test.csv +++ b/di/timer/test.csv @@ -131,6 +131,22 @@ true,0,0,q,.m.di.0timer.jobs[`dt2][`status],1,,still enabled - its next run is i run,0,0,q,.m.di.0timer.runandschedule[`dt2],1,,second run (next would be 12:00:30) true,0,0,q,not .m.di.0timer.jobs[`dt2][`status],1,,disabled - its next run would fall after the end time +comment,,,,,,,once - a one-off job that runs at a set time +run,0,0,q,.test.once:0,1,,run counter +run,0,0,q,timer.addjob.once[`once1;{.test.once+:1};();2025.03.03D11:00:00.000],1,,add a one-off job +true,0,0,q,2025.03.03D11:00:00.000=.m.di.0timer.jobs[`once1][`nextstart],1,,it is due at the requested time +run,0,0,q,.m.di.0timer.runandschedule[`once1],1,,run it +true,0,0,q,1=.test.once,1,,it ran once +true,0,0,q,not .m.di.0timer.jobs[`once1][`status],1,,and is then disabled + +comment,,,,,,,removefunc - remove jobs by function and parameters +run,0,0,q,.test.rf:{x},1,,shared job function +run,0,0,q,timer.addjob.custom[`rf1;.test.rf;enlist 1;10;1;()!()],1,,job on .test.rf with parameter 1 +run,0,0,q,timer.addjob.custom[`rf2;.test.rf;enlist 2;10;1;()!()],1,,job on .test.rf with parameter 2 +run,0,0,q,timer.removefunc[.test.rf;enlist 1],1,,remove the job with parameter 1 +true,0,0,q,not `rf1 in key .m.di.0timer.jobs,1,,the matching job is removed +true,0,0,q,`rf2 in key .m.di.0timer.jobs,1,,the job with other parameters stays + comment,,,,,,,params of any type, an atom first, do not type the params column run,0,0,q,timer.deletejobs exec id from timer.getalljobs[],1,,empty the jobs table run,0,0,q,"timer.addjob.custom[`pt1;{x+1};5;10;1;()!()]",1,,first job takes an atom parameter @@ -139,6 +155,13 @@ run,0,0,q,"timer.addjob.custom[`pt3;{x,y};(1;`x);10;1;()!()]",1,,and another a m true,0,0,q,all `pt1`pt2`pt3 in exec id from timer.getalljobs[],1,,all three jobs are added true,0,0,q,"(6;`sym;(1;`x))~{$[count y; x . (),y; x@`]}'[exec func from .m.di.0timer.jobs;exec params from .m.di.0timer.jobs]",1,,each job's function still gets its parameter as passed +comment,,,,,,,removefunc and once failure cases +run,0,0,q,timer.addjob.custom[`rfx;.test.rf;enlist 9;10;1;()!()],1,,a job on .test.rf +run,0,0,q,.test.n0:count timer.getalljobs[],1,,job count before +run,0,0,q,"timer.removefunc[{x+1};()]",1,,removefunc on a function that is not scheduled does not error +true,0,0,q,.test.n0=count timer.getalljobs[],1,,and removes nothing +fail,0,0,q,"timer.addjob.once[`rfx;{x};();2025.03.03D11:00:00.000]",1,,once rejects a job id that already exists + comment,,,,,,,a job added after the jobs table has emptied still runs (D-T3) run,0,0,q,timer.deletejobs exec id from timer.getalljobs[],1,,empty the jobs table run,0,0,q,.m.di.0timer.main[],1,,a scheduler tick on the empty table @@ -146,3 +169,11 @@ run,0,0,q,.test.dt3:0,1,,run counter run,0,0,q,timer.addjob.custom[`dt3;{.test.dt3+:1};();10;1;(enlist`startattime)!enlist 2025.03.03D11:00:00.000],1,,add a job that is already due run,0,0,q,.m.di.0timer.main[],1,,the next tick true,0,0,q,1=.test.dt3,1,,the job runs +run,0,0,q,timer.deletejobs `dt3,1,,remove it +run,0,0,q,".test.n3:0;.test.f3:{.test.n3+:1}",1,,counter and job function for the removefunc case +run,0,0,q,timer.addjob.custom[`dt3b;.test.f3;();10;1;(enlist`startattime)!enlist 2025.03.03D11:00:00.000],1,,a job on .test.f3 +run,0,0,q,timer.removefunc[.test.f3;()],1,,removefunc empties the jobs table +run,0,0,q,.m.di.0timer.main[],1,,a scheduler tick on the empty table +run,0,0,q,timer.addjob.custom[`dt3c;.test.f3;();10;1;(enlist`startattime)!enlist 2025.03.03D11:00:00.000],1,,add a new job that is already due +run,0,0,q,.m.di.0timer.main[],1,,the next tick +true,0,0,q,1=.test.n3,1,,the new job runs diff --git a/di/timer/timer.md b/di/timer/timer.md index a06ff64d7..8f6a8251c 100644 --- a/di/timer/timer.md +++ b/di/timer/timer.md @@ -95,6 +95,12 @@ Provides a fast way to schedule a job using sensible defaults — ideal for quic timer.addjob.simple[`job5;{show "Hi"};30] ``` +#### addjob.once +A one-off job that runs once at `runtime`, as TorQ's `.timer.once`. +```q +timer.addjob.once[`job6;{show x};enlist "once";2025.07.30D09:00:00] +``` + --- ### Control & Monitoring @@ -144,6 +150,12 @@ timer.deletejobs[`job4`job5] - Purpose: Removes jobs from jobs table. Can be done without disabling loop. - Usage: Ideal for re-defining job params wihtout interrupting other jobs. +#### removefunc +```q +timer.removefunc[myfunc;enlist 1] +``` +- Purpose: Removes every job running `func` with `params`, as TorQ's `.timer.removefunc`. + #### getactivejobs ```q timer.getactive[] From 0cc02d3f0c3c051efb85ccca7c1b2227b5b78954 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 20 Oct 2026 09:53:16 +0100 Subject: [PATCH 07/39] di.torq.servers: add startupdepcycles and startupdependent, as TorQ's trackservers.q reqproctypesnotconn and the two root projections on startupdepcyclestypename, alongside the existing startupdepnamecycles. Co-Authored-By: Claude Opus 5.5 --- di/torq/servers/servers.md | 14 +++++++------- di/torq/servers/servers.q | 6 ++++++ di/torq/servers/test.csv | 5 +++++ 3 files changed, 18 insertions(+), 7 deletions(-) diff --git a/di/torq/servers/servers.md b/di/torq/servers/servers.md index 073781f34..db9099c01 100644 --- a/di/torq/servers/servers.md +++ b/di/torq/servers/servers.md @@ -108,10 +108,10 @@ Published at root by `init`, same bodies as legacy: Also defined at root, for di.subscriptions' `.sub` and the tickerplants' startup waits: - `.servers.getservers` (5-arg; the exported 1-arg `getservers` is separate); - `.servers.connectcustom` (called by `retryrows`); -- `.servers.startupdepnamecycles`. +- `.servers.startupdepnamecycles`, `.servers.startupdepcycles` and `.servers.startupdependent`. -They are built on the module-private `attributematch`, `reqprocsnotconn`, `reqprocnamesnotconn` and -`startupdepcyclestypename`. +They are built on the module-private `attributematch`, `reqprocsnotconn`, `reqproctypesnotconn`, +`reqprocnamesnotconn` and `startupdepcyclestypename`. The discovery process (`di.torq.proc.discovery`) calls `addw`, `removerows`, `cleanup`, `startup`, reads `SERVERS`/`nontorqprocesstab`, and pushes `procupdate`/`autodiscovery` to @@ -137,8 +137,7 @@ peers. Peers call discovery's root `register` (as `` `..register ``) and `getser - `getserverbytype`/`gethpbytype`; - `names`/`types`/`unregistered`/`checkw`/`reset`; - the `addprocscustom` hook; -- `refreshattributes`; -- `reqproctypesnotconn`/`startupdepcycles`/`startupdependent`. +- `refreshattributes`. **Legacy behaviour that differs from di.torq.servers 0.3.0:** - `startup` no longer excludes this process's own row. @@ -151,12 +150,13 @@ peers. Peers call discovery's root `register` (as `` `..register ``) and `getser ## Tests -`test.q` + `test.csv` (56 checks) spawn real q peers. They cover: +`test.q` + `test.csv` (63 checks) spawn real q peers. They cover: - init validation, wiring and idempotency; - `startup` against a live and a dead peer (discovery off); - `gethandlebytype`, and retry recovering an ungraceful kill; - `waitfortype`, including a discovery stub that comes up after `startup`; -- `attributematch`, the root 5-arg `.servers.getservers` and `.servers.startupdepnamecycles`; +- `attributematch`, the root 5-arg `.servers.getservers`, `.servers.startupdepnamecycles`, + `.servers.startupdepcycles` and `.servers.startupdependent`; - input validation and `getapimeta`. The rest of the discovery protocol is covered by `di.torq.proc.discovery`'s suite. Run in a fresh diff --git a/di/torq/servers/servers.q b/di/torq/servers/servers.q index 80bf783c5..3e70fc78f 100644 --- a/di/torq/servers/servers.q +++ b/di/torq/servers/servers.q @@ -359,6 +359,8 @@ reqprocsnotconn:{[requiredprocs;typeorname] not all requiredprocs in ?[`.servers.SERVERS;enlist (`.dotz.liveh;`w);();typeorname] }; +reqproctypesnotconn:reqprocsnotconn[;`proctype]; + reqprocnamesnotconn:reqprocsnotconn[;`procname]; / block until all required processes are connected @@ -379,3 +381,7 @@ startupdepcyclestypename:{[requiredprocs;typeornamefunc;timeintv;cycles] / root, for chainedtp and segmentedtp .servers.startupdepnamecycles:startupdepcyclestypename[;reqprocnamesnotconn;;]; + +/ root, as TorQ's: block until all required proctypes are connected, for a number of cycles or forever +.servers.startupdepcycles:startupdepcyclestypename[;reqproctypesnotconn;;]; +.servers.startupdependent:startupdepcyclestypename[;reqproctypesnotconn;;0W]; diff --git a/di/torq/servers/test.csv b/di/torq/servers/test.csv index 85f2ed3db..e93604063 100644 --- a/di/torq/servers/test.csv +++ b/di/torq/servers/test.csv @@ -51,6 +51,11 @@ true,0,0,q,"0=count .servers.getservers[`proctype;`deadproc;()!();0b;0b]",1,1,ge run,0,0,q,".servers.startupdepnamecycles[`otherinst;0;1]",1,1,startupdepnamecycles returns once otherinst is connected fail,0,0,q,".servers.startupdepnamecycles[`nosuchinst;0;0]",1,1,startupdepnamecycles signals after its cycles are used up true,0,0,q,`connectionreport in exec ctx from logrows where lvl=`error,1,1,the failure was logged as a connectionreport error +run,0,0,q,".servers.startupdepcycles[`otherproc;0;1]",1,1,startupdepcycles returns once otherproc is connected +fail,0,0,q,".servers.startupdepcycles[`deadproc;0;0]",1,1,startupdepcycles signals after its cycles are used up +true,0,0,q,"any (exec msg from logrows where lvl=`error,ctx=`connectionreport) like ""*cannot connect to deadproc""",1,1,the error names the proctype it could not reach +run,0,0,q,".servers.startupdependent[`otherproc;0]",1,1,startupdependent returns once otherproc is connected +true,0,0,q,0W~last value .servers.startupdependent,1,1,startupdependent never gives up waiting (its cycle count is 0W) comment,,,,,,,waitfortype - discovery comes up after startup run,0,0,q,setupdisc[],1,1,add a discovery row to process.csv and write a discovery stub naming a tpproc peer run,0,0,q,"svc.init[svrdeps[`tpproc],`discoveryregister`connectionsfromdiscovery!11b]",1,1,re-init taking connections from discovery From 4a237581e97b26fe5e6a218758c701c2de94d8d7 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 20 Oct 2026 12:10:07 +0100 Subject: [PATCH 08/39] di.torq.config: run its test fixtures under a per-run directory The suite wrote to fixed /tmp/diconfig* directories, so on a shared host it failed in setup when another user owned them and ran no rows. Fixtures now live under /tmp/diconfig_/, built from TD, and are removed after the run. Test logic is unchanged. Co-Authored-By: Claude Opus 5.5 --- di/torq/config/test.csv | 64 +++++++++++++++++++++-------------------- 1 file changed, 33 insertions(+), 31 deletions(-) diff --git a/di/torq/config/test.csv b/di/torq/config/test.csv index 712c95b44..c1bb5a1be 100644 --- a/di/torq/config/test.csv +++ b/di/torq/config/test.csv @@ -1,45 +1,46 @@ action,ms,bytes,lang,code,repeat,minver,comment before,0,0,q,cfg:use`di.torq.config,1,1,load the module +before,0,0,q,"TD:""/tmp/diconfig_"",(string .z.i),""/""",1,1,per-run fixture root so concurrent or other-user runs never collide before,0,0,q,"logtab:([]lvl:`symbol$();ctx:`symbol$();msg:())",1,1,capturing log table before,0,0,q,"mocklog:`info`warn`error!({[c;m]`logtab upsert(`info;c;m)};{[c;m]`logtab upsert(`warn;c;m)};{[c;m]`logtab upsert(`error;c;m)})",1,1,define a capturing binary logger before,0,0,q,cfg.init[enlist[`log]!enlist mocklog],1,1,init with the required log dependency -before,0,0,q,"system""mkdir -p /tmp/diconfigbuiltin""",1,1,builtin root for the cascade -before,0,0,q,"system""mkdir -p /tmp/diconfigapp""",1,1,app root for the cascade -before,0,0,q,"(`:/tmp/diconfigbuiltin/default.q) 0: (""diconfiga:1"";""diconfigb:1"")",1,1,builtin/default flat name:value (two settings) -before,0,0,q,"(`:/tmp/diconfigbuiltin/rdb.q) 0: enlist ""diconfigb:10""",1,1,builtin/rdb proctype tier sets diconfigb -before,0,0,q,"(`:/tmp/diconfigapp/default.q) 0: (""diconfiga:100"";""diconfigb:5"")",1,1,app/default flat name:value (two settings) -before,0,0,q,"(`:/tmp/diconfigapp/rdb1.q) 0: enlist ""diconfiga:999""",1,1,app/rdb1 procname tier sets diconfiga +before,0,0,q,"system ""mkdir -p "",TD,""builtin""",1,1,builtin root for the cascade +before,0,0,q,"system ""mkdir -p "",TD,""app""",1,1,app root for the cascade +before,0,0,q,"(hsym`$TD,""builtin/default.q"") 0: (""diconfiga:1"";""diconfigb:1"")",1,1,builtin/default flat name:value (two settings) +before,0,0,q,"(hsym`$TD,""builtin/rdb.q"") 0: enlist ""diconfigb:10""",1,1,builtin/rdb proctype tier sets diconfigb +before,0,0,q,"(hsym`$TD,""app/default.q"") 0: (""diconfiga:100"";""diconfigb:5"")",1,1,app/default flat name:value (two settings) +before,0,0,q,"(hsym`$TD,""app/rdb1.q"") 0: enlist ""diconfiga:999""",1,1,app/rdb1 procname tier sets diconfiga before,0,0,q,"basecfg:`enabled`rows`syms`tab`byte`str!(0b;100;`a`b;([]a:`long$());0x01;"":olddb"")",1,1,base config dict for the overrideconfig tests (str is a char-string setting, as a .toml value would be) -before,0,0,q,"system""mkdir -p /tmp/diconfigskip""",1,1,dir for the malformed-line skip test -before,0,0,q,"(`:/tmp/diconfigskip/default.q) 0: (""a:1"";"""";""/ a comment"";""straynocolon"";""b:2"")",1,1,a .q file mixing valid pairs with blank/comment/no-colon lines -before,0,0,q,"system""mkdir -p /tmp/diconfigtoml""",1,1,dir for the toml-guard test -before,0,0,q,"(`:/tmp/diconfigtoml/present.toml) 0: enlist ""a = 1""",1,1,a .toml file that config parses by delegating to the reconciled di.util.toml (present on QPATH) +before,0,0,q,"system ""mkdir -p "",TD,""skip""",1,1,dir for the malformed-line skip test +before,0,0,q,"(hsym`$TD,""skip/default.q"") 0: (""a:1"";"""";""/ a comment"";""straynocolon"";""b:2"")",1,1,a .q file mixing valid pairs with blank/comment/no-colon lines +before,0,0,q,"system ""mkdir -p "",TD,""toml""",1,1,dir for the toml-guard test +before,0,0,q,"(hsym`$TD,""toml/present.toml"") 0: enlist ""a = 1""",1,1,a .toml file that config parses by delegating to the reconciled di.util.toml (present on QPATH) comment,,,,,,,init - dependency validation fail,0,0,q,cfg.init[(::)],1,1,init rejects a non-dictionary deps fail,0,0,q,cfg.init[enlist[`foo]!enlist 1],1,1,init rejects deps without a log key fail,0,0,q,cfg.init[enlist[`log]!enlist 42],1,1,init rejects a non-dict log value fail,0,0,q,cfg.init[enlist[`log]!enlist ((enlist`info)!enlist {[c;m]})],1,1,init rejects a log dict missing warn/error comment,,,,,,,parsefile - parse one flat .q settings file into a dict (.toml delegated to di.util.toml) -true,0,0,q,"1~cfg.parsefile[""/tmp/diconfigbuiltin/default.q""]`diconfiga",1,1,parsefile reads a flat name:value .q file into a dict -true,0,0,q,"2=count cfg.parsefile[""/tmp/diconfigbuiltin/default.q""]",1,1,parsefile returns every setting in the file -true,0,0,q,"0=count cfg.parsefile[""/tmp/diconfignope/default.q""]",1,1,parsefile returns an empty dict for a missing .q file -true,0,0,q,"(`a`b!1 2)~cfg.parsefile[""/tmp/diconfigskip/default.q""]",1,1,parsefile skips blank/comment/no-colon lines and returns only valid pairs (no-colon line must not crash the split) +true,0,0,q,"1~cfg.parsefile[(TD,""builtin/default.q"")]`diconfiga",1,1,parsefile reads a flat name:value .q file into a dict +true,0,0,q,"2=count cfg.parsefile[(TD,""builtin/default.q"")]",1,1,parsefile returns every setting in the file +true,0,0,q,"0=count cfg.parsefile[(TD,""nope/default.q"")]",1,1,parsefile returns an empty dict for a missing .q file +true,0,0,q,"(`a`b!1 2)~cfg.parsefile[(TD,""skip/default.q"")]",1,1,parsefile skips blank/comment/no-colon lines and returns only valid pairs (no-colon line must not crash the split) comment,,,,,,,parsefile - .toml integration with the reconciled di.util.toml (existence guarded first; existing .toml delegated) -true,0,0,q,"0=count cfg.parsefile[""/tmp/diconfignope/absent.toml""]",1,1,a MISSING .toml contributes nothing and does NOT require di.util.toml (existence checked before delegation) -true,0,0,q,"1j~(cfg.parsefile[""/tmp/diconfigtoml/present.toml""])`a",1,1,an EXISTING .toml now parses by delegating to di.util.toml (present on QPATH) -true,0,0,q,"-7h=type (cfg.parsefile[""/tmp/diconfigtoml/present.toml""])`a",1,1,the .toml integer came back a long - di.util.toml's typed parse flows through config.parsefile +true,0,0,q,"0=count cfg.parsefile[(TD,""nope/absent.toml"")]",1,1,a MISSING .toml contributes nothing and does NOT require di.util.toml (existence checked before delegation) +true,0,0,q,"1j~(cfg.parsefile[(TD,""toml/present.toml"")])`a",1,1,an EXISTING .toml now parses by delegating to di.util.toml (present on QPATH) +true,0,0,q,"-7h=type (cfg.parsefile[(TD,""toml/present.toml"")])`a",1,1,the .toml integer came back a long - di.util.toml's typed parse flows through config.parsefile comment,,,,,,,cascade - merged flat dict over two roots x default/proctype/procname (name-major; .toml>.q within a tier) -true,0,0,q,"100~(cfg.cascade[""/tmp/diconfigbuiltin"";""/tmp/diconfigapp"";`rdb;`rdbnofile])`diconfiga",1,1,within a name the later (app) root overrides the builtin root -true,0,0,q,"10~(cfg.cascade[""/tmp/diconfigbuiltin"";""/tmp/diconfigapp"";`rdb;`rdbnofile])`diconfigb",1,1,name-major: builtin proctype beats app default (would be 5 under root-major) -true,0,0,q,"999~(cfg.cascade[""/tmp/diconfigbuiltin"";""/tmp/diconfigapp"";`rdb;`rdb1])`diconfiga",1,1,name-major: the procname tier (app/rdb1) wins over every less-specific name -true,0,0,q,"10~(cfg.cascade[""/tmp/diconfigbuiltin"";""/tmp/diconfigapp"";`rdb;`rdb1])`diconfigb",1,1,a key absent from the procname tier keeps its most-specific set value (builtin proctype) -true,0,0,q,"not (`) in key cfg.cascade[""/tmp/diconfigbuiltin"";""/tmp/diconfigapp"";`rdb;`rdb1]",1,1,the sentinel merge key is dropped from the returned dict -true,0,0,q,"0=count cfg.cascade[""/tmp/diconfignope1"";""/tmp/diconfignope2"";`rdb;`rdb1]",1,1,an all-missing cascade resolves to an empty dict -true,0,0,q,"10~(cfg.cascade[""/tmp/diconfigbuiltin"";""/tmp/diconfigapp"";`rdb;`default])`diconfigb",1,1,dedup: procname=`default must NOT re-apply the default tier last and override proctype (would be 5 without distinct) -true,0,0,q,"100~(cfg.cascade[""/tmp/diconfigbuiltin"";""/tmp/diconfigapp"";`rdb;`rdb])`diconfiga",1,1,dedup: proctype~procname resolves correctly (each tier once) -fail,0,0,q,"cfg.cascade[""/tmp/diconfigbuiltin"";""/tmp/diconfigapp"";`rdb;(`)]",1,1,cascade rejects a null procname (else it resolves a bogus root/.q tier) -fail,0,0,q,"cfg.cascade[""/tmp/diconfigbuiltin"";""/tmp/diconfigapp"";(`);`rdb1]",1,1,cascade rejects a null proctype -fail,0,0,q,"cfg.cascade[""/tmp/diconfigbuiltin"";""/tmp/diconfigapp"";""rdb"";`rdb1]",1,1,cascade rejects a non-symbol (string) proctype +true,0,0,q,"100~(cfg.cascade[(TD,""builtin"");(TD,""app"");`rdb;`rdbnofile])`diconfiga",1,1,within a name the later (app) root overrides the builtin root +true,0,0,q,"10~(cfg.cascade[(TD,""builtin"");(TD,""app"");`rdb;`rdbnofile])`diconfigb",1,1,name-major: builtin proctype beats app default (would be 5 under root-major) +true,0,0,q,"999~(cfg.cascade[(TD,""builtin"");(TD,""app"");`rdb;`rdb1])`diconfiga",1,1,name-major: the procname tier (app/rdb1) wins over every less-specific name +true,0,0,q,"10~(cfg.cascade[(TD,""builtin"");(TD,""app"");`rdb;`rdb1])`diconfigb",1,1,a key absent from the procname tier keeps its most-specific set value (builtin proctype) +true,0,0,q,"not (`) in key cfg.cascade[(TD,""builtin"");(TD,""app"");`rdb;`rdb1]",1,1,the sentinel merge key is dropped from the returned dict +true,0,0,q,"0=count cfg.cascade[(TD,""nope1"");(TD,""nope2"");`rdb;`rdb1]",1,1,an all-missing cascade resolves to an empty dict +true,0,0,q,"10~(cfg.cascade[(TD,""builtin"");(TD,""app"");`rdb;`default])`diconfigb",1,1,dedup: procname=`default must NOT re-apply the default tier last and override proctype (would be 5 without distinct) +true,0,0,q,"100~(cfg.cascade[(TD,""builtin"");(TD,""app"");`rdb;`rdb])`diconfiga",1,1,dedup: proctype~procname resolves correctly (each tier once) +fail,0,0,q,"cfg.cascade[(TD,""builtin"");(TD,""app"");`rdb;(`)]",1,1,cascade rejects a null procname (else it resolves a bogus root/.q tier) +fail,0,0,q,"cfg.cascade[(TD,""builtin"");(TD,""app"");(`);`rdb1]",1,1,cascade rejects a null proctype +fail,0,0,q,"cfg.cascade[(TD,""builtin"");(TD,""app"");""rdb"";`rdb1]",1,1,cascade rejects a non-symbol (string) proctype comment,,,,,,,overrideconfig - command-line override layer applied onto a resolved config dict true,0,0,q,"1b~(cfg.overrideconfig[basecfg;`enabled`rows!(enlist""1"";enlist""500"")])`enabled",1,1,bool parsed and set from string true,0,0,q,"500~(cfg.overrideconfig[basecfg;`enabled`rows!(enlist""1"";enlist""500"")])`rows",1,1,long parsed and set from string @@ -75,12 +76,13 @@ true,0,0,q,0b~(1!cfg.getapimeta[])[`init]`public,1,1,framework plumbing (init) i comment,,,,,,,logger emission - real logger via a caller-side binary wrapper (must run last; re-inits cfg) run,0,0,q,kxlogger:use`kx.log,1,1,load the kx.log module run,0,0,q,kxinst:kxlogger.createLog[],1,1,create a real kx.log instance -run,0,0,q,kxh:hopen `:/tmp/diconfigkxsink.txt,1,1,open a file sink to capture output +run,0,0,q,"kxh:hopen hsym`$TD,""kxsink.txt""",1,1,open a file sink to capture output run,0,0,q,kxinst.add[kxh;`info],1,1,route info-level output to the file sink run,0,0,q,"kxbinary:`info`warn`error!({[c;m]kxinst[`info][string[c],"": "",m]};{[c;m]kxinst[`warn][string[c],"": "",m]};{[c;m]kxinst[`error][string[c],"": "",m]})",1,1,wrap the monadic logger into the binary {[c;m]} contract run,0,0,q,cfg.init[enlist[`log]!enlist kxbinary],1,1,re-init di.torq.config with the conforming binary logger run,0,0,q,"kxres:cfg.overrideconfig[enlist[`kxrows]!enlist 5;enlist[`kxrows]!enlist enlist""7""]",1,1,drive a real info-level log through the wrapped logger run,0,0,q,hclose kxh,1,1,flush and close the file sink true,0,0,q,7~kxres`kxrows,1,1,the override was applied (returned dict carries the new value) -true,0,0,q,"any (read0 `:/tmp/diconfigkxsink.txt) like ""*overrideconfig: setting*""",1,1,the override emitted an info line through the real logger -true,0,0,q,"any (read0 `:/tmp/diconfigkxsink.txt) like ""*kxrows*""",1,1,emitted message names the overridden setting +true,0,0,q,"any (read0 hsym`$TD,""kxsink.txt"") like ""*overrideconfig: setting*""",1,1,the override emitted an info line through the real logger +true,0,0,q,"any (read0 hsym`$TD,""kxsink.txt"") like ""*kxrows*""",1,1,emitted message names the overridden setting +after,0,0,q,"system ""rm -rf "",TD",1,1,remove this run's fixture root From d3ee4b4bd8d6866e91c2c19b76706b41e1c3b486 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 20 Oct 2026 12:39:13 +0100 Subject: [PATCH 09/39] di.timer: timespan periods, mode and dupcheck checks, legacy first-run timing; migrate callers As TorQ's timer.q, which the port is moving to: - period is a timespan, as .timer.repeat takes it; addjob rejects any other period type, and any mode outside the scheduling modes, before the job is stored (a stored bad row stopped the scheduler on every tick) - a job with the same function and parameters as an existing one is rejected unless dupcheck is 0b; dupcheck defaults on, as repeat/once - modes 1-3 first run: an unset start runs now, a past start aligns forward on its period (no catch-up burst); once is due at its runtime as given - a description column and opts key - mode 5 buckets on the period's minutes Callers in subscriptions, torq, logroll, housekeeping (dupcheck 0b, as legacy housekeeping.q:157), gateway, chainedtp, servers, tickerplant, segmentedtp, wdb and dataaccess pass timespans in the same commit, so no commit breaks. Their test mocks record timespans. timer, servers, subscriptions, logroll and asyncdispatch docs updated. Co-Authored-By: Claude Opus 5.5 --- di/asyncdispatch/asyncdispatch.md | 16 +-- di/dataaccess/dataaccess.q | 2 +- di/subscriptions/subscriptions.md | 2 +- di/subscriptions/subscriptions.q | 2 +- di/subscriptions/test.csv | 2 +- di/subscriptions/test.q | 4 +- di/timer/init.q | 40 +++++--- di/timer/test.csv | 125 ++++++++++++++++------- di/timer/timer.md | 39 +++---- di/torq/logroll/logroll.md | 4 +- di/torq/logroll/logroll.q | 2 +- di/torq/logroll/test.csv | 2 +- di/torq/proc/chainedtp/chainedtp.q | 2 +- di/torq/proc/gateway/gateway.q | 10 +- di/torq/proc/housekeeping/housekeeping.q | 2 +- di/torq/proc/housekeeping/test.csv | 2 +- di/torq/proc/housekeeping/test.q | 6 +- di/torq/proc/segmentedtp/segmentedtp.q | 2 +- di/torq/proc/segmentedtp/test.csv | 2 +- di/torq/proc/tickerplant/test.q | 8 +- di/torq/proc/tickerplant/tickerplant.q | 4 +- di/torq/proc/wdb/wdb.q | 4 +- di/torq/servers/servers.md | 2 +- di/torq/servers/servers.q | 4 +- di/torq/servers/test.csv | 2 +- di/torq/servers/test.q | 2 +- di/torq/torq.q | 2 +- 27 files changed, 180 insertions(+), 114 deletions(-) diff --git a/di/asyncdispatch/asyncdispatch.md b/di/asyncdispatch/asyncdispatch.md index 869aea4f0..fdcdad77c 100644 --- a/di/asyncdispatch/asyncdispatch.md +++ b/di/asyncdispatch/asyncdispatch.md @@ -127,28 +127,28 @@ ad.execqueryto[0Ni;shardquery;servertypes;raze;(`da.shardresult;reqid);0Wn;0b] Scan the queue for queries past their timeout, send a timeout error to each client, and mark them complete. Wire into your gateway's timer — every few seconds is typical. ```q // in gateway timer -timer.addjob.default[`asyncdispatch.checktimeout;{ad.checktimeout[]};();5i;1] +timer.addjob.default[`asyncdispatch.checktimeout;{ad.checktimeout[]};();0D00:00:05;1] ``` ### `removequeries[age]` Purge completed `queryqueue` rows older than `age`. Prevents unbounded growth. ```q // default age is querykeeptime (0D00:30) -timer.addjob.default[`asyncdispatch.removequeries;{ad.removequeries[0D00:30]};();300i;1] +timer.addjob.default[`asyncdispatch.removequeries;{ad.removequeries[0D00:30]};();0D00:05;1] ``` ### `removeinactive[age]` Purge `servers` rows for backends that have been disconnected longer than `age`. Prevents unbounded growth. ```q // default age is clearinactivetime (0D01:00) -timer.addjob.default[`asyncdispatch.removeinactive;{ad.removeinactive[0D01:00]};();300i;1] +timer.addjob.default[`asyncdispatch.removeinactive;{ad.removeinactive[0D01:00]};();0D00:05;1] ``` ### `removeclients[age]` Purge `clients` rows older than `age`. The `clients` table is appended to on every client connect (`addclientdetails`) for audit and is not otherwise pruned, so wire this into the timer to prevent unbounded growth. Choose `age` to match your audit retention requirements. ```q // retain one day of client audit history -timer.addjob.default[`asyncdispatch.removeclients;{ad.removeclients[1D]};();300i;1] +timer.addjob.default[`asyncdispatch.removeclients;{ad.removeclients[1D]};();0D00:05;1] ``` ### `setformatresponse[f]` @@ -210,10 +210,10 @@ ad.addserver[hopen`:backend2:5002;`hdb] .z.pc:{ad.removeserverhandle[.z.w];ad.removeclienthandle[.z.w]} // wire housekeeping into the gateway timer -timer.addjob.default[`asyncdispatch.checktimeout;{ad.checktimeout[]};();5i;1] -timer.addjob.default[`asyncdispatch.removequeries;{ad.removequeries[0D00:30]};();300i;1] -timer.addjob.default[`asyncdispatch.removeinactive;{ad.removeinactive[0D01:00]};();300i;1] -timer.addjob.default[`asyncdispatch.removeclients;{ad.removeclients[1D]};();300i;1] +timer.addjob.default[`asyncdispatch.checktimeout;{ad.checktimeout[]};();0D00:00:05;1] +timer.addjob.default[`asyncdispatch.removequeries;{ad.removequeries[0D00:30]};();0D00:05;1] +timer.addjob.default[`asyncdispatch.removeinactive;{ad.removeinactive[0D01:00]};();0D00:05;1] +timer.addjob.default[`asyncdispatch.removeclients;{ad.removeclients[1D]};();0D00:05;1] // a client calls this asynchronously: // execquery dispatches to rdb and hdb in parallel, razes results, replies to client diff --git a/di/dataaccess/dataaccess.q b/di/dataaccess/dataaccess.q index bf73c6860..174e64a9f 100644 --- a/di/dataaccess/dataaccess.q +++ b/di/dataaccess/dataaccess.q @@ -341,5 +341,5 @@ init:{[deps] set[`.dataaccess.shardresult;shardresult]; set[`.dataaccess.sharderror;sharderror]; .z.m.log[`info][`init;"di.dataaccess initialised"]; - (.z.m.timer`addjob)[`dataaccesspurge;removerequests;enlist .z.m.requestkeeptime;1800;1h;()!()]; + (.z.m.timer`addjob)[`dataaccesspurge;removerequests;enlist .z.m.requestkeeptime;0D00:30;1h;()!()]; }; diff --git a/di/subscriptions/subscriptions.md b/di/subscriptions/subscriptions.md index 74863a5b7..d2bc71c91 100644 --- a/di/subscriptions/subscriptions.md +++ b/di/subscriptions/subscriptions.md @@ -65,7 +65,7 @@ publisher for its `tptype` (`standard`, `chained` or `segmented`) and subscribes - Settings, both required; `di/torq/settings/default.q` declares them: `autoreconnect` (`0b`), `checksubscriptionperiod` (`0D00:00:10`). - `init` registers, once per process: `pc[::;]` on `.z.pc` through `handlers`, and - `checksubscriptions` every `checksubscriptionperiod` (converted to seconds, timer mode 1) through + `checksubscriptions` every `checksubscriptionperiod` (a timespan, timer mode 1) through `timer` when the period is above 0. ## Not yet (future) diff --git a/di/subscriptions/subscriptions.q b/di/subscriptions/subscriptions.q index 8d1e20926..002c1000d 100644 --- a/di/subscriptions/subscriptions.q +++ b/di/subscriptions/subscriptions.q @@ -28,7 +28,7 @@ init:{[config;deps] .z.m.checksubscriptionperiod:(not @[value;`.proc.lowpowermode;0b])*config`checksubscriptionperiod; if[not .z.m.registered; (deps[`handlers]`register)[`.z.pc;`;`sub;0j;pc[::;]]; - if[checksubscriptionperiod>0;(deps[`timer]`addjob)[`checksubscriptions;checksubscriptions;();`long$checksubscriptionperiod%0D00:00:01;1;()!()]]; + if[checksubscriptionperiod>0;(deps[`timer]`addjob)[`checksubscriptions;checksubscriptions;();checksubscriptionperiod;1;()!()]]; .z.m.registered:1b]; } diff --git a/di/subscriptions/test.csv b/di/subscriptions/test.csv index ee5269d14..43cb1761c 100644 --- a/di/subscriptions/test.csv +++ b/di/subscriptions/test.csv @@ -26,7 +26,7 @@ true,0,0,q,`S1=first trade`sym,1,,the replayed row is the subscribed sym comment,,,,,,,.sub at root true,0,0,q,"1=count select from handlercalls where event=`.z.pc,name=`sub",1,,init registered pc on .z.pc -true,0,0,q,"(enlist(`checksubscriptions;10;1))~flip value flip timercalls",1,,init registered checksubscriptions every 10s +true,0,0,q,"(enlist(`checksubscriptions;0D00:00:10;1))~flip value flip timercalls",1,,init registered checksubscriptions every 10s run,0,0,q,sub.init[subcfg ()!();deps[]],1,,init again true,0,0,q,"(1;1)~(count handlercalls;count timercalls)",1,,second init registers nothing new true,0,0,q,"((subcfg ()!())`autoreconnect`checksubscriptionperiod)~.m.di.0subscriptions.autoreconnect,.m.di.0subscriptions.checksubscriptionperiod",1,,init stores the settings file values diff --git a/di/subscriptions/test.q b/di/subscriptions/test.q index 0717e1ccc..8a70214ef 100644 --- a/di/subscriptions/test.q +++ b/di/subscriptions/test.q @@ -17,8 +17,8 @@ calls:([]lvl:`symbol$();ctx:`symbol$();msg:()) resetcalls:{[] `calls set ([]lvl:`symbol$();ctx:`symbol$();msg:()); } mocklogfn:{[lvl;ctx;msg] `calls insert (lvl;ctx;msg); } mocklog:{[] `info`warn`error!(mocklogfn[`info;;];mocklogfn[`warn;;];mocklogfn[`error;;])} -timercalls:([]id:`symbol$();period:`long$();mode:`long$()) -mocktimer:enlist[`addjob]!enlist {[id;func;params;period;mode;opts] `timercalls upsert (id;`long$period;`long$mode);} +timercalls:([]id:`symbol$();period:`timespan$();mode:`long$()) +mocktimer:enlist[`addjob]!enlist {[id;func;params;period;mode;opts] `timercalls upsert (id;period;`long$mode);} handlercalls:([]event:`symbol$();name:`symbol$()) mockhandlers:enlist[`register]!enlist {[ev;ph;nm;pri;fn] `handlercalls upsert (ev;nm);} deps:{[] `log`timer`handlers!(mocklog[];mocktimer;mockhandlers)} diff --git a/di/timer/init.q b/di/timer/init.q index 54384e92e..6db9344bf 100644 --- a/di/timer/init.q +++ b/di/timer/init.q @@ -9,7 +9,7 @@ jobs:( func:(); / function to be ran, can be passed as symbol reference or as a function itself params:(); / function parameters to be passed to function at execution created:`timestamp$(); / timestamp of function initiation - period:`int$(); / time period to base timer scheduling on + period:`timespan$(); / time period to base timer scheduling on mode:`short$(); / mode to base scheduling logic on prevstart:`timestamp$(); / scheduled start timestamp of previous run actualstart:`timestamp$(); / start timestamp of previous run @@ -20,20 +20,32 @@ jobs:( maxruns:`int$(); / optional flag to disable time function after number of runs maxtime:`timestamp$(); / optional flag to disable job after timestamp disableonfail:`boolean$(); / if job fails will disable future runs - startattime:`timestamp$() / optional custom start time to run for the first time + startattime:`timestamp$(); / optional custom start time to run for the first time + description:() / free text description, as TorQ's timer ); / job functions for adding new functions to be scheduled and executed -addjob.opts:(`maxruns`maxtime`disableonfail`startattime)!(0Wi;0Wp;1b;0Np); +addjob.opts:(`maxruns`maxtime`disableonfail`startattime`dupcheck`description)!(0Wi;0Wp;1b;0Np;1b;""); + +/ jobs running function f with parameters p +fpjobs:{[f;p] select from jobs where (f~/:func)&((),p)~/:params}; addjob.custom:{[id;func;params;period;mode;opts] / fully configurable base version of adding a timer job to in memory table if[id in key .z.M.jobs;'"Cannot add id : ",(string id)," already exists in jobs"]; + / as TorQ's .timer.rep, the period is a timespan and the mode one of the scheduling modes + if[-16h<>type period;'"period must be a timespan"]; + if[not (mode:`short$mode) in key nextstart;'"mode can only be one of ",-3!key nextstart]; if[-11h=type func;get func]; opts:addjob.opts,opts; - row:cols[.z.M.jobs]!(id;func;(),params;cp[];`int$period;`short$mode;0Np;0Np;0Np;0Np;0i;1b;`int$(opts`maxruns);opts`maxtime;opts`disableonfail;opts`startattime); + / as TorQ's timer check, a duplicate function and parameters is rejected unless dupcheck is off + if[opts[`dupcheck]&0type c;c;first c / assertion helpers factored here because they contain raw commas (which split CSV fields) loghas:{[sub;n] n=logcount[BASE,"/",sub]} -flushperiodok:{[] 2=first exec period from timercalls where id=`tpflush} +flushperiodok:{[] 0D00:00:02=first exec period from timercalls where id=`tpflush} rolledfile:{[sub;date] not ()~key hsym`$BASE,"/",sub,"/tp",string date} / init helpers that store handles / state for assertions diff --git a/di/torq/proc/tickerplant/tickerplant.q b/di/torq/proc/tickerplant/tickerplant.q index 36ce49282..025cf5979 100644 --- a/di/torq/proc/tickerplant/tickerplant.q +++ b/di/torq/proc/tickerplant/tickerplant.q @@ -184,9 +184,9 @@ init:{[config;deps] ]; / timer jobs: EOD roll check every second; batched flush every pubperiod seconds - (.z.m.timer`addjob)[`tpeodcheck;eodcheck;();1;1h;()!()]; + (.z.m.timer`addjob)[`tpeodcheck;eodcheck;();0D00:00:01;1h;()!()]; if[.z.m.publishmode=`batched; - (.z.m.timer`addjob)[`tpflush;flush;();.z.m.pubperiod;1h;()!()]]; + (.z.m.timer`addjob)[`tpflush;flush;();0D00:00:01*.z.m.pubperiod;1h;()!()]]; .z.m.log[`info][`tickerplant;"initialised, mode=",(string .z.m.publishmode),", tables=",", " sv string tabs]; } diff --git a/di/torq/proc/wdb/wdb.q b/di/torq/proc/wdb/wdb.q index ff69bf3d9..a7b803c64 100644 --- a/di/torq/proc/wdb/wdb.q +++ b/di/torq/proc/wdb/wdb.q @@ -262,7 +262,7 @@ doreload:{[pt] getprocs[;pt] each ro; $[.z.m.eodwaittime>0; [@[.z.m.timer`deletejobs;`sortflushend;{}]; - (.z.m.timer`addjob)[`sortflushend;flushend;();1;1h;`startattime`maxruns!(.z.m.timeouttime;1)]]; + (.z.m.timer`addjob)[`sortflushend;flushend;();0D00:00:01;1h;`startattime`maxruns!(.z.m.timeouttime;1)]]; flushend[]]; } @@ -749,7 +749,7 @@ init:{[config;deps] / addjob raises on an id that already exists, so clear any job a previous init left @[.z.m.timer`deletejobs;`wdbsave;{}]; / mode 3h reschedules from the end of the previous flush, as TorQ's .timer.repeat does - (.z.m.timer`addjob)[`wdbsave;savetodisk;();.z.m.settimer;3h;()!()]; + (.z.m.timer`addjob)[`wdbsave;savetodisk;();0D00:00:01*.z.m.settimer;3h;()!()]; msg:"initialised, mode=",(string .z.m.mode),", writedownmode=",(string .z.m.writedownmode),", savedir=",.z.m.savedirs; msg,:", hdbdir=",(1_string .z.m.hdbdir),", flush every ",(string .z.m.settimer),"s"; .z.m.log[`info][`wdb;msg,$[.z.m.sortenabled;"";", sort handed to ",", " sv string .z.m.sorttypes]]; diff --git a/di/torq/servers/servers.md b/di/torq/servers/servers.md index db9099c01..15bc38001 100644 --- a/di/torq/servers/servers.md +++ b/di/torq/servers/servers.md @@ -120,7 +120,7 @@ peers. Peers call discovery's root `register` (as `` `..register ``) and `getser **Conversions** (legacy calls with no di equivalent): - `.lg.*` becomes the injected `log`. - `.dotz.set` on `.z.pc` becomes `handlers[`register]`. -- `.timer.repeat` becomes `timer[`addjob]`, mode 3 (next run from finish), period in seconds. +- `.timer.repeat` becomes `timer[`addjob]`, mode 3 (next run from finish), period as a timespan. - `.proc.cp[]` becomes `.z.p`. - `.proc.procname`/`proctype` in `getdetails` become init's identity. - `.proc.readprocs` becomes `readprocesscsv`. diff --git a/di/torq/servers/servers.q b/di/torq/servers/servers.q index 3e70fc78f..496a6befa 100644 --- a/di/torq/servers/servers.q +++ b/di/torq/servers/servers.q @@ -80,8 +80,8 @@ init:{[deps] (.z.m.handlers[`register])[`.z.pc;`;`servers;0j;pc]; / retry timers if[.servers.enabled; - if[.servers.DISCOVERYRETRY>0;(.z.m.timer[`addjob])[`discoveryretry;retrydiscovery;();`long$.servers.DISCOVERYRETRY%0D00:00:01;3;()!()]]; - if[.servers.RETRY>0;(.z.m.timer[`addjob])[`serversretry;retry;();`long$.servers.RETRY%0D00:00:01;3;()!()]]]; + if[.servers.DISCOVERYRETRY>0;(.z.m.timer[`addjob])[`discoveryretry;retrydiscovery;();.servers.DISCOVERYRETRY;3;()!()]]; + if[.servers.RETRY>0;(.z.m.timer[`addjob])[`serversretry;retry;();.servers.RETRY;3;()!()]]]; .z.m.registered:1b; ]; .z.m.loginfo[`init;"di.torq.servers initialised"]; diff --git a/di/torq/servers/test.csv b/di/torq/servers/test.csv index e93604063..fa775413b 100644 --- a/di/torq/servers/test.csv +++ b/di/torq/servers/test.csv @@ -13,7 +13,7 @@ comment,,,,,,,init - wiring and idempotency run,0,0,q,svc.init[svrdeps[`otherproc`deadproc]],1,1,init with mock deps + config (dial otherproc and deadproc) true,0,0,q,"1=count select from handlercalls where event=`.z.pc,name=`servers",1,1,init registered its .z.pc observer via the handlers dep true,0,0,q,1=count select from timercalls where id=`serversretry,1,1,init scheduled the retry job via the timer dep -true,0,0,q,300=first exec period from timercalls where id=`serversretry,1,1,retry period is 300s +true,0,0,q,0D00:05=first exec period from timercalls where id=`serversretry,1,1,retry period is 5 minutes true,0,0,q,3 3~exec mode from timercalls where id in `serversretry`discoveryretry,1,1,both jobs use timer mode 3 true,0,0,q,1=count select from timercalls where id=`discoveryretry,1,1,init scheduled the discoveryretry job true,0,0,q,.servers.enabled,1,1,enabled defaults to 1b diff --git a/di/torq/servers/test.q b/di/torq/servers/test.q index 2f7a86351..c10dc3c33 100644 --- a/di/torq/servers/test.q +++ b/di/torq/servers/test.q @@ -13,7 +13,7 @@ mocklog:`info`warn`error!( / timer mock: records (id;period;mode) for the wiring asserts AND captures each job's func by id, so a / test can fire the retry cycle exactly as the real timer would (retry/cleanup are INTERNAL - not / exported - so they are driven only via this captured callback). -timercalls:([]id:`symbol$();period:`long$();mode:`long$()); +timercalls:([]id:`symbol$();period:`timespan$();mode:`long$()); timerjobs:(`symbol$())!(); mocktimer:enlist[`addjob]!enlist {[id;func;params;period;mode;opts] timerjobs[id]:func; `timercalls upsert (id;period;`long$mode);}; diff --git a/di/torq/torq.q b/di/torq/torq.q index f5a90c06b..b66ce4625 100644 --- a/di/torq/torq.q +++ b/di/torq/torq.q @@ -231,7 +231,7 @@ initquerylog:{[config;deps] ft:"j"$opt[`flushtime;86400]; if[ft>0; .z.m.qlflushtime:ft*0D00:00:01; - (deps[`timer][`addjob])[`querylogflush;flushquerylog;();"j"$opt[`flushinterval;1800];3h;()!()]]; + (deps[`timer][`addjob])[`querylogflush;flushquerylog;();0D00:00:01*"j"$opt[`flushinterval;1800];3h;()!()]]; msg:"query logging on (level ",(string cfg`level),", memory=",(string cfg`logtomemory),", disk=",(string cfg`logtodisk),")"; deps[`log][`info][`torq;msg," - di.querylog wraps .z.* directly; see torq.md Query logging"]; } From 6298ab537c4dba85ca4caf53698a1ed7ab290fe6 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 20 Oct 2026 12:55:23 +0100 Subject: [PATCH 10/39] di.torq: stamp q's -t interval into config as timerms q consumes its own -t, so cmdlinet reads it from the full command line .z.X, once, and init stamps it into config as timerms (ms, null if not given). The tickerplants batch on it as TorQ's .z.ts runs at -t, without reading the command line themselves - the same env-free boundary as processcsv. Tests launch real processes through torqx_init.q with and without -t. Co-Authored-By: Claude Opus 5.5 --- di/torq/test.csv | 3 +++ di/torq/test.q | 13 +++++++++++++ di/torq/torq.md | 4 ++++ di/torq/torq.q | 5 +++++ 4 files changed, 25 insertions(+) diff --git a/di/torq/test.csv b/di/torq/test.csv index d88c18710..9c598e0da 100644 --- a/di/torq/test.csv +++ b/di/torq/test.csv @@ -39,6 +39,9 @@ true,0,0,q,`di.torq.proc.segmentedtp~.m.di.0torq.builtin`segmentedchainedtp,1,,s run,0,0,q,r3:tq.init[TESTPROCNAME;`testinst;()!()],1,,explicit-identity init for a custom proctype true,0,0,q,TESTPROCNAME~r3`proctype,1,,identity resolved for the custom proctype true,0,0,q,`widget in key .k4unittestproc.capturedconfig,1,,config cascade reached the custom proctype's own settings file +true,0,0,q,"(`timerms in key .k4unittestproc.capturedconfig)&0N~.k4unittestproc.capturedconfig`timerms",1,,init stamps timerms from q's own -t (null here: this test process runs without -t) +true,0,0,q,"200~launchtimerms["" -t 200""]",1,,a process launched through torqx_init.q with -t 200 has timerms 200 in its config +true,0,0,q,"0N~launchtimerms[""""]",1,,a process launched without -t has a null timerms true,0,0,q,(`handlers`log`servers`timer)~asc key .k4unittestproc.captureddeps,1,,deps (incl injected servers) were passed through to the custom proctype's init exactly like a built-in one true,0,0,q,1=.k4unittestproc.runcalled,1,,the .run hook fired automatically after init - no launcher-side proctype knowledge needed true,0,0,q,1=.k4unittestproc.deferredcalled,1,,a function queued with .proc.addinitlist ran once after init diff --git a/di/torq/test.q b/di/torq/test.q index 7cd47722f..6a07a6676 100644 --- a/di/torq/test.q +++ b/di/torq/test.q @@ -14,6 +14,7 @@ APPBASE:"/tmp/di_torq_k4unit_app" HDBDIR:APPBASE,"/hdb" TESTPROCNAME:`k4unittestproc TESTPROCFILE:APPBASE,"/code/processes/",string[TESTPROCNAME],".q" +QBIN:first system "readlink -f /proc/",(string .z.i),"/exe" writelines:{[path;lines] (hsym `$path) 0: lines; } @@ -58,8 +59,20 @@ setupfixture:{[] " };"; "run:{[] runcalled::runcalled+1};"; "\\d .")]; + + / a launcher that starts a real process through torqx_init.q and writes the timerms its config carried + writelines[APPBASE,"/launch.q"; + ("system \"l \",getenv[`TORQXHOME],\"/di/torq/bin/torqx_init.q\";"; + "(hsym`$getenv[`TORQXAPPHOME],\"/timerms.txt\") 0: enlist .Q.s1 .k4unittestproc.capturedconfig`timerms;"; + "exit 0")]; } +/ launch a real process through torqx_init.q with extra q flags; return the timerms in its config +launchtimerms:{[flags] + f:APPBASE,"/timerms.txt"; system "rm -f ",f; + system QBIN," ",APPBASE,"/launch.q -proctype ",(string TESTPROCNAME)," -procname testinst",flags," -q ",APPBASE,"/launch.log 2>&1"; + value first read0 hsym`$f} + / helper so the test.csv cell stays comma-free (k4unit's CSV splits unquoted commas): writes / loadnamecode into the procname settings tier to turn on the procname-tier app-code cascade. enablenamecode:{[] writelines[APPBASE,"/settings/testinst.q";enlist "loadnamecode:1b"]; } diff --git a/di/torq/torq.md b/di/torq/torq.md index bc0236fcd..72e5a47c2 100644 --- a/di/torq/torq.md +++ b/di/torq/torq.md @@ -68,6 +68,10 @@ Three independent, explicitly-set env vars - not derived from each other: can find out who it is just by looking at its own `config` dict - no global to reach for. See `di.torq.config`'s own docs for the 5-tier cascade itself. +It also adds `timerms`: q's own `-t` in milliseconds, or null without `-t`. q consumes `-t`, so +`cmdlinet` reads it from the full command line `.z.X`, once. The tickerplants batch on it, as TorQ's +`.z.ts` runs at `-t`, without reading the command line themselves. + ### Dependency building `buildlogdep`/`buildtimerdep`/`buildhandlersdep` each build one of the three DI diff --git a/di/torq/torq.q b/di/torq/torq.q index b66ce4625..6d36659ea 100644 --- a/di/torq/torq.q +++ b/di/torq/torq.q @@ -256,6 +256,9 @@ reservedflags:`proctype`procname`torqxstackid`p`norun; / (parsed into its type) and skips any that don't name a real setting. Pure - unit-testable without .z.x. clioverrideparams:{[cmdlineopts] (key[cmdlineopts] except reservedflags)#cmdlineopts} +/ q's own -t in ms, null if not given; q consumes -t, so it is read from the full command line .z.X +cmdlinet:{[] $[`t in key o:.Q.opt .z.X;"J"$first o`t;0N]} + init:{[proctype;procname;overrides] / dependency check runs first, before anything else - a version mismatch should / be caught before identity resolution, config, or any module load even starts. @@ -292,6 +295,8 @@ init:{[proctype;procname;overrides] / the process.csv phone-book path, so di.torq.servers (and any consumer building its own startup config / slice from this config) can dial peers without reading env itself - keeps di.servers' env-free boundary. config:config,enlist[`processcsv]!enlist reqenv[`TORQXAPPCONFIG],"/process.csv"; + / the process -t interval in ms, null if not given + config:config,enlist[`timerms]!enlist cmdlinet[]; timerdep:buildtimerdep[overrides;logdep]; handlersdep:buildhandlersdep[overrides;logdep]; / servers is built LAST (it consumes log/timer/handlers at init) and injected alongside From 20b45a7c5f4293744eedc92e2381450bf661b2cb Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 20 Oct 2026 12:55:24 +0100 Subject: [PATCH 11/39] di.torq.proc.segmentedtp: batch every -t ms, as TorQ's .z.ts The stpzts job's period was fixed at 1s. It now follows config timerms (q's -t, stamped by di.torq), falling back to 1000ms when -t is unset or 0, as legacy segmentedtickerplant.q does. segmentedchainedtp gets the same period. Test peers start with -t 200, -t 0 and -t 300. Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/segmentedtp/segmentedtp.md | 2 +- di/torq/proc/segmentedtp/segmentedtp.q | 5 +++-- di/torq/proc/segmentedtp/test.csv | 5 ++++- di/torq/proc/segmentedtp/test.q | 7 +++++-- 4 files changed, 13 insertions(+), 6 deletions(-) diff --git a/di/torq/proc/segmentedtp/segmentedtp.md b/di/torq/proc/segmentedtp/segmentedtp.md index 9750a5f25..863987b9f 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.md +++ b/di/torq/proc/segmentedtp/segmentedtp.md @@ -65,7 +65,7 @@ Requires `log`, `timer` and `handlers`. It: 3. registers a `.z.pc` observer (chained: exit 1 when the upstream closes) and a `.z.exit` observer (flush `memorybatch`, close the logs); 4. sets `.u.upd` from `batchmode` and adds the `stpzts` timer job (the batch timer and the end checks, every - second); + `-t` milliseconds from the q command line, or every second without `-t`, as TorQ's `.z.ts`); 5. chained: waits for the upstream and subscribes; otherwise loads `schemafile`; 6. strips attributes from the published tables and opens the logs. diff --git a/di/torq/proc/segmentedtp/segmentedtp.q b/di/torq/proc/segmentedtp/segmentedtp.q index 224c2f24e..69adffb8c 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.q +++ b/di/torq/proc/segmentedtp/segmentedtp.q @@ -111,8 +111,9 @@ init:{[config;deps] .stplg.updmsg:.stplg.upd[batch]; .stplg.ts:.stplg.zts[batch]; .u.upd:.stpps.upd[chainmode]; - / the batch timer and end checks run as a 1s di.timer job; the end guards disable only this job - .z.m.timer[`addjob][`stpzts;.stpps.zts[chainmode];();0D00:00:01;1;(enlist`disableonfail)!enlist 0b]; + / the batch timer and end checks run every -t ms (config timerms, 1000 if unset), as TorQ's .z.ts; the end guards disable only this job + ms:$[`timerms in key .z.m.params;.z.m.params`timerms;0N]; + .z.m.timer[`addjob][`stpzts;.stpps.zts[chainmode];();0D00:00:00.001*$[ms>0;ms;1000];1;(enlist`disableonfail)!enlist 0b]; / error mode: failed updates go to a separate log if[.stplg.errmode; .stp.upd:.u.upd; diff --git a/di/torq/proc/segmentedtp/test.csv b/di/torq/proc/segmentedtp/test.csv index 610480468..871a0362f 100644 --- a/di/torq/proc/segmentedtp/test.csv +++ b/di/torq/proc/segmentedtp/test.csv @@ -20,7 +20,10 @@ true,0,0,q,"(`immediate;`singular;1D)~hb"".stplg`batchmode`multilog`multilogperi true,0,0,q,"1D~hc"".stplg.multilogperiod""",1,,tabular rolls daily true,0,0,q,"all `stpps`sctp in ha""exec name from h.list`.z.pc""",1,,.z.pc observers registered true,0,0,q,"`stplg in ha""exec name from h.list`.z.exit""",1,,.z.exit observer registered -true,0,0,q,"(`stpzts;0D00:00:01;1;(enlist`disableonfail)!enlist 0b)~ha""tickjob""",1,,batch timer added as a 1s timer job that retries on failure +true,0,0,q,"(`stpzts;0D00:00:01;1;(enlist`disableonfail)!enlist 0b)~ha""tickjob""",1,,batch timer added as a 1s timer job that retries on failure (no -t: 1000ms as legacy) +true,0,0,q,"(`stpzts;0D00:00:00.2;1;(enlist`disableonfail)!enlist 0b)~hb""tickjob""",1,,batch timer period follows -t (b started with -t 200 then sets its own \t 60000) as legacy .z.ts runs at -t +true,0,0,q,"(`stpzts;0D00:00:01;1;(enlist`disableonfail)!enlist 0b)~hc""tickjob""",1,,-t 0 falls back to 1000ms as legacy (system t 1000 when t is unset) +true,0,0,q,"(`stpzts;0D00:00:00.3;1;(enlist`disableonfail)!enlist 0b)~hs""tickjob""",1,,a segmentedchainedtp (s) started with -t 300 batches every 300ms comment,,,,,,,subscribe handshake true,0,0,q,"`segmented~ha""tptype""",1,,tptype is segmented diff --git a/di/torq/proc/segmentedtp/test.q b/di/torq/proc/segmentedtp/test.q index a9d02c13a..b475d8fed 100644 --- a/di/torq/proc/segmentedtp/test.q +++ b/di/torq/proc/segmentedtp/test.q @@ -5,7 +5,9 @@ QBIN:first system "readlink -f /proc/",(string .z.i),"/exe" isfree:{[p] not @[{hclose hopen x;1b};(`$":localhost:",string p;100);0b]} / a peer writes its port once initialised waitport:{[n] f:hsym`$FIXDIR,"/",string[n],".port"; d:.z.p+0D00:00:10; while[(.z.p",FIXDIR,"/",string[n],".log 2>&1 &"} +/ extra q flags per peer: b, c and s start with -t so their batch periods can be checked +TFLAGS:(`a`b`c`s`p!5#enlist""),`b`c`s!(" -t 200";" -t 0";" -t 300") +start:{[n] system QBIN," ",FIXDIR,"/",string[n],".q",(TFLAGS n)," -q ",FIXDIR,"/",string[n],".log 2>&1 &"} waitfor:{[f] d:.z.p+0D00:00:05; while[(.z.p Date: Tue, 20 Oct 2026 13:04:23 +0100 Subject: [PATCH 12/39] di.torq.proc.chainedtp: accept a sub-second pubinterval, as TorQ's chainedtp The whole-seconds guard existed only because di.timer took integer seconds. TorQ registers publishalltables with any timespan pubinterval (chainedtp.q:209-210); the port now does too, in timer mode 2 (legacy 1h). Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/chainedtp/chainedtp.md | 3 +-- di/torq/proc/chainedtp/chainedtp.q | 1 - di/torq/proc/chainedtp/test.csv | 7 +++++-- di/torq/proc/chainedtp/test.q | 4 ++-- 4 files changed, 8 insertions(+), 7 deletions(-) diff --git a/di/torq/proc/chainedtp/chainedtp.md b/di/torq/proc/chainedtp/chainedtp.md index ed8352066..64070faac 100644 --- a/di/torq/proc/chainedtp/chainedtp.md +++ b/di/torq/proc/chainedtp/chainedtp.md @@ -46,7 +46,7 @@ missing), then: 4. `.servers.startupdepnamecycles[tickerplantname;tpconnsleep;tpcheckcycles]`; 5. `subscribe[]`; 6. builds `tableschemas`; -7. when `pubinterval` is above 0, adds the `publishalltables` job (seconds, timer mode 2). +7. when `pubinterval` is above 0, adds the `publishalltables` job (every `pubinterval`, timer mode 2). di.torq runs `.ps.initialise[]` again after the module loads, which publishes the subscribed tables. @@ -57,7 +57,6 @@ di.torq runs `.ps.initialise[]` again after the module loads, which publishes th - An upstream that sends `endofday` rather than `.u.end` (a segmented tickerplant) does not end the day here. - `.u.icounts` values are one-item lists after an all-syms subscribe. - A corrupt own log is reported and opened anyway. -- `pubinterval` must be a whole number of seconds (the timer runs in seconds); anything else fails `init`. ## Downstream subscribers diff --git a/di/torq/proc/chainedtp/chainedtp.q b/di/torq/proc/chainedtp/chainedtp.q index d9640f017..de3d702a2 100644 --- a/di/torq/proc/chainedtp/chainedtp.q +++ b/di/torq/proc/chainedtp/chainedtp.q @@ -29,7 +29,6 @@ init:{[config;deps] .z.m.schema:config`schema; .z.m.clearlogonsubscription:config`clearlogonsubscription; .z.m.tpcheckcycles:config`tpcheckcycles; - if[0<>(`long$pubinterval) mod 1000000000;'"di.torq.proc.chainedtp: pubinterval must be a whole number of seconds"]; (deps[`handlers]`register)[`.z.pc;`;`chainedtp;0j;{[y] if[tph=y;.z.m.log[`error][`.z.pc;"lost connection to tickerplant : ",string tickerplantname];exit 0]}]; .z.m.upd:$[createlogfile; $[pubinterval;{[t;x] writetolog[t;x];batchpub[t;x];};{[t;x] writetolog[t;x];tickpub[t;x];}]; diff --git a/di/torq/proc/chainedtp/test.csv b/di/torq/proc/chainedtp/test.csv index 66806a44e..4eb02e827 100644 --- a/di/torq/proc/chainedtp/test.csv +++ b/di/torq/proc/chainedtp/test.csv @@ -9,8 +9,6 @@ fail,0,0,q,"ctp.init[cfg[];enlist[`log]!enlist mocklog]",1,,init without timer m fail,0,0,q,"ctp.init[cfg[];`log`timer!(mocklog;mocktimer)]",1,,init without handlers must error fail,0,0,q,"ctp.init[cfg[];`timer`handlers!(mocktimer;mockhandlers)]",1,,init without log must error fail,0,0,q,"ctp.init[`proctype`procname!(`chainedtp;`chainedtp1);deps[]]",1,,init without settings must error -fail,0,0,q,"ctp.init[cfg[],enlist[`pubinterval]!enlist 0D00:00:00.500;deps[]]",1,,a sub-second pubinterval must error -fail,0,0,q,"ctp.init[cfg[],enlist[`pubinterval]!enlist 0D00:00:01.500;deps[]]",1,,a fractional-second pubinterval must error comment,,,,,,,init - connect and subscribe run,0,0,q,"ctp.init[cfg[],`pubinterval`logdir`tickerplantname`subscribeto`subscribesyms!(""0D00:00:00"";""tplogs"";""tickerplant1"";"""";"""");deps[]]",1,,init with toml-style strings @@ -87,4 +85,9 @@ true,0,0,q,"sd2:sh""(.z.w)(`.u.subdetails;`;`)""; (11h=type sd2`tables) and `tra run,0,0,q,".m.di.0torq.0proc.0chainedtp.tph({(neg .z.w)(`upd;`trade;x)};rows 2)",1,,upstream publishes 2 rows true,0,0,q,"(`trade;2)~sh""(first last got;count last last got)""",1,,peer received the rows +comment,,,,,,,a sub-second pubinterval batches on a timer job at that period, as TorQ's .timer.rep with .ctp.pubinterval +run,0,0,q,"ctp.init[cfg[],enlist[`pubinterval]!enlist 0D00:00:00.500;deps[]]",1,,re-init with a 500ms pubinterval is accepted +true,0,0,q,"(0D00:00:00.5;2)~last each exec (period;mode) from timercalls where id=`publishalltables",1,,the batch job runs every 500ms in mode 2 (legacy mode 1h) +true,0,0,q,.m.di.0torq.0proc.0chainedtp.upd~.m.di.0torq.0proc.0chainedtp.batchpub,1,,the module's upd batches (root upd is kept from the first init) + after,0,0,q,teardownfixture[],1,,stop the peers and remove the fixture dir diff --git a/di/torq/proc/chainedtp/test.q b/di/torq/proc/chainedtp/test.q index 57bf48d3a..8b1dc9f61 100644 --- a/di/torq/proc/chainedtp/test.q +++ b/di/torq/proc/chainedtp/test.q @@ -2,8 +2,8 @@ logrows:([]lvl:`symbol$();ctx:`symbol$();msg:()) mocklog:`info`warn`error!({[c;m]`logrows upsert(`info;c;m)};{[c;m]`logrows upsert(`warn;c;m)};{[c;m]`logrows upsert(`error;c;m)}) -timercalls:([]id:`symbol$();period:`long$();mode:`long$()) -mocktimer:enlist[`addjob]!enlist {[id;func;params;period;mode;opts] `timercalls upsert (id;`long$period;`long$mode);} +timercalls:([]id:`symbol$();period:`timespan$();mode:`long$()) +mocktimer:enlist[`addjob]!enlist {[id;func;params;period;mode;opts] `timercalls upsert (id;period;`long$mode);} handlercalls:([]event:`symbol$();name:`symbol$()) mockhandlers:`register`remove`list!({[ev;ph;nm;pri;fn]`handlercalls upsert(ev;nm)};{[ev;ph;nm]};{[ev]}) errlogged:{[s] any (exec msg from logrows where lvl=`error) like "*",s,"*"} From 51745be330f708fd40f14d4b83325e8807801018 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 20 Oct 2026 13:14:37 +0100 Subject: [PATCH 13/39] di.torq.proc.tickerplant: -t decides batched or immediate, as TorQ's tickerplant.q publishmode and pubperiod are removed (breaking for port-format settings). As TorQ's classic tickerplant, the tickerplant batches every -t ms when q is started with -t (config timerms, stamped by di.torq) and publishes each update immediately otherwise. The end-of-day check stays its separate 1s job. Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/tickerplant/test.csv | 16 +++++++++++++++- di/torq/proc/tickerplant/test.q | 16 +++++++++------- di/torq/proc/tickerplant/tickerplant.md | 11 ++++++----- di/torq/proc/tickerplant/tickerplant.q | 22 +++++++++++----------- 4 files changed, 41 insertions(+), 24 deletions(-) diff --git a/di/torq/proc/tickerplant/test.csv b/di/torq/proc/tickerplant/test.csv index 05f789fe4..f5823591a 100644 --- a/di/torq/proc/tickerplant/test.csv +++ b/di/torq/proc/tickerplant/test.csv @@ -29,12 +29,26 @@ true,0,0,q,subdetailsbatchedok[],1,,batched: subdetails flushes the buffer to ex run,0,0,q,doinit[batchcfg[]],1,,re-init in batched mode true,0,0,q,scheduled[`tpflush],1,,batched mode schedules a flush job -true,0,0,q,flushperiodok[],1,,flush job uses the configured pubperiod +true,0,0,q,flushperiodok[],1,,flush job runs every timerms (2000ms here) run,0,0,q,feedtrades[3],1,,feed three trades in batched mode true,0,0,q,3=count trade,1,,batched mode buffers rows locally run,0,0,q,(tk`flush)[],1,,flush publishes and clears the buffer true,0,0,q,0=count trade,1,,flush emptied the buffered table +comment,,,,,,,-t decides the publish mode, as TorQ's tickerplant.q: batched every -t ms when -t is set, immediate otherwise +run,0,0,q,doinit[tcfg[200]],1,,init with timerms 200 (q started with -t 200) +true,0,0,q,0D00:00:00.2=first exec period from timercalls where id=`tpflush,1,,the flush job runs every 200ms +run,0,0,q,feedtrades[2],1,,feed two trades +true,0,0,q,2=count trade,1,,the rows are buffered for the flush +run,0,0,q,doinit[tcfg[0N]],1,,init with a null timerms (no -t) +true,0,0,q,not scheduled[`tpflush],1,,no flush job without -t +run,0,0,q,feedtrades[2],1,,feed two trades +true,0,0,q,0=count trade,1,,published immediately without -t +run,0,0,q,doinit[tcfg[0]],1,,init with timerms 0 (-t 0) +true,0,0,q,not scheduled[`tpflush],1,,no flush job with -t 0 +run,0,0,q,feedtrades[2],1,,feed two trades +true,0,0,q,0=count trade,1,,published immediately with -t 0 + run,0,0,q,doinit[replaycfg[]],1,,fresh batched init pointing at an empty replay log dir run,0,0,q,feedtrades[4],1,,write four trades to the replay log run,0,0,q,doinit[replaycfg[]],1,,re-init against the same log (simulates a restart) diff --git a/di/torq/proc/tickerplant/test.q b/di/torq/proc/tickerplant/test.q index 2f6dc9c33..a3d71e43d 100644 --- a/di/torq/proc/tickerplant/test.q +++ b/di/torq/proc/tickerplant/test.q @@ -40,13 +40,15 @@ setupfixture:{[] teardownfixture:{[] system "rm -rf ",BASE; } / config builders (kept out of test.csv: they contain commas/backticks) -immcfg:{[] `publishmode`tplogdir`schemafile!(`immediate;BASE,"/log";BASE,"/database.q")} -batchcfg:{[] `publishmode`pubperiod`tplogdir`schemafile!(`batched;2;BASE,"/batchlog";BASE,"/database.q")} -nologcfg:{[] `publishmode`schemafile!(`immediate;BASE,"/database.q")} -badcfg:{[] `publishmode`schemafile!(`immediate;BASE,"/badschema.q")} -replaycfg:{[] `publishmode`tplogdir`schemafile!(`batched;BASE,"/replog";BASE,"/database.q")} -subdcfg:{[] `publishmode`tplogdir`schemafile!(`immediate;BASE,"/subdlog";BASE,"/database.q")} -subdbcfg:{[] `publishmode`pubperiod`tplogdir`schemafile!(`batched;2;BASE,"/subdblog";BASE,"/database.q")} +immcfg:{[] `tplogdir`schemafile!(BASE,"/log";BASE,"/database.q")} +batchcfg:{[] `timerms`tplogdir`schemafile!(2000;BASE,"/batchlog";BASE,"/database.q")} +nologcfg:{[] enlist[`schemafile]!enlist BASE,"/database.q"} +badcfg:{[] enlist[`schemafile]!enlist BASE,"/badschema.q"} +replaycfg:{[] `timerms`tplogdir`schemafile!(2000;BASE,"/replog";BASE,"/database.q")} +subdcfg:{[] `tplogdir`schemafile!(BASE,"/subdlog";BASE,"/database.q")} +subdbcfg:{[] `timerms`tplogdir`schemafile!(2000;BASE,"/subdblog";BASE,"/database.q")} +/ -t decides the mode, as TorQ's tickerplant.q: timerms (q's -t, stamped by di.torq) 200, null or 0 +tcfg:{[ms] `timerms`schemafile!(ms;BASE,"/database.q")} / feed n trade rows through the published root upd (columns form, single record each) feedtrades:{[n] {upd[`trade;(.z.p;`$"S",string x;1.0*x;`int$x)]} each til n; } diff --git a/di/torq/proc/tickerplant/tickerplant.md b/di/torq/proc/tickerplant/tickerplant.md index d1f337600..44d03540c 100644 --- a/di/torq/proc/tickerplant/tickerplant.md +++ b/di/torq/proc/tickerplant/tickerplant.md @@ -22,9 +22,11 @@ coexists with `di.torq.servers`' own `.z.pc` hook (see Notes). ## Config +There is no publish-mode setting. As TorQ's `tickerplant.q`, q's `-t` decides: started with `-t ` +(di.torq stamps it into config as `timerms`) the tickerplant buffers updates and flushes them every `-t` +ms; without `-t`, or with `-t 0`, it publishes each update immediately. + ```toml -publishmode = "immediate" # "immediate" (publish each update) or "batched" (buffer, flush on a timer) -pubperiod = 1 # batched only: flush period in SECONDS (di.timer granularity) tplogdir = "tplog" # relative to TORQXDATAHOME, or absolute; empty/absent = no logging schemafile = "database.q" # defaults to /database.q (schema is code, not data) # rolltimezone / datatimezone / rolltimeoffset -> passed to di.eodtime (default GMT/GMT/0) @@ -49,7 +51,8 @@ schemafile = "database.q" # defaults to /database.q (schema is c and `upd` logs before it buffers, so a subscriber registered while rows sat unflushed would replay them from the log and then receive them again in the next flush. - **Timer jobs** (via injected `di.timer`): an EOD-roll check every second; plus, in - batched mode, a flush every `pubperiod` seconds (`di.pubsub.pubclear`). + batched mode, a flush every `-t` ms (`di.pubsub.pubclear`). In batched mode the EOD check stays this + separate 1s job, where TorQ runs it on every `.z.ts` tick. - **End of day** (`endofday`, published at root; fired by the roll-check job or via IPC): flush any buffer, `di.pubsub.callendofday`, roll the log (`di.tplogmgr.roll`), and advance di.eodtime's date / next-roll / daily-adjustment. @@ -70,8 +73,6 @@ because `di.tplogmgr.open` replays via `-11!`, which executes the root-level `up - A single malformed schema table (missing `time`/`sym`) is silently skipped rather than erroring (shape-filtering trade-off vs TorQ's strict assertion, chosen for robustness against ambient root tables). -- Batched flush granularity is whole seconds (di.timer's period unit); TorQ's `system"t"` - allows sub-second. Fine for v1. - `di.eodtime` is vendored from an unmerged PR and `rolltimeoffset` can't be expressed in TOML (no timespan type) — GMT-midnight rolls need no offset; a non-default offset needs a `.q` settings file for now. diff --git a/di/torq/proc/tickerplant/tickerplant.q b/di/torq/proc/tickerplant/tickerplant.q index 025cf5979..bebd0d6fa 100644 --- a/di/torq/proc/tickerplant/tickerplant.q +++ b/di/torq/proc/tickerplant/tickerplant.q @@ -19,7 +19,7 @@ resolvedir:{[base;dir] } / consumers coerce at point of use: config values may be symbols (.q) or strings (.toml) -astz:{[x] $[11h=abs type x;x;`$x]} / to symbol (timezones, publishmode) +astz:{[x] $[11h=abs type x;x;`$x]} / to symbol (timezones) / feed payloads may arrive as a table or as a list of columns; normalise to columns tocols:{[x] $[98h=type x;value flip x;x]} @@ -40,7 +40,7 @@ upd:{[t;x] x:stamp tocols x; if[.z.m.logh>0;(.z.m.tp`write)[.z.m.logh;(`upd;t;x)];.u.i+:1]; if[count .z.m.tplogdir;.u.icounts[t]+:count first x]; - $[.z.m.publishmode=`batched; + $[.z.m.batchms>0; t insert x; (.z.m.ps`publish)[t;flip (cols value t)!$[0>type first x;enlist each x;x]] ]; @@ -53,7 +53,7 @@ sub:{[x;y] if[x~`;:sub[;y] each .z.m.tables]; if[not x in .z.m.tables;'x]; / batched: flush first, so a replaying subscriber doesn't receive the buffer twice - if[.z.m.publishmode=`batched;(.z.m.ps`pubclear)[.z.m.tables]]; + if[.z.m.batchms>0;(.z.m.ps`pubclear)[.z.m.tables]]; r:(.z.m.ps`subscribe)[x;y]; (first r 0;first r 1)} @@ -75,7 +75,7 @@ subdetails:{[tabs;syms] / batched: flush FIRST, to the subscribers that already exist. rowcount counts every message logged, and upd logs / before it buffers - so a subscriber registered while rows sat in the buffer would replay them from the log and / then receive the same rows again in the next flush. flushed before it registers, it sees them exactly once - if[.z.m.publishmode=`batched;(.z.m.ps`pubclear)[.z.m.tables]]; + if[.z.m.batchms>0;(.z.m.ps`pubclear)[.z.m.tables]]; sub:(.z.m.ps`subscribe)[tabs;syms]; d:(.z.m.eod`getd)[]; lf:$[00;(.z.m.ps`pubclear)[.z.m.tables]]; d:(.z.m.eod`getd)[]; / tell subscribers (e.g. di.torq.proc.rdb) to end the day for partition d - AFTER any final flush / above, so they save exactly the day's data. Carries the date (vendored pubsub patch). @@ -122,8 +122,8 @@ init:{[config;deps] .z.m.timer:deps`timer; .z.m.handlers:deps`handlers; .z.m.cfg:config; - .z.m.publishmode:$[`publishmode in key config;astz config`publishmode;`immediate]; - .z.m.pubperiod:$[`pubperiod in key config;"j"$config`pubperiod;1]; + / batched every -t ms when -t is set (config timerms), immediate otherwise, as TorQ's tickerplant.q + .z.m.batchms:$[`timerms in key config;0^config`timerms;0]; .z.m.tplogdir:$[`tplogdir in key config;resolvedir[datahome[];config`tplogdir];""]; / schema: load the schema file at root; publishable tables are the UNKEYED ones with @@ -183,10 +183,10 @@ init:{[config;deps] .z.m.log[`info][`tickerplant;"opened tp log, replayed ",(string r 1)," message(s)"]; ]; - / timer jobs: EOD roll check every second; batched flush every pubperiod seconds + / timer jobs: EOD roll check every second; batched flush every -t ms (.z.m.timer`addjob)[`tpeodcheck;eodcheck;();0D00:00:01;1h;()!()]; - if[.z.m.publishmode=`batched; - (.z.m.timer`addjob)[`tpflush;flush;();0D00:00:01*.z.m.pubperiod;1h;()!()]]; + if[.z.m.batchms>0; + (.z.m.timer`addjob)[`tpflush;flush;();0D00:00:00.001*.z.m.batchms;1h;()!()]]; - .z.m.log[`info][`tickerplant;"initialised, mode=",(string .z.m.publishmode),", tables=",", " sv string tabs]; + .z.m.log[`info][`tickerplant;"initialised, mode=",$[.z.m.batchms>0;"batched every ",(string .z.m.batchms),"ms";"immediate"],", tables=",", " sv string tabs]; } From c7d7413a62ece3bf5fba39929be648d6cbee3978 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 20 Oct 2026 13:29:10 +0100 Subject: [PATCH 14/39] di.dbwrite: savedown hooks and TorQ's default sort, as dbwriteutils.q - savedownmanipulation and postreplay, as TorQ's .save hooks, configured through init and set only when passed (TorQ #762's intent); postreplay defaults to {[d;p]}, avoiding the 'rank that #762's projection causes in legacy - savedown and appenddown apply manipulate before enumerating; failures are logged and the original rows written, as .save.manipulate - the built-in default is TorQ's config/sort.csv: p# on sym, sorted by sym then time wdb's sort-mode test expectations change because of the new default sort (sym then time, p#); its sortcsvhonoured test now uses a time-only csv so it still proves an override. Co-Authored-By: Claude Opus 5.5 --- di/dbwrite/dbwrite.md | 8 ++++++-- di/dbwrite/dbwrite.q | 24 ++++++++++++++++++++---- di/dbwrite/init.q | 2 +- di/dbwrite/test.csv | 36 ++++++++++++++++++++++++++++++++++-- di/torq/proc/wdb/test.csv | 4 ++-- di/torq/proc/wdb/testsort.q | 25 ++++++++++++++----------- 6 files changed, 77 insertions(+), 22 deletions(-) diff --git a/di/dbwrite/dbwrite.md b/di/dbwrite/dbwrite.md index 037087c44..c0cec3a5d 100644 --- a/di/dbwrite/dbwrite.md +++ b/di/dbwrite/dbwrite.md @@ -68,6 +68,8 @@ default,,time,1 | `sort[tabname;dirs]` | Sort on-disk partition(s) for a table and apply attributes per stored config | | `savedown[dir;part;tabname;data]` | Write an in-memory table to an HDB partition, sort it, then run gc | | `appenddown[dir;part;tabname;data]` | Append rows to an existing partition (no sort) | +| `manipulate[t;x]` | Apply the table's `savedownmanipulation` function, as TorQ's `.save.manipulate`; keeps `x` if it fails | +| `postreplay[d;p]` | Call the `postreplay` hook after a partition is written, as TorQ's `.save.postreplay` | | `applyattr[dloc;colname;att]` | Apply a single kdb+ attribute to an on-disk column | | `gc[]` | Run `.Q.gc[]` and log memory stats before and after | @@ -77,6 +79,8 @@ default,,time,1 Wire injected dependencies. Must be called before any other function. Also resets the stored sort config to `(::)`. +Optional keys, as TorQ's `.save` hooks: `savedownmanipulation` (dict of table!function, applied to the data before `savedown`/`appenddown` enumerate it) and `postreplay` (`{[d;p]}`, called by writers through `postreplay` once a partition is written). Each is set only when its key is passed, so a later `init` without it keeps the hook; the defaults are `()!()` and `{[d;p]}`. + | Arg | Type | Description | |---|---|---| | `deps` | dict | Must contain `` `log `` → `` `info`warn`error!(infofn;warnfn;errfn) `` | @@ -128,7 +132,7 @@ dbwrite.getconfig[] ### `sort[tabname;dirs]` -Sort and apply attributes to the on-disk partition(s) for one table, using the config stored by `readcsv` or `setconfig`. Falls back to the built-in default (sort by `time` ascending) if no config has been loaded. +Sort and apply attributes to the on-disk partition(s) for one table, using the config stored by `readcsv` or `setconfig`. Falls back to the built-in default, TorQ's `config/sort.csv` (`p#` on `sym`, sorted by `sym` then `time`), if no config has been loaded. A table without `sym` logs the sort and attribute errors and is written unsorted, as in TorQ. | Parameter | Type | Description | |---|---|---| @@ -208,5 +212,5 @@ The suite injects binary mock loggers (`{[c;m] ...}`): a no-op logger, and a cap ## Exported symbols ```q -export:([init;readcsv;setconfig;getconfig;sort;applyattr;savedown;appenddown;gc]) +export:([init;readcsv;setconfig;getconfig;sort;applyattr;savedown;appenddown;manipulate;postreplay;gc;version]) ``` diff --git a/di/dbwrite/dbwrite.q b/di/dbwrite/dbwrite.q index 28c000ea3..d58ccd4f5 100644 --- a/di/dbwrite/dbwrite.q +++ b/di/dbwrite/dbwrite.q @@ -4,8 +4,12 @@ / attributes that may legitimately appear in a config (empty leaves a column unattributed) validatts:``p`s`g`u; -/ built-in fallback config - sort every table by time ascending when no config is supplied -defaultparams:([] tabname:enlist`default; att:enlist`; column:enlist`time; sort:enlist 1b); +/ built-in fallback config, TorQ's config/sort.csv: p# on sym, sorted by sym then time +defaultparams:([] tabname:`default`default; att:`p`; column:`sym`time; sort:11b); + +/ save down hooks, as TorQ's .save.savedownmanipulation and .save.postreplay; init sets them only when passed +savedownmanipulation:()!(); +posthook:{[d;p]}; init:{[deps] / wire the injected logger - required, no silent fallback. deps: a dict with a `log key @@ -24,8 +28,20 @@ init:{[deps] .z.m.logwarn:deps[`log]`warn; .z.m.logerr:deps[`log]`error; .z.m.sortconfig:(::); + if[`savedownmanipulation in key deps;.z.m.savedownmanipulation:deps`savedownmanipulation]; + if[`postreplay in key deps;.z.m.posthook:deps`postreplay]; + }; + +/ apply the table's savedownmanipulation, if any, keeping the data on failure, as TorQ's .save.manipulate +manipulate:{[t;x] + $[t in key .z.m.savedownmanipulation; + @[.z.m.savedownmanipulation t;x;{[x;e] .z.m.logerr[`manipulate;"save down manipulation failed : ",e];x}[x]]; + x] }; +/ call the postreplay hook after a partition is written, as TorQ's .save.postreplay +postreplay:{[d;p] .z.m.posthook[d;p]}; + readcsv:{[file] / read a sort-config csv and store it in .z.m.sortconfig; used by sort and savedown / the csv must have the columns tabname,att,column,sort (in any order) @@ -196,7 +212,7 @@ savedown:{[dir;part;tabname;data] / enumerates syms against the hdb sym file; sorting and attributes are driven by .z.m.sortconfig .z.m.loginfo[`savedown;"saving ",string[tabname]," partition ",string[part]," to ",string dir]; path:` sv (.Q.par[dir;part;tabname];`); - path set .Q.en[dir;data]; + path set .Q.en[dir;manipulate[tabname;data]]; sort[tabname;path]; .z.m.loginfo[`savedown;"finished saving ",string tabname]; gc[]; @@ -212,7 +228,7 @@ appenddown:{[dir;part;tabname;data] .z.m.logerr[`appenddown;err:"di.dbwrite: appenddown partition does not exist at ",string path]; 'err; ]; - .[path;();,;.Q.en[dir;data]]; + .[path;();,;.Q.en[dir;manipulate[tabname;data]]]; .z.m.loginfo[`appenddown;"finished appending ",string tabname]; }; diff --git a/di/dbwrite/init.q b/di/dbwrite/init.q index 115c2160e..5478b07df 100644 --- a/di/dbwrite/init.q +++ b/di/dbwrite/init.q @@ -8,4 +8,4 @@ / BOTH the file (pre-load manifest walk) and this export (post-load session audit). version:first read0`:::VERSION -export:([init;readcsv;setconfig;getconfig;sort;applyattr;savedown;appenddown;gc;version]) +export:([init;readcsv;setconfig;getconfig;sort;applyattr;savedown;appenddown;manipulate;postreplay;gc;version]) diff --git a/di/dbwrite/test.csv b/di/dbwrite/test.csv index a61af3c11..ba1a4f498 100644 --- a/di/dbwrite/test.csv +++ b/di/dbwrite/test.csv @@ -160,7 +160,7 @@ true,0,0,q,3=count get sdpath,1,1,three rows on disk after appenddown true,0,0,q,not (asc exec time from get sdpath)~exec time from get sdpath,1,1,rows not auto-sorted by appenddown run,0,0,q,dbwrite.init[enlist[`log]!enlist mylog],1,1,reset sortconfig to (::) for default-config sort run,0,0,q,dbwrite.sort[`trade;sdpath],1,1,sort the partition explicitly after appending -true,0,0,q,(asc exec time from get sdpath)~exec time from get sdpath,1,1,sorted by time after the explicit sort +true,0,0,q,"(update `#sym from `sym`time xasc t)~update `#sym from t:select from get sdpath",1,1,sorted by sym then time after the explicit sort (default config) fail,0,0,q,dbwrite.appenddown[`:dbw_hdb;2099.01.01;`nope;sdtbl],1,1,appenddown into a non-existent partition errors comment,,,,,,,integration - savedown realistic (repeated/unsorted sym) data builds a valid queryable partition @@ -176,7 +176,7 @@ true,0,0,q,1=count select from ip where sym=`AAPL,1,1,p# lookup is correct - one run,0,0,q,dbwrite.init[enlist[`log]!enlist mylog],1,1,reset sortconfig to (::) for default-config savedown run,0,0,q,dbwrite.savedown[`:dbw_ihdb;2024.01.02;`trade;rd],1,1,savedown repeated-sym data with the default (time) config must not crash true,0,0,q,(asc x)~x:exec time from get ` sv (.Q.par[`:dbw_ihdb;2024.01.02;`trade];`),1,1,default-config partition sorted by time -true,0,0,q,`=attr (get ` sv (.Q.par[`:dbw_ihdb;2024.01.02;`trade];`))`sym,1,1,default-config leaves sym unattributed (not falsely parted) +true,0,0,q,`p=attr (get ` sv (.Q.par[`:dbw_ihdb;2024.01.02;`trade];`))`sym,1,1,default config parts sym (TorQ's config/sort.csv) comment,,,,,,,log call verification - switch to capturing logger run,0,0,q,dbwrite.init[enlist[`log]!enlist logcap],1,1,re-init with capturing logger @@ -245,7 +245,39 @@ after,0,0,q,rmrf`:dbw_sort_tp,1,1,cleanup sort partition after,0,0,q,rmrf`:dbw_def_tp,1,1,cleanup default partition after,0,0,q,rmrf`:dbw_md1,1,1,cleanup md1 partition after,0,0,q,rmrf`:dbw_md2,1,1,cleanup md2 partition +comment,,,,,,,round 2 - savedown hooks, as TorQ's dbwriteutils.q .save.manipulate and .save.postreplay +run,0,0,q,"dpath:{[d;p;t] ` sv (.Q.par[d;p;t];`)};htbl:([]time:2024.01.01D09:00 2024.01.01D08:00;sym:`IBM`AAPL;price:100 200f)",1,1,partition path helper and a test table +run,0,0,q,"dbwrite.init[`log`savedownmanipulation!(mylog;enlist[`trade]!enlist {update price:2*price from x})]",1,1,init with a trade manipulation +run,0,0,q,"dbwrite.savedown[`:dbw_hook;2024.01.01;`trade;htbl]",1,1,savedown applies the manipulation before writing +true,0,0,q,"200 400f~asc exec price from get dpath[`:dbw_hook;2024.01.01;`trade]",1,1,the prices on disk are doubled +run,0,0,q,dbwrite.init[enlist[`log]!enlist mylog],1,1,a later init without the hook (as #762: a default must not overwrite a supplied hook) +run,0,0,q,"dbwrite.savedown[`:dbw_hook;2024.01.02;`trade;htbl]",1,1,savedown again +true,0,0,q,"200 400f~asc exec price from get dpath[`:dbw_hook;2024.01.02;`trade]",1,1,the supplied hook still applies +run,0,0,q,"caplog:0#caplog;dbwrite.init[`log`savedownmanipulation!(logcap;enlist[`trade]!enlist {'`boom})]",1,1,init with a failing manipulation +run,0,0,q,"dbwrite.savedown[`:dbw_hook;2024.01.03;`trade;htbl]",1,1,savedown with the failing hook +true,0,0,q,"(update sym:`#sym from `sym`time xasc htbl)~update sym:`#value sym from select from get dpath[`:dbw_hook;2024.01.03;`trade]",1,1,the original rows are written unchanged (as legacy .save.manipulate returns x on failure) +true,0,0,q,"any (exec msg from caplog where fn=`error,ctx=`manipulate) like ""*boom*""",1,1,the failure is logged at error level +run,0,0,q,"dbwrite.postreplay[`:dbw_hook;2024.01.01]",1,1,the default postreplay {[d;p]} runs without 'rank +run,0,0,q,"dbwrite.init[`log`postreplay!(mylog;{[d;p] `prcalled set (d;p)})];dbwrite.postreplay[`:dbw_hook;2024.01.01]",1,1,a configured postreplay is called +true,0,0,q,"(`:dbw_hook;2024.01.01)~prcalled",1,1,with the hdb dir and partition +run,0,0,q,"dbwrite.init[`log`savedownmanipulation`postreplay!(mylog;()!();{[d;p]})]",1,1,reset the hooks for later rows + +comment,,,,,,,round 2 - default sort is TorQ's config/sort.csv: p# on sym, sorted by sym then time +run,0,0,q,dbwrite.init[enlist[`log]!enlist mylog],1,1,no sort config set +run,0,0,q,"dbwrite.savedown[`:dbw_dsort;2024.01.01;`trade;htbl]",1,1,savedown with the default config +true,0,0,q,"`p~attr (get dpath[`:dbw_dsort;2024.01.01;`trade])`sym",1,1,sym has p# on disk +true,0,0,q,"`AAPL`IBM~value exec sym from get dpath[`:dbw_dsort;2024.01.01;`trade]",1,1,rows are sorted by sym +run,0,0,q,"dbwrite.setconfig ([]tabname:enlist`trade;att:enlist`;column:enlist`time;sort:enlist 1b)",1,1,a user config with a trade row and no default row +run,0,0,q,"dbwrite.savedown[`:dbw_dsort;2024.01.02;`trade;htbl];dbwrite.savedown[`:dbw_dsort;2024.01.02;`quote;htbl]",1,1,savedown trade and a table missing from the config +true,0,0,q,"`~attr (get dpath[`:dbw_dsort;2024.01.02;`trade])`sym",1,1,the user's trade row overrides the default (no p#) +true,0,0,q,"`~attr (get dpath[`:dbw_dsort;2024.01.02;`quote])`sym",1,1,a table missing from a config with no default row is not sorted (as legacy sorttab) +run,0,0,q,"dbwrite.setconfig ([]tabname:`trade`default`default;att:``p`;column:`time`sym`time;sort:111b)",1,1,a user config with a default row +run,0,0,q,"dbwrite.savedown[`:dbw_dsort;2024.01.03;`quote;htbl]",1,1,savedown a table missing from the config +true,0,0,q,"`p~attr (get dpath[`:dbw_dsort;2024.01.03;`quote])`sym",1,1,it gets the config's default row (p# on sym) + after,0,0,q,rmrf`:dbw_good,1,1,cleanup good partition +after,0,0,q,rmrf`:dbw_hook,1,1,cleanup hook hdb tree +after,0,0,q,rmrf`:dbw_dsort,1,1,cleanup default-sort hdb tree after,0,0,q,rmrf`:dbw_attr_tp,1,1,cleanup attr partition after,0,0,q,rmrf`:dbw_hdb,1,1,cleanup savedown hdb tree after,0,0,q,rmrf`:dbw_ihdb,1,1,cleanup integration hdb tree diff --git a/di/torq/proc/wdb/test.csv b/di/torq/proc/wdb/test.csv index 1720b7314..415bb7b8e 100644 --- a/di/torq/proc/wdb/test.csv +++ b/di/torq/proc/wdb/test.csv @@ -83,7 +83,7 @@ comment,,,,,,,sort mode - proctypes sort and sortworker run,0,0,q,"system ""l di/torq/proc/wdb/testsort.q""",1,,load the sort-mode fixture helpers run,0,0,q,setupfixture[],1,,fixture dirs and the env the module resolves paths against comment,,,,,,,the end of day tail -true,0,0,q,tailok[],1,,sym reloaded, both tables sorted by time, partition moved into the hdb, working dir gone +true,0,0,q,tailok[],1,,sym reloaded, both tables sorted by sym then time, partition moved into the hdb, working dir gone true,0,0,q,enumintact[],1,,the sym column still resolves after the move - the point of enumerating against hdb/sym true,0,0,q,discovertables[],1,,no table list means whatever is in the working partition true,0,0,q,defaultsavedir[],1,,an empty savedir on the wire falls back to the configured one @@ -97,7 +97,7 @@ true,0,0,q,badreloadorder[],1,,a reloadorder entry that is neither an hdb, rdb, true,0,0,q,idbreloadorder[],1,,idb in reloadorder is dispatched rather than reported as unknown comment,,,,,,,config true,0,0,q,stringconfig[],1,,string (toml / command-line) settings are parsed into the right types -true,0,0,q,sortcsvhonoured[],1,,a sortcsv overrides di.dbwrite's time-asc default +true,0,0,q,sortcsvhonoured[],1,,a sortcsv overrides di.dbwrite's sym-then-time p# default true,0,0,q,defaultsortcsv[],1,,with no sortcsv the app's sort.csv is used comment,,,,,,,the process entry point true,0,0,q,initpublishes[],1,,init opens hdb/rdb/idb/gateway/sortworker/wdb connections (never a tickerplant) and publishes the root entry point diff --git a/di/torq/proc/wdb/testsort.q b/di/torq/proc/wdb/testsort.q index 21f59d45c..4481a7b62 100644 --- a/di/torq/proc/wdb/testsort.q +++ b/di/torq/proc/wdb/testsort.q @@ -82,6 +82,9 @@ makepartition:{[] / the on-disk hdb partition for a table, read back hdbtable:{[t] get hsym `$hdbdir[],"/",(string PDATE),"/",string t}; +/ sorted by sym then time, di.dbwrite's default (TorQ's config/sort.csv) +symtimesorted:{[t] t:update `#sym from select from t; t~update `#sym from `sym`time xasc t}; + partitiontables:{[dir] asc key hsym `$dir,"/",string PDATE}; config:{[] `savedir`hdbdir`hdbtypes`rdbtypes`gatewaytypes`reloadorder`permitreload`gc`eodwaittime! @@ -99,15 +102,15 @@ freshwire:{[cfg] -/ the happy path: sym reloaded, both tables sorted by time, partition moved, working dir gone +/ the happy path: sym reloaded, both tables sorted by sym then time, partition moved, working dir gone tailok:{[] freshwire config[]; tail[savedir[];PDATE;`trade`quote]; tr:hdbtable`trade; qu:hdbtable`quote; chk `sortedtrade`sortedquote`rowstrade`rowsquote`moved`workinggone`symloaded`reloadlogged!( - tr[`time]~asc tr`time; - qu[`time]~asc qu`time; + symtimesorted tr; + symtimesorted qu; 4=count tr; 2=count qu; `quote`trade~partitiontables hdbdir[]; @@ -125,7 +128,7 @@ enumintact:{[] / against the root sym the module reloaded, which is the property under test chk `enumerated`resolves!( 20h=type tr`sym; - `msft`msft`ibm`ibm~value tr`sym) + `ibm`ibm`msft`msft~value tr`sym) }; / no table list means "whatever is in the working partition" - what an operator re-running a sort wants @@ -134,7 +137,7 @@ discovertables:{[] tail[savedir[];PDATE;`]; chk `moved`sorted!( `quote`trade~partitiontables hdbdir[]; - (hdbtable[`trade]`time)~asc hdbtable[`trade]`time) + symtimesorted hdbtable`trade) }; / an empty savedir on the wire means "use the one I was configured with" @@ -235,17 +238,17 @@ stringconfig:{[] `gateway`hdb`idb`rdb`sortworker`wdb~asc distinct exec arg from scalls where fn=`getservers) }; -/ the sortcsv is honoured: sorting by sym rather than the time-asc default changes the result +/ the sortcsv is honoured: time only, with no p#, rather than the sym-then-time p# default sortcsvhonoured:{[] system "mkdir -p ",BASE,"/appconfig"; - (hsym `$BASE,"/appconfig/sort.csv") 0: ("tabname,att,column,sort";"default,,sym,1"); + (hsym `$BASE,"/appconfig/sort.csv") 0: ("tabname,att,column,sort";"default,,time,1"); freshwire config[],(enlist`sortcsv)!enlist "appconfig/sort.csv"; tail[savedir[];PDATE;`trade]; tr:hdbtable`trade; hdel hsym `$BASE,"/appconfig/sort.csv"; - chk `sortedbysym`nottimesorted!( - (tr`sym)~asc tr`sym; - not (tr`time)~asc tr`time) + chk `timesorted`notparted!( + (tr`time)~asc tr`time; + not `p=attr tr`sym) }; / with no sortcsv set, the app's sort.csv under TORQXAPPCONFIG is used @@ -315,7 +318,7 @@ fanoutok:{[] tail[savedir[];PDATE;`trade`quote]; tr:hdbtable`trade; r:chk `sorted`moved`bothworked`logged!( - tr[`time]~asc tr`time; + symtimesorted tr; `quote`trade~partitiontables hdbdir[]; all 1=count each workersorted each WORKERS; loggedlike[`info;"sorting on worker sort*"]); From 6e7cf946a0c83513a4329ea35ebc2160506c092b Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 20 Oct 2026 13:38:40 +0100 Subject: [PATCH 15/39] di.torq.proc.wdb: save down hooks through di.dbwrite; postreplay unprotected, as TorQ's wdb The private manipulate and trapped postreplay go; wdb passes its config's savedownmanipulation and postreplay (defaulting as TorQ's wdb.q:78-79) to di.dbwrite and calls its manipulate and postreplay. As legacy wdb.q:334, a failing postreplay now propagates out of end of day after the move, leaving currentpartition on the old date. Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/wdb/test.csv | 3 ++- di/torq/proc/wdb/test.q | 12 ++++++++++++ di/torq/proc/wdb/wdb.md | 2 +- di/torq/proc/wdb/wdb.q | 31 ++++++++++--------------------- 4 files changed, 25 insertions(+), 23 deletions(-) diff --git a/di/torq/proc/wdb/test.csv b/di/torq/proc/wdb/test.csv index 415bb7b8e..f613cf08a 100644 --- a/di/torq/proc/wdb/test.csv +++ b/di/torq/proc/wdb/test.csv @@ -50,8 +50,9 @@ true,0,0,q,segments[],1,,an intraday flush writes one segment per parted value a true,0,0,q,failedmerge[],1,,a failed merge signals out of end of day and leaves the segments on disk true,0,0,q,missingtables[],1,,startup writes empty table schemas into the working partition true,0,0,q,tabsizes[],1,,tablelist orders tables by bytes written -true,0,0,q,manipulation[],1,,savedownmanipulation is applied before a table is written +true,0,0,q,manipulation[],1,,savedownmanipulation is applied once before a table is written (5 doubled to 10) true,0,0,q,postreplay[],1,,postreplay is called after the move +true,0,0,q,failedpostreplay[],1,,a failing postreplay stops end of day after the move: no reload and the partition does not advance (as TorQ's wdb) true,0,0,q,compression[],1,,compression is applied to the hdb and reset afterwards true,0,0,q,fixpartition[],1,,data replayed into the wrong partition is moved to the tp log date true,0,0,q,tpretry[],1,,init fails when no tickerplant connects within tpwaittimeout diff --git a/di/torq/proc/wdb/test.q b/di/torq/proc/wdb/test.q index c4efa4d9f..ba2689a05 100644 --- a/di/torq/proc/wdb/test.q +++ b/di/torq/proc/wdb/test.q @@ -158,6 +158,18 @@ postreplay:{[] (last POST)~today[] }; +/ a failing postreplay propagates out of end of day after the move, as TorQ's wdb: no reload, the partition does not advance +failedpostreplay:{[] + freshwdb cfg[],(enlist`postreplay)!enlist {[d;p] '"boom"}; + feed[]; + e:@[{.u.end x;""};today[];{x}]; + chk `signalled`moved`noreload`notadvanced!( + e~"boom"; + 0 table!function applied before each write # getpartition (optional, .q settings) -> niladic function returning the partition value # upd (optional, .q settings) -> {[t;x]} the live upd, and the one the replay calls; default insert -# postreplay (optional, .q settings) -> {[hdbdir;pt]} called after the move, before the reload +# postreplay (optional, .q settings) -> {[hdbdir;pt]} called after the move, before the reload; an error stops end of day, as TorQ # subscribeto / subscribesyms omitted -> all tables, all syms # ignorelist omitted -> `heartbeat`logmsg (not written) # numtab (optional) -> per-table row thresholds; overrides numrows for those tables diff --git a/di/torq/proc/wdb/wdb.q b/di/torq/proc/wdb/wdb.q index a7b803c64..c32a66782 100644 --- a/di/torq/proc/wdb/wdb.q +++ b/di/torq/proc/wdb/wdb.q @@ -53,13 +53,6 @@ tablelist:{[] ((exec tablename from `bytes xdesc .z.m.tabsizes) union tables[`.] / function that ensures a list of syms is returned no matter what is passed to it ensuresymlist:{[s] -1 _ `${@[x; where not ((type each x) in (10 -10h));string]} s,(::)} -/ applies the table's savedownmanipulation function, if any, before a save -manipulate:{[t;x] - $[t in key .z.m.savedownmanipulation; - @[.z.m.savedownmanipulation t;x;{[x;e] .z.m.log[`error][`manipulate;"save down manipulation failed : ",e];x}[x]]; - x] - } - / saves a table to the partition once over its row limit; cleared with @[`.;...] as bare writes land in the module savetables:{[dir;pt;forcesave;tabname] / check row count @@ -69,7 +62,7 @@ savetables:{[dir;pt;forcesave;tabname] .z.m.log[`info][`save;"saving ",(string tabname)," data to partition ",string pt]; / upsert data to partition .[upsert; - (` sv .Q.par[dir;pt;tabname],`;.Q.en[.z.m.hdbdir;r:0!manipulate[tabname;`. tabname]]); + (` sv .Q.par[dir;pt;tabname],`;.Q.en[.z.m.hdbdir;r:0!(.z.m.dbw`manipulate)[tabname;`. tabname]]); {[e] .z.m.log[`error][`savetables;"Failed to save table to disk : ",e];'e}]; / make addition to tabsizes .z.m.log[`info][`track;"appending table details to tabsizes"]; @@ -135,7 +128,7 @@ savetablesbypart:{[dir;pt;forcesave;tablename;writedownmode] / get list of distinct combinations for partition directories extrapartitions:$[writedownmode~`partbyfirstchar;.z.m.mrg`getfirstcharpartitions;.z.m.mrg`getextrapartitions][tablename;extrapartitiontype]; / enumerate data to be upserted - enumdata:.Q.en[.z.m.hdbdir;0!manipulate[tablename;`. tablename]]; + enumdata:.Q.en[.z.m.hdbdir;0!(.z.m.dbw`manipulate)[tablename;`. tablename]]; .z.m.log[`info][`save;"enumerated ",(string tablename)," table"]; / upsert data to specific partition directory upserttopartition[dir;tablename;enumdata;pt;extrapartitiontype;;writedownmode] each extrapartitions; @@ -342,16 +335,11 @@ endofdaysortdate:{[dir;pt;tablist;hdbsettings] " directory to the hdb directory ",hw:(.z.m.os`topath) -1_string .Q.par[hdbsettings`hdbdir;pt;`]]; .z.m.log[`info][`mvtohdb;"Attempting to move ",(", " sv string key hsym `$dw)," from ",dw," to ",hw]; .[movetohdb;(dw;hw;pt);{[e] .z.m.log[`error][`mvtohdb;"Function movetohdb failed with error: ",e]}]; - / call the posteod function - postreplay[hdbsettings`hdbdir;pt]; + / call the postreplay hook, unprotected as TorQ's wdb + (.z.m.dbw`postreplay)[hdbsettings`hdbdir;pt]; if[.z.m.permitreload;doreload pt]; } -/ post eod function, invoked after all the tables have been written down -postreplay:{[hdbdir;pt] - @[.z.m.posteod .;(hdbdir;pt);{[e] .z.m.log[`error][`postreplay;"postreplay failed: ",e]}]; - } - / the loaded sort config, or an empty one as legacy's .sort.params sortparams:{[] $[(::)~c:(.z.m.dbw`getconfig)[];([] tabname:`symbol$(); att:`symbol$(); column:`symbol$(); sort:`boolean$());c]} @@ -439,8 +427,8 @@ endofdaymerge:{[dir;pt;tablist;mergelimits;hdbsettings;mergemethod;writedownmode if[count key p:.Q.par[dir;pt;`]; .z.m.log[`info][`merge;"attempting to delete temp storage directory"]; @[.z.m.os`deldir;p;{[p;e] .z.m.log[`info][`eod;"could not delete directory: ",(1_string p)," - maybe something(IDB?) gets hold of it."]}[p]]]; - / call the posteod function - postreplay[hdbsettings`hdbdir;pt]; + / call the postreplay hook, unprotected as TorQ's wdb + (.z.m.dbw`postreplay)[hdbsettings`hdbdir;pt]; $[.z.m.permitreload;doreload pt;if[.z.m.gc;.Q.gc[]]]; } @@ -607,7 +595,10 @@ checksortparams:{[] / reads the sort.csv, as legacy the app's sort.csv when no sortcsv is set initdbwrite:{[config;deps] .z.m.dbw:use`di.dbwrite; - (.z.m.dbw`init)[enlist[`log]!enlist deps`log]; + / the save down hooks from config, defaulting as TorQ's wdb.q:78-79, go to di.dbwrite + sdm:$[`savedownmanipulation in key config;config`savedownmanipulation;()!()]; + pr:$[`postreplay in key config;config`postreplay;{[d;p]}]; + (.z.m.dbw`init)[`log`savedownmanipulation`postreplay!(deps`log;sdm;pr)]; f:$[`sortcsv in key config;resolvedir[apphome[];config`sortcsv];getenv[`TORQXAPPCONFIG],"/sort.csv"]; if[(`sortcsv in key config) or count key hsym `$f;(.z.m.dbw`readcsv) f]; } @@ -646,10 +637,8 @@ setconfig:{[config] .z.m.immediate:$[`immediate in key config;tobool config`immediate;0b]; .z.m.gc:$[`gc in key config;tobool config`gc;1b]; .z.m.partitiontype:$[`partitiontype in key config;assym config`partitiontype;`date]; - .z.m.savedownmanipulation:$[`savedownmanipulation in key config;config`savedownmanipulation;()!()]; .z.m.getpartition:$[`getpartition in key config;config`getpartition;defaultgetpartition]; .z.m.upd:$[`upd in key config;config`upd;insert]; - .z.m.posteod:$[`postreplay in key config;config`postreplay;{[d;p]}]; .z.m.reloadorder:$[`reloadorder in key config;astoklist config`reloadorder;`hdb`rdb`idb]; .z.m.permitreload:$[`permitreload in key config;tobool config`permitreload;1b]; .z.m.eodwaittime:$[`eodwaittime in key config;astimespan config`eodwaittime;0D00:00:10]; From 6f2bbbf3fec9681341f261e8f2f2e1a063d7b3ce Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 20 Oct 2026 14:37:52 +0100 Subject: [PATCH 16/39] di.torq.proc.tickerlogreplay: save down hooks through di.dbwrite, read from .replay.* at init The load-time .save.manipulate and root .save.savedownmanipulation / .save.postreplay go; init reads .replay.savedownmanipulation and .replay.postreplay (defaulting as TorQ's tickerlogreplay.q:40-41), passes them to di.dbwrite, and the replay calls its manipulate and postreplay. Hooks set after use and before init are now honoured. Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/tickerlogreplay/test.csv | 6 +++++- di/torq/proc/tickerlogreplay/test.q | 5 +++++ .../proc/tickerlogreplay/tickerlogreplay.md | 8 ++++---- .../proc/tickerlogreplay/tickerlogreplay.q | 19 ++++++------------- 4 files changed, 20 insertions(+), 18 deletions(-) diff --git a/di/torq/proc/tickerlogreplay/test.csv b/di/torq/proc/tickerlogreplay/test.csv index aea7fb3fd..b1142f68d 100644 --- a/di/torq/proc/tickerlogreplay/test.csv +++ b/di/torq/proc/tickerlogreplay/test.csv @@ -4,7 +4,7 @@ before,0,0,q,"system ""l di/torq/proc/tickerlogreplay/test.q""",1,,load fixture before,0,0,q,setupfixture[],1,,write the schema and a plain log; run a segmentedtp to write segmented logs comment,,,,,,,settings -true,0,0,q,all `savedownmanipulation`manipulate`postreplay in key .save,1,,save helpers defined +true,0,0,q,"not any `savedownmanipulation`manipulate`postreplay in @[key;`.save;()]",1,,no root .save hooks: they live in di.dbwrite fail,0,0,q,"tlr.init[()!();()!()]",1,,init without log must error comment,,,,,,,plain log @@ -51,6 +51,10 @@ true,0,0,q,"0=replayp[(""`.replay.savedownmanipulation set enlist[`trade]!enlist true,0,0,q,2 4 8f~asc hdb[D;`trade]`price,1,,the manipulation ran before saving true,0,0,q,"(""D""$D)~get fp""post""",1,,postreplay ran with the partition run,0,0,q,clearhdb[],1,, +true,0,0,q,"0=replayi[(""`.replay.savedownmanipulation set enlist[`trade]!enlist {update price:2*price from x}"";""`.replay.postreplay set {[d;p] ("",hp[""post2""],"") set p}"");sect plain ""()!()""]",1,,hooks set after the module loads and before init (read at init) +true,0,0,q,2 4 8f~asc hdb[D;`trade]`price,1,,the .replay.savedownmanipulation hook is applied once through di.dbwrite +true,0,0,q,"(""D""$D)~get fp""post2""",1,,the .replay.postreplay hook is called with the partition +run,0,0,q,clearhdb[],1,, true,0,0,q,"0=replayp[enlist""`.replay.upd set {[t;x] if[t~`trade;insert[t;x]]}"";sect plain ""()!()""]",1,,replay with an upd override true,0,0,q,(3;0)~(rows[D;`trade];rows[D;`quote]),1,,the upd override decided what was inserted diff --git a/di/torq/proc/tickerlogreplay/test.q b/di/torq/proc/tickerlogreplay/test.q index 63ceb8cc4..b62f24a05 100644 --- a/di/torq/proc/tickerlogreplay/test.q +++ b/di/torq/proc/tickerlogreplay/test.q @@ -16,6 +16,11 @@ replayp:{[pre;cfg] runq( "@[r.init[;enlist[`log]!enlist lg];",cfg,";{-1 \"ERR \",x;exit 3}]"; "exit 0"))} replay:replayp[()] +/ as replayp, but the q lines run after the module is loaded and before init, as a user setting hooks would +replayi:{[post;cfg] runq( + enlist["lg:`info`warn`error!({[c;m] -1 \"I \",string[c],\": \",m};{[c;m] -1 \"W \",string[c],\": \",m};{[c;m] -1 \"E \",string[c],\": \",m})"],(enlist"r:use`di.torq.proc.tickerlogreplay"),post,( + "@[r.init[;enlist[`log]!enlist lg];",cfg,";{-1 \"ERR \",x;exit 3}]"; + "exit 0"))} / replay settings for the plain log, with overrides plain:{[x] "(`schemafile`hdbdir`tplogfile`segmentedmode!(`$\"",FIXDIR,"/schema.q\";`$\":",FIXDIR,"/hdb\";`$\":",FIXDIR,"/tplog",D,"\";0b)),",x} sect:{[x] "((use`di.torq.config)[`parsefile] \"di/torq/settings/tickerlogreplay.q\"),",x} diff --git a/di/torq/proc/tickerlogreplay/tickerlogreplay.md b/di/torq/proc/tickerlogreplay/tickerlogreplay.md index a238c6fe1..4c361ef1e 100644 --- a/di/torq/proc/tickerlogreplay/tickerlogreplay.md +++ b/di/torq/proc/tickerlogreplay/tickerlogreplay.md @@ -7,9 +7,9 @@ at the end, or partition to a temporary directory and merge on disk. ## Files -`init.q` loads `tickerlogreplay.q`: the module `init`, then `.save.manipulate` (defined if absent), the `.replay.upd` -hook, and `.save.savedownmanipulation` / `.save.postreplay` from their `.replay` names. `sort.csv` is the default sort -config. +`init.q` loads `tickerlogreplay.q`: the module `init` and the `.replay.upd` hook. `init` reads the +`.replay.savedownmanipulation` / `.replay.postreplay` hooks and hands them to di.dbwrite, which applies them. +`sort.csv` is the default sort config. ## Surface @@ -17,7 +17,7 @@ config. |---|---| | `init[config;deps]` | applies the settings, checks them, loads the schema, and replays if `autoreplay` | | `.replay.upd[t;x]` | inserts a replayed message; set it before `use` to change how messages are applied | -| `.save.savedownmanipulation` / `.save.postreplay[d;p]` | table!function applied before saving / called after each log is saved; set `.replay.savedownmanipulation` / `.replay.postreplay` before `use` | +| `.replay.savedownmanipulation` / `.replay.postreplay[d;p]` | table!function applied before saving / called after each log is saved, through di.dbwrite; set them before `init` | ## Settings diff --git a/di/torq/proc/tickerlogreplay/tickerlogreplay.q b/di/torq/proc/tickerlogreplay/tickerlogreplay.q index c182194ba..489b29d81 100644 --- a/di/torq/proc/tickerlogreplay/tickerlogreplay.q +++ b/di/torq/proc/tickerlogreplay/tickerlogreplay.q @@ -17,7 +17,10 @@ init:{[config;deps] .z.m.log:deps`log; .z.m.tplog:use`di.tplog; .z.m.dbw:use`di.dbwrite; - .z.m.dbw.init enlist[`log]!enlist deps`log; + / the save down hooks from .replay.*, set before init, defaulting as TorQ's tickerlogreplay.q:40-41, go to di.dbwrite + sdm:@[value;`.replay.savedownmanipulation;()!()]; + pr:@[value;`.replay.postreplay;{{[d;p]}}]; + .z.m.dbw.init `log`savedownmanipulation`postreplay!(deps`log;sdm;pr); .z.m.os:use`di.os; / all settings required req:`firstmessage`lastmessage`messagechunks`segmentedmode`autoreplay`schemafile`tablelist`hdbdir`tplogfile`tplogdir; @@ -82,19 +85,9 @@ init:{[config;deps] if[autoreplay;initandrun[]]; }; -/ manipulate a table at save down time, defined if absent -if[not `manipulate in key `.save;.save.manipulate:{[t;x] - $[t in key .save.savedownmanipulation; - @[.save.savedownmanipulation[t];x;{.z.m.log[`error][`manipulate;"save down manipulation failed : ",y];x}[x]]; - x]}]; - / default upd; set .replay.upd before use to override .replay.upd:@[value;`.replay.upd;{{[t;x] insert[t;x]}}] -/ save down settings -.save.savedownmanipulation:@[value;`.replay.savedownmanipulation;()!()] // table!function applied to a table at save -.save.postreplay:@[value;`.replay.postreplay;{{[d;p] }}] // invoked after a log's tables are saved - // the path to the table to save pathtotable:{[h;p;t] `$(string .Q.par[h;partitiontype$p;t]),"/"} @@ -111,7 +104,7 @@ savetabdata:{[h;p;t;data;UPSERT;td] $[partandmerge;path:pathtotable[td;p;t];path:pathtotable[h;p;t]]; if[not partandmerge;.z.m.log[`info][`replay;"saving table ",(string t)," to ",string path]]; .z.m.pathlist[t],:path; - $[partandmerge;savetablesbypart[td;p;t;h];$[UPSERT;upsert;set] . (path;.Q.en[h;0!.save.manipulate[t;data]])] + $[partandmerge;savetablesbypart[td;p;t;h];$[UPSERT;upsert;set] . (path;.Q.en[h;0!.z.m.dbw.manipulate[t;data]])] } savetabdatatrapped:{[h;p;t;data;UPSERT;td] .[savetabdata;(h;p;t;data;UPSERT;td);{.z.m.log[`error][`replay;"failed to save table : ",x]}]} @@ -152,7 +145,7 @@ finishreplay:{[h;p;td] // save down any tables which haven't been saved savetab[td;h;p] each tabsincountorder[tablestoreplay]; // invoke any user defined post replay function - .save.postreplay[h;p]; + .z.m.dbw.postreplay[h;p]; } // takes in log file directories made with segmented tickerplant From aac042ac28426d671627a8a0fe49efbe42364edb Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 20 Oct 2026 14:50:49 +0100 Subject: [PATCH 17/39] di.torq.proc.rdb: save down hooks through di.dbwrite; keep g# after the standalone clear; postreplay unprotected, as TorQ's rdb init passes the config's savedownmanipulation and postreplay (defaulting as TorQ's rdb.q:42-43) to di.dbwrite, ahead of the tickerplant wait as legacy reads its hooks at load. Standalone end of day captures the in-memory attributes before the save, reapplies them after the clear, then calls postreplay unprotected before the hdb reload, as legacy rdb.q:104-118. Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/rdb/rdb.md | 12 ++++--- di/torq/proc/rdb/rdb.q | 18 ++++++---- di/torq/proc/rdb/test.csv | 9 +++++ di/torq/proc/rdb/test.q | 76 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 105 insertions(+), 10 deletions(-) create mode 100644 di/torq/proc/rdb/test.q diff --git a/di/torq/proc/rdb/rdb.md b/di/torq/proc/rdb/rdb.md index 2fa77af85..650486209 100644 --- a/di/torq/proc/rdb/rdb.md +++ b/di/torq/proc/rdb/rdb.md @@ -32,7 +32,9 @@ reloadenabled = false # false (default): save+clear own tables at EO # true: a wdb owns the writedown - defer to its reload[] call. # subscribeto / subscribesyms omitted -> all tables, all syms # ignorelist omitted -> `heartbeat`logmsg (not saved at EOD) -# sortcsv (optional) -> di.dbwrite sort/attribute config; else dbwrite's default (time asc) +# sortcsv (optional) -> di.dbwrite sort/attribute config; else dbwrite's default (sym then time, p# on sym) +# savedownmanipulation (optional, .q settings) -> table!function applied before each table is saved +# postreplay (optional, .q settings) -> {[hdbdir;date]} called after the save, clear and attribute reapply, before the hdb reload; an error stops end of day, as TorQ ``` Set `reloadenabled = true` **only** when a wdb is present in the stack — otherwise the EOD @@ -52,7 +54,8 @@ di.subscriptions defines the tables at root from what the TP returns. - **End of day**: `.u.end[date]` (from a tickerplant or chainedtp) or root `endofday[date;data]` (from a segmented tickerplant, which also calls the logging `endofperiod` stub). Behaviour depends on `reloadenabled`: - **standalone** (`0b`, default): saves every non-ignored root table to `hdbdir` for `date` - (`di.dbwrite.savedown` — enumerate, splay, sort, attr, gc), clears each (`@[`.;t;0#]`), + (`di.dbwrite.savedown` — manipulate, enumerate, splay, sort, attr, gc), clears each (`@[`.;t;0#]`), + reapplies the in-memory attributes the clear drops (`` `g# `` on sym), calls `postreplay[hdbdir;date]`, then tells every connected HDB to `.hdb.reload[]`. - **wdb-fronted** (`1b`): a wdb owns the writedown, so di.torq.proc.rdb only **snapshots** the per-table row counts (`.z.m.eodtabcount`) and escapes — the data stays live and @@ -104,8 +107,9 @@ and **clears** target root explicitly via `@[`.;…]`, and its `upd` is root-saf ## Testing -`test.csv` (k4unit) covers the dependency contract (init errors without `log`/`timer`) and -the export surface. The full subscribe → replay → live-capture → EOD-save → HDB-reload +`test.csv` (k4unit) covers the dependency contract (init errors without `log`/`timer`), the +export surface, and standalone end of day (`test.q`: `init` runs to the tickerplant wait against +mocked servers): attributes kept, the save down hooks, and the `reloadenabled` escape. The full subscribe → replay → live-capture → EOD-save → HDB-reload flow is proven in the **TorqX-POC end-to-end** (`torqx.sh start tickerplant1 hdb feed1 rdb1`): the RDB replays the tp log on startup, accumulates live trade/quote, and on a forced tickerplant `endofday` writes the partition to the HDB (verified on disk), clears, diff --git a/di/torq/proc/rdb/rdb.q b/di/torq/proc/rdb/rdb.q index 8fb3c2c4a..3b3d281d3 100644 --- a/di/torq/proc/rdb/rdb.q +++ b/di/torq/proc/rdb/rdb.q @@ -65,8 +65,12 @@ endofday:{[date] .z.m.eodtabcount:st!count each value each st; .z.m.log[`info][`rdb;"reload enabled - wdb owns writedown; snapshotted EOD row counts: ",.Q.s1 .z.m.eodtabcount]; :()]; + attrs:st!grabattrs each st; / capture before the clear wipes them, as legacy rdb.q:104 savefn[.z.m.hdbdir;date] each st; @[`.;;0#] each st; / clear the saved tables (root) + reapplyattrs'[st;attrs st]; + / call the postreplay hook, unprotected as TorQ's rdb.q:118 + (.z.m.dbw`postreplay)[hsym`$.z.m.hdbdir;date]; notifyhdbs[]; .z.m.log[`info][`rdb;"end of day complete, saved+cleared: ",(", " sv string st)]; } @@ -116,6 +120,14 @@ init:{[config;deps] replaylog:$[`replaylog in key config;`boolean$config`replaylog;1b]; timeout:$[`tpwaittimeout in key config;"j"$config`tpwaittimeout;30000]; + / di.dbwrite for savedown (optional sort.csv sort/attr config), set before the tickerplant wait as legacy reads its hooks at load + .z.m.dbw:use`di.dbwrite; + / the save down hooks from config, defaulting as TorQ's rdb.q:42-43, go to di.dbwrite + sdm:$[`savedownmanipulation in key config;config`savedownmanipulation;()!()]; + pr:$[`postreplay in key config;config`postreplay;{[d;p]}]; + (.z.m.dbw`init)[`log`savedownmanipulation`postreplay!(deps`log;sdm;pr)]; + if[`sortcsv in key config;(.z.m.dbw`readcsv)[resolvedir[apphome[];config`sortcsv]]]; + / publish the root-safe upd BEFORE subscribing (replay drives it too) @[`.;`upd;:;updfn]; @@ -136,12 +148,6 @@ init:{[config;deps] sd:.sub.subscribe[subscribeto;subscribesyms;1b;replaylog;first .sub.getsubscriptionhandles[tpt;`;()!()]]; if[count sd;.z.m.log[`info][`rdb;"subscribed, partition date ",string sd`d]]; - / di.dbwrite for savedown (optional sort.csv sort/attr config). Takes the injected binary - / (ctx;msg) log dep directly - no adapter, since di.dbwrite now uses the same contract. - .z.m.dbw:use`di.dbwrite; - (.z.m.dbw`init)[enlist[`log]!enlist deps`log]; - if[`sortcsv in key config;(.z.m.dbw`readcsv)[resolvedir[apphome[];config`sortcsv]]]; - / publish the EOD entry points at root. / reload[date] is the wdb's IPC entry point when reloadenabled (harmless if never called). set[`.u.end;endofday]; diff --git a/di/torq/proc/rdb/test.csv b/di/torq/proc/rdb/test.csv index 044f94cdb..be24f036f 100644 --- a/di/torq/proc/rdb/test.csv +++ b/di/torq/proc/rdb/test.csv @@ -7,3 +7,12 @@ fail,0,0,q,rdb.init[()!();(enlist`log)!enlist mlog],1,,init with log but no time true,0,0,q,`init`endofday`reload`version~key rdb,1,,module exports init/endofday/reload/version true,0,0,q,0 Date: Tue, 20 Oct 2026 16:10:52 +0100 Subject: [PATCH 18/39] di.compression: worker processes compress a table each, as TorQ #732; export single-file compress With -s below 0, compressfromtable peaches one table to each worker process, which compresses and verifies it there, as TorQ #732; the final state is unchanged. compress is exported for single-file use, as legacy housekeeping's kdbzip calls .cmp.compress. Co-Authored-By: Claude Opus 5.5 --- di/compression/compression.md | 2 ++ di/compression/compression.q | 4 +-- di/compression/init.q | 2 +- di/compression/test.csv | 13 ++++++++ di/compression/test.q | 61 +++++++++++++++++++++++++++++++++++ 5 files changed, 79 insertions(+), 3 deletions(-) create mode 100644 di/compression/test.q diff --git a/di/compression/compression.md b/di/compression/compression.md index 65165809c..3fc274a23 100644 --- a/di/compression/compression.md +++ b/di/compression/compression.md @@ -15,6 +15,7 @@ - Flexibility to compress different tables/columns with different compression parameters - Preview available before compression to display files to be compressed and how - Summary statistics for each file returned after compression/decompression complete +- With worker threads (`-s` above 0) files compress in parallel; with worker processes (`-s` below 0) each worker compresses and verifies one table, as TorQ --- @@ -69,6 +70,7 @@ depth, 10,default, 1, 17, 8 |`compressmaxage` | Compress files according to config up to the specified max age | |`docompression` | Compress all files in hdb according to compressioncsv config | |`getstatstab` | get function to retrieve summary stats post compression | +|`compress` | `[file;algo;blocksize;level;size]` compress (algo 0: decompress) one file to `file_kdbtempzip`, leaving the original in place | --- diff --git a/di/compression/compression.q b/di/compression/compression.q index 848b3a68b..8bf568395 100644 --- a/di/compression/compression.q +++ b/di/compression/compression.q @@ -86,12 +86,12 @@ showcomp:{[hdbpath;csvpath;maxage] compressfromtable:{[table] statstab::([] file:`$(); algo:`int$(); compressedLength:`long$();uncompressedLength:`long$()); - / Check if process is single threaded - if multi then compress in parallel then clean up after + / Check if process is single threaded - if multi then compress in parallel then clean up after; worker processes (s<0) take a table each, as TorQ #732 / Add metrics on any files due to be compressed to be used afterwards for comparison table:update compressionvaluepre:{(-21!x)`compressedLength}'[fullpath] from table; $[0= system"s"; singlethreadcompress[table]; - multithreadcompress[table]]; + $[0/dev/null 2>&1 &"} each 1 2; + / wait up to 10s for both port files + {[x] system "sleep 0.1"; x+1}/[{(x<100) and 2>count portfiles[]};0]; + `WPORTS set "J"$first each read0 each portfiles[]; + `WH set hopen each WPORTS; + }; + +/ compress the hdb with \s -2 over the workers, counting cleancompressed calls on this process +CLEANS:0; +workerrun:{[] + mkworkerhdb[]; + orig:.m.di.0compression.cleancompressed; + .m.di.0compression.cleancompressed:{[o;f;a] @[`.;`CLEANS;+;1]; o[f;a]}[orig]; + .z.pd:{`u#WH}; + system "s -2"; + r:@[{cmp.docompression[hsym`$WDIR,"/hdb";hsym`$WDIR,"/params.csv"];`ok};::;{x}]; + system "s 0"; + .m.di.0compression.cleancompressed:orig; + f:raze {p:.Q.par[hsym`$WDIR,"/hdb";2026.01.01;x]; ` sv/: p,/:key[p] except `.d} each `trade`quote; + `result`mainclean`algos`stats!(r;CLEANS;{(-21!x)`algorithm} each f;count cmp.getstatstab[]) + }; + +stopworkers:{[] + {neg[x] "exit 0"; neg[x][]} each WH; + system "rm -rf ",WDIR; + }; + +/ the single-file compress legacy housekeeping's kdbzip calls: .cmp.compress[f;2;17;4;hcount f] (housekeeping.q:64) +onefile:{[] + f:hsym`$WDIR,"_one"; + f set v:100000?100f; + cmp.compress[f;2;17;4;hcount f]; + t:hsym`$(string f),"_kdbtempzip"; + r:`original`temp`same!(0=count -21!f;2 17 4i~(-21!t)`algorithm`logicalBlockSize`zipLevel;v~get t); + hdel each (f;t); + r + }; From 99a4b721fab6c9e7dff43f77ede29534260032d4 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 20 Oct 2026 16:55:35 +0100 Subject: [PATCH 19/39] di.torq.proc.housekeeping: TorQ's job csv format and action names; rm skips directories, as TorQ's housekeeping The job csv is read as legacy housekeeping.q:44-51: function,path,match, exclude,age,agemin,checkfordirectory, the last two named by position and optional, rows with a null function or age skipped and logged. The actions are TorQ's rm, zip and tardir. rm on a matched directory is skipped and logged as an error, as legacy's rm -f fails on one. kdbzip stays out. Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/housekeeping/housekeeping.md | 68 ++++++++++----------- di/torq/proc/housekeeping/housekeeping.q | 72 ++++++++++------------- di/torq/proc/housekeeping/test.csv | 27 +++++++-- di/torq/proc/housekeeping/test.q | 31 +++++++--- 4 files changed, 107 insertions(+), 91 deletions(-) diff --git a/di/torq/proc/housekeeping/housekeeping.md b/di/torq/proc/housekeeping/housekeeping.md index 99217ae31..f6a9b3735 100644 --- a/di/torq/proc/housekeeping/housekeeping.md +++ b/di/torq/proc/housekeeping/housekeeping.md @@ -14,8 +14,8 @@ policy ("old `out_`/`err_` files accumulate forever… external housekeeping is ## Dependencies - **Injected** (from di.torq): `log`, `timer`. -- **`use`-imported**: `di.os` (for the `rm` action — it picks the right call for a file vs a - directory, and its dry-run mode makes a destructive action testable); declared in `deps.toml`. +- **`use`-imported**: `di.os` (for the `rm` action — its dry-run mode makes a destructive action + testable); declared in `deps.toml`. ## Config @@ -66,23 +66,29 @@ settings file can introduce it either way; it is the *command-line* tier that ne ## The job csv -One row per cleanup job. All seven columns are required: +One row per cleanup job, in legacy TorQ's format (`housekeeping.q:44-51`), so a TorQ or starter-pack +csv works unchanged: | column | type | meaning | |---|---|---| -| `action` | symbol | `rm`, `gzip` or `tar` | +| `function` | symbol | `rm`, `zip` (gzip) or `tardir` (tar the directory and remove it) | | `path` | string | directory to search (not recursive — `find -maxdepth 1`) | | `match` | string | glob to match, e.g. `*.log` | | `exclude` | string | glob to exclude; may be empty | -| `age` | int | minimum age, in `unit`s | -| `unit` | symbol | `d` (days) or `m` (minutes) | -| `dirs` | boolean | `1` to match directories instead of files (what `tar` wants) | +| `age` | int | minimum age, in days (or minutes if `agemin`) | +| `agemin` | boolean | `1` if `age` is in minutes; may be empty | +| `checkfordirectory` | boolean | `1` to match directories instead of files (what `tardir` wants); may be empty | + +The last two columns are named by position, and may be left out: TorQ's own +`config/housekeeping.csv` has only the first five, and gets both as `0`. A row with a null +`function` or `age` is skipped and logged. `rm` on a matched directory is skipped and logged as an +error, as legacy's `rm -f` fails on one. ```csv -action,path,match,exclude,age,unit,dirs -rm,{TORQXLOGDIR}/,*.log,keepme.log,10,d,0 -gzip,{TORQXLOGDIR}/,*.log,,2,d,0 -tar,{TORQXDATAHOME}/oldruns/,run_*,,30,d,1 +function,path,match,exclude,age,agemin,checkfordirectory +rm,{TORQXLOGDIR}/,*.log,keepme.log,10,, +zip,{TORQXLOGDIR}/,*.log,,2,, +tardir,{TORQXDATAHOME}/oldruns/,run_*,,30,,1 ``` `{ENVVAR}` placeholders in `path` are expanded from the environment, so a csv follows a @@ -107,7 +113,7 @@ This is the front door for what legacy TorQ got from `wrapper` calling `value` o root-level function the csv named — genuinely extensible, but unbounded: a csv naming `exit`, or any other root function, got it called with file paths. Dispatch here stays closed over one dictionary that an app adds to deliberately. `addaction` rejects a non-symbol name, a -non-function handler, and any attempt to shadow `rm`/`gzip`/`tar` (silently swapping `rm` out +non-function handler, and any attempt to shadow `rm`/`zip`/`tardir` (silently swapping `rm` out from under a job csv that already names it helps nobody); re-registering an existing custom action is allowed but warns. @@ -119,19 +125,11 @@ logged it. The csv is **re-read on every run**, so jobs can be edited without bouncing the process. -### Migrating a TorQ housekeeping csv - -Columns were renamed for clarity; the behaviour is the same: - -| legacy TorQ | here | -|---|---| -| `function` | `action` | -| `agemin` (boolean: age is in minutes) | `unit` (`d`/`m`) | -| `checkfordirectory` | `dirs` | +### Differences from a TorQ housekeeping csv -Legacy also allowed the last two columns to be omitted, and needed a fragile column-rename dance -to cope. Here all seven are required and a mismatched header is a clear error naming both the -columns found and the columns expected. +The format is TorQ's. Two things differ: a `function` must be `rm`, `zip`, `tardir` or one registered +with `addaction` (legacy called any root function of that name), and each job is trapped, so one +failing row is logged and the rest still run (legacy's `wrapper each` is not trapped per row). ## Behaviour @@ -163,8 +161,10 @@ explicit opt-in via `runnow`. A test asserts nothing is published at `.housekeep errors on Windows rather than starting half-working — legacy's own Windows `zip`/`tar` were never implemented either, and the framework tier has dropped Windows elsewhere (see `logroll.md`). Add if TorqX ever needs it. -- **`kdbzip`** (kdb `-19!` column compression). That whole concern belongs to `di.compression`, - which does it far more thoroughly, csv-driven, with its own stats. +- **`kdbzip`** (`housekeeping.q:63-67`). Legacy calls `.cmp.compress[f;2;17;4;hcount f]`, which only + writes a compressed `f_kdbtempzip` copy; nothing renames or cleans it, so every run leaves the + original uncompressed plus a copy. It is not in TorQ's `apidetails`, and neither TorQ's nor the + starter pack's csv uses it. - **"Run once and exit"** (legacy's `runnow` semantics). Exiting from inside `init` would fight `torqx.sh`, which owns this process's lifecycle. `runnow` here means "also run once now"; a genuine one-shot is a cron job calling `.housekeeping.runjobs[]` over IPC. @@ -178,11 +178,8 @@ Roughly in the order they'd pay off: - **Dry-run / report mode.** The highest-value gap for a process whose whole job is deleting things: ask "what *would* this csv remove tonight?" and get the match list without acting. `di.os` already has the machinery (`setdrysyscalls` caches calls instead of running them), but - it only covers the `rm` action — `gzip`/`tar` shell out directly, and `di.os` doesn't export + it only covers the `rm` action — `zip`/`tardir` shell out directly, and `di.os` doesn't export `syscall`, so a complete dry run needs either an export from `di.os` or a local indirection. -- **kdb-native compression as an action.** Legacy's `kdbzip` (`.cmp.compress`, `-19!`). Deliberately - dropped because `di.compression` does it far more thoroughly; a v2 could wire that module in as - a `kdbcompress` action rather than reimplementing it. - **Per-job schedules.** Every job runs at every `runtimes` entry. Retention policies usually want different cadences (nightly log sweep, weekly archive), which today needs two processes. - **Recursion / depth control.** `find -maxdepth 1` is hardcoded, so a job only sees the directory @@ -192,9 +189,6 @@ Roughly in the order they'd pay off: `di.compression`'s stats) so a dashboard or heartbeat can see that housekeeping is actually keeping up, rather than reading log lines. - **Windows.** The `.win` branch, if TorqX ever needs it. -- **Malformed-header reporting.** `0:` pads a too-short header with invented names, so the error - says `has columns wrong, header, entirely, x, x1, x2, x3`. Reporting the raw header line would - read better. - **`tar` path noise.** Absolute paths make `tar` emit `Removing leading '/' from member names` to stderr on every archive. Harmless and matches legacy, but `-C` would silence it. @@ -233,11 +227,13 @@ only reads the action dictionary, which exists from load — and a test asserts either way. **All three actions** are exercised, each against its own fixture directory (the `rm` job really -deletes its inputs, so a shared directory would make test order significant): `rm`, `gzip` -(asserting the `.gz` appears *and* the original is consumed), and `tar` with `dirs = 1` +deletes its inputs, so a shared directory would make test order significant): `rm`, `zip` +(asserting the `.gz` appears *and* the original is consumed), and `tardir` with `checkfordirectory = 1` (asserting the archive appears *and* that `--remove-files` deleted the original directory — the -most destructive thing this module does). A separate job uses `unit = m` to exercise `find`'s +most destructive thing this module does). A separate job uses `agemin = 1` to exercise `find`'s `-mmin` branch, which is otherwise one character from `-mtime` and would ship broken unnoticed. +The legacy layouts are covered too: TorQ's 5-column csv, a null-age row skipped while the next row +runs, and `rm` matching a directory, which leaves it in place and logs an error. `runnow` is tested in **both** directions: that setting it performs a run, and — asserted on the earlier no-`runnow` init, *before* the runnow test consumes the fixture — that omitting it does diff --git a/di/torq/proc/housekeeping/housekeeping.q b/di/torq/proc/housekeeping/housekeeping.q index 967976850..b824bc79f 100644 --- a/di/torq/proc/housekeeping/housekeeping.q +++ b/di/torq/proc/housekeeping/housekeeping.q @@ -1,13 +1,13 @@ / di.torq.proc.housekeeping - scheduled file-maintenance process type. Applies a list of -/ cleanup jobs (remove / gzip / tar files or directories older than some age) read from a csv, +/ cleanup jobs (remove / zip / tardir files or directories older than some age) read from a csv, / on a daily schedule. Ported from TorQ/code/processes/housekeeping.q. / --- / Scope (v1): unix only. Legacy shipped parallel .unix.*/.win.* implementations and dispatched / on .z.o; the .win branch is NOT ported (its own zip/tar were never implemented there, and the / framework tier has dropped Windows elsewhere - see di.torq.logroll's same note). init errors -/ on Windows rather than starting half-working. Also NOT ported: legacy's kdbzip action (kdb -/ -19! column compression) - that whole concern belongs to di.compression, which does it far -/ more thoroughly; and legacy's "runnow then exit" one-shot mode (see runnow below). +/ on Windows rather than starting half-working. Also NOT ported: legacy's kdbzip action, which +/ leaves the original uncompressed plus a _kdbtempzip copy on every run (see housekeeping.md); +/ and legacy's "runnow then exit" one-shot mode (see runnow below). / --- / Why a csv for the jobs and settings for the rest: the job list is tabular and / variable-length (one row per path/match/action), which a .q/.toml settings file models @@ -77,26 +77,17 @@ expandenv:{[s] first[c],raze {i:x?"}";$[i=count x;"{",x;getenv[`$i#x],(i+1)_x]} each 1_c } -/ the job csv's schema: column name -> its 0: type char, in order. Deliberately ONE structure -/ rather than a name list beside a "S***ISB" literal - they have to agree positionally, and -/ nothing but care keeps two parallel lists in step when a column is added. -/ NOT a setting, despite looking like config: these names are compiled into the field accesses -/ in findmatches/applyjob (j`action, j`path, ...), so an operator who renamed one would get a -/ csv that passes the header check and then fails on first use. Renamed from legacy TorQ's -/ function/agemin/checkfordirectory for clarity; housekeeping.md has the migration mapping. -jobschema:`action`path`match`exclude`age`unit`dirs!"S***ISB" - -/ read the job list. Re-read on every run rather than cached at init, so an operator can edit -/ the csv without bouncing the process (legacy read it per run too). All columns are required - -/ legacy allowed trailing optional ones and needed a fragile rename dance to cope; a strict -/ header with a clear error is easier to get right than to debug. +/ read the job list, as legacy housekeeping.q:44-51; re-read on every run so the csv can be edited without a restart readjobs:{[path] f:hsym `$path; if[not count key f;'"job csv not found at ",path]; - t:(value jobschema;enlist ",") 0: f; - if[not (key jobschema)~cols t; - '"job csv ",path," has columns ",(", " sv string cols t),"; expected ",", " sv string key jobschema]; - t + t:("S***IBB";enlist ",") 0: f; + / columns 6 and 7 are named by position; a 5-column csv gets them as 0b + t:@[cols t;5 6;:;`agemin`checkfordirectory] xcol t; + if[not all `function`path`match`exclude`age`agemin`checkfordirectory in cols t;'"job csv ",path," has incorrect layout"]; + / rows with a null function or age are skipped + if[any n:null[t`function] or null t`age;.z.m.log[`info][`readjobs;"Null values found in file, skipping line(s) ",", " sv string where n]]; + t where not n } / locate the paths one job matches. Shells out to find because kdb has no native stat, so file @@ -106,32 +97,34 @@ readjobs:{[path] / values reach the shell - they are quoted, but a csv is not a place to accept untrusted input. findmatches:{[j] p:expandenv j`path; - flag:$[j`dirs;"d";"f"]; - agearg:$[`m=j`unit;"-mmin";"-mtime"]; + flag:$[j`checkfordirectory;"d";"f"]; + agearg:$[j`agemin;"-mmin";"-mtime"]; cmd:"find \"",p,"\" -maxdepth 1 -type ",flag," -name \"",(j`match),"\" ",agearg," +",string j`age; if[count j`exclude;cmd,:" ! -name \"",(j`exclude),"\""]; @[system;cmd;{[e] .z.m.log[`error][`findmatches;"find failed: ",e];()}] } -/ one handler per action, dispatched by the csv's `action` column. rm goes through di.os so it -/ picks the right call for a file vs a directory (and honours di.os's dry-run mode); gzip/tar -/ have no di.os equivalent and shell out directly - part of why this module is unix-only. +/ one handler per action, dispatched by the csv's `function` column, named as legacy's rm/zip/tardir. rm goes through +/ di.os (and honours its dry-run mode); zip/tardir have no di.os equivalent and shell out directly - part of why this +/ module is unix-only. / None of these traps its own work: applyjob traps every action per match, so a handler here reads / the same as one an app registers. actions:()!() actions[`rm]:{[f] + / a directory is skipped and logged, as legacy's rm -f fails on one + if[(.z.m.os`isdir)f;'"cannot remove ",f,": Is a directory"]; .z.m.log[`info][`rm;"removing ",f]; - ($[(.z.m.os`isdir)f;.z.m.os`deldir;.z.m.os`del]) f; + (.z.m.os`del) f; } -actions[`gzip]:{[f] - .z.m.log[`info][`gzip;"compressing ",f]; +actions[`zip]:{[f] + .z.m.log[`info][`zip;"compressing ",f]; system "gzip \"",f,"\""; } -actions[`tar]:{[f] - .z.m.log[`info][`tar;"archiving ",f]; +actions[`tardir]:{[f] + .z.m.log[`info][`tardir;"archiving ",f]; system "tar -czf \"",f,".tar.gz\" \"",f,"\" --remove-files"; } @@ -158,9 +151,9 @@ addaction:{[name;handler] requireinit[`addaction]; if[not -11h=type name;'"di.torq.proc.housekeeping: addaction name must be a symbol"]; if[not 100h=type handler;'"di.torq.proc.housekeeping: addaction handler must be a function taking one matched path"]; - / refuse to shadow a built-in: silently swapping rm/gzip/tar out from under a job csv that + / refuse to shadow a built-in: silently swapping rm/zip/tardir out from under a job csv that / already names them is a footgun no caller wants, and a typo'd name should say so loudly - if[name in `rm`gzip`tar; + if[name in `rm`zip`tardir; '"di.torq.proc.housekeeping: cannot redefine the built-in action ",string name]; if[name in key actions; .z.m.log[`warn][`addaction;"replacing already-registered action ",string name]]; @@ -177,12 +170,12 @@ addaction:{[name;handler] / process's housekeeping job for good - and silently, as di.timer only logs that when its debug is / set. A custom handler registered via addaction must not be able to cost every later run. applyjob:{[j] - if[not (j`action) in key actions; - .z.m.log[`error][`applyjob;"unknown action ",(string j`action),"; expected one of ",", " sv string key actions]; + if[not (j`function) in key actions; + .z.m.log[`error][`applyjob;"unknown action ",(string j`function),"; expected one of ",", " sv string key actions]; :()]; m:findmatches j; - .z.m.log[`info][`applyjob;(string j`action)," ",(j`match)," in ",(expandenv j`path),": ",(string count m)," match(es)"]; - {[a;f] @[actions a;f;{[a;f;e] .z.m.log[`error][`applyjob;"action ",(string a)," failed on ",f,": ",e]}[a;f]]}[j`action;] each m; + .z.m.log[`info][`applyjob;(string j`function)," ",(j`match)," in ",(expandenv j`path),": ",(string count m)," match(es)"]; + {[a;f] @[actions a;f;{[a;f;e] .z.m.log[`error][`applyjob;"action ",(string a)," failed on ",f,": ",e]}[a;f]]}[j`function;] each m; } / run every job in the csv once. Called by the timer, by runnow at startup, and by an operator @@ -194,7 +187,7 @@ runjobs:{[] .z.m.log[`info][`runjobs;"housekeeping starting, reading ",.z.m.jobcsv]; jobs:@[readjobs;.z.m.jobcsv;{[e] .z.m.log[`error][`runjobs;"cannot read job csv: ",e];()}]; if[not count jobs;:()]; - {[j] @[applyjob;j;{[j;e] .z.m.log[`error][`runjobs;"job ",(string j`action)," failed: ",e]}[j]]} each jobs; + {[j] @[applyjob;j;{[j;e] .z.m.log[`error][`runjobs;"job ",(string j`function)," failed: ",e]}[j]]} each jobs; .z.m.log[`info][`runjobs;"housekeeping complete, ran ",(string count jobs)," job(s)"]; } @@ -227,8 +220,7 @@ init:{[config;deps] / tier). Tests assert both halves, because a silently disagreeing pair is how legacy TorQ shipped / runtimes:02:00:00 in settings and a dead 12:00 in code - with its -hkusage text quoting 12:00. .z.m.runtimes:$[`runtimes in key config;astimespans config`runtimes;enlist 0D02:00:00]; - / di.os for the rm action - it picks file vs directory, and its dry-run mode is what lets the - / tests assert on a destructive action without destroying anything + / di.os for the rm action - its dry-run mode is what lets the tests assert on a destructive action without destroying anything .z.m.os:use`di.os; / publish the IPC-callable surface at a real root-level name - use-loading this file compiles / it into a private namespace (see di.torq.proc.hdb.init's identical note), so a remote or diff --git a/di/torq/proc/housekeeping/test.csv b/di/torq/proc/housekeeping/test.csv index 712b698a9..2ec80bb43 100644 --- a/di/torq/proc/housekeeping/test.csv +++ b/di/torq/proc/housekeeping/test.csv @@ -50,15 +50,15 @@ true,0,0,q,`recent.log in survivors[],1,,a matching file newer than the age thre true,0,0,q,`excluded.log in survivors[],1,,a matching old file named in exclude was left alone run,0,0,q,resetcalls[],1,,reset call log -run,0,0,q,writegzipcsv[],1,,switch the csv to a gzip job -run,0,0,q,.housekeeping.runjobs[],1,,run the gzip action +run,0,0,q,writegzipcsv[],1,,switch the csv to a zip job +run,0,0,q,.housekeeping.runjobs[],1,,run the zip action true,0,0,q,`old1.log.gz in gzfiles[],1,,gzip produced a .gz for the first matching old file true,0,0,q,`old2.log.gz in gzfiles[],1,,gzip produced a .gz for the second one too true,0,0,q,not `old1.log in gzfiles[],1,,gzip consumed the original rather than leaving both copies run,0,0,q,resetcalls[],1,,reset call log -run,0,0,q,writetarcsv[],1,,switch the csv to a tar job matching directories not files -run,0,0,q,.housekeeping.runjobs[],1,,run the tar action +run,0,0,q,writetarcsv[],1,,switch the csv to a tardir job matching directories not files +run,0,0,q,.housekeeping.runjobs[],1,,run the tardir action true,0,0,q,`olddir.tar.gz in archfiles[],1,,tar archived the matched directory true,0,0,q,not `olddir in archfiles[],1,,tar --remove-files deleted the original directory - the most destructive thing this module does @@ -68,11 +68,26 @@ run,0,0,q,.housekeeping.runjobs[],1,,run the minutes-based job - exercises find' true,0,0,q,not `stale.log in minfiles[],1,,a file older than the 2 minute threshold was removed true,0,0,q,`justnow.log in minfiles[],1,,a file newer than the 2 minute threshold was left alone -true,0,0,q,`rm`gzip`tar~(hk`actionnames)[],1,,the built-in action set before any app registers anything +comment,,,,,,,legacy csv layouts (housekeeping.q:44-51) and rm on a directory +run,0,0,q,writefivecsv[],1,,switch to TorQ's own 5-column csv +run,0,0,q,.housekeeping.runjobs[],1,,run it +true,0,0,q,"not `old.log in dirfiles""five""",1,,a 5-column csv runs: agemin and checkfordirectory default to false +run,0,0,q,resetcalls[],1,,clear the log capture +run,0,0,q,writenullcsv[],1,,a csv whose first row has a null age +run,0,0,q,.housekeeping.runjobs[],1,,run it +true,0,0,q,"0 Date: Tue, 20 Oct 2026 17:29:09 +0100 Subject: [PATCH 20/39] di.torq.servers: addh, refreshattributes, gethpbytype, root gethandlebytype and the addprocscustom hook, as TorQ's trackservers Ports trackservers.q:130-134 (addh), :255-258 (refreshattributes), :97-107 (getserverbytype, gethpbytype, and root .servers.gethandlebytype, which reopens dead handles first, unlike the module export), and the addprocs hook .servers.addprocscustom (:244-247), kept if already defined. serverselect.md is included for the note that its getserverbytype and gethpbytype share these names but read its own server pool. Co-Authored-By: Claude Opus 5.5 --- di/serverselect/serverselect.md | 3 +++ di/torq/servers/servers.md | 27 ++++++++++++++++++++------- di/torq/servers/servers.q | 31 +++++++++++++++++++++++++++++-- di/torq/servers/test.csv | 10 ++++++++++ di/torq/servers/test.q | 27 ++++++++++++++++++++++++++- 5 files changed, 88 insertions(+), 10 deletions(-) diff --git a/di/serverselect/serverselect.md b/di/serverselect/serverselect.md index dd3ace3ad..aaf0b2b96 100644 --- a/di/serverselect/serverselect.md +++ b/di/serverselect/serverselect.md @@ -102,6 +102,9 @@ srvsel.addserversfromtable[`rdb`hdb; .servers.SERVERS] | `gethandlebytype[ptype;sel]` | Convenience projection of `getserverbytype` returning `handle` | | `gethpbytype[ptype;sel]` | Convenience projection of `getserverbytype` returning `hpup` | +These share their names with di.torq.servers' root `.servers.getserverbytype`/`.servers.gethpbytype` (TorQ's +`trackservers.q`), but read a different registry: this module's server pool, not `.servers.SERVERS`. + `getservers` returns a table including an `attribmatch` column — a dictionary of `attrname!(complete_match_bool;matched_values)` per attribute key in `req`. When `lookups` is not `` ` ``, `nameortype` must be `` `servertype `` or `` `procname ``; any other value throws (and logs) a `di.serverselect:` error rather than silently falling through to a `procname` lookup. All `di.serverselect:` error conditions — including the input-type checks on `addserverfull`/`setserveractive` and the connection-table column check on `addserversfromtable` — are logged via `.z.m.logerr` before being signalled. diff --git a/di/torq/servers/servers.md b/di/torq/servers/servers.md index 15bc38001..e0a12512f 100644 --- a/di/torq/servers/servers.md +++ b/di/torq/servers/servers.md @@ -87,6 +87,7 @@ Published at root by `init`, same bodies as legacy: | `.servers.cleanup` | l.116–118 | | `.servers.addnthawc` | l.121–128 | | `.servers.getdetails` | l.137 | +| `.servers.addh` | l.130–134 | | `.servers.addhw` / `.servers.addw` | l.139–150 | | `.servers.retry` | l.157 | | `.servers.retrydiscovery` | l.158–168 | @@ -96,8 +97,10 @@ Published at root by `init`, same bodies as legacy: | `.servers.register` | l.207–211 | | `.servers.querydiscovery` | l.215–221 | | `.servers.registerfromdiscovery` | l.225–231 | -| `.servers.addprocs` | l.233–244 | +| `.servers.addprocs` | l.233–244 (calls `.servers.addprocscustom`) | | `.servers.procupdate` | l.251 | +| `.servers.refreshattributes` | l.255–258 | +| `.servers.getserverbytype` / `.servers.gethandlebytype` / `.servers.gethpbytype` | l.97–107, over `SERVERS` | | `.servers.domainsocketsenabled` | l.261–267 | | `.servers.formathp` | l.271–307 | | `.servers.formatprocs` | l.310–314 | @@ -107,9 +110,17 @@ Published at root by `init`, same bodies as legacy: Also defined at root, for di.subscriptions' `.sub` and the tickerplants' startup waits: - `.servers.getservers` (5-arg; the exported 1-arg `getservers` is separate); -- `.servers.connectcustom` (called by `retryrows`); +- `.servers.connectcustom` (called by `retryrows`) and `.servers.addprocscustom` (called by `addprocs`), each kept if + already defined, as legacy; - `.servers.startupdepnamecycles`, `.servers.startupdepcycles` and `.servers.startupdependent`. +The root `.servers.gethandlebytype` is legacy's `getserverbytype[;`w;]`: it reopens dead handles first +(`getservers[…;1b;1b]`). The exported `gethandlebytype` does not; it picks only from live rows. + +`.servers.getserverbytype`/`.servers.gethpbytype` share their names with di.serverselect's +`getserverbytype`/`gethpbytype`, but read a different registry: these pick from `.servers.SERVERS` (this +process's connections, by proctype), di.serverselect's from its own server pool (filled by `addserver*`). + They are built on the module-private `attributematch`, `reqprocsnotconn`, `reqproctypesnotconn`, `reqprocnamesnotconn` and `startupdepcyclestypename`. @@ -134,10 +145,10 @@ peers. Peers call discovery's root `register` (as `` `..register ``) and `getser - passwords (`loadpassword`, `USERPASS`, `PASSWORDS`, `LOADPASSWORD`); - `SOCKETTYPE`/FinSpace (so `formathp`'s ipctype is always `` `tcp `` from `formatprocs`/`addhw`, and `retryrows` dials `hpup`); -- `getserverbytype`/`gethpbytype`; -- `names`/`types`/`unregistered`/`checkw`/`reset`; -- the `addprocscustom` hook; -- `refreshattributes`. +- `names`/`types`/`unregistered`/`checkw`/`reset`. + +**Residual:** `.servers.startup` is config-driven (`startup[config]`), so legacy's `.servers.startup[]` throws +`'type`. Accepting an empty call would silently connect to nothing; no port code calls it that way. **Legacy behaviour that differs from di.torq.servers 0.3.0:** - `startup` no longer excludes this process's own row. @@ -150,10 +161,12 @@ peers. Peers call discovery's root `register` (as `` `..register ``) and `getser ## Tests -`test.q` + `test.csv` (63 checks) spawn real q peers. They cover: +`test.q` + `test.csv` (71 checks) spawn real q peers. They cover: - init validation, wiring and idempotency; - `startup` against a live and a dead peer (discovery off); - `gethandlebytype`, and retry recovering an ungraceful kill; +- `.servers.gethpbytype` (live, dead and unknown-selection) and the root `.servers.gethandlebytype`, `.servers.addh`, the `.servers.addprocscustom` hook called by `addprocs`, and `.servers.refreshattributes` + re-registering with a live discovery stub; - `waitfortype`, including a discovery stub that comes up after `startup`; - `attributematch`, the root 5-arg `.servers.getservers`, `.servers.startupdepnamecycles`, `.servers.startupdepcycles` and `.servers.startupdependent`; diff --git a/di/torq/servers/servers.q b/di/torq/servers/servers.q index 496a6befa..3021a85ef 100644 --- a/di/torq/servers/servers.q +++ b/di/torq/servers/servers.q @@ -73,7 +73,8 @@ init:{[deps] set[`.dotz.liveh;{x in key .z.W}]; set[`.dotz.livehn;{x in 0Ni,key .z.W}]; set[`.dotz.liveh0;{x in 0i,key .z.W}]; - pub:`opencon`cleanup`addnthawc`getdetails`addhw`addw`retry`retrydiscovery`autodiscovery`retryrows`removerows`register`querydiscovery`registerfromdiscovery`addprocs`procupdate`domainsocketsenabled`formathp`formatprocs`startup`pc!(opencon;cleanup;addnthawc;getdetails;addhw;addw;retry;retrydiscovery;autodiscovery;retryrows;removerows;register;querydiscovery;registerfromdiscovery;addprocs;procupdate;domainsocketsenabled;formathp;formatprocs;startup;pc); + pub:`opencon`cleanup`addnthawc`getdetails`addhw`addw`addh`retry`retrydiscovery`autodiscovery`retryrows`removerows`register`querydiscovery`registerfromdiscovery`addprocs`procupdate`refreshattributes`getserverbytype`gethandlebytype`gethpbytype`domainsocketsenabled`formathp`formatprocs`startup`pc!(opencon;cleanup;addnthawc;getdetails;addhw;addw;addh;retry;retrydiscovery;autodiscovery;retryrows;removerows;register;querydiscovery;registerfromdiscovery;addprocs;procupdate;refreshattributes;getserverbytype;getserverbytype[;`w;];gethpbytype;domainsocketsenabled;formathp;formatprocs;startup;pc); + / root .servers.gethandlebytype is legacy's getserverbytype[;`w;] (reopens dead handles), not the export set'[` sv/:`.servers,/:key pub;value pub]; if[not .z.m.registered; / .z.pc @@ -134,6 +135,13 @@ addhw:{[hpuP;W] addw:addhw[`] +/ open a connection to a server and store its details, as trackservers.q:130-134 +addh:{[hpuP] + W:opencon hpuP; + $[null W; + '"failed to open handle to ",string hpuP; + addhw[hpuP;W]]} + / after getting new servers run retry to open connections retry:{retryrows exec i from `.servers.SERVERS where not .dotz.liveh0 w,not proctype=`discovery} @@ -196,11 +204,18 @@ addprocs:{[connectiontab;procs;connect] if[`attributes in cols connectiontab; .servers.SERVERS:.servers.SERVERS lj 3!select procname,proctype,hpup,attributes from connectiontab where not ([]procname;proctype;hpup) in select procname,proctype,hpup from .servers.SERVERS]]; removerows exec i from `.servers.SERVERS where hpup in exec hpup from res; - register[res;;connect] each $[procs~`ALL;exec distinct proctype from res;procs,()];} + register[res;;connect] each $[procs~`ALL;exec distinct proctype from res;procs,()]; + .servers.addprocscustom[res;procs]} / used to handle updates from the discovery service procupdate:{[procs] addprocs[procs;exec distinct proctype from procs;0b];} +/ re-register this process's attributes with each discovery service, as trackservers.q:255-258 +refreshattributes:{ + retrydiscovery[]; + (neg exec w from .servers.getservers[`proctype;`discovery;()!();0b;0b])@\:(`..register;`); + } + / return true if unix domain sockets can be used domainsocketsenabled:{[] notwin:not .z.o like "w*"; @@ -297,6 +312,16 @@ gethandlebytype:{[pt;selection] wh }; +/ one server value for a proctype from SERVERS, reopening dead handles first, as trackservers.q:97-107 +getserverbytype:{[ptype;serverval;selection] + r:.servers.getservers[`proctype;ptype;()!();1b;1b]; + if[count r; + r:selector[r;selection]; + updatestats[r`w]]; + r[serverval]} + +gethpbytype:getserverbytype[;`hpup;] + signalfound:{[pt] / internal - log and return 1b once a connection to pt exists. .z.m.loginfo[`servers;"connected to ",string pt]; @@ -353,6 +378,8 @@ attributematch:{[req;avail] / root, for .sub: run on (re)connected SERVERS rows .servers.connectcustom:@[value;`.servers.connectcustom;{[connectedrows]}]; +/ addprocs' hook for bespoke extensions when adding processes, as trackservers.q:246-247 +.servers.addprocscustom:@[value;`.servers.addprocscustom;{{[connectiontab;procs]}}]; / are any required processes not connected reqprocsnotconn:{[requiredprocs;typeorname] diff --git a/di/torq/servers/test.csv b/di/torq/servers/test.csv index fa775413b..886ac08e7 100644 --- a/di/torq/servers/test.csv +++ b/di/torq/servers/test.csv @@ -30,6 +30,11 @@ true,0,0,q,"warnlogged[""failed to open connection""]",1,1,the failed dial was l comment,,,,,,,gethandlebytype - a genuinely live remote handle run,0,0,q,h:svc.gethandlebytype[`otherproc;`any],1,1,get a handle to the peer true,0,0,q,"2=h ""1+1""",1,1,the handle is a live remote connection to a separate process +comment,,,,,,,root .servers.gethpbytype over SERVERS (trackservers.q:97-107) +true,0,0,q,".servers.gethpbytype[`otherproc;`any]~first exec hpup from .servers.SERVERS where proctype=`otherproc",1,1,gethpbytype returns the live otherproc row's hpup +true,0,0,q,"(`symbol$())~.servers.gethpbytype[`deadproc;`any]",1,1,a proctype with no live server gives an empty list after the reopen attempt (as legacy r[serverval]) +fail,0,0,q,".servers.gethpbytype[`otherproc;`nosuch]",1,1,an unknown selection signals +true,0,0,q,".servers.gethandlebytype[`otherproc;`any]~first exec w from .servers.SERVERS where proctype=`otherproc",1,1,root gethandlebytype (legacy getserverbytype[;`w;]) returns the live otherproc handle comment,,,,,,,cleanup + retry recover an ungraceful kill run,0,0,q,killpeer[],1,1,kill the peer ungracefully (handlers are mocked so no auto .z.pc fires) run,0,0,q,"@[{h ""1+1""};();{[e]e}]",1,1,touch the dead handle so kdb+ drops it from .z.W (protected - expected to error) @@ -40,6 +45,10 @@ run,0,0,q,".servers.connectcustom:{[r] `ccrows set r}",1,1,record what retryrows run,0,0,q,firejob[`serversretry],1,1,fire retry again - should reconnect now a peer is listening true,0,0,q,1=count svc.getservers[`otherproc],1,1,retry reconnected to otherproc true,0,0,q,(enlist`otherinst)~exec procname from ccrows,1,1,retryrows passed the reconnected row to .servers.connectcustom +comment,,,,,,,addh and the addprocscustom hook (trackservers.q:130-134; 244-247) +true,0,0,q,addhpeer[],1,1,addh opens a working handle to the peer and stores it in SERVERS +fail,0,0,q,".servers.addh `$"":localhost:"",string DEADPORT",1,1,addh signals when nothing is listening +true,0,0,q,addprocshook[],1,1,addprocs calls .servers.addprocscustom with the rows it added and the procs comment,,,,,,,waitfortype - connected vs timeout true,0,0,q,svc.waitfortype[`otherproc;2000;200],1,1,returns 1b immediately for an already-connected proctype true,0,0,q,0b~svc.waitfortype[`deadproc;700;200],1,1,returns 0b on timeout for a proctype that never comes up @@ -63,6 +72,7 @@ run,0,0,q,svc.startup[svrdeps[`tpproc]],1,1,startup while discovery is down - th true,0,0,q,0=count svc.getservers[`discovery],1,1,discovery is not live after startup run,0,0,q,spawndisc[],1,1,bring up the tpproc peer then discovery true,0,0,q,svc.waitfortype[`tpproc;3000;200],1,1,waitfortype reaches discovery and connects to the tpproc it names +true,0,0,q,refreshregisters[],1,1,refreshattributes sends one register to each live discovery service (trackservers.q:255-258) comment,,,,,,,retry periods from toml run,0,0,q,"svc.init[svrdeps[`otherproc],`retry`discoveryretry!(""0D00:00:10"";10)]",1,1,retry as a string and discoveryretry as seconds true,0,0,q,"(0D00:00:10;0D00:00:10)~(.servers.RETRY;.servers.DISCOVERYRETRY)",1,1,both become timespans diff --git a/di/torq/servers/test.q b/di/torq/servers/test.q index c10dc3c33..2b74f09ed 100644 --- a/di/torq/servers/test.q +++ b/di/torq/servers/test.q @@ -77,7 +77,7 @@ setupdisc:{[] TPPORT::pickport DISCPORT+1; (`$":",FIXDIR,"/process.csv") 0: (read0 `$":",FIXDIR,"/process.csv"),enlist "localhost,",string[DISCPORT],",discovery,discinst"; (`$":",FIXDIR,"/disc.q") 0: ( - "register:{}"; + "REGN:0;register:{[x] `REGN set REGN+1}"; "getservices:{[p;s] ([]procname:enlist`tpinst;proctype:enlist`tpproc;hpup:enlist`$\":localhost:",string[TPPORT],"\";attributes:enlist()!())}"); }; @@ -91,6 +91,31 @@ spawnq:{[args;port] spawndisc:{[] spawnq["";TPPORT]; spawnq[FIXDIR,"/disc.q";DISCPORT];}; killdisc:{[] {@[system;"kill ",string x;{}]} each DISCPIDS; DISCPIDS::`long$();}; +/ addh to the live peer: the handle it returns works and is stored in SERVERS; the row is removed after +addhpeer:{[] + W:.servers.addh `$":localhost:",string PEERPORT; + r:(2=W"1+1";1=count select from .servers.SERVERS where w=W); + delete from `.servers.SERVERS where w=W; hclose W; + all r}; + +/ addprocs calls .servers.addprocscustom with the new rows and the procs; the hook and row are reset after +addprocshook:{[] + / bind the .z.pc that addprocs' removerows calls, as setupdisc does; a fresh dead port so no fixture row is replaced + .z.pc:{}; + `APC set (); + .servers.addprocscustom:{[t;p] `APC set (exec procname from t;p)}; + .servers.addprocs[([]procname:enlist`newinst;proctype:enlist`newproc;hpup:enlist`$":localhost:",string pickport DEADPORT+1);enlist`newproc;0b]; + .servers.addprocscustom:{[connectiontab;procs]}; + delete from `.servers.SERVERS where procname=`newinst; + (enlist`newinst;enlist`newproc)~APC}; + +/ refreshattributes sends one register to each live discovery service +refreshregisters:{[] + h:first exec w from .servers.getservers[`proctype;`discovery;()!();0b;0b]; + b:h"REGN"; + .servers.refreshattributes[]; + (b+1)=h"REGN"}; + / build the deps dict di.torq would assemble: injectables + this process's config slice. / discovery off, so startup dials process.csv directly (trackservers.q's own defaults are 1b). svrdeps:{[conns] `log`timer`handlers`proctype`procname`connections`processcsv`discoveryregister`connectionsfromdiscovery!(mocklog;mocktimer;mockhandlers;`selfproc;`selfinst;conns;FIXDIR,"/process.csv";0b;0b)}; From 3370059abc1cd3b37f2653ea9b165f8f727e6b34 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 20 Oct 2026 17:34:49 +0100 Subject: [PATCH 21/39] di.eodtime: readers for the roll and data timezone and roll offset, as TorQ's .eodtime settings getrolltimezone, getdatatimezone and getrolltimeoffset return the settings init applied, which legacy callers read as .eodtime.rolltimezone, .eodtime.datatimezone and .eodtime.rolltimeoffset (e.g. dataaccessutils.q:11). Co-Authored-By: Claude Opus 5.5 --- di/eodtime/eodtime.md | 9 +++++++++ di/eodtime/eodtime.q | 4 ++++ di/eodtime/init.q | 2 +- di/eodtime/test.csv | 8 ++++++++ 4 files changed, 22 insertions(+), 1 deletion(-) diff --git a/di/eodtime/eodtime.md b/di/eodtime/eodtime.md index ff53355ce..fae4e9017 100644 --- a/di/eodtime/eodtime.md +++ b/di/eodtime/eodtime.md @@ -77,6 +77,15 @@ eodtime.getdailyadj[] / 0D01:00:00.000000000 ``` +### `getrolltimezone[]` / `getdatatimezone[]` / `getrolltimeoffset[]` +Return the settings `init` applied: the roll timezone, the data timezone and the roll offset. Legacy callers read +these as `.eodtime.rolltimezone`, `.eodtime.datatimezone` and `.eodtime.rolltimeoffset` (e.g. TorQ's +`dataaccessutils.q:11`, which fills them into its table properties). +```q +eodtime.getrolltimezone[] +/ `Europe/London +``` + ### `getdailyadjustment[]` **Recompute** the UTC offset for the data timezone at the current time. Call after an EOD roll to get a fresh offset - important when the data timezone observes DST. ```q diff --git a/di/eodtime/eodtime.q b/di/eodtime/eodtime.q index 3161ba161..f7f31f8fc 100644 --- a/di/eodtime/eodtime.q +++ b/di/eodtime/eodtime.q @@ -68,6 +68,10 @@ getroll:{[p] getd:{d}; getnextroll:{nextroll}; getdailyadj:{dailyadj}; +/ the settings, as legacy's .eodtime.rolltimezone/datatimezone/rolltimeoffset (read by dataaccessutils.q:11) +getrolltimezone:{rolltimezone}; +getdatatimezone:{datatimezone}; +getrolltimeoffset:{rolltimeoffset}; / state setters setnextroll:{.z.m.nextroll:x}; diff --git a/di/eodtime/init.q b/di/eodtime/init.q index bb21a7586..d6e2991ca 100644 --- a/di/eodtime/init.q +++ b/di/eodtime/init.q @@ -9,4 +9,4 @@ tz:use`di.tz / (pre-load manifest walk) and this export (post-load session audit of a loaded, declared peer). version:first read0`:::VERSION -export:([init;getd;getnextroll;getdailyadj;getroll;getdailyadjustment;setnextroll;setdailyadj;setd;version]) +export:([init;getd;getnextroll;getdailyadj;getrolltimezone;getdatatimezone;getrolltimeoffset;getroll;getdailyadjustment;setnextroll;setdailyadj;setd;version]) diff --git a/di/eodtime/test.csv b/di/eodtime/test.csv index 1f14fc9d1..94b39d3e8 100644 --- a/di/eodtime/test.csv +++ b/di/eodtime/test.csv @@ -89,6 +89,14 @@ comment,,,,,,,init - accepts any dict already shaped to the binary {[c;m]} contr run,0,0,q,sixlvllog:`trace`debug`info`warn`error`fatal!({[c;m]};{[c;m]};{[c;m]};{[c;m]};{[c;m]};{[c;m]}),1,1,hand-built six-level dict matching di.util.log's logdict shape run,0,0,q,eodtime.init[`log`rolltimezone!(sixlvllog;`$"GMT")],1,1,superset log dict accepted as-is - only info/warn/error are used +comment,,,,,,,settings readers (legacy .eodtime.rolltimezone/datatimezone/rolltimeoffset) +run,0,0,q,"eodtime.init[`log`rolltimezone`datatimezone`rolltimeoffset!(logdep;`$""Europe/London"";`$""America/New_York"";0D17:00:00.000)]",1,1,init with non-default settings +true,0,0,q,"(`$""Europe/London"")~eodtime.getrolltimezone[]",1,1,getrolltimezone returns the roll timezone init applied +true,0,0,q,"(`$""America/New_York"")~eodtime.getdatatimezone[]",1,1,getdatatimezone returns the data timezone init applied +true,0,0,q,0D17:00:00.000~eodtime.getrolltimeoffset[],1,1,getrolltimeoffset returns the roll offset init applied +run,0,0,q,eodtime.init[enlist[`log]!enlist logdep],1,1,init with defaults only +true,0,0,q,"((`$""GMT"");(`$""GMT"");0D)~(eodtime.getrolltimezone[];eodtime.getdatatimezone[];eodtime.getrolltimeoffset[])",1,1,the readers give legacy's defaults (GMT; GMT; 0D) + comment,,,,,,,log call verification - capturing logger sees init message with binary {[c;m]} args run,0,0,q,caplog:`info`warn`error!({[c;m] `.test.cap upsert(`info;m)};{[c;m] `.test.cap upsert(`warn;m)};{[c;m] `.test.cap upsert(`error;m)}),1,1,capturing log mock - binary {[c;m]} run,0,0,q,.test.cap:([] fn:`symbol$();msg:()),1,1,initialise log capture table From f97837ac2d84e0c4f3284e322c69ecde04e479d3 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 20 Oct 2026 17:42:12 +0100 Subject: [PATCH 22/39] di.torq.config: getconfig and getconfigfile over the two roots, as TorQ's .proc.getconfig getconfig[builtinroot;approot;path;level] returns the config file(s) for a path, app before builtin, at TorQ's levels 0/1/2 (torq.q:149-174); getconfigfile is level 0. Pure: the roots are arguments, as cascade. Legacy's $KDBSERVCONFIG tier has no port equivalent and is not searched. Co-Authored-By: Claude Opus 5.5 --- di/torq/config/config.md | 2 ++ di/torq/config/config.q | 15 +++++++++++++++ di/torq/config/init.q | 2 +- di/torq/config/test.csv | 10 ++++++++++ 4 files changed, 28 insertions(+), 1 deletion(-) diff --git a/di/torq/config/config.md b/di/torq/config/config.md index 3ee5a4121..87cde4e95 100644 --- a/di/torq/config/config.md +++ b/di/torq/config/config.md @@ -102,6 +102,8 @@ first — di.torq.config does no wrapping. | Function | Signature | Description | |---|---|---| | `cascade` | `cascade[builtinroot;approot;proctype;procname]` | Resolve the settings cascade over the two roots × the `default`/`{proctype}`/`{procname}` name sequence and **return one flat dict**. Pure — no `init`, no logger, no globals. Precedence is name-major with `.toml > .q` within a tier (see above). A key set nowhere is simply absent; an all-missing cascade returns an empty dict. | +| `getconfig` | `getconfig[builtinroot;approot;path;level]` | The config file(s) for `path` (relative to a root), as TorQ's `.proc.getconfig`. App before builtin. Level `0`: the first that exists, else the builtin path; `1`: the app path if it exists, then the builtin path; `2`: both, whether or not they exist. An empty `approot` is an unset app root. Returns a symbol list, as legacy. Pure: the roots are arguments, nothing is read from the environment. TorQ's middle `$KDBSERVCONFIG` tier has no port equivalent (two roots), so it is not searched. | +| `getconfigfile` | `getconfigfile[builtinroot;approot;path]` | `getconfig` at level 0, as TorQ's `.proc.getconfigfile`. | | `parsefile` | `parsefile[path]` | Parse a single settings file into a flat dict. A `.toml` path is delegated to `di.util.toml` (loaded lazily, behind the guard rail below); a `.q` path is flat `name:value` lines. A missing file (either extension) → empty dict. An existing `.toml` file with no `di.util.toml` on `QPATH` signals a clear error naming the file. Pure. | | `overrideconfig` | `overrideconfig[config;params]` | Apply the **command-line override layer** on top of a resolved config dict — the top tier of the cascade. `di.torq` parses the process command line (`.Q.opt .z.x`) and calls this after `cascade`, so launch-time flags (e.g. `-loglevel info`, `-rows 5000`) win over the settings files. `config` is the dict from `cascade`; `params` is a dict keyed by setting name (symbol) with string (or list-of-string) values, each parsed into that setting's **existing** type. Only keys already present with a basic type are overridden; unknown keys, non-basic types, unparseable values, and multi-value overrides of a single-valued (scalar/string) setting are logged and skipped. A vector setting (e.g. a symbol list) accepts multiple values. A `.section.key` (or `section.key`) name overrides that key of a dict-valued section, e.g. `-.clients.opencloseonly 0`, under the same rules; the key must already be in the section. Returns the **updated config dict**. Requires `init`. | | `init` | `init[deps]` | Wire the injected logger for `overrideconfig`. `deps` is a dict with a required `log` key — an already-conforming binary `` `info`warn`error `` dict of `{[c;m]}` functions. Errors immediately if the log dependency is missing or malformed. | diff --git a/di/torq/config/config.q b/di/torq/config/config.q index 89c7569b5..6c0112854 100644 --- a/di/torq/config/config.q +++ b/di/torq/config/config.q @@ -84,6 +84,19 @@ cascade:{[builtinroot;approot;proctype;procname] acc _ ` }; +/ the config file(s) for a path relative to the two roots, app before builtin, as TorQ's .proc.getconfig (torq.q:149-172): +/ level 0 the first existing (else the builtin path), 1 each existing app path then the builtin path, 2 both regardless. +/ an empty approot is an unset app root, as an unset $KDBAPPCONFIG. pure: no env read. +getconfig:{[builtinroot;approot;path;level] + appconf:$[count approot;`$approot,"/",path;()]; + if[(level<2) and $[count appconf;()~key hsym appconf;0b];appconf:()]; + conf:`$builtinroot,"/",path; + (),$[level;appconf,conf;first appconf,conf] + }; + +/ the first config file for a path, as TorQ's .proc.getconfigfile (torq.q:174) +getconfigfile:getconfig[;;;0]; + / --- command-line override layer (top of the cascade) --- hexchars:"0123456789abcdefABCDEF"; @@ -183,6 +196,8 @@ getapimeta:{[] (`init; 0b; "wire the injected logger (required by overrideconfig)"; "[dict: deps with a `log key]"; "null"); (`cascade; 1b; "resolve the settings cascade over two roots -> merged flat dict (name-major, .toml>.q)"; "[string: builtinroot; string: approot; symbol: proctype; symbol: procname]"; "dict: merged setting -> value"); (`overrideconfig; 1b; "apply the command-line override layer onto a resolved config dict"; "[dict: resolved config; dict: setting name (symbol) -> string or list of strings]"; "dict: updated config"); + (`getconfig; 1b; "the config file(s) for a path over the two roots, app before builtin (TorQ .proc.getconfig)"; "[string: builtinroot; string: approot (empty if unset); string: path; long: level 0/1/2]"; "symbol list: config file path(s)"); + (`getconfigfile; 1b; "the first config file for a path over the two roots (TorQ .proc.getconfigfile)"; "[string: builtinroot; string: approot; string: path]"; "symbol list: one config file path"); (`parsefile; 1b; "parse one .q or .toml settings file into a flat dict"; "[string: file path (.q flat name:value, or .toml via di.util.toml)]"; "dict: setting -> value (empty if the file is missing)"); (`getapimeta; 0b; "this module's api metadata rows"; "[]"; "table: metadata rows")); }; diff --git a/di/torq/config/init.q b/di/torq/config/init.q index 2e06d0141..81c1054ff 100644 --- a/di/torq/config/init.q +++ b/di/torq/config/init.q @@ -1,3 +1,3 @@ / configuration loading and cascade resolution for the modular torq world. \l ::config.q -export:([init;cascade;overrideconfig;parsefile;getapimeta]) +export:([init;cascade;getconfig;getconfigfile;overrideconfig;parsefile;getapimeta]) diff --git a/di/torq/config/test.csv b/di/torq/config/test.csv index c1bb5a1be..2018c43b5 100644 --- a/di/torq/config/test.csv +++ b/di/torq/config/test.csv @@ -68,6 +68,16 @@ true,0,0,q,"""new""~(cfg.overrideconfig[seccfg;enlist[`.replay.dir]!enlist ""new true,0,0,q,"7~(cfg.overrideconfig[seccfg;enlist[`replay.first]!enlist enlist""7""])[`replay;`first]",1,1,section.key (no leading dot) works and parses into the key's type true,0,0,q,"`xx`yy~(cfg.overrideconfig[seccfg;enlist[`.replay.tabs]!enlist (""xx"";""yy"")])[`replay;`tabs]",1,1,a vector key of a section takes several values true,0,0,q,"seccfg~cfg.overrideconfig[seccfg;`.replay.nope`.rows.x`.replay.a.b!3#enlist enlist""1""]",1,1,an unknown section key or a non-dict section or a deeper name is skipped +comment,,,,,,,getconfig / getconfigfile - TorQ's .proc.getconfig levels over the two roots (app before builtin) +run,0,0,q,"(hsym each `$TD,/:(""app/proc.csv"";""builtin/proc.csv"";""builtin/only.csv"")) 0:\: enlist ""a,b""",1,1,proc.csv in both roots; only.csv in builtin only +true,0,0,q,"(enlist`$TD,""app/proc.csv"")~cfg.getconfig[TD,""builtin"";TD,""app"";""proc.csv"";0]",1,1,level 0: the app file when it exists +true,0,0,q,"(enlist`$TD,""builtin/only.csv"")~cfg.getconfig[TD,""builtin"";TD,""app"";""only.csv"";0]",1,1,level 0: the builtin file when the app one is missing +true,0,0,q,"(enlist`$TD,""builtin/none.csv"")~cfg.getconfig[TD,""builtin"";TD,""app"";""none.csv"";0]",1,1,level 0: the builtin path even when neither exists (as legacy) +true,0,0,q,"(enlist`$TD,""builtin/proc.csv"")~cfg.getconfig[TD,""builtin"";"""";""proc.csv"";0]",1,1,level 0: an empty approot is an unset app root +true,0,0,q,"(`$TD,/:(""app/proc.csv"";""builtin/proc.csv""))~cfg.getconfig[TD,""builtin"";TD,""app"";""proc.csv"";1]",1,1,level 1: the existing app file then the builtin file +true,0,0,q,"(enlist`$TD,""builtin/only.csv"")~cfg.getconfig[TD,""builtin"";TD,""app"";""only.csv"";1]",1,1,level 1: a missing app file is left out +true,0,0,q,"(`$TD,/:(""app/only.csv"";""builtin/only.csv""))~cfg.getconfig[TD,""builtin"";TD,""app"";""only.csv"";2]",1,1,level 2: both paths whether or not they exist +true,0,0,q,"cfg.getconfig[TD,""builtin"";TD,""app"";""proc.csv"";0]~cfg.getconfigfile[TD,""builtin"";TD,""app"";""proc.csv""]",1,1,getconfigfile is getconfig at level 0 comment,,,,,,,getapimeta - module api metadata true,0,0,q,(asc key cfg)~asc exec name from cfg.getapimeta[],1,1,getapimeta documents exactly the module's exports true,0,0,q,`name`public`descrip`params`return~cols cfg.getapimeta[],1,1,getapimeta rows carry the registry columns From 84bad6e124f9cfd2560bcc54de7ee0db976f6f08 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 20 Oct 2026 17:54:31 +0100 Subject: [PATCH 23/39] di.torq, di.torq.config: -parentproctype tier for settings and app code, as TorQ's torq.q di.torq reads -parentproctype (torq.q:376-380) as a reserved flag and stamps it into config as a symbol atom. cascade takes it before proctype, so its settings tier sits between default and proctype (torq.q:593), and loadappcode loads code// between common and the proctype, gated by loadprocesscode (torq.q:643). One commit for both modules, since cascade's new argument would otherwise break di.torq's call. Co-Authored-By: Claude Opus 5.5 --- di/torq/config/config.md | 13 +++++++------ di/torq/config/config.q | 13 +++++++------ di/torq/config/test.csv | 27 ++++++++++++++++----------- di/torq/test.csv | 6 +++++- di/torq/test.q | 18 ++++++++++++++++++ di/torq/torq.md | 11 ++++++++--- di/torq/torq.q | 13 ++++++++----- 7 files changed, 69 insertions(+), 32 deletions(-) diff --git a/di/torq/config/config.md b/di/torq/config/config.md index 87cde4e95..ed9d5e298 100644 --- a/di/torq/config/config.md +++ b/di/torq/config/config.md @@ -14,7 +14,7 @@ files into namespaces or hold any global store. This is the shape `di.torq` cons ```q config:use`di.torq.config -cfg:config.cascade[builtinroot;approot;`rdb;`rdb1] / -> `subscribeto`rows`... !(...) +cfg:config.cascade[builtinroot;approot;`;`rdb;`rdb1] / -> `subscribeto`rows`... !(...); ` = no parentproctype / di.torq stamps identity and hands the whole dict to each module's init: cfg:cfg,`proctype`procname!(`rdb;`rdb1) rdb.init[cfg;`log`timer!(logdep;timerdep)] @@ -27,8 +27,9 @@ requires `init`. ## Precedence -The cascade is resolved over **two roots** (`builtinroot`, `approot`) × a **three-tier -name sequence** (`default` → `{proctype}` → `{procname}`). Precedence is **name-major**: +The cascade is resolved over **two roots** (`builtinroot`, `approot`) × a **name sequence** +(`default` → `{parentproctype}` → `{proctype}` → `{procname}`, as TorQ's `torq.q:593`; the +`{parentproctype}` tier only when one is given, a null symbol meaning none). Precedence is **name-major**: 1. A more specific **name** always wins — `{procname}` beats `{proctype}` beats `default`. 2. **Within a name**, the later (app) root overrides the builtin root. @@ -40,8 +41,8 @@ proctype** value, not the app default (name beats root). Effective load order, l priority: ``` -builtin/default(.q,.toml) → app/default → builtin/{proctype} → app/{proctype} - → builtin/{procname} → app/{procname} (each tier: .toml overrides .q) +builtin/default(.q,.toml) → app/default → [builtin/{parentproctype} → app/{parentproctype}] + → builtin/{proctype} → app/{proctype} → builtin/{procname} → app/{procname} (each tier: .toml overrides .q) ``` `overrideconfig` sits on **top** of all of this — the command-line layer (see below). @@ -101,7 +102,7 @@ first — di.torq.config does no wrapping. | Function | Signature | Description | |---|---|---| -| `cascade` | `cascade[builtinroot;approot;proctype;procname]` | Resolve the settings cascade over the two roots × the `default`/`{proctype}`/`{procname}` name sequence and **return one flat dict**. Pure — no `init`, no logger, no globals. Precedence is name-major with `.toml > .q` within a tier (see above). A key set nowhere is simply absent; an all-missing cascade returns an empty dict. | +| `cascade` | `cascade[builtinroot;approot;parentproctype;proctype;procname]` | Resolve the settings cascade over the two roots × the `default`/`{parentproctype}`/`{proctype}`/`{procname}` name sequence (`parentproctype` a null symbol for none) and **return one flat dict**. Pure — no `init`, no logger, no globals. Precedence is name-major with `.toml > .q` within a tier (see above). A key set nowhere is simply absent; an all-missing cascade returns an empty dict. | | `getconfig` | `getconfig[builtinroot;approot;path;level]` | The config file(s) for `path` (relative to a root), as TorQ's `.proc.getconfig`. App before builtin. Level `0`: the first that exists, else the builtin path; `1`: the app path if it exists, then the builtin path; `2`: both, whether or not they exist. An empty `approot` is an unset app root. Returns a symbol list, as legacy. Pure: the roots are arguments, nothing is read from the environment. TorQ's middle `$KDBSERVCONFIG` tier has no port equivalent (two roots), so it is not searched. | | `getconfigfile` | `getconfigfile[builtinroot;approot;path]` | `getconfig` at level 0, as TorQ's `.proc.getconfigfile`. | | `parsefile` | `parsefile[path]` | Parse a single settings file into a flat dict. A `.toml` path is delegated to `di.util.toml` (loaded lazily, behind the guard rail below); a `.q` path is flat `name:value` lines. A missing file (either extension) → empty dict. An existing `.toml` file with no `di.util.toml` on `QPATH` signals a clear error naming the file. Pure. | diff --git a/di/torq/config/config.q b/di/torq/config/config.q index 6c0112854..b0db366aa 100644 --- a/di/torq/config/config.q +++ b/di/torq/config/config.q @@ -61,8 +61,8 @@ parsetier:{[base] (parsefile base,".q"),parsefile base,".toml" }; -cascade:{[builtinroot;approot;proctype;procname] - / resolve the cascade over the two roots x (default;proctype;procname) and RETURN the merged flat +cascade:{[builtinroot;approot;parentproctype;proctype;procname] + / resolve the cascade over the two roots x (default;parentproctype;proctype;procname) and RETURN the merged flat / dict. pure (no init/logger/globals). name-major: a more specific NAME wins over the root layer, / and within a name the app root wins (parsetier gives .toml>.q within a tier). the accumulator is / seeded with a sentinel (`)!(::) key so its value list stays general from the first merge (a @@ -70,15 +70,16 @@ cascade:{[builtinroot;approot;proctype;procname] / proctype/procname must be non-null symbol atoms: string`` is "", which would build a bogus / "/" base and read a file named ".q"/".toml". a null means identity resolution failed, so / surface it. (a null symbol is still type -11h, so the null check is separate from the type check.) - if[not all -11h=type each (proctype;procname); - '"di.torq.config: cascade requires proctype and procname to be symbol atoms"]; + if[not all -11h=type each (parentproctype;proctype;procname); + '"di.torq.config: cascade requires parentproctype, proctype and procname to be symbol atoms"]; if[(null proctype)|null procname; '"di.torq.config: cascade requires non-null proctype and procname; got ",(-3!proctype)," and ",-3!procname]; dirs:(builtinroot;approot); / dedup (distinct keeps first-occurrence order, preserving least->most-specific). without it a / repeated name re-applies its tier at a LATER slot: procname~proctype is redundant, but / procname~`default would put default LAST and wrongly override proctype. - names:distinct `default,proctype,procname; + / a null parentproctype is none; when set its tier sits between default and proctype, as TorQ's torq.q:593 + names:distinct (`default,parentproctype,proctype,procname) except `; bases:raze {[ds;nm] ds,\:"/",string nm}[dirs;] each names; acc:{[a;b] a,parsetier b}/[(enlist `)!enlist(::);bases]; acc _ ` @@ -194,7 +195,7 @@ getapimeta:{[] / names are bare (di.torq qualifies them). one (name;public;descrip;params;return) row per line. :flip `name`public`descrip`params`return!flip( (`init; 0b; "wire the injected logger (required by overrideconfig)"; "[dict: deps with a `log key]"; "null"); - (`cascade; 1b; "resolve the settings cascade over two roots -> merged flat dict (name-major, .toml>.q)"; "[string: builtinroot; string: approot; symbol: proctype; symbol: procname]"; "dict: merged setting -> value"); + (`cascade; 1b; "resolve the settings cascade over two roots -> merged flat dict (name-major, .toml>.q)"; "[string: builtinroot; string: approot; symbol: parentproctype (` if none); symbol: proctype; symbol: procname]"; "dict: merged setting -> value"); (`overrideconfig; 1b; "apply the command-line override layer onto a resolved config dict"; "[dict: resolved config; dict: setting name (symbol) -> string or list of strings]"; "dict: updated config"); (`getconfig; 1b; "the config file(s) for a path over the two roots, app before builtin (TorQ .proc.getconfig)"; "[string: builtinroot; string: approot (empty if unset); string: path; long: level 0/1/2]"; "symbol list: config file path(s)"); (`getconfigfile; 1b; "the first config file for a path over the two roots (TorQ .proc.getconfigfile)"; "[string: builtinroot; string: approot; string: path]"; "symbol list: one config file path"); diff --git a/di/torq/config/test.csv b/di/torq/config/test.csv index 2018c43b5..8517888cb 100644 --- a/di/torq/config/test.csv +++ b/di/torq/config/test.csv @@ -9,6 +9,7 @@ before,0,0,q,"system ""mkdir -p "",TD,""app""",1,1,app root for the cascade before,0,0,q,"(hsym`$TD,""builtin/default.q"") 0: (""diconfiga:1"";""diconfigb:1"")",1,1,builtin/default flat name:value (two settings) before,0,0,q,"(hsym`$TD,""builtin/rdb.q"") 0: enlist ""diconfigb:10""",1,1,builtin/rdb proctype tier sets diconfigb before,0,0,q,"(hsym`$TD,""app/default.q"") 0: (""diconfiga:100"";""diconfigb:5"")",1,1,app/default flat name:value (two settings) +before,0,0,q,"(hsym`$TD,""app/pptp.q"") 0: (""diconfigb:3"";""diconfigc:7"")",1,1,app/pptp parentproctype tier sets diconfigb and diconfigc before,0,0,q,"(hsym`$TD,""app/rdb1.q"") 0: enlist ""diconfiga:999""",1,1,app/rdb1 procname tier sets diconfiga before,0,0,q,"basecfg:`enabled`rows`syms`tab`byte`str!(0b;100;`a`b;([]a:`long$());0x01;"":olddb"")",1,1,base config dict for the overrideconfig tests (str is a char-string setting, as a .toml value would be) before,0,0,q,"system ""mkdir -p "",TD,""skip""",1,1,dir for the malformed-line skip test @@ -30,17 +31,21 @@ true,0,0,q,"0=count cfg.parsefile[(TD,""nope/absent.toml"")]",1,1,a MISSING .tom true,0,0,q,"1j~(cfg.parsefile[(TD,""toml/present.toml"")])`a",1,1,an EXISTING .toml now parses by delegating to di.util.toml (present on QPATH) true,0,0,q,"-7h=type (cfg.parsefile[(TD,""toml/present.toml"")])`a",1,1,the .toml integer came back a long - di.util.toml's typed parse flows through config.parsefile comment,,,,,,,cascade - merged flat dict over two roots x default/proctype/procname (name-major; .toml>.q within a tier) -true,0,0,q,"100~(cfg.cascade[(TD,""builtin"");(TD,""app"");`rdb;`rdbnofile])`diconfiga",1,1,within a name the later (app) root overrides the builtin root -true,0,0,q,"10~(cfg.cascade[(TD,""builtin"");(TD,""app"");`rdb;`rdbnofile])`diconfigb",1,1,name-major: builtin proctype beats app default (would be 5 under root-major) -true,0,0,q,"999~(cfg.cascade[(TD,""builtin"");(TD,""app"");`rdb;`rdb1])`diconfiga",1,1,name-major: the procname tier (app/rdb1) wins over every less-specific name -true,0,0,q,"10~(cfg.cascade[(TD,""builtin"");(TD,""app"");`rdb;`rdb1])`diconfigb",1,1,a key absent from the procname tier keeps its most-specific set value (builtin proctype) -true,0,0,q,"not (`) in key cfg.cascade[(TD,""builtin"");(TD,""app"");`rdb;`rdb1]",1,1,the sentinel merge key is dropped from the returned dict -true,0,0,q,"0=count cfg.cascade[(TD,""nope1"");(TD,""nope2"");`rdb;`rdb1]",1,1,an all-missing cascade resolves to an empty dict -true,0,0,q,"10~(cfg.cascade[(TD,""builtin"");(TD,""app"");`rdb;`default])`diconfigb",1,1,dedup: procname=`default must NOT re-apply the default tier last and override proctype (would be 5 without distinct) -true,0,0,q,"100~(cfg.cascade[(TD,""builtin"");(TD,""app"");`rdb;`rdb])`diconfiga",1,1,dedup: proctype~procname resolves correctly (each tier once) -fail,0,0,q,"cfg.cascade[(TD,""builtin"");(TD,""app"");`rdb;(`)]",1,1,cascade rejects a null procname (else it resolves a bogus root/.q tier) -fail,0,0,q,"cfg.cascade[(TD,""builtin"");(TD,""app"");(`);`rdb1]",1,1,cascade rejects a null proctype -fail,0,0,q,"cfg.cascade[(TD,""builtin"");(TD,""app"");""rdb"";`rdb1]",1,1,cascade rejects a non-symbol (string) proctype +true,0,0,q,"100~(cfg.cascade[(TD,""builtin"");(TD,""app"");(`);`rdb;`rdbnofile])`diconfiga",1,1,within a name the later (app) root overrides the builtin root +true,0,0,q,"10~(cfg.cascade[(TD,""builtin"");(TD,""app"");(`);`rdb;`rdbnofile])`diconfigb",1,1,name-major: builtin proctype beats app default (would be 5 under root-major) +true,0,0,q,"999~(cfg.cascade[(TD,""builtin"");(TD,""app"");(`);`rdb;`rdb1])`diconfiga",1,1,name-major: the procname tier (app/rdb1) wins over every less-specific name +true,0,0,q,"10~(cfg.cascade[(TD,""builtin"");(TD,""app"");(`);`rdb;`rdb1])`diconfigb",1,1,a key absent from the procname tier keeps its most-specific set value (builtin proctype) +true,0,0,q,"7~(cfg.cascade[(TD,""builtin"");(TD,""app"");`pptp;`rdb;`rdb1])`diconfigc",1,1,parentproctype: its tier is read (app/pptp) +true,0,0,q,"10~(cfg.cascade[(TD,""builtin"");(TD,""app"");`pptp;`rdb;`rdb1])`diconfigb",1,1,parentproctype: the proctype tier beats it (builtin/rdb 10 over app/pptp 3) as TorQ default->parentproctype->proctype->procname +true,0,0,q,"100~(cfg.cascade[(TD,""builtin"");(TD,""app"");`pptp;`rdb;`rdbnofile])`diconfiga",1,1,parentproctype: it beats default (app/default 100 stays; pptp sets no diconfiga) +fail,0,0,q,"cfg.cascade[(TD,""builtin"");(TD,""app"");""pptp"";`rdb;`rdb1]",1,1,cascade rejects a non-symbol parentproctype +true,0,0,q,"not (`) in key cfg.cascade[(TD,""builtin"");(TD,""app"");(`);`rdb;`rdb1]",1,1,the sentinel merge key is dropped from the returned dict +true,0,0,q,"0=count cfg.cascade[(TD,""nope1"");(TD,""nope2"");(`);`rdb;`rdb1]",1,1,an all-missing cascade resolves to an empty dict +true,0,0,q,"10~(cfg.cascade[(TD,""builtin"");(TD,""app"");(`);`rdb;`default])`diconfigb",1,1,dedup: procname=`default must NOT re-apply the default tier last and override proctype (would be 5 without distinct) +true,0,0,q,"100~(cfg.cascade[(TD,""builtin"");(TD,""app"");(`);`rdb;`rdb])`diconfiga",1,1,dedup: proctype~procname resolves correctly (each tier once) +fail,0,0,q,"cfg.cascade[(TD,""builtin"");(TD,""app"");(`);`rdb;(`)]",1,1,cascade rejects a null procname (else it resolves a bogus root/.q tier) +fail,0,0,q,"cfg.cascade[(TD,""builtin"");(TD,""app"");(`);(`);`rdb1]",1,1,cascade rejects a null proctype +fail,0,0,q,"cfg.cascade[(TD,""builtin"");(TD,""app"");(`);""rdb"";`rdb1]",1,1,cascade rejects a non-symbol (string) proctype comment,,,,,,,overrideconfig - command-line override layer applied onto a resolved config dict true,0,0,q,"1b~(cfg.overrideconfig[basecfg;`enabled`rows!(enlist""1"";enlist""500"")])`enabled",1,1,bool parsed and set from string true,0,0,q,"500~(cfg.overrideconfig[basecfg;`enabled`rows!(enlist""1"";enlist""500"")])`rows",1,1,long parsed and set from string diff --git a/di/torq/test.csv b/di/torq/test.csv index 9c598e0da..ab7b1f592 100644 --- a/di/torq/test.csv +++ b/di/torq/test.csv @@ -29,7 +29,7 @@ true,0,0,q,"(2;3)~(HITS;UPD)",1,,is not skipped: the ignorelist check only match run,0,0,q,"zps:.z.ps; .m.di.0torq.zpsignorewired:0b; .m.di.0torq.initzpsignore[enlist[`zpsignore]!enlist enlist[`enabled]!enlist 0b]",1,,zpsignore with enabled 0b true,0,0,q,zps~.z.ps,1,,leaves .z.ps untouched run,0,0,q,".m.di.0clienttracking.hit:first ctorig; .m.di.0clienttracking.hite:last ctorig",1,,restore client tracking -run,0,0,q,"ctp:{(use`di.torq.config)[`cascade] . .m.di.0torq.roots[],x,`$string[x],""1""} each `tickerplant`segmentedtp",1,,cascade the tickerplant and segmentedtp settings +run,0,0,q,"ctp:{(use`di.torq.config)[`cascade] . .m.di.0torq.roots[],(`;x),`$string[x],""1""} each `tickerplant`segmentedtp",1,,cascade the tickerplant and segmentedtp settings true,0,0,q,"all {(1b;0b)~(x`clientsopencloseonly;(x`zpsignore)`enabled)} each ctp",1,,tickerplants track connections only and have no zpsignore run,0,0,q,r2:tq.init[`hdb;`hdb;enlist[`log]!enlist`di.util.log],1,,init with an explicit (if trivial) log override still works @@ -42,6 +42,9 @@ true,0,0,q,`widget in key .k4unittestproc.capturedconfig,1,,config cascade reach true,0,0,q,"(`timerms in key .k4unittestproc.capturedconfig)&0N~.k4unittestproc.capturedconfig`timerms",1,,init stamps timerms from q's own -t (null here: this test process runs without -t) true,0,0,q,"200~launchtimerms["" -t 200""]",1,,a process launched through torqx_init.q with -t 200 has timerms 200 in its config true,0,0,q,"0N~launchtimerms[""""]",1,,a process launched without -t has a null timerms +true,0,0,q,"(`pptparent;1;1;1b;0b)~launchppt["" -parentproctype pptparent""]",1,,-parentproctype: stamped as a symbol; its settings tier read; proctype beats it; code// loaded before code// +true,0,0,q,"((`);0N;1;0b;0N)~launchppt[""""]",1,,without -parentproctype: parentproctype is a null symbol and no parent tier or code is loaded +true,0,0,q,"(`pptparent;1;1;0b;0N)~launchppt["" -parentproctype pptparent -loadprocesscode 0""]",1,,loadprocesscode 0b: the parent's code is not loaded (gated as torq.q:643); its settings still are true,0,0,q,(`handlers`log`servers`timer)~asc key .k4unittestproc.captureddeps,1,,deps (incl injected servers) were passed through to the custom proctype's init exactly like a built-in one true,0,0,q,1=.k4unittestproc.runcalled,1,,the .run hook fired automatically after init - no launcher-side proctype knowledge needed true,0,0,q,1=.k4unittestproc.deferredcalled,1,,a function queued with .proc.addinitlist ran once after init @@ -71,6 +74,7 @@ true,0,0,q,not any `proctype`procname`torqxstackid`p`norun in key .m.di.0torq.cl true,0,0,q,(enlist"7")~(.m.di.0torq.clioverrideparams[cliopts])`myrows,1,,kept override values are unchanged (the .Q.opt string-list shape overrideconfig expects) true,0,0,q,0=count .m.di.0torq.clioverrideparams[()!()],1,,an empty command line yields no overrides true,0,0,q,0=count .m.di.0torq.clioverrideparams[`proctype`p!((enlist"hdb");(enlist"5560"))],1,,a command line of only reserved flags yields no overrides +true,0,0,q,"0=count .m.di.0torq.clioverrideparams[enlist[`parentproctype]!enlist enlist""wdb""]",1,,-parentproctype is a reserved flag (an identity input) not a config override comment,,,,,,,optional query logging - initquerylog wires di.querylog from a [querylog] settings section (init calls it last) run,0,0,q,.m.di.0torq.initquerylog[qlcfg 0b;r4`deps],1,,a [querylog] section with enabled=false is a silent no-op diff --git a/di/torq/test.q b/di/torq/test.q index 6a07a6676..da77fd433 100644 --- a/di/torq/test.q +++ b/di/torq/test.q @@ -29,6 +29,11 @@ setupfixture:{[] writelines[APPBASE,"/code/common/appcommon.q";enlist "APPCOMMON_LOADED:1b"]; writelines[APPBASE,"/code/",string[TESTPROCNAME],"/appproc.q";enlist "APPPROC_LOADED:1b"]; writelines[APPBASE,"/code/testinst/appname.q";enlist "APPNAME_LOADED:1b"]; + / -parentproctype fixtures: a parent settings tier (a parent-only key, a key the proctype also sets, and loadprocesscode + / declared so -loadprocesscode can override it) and parent code recording whether the proctype's code had loaded yet + writelines[APPBASE,"/settings/pptparent.q";("pptonly:1";"widget:0";"loadprocesscode:1b")]; + system "mkdir -p ",APPBASE,"/code/pptparent"; + writelines[APPBASE,"/code/pptparent/pptcode.q";("PPTCODE:1b";"PPTBEFOREPROC:@[value;`APPPROC_LOADED;0b]")]; / a scratch hdb: just a serialized table, the simplest thing \l can load (hsym `$HDBDIR,"/widgets") set ([]id:1 2 3); @@ -67,6 +72,19 @@ setupfixture:{[] "exit 0")]; } +/ a launcher that starts a real process through torqx_init.q and writes what -parentproctype changed +pptlauncher:{[] writelines[APPBASE,"/launchppt.q"; + ("system \"l \",getenv[`TORQXHOME],\"/di/torq/bin/torqx_init.q\";"; + "c:.k4unittestproc.capturedconfig;"; + "(hsym`$getenv[`TORQXAPPHOME],\"/ppt.txt\") 0: enlist .Q.s1 (c`parentproctype;$[`pptonly in key c;c`pptonly;0N];c`widget;@[value;`PPTCODE;0b];@[value;`PPTBEFOREPROC;0N]);"; + "exit 0")]} + +/ launch a real process with extra q flags; return (parentproctype;pptonly;widget;parent code loaded;proctype code loaded before it) +launchppt:{[flags] + pptlauncher[]; f:APPBASE,"/ppt.txt"; system "rm -f ",f; + system QBIN," ",APPBASE,"/launchppt.q -proctype ",(string TESTPROCNAME)," -procname testinst",flags," -q ",APPBASE,"/ppt.log 2>&1"; + value first read0 hsym`$f} + / launch a real process through torqx_init.q with extra q flags; return the timerms in its config launchtimerms:{[flags] f:APPBASE,"/timerms.txt"; system "rm -f ",f; diff --git a/di/torq/torq.md b/di/torq/torq.md index 72e5a47c2..a2c8ffbb2 100644 --- a/di/torq/torq.md +++ b/di/torq/torq.md @@ -116,15 +116,20 @@ The cascade mirrors the config cascade's shape: | tier | directory | flag | default | |------|-----------|------|---------| | common | `code/common/` | `loadcommoncode` | on | +| parentproctype | `code//` | `loadprocesscode`, and `-parentproctype` given | on when given | | proctype | `code//` | `loadprocesscode` | on | | procname | `code//` | `loadnamecode` | **off** | So **yes, it supports per-procname customisation** just like the config cascade — but, exactly as in TorQ (`.proc.loadnamecode` defaults `0b`), the procname tier is **off by default** and opt-in via `loadnamecode:1b` in that process's settings. Each flag is read from the merged -config (so it's overridable per-process in settings). `parentproctype` (TorQ's 4th tier, for -sharing code between a WDB and its sort workers) is omitted: proctypes `sort` and `sortworker` are -built in and run `di.torq.proc.wdb` itself, with `settings/sort.q` and `settings/sortworker.q`. +config (so it's overridable per-process in settings). `-parentproctype` (TorQ's 4th tier, read +from the command line as `torq.q:376-380` and stamped into config as a symbol atom, null if not +given) adds a `{parentproctype}` settings tier between `default` and `{proctype}`, and loads +`code//` between `common` and ``, gated by `loadprocesscode` as `torq.q:643`. +It is a reserved flag, not a config override. Proctypes `sort` and `sortworker` still run +`di.torq.proc.wdb` with `settings/sort.q` and `settings/sortworker.q`; `-parentproctype wdb` adds +only what an app puts in a `wdb` settings tier or `code/wdb/`. Within a directory, files load in this order: an optional `order.txt` (one filename per line) is loaded first, then the remaining `*.q`/`*.k` files alphabetically — matching TorQ's `loaddir`. diff --git a/di/torq/torq.q b/di/torq/torq.q index 6d36659ea..3711d19de 100644 --- a/di/torq/torq.q +++ b/di/torq/torq.q @@ -147,8 +147,7 @@ startcustom:{[proctype;config;deps] / plain `system "l"` lets each file's definitions land at the namespace ITS OWN \d directives / choose - a bare app query file like code/rdb/examplequeries.q (no \d) lands at ROOT, callable as / countbysym[...]. This is the same load mechanism startcustom already uses for code/processes/. -/ (parentproctype - torq.q's 4th tier, which existed so a sort process could load the wdb's code - -/ is omitted: proctypes sort and sortworker map to di.torq.proc.wdb itself. See wdb.md.) +/ parentproctype (torq.q's 4th tier) loads code// between common and proctype, gated by loadprocesscode, as torq.q:643. optflag:{[config;k;dflt] $[k in key config;`boolean$config k;dflt]} / load every q/k file in one dir at root: an optional order.txt lists files to load first, then @@ -165,6 +164,7 @@ loadappcodedir:{[lg;dir] loadappcode:{[lg;config;proctype;procname] base:reqenv[`TORQXAPPHOME],"/code/"; if[optflag[config;`loadcommoncode;1b]; loadappcodedir[lg;base,"common"]]; + if[optflag[config;`loadprocesscode;1b] and not null ppt:$[`parentproctype in key config;config`parentproctype;`]; loadappcodedir[lg;base,string ppt]]; if[optflag[config;`loadprocesscode;1b]; loadappcodedir[lg;base,string proctype]]; if[optflag[config;`loadnamecode;0b]; loadappcodedir[lg;base,string procname]]; } @@ -249,7 +249,7 @@ initzpsignore:{[config] / reserved launcher/identity flags parsed from the command line - consumed by the launcher and by / di.torq itself (identity, stack id, port, norun), NOT config settings. Everything else on the / command line is a candidate config override. -reservedflags:`proctype`procname`torqxstackid`p`norun; +reservedflags:`proctype`procname`parentproctype`torqxstackid`p`norun; / the config-override params from a parsed command-line opt dict (.Q.opt .z.x): drop the reserved / flags, keep the rest. di.torq.config.overrideconfig then applies each to the matching setting @@ -279,19 +279,22 @@ init:{[proctype;procname;overrides] (dc`checkversiongraph)[enlist builtin proctype]; (dc`checkversiongraphfile)[proctype;reqenv[`TORQXAPPHOME],"/code/processes/",(string proctype),".deps.toml"]]; r:roots[]; + / -parentproctype, as torq.q:376-380: a symbol atom, null if not given + parentproctype:$[`parentproctype in key o:.Q.opt .z.x;first `$o`parentproctype;`]; / the logger is built before config so di.torq.config's command-line override layer (below) can log through it logdep:buildlogdep[overrides]; cc:use`di.torq.config; (cc`init)[enlist[`log]!enlist logdep]; / segmentedchainedtp uses segmentedtp's settings settingsproctype:$[proctype=`segmentedchainedtp;`segmentedtp;proctype]; - config:(cc`cascade)[r 0;r 1;settingsproctype;procname]; + if[not null parentproctype;logdep[`info][`init;"read in process parameter of parentproctype=",string parentproctype]]; + config:(cc`cascade)[r 0;r 1;parentproctype;settingsproctype;procname]; / command-line override layer - the TOP cascade tier. A launch flag matching a settings name / overrides it (parsed into that setting's type); reserved launcher/identity flags are excluded, / and a flag that doesn't name a real setting is skipped (see di.torq.config.overrideconfig). config:(cc`overrideconfig)[config; clioverrideparams .Q.opt .z.x]; / self-identity is resolved by di.torq and authoritative - stamped AFTER overrides so it always wins - config:config,`proctype`procname!(proctype;procname); + config:config,`proctype`procname`parentproctype!(proctype;procname;parentproctype); / the process.csv phone-book path, so di.torq.servers (and any consumer building its own startup config / slice from this config) can dial peers without reading env itself - keeps di.servers' env-free boundary. config:config,enlist[`processcsv]!enlist reqenv[`TORQXAPPCONFIG],"/process.csv"; From 4941b05313b5234752d0cec197e6ddbb68bb58c7 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 20 Oct 2026 18:21:13 +0100 Subject: [PATCH 24/39] di.torq.proc.gateway: getdata behind the eod reload gate; log line says rejecting .gw.getdata is now the gateway's own wrapper over di.dataaccess's getdata, behind the same reload helper (ineod) as asyncexec/asyncexecjpt, so it is rejected during an EOD reload instead of being dispatched to the rdb and hdb mid-reload. The reloadstart log line says it rejects new queries. Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/gateway/gateway.md | 4 ++-- di/torq/proc/gateway/gateway.q | 12 +++++++--- di/torq/proc/gateway/test.csv | 12 ++++++++++ di/torq/proc/gateway/test.q | 42 +++++++++++++++++++++++++++++++++ 4 files changed, 65 insertions(+), 5 deletions(-) diff --git a/di/torq/proc/gateway/gateway.md b/di/torq/proc/gateway/gateway.md index 20d347463..11f80f5f2 100644 --- a/di/torq/proc/gateway/gateway.md +++ b/di/torq/proc/gateway/gateway.md @@ -45,8 +45,8 @@ di.serverselect — see the scope note). `query` is any value passed to `value` The wdb calls `(`.gw.reload;`reloadstart)` before moving its partition into the hdb and `(`.gw.reload;`reloadend)` after the hdb/rdb have reloaded (di.torq.proc.wdb's `informgateway` already sends -these — building this module makes that loop live). While gated, new queries are rejected with a -retry message so none straddle the rdb-drop / hdb-reload window; `reloadend` clears the gate and +these — building this module makes that loop live). While gated, new queries (`asyncexec`, `asyncexecjpt` and +`getdata`, through one helper, `ineod`) are rejected with a retry message so none straddle the rdb-drop / hdb-reload window; `reloadend` clears the gate and refreshes the backend registry. ## How it wires together (init) diff --git a/di/torq/proc/gateway/gateway.q b/di/torq/proc/gateway/gateway.q index a7084b4f9..6c3ff0776 100644 --- a/di/torq/proc/gateway/gateway.q +++ b/di/torq/proc/gateway/gateway.q @@ -49,11 +49,17 @@ registerbackends:{[] .z.m.log[`info][`gateway;"registered ",(string count ct)," backend server(s): ",", " sv string exec distinct proctype from ct]]; } +/ the reload rule for every client entry point: during an eod reload reply with an error and return 1b (caller returns) +ineod:{[] if[.z.m.eod;@[neg .z.w;.z.m.errorprefix,"gateway in eod reload - retry shortly";()]]; .z.m.eod} + +/ client entry point (published at root as .gw.getdata): di.dataaccess's getdata, behind the reload rule +getdata:{[tablename;starttime;endtime;by;aggs] if[ineod[];:()]; (.z.m.da`getdata)[tablename;starttime;endtime;by;aggs]} + / client entry point (published at root as .gw.asyncexecjpt): full control over join/postback/timeout. / protected so a routing/dispatch error becomes a formatted reply to the client rather than an / uncaught error on the async handler. asyncexecjpt:{[query;servertype;join;postback;timeout] - if[.z.m.eod;@[neg .z.w;.z.m.errorprefix,"gateway in eod reload - retry shortly";()];:()]; + if[ineod[];:()]; .[{[q;s;j;p;t] (.z.m.ad`execquery)[q;resolvetypes s;j;p;t;0b]}; (query;servertype;join;postback;timeout); {[e] @[neg .z.w;.z.m.errorprefix,e;()]}]; @@ -68,7 +74,7 @@ asyncexec:{[query;servertype] asyncexecjpt[query;servertype;raze;();0Wn]} / window. v1 rejects rather than queues-and-resumes; on reloadend it refreshes the backend registry. reload:{[msg] $[msg~`reloadstart; - [.z.m.eod:1b; .z.m.log[`info][`gateway;"eod reload start - holding new queries"]]; + [.z.m.eod:1b; .z.m.log[`info][`gateway;"eod reload start - rejecting new queries until reloadend"]]; msg~`reloadend; [.z.m.eod:0b; registerbackends[]; (.z.m.da`setpartitions)[buildpartitions[]]; .z.m.log[`info][`gateway;"eod reload end - resuming queries"]]; .z.m.log[`warn][`gateway;"unknown .gw.reload message: ",string msg]]; @@ -132,7 +138,7 @@ init:{[config;deps] / normalised query layer (di.dataaccess); the raw asyncexec/asyncexecjpt route query strings. set[`.gw.asyncexec;asyncexec]; set[`.gw.asyncexecjpt;asyncexecjpt]; - set[`.gw.getdata;.z.m.da`getdata]; + set[`.gw.getdata;getdata]; set[`.gw.reload;reload]; / housekeeping timers (asyncdispatch leaves scheduling to the caller), period as a timespan. diff --git a/di/torq/proc/gateway/test.csv b/di/torq/proc/gateway/test.csv index 5f48299e4..56345e3b6 100644 --- a/di/torq/proc/gateway/test.csv +++ b/di/torq/proc/gateway/test.csv @@ -25,3 +25,15 @@ run,0,0,q,hdbandrdb[],1,,the rdb connects after startup - di.torq.servers' retry run,0,0,q,fireconnectcustom[],1,,di.torq.servers' retryrows fires the hook with the connected rows true,0,0,q,`rdb in routable[],1,,REGRESSION: a backend that connected after startup becomes routable without a restart true,0,0,q,`hdb in routable[],1,,the already-registered hdb is undisturbed + +comment,,,,,,,reload gate covers getdata (a real gateway process and two counting backends) +run,0,0,q,startgwfixture[],1,,spawn two backends and a port gateway built as di.torq builds it +run,0,0,q,"GWH"".gw.reload[`reloadstart]""",1,,the wdb's reloadstart +run,0,0,q,G1:gwgetdata[],1,,getdata over yesterday..now during the reload +true,0,0,q,"(enlist""error: gateway in eod reload - retry shortly"")~G1`replies",1,,getdata is rejected during the reload with the same reply as asyncexec +true,0,0,q,0 0~G1`sent,1,,and nothing is sent to the rdb or the hdb +run,0,0,q,"GWH"".gw.reload[`reloadend]""",1,,the wdb's reloadend +run,0,0,q,G2:gwgetdata[],1,,getdata again after the reload +true,0,0,q,(1=count G2`replies)&2=count first G2`replies,1,,getdata works again: one reply with both rows +true,0,0,q,1 1~G2`sent,1,,one shard sent to each backend +run,0,0,q,stopgwfixture[],1,,stop the gateway and backends diff --git a/di/torq/proc/gateway/test.q b/di/torq/proc/gateway/test.q index dbffee66b..986c49eeb 100644 --- a/di/torq/proc/gateway/test.q +++ b/di/torq/proc/gateway/test.q @@ -44,3 +44,45 @@ hookinstalled:{[] @[{100h=type value x};`.servers.connectcustom;{[e] 0b}]} / fire the hook exactly as di.torq.servers' retryrows does - with the connected rows fireconnectcustom:{[] (value `.servers.connectcustom) BACKENDS; } + +/ --- reload gate against a real gateway process: two backends that count the async messages they are sent --- +GWDIR:"/tmp/di_gw_k4unit_",string .z.i; +GWQ:first system "readlink -f /proc/",(string .z.i),"/exe"; +gwfree:{[p] not @[{hclose hopen x;1b};(`$":localhost:",string p;100);0b]}; +gwpick:{[n] n#p where gwfree each p:30000+(.z.i mod 15000)+til 40}; +gwwait:{[p] {[p;x] system "sleep 0.05"; x+1}[p]/[{[p;x] (x<100) and gwfree p}[p];0]; not gwfree p}; +GWREPLIES:(); +startgwfixture:{[] + system "rm -rf ",GWDIR; system "mkdir -p ",GWDIR; + `GWP set gwpick 3; + (hsym`$GWDIR,"/backend.q") 0: ("trade:([]date:2#.z.d-1 0;time:(.z.d-1;.z.d)+0D10;sym:`a`b;price:1 2f);";"SENT:0; .z.ps:{`SENT set SENT+1; value x};"); + (hsym`$GWDIR,"/process.csv") 0: ("host,port,proctype,procname";"localhost,",(string GWP 1),",rdb,rdb1";"localhost,",(string GWP 2),",hdb,hdb1"); + (hsym`$GWDIR,"/gw.q") 0: ( + "lg:`info`warn`error!3#enlist {[c;m]};"; + "tm:use`di.timer; tm.init enlist[`log]!enlist lg;"; + "td:`addjob`deletejobs`enablejobs`disablejobs`getactivejobs!(tm.addjob.custom;tm.deletejobs;tm.enablejobs;tm.disablejobs;tm.getactivejobs);"; + "hz:use`di.torq.handlers; hz.init enlist[`log]!enlist lg; hd:`register`remove`list!(hz.register;hz.remove;hz.list);"; + "svc:use`di.torq.servers; svc.init[`log`timer`handlers`proctype`procname`processcsv`connections`discoveryregister`connectionsfromdiscovery!(lg;td;hd;`gateway;`gateway1;\"",GWDIR,"/process.csv\";`rdb`hdb;0b;0b)];"; + "gw:use`di.torq.proc.gateway; gw.init[enlist[`backendtypes]!enlist`rdb`hdb;`log`timer`handlers`servers!(lg;td;hd;svc)];"); + {system GWQ," ",GWDIR,"/backend.q -p ",(string x)," -q ",GWDIR,"/backend",(string x),".log 2>&1 &"} each 1_GWP; + / a failed start stops whichever backends did come up, so nothing is left running + gwstop:{{@[{h:hopen x;neg[h]"exit 0";neg[h][]};`$":localhost:",string x;()]} each x}; + if[not all gwwait each 1_GWP;gwstop 1_GWP;'"test: backends did not listen"]; + system GWQ," ",GWDIR,"/gw.q -p ",(string first GWP)," -q ",GWDIR,"/gw.log 2>&1 &"; + if[not gwwait first GWP;gwstop GWP;'"test: gateway did not listen"]; + `GWH set hopen `$":localhost:",string first GWP; + `GWBH set {hopen `$":localhost:",string x} each 1_GWP; + .z.ps:{`GWREPLIES set GWREPLIES,enlist x}; + }; +/ a getdata spanning yesterday and today (an rdb and an hdb shard); returns the replies and what each backend was sent +gwgetdata:{[] + {x"SENT:0"} each GWBH; + neg[GWH](`.gw.getdata;`trade;`timestamp$.z.d-1;.z.p;`;()); neg[GWH][]; + system "sleep 1"; GWH"1"; + r:GWREPLIES; `GWREPLIES set (); + `replies`sent!(r;{x"SENT"} each GWBH)}; +stopgwfixture:{[] + {@[{neg[x]"exit 0";neg[x][]};x;()]} each GWH,GWBH; + system "sleep 0.3"; system "rm -rf ",GWDIR; + }; + From 5e8b444f3ec43a26876ffded3c7ab34d7357a5a6 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 20 Oct 2026 18:30:19 +0100 Subject: [PATCH 25/39] di.torq.proc.gateway: single-type queries run during the eod reload, as TorQ's checkeod During a reload, ineod rejects only a query spanning more than one server type, as legacy's checkeod (gateway.q:93); a single-type query runs. A getdata's types are those of the partitions its range covers, from the same table di.dataaccess routes with. The test fixture now uses OS-assigned ports and checks each listener is the process it spawned. Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/gateway/gateway.md | 7 +++-- di/torq/proc/gateway/gateway.q | 20 ++++++++------ di/torq/proc/gateway/test.csv | 9 +++++++ di/torq/proc/gateway/test.q | 47 ++++++++++++++++++++------------- 4 files changed, 55 insertions(+), 28 deletions(-) diff --git a/di/torq/proc/gateway/gateway.md b/di/torq/proc/gateway/gateway.md index 11f80f5f2..0ce25bfa8 100644 --- a/di/torq/proc/gateway/gateway.md +++ b/di/torq/proc/gateway/gateway.md @@ -45,8 +45,11 @@ di.serverselect — see the scope note). `query` is any value passed to `value` The wdb calls `(`.gw.reload;`reloadstart)` before moving its partition into the hdb and `(`.gw.reload;`reloadend)` after the hdb/rdb have reloaded (di.torq.proc.wdb's `informgateway` already sends -these — building this module makes that loop live). While gated, new queries (`asyncexec`, `asyncexecjpt` and -`getdata`, through one helper, `ineod`) are rejected with a retry message so none straddle the rdb-drop / hdb-reload window; `reloadend` clears the gate and +these — building this module makes that loop live). While gated, a new query spanning more than one server type +(`asyncexec`, `asyncexecjpt`, or a `getdata` whose range covers more than one partition; one helper, `ineod`, as +TorQ's `checkeod`) is rejected with a retry message so none straddle the rdb-drop / hdb-reload window, while a +single-type query runs, as legacy. Legacy also holds multi-type async queries until `reloadend` and errors those +in flight at `reloadstart`; the port does not (backlog); `reloadend` clears the gate and refreshes the backend registry. ## How it wires together (init) diff --git a/di/torq/proc/gateway/gateway.q b/di/torq/proc/gateway/gateway.q index 6c3ff0776..b25c39a33 100644 --- a/di/torq/proc/gateway/gateway.q +++ b/di/torq/proc/gateway/gateway.q @@ -49,17 +49,21 @@ registerbackends:{[] .z.m.log[`info][`gateway;"registered ",(string count ct)," backend server(s): ",", " sv string exec distinct proctype from ct]]; } -/ the reload rule for every client entry point: during an eod reload reply with an error and return 1b (caller returns) -ineod:{[] if[.z.m.eod;@[neg .z.w;.z.m.errorprefix,"gateway in eod reload - retry shortly";()]]; .z.m.eod} +/ the reload rule for every client entry point, as TorQ's checkeod (gateway.q:93): during an eod reload a query +/ spanning more than one server type is rejected with an error reply (returns 1b; the caller returns); one type runs +ineod:{[types] r:.z.m.eod and 1=starttime;:()]; + (.z.m.da`getdata)[tablename;starttime;endtime;by;aggs]} / client entry point (published at root as .gw.asyncexecjpt): full control over join/postback/timeout. / protected so a routing/dispatch error becomes a formatted reply to the client rather than an / uncaught error on the async handler. asyncexecjpt:{[query;servertype;join;postback;timeout] - if[ineod[];:()]; + if[ineod @[resolvetypes;servertype;()];:()]; .[{[q;s;j;p;t] (.z.m.ad`execquery)[q;resolvetypes s;j;p;t;0b]}; (query;servertype;join;postback;timeout); {[e] @[neg .z.w;.z.m.errorprefix,e;()]}]; @@ -74,9 +78,9 @@ asyncexec:{[query;servertype] asyncexecjpt[query;servertype;raze;();0Wn]} / window. v1 rejects rather than queues-and-resumes; on reloadend it refreshes the backend registry. reload:{[msg] $[msg~`reloadstart; - [.z.m.eod:1b; .z.m.log[`info][`gateway;"eod reload start - rejecting new queries until reloadend"]]; + [.z.m.eod:1b; .z.m.log[`info][`gateway;"eod reload start - rejecting multi-type queries until reloadend"]]; msg~`reloadend; - [.z.m.eod:0b; registerbackends[]; (.z.m.da`setpartitions)[buildpartitions[]]; .z.m.log[`info][`gateway;"eod reload end - resuming queries"]]; + [.z.m.eod:0b; registerbackends[]; (.z.m.da`setpartitions)[.z.m.partitions:buildpartitions[]]; .z.m.log[`info][`gateway;"eod reload end - resuming queries"]]; .z.m.log[`warn][`gateway;"unknown .gw.reload message: ",string msg]]; } @@ -124,7 +128,7 @@ init:{[config;deps] / coverage for routing is built from .z.d (buildpartitions) and refreshed at EOD reloadend via / (.z.m.da`setpartitions), so post-roll queries for the just-saved day route to the hdb not the rdb. .z.m.da:use`di.dataaccess; - (.z.m.da`init)[`log`timer`partitions!(deps`log;deps`timer;buildpartitions[])]; + (.z.m.da`init)[`log`timer`partitions!(deps`log;deps`timer;.z.m.partitions:buildpartitions[])]; / handler callbacks via the injected handlers dep (di.torq.handlers): track client connect, and on any / handle close clean up whichever role it was - backend (asyncdispatch in-flight cleanup + diff --git a/di/torq/proc/gateway/test.csv b/di/torq/proc/gateway/test.csv index 56345e3b6..912307df3 100644 --- a/di/torq/proc/gateway/test.csv +++ b/di/torq/proc/gateway/test.csv @@ -32,6 +32,15 @@ run,0,0,q,"GWH"".gw.reload[`reloadstart]""",1,,the wdb's reloadstart run,0,0,q,G1:gwgetdata[],1,,getdata over yesterday..now during the reload true,0,0,q,"(enlist""error: gateway in eod reload - retry shortly"")~G1`replies",1,,getdata is rejected during the reload with the same reply as asyncexec true,0,0,q,0 0~G1`sent,1,,and nothing is sent to the rdb or the hdb +run,0,0,q,G3:gwasync[`hdb],1,,asyncexec to the hdb alone during the reload +true,0,0,q,(enlist enlist 2)~G3`replies,1,,a single-type query runs during the reload and is answered as outside it (as TorQ's checkeod) +true,0,0,q,0 1~G3`sent,1,,and is sent to the hdb only +run,0,0,q,G4:gwasync[`rdb`hdb],1,,asyncexec to the rdb and the hdb during the reload +true,0,0,q,"(enlist""error: gateway in eod reload - retry shortly"")~G4`replies",1,,a multi-type query is rejected during the reload +true,0,0,q,0 0~G4`sent,1,,and nothing is sent +run,0,0,q,G5:gwgetdatatoday[],1,,getdata over today only (the rdb partition alone) during the reload +true,0,0,q,(1=count G5`replies)&98h=type first G5`replies,1,,a getdata covering one partition runs during the reload +true,0,0,q,1 0~G5`sent,1,,and is sent to the rdb only run,0,0,q,"GWH"".gw.reload[`reloadend]""",1,,the wdb's reloadend run,0,0,q,G2:gwgetdata[],1,,getdata again after the reload true,0,0,q,(1=count G2`replies)&2=count first G2`replies,1,,getdata works again: one reply with both rows diff --git a/di/torq/proc/gateway/test.q b/di/torq/proc/gateway/test.q index 986c49eeb..2f4a3ab50 100644 --- a/di/torq/proc/gateway/test.q +++ b/di/torq/proc/gateway/test.q @@ -48,39 +48,50 @@ fireconnectcustom:{[] (value `.servers.connectcustom) BACKENDS; } / --- reload gate against a real gateway process: two backends that count the async messages they are sent --- GWDIR:"/tmp/di_gw_k4unit_",string .z.i; GWQ:first system "readlink -f /proc/",(string .z.i),"/exe"; -gwfree:{[p] not @[{hclose hopen x;1b};(`$":localhost:",string p;100);0b]}; -gwpick:{[n] n#p where gwfree each p:30000+(.z.i mod 15000)+til 40}; -gwwait:{[p] {[p;x] system "sleep 0.05"; x+1}[p]/[{[p;x] (x<100) and gwfree p}[p];0]; not gwfree p}; GWREPLIES:(); +/ start a q on an OS-assigned port (-p 0W); it writes its port to .port; wait for it and return the port +/ (no port picking: a port with no listener can still be unbindable, which made picked ports flaky) +gwspawn:{[script;name] + pf:GWDIR,"/",name,".port"; + system GWQ," ",GWDIR,"/",script," -p 0W -q ",GWDIR,"/",name,".log 2>&1 &"; + {[pf;x] system "sleep 0.05"; x+1}[pf]/[{[pf;x] (x<100) and ()~key hsym`$pf}[pf];0]; + if[()~key hsym`$pf;'"test: ",name," did not start (see ",GWDIR,"/",name,".log)"]; + "J"$first read0 hsym`$pf}; +/ the port and identity line each spawned q writes once it is listening +gwportline:{[name] "(hsym`$\"",GWDIR,"/",name,".port\") 0: enlist string system\"p\"; GWNAME:`",name,";"}; startgwfixture:{[] system "rm -rf ",GWDIR; system "mkdir -p ",GWDIR; - `GWP set gwpick 3; - (hsym`$GWDIR,"/backend.q") 0: ("trade:([]date:2#.z.d-1 0;time:(.z.d-1;.z.d)+0D10;sym:`a`b;price:1 2f);";"SENT:0; .z.ps:{`SENT set SENT+1; value x};"); - (hsym`$GWDIR,"/process.csv") 0: ("host,port,proctype,procname";"localhost,",(string GWP 1),",rdb,rdb1";"localhost,",(string GWP 2),",hdb,hdb1"); + {(hsym`$GWDIR,"/",x,".q") 0: ("trade:([]date:2#.z.d-1 0;time:(.z.d-1;.z.d)+0D10;sym:`a`b;price:1 2f);";"SENT:0; .z.ps:{`SENT set SENT+1; value x};";gwportline x)} each ("rdb1";"hdb1"); + bp:gwspawn'[("rdb1.q";"hdb1.q");("rdb1";"hdb1")]; + (hsym`$GWDIR,"/process.csv") 0: ("host,port,proctype,procname";"localhost,",(string bp 0),",rdb,rdb1";"localhost,",(string bp 1),",hdb,hdb1"); (hsym`$GWDIR,"/gw.q") 0: ( "lg:`info`warn`error!3#enlist {[c;m]};"; "tm:use`di.timer; tm.init enlist[`log]!enlist lg;"; "td:`addjob`deletejobs`enablejobs`disablejobs`getactivejobs!(tm.addjob.custom;tm.deletejobs;tm.enablejobs;tm.disablejobs;tm.getactivejobs);"; "hz:use`di.torq.handlers; hz.init enlist[`log]!enlist lg; hd:`register`remove`list!(hz.register;hz.remove;hz.list);"; "svc:use`di.torq.servers; svc.init[`log`timer`handlers`proctype`procname`processcsv`connections`discoveryregister`connectionsfromdiscovery!(lg;td;hd;`gateway;`gateway1;\"",GWDIR,"/process.csv\";`rdb`hdb;0b;0b)];"; - "gw:use`di.torq.proc.gateway; gw.init[enlist[`backendtypes]!enlist`rdb`hdb;`log`timer`handlers`servers!(lg;td;hd;svc)];"); - {system GWQ," ",GWDIR,"/backend.q -p ",(string x)," -q ",GWDIR,"/backend",(string x),".log 2>&1 &"} each 1_GWP; - / a failed start stops whichever backends did come up, so nothing is left running - gwstop:{{@[{h:hopen x;neg[h]"exit 0";neg[h][]};`$":localhost:",string x;()]} each x}; - if[not all gwwait each 1_GWP;gwstop 1_GWP;'"test: backends did not listen"]; - system GWQ," ",GWDIR,"/gw.q -p ",(string first GWP)," -q ",GWDIR,"/gw.log 2>&1 &"; - if[not gwwait first GWP;gwstop GWP;'"test: gateway did not listen"]; - `GWH set hopen `$":localhost:",string first GWP; - `GWBH set {hopen `$":localhost:",string x} each 1_GWP; + "gw:use`di.torq.proc.gateway; gw.init[enlist[`backendtypes]!enlist`rdb`hdb;`log`timer`handlers`servers!(lg;td;hd;svc)];"; + gwportline "gw"); + gp:gwspawn["gw.q";"gw"]; + `GWH set hopen `$":localhost:",string gp; + `GWBH set {hopen `$":localhost:",string x} each bp; + / the listeners are the processes this fixture spawned + if[not (`gw`rdb1`hdb1)~{x"GWNAME"} each GWH,GWBH;'"test: a port answered for a process this fixture did not spawn"]; .z.ps:{`GWREPLIES set GWREPLIES,enlist x}; }; -/ a getdata spanning yesterday and today (an rdb and an hdb shard); returns the replies and what each backend was sent -gwgetdata:{[] +/ send one async message to the gateway; returns the replies and what each backend (rdb;hdb) was sent +gwask:{[m] {x"SENT:0"} each GWBH; - neg[GWH](`.gw.getdata;`trade;`timestamp$.z.d-1;.z.p;`;()); neg[GWH][]; + neg[GWH] m; neg[GWH][]; system "sleep 1"; GWH"1"; r:GWREPLIES; `GWREPLIES set (); `replies`sent!(r;{x"SENT"} each GWBH)}; +/ a getdata spanning yesterday and today (an rdb and an hdb shard) +gwgetdata:{[] gwask (`.gw.getdata;`trade;`timestamp$.z.d-1;.z.p;`;())}; +/ a getdata over today only (the rdb partition alone) +gwgetdatatoday:{[] gwask (`.gw.getdata;`trade;`timestamp$.z.d;.z.p;`;())}; +/ asyncexec to the given server types +gwasync:{[t] gwask (`.gw.asyncexec;"count trade";t)}; stopgwfixture:{[] {@[{neg[x]"exit 0";neg[x][]};x;()]} each GWH,GWBH; system "sleep 0.3"; system "rm -rf ",GWDIR; From 4c507a20ede396ce396fde3797fef7c0f4f0f2b0 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 20 Oct 2026 18:32:49 +0100 Subject: [PATCH 26/39] di.torq.servers: test fixture on OS-assigned ports with a listener check Test-only. Ports a spawned peer binds are reserved by a q started with -p 0W that writes its port and exits, instead of probing for a port with no listener; each spawn logs to the per-run fixture dir and checks the listener's .z.i is the pid it spawned. FIXDIR is per run. Co-Authored-By: Claude Opus 5.5 --- di/torq/servers/test.q | 50 +++++++++++++++++++++++------------------- 1 file changed, 28 insertions(+), 22 deletions(-) diff --git a/di/torq/servers/test.q b/di/torq/servers/test.q index 2b74f09ed..a21fcc56f 100644 --- a/di/torq/servers/test.q +++ b/di/torq/servers/test.q @@ -30,34 +30,45 @@ warnlogged:{[s] any (exec msg from logrows where lvl=`warn) like "*",s,"*"}; firejob:{[id] timerjobs[id][]}; / --- real peer process fixture --- -FIXDIR:"/tmp/diserverstest"; +FIXDIR:"/tmp/diserverstest_",string .z.i; QBIN:first system "readlink -f /proc/",(string .z.i),"/exe"; isfree:{[p] not @[{hclose hopen x;1b};(`$":localhost:",string p;100);0b]}; -pickport:{[start] first (start+til 500) where isfree each start+til 500}; PEERPORT:0N; DEADPORT:0N; PEERPID:0N; +/ an OS-assigned free port: a q started with -p 0W writes its port and exits before any connection is made, +/ so the port can be bound again (no port picking: a port with no listener can still be unbindable) +reserveport:{[] + f:FIXDIR,"/port",string 1+count key hsym`$FIXDIR; + (hsym`$FIXDIR,"/portprobe.q") 0: enlist "(hsym`$first .z.x) 0: enlist string system\"p\"; exit 0"; + system QBIN," ",FIXDIR,"/portprobe.q ",f," -p 0W -q /dev/null 2>&1"; + "J"$first read0 hsym`$f}; + waitlisten:{[port;timeoutms] deadline:.z.p+`timespan$1000000*timeoutms; while[(.z.p/dev/null 2>&1 &"; - if[not waitlisten[PEERPORT;3000];'"test: peer failed to listen on ",string PEERPORT]; - h:hopen (`$":localhost:",string PEERPORT;2000); - PEERPID::h ".z.i"; - hclose h;}; +/ start q on port with args, logging to FIXDIR; wait until it listens and check the listener is the process +/ just spawned (its .z.i is the spawned pid); returns the pid +spawnat:{[args;port] + pid:"J"$first system QBIN," ",args," -p ",(string port)," -q ",FIXDIR,"/q",(string port),".log 2>&1 & echo $!"; + if[not waitlisten[port;3000];'"test: q failed to listen on ",(string port)," (see ",FIXDIR,"/q",(string port),".log)"]; + h:hopen (`$":localhost:",string port;2000); + ok:pid=h ".z.i"; + hclose h; + if[not ok;'"test: port ",(string port)," answered for a process this fixture did not spawn"]; + pid}; + +spawnpeer:{[] PEERPID::spawnat["";PEERPORT];}; killpeer:{[] if[not null PEERPID;@[system;"kill ",string PEERPID;{}]]; PEERPID::0N; system "sleep 0.3";}; setupfixture:{[] - / pick two free ports (peer + a never-listening dead one), then write a header'd process.csv + / reserve two ports (peer + a never-listening dead one), then write a header'd process.csv / phone book with self, the peer (otherproc), and a dead proctype. - PEERPORT::pickport 20000+`int$.z.i mod 20000; - DEADPORT::pickport PEERPORT+1; system "mkdir -p ",FIXDIR; + PEERPORT::reserveport[]; + DEADPORT::reserveport[]; (`$":",FIXDIR,"/process.csv") 0: ( "host,port,proctype,procname"; "localhost,",string[PEERPORT-2],",selfproc,selfinst"; @@ -73,20 +84,15 @@ DISCPORT:0N; TPPORT:0N; DISCPIDS:`long$(); / add a discovery row to process.csv, write the stub, and bind the .z.pc that addprocs calls setupdisc:{[] .z.pc:{}; - DISCPORT::pickport DEADPORT+1; - TPPORT::pickport DISCPORT+1; + DISCPORT::reserveport[]; + TPPORT::reserveport[]; (`$":",FIXDIR,"/process.csv") 0: (read0 `$":",FIXDIR,"/process.csv"),enlist "localhost,",string[DISCPORT],",discovery,discinst"; (`$":",FIXDIR,"/disc.q") 0: ( "REGN:0;register:{[x] `REGN set REGN+1}"; "getservices:{[p;s] ([]procname:enlist`tpinst;proctype:enlist`tpproc;hpup:enlist`$\":localhost:",string[TPPORT],"\";attributes:enlist()!())}"); }; -spawnq:{[args;port] - system QBIN," ",args," -p ",string[port]," -q /dev/null 2>&1 &"; - if[not waitlisten[port;3000];'"test: q failed to listen on ",string port]; - h:hopen (`$":localhost:",string port;2000); - DISCPIDS,:h ".z.i"; - hclose h;}; +spawnq:{[args;port] DISCPIDS,:spawnat[args;port];}; spawndisc:{[] spawnq["";TPPORT]; spawnq[FIXDIR,"/disc.q";DISCPORT];}; killdisc:{[] {@[system;"kill ",string x;{}]} each DISCPIDS; DISCPIDS::`long$();}; @@ -104,7 +110,7 @@ addprocshook:{[] .z.pc:{}; `APC set (); .servers.addprocscustom:{[t;p] `APC set (exec procname from t;p)}; - .servers.addprocs[([]procname:enlist`newinst;proctype:enlist`newproc;hpup:enlist`$":localhost:",string pickport DEADPORT+1);enlist`newproc;0b]; + .servers.addprocs[([]procname:enlist`newinst;proctype:enlist`newproc;hpup:enlist`$":localhost:",string reserveport[]);enlist`newproc;0b]; .servers.addprocscustom:{[connectiontab;procs]}; delete from `.servers.SERVERS where procname=`newinst; (enlist`newinst;enlist`newproc)~APC}; From 6cdfcd19cbf39ba34e65e496c4f375d456f4722f Mon Sep 17 00:00:00 2001 From: alowrydi Date: Thu, 22 Oct 2026 15:51:42 +0100 Subject: [PATCH 27/39] di.torq.proc.tickerplant: upd rolls the day first when past the roll, as TorQ's tickerplant.q As legacy tickerplant.q:50-51 (batched: the check sits in the branch that stamps unstamped data) and :70 (immediate: ts .z.p on every upd), upd now runs the roll check before logging. Before, only the 1s tpeodcheck job rolled, so messages between the roll time and the next check were logged into the old day (24 rows, up to 462ms late, in the TorqX-POC probe; none after this change). Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/tickerplant/test.csv | 12 ++++++++++++ di/torq/proc/tickerplant/test.q | 8 ++++++++ di/torq/proc/tickerplant/tickerplant.q | 5 ++++- 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/di/torq/proc/tickerplant/test.csv b/di/torq/proc/tickerplant/test.csv index f5823591a..c8cdc712c 100644 --- a/di/torq/proc/tickerplant/test.csv +++ b/di/torq/proc/tickerplant/test.csv @@ -64,4 +64,16 @@ run,0,0,q,endofday[],1,,force an end-of-day roll true,0,0,q,rolledfile["replog";ROLLDATE+1],1,,the roll opened the next day's log file true,0,0,q,"(ROLLDATE+1;0)~(.u.d;count .u.icounts)",1,,the roll advances .u.d and resets .u.icounts +comment,,,,,,,an upd after the roll time rolls the day first (TorQ tickerplant.q:50-51 and :70) +run,0,0,q,doinit[immcfg[]],1,,immediate mode with a log +run,0,0,q,R1:pastroll["log";0b],1,,an unstamped upd 1s after the roll +true,0,0,q,(1+R1 0)=R1 1,1,,immediate: the upd rolled the day before logging +true,0,0,q,1=R1 2,1,,immediate: the row went to the next day's log +run,0,0,q,doinit[batchcfg[]],1,,batched mode with a log +run,0,0,q,R2:pastroll["batchlog";0b],1,,an unstamped upd 1s after the roll +true,0,0,q,(1+R2 0)=R2 1,1,,batched unstamped: the upd rolled the day before logging +true,0,0,q,1=R2 2,1,,batched unstamped: the row went to the next day's log +run,0,0,q,R3:pastroll["batchlog";1b],1,,a feed-stamped upd 1s after the next roll +true,0,0,q,(R3 0)=R3 1,1,,batched feed-stamped: no roll in upd (as TorQ: the check is inside its unstamped branch); tpeodcheck rolls it + after,0,0,q,teardownfixture[],1,,remove the temp fixture dirs diff --git a/di/torq/proc/tickerplant/test.q b/di/torq/proc/tickerplant/test.q index a3d71e43d..c46b66d16 100644 --- a/di/torq/proc/tickerplant/test.q +++ b/di/torq/proc/tickerplant/test.q @@ -60,6 +60,14 @@ logcount:{[dir] c:-11!(-2;hsym`$dir,"/tp",string "d"$.z.p); $[0>type c;c;first c loghas:{[sub;n] n=logcount[BASE,"/",sub]} flushperiodok:{[] 0D00:00:02=first exec period from timercalls where id=`tpflush} rolledfile:{[sub;date] not ()~key hsym`$BASE,"/",sub,"/tp",string date} +/ an upd arriving after the roll time: put the roll 1s in the past, send one trade (stamped by the feed or not), +/ return (date before;date after;messages in the next day's log) +pastroll:{[sub;stamped] + (use`di.eodtime)[`setnextroll] .z.p-0D00:00:01; + d0:.u.d; + upd[`trade;$[stamped;(.z.p;`R;1f;1i);(`R;1f;1i)]]; + f:hsym`$BASE,"/",sub,"/tp",string d0+1; + (d0;.u.d;$[()~key f;0;first -11!(-2;f)])} / init helpers that store handles / state for assertions doinit:{[cfg] resetcalls[]; resettimer[]; resethandlers[]; (tk`init)[cfg;deps[]]; } diff --git a/di/torq/proc/tickerplant/tickerplant.q b/di/torq/proc/tickerplant/tickerplant.q index bebd0d6fa..840c893d4 100644 --- a/di/torq/proc/tickerplant/tickerplant.q +++ b/di/torq/proc/tickerplant/tickerplant.q @@ -37,7 +37,10 @@ stamp:{[x] / stamps, logs (unless replaying - logh is 0 during the replay inside tplog.open), then / publishes immediately or buffers into the root table for the flush job. upd:{[t;x] - x:stamp tocols x; + x:tocols x; + / roll the day first if past the roll: always when immediate, for unstamped data when batched + if[$[.z.m.batchms>0;not -12=type first first x;1b];eodcheck[]]; + x:stamp x; if[.z.m.logh>0;(.z.m.tp`write)[.z.m.logh;(`upd;t;x)];.u.i+:1]; if[count .z.m.tplogdir;.u.icounts[t]+:count first x]; $[.z.m.batchms>0; From 389f56b259a234eb107f2c9439b456d9cec8d924 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Thu, 22 Oct 2026 16:00:36 +0100 Subject: [PATCH 28/39] di.torq.proc.tickerlogreplay: upd and save down hooks from config, as wdb and rdb upd, savedownmanipulation and postreplay are read from the config dict in init, so a launched process can set them in its .q settings file. Legacy reads them as .replay.upd / .replay.savedownmanipulation / .replay.postreplay under \d .replay (TorQ tickerlogreplay.q:25,40-41); here they were read from those root names at load, before any settings file could set them. Breaking: root .replay.upd, .replay.savedownmanipulation and .replay.postreplay are no longer read. Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/tickerlogreplay/test.csv | 16 ++++++---------- di/torq/proc/tickerlogreplay/test.q | 5 ----- di/torq/proc/tickerlogreplay/tickerlogreplay.md | 13 ++++++++----- di/torq/proc/tickerlogreplay/tickerlogreplay.q | 15 +++++++-------- 4 files changed, 21 insertions(+), 28 deletions(-) diff --git a/di/torq/proc/tickerlogreplay/test.csv b/di/torq/proc/tickerlogreplay/test.csv index b1142f68d..167f6133c 100644 --- a/di/torq/proc/tickerlogreplay/test.csv +++ b/di/torq/proc/tickerlogreplay/test.csv @@ -45,18 +45,14 @@ run,0,0,q,"(fp""hdb/"",D,""/junk/"") set ([]a:1 2)",1,, true,0,0,q,"0=replay sect plain ""enlist[`clean]!enlist 0b""",1,,replay without clean true,0,0,q,"`junk in key fp[""hdb/"",D]",1,,the partition was kept -comment,,,,,,,overrides set before use +comment,,,,,,,hooks from config (a launched process sets them in its settings file) run,0,0,q,clearhdb[],1,, -true,0,0,q,"0=replayp[(""`.replay.savedownmanipulation set enlist[`trade]!enlist {update price:2*price from x}"";""`.replay.postreplay set {[d;p] ("",hp[""post""],"") set p}"");sect plain ""()!()""]",1,,replay with savedownmanipulation and postreplay -true,0,0,q,2 4 8f~asc hdb[D;`trade]`price,1,,the manipulation ran before saving -true,0,0,q,"(""D""$D)~get fp""post""",1,,postreplay ran with the partition +true,0,0,q,"0=replay sect plain ""(`savedownmanipulation`postreplay!(enlist[`trade]!enlist {update price:2*price from x};{[d;p] ("",hp[""post""],"") set p}))""",1,,replay with savedownmanipulation and postreplay in config +true,0,0,q,2 4 8f~asc hdb[D;`trade]`price,1,,the config savedownmanipulation is applied once through di.dbwrite +true,0,0,q,"(""D""$D)~get fp""post""",1,,the config postreplay is called with the partition run,0,0,q,clearhdb[],1,, -true,0,0,q,"0=replayi[(""`.replay.savedownmanipulation set enlist[`trade]!enlist {update price:2*price from x}"";""`.replay.postreplay set {[d;p] ("",hp[""post2""],"") set p}"");sect plain ""()!()""]",1,,hooks set after the module loads and before init (read at init) -true,0,0,q,2 4 8f~asc hdb[D;`trade]`price,1,,the .replay.savedownmanipulation hook is applied once through di.dbwrite -true,0,0,q,"(""D""$D)~get fp""post2""",1,,the .replay.postreplay hook is called with the partition -run,0,0,q,clearhdb[],1,, -true,0,0,q,"0=replayp[enlist""`.replay.upd set {[t;x] if[t~`trade;insert[t;x]]}"";sect plain ""()!()""]",1,,replay with an upd override -true,0,0,q,(3;0)~(rows[D;`trade];rows[D;`quote]),1,,the upd override decided what was inserted +true,0,0,q,"0=replay sect plain ""(enlist[`upd]!enlist {[t;x] if[t~`trade;insert[t;x]]})""",1,,replay with an upd in config +true,0,0,q,(3;0)~(rows[D;`trade];rows[D;`quote]),1,,the config upd decided what was inserted (the default would insert quote too) comment,,,,,,,checks at init true,0,0,q,"3=replay ""()!()""",1,,init without the settings exits 3 diff --git a/di/torq/proc/tickerlogreplay/test.q b/di/torq/proc/tickerlogreplay/test.q index b62f24a05..63ceb8cc4 100644 --- a/di/torq/proc/tickerlogreplay/test.q +++ b/di/torq/proc/tickerlogreplay/test.q @@ -16,11 +16,6 @@ replayp:{[pre;cfg] runq( "@[r.init[;enlist[`log]!enlist lg];",cfg,";{-1 \"ERR \",x;exit 3}]"; "exit 0"))} replay:replayp[()] -/ as replayp, but the q lines run after the module is loaded and before init, as a user setting hooks would -replayi:{[post;cfg] runq( - enlist["lg:`info`warn`error!({[c;m] -1 \"I \",string[c],\": \",m};{[c;m] -1 \"W \",string[c],\": \",m};{[c;m] -1 \"E \",string[c],\": \",m})"],(enlist"r:use`di.torq.proc.tickerlogreplay"),post,( - "@[r.init[;enlist[`log]!enlist lg];",cfg,";{-1 \"ERR \",x;exit 3}]"; - "exit 0"))} / replay settings for the plain log, with overrides plain:{[x] "(`schemafile`hdbdir`tplogfile`segmentedmode!(`$\"",FIXDIR,"/schema.q\";`$\":",FIXDIR,"/hdb\";`$\":",FIXDIR,"/tplog",D,"\";0b)),",x} sect:{[x] "((use`di.torq.config)[`parsefile] \"di/torq/settings/tickerlogreplay.q\"),",x} diff --git a/di/torq/proc/tickerlogreplay/tickerlogreplay.md b/di/torq/proc/tickerlogreplay/tickerlogreplay.md index 4c361ef1e..b089462ce 100644 --- a/di/torq/proc/tickerlogreplay/tickerlogreplay.md +++ b/di/torq/proc/tickerlogreplay/tickerlogreplay.md @@ -7,8 +7,8 @@ at the end, or partition to a temporary directory and merge on disk. ## Files -`init.q` loads `tickerlogreplay.q`: the module `init` and the `.replay.upd` hook. `init` reads the -`.replay.savedownmanipulation` / `.replay.postreplay` hooks and hands them to di.dbwrite, which applies them. +`init.q` loads `tickerlogreplay.q`. `init` reads the `upd`, `savedownmanipulation` and `postreplay` hooks from +config (so a launched process sets them in its settings file) and hands the save down hooks to di.dbwrite. `sort.csv` is the default sort config. ## Surface @@ -16,12 +16,15 @@ at the end, or partition to a temporary directory and merge on disk. | Name | What | |---|---| | `init[config;deps]` | applies the settings, checks them, loads the schema, and replays if `autoreplay` | -| `.replay.upd[t;x]` | inserts a replayed message; set it before `use` to change how messages are applied | -| `.replay.savedownmanipulation` / `.replay.postreplay[d;p]` | table!function applied before saving / called after each log is saved, through di.dbwrite; set them before `init` | ## Settings -Every setting is required in `config` and kept module-private; `di/torq/settings/tickerlogreplay.q` declares +Optional hooks, in config (a `.q` settings file, since TOML can't hold functions): `upd` `{[t;x]}` applies each +replayed message (default insert); `savedownmanipulation` is table!function applied before saving; +`postreplay` `{[d;p]}` is called after each log is saved. Before this they were root `.replay.upd`, +`.replay.savedownmanipulation` and `.replay.postreplay`, set before `use`; those are no longer read. + +Every other setting is required in `config` and kept module-private; `di/torq/settings/tickerlogreplay.q` declares them all with these defaults: | Key | Default | diff --git a/di/torq/proc/tickerlogreplay/tickerlogreplay.q b/di/torq/proc/tickerlogreplay/tickerlogreplay.q index 489b29d81..12a9ad620 100644 --- a/di/torq/proc/tickerlogreplay/tickerlogreplay.q +++ b/di/torq/proc/tickerlogreplay/tickerlogreplay.q @@ -17,9 +17,9 @@ init:{[config;deps] .z.m.log:deps`log; .z.m.tplog:use`di.tplog; .z.m.dbw:use`di.dbwrite; - / the save down hooks from .replay.*, set before init, defaulting as TorQ's tickerlogreplay.q:40-41, go to di.dbwrite - sdm:@[value;`.replay.savedownmanipulation;()!()]; - pr:@[value;`.replay.postreplay;{{[d;p]}}]; + / the save down hooks from config go to di.dbwrite + sdm:$[`savedownmanipulation in key config;config`savedownmanipulation;()!()]; + pr:$[`postreplay in key config;config`postreplay;{[d;p]}]; .z.m.dbw.init `log`savedownmanipulation`postreplay!(deps`log;sdm;pr); .z.m.os:use`di.os; / all settings required @@ -76,6 +76,8 @@ init:{[config;deps] @[system;"l ",string schemafile;{ex[`replayinit;"failed to load replay file ",(string x)," - ",y;2]}[schemafile]]; .z.m.log[`info][`replayinit;"hdb directory is set to ",string .z.m.hdbdir:hsym hdbdir]; .z.m.log[`info][`replayinit;"tempdir directory is set to ",string .z.m.tempdir:hsym tempdir]; + / the replay upd from config, default insert + .z.m.realupd:applyupd $[`upd in key config;config`upd;{[t;x] insert[t;x]}]; / filter on the table list if[(not tablelist~enlist `all) and not segmentedmode; .z.m.realupd:{[f;t;x] if[t in tablestoreplay; f[t;x]]}[realupd]]; / chunked saves @@ -85,9 +87,6 @@ init:{[config;deps] if[autoreplay;initandrun[]]; }; -/ default upd; set .replay.upd before use to override -.replay.upd:@[value;`.replay.upd;{{[t;x] insert[t;x]}}] - // the path to the table to save pathtotable:{[h;p;t] `$(string .Q.par[h;partitiontype$p;t]),"/"} @@ -222,12 +221,12 @@ readintofifo:{[filename] }; // upd functions down here -realupd:{[f;t;x] +applyupd:{[f;t;x] // increment the tablecounts .z.m.tablecounts[t]+:count first x; // run the supplied function in the error trap .[f;(t;x);{[t;x;e] .z.m.errorcounts[t]+:count first x}[t;x]]; - }[.replay.upd] + } initialupd:{[t;x] // spin through the first X messages From 4f150ed30e88b58f0c56662babbc3f3d98ac2382 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Thu, 22 Oct 2026 16:56:34 +0100 Subject: [PATCH 29/39] di.torq.proc.wdb: doc, sortcsv fallback is di.dbwrite's sym-then-time p# default Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/wdb/wdb.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/di/torq/proc/wdb/wdb.md b/di/torq/proc/wdb/wdb.md index 8743add71..e7106fece 100644 --- a/di/torq/proc/wdb/wdb.md +++ b/di/torq/proc/wdb/wdb.md @@ -67,7 +67,7 @@ permitreload = true # false: sort and move, but leave downstream a # subscribeto / subscribesyms omitted -> all tables, all syms # ignorelist omitted -> `heartbeat`logmsg (not written) # numtab (optional) -> per-table row thresholds; overrides numrows for those tables -# sortcsv (optional) -> di.dbwrite sort/attribute config; else $TORQXAPPCONFIG/sort.csv if present, else time asc +# sortcsv (optional) -> di.dbwrite sort/attribute config; else $TORQXAPPCONFIG/sort.csv if present, else the di.dbwrite default (sort by sym then time, p# on sym) ``` The schema comes from the **tickerplant**, not a local `database.q`: `.sub.subscribe` finds the From f628a50d0cf5b3fe17f9c54b92c21697dab4b1d9 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Thu, 22 Oct 2026 16:56:34 +0100 Subject: [PATCH 30/39] di.dbwrite: doc, built-in default sort is p# on sym, sorted by sym then time Co-Authored-By: Claude Opus 5.5 --- di/dbwrite/dbwrite.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/di/dbwrite/dbwrite.md b/di/dbwrite/dbwrite.md index c0cec3a5d..e55132248 100644 --- a/di/dbwrite/dbwrite.md +++ b/di/dbwrite/dbwrite.md @@ -2,7 +2,7 @@ Write, sort, and attribute utilities for kdb+ processes that persist data to disk (rdb, wdb, tickerlogreplay). -A **config table** (`tabname`,`att`,`column`,`sort`) drives which columns are sorted and which attributes are applied per table. Load it once with `readcsv` (from a CSV) or `setconfig` (from an in-memory table); `sort` and `savedown` read from module state automatically. A table with no explicit entry falls back to a `default` row; if no config has been loaded, the built-in default (sort every table by `time` ascending) applies. +A **config table** (`tabname`,`att`,`column`,`sort`) drives which columns are sorted and which attributes are applied per table. Load it once with `readcsv` (from a CSV) or `setconfig` (from an in-memory table); `sort` and `savedown` read from module state automatically. A table with no explicit entry falls back to a `default` row; if no config has been loaded, the built-in default (`p#` on `sym`, sorted by `sym` then `time`) applies. --- From 2143e1070c8bdd33c80fef6ba1df7c24afd48486 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Fri, 23 Oct 2026 15:50:32 +0100 Subject: [PATCH 31/39] di.torq.proc.tickerplant: rolltimezone/datatimezone/rolltimeoffset reach di.eodtime intact eoddeps amended keys into enlist[`log]!enlist logdep, whose values are a one-row table, so each added value became a row of the log dict and di.eodtime's init threw 'type: any timezone or roll-offset setting stopped the tickerplant starting. Build the extra keys with joins and join log first, as segmentedtp.q:29. From #128. Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/tickerplant/test.csv | 4 ++++ di/torq/proc/tickerplant/test.q | 1 + di/torq/proc/tickerplant/tickerplant.q | 11 ++++++----- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/di/torq/proc/tickerplant/test.csv b/di/torq/proc/tickerplant/test.csv index c8cdc712c..cad8f2cca 100644 --- a/di/torq/proc/tickerplant/test.csv +++ b/di/torq/proc/tickerplant/test.csv @@ -75,5 +75,9 @@ true,0,0,q,(1+R2 0)=R2 1,1,,batched unstamped: the upd rolled the day before log true,0,0,q,1=R2 2,1,,batched unstamped: the row went to the next day's log run,0,0,q,R3:pastroll["batchlog";1b],1,,a feed-stamped upd 1s after the next roll true,0,0,q,(R3 0)=R3 1,1,,batched feed-stamped: no roll in upd (as TorQ: the check is inside its unstamped branch); tpeodcheck rolls it +run,0,0,q,doinit[tzcfg[]],1,,init with rolltimezone datatimezone and rolltimeoffset set +true,0,0,q,(tzcfg[]`rolltimezone)~(use`di.eodtime)[`getrolltimezone][],1,,rolltimezone reaches di.eodtime as a symbol +true,0,0,q,(tzcfg[]`datatimezone)~(use`di.eodtime)[`getdatatimezone][],1,,datatimezone reaches di.eodtime as a symbol +true,0,0,q,0D01~(use`di.eodtime)[`getrolltimeoffset][],1,,rolltimeoffset reaches di.eodtime as a timespan after,0,0,q,teardownfixture[],1,,remove the temp fixture dirs diff --git a/di/torq/proc/tickerplant/test.q b/di/torq/proc/tickerplant/test.q index c46b66d16..f835afbbb 100644 --- a/di/torq/proc/tickerplant/test.q +++ b/di/torq/proc/tickerplant/test.q @@ -47,6 +47,7 @@ badcfg:{[] enlist[`schemafile]!enlist BASE,"/badschema.q"} replaycfg:{[] `timerms`tplogdir`schemafile!(2000;BASE,"/replog";BASE,"/database.q")} subdcfg:{[] `tplogdir`schemafile!(BASE,"/subdlog";BASE,"/database.q")} subdbcfg:{[] `timerms`tplogdir`schemafile!(2000;BASE,"/subdblog";BASE,"/database.q")} +tzcfg:{[] `schemafile`rolltimezone`datatimezone`rolltimeoffset!(BASE,"/database.q";`$"America/New_York";`$"Asia/Tokyo";0D01)} / -t decides the mode, as TorQ's tickerplant.q: timerms (q's -t, stamped by di.torq) 200, null or 0 tcfg:{[ms] `timerms`schemafile!(ms;BASE,"/database.q")} diff --git a/di/torq/proc/tickerplant/tickerplant.q b/di/torq/proc/tickerplant/tickerplant.q index 840c893d4..d67ba4470 100644 --- a/di/torq/proc/tickerplant/tickerplant.q +++ b/di/torq/proc/tickerplant/tickerplant.q @@ -110,11 +110,12 @@ eodcheck:{[] if[(.z.m.eod`getnextroll)[]<.z.p;endofday[]];} / timezone values to symbols. rolltimeoffset only passed if already a timespan (TOML has / no timespan type, so a .toml settings file leaves it at eodtime's default). eoddeps:{[config;logdep] - d:enlist[`log]!enlist logdep; - if[`rolltimezone in key config;d[`rolltimezone]:astz config`rolltimezone]; - if[`datatimezone in key config;d[`datatimezone]:astz config`datatimezone]; - if[(`rolltimeoffset in key config) and -16h=type config`rolltimeoffset;d[`rolltimeoffset]:config`rolltimeoffset]; - d + d:()!(); + if[`rolltimezone in key config;d:d,enlist[`rolltimezone]!enlist astz config`rolltimezone]; + if[`datatimezone in key config;d:d,enlist[`datatimezone]!enlist astz config`datatimezone]; + if[(`rolltimeoffset in key config) and -16h=type config`rolltimeoffset;d:d,enlist[`rolltimeoffset]!enlist config`rolltimeoffset]; + / joins not amends, log last: amending a typed or log-valued dict mangles mixed values + (enlist[`log]!enlist logdep),d } init:{[config;deps] From ee3ea38862f2c4eb4bce1234d5a16d21210b8ddd Mon Sep 17 00:00:00 2001 From: alowrydi Date: Fri, 23 Oct 2026 15:50:32 +0100 Subject: [PATCH 32/39] di.torq.proc.gateway: synccallsallowed reaches di.asyncdispatch as a boolean adcfg amended synccallsallowed into enlist[`log]!enlist deps`log, whose values are a one-row table, so it arrived as `info`warn`error!111b and asyncdispatch's syncexec check would throw 'type. Join it, log first, as segmentedtp.q:29. From #128. Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/gateway/gateway.q | 7 ++++--- di/torq/proc/gateway/test.csv | 4 ++++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/di/torq/proc/gateway/gateway.q b/di/torq/proc/gateway/gateway.q index b25c39a33..f6dbfe444 100644 --- a/di/torq/proc/gateway/gateway.q +++ b/di/torq/proc/gateway/gateway.q @@ -101,9 +101,10 @@ init:{[config;deps] / callbacks at root .gw.* and tell it to reply to those names (baked into the shipped executor by / the vendor patch, so backends need no cooperating code). .z.m.ad:use`di.asyncdispatch; - adcfg:enlist[`log]!enlist deps`log; - if[`synccallsallowed in key config;adcfg[`synccallsallowed]:`boolean$config`synccallsallowed]; - (.z.m.ad`init)[adcfg]; + adcfg:()!(); + if[`synccallsallowed in key config;adcfg:adcfg,enlist[`synccallsallowed]!enlist`boolean$config`synccallsallowed]; + / joins not amends, log last: amending a log-valued dict makes each new value a row of the log dict + (.z.m.ad`init)[(enlist[`log]!enlist deps`log),adcfg]; / NB: param is `sel`, NOT `ss` - `ss` is the built-in string-search function and q would / resolve ss[...] to the builtin instead of the projected serverselect dict (throws 'match). (.z.m.ad`setavailableservers)[{[sel;excludeinuse] select handle,servertype from sel[`getserverstable][] where active}[.z.m.srvsel]]; diff --git a/di/torq/proc/gateway/test.csv b/di/torq/proc/gateway/test.csv index 912307df3..e3de26cbe 100644 --- a/di/torq/proc/gateway/test.csv +++ b/di/torq/proc/gateway/test.csv @@ -12,6 +12,10 @@ run,0,0,q,gjobs:(`symbol$())!`short$(),1,,record of timer job modes run,0,0,q,"gdeps:`log`timer`handlers`servers!(mlog;`addjob`deletejobs!({[id;f;p;per;md;o] gjobs[id]:`short$md;};{[x]});`register`remove`list!({[ev;ph;nm;pri;fn]};{[ev;ph;nm]};{[ev]});`startup`getservers!({[c]};{[t] ([]w:`int$();proctype:`$();procname:`$();hpup:`$())}))",1,,mock deps with a recording timer and no backends run,0,0,q,gw.init[()!();gdeps],1,,init the gateway true,0,0,q,all 3h=gjobs`gwtimeout`gwrmqueries`gwrminactive,1,,query housekeeping jobs reschedule from the end of the previous run (mode 3) as TorQ's .timer.repeat does +run,0,0,q,gw.init[(enlist`synccallsallowed)!enlist 1b;gdeps],1,,init with synccallsallowed set +true,0,0,q,1b~.m.di.0asyncdispatch.synccallsallowed,1,,synccallsallowed reaches di.asyncdispatch as a boolean +run,0,0,q,gw.init[(enlist`synccallsallowed)!enlist 0b;gdeps],1,,init with synccallsallowed off +true,0,0,q,0b~.m.di.0asyncdispatch.synccallsallowed,1,,and back to the default before,0,0,q,system "l di/torq/proc/gateway/test.q",1,,mock log/timer/handlers/servers deps before,0,0,q,hdbonly[],1,,only the hdb is connected when the gateway starts From 430fc1f3b1367de7368a67ca38028114fb33a68f Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 27 Oct 2026 11:23:55 +0000 Subject: [PATCH 33/39] di.torq.proc.gateway: fixture rows no longer depend on the time of day The fixture stamped today's row at 10:00 UTC, so a getdata over midnight..now excluded it before 10:00 and the suite failed. Rows are now at midnight. Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/gateway/test.q | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/di/torq/proc/gateway/test.q b/di/torq/proc/gateway/test.q index 2f4a3ab50..b638134d8 100644 --- a/di/torq/proc/gateway/test.q +++ b/di/torq/proc/gateway/test.q @@ -61,7 +61,7 @@ gwspawn:{[script;name] gwportline:{[name] "(hsym`$\"",GWDIR,"/",name,".port\") 0: enlist string system\"p\"; GWNAME:`",name,";"}; startgwfixture:{[] system "rm -rf ",GWDIR; system "mkdir -p ",GWDIR; - {(hsym`$GWDIR,"/",x,".q") 0: ("trade:([]date:2#.z.d-1 0;time:(.z.d-1;.z.d)+0D10;sym:`a`b;price:1 2f);";"SENT:0; .z.ps:{`SENT set SENT+1; value x};";gwportline x)} each ("rdb1";"hdb1"); + {(hsym`$GWDIR,"/",x,".q") 0: ("trade:([]date:2#.z.d-1 0;time:`timestamp$.z.d-1 0;sym:`a`b;price:1 2f);";"SENT:0; .z.ps:{`SENT set SENT+1; value x};";gwportline x)} each ("rdb1";"hdb1"); bp:gwspawn'[("rdb1.q";"hdb1.q");("rdb1";"hdb1")]; (hsym`$GWDIR,"/process.csv") 0: ("host,port,proctype,procname";"localhost,",(string bp 0),",rdb,rdb1";"localhost,",(string bp 1),",hdb,hdb1"); (hsym`$GWDIR,"/gw.q") 0: ( From 7b04806249882c274d03c88197a1adbbfffba0d7 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 27 Oct 2026 11:25:34 +0000 Subject: [PATCH 34/39] di.subscriptions: checksubscriptionperiod accepts TOML values Co-Authored-By: Claude Opus 5.5 --- di/subscriptions/subscriptions.q | 7 ++++++- di/subscriptions/test.csv | 4 ++++ di/subscriptions/test.q | 3 +++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/di/subscriptions/subscriptions.q b/di/subscriptions/subscriptions.q index 002c1000d..fb33c95fb 100644 --- a/di/subscriptions/subscriptions.q +++ b/di/subscriptions/subscriptions.q @@ -16,6 +16,9 @@ SUBSCRIPTIONS:([]handle:`int$();tabs:();syms:();subtime:`timestamp$()) / .sub .z.pc handler and check job are registered once registered:0b +/ a timespan, string, symbol or number of seconds as a timespan; null if not convertible +totimespan:{[x] $[-16h=type x;x;10h=abs type x;"N"$(),x;-11h=type x;"N"$string x;type[x] in -5 -6 -7h;0D00:00:01*x;0Nn]}; + init:{[config;deps] if[not `log in key deps;'"di.subscriptions: log dependency is required - see di.util.log"]; if[not `timer in key deps;'"di.subscriptions: timer dependency is required - see di.timer"]; @@ -25,7 +28,9 @@ init:{[config;deps] / all settings required if[count m:`autoreconnect`checksubscriptionperiod except key config;'"di.subscriptions: missing settings: ",", " sv string m]; .z.m.autoreconnect:config`autoreconnect; - .z.m.checksubscriptionperiod:(not @[value;`.proc.lowpowermode;0b])*config`checksubscriptionperiod; + p:totimespan config`checksubscriptionperiod; + if[null p;'"di.subscriptions: checksubscriptionperiod must be a timespan"]; + .z.m.checksubscriptionperiod:(not @[value;`.proc.lowpowermode;0b])*p; if[not .z.m.registered; (deps[`handlers]`register)[`.z.pc;`;`sub;0j;pc[::;]]; if[checksubscriptionperiod>0;(deps[`timer]`addjob)[`checksubscriptions;checksubscriptions;();checksubscriptionperiod;1;()!()]]; diff --git a/di/subscriptions/test.csv b/di/subscriptions/test.csv index 43cb1761c..52be2c0c4 100644 --- a/di/subscriptions/test.csv +++ b/di/subscriptions/test.csv @@ -54,5 +54,9 @@ run,0,0,q,".servers.enabled:1b;.servers.connectcustom:{[r]};.m.di.0subscriptions run,0,0,q,".sub.subscribe[`trade;`;0b;0b;peerproc[]]",1,,subscribe true,0,0,q,.m.di.0subscriptions.reconnectinit,1,,subscribe wrapped .servers.connectcustom for autoreconnect once true,0,0,q,10b~pcclosecheck[],1,,closing a subscribed handle marks it inactive through .z.pc at once (no checksubscriptions run) +comment,,,,,,,checksubscriptionperiod from TOML values +true,0,0,q,"(enlist(`checksubscriptions;0D00:00:10;1))~periodinit ""0D00:00:10""",1,,a string period registers a timespan job +true,0,0,q,(enlist(`checksubscriptions;0D00:00:10;1))~periodinit 10,1,,a number of seconds registers a timespan job +fail,0,0,q,"periodinit ""junk""",1,,an unparseable period errors after,0,0,q,teardownfixture[],1,,remove the temp log dir diff --git a/di/subscriptions/test.q b/di/subscriptions/test.q index 8a70214ef..30decdf4d 100644 --- a/di/subscriptions/test.q +++ b/di/subscriptions/test.q @@ -82,4 +82,7 @@ pcclosecheck:{[] (a;b) } +/ a fresh init with checksubscriptionperiod p; returns the timer jobs it registered +periodinit:{[p] .m.di.0subscriptions.registered:0b; delete from `timercalls; sub.init[subcfg enlist[`checksubscriptionperiod]!enlist p;deps[]]; flip value flip timercalls} + teardownfixture:{[] @[{(neg x)"exit 0";(neg x)[]};tph;()]; system "sleep 0.3"; system "rm -rf ",BASE; } From 36414a9a5e88b45d36d68d09cf247c31f6138a8e Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 27 Oct 2026 11:27:03 +0000 Subject: [PATCH 35/39] di.torq.proc.tickerplant: rolltimeoffset accepts TOML values Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/tickerplant/test.csv | 5 +++++ di/torq/proc/tickerplant/test.q | 2 ++ di/torq/proc/tickerplant/tickerplant.md | 6 +++--- di/torq/proc/tickerplant/tickerplant.q | 12 +++++++----- 4 files changed, 17 insertions(+), 8 deletions(-) diff --git a/di/torq/proc/tickerplant/test.csv b/di/torq/proc/tickerplant/test.csv index cad8f2cca..68b0b5f96 100644 --- a/di/torq/proc/tickerplant/test.csv +++ b/di/torq/proc/tickerplant/test.csv @@ -79,5 +79,10 @@ run,0,0,q,doinit[tzcfg[]],1,,init with rolltimezone datatimezone and rolltimeoff true,0,0,q,(tzcfg[]`rolltimezone)~(use`di.eodtime)[`getrolltimezone][],1,,rolltimezone reaches di.eodtime as a symbol true,0,0,q,(tzcfg[]`datatimezone)~(use`di.eodtime)[`getdatatimezone][],1,,datatimezone reaches di.eodtime as a symbol true,0,0,q,0D01~(use`di.eodtime)[`getrolltimeoffset][],1,,rolltimeoffset reaches di.eodtime as a timespan +run,0,0,q,doinit[tzstrcfg[]],1,,init with the eodtime settings as TOML strings +true,0,0,q,(`$"America/New_York")~(use`di.eodtime)[`getrolltimezone][],1,,a string rolltimezone reaches di.eodtime as a symbol +true,0,0,q,(`$"Asia/Tokyo")~(use`di.eodtime)[`getdatatimezone][],1,,a string datatimezone reaches di.eodtime as a symbol +true,0,0,q,0D17:00:00~(use`di.eodtime)[`getrolltimeoffset][],1,,a string rolltimeoffset reaches di.eodtime as a timespan +fail,0,0,q,"doinit tzstrcfg[],enlist[`rolltimeoffset]!enlist ""junk""",1,,an unparseable rolltimeoffset errors after,0,0,q,teardownfixture[],1,,remove the temp fixture dirs diff --git a/di/torq/proc/tickerplant/test.q b/di/torq/proc/tickerplant/test.q index f835afbbb..d64d0bb11 100644 --- a/di/torq/proc/tickerplant/test.q +++ b/di/torq/proc/tickerplant/test.q @@ -48,6 +48,8 @@ replaycfg:{[] `timerms`tplogdir`schemafile!(2000;BASE,"/replog";BASE,"/database. subdcfg:{[] `tplogdir`schemafile!(BASE,"/subdlog";BASE,"/database.q")} subdbcfg:{[] `timerms`tplogdir`schemafile!(2000;BASE,"/subdblog";BASE,"/database.q")} tzcfg:{[] `schemafile`rolltimezone`datatimezone`rolltimeoffset!(BASE,"/database.q";`$"America/New_York";`$"Asia/Tokyo";0D01)} +/ the same settings as TOML delivers them: strings +tzstrcfg:{[] `schemafile`rolltimezone`datatimezone`rolltimeoffset!(BASE,"/database.q";"America/New_York";"Asia/Tokyo";"0D17:00:00.000")} / -t decides the mode, as TorQ's tickerplant.q: timerms (q's -t, stamped by di.torq) 200, null or 0 tcfg:{[ms] `timerms`schemafile!(ms;BASE,"/database.q")} diff --git a/di/torq/proc/tickerplant/tickerplant.md b/di/torq/proc/tickerplant/tickerplant.md index 44d03540c..8fd77262a 100644 --- a/di/torq/proc/tickerplant/tickerplant.md +++ b/di/torq/proc/tickerplant/tickerplant.md @@ -30,6 +30,7 @@ ms; without `-t`, or with `-t 0`, it publishes each update immediately. tplogdir = "tplog" # relative to TORQXDATAHOME, or absolute; empty/absent = no logging schemafile = "database.q" # defaults to /database.q (schema is code, not data) # rolltimezone / datatimezone / rolltimeoffset -> passed to di.eodtime (default GMT/GMT/0) +# rolltimeoffset = "0D17:00:00" -> a timespan string or a number of seconds ``` ## Behaviour @@ -73,9 +74,8 @@ because `di.tplogmgr.open` replays via `-11!`, which executes the root-level `up - A single malformed schema table (missing `time`/`sym`) is silently skipped rather than erroring (shape-filtering trade-off vs TorQ's strict assertion, chosen for robustness against ambient root tables). -- `di.eodtime` is vendored from an unmerged PR and `rolltimeoffset` can't be expressed - in TOML (no timespan type) — GMT-midnight rolls need no offset; a non-default offset - needs a `.q` settings file for now. +- `di.eodtime` is vendored from an unmerged PR. Timezone strings become symbols and + `rolltimeoffset` strings or seconds become a timespan; an unconvertible offset errors at init. ## Testing diff --git a/di/torq/proc/tickerplant/tickerplant.q b/di/torq/proc/tickerplant/tickerplant.q index d67ba4470..b85183638 100644 --- a/di/torq/proc/tickerplant/tickerplant.q +++ b/di/torq/proc/tickerplant/tickerplant.q @@ -20,6 +20,8 @@ resolvedir:{[base;dir] / consumers coerce at point of use: config values may be symbols (.q) or strings (.toml) astz:{[x] $[11h=abs type x;x;`$x]} / to symbol (timezones) +/ a timespan, string, symbol or number of seconds as a timespan; null if not convertible +totimespan:{[x] $[-16h=type x;x;10h=abs type x;"N"$(),x;-11h=type x;"N"$string x;type[x] in -5 -6 -7h;0D00:00:01*x;0Nn]}; / feed payloads may arrive as a table or as a list of columns; normalise to columns tocols:{[x] $[98h=type x;value flip x;x]} @@ -106,15 +108,15 @@ endofday:{[] / EOD check (timer job, ~1s): roll when the next-roll time has passed. eodcheck:{[] if[(.z.m.eod`getnextroll)[]<.z.p;endofday[]];} -/ builds eodtime's merged init dict from the log dep + any tz config present, coercing -/ timezone values to symbols. rolltimeoffset only passed if already a timespan (TOML has -/ no timespan type, so a .toml settings file leaves it at eodtime's default). +/ di.eodtime init dict: timezones as symbols, rolltimeoffset as a timespan eoddeps:{[config;logdep] d:()!(); if[`rolltimezone in key config;d:d,enlist[`rolltimezone]!enlist astz config`rolltimezone]; if[`datatimezone in key config;d:d,enlist[`datatimezone]!enlist astz config`datatimezone]; - if[(`rolltimeoffset in key config) and -16h=type config`rolltimeoffset;d:d,enlist[`rolltimeoffset]!enlist config`rolltimeoffset]; - / joins not amends, log last: amending a typed or log-valued dict mangles mixed values + if[`rolltimeoffset in key config; + if[null o:totimespan config`rolltimeoffset;'"di.torq.proc.tickerplant: rolltimeoffset must be a timespan"]; + d:d,enlist[`rolltimeoffset]!enlist o]; + / log first, then the eodtime keys (enlist[`log]!enlist logdep),d } From 0639b217da08c6707171a61e2f468dd50b92b7a0 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 27 Oct 2026 11:29:28 +0000 Subject: [PATCH 36/39] di.torq.proc.segmentedtp: [eodtime] section accepts TOML values Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/segmentedtp/segmentedtp.md | 4 +++- di/torq/proc/segmentedtp/segmentedtp.q | 15 ++++++++++++++- di/torq/proc/segmentedtp/test.csv | 5 +++++ di/torq/proc/segmentedtp/test.q | 9 ++++++++- 4 files changed, 30 insertions(+), 3 deletions(-) diff --git a/di/torq/proc/segmentedtp/segmentedtp.md b/di/torq/proc/segmentedtp/segmentedtp.md index 863987b9f..419ea5338 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.md +++ b/di/torq/proc/segmentedtp/segmentedtp.md @@ -51,7 +51,9 @@ its own, and `di/torq/settings/segmentedtp.q` declares them all. `stplg` se Any of them can be given on the command line as `-stplg`, `-sctp` or `-createlogs`; an app sets only the keys it overrides. -An `eodtime` section, passed to di.eodtime's `init`: `rolltimezone`, `datatimezone`, `rolltimeoffset`. +An `eodtime` section, passed to di.eodtime's `init`: `rolltimezone`, `datatimezone`, `rolltimeoffset`. Timezone +strings become symbols and a `rolltimeoffset` string or number of seconds becomes a timespan; an unconvertible offset +errors at init. Flat: `schemafile` (required unless chained), `createlogs` (`1b`, required). diff --git a/di/torq/proc/segmentedtp/segmentedtp.q b/di/torq/proc/segmentedtp/segmentedtp.q index 69adffb8c..fd66a29da 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.q +++ b/di/torq/proc/segmentedtp/segmentedtp.q @@ -2,6 +2,19 @@ / a symbol, a string or a list of strings (TOML has no symbol type) tosym:{[x] $[type[x] in 0 10 -10h;`$x;x]}; +/ a timespan, string, symbol or number of seconds as a timespan; null if not convertible +totimespan:{[x] $[-16h=type x;x;10h=abs type x;"N"$(),x;-11h=type x;"N"$string x;type[x] in -5 -6 -7h;0D00:00:01*x;0Nn]}; + +/ di.eodtime settings from an [eodtime] section: timezones as symbols, rolltimeoffset as a timespan +eodconfig:{[s] + d:()!(); + if[`rolltimezone in key s;d:d,enlist[`rolltimezone]!enlist tosym s`rolltimezone]; + if[`datatimezone in key s;d:d,enlist[`datatimezone]!enlist tosym s`datatimezone]; + if[`rolltimeoffset in key s; + if[null o:totimespan s`rolltimeoffset;'"di.torq.proc.segmentedtp: rolltimeoffset must be a timespan"]; + d:d,enlist[`rolltimeoffset]!enlist o]; + d + }; / a relative path is under the app home (TorQ's app config dir) apppath:{[x] s:$[":"=first s:string x;1_s;s]; hsym`$$[("/"=first s) or 0=count h:getenv`TORQXAPPHOME;s;h,"/",s]}; @@ -26,7 +39,7 @@ init:{[config;deps] r[`.z.pc;`;`stpps;0j;.stpps.closesub]; .z.m.os:use`di.os; .z.m.eod:use`di.eodtime; - .z.m.eod.init[(enlist[`log]!enlist deps`log),$[`eodtime in key config;config`eodtime;()!()]]; + .z.m.eod.init[(enlist[`log]!enlist deps`log),eodconfig $[`eodtime in key config;config`eodtime;()!()]]; if[`stplgkdbtplog in key config;.stplg.kdbtplog:tosym config`stplgkdbtplog]; .stplg.multilog:tosym config`stplgmultilog; .stplg.multilogperiod:config`stplgmultilogperiod; diff --git a/di/torq/proc/segmentedtp/test.csv b/di/torq/proc/segmentedtp/test.csv index 871a0362f..31b34327f 100644 --- a/di/torq/proc/segmentedtp/test.csv +++ b/di/torq/proc/segmentedtp/test.csv @@ -16,6 +16,10 @@ true,0,0,q,"{all {[c;k] c[k]~ha ""get "",-3!` sv ``sctp,`$4_string k}[x] each k true,0,0,q,"`:/x/c.csv~.m.di.0torq.0proc.0segmentedtp.apppath`$""/x/c.csv""",1,,an absolute customcsv is kept true,0,0,q,"`:/x/c.csv~.m.di.0torq.0proc.0segmentedtp.apppath`:/x/c.csv",1,,an hsym customcsv is kept true,0,0,q,"(hsym`$$[count h:getenv`TORQXAPPHOME;h,""/"";""""],""a/c.csv"")~.m.di.0torq.0proc.0segmentedtp.apppath`$""a/c.csv""",1,,a relative customcsv is under the app home +true,0,0,q,"((`$""America/New_York"");`$""Asia/Tokyo"";0D17:00:00)~eodinit`rolltimezone`datatimezone`rolltimeoffset!(""America/New_York"";""Asia/Tokyo"";""0D17:00:00"")",1,,an [eodtime] section of strings reaches di.eodtime as symbols and a timespan +true,0,0,q,"(`GMT;`GMT;0D01)~eodinit enlist[`rolltimeoffset]!enlist""0D01:00:00""",1,,a string rolltimeoffset alone reaches di.eodtime as a timespan +true,0,0,q,"(`$""Asia/Tokyo"";`GMT;0D)~eodinit enlist[`rolltimezone]!enlist""Asia/Tokyo""",1,,a string rolltimezone alone reaches di.eodtime as a symbol +fail,0,0,q,"eodinit enlist[`rolltimeoffset]!enlist""junk""",1,,an unparseable rolltimeoffset errors true,0,0,q,"(`immediate;`singular;1D)~hb"".stplg`batchmode`multilog`multilogperiod""",1,,stplg keys override the defaults; singular rolls daily true,0,0,q,"1D~hc"".stplg.multilogperiod""",1,,tabular rolls daily true,0,0,q,"all `stpps`sctp in ha""exec name from h.list`.z.pc""",1,,.z.pc observers registered @@ -81,6 +85,7 @@ true,0,0,q,"(string hs""currlog[`trade;`logname]"") like ""*/sctp1_"",(string .z true,0,0,q,"(`parent;`stp1;`)~hp"".sctp`loggingmode`tickerplantname`subscribeto""",1,,toml-style sctp strings become symbols true,0,0,q,"(ha"".stplg.replaylog`trade"")~hp"".stplg.replaylog`trade""",1,,parent mode replays the upstream logs true,0,0,q,"hp""all (::)~/:value loghandles""",1,,parent mode writes no logs +true,0,0,q,"(`GMT;0D)~hp""e:use`di.eodtime;(e[`getrolltimezone][];e[`getrolltimeoffset][])""",1,,toml-style eodtime strings reach di.eodtime comment,,,,,,,end of period run,0,0,q,"eops:(); ha"".stplg.nextperiod:.z.p-0D00:00:01; .stplg.getnextendUTC[]; tick[]""",1,,force the period end diff --git a/di/torq/proc/segmentedtp/test.q b/di/torq/proc/segmentedtp/test.q index b475d8fed..ebdf6424d 100644 --- a/di/torq/proc/segmentedtp/test.q +++ b/di/torq/proc/segmentedtp/test.q @@ -19,7 +19,14 @@ CFGS:`a`b`c`s`p!( "`procname`schemafile`stplgkdbtplog`stplgbatchmode`stplgmultilog!(`stp2;FIXDIR,\"/schema.q\";`$FIXDIR,\"/b\";`immediate;`singular)"; "`procname`schemafile`stplgkdbtplog`stplgbatchmode`stplgmultilog!(`stp3;FIXDIR,\"/schema.q\";`$FIXDIR,\"/c\";`memorybatch;`tabular)"; "`procname`createlogs`autoreconnect`stplgkdbtplog`sctpchainedtp`sctploggingmode!(`sctp1;0b;0b;`$FIXDIR,\"/s\";1b;`create)"; - "`procname`createlogs`autoreconnect`stplgkdbtplog`sctpchainedtp`sctploggingmode`sctptickerplantname`sctpsubscribeto!(`sctp2;0b;0b;`$FIXDIR,\"/p\";1b;\"parent\";\"stp1\";\"\")") + "`procname`createlogs`autoreconnect`stplgkdbtplog`sctpchainedtp`sctploggingmode`sctptickerplantname`sctpsubscribeto`eodtime!(`sctp2;0b;0b;`$FIXDIR,\"/p\";1b;\"parent\";\"stp1\";\"\";`rolltimezone`rolltimeoffset!(\"GMT\";\"0D00:00:00\"))") + +/ di.eodtime rolltimezone, datatimezone and rolltimeoffset after init with an [eodtime] section s, as init passes it +eodinit:{[s] + e:use`di.eodtime; + e[`init](enlist[`log]!enlist`info`warn`error!3#enlist{[c;m]}),.m.di.0torq.0proc.0segmentedtp.eodconfig s; + (e[`getrolltimezone][];e[`getdatatimezone][];e[`getrolltimeoffset][]) + } setupfixture:{[] system "rm -rf ",FIXDIR; system "mkdir -p ",FIXDIR; From 885698fdb48235ee3231bfe87f838c0f96bdf5d0 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Wed, 28 Oct 2026 10:48:49 +0000 Subject: [PATCH 37/39] di.torq: find the framework checkout through QPATH when TORQXHOME is unset Co-Authored-By: Claude Opus 5.5 --- di/torq/bin/torqx.sh | 12 +++++++----- di/torq/bin/torqx_init.q | 2 +- di/torq/test.csv | 7 +++++++ di/torq/test.q | 16 +++++++++++----- di/torq/torq.md | 13 +++++++------ di/torq/torq.q | 13 +++++++++++-- 6 files changed, 44 insertions(+), 19 deletions(-) diff --git a/di/torq/bin/torqx.sh b/di/torq/bin/torqx.sh index f93ce6d2c..162640ac6 100755 --- a/di/torq/bin/torqx.sh +++ b/di/torq/bin/torqx.sh @@ -1,7 +1,7 @@ #!/bin/bash # TorqX process orchestrator - start/stop/restart/status across process.csv. # Lives once in the kdbx-modules checkout (never copied into a project), -# invoked from a project directory: cd myproject && $TORQXHOME/di/torq/bin/torqx.sh start +# invoked from a project directory: cd myproject && /di/torq/bin/torqx.sh start # # Deliberately thin: reads process.csv only to ENUMERATE rows (which processes # exist, for "start all"/"status all") and to look up a named row's proctype/port. @@ -27,7 +27,9 @@ else exit 1 fi -: "${TORQXHOME:?TORQXHOME must be set (see setenv.sh)}" +# torqx_init.q's directory: $TORQXHOME/di/torq/bin if set, else this script's own directory +TORQXBIN="${TORQXHOME:+$TORQXHOME/di/torq/bin}" +: "${TORQXBIN:=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}" : "${TORQXAPPCONFIG:?TORQXAPPCONFIG must be set (see setenv.sh)}" : "${TORQXAPPHOME:?TORQXAPPHOME must be set (see setenv.sh)}" : "${TORQXSTACKID:?TORQXSTACKID must be set (see setenv.sh)}" @@ -126,7 +128,7 @@ start_one() { return fi echo "starting $procname ($PROCTYPE)... log: $logfile" - QINIT="$TORQXHOME/di/torq/bin/torqx_init.q" nohup $QCMD \ + QINIT="$TORQXBIN/torqx_init.q" nohup $QCMD \ -torqxstackid "$TORQXSTACKID" -proctype "$PROCTYPE" -procname "$procname" \ $portarg "$@" > "$logfile" 2>&1 & disown @@ -157,7 +159,7 @@ start_one_tmux() { # a single bash -c string), then env applies the QHOME/QLIC policy above before exec'ing q. local extra="$*" tmux new-session -d -s "$sess" -c "$PWD" \ - "bash -c 'source \"$SETENV\" && exec env $uflags QINIT=\"\$TORQXHOME/di/torq/bin/torqx_init.q\" $aflags \$QCMD -torqxstackid \"\$TORQXSTACKID\" -proctype \"$PROCTYPE\" -procname \"$procname\" $portarg $extra'" + "bash -c 'source \"$SETENV\" && exec env $uflags QINIT=\"$TORQXBIN/torqx_init.q\" $aflags \$QCMD -torqxstackid \"\$TORQXSTACKID\" -proctype \"$PROCTYPE\" -procname \"$procname\" $portarg $extra'" # keep a crashed process's pane (and its stack trace) visible instead of the session vanishing tmux set-option -t "$sess" remain-on-exit on >/dev/null # tee the pane to the usual logfile so logs still exist in tmux mode @@ -207,7 +209,7 @@ After=network.target [Service] Type=simple WorkingDirectory=${TORQXAPPHOME} -ExecStart=/bin/bash -lc 'source "${TORQXAPPHOME}/setenv.sh" && exec env QINIT="\$TORQXHOME/di/torq/bin/torqx_init.q" \$QCMD -torqxstackid "\$TORQXSTACKID" -proctype ${PROCTYPE} -procname ${procname} ${portarg}' +ExecStart=/bin/bash -lc 'source "${TORQXAPPHOME}/setenv.sh" && exec env QINIT="${TORQXBIN}/torqx_init.q" \$QCMD -torqxstackid "\$TORQXSTACKID" -proctype ${PROCTYPE} -procname ${procname} ${portarg}' Restart=on-failure RestartSec=2 diff --git a/di/torq/bin/torqx_init.q b/di/torq/bin/torqx_init.q index d1403e144..47a77fb75 100644 --- a/di/torq/bin/torqx_init.q +++ b/di/torq/bin/torqx_init.q @@ -2,7 +2,7 @@ / project. Turns this q session into a TorqX process. Replaces per-process / start_.q launcher files. / - -/ Usage (via an alias such as `alias torqx='QINIT=$TORQXHOME/di/torq/bin/torqx_init.q $QCMD'`, +/ Usage (via an alias such as `alias torqx='QINIT=/di/torq/bin/torqx_init.q $QCMD'`, / see TorqX-POC/setenv.sh, or invoked directly by bin/torqx.sh): / torqx -proctype hdb -procname hdb1 (explicit identity) / torqx -p 5560 (auto-detect identity from process.csv) diff --git a/di/torq/test.csv b/di/torq/test.csv index ab7b1f592..ea5b04d80 100644 --- a/di/torq/test.csv +++ b/di/torq/test.csv @@ -5,6 +5,13 @@ before,0,0,q,setupfixture[],1,,create a temp app fixture: settings, process.csv, fail,0,0,q,tq.reqenv[`DI_TORQ_TEST_NO_SUCH_VAR],1,,reqenv on a missing env var must error +comment,,,,,,,framework home: TORQXHOME if set, else the QPATH entry holding di/torq +true,0,0,q,"REPO~withenv[`TORQXHOME;"""";{.m.di.0torq.frameworkhome[]}]",1,,without TORQXHOME the framework home is the QPATH checkout +true,0,0,q,"""/opt/torqx""~withenv[`TORQXHOME;""/opt/torqx"";{.m.di.0torq.frameworkhome[]}]",1,,TORQXHOME is used as given when set +fail,0,0,q,"withenv[`TORQXHOME;"""";{withenv[`QPATH;""/nonexistent"";{.m.di.0torq.frameworkhome[]}]}]",1,,without TORQXHOME and no QPATH entry holding di/torq it errors +true,0,0,q,"(REPO,""/di/torq/settings"")~first withenv[`TORQXHOME;"""";{.m.di.0torq.roots[]}]",1,,the builtin settings root needs no TORQXHOME +true,0,0,q,"(REPO,""/di/torq/permissions"")~first withenv[`TORQXHOME;"""";{.m.di.0torq.permissionroots[]}]",1,,the framework permissions root needs no TORQXHOME + fail,0,0,q,tq.init[`;`;()!()],1,,"auto-detect with no port set (system""p""=0) and two localhost rows in process.csv must fail as ambiguous" run,0,0,q,system "p 19999",1,,bind a port that appears nowhere in the fixture process.csv diff --git a/di/torq/test.q b/di/torq/test.q index da77fd433..b43f69932 100644 --- a/di/torq/test.q +++ b/di/torq/test.q @@ -1,7 +1,7 @@ / fixture helpers for di.torq's tests. -/ Assumes q is started with the kdbx-modules repo root as the working directory AND with -/ TORQXHOME already pointing at the real kdbx-modules checkout (di.torq's own built-in -/ settings and `builtin` registry genuinely live there - there is no faking that part). +/ Assumes q is started with the kdbx-modules repo root as the working directory and on QPATH +/ (di.torq's own built-in settings and `builtin` registry genuinely live there - there is no +/ faking that part). / TORQXAPPCONFIG and TORQXAPPHOME are both repointed at a temp fixture below to / isolate everything else (process.csv, app-level settings, a scratch hdb dir, the / custom proctype's code file) from any real app - nothing this test does touches a @@ -18,6 +18,12 @@ QBIN:first system "readlink -f /proc/",(string .z.i),"/exe" writelines:{[path;lines] (hsym `$path) 0: lines; } +/ the kdbx-modules checkout: the working directory +REPO:system "cd" + +/ f[] with env var e set to v, then e restored; f's error is re-signalled after the restore +withenv:{[e;v;f] o:getenv e; setenv[e;v]; r:@[{(1b;x[])};f;{(0b;x)}]; setenv[e;o]; $[r 0;r 1;'r 1]} + setupfixture:{[] system "rm -rf ",APPBASE; system "mkdir -p ",APPBASE,"/settings ",APPBASE,"/code/processes ",APPBASE,"/code/common ",APPBASE,"/code/",string[TESTPROCNAME]," ",APPBASE,"/code/testinst ",HDBDIR; @@ -67,14 +73,14 @@ setupfixture:{[] / a launcher that starts a real process through torqx_init.q and writes the timerms its config carried writelines[APPBASE,"/launch.q"; - ("system \"l \",getenv[`TORQXHOME],\"/di/torq/bin/torqx_init.q\";"; + ("system \"l ",REPO,"/di/torq/bin/torqx_init.q\";"; "(hsym`$getenv[`TORQXAPPHOME],\"/timerms.txt\") 0: enlist .Q.s1 .k4unittestproc.capturedconfig`timerms;"; "exit 0")]; } / a launcher that starts a real process through torqx_init.q and writes what -parentproctype changed pptlauncher:{[] writelines[APPBASE,"/launchppt.q"; - ("system \"l \",getenv[`TORQXHOME],\"/di/torq/bin/torqx_init.q\";"; + ("system \"l ",REPO,"/di/torq/bin/torqx_init.q\";"; "c:.k4unittestproc.capturedconfig;"; "(hsym`$getenv[`TORQXAPPHOME],\"/ppt.txt\") 0: enlist .Q.s1 (c`parentproctype;$[`pptonly in key c;c`pptonly;0N];c`widget;@[value;`PPTCODE;0b];@[value;`PPTBEFOREPROC;0N]);"; "exit 0")]} diff --git a/di/torq/torq.md b/di/torq/torq.md index a2c8ffbb2..37c46777c 100644 --- a/di/torq/torq.md +++ b/di/torq/torq.md @@ -51,18 +51,18 @@ nothing at all). ### Environment variables -Three independent, explicitly-set env vars - not derived from each other: +`TORQXHOME` is optional; the app sets the other two: | var | what it points at | used for | |---|---|---| -| `TORQXHOME` | the `di.torq`/framework checkout | builtin settings root (`$TORQXHOME/di/torq/settings`) | +| `TORQXHOME` | the `di.torq`/framework checkout; when unset, the `QPATH` entry that holds `di/torq` | builtin settings root (`/di/torq/settings`) and framework permissions root (`/di/torq/permissions`) | | `TORQXAPPCONFIG` | the app's `appconfig/` directory | app settings root (`$TORQXAPPCONFIG/settings`) and `process.csv` | | `TORQXAPPHOME` | the app's own project root | `code/processes/{proctype}.q` (custom proctypes), and where `di.torq.proc.hdb`'s relative `dir:` settings resolve against | ### Config cascade `roots[]` builds the two roots `di.torq.config.cascade` needs -(`` `$TORQXHOME/di/torq/settings ``, `` `$TORQXAPPCONFIG/settings ``); `init` calls +(`` `/di/torq/settings ``, `` `$TORQXAPPCONFIG/settings ``); `init` calls `` (cc`cascade)[r 0;r 1;proctype;procname] `` and then adds the resolved `proctype`/`procname` into the result itself, so any module (or anything it calls) can find out who it is just by looking at its own `config` dict - no global to reach @@ -351,9 +351,10 @@ freshly-started process. tmux mode is for local development; production stays on module's tests, and `di.torq`'s actual job is wiring them together correctly, which mocking them away wouldn't exercise. Only `TORQXAPPCONFIG`/`TORQXAPPHOME` are repointed at a temp fixture (a scratch settings tree, `process.csv`, and a throwaway -custom proctype file that publishes its own `run` hook to assert on) - `TORQXHOME` -stays real, since `di.torq`'s own built-in settings and registry genuinely live -there. Covers: `reqenv` erroring on a missing var, both auto-detect failure modes +custom proctype file that publishes its own `run` hook to assert on); the built-in +settings and registry are the checkout's own, found through `QPATH`, so the suite needs +no env vars set. Covers: `reqenv` erroring on a missing var, the framework home with and +without `TORQXHOME`, both auto-detect failure modes (no match, ambiguous), explicit-identity init for both a built-in and a custom proctype, config-cascade/deps reaching the started process type correctly, the `.run` hook firing by default and being skipped when `norun` is set, and successful diff --git a/di/torq/torq.q b/di/torq/torq.q index 5b10a5d27..3eebf17c0 100644 --- a/di/torq/torq.q +++ b/di/torq/torq.q @@ -12,8 +12,17 @@ reqenv:{[e] v } +/ the kdbx-modules checkout holding di.torq: TORQXHOME if set, else the QPATH entry that holds di/torq +frameworkhome:{[] + if[count h:getenv`TORQXHOME;:h]; + d:{$["/"=first x;x;(system "cd"),"/",x]} each ":" vs getenv`QPATH; + d:d where {not ()~key hsym `$x,"/di/torq/init.q"} each d; + if[not count d;'"di.torq: TORQXHOME is not set and no QPATH entry holds di/torq"]; + first d + } + roots:{ - builtinroot:reqenv[`TORQXHOME],"/di/torq/settings"; + builtinroot:frameworkhome[],"/di/torq/settings"; approot:reqenv[`TORQXAPPCONFIG],"/settings"; (builtinroot;approot) } @@ -222,7 +231,7 @@ initpermissions:{[config;deps] / permissions cascade. The rules are code (a paramcheck is a lambda), so they cannot be settings. / Loaded with `system "l"` at root, like loadappcodedir, so a rule file is an ordinary caller. permissionroots:{[] - (reqenv[`TORQXHOME],"/di/torq/permissions";reqenv[`TORQXAPPCONFIG],"/permissions") + (frameworkhome[],"/di/torq/permissions";reqenv[`TORQXAPPCONFIG],"/permissions") } loadpermissionrules:{[lg;config;proctype;procname] From 276cb89e43ae8fd375c0df032759a7cd25cbb88b Mon Sep 17 00:00:00 2001 From: alowrydi Date: Wed, 28 Oct 2026 11:06:55 +0000 Subject: [PATCH 38/39] di.torq: frameworkhome searches where use does, skipping empty QPATH entries Co-Authored-By: Claude Opus 5.5 --- di/torq/test.csv | 3 +++ di/torq/torq.md | 2 +- di/torq/torq.q | 9 ++++++--- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/di/torq/test.csv b/di/torq/test.csv index ea5b04d80..d14d8c814 100644 --- a/di/torq/test.csv +++ b/di/torq/test.csv @@ -9,6 +9,9 @@ comment,,,,,,,framework home: TORQXHOME if set, else the QPATH entry holding di/ true,0,0,q,"REPO~withenv[`TORQXHOME;"""";{.m.di.0torq.frameworkhome[]}]",1,,without TORQXHOME the framework home is the QPATH checkout true,0,0,q,"""/opt/torqx""~withenv[`TORQXHOME;""/opt/torqx"";{.m.di.0torq.frameworkhome[]}]",1,,TORQXHOME is used as given when set fail,0,0,q,"withenv[`TORQXHOME;"""";{withenv[`QPATH;""/nonexistent"";{.m.di.0torq.frameworkhome[]}]}]",1,,without TORQXHOME and no QPATH entry holding di/torq it errors +fail,0,0,q,"withenv[`TORQXHOME;"""";{withenv[`QPATH;""/nonexistent:"";{.m.di.0torq.frameworkhome[]}]}]",1,,an empty QPATH entry is not the working directory +run,0,0,q,"system ""mkdir -p "",APPBASE,""/qhome/mod/di/torq""; (hsym`$APPBASE,""/qhome/mod/di/torq/init.q"") 0: ()",1,,a QHOME holding di/torq under mod +true,0,0,q,"(APPBASE,""/qhome/mod"")~withenv[`TORQXHOME;"""";{withenv[`QHOME;APPBASE,""/qhome"";{withenv[`QPATH;"""";{.m.di.0torq.frameworkhome[]}]}]}]",1,,without QPATH the framework home is $QHOME/mod, where use searches true,0,0,q,"(REPO,""/di/torq/settings"")~first withenv[`TORQXHOME;"""";{.m.di.0torq.roots[]}]",1,,the builtin settings root needs no TORQXHOME true,0,0,q,"(REPO,""/di/torq/permissions"")~first withenv[`TORQXHOME;"""";{.m.di.0torq.permissionroots[]}]",1,,the framework permissions root needs no TORQXHOME diff --git a/di/torq/torq.md b/di/torq/torq.md index 37c46777c..b50f8773b 100644 --- a/di/torq/torq.md +++ b/di/torq/torq.md @@ -55,7 +55,7 @@ nothing at all). | var | what it points at | used for | |---|---|---| -| `TORQXHOME` | the `di.torq`/framework checkout; when unset, the `QPATH` entry that holds `di/torq` | builtin settings root (`/di/torq/settings`) and framework permissions root (`/di/torq/permissions`) | +| `TORQXHOME` | the `di.torq`/framework checkout; when unset, the module search path entry that holds `di/torq` (`QPATH`'s non-empty entries, or `$QHOME/mod` when it has none, as `use` searches) | builtin settings root (`/di/torq/settings`) and framework permissions root (`/di/torq/permissions`) | | `TORQXAPPCONFIG` | the app's `appconfig/` directory | app settings root (`$TORQXAPPCONFIG/settings`) and `process.csv` | | `TORQXAPPHOME` | the app's own project root | `code/processes/{proctype}.q` (custom proctypes), and where `di.torq.proc.hdb`'s relative `dir:` settings resolve against | diff --git a/di/torq/torq.q b/di/torq/torq.q index 3eebf17c0..431489e44 100644 --- a/di/torq/torq.q +++ b/di/torq/torq.q @@ -12,12 +12,15 @@ reqenv:{[e] v } -/ the kdbx-modules checkout holding di.torq: TORQXHOME if set, else the QPATH entry that holds di/torq +/ the kdbx-modules checkout holding di.torq: TORQXHOME if set, else the module search path entry that holds di/torq frameworkhome:{[] if[count h:getenv`TORQXHOME;:h]; - d:{$["/"=first x;x;(system "cd"),"/",x]} each ":" vs getenv`QPATH; + / the module search path, as use searches it: QPATH's non-empty entries, or $QHOME/mod when it has none + p:":" vs getenv`QPATH; + p:$[count p:p where 0 Date: Wed, 28 Oct 2026 11:17:23 +0000 Subject: [PATCH 39/39] di.torq: frameworkhome skips the $QHOME/mod fallback when QHOME is unset and names what it searched Co-Authored-By: Claude Opus 5.5 --- di/torq/test.csv | 2 ++ di/torq/torq.md | 2 +- di/torq/torq.q | 5 +++-- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/di/torq/test.csv b/di/torq/test.csv index d14d8c814..e185afb7a 100644 --- a/di/torq/test.csv +++ b/di/torq/test.csv @@ -12,6 +12,8 @@ fail,0,0,q,"withenv[`TORQXHOME;"""";{withenv[`QPATH;""/nonexistent"";{.m.di.0tor fail,0,0,q,"withenv[`TORQXHOME;"""";{withenv[`QPATH;""/nonexistent:"";{.m.di.0torq.frameworkhome[]}]}]",1,,an empty QPATH entry is not the working directory run,0,0,q,"system ""mkdir -p "",APPBASE,""/qhome/mod/di/torq""; (hsym`$APPBASE,""/qhome/mod/di/torq/init.q"") 0: ()",1,,a QHOME holding di/torq under mod true,0,0,q,"(APPBASE,""/qhome/mod"")~withenv[`TORQXHOME;"""";{withenv[`QHOME;APPBASE,""/qhome"";{withenv[`QPATH;"""";{.m.di.0torq.frameworkhome[]}]}]}]",1,,without QPATH the framework home is $QHOME/mod, where use searches +true,0,0,q,"@[{withenv[`TORQXHOME;"""";{withenv[`QPATH;"""";{withenv[`QHOME;"""";{.m.di.0torq.frameworkhome[]}]}]}]};::;{x}] like ""*QPATH and QHOME are unset*""",1,,without QPATH or QHOME the error says so rather than searching /mod +true,0,0,q,"@[{withenv[`TORQXHOME;"""";{withenv[`QPATH;""/nonexistent"";{.m.di.0torq.frameworkhome[]}]}]};::;{x}] like ""*searched: /nonexistent*""",1,,the error names the entries searched true,0,0,q,"(REPO,""/di/torq/settings"")~first withenv[`TORQXHOME;"""";{.m.di.0torq.roots[]}]",1,,the builtin settings root needs no TORQXHOME true,0,0,q,"(REPO,""/di/torq/permissions"")~first withenv[`TORQXHOME;"""";{.m.di.0torq.permissionroots[]}]",1,,the framework permissions root needs no TORQXHOME diff --git a/di/torq/torq.md b/di/torq/torq.md index b50f8773b..76527af31 100644 --- a/di/torq/torq.md +++ b/di/torq/torq.md @@ -55,7 +55,7 @@ nothing at all). | var | what it points at | used for | |---|---|---| -| `TORQXHOME` | the `di.torq`/framework checkout; when unset, the module search path entry that holds `di/torq` (`QPATH`'s non-empty entries, or `$QHOME/mod` when it has none, as `use` searches) | builtin settings root (`/di/torq/settings`) and framework permissions root (`/di/torq/permissions`) | +| `TORQXHOME` | the `di.torq`/framework checkout; when unset, the module search path entry that holds `di/torq` (`QPATH`'s non-empty entries, or `$QHOME/mod` when it has none, as `use` searches; with both unset, set `TORQXHOME`) | builtin settings root (`/di/torq/settings`) and framework permissions root (`/di/torq/permissions`) | | `TORQXAPPCONFIG` | the app's `appconfig/` directory | app settings root (`$TORQXAPPCONFIG/settings`) and `process.csv` | | `TORQXAPPHOME` | the app's own project root | `code/processes/{proctype}.q` (custom proctypes), and where `di.torq.proc.hdb`'s relative `dir:` settings resolve against | diff --git a/di/torq/torq.q b/di/torq/torq.q index 431489e44..44e93d88a 100644 --- a/di/torq/torq.q +++ b/di/torq/torq.q @@ -17,10 +17,11 @@ frameworkhome:{[] if[count h:getenv`TORQXHOME;:h]; / the module search path, as use searches it: QPATH's non-empty entries, or $QHOME/mod when it has none p:":" vs getenv`QPATH; - p:$[count p:p where 0