Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
273 changes: 67 additions & 206 deletions di/torq/proc/idb/idb.md

Large diffs are not rendered by default.

150 changes: 69 additions & 81 deletions di/torq/proc/idb/idb.q
Original file line number Diff line number Diff line change
@@ -1,117 +1,105 @@
/ di.torq.proc.idb - intraday database process type. Mounts the WDB's *working* directory (the
/ same `savedir` the wdb writes/appends into during the day, before EOD sort+move into the
/ hdb - see di.torq.proc.wdb) so queries can see today's not-yet-persisted-to-hdb data intraday.
/ ---
/ v1 is a minimal, di.torq.proc.hdb-shaped mount + remount: di.torq.proc.idb only exposes a
/ remotely-triggerable `.idb.intradayreload[]`, same shape as di.torq.proc.hdb's `.hdb.reload[]` -
/ something else has to call it after data changes on disk. idb itself never polls or pushes;
/ that something else is the wdb, which calls `.idb.intradayreload[]` on every idbtypes connection two
/ ways - after any intraday flush that actually wrote something (unconditional), and again at
/ EOD if `idb` is opted into `reloadorder` (see di.torq.proc.wdb's wdb.q/wdb.md).
/ ---
/ It mounts savedir ITSELF, as a partitioned database, exactly as legacy TorQ's idb does in
/ default writedown mode (idbdir::.Q.dd[savedir;`]). So the tables carry a virtual `date` column
/ and the idb never needs to know which date the wdb is on - a new day's partition simply appears
/ under the root and the next reload picks it up. Mounting a single date directory instead would
/ mean tracking the wdb's partition, which wall-clock .z.d gets wrong for any end of day that is
/ not at midnight.
/ ---
/ The wdb enumerates every flushed table against ITS hdbdir, not against savedir (see
/ di.torq.proc.wdb's flushtable, `.Q.en[.z.m.hdbdir;...]`) - live, on every flush, not just at
/ EOD (`.Q.en` extends the domain AND rewrites hdbdir/sym on disk whenever it sees a symbol
/ that domain doesn't already have). So the mounted working-partition tables' symbol columns
/ are enumerated (foreign-keyed) against that SAME hdbdir/sym, not anything under savedir -
/ idb needs `hdbdir` as its own config, purely to load that file into its own session's root
/ `sym`, independently of mounting savedir. Without it, `` `sym `` never exists in the idb's
/ session and a symbol column reads back as raw enum indices instead of symbols.
/ di.torq.proc.idb - ported from TorQ's idb.q
/ mounts the wdb's working directory so today's data can be queried before it reaches the hdb

astz:{[x] $[11h=abs type x;x;`$(),x]}
tolong:{[x] $[10h=abs type x;"J"$(),x;"j"$x]}

/ legacy TorQ's symfilehaschanged. Size, not mtime: .Q.en only ever appends.
/ hcount is trapped where legacy calls it bare: the wdb creates hdb/sym on its first .Q.en, so a
/ wdb that is up but has not flushed yet leaves us statting a file that is not there.
symfilehaschanged:{[]
.z.m.symsize<>@[hcount;.z.m.symfilepath;0]
}

/ legacy TorQ's `load symfilepath` - it names the variable after the file, so it sets root `sym`
/ even from inside a use-loaded module (verified). REPLACES rather than merges: the file is the
/ enumeration domain and the on-disk columns are positions in it, so root sym must match its order
/ exactly - a union against a reordered sym resolves every symbol column to the wrong value.
readsym:{[f]
load f;
.z.m.log[`info][`loadsym;"loaded sym domain (",(string count get `sym),") from ",string f];
.z.m.symsize:@[hcount;f;0];
/ force loads sym file; the size is only recorded once the load succeeds, so a failed read is retried
loadsym:{[]
.z.m.log[`info][`load;"loading the sym file"];
@[{load x;.z.m.symsize:@[hcount;x;0]};.z.m.symfilepath;{.z.m.log[`error][`load;"failed to load sym file: ",(1_string .z.m.symfilepath)," error: ",x]}];
}

/ force-load the sym domain; the caller decides whether to skip, as legacy splits loaddb from
/ intradayreload. A missing file is logged and survived - symsize stays 0 so the next reload
/ picks it up once a wdb has flushed.
loadsym:{[]
.z.m.log[`info][`loadsym;"loading the sym file"];
@[readsym;.z.m.symfilepath;{.z.m.log[`error][`loadsym;"failed to load sym file: ",(1_string .z.m.symfilepath),", with error: ",x]}];
/ force loads IDB
loadidb:{[]
.z.m.log[`info][`load;"loading the db"];
@[system;"l ",1_string .z.m.idbdir;{.z.m.log[`error][`load;"failed to load IDB: ",(1_string .z.m.idbdir)," error: ",x]}];
.z.m.partitionsize:count key .z.m.idbdir;
Comment thread
DI-Dexter marked this conversation as resolved.
Resolved
}

/ (re)mount savedir as a partitioned db. Empty or absent is normal - the wdb creates it on its
/ first flush - so warn and leave what is loaded rather than let system "l" take the process down.
domount:{[]
d:1_string .z.m.savedir;
$[count key .z.m.savedir;
[system "l ",d; .z.m.log[`info][`domount;"loaded tables: ",", " sv string tables[]]];
.z.m.log[`warn][`domount;"no working directory at ",d," yet - nothing to mount"]];
/ force loads the idb and the sym file
loaddb:{[]
starttime:.z.t;
loadsym[];
loadidb[];
.z.m.log[`info][`load;"IDB load has been finished for partition: ",(string .z.m.currentpartition),". Time taken(ms): ",string .z.t-starttime];
}

/ the wdb has rolled to a new day (legacy's .idb.rollover). The root mount finds the new day by
/ itself, so .z.m.partition drives nothing today - it is kept for the two things that will need it:
/ gateway routing (legacy's .proc.getattributes) and the partition-scoped writedown modes, where
/ the mount is savedir/<partition> rather than the root. Not exposed until one of them lands.
/ sets current partition and force loads the idb and the sym file. Called by the wdb after EOD.
rollover:{[pt]
.z.m.partition:pt;
.z.m.log[`info][`rollover;"wdb rolled to partition ",string pt];
intradayreload[];
.z.m.currentpartition:pt;
.z.m.idbdir:.Q.dd[.z.m.savedir;$[.z.m.writedownmode~`default;`;pt]];
.z.m.log[`info][`rollover;"IDB folder has been set to: ",1_string .z.m.idbdir];
loaddb[];
}

/ reloads the db. Called by the wdb after an intraday flush.
intradayreload:{[]
Comment thread
DI-Dexter marked this conversation as resolved.
Resolved
.z.m.log[`info][`reload;"reloading idb from ",1_string .z.m.savedir];
starttime:.z.t;
if[symfilehaschanged[];loadsym[]];
domount[];
if[partitioncounthaschanged[];loadidb[]];
clearrowcountcache[];
.z.m.log[`info][`intradayreload;"IDB reload has been finished for partition: ",(string .z.m.currentpartition),". Time taken(ms): ",string .z.t-starttime];
}

/ ask the wdb where it is writing and set our state from it - same name and job as legacy's.
/ The two must agree on savedir and hdbdir, and config on both sides drifts apart.
/ checks if sym file has changed since last load of the IDB; hcount trapped as hdb/sym is absent until the wdb's first .Q.en
symfilehaschanged:{[] .z.m.symsize<>@[hcount;.z.m.symfilepath;0]}

/ checks if count of partitions has changed since last reload of the IDB. Records new partition count if changed.
/ the default writedown method doesn't need db reloading as no new directory is being created there.
partitioncounthaschanged:{[]
if[(1j~.z.m.partitionsize) and .z.m.writedownmode~`default;:0b];
$[.z.m.partitionsize<>c:count key .z.m.idbdir;[.z.m.partitionsize:c;1b];0b]
}

/ this makes sure running "count trade" queries will return correct row count
clearrowcountcache:{[] set[`.Q.pn;.Q.pt!(count .Q.pt)#()]}

/ reads savedir, hdbdir, the current partition and the writedown mode from the wdb
setparametersfromwdb:{[config]
wt:$[`wdbtypes in key config;astz config`wdbtypes;`wdb];
t:$[`connecttimeoutms in key config;tolong config`connecttimeoutms;30000];
(.z.m.svc`startup)[config,(enlist`connections)!enlist enlist wt];
if[not (.z.m.svc`waitfortype)[wt;t;500];
'"di.torq.proc.idb: no ",(string wt)," connection within ",(string t),"ms - cannot resolve savedir/hdbdir"];
h:(.z.m.svc`gethandlebytype)[wt;`any];
/ the error carries the offending name, so it needs no interpolation of our own
p:@[h;(each;value;`.wdb.savedir`.wdb.hdbdir`.wdb.currentpartition);{'"di.torq.proc.idb: could not read from the wdb: ",x}];
/ the wdb's paths are already hsyms; keep them as such and build the sym path with .Q.dd, as
/ legacy's symfilepath does. It is never partition-scoped - every day enumerates against the one.
.z.m.savedir:p 0;
.z.m.symfilepath:.Q.dd[p 1;`sym];
.z.m.partition:p 2;
.z.m.log[`info][`setparametersfromwdb;"savedir=",(1_string .z.m.savedir),", partition=",string .z.m.partition];
.z.m.log[`info][`init;"querying WDB, HDB locations, current partition and writedown mode from WDB"];
params:@[h;(each;value;`.wdb.savedir`.wdb.hdbdir`.wdb.currentpartition`.wdb.writedownmode);{'"di.torq.proc.idb: could not read from the wdb: ",x}];
.z.m.savedir:hsym params 0;
.z.m.currentpartition:params 2;
.z.m.symfilepath:.Q.dd[hsym params 1;`sym];
.z.m.writedownmode:params 3;
.z.m.idbdir:.Q.dd[.z.m.savedir;$[.z.m.writedownmode~`default;`;.z.m.currentpartition]];
.z.m.log[`info][`init;"Current settings: db folder: ",(1_string .z.m.idbdir),", sym file: ",(1_string .z.m.symfilepath),", writedownmode: ",string .z.m.writedownmode];
}

/ helper function to support queries against the sym column
maptoint:{[val]
$[(abs type val) in 5 6 7h;
/ if using an integer column, clamp value between 0 and max int (null maps to 0)
0|2147483647&`long$val;
/ if using a symbol column, enumerate against the hdb sym file
(`. `sym)?`TORQNULLSYMBOL^val]
}

/ helper function to support queries against the sym column in partbyfirstchar
mapfctoint:{[val] .Q.an?$[0<type val;first each;first] string val}

/ reads deps and the wdb's parameters, then loads the db and the sym file
init:{[config;deps]
if[not `log in key deps;'"di.torq.proc.idb: log dependency is required - see di.util.log"];
.z.m.log:deps`log;
if[not `servers in key deps;'"di.torq.proc.idb: servers dependency is required - injected by di.torq, see di.torq.servers"];
.z.m.svc:deps`servers;
setparametersfromwdb config;
.z.m.log[`info][`init;"mounting idb from ",1_string .z.m.savedir];
/ symsize starts at 0, which is also what a missing sym file stats as - so the first load always
/ happens, and readsym only records a size on success
.z.m.symsize:0;
loadsym[];
domount[];
/ 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: a remote
/ `.idb.intradayreload[]` call would otherwise hit an undefined-function error).
.z.m.partitionsize:0;
.z.m.log[`info][`init;"loading the db and the sym file first time"];
loaddb[];
/ use-loading compiles into a private namespace, so publish the IPC surface and query helpers at root
set[`.idb.intradayreload;intradayreload];
set[`.idb.rollover;rollover];
set[`maptoint;maptoint];
set[`mapfctoint;mapfctoint];
.z.m.log[`info][`init;"Initialisation of the IDB is done."];
}
29 changes: 25 additions & 4 deletions di/torq/proc/idb/test.csv
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,16 @@ true,0,0,q,`intradayreload in key `.idb,1,,init published reload at the real roo
true,0,0,q,`a`b`c~sym,1,,init loaded the hdb's sym domain into the root `sym`
true,0,0,q,`a`b`c~asc distinct value exec name from select name from widgets,1,,the enumerated `name` column resolves to real symbols, not raw indices

run,0,0,q,delete widgets from `.,1,,drop the in-memory table to prove reload actually remounts it
run,0,0,q,addpartition[TESTDATE-1],1,,a third dated partition appears under the savedir root
run,0,0,q,.idb.intradayreload[],1,,call the published root-level reload entry point
true,0,0,q,`widgets in tables[],1,,reload remounted the fixture table
true,0,0,q,9=count widgets,1,,the partition count changed so reload remounted and sees all three

run,0,0,q,delete widgets from `.,1,,drop it again before testing a savedir that is not on disk
run,0,0,q,resetcalls[],1,,reset call log
run,0,0,q,setwdbmissingdir[],1,,the wdb reports a savedir that does not exist yet
run,0,0,q,idb[`init][cfg[];mockdeps[]],1,,init against a savedir that does not exist must not throw
true,0,0,q,not `widgets in tables[],1,,nothing was mounted - the savedir did not exist
true,0,0,q,0<count select from calls where lvl=`warn,1,,init logged a warning about the missing savedir instead of erroring
true,0,0,q,0<count select from calls where lvl=`error,1,,init logged the failed load of the missing savedir instead of throwing
true,0,0,q,`intradayreload in key `.idb,1,,init still published reload even though nothing was mounted

run,0,0,q,resetcalls[],1,,reset call log
Expand Down Expand Up @@ -99,7 +99,7 @@ run,0,0,q,setwdbparams[],1,,the wdb will report the fixture dirs
run,0,0,q,delete widgets from `.,1,,drop the table so the mount has to bring it back
run,0,0,q,idb[`init][cfg[];mockdeps[]],1,,init must ask the wdb for the dirs
true,0,0,q,askedwdb[],1,,it waited for a wdb and queried it
true,0,0,q,askedforvars[],1,,and asked for exactly .wdb.savedir/.wdb.hdbdir/.wdb.currentpartition
true,0,0,q,askedforvars[],1,,and asked for exactly .wdb.savedir/.wdb.hdbdir/.wdb.currentpartition/.wdb.writedownmode
true,0,0,q,TESTDATE~recordedpartition[],1,,and recorded the wdb's current partition
true,0,0,q,`widgets in tables[],1,,and mounted the directory the wdb reported
true,0,0,q,`widgets in .Q.pt,1,,still a partitioned root mount
Expand All @@ -123,5 +123,26 @@ comment,,,,,,,a wdb that does not publish everything we ask for
true,0,0,q,initnovar[`savedir],1,,a wdb missing .wdb.savedir fails init naming that variable
true,0,0,q,initnovar[`hdbdir],1,,a wdb missing .wdb.hdbdir fails init naming that variable
true,0,0,q,initnovar[`currentpartition],1,,a wdb missing .wdb.currentpartition fails init naming that variable
true,0,0,q,initnovar[`writedownmode],1,,a wdb missing .wdb.writedownmode fails init naming that variable

comment,,,,,,,writedown modes - the idb mounts savedir in default mode and savedir/<partition> otherwise
run,0,0,q,setupfixture[],1,,fixture on disk
run,0,0,q,setwdbparams[],1,,a default-mode wdb
run,0,0,q,idb[`init][cfg[];mockdeps[]],1,,init in default mode
true,0,0,q,rootmounted[],1,,default mode mounts the savedir root
run,0,0,q,resetcalls[],1,,reset call log
run,0,0,q,.idb.intradayreload[],1,,an intraday reload with the partition count unchanged
true,0,0,q,not 0<count select from calls where msg like "loading the db*",1,,does not remount
run,0,0,q,setupenumfixture[],1,,a partbyenum wdb with two int partitions under the date
run,0,0,q,delete widgets from `.,1,,drop the table so the mount has to bring it back
run,0,0,q,idb[`init][cfg[];mockdeps[]],1,,init in partbyenum mode
true,0,0,q,datemounted TESTDATE,1,,a partitioned mode mounts savedir/<partition>
true,0,0,q,6=count widgets,1,,both int partitions are visible - 3 rows each
true,0,0,q,`int in .Q.pf,1,,the mount is int-partitioned
run,0,0,q,.idb.rollover[TESTDATE+1],1,,the wdb rolls the idb to the next day
true,0,0,q,datemounted TESTDATE+1,1,,rollover moves the mount to the new partition
true,0,0,q,0 5~maptoint 0N 5,1,,maptoint is published at root and maps a null int to 0
true,0,0,q,(.Q.an?"b")~mapfctoint`bob,1,,mapfctoint is published at root
run,0,0,q,set[`.wdb.writedownmode;`default],1,,restore default mode

after,0,0,q,teardownfixture[],1,,remove the temp fixture directory
22 changes: 18 additions & 4 deletions di/torq/proc/idb/test.q
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ mockservers:{[] `startup`getservers`gethandlebytype`waitfortype!(mockstartup;moc
mockdeps:{[] `log`servers!(`info`warn`error!(mocklogfn[`info;;];mocklogfn[`warn;;];mocklogfn[`error;;]);mockservers[])}

/ the root variables a real wdb publishes, which the evaluated query reads
setwdb:{[sd] set[`.wdb.savedir;sd]; set[`.wdb.hdbdir;hsym `$FIXTUREHDBDIR]; set[`.wdb.currentpartition;TESTDATE];}
setwdb:{[sd] set[`.wdb.savedir;sd]; set[`.wdb.hdbdir;hsym `$FIXTUREHDBDIR]; set[`.wdb.currentpartition;TESTDATE]; set[`.wdb.writedownmode;`default];}
setwdbparams:{[] setwdb hsym `$FIXTUREDIR;}

/ the wdb reports a savedir that is not on disk - the window before its first flush
Expand All @@ -49,7 +49,7 @@ initnovar:{[v]
askedwdb:{[] `waitfortype in exec fn from scalls}

/ the query the idb actually sent, captured by the mock handle
askedforvars:{[] LASTQ~(each;value;`.wdb.savedir`.wdb.hdbdir`.wdb.currentpartition)}
askedforvars:{[] LASTQ~(each;value;`.wdb.savedir`.wdb.hdbdir`.wdb.currentpartition`.wdb.writedownmode)}
resetservercalls:{[] `scalls set ([]fn:`symbol$();arg:()); `WAITOK set 1b; `LASTQ set ();}

FIXTUREDIR:"/tmp/di_idb_k4unit_fixture"
Expand Down Expand Up @@ -104,7 +104,7 @@ stalecfg:{[] `wdbtypes`savedir`hdbdir!(`wdb;`$":",FIXTUREDIR;`$":",FIXTUREHDBDIR

/ an unchanged sym file is silent, so a skip is proven by the absence of the entry log
symattempted:{[] 0<count select from calls where lvl=`info,msg like "loading the sym file*"}
symreloaded:{[] 0<count select from calls where lvl=`info,msg like "loaded sym domain*"}
symreloaded:{[] symattempted[] and not symfailed[]}
symfailed:{[] 0<count select from calls where lvl=`error,msg like "failed to load sym file*"}

/ .Q.en with an unseen symbol rewrites FIXTUREHDBDIR/sym, making it strictly bigger
Expand All @@ -127,4 +127,18 @@ corruptsymfile:{[] (hsym `$FIXTUREHDBDIR,"/sym") 0: enlist "not a serialised sym

/ the partition the module recorded. Not exposed by the module (nothing consumes it), so the tests
/ reach into its private namespace rather than the module inventing an accessor for their benefit.
recordedpartition:{[] get `.m.di.0torq.0proc.0idb.partition}
recordedpartition:{[] get `.m.di.0torq.0proc.0idb.currentpartition}
idbdir:{[] get `.m.di.0torq.0proc.0idb.idbdir}
rootmounted:{[] idbdir[]~.Q.dd[hsym `$FIXTUREDIR;`]}
datemounted:{[d] idbdir[]~.Q.dd[hsym `$FIXTUREDIR;d]}

/ a new dated partition appears under the savedir root, as the wdb's first flush of a new day makes
addpartition:{[d] (` sv (hsym `$FIXTUREDIR,"/",(string d),"/widgets";`)) set .Q.en[hsym `$FIXTUREHDBDIR;([]id:1 2 3;name:`a`b`c)];}

/ a partitioned writedown mode: savedir/<partition>/<int partition>/<table>, as the wdb's partbyenum writes
setupenumfixture:{[]
system "rm -rf ",FIXTUREDIR;
widgets:.Q.en[hsym `$FIXTUREHDBDIR;([]id:1 2 3;name:`a`b`c)];
{[w;i] (` sv (hsym `$FIXTUREDIR,"/",(string TESTDATE),"/",(string i),"/widgets";`)) set w}[widgets] each 0 1;
set[`.wdb.writedownmode;`partbyenum];
}
2 changes: 1 addition & 1 deletion di/torq/proc/wdb/VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.2.0
0.3.0
1 change: 1 addition & 0 deletions di/torq/proc/wdb/deps.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@
"di.torq.servers" = "0.3.0" # requires the INJECTED-servers contract (deps`servers)
"di.subscriptions" = "0.1.0"
"di.dbwrite" = "0.1.0"
"di.merge" = "0.1.0"
2 changes: 1 addition & 1 deletion di/torq/proc/wdb/init.q
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@

version:first read0`:::VERSION

export:([init;endofday;version])
export:([init;endofday;endofdaysort;version])
Loading