diff --git a/di/torq/proc/idb/idb.md b/di/torq/proc/idb/idb.md index 32d0fec4..6090f147 100644 --- a/di/torq/proc/idb/idb.md +++ b/di/torq/proc/idb/idb.md @@ -1,136 +1,67 @@ # di.torq.proc.idb -The intraday database process type: mounts the **wdb's working directory** (the same -`savedir` that `di.torq.proc.wdb` incrementally writes/appends into during the day, before its -end-of-day sort + move into the hdb), independently loads the **hdb's sym domain** so the -mounted tables' symbol columns resolve correctly, and exposes a remotely-triggerable reload - -so queries can see today's data before it lands in the hdb. Started by `di.torq` through the -same `init[config;deps]` convention as every other built-in proctype. - -## Design - -### Why point at the wdb's working directory, not the hdb - -`di.torq.proc.wdb` deliberately writes through a permanent working directory and only **moves** -each table into the hdb once it is complete and sorted (see wdb.md, "Why a separate working -dir + move"). That move is what keeps the hdb always either absent-or-complete for a given -partition — a mid-day crash can't leave partial data there. The trade-off is that the hdb -alone can't answer "what happened so far today"; `di.torq.proc.idb` fills that gap by mounting -the wdb's working dir directly, accepting that data there may be unsorted and can, in the -narrow window of an in-flight flush, be incompletely appended (see "Known gaps"). - -### `.z.m.symfilepath` / `loadsym[]` - -The wdb enumerates every flushed table's symbol columns against **its `hdbdir`**, not -`savedir` (`di.torq.proc.wdb`'s `flushtable`, `` .Q.en[.z.m.hdbdir;...] ``) - live, on every -flush, not just at EOD. So the working-partition tables idb mounts carry symbol columns that -are true kdb+ enumerations (foreign keys) against `hdbdir/sym`, and reading them back -correctly requires that **same** `sym` domain to exist in idb's own session - without it, a -symbol column reads back as raw integer indices instead of symbols. `.z.m.symfilepath` is the fixed -path to that file, derived once in `setparametersfromwdb[]` from the `hdbdir` the wdb reported, -as legacy sets its `symfilepath`. It is not partition-scoped: the wdb enumerates every -day against the same one. `loadsym[]` reads it into the root `sym`, -called from `init` (always) and from `intradayreload[]` (only when the file has changed - see -`symfilehaschanged[]` below), in both cases before `domount[]`, matching legacy TorQ's own -`loadsym`-before-`loadidb` order in `loaddb`. - -### `symfilehaschanged[]` - -The wdb calls `.idb.intradayreload[]` after **every** intraday flush that wrote anything, but `.Q.en` -only rewrites `hdbdir/sym` when it meets a symbol the domain doesn't already have. On a busy -day the overwhelming majority of those reloads therefore have nothing new to read, so -**`intradayreload[]` gates its `loadsym[]` call** on `symfilehaschanged[]` - after legacy TorQ's function -of the same name (`TorQ/code/processes/idb.q`). It turns the common case from a full read of a -domain that grows all day into a `hcount` stat. - -Unlike legacy, the check is a **pure predicate**: the new size is recorded by `readsym[]`, only -once the `load` has actually succeeded. Legacy stamps the size the moment it detects a change, so -a read that then fails is never retried and root `sym` stays stale until the file changes again. -Recording on success instead means a failed read leaves `symsize` alone and the next reload tries -again. - -The gate lives in the **caller**, not in `loadsym[]`, which stays an unconditional force-load - -the same split legacy TorQ has between `loaddb` (force: startup and rollover) and -`intradayreload` (gated). `init` additionally clears `symsize` before force-loading: a size -recorded against a previous `init`'s `hdbdir` says nothing about the file this one was handed, -and since a failed read records nothing, it could otherwise carry over indefinitely. - -One consequence worth knowing: if a read fails and the file is later restored to **exactly** the -size of the last good one, the reload is skipped. That is harmless - a failed `load` never -modifies root `sym`, so the domain still in memory is the one that file holds. `domount[]` is -*not* gated - see "Mounting" below. - -It compares **size**, not modification time: the sym file only ever grows (`.Q.en` appends), so -a size change is exactly a content change, while mtime granularity can miss two writes within -the same second. `hcount` is trapped to `0` rather than left to throw, and the guard is checked -*after* `loadsym[]`'s existence test - so a sym file appearing for the first time is always -read, since a missing file stats as `0`, which is also `symsize`'s initial value. - -`init` calls `loadsym[]` directly, so it always reads the file it has just been pointed at -rather than trusting a size recorded against a previous init's `hdbdir`. - -`loadsym[]` uses legacy TorQ's plain `load`, which **replaces** root `sym` with the file's -contents rather than merging into it. The file is the enumeration domain and the on-disk columns -are integer positions in it, so root `sym` has to match its order exactly; a union against a `sym` -that had drifted out of step would keep the wrong order and resolve every symbol column to the -wrong value, silently. - -`load` is one of the few writes that does **not** need the `` @[`.;...] `` root anchoring the rest -of this tier uses - it names the variable after the file, and lands at root even when called from -inside a `use`-loaded module (verified directly; `sym` never appears in the module's private -namespace). - -### Mounting - -`domount[]` mounts **`savedir` itself** with a plain `\l`, as a partitioned database - the same -thing legacy TorQ's idb does in `default` writedown mode (`idbdir::.Q.dd[savedir;`]`). The tables -therefore carry a virtual `date` column, and the idb never has to know which date the wdb is on: a -new day's partition simply appears under the root and the next reload sees it. - -That matters because the wdb's partition and the wall clock are not the same thing. At end of day -the wdb moves to `pt+1` while `.z.d` is still `pt`, so any idb that derived its own date from the -clock would spend the rest of the day mounting a directory that had just been moved into the hdb. -Mounting the root sidesteps it entirely, with no date on the wire and no wdb handshake. - -The remount is unconditional. Measured on a root mount: rows appended to an existing partition are -**not** visible without one, and neither is a new partition directory - so there is nothing to gate -on. Legacy gates `loadidb` with `partitioncounthaschanged[]` and leans on `clearrowcountcache[]` -(`.Q.pn` reset) for the append case; that does not hold up here - clearing `.Q.pn` left `count` -stale, and only a remount refreshed it. `\l` of one directory is cheap and a reload is driven by -the wdb, not a timer. - -`loadsym[]` (see above), then `domount[]`, which mounts `savedir` **only if it currently exists** -- otherwise it logs a warning and leaves whatever was already loaded in place. It legitimately -does not exist at idb startup, if the idb comes up before the wdb has flushed anything at all. -Without the guard, `system "l"` on a missing directory throws, which would crash `init` before it -reached `` set[`.idb.intradayreload;intradayreload] `` - leaving no entry point to recover with. -Guarding it means `init` always finishes and publishes, so the very next `intradayreload[]` (once -the wdb produces data) picks it up normally. - -`intradayreload` and `rollover` are published at real root names for the same reason -`di.torq.proc.hdb` publishes `.hdb.reload` - `use`-loading this module compiles it into a private, -mangled namespace, so a remote `` .idb.intradayreload[] `` call needs a plain root-level entry -point to exist (torq-developer skill, Rule E3). +The intraday database process type, ported from TorQ's `code/processes/idb.q`. It mounts the +**wdb's working directory** and the **hdb's sym file**, so today's data can be queried before the +wdb's end of day moves it into the hdb. Started by `di.torq` through the same +`init[config;deps]` convention as every other built-in proctype. + +## How it works + +At `init` the idb asks the wdb where it is writing (`setparametersfromwdb`), then force-loads the +sym file and the db (`loaddb`). After that it only reacts to the wdb: + +| Call | From | Does | +|---|---|---| +| `.idb.intradayreload[]` | the wdb, after a flush that wrote something | reloads the sym file if it grew, remounts if the partition count changed, clears the `.Q.pn` row-count cache | +| `.idb.rollover[pt]` | the wdb or sort process, at end of day | sets the current partition, moves the mount for it, force-loads the db | + +### What gets mounted + +As legacy, the mount depends on the wdb's writedown mode: + +| `writedownmode` | `idbdir` | Mounted as | +|---|---|---| +| `default` | `savedir` | a date-partitioned db, with a virtual `date` column | +| `partbyenum`, `partbyfirstchar` | `savedir/` | an int-partitioned db, one partition per enumerated value / first character | + +`partbyattr` gets the `savedir/` mount too, but as in legacy the wdb never sends +it a reload, so it is not served intraday. + +For querying the int-partitioned modes, `maptoint` and `mapfctoint` are published at root, as in +legacy: they map a sym (or int) value, or a sym's first character, to its int partition. + +### Reloads + +`intradayreload` only remounts when `partitioncounthaschanged[]`. Rows appended to a partition +that is already mounted are seen by a `select` without a remount; only `count` is cached, in +`.Q.pn`, which `clearrowcountcache[]` resets. In `default` mode a single partition never needs a +remount at all. + +### The sym file + +The wdb enumerates against the hdb's `sym`, so the idb loads that file into root `sym` +(`loadsym`). It is reloaded only when its size changes (`symfilehaschanged[]`), since `.Q.en` only +ever appends. + +Two differences from legacy: +- **The size is recorded only after a successful load.** Legacy records it as soon as it sees a + change, so a load that then fails is never retried. +- **`hcount` is trapped.** The sym file does not exist until the wdb's first `.Q.en`, so the idb + can start before it. + +A missing `savedir` at startup is logged as an error by `loadidb`, as legacy, and does not stop +`init`; the next reload after the wdb has written picks it up. ## The wdb handshake -`savedir` and `hdbdir` must resolve to the **same directories the wdb uses**. Rather than leave -that to two config files kept in step by hand, `init` asks the wdb — `setparametersfromwdb[]`, -named after legacy's function of the same job. It calls `servers` `startup` with a `wdbtypes` -connection, blocks on `waitfortype`, then reads the wdb's own root variables: +`setparametersfromwdb` connects to a `wdbtypes` process, waits for it, and reads: ```q -(each;value;`.wdb.savedir`.wdb.hdbdir`.wdb.currentpartition) +(each;value;`.wdb.savedir`.wdb.hdbdir`.wdb.currentpartition`.wdb.writedownmode) ``` -exactly as legacy reads `.wdb.savedir` and friends. It sets `savedir`, `symfilepath` and -`partition` from the answer; nothing else in the module derives them. - -`savedir`/`hdbdir` are not settings the idb reads at all — the wdb is the only source — so -`di/torq/settings/idb.q` is gone rather than empty. - -Failing to reach a wdb within the timeout **fails init**, naming the proctype. That is a real -startup dependency the module did not previously have. +The idb takes `savedir` and `hdbdir` from the wdb, never from its own config. Failing to reach a +wdb within `connecttimeoutms` fails `init`. ## Dependencies @@ -141,94 +72,24 @@ startup dependency the module did not previously have. | key | meaning | |---|---| -| `wdbtypes` | proctype(s) to ask for `savedir`/`hdbdir`. Default `` `wdb ``. | +| `wdbtypes` | proctype to ask for its directories and writedown mode. Default `` `wdb ``. | | `connecttimeoutms` | how long to wait for a wdb before failing init. Default 30000. | -## Usage - -```q -q)idb:use`di.torq.proc.idb -q)lg:use`di.util.log -q)logdep:`info`warn`error!(lg`info;lg`warn;lg`error) -q)cfg:`savedir`hdbdir!(`$":/tmp/di_idb_readme_demo";`$":/tmp/di_idb_readme_hdb_demo") -q)idb[`init][cfg;enlist[`log]!enlist logdep] -2026.07.09D12:41:24.703763000 INFO init mounting idb from :/tmp/di_idb_readme_demo/2026.07.09 -2026.07.09D12:41:24.703850000 WARN loadsym no sym file at /tmp/di_idb_readme_hdb_demo/sym yet - symbol columns may not resolve -2026.07.09D12:41:24.703897000 INFO domount loaded tables: trade -q)tables[] -,`trade -q)delete trade from `. -q).idb.intradayreload[] -2026.07.09D12:41:24.703928000 INFO reload reloading idb from :/tmp/di_idb_readme_demo/2026.07.09 -q)tables[] -,`trade -``` +## Not ported -(Called via `idb[`init]`, not `idb.init` - dot-syntax on a module dict returned by a `use` call -in the same session/frame is unreliable in this kdb-x build; see `test.csv`'s comment and -`di.torq`'s own `buildlogdep` note for the same caveat elsewhere. `.idb.intradayreload[]` is unaffected -- it's a plain root function, not accessed through the module dict.) - -In the real sample app, `di.torq` builds `config`/`deps` from the settings cascade and calls -`(m`init)[config;deps]` itself (`torq.q`'s `startbuiltin` - bracket-indexed, same reasoning as -above) when `proctype` is `` `idb ``. Pointing an idb's `savedir` at -the **same** directory as a running wdb's `savedir` (matching config value, resolved to the -same absolute path) is what makes it see that wdb's intraday writes. - -## Known gaps (v1) - -- **No `writedownmode` awareness in the handshake.** `setparametersfromwdb[]` takes `savedir` and `hdbdir` - from the wdb and records `currentpartition`, which nothing consumes yet - the root mount needs - no date. It is kept for gateway routing and for the partition-scoped writedown modes below, - either of which makes it load-bearing. It does not ask for `writedownmode`, which legacy uses - to choose between mounting the root and mounting a single partition. Moot while only `default` - writedown exists. -- **No self-registration or attribute-based gateway routing.** Legacy TorQ's idb registers - itself with the wdb (`` .servers.registerfromdiscovery ``) and publishes - `` .proc.getattributes `` (`` `partition`tables!(partition;tables[]) ``) so a - gateway can route queries to whichever idb currently holds the relevant partition/tables. - `di.torq.proc.idb` does neither: the wdb finds it the same static way it finds every other - peer (`process.csv` + `idbtypes` in `CONNECTIONS`), and there is nothing to register with a - gateway anyway - `di.torq.proc.gateway` v1 has no backend attribute-reporting plumbing yet - for *any* backend type, not just idb (see gateway.q's "EMPTY attributes" note). -- **`writedownmode`-aware layout, and the `partbyenum`/`partbyfirstchar` query-mapping - helpers** (`maptoint`/`mapfctoint` in `TorQ/code/processes/idb.q`). Legacy TorQ's idb picks - its mount directory differently depending on the wdb's active writedown mode, and ships - helpers for querying a `partbyenum`/`partbyfirstchar`-mapped sym column. Moot while - `di.torq.proc.wdb` only implements the classic `default` writedown mode (see wdb.md, "Not - included") - would need porting together if wdb ever grows the advanced modes. -- **No sort/attribute awareness.** The idb mounts whatever is on disk, unsorted, exactly as the - wdb wrote it (matching `di.dbwrite`'s appended-not-sorted intraday writes). -- **`domount[]` is never gated**, unlike legacy TorQ's `loadidb`, and there is no `.Q.pn` - row-count-cache reset. Both follow from mounting a single date directory of splayed tables - see "Mounting" above - a remount is the only thing that refreshes either, so there is nothing - to gate on. -- **Read-during-write race.** The wdb's per-table flush (create-or-append) is not atomic - from a reader's point of view; a reload that lands mid-flush could see a partially - appended table. Same class of risk legacy TorQ's idb accepts for intraday data - only the - hdb (post-move) is guaranteed complete-or-absent. -- **One directory, one mount** - no multi-database layout beyond what a plain `` \l `` already - gives (matching `di.torq.proc.hdb`'s equivalent gap). +- **Registering with the wdb** (`` .servers.registerfromdiscovery ``). The wdb finds the idb + through `process.csv` and `idbtypes`, like any other peer. +- **`.proc.getattributes`**, for gateway routing. `di.torq.proc.gateway` has no attribute + reporting for any backend yet. +- **A root `reload`.** The sort process calls `.idb.intradayreload[]` by name. ## Testing -`test.csv`/`test.q` (k4unit) cover: init failing without a `log` or `servers` dependency, init -failing when no wdb answers within the timeout, the handshake being made and its `savedir`/ -`hdbdir`/`currentpartition` taken, `savedir`/`hdbdir` still set in config being ignored rather -than used, the mount being partitioned with a virtual `date` column and both dated fixture -partitions visible, the loaded root `sym` matching the fixture domain and the fixture's -genuinely-enumerated `name` column resolving to real symbols (not raw indices - the exact failure -mode `loadsym[]` exists to prevent), the published `.idb.intradayreload[]` actually remounting -after a table is dropped, `.idb.rollover[pt]` recording the new partition and remounting, and a -wdb reporting a `savedir` that is not on disk (must warn, not throw, and recover on the next -reload once data appears). The fixture's `widgets` table is -built with `.Q.en` and written with a trailing-slash path (`` ` sv (path;`) ``, matching -`di.torq.proc.wdb`'s own `flushtable`) so it's a genuine splayed, enumerated table on disk, not -a flat serialised file - a bare `` `:dir/widgets `` (no trailing slash) silently "worked" with -the old non-enumerated fixture but throws `'type` on mount for a real enum column. Every -`idb[...]` call in `test.csv` is bracket-indexed, not `idb.xxx` - see the Usage section above. -Run in a fresh q session (this suite calls `setenv`, so don't interleave it with other -modules' tests in one shared process): +`test.csv`/`test.q` (k4unit) cover the dependency checks, the wdb handshake (including a wdb that +does not publish each variable), the default and `partbyenum` mounts, rollover moving the mount, +reloads remounting only when the partition count changes, the sym-file change detection and +retry, and a missing `savedir`. Every `idb[...]` call is bracket-indexed, not `idb.xxx`. Run in a +fresh q session, as the suite calls `setenv`: ```q q)k4unit:use`di.k4unit diff --git a/di/torq/proc/idb/idb.q b/di/torq/proc/idb/idb.q index 01626b63..f2b9c338 100644 --- a/di/torq/proc/idb/idb.q +++ b/di/torq/proc/idb/idb.q @@ -1,85 +1,61 @@ -/ 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; } -/ (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/ 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:{[] - .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]; @@ -87,31 +63,43 @@ setparametersfromwdb:{[config] 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 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 +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 diff --git a/di/torq/proc/idb/test.q b/di/torq/proc/idb/test.q index 5500a336..ed6aef58 100644 --- a/di/torq/proc/idb/test.q +++ b/di/torq/proc/idb/test.q @@ -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 @@ -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" @@ -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//, 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]; + } diff --git a/di/torq/proc/wdb/VERSION b/di/torq/proc/wdb/VERSION index 0ea3a944..0d91a54c 100644 --- a/di/torq/proc/wdb/VERSION +++ b/di/torq/proc/wdb/VERSION @@ -1 +1 @@ -0.2.0 +0.3.0 diff --git a/di/torq/proc/wdb/deps.toml b/di/torq/proc/wdb/deps.toml index cadf4f5f..ecd0c78e 100644 --- a/di/torq/proc/wdb/deps.toml +++ b/di/torq/proc/wdb/deps.toml @@ -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" diff --git a/di/torq/proc/wdb/init.q b/di/torq/proc/wdb/init.q index 24eb5f85..be39c627 100644 --- a/di/torq/proc/wdb/init.q +++ b/di/torq/proc/wdb/init.q @@ -2,4 +2,4 @@ version:first read0`:::VERSION -export:([init;endofday;version]) +export:([init;endofday;endofdaysort;version]) diff --git a/di/torq/proc/wdb/test.csv b/di/torq/proc/wdb/test.csv index bd357106..d1600882 100644 --- a/di/torq/proc/wdb/test.csv +++ b/di/torq/proc/wdb/test.csv @@ -1,9 +1,107 @@ action,ms,bytes,lang,code,repeat,minver,comment before,0,0,q,wdb:use`di.torq.proc.wdb,1,,load module before,0,0,q,mlog:`info`warn`error!(3#enlist {[c;m]}),1,,a minimal (dyadic) log dep dict +before,0,0,q,mtimer:`addjob`deletejobs!(2#enlist {[x]}),1,,a minimal timer dep dict +before,0,0,q,mservers:`startup`getservers`gethandlebytype`waitfortype!(4#enlist {[x]}),1,,a minimal servers dep dict +before,0,0,q,"mhandlers:`register`remove`list!({[ev;ph;nm;pri;fn]};{[ev;ph;nm]};{[ev]})",1,,a minimal handlers dep dict - di.subscriptions requires it +before,0,0,q,"alldeps:`log`timer`servers`handlers!(mlog;mtimer;mservers;mhandlers)",1,,every injected dep the wdb requires +before,0,0,q,"initerr:{[c] @[{[x] wdb.init[x;alldeps]};c;{x}]}",1,,run init for a config and return the error string fail,0,0,q,wdb.init[()!();()!()],1,,init without the log dependency must error fail,0,0,q,wdb.init[()!();(enlist`log)!enlist mlog],1,,init with log but no timer dependency must error -true,0,0,q,`init`endofday`version~key wdb,1,,module exports init/endofday/version +true,0,0,q,`init`endofday`endofdaysort`version~key wdb,1,,module exports init/endofday/endofdaysort/version true,0,0,q,0/dev/null 2>&1 &"; + n:0; + while[(null TPH) and 50>n+:1;`TPH set @[hopen;(`$"::",string TPPORT;200);{0Ni}];if[null TPH;system "sleep 0.1"]]; + }; + +stoptp:{[] @[{neg[x](exit;0);neg[x][]};TPH;::]; @[hclose;TPH;::]; `TPH set 0Ni;}; + +setup:{[] + system "rm -rf ",BASE; + system "mkdir -p ",BASE,"/appconfig"; + setenv[`TORQXDATAHOME;BASE]; + setenv[`TORQXAPPHOME;BASE]; + setenv[`TORQXAPPCONFIG;BASE,"/appconfig"]; + (hsym `$BASE,"/appconfig/sort.csv") 0: ("tabname,att,column,sort";"default,p,sym,1";"default,,time,1"); + starttp[]; + }; + +/ numtab is pinned empty so numrows governs every table; the shipped default is covered by numtabdefault[] +cfg:{[] + `savedir`hdbdir`sortcsv`numrows`numtab`replaynumtab`eodwaittime`reloadorder`ignorelist! + ("wdb";"hdb";"appconfig/sort.csv";100000;(`symbol$())!`long$();(`symbol$())!`long$();0;`hdb;`heartbeat`logmsg`calls`scalls) + }; + +today:{[] .z.D}; +hdbpart:{[t] hsym `$BASE,"/hdb/",(string today[]),"/",string t}; +wdbpart:{[] hsym `$BASE,"/wdb/",string today[]}; + +freshwdb:{[c] + `calls set 0#calls; + system "rm -rf ",BASE,"/wdb ",BASE,"/hdb"; + wdb.init[c;recdeps[]]; + }; + +/ 8 trades over three syms, fed in two batches so a partitioned mode writes more than one segment +feed:{[] + upd[`trade;([]time:.z.D+0D09 0D12 0D10 0D11;sym:`ibm`msft`ibm`aapl;price:4?100f)]; + upd[`quote;([]time:.z.D+0D09 0D08;sym:`ibm`msft;bid:2?10f)]; + .m.di.0torq.0proc.0wdb.savetodisk[]; + upd[`trade;([]time:.z.D+0D15 0D14 0D13 0D16;sym:`msft`aapl`ibm`msft;price:4?100f)]; + }; + +/ the whole day ends up in the hdb, grouped by sym with p# applied, and the working partition is gone +eodok:{[c] + freshwdb c; + feed[]; + endofday today[]; + t:select from get hdbpart`trade; + / enum on disk, but select resolves it once the sym domain is loaded - take the column as-is + s:t`sym; + chk `rows`psym`grouped`quote`wdbgone!( + 8=count t; + `p=attr (get hdbpart`trade)`sym; + (count distinct s)=sum differ s; + 2=count get hdbpart`quote; + 0=count key wdbpart[]) + }; + +defaultmode:{[] eodok cfg[]}; +partbyattr:{[m] eodok cfg[],`writedownmode`mergemode!(`partbyattr;m)}; +partbyenum:{[m] eodok cfg[],`writedownmode`mergemode!(`partbyenum;m)}; +partbyfirstchar:{[m] eodok cfg[],`writedownmode`mergemode!(`partbyfirstchar;m)}; + +/ each intraday flush writes one segment per parted value, and the sizes are tracked for the merge +segments:{[] + freshwdb cfg[],`writedownmode`immediate!(`partbyattr;1b); + feed[]; + ps:(use`di.merge)[`getpartsizes][]; + chk `segs`tracked!( + `aapl`ibm`msft~asc key hsym `$(1_string wdbpart[]),"/trade"; + 3=count select from ps where ptdir like "*trade*") + }; + +/ startup writes empty schemas into the working partition for the idb +missingtables:{[] + freshwdb cfg[]; + chk `trade`quote!(0=count get ` sv (wdbpart[];`trade;`);0=count get ` sv (wdbpart[];`quote;`)) + }; + +tabsizes:{[] + freshwdb cfg[],(enlist`immediate)!enlist 1b; + upd[`quote;([]time:.z.D+0D01*til 5;sym:5#`ibm;bid:5?10f)]; + upd[`trade;([]time:.z.D+0D01*til 2;sym:2#`ibm;price:2?10f)]; + .m.di.0torq.0proc.0wdb.savetodisk[]; + `quote`trade~2#.m.di.0torq.0proc.0wdb.tablelist[] + }; + +manipulation:{[] + freshwdb cfg[],(enlist`savedownmanipulation)!enlist (enlist`trade)!enlist {update price:2*price from x}; + upd[`trade;([]time:enlist .z.D+0D01;sym:enlist`ibm;price:enlist 5f)]; + endofday today[]; + 10f~first (get hdbpart`trade)`price + }; + +postreplay:{[] + `POST set (); + freshwdb cfg[],(enlist`postreplay)!enlist {[d;p] `POST set (d;p)}; + feed[]; + endofday today[]; + (last POST)~today[] + }; + +compression:{[] + freshwdb cfg[],(enlist`compression)!enlist 17 2 6; + feed[]; + endofday today[]; + chk `compressed`reset!( + 0/dev/null 2>&1 &"; + h:0Ni;n:0; + while[(null h) and 50>n+:1;h:@[hopen;(`$"::",string port;200);{0Ni}];if[null h;system "sleep 0.1"]]; + `PEERH set PEERH,h; + h + }; + +stoppeers:{[] + {@[{neg[x](exit;0);neg[x][]};x;::];@[hclose;x;::]} each PEERH; + `PEERH set `int$(); + `PEERS set (`symbol$())!(); + }; + +/ a saveandsort wdb started with a negative -s merges on its sortworkers +workermerge:{[] + `PEERS set enlist[`sortworker]!enlist h:startpeer each `sortworker`sortworker; + system "s -2"; + r:eodok cfg[],`writedownmode`mergemode!(`partbyattr;`hybrid); + system "s 0"; + merged:{[h] count h"select from LOGS where ctx=`merge,msg like \"*merge complete\""} each h; + stoppeers[]; + r and all 0/dev/null"}; + r:@[{(1b;x[])};f;{(0b;x)}]; + OSSYSCALL set o; + $[first r;last r;'last r] + }; + +/ a date with no working partition logs the failed move rather than throwing +emptypartition:{[] + freshwire config[]; + quietshell {tail[savedir[];PDATE+10;`]}; + chk `logged`nothdb!( + loggedlike[`error;"Failed to move data from wdb*"]; + 0=count key hsym `$hdbdir[],"/",string PDATE+10) + }; + +/ string settings (toml / command-line overrides) reach module state as the right types +stringconfig:{[] + c:`savedir`hdbdir`hdbtypes`rdbtypes`gatewaytypes`reloadorder`permitreload`gc`eodwaittime! + ("wdb";"hdb";"hdb";"rdb";"gateway";"hdb rdb";"true";"false";"0"); + freshwire c; + tail["";PDATE;`]; + chk `moved`reloadorderparsed!( + `quote`trade~partitiontables hdbdir[]; + `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 +sortcsvhonoured:{[] + system "mkdir -p ",BASE,"/appconfig"; + (hsym `$BASE,"/appconfig/sort.csv") 0: ("tabname,att,column,sort";"default,,sym,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) + }; + +/ with no sortcsv set, the app's sort.csv under TORQXAPPCONFIG is used +defaultsortcsv:{[] + system "mkdir -p ",BASE,"/appconfig"; + (hsym `$BASE,"/appconfig/sort.csv") 0: ("tabname,att,column,sort";"default,,sym,1"); + freshwire config[]; + tail[savedir[];PDATE;`trade]; + tr:hdbtable`trade; + hdel hsym `$BASE,"/appconfig/sort.csv"; + (tr`sym)~asc tr`sym + }; + + +/ a sort process opens its own connections and publishes the root entry point +initpublishes:{[] + resetmocks[]; + makepartition[]; + set[`.wdb.endofdaysort;(::)]; + wdb.init[config[],(enlist`mode)!enlist`sort;deps[]]; + c:first exec arg from scalls where fn=`startup; + chk `startedup`connections`nott`published!( + 1=count select from scalls where fn=`startup; + `gateway`hdb`idb`rdb`sortworker`wdb~asc c`connections; + not `tickerplant in c`connections; + not (::)~ .wdb.endofdaysort) + }; + +/ --- sortworkers: real q processes, each on a fresh port so a dying one is never reconnected to --- + +NEXTPORT:25931; + +/ a sortworker is the wdb module in sort mode with every connection type emptied, as di/torq/settings/sortworker.q does +WCFG:"((enlist`mode)!enlist`sort),`tickerplanttypes`hdbtypes`rdbtypes`idbtypes`gatewaytypes`sorttypes`sortworkertypes`wdbtypes!8#enlist`symbol$()"; +workerinit:{[cfg] "w.init[(",WCFG,"),",cfg,";`log`timer`servers!(`info`warn`error!(lg`info;lg`warn;lg`error);(`symbol$())!();`startup`getservers!({[c]};{[pt] ([]w:`int$())}))];"}; +workerlog:("lg:{[l;c;m] `LOGS upsert `lvl`ctx`msg!(l;c;m);};";"LOGS:([]lvl:`symbol$();ctx:`symbol$();msg:());";"w:use`di.torq.proc.wdb;"); + +workerscript:(!) . flip ( + (`real;workerlog,enlist workerinit "()!()"); + (`symsort;workerlog,enlist workerinit "(enlist`sortcsv)!enlist \"appconfig/sym.csv\""); + (`bare;enlist "")); + +startworker:{[kind;port] + f:BASE,"/worker_",(string kind),".q"; + (hsym `$f) 0: workerscript kind; + system "timeout 120 ",(first .z.X)," ",f," -p ",(string port)," -q /dev/null 2>&1 &"; + h:0Ni;n:0; + while[(null h) and 50>n+:1;h:@[hopen;(`$"::",string port;200);{0Ni}];if[null h;system "sleep 0.1"]]; + h + }; + +startworkers:{[kinds] `WORKERS set kinds startworker' NEXTPORT+til count kinds;`NEXTPORT set NEXTPORT+count kinds;}; + +stopworkers:{[] + {@[{neg[x](exit;0);neg[x][]};x;::];@[hclose;x;::]} each WORKERS; + `WORKERS set `int$(); + system "s 0"; + }; + +workersorted:{[h] exec msg from h"LOGS" where ctx=`sort,msg like "finished*"}; + +/ with -s negative, each of two workers sorts one table +fanoutok:{[] + startworkers`real`real; + system "s -2"; + freshwire config[]; + tail[savedir[];PDATE;`trade`quote]; + tr:hdbtable`trade; + r:chk `sorted`moved`bothworked`logged!( + tr[`time]~asc tr`time; + `quote`trade~partitiontables hdbdir[]; + all 1=count each workersorted each WORKERS; + loggedlike[`info;"sorting on worker sort*"]); + stopworkers[]; + r + }; + +/ a worker sorts to its own sortcsv, as legacy's did +workersortcsv:{[] + system "mkdir -p ",BASE,"/appconfig"; + (hsym `$BASE,"/appconfig/sym.csv") 0: ("tabname,att,column,sort";"default,,sym,1"); + startworkers`symsort`symsort; + system "s -2"; + freshwire config[]; + tail[savedir[];PDATE;`trade`quote]; + tr:hdbtable`trade; + r:chk `sortedbysym`nottimesorted!((tr`sym)~asc tr`sym;not (tr`time)~asc tr`time); + stopworkers[]; + r + }; + +/ without a negative -s, connected workers are not used +noworkers:{[] + startworkers`real`real; + freshwire config[]; + tail[savedir[];PDATE;`trade`quote]; + r:chk `main`idle!(loggedlike[`info;"sorting on main sort"];all 0=count each workersorted each WORKERS); + stopworkers[]; + r + }; + +/ a failing worker makes the tail throw before the move +workerfails:{[] + startworkers enlist`bare; + system "s -1"; + freshwire config[]; + r:chk `threw`notmoved!( + 0 e.g. 17 2 6, applied (.z.zd) while sorting/merging, then reset to 16 0 0 +# savedownmanipulation (optional, .q settings) -> 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 # 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 dbwrite's default (time asc) +# sortcsv (optional) -> di.dbwrite sort/attribute config; else $TORQXAPPCONFIG/sort.csv if present, else time asc ``` The schema comes from the **tickerplant** (via `subdetails`), not a local `database.q` — @@ -50,37 +78,40 @@ di.subscriptions defines the tables at root from what the TP returns. - **Startup**: connect (TP/HDB/RDB) via di.torq.servers; clear any stale working-partition data; install a **flushing replay `upd`** at root; block until a TP is up; subscribe + replay. The replay runs through that flushing `upd`, so it writes to disk past `numrows` and never holds a - whole day in RAM. After replay the root `upd` is swapped to a plain accumulate. + whole day in RAM. After replay the root `upd` is swapped to `insert`, or the configured `upd`. - **Intraday** (`savetodisk`, timer job every `settimer`s): flush any table over its threshold (or every table, if `immediate`) to the working partition — **create on first write, append after**, enumerating syms against the **HDB** sym file, then clear it in memory. If that - flushed at least one table, every connected `idbtypes` process is notified - (`` .idb.intradayreload[] ``, async, no partition — the idb mounts the savedir root and finds - the day itself) — an all-skipped tick (nothing over threshold) stays silent. This is + flushed at least one table, the partition is filled (`filldb`) and every connected `idbtypes` process is notified + (`` .idb.intradayreload[] ``, async) — an all-skipped tick (nothing over threshold) stays silent. This is unconditional on `reloadorder`; it only needs an idb to be connected. - **End of day** (`endofday[date]`, published at root): the tickerplant broadcasts `(`endofday;date)` at roll (the same trigger as di.torq.proc.rdb). di.torq.proc.wdb flushes what - remains, sorts each working partition (`di.dbwrite.sort` — driven by `sortcsv` or the time-asc - default), **moves** each table dir into `hdbdir/date/` (skipping any that already exist, to - never corrupt the hdb), then reloads downstream in `reloadorder`. The hdb and rdb are given the - date just **closed**; an `idb` entry in `reloadorder` instead gets - `` .idb.rollover[date+1] `` — the partition the wdb has moved **on** to — which records the new - day and remounts. Both idb legs go through the one `notifyidbs[func;params]`, as legacy TorQ. + remains, then runs `endofdaysort` — `saveandsort` in-process, `save` by an async + `.wdb.endofdaysort[dir;pt;tablist;writedownmode;mergelimits;hdbsettings;mergemethod]` to each + connected sort process. With no sort process connected, `save` + logs an error and runs the tail here anyway rather than stranding the day's data in the working + directory. The tail's `idbreload` then initialises the next partition and sends + `` .idb.rollover[date+1] `` to every idb. The intraday `.idb.intradayreload` leg stays in the wdb + (`notifyidbs`), and after each flush that wrote something the partition is filled with `.Q.chk` + (`filldb`) first. ## What the wdb publishes for the idb -`init` publishes three root variables the idb reads at startup, the way legacy TorQ's +`init` publishes four root variables the idb reads at startup, the way legacy TorQ's `setparametersfromwdb` reads `.wdb.savedir` and friends: ```q set[`.wdb.savedir;.z.m.savedir]; set[`.wdb.hdbdir;.z.m.hdbdir]; set[`.wdb.currentpartition;.z.m.currentpartition]; +set[`.wdb.writedownmode;.z.m.writedownmode]; ``` -They are read with `` (each;value;`.wdb.savedir`.wdb.hdbdir`.wdb.currentpartition) ``, so the idb -is not configured with the two directories by hand — one source of truth, no pair to keep in step. -`endofday` republishes `currentpartition` after it advances; the other two are fixed for the life +They are read with `` (each;value;`.wdb.savedir`.wdb.hdbdir`.wdb.currentpartition`.wdb.writedownmode) ``, +so the idb is not configured with the two directories by hand — one source of truth, no pair to keep in step. +The writedown mode decides whether the idb mounts `savedir` or `savedir/`. +`endofday` republishes `currentpartition` after it advances; the other three are fixed for the life of the process. ## RDB / WDB interaction @@ -112,21 +143,101 @@ enumerate dir == the write dir) don't fit the write path — the create-or-appen wdb-local; di.dbwrite is reused only for the EOD `sort`/`applyattr`. (A future di.dbwrite could grow an optional enum-dir param and absorb this.) -## Not included (future / other-process / deprecated) - -- **Sort / sortworker as separate processes** (`mode` = `save`/`sort`, `.z.pd` worker fan-out). - v1 is `saveandsort` in-process only. -- **Advanced writedown modes** (`partbyattr`/`partbyenum`/`partbyfirstchar`) and all of - `merge.q`. v1 is `default` writedown only. -- **`filldb`/`initmissingtables`** (legacy TorQ's other `notifyidbs`-adjacent EOD helpers - an - idb here just remounts its savedir wholesale on reload, see `di.torq.proc.idb`, so there is no - separate "fill" step to port). Per-flush notify itself **is** ported - see "Intraday" above. -- **Compression** (`.z.zd`). -- **Cross-date replay** (`fixpartition` — moving already-written temp data when the tp log date - differs from today). v1 assumes same-day start; it logs a warning and uses the log date, but - does not relocate data already written under the wrong partition. -- **Gateway** block/unblock is a no-op until a gateway is connected (di.torq.proc.gateway not built). -- **FinSpace/AWS** and the `endofperiod` STP stub — stripped. +## Modes + +| `mode` | behaviour | +| --- | --- | +| `saveandsort` (default) | subscribe, save, and run the EOD sort in this process | +| `save` | subscribe and save; hand the EOD sort to a `sorttypes` process over IPC | +| `sort` | no tickerplant: wait for `.wdb.endofdaysort` from a `save`-mode wdb | + +Proctypes `sort` and `sortworker` run this module with framework settings +`di/torq/settings/sort.q` and `sortworker.q`, which set `mode:`sort`. That is legacy's +arrangement, where both loaded `wdb.q` with `-parentproctype wdb`. A sort process connects to the +hdb, rdb, idb, gateway, sortworker and wdb types. `endofdaysort`'s `dir`, `tablist` and +`hdbsettings` can be null, meaning this process's own `savedir`, the tables in the working +partition, and its own `hdbdir`/`compression`. + +If a `save`-mode wdb finds no sort process connected it logs an error and sorts the day itself, +as legacy does. + +## Sortworkers + +`settings/sortworker.q` empties every connection type, so a sortworker dials nothing and waits. +`init` defines `.z.pd` to return the connected `sortworkertypes` handles, and the per-table sort +or merge goes to the workers when some are connected **and** the process has a negative `-s`, +from the command line or the `workers` setting. Each worker is first sent the sym file to reload +and, for the `part` and `hybrid` merges, the partition sizes. The work is legacy's `peach` +lambdas, calling root names every mode publishes: `.sort.sorttab`, `.wdb.merge`, +`.wdb.setcompression`, `.wdb.reloadsymfile` and `.wdb.gc`. A worker sorts to its own `sortcsv`, +which defaults to the app's `sort.csv`. + +An error on a worker propagates out of the `peach` and stops the sort before the move, leaving the +working copy in place. As legacy, a new hdb partition is moved in with one rename; if the hdb +partition already exists and any table is in both, the whole move is aborted and logged, so nothing +is overwritten. + +## Writedown modes + +| `writedownmode` | intraday layout | end of day | +| --- | --- | --- | +| `default` | `//
/` | sort each table, move into the hdb | +| `partbyattr` | `//
//` | merge the segments into the hdb | +| `partbyenum` | `///
/` | merge the segments into the hdb | +| `partbyfirstchar` | `///
/` | sort each segment, then merge | + +The parted column comes from the `p` attribute in `sortcsv`; init reports an error if the +partitioned modes find no `default` row with one. Each segment's size is tracked in `di.merge` so +the merge can batch by `mergenumrows` / `mergenumbytes`. In `save` mode the sizes are sent to the +sort process with `.merge.syncpartsizes` before the hand-off. + +## Startup + +- The working partition is cleared, the log replayed with the `replaynumrows` threshold, and, if + the tickerplant log date differs from the current partition, the replayed data is moved to the + log's date (`fixpartition`). +- In `default` and `partbyenum` modes empty table schemas are written into the working partition + (`initmissingtables`), so an idb can mount it. `.wdb.initmissingtables` is published at root for a + sort process to call at end of day. + +## Not included (deprecated) + +- **FinSpace/AWS** — stripped. + +The `endofperiod` stub legacy shipped in `writedown.q` **is** kept: `di.pubsub.callendofperiod` +broadcasts `` (`endofperiod;(current;next;data)) `` to every subscriber on each period roll, so a wdb +pointed at a segmented tickerplant would otherwise raise `'endofperiod` every period. The stub is +published at root by `init` and only logs. It is **monadic**, matching `callendofperiod`, which +sends the triple as a single argument. + +## Migrating a TorQ wdb settings file + +Config comes from the merged config dictionary, not `@[value;...]`, so a setting this module does +not know is **ignored silently**. These TorQ names changed: + +| TorQ setting | this module | +| --- | --- | +| `subtabs` | `subscribeto` | +| `subsyms` | `subscribesyms` | +| `replay` | `replaylog` | +| `tpconnsleepintv`, `tpcheckcycles` | `tpwaittimeout` (a single ms budget) | +| `schema` | dropped — the schema always comes from the tickerplant's `subdetails` | + +`settimer` is a **number of seconds**, not a timespan: a TorQ-style `0D00:00:10` throws. `numtab` +and `mergenumtab` keep legacy's `` `quote`trade!10000 50000 `` default, so `numrows` / +`mergenumrows` do **not** apply to those two tables unless you override `numtab` / `mergenumtab`. + +### Upgrading from 0.2.0 — behaviour change + +**`numtab` now defaults to `` `quote`trade!10000 50000 ``; 0.2.0 defaulted it to an empty +dictionary.** A config with no `numtab` key therefore flushes `quote` at 10,000 rows and `trade` +at 50,000 instead of at `numrows`, so those two tables write down more often than they did on +0.2.0. This restores TorQ's default (`code/wdb/writedown.q`) and matches `mergenumtab`, which +already shipped it. To keep 0.2.0's behaviour, set `numtab` explicitly: + +```toml +numtab = {} # every table uses numrows, as in 0.2.0 +``` ## Module-namespace notes @@ -136,8 +247,18 @@ replay) lands in the module's private namespace. The replay `upd` is therefore r ## Testing -`test.csv` (k4unit) covers the dependency contract (init errors without `log`/`timer`) and the -export surface. The full subscribe → replay-to-disk → intraday-append → EOD sort+move → hdb +`test.csv` + `test.q` (k4unit) cover the dependency contract, the export surface and `mode` +validation. They also run the wdb end to end against a spawned process standing in for the +tickerplant: every writedown mode with every merge method, segment tracking, `initmissingtables`, +`tabsizes`, `savedownmanipulation`, `postreplay`, compression, `fixpartition`, the tickerplant retry +cycles, the `p`-attribute check, replay thresholds, merging on real sortworkers, `save` mode handing +off to a real sort process, and the `eodwaittime` reload handshake against a spawned hdb. +`testsort.q` covers sort mode against an unsorted working partition on disk: the sort and move, +table discovery, the `savedir` fallback, the no-overwrite rule, `permitreload` and `reloadorder`, +string settings, the `sortcsv` default, the sort process's connections, and fanning out to real +sortworker processes. + +The full subscribe → replay-to-disk → intraday-append → EOD sort+move → hdb reload + rdb `dropfirstnrows` flow is proven in the **TorqX-POC end-to-end** (`torqx.sh start tickerplant1 hdb feed1 rdb1 wdb1`, with `rdb1` in `reloadenabled` mode). diff --git a/di/torq/proc/wdb/wdb.q b/di/torq/proc/wdb/wdb.q index 78a13d32..a02e2af1 100644 --- a/di/torq/proc/wdb/wdb.q +++ b/di/torq/proc/wdb/wdb.q @@ -1,268 +1,756 @@ -/ di.torq.proc.wdb - the write database. Subscribes to a tickerplant (via di.subscriptions), replays -/ the day's tp log (flushing to disk as it goes so a full day never sits in RAM), then during -/ the day incrementally writes each in-memory table to a working partition when it exceeds a row -/ threshold. At end of day it flushes what remains, sorts each table on disk, MOVES the working -/ partition into the hdb, and triggers a reload of the hdb(s) and rdb(s). Ported from the -/ CRITICAL path of TorQ/code/processes/wdb.q (+ code/wdb/writedown.q). -/ --- -/ Scope (v1, classic saveandsort, in-process, `default` writedown mode - see the wdb.q -/ Chesterton's-Fence audit). NOT included (future/other-process): sort/sortworker as -/ separate processes (mode save/sort, .z.pd fan-out); advanced writedown modes -/ (partbyattr/partbyenum/partbyfirstchar) and all of merge.q; compression. REMOVED -/ (deprecated): finspace/aws and the .z.pd tempfix guards; the endofperiod STP stub. -/ --- -/ idb (di.torq.proc.idb) is notified through notifyidbs, as legacy TorQ: .idb.intradayreload after any -/ intraday flush that wrote something, and .idb.rollover with the new partition at EOD (opt in by -/ putting idb in reloadorder). No partition on the intraday leg - the idb mounts the savedir root. -/ --- -/ Why a working dir + move (not write-straight-to-hdb): the hdb partition only ever appears -/ complete AND sorted, after the move - a mid-day crash can't leave partial/unsorted data in -/ the hdb, and (later) an idb can read the working partition intraday. Enumeration is against -/ the HDB sym file (so the moved partition's enum indices already match hdb/sym), which is -/ also why di.dbwrite.savedown/appenddown (single enum==write dir) don't fit the write path; -/ we reuse di.dbwrite only for the EOD sort/attr. When a wdb is present the rdb must run -/ reloadenabled=1b (it then does NOT enumerate) so only ONE process writes hdb/sym. -/ --- -/ Module-namespace notes (see di.subscriptions): root tables are READ via bare `value t` -/ (bare reads fall through to root) but WRITTEN/cleared via @[`.;..] (a bare write from a -/ use-loaded module, or under -11! replay, lands in the module's private namespace). - -/ config coercion (values are symbols from .q settings or strings from .toml) +/ di.torq.proc.wdb - ported from TorQ's wdb.q +/ subscribes to the tickerplant and appends data to disk after the in-memory table exceeds a specified number of rows +/ at eod the on-disk data is sorted and attributes applied as specified in the sort.csv file +/ modes: saveandsort, save (the sort is handed to a sort process) and sort (proctypes sort and sortworker) + +/ config coercion: toml and command-line values arrive as strings, which must be parsed not cast assym:{[x] $[11h=abs type x;x;`$x]} aslist:{[x] $[0>type x;enlist x;x]} +tolong:{[x] + r:$[10h=abs type x;"J"$(),x;"j"$x]; + if[null r;'"di.torq.proc.wdb: could not parse \"",$[10h=abs type x;x;string x],"\" as a number"]; + r + } +tobool:{[x] $[-1h=type x;x;10h=abs type x;(lower (),x) in ("true";(),"1";(),"t";(),"y";"yes");`boolean$x]} +astimespan:{[x] $[10h=abs type x;$[any ((),x) in "D:";"N"$(),x;`timespan$1000000000*"J"$(),x];-16h=type x;x;`timespan$1000000000*x]} -/ a token-list config (e.g. reloadorder): accept a space-separated string ("hdb rdb"), a -/ single symbol, a symbol list, or a list of strings -> always a symbol list. +/ a token-list config (e.g. reloadorder) as a symbol list astoklist:{[x] $[10h=type x;`$" " vs x;-11h=type x;enlist x;11h=type x;x;`$x]} -/ base dirs: CODE/CONFIG under TORQXAPPHOME, runtime DATA under TORQXDATAHOME (falls back to -/ TORQXAPPHOME when unset - fine for a sample app where they coincide). +/ base dirs: code/config under TORQXAPPHOME, runtime data under TORQXDATAHOME falling back to TORQXAPPHOME apphome:{getenv[`TORQXAPPHOME]} datahome:{$[count h:getenv[`TORQXDATAHOME];h;getenv[`TORQXAPPHOME]]} -/ resolve a possibly-relative dir setting to an absolute path STRING under `base` +/ resolves a possibly-relative dir setting to an absolute path string under base resolvedir:{[base;dir] dir:$[10h=abs type dir;dir;string dir]; dir:$[(0 updfn. -replayupd:{[t;x] updfn[t;x]; if[maxrows[t] < count value t;flushtable[0b;t]];} - -/ create-or-append one root table's rows into its working partition, then clear it in memory. -/ force=1b writes regardless of count (EOD flush); else only when over maxrows. Enumerates -/ against the HDB sym file (NOT the working dir) so the partition can later move into the hdb. -flushtable:{[force;t] - n:count value t; - if[not force; if[not maxrows[t] < n; :0b]]; - if[0=n; :0b]; - data:.Q.en[.z.m.hdbdir;0!value t]; / enumerate syms vs hdb/sym (persists it) - path:` sv (.Q.par[.z.m.savedir;.z.m.currentpartition;t];`); - $[count @[key;path;{`$()}]; - .[path;();,;data]; / append to existing splayed partition - path set data]; / create the partition - @[`.;t;0#]; / clear the in-memory table (root-safe) - .z.m.log[`info][`wdb;"flushed ",(string n)," rows of ",(string t)," to ",string path]; - 1b - } - -/ timer job: flush every table over threshold (or all of them when immediate), then notify any -/ connected idb(s) IF that actually changed something on disk (flushtable returns 1b per table -/ it wrote, 0b for one it skipped as empty/under-threshold) - an all-skipped tick stays silent, -/ so an idle wdb doesn't spam idb reloads. This is the per-flush leg from the header note above; -/ notifyidbs no-ops when no idb is connected, so this is safe to call unconditionally. +/ saves a table split by its extra partition once over its row limit +savetablesbypart:{[dir;pt;forcesave;tablename;writedownmode] + / check row count and save if maxrows exceeded + / forcesave will flush the data to disk irrespective of counts + if[forcesave or maxrows[tablename] < arows:count value tablename; + .z.m.log[`info][`rowcheck;"the ",(string tablename)," table consists of ",(string arows)," rows"]; + / get additional partition(s) defined by parted attribute in sort.csv + extrapartitiontype:getextrapartitiontype[tablename]; + if[(writedownmode in `partbyenum`partbyfirstchar) and 1 lmt; + .z.m.log[`info][`replayupd; + "row limit (",(string lmt),") exceeded for ",(string t), + ". Table count is : ",(string rpc),". Flushing table to disk..."]; + savetab[.z.m.savedir;getpartition[];0b;t]]; + } + +/ will check on each upd to determine where data should be flushed to disk (if max row limit has been exceeded) +replayupd:{[t;x] .z.m.upd[t;x]; replaymaxrowcheck[t;replaymaxrows t];} + +/ saves each table over its row limit, then notifies the idbs savetodisk:{[] - changes:flushtable[.z.m.immediate;] each tablelist[]; - if[any changes;notifyidbs[`.idb.intradayreload;enlist()]]; + changes:savetab[.z.m.savedir;getpartition[];.z.m.immediate;] each tablelist[]; + / we have to let the idbs know of the changes in the wdbhdb. using filldb[] to make sure it is a db with all the tables + if[any[changes] and .z.m.writedownmode in `partbyenum`partbyfirstchar`default; + filldb getpartition[]; + notifyidbs[`.idb.intradayreload;enlist()]]; } -/ remove any pre-existing working data for the current partition before replay (replay rebuilds -/ it from the log, so stale data from a previous run would be double-counted). Scoped to the -/ wdb's own working partition dir. +/ if there is data in the wdb directory for the partition remove it before replay clearwdbdata:{[] - pdir:.Q.par[.z.m.savedir;.z.m.currentpartition;`]; - if[count key pdir; - d:1_string pdir; - system "rm -rf ",d; - .z.m.log[`info][`wdb;"cleared existing wdb working data at ",d]]; - } - -/ EOD sort: sort + apply attributes on the working partition for table t (di.dbwrite, driven by -/ the sort config / its time-asc default). In-process, so the sym file this process enumerated -/ against is already current - no reloadsymfile needed (that is a separate-sort-worker concern). -sortpart:{[pt;t] - dir:` sv (.Q.par[.z.m.savedir;pt;t];`); - if[count key dir;(.z.m.dbw`sort)[t;dir]]; - } - -/ move the working partition into the hdb, one table dir at a time. A table already present in the -/ hdb partition is skipped (never overwrite - that would corrupt the hdb), mirroring TorQ. -movetohdb:{[pt] - src:.Q.par[.z.m.savedir;pt;`]; - if[not count key src;.z.m.log[`warn][`wdb;"no working partition to move for ",string pt];:()]; - dst:.Q.par[.z.m.hdbdir;pt;`]; - srcs:1_string src; dsts:1_string dst; - system "mkdir -p ",dsts; - {[srcs;dsts;t] - s:srcs,"/",string t; d:dsts,"/",string t; - $[count key hsym `$d; - .z.m.log[`error][`wdb;"table ",(string t)," already in hdb partition ",dsts," - skipped to avoid corruption"]; - [system "mv ",s," ",d;.z.m.log[`info][`wdb;"moved ",(string t)," -> ",d]]]; - }[srcs;dsts;] each key src; - if[0=count key src;system "rm -rf ",srcs]; - } - -/ inform the gateway(s) that a reload is starting/ending. POC has no gateway (and di.torq.proc.gateway -/ is not built yet), so this is a no-op when none is connected - the hook is kept for when it -/ lands. TorQ's protocol is (`reloadstart;`) / (`reloadend;`) to block/unblock in-flight queries. -informgateway:{[msg] - h:raze {exec w from (.z.m.svc`getservers)[x]} each .z.m.gatewaytypes; - if[0=count h;:()]; - {[wh;msg] @[neg wh;(`.gw.reload;msg);{[e] .z.m.log[`error][`wdb;"gateway inform failed: ",e]}]}[;msg] each h; + $[not ()~key wdbpart:.Q.par[.z.m.savedir;getpartition[];`]; + [.z.m.log[`info][`deletewdbdata;"removing wdb data (",(delstrg:1_string wdbpart),") prior to log replay"]; + @[.z.m.os`deldir;delstrg;{[e] .z.m.log[`error][`deletewdbdata;"Failed to delete existing wdb data. Error was : ",e];'e}]; + .z.m.log[`info][`deletewdbdata;"finished removing wdb data prior to log replay"]]; + .z.m.log[`info][`deletewdbdata;"no directory found at ",1_string wdbpart]]; } -/ tell every hdb of these types to reload (pick up the just-moved partition). `pt` (the -/ partition being reloaded) is unused - kept so the doreload dispatch below can call every -/ reload*[pt] uniformly. -reloadhdbs:{[pt] - h:raze {exec w from (.z.m.svc`getservers)[x]} each .z.m.hdbtypes; - {[wh] @[wh;".hdb.reload[]";{[e] .z.m.log[`error][`wdb;"hdb reload failed: ",e]}]} each h; +/ function to rectify data written to wrong partition +fixpartition:{[tplogdate] + / check if the tp logdate matches current date + if[not tplogdate~orig:.z.m.currentpartition; + .z.m.log[`info][`fixpartition;"Current partition date does not match the ticker plant log date"]; + / set the current partition date to the log date + .z.m.currentpartition:tplogdate; + / move the data that has been written to correct partition + pth1:1_string .Q.par[.z.m.savedir;orig;`]; + pth2:1_string .Q.par[.z.m.savedir;tplogdate;`]; + if[count key hsym `$pth1; + / delete any data in the current partition directory + clearwdbdata[]; + .z.m.log[`info][`fixpartition;"Moving data from partition ",pth1," to partition ",pth2]; + .[.z.m.os`mv; + (pth1;pth2); + {[p1;p2;e] .z.m.log[`error][`fixpartition; + "Failed to move data from wdb partition ",p1," to wdb partition ",p2," : ",e]}[pth1;pth2]]]]; } -/ tell every rdb of these types to reload[pt] (drop the prior day it was holding in memory). -/ async - the rdb's root reload[pt] does the dropfirstnrows (see di.torq.proc.rdb, reloadenabled=1b). -reloadrdbs:{[pt] - h:raze {exec w from (.z.m.svc`getservers)[x]} each .z.m.rdbtypes; - {[wh;pt] @[neg wh;(`reload;pt);{[e] .z.m.log[`error][`wdb;"rdb reload send failed: ",e]}]}[;pt] each h; +/ fills missing tables in the partition so it is usable intraday +filldb:{[pt] .Q.chk .Q.par[.z.m.savedir;pt;`];} + +/ initialises table t in db with its schema in part +inittable:{[t;pt] + tdir:` sv $[.z.m.writedownmode in `partbyenum`partbyfirstchar;.Q.par[.Q.dd[.z.m.savedir;pt];0;t];.Q.par[.z.m.savedir;pt;t]],`; + if[()~key tdir;tdir set .Q.en[.z.m.hdbdir;0#value t]]; } -/ one path for both idb notifications, as legacy's notifyidbs. Async: the intraday leg fires after -/ every flush, so it must not block; the trap therefore only sees send failures. -notifyidbs:{[func;params] - h:raze {exec w from (.z.m.svc`getservers)[x]} each .z.m.idbtypes; - if[0=count h;:()]; - .z.m.log[`info][`notifyidbs;"notifying ",(string count h)," idb(s) with ",string func]; - {[wh;func;params] @[neg wh;enlist[func],params;{[e] .z.m.log[`error][`wdb;"idb notify send failed: ",e]}]}[;func;params] each h; - } - -/ reload downstream in the configured order (default `hdb`rdb: hdb first so it sees the new -/ partition, then rdb so it drops the prior day), bracketed by the gateway block/unblock. -/ `idb` is a valid reloadorder entry too (opt in by adding it, e.g. "hdb rdb idb") but is not -/ in the default order - existing apps that don't run an idb see no behaviour change here (the -/ separate, always-on intraday notify leg in savetodisk is unaffected by reloadorder either way). -/ pt is the day just closed - the hdb and rdb want that; the idb wants the one now being written +/ makes sure partition 0/currentpartition has all the tables for partbyenum/partbyfirstchar/default +initmissingtables:{[pt] + .z.m.log[`info][`fixpartition;"Adding missing tables(empty) to partition ",string pt]; + inittable[;pt] each tablelist[]; + filldb pt; + } + +/ eod - flush remaining data to disk +endofdaysave:{[dir;pt] + / save remaining table rows to disk + .z.m.log[`info][`save;"saving the ",(", " sv string tl:tablelist[],())," table(s) to disk"]; + savetab[dir;pt;1b;] each tl; + .z.m.log[`info][`savefinish;"finished saving data to disk"]; + } + +/ add entries to table of callbacks. if timeout has expired or d now contains all expected rows then it releases each waiting process +handler:{[x] + .z.m.reloadsummary[.z.w]:x; + .z.m.log[`info][`reloadproc;"the ",(string x 0)," process ",string x 2]; + if[(.z.p>.z.m.timeouttime) or count[.z.m.reloadsummary]=.z.m.countreload; + .z.m.log[`info][`handler;"releasing processes"]; + .z.m.log[`info][`reload; + (string count select from .z.m.reloadsummary where status)," out of ", + (string count .z.m.reloadsummary)," processes successfully reloaded"]; + flushend[]; + .z.m.reloadsummary:0#.z.m.reloadsummary]; + } + +/ evaluate contents of d dictionary asynchronously; notify the gateway that we are done +flushend:{[] + if[not .z.m.reloadcomplete; + if[.z.m.eodwaittime>0;@[{neg[x]"";neg[x][]};;()] each exec handle from .z.m.reloadsummary]; + informgateway`reloadend; + .z.m.log[`info][`sort;"end of day sort is now complete"]; + .z.m.reloadcomplete:1b]; + / run a garbage collection (if enabled) + if[.z.m.gc;.Q.gc[]]; + } + +/ triggers the reload of each reloadorder type in turn doreload:{[pt] - informgateway[`reloadstart]; - {[pt;ptype] - $[ptype in .z.m.hdbtypes;reloadhdbs[pt]; - ptype in .z.m.rdbtypes;reloadrdbs[pt]; - ptype in .z.m.idbtypes;notifyidbs[`.idb.rollover;pt+1]; - .z.m.log[`warn][`wdb;"reloadorder entry ",(string ptype)," is neither an hdb, rdb, nor idb type - skipped"]] - }[pt;] each .z.m.reloadorder; - informgateway[`reloadend]; - } - -/ end of day: called by the tickerplant as endofday[pt] (di.pubsub's dated broadcast, same -/ trigger as di.torq.proc.rdb). Flush what remains, sort each working partition, move it into the hdb, then -/ reload downstream. Advance the partition for the new day. + .z.m.reloadcomplete:0b; + / inform gateway of reload start + informgateway`reloadstart; + ro:.z.m.reloadorder inter knowntypes[]; + .z.m.countreload:sum {count (.z.m.svc`getservers) x} each ro where not (::)~/:reloadexpr each ro; + .z.m.timeouttime:.z.p+.z.m.eodwaittime; + 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)]]; + flushend[]]; + } + +/ set .z.zd to control how data gets compressed +setcompression:{[compression] + if[3=count compression; + .z.m.log[`info][`compression;$[compression~16 0 0;"resetting";"setting"]," compression level to (",(";" sv string compression),")"]; + @[`.z;`zd;:;compression]]; + } + +resetcompression:{[] setcompression 16 0 0} + +/ check if the hdb directory contains current partition +/ if yes check if partition is empty and if it is not see if any of the tables exist in both the +/ temporary partition and the hdb partition. If there is a clash abort operation otherwise copy +/ each table to the hdb partition +movetohdb:{[dw;hw;pt] + (.z.m.os`mkdir) hdbroot:(neg count string pt)_hw; + $[not (`$string pt) in key hsym `$hdbroot; + .[.z.m.os`mv;(dw;hw);{[dw;hw;e] .z.m.log[`error][`mvtohdb;"Failed to move data from wdb ",dw," to hdb directory ",hw," : ",e]}[dw;hw]]; + not any a[dw] in (a:{key hsym `$x}) hw; + [{[y;x] + $[not (b:`$last "/" vs x) in key y; + [.[.z.m.os`mv;(x;y);{[x;y;e] .z.m.log[`error][`mvtohdb;"Table ",(string x)," has failed to copy to ",(string y)," with error: ",e];'e}[b;y]]; + .z.m.log[`info][`mvtohdb;"Table ",(string b)," has been successfully moved to ",string y]]; + .z.m.log[`error][`mvtohdb;"Table ",(string b)," was skipped because it already exists in ",string y]]; + }[hsym `$hw]'[dw,/:"/",/:string key hsym `$dw]; + $[0=count key hsym `$dw; + @[.z.m.os`deldir;dw;{[x;y] .z.m.log[`error][`mvtohdb;"Failed to delete folder ",x," with error: ",y]}[dw]]; + .z.m.log[`error][`mvtohdb; + "Table(s) ",(", " sv string key hsym `$dw)," are still in ",dw, + " - the partition is split across the wdb and the hdb"]]]; + .z.m.log[`error][`mvtohdb; + raze "Table(s) ",string[(key hsym `$hw) inter key hsym `$dw], + " is present in both location. Operation will be aborted to avoid corrupting the hdb"]] + } + +/ root sym is set with @[`.;...]: a bare load from a use-loaded module lands in its private namespace +reloadsymfile:{[symfilepath] + if[not count key symfilepath; + .z.m.log[`warn][`reloadsymfile;"no sym file at ",(1_string symfilepath)," - nothing to load"]; + :()]; + .z.m.log[`info][`reloadsymfile;"reloading the sym file from ",1_string symfilepath]; + @[{@[`.;`sym;:;get x]};symfilepath;{[e] .z.m.log[`error][`sort;"failed to reload sym file: ",e]}] + } + +/ legacy's .sort.sorttab: x is (table;dir) +sorttab:{[x] (.z.m.dbw`sort)[x 0;x 1]} + +/ as legacy, workers are only used when this process was started with a negative -s +useworkers:{[] (0system"s"} + +/ sends each worker the sym file to reload, async then flushed +reloadworkersym:{[hdbsettings] {(neg x)(`.wdb.reloadsymfile;y);(neg x)(::)}[;.Q.dd[hdbsettings`hdbdir;`sym]] each .z.pd[]} + +/ sorts each (table;dir), on the sortworkers when there are any +sortall:{[tnds;hdbsettings] + $[useworkers[]; + [.z.m.log[`info][`sort;"sorting on worker sort ",string .z.p]; + reloadworkersym hdbsettings; + / sort the table and garbage collect (if enabled) + {[x;compression] .wdb.setcompression compression;.sort.sorttab x;if[.wdb.gc;.Q.gc[]]}[;hdbsettings`compression] peach tnds]; + [.z.m.log[`info][`sort;"sorting on main sort"]; + reloadsymfile .Q.dd[hdbsettings`hdbdir;`sym]; + {[x] sorttab x;if[.z.m.gc;.Q.gc[]]} each tnds]]; + } + +/ sorts the working partition, moves it into the hdb and reloads +endofdaysortdate:{[dir;pt;tablist;hdbsettings] + / sort permitted tables in database + .z.m.log[`info][`sort;"starting to sort data"]; + sortall[tablist,'.Q.par[dir;pt;] each tablist;hdbsettings]; + .z.m.log[`info][`sort;"finished sorting data"]; + / move data into hdb + .z.m.log[`info][`mvtohdb; + "Moving partition from the temp wdb ",(dw:(.z.m.os`topath) -1_string .Q.par[dir;pt;`]), + " 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]; + 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]} + +/ the parted column(s) for a table from the sort config, falling back to the default row +getextrapartitiontype:{[tablename] + params:sortparams[]; + if[count tabparts:distinct exec column from params where tabname=tablename,sort,att=`p; + .z.m.log[`info][`getextraparttype;"parted attribute p found in sort.csv for ",(string tablename)," table"]; + :tabparts]; + if[count defaultparts:distinct exec column from params where tabname=`default,sort,att=`p; + .z.m.log[`info][`getextraparttype;"parted attribute p not found in sort.csv for ",(string tablename)," table, using default instead"]; + :defaultparts]; + .z.m.log[`error][`getextraparttype;"parted attribute p not found in sort.csv for ",(string tablename)," table and default not defined"]; + `symbol$() + } + +/ merges one table's segments into the hdb partition +merge:{[dir;pt;tableinfo;mergelimits;hdbsettings;mergemethod;writedownmode] + setcompression hdbsettings`compression; + / get tablename + tabname:tableinfo 0; + ep:getextrapartitiontype tabname; + / get list of partition directories for specified table - partbyenum & partbyfirstchar use different folder structures vs partbyattr/default + partdirs:$[writedownmode in `partbyenum`partbyfirstchar; + p where 0//
+/ this function deletes
folder or the whole if it only has one element +removetablefromenumdir:{[partdir] + enumdir:` sv -1_` vs partdir; + (.z.m.os`deldir) $[1=count key enumdir;enumdir;partdir]; + } + +/ merges each table into the hdb, on the sortworkers when there are any, then reloads +endofdaymerge:{[dir;pt;tablist;mergelimits;hdbsettings;mergemethod;writedownmode] + / merge data from partitions + ti:flip (key tablist;value tablist); + $[useworkers[]; + [.z.m.log[`info][`merge;"merging on worker"]; + reloadworkersym hdbsettings; + / upsert .merge.partsize data to sort workers, only needed for part and hybrid method + if[.z.m.mergemode in `hybrid`part; + {(neg x)(`.merge.syncpartsizes;y);(neg x)(::)}[;(.z.m.mrg`getpartsizes)[]] each .z.pd[]]; + {[dir;pt;ml;hs;mm;wm;x] .wdb.merge[dir;pt;x;ml;hs;mm;wm]}[dir;pt;mergelimits;hdbsettings;mergemethod;writedownmode] peach ti; + / clear out in memory table, .merge.partsizes, and call sort worker processes to do the same + .z.m.log[`info][`eod;"Delete from partsizes"]; + (.z.m.mrg`clearpartsizes)[]; + {(neg x)({[x] .merge.clearpartsizes[];if[.wdb.gc;.Q.gc[]]};`);(neg x)(::)} each .z.pd[]]; + [.z.m.log[`info][`merge;"merging on main"]; + reloadsymfile .Q.dd[hdbsettings`hdbdir;`sym]; + merge[dir;pt;;mergelimits;hdbsettings;mergemethod;writedownmode] each ti; + .z.m.log[`info][`eod;"Delete from partsizes"]; + (.z.m.mrg`clearpartsizes)[]]]; + / if path exists, delete it + 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]; + $[.z.m.permitreload;doreload pt;if[.z.m.gc;.Q.gc[]]]; + } + +/ end of day sort and merge only used by writedown mode partbyfirstchar, requiring sort pre-merge +endofdaysortandmerge:{[dir;pt;tablist;mergelimits;hdbsettings;mergemethod;writedownmode] + / sort permitted tables in database + .z.m.log[`info][`sort;"starting to sort data"]; + tnds:raze {y,/:.Q.dd[x;] each key[x],\:y}[.Q.dd[dir;pt]] each key tablist; + tnds:tnds where tnds[;1] in exec ptdir from (.z.m.mrg`getpartsizes)[]; + if[count tnds;sortall[tnds;hdbsettings]]; + .z.m.log[`info][`sort;"finished sorting data"]; + endofdaymerge[dir;pt;tablist;mergelimits;hdbsettings;mergemethod;writedownmode]; + } + +/ end of day sort [depends on writedown mode]; dir, tablist and hdbsettings may be null to use this process's own config +endofdaysort:{[dir;pt;tablist;writedownmode;mergelimits;hdbsettings;mergemethod] + sd:$[0=count s:$[10h=abs type dir;(),dir;string dir];.z.m.savedirs;resolvedir[datahome[];s]]; + dir:hsym `$sd; + if[not 99h=type hdbsettings;hdbsettings:()!()]; + hdbsettings:.z.m.hdbsettings,hdbsettings; + hdbsettings[`hdbdir]:hsym `$resolvedir[datahome[];hdbsettings`hdbdir]; + if[not 99h=type tablist; + t:(),tablist; + t:$[(0=count t) or t~enlist`;key .Q.par[dir;pt;`];t]; + tablist:t!(count t)#enlist ()]; + writedownmode:$[null writedownmode;`default;assym writedownmode]; + mergemethod:$[null mergemethod;.z.m.mergemode;assym mergemethod]; + .z.m.log[`info][`endofdaysort;"starting for partition ",(string pt)," in ",sd,": ",$[count tablist;", " sv string key tablist;"no tables"]]; + / set compression level (.z.zd) + setcompression hdbsettings`compression; + $[writedownmode in .z.m.partwritemodes; + $[writedownmode~`partbyfirstchar;endofdaysortandmerge;endofdaymerge][dir;pt;tablist;mergelimits;hdbsettings;mergemethod;writedownmode]; + endofdaysortdate[dir;pt;key tablist;hdbsettings]]; + / reset compression level (.z.zd) + resetcompression[]; + / run steps to rollover idb + idbreload[pt+1;writedownmode]; + .z.m.log[`info][`endofdaysort;"complete for partition ",string pt]; + } + +/ the call each reloadorder type makes on the far side +/ anything other than an hdb or idb gets legacy's root `reload`, which is what the rdb exposes +reloadexpr:{[ptype] + $[ptype in .z.m.hdbtypes;{[d] .hdb.reload[]}; + ptype in .z.m.idbtypes;{[d] .idb.intradayreload[]}; + {[d] `. [`reload] d}] + } + +/ function to send reload message to rdbs/hdbs/idbs +reloadproc:{[h;d;ptype;f] + / async call back function executed when eodwaittime>0 + sendfunc:{[x;y;ptype] @[neg y;x;{[ptype;e] .z.m.log[`error][`reloadproc;"failed to reload the ",string ptype]}[ptype]]}; + / reload function sent to processes by sendfunc; runs there, so it calls back .wdb.handler with the outcome + reloadfunc:{[f;d;ptype] r:@[{(1b;x y)}[f];d;{(0b;x)}]; + (neg .z.w)(`.wdb.handler;(ptype;first r;$[first r;`$"reloaded successfully";`$"reload failed with error ",last r]));(neg .z.w)[]}; + / reload function to be executed if eodwaitime = 0 - sync message processes to reload and log if reload was successful or failed + syncreloadfunc:{[h;f;d;ptype] + r:@[h;({[f;d] (1b;f d)};f;d); + {[ptype;e] .z.m.log[`error][`reloadproc; + "failed to reload the ",(string ptype),". The error was : ",e];(0b;e)}[ptype]]; + .z.m.log[`info][`reloadproc;"the ",(string ptype)," ",$[first r;"successfully reloaded";"failed to reload"]]}; + .z.m.log[`info][`reloadproc;"sending reload call to ",string ptype]; + $[.z.m.eodwaittime>0;sendfunc[(reloadfunc;f;d;ptype);h;ptype];syncreloadfunc[h;f;d;ptype]]; + } + +/ function to discover rdbs/hdbs and attempt to reconnect +getprocs:{[x;y] + f:reloadexpr x; + a:exec w from (.z.m.svc`getservers) x; + / exit if no valid handle + if[0=count a;.z.m.log[`error][`connection;"no connection to the ",(string x)," could be established... failed to reload ",string x];:()]; + .z.m.log[`info][`connection;"connection to the ",(string x)," has been located"]; + / send message along each handle + reloadproc[;y;x;f] each a; + } + +/ the proctypes in the phone book, or the reloadorder when the servers dep cannot list them +knowntypes:{[] $[`getallservers in key .z.m.svc;exec distinct proctype from (.z.m.svc`getallservers)[];.z.m.reloadorder]} + +/ function to send messages to gateway +informgateway:{[msg] + .z.m.log[`info][`informgateway;"sending message to gateway(s)"]; + if[0=count h:raze {exec w from x} each (.z.m.svc`getservers) each .z.m.gatewaytypes; + :.z.m.log[`info][`informgateway;"no gateway detected - nothing to reload"]]; + {[wh;msg] @[neg wh;(`.gw.reload;msg);{[e] .z.m.log[`error][`informgateway;"unable to run command on gateway: ",e]}]}[;msg] each h; + .z.m.log[`info][`informgateway;"the message - ",(.Q.s1 msg)," was sent to the gateways"]; + } + +/ function to call that will cause sort & reload process to sort data and reload rdb and hdbs; async so the wdb can take the new day +informsortandreload:{[dir;pt;tablist;writedownmode;mergelimits;hdbsettings;mergemethod] + .z.m.log[`info][`informsortandreload;"attempting to contact sort process to initiate data ",$[writedownmode~`default;"sort";"merge"]]; + if[0=count h:raze {exec w from x} each (.z.m.svc`getservers) each .z.m.sorttypes; + .z.m.log[`error][`informsortandreload;"can't connect to the sortandreload - no sortandreload process detected"]; + / try to run the sort locally + :endofdaysort[dir;pt;tablist;writedownmode;mergelimits;hdbsettings;mergemethod]]; + / for part and hybrid method sort procs need access to partsizes table data + if[mergemethod in `hybrid`part; + {[p;h] neg[h](`.merge.syncpartsizes;p);neg[h][]}[(.z.m.mrg`getpartsizes)[]] each h]; + msg:(`.wdb.endofdaysort;dir;pt;tablist;writedownmode;mergelimits;hdbsettings;mergemethod); + {[msg;wh] @[{[msg;wh] neg[wh] msg;neg[wh][]}[msg];wh; + {[e] .z.m.log[`error][`informsortandreload;"unable to run command on sort and reload process: ",e]}]}[msg] each h; + } + +/ send an intraday reload message to idbs +notifyidbs:{[func;params] + ws:raze {exec w from x} each (.z.m.svc`getservers) each .z.m.idbtypes; + .z.m.log[`info][`reload;"found ",(string count ws)," idb(s) to trigger reload with function ",string func]; + / send async message along each handle + {[w;func;params] @[neg w;enlist[func],params;{[e] .z.m.log[`error][`notifyidbs;"idb notify send failed: ",e]}]}[;func;params] each ws; + } + +/ triggers idb reload steps; a sort process asks the wdb(s) to run initmissingtables +idbreload:{[pt;writedownmode] + .z.m.log[`info][`idb;"starting idb reload"]; + if[writedownmode in `partbyenum`default`partbyfirstchar; + .z.m.log[`info][`eod;"initialising wdbhdb for partition: ",string pt]; + $[.z.m.mode~`sort; + {[pt;w] @[w;(`.wdb.initmissingtables;pt); + {[e] .z.m.log[`error][`idb;"initmissingtables failed on the wdb: ",e]}]}[pt] each + raze {exec w from x} each (.z.m.svc`getservers) each .z.m.wdbtypes; + @[initmissingtables;pt;{[e] .z.m.log[`error][`idb;"initmissingtables failed: ",e]}]]; + .z.m.log[`info][`eod;"notifying idbs for newly created partition"]; + notifyidbs[`.idb.rollover;enlist pt]]; + .z.m.log[`info][`idb;"idb reload complete"]; + } + +/ flushes, sorts or hands off the partition, and advances to the next endofday:{[pt] - .z.m.log[`info][`wdb;"end of day for partition ",string pt]; - flushtable[1b;] each tablelist[]; / flush all remaining rows - st:tablelist[]; - sortpart[pt] each st; - movetohdb[pt]; - doreload[pt]; + .z.m.log[`info][`eod;"end of day message received - ",string pt]; + / set what type of merge method to be used + mergemethod:.z.m.mergemode; + / create a dictionary of tables and merge limits, byte or row count limit depending on settings + .z.m.log[`info][`merge;"merging partitions by ",$[.z.m.mergebybytelimit;"byte estimate";"row count"]," limit"]; + tl:tablelist[],(); + mergelimits:tl!$[.z.m.mergebybytelimit;(count tl)#.z.m.mergenumbytes;mergemaxrows each tl],(); + tablist:tl!{0#value x} each tl; + / if save mode is enabled then flush all data to disk + if[.z.m.saveenabled; + endofdaysave[.z.m.savedir;pt]; + / if sort mode enable call endofdaysort within the process, else inform the sort and reload process to do it + $[.z.m.sortenabled;endofdaysort;informsortandreload] . (.z.m.savedirs;pt;tablist;.z.m.writedownmode;mergelimits;.z.m.hdbsettings;mergemethod)]; + .z.m.log[`info][`eod;"deleting data from ",$[.z.m.writedownmode in .z.m.partwritemodes;"partsizes and tabsizes";"tabsizes"]]; + if[.z.m.writedownmode in .z.m.partwritemodes;(.z.m.mrg`clearpartsizes)[]]; + .z.m.tabsizes:0#.z.m.tabsizes; .z.m.currentpartition:pt+1; set[`.wdb.currentpartition;.z.m.currentpartition]; - .z.m.log[`info][`wdb;"end of day complete, wrote+moved: ",(", " sv string st)]; + .z.m.log[`info][`eod;"end of day is now complete"]; } -init:{[config;deps] - if[not `log in key deps;'"di.torq.proc.wdb: log dependency is required - see di.util.log"]; - if[not `timer in key deps;'"di.torq.proc.wdb: timer dependency is required - see di.timer"]; - if[not `servers in key deps;'"di.torq.proc.wdb: servers dependency is required - injected by di.torq, see di.torq.servers"]; - .z.m.log:deps`log; - .z.m.timer:deps`timer; +/ checks sort.csv sets the p attribute every partitioned writedown mode needs +checksortparams:{[] + if[not .z.m.writedownmode in .z.m.partwritemodes;:()]; + params:sortparams[]; + / check that default table is defined + $[count exec distinct tabname from params where tabname=`default,att=`p,sort; + .z.m.log[`info][`init;"default table defined in sort.csv and with at least one `p attribute and sort=1b"]; + .z.m.log[`error][`init;"default table not defined in sort.csv with at least one `p attribute and sort=1b"]]; + / check for `p attributes + $[count notparted:distinct params[`tabname] except distinct exec tabname from params where att in `p; + .z.m.log[`error][`init;"parted attribute p not set at least once in sort.csv for table(s): ",", " sv string notparted]; + .z.m.log[`info][`init;"parted attribute p set at least once for each table in sort.csv"]]; + } + +/ 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]; + 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]; + } + +/ reads every setting from config into the module +setconfig:{[config] .z.m.tptypes:$[`tickerplanttypes in key config;aslist assym config`tickerplanttypes;enlist`tickerplant]; .z.m.hdbtypes:$[`hdbtypes in key config;aslist assym config`hdbtypes;enlist`hdb]; .z.m.rdbtypes:$[`rdbtypes in key config;aslist assym config`rdbtypes;enlist`rdb]; .z.m.idbtypes:$[`idbtypes in key config;aslist assym config`idbtypes;enlist`idb]; .z.m.gatewaytypes:$[`gatewaytypes in key config;aslist assym config`gatewaytypes;enlist`gateway]; - .z.m.reloadorder:$[`reloadorder in key config;astoklist config`reloadorder;`hdb`rdb]; + .z.m.sorttypes:$[`sorttypes in key config;aslist assym config`sorttypes;enlist`sort]; + .z.m.sortworkertypes:$[`sortworkertypes in key config;aslist assym config`sortworkertypes;enlist`sortworker]; + .z.m.wdbtypes:$[`wdbtypes in key config;aslist assym config`wdbtypes;enlist`wdb]; .z.m.ignorelist:$[`ignorelist in key config;aslist assym config`ignorelist;`heartbeat`logmsg]; .z.m.hdbdir:hsym `$$[`hdbdir in key config;resolvedir[datahome[];config`hdbdir];datahome[],"/hdb"]; .z.m.savedir:hsym `$$[`savedir in key config;resolvedir[datahome[];config`savedir];datahome[],"/wdb"]; - .z.m.numrows:$[`numrows in key config;"j"$config`numrows;100000]; - .z.m.numtab:$[`numtab in key config;config`numtab;(`symbol$())!`long$()]; - .z.m.immediate:$[`immediate in key config;`boolean$config`immediate;0b]; - settimer:$[`settimer in key config;"j"$config`settimer;10]; - subscribeto:$[`subscribeto in key config;assym config`subscribeto;`]; - subscribesyms:$[`subscribesyms in key config;assym config`subscribesyms;`]; - replaylog:$[`replaylog in key config;`boolean$config`replaylog;1b]; - timeout:$[`tpwaittimeout in key config;"j"$config`tpwaittimeout;30000]; - - / v1 uses today's date as the partition; the tp log date is checked against it after - / subscribe. Cross-date replay (log date != today, needing the written working data moved to - / the right partition - TorQ's fixpartition) is deferred; the POC runs same-day. - .z.m.currentpartition:.z.D; - system "mkdir -p ",1_string .z.m.savedir; - clearwdbdata[]; + .z.m.savedirs:1_string .z.m.savedir; + .z.m.mode:$[`mode in key config;assym config`mode;`saveandsort]; + if[not .z.m.mode in `saveandsort`save`sort;'"di.torq.proc.wdb: mode must be saveandsort, save or sort, got ",string .z.m.mode]; + .z.m.saveenabled:.z.m.mode in `save`saveandsort; + .z.m.sortenabled:.z.m.mode in `saveandsort`sort; + .z.m.writedownmode:$[`writedownmode in key config;assym config`writedownmode;`default]; + if[not .z.m.writedownmode in `default,.z.m.partwritemodes; + '"di.torq.proc.wdb: writedownmode must be default, partbyattr, partbyenum or partbyfirstchar, got ",string .z.m.writedownmode]; + .z.m.mergemode:$[`mergemode in key config;assym config`mergemode;`part]; + if[not .z.m.mergemode in `part`col`hybrid;'"di.torq.proc.wdb: mergemode must be part, col or hybrid, got ",string .z.m.mergemode]; + .z.m.mergebybytelimit:$[`mergebybytelimit in key config;tobool config`mergebybytelimit;0b]; + .z.m.mergenumbytes:$[`mergenumbytes in key config;tolong config`mergenumbytes;500000000]; + .z.m.mergenumrows:$[`mergenumrows in key config;tolong config`mergenumrows;100000]; + .z.m.mergenumtab:$[`mergenumtab in key config;config`mergenumtab;`quote`trade!10000 50000]; + .z.m.numrows:$[`numrows in key config;tolong config`numrows;100000]; + .z.m.numtab:$[`numtab in key config;config`numtab;`quote`trade!10000 50000]; + .z.m.replaynumrows:$[`replaynumrows in key config;tolong config`replaynumrows;.z.m.numrows]; + .z.m.replaynumtab:$[`replaynumtab in key config;config`replaynumtab;.z.m.numtab]; + .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]; + .z.m.hdbsettings:`compression`hdbdir!($[`compression in key config;config`compression;()];.z.m.hdbdir); + .z.m.tabsizes:([tablename:`symbol$()] rowcount:`long$(); bytes:`long$()); + .z.m.settimer:$[`settimer in key config;tolong config`settimer;10]; + .z.m.subscribeto:$[`subscribeto in key config;assym config`subscribeto;`]; + .z.m.subscribesyms:$[`subscribesyms in key config;assym config`subscribesyms;`]; + .z.m.replaylog:$[`replaylog in key config;tobool config`replaylog;1b]; + .z.m.tpwaittimeout:$[`tpwaittimeout in key config;tolong config`tpwaittimeout;30000]; + .z.m.currentpartition:0N; + } - / di.dbwrite for the EOD sort/attr (optional sort.csv 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]]]; +/ logging stub for the period roll, as legacy's writedown.q shipped +/ monadic: di.pubsub.callendofperiod sends (`endofperiod;(currentpd;nextpd;data)) as one argument +endofperiod:{[x] + .z.m.log[`info][`endofperiod;"received endofperiod ",.Q.s1 x]; + } + +/ publishes the root names other processes and legacy's peach lambdas call +setroot:{[] + set[`.wdb.endofdaysort;endofdaysort]; + set[`.wdb.handler;handler]; + set[`.wdb.reloadsymfile;reloadsymfile]; + set[`.wdb.setcompression;setcompression]; + set[`.wdb.merge;merge]; + set[`.wdb.gc;.z.m.gc]; + set[`.wdb.initmissingtables;initmissingtables]; + set[`.sort.sorttab;sorttab]; + set[`.merge.syncpartsizes;.z.m.mrg`syncpartsizes]; + set[`.merge.clearpartsizes;.z.m.mrg`clearpartsizes]; + / define .z.pd in order to connect to any worker processes + @[`.z;`pd;:;{[] `u#raze {exec w from x} each (.z.m.svc`getservers) each .z.m.sortworkertypes}]; + @[`.;`upd;:;.z.m.upd]; + @[`.;`endofday;:;endofday]; + @[`.;`endofperiod;:;endofperiod]; + set[`.u.end;endofday]; + / the idb reads these at startup; currentpartition is republished at each end of day + set[`.wdb.savedir;.z.m.savedir]; + set[`.wdb.hdbdir;.z.m.hdbdir]; + set[`.wdb.currentpartition;.z.m.currentpartition]; + set[`.wdb.writedownmode;.z.m.writedownmode]; + } - / connect to the tickerplant + hdb(s) + rdb(s) (+ gateway) via the INJECTED di.torq.servers - / (di.torq already ran init - shared once-init'd registry); we call only startup with our - / own connection list, and use the lookup fns off the same injected instance. +/ reads deps and config; a save mode then connects, subscribes and replays the tp log, a sort mode waits to be called +init:{[config;deps] + if[99h<>type deps;'"di.torq.proc.wdb: deps must be a dictionary of `log`timer`servers - injected by di.torq"]; + if[not `log in key deps;'"di.torq.proc.wdb: log dependency is required - see di.util.log"]; + if[not `timer in key deps;'"di.torq.proc.wdb: timer dependency is required - see di.timer"]; + if[not `servers in key deps;'"di.torq.proc.wdb: servers dependency is required - injected by di.torq, see di.torq.servers"]; + .z.m.log:deps`log; + .z.m.timer:deps`timer; .z.m.svc:deps`servers; - sconfig:config,(enlist`connections)!enlist distinct .z.m.tptypes,.z.m.hdbtypes,.z.m.rdbtypes,.z.m.idbtypes,.z.m.gatewaytypes; - (.z.m.svc`startup)[sconfig]; + setconfig config; + / legacy passes -s -N on the command line; torqx.sh has no per-process flags, so it is a setting + if[0.z.m.replaynumrows; + {replaymaxrowcheck[x;maxrows x]} each tablelist[]]; - / timer job: check/flush to disk every settimer seconds (di.timer mode 1h period is seconds) - (.z.m.timer`addjob)[`wdbsave;savetodisk;();settimer;1h;()!()]; - .z.m.log[`info][`wdb;"initialised, savedir=",(1_string .z.m.savedir),", hdbdir=",(1_string .z.m.hdbdir),", flush every ",(string settimer),"s"]; + setroot[]; + / addjob raises on an id that already exists, so clear any job a previous init left + @[.z.m.timer`deletejobs;`wdbsave;{}]; + (.z.m.timer`addjob)[`wdbsave;savetodisk;();.z.m.settimer;1h;()!()]; + 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/settings/sort.q b/di/torq/settings/sort.q new file mode 100644 index 00000000..a451986f --- /dev/null +++ b/di/torq/settings/sort.q @@ -0,0 +1 @@ +mode:`sort diff --git a/di/torq/settings/sortworker.q b/di/torq/settings/sortworker.q new file mode 100644 index 00000000..efc619bc --- /dev/null +++ b/di/torq/settings/sortworker.q @@ -0,0 +1,9 @@ +mode:`sort +tickerplanttypes:`symbol$() +hdbtypes:`symbol$() +rdbtypes:`symbol$() +idbtypes:`symbol$() +gatewaytypes:`symbol$() +sorttypes:`symbol$() +sortworkertypes:`symbol$() +wdbtypes:`symbol$() diff --git a/di/torq/torq.md b/di/torq/torq.md index 56ddef7b..c3bae0ce 100644 --- a/di/torq/torq.md +++ b/di/torq/torq.md @@ -115,7 +115,8 @@ So **yes, it supports per-procname customisation** just like the config cascade 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 — there is no sort-worker tier yet. +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`. 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 4046f0f5..e676b63f 100644 --- a/di/torq/torq.q +++ b/di/torq/torq.q @@ -4,7 +4,7 @@ / same init[config;deps] calling convention. / built-in process type registry: proctype -> di.* module name -builtin:`hdb`tickerplant`rdb`wdb`gateway`idb`segmentedtp`chainedtp`housekeeping`discovery!`di.torq.proc.hdb`di.torq.proc.tickerplant`di.torq.proc.rdb`di.torq.proc.wdb`di.torq.proc.gateway`di.torq.proc.idb`di.torq.proc.segmentedtp`di.torq.proc.chainedtp`di.torq.proc.housekeeping`di.torq.proc.discovery +builtin:`hdb`tickerplant`rdb`wdb`sort`gateway`idb`segmentedtp`chainedtp`housekeeping`sortworker`discovery!`di.torq.proc.hdb`di.torq.proc.tickerplant`di.torq.proc.rdb`di.torq.proc.wdb`di.torq.proc.wdb`di.torq.proc.gateway`di.torq.proc.idb`di.torq.proc.segmentedtp`di.torq.proc.chainedtp`di.torq.proc.housekeeping`di.torq.proc.wdb`di.torq.proc.discovery reqenv:{[e] v:getenv e; @@ -147,7 +147,8 @@ 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, for wdb/sort sharing - is omitted: no sort-worker tier yet.) +/ (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.) 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